@tokenoftrust/cli 7.15.0 → 8.0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.15.0",
3
+ "version": "8.0.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",
@@ -83,6 +83,22 @@ function parseJson(text) {
83
83
  }
84
84
  }
85
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
+
86
102
  function topicOf(body) {
87
103
  const parsed = parseJson(body);
88
104
  if (!parsed.ok) return "invalid-json";
@@ -117,9 +133,13 @@ export async function handleOfflineDelivery({ method, url, headers, body }, { ke
117
133
  const topic = topicOf(body);
118
134
  const deliveryId = headers["tot-delivery-id"] || headers["tot-request-id"] || null;
119
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
+ }
120
140
  if (!forwardTo) {
121
141
  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 }) };
142
+ return { status: 200, text: JSON.stringify({ received: true, signature }) };
123
143
  }
124
144
  const sent = await forward({
125
145
  url: forwardTo, body, keys, fetchImpl,
@@ -127,7 +147,7 @@ export async function handleOfflineDelivery({ method, url, headers, body }, { ke
127
147
  traceparent: headers.traceparent || makeTraceparent(),
128
148
  });
129
149
  if (sent.error) {
130
- log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: sent.latencyMs, note: `could not reach ${forwardTo}: ${sent.error}` }, color));
150
+ log(formatDeliveryLog({ at, topic, deliveryId, signature, status: null, latencyMs: sent.latencyMs, note: `could not reach ${displayUrl(forwardTo)}: ${redactError(sent.error, forwardTo)}` }, color));
131
151
  return { status: 502, text: JSON.stringify({ error: "forward_failed" }) };
132
152
  }
133
153
  log(formatDeliveryLog({ at, topic, deliveryId, signature, status: sent.status, latencyMs: sent.latencyMs }, color));
@@ -171,7 +191,7 @@ export async function pollOnce({ transport, tenant, installId, forwardTo, keys,
171
191
  log(formatDeliveryLog({
172
192
  at, topic: d.topic, deliveryId: d.deliveryId, signature: "n/a",
173
193
  status: sent.error ? null : sent.status, latencyMs: sent.latencyMs,
174
- note: sent.error ? `could not reach ${forwardTo}: ${sent.error}` : note,
194
+ note: sent.error ? `could not reach ${displayUrl(forwardTo)}: ${redactError(sent.error, forwardTo)}` : note,
175
195
  }, color));
176
196
  }
177
197
  return { ok: true, forwarded: fresh.length };
@@ -197,7 +217,7 @@ export async function run(argv, ctx, deps = {}) {
197
217
  if (args.help) { out(USAGE); return 0; }
198
218
  if (args.unknown.length) { err(fail(`unknown option ${args.unknown[0]}`, "tot app listen --help")); return 2; }
199
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; }
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; }
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; }
201
221
  const color = args.color ?? Boolean(process.stdout.isTTY && !env.NO_COLOR);
202
222
  const keys = await ensureDevKeys(appDir, { kid: manifestKeyId(appDir) });
203
223
 
@@ -209,7 +229,7 @@ export async function run(argv, ctx, deps = {}) {
209
229
  if (!tenant) { err(fail("no store to act on", "pass --tenant <appDomain>, or run inside a store checkout")); return 2; }
210
230
  const transport = await (deps.resolveViewerTransport || resolveViewerTransport)({ tenant, env, fetchImpl, storefrontUrl: args.url || env.TOT_STOREFRONT_URL || null });
211
231
  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)`);
232
+ out(`tailing deliveries for ${args.install} on ${tenant} → ${displayUrl(args.forwardTo)} (every ${args.interval}ms, ctrl-c to stop)`);
213
233
  const seen = new Set();
214
234
  let primed = false;
215
235
  while (!deps.signal?.aborted) {
@@ -243,7 +263,7 @@ export async function run(argv, ctx, deps = {}) {
243
263
  }
244
264
  const address = server.address();
245
265
  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"})`);
266
+ out(`listening on http://localhost:${port}/webhooks (verifying with keyid ${keys.kid}${args.forwardTo ? `, forwarding to ${displayUrl(args.forwardTo)}` : ", no --forward-to"})`);
247
267
  out("send one with: tot app trigger <topic>");
248
268
  if (deps.onListening) deps.onListening({ port, close: () => new Promise((r) => server.close(r)) });
249
269
  await new Promise((r) => { server.once("close", r); deps.signal?.addEventListener("abort", () => server.close()); process.once("SIGINT", () => server.close()); });
@@ -25,30 +25,63 @@ Signs with <app>/.tot/dev-keys.json (RFC 9421 + Content-Digest). Default --url $
25
25
  (where \`tot app listen\` waits).`;
26
26
 
27
27
  const ORDER = {
28
- id: "ord_synthetic_10482", status: "created", currency: "USD", customerHash: "cus_h_synthetic0001",
28
+ id: "ord_synthetic_10482", status: "created", currency: "USD",
29
29
  subtotal: 84, total: 91.35,
30
30
  lineItems: [{ sku: "SYNTHETIC-SKU", handle: "synthetic-product", quantity: 1, lineTotal: 84 }],
31
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";
32
39
 
33
- /** Per-topic `data` for synthetic events; topics not listed get a generic resource envelope. */
40
+ /** Per-topic `data`, one closed payload per AsyncAPI message (docs/private-apps/contract/asyncapi.yaml). */
34
41
  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" },
42
+ "app.installed": {},
43
+ "app.uninstalled": {},
44
+ "catalog.product.updated": { handle: "synthetic-product" },
38
45
  "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" },
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,
41
58
  "order.fulfilled": { ...ORDER, status: "fulfilled" },
42
- "order.partially_fulfilled": { ...ORDER, status: "partially_fulfilled" },
59
+ "order.partially_fulfilled": ORDER,
43
60
  "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" },
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" },
52
85
  };
53
86
 
54
87
  export function supportedTopics() {
@@ -58,8 +91,7 @@ export function supportedTopics() {
58
91
  /** Build a synthetic CloudEvent for `topic`. `now`/`tenant`/`installId` are injectable for tests. */
59
92
  export function syntheticCloudEvent(topic, { now = new Date(), tenant = "example", installId = "inst_synthetic" } = {}) {
60
93
  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)));
94
+ const data = JSON.parse(JSON.stringify(DATA[topic] ?? {}).replace(/"@now"/g, JSON.stringify(iso)));
63
95
  const rand = Buffer.from(crypto.getRandomValues(new Uint8Array(8))).toString("hex");
64
96
  return {
65
97
  specversion: "1.0",