@tokenoftrust/cli 7.4.5 → 7.5.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 CHANGED
@@ -79,13 +79,14 @@ 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 conformance --url <webhookUrl>", blurb: "check a running local connector's webhook contract" },
82
83
  { invocation: "app install", blurb: "install your Private App on your store (env defaults to test); prints the client secret once" },
83
84
  { invocation: "app update <installId>", blurb: "push your app's current version, scopes and manifest to an install" },
84
85
  { invocation: "app rotate <installId>", blurb: "issue a new client secret for an install (printed once)" },
85
86
  { invocation: "app list", blurb: "your store's app installs — id, app, version, env, status, scopes" },
86
87
  { invocation: "app replay <deliveryId>", blurb: "re-send a webhook delivery to its install" },
87
88
  { invocation: "app test-order bind <installId> | create | release <orderId>", blurb: "synthetic preview orders bound to your test install (preview host)" },
88
- { invocation: "app candidate", blurb: "stage a production candidate (pending_approval) for owner approval" },
89
+ { invocation: "app candidate [--generate-keys [dir]]", blurb: "stage a production candidate for owner approval" },
89
90
  { invocation: "app candidate status", blurb: "your store's candidates and their status" },
90
91
  { invocation: "app candidate withdraw <candidateId>", blurb: "withdraw a pending production candidate" },
91
92
  { invocation: "app suspend <installId>", blurb: "disable an install's tokens, webhooks and widgets (reversible)" },
