# `daemonx.onboarding.completed` Webhook Event

> **Event Type:** `daemonx.onboarding.completed`  
> **Source Service:** Nyxzie Cloud Core API  
> **Transport:** HTTPS POST  
> **Authentication:** HMAC SHA-256 Signature (`X-Nyxzie-Signature`)  
> **Introduced In:** v1.0.0  
> **Last Updated:** v1.1.0  

---

## 1. Description & Purpose

`daemonx.onboarding.completed` is an asynchronous event dispatched by Nyxzie Cloud Core immediately after a physical cashier workstation successfully completes pairing and device profile binding with the cloud.

### Lifecycle Trigger:
1. A merchant or developer initializes an onboarding session via [`POST /api/v1/daemonx/onboarding/sessions`](./02a_POST_api_v1_daemonx_onboarding_sessions.md), generating an ephemeral 6-digit code.
2. The cashier/technician opens the **DaemonX Desktop Bridge** application on their physical Windows workstation and enters the 6-digit pairing code.
3. The desktop bridge activates against Core, generates its local cryptographic profile secret, and binds to the workstation.
4. **Core issues a new `counter_id` UUID** and automatically dispatches this `daemonx.onboarding.completed` webhook to your registered webhook target URL.

---

## 2. Delivery Characteristics

| Attribute | Specification |
| :--- | :--- |
| **HTTP Method** | `POST` |
| **Content-Type** | `application/json` |
| **User-Agent** | `Nyxzie-Webhooks/2.0` |
| **Timeout** | 10 seconds per delivery attempt |
| **Retry Strategy** | Exponential backoff (`min(21600, 2^(attempt-1) * 60)` seconds) |
| **Max Retry Attempts**| 5 attempts |
| **Idempotency Key** | `event_id` (`X-Nyxzie-Event-Id`) is uniquely guaranteed per delivery |
| **Manual Replay** | Replayable on-demand via [`POST /onboarding/sessions/:id/webhook/replay`](./02d_POST_api_v1_daemonx_onboarding_sessions_webhook_replay.md) |

---

## 3. Delivery HTTP Headers

Every outbound webhook request sent to your server includes the following verification headers:

| Header Name | Type | Description | Example |
| :--- | :--- | :--- | :--- |
| `Content-Type` | `string` | Payload format | `application/json` |
| `User-Agent` | `string` | Outbound dispatcher agent | `Nyxzie-Webhooks/2.0` |
| `X-Nyxzie-Event` | `string` | Canonical event name *(v2 standard)* | `daemonx.onboarding.completed` |
| `X-Nyxzie-Event-Id` | `string` | Unique event UUID prefix | `evt_4a781b9e-2dc1-4cf4-b630-f9479b12e301` |
| `X-Nyxzie-Timestamp` | `string` | ISO 8601 UTC dispatch timestamp | `2026-10-15T12:00:00.000Z` |
| `X-Nyxzie-Signature` | `string` | HMAC-SHA256 signature prefixed with `v1=` | `v1=6b431eda073e6cb462bd0a9971687376ef5481...` |

---

## 4. Webhook Payload Schema

### Field Specifications:

| Field | Type | Required | Description | Example |
| :--- | :--- | :--- | :--- | :--- |
| `event` | `string` | **Yes** | Event identifier. Always `daemonx.onboarding.completed`. | `daemonx.onboarding.completed` |
| `event_id` | `string` | **Yes** | Unique idempotency ID for this event delivery. | `evt_4a781b9e-2dc1-4cf4-b630-f9479b12e301` |
| `onboarding_session_id` | `string` | **Yes** | UUID of the pairing session that was completed. | `4b68ff5e-f001-4475-8025-a741544256eb` |
| `environment` | `string` | **Yes** | Developer token environment: `"live"` or `"sandbox"`. | `live` |
| `is_sandbox` | `boolean` | **Yes** | Convenience flag indicating whether this is a sandbox counter. | `false` |
| `external_counter_ref` | `string` | **Yes** | **Guaranteed register identifier** provided during session creation. | `pos_lane_01` |
| `external_customer_ref` | `string \| null`| Optional | Merchant / site identifier (if supplied during session creation). | `cust_milan_01` |
| `external_location_ref` | `string \| null`| Optional | Store branch or venue identifier (if supplied). | `loc_colombo_flagship` |
| `counter_id` | `string` | **Yes** | **Canonical Counter UUID** issued to this hardware workstation. | `f5aa910c-444e-4462-88db-b26cbbc30961` |
| `counter_name` | `string` | **Yes** | Display name assigned to the register workstation. | `Cashier Counter 1` |
| `occurred_at` | `string` | **Yes** | ISO 8601 UTC timestamp when pairing was completed. | `2026-10-15T12:00:00.000Z` |

