@tokenoftrust/cli 7.10.0 → 7.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "7.10.0",
3
+ "version": "7.11.1",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -176,7 +176,12 @@ function nextForRefusal(status, body, code, target) {
176
176
  }
177
177
  if (status === 401) return "run `tot login`, then re-run";
178
178
  if (code === "scope_denied") return "remove the refused scopes from tot-app.json, then re-run";
179
- if (code === "already_installed") return "run `tot app list` for its installId, then `tot app update <installId>`";
179
+ if (code === "already_installed") {
180
+ if (typeof body?.error === "string" && body.error.includes("by another developer")) {
181
+ return "on a shared store, give \"id\" in tot-app.json your own suffix (e.g. com.example.my-app-<name>) and re-run `tot app install` (do not update another developer's install)";
182
+ }
183
+ return "if it is your install, run `tot app list` for its installId, then `tot app update <installId>`; on a shared store, give \"id\" in tot-app.json your own suffix and re-run `tot app install`";
184
+ }
180
185
  if (code === "install_not_found") return "run `tot app list` to see this store's installs";
181
186
  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>\``;
182
187
  if (code === "install_not_processor") {
@@ -1,18 +1,20 @@
1
1
  {
2
2
  "source": "tokenoftrust/storefront-devkit",
3
3
  "path": "packages/connector-kit/src",
4
- "commit": "50ee510266b2af5daa7c86dd93af128fbbb4d7a7",
4
+ "commit": "13982b168b9f9b4c1bbb0d7403807bef1321423f",
5
5
  "kitVersion": "1.1.0",
6
6
  "files": {
7
- "api.js": "ff6c8a90a9d2f5c7421916ec1fca6f46ee078748011963e68be75afa1efe8b4b",
7
+ "api.js": "3a5f56f91e57164af839a60113b40d637a6015941c44062792d768075fff616c",
8
8
  "auth.js": "3d350e8a377024837f89c7789f7a10bec961ba182ef5ad7bd7e78b6e50a2f267",
9
9
  "encoding.js": "6de8900e65174a9d53c6fb55bcfee2afe12a08f99a34280c002a176f1c1a388c",
10
10
  "errors.js": "f27facae7a1646baf223babb5384d03d376f9c21ddad7b685ebfe6d8e91fdc6a",
11
- "http-signature.js": "a823f1e897e65839a65562951102baccb7e64395db4201b13cb1e6c21891b424",
12
- "index.js": "e60e2691cbe82cc1ec02028073eb8c0f37c7b1774c9e127e8a9434ad93f719ed",
13
- "metadata.js": "a0722dc06899adbe0237c71b45908186931f0131f95caa060ae04b1c4dfa625e",
11
+ "http-signature.js": "85d580fe46fafb6213dfd3f06aacf55c545599efaa203593f802748f9678dac3",
12
+ "index.d.ts": "c98756316b2d1b08b7af17f77b43d1bee455b8f828347acfeb6a7412952b54f8",
13
+ "index.js": "ce1527158546228de9a23b1ada303ca068137121aa8b3f9696f1ab3f2feaf5a7",
14
+ "metadata.js": "e3c61fd39334893e0b8a2c2bd3d33f7c958ddf3a7af4e280d6b00b3b193b13cc",
15
+ "rate-limit.js": "528b85d496bc533a051f50adbfb22f6a66286baaee7ee057e31653055b85b889",
14
16
  "retry.js": "b30f0776bf861894a297a589bf4df474e92aa0677c26140fc34ee692fcfbfc31",
15
17
  "structured-fields.js": "e253d027e19c61f5c48dbb09d927dc42d9cf43c926fe512c44cc06c77d08d5cc",
16
- "webhook.js": "c90534b1db38e289fdae2c6d7c090389d6e0077f0fc919f95cc2dc07d703e428"
18
+ "webhook.js": "bdfd2a10c126cafc68114064429ec4211e6f142c9f4a663d13e80c16b5df3489"
17
19
  }
18
20
  }
@@ -216,7 +216,9 @@ export class ApiClient {
216
216
  if (res.status >= 300 && res.status < 400) return new TransportError({ code: 'redirect_refused', status: res.status, requestId });
217
217
  const code = safeCode(body?.code ?? body?.error ?? (body === null ? `http_${res.status}` : undefined));
218
218
  const holds = Array.isArray(body?.holds) ? body.holds.map(safeCode) : undefined;
219
- const isInventoryBatchRefusal = path?.startsWith('/inventory/') && (res.status === 400 || res.status === 422);
219
+ const isInventoryBatchRefusal =
220
+ path?.startsWith('/inventory/') &&
221
+ (res.status === 400 || res.status === 422 || (res.status === 409 && code === 'balance-out-of-range'));
220
222
  return new ApiError({
221
223
  code,
222
224
  status: res.status,
@@ -1,17 +1,21 @@
1
1
  // Webhook authenticity primitives, as apps/private/webhooks-and-api.md
2
2
  // specifies: a Content-Digest carrying sha-256 (RFC 9530) and one RFC 9421
3
3
  // signature labelled `sig1` covering "@method" "@target-uri" "content-digest",
4
- // with created/keyid/alg parameters and alg `rsa-v1_5-sha256`. Most callers use
5
- // WebhookReceiver, which applies these in order; they are exported for callers
6
- // that need a single step.
4
+ // with created/keyid/alg parameters and alg `rsa-v1_5-sha256` or `ed25519`.
5
+ // Most callers use WebhookReceiver, which applies these in order; they are
6
+ // exported for callers that need a single step.
7
7
  import { base64Encode, constantTimeEqual, sha256, toBytes, utf8 } from './encoding.js';
8
8
  import { parseDictionary, StructuredFieldError } from './structured-fields.js';
9
9
 
10
10
  export const SIGNATURE_LABEL = 'sig1';
11
11
  export const SIGNATURE_ALG = 'rsa-v1_5-sha256';
12
+ export const ED25519_SIGNATURE_ALG = 'ed25519';
13
+ export const SIGNATURE_ALGORITHMS = Object.freeze([SIGNATURE_ALG, ED25519_SIGNATURE_ALG]);
12
14
  export const REQUIRED_COMPONENTS = Object.freeze(['@method', '@target-uri', 'content-digest']);
13
- /** Web Crypto parameters for a webhook signing key (JWK alg RS256). */
15
+ /** Web Crypto parameters for an RSA webhook signing key (JWK alg RS256). */
14
16
  export const RSA_VERIFY_ALGORITHM = Object.freeze({ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' });
17
+ /** Web Crypto parameters for an Ed25519 webhook signing key (JWK crv Ed25519 / alg EdDSA). */
18
+ export const ED25519_VERIFY_ALGORITHM = Object.freeze({ name: 'Ed25519' });
15
19
 
16
20
  function fail(code, reason) {
17
21
  return { ok: false, code, reason };
@@ -101,7 +105,9 @@ export async function verifyMessageSignature({
101
105
  const expires = input.params.get('expires');
102
106
  if (!Number.isInteger(created)) return fail('signature_malformed', 'created is required');
103
107
  if (typeof keyid !== 'string' || keyid === '') return fail('signature_malformed', 'keyid is required');
104
- if (alg !== SIGNATURE_ALG) return fail('unsupported_alg', `alg must be ${SIGNATURE_ALG}`);
108
+ if (!SIGNATURE_ALGORITHMS.includes(alg)) {
109
+ return fail('unsupported_alg', `alg must be ${SIGNATURE_ALGORITHMS.join(' or ')}`);
110
+ }
105
111
  const nowSeconds = Math.floor(now / 1000);
106
112
  if (nowSeconds - created > maxAgeSeconds) return fail('signature_expired', 'created is too old');
107
113
  if (created - nowSeconds > maxClockSkewSeconds) return fail('signature_expired', 'created is in the future');
@@ -112,6 +118,11 @@ export async function verifyMessageSignature({
112
118
  const key = await resolveKey(keyid);
113
119
  if (!key) return fail('unknown_key', 'keyid is not a published webhook signing key');
114
120
 
121
+ const verifyAlgorithm = alg === ED25519_SIGNATURE_ALG ? ED25519_VERIFY_ALGORITHM : RSA_VERIFY_ALGORITHM;
122
+ if (key.algorithm?.name && key.algorithm.name !== verifyAlgorithm.name) {
123
+ return fail('signature_invalid', 'key algorithm does not match signature alg');
124
+ }
125
+
115
126
  const lines = [];
116
127
  for (const name of names) {
117
128
  const value = componentValue(name, { method, targetUri, headers });
@@ -121,7 +132,7 @@ export async function verifyMessageSignature({
121
132
  lines.push(`"@signature-params": ${input.raw}`);
122
133
  let verified = false;
123
134
  try {
124
- verified = await crypto.subtle.verify(RSA_VERIFY_ALGORITHM, key, signature.value.bytes, utf8(lines.join('\n')));
135
+ verified = await crypto.subtle.verify(verifyAlgorithm, key, signature.value.bytes, utf8(lines.join('\n')));
125
136
  } catch {
126
137
  verified = false;
127
138
  }
@@ -0,0 +1,511 @@
1
+ export const KIT_VERSION: string;
2
+ export const CONTRACT_VERSION: 'private-apps@1.4';
3
+
4
+ export interface RetryPolicy {
5
+ maxAttempts: number;
6
+ baseDelayMs: number;
7
+ maxDelayMs: number;
8
+ maxRetryAfterMs: number;
9
+ }
10
+
11
+ export const DEFAULT_RETRY_POLICY: Readonly<RetryPolicy>;
12
+ export const RETRYABLE_STATUS: Set<number>;
13
+ export function parseRetryAfter(value: string | null | undefined, nowMs?: number): number | undefined;
14
+
15
+ export const CLIENT_ASSERTION_TYPE: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
16
+ export const CLIENT_AUTH_METHODS: readonly ['client_secret_basic', 'client_secret_post', 'private_key_jwt'];
17
+ export const MAX_ASSERTION_LIFETIME_SECONDS: 300;
18
+
19
+ type ClientAuthMethod = typeof CLIENT_AUTH_METHODS[number];
20
+ type Jwk = JsonWebKey & { kid?: string };
21
+
22
+ interface StoreOptions {
23
+ origin: string;
24
+ /** Store slug on a shared host. Omit when the slug is already in origin. */
25
+ tenant?: string;
26
+ }
27
+
28
+ export type ConnectorAuthClientOptions = StoreOptions & {
29
+ clientId: string;
30
+ keyId?: string;
31
+ refreshSkewSeconds?: number;
32
+ assertionLifetimeSeconds?: number;
33
+ retry?: Partial<RetryPolicy>;
34
+ fetch?: typeof fetch;
35
+ now?: () => number;
36
+ sleep?: (ms: number) => Promise<void>;
37
+ random?: () => number;
38
+ randomId?: () => string;
39
+ } & (
40
+ | { method?: 'client_secret_basic' | 'client_secret_post'; clientSecret: string; privateKey?: never }
41
+ | { method?: 'private_key_jwt'; clientSecret?: never; privateKey: CryptoKey | Jwk }
42
+ );
43
+
44
+ export interface AccessToken {
45
+ accessToken: string;
46
+ issuedAt: number;
47
+ expiresAt: number;
48
+ scope: string[];
49
+ }
50
+
51
+ export class ConnectorAuthClient {
52
+ constructor(options: ConnectorAuthClientOptions);
53
+ origin: string;
54
+ tokenEndpoint: string;
55
+ clientId: string;
56
+ method: ClientAuthMethod;
57
+ getAccessToken(options?: { forceRefresh?: boolean }): Promise<string>;
58
+ getToken(options?: { forceRefresh?: boolean }): Promise<AccessToken>;
59
+ invalidate(accessToken?: string): void;
60
+ createClientAssertion(): Promise<string>;
61
+ }
62
+
63
+ export type ConnectorErrorKind = 'api' | 'auth' | 'transport';
64
+
65
+ export interface ConnectorErrorFields {
66
+ code: string;
67
+ status?: number;
68
+ requestId?: string;
69
+ retryable?: boolean;
70
+ retryAfterMs?: number;
71
+ holds?: string[];
72
+ field?: string;
73
+ index?: number;
74
+ reasons?: string[];
75
+ idempotencyKey?: string;
76
+ cause?: unknown;
77
+ }
78
+
79
+ export class ConnectorError extends Error implements ConnectorErrorFields {
80
+ constructor(fields: ConnectorErrorFields & { kind: ConnectorErrorKind });
81
+ kind: ConnectorErrorKind;
82
+ code: string;
83
+ status?: number;
84
+ requestId?: string;
85
+ retryable: boolean;
86
+ retryAfterMs?: number;
87
+ holds?: string[];
88
+ field?: string;
89
+ index?: number;
90
+ reasons?: string[];
91
+ idempotencyKey?: string;
92
+ cause?: unknown;
93
+ toJSON(): Omit<ConnectorErrorFields, 'cause'> & { kind: ConnectorErrorKind; retryable: boolean };
94
+ }
95
+
96
+ export class ApiError extends ConnectorError {
97
+ constructor(fields: ConnectorErrorFields);
98
+ kind: 'api';
99
+ }
100
+
101
+ export class AuthError extends ConnectorError {
102
+ constructor(fields: ConnectorErrorFields);
103
+ kind: 'auth';
104
+ }
105
+
106
+ export class TransportError extends ConnectorError {
107
+ constructor(fields: ConnectorErrorFields);
108
+ kind: 'transport';
109
+ }
110
+
111
+ export function safeCode(value: unknown): string;
112
+
113
+ export interface ApiClientOptions extends StoreOptions {
114
+ auth: { getAccessToken(): Promise<string>; invalidate?(token: string): void };
115
+ retry?: Partial<RetryPolicy>;
116
+ fetch?: typeof fetch;
117
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
118
+ random?: () => number;
119
+ now?: () => number;
120
+ onRetry?: (info: { attempt: number; delayMs: number; error: ConnectorError }) => void;
121
+ }
122
+
123
+ export interface ApiReadOptions {
124
+ query?: Record<string, unknown>;
125
+ traceparent?: string;
126
+ headers?: Record<string, string>;
127
+ signal?: AbortSignal;
128
+ }
129
+
130
+ export interface ApiWriteOptions extends ApiReadOptions {
131
+ idempotencyKey?: string;
132
+ }
133
+
134
+ export interface ApiRequest extends ApiWriteOptions {
135
+ method: string;
136
+ path: string;
137
+ body?: unknown;
138
+ }
139
+
140
+ export interface ApiResponse<Body = unknown> {
141
+ status: number;
142
+ body: Body;
143
+ headers: Headers;
144
+ requestId?: string;
145
+ idempotencyKey?: string;
146
+ }
147
+
148
+ export interface PaginationOptions {
149
+ query?: Record<string, unknown>;
150
+ limit?: number;
151
+ updatedSince?: string | Date;
152
+ cursor?: string;
153
+ itemsKey?: string;
154
+ maxPages?: number;
155
+ signal?: AbortSignal;
156
+ }
157
+
158
+ export interface ApiPage<Item = unknown, Body = unknown> {
159
+ items: Item[];
160
+ nextCursor?: string;
161
+ truncated: boolean;
162
+ body: Body;
163
+ requestId?: string;
164
+ }
165
+
166
+ export class ApiClient {
167
+ constructor(options: ApiClientOptions);
168
+ origin: string;
169
+ url(path: string, query?: Record<string, unknown>): string;
170
+ request<Body = unknown>(request: ApiRequest): Promise<ApiResponse<Body>>;
171
+ get<Body = unknown>(path: string, options?: ApiReadOptions): Promise<ApiResponse<Body>>;
172
+ delete<Body = unknown>(path: string, options?: ApiWriteOptions): Promise<ApiResponse<Body>>;
173
+ post<Body = unknown>(path: string, body: unknown, options?: ApiWriteOptions): Promise<ApiResponse<Body>>;
174
+ put<Body = unknown>(path: string, body: unknown, options?: ApiWriteOptions): Promise<ApiResponse<Body>>;
175
+ patch<Body = unknown>(path: string, body: unknown, options?: ApiWriteOptions): Promise<ApiResponse<Body>>;
176
+ pages<Item = unknown, Body = unknown>(path: string, options?: PaginationOptions): AsyncGenerator<ApiPage<Item, Body>, void, unknown>;
177
+ items<Item = unknown>(path: string, options?: PaginationOptions): AsyncGenerator<Item, void, unknown>;
178
+ collect<Item = unknown>(path: string, options?: PaginationOptions): Promise<{ items: Item[]; truncated: boolean; pages: number }>;
179
+ }
180
+
181
+ export function newIdempotencyKey(prefix?: string): string;
182
+ export function deriveIdempotencyKey(prefix: string, ...parts: unknown[]): Promise<string>;
183
+
184
+ export const METADATA_PATH: '/.well-known/tot-app-authorization-metadata';
185
+ export const TOKEN_PATH: '/api/apps/oauth/token';
186
+ export const API_PREFIX: '/api/apps/v1';
187
+
188
+ export interface SigningKeys {
189
+ resolveSigningKey(keyid: string): Promise<CryptoKey | null>;
190
+ }
191
+
192
+ export interface AuthorizationMetadataOptions {
193
+ /** Bare storefront origin, including for stores on a shared host. */
194
+ origin: string;
195
+ fetch?: typeof fetch;
196
+ now?: () => number;
197
+ minRefreshIntervalMs?: number;
198
+ }
199
+
200
+ export interface AuthorizationMetadataDocument {
201
+ /** The unvalidated endpoint from the metadata document. */
202
+ tokenEndpoint: unknown;
203
+ authMethods: unknown[];
204
+ keys: Map<string, CryptoKey>;
205
+ expiresAt: number;
206
+ }
207
+
208
+ export class AuthorizationMetadata implements SigningKeys {
209
+ constructor(options: AuthorizationMetadataOptions);
210
+ origin: string;
211
+ url: string;
212
+ load(force?: boolean): Promise<AuthorizationMetadataDocument>;
213
+ tokenEndpoint(): Promise<string>;
214
+ resolveSigningKey(keyid: string): Promise<CryptoKey | null>;
215
+ }
216
+
217
+ export class StaticSigningKeys implements SigningKeys {
218
+ constructor(jwks: { keys: readonly Jwk[] });
219
+ resolveSigningKey(keyid: string): Promise<CryptoKey | null>;
220
+ }
221
+
222
+ export function importWebhookSigningKey(jwk: unknown): Promise<{ kid: string; key: CryptoKey } | null>;
223
+ export function normalizeOrigin(origin: string): string;
224
+
225
+ export const EVENT_TYPE_PREFIX: 'com.tokenoftrust.storefront.';
226
+ export const DEFAULT_MAX_BODY_BYTES: number;
227
+ export const WEBHOOK_REFUSALS: Readonly<{
228
+ method_not_allowed: 405;
229
+ body_too_large: 413;
230
+ digest_missing: 400;
231
+ digest_malformed: 400;
232
+ digest_unsupported: 400;
233
+ digest_mismatch: 400;
234
+ signature_missing: 401;
235
+ signature_malformed: 401;
236
+ signature_coverage: 401;
237
+ unsupported_alg: 401;
238
+ signature_expired: 401;
239
+ unknown_key: 401;
240
+ signature_invalid: 401;
241
+ body_not_json: 400;
242
+ envelope_invalid: 400;
243
+ tenant_mismatch: 403;
244
+ replayed_event: 200;
245
+ }>;
246
+
247
+ type WebhookRefusalCode = keyof typeof WEBHOOK_REFUSALS;
248
+ type WebhookRefusal = {
249
+ [Code in WebhookRefusalCode]: { ok: false; status: typeof WEBHOOK_REFUSALS[Code]; code: Code };
250
+ }[WebhookRefusalCode];
251
+ type RawBody = ArrayBuffer | ArrayBufferView | string;
252
+ type HeaderValue = string | readonly string[] | null | undefined;
253
+ type WebhookHeaders = Headers | Record<string, HeaderValue> | readonly (readonly [string, HeaderValue])[];
254
+
255
+ export interface WebhookEvent<Data extends object = Record<string, unknown>> {
256
+ specversion: '1.0';
257
+ id: string;
258
+ source: string;
259
+ type: `${typeof EVENT_TYPE_PREFIX}${string}`;
260
+ time: string;
261
+ datacontenttype: 'application/json';
262
+ tenantid: string;
263
+ appinstallid: string;
264
+ dataschemaversion: '1';
265
+ retrycount?: number;
266
+ totrequestid?: string;
267
+ traceparent?: string;
268
+ data: Data;
269
+ }
270
+
271
+ export interface SeenEventStore {
272
+ claim(key: string, ttlSeconds: number): Promise<boolean>;
273
+ release(key: string): Promise<void>;
274
+ }
275
+
276
+ export class MemorySeenEventStore implements SeenEventStore {
277
+ constructor(options?: { maxEntries?: number; now?: () => number });
278
+ claim(key: string, ttlSeconds: number): Promise<boolean>;
279
+ release(key: string): Promise<void>;
280
+ }
281
+
282
+ export interface WebhookReceiverOptions {
283
+ endpoint: string;
284
+ keys: SigningKeys;
285
+ tenant?: string;
286
+ appInstallId?: string;
287
+ seenEvents?: SeenEventStore;
288
+ maxAgeSeconds?: number;
289
+ maxClockSkewSeconds?: number;
290
+ replayTtlSeconds?: number;
291
+ maxBodyBytes?: number;
292
+ now?: () => number;
293
+ }
294
+
295
+ export interface WebhookDelivery {
296
+ method: string;
297
+ headers: WebhookHeaders;
298
+ body: RawBody;
299
+ }
300
+
301
+ export interface WebhookContext {
302
+ keyid: string;
303
+ created: number;
304
+ }
305
+
306
+ type WebhookHandler = (event: WebhookEvent, context: WebhookContext) => unknown;
307
+
308
+ export type WebhookVerification = (WebhookContext & { ok: true; event: WebhookEvent; replayKey: string }) | WebhookRefusal;
309
+ export type WebhookReceiveResult =
310
+ | { status: 202; body: { accepted: true; duplicate?: never }; error?: never }
311
+ | { status: 200; body: { accepted: true; duplicate: true }; error?: never }
312
+ | { status: 400 | 401 | 403 | 405 | 413; body: { accepted: false; code: Exclude<WebhookRefusalCode, 'replayed_event'> }; error?: never }
313
+ | { status: 500; body: { accepted: false; code: 'handler_failed' }; error: unknown };
314
+
315
+ export class WebhookReceiver {
316
+ constructor(options: WebhookReceiverOptions);
317
+ endpoint: string;
318
+ tenant?: string;
319
+ appInstallId?: string;
320
+ verify(delivery: WebhookDelivery): Promise<WebhookVerification>;
321
+ release(replayKey: string): Promise<void>;
322
+ receive(delivery: WebhookDelivery, onEvent: WebhookHandler): Promise<WebhookReceiveResult>;
323
+ handleRequest(request: Request, onEvent: WebhookHandler): Promise<Response>;
324
+ }
325
+
326
+ export function normalizeHeaders(headers?: WebhookHeaders | null): Record<string, string>;
327
+
328
+ export const SIGNATURE_LABEL: 'sig1';
329
+ export const SIGNATURE_ALG: 'rsa-v1_5-sha256';
330
+ export const ED25519_SIGNATURE_ALG: 'ed25519';
331
+ export const SIGNATURE_ALGORITHMS: readonly ['rsa-v1_5-sha256', 'ed25519'];
332
+ export const REQUIRED_COMPONENTS: readonly ['@method', '@target-uri', 'content-digest'];
333
+
334
+ type VerificationFailure<Code> = { ok: false; code: Code; reason: string };
335
+ type SignatureRefusalCode = Extract<WebhookRefusalCode, `signature_${string}` | 'unsupported_alg' | 'unknown_key'>;
336
+ type WebhookSignatureAlgorithm = typeof SIGNATURE_ALGORITHMS[number];
337
+
338
+ export function contentDigestFor(body: RawBody): Promise<string>;
339
+ export function verifyContentDigest(
340
+ headerValue: string | null | undefined,
341
+ body: RawBody,
342
+ ): Promise<{ ok: true } | VerificationFailure<Extract<WebhookRefusalCode, `digest_${string}`>>>;
343
+ export function verifyMessageSignature(input: {
344
+ method: string;
345
+ targetUri: string;
346
+ headers: Record<string, string>;
347
+ resolveKey: (keyid: string) => Promise<CryptoKey | null>;
348
+ now?: number;
349
+ maxAgeSeconds?: number;
350
+ maxClockSkewSeconds?: number;
351
+ }): Promise<
352
+ | (WebhookContext & { ok: true; label: typeof SIGNATURE_LABEL; alg: WebhookSignatureAlgorithm })
353
+ | VerificationFailure<SignatureRefusalCode>
354
+ >;
355
+
356
+ export interface RateLimiterOptions {
357
+ requestsPerMinute: number;
358
+ burst?: number;
359
+ now?: () => number;
360
+ sleep?: (ms: number) => Promise<void>;
361
+ }
362
+
363
+ export interface RateLimiterWrapOptions {
364
+ /** Return a delay in seconds, or undefined to use the standard headers. */
365
+ parseResetSeconds?: (response: Response) => number | undefined;
366
+ }
367
+
368
+ export interface RateLimiter {
369
+ acquire(): Promise<void>;
370
+ /** Pace the fetch and return its response without retrying. */
371
+ wrap<Args extends unknown[], Result extends Response>(
372
+ fetchFn: (...args: Args) => Promise<Result> | Result,
373
+ options?: RateLimiterWrapOptions,
374
+ ): (...args: Args) => Promise<Result>;
375
+ }
376
+
377
+ export function createRateLimiter(options: RateLimiterOptions): RateLimiter;
378
+
379
+ // Payload shapes from apps/private/contract/openapi.yaml and asyncapi.yaml.
380
+
381
+ export type CarrierCode =
382
+ | 'UPS' | 'FEDEX' | 'USPS' | 'DHL' | 'ONTRAC' | 'LSO'
383
+ | 'BETTER_TRUCKS' | 'GLS_US' | 'SPEE_DEE' | 'STAT_OVERNIGHT';
384
+ type FulfillmentStage = 'preview' | 'publication';
385
+ type AdultSignature = 'accepted' | 'refused' | 'absent';
386
+
387
+ export interface AssignmentLine {
388
+ sku: string;
389
+ quantity: number;
390
+ }
391
+
392
+ export interface AssignmentReadLine extends AssignmentLine {
393
+ lineId: string;
394
+ locationId: string;
395
+ shipped: number;
396
+ cancelled: number;
397
+ remaining: number;
398
+ }
399
+
400
+ /** One reconciliation row from GET /fulfillment/assignments. */
401
+ export interface Assignment {
402
+ assignmentId: string;
403
+ orderId: string;
404
+ stage: FulfillmentStage;
405
+ eventVersion: number;
406
+ assignedAt: string;
407
+ purchaseId: string;
408
+ lineItems: AssignmentLine[];
409
+ locationId: string;
410
+ allowedCarriers: CarrierCode[];
411
+ adultSignatureRequired: boolean;
412
+ lines: AssignmentReadLine[];
413
+ }
414
+
415
+ export interface FulfillmentAssignmentList {
416
+ assignments: Assignment[];
417
+ nextCursor?: string;
418
+ }
419
+
420
+ /** The data payload for fulfillment.assignment.created and fulfillment.assignment.updated. */
421
+ export interface FulfillmentAssignmentData {
422
+ assignmentId: string;
423
+ orderId: string;
424
+ stage: FulfillmentStage;
425
+ state: 'active' | 'held' | 'cancelled';
426
+ eventVersion: number;
427
+ occurredAt: string;
428
+ }
429
+
430
+ interface EvidenceBase {
431
+ assignmentId: string;
432
+ purchaseId: string;
433
+ expectedVersion?: number;
434
+ }
435
+
436
+ interface PurchasedLabel {
437
+ carrier: CarrierCode;
438
+ service: string;
439
+ trackingNumber: string;
440
+ trackingUrl: string;
441
+ adultSignature: AdultSignature;
442
+ }
443
+
444
+ export type ShipmentEvidence = EvidenceBase & (
445
+ | ({ kind: 'label-outcome'; outcome: 'purchased' } & PurchasedLabel)
446
+ | ({ kind: 'label-outcome'; outcome: 'unknown' | 'voided' } & Partial<PurchasedLabel>)
447
+ | { kind: 'label-voided' }
448
+ | { kind: 'handoff'; carrier: CarrierCode }
449
+ );
450
+
451
+ export interface AssignmentShipmentWrite {
452
+ lines: AssignmentLine[];
453
+ carrier: string;
454
+ service?: string;
455
+ trackingNumber: string;
456
+ trackingUrl?: string;
457
+ adultSignature?: AdultSignature;
458
+ }
459
+
460
+ export interface AssignmentExceptionWrite {
461
+ lines: AssignmentLine[];
462
+ code: 'vendor_rejected' | 'backordered' | 'out_of_stock' | 'damaged' | 'address_undeliverable' | 'carrier_refused' | 'other';
463
+ note?: string;
464
+ }
465
+
466
+ export interface InventoryLocationWrite {
467
+ name: string;
468
+ kind: 'warehouse' | '3pl' | 'dropship_vendor' | 'retail';
469
+ isFulfillable?: boolean;
470
+ status?: 'active' | 'archived';
471
+ }
472
+
473
+ export interface InventoryMovementBatchWrite {
474
+ items: {
475
+ sku: string;
476
+ locationId?: string;
477
+ quantityDelta: number;
478
+ reason: 'received' | 'picked' | 'restock' | 'cycle_count' | 'damaged' | 'transfer' | 'adjustment';
479
+ }[];
480
+ }
481
+
482
+ /** OpenAPI InventoryLevelsWrite, sent to PUT /inventory/levels. */
483
+ export interface InventoryLevelBatchWrite {
484
+ items: {
485
+ sku: string;
486
+ locationId?: string;
487
+ onHand: number;
488
+ observedAt: string;
489
+ }[];
490
+ }
491
+
492
+ /** The sales-velocity snapshot within the GET /reports response. */
493
+ export interface SalesVelocityReport {
494
+ id: string;
495
+ generatedAt: string;
496
+ title?: string;
497
+ format?: 'json' | 'csv';
498
+ downloadUrl?: string;
499
+ window?: { days: number; from: string; to: string };
500
+ skus?: {
501
+ sku: string;
502
+ soldUnits: number;
503
+ unsoldUnits: number;
504
+ velocityPerDay: number;
505
+ daysOfCover: number | null;
506
+ }[];
507
+ }
508
+
509
+ export interface ReportList {
510
+ reports: SalesVelocityReport[];
511
+ }
@@ -11,11 +11,14 @@ export { ApiClient, newIdempotencyKey, deriveIdempotencyKey } from './api.js';
11
11
  export { AuthorizationMetadata, StaticSigningKeys, importWebhookSigningKey, normalizeOrigin, METADATA_PATH, TOKEN_PATH, API_PREFIX } from './metadata.js';
12
12
  export { ConnectorError, ApiError, AuthError, TransportError, safeCode } from './errors.js';
13
13
  export { DEFAULT_RETRY_POLICY, RETRYABLE_STATUS, parseRetryAfter } from './retry.js';
14
+ export { createRateLimiter } from './rate-limit.js';
14
15
  export {
15
16
  contentDigestFor,
16
17
  verifyContentDigest,
17
18
  verifyMessageSignature,
18
19
  SIGNATURE_LABEL,
19
20
  SIGNATURE_ALG,
21
+ ED25519_SIGNATURE_ALG,
22
+ SIGNATURE_ALGORITHMS,
20
23
  REQUIRED_COMPONENTS,
21
24
  } from './http-signature.js';
@@ -1,9 +1,9 @@
1
1
  // Gateway discovery: `GET /.well-known/tot-app-authorization-metadata` on the
2
2
  // storefront origin publishes `token_endpoint` and `webhook_signing_keys`, a JWK
3
- // Set of the RSA public keys (alg RS256) that sign webhook deliveries. The
4
- // document is cached for its `Cache-Control` max-age. An unknown keyid forces
5
- // one refetch (keys rotate), rate-limited, before a delivery is rejected.
6
- import { RSA_VERIFY_ALGORITHM } from './http-signature.js';
3
+ // Set of the public keys (RSA RS256 or OKP Ed25519/EdDSA) that sign webhook
4
+ // deliveries. The document is cached for its `Cache-Control` max-age. An unknown
5
+ // keyid forces one refetch (keys rotate), rate-limited, before a delivery is rejected.
6
+ import { ED25519_VERIFY_ALGORITHM, RSA_VERIFY_ALGORITHM } from './http-signature.js';
7
7
  import { TransportError } from './errors.js';
8
8
 
9
9
  export const METADATA_PATH = '/.well-known/tot-app-authorization-metadata';
@@ -60,17 +60,34 @@ function maxAgeSeconds(cacheControl) {
60
60
  return m ? Number(m[1]) : DEFAULT_MAX_AGE_SECONDS;
61
61
  }
62
62
 
63
- /** Import one published webhook signing key; anything but a public RS256 signing key yields null. */
63
+ /** Import one published webhook signing key; anything but a public RS256 or Ed25519 signing key yields null. */
64
64
  export async function importWebhookSigningKey(jwk) {
65
- if (!jwk || jwk.kty !== 'RSA' || typeof jwk.kid !== 'string' || jwk.d !== undefined) return null;
66
- if (jwk.use !== undefined && jwk.use !== 'sig') return null;
67
- if (jwk.alg !== undefined && jwk.alg !== 'RS256') return null;
68
- try {
69
- const key = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS256', ext: true }, RSA_VERIFY_ALGORITHM, false, ['verify']);
70
- return { kid: jwk.kid, key };
71
- } catch {
65
+ if (!jwk || typeof jwk !== 'object' || typeof jwk.kid !== 'string' || jwk.kid === '') return null;
66
+ if (jwk.d !== undefined || jwk.p !== undefined || jwk.q !== undefined || jwk.dp !== undefined || jwk.dq !== undefined || jwk.qi !== undefined || jwk.oth !== undefined) {
72
67
  return null;
73
68
  }
69
+ if (jwk.use !== undefined && jwk.use !== 'sig') return null;
70
+ if (jwk.kty === 'RSA') {
71
+ if (jwk.alg !== undefined && jwk.alg !== 'RS256') return null;
72
+ if (typeof jwk.n !== 'string' || jwk.n === '' || typeof jwk.e !== 'string' || jwk.e === '') return null;
73
+ try {
74
+ const key = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS256', ext: true }, RSA_VERIFY_ALGORITHM, false, ['verify']);
75
+ return { kid: jwk.kid, key };
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+ if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {
81
+ if (jwk.alg !== undefined && jwk.alg !== 'EdDSA' && jwk.alg !== 'ed25519') return null;
82
+ if (typeof jwk.x !== 'string' || jwk.x === '') return null;
83
+ try {
84
+ const key = await crypto.subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x, ext: true }, ED25519_VERIFY_ALGORITHM, false, ['verify']);
85
+ return { kid: jwk.kid, key };
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ return null;
74
91
  }
75
92
 
76
93
  async function importKeySet(jwks) {
@@ -0,0 +1,69 @@
1
+ import { defaultSleep, parseRetryAfter } from './retry.js';
2
+
3
+ const MINUTE_MS = 60_000;
4
+ const MAX_TIMER_MS = 2_147_483_647;
5
+
6
+ function resetDelayMs(response, nowMs) {
7
+ const headers = response.headers;
8
+ if (response.status !== 429 && headers.get('x-rate-limit-remaining') !== '0') return 0;
9
+ const retryAfterMs = parseRetryAfter(headers.get('retry-after'), nowMs);
10
+ const reset = headers.get('x-rate-limit-reset');
11
+ const resetAtMs = reset !== null && /^\d+$/.test(reset) ? Number(reset) * 1000 : 0;
12
+ const resetMs = resetAtMs > 0 && Number.isFinite(resetAtMs) ? resetAtMs - nowMs : 0;
13
+ return Math.max(retryAfterMs ?? 0, resetMs);
14
+ }
15
+
16
+ /**
17
+ * Pace outbound requests through a shared token bucket. A wrapper records
18
+ * cooldowns for future requests and returns the original response.
19
+ */
20
+ export function createRateLimiter({ requestsPerMinute, burst = 1, now = Date.now, sleep = defaultSleep }) {
21
+ const intervalMs = MINUTE_MS / requestsPerMinute;
22
+ if (!Number.isFinite(requestsPerMinute) || requestsPerMinute <= 0 || !Number.isFinite(intervalMs)) {
23
+ throw new TypeError('requestsPerMinute must be a positive finite rate');
24
+ }
25
+ if (!Number.isSafeInteger(burst) || burst < 1) throw new TypeError('burst must be a positive safe integer');
26
+
27
+ let tokens = burst;
28
+ let refillAt = now();
29
+ let blockedUntil = -Infinity;
30
+ let queue = Promise.resolve();
31
+
32
+ async function takeToken() {
33
+ for (;;) {
34
+ const at = now();
35
+ const elapsed = Math.max(0, at - refillAt);
36
+ tokens = Math.min(burst, tokens + elapsed / intervalMs);
37
+ refillAt = Math.max(at, refillAt);
38
+
39
+ if (tokens >= 1 && at >= blockedUntil) {
40
+ tokens--;
41
+ return;
42
+ }
43
+ // Another response can extend the cooldown while this request sleeps.
44
+ const waitMs = Math.max((1 - tokens) * intervalMs, blockedUntil - at);
45
+ await sleep(Math.min(MAX_TIMER_MS, Math.ceil(waitMs)));
46
+ }
47
+ }
48
+
49
+ function acquire() {
50
+ const next = queue.then(takeToken);
51
+ queue = next.catch(() => {});
52
+ return next;
53
+ }
54
+
55
+ return {
56
+ acquire,
57
+ wrap(fetchFn, { parseResetSeconds } = {}) {
58
+ return async (...args) => {
59
+ await acquire();
60
+ const response = await fetchFn(...args);
61
+ const at = now();
62
+ const seconds = parseResetSeconds?.(response);
63
+ const delayMs = seconds === undefined ? resetDelayMs(response, at) : seconds * 1000;
64
+ if (Number.isFinite(delayMs) && delayMs > 0) blockedUntil = Math.max(blockedUntil, at + delayMs);
65
+ return response;
66
+ };
67
+ },
68
+ };
69
+ }
@@ -28,6 +28,7 @@ export const WEBHOOK_REFUSALS = Object.freeze({
28
28
  signature_invalid: 401,
29
29
  body_not_json: 400,
30
30
  envelope_invalid: 400,
31
+ tenant_mismatch: 403,
31
32
  // A replay is acknowledged with 200 so the sender stops, and never reaches the application.
32
33
  replayed_event: 200,
33
34
  });
@@ -77,7 +78,9 @@ function envelopeProblem(event) {
77
78
  if (!event || typeof event !== 'object' || Array.isArray(event)) return 'not an object';
78
79
  for (const key of ENVELOPE_REQUIRED) if (!(key in event)) return `missing ${key}`;
79
80
  if (event.specversion !== '1.0') return 'specversion';
80
- for (const key of ['id', 'source', 'type', 'tenantid', 'appinstallid']) {
81
+ if (event.dataschemaversion !== '1') return 'dataschemaversion';
82
+ if (event.datacontenttype !== 'application/json') return 'datacontenttype';
83
+ for (const key of ['id', 'source', 'type', 'time', 'tenantid', 'appinstallid']) {
81
84
  if (typeof event[key] !== 'string' || event[key] === '') return key;
82
85
  }
83
86
  if (!event.type.startsWith(EVENT_TYPE_PREFIX)) return 'type';
@@ -85,11 +88,23 @@ function envelopeProblem(event) {
85
88
  return null;
86
89
  }
87
90
 
91
+ const SOURCE_TENANT = /^\/tenants\/([^/]+)(?:\/|$)/;
92
+
93
+ function tenantProblem(event, expectedTenant, expectedAppInstallId) {
94
+ const sourceMatch = SOURCE_TENANT.exec(event.source);
95
+ if (sourceMatch && sourceMatch[1] !== event.tenantid) return 'source_tenant_mismatch';
96
+ if (expectedTenant !== undefined && event.tenantid !== expectedTenant) return 'tenant_mismatch';
97
+ if (expectedAppInstallId !== undefined && event.appinstallid !== expectedAppInstallId) return 'appinstall_mismatch';
98
+ return null;
99
+ }
100
+
88
101
  export class WebhookReceiver {
89
102
  /**
90
103
  * @param {object} options
91
104
  * @param {string} options.endpoint The webhook endpoint exactly as registered in tot-app.json (the signed `@target-uri`).
92
105
  * @param {{ resolveSigningKey(keyid: string): Promise<CryptoKey|null> }} options.keys AuthorizationMetadata or StaticSigningKeys.
106
+ * @param {string} [options.tenant] Optional expected `tenantid` for single-tenant receivers; mismatched events are refused with 403 `tenant_mismatch`.
107
+ * @param {string} [options.appInstallId] Optional expected `appinstallid`; mismatched events are refused with 403 `tenant_mismatch`.
93
108
  * @param {{ claim(key: string, ttlSeconds: number): Promise<boolean>, release(key: string): Promise<void> }} [options.seenEvents]
94
109
  * @param {number} [options.maxAgeSeconds] Oldest acceptable signature `created` (default 300).
95
110
  * @param {number} [options.maxClockSkewSeconds] Furthest-future acceptable `created` (default 60).
@@ -100,6 +115,8 @@ export class WebhookReceiver {
100
115
  constructor({
101
116
  endpoint,
102
117
  keys,
118
+ tenant,
119
+ appInstallId,
103
120
  seenEvents = new MemorySeenEventStore(),
104
121
  maxAgeSeconds = 300,
105
122
  maxClockSkewSeconds = 60,
@@ -112,11 +129,19 @@ export class WebhookReceiver {
112
129
  throw new TypeError('endpoint must be the absolute webhook URL registered in tot-app.json');
113
130
  }
114
131
  if (!keys || typeof keys.resolveSigningKey !== 'function') throw new TypeError('keys must provide resolveSigningKey(keyid)');
132
+ if (tenant !== undefined && (typeof tenant !== 'string' || tenant === '')) {
133
+ throw new TypeError('tenant must be a non-empty store slug');
134
+ }
135
+ if (appInstallId !== undefined && (typeof appInstallId !== 'string' || appInstallId === '')) {
136
+ throw new TypeError('appInstallId must be a non-empty installation id');
137
+ }
115
138
  if (!seenEvents || typeof seenEvents.claim !== 'function' || typeof seenEvents.release !== 'function') {
116
139
  throw new TypeError('seenEvents must provide claim(key, ttlSeconds) and release(key)');
117
140
  }
118
141
  this.endpoint = endpoint;
119
142
  this.keys = keys;
143
+ this.tenant = tenant;
144
+ this.appInstallId = appInstallId;
120
145
  this.seenEvents = seenEvents;
121
146
  this.maxAgeSeconds = maxAgeSeconds;
122
147
  this.maxClockSkewSeconds = maxClockSkewSeconds;
@@ -166,6 +191,7 @@ export class WebhookReceiver {
166
191
  return refuse('body_not_json');
167
192
  }
168
193
  if (envelopeProblem(event)) return refuse('envelope_invalid');
194
+ if (tenantProblem(event, this.tenant, this.appInstallId)) return refuse('tenant_mismatch');
169
195
 
170
196
  const replayKey = `${event.tenantid}/${event.id}`;
171
197
  if (!(await this.seenEvents.claim(replayKey, this.replayTtlSeconds))) return refuse('replayed_event');