@tokenoftrust/cli 6.14.5 → 6.14.6

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": "6.14.5",
3
+ "version": "6.14.6",
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",
@@ -5,10 +5,13 @@
5
5
  * network — a developer building a Storefront Private App gets a runnable
6
6
  * skeleton before they've registered anything with Token of Trust.
7
7
  *
8
- * The scaffolded tree also gets its own copy of `src/vendor/private-apps-devkit.mjs`
9
- * (as `lib/private-apps-devkit.mjs`) so the stub `server.js` can verify webhook
10
- * signatures with zero runtime dependencies — see that file's module doc for
11
- * why this is a vendored copy rather than a package.json dependency.
8
+ * The scaffolded tree gets two vendored copies, neither a package.json dependency:
9
+ * - `vendor/connector-kit/` — the Devkit's connector-kit source (auth, RFC 9421
10
+ * webhook verification, idempotent API client), pinned to a Devkit commit by
11
+ * `src/vendor/connector-kit/PIN.json`. It ships inside this package so
12
+ * scaffolding stays offline and a given CLI version always emits the same
13
+ * reviewed bytes; `scripts/vendor-connector-kit.mjs` refreshes it.
14
+ * - `lib/private-apps-devkit.mjs` — the dev-only signer the template's tests use.
12
15
  */
13
16
  import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
14
17
  import { fileURLToPath } from "node:url";
@@ -26,6 +29,11 @@ export function vendoredDevkitPath() {
26
29
  return resolve(here, "vendor", "private-apps-devkit.mjs");
27
30
  }
28
31
 
32
+ /** Absolute path to the vendored connector-kit source (with its PIN.json) copied into every scaffolded app. */
33
+ export function vendoredConnectorKitDir() {
34
+ return resolve(here, "vendor", "connector-kit");
35
+ }
36
+
29
37
  /** A directory carries a scaffolded app if it has a `tot-app.json` manifest. */