> [!IMPORTANT]
> **Identity Correlation & Counter ID Storage Contract:**
> - **Who owns `external_counter_ref`?** You (the developer). You provided this identifier (e.g. `pos_lane_01` or your internal register UUID) when creating the session via [`POST /api/v1/daemonx/onboarding/sessions`](./02a_POST_api_v1_daemonx_onboarding_sessions.md). In that initial session response, `counter_id` was `null` because physical pairing had not yet happened.
> - **Who issues `counter_id`?** Nyxzie Cloud Core. Once the cashier activates the physical desktop workstation using the 6-digit pairing code, Core mints and issues this canonical UUID (`f5aa910c-444e-4462-88db-b26cbbc30961`).
> - **Your Action on Webhook Receipt:** Locate your internal register record in your database using `external_counter_ref`, and **store the newly issued `counter_id`** on that register row.
> - **Why you must store `counter_id`:** All local hardware bridge operations on the physical register—such as discovering printers ([`GET /api/printers`](../bridge/02_GET_api_printers.md)), silent thermal printing ([`POST /api/print/thermal`](../bridge/03_POST_api_print_thermal.md)), and drawer kicks ([`POST /api/drawer/open`](../bridge/05_POST_api_drawer_open.md))—require the Web POS to pass `X-Bridge-Counter-Id: <counter_id>`.
> - **Optional References:** `external_customer_ref` (merchant/site ID) and `external_location_ref` (store branch ID) are echoed back if provided during session creation, allowing multi-store systems to validate tenant boundaries.

---

## 5. TypeScript Contracts

```typescript
export interface DaemonxOnboardingCompletedWebhookPayload {
  event: 'daemonx.onboarding.completed';
  event_id: string;
  onboarding_session_id: string;
  environment: 'live' | 'sandbox';
  is_sandbox: boolean;
  external_counter_ref: string;
  external_customer_ref?: string | null;
  external_location_ref?: string | null;
  counter_id: string;
  counter_name: string;
  occurred_at: string;
}
```

---

## 6. Example Webhook Delivery

### HTTP Request:

```http
POST /api/webhooks/daemonx HTTP/1.1
Host: your-domain.com
Content-Type: application/json
User-Agent: Nyxzie-Webhooks/2.0
X-Nyxzie-Event: daemonx.onboarding.completed
X-Nyxzie-Event-Id: evt_4a781b9e-2dc1-4cf4-b630-f9479b12e301
X-Nyxzie-Timestamp: 2026-10-15T12:00:00.000Z
X-Nyxzie-Signature: v1=3f8a91f57d60f4e4e9b89736c4b2b2b1a8f9038d172e6b219bb4e92a2a7587ef

{
  "event": "daemonx.onboarding.completed",
  "event_id": "evt_4a781b9e-2dc1-4cf4-b630-f9479b12e301",
  "onboarding_session_id": "4b68ff5e-f001-4475-8025-a741544256eb",
  "environment": "live",
  "is_sandbox": false,
  "external_counter_ref": "pos_lane_01",
  "external_customer_ref": "cust_milan_01",
  "external_location_ref": "loc_colombo_flagship",
  "counter_id": "f5aa910c-444e-4462-88db-b26cbbc30961",
  "counter_name": "Cashier Counter 1",
  "occurred_at": "2026-10-15T12:00:00.000Z"
}
```

---

## 7. Receiver Expected Response

Your webhook receiver endpoint must respond with an HTTP `2xx` status code (e.g. `200 OK`) to acknowledge successful receipt.

### Success Response Body:
```json
{
  "success": true,
  "received": true
}
```

*If your server returns any non-2xx status code (e.g., `429`, `500`, `502`) or times out (> 10s), Core will schedule a retry according to the exponential backoff policy.*

---

## 8. Cryptographic Signature Verification

To ensure webhook events originate genuinely from Nyxzie Core and have not been tampered with or intercepted in transit, verify the `X-Nyxzie-Signature` header using your webhook signing secret (`NYXZIE_DAEMONX_API_WEBHOOK_SEC`).

