@tokenoftrust/cli 6.14.5 → 6.14.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
1
+ // Webhook receiver. The order follows apps/private/webhooks-and-api.md: raw
2
+ // body, Content-Digest, RFC 9421 signature (with a created/expires window and
3
+ // keyid resolution against the published `webhook_signing_keys`), CloudEvents
4
+ // envelope, then a replay guard on the event id through an injectable store.
5
+ // Only an event that passed every step reaches application code.
6
+ import { toBytes } from './encoding.js';
7
+ import { verifyContentDigest, verifyMessageSignature } from './http-signature.js';
8
+
9
+ export const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
10
+ export const EVENT_TYPE_PREFIX = 'com.tokenoftrust.storefront.';
11
+ const ENVELOPE_REQUIRED = ['specversion', 'id', 'source', 'type', 'time', 'datacontenttype', 'tenantid', 'appinstallid', 'dataschemaversion', 'data'];
12
+ const SEVEN_DAYS_SECONDS = 7 * 24 * 60 * 60;
13
+
14
+ /** HTTP status for each refusal code. */
15
+ export const WEBHOOK_REFUSALS = Object.freeze({
16
+ method_not_allowed: 405,
17
+ body_too_large: 413,
18
+ digest_missing: 400,
19
+ digest_malformed: 400,
20
+ digest_unsupported: 400,
21
+ digest_mismatch: 400,
22
+ signature_missing: 401,
23
+ signature_malformed: 401,
24
+ signature_coverage: 401,
25
+ unsupported_alg: 401,
26
+ signature_expired: 401,
27
+ unknown_key: 401,
28
+ signature_invalid: 401,
29
+ body_not_json: 400,
30
+ envelope_invalid: 400,
31
+ // A replay is acknowledged with 200 so the sender stops, and never reaches the application.
32
+ replayed_event: 200,
33
+ });
34
+
35
+ /**
36
+ * In-memory seen-event store, bounded by entry count and TTL. It does not
37
+ * survive a restart or span instances: production receivers implement the same
38
+ * two methods over durable storage (a unique-key insert with an expiry).
39
+ */
40
+ export class MemorySeenEventStore {
41
+ constructor({ maxEntries = 100_000, now = () => Date.now() } = {}) {
42
+ this.maxEntries = maxEntries;
43
+ this.now = now;
44
+ this.entries = new Map();
45
+ }
46
+
47
+ /** Record `key` as seen. Resolves true when it was new, false when already present and unexpired. */
48
+ async claim(key, ttlSeconds) {
49
+ const at = this.now();
50
+ const expiresAt = this.entries.get(key);
51
+ if (expiresAt !== undefined && expiresAt > at) return false;
52
+ this.entries.delete(key);
53
+ this.entries.set(key, at + ttlSeconds * 1000);
54
+ while (this.entries.size > this.maxEntries) this.entries.delete(this.entries.keys().next().value);
55
+ return true;
56
+ }
57
+
58
+ /** Forget `key` so a redelivery is processed (the application failed to handle it). */
59
+ async release(key) {
60
+ this.entries.delete(key);
61
+ }
62
+ }
63
+
64
+ /** Lowercased, single-string header map from a Headers object, a plain object, or entry pairs. */
65
+ export function normalizeHeaders(headers) {
66
+ const out = {};
67
+ if (!headers) return out;
68
+ const entries = typeof headers.entries === 'function' && !Array.isArray(headers) ? headers.entries() : Array.isArray(headers) ? headers : Object.entries(headers);
69
+ for (const [name, value] of entries) {
70
+ if (value === undefined || value === null) continue;
71
+ out[String(name).toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function envelopeProblem(event) {
77
+ if (!event || typeof event !== 'object' || Array.isArray(event)) return 'not an object';
78
+ for (const key of ENVELOPE_REQUIRED) if (!(key in event)) return `missing ${key}`;
79
+ if (event.specversion !== '1.0') return 'specversion';
80
+ for (const key of ['id', 'source', 'type', 'tenantid', 'appinstallid']) {
81
+ if (typeof event[key] !== 'string' || event[key] === '') return key;
82
+ }
83
+ if (!event.type.startsWith(EVENT_TYPE_PREFIX)) return 'type';
84
+ if (!event.data || typeof event.data !== 'object' || Array.isArray(event.data)) return 'data';
85
+ return null;
86
+ }
87
+
88
+ export class WebhookReceiver {
89
+ /**
90
+ * @param {object} options
91
+ * @param {string} options.endpoint The webhook endpoint exactly as registered in tot-app.json (the signed `@target-uri`).
92
+ * @param {{ resolveSigningKey(keyid: string): Promise<CryptoKey|null> }} options.keys AuthorizationMetadata or StaticSigningKeys.
93
+ * @param {{ claim(key: string, ttlSeconds: number): Promise<boolean>, release(key: string): Promise<void> }} [options.seenEvents]
94
+ * @param {number} [options.maxAgeSeconds] Oldest acceptable signature `created` (default 300).
95
+ * @param {number} [options.maxClockSkewSeconds] Furthest-future acceptable `created` (default 60).
96
+ * @param {number} [options.replayTtlSeconds] How long an event id is remembered (default 7 days).
97
+ * @param {number} [options.maxBodyBytes] Largest accepted body (default 1 MiB).
98
+ * @param {() => number} [options.now] Milliseconds since the epoch.
99
+ */
100
+ constructor({
101
+ endpoint,
102
+ keys,
103
+ seenEvents = new MemorySeenEventStore(),
104
+ maxAgeSeconds = 300,
105
+ maxClockSkewSeconds = 60,
106
+ replayTtlSeconds = SEVEN_DAYS_SECONDS,
107
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
108
+ now = () => Date.now(),
109
+ }) {
110
+ // The registered string is kept verbatim: it is signed character for character.
111
+ if (typeof endpoint !== 'string' || !URL.canParse(endpoint)) {
112
+ throw new TypeError('endpoint must be the absolute webhook URL registered in tot-app.json');
113
+ }
114
+ if (!keys || typeof keys.resolveSigningKey !== 'function') throw new TypeError('keys must provide resolveSigningKey(keyid)');
115
+ if (!seenEvents || typeof seenEvents.claim !== 'function' || typeof seenEvents.release !== 'function') {
116
+ throw new TypeError('seenEvents must provide claim(key, ttlSeconds) and release(key)');
117
+ }
118
+ this.endpoint = endpoint;
119
+ this.keys = keys;
120
+ this.seenEvents = seenEvents;
121
+ this.maxAgeSeconds = maxAgeSeconds;
122
+ this.maxClockSkewSeconds = maxClockSkewSeconds;
123
+ this.replayTtlSeconds = replayTtlSeconds;
124
+ this.maxBodyBytes = maxBodyBytes;
125
+ this.now = now;
126
+ }
127
+
128
+ /**
129
+ * Verify one delivery and claim its event id.
130
+ *
131
+ * Resolves `{ ok: true, event, keyid, created, replayKey }`, or
132
+ * `{ ok: false, status, code }` where `status` is the HTTP status to answer.
133
+ * After `ok: true` the id is claimed: call `release(replayKey)` if the event
134
+ * could not be handled, so the sender's retry is processed.
135
+ *
136
+ * @param {object} delivery
137
+ * @param {string} delivery.method
138
+ * @param {Headers|Record<string, string|string[]>} delivery.headers
139
+ * @param {Uint8Array|ArrayBuffer|string} delivery.body The exact raw body bytes.
140
+ */
141
+ async verify({ method, headers, body }) {
142
+ const refuse = (code) => ({ ok: false, status: WEBHOOK_REFUSALS[code], code });
143
+ if (String(method).toUpperCase() !== 'POST') return refuse('method_not_allowed');
144
+ const bytes = toBytes(body);
145
+ if (bytes.length > this.maxBodyBytes) return refuse('body_too_large');
146
+ const h = normalizeHeaders(headers);
147
+
148
+ const digest = await verifyContentDigest(h['content-digest'], bytes);
149
+ if (!digest.ok) return refuse(digest.code);
150
+
151
+ const signature = await verifyMessageSignature({
152
+ method: 'POST',
153
+ targetUri: this.endpoint,
154
+ headers: h,
155
+ resolveKey: (keyid) => this.keys.resolveSigningKey(keyid),
156
+ now: this.now(),
157
+ maxAgeSeconds: this.maxAgeSeconds,
158
+ maxClockSkewSeconds: this.maxClockSkewSeconds,
159
+ });
160
+ if (!signature.ok) return refuse(signature.code);
161
+
162
+ let event;
163
+ try {
164
+ event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
165
+ } catch {
166
+ return refuse('body_not_json');
167
+ }
168
+ if (envelopeProblem(event)) return refuse('envelope_invalid');
169
+
170
+ const replayKey = `${event.tenantid}/${event.id}`;
171
+ if (!(await this.seenEvents.claim(replayKey, this.replayTtlSeconds))) return refuse('replayed_event');
172
+ return { ok: true, event, keyid: signature.keyid, created: signature.created, replayKey };
173
+ }
174
+
175
+ /** Forget a claimed event id so its redelivery is processed. */
176
+ release(replayKey) {
177
+ return this.seenEvents.release(replayKey);
178
+ }
179
+
180
+ /**
181
+ * Verify, then run `onEvent(event, context)`. Answers 202 once the handler
182
+ * resolves, 200 for a replay, the refusal status otherwise, and 500 (with the
183
+ * id released, so the sender retries) when the handler throws.
184
+ *
185
+ * @returns {Promise<{ status: number, body: object, error?: unknown }>}
186
+ */
187
+ async receive(delivery, onEvent) {
188
+ const result = await this.verify(delivery);
189
+ if (!result.ok) {
190
+ return { status: result.status, body: result.code === 'replayed_event' ? { accepted: true, duplicate: true } : { accepted: false, code: result.code } };
191
+ }
192
+ try {
193
+ await onEvent(result.event, { keyid: result.keyid, created: result.created });
194
+ } catch (error) {
195
+ await this.release(result.replayKey);
196
+ return { status: 500, body: { accepted: false, code: 'handler_failed' }, error };
197
+ }
198
+ return { status: 202, body: { accepted: true } };
199
+ }
200
+
201
+ /** `receive` for a fetch-style Request; resolves a Response. */
202
+ async handleRequest(request, onEvent) {
203
+ const body = await readCapped(request, this.maxBodyBytes);
204
+ const result = body === null
205
+ ? { status: 413, body: { accepted: false, code: 'body_too_large' } }
206
+ : await this.receive({ method: request.method, headers: request.headers, body }, onEvent);
207
+ return new Response(JSON.stringify(result.body), {
208
+ status: result.status,
209
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
210
+ });
211
+ }
212
+ }
213
+
214
+ /** The request body, or null once it exceeds maxBytes (declared or streamed); never buffers past the cap. */
215
+ async function readCapped(request, maxBytes) {
216
+ const declared = Number(request.headers.get('content-length'));
217
+ if (request.headers.has('content-length') && Number.isFinite(declared) && declared > maxBytes) return null;
218
+ if (!request.body) return new Uint8Array(0);
219
+ const reader = request.body.getReader();
220
+ const chunks = [];
221
+ let size = 0;
222
+ for (;;) {
223
+ const { done, value } = await reader.read();
224
+ if (done) break;
225
+ size += value.byteLength;
226
+ if (size > maxBytes) {
227
+ await reader.cancel().catch(() => {});
228
+ return null;
229
+ }
230
+ chunks.push(value);
231
+ }
232
+ const out = new Uint8Array(size);
233
+ let offset = 0;
234
+ for (const chunk of chunks) {
235
+ out.set(chunk, offset);
236
+ offset += chunk.byteLength;
237
+ }
238
+ return out;
239
+ }
@@ -4,11 +4,16 @@
4
4
  # Port the stub webhook receiver (server.js) listens on.
5
5
  PORT=8787
6
6
 
7
- # Optional externally visible webhook origin (without trailing slash) when running
8
- # behind a local preview tunnel (cloudflared, Microsoft devtunnel, ngrok) or
9
- # reverse-proxied container host so RFC 9421 @target-uri verification matches
10
- # the HTTPS URL Storefront signed.
11
- # WEBHOOK_PUBLIC_URL=https://random-words.trycloudflare.com
7
+ # Your registered webhooks.endpoint, character for character: it is the signed
8
+ # @target-uri, so a local tunnel or reverse proxy must be named here, not guessed
9
+ # from request headers. Defaults to http://localhost:$PORT/webhooks.
10
+ # WEBHOOK_ENDPOINT=https://random-words.trycloudflare.com/webhooks
11
+
12
+ # Set these to leave local mode: webhook keys then come from the store's
13
+ # published metadata and the connector gets an API client (connector.js).
14
+ # TOT_STOREFRONT_ORIGIN=https://acme.tokenoftrust.store
15
+ # TOT_CLIENT_ID=
16
+ # TOT_CLIENT_SECRET=
12
17
 
13
18
  # Must match tot-app.json's webhooks.signatureKeyId. `tot app dev` writes the
14
19
  # matching public key alongside this app at .tot/dev-keys.json for local runs
@@ -19,12 +19,20 @@ are the stable human and LLM entry points.
19
19
  [`apps/private/contract/examples/`](https://github.com/tokenoftrust/storefront-devkit/tree/main/apps/private/contract/examples/))
20
20
  you can sign and deliver to your own receiver locally, before you have a
21
21
  real install. Add one fixture per topic you subscribe to.
22
- - **`server.js`** — a minimal Node HTTP receiver for `webhooks.endpoint`. It
23
- verifies the RFC 9421 HTTP Message Signature + RFC 9530 Content-Digest on
24
- every inbound request before trusting the body — replace the handler logic,
25
- keep the verification. Supports `WEBHOOK_PUBLIC_URL` (or `X-Forwarded-Proto`
26
- / `X-Forwarded-Host`) for local tunnels and reverse-proxied container hosts,
27
- and logs `event.tenantid` + `event.appinstallid` for multi-tenant routing.
22
+ - **`vendor/connector-kit/`** — the Devkit's
23
+ [connector-kit](https://github.com/tokenoftrust/storefront-devkit/tree/main/packages/connector-kit),
24
+ vendored as source and pinned to a Devkit commit in `vendor/connector-kit/PIN.json`. It gives
25
+ you `WebhookReceiver` (Content-Digest, RFC 9421 signature, `created` window, published-key
26
+ lookup, replay guard), `ConnectorAuthClient` (installation tokens) and `ApiClient`
27
+ (`Idempotency-Key` reused on retry, `Retry-After`, pagination). Treat it as read-only; to upgrade,
28
+ replace the directory with a newer copy and read the Devkit changelog.
29
+ - **`connector.js`** — wires the kit from the environment and holds `handleEvent`, where your
30
+ logic goes. A delivery is a notification: read current state through `api` before acting.
31
+ - **`server.js`** — a minimal Node HTTP server in front of the receiver. Nothing reaches
32
+ `handleEvent` unverified. Set `WEBHOOK_ENDPOINT` to your registered `webhooks.endpoint`
33
+ (it is the signed `@target-uri`; the default is `http://localhost:$PORT/webhooks`).
34
+ - **`tests/`** — `npm test` runs offline: signed delivery accepted once, tampered and unknown-key
35
+ deliveries refused, API writes sent with a token and a stable `Idempotency-Key`.
28
36
  - **`Dockerfile`** — portable Node 22 Alpine container for self-hosted
29
37
  container platforms (Google Cloud Run, Azure Container Apps, Fly.io, Render,
30
38
  Railway, AWS ECS) or optional `installMode: "hosted"`.
@@ -35,7 +43,8 @@ are the stable human and LLM entry points.
35
43
  ```
36
44
  # lint tot-app.json against the contract
37
45
  tot app dev validate
38
- # start the stub receiver
46
+ # run the connector's tests, then start the receiver
47
+ npm test
39
48
  node server.js &
40
49
  # sign a fixture CloudEvent and POST it in
41
50
  tot app dev emit order.created
@@ -144,9 +153,11 @@ curl -s https://storefront.tokenoftrust.store/<tenant>/api/apps/v1/<path> \
144
153
 
145
154
  ## Going live (`private_key_jwt` candidate staging & 1-click Owner approval)
146
155
 
147
- 1. Point `webhooks.endpoint` at your real, publicly reachable HTTPS receiver and swap the dev-only
148
- signature verification in `server.js` for the platform's published JWKS/signing-key metadata
149
- (see the Devkit's
156
+ 1. Point `webhooks.endpoint` at your real, publicly reachable HTTPS receiver, set
157
+ `WEBHOOK_ENDPOINT` to that exact URL, and set `TOT_STOREFRONT_ORIGIN`, `TOT_CLIENT_ID` and
158
+ `TOT_CLIENT_SECRET` so the connector verifies against the platform's published signing keys
159
+ and gets its API client. Replace the in-memory replay guard with a durable store if you run more
160
+ than one instance (see the Devkit's
150
161
  [`webhooks-and-api.md`](https://github.com/tokenoftrust/storefront-devkit/blob/main/apps/private/webhooks-and-api.md)).
151
162
  2. **Stage a `private_key_jwt` `production` candidate (`pending_approval`):**
152
163
  Run `tot app candidate --jwks-uri https://...` (or `--jwks <file>` with `{ keys: [ <publicKeyJwk> ] }`;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The connector's wiring: webhook verification, installation auth and API
3
+ * calls, all from the vendored connector-kit (`vendor/connector-kit/`, pinned
4
+ * by `vendor/connector-kit/PIN.json`; read its README in the Devkit at
5
+ * `packages/connector-kit`). Treat the vendored directory as read-only — upgrade by
6
+ * replacing it. Put your business logic in `handleEvent`.
7
+ *
8
+ * Environment (see `.env.example`):
9
+ * TOT_STOREFRONT_ORIGIN the store's origin, e.g. https://acme.tokenoftrust.store.
10
+ * Set -> webhook keys come from the store's published
11
+ * metadata, and the API client is created when
12
+ * the credentials below are also set.
13
+ * Unset -> local mode: webhooks are checked against the
14
+ * throwaway key `tot app dev` wrote to .tot/dev-keys.json.
15
+ * TOT_CLIENT_ID, TOT_CLIENT_SECRET installation credentials (client_secret_basic).
16
+ * WEBHOOK_ENDPOINT your registered `webhooks.endpoint`, character for
17
+ * character. It is the signed @target-uri.
18
+ * TOT_DEV_KEYS path to the dev key file (default .tot/dev-keys.json).
19
+ */
20
+ import { existsSync, readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import {
23
+ ApiClient,
24
+ AuthorizationMetadata,
25
+ ConnectorAuthClient,
26
+ StaticSigningKeys,
27
+ WebhookReceiver,
28
+ } from "./vendor/connector-kit/index.js";
29
+
30
+ /** Local-mode keys: the public half of `tot app dev`'s key, re-read on every lookup. */
31
+ export function devSigningKeys(path) {
32
+ return {
33
+ async resolveSigningKey(keyid) {
34
+ if (!existsSync(path)) return null;
35
+ const { kid, publicKeyJwk } = JSON.parse(readFileSync(path, "utf8"));
36
+ const keys = new StaticSigningKeys({ keys: [{ ...publicKeyJwk, kid, alg: "RS256", use: "sig" }] });
37
+ return keys.resolveSigningKey(keyid);
38
+ },
39
+ };
40
+ }
41
+
42
+ /** Reconcile here: a delivery is a notification, so read current state through `api` before acting. */
43
+ export async function handleEvent(event, { keyid, created }, { log = console.log, api = null } = {}) {
44
+ log(`verified delivery (keyid=${keyid}, created=${created})`);
45
+ log(`${event.type.replace("com.tokenoftrust.storefront.", "")} for tenant ${event.tenantid} (install=${event.appinstallid}, eventId=${event.id})`);
46
+ }
47
+
48
+ /**
49
+ * @param {Record<string, string | undefined>} env
50
+ * @param {{ fetch?: typeof fetch, keys?: { resolveSigningKey(keyid: string): Promise<unknown> }, now?: () => number, onEvent?: Function }} [overrides]
51
+ */
52
+ export function createConnector(env = process.env, overrides = {}) {
53
+ const origin = env.TOT_STOREFRONT_ORIGIN || null;
54
+ const port = Number(env.PORT || 8787);
55
+ const endpoint = env.WEBHOOK_ENDPOINT || `http://localhost:${port}/webhooks`;
56
+ const fetchImpl = overrides.fetch;
57
+ const clock = overrides.now ? { now: overrides.now } : {};
58
+
59
+ const keys =
60
+ overrides.keys ??
61
+ (origin
62
+ ? new AuthorizationMetadata({ origin, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock })
63
+ : devSigningKeys(env.TOT_DEV_KEYS || join(process.cwd(), ".tot", "dev-keys.json")));
64
+ const receiver = new WebhookReceiver({ endpoint, keys, ...clock });
65
+
66
+ let auth = null;
67
+ let api = null;
68
+ if (origin && env.TOT_CLIENT_ID && env.TOT_CLIENT_SECRET) {
69
+ auth = new ConnectorAuthClient({
70
+ origin,
71
+ clientId: env.TOT_CLIENT_ID,
72
+ clientSecret: env.TOT_CLIENT_SECRET,
73
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
74
+ ...clock,
75
+ });
76
+ api = new ApiClient({ origin, auth, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock });
77
+ }
78
+
79
+ const onEvent = overrides.onEvent ?? ((event, info) => handleEvent(event, info, { api }));
80
+ return { endpoint, receiver, auth, api, onEvent, handleRequest: (request) => receiver.handleRequest(request, onEvent) };
81
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "my-app",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "A Storefront Private App connector.",
7
+ "engines": { "node": ">=20" },
8
+ "scripts": {
9
+ "start": "node server.js",
10
+ "test": "node --test tests/*.spec.js"
11
+ }
12
+ }
@@ -1,98 +1,54 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Minimal webhook receiver stub for a Storefront Private App. Verifies the
4
- * RFC 9421 HTTP Message Signature + RFC 9530 Content-Digest on every inbound
5
- * request BEFORE trusting the body — replace the "handle the event" bit
6
- * below, keep the verification.
3
+ * Webhook receiver for a Storefront Private App. The connector-kit's
4
+ * WebhookReceiver verifies the Content-Digest, the RFC 9421 signature, the
5
+ * `created` window and the replay guard BEFORE your handler sees an event;
6
+ * edit `handleEvent` in connector.js, keep the verification.
7
7
  *
8
- * Trusts the public key `tot app dev` wrote to .tot/dev-keys.json (re-read on
9
- * every request, so it always sees the harness's current key). That file is
10
- * dev-only scaffolding: your real receiver checks against the platform's
11
- * published JWKS/signing-key metadata instead — see the Devkit's
12
- * https://github.com/tokenoftrust/storefront-devkit/tree/main/apps/private
13
- * (`examples/hello-inventory`, `recipes/inventory-sync-wms`,
14
- * `recipes/fulfillment-label-station`, `recipes/dropship-multi-supplier`).
8
+ * Local mode (no TOT_STOREFRONT_ORIGIN) trusts the key `tot app dev` wrote to
9
+ * .tot/dev-keys.json. With TOT_STOREFRONT_ORIGIN set, keys come from the
10
+ * store's published authorization metadata. See connector.js and README.md.
15
11
  *
16
- * Online preview & production flow (see README.md):
17
- * 1. `tot catalog seed --preset=general|regulated-vape|multi-warehouse` (then `tot preview`)
18
- * 2. `tot app install --tenant <tenant> --env test --app .`
19
- * 3. `POST /api/apps/admin/test-orders` (synthetic preview orders bound to `test` install)
20
- * 4. `POST /api/apps/admin/candidates` (`private_key_jwt`, `pending_approval`) ->
21
- * 1-click Store Owner approval in `/admin#integrations` (`POST /api/apps/admin/candidates/decide`)
12
+ * The replay guard defaults to per-process memory; give WebhookReceiver a
13
+ * durable `seenEvents` store before running more than one instance.
22
14
  */
23
15
  import { createServer } from "node:http";
24
- import { existsSync, readFileSync } from "node:fs";
25
- import { join } from "node:path";
26
- import { verifyWebhookSignature } from "./lib/private-apps-devkit.mjs";
27
-
28
- const PORT = Number(process.env.PORT || 8787);
29
- const DEV_KEYS_PATH = join(process.cwd(), ".tot", "dev-keys.json");
30
-
31
- function loadDevPublicKey() {
32
- if (!existsSync(DEV_KEYS_PATH)) return null;
33
- const { publicKeyJwk } = JSON.parse(readFileSync(DEV_KEYS_PATH, "utf8"));
34
- return crypto.subtle.importKey("jwk", publicKeyJwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
16
+ import { Readable } from "node:stream";
17
+ import { realpathSync } from "node:fs";
18
+ import { fileURLToPath } from "node:url";
19
+ import { createConnector } from "./connector.js";
20
+
21
+ /** Adapt a Node request to the fetch-style Request the receiver reads. */
22
+ function toRequest(req, port) {
23
+ const host = req.headers.host || `localhost:${port}`;
24
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
25
+ return new Request(new URL(req.url, `http://${host}`), {
26
+ method: req.method,
27
+ headers: req.headers,
28
+ ...(hasBody ? { body: Readable.toWeb(req), duplex: "half" } : {}),
29
+ });
35
30
  }
36
31
 
37
- function readBody(req) {
38
- return new Promise((resolvePromise, reject) => {
39
- const chunks = [];
40
- req.on("data", (c) => chunks.push(c));
41
- req.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8")));
42
- req.on("error", reject);
32
+ export function createWebhookServer(connector, port = Number(process.env.PORT || 8787)) {
33
+ return createServer(async (req, res) => {
34
+ const requestId = req.headers["tot-request-id"] || "(none)";
35
+ try {
36
+ const response = await connector.handleRequest(toRequest(req, port));
37
+ if (response.status >= 400 && response.status !== 405) console.error(`[${requestId}] delivery refused: ${response.status}`);
38
+ res.writeHead(response.status, Object.fromEntries(response.headers)).end(await response.text());
39
+ } catch (error) {
40
+ console.error(`[${requestId}] receiver error: ${error?.code ?? "unexpected"}`);
41
+ res.writeHead(500, { "content-type": "application/json" }).end(JSON.stringify({ accepted: false, code: "receiver_error" }));
42
+ }
43
43
  });
44
44
  }
45
45
 
46
- const server = createServer(async (req, res) => {
47
- const requestId = req.headers["tot-request-id"] || "(none)";
48
- if (req.method !== "POST") {
49
- res.writeHead(405).end();
50
- return;
51
- }
52
-
53
- const body = await readBody(req);
54
- const publicKey = await loadDevPublicKey();
55
- if (!publicKey) {
56
- console.error(`[${requestId}] no .tot/dev-keys.json — run \`tot app dev emit\` first`);
57
- res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "no trusted key on file" }));
58
- return;
59
- }
60
-
61
- const proto = req.headers["x-forwarded-proto"] || "http";
62
- const host = req.headers["x-forwarded-host"] || req.headers.host || `localhost:${PORT}`;
63
- const targetUrl = process.env.WEBHOOK_PUBLIC_URL
64
- ? new URL(req.url, process.env.WEBHOOK_PUBLIC_URL).toString()
65
- : `${proto}://${host}${req.url}`;
66
-
67
- const result = await verifyWebhookSignature({
68
- method: req.method,
69
- url: targetUrl,
70
- body,
71
- headers: {
72
- "content-digest": req.headers["content-digest"],
73
- "signature-input": req.headers["signature-input"],
74
- signature: req.headers["signature"],
75
- },
76
- publicKey,
46
+ const entry = process.argv[1] ? realpathSync(process.argv[1]) : null;
47
+ const self = realpathSync(fileURLToPath(import.meta.url));
48
+ if (entry === self) {
49
+ const port = Number(process.env.PORT || 8787);
50
+ const connector = createConnector(process.env);
51
+ createWebhookServer(connector, port).listen(port, () => {
52
+ console.log(`webhook receiver listening on http://localhost:${port} (POST ${connector.endpoint} — see tot-app.json webhooks.endpoint)`);
77
53
  });
78
-
79
- if (!result.ok) {
80
- console.error(`[${requestId}] signature verification FAILED: ${result.code} — ${result.reason}`);
81
- res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify(result));
82
- return;
83
- }
84
-
85
- console.log(`[${requestId}] verified delivery (keyid=${result.keyid}, created=${result.created})`);
86
- // ── Handle the event (multi-tenant ready: route by tenantid + appinstallid) ─
87
- const event = JSON.parse(body);
88
- console.log(
89
- `[${requestId}] ${event.type} for tenant ${event.tenantid} (install=${event.appinstallid}, eventId=${event.id})`,
90
- );
91
- // ─────────────────────────────────────────────────────────────────────────
92
-
93
- res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true }));
94
- });
95
-
96
- server.listen(PORT, () => {
97
- console.log(`webhook receiver listening on http://localhost:${PORT} (POST here — see tot-app.json webhooks.endpoint)`);
98
- });
54
+ }
@@ -0,0 +1,93 @@
1
+ // Runs offline: `npm test`. Signs fixtures with the dev-only signer in lib/ and
2
+ // checks that connector.js, built on the vendored connector-kit, accepts a
3
+ // good delivery, refuses a tampered or replayed one, and sends API calls with
4
+ // an installation token and an Idempotency-Key.
5
+ import { test } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { readFileSync } from "node:fs";
8
+ import { generateDevRs256KeyPair, signWebhookRequest } from "../lib/private-apps-devkit.mjs";
9
+ import { createConnector } from "../connector.js";
10
+
11
+ const ENDPOINT = "https://connector.example.com/webhooks/tot";
12
+ const KID = "test-key-1";
13
+ const fixture = () => readFileSync(new URL("../fixtures/order.created.cloudevent.json", import.meta.url), "utf8");
14
+
15
+ async function setup(extraEnv = {}, overrides = {}) {
16
+ const { privateKey, publicKey } = await generateDevRs256KeyPair();
17
+ const publicKeyJwk = await crypto.subtle.exportKey("jwk", publicKey);
18
+ const events = [];
19
+ const connector = createConnector(
20
+ { WEBHOOK_ENDPOINT: ENDPOINT, ...extraEnv },
21
+ {
22
+ keys: { resolveSigningKey: async (keyid) => (keyid === KID ? await crypto.subtle.importKey("jwk", { kty: "RSA", n: publicKeyJwk.n, e: publicKeyJwk.e, alg: "RS256", ext: true }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]) : null) },
23
+ onEvent: async (event) => events.push(event.id),
24
+ ...overrides,
25
+ },
26
+ );
27
+ const deliver = async (body, tamper = (b) => b) => {
28
+ const { headers } = await signWebhookRequest({ method: "POST", url: ENDPOINT, body, key: privateKey, kid: KID });
29
+ return connector.handleRequest(new Request(ENDPOINT, { method: "POST", headers, body: tamper(body) }));
30
+ };
31
+ return { connector, events, deliver };
32
+ }
33
+
34
+ test("a signed delivery is verified and reaches the handler once", async () => {
35
+ const { events, deliver } = await setup();
36
+ const first = await deliver(fixture());
37
+ assert.equal(first.status, 202);
38
+ assert.equal(events.length, 1);
39
+ const replay = await deliver(fixture());
40
+ assert.equal(replay.status, 200);
41
+ assert.deepEqual(await replay.json(), { accepted: true, duplicate: true });
42
+ assert.equal(events.length, 1, "a replayed event id never reaches the handler");
43
+ });
44
+
45
+ test("a tampered body is refused before the handler runs", async () => {
46
+ const { events, deliver } = await setup();
47
+ const res = await deliver(fixture(), (b) => b.replace('"total": 91.35', '"total": 1.00'));
48
+ assert.equal(res.status, 400);
49
+ assert.deepEqual(await res.json(), { accepted: false, code: "digest_mismatch" });
50
+ assert.equal(events.length, 0);
51
+ });
52
+
53
+ test("an unknown signing key is refused", async () => {
54
+ const { privateKey } = await generateDevRs256KeyPair();
55
+ const { connector, events } = await setup();
56
+ const { headers } = await signWebhookRequest({ method: "POST", url: ENDPOINT, body: fixture(), key: privateKey, kid: "other-key" });
57
+ const res = await connector.handleRequest(new Request(ENDPOINT, { method: "POST", headers, body: fixture() }));
58
+ assert.equal(res.status, 401);
59
+ assert.equal(events.length, 0);
60
+ });
61
+
62
+ test("API writes carry an installation token and a reused Idempotency-Key", async () => {
63
+ const calls = [];
64
+ let writes = 0;
65
+ const fetch = async (url, init = {}) => {
66
+ calls.push({ url: String(url), headers: new Headers(init.headers), method: init.method });
67
+ if (String(url).endsWith("/api/apps/oauth/token")) {
68
+ return Response.json({ access_token: "tok-1", token_type: "Bearer", expires_in: 3600, scope: "inventory:write" });
69
+ }
70
+ if (++writes === 1) return new Response("{}", { status: 503, headers: { "retry-after": "0" } });
71
+ return Response.json({ ok: true });
72
+ };
73
+ const { connector } = await setup(
74
+ { TOT_STOREFRONT_ORIGIN: "https://acme.example.com", TOT_CLIENT_ID: "client-1", TOT_CLIENT_SECRET: "secret-1" },
75
+ { fetch },
76
+ );
77
+ assert.ok(connector.api, "api client exists once the origin and credentials are set");
78
+ const res = await connector.api.post("/inventory/movements", { sku: "SKU-1", quantityDelta: -1 });
79
+ assert.equal(res.status, 200);
80
+
81
+ const token = calls.find((c) => c.url.endsWith("/api/apps/oauth/token"));
82
+ assert.match(token.headers.get("authorization"), /^Basic /);
83
+ const posts = calls.filter((c) => c.url.endsWith("/api/apps/v1/inventory/movements"));
84
+ assert.equal(posts.length, 2, "the 503 was retried");
85
+ assert.equal(posts[0].headers.get("authorization"), "Bearer tok-1");
86
+ assert.ok(posts[0].headers.get("idempotency-key"));
87
+ assert.equal(posts[0].headers.get("idempotency-key"), posts[1].headers.get("idempotency-key"));
88
+ });
89
+
90
+ test("without credentials there is no API client", async () => {
91
+ const { connector } = await setup();
92
+ assert.equal(connector.api, null);
93
+ });