@tokenoftrust/cli 7.14.3 → 7.15.1
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 +2 -0
- package/package.json +1 -1
- package/src/commands/app/index.mjs +10 -0
- package/src/commands/app/listen.mjs +271 -0
- package/src/commands/app/trigger.mjs +185 -0
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.
|
|
3
|
+
"version": "7.15.1",
|
|
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",
|
|
@@ -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,271 @@
|
|
|
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
|
+
/** The forward URL as safe to print: no userinfo, query or fragment. Forwarding uses the full URL. */
|
|
87
|
+
export function displayUrl(raw) {
|
|
88
|
+
try {
|
|
89
|
+
const u = new URL(String(raw));
|
|
90
|
+
const query = u.search ? "?…" : "";
|
|
91
|
+
return `${u.protocol}//${u.host}${u.pathname}${query}`;
|
|
92
|
+
} catch {
|
|
93
|
+
return "<unparseable url>";
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** An error message with every occurrence of the full forward URL replaced by its display form. */
|
|
98
|
+
function redactError(message, raw) {
|
|
99
|
+
return String(message).split(String(raw)).join(displayUrl(raw));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function topicOf(body) {
|
|
103
|
+
const parsed = parseJson(body);
|
|
104
|
+
if (!parsed.ok) return "invalid-json";
|
|
105
|
+
const type = parsed.value?.type;
|
|
106
|
+
return typeof type === "string" ? type.replace(CLOUDEVENT_TYPE_PREFIX, "") : "unknown";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Sign `body` for `url` with the dev key and POST it. Returns { status, text } or { error }. */
|
|
110
|
+
async function forward({ url, body, keys, fetchImpl, requestId, traceparent }) {
|
|
111
|
+
const { headers } = await signWebhookRequest({ method: "POST", url, body, key: keys.privateKey, kid: keys.kid });
|
|
112
|
+
const started = Date.now();
|
|
113
|
+
try {
|
|
114
|
+
const res = await fetchImpl(url, {
|
|
115
|
+
method: "POST",
|
|
116
|
+
headers: { ...headers, "content-type": "application/json", "tot-request-id": requestId, traceparent },
|
|
117
|
+
body,
|
|
118
|
+
});
|
|
119
|
+
return { status: res.status, text: await res.text(), latencyMs: Date.now() - started };
|
|
120
|
+
} catch (e) {
|
|
121
|
+
return { error: e?.message || String(e), latencyMs: Date.now() - started };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Handle one offline delivery: verify against the dev public key, forward, log.
|
|
127
|
+
* @returns {Promise<{ status: number, text: string }>} what to answer the sender
|
|
128
|
+
*/
|
|
129
|
+
export async function handleOfflineDelivery({ method, url, headers, body }, { keys, forwardTo, fetchImpl, log, color, now = () => new Date() }) {
|
|
130
|
+
const at = now();
|
|
131
|
+
const verified = await verifyWebhookSignature({ method, url, body, headers, publicKey: keys.publicKey });
|
|
132
|
+
const signature = verified.ok ? "ok" : verified.code;
|
|
133
|
+
const topic = topicOf(body);
|
|
134
|
+
const deliveryId = headers["tot-delivery-id"] || headers["tot-request-id"] || null;
|
|
135
|
+
|
|
136
|
+
if (!verified.ok) {
|
|
137
|
+
log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: null, note: "signature verification failed; rejected, not forwarded" }, color));
|
|
138
|
+
return { status: 401, text: JSON.stringify({ received: false, signature }) };
|
|
139
|
+
}
|
|
140
|
+
if (!forwardTo) {
|
|
141
|
+
log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: null, note: "no --forward-to; not forwarded" }, color));
|
|
142
|
+
return { status: 200, text: JSON.stringify({ received: true, signature }) };
|
|
143
|
+
}
|
|
144
|
+
const sent = await forward({
|
|
145
|
+
url: forwardTo, body, keys, fetchImpl,
|
|
146
|
+
requestId: headers["tot-request-id"] || makeRequestId(),
|
|
147
|
+
traceparent: headers.traceparent || makeTraceparent(),
|
|
148
|
+
});
|
|
149
|
+
if (sent.error) {
|
|
150
|
+
log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: sent.latencyMs, note: `could not reach ${displayUrl(forwardTo)}: ${redactError(sent.error, forwardTo)}` }, color));
|
|
151
|
+
return { status: 502, text: JSON.stringify({ error: "forward_failed" }) };
|
|
152
|
+
}
|
|
153
|
+
log(formatDeliveryLog({ at, topic, deliveryId, signature, status: sent.status, latencyMs: sent.latencyMs }, color));
|
|
154
|
+
return { status: sent.status, text: sent.text };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* One poll pass: fetch deliveries, forward each one not in `seen`, log it.
|
|
159
|
+
* @returns {Promise<{ ok: true, forwarded: number } | { ok: false, message: string, hint?: string }>}
|
|
160
|
+
*/
|
|
161
|
+
export async function pollOnce({ transport, tenant, installId, forwardTo, keys, fetchImpl, seen, log, color, now = () => new Date() }) {
|
|
162
|
+
let res;
|
|
163
|
+
let text;
|
|
164
|
+
try {
|
|
165
|
+
res = await fetchImpl(`${transport.base}/api/apps/admin/webhooks/deliveries?tenant=${encodeURIComponent(tenant)}`, {
|
|
166
|
+
headers: { ...transport.authHeaders, accept: "application/json" },
|
|
167
|
+
});
|
|
168
|
+
text = await res.text();
|
|
169
|
+
} catch (e) {
|
|
170
|
+
return { ok: false, message: `could not reach the store: ${e?.message || e}`, hint: "check --url / your network" };
|
|
171
|
+
}
|
|
172
|
+
const parsed = parseJson(text);
|
|
173
|
+
const data = parsed.ok ? parsed.value : undefined;
|
|
174
|
+
if (res.ok && !parsed.ok) {
|
|
175
|
+
return { ok: false, message: `the store returned an unreadable delivery list (${parsed.error})`, hint: "retry shortly" };
|
|
176
|
+
}
|
|
177
|
+
if (!res.ok) {
|
|
178
|
+
const reason = typeof data?.error === "string" ? data.error : `HTTP ${res.status}`;
|
|
179
|
+
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" };
|
|
180
|
+
}
|
|
181
|
+
const fresh = (Array.isArray(data?.deliveries) ? data.deliveries : [])
|
|
182
|
+
.filter((d) => d?.installId === installId && d.deliveryId && !seen.has(d.deliveryId))
|
|
183
|
+
.sort((x, y) => String(x.createdAt).localeCompare(String(y.createdAt)));
|
|
184
|
+
for (const d of fresh) {
|
|
185
|
+
seen.add(d.deliveryId);
|
|
186
|
+
if (!forwardTo) continue;
|
|
187
|
+
const at = now();
|
|
188
|
+
const body = JSON.stringify(syntheticCloudEvent(d.topic, { tenant, installId }), null, 2) + "\n";
|
|
189
|
+
const note = `store state=${d.state} attempts=${d.attempts}; payload is synthetic (store does not expose bodies)`;
|
|
190
|
+
const sent = await forward({ url: forwardTo, body, keys, fetchImpl, requestId: d.lastTraceId || makeRequestId(), traceparent: makeTraceparent() });
|
|
191
|
+
log(formatDeliveryLog({
|
|
192
|
+
at, topic: d.topic, deliveryId: d.deliveryId, signature: "n/a",
|
|
193
|
+
status: sent.error ? null : sent.status, latencyMs: sent.latencyMs,
|
|
194
|
+
note: sent.error ? `could not reach ${displayUrl(forwardTo)}: ${redactError(sent.error, forwardTo)}` : note,
|
|
195
|
+
}, color));
|
|
196
|
+
}
|
|
197
|
+
return { ok: true, forwarded: fresh.length };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function validForwardUrl(u) {
|
|
201
|
+
try { return ["http:", "https:"].includes(new URL(u).protocol); } catch { return false; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* @param {string[]} argv @param {any} ctx
|
|
206
|
+
* @param {Record<string, any>} [deps] injectable: out, err, env, fetchImpl, resolveViewerTransport, signal, sleep
|
|
207
|
+
*/
|
|
208
|
+
export async function run(argv, ctx, deps = {}) {
|
|
209
|
+
const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
|
|
210
|
+
const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
|
|
211
|
+
const env = deps.env || process.env;
|
|
212
|
+
const fetchImpl = deps.fetchImpl || fetch;
|
|
213
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
214
|
+
|
|
215
|
+
const { appDir, rest } = parseTopArgs(argv);
|
|
216
|
+
const args = parseListenArgs(rest);
|
|
217
|
+
if (args.help) { out(USAGE); return 0; }
|
|
218
|
+
if (args.unknown.length) { err(fail(`unknown option ${args.unknown[0]}`, "tot app listen --help")); return 2; }
|
|
219
|
+
if (args.mode !== "offline" && args.mode !== "poll") { err(fail(`--mode must be offline or poll (got "${args.mode}")`, "tot app listen --help")); return 2; }
|
|
220
|
+
if (args.forwardTo && !validForwardUrl(args.forwardTo)) { err(fail(`--forward-to must be an http(s) URL (got "${displayUrl(args.forwardTo)}")`, "e.g. --forward-to http://localhost:8787/webhooks")); return 2; }
|
|
221
|
+
const color = args.color ?? Boolean(process.stdout.isTTY && !env.NO_COLOR);
|
|
222
|
+
const keys = await ensureDevKeys(appDir, { kid: manifestKeyId(appDir) });
|
|
223
|
+
|
|
224
|
+
if (args.mode === "poll") {
|
|
225
|
+
if (!args.install) { err(fail("--mode=poll needs --install <installId>", "find it with `tot app list`")); return 2; }
|
|
226
|
+
if (!args.forwardTo) { err(fail("--mode=poll needs --forward-to <local-url>", "e.g. --forward-to http://localhost:8787/webhooks")); return 2; }
|
|
227
|
+
if (!Number.isFinite(args.interval) || args.interval < 250) { err(fail("--interval must be at least 250 (ms)")); return 2; }
|
|
228
|
+
const tenant = String(args.tenant || ctx?.tenant || "").trim().toLowerCase();
|
|
229
|
+
if (!tenant) { err(fail("no store to act on", "pass --tenant <appDomain>, or run inside a store checkout")); return 2; }
|
|
230
|
+
const transport = await (deps.resolveViewerTransport || resolveViewerTransport)({ tenant, env, fetchImpl, storefrontUrl: args.url || env.TOT_STOREFRONT_URL || null });
|
|
231
|
+
if (!transport.ok) { err(`✗ ${transport.message}\n\n → next: ${transport.hint}`); return 1; }
|
|
232
|
+
out(`tailing deliveries for ${args.install} on ${tenant} → ${displayUrl(args.forwardTo)} (every ${args.interval}ms, ctrl-c to stop)`);
|
|
233
|
+
const seen = new Set();
|
|
234
|
+
let primed = false;
|
|
235
|
+
while (!deps.signal?.aborted) {
|
|
236
|
+
// First pass records the existing backlog so only deliveries that arrive afterwards are forwarded.
|
|
237
|
+
const pass = await pollOnce({ transport, tenant, installId: args.install, forwardTo: primed ? args.forwardTo : null, keys, fetchImpl, seen, log: out, color });
|
|
238
|
+
if (!pass.ok) { err(`✗ ${pass.message}${pass.hint ? `\n\n → next: ${pass.hint}` : ""}`); return 1; }
|
|
239
|
+
primed = true;
|
|
240
|
+
if (deps.once) return 0;
|
|
241
|
+
await sleep(args.interval);
|
|
242
|
+
}
|
|
243
|
+
return 0;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const server = createServer(async (req, res) => {
|
|
247
|
+
const chunks = [];
|
|
248
|
+
for await (const c of req) chunks.push(c);
|
|
249
|
+
const body = Buffer.concat(chunks).toString("utf8");
|
|
250
|
+
const headers = Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v]));
|
|
251
|
+
const result = await handleOfflineDelivery(
|
|
252
|
+
{ method: req.method || "POST", url: `http://${req.headers.host}${req.url}`, headers, body },
|
|
253
|
+
{ keys, forwardTo: args.forwardTo, fetchImpl, log: out, color },
|
|
254
|
+
);
|
|
255
|
+
res.writeHead(result.status, { "content-type": "application/json" });
|
|
256
|
+
res.end(result.text);
|
|
257
|
+
});
|
|
258
|
+
try {
|
|
259
|
+
await new Promise((resolveListen, reject) => { server.once("error", reject); server.listen(args.port, "127.0.0.1", () => resolveListen(undefined)); });
|
|
260
|
+
} catch (e) {
|
|
261
|
+
err(fail(`could not listen on port ${args.port}: ${e.message}`, "pass a free --port"));
|
|
262
|
+
return 1;
|
|
263
|
+
}
|
|
264
|
+
const address = server.address();
|
|
265
|
+
const port = address && typeof address === "object" ? address.port : args.port;
|
|
266
|
+
out(`listening on http://localhost:${port}/webhooks (verifying with keyid ${keys.kid}${args.forwardTo ? `, forwarding to ${displayUrl(args.forwardTo)}` : ", no --forward-to"})`);
|
|
267
|
+
out("send one with: tot app trigger <topic>");
|
|
268
|
+
if (deps.onListening) deps.onListening({ port, close: () => new Promise((r) => server.close(r)) });
|
|
269
|
+
await new Promise((r) => { server.once("close", r); deps.signal?.addEventListener("abort", () => server.close()); process.once("SIGINT", () => server.close()); });
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
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",
|
|
29
|
+
subtotal: 84, total: 91.35,
|
|
30
|
+
lineItems: [{ sku: "SYNTHETIC-SKU", handle: "synthetic-product", quantity: 1, lineTotal: 84 }],
|
|
31
|
+
};
|
|
32
|
+
const PO = {
|
|
33
|
+
poId: "po_synthetic_1", poNumber: 1, supplierId: "sup_synthetic", status: "draft", version: 0,
|
|
34
|
+
locationId: "unspecified", currency: "USD", asOf: "@now",
|
|
35
|
+
};
|
|
36
|
+
const PROPOSAL = { proposalId: "prop_synthetic", kind: "synthetic.kind", schemaVersion: 1, state: "pending", transitionAt: "@now" };
|
|
37
|
+
const ASSIGNMENT = { assignmentId: "asg_synthetic", orderId: ORDER.id, stage: "preview", state: "active", eventVersion: 1, occurredAt: "@now" };
|
|
38
|
+
const INVOICE_NUMBER = "INV-000001";
|
|
39
|
+
|
|
40
|
+
/** Per-topic `data`, one closed payload per AsyncAPI message (docs/private-apps/contract/asyncapi.yaml). */
|
|
41
|
+
const DATA = {
|
|
42
|
+
"app.installed": {},
|
|
43
|
+
"app.uninstalled": {},
|
|
44
|
+
"catalog.product.updated": { handle: "synthetic-product" },
|
|
45
|
+
"inventory.changed": { sku: "SYNTHETIC-SKU", locationId: "unspecified", balance: 12, available: 12, asOf: "@now" },
|
|
46
|
+
"inventory.stocktake.completed": {
|
|
47
|
+
sessionId: "st_syntheticSessionId01", locationId: "unspecified", kind: "full", completedAt: "@now",
|
|
48
|
+
lineCount: 1, varianceCount: 0, netDelta: 0,
|
|
49
|
+
},
|
|
50
|
+
"purchase_order.created": PO,
|
|
51
|
+
"purchase_order.updated": { ...PO, status: "sent", version: 1 },
|
|
52
|
+
"purchase_order.received": {
|
|
53
|
+
...PO, status: "received", version: 2, receiptKey: "rcpt_synthetic_1",
|
|
54
|
+
lines: [{ lineNo: 1, sku: "SYNTHETIC-SKU", quantity: 1 }],
|
|
55
|
+
},
|
|
56
|
+
"order.created": ORDER,
|
|
57
|
+
"order.paid": ORDER,
|
|
58
|
+
"order.fulfilled": { ...ORDER, status: "fulfilled" },
|
|
59
|
+
"order.partially_fulfilled": ORDER,
|
|
60
|
+
"order.cancelled": { ...ORDER, status: "cancelled" },
|
|
61
|
+
"order.updated": ORDER,
|
|
62
|
+
"order.refunded": { orderId: ORDER.id, refundId: "ref_synthetic", currency: "USD", amountMinor: 9135, occurredAt: "@now" },
|
|
63
|
+
"order.disputed": { orderId: ORDER.id, disputeId: "dsp_synthetic", status: "opened", currency: "USD", amountMinor: 9135, occurredAt: "@now" },
|
|
64
|
+
"order.invoiced": {
|
|
65
|
+
orderId: ORDER.id, invoiceNumber: INVOICE_NUMBER, settlementMode: "net_terms", netTermsDays: 30, currency: "USD",
|
|
66
|
+
subtotal: 84, total: 91.35, lineItems: ORDER.lineItems, issuedAt: "@now",
|
|
67
|
+
},
|
|
68
|
+
"invoice.settled": { orderId: ORDER.id, invoiceNumber: INVOICE_NUMBER, settlementMode: "net_terms", currency: "USD", total: 91.35, settledAt: "@now" },
|
|
69
|
+
"settlement.recorded": { settlementId: "set_synthetic", currency: "USD", grossMinor: 9135, feeMinor: 300, netMinor: 8835, entryCount: 1, settledAt: "@now" },
|
|
70
|
+
"customer.marketing_consent.updated": { customerHash: "cus_h_synthetic0001", marketingConsent: true, updatedAt: "@now" },
|
|
71
|
+
"attribution.finalized": { attributionId: "attr_synthetic", orderId: ORDER.id },
|
|
72
|
+
"checkout.abandoned": { checkoutId: "chk_synthetic", currency: "USD", subtotalMinor: 8400, lineCount: 1, abandonedAt: "@now" },
|
|
73
|
+
"export.completed": {
|
|
74
|
+
exportId: "exp_synthetic", dataset: "orders_financial", format: "ndjson", schemaVersion: "1", rowCount: 0, byteSize: 0,
|
|
75
|
+
sha256Digest: "0".repeat(64), partCount: 1, expiresAt: "@now", completedAt: "@now",
|
|
76
|
+
},
|
|
77
|
+
"export.failed": { exportId: "exp_synthetic", dataset: "orders_financial", errorCode: "timeout", failedAt: "@now" },
|
|
78
|
+
"fulfillment.assignment.created": ASSIGNMENT,
|
|
79
|
+
"fulfillment.assignment.updated": { ...ASSIGNMENT, state: "held", eventVersion: 2 },
|
|
80
|
+
"fulfillment.label.voided": { assignmentId: ASSIGNMENT.assignmentId, orderId: ORDER.id, purchaseId: "pur_synthetic", occurredAt: "@now" },
|
|
81
|
+
"proposal.filed": PROPOSAL,
|
|
82
|
+
"proposal.applied": { ...PROPOSAL, state: "applied" },
|
|
83
|
+
"proposal.rejected": { ...PROPOSAL, state: "rejected" },
|
|
84
|
+
"proposal.expired": { ...PROPOSAL, state: "expired" },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export function supportedTopics() {
|
|
88
|
+
return [...MANIFEST_WEBHOOK_TOPICS];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Build a synthetic CloudEvent for `topic`. `now`/`tenant`/`installId` are injectable for tests. */
|
|
92
|
+
export function syntheticCloudEvent(topic, { now = new Date(), tenant = "example", installId = "inst_synthetic" } = {}) {
|
|
93
|
+
const iso = now.toISOString();
|
|
94
|
+
const data = JSON.parse(JSON.stringify(DATA[topic] ?? {}).replace(/"@now"/g, JSON.stringify(iso)));
|
|
95
|
+
const rand = Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString("hex");
|
|
96
|
+
return {
|
|
97
|
+
specversion: "1.0",
|
|
98
|
+
id: `evt_synthetic_${rand}`,
|
|
99
|
+
source: `/tenants/${tenant}/storefront`,
|
|
100
|
+
type: `${CLOUDEVENT_TYPE_PREFIX}${topic}`,
|
|
101
|
+
time: iso,
|
|
102
|
+
datacontenttype: "application/json",
|
|
103
|
+
dataschemaversion: "1",
|
|
104
|
+
tenantid: tenant,
|
|
105
|
+
appinstallid: installId,
|
|
106
|
+
retrycount: 0,
|
|
107
|
+
data,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** @param {string[]} argv */
|
|
112
|
+
export function parseTriggerArgs(argv) {
|
|
113
|
+
/** @type {any} */
|
|
114
|
+
const a = { topic: null, url: DEFAULT_TRIGGER_URL, fixture: null, json: false, list: false, unknown: [] };
|
|
115
|
+
for (let i = 0; i < argv.length; i++) {
|
|
116
|
+
const t = argv[i];
|
|
117
|
+
if (t === "--url") a.url = argv[++i];
|
|
118
|
+
else if (t === "--fixture") a.fixture = argv[++i];
|
|
119
|
+
else if (t === "--json") a.json = true;
|
|
120
|
+
else if (t === "--list") a.list = true;
|
|
121
|
+
else if (t.startsWith("--")) a.unknown.push(t);
|
|
122
|
+
else if (!a.topic) a.topic = t;
|
|
123
|
+
}
|
|
124
|
+
return a;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Resolve the body: explicit/app fixture first, else synthetic. Returns { body, source }. */
|
|
128
|
+
export function resolveTriggerBody(topic, { appDir, fixture }) {
|
|
129
|
+
const path = resolve(fixture || join(appDir, "fixtures", `${topic}.cloudevent.json`));
|
|
130
|
+
if (existsSync(path)) return { ok: true, body: readFileSync(path, "utf8"), source: path };
|
|
131
|
+
if (fixture) return { ok: false, message: `no fixture at ${path}` };
|
|
132
|
+
if (!MANIFEST_WEBHOOK_TOPICS.includes(topic)) {
|
|
133
|
+
return { ok: false, message: `unknown topic "${topic}" and no fixture at ${path}` };
|
|
134
|
+
}
|
|
135
|
+
return { ok: true, body: JSON.stringify(syntheticCloudEvent(topic), null, 2) + "\n", source: "synthetic" };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {string[]} argv
|
|
140
|
+
* @param {{ out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch }} [deps]
|
|
141
|
+
*/
|
|
142
|
+
export async function run(argv, deps = {}) {
|
|
143
|
+
const out = deps.out || ((s) => process.stdout.write(`${s}\n`));
|
|
144
|
+
const err = deps.err || ((s) => process.stderr.write(`${s}\n`));
|
|
145
|
+
const fetchImpl = deps.fetchImpl || fetch;
|
|
146
|
+
|
|
147
|
+
if (argv[0] === "--help" || argv[0] === "-h" || argv[0] === "help") { out(USAGE); return 0; }
|
|
148
|
+
const { appDir, rest } = parseTopArgs(argv);
|
|
149
|
+
const args = parseTriggerArgs(rest);
|
|
150
|
+
if (args.list) { out(supportedTopics().join("\n")); return 0; }
|
|
151
|
+
if (args.unknown.length) { err(fail(`unknown option ${args.unknown[0]}`, "tot app trigger --help")); return 2; }
|
|
152
|
+
if (!args.topic) { err(fail("tot app trigger needs a topic", "tot app trigger order.created (see --list)")); return 2; }
|
|
153
|
+
|
|
154
|
+
const resolved = resolveTriggerBody(args.topic, { appDir, fixture: args.fixture });
|
|
155
|
+
if (!resolved.ok) { err(fail(resolved.message, "tot app trigger --list, or pass --fixture <path>")); return 2; }
|
|
156
|
+
|
|
157
|
+
const keys = await ensureDevKeys(appDir, { kid: manifestKeyId(appDir) });
|
|
158
|
+
const { headers } = await signWebhookRequest({ method: "POST", url: args.url, body: resolved.body, key: keys.privateKey, kid: keys.kid });
|
|
159
|
+
const requestId = makeRequestId();
|
|
160
|
+
const traceparent = makeTraceparent();
|
|
161
|
+
const sent = { ...headers, "content-type": "application/json", "tot-request-id": requestId, traceparent };
|
|
162
|
+
|
|
163
|
+
const report = { topic: args.topic, url: args.url, keyid: keys.kid, fixture: resolved.source, requestId, traceparent, signatureInput: headers["signature-input"], contentDigest: headers["content-digest"] };
|
|
164
|
+
if (!args.json) {
|
|
165
|
+
out(`→ POST ${args.url} (topic: ${args.topic}, fixture: ${resolved.source}, keyid: ${keys.kid})`);
|
|
166
|
+
out(` tot-request-id: ${requestId}`);
|
|
167
|
+
out(` traceparent: ${traceparent}`);
|
|
168
|
+
out(` content-digest: ${headers["content-digest"]}`);
|
|
169
|
+
out(` signature-input: ${headers["signature-input"]}`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let response;
|
|
173
|
+
const started = Date.now();
|
|
174
|
+
try {
|
|
175
|
+
response = await fetchImpl(args.url, { method: "POST", headers: sent, body: resolved.body });
|
|
176
|
+
} catch (e) {
|
|
177
|
+
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`"));
|
|
178
|
+
return 1;
|
|
179
|
+
}
|
|
180
|
+
const text = await response.text();
|
|
181
|
+
const latencyMs = Date.now() - started;
|
|
182
|
+
if (args.json) out(JSON.stringify({ ...report, status: response.status, ok: response.ok, latencyMs, response: text }));
|
|
183
|
+
else out(`← ${response.status} ${response.statusText || ""} (${latencyMs}ms)\n${text}`.trimEnd());
|
|
184
|
+
return response.ok ? 0 : 1;
|
|
185
|
+
}
|