@@ -446,13 +447,15 @@ async function main() {
446
447
  const diagnostics = currentInvocationDiagnostics();
447
448
  const diagnosticIds = diagnostics.map((entry) => entry.diagnosticId).filter(Boolean);
448
449
  const session = currentInvocationSession();
449
- // Best-effort activity breadcrumb (never throws, never blocks). `feedback`'s own
450
- // free-text message is omitted — it's user-typed and belongs only in the report.
450
+ // Keep feedback text and conformance certification inputs out of activity attachments.
451
+ let activityArgs = ["«omitted»"];
452
+ if (cmd === "app" && rest[0] === "conformance") activityArgs = ["conformance"];
453
+ else if (cmd !== "feedback") activityArgs = redactArgs(rest);
451
454
  recordActivity({
452
455
  ts: new Date().toISOString(),
453
456
  v: VERSION,
454
457
  cmd: command,
455
- args: cmd === "feedback" ? ["«omitted»"] : redactArgs(rest),
458
+ args: activityArgs,
456
459
  code: exitCode,
457
460
  ms: durationMs,
458
461
  ...(errMsg ? { err: String(errMsg).slice(0, 200) } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.4.5",
3
+ "version": "7.5.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",
@@ -21,6 +21,7 @@ import { join, resolve } from "node:path";
21
21
  import { DEFAULT_STOREFRONT_ORIGIN, resolveViewerTransport } from "../../viewer-session.mjs";
22
22
  import { missingGrantsOf, refusalHint } from "../../admission-hint.mjs";
23
23
  import { validateManifest } from "../../vendor/private-apps-devkit.mjs";
24
+ import { generateCandidateKeys } from "./candidate-keys.mjs";
24
25
 
25
26
  export const DEFAULT_APP_ENV = "test";
26
27
  const OPTION_VERBS = new Set(["install", "update", "rotate", "list", "replay", "test-order", "candidate", "suspend", "resume", "uninstall", "validate"]);
@@ -55,9 +56,10 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
55
56
  tot app candidate status this store's candidates: id, app, version, status
56
57
  tot app candidate withdraw <candidateId>
57
58
  withdraw a pending production candidate
58
- tot app candidate [--app <dir>] [--jwks-uri <url> | --jwks <file>] [--request-consent] [--webhook-endpoint <url>]
59
- stage a production candidate (pending_approval) for owner approval;
60
- keys come from --jwks-uri, --jwks, or the manifest's clientAuth
59
+ tot app candidate [--app <dir>] [--jwks-uri <url> | --jwks <file> | --generate-keys [dir]] [--request-consent] [--webhook-endpoint <url>]
60
+ stage a production candidate (pending_approval) for owner approval
61
+ with one key source or the manifest's clientAuth
62
+ --generate-keys saves an ES256 key pair under <app>/.tot/candidate-keys by default
61
63
 
62
64
  Options (all online commands):
63
65
  --tenant <appDomain> the store (default: the current checkout's store)
@@ -73,10 +75,11 @@ Options (all online commands):
73
75
  export function parseAdminArgs(argv) {
74
76
  /** @type {{ verb: string|null, positional: string[], app: string|null, env: string|null, tenant: string|null,
75
77
  * url: string|null, webhookEndpoint: string|null|undefined, jwksUri: string|null, jwks: string|null,
78
+ * generateKeys: string|null,
76
79
  * location: string|null, lines: string[], quantity: string|null, region: string|null,
77
80
  * requestConsent: boolean, json: boolean, help: boolean, unknown: string[] }} */
78
81
  const a = { verb: null, positional: [], app: null, env: null, tenant: null, url: null,
79
- webhookEndpoint: undefined, jwksUri: null, jwks: null, location: null, lines: [], quantity: null, region: null,
82
+ webhookEndpoint: undefined, jwksUri: null, jwks: null, generateKeys: null, location: null, lines: [], quantity: null, region: null,
80
83
  requestConsent: false, json: false, help: false, unknown: [] };
81
84
  const valueOf = (i, t) => {
82
85
  const eq = t.indexOf("=");
@@ -90,7 +93,17 @@ export function parseAdminArgs(argv) {
90
93
  if (t === "--json") a.json = true;
91
94
  else if (t === "--request-consent") a.requestConsent = true;
92
95
  else if (t === "--help" || t === "-h") a.help = true;
93
- else if (flag === "--app" || flag === "--env" || flag === "--tenant" || flag === "--url" || flag === "--webhook-endpoint"
96
+ else if (flag === "--generate-keys") {
97
+ const nextArg = argv[i + 1];
98
+ const isCandidateAction = a.verb === "candidate" && a.positional.length === 0 && (nextArg === "status" || nextArg === "withdraw");
99
+ if (t === flag && (isCandidateAction || nextArg === "-h")) {
100
+ a.generateKeys = "";
101
+ } else {
102
+ const { value, next } = valueOf(i, t);
103
+ a.generateKeys = value;
104
+ i = next;
105
+ }
106
+ } else if (flag === "--app" || flag === "--env" || flag === "--tenant" || flag === "--url" || flag === "--webhook-endpoint"
94
107
  || flag === "--jwks-uri" || flag === "--jwks" || flag === "--location" || flag === "--line"
95
108
  || flag === "--quantity" || flag === "--region") {
96
109
  const { value, next } = valueOf(i, t);
@@ -200,6 +213,14 @@ export async function runAdmin(argv, ctx, deps = {}) {
200
213
  }
201
214
  if (args.unknown.length) return fail(`unknown option ${args.unknown[0]}`, "tot app --help");
202
215
  const verb = args.verb;
216
+ if (args.generateKeys !== null) {
217
+ if (verb !== "candidate" || args.positional.length) {
218
+ return fail("--generate-keys is only for staging a candidate", "tot app candidate --help");
219
+ }
220
+ if (args.jwks !== null || args.jwksUri !== null) {
221
+ return fail("pass only one of --generate-keys, --jwks-uri and --jwks", "re-run with one key source");
222
+ }
223
+ }
203
224
  const testOrderOptions = [
204
225
  [args.location !== null, "--location"],
205
226
  [args.lines.length > 0, "--line"],
@@ -213,8 +234,9 @@ export async function runAdmin(argv, ctx, deps = {}) {
213
234
  if (verb === "validate") return runValidateManifest(args, ctx, out, err);
214
235
 
215
236
  // ── build the request from local files and arguments, before any network call ──
216
- /** @type {{ method: string, path: string, body?: unknown }} */
237
+ /** @type {{ method: string, path: string, body?: object }} */
217
238
  let request;
239
+ let candidateKeysDirectory;
218
240
  if (verb === "install") {
219
241
  const appEnv = args.env === null ? DEFAULT_APP_ENV : args.env;
220
242
  if (appEnv !== "test" && appEnv !== "production") {
@@ -305,6 +327,14 @@ export async function runAdmin(argv, ctx, deps = {}) {
305
327
  if (!loaded.ok) return fail(loaded.message, loaded.next);
306
328
  const m = loaded.manifest;
307
329
  if (args.jwksUri && args.jwks) return fail("pass only one of --jwks-uri and --jwks", "re-run with one key source");
330
+ if (args.generateKeys !== null) {
331
+ if (m.clientAuth !== undefined) {
332
+ return fail("--generate-keys conflicts with the manifest's clientAuth", "re-run with the manifest's key source, or remove clientAuth before generating keys");
333
+ }
334
+ candidateKeysDirectory = args.generateKeys
335
+ ? resolve(ctx?.cwd || process.cwd(), args.generateKeys)
336
+ : join(loaded.dir, ".tot", "candidate-keys");
337
+ }
308
338
  let jwks;
309
339
  if (args.jwks) {
310
340
  try { jwks = JSON.parse(readFileSync(resolve(ctx?.cwd || process.cwd(), args.jwks), "utf8")); }
@@ -337,7 +367,23 @@ export async function runAdmin(argv, ctx, deps = {}) {
337
367
  return 1;
338
368
  }
339
369
 
370
+ let generatedKeys;
371
+ if (candidateKeysDirectory) {
372
+ try {
373
+ const { jwks, privateKeyPath, publicJwksPath } = await generateCandidateKeys(candidateKeysDirectory);
374
+ generatedKeys = { privateKeyPath, publicJwksPath };
375
+ request.body = { ...request.body, jwks };
376
+ } catch (e) {
377
+ const reason = e.code === "EEXIST" ? `${e.path} already exists` : e.message;
378
+ return fail(`could not generate candidate keys (${reason})`, "use a fresh directory, or stage your existing public keys with --jwks <file>");
379
+ }
380
+ }
381
+ const retryKeys = generatedKeys
382
+ ? `\n Reuse the saved keys by replacing --generate-keys with --jwks ${quoteShellArg(generatedKeys.publicJwksPath)}`
383
+ : "";
384
+
340
385
  let res;
386
+ let data;
341
387
  try {
342
388
  // Every admin route admits a console session only for the store named by `?tenant=`.
343
389
  res = await fetchImpl(`${transport.base}${request.path}?tenant=${encodeURIComponent(tenant)}`, {
@@ -349,11 +395,11 @@ export async function runAdmin(argv, ctx, deps = {}) {
349
395
  },
350
396
  ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
351
397
  });
398
+ data = parseJsonBody(await res.text());
352
399
  } catch (e) {
353
- err(`✗ could not reach the store: ${e?.message || e}\n\n → next: check --url / your network, then re-run`);
400
+ err(`✗ could not reach the store: ${e?.message || e}\n\n → next: check --url / your network, then re-run${retryKeys}`);
354
401
  return 1;
355
402
  }
356
- const data = parseJsonBody(await res.text());
357
403
  if (!res.ok) {
358
404
  const reason = typeof data?.error === "string" ? data.error : `the store refused the request (HTTP ${res.status}).`;
359
405
  const denials = Array.isArray(data?.denials) && data.denials.length
@@ -363,7 +409,7 @@ export async function runAdmin(argv, ctx, deps = {}) {
363
409
  const action = args.positional[0];
364
410
  const code = refusalCode(res.status, data, verb, action);
365
411
  const plain = plainRefusal(res.status, data, code);
366
- err(`✗ tot app ${verb}: ${plain ? `${plain} (${reason})` : reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, code, { tenant, urlOverridden, verb, action })}`);
412
+ err(`✗ tot app ${verb}: ${plain ? `${plain} (${reason})` : reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, code, { tenant, urlOverridden, verb, action })}${retryKeys}`);
367
413
  return res.status === 401 || res.status === 403 ? 1 : (res.status >= 500 ? 1 : 2);
368
414
  }
369
415
 
@@ -391,10 +437,14 @@ export async function runAdmin(argv, ctx, deps = {}) {
391
437
  return 0;
392
438
  }
393
439
  if (verb === "candidate") {
394
- if (args.json) out(JSON.stringify(data));
440
+ if (args.json) out(JSON.stringify(generatedKeys ? { ...data, generatedKeys } : data));
395
441
  else {
396
442
  const c = data?.candidate ?? data;
397
443
  out(`✓ staged ${c?.appId ?? "the app"} ${c?.appVersion ?? ""} as candidate ${c?.candidateId ?? c?.id ?? ""} (${c?.status ?? "pending_approval"}); the store owner approves it in /admin#integrations`.replace(/ {2,}/g, " "));
444
+ if (generatedKeys) {
445
+ out(` Public JWKS saved to ${generatedKeys.publicJwksPath}`);
446
+ out(` export TOT_PRIVATE_KEY_JWK_PATH=${quoteShellArg(generatedKeys.privateKeyPath)}`);
447
+ }
398
448
  }
399
449
  return 0;
400
450
  }
@@ -451,7 +501,10 @@ function parseJsonBody(text) {
451
501
  }
452
502
  }
453
503
 
454
- /** @param {string|null} appDir @param {any} ctx */
504
+ /**
505
+ * @param {string|null} appDir @param {any} ctx
506
+ * @returns {{ ok: true, manifest: any, dir: string } | { ok: false, message: string, next: string }}
507
+ */
455
508
  function loadManifest(appDir, ctx) {
456
509
  const dir = resolve(appDir || ctx?.cwd || process.cwd());
457
510
  const path = join(dir, "tot-app.json");
@@ -465,7 +518,12 @@ function loadManifest(appDir, ctx) {
465
518
  if (!result.ok) {
466
519
  return { ok: false, message: `${path} is not a valid manifest:\n${(result.errors || []).map((e) => ` - ${e}`).join("\n")}`, next: "tot app dev validate" };
467
520
  }
468
- return { ok: true, manifest: parsed };
521
+ return { ok: true, manifest: parsed, dir };
522
+ }
523
+
524
+ /** @param {string} value */
525
+ function quoteShellArg(value) {
526
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
469
527
  }
470
528
 
471
529
  function renderCredential(verb, data, json, out, err) {
@@ -0,0 +1,46 @@
1
+ import { randomUUID, subtle } from "node:crypto";
2
+ import { closeSync, fchmodSync, mkdirSync, openSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /** @param {string} directory */
6
+ export async function generateCandidateKeys(directory) {
7
+ const pair = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
8
+ const [privateJwk, { kty, crv, x, y }] = await Promise.all([
9
+ subtle.exportKey("jwk", pair.privateKey),
10
+ subtle.exportKey("jwk", pair.publicKey),
11
+ ]);
12
+ const metadata = { kid: randomUUID(), alg: "ES256", use: "sig" };
13
+ const jwks = { keys: [{ kty, crv, x, y, ...metadata }] };
14
+ const privateKeyPath = join(directory, "private-jwk.json");
15
+ const publicJwksPath = join(directory, "public-jwks.json");
16
+
17
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
18
+ const created = [];
19
+ try {
20
+ writeExclusiveJson(privateKeyPath, { ...privateJwk, ...metadata }, 0o600, created);
21
+ writeExclusiveJson(publicJwksPath, jwks, 0o644, created);
22
+ } catch (error) {
23
+ const remaining = [];
24
+ for (const path of created.reverse()) {
25
+ try { unlinkSync(path); }
26
+ catch (cleanupError) { if (cleanupError.code !== "ENOENT") remaining.push(path); }
27
+ }
28
+ if (remaining.length) {
29
+ throw new Error(`could not remove incomplete key files: ${remaining.join(", ")}`, { cause: error });
30
+ }
31
+ throw error;
32
+ }
33
+ return { jwks, privateKeyPath, publicJwksPath };
34
+ }
35
+
36
+ /** @param {string} path @param {object} body @param {number} mode @param {string[]} created */
37
+ function writeExclusiveJson(path, body, mode, created) {
38
+ const fd = openSync(path, "wx", mode);
39
+ created.push(path);
40
+ try {
41
+ if (mode === 0o600) fchmodSync(fd, mode);
42
+ writeFileSync(fd, `${JSON.stringify(body, null, 2)}\n`);
43
+ } finally {
44
+ closeSync(fd);
45
+ }
46
+ }
@@ -0,0 +1,399 @@
1
+ import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto";
2
+ import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
3
+ import { createServer, request as requestHttp } from "node:http";
4
+ import { request as requestHttps } from "node:https";
5
+ import { isIP } from "node:net";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { parseArgs } from "node:util";
8
+ import { resolveDeveloperSession } from "../../auth.mjs";
9
+ import { fail } from "../../errors.mjs";
10
+ import { selectedAuthority } from "../../token-store.mjs";
11
+ import { DEFAULT_STOREFRONT_ORIGIN, TOKEN_OF_TRUST_MCP_ORIGINS } from "../../viewer-session.mjs";
12
+ import {
13
+ SIGNATURE_LABEL,
14
+ WEBHOOK_SIGNATURE_COVERED_COMPONENTS,
15
+ buildSignatureBase,
16
+ buildSignatureParamsValue,
17
+ computeContentDigestSha256,
18
+ } from "../../vendor/private-apps-devkit.mjs";
19
+
20
+ const METADATA_HOST = "127.0.0.1";
21
+ const METADATA_PORT = 37891;
22
+ const METADATA_PATH = "/.well-known/tot-app-authorization-metadata";
23
+ const METADATA_URL = `http://${METADATA_HOST}:${METADATA_PORT}${METADATA_PATH}`;
24
+ const ARCHETYPES = ["label-station", "dropship", "inventory-sync"];
25
+ const REQUEST_TIMEOUT_MS = 5000;
26
+ const STAFF_SESSION_TIMEOUT_MS = 30_000;
27
+ const MAX_ACK_BYTES = 4096;
28
+ const CERTIFICATION_SCHEMA = "tot-staff-connector-certification.v1";
29
+ const APP_ID = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;
30
+ const VERIFIED_ACTOR = /^staff:[a-f0-9]{64}$/;
31
+ const OFFLINE_ACTOR = /^[A-Za-z][A-Za-z0-9._-]{0,159}$/;
32
+
33
+ const USAGE = `tot app conformance --url <webhookUrl> [--archetype ${ARCHETYPES.join("|")}]
34
+
35
+ Start your connector in local test mode with clean state. Set the verifier's
36
+ expected @target-uri to the normalized webhook URL. localhost connects to IPv4 loopback.
37
+
38
+ By default and for dropship, the checklist sends synthetic fulfillment and
39
+ inventory events. label-station checks assignment events and their replay.
40
+ inventory-sync checks inventory events and their replay.
41
+
42
+ Configure your local Ed25519 verifier to load webhook_signing_keys from
43
+ ${METADATA_URL}
44
+ when it receives a delivery. The command serves the ephemeral public key there
45
+ for the duration of the run. The bundled RSA verifier works with tot app dev emit.
46
+
47
+ For replay, return a 2xx JSON response with {"accepted":true,"duplicate":true}
48
+ when the same CloudEvent ID is received again. Check connector state separately
49
+ to confirm idempotent side effects and handling of stale inventory.
50
+
51
+ ToT Staff certification:
52
+ tot app conformance --url <webhookUrl> --archetype <name> --certify --app-id <id>
53
+ [--receipt <path>] [--staff-actor <id>] [--api-base ${DEFAULT_STOREFRONT_ORIGIN}]
54
+
55
+ Use --api-base with your signed-in ToT staff session. An optional --staff-actor
56
+ must match the verified actor. For an offline staff run, set TOT_STAFF_CERTIFIER=1
57
+ in a controlled environment and pass --staff-actor with your opaque staff ID.
58
+ The receipt goes to stdout and, when requested, to --receipt as a private file.`;
59
+
60
+ /** @param {string} input */
61
+ function loopbackUrl(input) {
62
+ const target = URL.parse(input);
63
+ if (!target || !["http:", "https:"].includes(target.protocol) || target.username || target.password || target.href.includes("#") || target.port === "0") {
64
+ return null;
65
+ }
66
+ const { hostname } = target;
67
+ const loopback = hostname === "localhost" || hostname === "[::1]" || (isIP(hostname) === 4 && hostname.startsWith("127."));
68
+ return loopback ? target : null;
69
+ }
70
+
71
+ /** @param {number} minute */
72
+ const fixtureTime = (minute) => new Date(Date.UTC(2026, 0, 1, 12, minute)).toISOString();
73
+
74
+ /** @param {string} state @param {number} eventVersion @param {number} minute */
75
+ function assignmentData(state, eventVersion, minute) {
76
+ return {
77
+ assignmentId: "conformance-assignment",
78
+ orderId: "conformance-order",
79
+ stage: "preview",
80
+ state,
81
+ eventVersion,
82
+ occurredAt: fixtureTime(minute),
83
+ };
84
+ }
85
+
86
+ /** @param {number} balance @param {number} available @param {number} minute */
87
+ function inventoryData(balance, available, minute) {
88
+ return { sku: "CONFORMANCE-SKU", locationId: "conformance-location", balance, available, asOf: fixtureTime(minute) };
89
+ }
90
+
91
+ /** @param {string | undefined} archetype */
92
+ function fixtures(archetype) {
93
+ const created = { id: "assignment-created", topic: "fulfillment.assignment.created", data: assignmentData("active", 1, 0) };
94
+ const advanced = { id: "inventory-advanced", topic: "inventory.changed", data: inventoryData(20, 18, 4) };
95
+ const assignments = [
96
+ { ...created, label: "Assignment created", acknowledgment: "initial", minute: 0 },
97
+ { ...created, label: "Assignment replay", acknowledgment: "replay", minute: 1 },
98
+ { label: "Assignment held", id: "assignment-held", topic: "fulfillment.assignment.updated", data: assignmentData("held", 2, 2), minute: 2 },
99
+ { label: "Assignment cancelled", id: "assignment-cancelled", topic: "fulfillment.assignment.updated", data: assignmentData("cancelled", 3, 3), minute: 3 },
100
+ ];
101
+ const inventory = [
102
+ { ...advanced, label: "Inventory advanced", acknowledgment: archetype === "inventory-sync" ? "initial" : undefined, minute: 4 },
103
+ ...(archetype === "inventory-sync" ? [{ ...advanced, label: "Inventory replay", acknowledgment: "replay", minute: 5 }] : []),
104
+ { label: "Inventory stale", id: "inventory-stale", topic: "inventory.changed", data: inventoryData(12, 10, 3), minute: 6 },
105
+ ];
106
+ const selected = [
107
+ ...(archetype === "inventory-sync" ? [] : assignments),
108
+ ...(archetype === "label-station" ? [] : inventory),
109
+ ];
110
+ return selected.map(({ label, id, topic, data, acknowledgment, minute }) => ({
111
+ label,
112
+ acknowledgment,
113
+ body: JSON.stringify({
114
+ specversion: "1.0",
115
+ id: `conformance-${id}`,
116
+ source: "/tenants/conformance/storefront",
117
+ type: `com.tokenoftrust.storefront.${topic}`,
118
+ time: fixtureTime(minute),
119
+ datacontenttype: "application/json",
120
+ dataschemaversion: "1",
121
+ tenantid: "conformance",
122
+ appinstallid: "conformance-install",
123
+ retrycount: acknowledgment === "replay" ? 1 : 0,
124
+ data,
125
+ }),
126
+ }));
127
+ }
128
+
129
+ /** @param {ReturnType<typeof createServer>} server */
130
+ function listen(server) {
131
+ return new Promise((resolve, reject) => {
132
+ server.once("error", reject);
133
+ server.listen(METADATA_PORT, METADATA_HOST, () => {
134
+ server.off("error", reject);
135
+ resolve(undefined);
136
+ });
137
+ });
138
+ }
139
+
140
+ /** @param {ReturnType<typeof createServer>} server */
141
+ function close(server) {
142
+ return new Promise((resolve) => {
143
+ server.close(resolve);
144
+ server.closeAllConnections();
145
+ });
146
+ }
147
+
148
+ /** @param {import("node:http").IncomingMessage} response */
149
+ async function duplicateAcknowledged(response) {
150
+ const chunks = [];
151
+ let total = 0;
152
+ for await (const chunk of response) {
153
+ total += chunk.length;
154
+ if (total > MAX_ACK_BYTES) return false;
155
+ chunks.push(chunk);
156
+ }
157
+ try {
158
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
159
+ return body?.accepted === true && body?.duplicate === true;
160
+ } catch {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ /** @param {URL} target @param {import("node:https").RequestOptions} options @param {(response: import("node:http").IncomingMessage) => void} callback */
166
+ function directRequest(target, options, callback) {
167
+ const request = target.protocol === "https:" ? requestHttps : requestHttp;
168
+ return request(target, options, callback);
169
+ }
170
+
171
+ /** @param {URL} target @param {string} body @param {Record<string, string>} headers @param {boolean} checkDuplicate @param {typeof directRequest} request */
172
+ function post(target, body, headers, checkDuplicate, request) {
173
+ const localhost = target.hostname === "localhost";
174
+ return new Promise((resolve, reject) => {
175
+ const req = request(target, {
176
+ method: "POST",
177
+ path: target.href.slice(target.origin.length),
178
+ ...(localhost ? { hostname: METADATA_HOST, servername: "localhost" } : {}),
179
+ rejectUnauthorized: true,
180
+ agent: false,
181
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
182
+ headers: { ...headers, host: target.host, "content-length": String(Buffer.byteLength(body)) },
183
+ }, (response) => {
184
+ const status = response.statusCode ?? 0;
185
+ if (checkDuplicate && status >= 200 && status < 300) {
186
+ void duplicateAcknowledged(response).then((duplicate) => resolve({ status, duplicate }), reject);
187
+ } else {
188
+ response.destroy();
189
+ resolve({ status, duplicate: false });
190
+ }
191
+ });
192
+ req.once("error", reject);
193
+ req.end(body);
194
+ });
195
+ }
196
+
197
+ /** @param {unknown} actor @param {RegExp} pattern @returns {actor is string} */
198
+ function isStaffActor(actor, pattern) {
199
+ return typeof actor === "string" && actor === actor.trim() && pattern.test(actor);
200
+ }
201
+
202
+ /** @param {string | undefined} apiBase @param {string | undefined} actor @param {NodeJS.ProcessEnv} env
203
+ * @param {typeof resolveDeveloperSession} resolveDev @param {typeof fetch} fetchImpl
204
+ * @returns {Promise<{ kind: "admitted", actor: string } | { kind: "refused" | "unavailable" }>}
205
+ */
206
+ async function certificationAdmission(apiBase, actor, env, resolveDev, fetchImpl) {
207
+ const refused = /** @type {const} */ ({ kind: "refused" });
208
+ const unavailable = /** @type {const} */ ({ kind: "unavailable" });
209
+ if (apiBase === undefined) {
210
+ const admitted = isStaffActor(actor, OFFLINE_ACTOR) || isStaffActor(actor, VERIFIED_ACTOR);
211
+ return env.TOT_STAFF_CERTIFIER === "1" && admitted ? { kind: "admitted", actor } : refused;
212
+ }
213
+ if (actor !== undefined && !isStaffActor(actor, VERIFIED_ACTOR)) return refused;
214
+
215
+ // An operator-supplied URL must never choose where the cached bearer goes.
216
+ const base = URL.parse(apiBase);
217
+ if (!base || base.href !== `${DEFAULT_STOREFRONT_ORIGIN}/`) return refused;
218
+ try {
219
+ const mcpOrigin = selectedAuthority(env);
220
+ if (!TOKEN_OF_TRUST_MCP_ORIGINS.has(mcpOrigin)) return refused;
221
+ const session = await resolveDev(null, env, { fetchImpl });
222
+ if (session.identity !== "developer" || !session.token || !session.mcpUrl || URL.parse(session.mcpUrl)?.origin !== mcpOrigin) return refused;
223
+ const response = await fetchImpl(new URL("api/dev/cli-session", base).href, {
224
+ method: "POST",
225
+ headers: { authorization: `Bearer ${session.token}`, "content-type": "application/json" },
226
+ body: JSON.stringify({ mcpOrigin, principal: "staff-certifier" }),
227
+ redirect: "error",
228
+ signal: AbortSignal.timeout(STAFF_SESSION_TIMEOUT_MS),
229
+ });
230
+ if (response.status >= 500) return unavailable;
231
+ if (response.status !== 200) return refused;
232
+ const body = await response.json();
233
+ if (body?.ok !== true || !isStaffActor(body.staffActor, VERIFIED_ACTOR) || (actor && actor !== body.staffActor)) return refused;
234
+ return { kind: "admitted", actor: body.staffActor };
235
+ } catch {
236
+ return unavailable;
237
+ }
238
+ }
239
+
240
+ /** @param {string} path @param {string} receipt */
241
+ async function writeReceipt(path, receipt) {
242
+ const destination = resolve(path);
243
+ const directory = await mkdtemp(join(dirname(destination), ".tot-certification-"));
244
+ const staged = join(directory, "receipt.json");
245
+ try {
246
+ await writeFile(staged, `${receipt}\n`, { mode: 0o600, flag: "wx" });
247
+ await rename(staged, destination);
248
+ } finally {
249
+ await rm(directory, { recursive: true, force: true });
250
+ }
251
+ }
252
+
253
+ /**
254
+ * @param {string[]} argv
255
+ * @param {{ makeServer?: typeof createServer, request?: typeof directRequest, now?: () => number, log?: (line: string) => void, error?: (line: string) => void, env?: NodeJS.ProcessEnv, resolveDev?: typeof resolveDeveloperSession, fetchImpl?: typeof fetch }} [deps]
256
+ */
257
+ export async function runAppConformance(argv, {
258
+ makeServer = createServer,
259
+ request = directRequest,
260
+ now = Date.now,
261
+ log = console.log,
262
+ error = console.error,
263
+ env = process.env,
264
+ resolveDev = resolveDeveloperSession,
265
+ fetchImpl = fetch,
266
+ } = {}) {
267
+ let values;
268
+ try {
269
+ ({ values } = parseArgs({ args: argv, options: {
270
+ url: { type: "string" }, archetype: { type: "string" }, help: { type: "boolean", short: "h" },
271
+ certify: { type: "boolean" }, receipt: { type: "string" }, "staff-actor": { type: "string" },
272
+ "api-base": { type: "string" }, "app-id": { type: "string" },
273
+ } }));
274
+ } catch {
275
+ error(fail("Invalid conformance options", "tot app conformance --help"));
276
+ return 2;
277
+ }
278
+ if (values.help) {
279
+ log(USAGE);
280
+ return 0;
281
+ }
282
+ const { certify, archetype, receipt, "app-id": appId, "staff-actor": actor, "api-base": apiBase } = values;
283
+ if (!certify && [receipt, appId, actor, apiBase].some((option) => option !== undefined)) {
284
+ error(fail("Certification options require --certify", "tot app conformance --help"));
285
+ return 2;
286
+ }
287
+ let certifiedBy;
288
+ if (certify) {
289
+ const admission = await certificationAdmission(apiBase, actor, env, resolveDev, fetchImpl);
290
+ if (admission.kind !== "admitted") {
291
+ const message = admission.kind === "unavailable"
292
+ ? "Unable to verify ToT staff admission"
293
+ : "Certification requires ToT staff admission";
294
+ error(fail(message, "tot app conformance --help"));
295
+ return 1;
296
+ }
297
+ certifiedBy = admission.actor;
298
+ if (!appId || appId.length > 128 || appId !== appId.trim() || !APP_ID.test(appId) || !archetype || (receipt !== undefined && !receipt.trim())) {
299
+ error(fail("Certification requires --app-id and --archetype, and --receipt must name a file when supplied", "tot app conformance --help"));
300
+ return 2;
301
+ }
302
+ }
303
+ const target = values.url && loopbackUrl(values.url);
304
+ if (!target) {
305
+ error(fail("Conformance requires --url with a loopback HTTP(S) webhook URL", "tot app conformance --help"));
306
+ return 2;
307
+ }
308
+ if (values.archetype !== undefined && !ARCHETYPES.includes(values.archetype)) {
309
+ error(fail("Choose a supported conformance archetype", "tot app conformance --help"));
310
+ return 2;
311
+ }
312
+
313
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
314
+ const kid = `conformance-${randomUUID()}`;
315
+ const jwk = { ...publicKey.export({ format: "jwk" }), kid, alg: "EdDSA", use: "sig" };
316
+ const metadata = JSON.stringify({ webhook_signing_keys: { keys: [jwk] } });
317
+ const server = makeServer((req, res) => {
318
+ if (req.method === "GET" && req.url === METADATA_PATH) {
319
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store, max-age=0" });
320
+ res.end(metadata);
321
+ } else {
322
+ res.writeHead(404).end();
323
+ }
324
+ });
325
+ try {
326
+ await listen(server);
327
+ } catch {
328
+ error(fail(`Unable to serve conformance signing keys at ${METADATA_URL}`));
329
+ return 1;
330
+ }
331
+
332
+ try {
333
+ if (!certify) log(`Webhook conformance${archetype ? ` (${archetype})` : ""}`);
334
+ const checks = [];
335
+ let passed = true;
336
+ let initialAccepted = false;
337
+ for (const { label, acknowledgment, body } of fixtures(archetype)) {
338
+ const replay = acknowledgment === "replay";
339
+ const digest = await computeContentDigestSha256(body);
340
+ const params = buildSignatureParamsValue(WEBHOOK_SIGNATURE_COVERED_COMPONENTS, {
341
+ created: Math.floor(now() / 1000), keyid: kid, alg: "ed25519",
342
+ });
343
+ const base = buildSignatureBase([["@method", "POST"], ["@target-uri", target.href], ["content-digest", digest]], params);
344
+ const headers = {
345
+ "content-type": "application/cloudevents+json",
346
+ "content-digest": digest,
347
+ "signature-input": `${SIGNATURE_LABEL}=${params}`,
348
+ signature: `${SIGNATURE_LABEL}=:${sign(null, Buffer.from(base), privateKey).toString("base64")}:`,
349
+ };
350
+ let finding;
351
+ try {
352
+ const { status, duplicate } = await post(target, body, headers, Boolean(acknowledgment), request);
353
+ if (status >= 300 && status < 400) finding = `HTTP ${status} redirect refused`;
354
+ else if (status < 200 || status >= 300) finding = `HTTP ${status} delivery rejected`;
355
+ else if (acknowledgment === "initial" && duplicate) finding = `HTTP ${status} initial delivery already known. Use clean local state.`;
356
+ else if (replay && !duplicate) finding = `HTTP ${status} delivery acknowledged without duplicate confirmation`;
357
+ else if (replay && !initialAccepted) finding = `HTTP ${status} duplicate reported without a successful initial delivery`;
358
+ else {
359
+ if (acknowledgment === "initial") initialAccepted = true;
360
+ // Sorted keys and fixed fixture order give this flat evidence a canonical JSON encoding.
361
+ checks.push({ label, passed: true, status });
362
+ if (!certify) log(`PASS ${label} — HTTP ${status} ${replay ? "duplicate acknowledged" : "delivery acknowledged"}`);
363
+ continue;
364
+ }
365
+ } catch {
366
+ finding = "request failed or timed out";
367
+ }
368
+ (certify ? error : log)(`FAIL ${label} — ${finding}`);
369
+ passed = false;
370
+ }
371
+ if (!certify) log("Results reflect webhook responses. Inspect connector state to assess side effects.");
372
+ if (!passed) return 1;
373
+ if (certify) {
374
+ const output = JSON.stringify({
375
+ schema: CERTIFICATION_SCHEMA,
376
+ visibility: "tot-staff-internal-only",
377
+ appId,
378
+ archetype,
379
+ certifiedBy,
380
+ certifiedAt: new Date(now()).toISOString(),
381
+ passed: true,
382
+ checks,
383
+ evidenceSha256: createHash("sha256").update(JSON.stringify(checks)).digest("hex"),
384
+ });
385
+ if (receipt !== undefined) {
386
+ try {
387
+ await writeReceipt(receipt, output);
388
+ } catch {
389
+ error(fail("Unable to write the certification receipt"));
390
+ return 1;
391
+ }
392
+ }
393
+ log(output);
394
+ }
395
+ return 0;
396
+ } finally {
397
+ await close(server);
398
+ }
399
+ }
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * tot app scaffold <name> materialize a runnable Private App skeleton
7
7
  * tot app dev ... local, offline webhook/manifest/JWT harness
8
+ * tot app conformance check a running local connector's webhook contract
8
9
  * tot app install|update|rotate|list|replay online install management (admin.mjs)
9
10
  */
10
11
  import { fail } from "../../errors.mjs";
@@ -13,6 +14,8 @@ const USAGE = `tot app — build and install a Storefront Private App
13
14
 
14
15
  tot app scaffold <name> scaffold a runnable Private App skeleton
15
16
  tot app dev ... local, offline webhook/manifest/JWT harness (see \`tot app dev --help\`)
17
+ tot app conformance --url <webhookUrl> check a running local connector's webhook contract
18
+ tot app conformance --certify issue a conformance receipt (staff only, see \`tot app conformance --help\`)
16
19
  tot app install install your app on your store (env defaults to test); prints the client secret once
17
20
  tot app update <installId> push your app's current version, scopes and manifest to an install
18
21
  tot app rotate <installId> issue a new client secret (printed once)
@@ -23,7 +26,7 @@ const USAGE = `tot app — build and install a Storefront Private App
23
26
  tot app validate [<manifest>] lint tot-app.json offline (invalid_manifest on refusal)
24
27
  tot app candidate status your store's candidates and their status
25
28
  tot app candidate withdraw <candidateId> withdraw a pending production candidate
26
- tot app candidate stage a production candidate (pending_approval) for owner approval
29
+ tot app candidate [--generate-keys [dir]] stage a production candidate for owner approval
27
30
 
28
31
  Run \`tot app <command> --help\` for options. Online commands use your \`tot login\` session.`;
29
32
 
@@ -43,6 +46,10 @@ export async function run(argv, ctx) {
43
46
  const { run: runDev } = await import("./dev.mjs");
44
47
  return /** @type {any} */ (runDev)(rest, ctx);
45
48
  }
49
+ if (sub === "conformance") {
50
+ const { runAppConformance } = await import("./conformance.mjs");
51
+ return runAppConformance(rest);
52
+ }
46
53
  if (sub === "install" || sub === "update" || sub === "rotate" || sub === "list" || sub === "replay" || sub === "test-order" || sub === "candidate" || sub === "suspend" || sub === "resume" || sub === "uninstall" || sub === "validate") {
47
54
  const { runAdmin } = await import("./admin.mjs");
48
55
  return runAdmin(argv, ctx);