@tokenoftrust/cli 6.14.5 → 6.15.0

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.
@@ -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
+ });