@tokenoftrust/cli 7.4.5 → 7.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/tot.mjs
CHANGED
|
@@ -79,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
|
|
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)" },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/cli",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.5.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",
|
|
@@ -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
|
-
|
|
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 === "--
|
|
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?:
|
|
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
|
-
/**
|
|
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,272 @@
|
|
|
1
|
+
import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
|
|
2
|
+
import { createServer, request as requestHttp } from "node:http";
|
|
3
|
+
import { request as requestHttps } from "node:https";
|
|
4
|
+
import { isIP } from "node:net";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { fail } from "../../errors.mjs";
|
|
7
|
+
import {
|
|
8
|
+
SIGNATURE_LABEL,
|
|
9
|
+
WEBHOOK_SIGNATURE_COVERED_COMPONENTS,
|
|
10
|
+
buildSignatureBase,
|
|
11
|
+
buildSignatureParamsValue,
|
|
12
|
+
computeContentDigestSha256,
|
|
13
|
+
} from "../../vendor/private-apps-devkit.mjs";
|
|
14
|
+
|
|
15
|
+
const METADATA_HOST = "127.0.0.1";
|
|
16
|
+
const METADATA_PORT = 37891;
|
|
17
|
+
const METADATA_PATH = "/.well-known/tot-app-authorization-metadata";
|
|
18
|
+
const METADATA_URL = `http://${METADATA_HOST}:${METADATA_PORT}${METADATA_PATH}`;
|
|
19
|
+
const ARCHETYPES = ["label-station", "dropship", "inventory-sync"];
|
|
20
|
+
const REQUEST_TIMEOUT_MS = 5000;
|
|
21
|
+
const MAX_ACK_BYTES = 4096;
|
|
22
|
+
|
|
23
|
+
const USAGE = `tot app conformance --url <webhookUrl> [--archetype ${ARCHETYPES.join("|")}]
|
|
24
|
+
|
|
25
|
+
Start your connector in local test mode with clean state. Set the verifier's
|
|
26
|
+
expected @target-uri to the normalized webhook URL. localhost connects to IPv4 loopback.
|
|
27
|
+
|
|
28
|
+
By default and for dropship, the checklist sends synthetic fulfillment and
|
|
29
|
+
inventory events. label-station checks assignment events and their replay.
|
|
30
|
+
inventory-sync checks inventory events and their replay.
|
|
31
|
+
|
|
32
|
+
Configure your local Ed25519 verifier to load webhook_signing_keys from
|
|
33
|
+
${METADATA_URL}
|
|
34
|
+
when it receives a delivery. The command serves the ephemeral public key there
|
|
35
|
+
for the duration of the run. The bundled RSA verifier works with tot app dev emit.
|
|
36
|
+
|
|
37
|
+
For replay, return a 2xx JSON response with {"accepted":true,"duplicate":true}
|
|
38
|
+
when the same CloudEvent ID is received again. Check connector state separately
|
|
39
|
+
to confirm idempotent side effects and handling of stale inventory.`;
|
|
40
|
+
|
|
41
|
+
/** @param {string} input */
|
|
42
|
+
function loopbackUrl(input) {
|
|
43
|
+
const target = URL.parse(input);
|
|
44
|
+
if (!target || !["http:", "https:"].includes(target.protocol) || target.username || target.password || target.href.includes("#") || target.port === "0") {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const { hostname } = target;
|
|
48
|
+
const loopback = hostname === "localhost" || hostname === "[::1]" || (isIP(hostname) === 4 && hostname.startsWith("127."));
|
|
49
|
+
return loopback ? target : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** @param {number} minute */
|
|
53
|
+
const fixtureTime = (minute) => new Date(Date.UTC(2026, 0, 1, 12, minute)).toISOString();
|
|
54
|
+
|
|
55
|
+
/** @param {string} state @param {number} eventVersion @param {number} minute */
|
|
56
|
+
function assignmentData(state, eventVersion, minute) {
|
|
57
|
+
return {
|
|
58
|
+
assignmentId: "conformance-assignment",
|
|
59
|
+
orderId: "conformance-order",
|
|
60
|
+
stage: "preview",
|
|
61
|
+
state,
|
|
62
|
+
eventVersion,
|
|
63
|
+
occurredAt: fixtureTime(minute),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param {number} balance @param {number} available @param {number} minute */
|
|
68
|
+
function inventoryData(balance, available, minute) {
|
|
69
|
+
return { sku: "CONFORMANCE-SKU", locationId: "conformance-location", balance, available, asOf: fixtureTime(minute) };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {string | undefined} archetype */
|
|
73
|
+
function fixtures(archetype) {
|
|
74
|
+
const created = { id: "assignment-created", topic: "fulfillment.assignment.created", data: assignmentData("active", 1, 0) };
|
|
75
|
+
const advanced = { id: "inventory-advanced", topic: "inventory.changed", data: inventoryData(20, 18, 4) };
|
|
76
|
+
const assignments = [
|
|
77
|
+
{ ...created, label: "Assignment created", acknowledgment: "initial", minute: 0 },
|
|
78
|
+
{ ...created, label: "Assignment replay", acknowledgment: "replay", minute: 1 },
|
|
79
|
+
{ label: "Assignment held", id: "assignment-held", topic: "fulfillment.assignment.updated", data: assignmentData("held", 2, 2), minute: 2 },
|
|
80
|
+
{ label: "Assignment cancelled", id: "assignment-cancelled", topic: "fulfillment.assignment.updated", data: assignmentData("cancelled", 3, 3), minute: 3 },
|
|
81
|
+
];
|
|
82
|
+
const inventory = [
|
|
83
|
+
{ ...advanced, label: "Inventory advanced", acknowledgment: archetype === "inventory-sync" ? "initial" : undefined, minute: 4 },
|
|
84
|
+
...(archetype === "inventory-sync" ? [{ ...advanced, label: "Inventory replay", acknowledgment: "replay", minute: 5 }] : []),
|
|
85
|
+
{ label: "Inventory stale", id: "inventory-stale", topic: "inventory.changed", data: inventoryData(12, 10, 3), minute: 6 },
|
|
86
|
+
];
|
|
87
|
+
const selected = [
|
|
88
|
+
...(archetype === "inventory-sync" ? [] : assignments),
|
|
89
|
+
...(archetype === "label-station" ? [] : inventory),
|
|
90
|
+
];
|
|
91
|
+
return selected.map(({ label, id, topic, data, acknowledgment, minute }) => ({
|
|
92
|
+
label,
|
|
93
|
+
acknowledgment,
|
|
94
|
+
body: JSON.stringify({
|
|
95
|
+
specversion: "1.0",
|
|
96
|
+
id: `conformance-${id}`,
|
|
97
|
+
source: "/tenants/conformance/storefront",
|
|
98
|
+
type: `com.tokenoftrust.storefront.${topic}`,
|
|
99
|
+
time: fixtureTime(minute),
|
|
100
|
+
datacontenttype: "application/json",
|
|
101
|
+
dataschemaversion: "1",
|
|
102
|
+
tenantid: "conformance",
|
|
103
|
+
appinstallid: "conformance-install",
|
|
104
|
+
retrycount: acknowledgment === "replay" ? 1 : 0,
|
|
105
|
+
data,
|
|
106
|
+
}),
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** @param {ReturnType<typeof createServer>} server */
|
|
111
|
+
function listen(server) {
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
server.once("error", reject);
|
|
114
|
+
server.listen(METADATA_PORT, METADATA_HOST, () => {
|
|
115
|
+
server.off("error", reject);
|
|
116
|
+
resolve(undefined);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** @param {ReturnType<typeof createServer>} server */
|
|
122
|
+
function close(server) {
|
|
123
|
+
return new Promise((resolve) => {
|
|
124
|
+
server.close(resolve);
|
|
125
|
+
server.closeAllConnections();
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** @param {import("node:http").IncomingMessage} response */
|
|
130
|
+
async function duplicateAcknowledged(response) {
|
|
131
|
+
const chunks = [];
|
|
132
|
+
let total = 0;
|
|
133
|
+
for await (const chunk of response) {
|
|
134
|
+
total += chunk.length;
|
|
135
|
+
if (total > MAX_ACK_BYTES) return false;
|
|
136
|
+
chunks.push(chunk);
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
140
|
+
return body?.accepted === true && body?.duplicate === true;
|
|
141
|
+
} catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {URL} target @param {import("node:https").RequestOptions} options @param {(response: import("node:http").IncomingMessage) => void} callback */
|
|
147
|
+
function directRequest(target, options, callback) {
|
|
148
|
+
const request = target.protocol === "https:" ? requestHttps : requestHttp;
|
|
149
|
+
return request(target, options, callback);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @param {URL} target @param {string} body @param {Record<string, string>} headers @param {boolean} checkDuplicate @param {typeof directRequest} request */
|
|
153
|
+
function post(target, body, headers, checkDuplicate, request) {
|
|
154
|
+
const localhost = target.hostname === "localhost";
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const req = request(target, {
|
|
157
|
+
method: "POST",
|
|
158
|
+
path: target.href.slice(target.origin.length),
|
|
159
|
+
...(localhost ? { hostname: METADATA_HOST, servername: "localhost" } : {}),
|
|
160
|
+
rejectUnauthorized: true,
|
|
161
|
+
agent: false,
|
|
162
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
163
|
+
headers: { ...headers, host: target.host, "content-length": String(Buffer.byteLength(body)) },
|
|
164
|
+
}, (response) => {
|
|
165
|
+
const status = response.statusCode ?? 0;
|
|
166
|
+
if (checkDuplicate && status >= 200 && status < 300) {
|
|
167
|
+
void duplicateAcknowledged(response).then((duplicate) => resolve({ status, duplicate }), reject);
|
|
168
|
+
} else {
|
|
169
|
+
response.destroy();
|
|
170
|
+
resolve({ status, duplicate: false });
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
req.once("error", reject);
|
|
174
|
+
req.end(body);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @param {string[]} argv
|
|
180
|
+
* @param {{ makeServer?: typeof createServer, request?: typeof directRequest, now?: () => number, log?: (line: string) => void, error?: (line: string) => void }} [deps]
|
|
181
|
+
*/
|
|
182
|
+
export async function runAppConformance(argv, {
|
|
183
|
+
makeServer = createServer,
|
|
184
|
+
request = directRequest,
|
|
185
|
+
now = Date.now,
|
|
186
|
+
log = console.log,
|
|
187
|
+
error = console.error,
|
|
188
|
+
} = {}) {
|
|
189
|
+
let values;
|
|
190
|
+
try {
|
|
191
|
+
({ values } = parseArgs({ args: argv, options: {
|
|
192
|
+
url: { type: "string" }, archetype: { type: "string" }, help: { type: "boolean", short: "h" },
|
|
193
|
+
} }));
|
|
194
|
+
} catch {
|
|
195
|
+
error(fail("Invalid conformance options", "tot app conformance --help"));
|
|
196
|
+
return 2;
|
|
197
|
+
}
|
|
198
|
+
if (values.help) {
|
|
199
|
+
log(USAGE);
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
const target = values.url && loopbackUrl(values.url);
|
|
203
|
+
if (!target) {
|
|
204
|
+
error(fail("Conformance requires --url with a loopback HTTP(S) webhook URL", "tot app conformance --help"));
|
|
205
|
+
return 2;
|
|
206
|
+
}
|
|
207
|
+
if (values.archetype !== undefined && !ARCHETYPES.includes(values.archetype)) {
|
|
208
|
+
error(fail("Choose a supported conformance archetype", "tot app conformance --help"));
|
|
209
|
+
return 2;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
213
|
+
const kid = `conformance-${randomUUID()}`;
|
|
214
|
+
const jwk = { ...publicKey.export({ format: "jwk" }), kid, alg: "EdDSA", use: "sig" };
|
|
215
|
+
const metadata = JSON.stringify({ webhook_signing_keys: { keys: [jwk] } });
|
|
216
|
+
const server = makeServer((req, res) => {
|
|
217
|
+
if (req.method === "GET" && req.url === METADATA_PATH) {
|
|
218
|
+
res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store, max-age=0" });
|
|
219
|
+
res.end(metadata);
|
|
220
|
+
} else {
|
|
221
|
+
res.writeHead(404).end();
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
try {
|
|
225
|
+
await listen(server);
|
|
226
|
+
} catch {
|
|
227
|
+
error(fail(`Unable to serve conformance signing keys at ${METADATA_URL}`));
|
|
228
|
+
return 1;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
try {
|
|
232
|
+
log(`Webhook conformance${values.archetype ? ` (${values.archetype})` : ""}`);
|
|
233
|
+
let passed = true;
|
|
234
|
+
let initialAccepted = false;
|
|
235
|
+
for (const { label, acknowledgment, body } of fixtures(values.archetype)) {
|
|
236
|
+
const replay = acknowledgment === "replay";
|
|
237
|
+
const digest = await computeContentDigestSha256(body);
|
|
238
|
+
const params = buildSignatureParamsValue(WEBHOOK_SIGNATURE_COVERED_COMPONENTS, {
|
|
239
|
+
created: Math.floor(now() / 1000), keyid: kid, alg: "ed25519",
|
|
240
|
+
});
|
|
241
|
+
const base = buildSignatureBase([["@method", "POST"], ["@target-uri", target.href], ["content-digest", digest]], params);
|
|
242
|
+
const headers = {
|
|
243
|
+
"content-type": "application/cloudevents+json",
|
|
244
|
+
"content-digest": digest,
|
|
245
|
+
"signature-input": `${SIGNATURE_LABEL}=${params}`,
|
|
246
|
+
signature: `${SIGNATURE_LABEL}=:${sign(null, Buffer.from(base), privateKey).toString("base64")}:`,
|
|
247
|
+
};
|
|
248
|
+
let finding;
|
|
249
|
+
try {
|
|
250
|
+
const { status, duplicate } = await post(target, body, headers, Boolean(acknowledgment), request);
|
|
251
|
+
if (status >= 300 && status < 400) finding = `HTTP ${status} redirect refused`;
|
|
252
|
+
else if (status < 200 || status >= 300) finding = `HTTP ${status} delivery rejected`;
|
|
253
|
+
else if (acknowledgment === "initial" && duplicate) finding = `HTTP ${status} initial delivery already known. Use clean local state.`;
|
|
254
|
+
else if (replay && !duplicate) finding = `HTTP ${status} delivery acknowledged without duplicate confirmation`;
|
|
255
|
+
else if (replay && !initialAccepted) finding = `HTTP ${status} duplicate reported without a successful initial delivery`;
|
|
256
|
+
else {
|
|
257
|
+
if (acknowledgment === "initial") initialAccepted = true;
|
|
258
|
+
log(`PASS ${label} — HTTP ${status} ${replay ? "duplicate acknowledged" : "delivery acknowledged"}`);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
} catch {
|
|
262
|
+
finding = "request failed or timed out";
|
|
263
|
+
}
|
|
264
|
+
log(`FAIL ${label} — ${finding}`);
|
|
265
|
+
passed = false;
|
|
266
|
+
}
|
|
267
|
+
log("Results reflect webhook responses. Inspect connector state to assess side effects.");
|
|
268
|
+
return passed ? 0 : 1;
|
|
269
|
+
} finally {
|
|
270
|
+
await close(server);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -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,7 @@ 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
|
|
16
18
|
tot app install install your app on your store (env defaults to test); prints the client secret once
|
|
17
19
|
tot app update <installId> push your app's current version, scopes and manifest to an install
|
|
18
20
|
tot app rotate <installId> issue a new client secret (printed once)
|
|
@@ -23,7 +25,7 @@ const USAGE = `tot app — build and install a Storefront Private App
|
|
|
23
25
|
tot app validate [<manifest>] lint tot-app.json offline (invalid_manifest on refusal)
|
|
24
26
|
tot app candidate status your store's candidates and their status
|
|
25
27
|
tot app candidate withdraw <candidateId> withdraw a pending production candidate
|
|
26
|
-
tot app candidate
|
|
28
|
+
tot app candidate [--generate-keys [dir]] stage a production candidate for owner approval
|
|
27
29
|
|
|
28
30
|
Run \`tot app <command> --help\` for options. Online commands use your \`tot login\` session.`;
|
|
29
31
|
|
|
@@ -43,6 +45,10 @@ export async function run(argv, ctx) {
|
|
|
43
45
|
const { run: runDev } = await import("./dev.mjs");
|
|
44
46
|
return /** @type {any} */ (runDev)(rest, ctx);
|
|
45
47
|
}
|
|
48
|
+
if (sub === "conformance") {
|
|
49
|
+
const { runAppConformance } = await import("./conformance.mjs");
|
|
50
|
+
return runAppConformance(rest);
|
|
51
|
+
}
|
|
46
52
|
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
53
|
const { runAdmin } = await import("./admin.mjs");
|
|
48
54
|
return runAdmin(argv, ctx);
|