30
38
  export function isAppScaffold(dir) {
31
39
  return existsSync(join(dir, "tot-app.json"));
@@ -44,7 +52,7 @@ function isEmptyDir(dir) {
44
52
  /**
45
53
  * Materialize a Private App skeleton at `destDir`: copy the bundled template
46
54
  * (`tot-app.json`, `fixtures/`, `README.md`, `Dockerfile`, `.env.example`,
47
- * `server.js`) in, then drop this package's vendored devkit at `lib/`.
55
+ * `server.js`, `connector.js`, `test/`) in, then drop this package's vendored devkit at `lib/`.
48
56
  * Idempotent — re-running against an already-scaffolded directory is a no-op
49
57
  * that returns it. Refuses to clobber a non-scaffold, non-empty directory.
50
58
  *
@@ -78,6 +86,7 @@ export function scaffoldApp(destDir, { force = false, log = () => {} } = {}) {
78
86
  cpSync(template, dir, { recursive: true });
79
87
  mkdirSync(join(dir, "lib"), { recursive: true });
80
88
  cpSync(vendoredDevkitPath(), join(dir, "lib", "private-apps-devkit.mjs"));
89
+ cpSync(vendoredConnectorKitDir(), join(dir, "vendor", "connector-kit"), { recursive: true });
81
90
 
82
91
  log(` ✓ scaffolded a private app → ${dir}`);
83
92
  return { dir, created: true };
@@ -0,0 +1,18 @@
1
+ {
2
+ "source": "tokenoftrust/storefront-devkit",
3
+ "path": "packages/connector-kit/src",
4
+ "commit": "1c64de79cdbf0860cbdcb76fa0cf78b442a79758",
5
+ "kitVersion": "1.0.0",
6
+ "files": {
7
+ "api.js": "b183146afb89fb45a2a36316fc305dde9bea80e93b8c8d3181a784cd510c5001",
8
+ "auth.js": "dfd1cf50703de0976e6c5387632cf8ff593516cf32d19277fd44b8f7c99d2129",
9
+ "encoding.js": "6de8900e65174a9d53c6fb55bcfee2afe12a08f99a34280c002a176f1c1a388c",
10
+ "errors.js": "de5a6bb0b4ef23d8820fc2afc2ab2174a45ce2ea74f91f3382950da4ab02b0d2",
11
+ "http-signature.js": "a823f1e897e65839a65562951102baccb7e64395db4201b13cb1e6c21891b424",
12
+ "index.js": "9a967f429b55a2c5f51b6c2a38e8882e1b2cbef6396b611903e0847680f03570",
13
+ "metadata.js": "0c4af4c3e9d7fdd0110d70283b99c4991a83cdeb09c8dc3ead2cecec46aded67",
14
+ "retry.js": "b28bffdf79d792a059b03387e9f1d7e4fdfdf0bdc02768024b420e40209496d4",
15
+ "structured-fields.js": "e253d027e19c61f5c48dbb09d927dc42d9cf43c926fe512c44cc06c77d08d5cc",
16
+ "webhook.js": "c90534b1db38e289fdae2c6d7c090389d6e0077f0fc919f95cc2dc07d703e428"
17
+ }
18
+ }
@@ -0,0 +1,271 @@
1
+ // Pull API client for `/api/apps/v1`. Every mutating call carries an
2
+ // Idempotency-Key, generated once per call when the caller supplies none, and
3
+ // every retry re-sends the same bytes under the same key, so a lost response is
4
+ // safe to retry. 408/429/502/503/504 and network failures are retried with
5
+ // bounded backoff; `Retry-After` is honored exactly. One 401 refreshes the
6
+ // token and repeats the call. Cursor pagination (`cursor` / `nextCursor`, with
7
+ // `limit` and `updatedSince`) drains every page.
8
+ import { ApiError, AuthError, ConnectorError, TransportError, safeCode, safeRequestId } from './errors.js';
9
+ import { hex, sha256, utf8 } from './encoding.js';
10
+ import { API_PREFIX, normalizeOrigin } from './metadata.js';
11
+ import { RETRYABLE_STATUS, backoffDelay, defaultSleep, parseRetryAfter, retryPolicy } from './retry.js';
12
+
13
+ const MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
14
+ const METHODS = new Set(['GET', 'HEAD', ...MUTATING]);
15
+ const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
16
+ const TRACEPARENT = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
17
+ const SAFE_PATH = /^\/[A-Za-z0-9._~%!$&'()*+,;=:@/-]*$/;
18
+
19
+ /** A random Idempotency-Key for one logical write. */
20
+ export function newIdempotencyKey(prefix = 'ck') {
21
+ return `${prefix}-${crypto.randomUUID()}`;
22
+ }
23
+
24
+ /**
25
+ * A deterministic Idempotency-Key: the same prefix and parts always yield the
26
+ * same key, so a write re-derived after a restart replays instead of
27
+ * duplicating. Parts are JSON-serialized with sorted object keys.
28
+ */
29
+ export async function deriveIdempotencyKey(prefix, ...parts) {
30
+ const canonical = JSON.stringify(parts, (_k, v) =>
31
+ v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v,
32
+ );
33
+ return `${prefix}-${hex(await sha256(utf8(canonical))).slice(0, 48)}`;
34
+ }
35
+
36
+ function appendQuery(params, query) {
37
+ for (const [key, value] of Object.entries(query ?? {})) {
38
+ if (value === undefined || value === null) continue;
39
+ for (const v of Array.isArray(value) ? value : [value]) params.append(key, v instanceof Date ? v.toISOString() : String(v));
40
+ }
41
+ }
42
+
43
+ function itemsOf(body, itemsKey) {
44
+ if (itemsKey !== undefined) {
45
+ if (!Array.isArray(body?.[itemsKey])) throw new TypeError(`page has no "${itemsKey}" array`);
46
+ return body[itemsKey];
47
+ }
48
+ const arrays = Object.keys(body ?? {}).filter((k) => Array.isArray(body[k]));
49
+ if (arrays.length !== 1) throw new TypeError('cannot infer the items array of this page; pass itemsKey');
50
+ return body[arrays[0]];
51
+ }
52
+
53
+ export class ApiClient {
54
+ /**
55
+ * @param {object} options
56
+ * @param {string} options.origin The storefront origin, e.g. https://acme.tokenoftrust.store.
57
+ * @param {{ getAccessToken(): Promise<string>, invalidate?(token: string): void }} options.auth Usually a ConnectorAuthClient.
58
+ * @param {object} [options.retry] Retry policy overrides (see DEFAULT_RETRY_POLICY).
59
+ * @param {typeof fetch} [options.fetch]
60
+ * @param {(ms: number, signal?: AbortSignal) => Promise<void>} [options.sleep]
61
+ * @param {() => number} [options.random]
62
+ * @param {() => number} [options.now] Milliseconds since the epoch.
63
+ * @param {(info: { attempt: number, delayMs: number, error: ConnectorError }) => void} [options.onRetry] Observe retries (for logging).
64
+ */
65
+ constructor({
66
+ origin,
67
+ auth,
68
+ retry,
69
+ fetch: fetchImpl = (...args) => globalThis.fetch(...args),
70
+ sleep = defaultSleep,
71
+ random = Math.random,
72
+ now = () => Date.now(),
73
+ onRetry,
74
+ }) {
75
+ if (!auth || typeof auth.getAccessToken !== 'function') throw new TypeError('auth must provide getAccessToken()');
76
+ this.origin = normalizeOrigin(origin);
77
+ this.auth = auth;
78
+ this.retry = retryPolicy(retry);
79
+ this.fetch = fetchImpl;
80
+ this.sleep = sleep;
81
+ this.random = random;
82
+ this.now = now;
83
+ this.onRetry = onRetry;
84
+ }
85
+
86
+ get(path, options) {
87
+ return this.request({ ...options, method: 'GET', path });
88
+ }
89
+
90
+ delete(path, options) {
91
+ return this.request({ ...options, method: 'DELETE', path });
92
+ }
93
+
94
+ post(path, body, options) {
95
+ return this.request({ ...options, method: 'POST', path, body });
96
+ }
97
+
98
+ put(path, body, options) {
99
+ return this.request({ ...options, method: 'PUT', path, body });
100
+ }
101
+
102
+ patch(path, body, options) {
103
+ return this.request({ ...options, method: 'PATCH', path, body });
104
+ }
105
+
106
+ url(path, query) {
107
+ const refuse = () => new TypeError('path must be an absolute path under /api/apps/v1, e.g. /inventory; pass query separately');
108
+ if (typeof path !== 'string' || !SAFE_PATH.test(path)) throw refuse();
109
+ const url = new URL(`${API_PREFIX}${path}`, this.origin);
110
+ // 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();
112
+ appendQuery(url.searchParams, query);
113
+ return url.toString();
114
+ }
115
+
116
+ /**
117
+ * One API call with retries.
118
+ *
119
+ * @param {object} req
120
+ * @param {string} req.method
121
+ * @param {string} req.path Path under /api/apps/v1, e.g. `/inventory/movements`.
122
+ * @param {Record<string, unknown>} [req.query]
123
+ * @param {unknown} [req.body] JSON-serialized once.
124
+ * @param {string} [req.idempotencyKey] Mutating calls only; generated when omitted.
125
+ * @param {string} [req.traceparent] W3C Trace Context to propagate.
126
+ * @param {Record<string, string>} [req.headers] Extra headers.
127
+ * @param {AbortSignal} [req.signal]
128
+ * @returns {Promise<{ status: number, body: any, headers: Headers, requestId?: string, idempotencyKey?: string }>}
129
+ */
130
+ async request({ method, path, query, body, idempotencyKey, traceparent, headers = {}, signal }) {
131
+ const verb = String(method).toUpperCase();
132
+ if (!METHODS.has(verb)) throw new TypeError(`unsupported method ${method}`);
133
+ const url = this.url(path, query);
134
+ const sendHeaders = { accept: 'application/json' };
135
+ for (const [k, v] of Object.entries(headers)) sendHeaders[k.toLowerCase()] = String(v);
136
+ let key;
137
+ if (MUTATING.has(verb)) {
138
+ key = idempotencyKey ?? newIdempotencyKey();
139
+ if (!IDEMPOTENCY_KEY.test(key)) throw new TypeError('idempotencyKey must be 8..128 printable ASCII characters');
140
+ sendHeaders['idempotency-key'] = key;
141
+ } else if (idempotencyKey !== undefined) {
142
+ throw new TypeError(`${verb} takes no idempotencyKey`);
143
+ }
144
+ if (traceparent !== undefined) {
145
+ if (!TRACEPARENT.test(traceparent)) throw new TypeError('traceparent must be a W3C trace context value');
146
+ sendHeaders.traceparent = traceparent;
147
+ }
148
+ // Serialized once: every retry re-sends these exact bytes.
149
+ const payload = body === undefined ? undefined : JSON.stringify(body);
150
+ if (payload !== undefined) sendHeaders['content-type'] = 'application/json';
151
+
152
+ let refreshedAfter401 = false;
153
+ for (let attempt = 1; ; attempt++) {
154
+ let error;
155
+ let token;
156
+ try {
157
+ token = await this.auth.getAccessToken();
158
+ const res = await this.send(url, { method: verb, headers: { ...sendHeaders, authorization: `Bearer ${token}` }, body: payload, signal });
159
+ const result = await this.read(res);
160
+ if (res.ok) return { ...result, ...(key ? { idempotencyKey: key } : {}) };
161
+ error = this.refusal(res, result);
162
+ } catch (err) {
163
+ if (!(err instanceof ConnectorError)) throw err;
164
+ error = err;
165
+ }
166
+ // A failed write may still have committed: the caller resends under this key.
167
+ if (key) error.idempotencyKey = key;
168
+ // The auth client already retried its own token request.
169
+ if (error instanceof AuthError) throw error;
170
+ if (error instanceof ApiError && error.status === 401 && !refreshedAfter401) {
171
+ refreshedAfter401 = true;
172
+ this.auth.invalidate?.(token);
173
+ attempt--;
174
+ continue;
175
+ }
176
+ if (!error.retryable || attempt >= this.retry.maxAttempts) throw error;
177
+ if (error.retryAfterMs !== undefined && error.retryAfterMs > this.retry.maxRetryAfterMs) throw error;
178
+ const delayMs = error.retryAfterMs ?? backoffDelay(attempt, this.retry, this.random);
179
+ this.onRetry?.({ attempt, delayMs, error });
180
+ await this.sleep(delayMs, signal);
181
+ }
182
+ }
183
+
184
+ async send(url, init) {
185
+ try {
186
+ return await this.fetch(url, { ...init, redirect: 'manual' });
187
+ } catch (cause) {
188
+ if (init.signal?.aborted) throw new TransportError({ code: 'aborted', cause });
189
+ throw new TransportError({ code: 'network', retryable: true, cause });
190
+ }
191
+ }
192
+
193
+ async read(res) {
194
+ const requestId = safeRequestId(res.headers.get('tot-request-id'));
195
+ const text = await res.text();
196
+ let body = null;
197
+ if (text !== '') {
198
+ try {
199
+ body = JSON.parse(text);
200
+ } catch {
201
+ body = null;
202
+ }
203
+ }
204
+ return { status: res.status, body, headers: res.headers, requestId };
205
+ }
206
+
207
+ refusal(res, { body, requestId }) {
208
+ if (res.status >= 300 && res.status < 400) return new TransportError({ code: 'redirect_refused', status: res.status, requestId });
209
+ const code = safeCode(body?.code ?? body?.error ?? (body === null ? `http_${res.status}` : undefined));
210
+ const holds = Array.isArray(body?.holds) ? body.holds.map(safeCode) : undefined;
211
+ return new ApiError({
212
+ code,
213
+ status: res.status,
214
+ requestId: requestId ?? safeRequestId(body?.requestId),
215
+ retryable: RETRYABLE_STATUS.has(res.status),
216
+ retryAfterMs: parseRetryAfter(res.headers.get('retry-after'), this.now()),
217
+ holds,
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Every page of a cursor-paginated list.
223
+ *
224
+ * @param {string} path e.g. `/catalog/products`.
225
+ * @param {object} [options]
226
+ * @param {Record<string, unknown>} [options.query] Extra filters.
227
+ * @param {number} [options.limit] Page size (1..100).
228
+ * @param {string|Date} [options.updatedSince] Only records changed since then.
229
+ * @param {string} [options.cursor] Resume from a saved `nextCursor`.
230
+ * @param {string} [options.itemsKey] The page's items array; inferred when the page has exactly one array.
231
+ * @param {number} [options.maxPages] Stop after this many pages.
232
+ * @param {AbortSignal} [options.signal]
233
+ * @returns {AsyncGenerator<{ items: any[], nextCursor?: string, truncated: boolean, body: any, requestId?: string }>}
234
+ */
235
+ async *pages(path, { query, limit, updatedSince, cursor, itemsKey, maxPages = Infinity, signal } = {}) {
236
+ let next = cursor;
237
+ const seen = new Set(cursor === undefined ? [] : [cursor]);
238
+ for (let page = 0; page < maxPages; page++) {
239
+ const res = await this.get(path, { query: { ...query, limit, updatedSince, cursor: next }, signal });
240
+ const nextCursor = typeof res.body?.nextCursor === 'string' && res.body.nextCursor !== '' ? res.body.nextCursor : undefined;
241
+ yield { items: itemsOf(res.body, itemsKey), nextCursor, truncated: res.body?.truncated === true, body: res.body, requestId: res.requestId };
242
+ if (nextCursor === undefined) return;
243
+ // A repeated cursor (A→A or A→B→A) would page forever.
244
+ if (seen.has(nextCursor)) throw new TransportError({ code: 'pagination_stalled', requestId: res.requestId });
245
+ seen.add(nextCursor);
246
+ next = nextCursor;
247
+ }
248
+ }
249
+
250
+ /** Every item across every page. Same options as `pages`. */
251
+ async *items(path, options) {
252
+ for await (const page of this.pages(path, options)) yield* page.items;
253
+ }
254
+
255
+ /**
256
+ * Drain a list into memory. `truncated` is true when any page said the
257
+ * server did not return everything (e.g. orders changed since `updatedSince`
258
+ * beyond its cap): run a full backfill without `updatedSince`.
259
+ */
260
+ async collect(path, options) {
261
+ const items = [];
262
+ let truncated = false;
263
+ let pages = 0;
264
+ for await (const page of this.pages(path, options)) {
265
+ items.push(...page.items);
266
+ truncated ||= page.truncated;
267
+ pages++;
268
+ }
269
+ return { items, truncated, pages };
270
+ }
271
+ }
@@ -0,0 +1,233 @@
1
+ // Installation tokens: the RFC 6749 section 4.4 client-credentials grant at
2
+ // `POST /api/apps/oauth/token`, with exactly one client authentication method:
3
+ //
4
+ // client_secret_basic HTTP Basic, each half form-urlencoded (RFC 6749 2.3.1)
5
+ // client_secret_post client_id and client_secret in the form body
6
+ // private_key_jwt an RFC 7523 assertion signed RS256 or ES256
7
+ //
8
+ // The token is cached and refreshed early, before it expires, and concurrent
9
+ // callers share one refresh. Credentials, assertions and tokens never enter an
10
+ // error, and a refusal carries only the OAuth `error` code.
11
+ import { AuthError, TransportError, safeRequestId } from './errors.js';
12
+ import { base64Encode, base64UrlEncode, utf8 } from './encoding.js';
13
+ import { TOKEN_PATH, normalizeOrigin } from './metadata.js';
14
+ import { RETRYABLE_STATUS, backoffDelay, defaultSleep, parseRetryAfter, retryPolicy } from './retry.js';
15
+
16
+ export const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
17
+ export const CLIENT_AUTH_METHODS = Object.freeze(['client_secret_basic', 'client_secret_post', 'private_key_jwt']);
18
+ /** The gateway refuses an assertion whose `exp` is more than this far ahead. */
19
+ export const MAX_ASSERTION_LIFETIME_SECONDS = 300;
20
+
21
+ const OAUTH_ERRORS = new Set(['invalid_request', 'unsupported_grant_type', 'invalid_client', 'invalid_grant', 'temporarily_unavailable']);
22
+ const TOKEN_RETRY_DEFAULTS = { maxAttempts: 3 };
23
+
24
+ function formEncode(value) {
25
+ return new URLSearchParams({ v: value }).toString().slice(2);
26
+ }
27
+
28
+ async function importSigningKey(privateKey) {
29
+ if (privateKey && typeof privateKey === 'object' && privateKey.type === 'private' && privateKey.algorithm) {
30
+ return { key: privateKey, kid: undefined };
31
+ }
32
+ const jwk = privateKey;
33
+ if (!jwk || typeof jwk !== 'object' || typeof jwk.d !== 'string') {
34
+ throw new TypeError('privateKey must be a private CryptoKey or a private JWK');
35
+ }
36
+ let algorithm;
37
+ if (jwk.kty === 'RSA') algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
38
+ else if (jwk.kty === 'EC' && jwk.crv === 'P-256') algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
39
+ else throw new TypeError('privateKey must be an RSA key or an EC P-256 key');
40
+ const { alg: _alg, key_ops: _ops, use: _use, ...material } = jwk;
41
+ const key = await crypto.subtle.importKey('jwk', material, algorithm, false, ['sign']);
42
+ return { key, kid: typeof jwk.kid === 'string' ? jwk.kid : undefined };
43
+ }
44
+
45
+ function jwsAlgFor(key) {
46
+ if (key.algorithm.name === 'RSASSA-PKCS1-v1_5') return 'RS256';
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)');
49
+ }
50
+
51
+ export class ConnectorAuthClient {
52
+ // The token, the in-flight token request and every credential are #private,
53
+ // so logging, inspecting or serializing the client prints none of them.
54
+ #token = null;
55
+ #inflight = null;
56
+ #secret;
57
+ #signer;
58
+
59
+ /**
60
+ * @param {object} options
61
+ * @param {string} options.origin The storefront origin, e.g. https://acme.tokenoftrust.store.
62
+ * @param {string} options.clientId The installation's client id.
63
+ * @param {string} [options.clientSecret] For `client_secret_basic` (default) or `client_secret_post`.
64
+ * @param {CryptoKey|object} [options.privateKey] For `private_key_jwt`: a private CryptoKey or private JWK (RSA or EC P-256).
65
+ * @param {string} [options.keyId] The `kid` of the registered public key. Defaults to the JWK's `kid`.
66
+ * @param {'client_secret_basic'|'client_secret_post'|'private_key_jwt'} [options.method]
67
+ * @param {number} [options.refreshSkewSeconds] Refresh this long before expiry (at most half the token lifetime).
68
+ * @param {number} [options.assertionLifetimeSeconds] Lifetime of each client assertion (1..300).
69
+ * @param {object} [options.retry] Retry policy overrides for the token request (default 3 attempts).
70
+ * @param {typeof fetch} [options.fetch]
71
+ * @param {() => number} [options.now] Milliseconds since the epoch.
72
+ * @param {(ms: number) => Promise<void>} [options.sleep]
73
+ * @param {() => number} [options.random]
74
+ * @param {() => string} [options.randomId] Source of assertion `jti` values.
75
+ */
76
+ constructor({
77
+ origin,
78
+ clientId,
79
+ clientSecret,
80
+ privateKey,
81
+ keyId,
82
+ method,
83
+ refreshSkewSeconds = 60,
84
+ assertionLifetimeSeconds = 60,
85
+ retry,
86
+ fetch: fetchImpl = (...args) => globalThis.fetch(...args),
87
+ now = () => Date.now(),
88
+ sleep = defaultSleep,
89
+ random = Math.random,
90
+ randomId = () => crypto.randomUUID(),
91
+ }) {
92
+ if (typeof clientId !== 'string' || clientId === '') throw new TypeError('clientId is required');
93
+ const resolved = method ?? (privateKey !== undefined ? 'private_key_jwt' : 'client_secret_basic');
94
+ if (!CLIENT_AUTH_METHODS.includes(resolved)) throw new TypeError(`method must be one of ${CLIENT_AUTH_METHODS.join(', ')}`);
95
+ if (resolved === 'private_key_jwt') {
96
+ if (privateKey === undefined) throw new TypeError('private_key_jwt requires privateKey');
97
+ if (clientSecret !== undefined) throw new TypeError('private_key_jwt takes no clientSecret');
98
+ } else {
99
+ if (typeof clientSecret !== 'string' || clientSecret === '') throw new TypeError(`${resolved} requires clientSecret`);
100
+ if (privateKey !== undefined) throw new TypeError(`${resolved} takes no privateKey`);
101
+ }
102
+ if (!Number.isInteger(assertionLifetimeSeconds) || assertionLifetimeSeconds < 1 || assertionLifetimeSeconds > MAX_ASSERTION_LIFETIME_SECONDS) {
103
+ throw new TypeError(`assertionLifetimeSeconds must be an integer in 1..${MAX_ASSERTION_LIFETIME_SECONDS}`);
104
+ }
105
+ this.origin = normalizeOrigin(origin);
106
+ this.tokenEndpoint = `${this.origin}${TOKEN_PATH}`;
107
+ this.clientId = clientId;
108
+ this.method = resolved;
109
+ this.refreshSkewMs = refreshSkewSeconds * 1000;
110
+ this.assertionLifetimeSeconds = assertionLifetimeSeconds;
111
+ this.retry = retryPolicy({ ...TOKEN_RETRY_DEFAULTS, ...retry });
112
+ this.fetch = fetchImpl;
113
+ this.now = now;
114
+ this.sleep = sleep;
115
+ this.random = random;
116
+ this.randomId = randomId;
117
+ this.#secret = clientSecret ?? null;
118
+ this.#signer = resolved === 'private_key_jwt' ? importSigningKey(privateKey) : null;
119
+ this.#signer?.catch(() => {});
120
+ this.keyId = keyId;
121
+ }
122
+
123
+ /** A bearer access token, refreshed early when the cached one is close to expiry. */
124
+ async getAccessToken({ forceRefresh = false } = {}) {
125
+ return (await this.getToken({ forceRefresh })).accessToken;
126
+ }
127
+
128
+ /** The cached token, its expiry (ms since epoch) and granted scopes, refreshing when needed. */
129
+ async getToken({ forceRefresh = false } = {}) {
130
+ if (!forceRefresh && this.#token && !this.needsRefresh(this.#token)) return this.#token;
131
+ this.#inflight ??= this.requestToken().finally(() => {
132
+ this.#inflight = null;
133
+ });
134
+ return this.#inflight;
135
+ }
136
+
137
+ /**
138
+ * Drop the cached token. Pass the token a request was refused with so a
139
+ * concurrent caller's newer token is not discarded.
140
+ */
141
+ invalidate(accessToken) {
142
+ if (accessToken === undefined || this.#token?.accessToken === accessToken) this.#token = null;
143
+ }
144
+
145
+ needsRefresh(token) {
146
+ const lifetime = token.expiresAt - token.issuedAt;
147
+ const skew = Math.min(this.refreshSkewMs, lifetime / 2);
148
+ return this.now() >= token.expiresAt - skew;
149
+ }
150
+
151
+ /** A fresh, signed RFC 7523 client assertion. Exposed for diagnostics and tests. */
152
+ async createClientAssertion() {
153
+ const signer = this.#signer;
154
+ if (!signer) throw new TypeError('createClientAssertion requires private_key_jwt');
155
+ const { key, kid: jwkKid } = await signer;
156
+ const alg = jwsAlgFor(key);
157
+ const kid = this.keyId ?? jwkKid;
158
+ const iat = Math.floor(this.now() / 1000);
159
+ const header = { alg, typ: 'JWT', ...(kid ? { kid } : {}) };
160
+ const payload = { iss: this.clientId, sub: this.clientId, aud: this.tokenEndpoint, iat, exp: iat + this.assertionLifetimeSeconds, jti: this.randomId() };
161
+ const signingInput = `${base64UrlEncode(JSON.stringify(header))}.${base64UrlEncode(JSON.stringify(payload))}`;
162
+ const params = alg === 'RS256' ? { name: 'RSASSA-PKCS1-v1_5' } : { name: 'ECDSA', hash: 'SHA-256' };
163
+ const signature = new Uint8Array(await crypto.subtle.sign(params, key, utf8(signingInput)));
164
+ return `${signingInput}.${base64UrlEncode(signature)}`;
165
+ }
166
+
167
+ async buildRequest() {
168
+ const form = new URLSearchParams({ grant_type: 'client_credentials' });
169
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };
170
+ if (this.method === 'client_secret_basic') {
171
+ headers.authorization = `Basic ${base64Encode(utf8(`${formEncode(this.clientId)}:${formEncode(this.#secret)}`))}`;
172
+ } else if (this.method === 'client_secret_post') {
173
+ form.set('client_id', this.clientId);
174
+ form.set('client_secret', this.#secret);
175
+ } else {
176
+ form.set('client_id', this.clientId);
177
+ form.set('client_assertion_type', CLIENT_ASSERTION_TYPE);
178
+ form.set('client_assertion', await this.createClientAssertion());
179
+ }
180
+ return { method: 'POST', headers, body: form.toString(), redirect: 'manual' };
181
+ }
182
+
183
+ async requestOnce() {
184
+ const init = await this.buildRequest();
185
+ const sentAt = this.now();
186
+ let res;
187
+ try {
188
+ res = await this.fetch(this.tokenEndpoint, init);
189
+ } catch (cause) {
190
+ throw new TransportError({ code: 'network', retryable: true, cause });
191
+ }
192
+ const requestId = safeRequestId(res.headers.get('tot-request-id'));
193
+ let body = null;
194
+ try {
195
+ body = await res.json();
196
+ } catch {
197
+ body = null;
198
+ }
199
+ if (!res.ok) {
200
+ const code = OAUTH_ERRORS.has(body?.error) ? body.error : 'unexpected';
201
+ throw new AuthError({
202
+ code,
203
+ status: res.status,
204
+ requestId,
205
+ retryable: RETRYABLE_STATUS.has(res.status),
206
+ retryAfterMs: parseRetryAfter(res.headers.get('retry-after'), this.now()),
207
+ });
208
+ }
209
+ const expiresIn = Number(body?.expires_in);
210
+ if (typeof body?.access_token !== 'string' || body.access_token === '' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
211
+ throw new AuthError({ code: 'invalid_token_response', status: res.status, requestId });
212
+ }
213
+ return {
214
+ accessToken: body.access_token,
215
+ issuedAt: sentAt,
216
+ expiresAt: sentAt + expiresIn * 1000,
217
+ scope: typeof body.scope === 'string' && body.scope !== '' ? body.scope.split(' ') : [],
218
+ };
219
+ }
220
+
221
+ async requestToken() {
222
+ for (let attempt = 1; ; attempt++) {
223
+ try {
224
+ this.#token = await this.requestOnce();
225
+ return this.#token;
226
+ } catch (err) {
227
+ if (!err.retryable || attempt >= this.retry.maxAttempts) throw err;
228
+ if (err.retryAfterMs !== undefined && err.retryAfterMs > this.retry.maxRetryAfterMs) throw err;
229
+ await this.sleep(err.retryAfterMs ?? backoffDelay(attempt, this.retry, this.random));
230
+ }
231
+ }
232
+ }
233
+ }
@@ -0,0 +1,57 @@
1
+ // Byte helpers built on Web Crypto, TextEncoder and atob/btoa only, so the kit
2
+ // runs unchanged on Node 20+ and on fetch-based edge runtimes.
3
+
4
+ const encoder = new TextEncoder();
5
+
6
+ /** UTF-8 bytes of a string. */
7
+ export function utf8(text) {
8
+ return encoder.encode(text);
9
+ }
10
+
11
+ /**
12
+ * The exact bytes of a request body. Accepts Uint8Array (and its Node
13
+ * subclass), ArrayBuffer, an ArrayBuffer view, or a string (encoded as UTF-8).
14
+ */
15
+ export function toBytes(body) {
16
+ if (body instanceof Uint8Array) return body;
17
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
18
+ if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
19
+ if (typeof body === 'string') return utf8(body);
20
+ throw new TypeError('body must be a Uint8Array, ArrayBuffer or string');
21
+ }
22
+
23
+ export function base64Encode(bytes) {
24
+ let binary = '';
25
+ const view = toBytes(bytes);
26
+ for (let i = 0; i < view.length; i += 0x8000) {
27
+ binary += String.fromCharCode(...view.subarray(i, i + 0x8000));
28
+ }
29
+ return btoa(binary);
30
+ }
31
+
32
+ export function base64Decode(text) {
33
+ const binary = atob(text);
34
+ const out = new Uint8Array(binary.length);
35
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
36
+ return out;
37
+ }
38
+
39
+ export function base64UrlEncode(input) {
40
+ return base64Encode(input).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
41
+ }
42
+
43
+ export async function sha256(bytes) {
44
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', toBytes(bytes)));
45
+ }
46
+
47
+ export function hex(bytes) {
48
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
49
+ }
50
+
51
+ /** Compare two byte arrays without an early exit on the first difference. */
52
+ export function constantTimeEqual(a, b) {
53
+ if (a.length !== b.length) return false;
54
+ let diff = 0;
55
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
56
+ return diff === 0;
57
+ }