@tokenoftrust/cli 7.4.4 → 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.4",
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",
@@ -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
+ });