@tokenoftrust/cli 7.4.3 → 7.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.4.3",
3
+ "version": "7.4.5",
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",
@@ -24,6 +24,7 @@ import { validateManifest } from "../../vendor/private-apps-devkit.mjs";
24
24
 
25
25
  export const DEFAULT_APP_ENV = "test";
26
26
  const OPTION_VERBS = new Set(["install", "update", "rotate", "list", "replay", "test-order", "candidate", "suspend", "resume", "uninstall", "validate"]);
27
+ const TEST_ORDER_TRANSITIONS = new Map([["release", "released"], ["hold", "held"], ["cancel", "canceled"]]);
27
28
 
28
29
  export const ADMIN_USAGE = `tot app — manage Private App installs on your store
29
30
 
@@ -38,12 +39,17 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
38
39
  tot app rotate <installId> issue a new client secret (printed ONCE); the old one stops working
39
40
  tot app list your store's installs: id, app, version, env, status, scopes (never secrets)
40
41
  tot app replay <deliveryId> re-send a webhook delivery to its install
41
- tot app test-order bind <installId>
42
+ tot app test-order bind <installId> [--location <id>]
42
43
  bind your test install as the store's preview processor
43
44
  (it must be active, with a webhook endpoint and fulfillment:process)
44
- tot app test-order create write one synthetic preview order
45
+ tot app test-order create [--location <id>] [--line <sku>:<qty> ... | --quantity <n>] [--region <state>]
46
+ write one synthetic preview order (--quantity sets the amount of synthetic-sku)
45
47
  tot app test-order release <orderId>
46
48
  claim and release one synthetic preview order
49
+ tot app test-order hold <orderId>
50
+ put a synthetic preview order on hold
51
+ tot app test-order cancel <orderId>
52
+ cancel a synthetic preview order
47
53
  (test orders always act on the store's preview stage, at
48
54
  ${DEFAULT_STOREFRONT_ORIGIN}/<tenant>; no --url needed)
49
55
  tot app candidate status this store's candidates: id, app, version, status
@@ -66,12 +72,17 @@ Options (all online commands):
66
72
  /** Parse the online `tot app` argv. Pure — unit-tested. @param {string[]} argv */
67
73
  export function parseAdminArgs(argv) {
68
74
  /** @type {{ verb: string|null, positional: string[], app: string|null, env: string|null, tenant: string|null,
69
- * url: string|null, webhookEndpoint: string|null|undefined, jwksUri: string|null, jwks: string|null, requestConsent: boolean, json: boolean, help: boolean, unknown: string[] }} */
75
+ * url: string|null, webhookEndpoint: string|null|undefined, jwksUri: string|null, jwks: string|null,
76
+ * location: string|null, lines: string[], quantity: string|null, region: string|null,
77
+ * requestConsent: boolean, json: boolean, help: boolean, unknown: string[] }} */
70
78
  const a = { verb: null, positional: [], app: null, env: null, tenant: null, url: null,
71
- webhookEndpoint: undefined, jwksUri: null, jwks: null, requestConsent: false, json: false, help: false, unknown: [] };
79
+ webhookEndpoint: undefined, jwksUri: null, jwks: null, location: null, lines: [], quantity: null, region: null,
80
+ requestConsent: false, json: false, help: false, unknown: [] };
72
81
  const valueOf = (i, t) => {
73
82
  const eq = t.indexOf("=");
74
- return eq >= 0 ? { value: t.slice(eq + 1), next: i } : { value: argv[i + 1], next: i + 1 };
83
+ if (eq >= 0) return { value: t.slice(eq + 1), next: i };
84
+ const value = argv[i + 1];
85
+ return value === undefined || value.startsWith("--") ? { value: "", next: i } : { value, next: i + 1 };
75
86
  };
76
87
  for (let i = 0; i < argv.length; i++) {
77
88
  const t = argv[i];
@@ -80,7 +91,8 @@ export function parseAdminArgs(argv) {
80
91
  else if (t === "--request-consent") a.requestConsent = true;
81
92
  else if (t === "--help" || t === "-h") a.help = true;
82
93
  else if (flag === "--app" || flag === "--env" || flag === "--tenant" || flag === "--url" || flag === "--webhook-endpoint"
83
- || flag === "--jwks-uri" || flag === "--jwks") {
94
+ || flag === "--jwks-uri" || flag === "--jwks" || flag === "--location" || flag === "--line"
95
+ || flag === "--quantity" || flag === "--region") {
84
96
  const { value, next } = valueOf(i, t);
85
97
  i = next;
86
98
  const v = value === undefined || value.startsWith("--") ? "" : value;
@@ -90,6 +102,10 @@ export function parseAdminArgs(argv) {
90
102
  else if (flag === "--url") a.url = v;
91
103
  else if (flag === "--jwks-uri") a.jwksUri = v;
92
104
  else if (flag === "--jwks") a.jwks = v;
105
+ else if (flag === "--location") a.location = v;
106
+ else if (flag === "--line") a.lines.push(v);
107
+ else if (flag === "--quantity") a.quantity = v;
108
+ else if (flag === "--region") a.region = v;
93
109
  else a.webhookEndpoint = v === "none" ? null : v;
94
110
  } else if (t.startsWith("--")) a.unknown.push(t);
95
111
  else if (a.verb === null) a.verb = t;
@@ -112,18 +128,25 @@ function processorReasonsOf(body) {
112
128
  /** Verbs whose request addresses one install by id, so a bare 404 `not_found` means that install. */
113
129
  const INSTALL_VERBS = new Set(["update", "rotate", "suspend", "resume", "uninstall"]);
114
130
 
115
- /** Plain wording for the not-found, processor and entitlement refusals; null when none applies. */
116
- function plainRefusal(status, body, verb) {
131
+ function refusalCode(status, body, verb, action) {
117
132
  const code = typeof body?.code === "string" ? body.code : "";
118
- if (status === 404 && (code === "install_not_found" || (code === "not_found" && INSTALL_VERBS.has(verb)))) {
119
- return "install_not_found: this store has no install with that id";
133
+ const installAddressed = INSTALL_VERBS.has(verb) || (verb === "test-order" && action === "bind");
134
+ if (status === 404 && installAddressed && (code === "not_found" || (!code && body?.error === "not_found"))) {
135
+ return "install_not_found";
120
136
  }
137
+ if (status === 403 && !code) return "not_entitled";
138
+ return code;
139
+ }
140
+
141
+ /** Plain wording for the not-found, processor and entitlement refusals; null when none applies. */
142
+ function plainRefusal(status, body, code) {
143
+ if (status === 404 && code === "install_not_found") return "install_not_found: this store has no install with that id";
121
144
  if (status === 404 && code === "order_not_found") return "order_not_found: this store has no synthetic preview order with that id";
122
145
  if (code === "install_not_processor") {
123
146
  const says = processorReasonsOf(body).map((r) => PROCESSOR_REASONS[r]?.says ?? r);
124
147
  return `install_not_processor: that install cannot be the preview processor${says.length ? ` — ${says.join("; ")}` : ""}`;
125
148
  }
126
- if (code === "owner_required_for_production_app" || (status === 403 && missingGrantsOf(body).length)) {
149
+ if (code === "owner_required_for_production_app" || code === "not_entitled" || (status === 403 && missingGrantsOf(body).length)) {
127
150
  return "not_entitled: your sign-in is not allowed to do this on this store";
128
151
  }
129
152
  return null;
@@ -131,18 +154,18 @@ function plainRefusal(status, body, verb) {
131
154
 
132
155
  /**
133
156
  * The next step for a refused call: the server's `code` first, then the generic admission hint.
134
- * @param {number} status @param {any} body @param {{ tenant: string, urlOverridden: boolean }} target
157
+ * @param {number} status @param {any} body @param {string} code
158
+ * @param {{ tenant: string, urlOverridden: boolean, verb: string, action: string }} target
135
159
  */
136
- function nextForRefusal(status, body, target) {
137
- const code = typeof body?.code === "string" ? body.code : "";
160
+ function nextForRefusal(status, body, code, target) {
138
161
  if (code === "owner_required_for_production_app") {
139
162
  return "ask the store owner to install the production app, or install with --env=test";
140
163
  }
141
164
  if (status === 401) return "run `tot login`, then re-run";
142
165
  if (code === "scope_denied") return "remove the refused scopes from tot-app.json, then re-run";
143
166
  if (code === "already_installed") return "run `tot app list` for its installId, then `tot app update <installId>`";
144
- if (code === "not_found" || code === "install_not_found") return "run `tot app list` to see this store's installs";
145
- if (code === "order_not_found") return "create one with `tot app test-order create`, then release the orderId it prints";
167
+ if (code === "install_not_found") return "run `tot app list` to see this store's installs";
168
+ if (code === "order_not_found") return `run \`tot app test-order create\`, then use the orderId it prints with \`tot app test-order ${target.action} <orderId>\``;
146
169
  if (code === "install_not_processor") {
147
170
  const fixes = processorReasonsOf(body).map((r) => PROCESSOR_REASONS[r]?.fix).filter(Boolean);
148
171
  return `${fixes.length ? fixes.join("; then ") : "run `tot app list` to check the install"}; then re-run \`tot app test-order bind <installId>\``;
@@ -154,7 +177,7 @@ function nextForRefusal(status, body, target) {
154
177
  : `${preview} has not yet been redeployed with host-free test orders; re-run after its next deploy, or report it with \`tot feedback\``;
155
178
  }
156
179
  if (code === "test_install_required") return "bind an install with env test: `tot app list`, then `tot app test-order bind <installId>`";
157
- if (code === "invalid_state") return "run `tot app list` to check the install's status";
180
+ if (code === "invalid_state" && INSTALL_VERBS.has(target.verb)) return "run `tot app list` to check the install's status";
158
181
  if (status === 403) return refusalHint(status, missingGrantsOf(body));
159
182
  if (status === 429) return "wait a minute, then re-run";
160
183
  if (status >= 500) return "retry shortly; if it persists, report it with `tot feedback`";
@@ -177,6 +200,15 @@ export async function runAdmin(argv, ctx, deps = {}) {
177
200
  }
178
201
  if (args.unknown.length) return fail(`unknown option ${args.unknown[0]}`, "tot app --help");
179
202
  const verb = args.verb;
203
+ const testOrderOptions = [
204
+ [args.location !== null, "--location"],
205
+ [args.lines.length > 0, "--line"],
206
+ [args.quantity !== null, "--quantity"],
207
+ [args.region !== null, "--region"],
208
+ ].filter(([present]) => present).map(([, flag]) => flag);
209
+ if (verb !== "test-order" && testOrderOptions.length) {
210
+ return fail(`unknown option ${testOrderOptions[0]}`, "tot app --help");
211
+ }
180
212
 
181
213
  if (verb === "validate") return runValidateManifest(args, ctx, out, err);
182
214
 
@@ -223,17 +255,41 @@ export async function runAdmin(argv, ctx, deps = {}) {
223
255
  } else if (verb === "list") {
224
256
  request = { method: "GET", path: "/api/apps/admin/list" };
225
257
  } else if (verb === "test-order") {
226
- const action = args.positional[0];
227
- const id = args.positional[1];
228
- if (action !== "bind" && action !== "create" && action !== "release") {
229
- return fail("test-order needs an action: bind, create or release", "tot app test-order bind <installId> | create | release <orderId>");
258
+ const [action, id, extra] = args.positional;
259
+ if (action !== "bind" && action !== "create" && !TEST_ORDER_TRANSITIONS.has(action)) {
260
+ return fail("test-order needs an action: bind, create, release, hold or cancel", "tot app test-order --help");
230
261
  }
231
262
  if (action === "bind" && !id) return fail("no install to bind", "tot app test-order bind <installId> (find it with `tot app list`)");
232
- if (action === "release" && !id) return fail("no order to release", "tot app test-order release <orderId>");
233
- request = {
234
- method: "POST", path: "/api/apps/admin/test-orders",
235
- body: action === "bind" ? { action, installId: id } : action === "release" ? { action, orderId: id } : { action },
236
- };
263
+ if (TEST_ORDER_TRANSITIONS.has(action) && !id) return fail(`no order to ${action}`, `tot app test-order ${action} <orderId>`);
264
+ if (extra || (action === "create" && id)) return fail("unexpected test-order argument", "tot app test-order --help");
265
+ const misplaced = testOrderOptions.find((flag) => action !== "create" && (action !== "bind" || flag !== "--location"));
266
+ if (misplaced) return fail(`test-order ${action} does not accept ${misplaced}`, "tot app test-order --help");
267
+ if (args.location !== null && !args.location.trim()) return fail("--location needs a location id");
268
+ if (args.region !== null && !args.region.trim()) return fail("--region needs a state");
269
+ const location = args.location ? { locationId: args.location.trim() } : {};
270
+ let body;
271
+ if (action === "bind") {
272
+ body = { action, installId: id, ...location };
273
+ } else if (action === "create") {
274
+ if (args.quantity !== null && args.lines.length) return fail("use --quantity or --line, one at a time");
275
+ const lines = [];
276
+ for (const entry of args.lines) {
277
+ const match = /^(.+):(\d+)$/.exec(entry);
278
+ const sku = match?.[1].trim();
279
+ const quantity = Number(match?.[2]);
280
+ if (!sku || !Number.isSafeInteger(quantity) || quantity < 1) return fail("--line needs <sku>:<positive integer>");
281
+ lines.push({ sku, quantity });
282
+ }
283
+ if (args.quantity !== null) {
284
+ const quantity = Number(args.quantity);
285
+ if (!/^\d+$/.test(args.quantity) || !Number.isSafeInteger(quantity) || quantity < 1) return fail("--quantity needs a positive integer");
286
+ lines.push({ sku: "synthetic-sku", quantity });
287
+ }
288
+ body = { action, ...location, ...(lines.length ? { lines } : {}), ...(args.region ? { region: args.region.trim() } : {}) };
289
+ } else {
290
+ body = { action, orderId: id };
291
+ }
292
+ request = { method: "POST", path: "/api/apps/admin/test-orders", body };
237
293
  } else if (verb === "suspend" || verb === "resume" || verb === "uninstall") {
238
294
  const installId = args.positional[0];
239
295
  if (!installId) return fail(`no install to ${verb}`, `tot app ${verb} <installId> (find it with \`tot app list\`)`);
@@ -304,8 +360,10 @@ export async function runAdmin(argv, ctx, deps = {}) {
304
360
  ? `\n refused scopes: ${data.denials.map((d) => d?.scope ?? d?.id ?? JSON.stringify(d)).join(", ")}` : "";
305
361
  const storefrontUrl = String(args.url || env.TOT_STOREFRONT_URL || "").trim().replace(/\/+$/, "");
306
362
  const urlOverridden = storefrontUrl !== "" && storefrontUrl !== DEFAULT_STOREFRONT_ORIGIN;
307
- const plain = plainRefusal(res.status, data, verb);
308
- err(`✗ tot app ${verb}: ${plain ? `${plain} (${reason})` : reason}${denials}\n\n → next: ${nextForRefusal(res.status, data, { tenant, urlOverridden })}`);
363
+ const action = args.positional[0];
364
+ const code = refusalCode(res.status, data, verb, action);
365
+ 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 })}`);
309
367
  return res.status === 401 || res.status === 403 ? 1 : (res.status >= 500 ? 1 : 2);
310
368
  }
311
369
 
@@ -432,11 +490,13 @@ function renderTestOrder(data, args, out) {
432
490
  const action = args.positional[0];
433
491
  if (action === "bind") {
434
492
  const p = data?.processor;
435
- out(`✓ bound ${p?.installId ?? args.positional[1]} as the preview processor (notifiable: ${p?.notifiable}, consent granted: ${p?.consentGranted})`);
493
+ const locationId = p?.locationId ?? args.location?.trim();
494
+ out(`✓ bound ${p?.installId ?? args.positional[1]} as the preview processor${locationId ? ` for ${locationId}` : ""} (notifiable: ${p?.notifiable}, consent granted: ${p?.consentGranted})`);
436
495
  } else if (action === "create") {
437
496
  out(`✓ created synthetic order ${data?.order?.orderId ?? ""} (${data?.order?.stage ?? "preview"})`);
438
497
  } else {
439
- out(`✓ released ${data?.order?.orderId ?? args.positional[1]} (${data?.order?.fulfillment ?? ""}, assigned to ${data?.order?.assignedInstallId ?? "no install"})`);
498
+ const order = data?.order;
499
+ out(`✓ ${TEST_ORDER_TRANSITIONS.get(action)} ${order?.orderId ?? args.positional[1]} (${order?.fulfillment ?? ""}, assigned to ${order?.assignedInstallId ?? "no install"})`);
440
500
  }
441
501
  return 0;
442
502
  }
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "source": "tokenoftrust/storefront-devkit",
3
3
  "path": "packages/connector-kit/src",
4
- "commit": "1c64de79cdbf0860cbdcb76fa0cf78b442a79758",
5
- "kitVersion": "1.0.0",
4
+ "commit": "50ee510266b2af5daa7c86dd93af128fbbb4d7a7",
5
+ "kitVersion": "1.1.0",
6
6
  "files": {
7
- "api.js": "b183146afb89fb45a2a36316fc305dde9bea80e93b8c8d3181a784cd510c5001",
8
- "auth.js": "dfd1cf50703de0976e6c5387632cf8ff593516cf32d19277fd44b8f7c99d2129",
7
+ "api.js": "ff6c8a90a9d2f5c7421916ec1fca6f46ee078748011963e68be75afa1efe8b4b",
8
+ "auth.js": "3d350e8a377024837f89c7789f7a10bec961ba182ef5ad7bd7e78b6e50a2f267",
9
9
  "encoding.js": "6de8900e65174a9d53c6fb55bcfee2afe12a08f99a34280c002a176f1c1a388c",
10
- "errors.js": "de5a6bb0b4ef23d8820fc2afc2ab2174a45ce2ea74f91f3382950da4ab02b0d2",
10
+ "errors.js": "f27facae7a1646baf223babb5384d03d376f9c21ddad7b685ebfe6d8e91fdc6a",
11
11
  "http-signature.js": "a823f1e897e65839a65562951102baccb7e64395db4201b13cb1e6c21891b424",
12
- "index.js": "9a967f429b55a2c5f51b6c2a38e8882e1b2cbef6396b611903e0847680f03570",
13
- "metadata.js": "0c4af4c3e9d7fdd0110d70283b99c4991a83cdeb09c8dc3ead2cecec46aded67",
14
- "retry.js": "b28bffdf79d792a059b03387e9f1d7e4fdfdf0bdc02768024b420e40209496d4",
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, normalizeOrigin } from './metadata.js';
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
- this.origin = normalizeOrigin(origin);
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
- const url = new URL(`${API_PREFIX}${path}`, this.origin);
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 !== `${API_PREFIX}${path}`) throw refuse();
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, normalizeOrigin } from './metadata.js';
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
- this.origin = normalizeOrigin(origin);
106
- this.tokenEndpoint = `${this.origin}${TOKEN_PATH}`;
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 text (`message`, `error_description`, any body field that is not a
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.test(value) ? value : 'unexpected';
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.test(value) ? value : undefined;
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.0.0';
6
- export const CONTRACT_VERSION = 'private-apps@1.3';
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(String(origin));
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
- if (url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) {
31
- throw new TypeError('origin must be scheme://host[:port] with no path, query or credentials');
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 url.origin;
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 timer = setTimeout(resolve, ms);
50
- signal?.addEventListener(
51
- 'abort',
52
- () => {
53
- clearTimeout(timer);
54
- reject(signal.reason);
55
- },
56
- { once: true },
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
- origin,
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({ origin, auth, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock });
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
+ });