@tokenoftrust/cli 7.5.0 → 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
@@ -447,13 +447,15 @@ async function main() {
447
447
  const diagnostics = currentInvocationDiagnostics();
448
448
  const diagnosticIds = diagnostics.map((entry) => entry.diagnosticId).filter(Boolean);
449
449
  const session = currentInvocationSession();
450
- // Best-effort activity breadcrumb (never throws, never blocks). `feedback`'s own
451
- // 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);
452
454
  recordActivity({
453
455
  ts: new Date().toISOString(),
454
456
  v: VERSION,
455
457
  cmd: command,
456
- args: cmd === "feedback" ? ["«omitted»"] : redactArgs(rest),
458
+ args: activityArgs,
457
459
  code: exitCode,
458
460
  ms: durationMs,
459
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.5.0",
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",
@@ -1,9 +1,14 @@
1
- import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
1
+ import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto";
2
+ import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
2
3
  import { createServer, request as requestHttp } from "node:http";
3
4
  import { request as requestHttps } from "node:https";
4
5
  import { isIP } from "node:net";
6
+ import { dirname, join, resolve } from "node:path";
5
7
  import { parseArgs } from "node:util";
8
+ import { resolveDeveloperSession } from "../../auth.mjs";
6
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";
7
12
  import {
8
13
  SIGNATURE_LABEL,
9
14
  WEBHOOK_SIGNATURE_COVERED_COMPONENTS,
@@ -18,7 +23,12 @@ const METADATA_PATH = "/.well-known/tot-app-authorization-metadata";
18
23
  const METADATA_URL = `http://${METADATA_HOST}:${METADATA_PORT}${METADATA_PATH}`;
19
24
  const ARCHETYPES = ["label-station", "dropship", "inventory-sync"];
20
25
  const REQUEST_TIMEOUT_MS = 5000;
26
+ const STAFF_SESSION_TIMEOUT_MS = 30_000;
21
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}$/;
22
32
 
23
33
  const USAGE = `tot app conformance --url <webhookUrl> [--archetype ${ARCHETYPES.join("|")}]
24
34
 
@@ -36,7 +46,16 @@ for the duration of the run. The bundled RSA verifier works with tot app dev emi
36
46
 
37
47
  For replay, return a 2xx JSON response with {"accepted":true,"duplicate":true}
38
48
  when the same CloudEvent ID is received again. Check connector state separately
39
- to confirm idempotent side effects and handling of stale inventory.`;
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.`;
40
59
 
41
60
  /** @param {string} input */
42
61
  function loopbackUrl(input) {
@@ -175,9 +194,65 @@ function post(target, body, headers, checkDuplicate, request) {
175
194
  });
176
195
  }
177
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
+
178
253
  /**
179
254
  * @param {string[]} argv
180
- * @param {{ makeServer?: typeof createServer, request?: typeof directRequest, now?: () => number, log?: (line: string) => void, error?: (line: string) => void }} [deps]
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]
181
256
  */
182
257
  export async function runAppConformance(argv, {
183
258
  makeServer = createServer,
@@ -185,11 +260,16 @@ export async function runAppConformance(argv, {
185
260
  now = Date.now,
186
261
  log = console.log,
187
262
  error = console.error,
263
+ env = process.env,
264
+ resolveDev = resolveDeveloperSession,
265
+ fetchImpl = fetch,
188
266
  } = {}) {
189
267
  let values;
190
268
  try {
191
269
  ({ values } = parseArgs({ args: argv, options: {
192
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" },
193
273
  } }));
194
274
  } catch {
195
275
  error(fail("Invalid conformance options", "tot app conformance --help"));
@@ -199,6 +279,27 @@ export async function runAppConformance(argv, {
199
279
  log(USAGE);
200
280
  return 0;
201
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
+ }
202
303
  const target = values.url && loopbackUrl(values.url);
203
304
  if (!target) {
204
305
  error(fail("Conformance requires --url with a loopback HTTP(S) webhook URL", "tot app conformance --help"));
@@ -229,10 +330,11 @@ export async function runAppConformance(argv, {
229
330
  }
230
331
 
231
332
  try {
232
- log(`Webhook conformance${values.archetype ? ` (${values.archetype})` : ""}`);
333
+ if (!certify) log(`Webhook conformance${archetype ? ` (${archetype})` : ""}`);
334
+ const checks = [];
233
335
  let passed = true;
234
336
  let initialAccepted = false;
235
- for (const { label, acknowledgment, body } of fixtures(values.archetype)) {
337
+ for (const { label, acknowledgment, body } of fixtures(archetype)) {
236
338
  const replay = acknowledgment === "replay";
237
339
  const digest = await computeContentDigestSha256(body);
238
340
  const params = buildSignatureParamsValue(WEBHOOK_SIGNATURE_COVERED_COMPONENTS, {
@@ -255,17 +357,42 @@ export async function runAppConformance(argv, {
255
357
  else if (replay && !initialAccepted) finding = `HTTP ${status} duplicate reported without a successful initial delivery`;
256
358
  else {
257
359
  if (acknowledgment === "initial") initialAccepted = true;
258
- log(`PASS ${label} — HTTP ${status} ${replay ? "duplicate acknowledged" : "delivery acknowledged"}`);
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"}`);
259
363
  continue;
260
364
  }
261
365
  } catch {
262
366
  finding = "request failed or timed out";
263
367
  }
264
- log(`FAIL ${label} — ${finding}`);
368
+ (certify ? error : log)(`FAIL ${label} — ${finding}`);
265
369
  passed = false;
266
370
  }
267
- log("Results reflect webhook responses. Inspect connector state to assess side effects.");
268
- return passed ? 0 : 1;
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;
269
396
  } finally {
270
397
  await close(server);
271
398
  }
@@ -15,6 +15,7 @@ const USAGE = `tot app — build and install a Storefront Private App
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
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\`)
18
19
  tot app install install your app on your store (env defaults to test); prints the client secret once
19
20
  tot app update <installId> push your app's current version, scopes and manifest to an install
20
21
  tot app rotate <installId> issue a new client secret (printed once)