### Verification Algorithm:
1. Extract `X-Nyxzie-Timestamp` and `X-Nyxzie-Signature` from incoming request headers.
2. Read the raw, unparsed request body string (do not verify against re-stringified JSON).
3. Compute the expected HMAC-SHA256 signature over `${timestamp}.${rawBody}`:
   ```text
   expected_signature = "v1=" + HMAC_SHA256("${timestamp}.${rawBody}", webhook_secret)
   ```
4. Compare signatures using a **constant-time string comparison** function to prevent timing attacks.
5. Validate timestamp freshness: Reject requests if the timestamp is drifted more than **5 minutes** from current time (prevents replay attacks).

---

### Implementation Examples

#### Node.js / TypeScript (Next.js App Router / Express)

```typescript
import crypto from 'crypto';

export function verifyDaemonxWebhookSignature(params: {
  rawBody: string;
  signatureHeader: string | null;
  timestampHeader: string | null;
  secret: string;
}): boolean {
  const { rawBody, signatureHeader, timestampHeader, secret } = params;

  if (!signatureHeader || !timestampHeader || !secret) {
    return false;
  }

  // 1. Replay defense: verify timestamp freshness within 5 minutes
  const timestampMs = new Date(timestampHeader).getTime();
  if (isNaN(timestampMs) || Math.abs(Date.now() - timestampMs) > 5 * 60 * 1000) {
    return false;
  }

  try {
    // 2. Compute expected HMAC
    const expected = `v1=${crypto
      .createHmac('sha256', secret)
      .update(`${timestampHeader}.${rawBody}`)
      .digest('hex')}`;

    if (expected.length !== signatureHeader.length) {
      return false;
    }

    // 3. Constant-time comparison
    return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signatureHeader));
  } catch {
    return false;
  }
}
```

#### Python (FastAPI / Flask)

```python
import hmac
import hashlib
from datetime import datetime, timezone

def verify_daemonx_webhook_signature(
    raw_body: bytes,
    signature_header: str,
    timestamp_header: str,
    secret: str,
) -> bool:
    if not signature_header or not timestamp_header or not secret:
        return False

    # 1. Replay defense: 5-minute tolerance
    try:
        ts = datetime.fromisoformat(timestamp_header.replace("Z", "+00:00"))
        now = datetime.now(timezone.utc)
        if abs((now - ts).total_seconds()) > 300:
            return False
    except Exception:
        return False

    # 2. Compute expected HMAC
    signing_input = f"{timestamp_header}.".encode("utf-8") + raw_body
    expected_hex = hmac.new(
        secret.encode("utf-8"),
        signing_input,
        hashlib.sha256
    ).hexdigest()
    expected_signature = f"v1={expected_hex}"

    # 3. Constant-time comparison
    return hmac.compare_digest(expected_signature, signature_header)
```

---

## 9. Receiver Business Logic Recommendations

When your receiver gets a verified `daemonx.onboarding.completed` event:

1. **Idempotent Match & Save `counter_id`:** Find your local register record using your own `external_counter_ref` and persist the newly issued `counter_id`:
   ```sql
   UPDATE pos_registers
   SET register_meta = COALESCE(register_meta, '{}'::jsonb) || jsonb_build_object(
       'daemonx_counter_id', $1::text,
       'daemonx_counter_name', $2::text,
       'daemonx_status', 'active',
       'daemonx_paired_at', $3::text,
       'daemonx_onboarding_session_id', $4::text
   ),
   updated_at = NOW()
   WHERE id = $5::uuid;
   ```
2. **Authorize Local Bridge Communication:** Once `counter_id` is saved on the register, your Web POS backend can issue bridge credentials to the cashier's browser session. The browser then passes `X-Bridge-Counter-Id: <counter_id>` to local bridge endpoints such as [`GET /api/printers`](../bridge/02_GET_api_printers.md) and [`POST /api/print/thermal`](../bridge/03_POST_api_print_thermal.md).
3. **Invalidate Bridge Auth Cache:** Clear any cached device auth tokens or bridge contexts so incoming print jobs immediately route to the new `counter_id`.
4. **Emit Real-Time Browser Notification:** If cashiers are viewing an onboarding modal, broadcast an SSE or WebSocket event with the new `counter_id` so the UI automatically transitions to `"Pairing Complete!"`.
