mppx 0.17.5 → 0.18.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/CHANGELOG.md +40 -0
- package/dist/cli/cli.js +141 -139
- package/dist/cli/plugins/index.js +6 -6
- package/dist/cli/stripe.d.ts +6 -1
- package/dist/cli/stripe.js +89 -5
- package/dist/client/Mppx.js +13 -3
- package/dist/client/internal/Fetch.js +9 -5
- package/dist/extensions/identity/attestation/Constants.d.ts +23 -0
- package/dist/extensions/identity/attestation/Constants.js +23 -0
- package/dist/extensions/identity/attestation/Jwks.d.ts +30 -0
- package/dist/extensions/identity/attestation/Jwks.js +114 -0
- package/dist/extensions/identity/attestation/Token.d.ts +80 -0
- package/dist/extensions/identity/attestation/Token.js +143 -0
- package/dist/extensions/identity/attestation/Types.d.ts +48 -0
- package/dist/extensions/identity/attestation/Types.js +2 -0
- package/dist/extensions/identity/attestation/client/index.d.ts +66 -0
- package/dist/extensions/identity/attestation/client/index.js +273 -0
- package/dist/extensions/identity/attestation/index.d.ts +20 -0
- package/dist/extensions/identity/attestation/index.js +18 -0
- package/dist/extensions/identity/attestation/internal/Cache.d.ts +120 -0
- package/dist/extensions/identity/attestation/internal/Cache.js +90 -0
- package/dist/extensions/identity/attestation/server/index.d.ts +66 -0
- package/dist/extensions/identity/attestation/server/index.js +119 -0
- package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
- package/dist/extensions/identity/email-otp/Constants.js +17 -0
- package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
- package/dist/extensions/identity/email-otp/Types.js +2 -0
- package/dist/extensions/identity/email-otp/client/index.d.ts +123 -0
- package/dist/extensions/identity/email-otp/client/index.js +131 -0
- package/dist/extensions/identity/email-otp/index.d.ts +12 -0
- package/dist/extensions/identity/email-otp/index.js +11 -0
- package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
- package/dist/extensions/identity/email-otp/server/index.js +59 -0
- package/dist/extensions/identity/index.d.ts +4 -0
- package/dist/extensions/identity/index.js +4 -0
- package/dist/extensions/identity/internal/Verification.js +9 -5
- package/dist/identity/Callback.d.ts +66 -0
- package/dist/identity/Callback.js +88 -0
- package/dist/identity/Client.d.ts +78 -5
- package/dist/identity/Client.js +165 -48
- package/dist/identity/Headers.d.ts +16 -0
- package/dist/identity/Headers.js +19 -0
- package/dist/identity/Server.d.ts +159 -37
- package/dist/identity/Server.js +307 -138
- package/dist/identity/Status.d.ts +14 -0
- package/dist/identity/Status.js +19 -0
- package/dist/identity/Types.d.ts +161 -65
- package/dist/identity/index.d.ts +3 -0
- package/dist/identity/index.js +3 -0
- package/dist/identity/internal/Requirements.d.ts +28 -0
- package/dist/identity/internal/Requirements.js +78 -0
- package/dist/integrations/x402/Evm.d.ts +1 -0
- package/dist/internal/env.d.ts +14 -0
- package/dist/internal/env.js +38 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/internal/Headers.d.ts +1 -1
- package/dist/proxy/internal/Headers.js +7 -1
- package/dist/server/Mppx.d.ts +14 -6
- package/dist/server/Mppx.js +252 -148
- package/dist/server/internal/challengeMeta.d.ts +0 -6
- package/dist/server/internal/challengeMeta.js +3 -17
- package/dist/tempo/server/Charge.d.ts +14 -9
- package/dist/tempo/server/Charge.js +5 -1
- package/dist/tempo/server/Methods.js +4 -1
- package/dist/tempo/server/Subscription.d.ts +8 -0
- package/dist/tempo/server/internal/fallback-store.d.ts +7 -2
- package/dist/tempo/server/internal/fallback-store.js +12 -3
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/server/Session.d.ts +5 -1
- package/package.json +9 -1
package/dist/cli/stripe.d.ts
CHANGED
|
@@ -38,7 +38,12 @@ export declare namespace readStripeCliKey {
|
|
|
38
38
|
projectName?: string | undefined;
|
|
39
39
|
};
|
|
40
40
|
}
|
|
41
|
-
/**
|
|
41
|
+
/** Whether a deposit address has its network's format: 0x hex for Tempo and Base, a 32-byte base58 key for Solana. */
|
|
42
|
+
export declare function isAddress(network: string, value: unknown): value is string;
|
|
43
|
+
/**
|
|
44
|
+
* Sets `key=value` in a dotenv file as its only assignment of `key`: the first existing one is
|
|
45
|
+
* replaced and any later ones are removed, since loaders that take the last would keep them.
|
|
46
|
+
*/
|
|
42
47
|
export declare function writeEnvValue(file: string, key: string, value: string): void;
|
|
43
48
|
/**
|
|
44
49
|
* Gives a bare `--env` on `mppx stripe address` its default path, since incur flags can't take an
|
package/dist/cli/stripe.js
CHANGED
|
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
2
2
|
import * as fs from 'node:fs';
|
|
3
3
|
import * as os from 'node:os';
|
|
4
4
|
import * as path from 'node:path';
|
|
5
|
+
import * as util from 'node:util';
|
|
5
6
|
/** The Stripe CLI's keyring service name (stripe-cli pkg/config KeyManagementService). */
|
|
6
7
|
const keyringService = 'StripeCLI';
|
|
7
8
|
/**
|
|
@@ -120,17 +121,100 @@ function readProfile(file, project) {
|
|
|
120
121
|
}
|
|
121
122
|
return values;
|
|
122
123
|
}
|
|
123
|
-
/**
|
|
124
|
+
/** Whether a deposit address has its network's format: 0x hex for Tempo and Base, a 32-byte base58 key for Solana. */
|
|
125
|
+
export function isAddress(network, value) {
|
|
126
|
+
// The response is only type-cast, so a non-string (such as a one-element array) must not pass.
|
|
127
|
+
if (typeof value !== 'string')
|
|
128
|
+
return false;
|
|
129
|
+
if (network === 'solana')
|
|
130
|
+
return base58Length(value) === 32;
|
|
131
|
+
return /^0x[0-9a-fA-F]{40}$/.test(value);
|
|
132
|
+
}
|
|
133
|
+
const base58Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
134
|
+
/** How many bytes a base58 string decodes to, or `undefined` when it isn't base58. */
|
|
135
|
+
function base58Length(value) {
|
|
136
|
+
if (!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(value))
|
|
137
|
+
return undefined;
|
|
138
|
+
let number = 0n;
|
|
139
|
+
for (const char of value)
|
|
140
|
+
number = number * 58n + BigInt(base58Alphabet.indexOf(char));
|
|
141
|
+
const zeros = /^1*/.exec(value)[0].length;
|
|
142
|
+
const hex = number === 0n ? '' : number.toString(16);
|
|
143
|
+
return zeros + Math.ceil(hex.length / 2);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Sets `key=value` in a dotenv file as its only assignment of `key`: the first existing one is
|
|
147
|
+
* replaced and any later ones are removed, since loaders that take the last would keep them.
|
|
148
|
+
*/
|
|
124
149
|
export function writeEnvValue(file, key, value) {
|
|
150
|
+
// A line break would let the value add assignments of its own.
|
|
151
|
+
if (/[\r\n]/.test(key) || /[\r\n]/.test(value))
|
|
152
|
+
throw new Error('env values cannot contain line breaks');
|
|
125
153
|
const line = `${key}=${value}`;
|
|
126
154
|
if (!fs.existsSync(file))
|
|
127
155
|
return fs.writeFileSync(file, `${line}\n`, { mode: 0o600 });
|
|
128
156
|
const existing = fs.readFileSync(file, 'utf8');
|
|
129
|
-
const pattern = new RegExp(
|
|
130
|
-
|
|
131
|
-
return fs.writeFileSync(file, existing.replace(pattern, () => line));
|
|
157
|
+
const pattern = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
|
|
158
|
+
const { lines: kept, found } = replaceAssignments(existing.split('\n'), pattern, line);
|
|
132
159
|
const separator = existing === '' || existing.endsWith('\n') ? '' : '\n';
|
|
133
|
-
|
|
160
|
+
const output = found ? kept.join('\n') : `${existing}${separator}${line}\n`;
|
|
161
|
+
// Node's own parser must read back exactly this value, so a dotenv form the line logic
|
|
162
|
+
// misreads fails here instead of leaving a stale or missing address.
|
|
163
|
+
const parseEnv = util.parseEnv;
|
|
164
|
+
if (parseEnv) {
|
|
165
|
+
// Every other key must keep its value too, so no other entry is cut or merged.
|
|
166
|
+
const before = parseEnv(existing);
|
|
167
|
+
const after = parseEnv(output);
|
|
168
|
+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
169
|
+
keys.delete(key);
|
|
170
|
+
if (after[key] !== value || [...keys].some((name) => before[name] !== after[name]))
|
|
171
|
+
throw new Error(`could not update ${key} in ${file} safely: edit it by hand`);
|
|
172
|
+
}
|
|
173
|
+
fs.writeFileSync(file, output);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Replaces the first assignment matching `pattern` with `line` and drops the rest. Each
|
|
177
|
+
* assignment is taken whole, quoted multiline value included, and lines inside another key's
|
|
178
|
+
* multiline value are kept, since they only look like assignments.
|
|
179
|
+
*/
|
|
180
|
+
function replaceAssignments(lines, pattern, line) {
|
|
181
|
+
// For each quote, the first line at or after each index that holds it: one backward pass, so
|
|
182
|
+
// finding where a multiline value closes never rescans the file.
|
|
183
|
+
const next = {};
|
|
184
|
+
for (const quote of ['"', "'", '`']) {
|
|
185
|
+
const indexes = new Array(lines.length + 1);
|
|
186
|
+
indexes[lines.length] = -1;
|
|
187
|
+
for (let i = lines.length - 1; i >= 0; i--)
|
|
188
|
+
indexes[i] = closes(lines[i], quote) ? i : indexes[i + 1];
|
|
189
|
+
next[quote] = indexes;
|
|
190
|
+
}
|
|
191
|
+
const kept = [];
|
|
192
|
+
let found = false;
|
|
193
|
+
for (let index = 0; index < lines.length; index++) {
|
|
194
|
+
let end = index;
|
|
195
|
+
// Like Node's --env-file, any text before the first = is a key, unless the line is a comment.
|
|
196
|
+
// `s` lets the value run over a CRLF file's trailing \r.
|
|
197
|
+
const opening = /^[ \t]*[^#=\s][^=]*=[ \t]*(["'`])(.*)$/s.exec(lines[index]);
|
|
198
|
+
// A quote closed on a later line spans to it; one never closed is a one-line value, as in Node.
|
|
199
|
+
if (opening && !closes(opening[2], opening[1])) {
|
|
200
|
+
const close = next[opening[1]][index + 1];
|
|
201
|
+
if (close !== -1)
|
|
202
|
+
end = close;
|
|
203
|
+
}
|
|
204
|
+
const target = pattern.test(lines[index]);
|
|
205
|
+
if (target && !found)
|
|
206
|
+
kept.push(lines[index].endsWith('\r') ? `${line}\r` : line);
|
|
207
|
+
found ||= target;
|
|
208
|
+
if (!target)
|
|
209
|
+
for (let i = index; i <= end; i++)
|
|
210
|
+
kept.push(lines[i]);
|
|
211
|
+
index = end;
|
|
212
|
+
}
|
|
213
|
+
return { lines: kept, found };
|
|
214
|
+
}
|
|
215
|
+
/** Whether a line holds the closing `quote`. Like Node's --env-file, a backslash doesn't escape it. */
|
|
216
|
+
function closes(text, quote) {
|
|
217
|
+
return text.includes(quote);
|
|
134
218
|
}
|
|
135
219
|
/**
|
|
136
220
|
* Gives a bare `--env` on `mppx stripe address` its default path, since incur flags can't take an
|
package/dist/client/Mppx.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as Constants from '../Constants.js';
|
|
2
2
|
import * as Expires from '../Expires.js';
|
|
3
3
|
import * as IdentityClient from '../identity/Client.js';
|
|
4
|
+
import * as IdentityHeaders from '../identity/Headers.js';
|
|
4
5
|
import * as AcceptPayment from '../internal/AcceptPayment.js';
|
|
5
6
|
import * as Fetch from './internal/Fetch.js';
|
|
6
7
|
import * as MethodChallenge from './internal/MethodChallenge.js';
|
|
@@ -222,6 +223,7 @@ export function create(config) {
|
|
|
222
223
|
return rawFetch(paidRequest);
|
|
223
224
|
const { response } = await identityClient.send(rawFetch, paidRequest, {
|
|
224
225
|
challenge: payment.challenge,
|
|
226
|
+
headers: preparedHttp.identityHeaders,
|
|
225
227
|
});
|
|
226
228
|
return response;
|
|
227
229
|
},
|
|
@@ -277,6 +279,7 @@ const bodyHeaders = [
|
|
|
277
279
|
'content-type',
|
|
278
280
|
'transfer-encoding',
|
|
279
281
|
];
|
|
282
|
+
/** Credential headers never sent across origins; identity headers come from `Identity.Headers` and the provers. */
|
|
280
283
|
const crossOriginHeaders = [
|
|
281
284
|
'authorization',
|
|
282
285
|
'cookie',
|
|
@@ -291,24 +294,30 @@ async function prepareHttpRequest(parameters) {
|
|
|
291
294
|
const { acceptPayment, acceptPaymentPolicy, fetch, identity, init, input, maxRedirects } = parameters;
|
|
292
295
|
if (!Number.isInteger(maxRedirects) || maxRedirects < 0)
|
|
293
296
|
throw new TypeError('maxRedirects must be a non-negative integer.');
|
|
297
|
+
const stripped = new Set([
|
|
298
|
+
...crossOriginHeaders,
|
|
299
|
+
...IdentityHeaders.request,
|
|
300
|
+
...(identity?.headers ?? []),
|
|
301
|
+
]);
|
|
294
302
|
let request = new Request(input, { ...init, redirect: 'manual' });
|
|
295
303
|
const explicitAcceptPayment = request.headers.has(Constants.Headers.acceptPayment);
|
|
296
304
|
let body = await replayBody(request, init?.body);
|
|
297
305
|
const redirects = [];
|
|
298
306
|
for (;;) {
|
|
299
307
|
request = withAcceptPayment(request, acceptPayment, explicitAcceptPayment, acceptPaymentPolicy);
|
|
300
|
-
const { request: sentRequest, response } = await (async () => {
|
|
308
|
+
const { request: sentRequest, response, headers: identityHeaders, } = await (async () => {
|
|
301
309
|
// `request` stays unread for replay; the reported request is the one actually sent.
|
|
302
310
|
if (identity)
|
|
303
311
|
return identity.send(fetch, request.clone());
|
|
304
312
|
const sent = request.clone();
|
|
305
|
-
return { request: sent, response: await fetch(sent) };
|
|
313
|
+
return { request: sent, response: await fetch(sent), headers: [] };
|
|
306
314
|
})();
|
|
307
315
|
if (response.type === 'opaqueredirect' || response.status === 0)
|
|
308
316
|
throw new Error('prepareRequest requires a runtime that exposes manual redirect responses.');
|
|
309
317
|
if (!redirectStatuses.has(response.status))
|
|
310
318
|
return {
|
|
311
319
|
body,
|
|
320
|
+
identityHeaders,
|
|
312
321
|
replayRequest: request,
|
|
313
322
|
request: sentRequest,
|
|
314
323
|
response,
|
|
@@ -318,6 +327,7 @@ async function prepareHttpRequest(parameters) {
|
|
|
318
327
|
if (!location)
|
|
319
328
|
return {
|
|
320
329
|
body,
|
|
330
|
+
identityHeaders,
|
|
321
331
|
replayRequest: request,
|
|
322
332
|
request: sentRequest,
|
|
323
333
|
response,
|
|
@@ -346,7 +356,7 @@ async function prepareHttpRequest(parameters) {
|
|
|
346
356
|
if (from.origin !== to.origin)
|
|
347
357
|
for (const header of [...headers.keys()]) {
|
|
348
358
|
const value = headers.get(header) ?? '';
|
|
349
|
-
if (
|
|
359
|
+
if (stripped.has(header) || value.startsWith('Payment '))
|
|
350
360
|
headers.delete(header);
|
|
351
361
|
}
|
|
352
362
|
redirects.push(Object.freeze({ from: from.href, status: response.status, to: to.href }));
|
|
@@ -118,15 +118,18 @@ export function from(config) {
|
|
|
118
118
|
// which can duplicate retries and make restore semantics fragile.
|
|
119
119
|
const baseFetch = unwrapFetch(fetch);
|
|
120
120
|
const send = async (input, init, context) => identity
|
|
121
|
-
?
|
|
122
|
-
: baseFetch(input, init);
|
|
121
|
+
? identity.send(baseFetch, new Request(input, init), context)
|
|
122
|
+
: { response: await baseFetch(input, init), headers: [] };
|
|
123
123
|
const request = async (input, init, canRefetch) => {
|
|
124
124
|
const callerHeaders = getCallerHeaders(input, init?.headers);
|
|
125
125
|
const hasExplicitAcceptPayment = callerHeaders.has(Constants.Headers.acceptPayment);
|
|
126
126
|
const paymentPreferences = resolvePaymentPreferences(callerHeaders, resolvedAcceptPayment);
|
|
127
127
|
const capturedBody = captureRequestBody(input, init, callerHeaders);
|
|
128
128
|
const initialRequest = prepareInitialRequest(input, init, callerHeaders, paymentPreferences.header, hasExplicitAcceptPayment, acceptPaymentPolicy);
|
|
129
|
-
|
|
129
|
+
const first = await send(cloneRequestInput(initialRequest.input), initialRequest.init);
|
|
130
|
+
let response = first.response;
|
|
131
|
+
// Retry headers from the unpaid attempt (such as an attestation) go on the paid attempt too.
|
|
132
|
+
const identityHeaders = first.headers;
|
|
130
133
|
const transportRequest = withCapturedBody(initialRequest.init, await capturedBody);
|
|
131
134
|
if (init?.[skipPayment])
|
|
132
135
|
return response;
|
|
@@ -261,14 +264,15 @@ export function from(config) {
|
|
|
261
264
|
transactionHash: MethodResponse.getTransactionHash(selected.method, credential),
|
|
262
265
|
});
|
|
263
266
|
try {
|
|
264
|
-
|
|
267
|
+
;
|
|
268
|
+
({ response } = await send(paymentInput, {
|
|
265
269
|
...transport.setCredential({
|
|
266
270
|
...fetchInit,
|
|
267
271
|
headers: initialRequest.headers,
|
|
268
272
|
}, credential, { challenge: selectedChallenge }),
|
|
269
273
|
// Runtimes do not strip custom payment headers on cross-origin redirects.
|
|
270
274
|
redirect: 'manual',
|
|
271
|
-
}, { challenge: selectedChallenge });
|
|
275
|
+
}, { challenge: selectedChallenge, headers: identityHeaders }));
|
|
272
276
|
}
|
|
273
277
|
catch (cause) {
|
|
274
278
|
outcomeUnknown = unknownOutcome(cause);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Values shared by every MPP identity attestation. */
|
|
2
|
+
export declare const Constants: {
|
|
3
|
+
/** Request header carrying one or more attestations, separated by commas. */
|
|
4
|
+
readonly header: 'Identity-Attestation';
|
|
5
|
+
/** Response header listing the attestations a route requires, as a structured list. */
|
|
6
|
+
readonly requiredHeader: 'Identity-Attestation-Required';
|
|
7
|
+
/** JWS `typ` header of an attestation. */
|
|
8
|
+
readonly tokenType: 'mpp-attestation+jwt';
|
|
9
|
+
/** JWS algorithm of an attestation: EdDSA over Ed25519. */
|
|
10
|
+
readonly algorithm: 'EdDSA';
|
|
11
|
+
/** Path of the issuer's JSON Web Key Set, relative to the issuer URL. */
|
|
12
|
+
readonly jwksPath: '/.well-known/jwks.json';
|
|
13
|
+
/** Clock tolerance, in seconds, applied to `iat` and `exp`. */
|
|
14
|
+
readonly clockTolerance: 60;
|
|
15
|
+
/**
|
|
16
|
+
* Seconds before expiry at which a client stops sending an attestation on unpaid attempts and
|
|
17
|
+
* replaces it, capped at half the attestation's lifetime.
|
|
18
|
+
*/
|
|
19
|
+
readonly refreshMargin: 300;
|
|
20
|
+
/** Longest attestation accepted, in characters. */
|
|
21
|
+
readonly maxLength: 8192;
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=Constants.d.ts.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Values shared by every MPP identity attestation. */
|
|
2
|
+
export const Constants = {
|
|
3
|
+
/** Request header carrying one or more attestations, separated by commas. */
|
|
4
|
+
header: 'Identity-Attestation',
|
|
5
|
+
/** Response header listing the attestations a route requires, as a structured list. */
|
|
6
|
+
requiredHeader: 'Identity-Attestation-Required',
|
|
7
|
+
/** JWS `typ` header of an attestation. */
|
|
8
|
+
tokenType: 'mpp-attestation+jwt',
|
|
9
|
+
/** JWS algorithm of an attestation: EdDSA over Ed25519. */
|
|
10
|
+
algorithm: 'EdDSA',
|
|
11
|
+
/** Path of the issuer's JSON Web Key Set, relative to the issuer URL. */
|
|
12
|
+
jwksPath: '/.well-known/jwks.json',
|
|
13
|
+
/** Clock tolerance, in seconds, applied to `iat` and `exp`. */
|
|
14
|
+
clockTolerance: 60,
|
|
15
|
+
/**
|
|
16
|
+
* Seconds before expiry at which a client stops sending an attestation on unpaid attempts and
|
|
17
|
+
* replaces it, capped at half the attestation's lifetime.
|
|
18
|
+
*/
|
|
19
|
+
refreshMargin: 300,
|
|
20
|
+
/** Longest attestation accepted, in characters. */
|
|
21
|
+
maxLength: 8_192,
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=Constants.js.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type * as Types from './Types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a key resolver that reads an issuer's JSON Web Key Set.
|
|
4
|
+
*
|
|
5
|
+
* Fetches `<issuer>/.well-known/jwks.json` and caches its Ed25519 keys for
|
|
6
|
+
* `ttl` seconds. An unknown key ID refetches the set at most once every
|
|
7
|
+
* `refreshInterval` seconds per issuer, and concurrent lookups share one fetch,
|
|
8
|
+
* so callers cannot trigger a fetch per request. While the issuer is
|
|
9
|
+
* unreachable, the last key set fetched successfully keeps verifying for up to
|
|
10
|
+
* `maxStale` seconds after it was fetched; after that, verification fails closed.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolver(options?: resolver.Options): Types.KeyResolver;
|
|
13
|
+
export declare namespace resolver {
|
|
14
|
+
type Options = {
|
|
15
|
+
/** Fetch implementation. @default globalThis.fetch */
|
|
16
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
17
|
+
/** Seconds a fetched key set is cached. @default 300 */
|
|
18
|
+
readonly ttl?: number | undefined;
|
|
19
|
+
/** Seconds before a key set fetch is abandoned. @default 5 */
|
|
20
|
+
readonly timeout?: number | undefined;
|
|
21
|
+
/** Minimum seconds between refetches for an unknown key ID, per issuer. @default 30 */
|
|
22
|
+
readonly refreshInterval?: number | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Seconds after its fetch that the last good key set keeps verifying while
|
|
25
|
+
* the issuer is unreachable, so a rotated-out key stops working. @default 3600
|
|
26
|
+
*/
|
|
27
|
+
readonly maxStale?: number | undefined;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=Jwks.d.ts.map
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { unwrapFetch } from '../../../client/internal/Fetch.js';
|
|
2
|
+
import { Constants } from './Constants.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a key resolver that reads an issuer's JSON Web Key Set.
|
|
5
|
+
*
|
|
6
|
+
* Fetches `<issuer>/.well-known/jwks.json` and caches its Ed25519 keys for
|
|
7
|
+
* `ttl` seconds. An unknown key ID refetches the set at most once every
|
|
8
|
+
* `refreshInterval` seconds per issuer, and concurrent lookups share one fetch,
|
|
9
|
+
* so callers cannot trigger a fetch per request. While the issuer is
|
|
10
|
+
* unreachable, the last key set fetched successfully keeps verifying for up to
|
|
11
|
+
* `maxStale` seconds after it was fetched; after that, verification fails closed.
|
|
12
|
+
*/
|
|
13
|
+
export function resolver(options = {}) {
|
|
14
|
+
const ttl = (options.ttl ?? 300) * 1_000;
|
|
15
|
+
const refreshInterval = (options.refreshInterval ?? 30) * 1_000;
|
|
16
|
+
const maxStale = (options.maxStale ?? 3_600) * 1_000;
|
|
17
|
+
const timeout = (options.timeout ?? 5) * 1_000;
|
|
18
|
+
// Unwrapped, so an issuer's 402 is never paid in a process that also runs the client.
|
|
19
|
+
const fetch = unwrapFetch(options.fetch ?? globalThis.fetch);
|
|
20
|
+
// The newest fetch per issuer, started at `startedAt`; shared by concurrent lookups.
|
|
21
|
+
const sets = new Map();
|
|
22
|
+
// The last set fetched successfully per issuer, served while a refetch fails.
|
|
23
|
+
const good = new Map();
|
|
24
|
+
function load(issuer) {
|
|
25
|
+
const startedAt = Date.now();
|
|
26
|
+
const keys = (async () => {
|
|
27
|
+
const response = await fetch(`${issuer.replace(/\/+$/, '')}${Constants.jwksPath}`, {
|
|
28
|
+
headers: { accept: 'application/json' },
|
|
29
|
+
signal: AbortSignal.timeout(timeout),
|
|
30
|
+
// Workers reject 'error'; a redirect is not ok, so it fails below.
|
|
31
|
+
redirect: 'manual',
|
|
32
|
+
});
|
|
33
|
+
if (!response.ok)
|
|
34
|
+
throw new Error(`JWKS request failed with ${response.status}.`);
|
|
35
|
+
const body = (await response.json());
|
|
36
|
+
// A body without a key list is a failed fetch, so it never replaces the last good set.
|
|
37
|
+
if (!body || !Array.isArray(body.keys))
|
|
38
|
+
throw new Error('JWKS response has no keys list.');
|
|
39
|
+
const result = new Map();
|
|
40
|
+
for (const jwk of body.keys) {
|
|
41
|
+
if (!jwk || typeof jwk !== 'object')
|
|
42
|
+
continue;
|
|
43
|
+
const { alg, crv, key_ops, kid, kty, use, x } = jwk;
|
|
44
|
+
if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || typeof kid !== 'string')
|
|
45
|
+
continue;
|
|
46
|
+
// Honor the issuer's restrictions on what the key may do.
|
|
47
|
+
if (use !== undefined && use !== 'sig')
|
|
48
|
+
continue;
|
|
49
|
+
if (alg !== undefined && alg !== 'EdDSA' && alg !== 'Ed25519')
|
|
50
|
+
continue;
|
|
51
|
+
if (key_ops !== undefined && !(Array.isArray(key_ops) && key_ops.includes('verify')))
|
|
52
|
+
continue;
|
|
53
|
+
// A malformed key is skipped, so it cannot take the issuer's other keys down.
|
|
54
|
+
try {
|
|
55
|
+
result.set(kid, await crypto.subtle.importKey('jwk', { crv, kty, x }, { name: 'Ed25519' }, true, [
|
|
56
|
+
'verify',
|
|
57
|
+
]));
|
|
58
|
+
}
|
|
59
|
+
catch { }
|
|
60
|
+
}
|
|
61
|
+
good.set(issuer, { fetchedAt: startedAt, keys: result });
|
|
62
|
+
return result;
|
|
63
|
+
})();
|
|
64
|
+
const entry = { failed: false, startedAt, keys };
|
|
65
|
+
// A failed fetch is retried after `refreshInterval` rather than cached for `ttl`.
|
|
66
|
+
keys.catch(() => {
|
|
67
|
+
entry.failed = true;
|
|
68
|
+
});
|
|
69
|
+
sets.set(issuer, entry);
|
|
70
|
+
return entry;
|
|
71
|
+
}
|
|
72
|
+
/** The newest fetch, or one started now if the newest is older than `age`. */
|
|
73
|
+
function current(issuer, age) {
|
|
74
|
+
const entry = sets.get(issuer);
|
|
75
|
+
const limit = entry?.failed ? Math.min(age, refreshInterval) : age;
|
|
76
|
+
return entry && Date.now() - entry.startedAt <= limit ? entry : load(issuer);
|
|
77
|
+
}
|
|
78
|
+
/** Awaits a fetch, falling back to the last good set while it is within `maxStale`. */
|
|
79
|
+
async function keysOf(issuer, entry) {
|
|
80
|
+
try {
|
|
81
|
+
return await entry.keys;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
const last = good.get(issuer);
|
|
85
|
+
if (last && Date.now() - last.fetchedAt <= maxStale)
|
|
86
|
+
return last.keys;
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return async ({ issuer, keyId }) => {
|
|
91
|
+
// A known key in a set fetched within `ttl` is served at once, so a refetch
|
|
92
|
+
// an unknown key ID started does not hold up other lookups.
|
|
93
|
+
const last = good.get(issuer);
|
|
94
|
+
if (last && Date.now() - last.fetchedAt <= ttl && last.keys.has(keyId))
|
|
95
|
+
return last.keys.get(keyId);
|
|
96
|
+
const keys = await keysOf(issuer, current(issuer, ttl));
|
|
97
|
+
if (keys.has(keyId))
|
|
98
|
+
return keys.get(keyId);
|
|
99
|
+
// An unknown key ID: join the newest fetch, or start one if it is old enough.
|
|
100
|
+
// If that fetch fails, a stale set cannot say the key is unknown (it may be
|
|
101
|
+
// newly rotated in), so the outage is thrown and answered with 503.
|
|
102
|
+
const entry = current(issuer, refreshInterval);
|
|
103
|
+
try {
|
|
104
|
+
return (await entry.keys).get(keyId);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
const stale = good.get(issuer);
|
|
108
|
+
if (stale && Date.now() - stale.fetchedAt <= maxStale && stale.keys.has(keyId))
|
|
109
|
+
return stale.keys.get(keyId);
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=Jwks.js.map
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type * as Types from './Types.js';
|
|
2
|
+
/** A decoded, unverified attestation. */
|
|
3
|
+
export type Decoded = {
|
|
4
|
+
/** JWS protected header. */
|
|
5
|
+
readonly header: {
|
|
6
|
+
readonly alg?: unknown;
|
|
7
|
+
readonly kid?: unknown;
|
|
8
|
+
readonly typ?: unknown;
|
|
9
|
+
};
|
|
10
|
+
/** Unverified claims. */
|
|
11
|
+
readonly claims: Partial<Types.Claims> & Readonly<Record<string, unknown>>;
|
|
12
|
+
/** The signed bytes: `base64url(header) + '.' + base64url(claims)`. */
|
|
13
|
+
readonly signingInput: Uint8Array;
|
|
14
|
+
/** Signature bytes. */
|
|
15
|
+
readonly signature: Uint8Array;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The outcome of {@link verify}: `unavailable` when the issuer's keys could not be fetched,
|
|
19
|
+
* which says nothing about the token.
|
|
20
|
+
*/
|
|
21
|
+
export type VerifyResult = {
|
|
22
|
+
readonly status: 'valid';
|
|
23
|
+
readonly claims: Types.Claims;
|
|
24
|
+
} | {
|
|
25
|
+
readonly status: 'invalid' | 'unavailable';
|
|
26
|
+
readonly reason: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Signs attestation claims as a compact JWS (EdDSA over Ed25519).
|
|
30
|
+
*
|
|
31
|
+
* For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
|
|
32
|
+
* published in the issuer's JSON Web Key Set.
|
|
33
|
+
*/
|
|
34
|
+
export declare function sign(claims: Types.Claims, options: {
|
|
35
|
+
readonly key: CryptoKey;
|
|
36
|
+
readonly keyId: string;
|
|
37
|
+
}): Promise<string>;
|
|
38
|
+
/** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
|
|
39
|
+
export declare function decode(token: string): Decoded | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Verifies an attestation's signature and claims.
|
|
42
|
+
*
|
|
43
|
+
* Checks the EdDSA algorithm and `typ`, the issuer, audience and type, and the
|
|
44
|
+
* `iat` and `exp` times (with `clockTolerance`), then the signature with the
|
|
45
|
+
* key `keyResolver` returns for the header's `kid`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function verify(token: string, options: verify.Options): Promise<VerifyResult>;
|
|
48
|
+
export declare namespace verify {
|
|
49
|
+
type Options = {
|
|
50
|
+
/** Accepted attestation type, such as `email`. */
|
|
51
|
+
readonly type: string;
|
|
52
|
+
/** Trusted issuer URL. */
|
|
53
|
+
readonly issuer: string;
|
|
54
|
+
/** Origin the attestation must be bound to. */
|
|
55
|
+
readonly audience: string;
|
|
56
|
+
/** Resolves the issuer's public key by key ID. */
|
|
57
|
+
readonly keyResolver: Types.KeyResolver;
|
|
58
|
+
/** Oldest accepted `iat`, in seconds before now. Defaults to the attestation's own `exp`. */
|
|
59
|
+
readonly maxAge?: number | undefined;
|
|
60
|
+
/** Clock tolerance in seconds. @default 60 */
|
|
61
|
+
readonly clockTolerance?: number | undefined;
|
|
62
|
+
/** Current Unix time in seconds, for tests. */
|
|
63
|
+
readonly now?: number | undefined;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** Splits an `Identity-Attestation` header value into its attestations. */
|
|
67
|
+
export declare function parseHeader(value: string | null): readonly string[];
|
|
68
|
+
/**
|
|
69
|
+
* Throws a `TypeError` unless `clockTolerance`, `maxAge` and `now` are each absent or a
|
|
70
|
+
* non-negative integer of seconds: `NaN` or `Infinity` would turn the time checks off.
|
|
71
|
+
* @internal
|
|
72
|
+
*/
|
|
73
|
+
export declare function assertTimes(options: {
|
|
74
|
+
readonly clockTolerance?: number | undefined;
|
|
75
|
+
readonly maxAge?: number | undefined;
|
|
76
|
+
readonly now?: number | undefined;
|
|
77
|
+
}): void;
|
|
78
|
+
/** Accepts https issuers, and http only on localhost for development. */
|
|
79
|
+
export declare function isIssuer(value: string): boolean;
|
|
80
|
+
//# sourceMappingURL=Token.d.ts.map
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { Base64 } from 'ox';
|
|
2
|
+
import { Constants } from './Constants.js';
|
|
3
|
+
/**
|
|
4
|
+
* Signs attestation claims as a compact JWS (EdDSA over Ed25519).
|
|
5
|
+
*
|
|
6
|
+
* For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
|
|
7
|
+
* published in the issuer's JSON Web Key Set.
|
|
8
|
+
*/
|
|
9
|
+
export async function sign(claims, options) {
|
|
10
|
+
const header = { alg: Constants.algorithm, kid: options.keyId, typ: Constants.tokenType };
|
|
11
|
+
const input = `${encode(header)}.${encode(claims)}`;
|
|
12
|
+
const signature = await crypto.subtle.sign({ name: 'Ed25519' }, options.key, new TextEncoder().encode(input));
|
|
13
|
+
return `${input}.${Base64.fromBytes(new Uint8Array(signature), { pad: false, url: true })}`;
|
|
14
|
+
}
|
|
15
|
+
/** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
|
|
16
|
+
export function decode(token) {
|
|
17
|
+
if (token.length > Constants.maxLength)
|
|
18
|
+
return undefined;
|
|
19
|
+
const parts = token.split('.');
|
|
20
|
+
if (parts.length !== 3 || parts.some((part) => !/^[A-Za-z0-9_-]+$/.test(part)))
|
|
21
|
+
return undefined;
|
|
22
|
+
try {
|
|
23
|
+
const header = JSON.parse(Base64.toString(parts[0]));
|
|
24
|
+
const claims = JSON.parse(Base64.toString(parts[1]));
|
|
25
|
+
if (!isObject(header) || !isObject(claims))
|
|
26
|
+
return undefined;
|
|
27
|
+
return {
|
|
28
|
+
header,
|
|
29
|
+
claims,
|
|
30
|
+
signingInput: new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
|
|
31
|
+
signature: Base64.toBytes(parts[2]),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Verifies an attestation's signature and claims.
|
|
40
|
+
*
|
|
41
|
+
* Checks the EdDSA algorithm and `typ`, the issuer, audience and type, and the
|
|
42
|
+
* `iat` and `exp` times (with `clockTolerance`), then the signature with the
|
|
43
|
+
* key `keyResolver` returns for the header's `kid`.
|
|
44
|
+
*/
|
|
45
|
+
export async function verify(token, options) {
|
|
46
|
+
assertTimes(options);
|
|
47
|
+
const decoded = decode(token);
|
|
48
|
+
if (!decoded)
|
|
49
|
+
return invalid('The attestation is malformed.');
|
|
50
|
+
const { header, claims } = decoded;
|
|
51
|
+
if (header.alg !== Constants.algorithm)
|
|
52
|
+
return invalid('The attestation algorithm is not EdDSA.');
|
|
53
|
+
if (header.typ !== Constants.tokenType)
|
|
54
|
+
return invalid('The attestation type header is wrong.');
|
|
55
|
+
if (typeof header.kid !== 'string' || header.kid === '')
|
|
56
|
+
return invalid('The attestation has no key ID.');
|
|
57
|
+
if (claims.iss !== options.issuer)
|
|
58
|
+
return invalid('The attestation issuer is not trusted.');
|
|
59
|
+
if (claims.type !== options.type)
|
|
60
|
+
return invalid('The attestation type is not accepted.');
|
|
61
|
+
if (claims.aud !== options.audience)
|
|
62
|
+
return invalid('The attestation is for another audience.');
|
|
63
|
+
if (typeof claims.sub !== 'string' || claims.sub === '')
|
|
64
|
+
return invalid('The attestation has no subject.');
|
|
65
|
+
if (claims.jti !== undefined && typeof claims.jti !== 'string')
|
|
66
|
+
return invalid('The attestation ID is malformed.');
|
|
67
|
+
if (!isTime(claims.iat) || !isTime(claims.exp))
|
|
68
|
+
return invalid('The attestation times are malformed.');
|
|
69
|
+
const now = options.now ?? Math.floor(Date.now() / 1_000);
|
|
70
|
+
const tolerance = options.clockTolerance ?? Constants.clockTolerance;
|
|
71
|
+
if (claims.exp <= now - tolerance)
|
|
72
|
+
return invalid('The attestation has expired.');
|
|
73
|
+
if (claims.iat > now + tolerance)
|
|
74
|
+
return invalid('The attestation was issued in the future.');
|
|
75
|
+
if (options.maxAge !== undefined && now - claims.iat > options.maxAge + tolerance)
|
|
76
|
+
return invalid('The attestation is too old.');
|
|
77
|
+
let key;
|
|
78
|
+
try {
|
|
79
|
+
key = await options.keyResolver({ issuer: options.issuer, keyId: header.kid });
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// The issuer's keys are unreachable, which says nothing about the token.
|
|
83
|
+
return { status: 'unavailable', reason: 'The attestation key could not be resolved.' };
|
|
84
|
+
}
|
|
85
|
+
if (!key)
|
|
86
|
+
return invalid('No public key is available for the attestation key ID.');
|
|
87
|
+
let valid = false;
|
|
88
|
+
try {
|
|
89
|
+
valid = await crypto.subtle.verify({ name: 'Ed25519' }, key, decoded.signature, decoded.signingInput);
|
|
90
|
+
}
|
|
91
|
+
catch { }
|
|
92
|
+
if (!valid)
|
|
93
|
+
return invalid('The attestation signature is invalid.');
|
|
94
|
+
return { status: 'valid', claims: Object.freeze({ ...claims }) };
|
|
95
|
+
}
|
|
96
|
+
/** Splits an `Identity-Attestation` header value into its attestations. */
|
|
97
|
+
export function parseHeader(value) {
|
|
98
|
+
if (!value)
|
|
99
|
+
return [];
|
|
100
|
+
return value
|
|
101
|
+
.split(',')
|
|
102
|
+
.map((token) => token.trim())
|
|
103
|
+
.filter(Boolean);
|
|
104
|
+
}
|
|
105
|
+
function encode(value) {
|
|
106
|
+
return Base64.fromString(JSON.stringify(value), { pad: false, url: true });
|
|
107
|
+
}
|
|
108
|
+
function invalid(reason) {
|
|
109
|
+
return { status: 'invalid', reason };
|
|
110
|
+
}
|
|
111
|
+
function isObject(value) {
|
|
112
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Throws a `TypeError` unless `clockTolerance`, `maxAge` and `now` are each absent or a
|
|
116
|
+
* non-negative integer of seconds: `NaN` or `Infinity` would turn the time checks off.
|
|
117
|
+
* @internal
|
|
118
|
+
*/
|
|
119
|
+
export function assertTimes(options) {
|
|
120
|
+
for (const [name, value] of [
|
|
121
|
+
['clockTolerance', options.clockTolerance],
|
|
122
|
+
['maxAge', options.maxAge],
|
|
123
|
+
['now', options.now],
|
|
124
|
+
])
|
|
125
|
+
if (value !== undefined && !isTime(value))
|
|
126
|
+
throw new TypeError(`Attestation ${name} must be a non-negative integer of seconds.`);
|
|
127
|
+
}
|
|
128
|
+
function isTime(value) {
|
|
129
|
+
// Bounded by the largest time a Date holds, so every accepted time converts to a valid Date.
|
|
130
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= maxTime;
|
|
131
|
+
}
|
|
132
|
+
/** Latest time, in Unix seconds, that a JavaScript Date can represent. */
|
|
133
|
+
const maxTime = 8_640_000_000_000;
|
|
134
|
+
/** Accepts https issuers, and http only on localhost for development. */
|
|
135
|
+
export function isIssuer(value) {
|
|
136
|
+
if (!URL.canParse(value))
|
|
137
|
+
return false;
|
|
138
|
+
const url = new URL(value);
|
|
139
|
+
if (url.protocol === 'https:')
|
|
140
|
+
return true;
|
|
141
|
+
return url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=Token.js.map
|