@tokenoftrust/cli 7.14.2 → 7.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.
package/bin/tot.mjs CHANGED
@@ -79,6 +79,8 @@ const COMMANDS = [
79
79
  { invocation: "inbox [list|read|ack|done|snooze|reply|threshold]", blurb: "your Token of Trust inbox — replies to your feedback and other news" },
80
80
  { invocation: "app scaffold <name>", blurb: "scaffold a Storefront Private App" },
81
81
  { invocation: "app dev ...", blurb: "local, offline Private App webhook/manifest/JWT harness" },
82
+ { invocation: "app listen [--forward-to <url>] [--mode=offline|poll]", blurb: "local webhook relay/inspector: verify, forward and log deliveries without secrets" },
83
+ { invocation: "app trigger <topic>", blurb: "send a signed synthetic CloudEvent (any manifest topic) to your local app" },
82
84
  { invocation: "app conformance --url <webhookUrl>", blurb: "check a running local connector's webhook contract" },
83
85
  { invocation: "app install", blurb: "install your Private App on your store (env defaults to test); prints the client secret once" },
84
86
  { invocation: "app update <installId>", blurb: "push your app's current version, scopes and manifest to an install" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.14.2",
3
+ "version": "7.15.0",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -16,7 +16,7 @@ const MAX_MOCK_BODY_BYTES = 65_536;
16
16
  const CURRENCY = "USD";
17
17
 
18
18
  /**
19
- * @typedef {{ method: string, path: string, idempotencyKey: string | null, body: string }} MockRequest
19
+ * @typedef {{ method: string, path: string, idempotencyKey: string | null, body: string, status?: number }} MockRequest
20
20
  * @typedef {{ status: number, headers: Record<string, string>, body: string }} MockResponse
21
21
  * @typedef {{ log: MockRequest[], mark: number }} StepContext
22
22
  * @typedef {{
@@ -24,6 +24,7 @@ const CURRENCY = "USD";
24
24
  * body: string,
25
25
  * acknowledgment?: "initial" | "replay",
26
26
  * tamper?: boolean,
27
+ * observed?: (context: StepContext) => string | undefined,
27
28
  * expect?: (ack: any, context: StepContext) => string | undefined,
28
29
  * rejected?: (status: number) => string,
29
30
  * refusal?: string,
@@ -196,7 +197,10 @@ function marketingEsp() {
196
197
  evaluate(log) {
197
198
  const push = log.find((request) => request.path.startsWith(`${API_PREFIX}customers`) && request.method !== "GET"
198
199
  && !(request.method === "POST" && request.path.endsWith("/marketing-opt-out")));
199
- return push && `contact push refused: ${push.method} ${push.path}`;
200
+ if (!push) return undefined;
201
+ // The path is connector-chosen and may carry a contact value, so only the reviewed operation name is reported.
202
+ const operation = /\/(marketing-contact|consent|marketing-opt-out)$/.exec(push.path)?.[1] ?? "customer route";
203
+ return `contact push refused: ${push.method} ${operation}`;
200
204
  },
201
205
  },
202
206
  {
@@ -373,8 +377,9 @@ function accountingGl() {
373
377
  expect(ack) {
374
378
  const debit = ack?.journal?.debitMinor;
375
379
  const credit = ack?.journal?.creditMinor;
376
- const balanced = Number.isSafeInteger(debit) && Number.isSafeInteger(credit) && debit === credit && debit > 0;
377
- return balanced ? undefined : `unbalanced journal (debitMinor ${JSON.stringify(debit) ?? "missing"}, creditMinor ${JSON.stringify(credit) ?? "missing"})`;
380
+ // Only validated integers reach the finding: an acknowledgment field is connector-chosen and may hold anything.
381
+ if (!Number.isSafeInteger(debit) || !Number.isSafeInteger(credit)) return "acknowledgment carries no integer journal.debitMinor and journal.creditMinor";
382
+ return debit === credit && debit > 0 ? undefined : `unbalanced journal (debitMinor ${debit}, creditMinor ${credit})`;
378
383
  },
379
384
  }),
380
385
  step("Settlement replay", {
@@ -564,10 +569,19 @@ function biExport() {
564
569
  }
565
570
 
566
571
  const statusPath = `${API_PREFIX}exports/${scopeDenied.id}`;
572
+ const scopeDeniedPaths = [statusPath, `${statusPath}/download`];
573
+ /** A verdict on digest counts only when this delivery fetched that fixture's bytes. @param {{ id: string }} fixture */
574
+ const bytesDownloaded = (fixture) => (/** @type {StepContext} */ { log, mark }) => {
575
+ const path = `${DOWNLOAD_PREFIX}${fixture.id}/0`;
576
+ return log.slice(mark).some((request) => request.method === "GET" && request.path === path && request.status === 200)
577
+ ? undefined
578
+ : "export bytes not downloaded (fetch the download URL and hash those bytes before acknowledging)";
579
+ };
567
580
  const steps = [
568
581
  step("Signature tamper refused", { id: "export-tampered", topic: "export.completed", data: tampered.event, minute: 10, tamper: true }),
569
582
  step("Export verified", {
570
583
  id: "export-verified", topic: "export.completed", data: verified.event, minute: 11, acknowledgment: "initial",
584
+ observed: bytesDownloaded(verified),
571
585
  expect(ack) {
572
586
  if (ack?.verified !== true) return "export not verified (acknowledge {\"verified\":true} after the bytes match sha256Digest)";
573
587
  return ack?.watermark === verified.event.watermarkMaxUpdatedAt
@@ -578,6 +592,7 @@ function biExport() {
578
592
  step("Export replay", { id: "export-verified", topic: "export.completed", data: verified.event, minute: 12, acknowledgment: "replay" }),
579
593
  step("Digest mismatch refused", {
580
594
  id: "export-mismatch", topic: "export.completed", data: mismatch.event, minute: 13, refusal: "digest mismatch refused",
595
+ observed: bytesDownloaded(mismatch),
581
596
  expect(ack) {
582
597
  if (ack?.verified === true) return "digest mismatch accepted";
583
598
  return ack?.verified === false ? undefined : "acknowledgment carries no verified:false for a digest mismatch";
@@ -586,9 +601,13 @@ function biExport() {
586
601
  step("Scope-denied export handled", {
587
602
  id: "export-scope-denied", topic: "export.completed", data: scopeDenied.event, minute: 14,
588
603
  rejected: (status) => `HTTP ${status} scope_denied refusal not handled; answer 2xx with {"verified":false} so the platform does not retry`,
604
+ observed({ log, mark }) {
605
+ const denied = log.slice(mark).some((request) => scopeDeniedPaths.includes(request.path) && request.status === 403);
606
+ return denied ? undefined : "no 403 scope_denied read observed (read the export before acknowledging)";
607
+ },
589
608
  expect(ack, { log, mark }) {
590
609
  if (ack?.verified !== false) return "scope-denied export loaded (acknowledge {\"verified\":false})";
591
- return retriedRead(log.slice(mark), [statusPath, `${statusPath}/download`]);
610
+ return retriedRead(log.slice(mark), scopeDeniedPaths);
592
611
  },
593
612
  }),
594
613
  ];
@@ -615,7 +634,9 @@ export function createArchetypePlan(archetype) {
615
634
  /** @type {MockRequest} */
616
635
  const request = { method, path: parsed.pathname, idempotencyKey: typeof key === "string" ? key : null, body };
617
636
  log.push(request);
618
- return route(request, parsed);
637
+ const response = route(request, parsed);
638
+ request.status = response.status;
639
+ return response;
619
640
  },
620
641
  };
621
642
  }
@@ -667,8 +688,12 @@ export function judgeDelivery(step, { status, ack, initialAccepted, log, mark })
667
688
  return { finding: `HTTP ${status} tampered delivery not refused with 4xx`, initial: false };
668
689
  }
669
690
  if (status >= 300 && status < 400) return { finding: `HTTP ${status} redirect refused`, initial: false };
691
+ // Evidence the connector did the work, judged from the mock platform API log before any verdict it states.
692
+ const missing = step.observed?.({ log, mark });
670
693
  if (!success) {
671
- if (step.refusal && status >= 400 && status < 500) return { detail: step.refusal, initial: false };
694
+ if (step.refusal && status >= 400 && status < 500) {
695
+ return missing ? { finding: `HTTP ${status} ${missing}`, initial: false } : { detail: step.refusal, initial: false };
696
+ }
672
697
  return { finding: step.rejected ? step.rejected(status) : `HTTP ${status} delivery rejected`, initial: false };
673
698
  }
674
699
  const duplicate = ack?.accepted === true && ack?.duplicate === true;
@@ -677,7 +702,7 @@ export function judgeDelivery(step, { status, ack, initialAccepted, log, mark })
677
702
  if (replay && !duplicate) return { finding: `HTTP ${status} delivery acknowledged without duplicate confirmation`, initial: false };
678
703
  if (replay && !initialAccepted) return { finding: `HTTP ${status} duplicate reported without a successful initial delivery`, initial: false };
679
704
  const initial = step.acknowledgment === "initial";
680
- const finding = step.expect?.(ack, { log, mark });
705
+ const finding = missing ?? step.expect?.(ack, { log, mark });
681
706
  if (finding) return { finding: `HTTP ${status} ${finding}`, initial };
682
707
  return { detail: replay ? "duplicate acknowledged" : "delivery acknowledged", initial };
683
708
  }
@@ -14,6 +14,8 @@ const USAGE = `tot app — build and install a Storefront Private App
14
14
 
15
15
  tot app scaffold <name> scaffold a runnable Private App skeleton
16
16
  tot app dev ... local, offline webhook/manifest/JWT harness (see \`tot app dev --help\`)
17
+ tot app listen [--forward-to <url>] [--mode=offline|poll] local webhook relay/inspector (see \`tot app listen --help\`)
18
+ tot app trigger <topic> send a signed synthetic webhook to your local app (see \`tot app trigger --help\`)
17
19
  tot app conformance --url <webhookUrl> check a running local connector's webhook contract
18
20
  tot app conformance --certify issue a conformance receipt (see \`tot app conformance --help\`)
19
21
  tot app install install your app on your store (env defaults to test); prints the client secret once
@@ -46,6 +48,14 @@ export async function run(argv, ctx) {
46
48
  const { run: runDev } = await import("./dev.mjs");
47
49
  return /** @type {any} */ (runDev)(rest, ctx);
48
50
  }
51
+ if (sub === "listen") {
52
+ const { run: runListen } = await import("./listen.mjs");
53
+ return runListen(rest, ctx);
54
+ }
55
+ if (sub === "trigger") {
56
+ const { run: runTrigger } = await import("./trigger.mjs");
57
+ return runTrigger(rest);
58
+ }
49
59
  if (sub === "conformance") {
50
60
  const { runAppConformance } = await import("./conformance.mjs");
51
61
  return runAppConformance(rest);
@@ -0,0 +1,251 @@
1
+ /**
2
+ * `tot app listen` — a local webhook relay/inspector for a Private App.
3
+ *
4
+ * --mode=offline (default) HTTP receiver on --port that verifies each delivery's
5
+ * RFC 9421 signature against <app>/.tot/dev-keys.json,
6
+ * re-signs it for --forward-to, forwards, and logs it.
7
+ * Pair it with `tot app trigger`.
8
+ * --mode=poll --install <id> tails the store's /api/apps/admin/webhooks/deliveries
9
+ * and forwards each new delivery to --forward-to, no tunnel.
10
+ * The store does not expose delivery bodies, so the forwarded
11
+ * payload is a synthetic CloudEvent for the delivery's topic.
12
+ *
13
+ * Logs carry timestamp, topic, delivery id, signature result, forwarded status and
14
+ * latency. Signatures, keys and credentials are never printed.
15
+ */
16
+ import { createServer } from "node:http";
17
+ import { fail } from "../../errors.mjs";
18
+ import { resolveViewerTransport } from "../../viewer-session.mjs";
19
+ import { signWebhookRequest, verifyWebhookSignature } from "../../vendor/private-apps-devkit.mjs";
20
+ import { ensureDevKeys, manifestKeyId, makeRequestId, makeTraceparent, parseTopArgs } from "./dev.mjs";
21
+ import { CLOUDEVENT_TYPE_PREFIX, DEFAULT_LISTEN_PORT, syntheticCloudEvent } from "./trigger.mjs";
22
+
23
+ const DEFAULT_POLL_INTERVAL_MS = 3000;
24
+
25
+ const USAGE = `tot app listen — local webhook relay and inspector
26
+
27
+ tot app listen [--forward-to <local-url>] [--port <port>] [--app <dir>]
28
+ offline: receive \`tot app trigger\` deliveries, verify, forward, log
29
+ tot app listen --mode=poll --install <installId> --forward-to <local-url> [--tenant <appDomain>]
30
+ [--url <storefront>] [--interval <ms>]
31
+ poll: tail the store's deliveries and forward them locally
32
+
33
+ Default --port ${DEFAULT_LISTEN_PORT}. Logs never include signatures, keys or credentials.`;
34
+
35
+ /** @param {string[]} argv */
36
+ export function parseListenArgs(argv) {
37
+ /** @type {any} */
38
+ const a = { mode: "offline", forwardTo: null, port: DEFAULT_LISTEN_PORT, install: null, tenant: null, url: null, interval: DEFAULT_POLL_INTERVAL_MS, color: null, help: false, unknown: [] };
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const t = argv[i];
41
+ const eq = t.startsWith("--") ? t.indexOf("=") : -1;
42
+ const flag = eq > 0 ? t.slice(0, eq) : t;
43
+ const value = () => (eq > 0 ? t.slice(eq + 1) : argv[++i]);
44
+ if (flag === "--forward-to") a.forwardTo = value();
45
+ else if (flag === "--port") a.port = Number(value());
46
+ else if (flag === "--mode") a.mode = value();
47
+ else if (flag === "--install") a.install = value();
48
+ else if (flag === "--tenant") a.tenant = value();
49
+ else if (flag === "--url") a.url = value();
50
+ else if (flag === "--interval") a.interval = Number(value());
51
+ else if (flag === "--no-color") a.color = false;
52
+ else if (flag === "--help" || flag === "-h") a.help = true;
53
+ else a.unknown.push(t);
54
+ }
55
+ return a;
56
+ }
57
+
58
+ const paint = (on, code, s) => (on ? `\x1b[${code}m${s}\x1b[0m` : s);
59
+
60
+ /**
61
+ * One log line. Pure: timestamp and color are inputs.
62
+ * @param {any} entry { at, topic, deliveryId, signature, status, latencyMs, note }
63
+ * @param {boolean} [color]
64
+ */
65
+ export function formatDeliveryLog(entry, color = false) {
66
+ const { at, topic, deliveryId, signature, status, latencyMs, note } = entry;
67
+ const ts = at.toISOString().slice(11, 23);
68
+ const sig = signature === "ok" ? paint(color, 32, "sig=ok")
69
+ : signature === "n/a" ? paint(color, 90, "sig=n/a")
70
+ : paint(color, 31, `sig=FAIL(${signature})`);
71
+ const code = status === null || status === undefined ? paint(color, 31, "fwd=none")
72
+ : `fwd=${paint(color, status >= 200 && status < 300 ? 32 : 31, String(status))}`;
73
+ const ms = latencyMs === null || latencyMs === undefined ? "" : ` ${latencyMs}ms`;
74
+ return `${paint(color, 90, ts)} ${paint(color, 36, topic || "?")} delivery=${deliveryId || "?"} ${sig} ${code}${ms}${note ? ` — ${note}` : ""}`;
75
+ }
76
+
77
+ /** Parse JSON without throwing: { ok: true, value } or { ok: false, error }. */
78
+ function parseJson(text) {
79
+ try {
80
+ return { ok: true, value: JSON.parse(text) };
81
+ } catch (e) {
82
+ return { ok: false, error: e?.message || String(e) };
83
+ }
84
+ }
85
+
86
+ function topicOf(body) {
87
+ const parsed = parseJson(body);
88
+ if (!parsed.ok) return "invalid-json";
89
+ const type = parsed.value?.type;
90
+ return typeof type === "string" ? type.replace(CLOUDEVENT_TYPE_PREFIX, "") : "unknown";
91
+ }
92
+
93
+ /** Sign `body` for `url` with the dev key and POST it. Returns { status, text } or { error }. */
94
+ async function forward({ url, body, keys, fetchImpl, requestId, traceparent }) {
95
+ const { headers } = await signWebhookRequest({ method: "POST", url, body, key: keys.privateKey, kid: keys.kid });
96
+ const started = Date.now();
97
+ try {
98
+ const res = await fetchImpl(url, {
99
+ method: "POST",
100
+ headers: { ...headers, "content-type": "application/json", "tot-request-id": requestId, traceparent },
101
+ body,
102
+ });
103
+ return { status: res.status, text: await res.text(), latencyMs: Date.now() - started };
104
+ } catch (e) {
105
+ return { error: e?.message || String(e), latencyMs: Date.now() - started };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Handle one offline delivery: verify against the dev public key, forward, log.
111
+ * @returns {Promise<{ status: number, text: string }>} what to answer the sender
112
+ */
113
+ export async function handleOfflineDelivery({ method, url, headers, body }, { keys, forwardTo, fetchImpl, log, color, now = () => new Date() }) {
114
+ const at = now();
115
+ const verified = await verifyWebhookSignature({ method, url, body, headers, publicKey: keys.publicKey });
116
+ const signature = verified.ok ? "ok" : verified.code;
117
+ const topic = topicOf(body);
118
+ const deliveryId = headers["tot-delivery-id"] || headers["tot-request-id"] || null;
119
+
120
+ if (!forwardTo) {
121
+ log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: null, note: "no --forward-to; not forwarded" }, color));
122
+ return { status: verified.ok ? 200 : 401, text: JSON.stringify({ received: true, signature }) };
123
+ }
124
+ const sent = await forward({
125
+ url: forwardTo, body, keys, fetchImpl,
126
+ requestId: headers["tot-request-id"] || makeRequestId(),
127
+ traceparent: headers.traceparent || makeTraceparent(),
128
+ });
129
+ if (sent.error) {
130
+ log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: sent.latencyMs, note: `could not reach ${forwardTo}: ${sent.error}` }, color));
131
+ return { status: 502, text: JSON.stringify({ error: "forward_failed" }) };
132
+ }
133
+ log(formatDeliveryLog({ at, topic, deliveryId, signature, status: sent.status, latencyMs: sent.latencyMs }, color));
134
+ return { status: sent.status, text: sent.text };
135
+ }
136
+
137
+ /**
138
+ * One poll pass: fetch deliveries, forward each one not in `seen`, log it.
139
+ * @returns {Promise<{ ok: true, forwarded: number } | { ok: false, message: string, hint?: string }>}
140
+ */
141
+ export async function pollOnce({ transport, tenant, installId, forwardTo, keys, fetchImpl, seen, log, color, now = () => new Date() }) {
142
+ let res;
143
+ let text;
144
+ try {
145
+ res = await fetchImpl(`${transport.base}/api/apps/admin/webhooks/deliveries?tenant=${encodeURIComponent(tenant)}`, {
146
+ headers: { ...transport.authHeaders, accept: "application/json" },
147
+ });
148
+ text = await res.text();
149
+ } catch (e) {
150
+ return { ok: false, message: `could not reach the store: ${e?.message || e}`, hint: "check --url / your network" };
151
+ }
152
+ const parsed = parseJson(text);
153
+ const data = parsed.ok ? parsed.value : undefined;
154
+ if (res.ok && !parsed.ok) {
155
+ return { ok: false, message: `the store returned an unreadable delivery list (${parsed.error})`, hint: "retry shortly" };
156
+ }
157
+ if (!res.ok) {
158
+ const reason = typeof data?.error === "string" ? data.error : `HTTP ${res.status}`;
159
+ return { ok: false, message: `the store refused the delivery list (${reason})`, hint: res.status === 401 || res.status === 403 ? "tot login, then re-run" : "retry shortly" };
160
+ }
161
+ const fresh = (Array.isArray(data?.deliveries) ? data.deliveries : [])
162
+ .filter((d) => d?.installId === installId && d.deliveryId && !seen.has(d.deliveryId))
163
+ .sort((x, y) => String(x.createdAt).localeCompare(String(y.createdAt)));
164
+ for (const d of fresh) {
165
+ seen.add(d.deliveryId);
166
+ if (!forwardTo) continue;
167
+ const at = now();
168
+ const body = JSON.stringify(syntheticCloudEvent(d.topic, { tenant, installId }), null, 2) + "\n";
169
+ const note = `store state=${d.state} attempts=${d.attempts}; payload is synthetic (store does not expose bodies)`;
170
+ const sent = await forward({ url: forwardTo, body, keys, fetchImpl, requestId: d.lastTraceId || makeRequestId(), traceparent: makeTraceparent() });
171
+ log(formatDeliveryLog({
172
+ at, topic: d.topic, deliveryId: d.deliveryId, signature: "n/a",
173
+ status: sent.error ? null : sent.status, latencyMs: sent.latencyMs,
174
+ note: sent.error ? `could not reach ${forwardTo}: ${sent.error}` : note,
175
+ }, color));
176
+ }
177
+ return { ok: true, forwarded: fresh.length };
178
+ }
179
+
180
+ function validForwardUrl(u) {
181
+ try { return ["http:", "https:"].includes(new URL(u).protocol); } catch { return false; }
182
+ }
183
+
184
+ /**
185
+ * @param {string[]} argv @param {any} ctx
186
+ * @param {Record<string, any>} [deps] injectable: out, err, env, fetchImpl, resolveViewerTransport, signal, sleep
187
+ */
188
+ export async function run(argv, ctx, deps = {}) {
189
+ const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
190
+ const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
191
+ const env = deps.env || process.env;
192
+ const fetchImpl = deps.fetchImpl || fetch;
193
+ const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
194
+
195
+ const { appDir, rest } = parseTopArgs(argv);
196
+ const args = parseListenArgs(rest);
197
+ if (args.help) { out(USAGE); return 0; }
198
+ if (args.unknown.length) { err(fail(`unknown option ${args.unknown[0]}`, "tot app listen --help")); return 2; }
199
+ if (args.mode !== "offline" && args.mode !== "poll") { err(fail(`--mode must be offline or poll (got "${args.mode}")`, "tot app listen --help")); return 2; }
200
+ if (args.forwardTo && !validForwardUrl(args.forwardTo)) { err(fail(`--forward-to must be an http(s) URL (got "${args.forwardTo}")`, "e.g. --forward-to http://localhost:8787/webhooks")); return 2; }
201
+ const color = args.color ?? Boolean(process.stdout.isTTY && !env.NO_COLOR);
202
+ const keys = await ensureDevKeys(appDir, { kid: manifestKeyId(appDir) });
203
+
204
+ if (args.mode === "poll") {
205
+ if (!args.install) { err(fail("--mode=poll needs --install <installId>", "find it with `tot app list`")); return 2; }
206
+ if (!args.forwardTo) { err(fail("--mode=poll needs --forward-to <local-url>", "e.g. --forward-to http://localhost:8787/webhooks")); return 2; }
207
+ if (!Number.isFinite(args.interval) || args.interval < 250) { err(fail("--interval must be at least 250 (ms)")); return 2; }
208
+ const tenant = String(args.tenant || ctx?.tenant || "").trim().toLowerCase();
209
+ if (!tenant) { err(fail("no store to act on", "pass --tenant <appDomain>, or run inside a store checkout")); return 2; }
210
+ const transport = await (deps.resolveViewerTransport || resolveViewerTransport)({ tenant, env, fetchImpl, storefrontUrl: args.url || env.TOT_STOREFRONT_URL || null });
211
+ if (!transport.ok) { err(`✗ ${transport.message}\n\n → next: ${transport.hint}`); return 1; }
212
+ out(`tailing deliveries for ${args.install} on ${tenant} → ${args.forwardTo} (every ${args.interval}ms, ctrl-c to stop)`);
213
+ const seen = new Set();
214
+ let primed = false;
215
+ while (!deps.signal?.aborted) {
216
+ // First pass records the existing backlog so only deliveries that arrive afterwards are forwarded.
217
+ const pass = await pollOnce({ transport, tenant, installId: args.install, forwardTo: primed ? args.forwardTo : null, keys, fetchImpl, seen, log: out, color });
218
+ if (!pass.ok) { err(`✗ ${pass.message}${pass.hint ? `\n\n → next: ${pass.hint}` : ""}`); return 1; }
219
+ primed = true;
220
+ if (deps.once) return 0;
221
+ await sleep(args.interval);
222
+ }
223
+ return 0;
224
+ }
225
+
226
+ const server = createServer(async (req, res) => {
227
+ const chunks = [];
228
+ for await (const c of req) chunks.push(c);
229
+ const body = Buffer.concat(chunks).toString("utf8");
230
+ const headers = Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v]));
231
+ const result = await handleOfflineDelivery(
232
+ { method: req.method || "POST", url: `http://${req.headers.host}${req.url}`, headers, body },
233
+ { keys, forwardTo: args.forwardTo, fetchImpl, log: out, color },
234
+ );
235
+ res.writeHead(result.status, { "content-type": "application/json" });
236
+ res.end(result.text);
237
+ });
238
+ try {
239
+ await new Promise((resolveListen, reject) => { server.once("error", reject); server.listen(args.port, "127.0.0.1", () => resolveListen(undefined)); });
240
+ } catch (e) {
241
+ err(fail(`could not listen on port ${args.port}: ${e.message}`, "pass a free --port"));
242
+ return 1;
243
+ }
244
+ const address = server.address();
245
+ const port = address && typeof address === "object" ? address.port : args.port;
246
+ out(`listening on http://localhost:${port}/webhooks (verifying with keyid ${keys.kid}${args.forwardTo ? `, forwarding to ${args.forwardTo}` : ", no --forward-to"})`);
247
+ out("send one with: tot app trigger <topic>");
248
+ if (deps.onListening) deps.onListening({ port, close: () => new Promise((r) => server.close(r)) });
249
+ await new Promise((r) => { server.once("close", r); deps.signal?.addEventListener("abort", () => server.close()); process.once("SIGINT", () => server.close()); });
250
+ return 0;
251
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * `tot app trigger <topic>` — the ergonomic front-end over `tot app dev emit`.
3
+ * Loads `fixtures/<topic>.cloudevent.json` when the app has one, otherwise
4
+ * synthesizes a contract-shaped CloudEvent for any manifest webhook topic, signs it
5
+ * with the app's `.tot/dev-keys.json` (RFC 9421 + Content-Digest) and POSTs it,
6
+ * printing the exact HTTP response plus signature diagnostics.
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { join, resolve } from "node:path";
10
+ import { fail } from "../../errors.mjs";
11
+ import { MANIFEST_WEBHOOK_TOPICS, signWebhookRequest } from "../../vendor/private-apps-devkit.mjs";
12
+ import { ensureDevKeys, manifestKeyId, makeRequestId, makeTraceparent, parseTopArgs } from "./dev.mjs";
13
+
14
+ export const DEFAULT_LISTEN_PORT = 8788;
15
+ export const DEFAULT_TRIGGER_URL = `http://localhost:${DEFAULT_LISTEN_PORT}/webhooks`;
16
+ export const CLOUDEVENT_TYPE_PREFIX = "com.tokenoftrust.storefront.";
17
+
18
+ const USAGE = `tot app trigger — send a signed synthetic webhook to your local app
19
+
20
+ tot app trigger <topic> [--url <url>] [--fixture <path>] [--app <dir>] [--json]
21
+ tot app trigger --list list every supported topic
22
+
23
+ Uses fixtures/<topic>.cloudevent.json when present, otherwise a synthetic CloudEvent.
24
+ Signs with <app>/.tot/dev-keys.json (RFC 9421 + Content-Digest). Default --url ${DEFAULT_TRIGGER_URL}
25
+ (where \`tot app listen\` waits).`;
26
+
27
+ const ORDER = {
28
+ id: "ord_synthetic_10482", status: "created", currency: "USD", customerHash: "cus_h_synthetic0001",
29
+ subtotal: 84, total: 91.35,
30
+ lineItems: [{ sku: "SYNTHETIC-SKU", handle: "synthetic-product", quantity: 1, lineTotal: 84 }],
31
+ };
32
+
33
+ /** Per-topic `data` for synthetic events; topics not listed get a generic resource envelope. */
34
+ const DATA = {
35
+ "app.installed": { installId: "inst_synthetic", appId: "synthetic-app" },
36
+ "app.uninstalled": { installId: "inst_synthetic", appId: "synthetic-app" },
37
+ "catalog.product.updated": { id: "prod_synthetic", handle: "synthetic-product", title: "Synthetic product" },
38
+ "inventory.changed": { sku: "SYNTHETIC-SKU", locationId: "unspecified", balance: 12, available: 12, asOf: "@now" },
39
+ "inventory.stocktake.completed": { stocktakeId: "stk_synthetic", locationId: "unspecified", adjustments: 0 },
40
+ "order.paid": { ...ORDER, status: "paid" },
41
+ "order.fulfilled": { ...ORDER, status: "fulfilled" },
42
+ "order.partially_fulfilled": { ...ORDER, status: "partially_fulfilled" },
43
+ "order.cancelled": { ...ORDER, status: "cancelled" },
44
+ "order.updated": { ...ORDER, status: "updated" },
45
+ "order.refunded": { ...ORDER, status: "refunded", refundTotal: 91.35 },
46
+ "order.disputed": { ...ORDER, status: "disputed" },
47
+ "order.invoiced": { ...ORDER, status: "invoiced", invoiceId: "inv_synthetic" },
48
+ "invoice.settled": { invoiceId: "inv_synthetic", orderId: ORDER.id, amount: 91.35, currency: "USD" },
49
+ "settlement.recorded": { settlementId: "set_synthetic", orderId: ORDER.id, amount: 91.35, currency: "USD" },
50
+ "export.completed": { exportId: "exp_synthetic", kind: "orders", rows: 0 },
51
+ "export.failed": { exportId: "exp_synthetic", kind: "orders", errorClass: "synthetic" },
52
+ };
53
+
54
+ export function supportedTopics() {
55
+ return [...MANIFEST_WEBHOOK_TOPICS];
56
+ }
57
+
58
+ /** Build a synthetic CloudEvent for `topic`. `now`/`tenant`/`installId` are injectable for tests. */
59
+ export function syntheticCloudEvent(topic, { now = new Date(), tenant = "example", installId = "inst_synthetic" } = {}) {
60
+ const iso = now.toISOString();
61
+ const base = DATA[topic] ?? (topic.startsWith("order.") ? { ...ORDER, status: topic.slice(6) } : { id: `${topic.replace(/\W+/g, "_")}_synthetic`, topic });
62
+ const data = JSON.parse(JSON.stringify(base).replace(/"@now"/g, JSON.stringify(iso)));
63
+ const rand = Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString("hex");
64
+ return {
65
+ specversion: "1.0",
66
+ id: `evt_synthetic_${rand}`,
67
+ source: `/tenants/${tenant}/storefront`,
68
+ type: `${CLOUDEVENT_TYPE_PREFIX}${topic}`,
69
+ time: iso,
70
+ datacontenttype: "application/json",
71
+ dataschemaversion: "1",
72
+ tenantid: tenant,
73
+ appinstallid: installId,
74
+ retrycount: 0,
75
+ data,
76
+ };
77
+ }
78
+
79
+ /** @param {string[]} argv */
80
+ export function parseTriggerArgs(argv) {
81
+ /** @type {any} */
82
+ const a = { topic: null, url: DEFAULT_TRIGGER_URL, fixture: null, json: false, list: false, unknown: [] };
83
+ for (let i = 0; i < argv.length; i++) {
84
+ const t = argv[i];
85
+ if (t === "--url") a.url = argv[++i];
86
+ else if (t === "--fixture") a.fixture = argv[++i];
87
+ else if (t === "--json") a.json = true;
88
+ else if (t === "--list") a.list = true;
89
+ else if (t.startsWith("--")) a.unknown.push(t);
90
+ else if (!a.topic) a.topic = t;
91
+ }
92
+ return a;
93
+ }
94
+
95
+ /** Resolve the body: explicit/app fixture first, else synthetic. Returns { body, source }. */
96
+ export function resolveTriggerBody(topic, { appDir, fixture }) {
97
+ const path = resolve(fixture || join(appDir, "fixtures", `${topic}.cloudevent.json`));
98
+ if (existsSync(path)) return { ok: true, body: readFileSync(path, "utf8"), source: path };
99
+ if (fixture) return { ok: false, message: `no fixture at ${path}` };
100
+ if (!MANIFEST_WEBHOOK_TOPICS.includes(topic)) {
101
+ return { ok: false, message: `unknown topic "${topic}" and no fixture at ${path}` };
102
+ }
103
+ return { ok: true, body: JSON.stringify(syntheticCloudEvent(topic), null, 2) + "\n", source: "synthetic" };
104
+ }
105
+
106
+ /**
107
+ * @param {string[]} argv
108
+ * @param {{ out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch }} [deps]
109
+ */
110
+ export async function run(argv, deps = {}) {
111
+ const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
112
+ const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
113
+ const fetchImpl = deps.fetchImpl || fetch;
114
+
115
+ if (argv[0] === "--help" || argv[0] === "-h" || argv[0] === "help") { out(USAGE); return 0; }
116
+ const { appDir, rest } = parseTopArgs(argv);
117
+ const args = parseTriggerArgs(rest);
118
+ if (args.list) { out(supportedTopics().join("\n")); return 0; }
119
+ if (args.unknown.length) { err(fail(`unknown option ${args.unknown[0]}`, "tot app trigger --help")); return 2; }
120
+ if (!args.topic) { err(fail("tot app trigger needs a topic", "tot app trigger order.created (see --list)")); return 2; }
121
+
122
+ const resolved = resolveTriggerBody(args.topic, { appDir, fixture: args.fixture });
123
+ if (!resolved.ok) { err(fail(resolved.message, "tot app trigger --list, or pass --fixture <path>")); return 2; }
124
+
125
+ const keys = await ensureDevKeys(appDir, { kid: manifestKeyId(appDir) });
126
+ const { headers } = await signWebhookRequest({ method: "POST", url: args.url, body: resolved.body, key: keys.privateKey, kid: keys.kid });
127
+ const requestId = makeRequestId();
128
+ const traceparent = makeTraceparent();
129
+ const sent = { ...headers, "content-type": "application/json", "tot-request-id": requestId, traceparent };
130
+
131
+ const report = { topic: args.topic, url: args.url, keyid: keys.kid, fixture: resolved.source, requestId, traceparent, signatureInput: headers["signature-input"], contentDigest: headers["content-digest"] };
132
+ if (!args.json) {
133
+ out(`→ POST ${args.url} (topic: ${args.topic}, fixture: ${resolved.source}, keyid: ${keys.kid})`);
134
+ out(` tot-request-id: ${requestId}`);
135
+ out(` traceparent: ${traceparent}`);
136
+ out(` content-digest: ${headers["content-digest"]}`);
137
+ out(` signature-input: ${headers["signature-input"]}`);
138
+ }
139
+
140
+ let response;
141
+ const started = Date.now();
142
+ try {
143
+ response = await fetchImpl(args.url, { method: "POST", headers: sent, body: resolved.body });
144
+ } catch (e) {
145
+ err(fail(`could not reach ${args.url}: ${e.message}`, "start a receiver first: `tot app listen --forward-to <your-app-url>` or `node server.js`"));
146
+ return 1;
147
+ }
148
+ const text = await response.text();
149
+ const latencyMs = Date.now() - started;
150
+ if (args.json) out(JSON.stringify({ ...report, status: response.status, ok: response.ok, latencyMs, response: text }));
151
+ else out(`← ${response.status} ${response.statusText || ""} (${latencyMs}ms)\n${text}`.trimEnd());
152
+ return response.ok ? 0 : 1;
153
+ }