@tokenoftrust/cli 6.14.4 → 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 +1 -1
- package/src/app-scaffold.mjs +14 -5
- package/src/commands/catalog.mjs +17 -1
- package/src/vendor/connector-kit/PIN.json +18 -0
- package/src/vendor/connector-kit/api.js +271 -0
- package/src/vendor/connector-kit/auth.js +233 -0
- package/src/vendor/connector-kit/encoding.js +57 -0
- package/src/vendor/connector-kit/errors.js +76 -0
- package/src/vendor/connector-kit/http-signature.js +130 -0
- package/src/vendor/connector-kit/index.js +21 -0
- package/src/vendor/connector-kit/metadata.js +137 -0
- package/src/vendor/connector-kit/retry.js +58 -0
- package/src/vendor/connector-kit/structured-fields.js +167 -0
- package/src/vendor/connector-kit/webhook.js +239 -0
- package/template/private-app/.env.example +10 -5
- package/template/private-app/README.md +21 -10
- package/template/private-app/connector.js +81 -0
- package/template/private-app/package.json +12 -0
- package/template/private-app/server.js +42 -86
- package/template/private-app/tests/connector.spec.js +93 -0
|
@@ -0,0 +1,76 @@
|
|
|
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.
|
|
4
|
+
|
|
5
|
+
const SAFE_CODE = /^[a-z][a-z0-9_.:-]{0,63}$/;
|
|
6
|
+
const SAFE_REQUEST_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
7
|
+
|
|
8
|
+
/** A remote code if it is shaped like one, otherwise `unexpected`. */
|
|
9
|
+
export function safeCode(value) {
|
|
10
|
+
return typeof value === 'string' && SAFE_CODE.test(value) ? value : 'unexpected';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A remote correlation id if it is shaped like one, otherwise undefined. */
|
|
14
|
+
export function safeRequestId(value) {
|
|
15
|
+
return typeof value === 'string' && SAFE_REQUEST_ID.test(value) ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class ConnectorError extends Error {
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} fields
|
|
21
|
+
* @param {'api'|'auth'|'transport'} fields.kind
|
|
22
|
+
* @param {string} fields.code Stable machine code.
|
|
23
|
+
* @param {number} [fields.status] HTTP status, when a response was received.
|
|
24
|
+
* @param {string} [fields.requestId] The `tot-request-id` of the response.
|
|
25
|
+
* @param {boolean} [fields.retryable] Whether retrying the same request can succeed.
|
|
26
|
+
* @param {number} [fields.retryAfterMs] The server's `Retry-After`, in milliseconds.
|
|
27
|
+
* @param {string[]} [fields.holds] Hold codes a refusal listed.
|
|
28
|
+
* @param {string} [fields.idempotencyKey] The key a failed write was sent under; resend under it.
|
|
29
|
+
* @param {unknown} [fields.cause]
|
|
30
|
+
*/
|
|
31
|
+
constructor({ kind, code, status, requestId, retryable = false, retryAfterMs, holds, idempotencyKey, cause }) {
|
|
32
|
+
super(status === undefined ? `${kind}:${code}` : `${kind}:${code} (${status})`, cause === undefined ? undefined : { cause });
|
|
33
|
+
this.name = 'ConnectorError';
|
|
34
|
+
this.kind = kind;
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.requestId = requestId;
|
|
38
|
+
this.retryable = retryable;
|
|
39
|
+
this.retryAfterMs = retryAfterMs;
|
|
40
|
+
this.holds = holds;
|
|
41
|
+
this.idempotencyKey = idempotencyKey;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The loggable fields. Never includes a cause, a body or a credential. */
|
|
45
|
+
toJSON() {
|
|
46
|
+
const out = { kind: this.kind, code: this.code };
|
|
47
|
+
for (const key of ['status', 'requestId', 'retryable', 'retryAfterMs', 'holds', 'idempotencyKey']) {
|
|
48
|
+
if (this[key] !== undefined) out[key] = this[key];
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A non-2xx answer from `/api/apps/v1`. `code` is the body's `code`. */
|
|
55
|
+
export class ApiError extends ConnectorError {
|
|
56
|
+
constructor(fields) {
|
|
57
|
+
super({ ...fields, kind: 'api' });
|
|
58
|
+
this.name = 'ApiError';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The token endpoint refused, or answered something that is not a token. `code` is the OAuth `error`. */
|
|
63
|
+
export class AuthError extends ConnectorError {
|
|
64
|
+
constructor(fields) {
|
|
65
|
+
super({ ...fields, kind: 'auth' });
|
|
66
|
+
this.name = 'AuthError';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** No usable HTTP response: network failure, abort, or a destination the kit refuses. */
|
|
71
|
+
export class TransportError extends ConnectorError {
|
|
72
|
+
constructor(fields) {
|
|
73
|
+
super({ ...fields, kind: 'transport' });
|
|
74
|
+
this.name = 'TransportError';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Webhook authenticity primitives, as apps/private/webhooks-and-api.md
|
|
2
|
+
// specifies: a Content-Digest carrying sha-256 (RFC 9530) and one RFC 9421
|
|
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.
|
|
7
|
+
import { base64Encode, constantTimeEqual, sha256, toBytes, utf8 } from './encoding.js';
|
|
8
|
+
import { parseDictionary, StructuredFieldError } from './structured-fields.js';
|
|
9
|
+
|
|
10
|
+
export const SIGNATURE_LABEL = 'sig1';
|
|
11
|
+
export const SIGNATURE_ALG = 'rsa-v1_5-sha256';
|
|
12
|
+
export const REQUIRED_COMPONENTS = Object.freeze(['@method', '@target-uri', 'content-digest']);
|
|
13
|
+
/** Web Crypto parameters for a webhook signing key (JWK alg RS256). */
|
|
14
|
+
export const RSA_VERIFY_ALGORITHM = Object.freeze({ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' });
|
|
15
|
+
|
|
16
|
+
function fail(code, reason) {
|
|
17
|
+
return { ok: false, code, reason };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The Content-Digest header value for a body: `sha-256=:<base64>:`. */
|
|
21
|
+
export async function contentDigestFor(body) {
|
|
22
|
+
return `sha-256=:${base64Encode(await sha256(toBytes(body)))}:`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Recompute the sha-256 Content-Digest over the raw body and reject a mismatch. */
|
|
26
|
+
export async function verifyContentDigest(headerValue, body) {
|
|
27
|
+
if (!headerValue) return fail('digest_missing', 'Content-Digest header is required');
|
|
28
|
+
let dict;
|
|
29
|
+
try {
|
|
30
|
+
dict = parseDictionary(headerValue);
|
|
31
|
+
} catch (err) {
|
|
32
|
+
if (err instanceof StructuredFieldError) return fail('digest_malformed', err.message);
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
const member = dict.get('sha-256');
|
|
36
|
+
if (!member) return fail('digest_unsupported', 'Content-Digest must carry sha-256');
|
|
37
|
+
if (!member.value?.bytes) return fail('digest_malformed', 'sha-256 is not a byte sequence');
|
|
38
|
+
const expected = await sha256(toBytes(body));
|
|
39
|
+
if (!constantTimeEqual(member.value.bytes, expected)) return fail('digest_mismatch', 'sha-256 does not match the body');
|
|
40
|
+
return { ok: true };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function componentValue(name, { method, targetUri, headers }) {
|
|
44
|
+
if (name === '@method') return method.toUpperCase();
|
|
45
|
+
if (name === '@target-uri') return targetUri;
|
|
46
|
+
if (name.startsWith('@')) return undefined;
|
|
47
|
+
const value = headers[name];
|
|
48
|
+
return value === undefined ? undefined : value.trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Verify the `sig1` signature over a delivery.
|
|
53
|
+
*
|
|
54
|
+
* @param {object} input
|
|
55
|
+
* @param {string} input.method The request method.
|
|
56
|
+
* @param {string} input.targetUri The endpoint the app registered, never a value read from the request.
|
|
57
|
+
* @param {Record<string, string>} input.headers Lowercased header names.
|
|
58
|
+
* @param {(keyid: string) => Promise<CryptoKey|null>} input.resolveKey A published webhook signing key, or null.
|
|
59
|
+
* @param {number} [input.now] Milliseconds since the epoch.
|
|
60
|
+
* @param {number} [input.maxAgeSeconds] Oldest acceptable `created`.
|
|
61
|
+
* @param {number} [input.maxClockSkewSeconds] Furthest-future acceptable `created`.
|
|
62
|
+
*/
|
|
63
|
+
export async function verifyMessageSignature({
|
|
64
|
+
method,
|
|
65
|
+
targetUri,
|
|
66
|
+
headers,
|
|
67
|
+
resolveKey,
|
|
68
|
+
now = Date.now(),
|
|
69
|
+
maxAgeSeconds = 300,
|
|
70
|
+
maxClockSkewSeconds = 60,
|
|
71
|
+
}) {
|
|
72
|
+
const inputHeader = headers['signature-input'];
|
|
73
|
+
const signatureHeader = headers.signature;
|
|
74
|
+
if (!inputHeader || !signatureHeader) return fail('signature_missing', 'Signature-Input and Signature are required');
|
|
75
|
+
let input;
|
|
76
|
+
let signature;
|
|
77
|
+
try {
|
|
78
|
+
input = parseDictionary(inputHeader).get(SIGNATURE_LABEL);
|
|
79
|
+
signature = parseDictionary(signatureHeader).get(SIGNATURE_LABEL);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if (err instanceof StructuredFieldError) return fail('signature_malformed', err.message);
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
if (!input || !signature) return fail('signature_missing', `no ${SIGNATURE_LABEL} signature`);
|
|
85
|
+
if (!input.innerList || !signature.value?.bytes) return fail('signature_malformed', `${SIGNATURE_LABEL} is not a signature`);
|
|
86
|
+
|
|
87
|
+
const names = [];
|
|
88
|
+
for (const item of input.value) {
|
|
89
|
+
if (typeof item.value !== 'string') return fail('signature_malformed', 'components must be strings');
|
|
90
|
+
if (item.params.size > 0) return fail('signature_malformed', 'component parameters are not supported');
|
|
91
|
+
names.push(item.value);
|
|
92
|
+
}
|
|
93
|
+
if (new Set(names).size !== names.length) return fail('signature_malformed', 'duplicate component');
|
|
94
|
+
if (!REQUIRED_COMPONENTS.every((c) => names.includes(c))) {
|
|
95
|
+
return fail('signature_coverage', `the signature must cover ${REQUIRED_COMPONENTS.join(', ')}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const created = input.params.get('created');
|
|
99
|
+
const keyid = input.params.get('keyid');
|
|
100
|
+
const alg = input.params.get('alg');
|
|
101
|
+
const expires = input.params.get('expires');
|
|
102
|
+
if (!Number.isInteger(created)) return fail('signature_malformed', 'created is required');
|
|
103
|
+
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}`);
|
|
105
|
+
const nowSeconds = Math.floor(now / 1000);
|
|
106
|
+
if (nowSeconds - created > maxAgeSeconds) return fail('signature_expired', 'created is too old');
|
|
107
|
+
if (created - nowSeconds > maxClockSkewSeconds) return fail('signature_expired', 'created is in the future');
|
|
108
|
+
if (expires !== undefined && (!Number.isInteger(expires) || expires <= nowSeconds)) {
|
|
109
|
+
return fail('signature_expired', 'expires has passed');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const key = await resolveKey(keyid);
|
|
113
|
+
if (!key) return fail('unknown_key', 'keyid is not a published webhook signing key');
|
|
114
|
+
|
|
115
|
+
const lines = [];
|
|
116
|
+
for (const name of names) {
|
|
117
|
+
const value = componentValue(name, { method, targetUri, headers });
|
|
118
|
+
if (value === undefined) return fail('signature_malformed', `covered component ${name} is absent`);
|
|
119
|
+
lines.push(`"${name}": ${value}`);
|
|
120
|
+
}
|
|
121
|
+
lines.push(`"@signature-params": ${input.raw}`);
|
|
122
|
+
let verified = false;
|
|
123
|
+
try {
|
|
124
|
+
verified = await crypto.subtle.verify(RSA_VERIFY_ALGORITHM, key, signature.value.bytes, utf8(lines.join('\n')));
|
|
125
|
+
} catch {
|
|
126
|
+
verified = false;
|
|
127
|
+
}
|
|
128
|
+
if (!verified) return fail('signature_invalid', 'signature verification failed');
|
|
129
|
+
return { ok: true, label: SIGNATURE_LABEL, keyid, created, alg };
|
|
130
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// connector-kit: the reviewed client half of the Storefront Private Apps
|
|
2
|
+
// contract (apps/private/contract). Vendor this directory; do not edit it in
|
|
3
|
+
// place. Zero dependencies, ESM, Web Crypto and fetch only.
|
|
4
|
+
|
|
5
|
+
export const KIT_VERSION = '1.0.0';
|
|
6
|
+
export const CONTRACT_VERSION = 'private-apps@1.3';
|
|
7
|
+
|
|
8
|
+
export { ConnectorAuthClient, CLIENT_ASSERTION_TYPE, CLIENT_AUTH_METHODS, MAX_ASSERTION_LIFETIME_SECONDS } from './auth.js';
|
|
9
|
+
export { WebhookReceiver, MemorySeenEventStore, WEBHOOK_REFUSALS, EVENT_TYPE_PREFIX, DEFAULT_MAX_BODY_BYTES, normalizeHeaders } from './webhook.js';
|
|
10
|
+
export { ApiClient, newIdempotencyKey, deriveIdempotencyKey } from './api.js';
|
|
11
|
+
export { AuthorizationMetadata, StaticSigningKeys, importWebhookSigningKey, normalizeOrigin, METADATA_PATH, TOKEN_PATH, API_PREFIX } from './metadata.js';
|
|
12
|
+
export { ConnectorError, ApiError, AuthError, TransportError, safeCode } from './errors.js';
|
|
13
|
+
export { DEFAULT_RETRY_POLICY, RETRYABLE_STATUS, parseRetryAfter } from './retry.js';
|
|
14
|
+
export {
|
|
15
|
+
contentDigestFor,
|
|
16
|
+
verifyContentDigest,
|
|
17
|
+
verifyMessageSignature,
|
|
18
|
+
SIGNATURE_LABEL,
|
|
19
|
+
SIGNATURE_ALG,
|
|
20
|
+
REQUIRED_COMPONENTS,
|
|
21
|
+
} from './http-signature.js';
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Gateway discovery: `GET /.well-known/tot-app-authorization-metadata` on the
|
|
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';
|
|
7
|
+
import { TransportError } from './errors.js';
|
|
8
|
+
|
|
9
|
+
export const METADATA_PATH = '/.well-known/tot-app-authorization-metadata';
|
|
10
|
+
export const TOKEN_PATH = '/api/apps/oauth/token';
|
|
11
|
+
export const API_PREFIX = '/api/apps/v1';
|
|
12
|
+
|
|
13
|
+
const DEFAULT_MAX_AGE_SECONDS = 300;
|
|
14
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The storefront origin as `scheme://host[:port]`. HTTPS is required except for
|
|
18
|
+
* a loopback host (a local simulator). A path, query, fragment or userinfo is
|
|
19
|
+
* refused so a base URL with `/api/apps/v1` appended is caught at construction.
|
|
20
|
+
*/
|
|
21
|
+
export function normalizeOrigin(origin) {
|
|
22
|
+
let url;
|
|
23
|
+
try {
|
|
24
|
+
url = new URL(String(origin));
|
|
25
|
+
} catch {
|
|
26
|
+
throw new TypeError('origin must be an absolute URL such as https://acme.tokenoftrust.store');
|
|
27
|
+
}
|
|
28
|
+
const loopback = url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);
|
|
29
|
+
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');
|
|
32
|
+
}
|
|
33
|
+
return url.origin;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function maxAgeSeconds(cacheControl) {
|
|
37
|
+
const m = /max-age=(\d+)/.exec(cacheControl ?? '');
|
|
38
|
+
return m ? Number(m[1]) : DEFAULT_MAX_AGE_SECONDS;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Import one published webhook signing key; anything but a public RS256 signing key yields null. */
|
|
42
|
+
export async function importWebhookSigningKey(jwk) {
|
|
43
|
+
if (!jwk || jwk.kty !== 'RSA' || typeof jwk.kid !== 'string' || jwk.d !== undefined) return null;
|
|
44
|
+
if (jwk.use !== undefined && jwk.use !== 'sig') return null;
|
|
45
|
+
if (jwk.alg !== undefined && jwk.alg !== 'RS256') return null;
|
|
46
|
+
try {
|
|
47
|
+
const key = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS256', ext: true }, RSA_VERIFY_ALGORITHM, false, ['verify']);
|
|
48
|
+
return { kid: jwk.kid, key };
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function importKeySet(jwks) {
|
|
55
|
+
const entries = await Promise.all((jwks?.keys ?? []).map(importWebhookSigningKey));
|
|
56
|
+
return new Map(entries.filter(Boolean).map(({ kid, key }) => [kid, key]));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A fixed set of webhook signing keys, for tests or a pinned key set. */
|
|
60
|
+
export class StaticSigningKeys {
|
|
61
|
+
/** @param {{ keys: object[] }} jwks A JWK Set of public RS256 keys. */
|
|
62
|
+
constructor(jwks) {
|
|
63
|
+
this.ready = importKeySet(jwks);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async resolveSigningKey(keyid) {
|
|
67
|
+
return (await this.ready).get(keyid) ?? null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The gateway's published authorization metadata, cached. */
|
|
72
|
+
export class AuthorizationMetadata {
|
|
73
|
+
/**
|
|
74
|
+
* @param {object} options
|
|
75
|
+
* @param {string} options.origin The storefront origin.
|
|
76
|
+
* @param {typeof fetch} [options.fetch]
|
|
77
|
+
* @param {() => number} [options.now] Milliseconds since the epoch.
|
|
78
|
+
* @param {number} [options.minRefreshIntervalMs] Least time between forced refetches on an unknown keyid.
|
|
79
|
+
*/
|
|
80
|
+
constructor({ origin, fetch: fetchImpl = (...args) => globalThis.fetch(...args), now = () => Date.now(), minRefreshIntervalMs = 30_000 }) {
|
|
81
|
+
this.origin = normalizeOrigin(origin);
|
|
82
|
+
this.url = `${this.origin}${METADATA_PATH}`;
|
|
83
|
+
this.expectedTokenEndpoint = `${this.origin}${TOKEN_PATH}`;
|
|
84
|
+
this.fetch = fetchImpl;
|
|
85
|
+
this.now = now;
|
|
86
|
+
this.minRefreshIntervalMs = minRefreshIntervalMs;
|
|
87
|
+
this.cached = null;
|
|
88
|
+
this.lastFetchAt = -Infinity;
|
|
89
|
+
this.inflight = null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async load(force = false) {
|
|
93
|
+
if (!force && this.cached && this.cached.expiresAt > this.now()) return this.cached;
|
|
94
|
+
this.inflight ??= this.fetchDocument().finally(() => {
|
|
95
|
+
this.inflight = null;
|
|
96
|
+
});
|
|
97
|
+
return this.inflight;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async fetchDocument() {
|
|
101
|
+
this.lastFetchAt = this.now();
|
|
102
|
+
let res;
|
|
103
|
+
try {
|
|
104
|
+
res = await this.fetch(this.url, { method: 'GET', headers: { accept: 'application/json' }, redirect: 'manual' });
|
|
105
|
+
} catch (cause) {
|
|
106
|
+
throw new TransportError({ code: 'metadata_unreachable', retryable: true, cause });
|
|
107
|
+
}
|
|
108
|
+
if (!res.ok) throw new TransportError({ code: 'metadata_unavailable', status: res.status, retryable: res.status >= 500 });
|
|
109
|
+
let doc;
|
|
110
|
+
try {
|
|
111
|
+
doc = await res.json();
|
|
112
|
+
} catch {
|
|
113
|
+
throw new TransportError({ code: 'metadata_unavailable', status: res.status });
|
|
114
|
+
}
|
|
115
|
+
this.cached = {
|
|
116
|
+
tokenEndpoint: doc?.token_endpoint,
|
|
117
|
+
authMethods: Array.isArray(doc?.token_endpoint_auth_methods_supported) ? doc.token_endpoint_auth_methods_supported : [],
|
|
118
|
+
keys: await importKeySet(doc?.webhook_signing_keys),
|
|
119
|
+
expiresAt: this.now() + maxAgeSeconds(res.headers.get('cache-control')) * 1000,
|
|
120
|
+
};
|
|
121
|
+
return this.cached;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The published token endpoint, accepted only as this origin's exact OAuth path. */
|
|
125
|
+
async tokenEndpoint() {
|
|
126
|
+
const { tokenEndpoint } = await this.load();
|
|
127
|
+
if (tokenEndpoint !== this.expectedTokenEndpoint) throw new TransportError({ code: 'token_endpoint_refused' });
|
|
128
|
+
return tokenEndpoint;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The webhook signing key for `keyid`, refetching once (rate-limited) when it is unknown. */
|
|
132
|
+
async resolveSigningKey(keyid) {
|
|
133
|
+
let doc = await this.load();
|
|
134
|
+
if (!doc.keys.has(keyid) && this.now() - this.lastFetchAt >= this.minRefreshIntervalMs) doc = await this.load(true);
|
|
135
|
+
return doc.keys.get(keyid) ?? null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Retry policy shared by the API client and the token client: bounded
|
|
2
|
+
// exponential backoff with full jitter, and `Retry-After` honored exactly.
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_RETRY_POLICY = Object.freeze({
|
|
5
|
+
/** Total attempts, including the first. */
|
|
6
|
+
maxAttempts: 5,
|
|
7
|
+
/** First backoff ceiling; doubles per attempt. */
|
|
8
|
+
baseDelayMs: 250,
|
|
9
|
+
/** Largest backoff the kit computes itself. */
|
|
10
|
+
maxDelayMs: 20_000,
|
|
11
|
+
/** Largest `Retry-After` the kit waits in-process. A longer one is returned to the caller to schedule. */
|
|
12
|
+
maxRetryAfterMs: 120_000,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/** Statuses where the same request can succeed later. */
|
|
16
|
+
export const RETRYABLE_STATUS = new Set([408, 429, 502, 503, 504]);
|
|
17
|
+
|
|
18
|
+
export function retryPolicy(overrides = {}) {
|
|
19
|
+
const policy = { ...DEFAULT_RETRY_POLICY, ...overrides };
|
|
20
|
+
for (const [key, value] of Object.entries(policy)) {
|
|
21
|
+
if (!Number.isFinite(value) || value < 0) throw new TypeError(`retry.${key} must be a non-negative number`);
|
|
22
|
+
}
|
|
23
|
+
if (policy.maxAttempts < 1) throw new TypeError('retry.maxAttempts must be at least 1');
|
|
24
|
+
return policy;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* `Retry-After` in milliseconds: delta-seconds or an HTTP-date (RFC 9110
|
|
29
|
+
* section 10.2.3). Undefined when absent or unreadable.
|
|
30
|
+
*/
|
|
31
|
+
export function parseRetryAfter(value, nowMs = Date.now()) {
|
|
32
|
+
if (value === null || value === undefined) return undefined;
|
|
33
|
+
const text = String(value).trim();
|
|
34
|
+
if (/^\d+$/.test(text)) return Number(text) * 1000;
|
|
35
|
+
const at = Date.parse(text);
|
|
36
|
+
if (Number.isNaN(at)) return undefined;
|
|
37
|
+
return Math.max(0, at - nowMs);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Full-jitter backoff for the given 1-based attempt that just failed. */
|
|
41
|
+
export function backoffDelay(attempt, policy, random = Math.random) {
|
|
42
|
+
const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (attempt - 1));
|
|
43
|
+
return Math.floor(random() * ceiling);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const defaultSleep = (ms, signal) =>
|
|
47
|
+
new Promise((resolve, reject) => {
|
|
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
|
+
);
|
|
58
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// Minimal RFC 8941 Structured Field Values parser: just enough to read the
|
|
2
|
+
// Dictionary-valued headers RFC 9421 (Signature-Input, Signature) and
|
|
3
|
+
// RFC 9530 (Content-Digest) use. Every member keeps its raw text so the
|
|
4
|
+
// verifier can rebuild "@signature-params" exactly as the signer serialized it.
|
|
5
|
+
import { base64Decode } from './encoding.js';
|
|
6
|
+
|
|
7
|
+
export class StructuredFieldError extends Error {}
|
|
8
|
+
|
|
9
|
+
const KEY_START = /[a-z*]/;
|
|
10
|
+
const KEY_CHAR = /[a-z0-9_\-.*]/;
|
|
11
|
+
const TOKEN_START = /[A-Za-z*]/;
|
|
12
|
+
const TOKEN_CHAR = /[A-Za-z0-9!#$%&'*+\-.^_`|~:/]/;
|
|
13
|
+
|
|
14
|
+
export function parseDictionary(text) {
|
|
15
|
+
const p = { s: String(text ?? ''), i: 0 };
|
|
16
|
+
const out = new Map();
|
|
17
|
+
skipSP(p);
|
|
18
|
+
if (p.i >= p.s.length) throw new StructuredFieldError('empty dictionary');
|
|
19
|
+
while (p.i < p.s.length) {
|
|
20
|
+
const start = p.i;
|
|
21
|
+
const key = parseKey(p);
|
|
22
|
+
let member;
|
|
23
|
+
if (p.s[p.i] === '=') {
|
|
24
|
+
p.i++;
|
|
25
|
+
member = parseItemOrInnerList(p);
|
|
26
|
+
} else {
|
|
27
|
+
member = { value: true, params: parseParams(p) };
|
|
28
|
+
}
|
|
29
|
+
member.raw = p.s.slice(start + key.length + 1, p.i);
|
|
30
|
+
out.set(key, member);
|
|
31
|
+
skipOWS(p);
|
|
32
|
+
if (p.i >= p.s.length) break;
|
|
33
|
+
if (p.s[p.i] !== ',') throw new StructuredFieldError(`unexpected "${p.s[p.i]}"`);
|
|
34
|
+
p.i++;
|
|
35
|
+
skipOWS(p);
|
|
36
|
+
if (p.i >= p.s.length) throw new StructuredFieldError('trailing comma');
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseItemOrInnerList(p) {
|
|
42
|
+
if (p.s[p.i] === '(') return parseInnerList(p);
|
|
43
|
+
const value = parseBareItem(p);
|
|
44
|
+
return { value, params: parseParams(p) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseInnerList(p) {
|
|
48
|
+
p.i++;
|
|
49
|
+
const items = [];
|
|
50
|
+
for (;;) {
|
|
51
|
+
skipSP(p);
|
|
52
|
+
if (p.s[p.i] === ')') {
|
|
53
|
+
p.i++;
|
|
54
|
+
return { value: items, innerList: true, params: parseParams(p) };
|
|
55
|
+
}
|
|
56
|
+
if (p.i >= p.s.length) throw new StructuredFieldError('unterminated inner list');
|
|
57
|
+
const value = parseBareItem(p);
|
|
58
|
+
items.push({ value, params: parseParams(p) });
|
|
59
|
+
if (p.s[p.i] !== ' ' && p.s[p.i] !== ')') throw new StructuredFieldError('bad inner list');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseParams(p) {
|
|
64
|
+
const params = new Map();
|
|
65
|
+
while (p.s[p.i] === ';') {
|
|
66
|
+
p.i++;
|
|
67
|
+
skipSP(p);
|
|
68
|
+
const key = parseKey(p);
|
|
69
|
+
let value = true;
|
|
70
|
+
if (p.s[p.i] === '=') {
|
|
71
|
+
p.i++;
|
|
72
|
+
value = parseBareItem(p);
|
|
73
|
+
}
|
|
74
|
+
params.set(key, value);
|
|
75
|
+
}
|
|
76
|
+
return params;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function parseKey(p) {
|
|
80
|
+
if (!KEY_START.test(p.s[p.i] ?? '')) throw new StructuredFieldError('bad key');
|
|
81
|
+
const start = p.i;
|
|
82
|
+
while (p.i < p.s.length && KEY_CHAR.test(p.s[p.i])) p.i++;
|
|
83
|
+
return p.s.slice(start, p.i);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseBareItem(p) {
|
|
87
|
+
const c = p.s[p.i];
|
|
88
|
+
if (c === '"') return parseString(p);
|
|
89
|
+
if (c === ':') return parseBytes(p);
|
|
90
|
+
if (c === '?') return parseBoolean(p);
|
|
91
|
+
if (c === '-' || /[0-9]/.test(c ?? '')) return parseNumber(p);
|
|
92
|
+
if (TOKEN_START.test(c ?? '')) return parseToken(p);
|
|
93
|
+
throw new StructuredFieldError('bad item');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function parseString(p) {
|
|
97
|
+
p.i++;
|
|
98
|
+
let out = '';
|
|
99
|
+
while (p.i < p.s.length) {
|
|
100
|
+
const c = p.s[p.i++];
|
|
101
|
+
if (c === '\\') {
|
|
102
|
+
const n = p.s[p.i++];
|
|
103
|
+
if (n !== '"' && n !== '\\') throw new StructuredFieldError('bad escape');
|
|
104
|
+
out += n;
|
|
105
|
+
} else if (c === '"') {
|
|
106
|
+
return out;
|
|
107
|
+
} else {
|
|
108
|
+
const code = c.charCodeAt(0);
|
|
109
|
+
if (code < 0x20 || code > 0x7e) throw new StructuredFieldError('bad string char');
|
|
110
|
+
out += c;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
throw new StructuredFieldError('unterminated string');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function parseBytes(p) {
|
|
117
|
+
p.i++;
|
|
118
|
+
const end = p.s.indexOf(':', p.i);
|
|
119
|
+
if (end < 0) throw new StructuredFieldError('unterminated byte sequence');
|
|
120
|
+
const b64 = p.s.slice(p.i, end);
|
|
121
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 !== 0) throw new StructuredFieldError('bad base64');
|
|
122
|
+
p.i = end + 1;
|
|
123
|
+
try {
|
|
124
|
+
return { bytes: base64Decode(b64) };
|
|
125
|
+
} catch {
|
|
126
|
+
throw new StructuredFieldError('bad base64');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function parseBoolean(p) {
|
|
131
|
+
const v = p.s[p.i + 1];
|
|
132
|
+
if (v !== '0' && v !== '1') throw new StructuredFieldError('bad boolean');
|
|
133
|
+
p.i += 2;
|
|
134
|
+
return v === '1';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// RFC 8941 §4.2.4: an Integer (up to 15 digits) or a Decimal (up to 12
|
|
138
|
+
// integer and 1-3 fractional digits). Decimals parse so that unrelated members
|
|
139
|
+
// carrying one never make the whole dictionary unreadable; the verifier only
|
|
140
|
+
// reads the Integer parameters it needs.
|
|
141
|
+
function parseNumber(p) {
|
|
142
|
+
const rest = p.s.slice(p.i);
|
|
143
|
+
const decimal = /^-?[0-9]{1,12}\.[0-9]{1,3}/.exec(rest);
|
|
144
|
+
if (decimal && !/[0-9.]/.test(rest[decimal[0].length] ?? '')) {
|
|
145
|
+
p.i += decimal[0].length;
|
|
146
|
+
return { decimal: Number(decimal[0]) };
|
|
147
|
+
}
|
|
148
|
+
const m = /^-?[0-9]{1,15}/.exec(rest);
|
|
149
|
+
if (!m || /[0-9.]/.test(rest[m[0].length] ?? '')) throw new StructuredFieldError('bad number');
|
|
150
|
+
p.i += m[0].length;
|
|
151
|
+
return Number(m[0]);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function parseToken(p) {
|
|
155
|
+
const start = p.i;
|
|
156
|
+
p.i++;
|
|
157
|
+
while (p.i < p.s.length && TOKEN_CHAR.test(p.s[p.i])) p.i++;
|
|
158
|
+
return { token: p.s.slice(start, p.i) };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function skipSP(p) {
|
|
162
|
+
while (p.s[p.i] === ' ') p.i++;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function skipOWS(p) {
|
|
166
|
+
while (p.s[p.i] === ' ' || p.s[p.i] === '\t') p.i++;
|
|
167
|
+
}
|