@tokenoftrust/cli 7.4.4 → 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 +2 -1
- package/package.json +1 -1
- package/src/commands/app/admin.mjs +70 -12
- package/src/commands/app/candidate-keys.mjs +46 -0
- package/src/commands/app/conformance.mjs +272 -0
- package/src/commands/app/index.mjs +7 -1
- package/src/vendor/connector-kit/PIN.json +8 -8
- package/src/vendor/connector-kit/api.js +21 -6
- package/src/vendor/connector-kit/auth.js +8 -5
- package/src/vendor/connector-kit/errors.js +15 -6
- package/src/vendor/connector-kit/index.js +2 -2
- package/src/vendor/connector-kit/metadata.js +26 -4
- package/src/vendor/connector-kit/retry.js +9 -9
- package/template/private-app/.env.example +4 -0
- package/template/private-app/connector.js +4 -2
- package/template/private-app/tests/connector.spec.js +69 -1
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);
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"source": "tokenoftrust/storefront-devkit",
|
|
3
3
|
"path": "packages/connector-kit/src",
|
|
4
|
-
"commit": "
|
|
5
|
-
"kitVersion": "1.
|
|
4
|
+
"commit": "50ee510266b2af5daa7c86dd93af128fbbb4d7a7",
|
|
5
|
+
"kitVersion": "1.1.0",
|
|
6
6
|
"files": {
|
|
7
|
-
"api.js": "
|
|
8
|
-
"auth.js": "
|
|
7
|
+
"api.js": "ff6c8a90a9d2f5c7421916ec1fca6f46ee078748011963e68be75afa1efe8b4b",
|
|
8
|
+
"auth.js": "3d350e8a377024837f89c7789f7a10bec961ba182ef5ad7bd7e78b6e50a2f267",
|
|
9
9
|
"encoding.js": "6de8900e65174a9d53c6fb55bcfee2afe12a08f99a34280c002a176f1c1a388c",
|
|
10
|
-
"errors.js": "
|
|
10
|
+
"errors.js": "f27facae7a1646baf223babb5384d03d376f9c21ddad7b685ebfe6d8e91fdc6a",
|
|
11
11
|
"http-signature.js": "a823f1e897e65839a65562951102baccb7e64395db4201b13cb1e6c21891b424",
|
|
12
|
-
"index.js": "
|
|
13
|
-
"metadata.js": "
|
|
14
|
-
"retry.js": "
|
|
12
|
+
"index.js": "e60e2691cbe82cc1ec02028073eb8c0f37c7b1774c9e127e8a9434ad93f719ed",
|
|
13
|
+
"metadata.js": "a0722dc06899adbe0237c71b45908186931f0131f95caa060ae04b1c4dfa625e",
|
|
14
|
+
"retry.js": "b30f0776bf861894a297a589bf4df474e92aa0677c26140fc34ee692fcfbfc31",
|
|
15
15
|
"structured-fields.js": "e253d027e19c61f5c48dbb09d927dc42d9cf43c926fe512c44cc06c77d08d5cc",
|
|
16
16
|
"webhook.js": "c90534b1db38e289fdae2c6d7c090389d6e0077f0fc919f95cc2dc07d703e428"
|
|
17
17
|
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// `limit` and `updatedSince`) drains every page.
|
|
8
8
|
import { ApiError, AuthError, ConnectorError, TransportError, safeCode, safeRequestId } from './errors.js';
|
|
9
9
|
import { hex, sha256, utf8 } from './encoding.js';
|
|
10
|
-
import { API_PREFIX,
|
|
10
|
+
import { API_PREFIX, resolveStoreBase } from './metadata.js';
|
|
11
11
|
import { RETRYABLE_STATUS, backoffDelay, defaultSleep, parseRetryAfter, retryPolicy } from './retry.js';
|
|
12
12
|
|
|
13
13
|
const MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
@@ -51,9 +51,12 @@ function itemsOf(body, itemsKey) {
|
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
export class ApiClient {
|
|
54
|
+
#apiPrefix;
|
|
55
|
+
|
|
54
56
|
/**
|
|
55
57
|
* @param {object} options
|
|
56
58
|
* @param {string} options.origin The storefront origin, e.g. https://acme.tokenoftrust.store.
|
|
59
|
+
* @param {string} [options.tenant] Store slug on a shared host. Can also be supplied as a single path segment in origin.
|
|
57
60
|
* @param {{ getAccessToken(): Promise<string>, invalidate?(token: string): void }} options.auth Usually a ConnectorAuthClient.
|
|
58
61
|
* @param {object} [options.retry] Retry policy overrides (see DEFAULT_RETRY_POLICY).
|
|
59
62
|
* @param {typeof fetch} [options.fetch]
|
|
@@ -64,6 +67,7 @@ export class ApiClient {
|
|
|
64
67
|
*/
|
|
65
68
|
constructor({
|
|
66
69
|
origin,
|
|
70
|
+
tenant,
|
|
67
71
|
auth,
|
|
68
72
|
retry,
|
|
69
73
|
fetch: fetchImpl = (...args) => globalThis.fetch(...args),
|
|
@@ -73,7 +77,9 @@ export class ApiClient {
|
|
|
73
77
|
onRetry,
|
|
74
78
|
}) {
|
|
75
79
|
if (!auth || typeof auth.getAccessToken !== 'function') throw new TypeError('auth must provide getAccessToken()');
|
|
76
|
-
|
|
80
|
+
const { bareOrigin, base } = resolveStoreBase(origin, tenant);
|
|
81
|
+
this.origin = bareOrigin;
|
|
82
|
+
this.#apiPrefix = `${base.slice(bareOrigin.length)}${API_PREFIX}`;
|
|
77
83
|
this.auth = auth;
|
|
78
84
|
this.retry = retryPolicy(retry);
|
|
79
85
|
this.fetch = fetchImpl;
|
|
@@ -106,9 +112,11 @@ export class ApiClient {
|
|
|
106
112
|
url(path, query) {
|
|
107
113
|
const refuse = () => new TypeError('path must be an absolute path under /api/apps/v1, e.g. /inventory; pass query separately');
|
|
108
114
|
if (typeof path !== 'string' || !SAFE_PATH.test(path)) throw refuse();
|
|
109
|
-
|
|
115
|
+
if (this.#apiPrefix !== API_PREFIX && /%2f|%5c/i.test(path)) throw refuse();
|
|
116
|
+
const pathname = `${this.#apiPrefix}${path}`;
|
|
117
|
+
const url = new URL(pathname, this.origin);
|
|
110
118
|
// Any normalization (a dot segment, an encoded dot) would move the call elsewhere.
|
|
111
|
-
if (url.origin !== this.origin || url.pathname !==
|
|
119
|
+
if (url.origin !== this.origin || url.pathname !== pathname) throw refuse();
|
|
112
120
|
appendQuery(url.searchParams, query);
|
|
113
121
|
return url.toString();
|
|
114
122
|
}
|
|
@@ -158,7 +166,7 @@ export class ApiClient {
|
|
|
158
166
|
const res = await this.send(url, { method: verb, headers: { ...sendHeaders, authorization: `Bearer ${token}` }, body: payload, signal });
|
|
159
167
|
const result = await this.read(res);
|
|
160
168
|
if (res.ok) return { ...result, ...(key ? { idempotencyKey: key } : {}) };
|
|
161
|
-
error = this.refusal(res, result);
|
|
169
|
+
error = this.refusal(res, result, path);
|
|
162
170
|
} catch (err) {
|
|
163
171
|
if (!(err instanceof ConnectorError)) throw err;
|
|
164
172
|
error = err;
|
|
@@ -204,10 +212,11 @@ export class ApiClient {
|
|
|
204
212
|
return { status: res.status, body, headers: res.headers, requestId };
|
|
205
213
|
}
|
|
206
214
|
|
|
207
|
-
refusal(res, { body, requestId }) {
|
|
215
|
+
refusal(res, { body, requestId }, path) {
|
|
208
216
|
if (res.status >= 300 && res.status < 400) return new TransportError({ code: 'redirect_refused', status: res.status, requestId });
|
|
209
217
|
const code = safeCode(body?.code ?? body?.error ?? (body === null ? `http_${res.status}` : undefined));
|
|
210
218
|
const holds = Array.isArray(body?.holds) ? body.holds.map(safeCode) : undefined;
|
|
219
|
+
const isInventoryBatchRefusal = path?.startsWith('/inventory/') && (res.status === 400 || res.status === 422);
|
|
211
220
|
return new ApiError({
|
|
212
221
|
code,
|
|
213
222
|
status: res.status,
|
|
@@ -215,6 +224,9 @@ export class ApiClient {
|
|
|
215
224
|
retryable: RETRYABLE_STATUS.has(res.status),
|
|
216
225
|
retryAfterMs: parseRetryAfter(res.headers.get('retry-after'), this.now()),
|
|
217
226
|
holds,
|
|
227
|
+
field: body?.field,
|
|
228
|
+
index: isInventoryBatchRefusal ? body?.index : undefined,
|
|
229
|
+
reasons: res.status === 409 ? body?.reasons : undefined,
|
|
218
230
|
});
|
|
219
231
|
}
|
|
220
232
|
|
|
@@ -233,6 +245,9 @@ export class ApiClient {
|
|
|
233
245
|
* @returns {AsyncGenerator<{ items: any[], nextCursor?: string, truncated: boolean, body: any, requestId?: string }>}
|
|
234
246
|
*/
|
|
235
247
|
async *pages(path, { query, limit, updatedSince, cursor, itemsKey, maxPages = Infinity, signal } = {}) {
|
|
248
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
|
|
249
|
+
throw new TypeError('limit must be an integer in 1..100');
|
|
250
|
+
}
|
|
236
251
|
let next = cursor;
|
|
237
252
|
const seen = new Set(cursor === undefined ? [] : [cursor]);
|
|
238
253
|
for (let page = 0; page < maxPages; page++) {
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// error, and a refusal carries only the OAuth `error` code.
|
|
11
11
|
import { AuthError, TransportError, safeRequestId } from './errors.js';
|
|
12
12
|
import { base64Encode, base64UrlEncode, utf8 } from './encoding.js';
|
|
13
|
-
import { TOKEN_PATH,
|
|
13
|
+
import { TOKEN_PATH, resolveStoreBase } from './metadata.js';
|
|
14
14
|
import { RETRYABLE_STATUS, backoffDelay, defaultSleep, parseRetryAfter, retryPolicy } from './retry.js';
|
|
15
15
|
|
|
16
16
|
export const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
|
|
@@ -43,9 +43,9 @@ async function importSigningKey(privateKey) {
|
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
function jwsAlgFor(key) {
|
|
46
|
-
if (key.algorithm.name === 'RSASSA-PKCS1-v1_5') return 'RS256';
|
|
46
|
+
if (key.algorithm.name === 'RSASSA-PKCS1-v1_5' && key.algorithm.hash?.name === 'SHA-256') return 'RS256';
|
|
47
47
|
if (key.algorithm.name === 'ECDSA' && key.algorithm.namedCurve === 'P-256') return 'ES256';
|
|
48
|
-
throw new TypeError('privateKey must be RSASSA-PKCS1-v1_5 (RS256) or ECDSA P-256 (ES256)');
|
|
48
|
+
throw new TypeError('privateKey must be RSASSA-PKCS1-v1_5 with SHA-256 (RS256) or ECDSA P-256 (ES256)');
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
export class ConnectorAuthClient {
|
|
@@ -59,6 +59,7 @@ export class ConnectorAuthClient {
|
|
|
59
59
|
/**
|
|
60
60
|
* @param {object} options
|
|
61
61
|
* @param {string} options.origin The storefront origin, e.g. https://acme.tokenoftrust.store.
|
|
62
|
+
* @param {string} [options.tenant] Store slug on a shared host. Can also be supplied as a single path segment in origin.
|
|
62
63
|
* @param {string} options.clientId The installation's client id.
|
|
63
64
|
* @param {string} [options.clientSecret] For `client_secret_basic` (default) or `client_secret_post`.
|
|
64
65
|
* @param {CryptoKey|object} [options.privateKey] For `private_key_jwt`: a private CryptoKey or private JWK (RSA or EC P-256).
|
|
@@ -75,6 +76,7 @@ export class ConnectorAuthClient {
|
|
|
75
76
|
*/
|
|
76
77
|
constructor({
|
|
77
78
|
origin,
|
|
79
|
+
tenant,
|
|
78
80
|
clientId,
|
|
79
81
|
clientSecret,
|
|
80
82
|
privateKey,
|
|
@@ -102,8 +104,9 @@ export class ConnectorAuthClient {
|
|
|
102
104
|
if (!Number.isInteger(assertionLifetimeSeconds) || assertionLifetimeSeconds < 1 || assertionLifetimeSeconds > MAX_ASSERTION_LIFETIME_SECONDS) {
|
|
103
105
|
throw new TypeError(`assertionLifetimeSeconds must be an integer in 1..${MAX_ASSERTION_LIFETIME_SECONDS}`);
|
|
104
106
|
}
|
|
105
|
-
|
|
106
|
-
this.
|
|
107
|
+
const { bareOrigin, base } = resolveStoreBase(origin, tenant);
|
|
108
|
+
this.origin = bareOrigin;
|
|
109
|
+
this.tokenEndpoint = `${base}${TOKEN_PATH}`;
|
|
107
110
|
this.clientId = clientId;
|
|
108
111
|
this.method = resolved;
|
|
109
112
|
this.refreshSkewMs = refreshSkewSeconds * 1000;
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
// The kit's error model. Every failure carries a stable machine `code` to branch
|
|
2
|
-
// on. Remote
|
|
3
|
-
// code) is never copied into an error, so an error is always safe to log.
|
|
2
|
+
// on. Remote prose (`message`, `error_description`) is never copied into an error.
|
|
4
3
|
|
|
5
4
|
const SAFE_CODE = /^[a-z][a-z0-9_.:-]{0,63}$/;
|
|
6
5
|
const SAFE_REQUEST_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
6
|
+
const SAFE_FIELD = /^[A-Za-z0-9_.\[\]:-]{1,128}$/;
|
|
7
7
|
|
|
8
8
|
/** A remote code if it is shaped like one, otherwise `unexpected`. */
|
|
9
9
|
export function safeCode(value) {
|
|
10
|
-
return typeof value === 'string' && SAFE_CODE.
|
|
10
|
+
return typeof value === 'string' && SAFE_CODE.exec(value)?.[0] === value ? value : 'unexpected';
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
/** A remote correlation id if it is shaped like one, otherwise undefined. */
|
|
14
14
|
export function safeRequestId(value) {
|
|
15
|
-
return typeof value === 'string' && SAFE_REQUEST_ID.
|
|
15
|
+
return typeof value === 'string' && SAFE_REQUEST_ID.exec(value)?.[0] === value ? value : undefined;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export class ConnectorError extends Error {
|
|
@@ -25,10 +25,13 @@ export class ConnectorError extends Error {
|
|
|
25
25
|
* @param {boolean} [fields.retryable] Whether retrying the same request can succeed.
|
|
26
26
|
* @param {number} [fields.retryAfterMs] The server's `Retry-After`, in milliseconds.
|
|
27
27
|
* @param {string[]} [fields.holds] Hold codes a refusal listed.
|
|
28
|
+
* @param {string} [fields.field] Field named by a refusal.
|
|
29
|
+
* @param {number} [fields.index] Index named by an inventory batch refusal.
|
|
30
|
+
* @param {string[]} [fields.reasons] Machine-readable conflict reasons.
|
|
28
31
|
* @param {string} [fields.idempotencyKey] The key a failed write was sent under; resend under it.
|
|
29
32
|
* @param {unknown} [fields.cause]
|
|
30
33
|
*/
|
|
31
|
-
constructor({ kind, code, status, requestId, retryable = false, retryAfterMs, holds, idempotencyKey, cause }) {
|
|
34
|
+
constructor({ kind, code, status, requestId, retryable = false, retryAfterMs, holds, field, index, reasons, idempotencyKey, cause }) {
|
|
32
35
|
super(status === undefined ? `${kind}:${code}` : `${kind}:${code} (${status})`, cause === undefined ? undefined : { cause });
|
|
33
36
|
this.name = 'ConnectorError';
|
|
34
37
|
this.kind = kind;
|
|
@@ -38,13 +41,19 @@ export class ConnectorError extends Error {
|
|
|
38
41
|
this.retryable = retryable;
|
|
39
42
|
this.retryAfterMs = retryAfterMs;
|
|
40
43
|
this.holds = holds;
|
|
44
|
+
if (typeof field === 'string' && SAFE_FIELD.exec(field)?.[0] === field) this.field = field;
|
|
45
|
+
if (Number.isSafeInteger(index) && index >= 0) this.index = index;
|
|
46
|
+
if (Array.isArray(reasons)) {
|
|
47
|
+
const valid = reasons.filter((reason) => safeCode(reason) === reason);
|
|
48
|
+
if (valid.length > 0 || reasons.length === 0) this.reasons = valid;
|
|
49
|
+
}
|
|
41
50
|
this.idempotencyKey = idempotencyKey;
|
|
42
51
|
}
|
|
43
52
|
|
|
44
53
|
/** The loggable fields. Never includes a cause, a body or a credential. */
|
|
45
54
|
toJSON() {
|
|
46
55
|
const out = { kind: this.kind, code: this.code };
|
|
47
|
-
for (const key of ['status', 'requestId', 'retryable', 'retryAfterMs', 'holds', 'idempotencyKey']) {
|
|
56
|
+
for (const key of ['status', 'requestId', 'retryable', 'retryAfterMs', 'holds', 'field', 'index', 'reasons', 'idempotencyKey']) {
|
|
48
57
|
if (this[key] !== undefined) out[key] = this[key];
|
|
49
58
|
}
|
|
50
59
|
return out;
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// contract (apps/private/contract). Vendor this directory; do not edit it in
|
|
3
3
|
// place. Zero dependencies, ESM, Web Crypto and fetch only.
|
|
4
4
|
|
|
5
|
-
export const KIT_VERSION = '1.
|
|
6
|
-
export const CONTRACT_VERSION = 'private-apps@1.
|
|
5
|
+
export const KIT_VERSION = '1.1.0';
|
|
6
|
+
export const CONTRACT_VERSION = 'private-apps@1.4';
|
|
7
7
|
|
|
8
8
|
export { ConnectorAuthClient, CLIENT_ASSERTION_TYPE, CLIENT_AUTH_METHODS, MAX_ASSERTION_LIFETIME_SECONDS } from './auth.js';
|
|
9
9
|
export { WebhookReceiver, MemorySeenEventStore, WEBHOOK_REFUSALS, EVENT_TYPE_PREFIX, DEFAULT_MAX_BODY_BYTES, normalizeHeaders } from './webhook.js';
|
|
@@ -12,6 +12,8 @@ export const API_PREFIX = '/api/apps/v1';
|
|
|
12
12
|
|
|
13
13
|
const DEFAULT_MAX_AGE_SECONDS = 300;
|
|
14
14
|
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
15
|
+
const STORE_URL = /^(https?:\/\/[^/?#\\@\s]+)(?:\/([a-z0-9][a-z0-9.-]{0,127}))?\/?$/i;
|
|
16
|
+
const TENANT = /^[a-z0-9][a-z0-9.-]{0,127}$/;
|
|
15
17
|
|
|
16
18
|
/**
|
|
17
19
|
* The storefront origin as `scheme://host[:port]`. HTTPS is required except for
|
|
@@ -19,18 +21,38 @@ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
|
19
21
|
* refused so a base URL with `/api/apps/v1` appended is caught at construction.
|
|
20
22
|
*/
|
|
21
23
|
export function normalizeOrigin(origin) {
|
|
24
|
+
const { bareOrigin } = parseStoreUrl(origin, false);
|
|
25
|
+
return bareOrigin;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function parseStoreUrl(origin, allowTenantPath) {
|
|
29
|
+
// Inspect the raw path before URL parsing can discard dot segments or empty query/fragment markers.
|
|
30
|
+
const input = String(origin);
|
|
31
|
+
const match = STORE_URL.exec(input);
|
|
32
|
+
if (!match || match[0] !== input || (!allowTenantPath && match[2])) {
|
|
33
|
+
const pathRule = allowTenantPath ? 'at most one tenant path segment' : 'no path';
|
|
34
|
+
throw new TypeError(`origin must be scheme://host[:port] with ${pathRule} and no query, fragment or credentials`);
|
|
35
|
+
}
|
|
22
36
|
let url;
|
|
23
37
|
try {
|
|
24
|
-
url = new URL(
|
|
38
|
+
url = new URL(match[1]);
|
|
25
39
|
} catch {
|
|
26
40
|
throw new TypeError('origin must be an absolute URL such as https://acme.tokenoftrust.store');
|
|
27
41
|
}
|
|
28
42
|
const loopback = url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);
|
|
29
43
|
if (url.protocol !== 'https:' && !loopback) throw new TypeError('origin must use https');
|
|
30
|
-
|
|
31
|
-
|
|
44
|
+
return { bareOrigin: url.origin, pathTenant: match[2] };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Resolve the OAuth and API base while keeping discovery on the bare host. */
|
|
48
|
+
export function resolveStoreBase(origin, tenant) {
|
|
49
|
+
const { bareOrigin, pathTenant } = parseStoreUrl(origin, true);
|
|
50
|
+
if (pathTenant !== undefined && tenant !== undefined) throw new TypeError('pass tenant in origin or as an option, not both');
|
|
51
|
+
const store = tenant === undefined ? pathTenant : tenant;
|
|
52
|
+
if (store !== undefined && (typeof store !== 'string' || !TENANT.test(store) || /\s/.test(store))) {
|
|
53
|
+
throw new TypeError('tenant must be a valid store slug');
|
|
32
54
|
}
|
|
33
|
-
return
|
|
55
|
+
return { bareOrigin, base: store === undefined ? bareOrigin : `${bareOrigin}/${store}` };
|
|
34
56
|
}
|
|
35
57
|
|
|
36
58
|
function maxAgeSeconds(cacheControl) {
|
|
@@ -46,13 +46,13 @@ export function backoffDelay(attempt, policy, random = Math.random) {
|
|
|
46
46
|
export const defaultSleep = (ms, signal) =>
|
|
47
47
|
new Promise((resolve, reject) => {
|
|
48
48
|
if (signal?.aborted) return reject(signal.reason);
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
);
|
|
49
|
+
const abort = () => {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
reject(signal.reason);
|
|
52
|
+
};
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
signal?.removeEventListener('abort', abort);
|
|
55
|
+
resolve();
|
|
56
|
+
}, ms);
|
|
57
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
58
58
|
});
|
|
@@ -12,6 +12,10 @@ PORT=8787
|
|
|
12
12
|
# Set these to leave local mode: webhook keys then come from the store's
|
|
13
13
|
# published metadata and the connector gets an API client (connector.js).
|
|
14
14
|
# TOT_STOREFRONT_ORIGIN=https://acme.tokenoftrust.store
|
|
15
|
+
# On a shared host such as https://storefront.tokenoftrust.store, set the bare
|
|
16
|
+
# host as TOT_STOREFRONT_ORIGIN and set TOT_TENANT to route token and API calls.
|
|
17
|
+
# Leave TOT_TENANT unset on a dedicated tenant host.
|
|
18
|
+
# TOT_TENANT=acme
|
|
15
19
|
# TOT_CLIENT_ID=
|
|
16
20
|
# TOT_CLIENT_SECRET=
|
|
17
21
|
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* the credentials below are also set.
|
|
13
13
|
* Unset -> local mode: webhooks are checked against the
|
|
14
14
|
* throwaway key `tot app dev` wrote to .tot/dev-keys.json.
|
|
15
|
+
* TOT_TENANT optional tenant slug for token and API paths on a shared host.
|
|
15
16
|
* TOT_CLIENT_ID, TOT_CLIENT_SECRET installation credentials (client_secret_basic).
|
|
16
17
|
* WEBHOOK_ENDPOINT your registered `webhooks.endpoint`, character for
|
|
17
18
|
* character. It is the signed @target-uri.
|
|
@@ -66,14 +67,15 @@ export function createConnector(env = process.env, overrides = {}) {
|
|
|
66
67
|
let auth = null;
|
|
67
68
|
let api = null;
|
|
68
69
|
if (origin && env.TOT_CLIENT_ID && env.TOT_CLIENT_SECRET) {
|
|
70
|
+
const routing = { origin, ...(env.TOT_TENANT ? { tenant: env.TOT_TENANT } : {}) };
|
|
69
71
|
auth = new ConnectorAuthClient({
|
|
70
|
-
|
|
72
|
+
...routing,
|
|
71
73
|
clientId: env.TOT_CLIENT_ID,
|
|
72
74
|
clientSecret: env.TOT_CLIENT_SECRET,
|
|
73
75
|
...(fetchImpl ? { fetch: fetchImpl } : {}),
|
|
74
76
|
...clock,
|
|
75
77
|
});
|
|
76
|
-
api = new ApiClient({
|
|
78
|
+
api = new ApiClient({ ...routing, auth, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock });
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
const onEvent = overrides.onEvent ?? ((event, info) => handleEvent(event, info, { api }));
|
|
@@ -7,6 +7,7 @@ import assert from "node:assert/strict";
|
|
|
7
7
|
import { readFileSync } from "node:fs";
|
|
8
8
|
import { generateDevRs256KeyPair, signWebhookRequest } from "../lib/private-apps-devkit.mjs";
|
|
9
9
|
import { createConnector } from "../connector.js";
|
|
10
|
+
import { ApiError } from "../vendor/connector-kit/index.js";
|
|
10
11
|
|
|
11
12
|
const ENDPOINT = "https://connector.example.com/webhooks/tot";
|
|
12
13
|
const KID = "test-key-1";
|
|
@@ -28,7 +29,7 @@ async function setup(extraEnv = {}, overrides = {}) {
|
|
|
28
29
|
const { headers } = await signWebhookRequest({ method: "POST", url: ENDPOINT, body, key: privateKey, kid: KID });
|
|
29
30
|
return connector.handleRequest(new Request(ENDPOINT, { method: "POST", headers, body: tamper(body) }));
|
|
30
31
|
};
|
|
31
|
-
return { connector, events, deliver };
|
|
32
|
+
return { connector, events, deliver, publicKeyJwk };
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
test("a signed delivery is verified and reaches the handler once", async () => {
|
|
@@ -91,3 +92,70 @@ test("without credentials there is no API client", async () => {
|
|
|
91
92
|
const { connector } = await setup();
|
|
92
93
|
assert.equal(connector.api, null);
|
|
93
94
|
});
|
|
95
|
+
|
|
96
|
+
for (const { label, origin, tenant } of [
|
|
97
|
+
{ label: "single-tenant host", origin: "https://acme.example.com", tenant: "" },
|
|
98
|
+
{ label: "shared host", origin: "https://storefront.tokenoftrust.store", tenant: "acme" },
|
|
99
|
+
]) {
|
|
100
|
+
test(`${label} routes API calls and discovers signing keys at the bare origin`, async () => {
|
|
101
|
+
const root = tenant ? `${origin}/${tenant}` : origin;
|
|
102
|
+
const metadataUrl = `${origin}/.well-known/tot-app-authorization-metadata`;
|
|
103
|
+
const tokenUrl = `${root}/api/apps/oauth/token`;
|
|
104
|
+
const assignmentsUrl = `${root}/api/apps/v1/fulfillment/assignments`;
|
|
105
|
+
const calls = [];
|
|
106
|
+
let signingKey;
|
|
107
|
+
const fetch = async (url) => {
|
|
108
|
+
const address = String(url);
|
|
109
|
+
calls.push(address);
|
|
110
|
+
if (address === metadataUrl) return Response.json({ webhook_signing_keys: { keys: [signingKey] } });
|
|
111
|
+
if (address === tokenUrl) return Response.json({ access_token: "tok-1", token_type: "Bearer", expires_in: 3600 });
|
|
112
|
+
assert.equal(address, assignmentsUrl);
|
|
113
|
+
return Response.json({ items: [] });
|
|
114
|
+
};
|
|
115
|
+
const { connector, deliver, publicKeyJwk } = await setup({
|
|
116
|
+
TOT_STOREFRONT_ORIGIN: origin,
|
|
117
|
+
TOT_TENANT: tenant,
|
|
118
|
+
TOT_CLIENT_ID: "client-1",
|
|
119
|
+
TOT_CLIENT_SECRET: "secret-1",
|
|
120
|
+
}, { fetch, keys: undefined });
|
|
121
|
+
signingKey = { ...publicKeyJwk, kid: KID, alg: "RS256", use: "sig" };
|
|
122
|
+
|
|
123
|
+
assert.equal((await deliver(fixture())).status, 202);
|
|
124
|
+
const assignments = await connector.api.get("/fulfillment/assignments");
|
|
125
|
+
assert.deepEqual(assignments.body, { items: [] });
|
|
126
|
+
assert.deepEqual(calls, [metadataUrl, tokenUrl, assignmentsUrl]);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
test("API failures keep structured field, index and processor reasons", async () => {
|
|
131
|
+
const fetch = async (url) => {
|
|
132
|
+
const { pathname } = new URL(url);
|
|
133
|
+
switch (pathname) {
|
|
134
|
+
case "/api/apps/oauth/token":
|
|
135
|
+
return Response.json({ access_token: "tok-1", token_type: "Bearer", expires_in: 3600 });
|
|
136
|
+
case "/api/apps/v1/inventory/movements":
|
|
137
|
+
return Response.json({ code: "malformed", field: "sku", index: 0 }, { status: 400 });
|
|
138
|
+
case "/api/apps/v1/admin/test-orders":
|
|
139
|
+
return Response.json({ code: "install_not_processor", reasons: ["processor-scope-missing"] }, { status: 409 });
|
|
140
|
+
default:
|
|
141
|
+
assert.fail(`Unexpected request path ${pathname}`);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
const { connector } = await setup({
|
|
145
|
+
TOT_STOREFRONT_ORIGIN: "https://acme.example.com",
|
|
146
|
+
TOT_CLIENT_ID: "client-1",
|
|
147
|
+
TOT_CLIENT_SECRET: "secret-1",
|
|
148
|
+
}, { fetch });
|
|
149
|
+
|
|
150
|
+
await assert.rejects(connector.api.post("/inventory/movements", { items: [] }), (error) => {
|
|
151
|
+
assert.ok(error instanceof ApiError);
|
|
152
|
+
assert.equal(error.field, "sku");
|
|
153
|
+
assert.equal(error.index, 0);
|
|
154
|
+
return true;
|
|
155
|
+
});
|
|
156
|
+
await assert.rejects(connector.api.post("/admin/test-orders", {}), (error) => {
|
|
157
|
+
assert.ok(error instanceof ApiError);
|
|
158
|
+
assert.deepEqual(error.reasons, ["processor-scope-missing"]);
|
|
159
|
+
return true;
|
|
160
|
+
});
|
|
161
|
+
});
|