npm package: @nearid/sdk
Description: NearID Node.js SDK
Latest version: 2.0.1

# NearID Node.js SDK

This directory contains the official Node.js SDK for interacting with the NearID Cloud backend.
It implements REST API wrappers and webhook verification logic exactly as defined in the protocol specification.

All SDK behavior follows: protocol/spec.md

---

## Features

- Typed API client (TypeScript)
- REST methods for orgs, sessions lifecycle, receivers, presence, billing, incidents
- Webhook signature verification
- Pagination helpers
- Error handling & retry wrappers
- Full API reference (method-by-method)

---

## Installation

npm install @nearid/sdk

---

## API Reference

See the complete method-by-method docs, parameters, responses, and errors in:

- `../API_REFERENCE.md`

---

## Usage Example

import { NearIDClient } from "@nearid/sdk";

const client = new NearIDClient({
  apiKey: "YOUR_API_KEY",
  baseUrl: "https://api.nearid.example"
});

const events = await client.listPresenceEvents({ orgId: "org_123" });

await client.createLink({
  orgId: "org_123",
  userRef: "emp_45"
});

await client.linkPresenceSession({
  presenceSessionId: "psess_001",
  userRef: "emp_45",
  orgId: "org_123"
});

---

## Webhook Verification

import { verifyNearIDWebhook } from "@nearid/sdk";

const isValid = verifyNearIDWebhook({
  rawBody,
  signature: headers["x-hnnp-signature"],
  timestamp: headers["x-hnnp-timestamp"],
  webhookSecret: process.env.WEBHOOK_SECRET
});

---

## Webhook Consumer Example (Express)

You can use the SDK helper inside a minimal Express server. An example is provided in:

- `examples/webhook-consumer.ts`

Outline:

```ts
import express from "express";
import { verifyNearIDWebhook } from "@nearid/sdk";

const app = express();
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = Buffer.from(buf); } }));

app.post("/nearid/webhook", (req, res) => {
  const isValid = verifyNearIDWebhook({
    rawBody: req.rawBody,
    signature: req.header("X-HNNP-Signature"),
    timestamp: req.header("X-HNNP-Timestamp"),
    webhookSecret: process.env.WEBHOOK_SECRET
  });

  if (!isValid) return res.status(400).json({ error: "invalid_webhook_signature" });

  console.log("Received NearID webhook", req.body);
  return res.status(200).json({ status: "ok" });
});
```

---

## Available Methods

Receivers
- listReceivers({ orgId })
- createReceiver({ orgId, receiverId, authMode, ... }) // authMode: "hmac_shared_secret" | "public_key"
- updateReceiver({ orgId, receiverId, ... })

Presence (public)
- listPresenceEvents({ orgId, ... })
- listPresenceSessions({ orgId, ... })

Links (public)
- createLink({ orgId, userRef, deviceId? })
- createLinkV2({ orgId, presenceSessionId, userRef, registrationBlob? })
- activateLink(id)
- revokeLink(id)
- revokeLinkV2({ orgId, linkId })
- listLinks({ orgId, userRef? })
- linkPresenceSession({ orgId, presenceSessionId, userRef })
- unlink(id)

Org console
- listOrgs()
- getOrg({ orgId })
- getOrgSettings({ orgId })
- updateOrgSettings({ orgId, settings })
- getOrgConfig({ orgId })
- updateOrgConfig({ orgId, config })
- getOrgMetricsRealtime({ orgId, ... })
- listOrgUsers({ orgId })

Receivers health (org console)
- listReceiversAdmin()
- getReceiver({ receiverId })
- updateReceiverAdmin({ receiverId, payload })
- getReceiverStatus({ receiverId })
- getReceiverHealth({ receiverId })

Sessions lifecycle (org console)
- listOrgSessions()
- getOrgSessionsSummary()
- createOrgSession(payload)
- updateOrgSession({ sessionId, payload })
- deleteOrgSession({ sessionId })
- finalizeOrgSession({ sessionId })

Attendance + presence (org console)
- getPresenceLive()
- getPresenceLogs()
- getPresenceEvents()
- listLocations()
- listGroups()
- createGroup(payload)
- updateGroup({ groupId, payload })
- deleteGroup({ groupId })
- getAttendance()
- exportAttendanceCsv()

Billing
- getBillingSummary()
- listInvoices()
- getInvoicePdf({ invoiceId })

Incidents + safety
- listIncidents()
- getIncident({ incidentId })
- getIncidentRollcall({ incidentId })
- getSafetyStatus()
- getSafetySummary()

---

## File Structure

src/
  index.ts
  client.ts
  http.ts
  webhook.ts
  types.ts

---

## Environment Variables

WEBHOOK_SECRET=your_org_webhook_secret

---

## Notes

- Webhook signing follows the HMAC rules in Section 10.3 of the v2 spec.
- All network calls use HTTPS.
- SDK MUST NOT alter any packet formats or cryptographic logic.
- Some endpoints require an org admin JWT (org console auth) instead of an API key.
- Presence events include `verification_status` with values `verified`, `weak`, or `rejected`.
- If `verification_status` is `verified` and `user_ref` is present, the event is linked.

Typed models are exported from `@nearid/sdk` (see `types.ts`).

Webhook event payloads are also typed:
- `WebhookEvent`
- `WebhookPresenceCheckIn`
- `WebhookPresenceUnknown`
- `WebhookLinkCreated`
- `WebhookLinkRevoked`

---

## Pagination helpers

```ts
for await (const evt of client.iteratePresenceEvents({ orgId: "org_123" })) {
  console.log(evt.id);
}

for await (const sess of client.iteratePresenceSessions({ orgId: "org_123" })) {
  console.log(sess.session_id);
}

for await (const rcv of client.iterateReceivers({ orgId: "org_123" })) {
  console.log(rcv.receiver_id);
}
```

---

## Rate limiting

The client retries on `5xx` and `429` responses with exponential backoff.  
If `Retry-After` is provided, it is respected (up to 30s).

---

## Testing

npm test

---

## Reference

Full protocol spec: ../../protocol/spec.md