@tokenoftrust/cli 6.14.5 → 6.15.0
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/bin/tot.mjs +5 -0
- package/package.json +1 -1
- package/src/app-scaffold.mjs +14 -5
- package/src/commands/app/admin.mjs +69 -2
- package/src/commands/app/index.mjs +4 -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,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
|
+
}
|
|
@@ -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
|
+
}
|