mppx 0.17.5 → 0.17.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli/cli.js +14 -12
  3. package/dist/cli/stripe.d.ts +6 -1
  4. package/dist/cli/stripe.js +89 -5
  5. package/dist/client/Mppx.js +1 -0
  6. package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
  7. package/dist/extensions/identity/email-otp/Constants.js +16 -0
  8. package/dist/extensions/identity/email-otp/Types.d.ts +12 -0
  9. package/dist/extensions/identity/email-otp/Types.js +2 -0
  10. package/dist/extensions/identity/email-otp/client/index.d.ts +116 -0
  11. package/dist/extensions/identity/email-otp/client/index.js +119 -0
  12. package/dist/extensions/identity/email-otp/index.d.ts +17 -0
  13. package/dist/extensions/identity/email-otp/index.js +16 -0
  14. package/dist/extensions/identity/email-otp/internal/Attestation.d.ts +66 -0
  15. package/dist/extensions/identity/email-otp/internal/Attestation.js +128 -0
  16. package/dist/extensions/identity/email-otp/internal/Constants.d.ts +20 -0
  17. package/dist/extensions/identity/email-otp/internal/Constants.js +20 -0
  18. package/dist/extensions/identity/email-otp/internal/Jwks.d.ts +30 -0
  19. package/dist/extensions/identity/email-otp/internal/Jwks.js +114 -0
  20. package/dist/extensions/identity/email-otp/internal/Prover.d.ts +46 -0
  21. package/dist/extensions/identity/email-otp/internal/Prover.js +168 -0
  22. package/dist/extensions/identity/email-otp/internal/Types.d.ts +48 -0
  23. package/dist/extensions/identity/email-otp/internal/Types.js +2 -0
  24. package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +56 -0
  25. package/dist/extensions/identity/email-otp/internal/Verifier.js +116 -0
  26. package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
  27. package/dist/extensions/identity/email-otp/server/index.js +56 -0
  28. package/dist/extensions/identity/index.d.ts +2 -0
  29. package/dist/extensions/identity/index.js +2 -0
  30. package/dist/identity/Callback.d.ts +47 -0
  31. package/dist/identity/Callback.js +64 -0
  32. package/dist/identity/index.d.ts +1 -0
  33. package/dist/identity/index.js +1 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/proxy/internal/Headers.js +2 -0
  37. package/dist/tempo/server/internal/html.gen.js +1 -1
  38. package/package.json +5 -1
@@ -38,7 +38,12 @@ export declare namespace readStripeCliKey {
38
38
  projectName?: string | undefined;
39
39
  };
40
40
  }
41
- /** Sets `key=value` in a dotenv file, replacing an existing assignment or appending one. */
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
@@ -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
- /** Sets `key=value` in a dotenv file, replacing an existing assignment or appending one. */
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(`^(?:export\\s+)?${key}\\s*=.*$`, 'm');
130
- if (pattern.test(existing))
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
- fs.writeFileSync(file, `${existing}${separator}${line}\n`);
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
@@ -282,6 +282,7 @@ const crossOriginHeaders = [
282
282
  'cookie',
283
283
  'cookie2',
284
284
  'host',
285
+ 'identity-attestation',
285
286
  'payment-authorization',
286
287
  'payment-signature',
287
288
  'proxy-authorization',
@@ -0,0 +1,16 @@
1
+ /** Email OTP attestation values. */
2
+ export declare const Constants: {
3
+ /** Request header carrying the email attestation. */
4
+ readonly header: 'Identity-Attestation';
5
+ /** Response header naming the issuer to get an attestation from. */
6
+ readonly requiredHeader: 'Identity-Attestation-Required';
7
+ /** Attestation type for a verified email address. */
8
+ readonly type: 'email';
9
+ /** Issuer path that emails a one-time code. */
10
+ readonly otpPath: '/email/otp';
11
+ /** Issuer path that exchanges a one-time code for an attestation. */
12
+ readonly verifyPath: '/email/verify';
13
+ /** Times the prover asks for a code before giving up. */
14
+ readonly codeAttempts: 3;
15
+ };
16
+ //# sourceMappingURL=Constants.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Email OTP attestation values. */
2
+ export const Constants = {
3
+ /** Request header carrying the email attestation. */
4
+ header: 'Identity-Attestation',
5
+ /** Response header naming the issuer to get an attestation from. */
6
+ requiredHeader: 'Identity-Attestation-Required',
7
+ /** Attestation type for a verified email address. */
8
+ type: 'email',
9
+ /** Issuer path that emails a one-time code. */
10
+ otpPath: '/email/otp',
11
+ /** Issuer path that exchanges a one-time code for an attestation. */
12
+ verifyPath: '/email/verify',
13
+ /** Times the prover asks for a code before giving up. */
14
+ codeAttempts: 3,
15
+ };
16
+ //# sourceMappingURL=Constants.js.map
@@ -0,0 +1,12 @@
1
+ /** A verified email address. */
2
+ export type VerifiedEmail = {
3
+ /** The email address the issuer sent a one-time code to, lowercased. */
4
+ email: string;
5
+ /** Issuer URL. */
6
+ issuer: string;
7
+ /** When the attestation expires. */
8
+ expiresAt: Date;
9
+ /** Attestation identifier (`jti`), if the issuer set one. */
10
+ id?: string | undefined;
11
+ };
12
+ //# sourceMappingURL=Types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Types.js.map
@@ -0,0 +1,116 @@
1
+ import type * as Identity from '../../../../identity/Types.js';
2
+ import type { MaybePromise } from '../../../../internal/types.js';
3
+ /**
4
+ * Asks an issuer to email a one-time code for `audience`.
5
+ *
6
+ * Returns the code request's `id`, which {@link verifyCode} exchanges, with the code, for an attestation.
7
+ */
8
+ export declare function sendCode(parameters: sendCode.Parameters): Promise<sendCode.ReturnType>;
9
+ export declare namespace sendCode {
10
+ type Parameters = {
11
+ /** Issuer URL. */
12
+ issuer: string;
13
+ /** Email address to send the code to. */
14
+ email: string;
15
+ /** Origin of the server the attestation is for. */
16
+ audience: string;
17
+ /** Fetch implementation. @default globalThis.fetch */
18
+ fetch?: typeof globalThis.fetch | undefined;
19
+ };
20
+ type ReturnType = {
21
+ id: string;
22
+ expiresAt: Date;
23
+ };
24
+ }
25
+ /** Exchanges an emailed one-time code for an email attestation. */
26
+ export declare function verifyCode(parameters: verifyCode.Parameters): Promise<verifyCode.ReturnType>;
27
+ export declare namespace verifyCode {
28
+ type Parameters = {
29
+ /** Issuer URL. */
30
+ issuer: string;
31
+ /** Code request ID from {@link sendCode}. */
32
+ id: string;
33
+ /** The code from the email. */
34
+ code: string;
35
+ /** Fetch implementation. @default globalThis.fetch */
36
+ fetch?: typeof globalThis.fetch | undefined;
37
+ };
38
+ type ReturnType = {
39
+ attestation: string;
40
+ expiresAt: Date;
41
+ };
42
+ }
43
+ /**
44
+ * Creates a prover that verifies an email address when a server asks for one.
45
+ *
46
+ * When a server answers with `Identity-Attestation-Required: email;issuer="…"`,
47
+ * the prover asks the issuer to email a code to `email`, gets the code from
48
+ * `code` (such as a terminal prompt or a form), exchanges it for an
49
+ * attestation bound to the server's origin and sends the request again with it.
50
+ * Later requests to that origin reuse it until it expires.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * const mppx = Mppx.create({
55
+ * identity: [
56
+ * EmailOtp.Client.prover({
57
+ * code: () => prompt('Code:'),
58
+ * email: 'me@example.com',
59
+ * issuers: ['https://issuer.example'],
60
+ * scope: '*',
61
+ * }),
62
+ * ],
63
+ * methods: [tempo({ account })],
64
+ * })
65
+ * ```
66
+ */
67
+ export declare function prover(config: prover.Config): Identity.Prover;
68
+ export declare namespace prover {
69
+ type Config = {
70
+ /** Origins that may ask for and receive the attestation, or `'*'` for any origin. */
71
+ scope: Identity.Prover['scope'];
72
+ /** Email address to verify, or a function that returns it (or `undefined` to decline). */
73
+ email: string | ((parameters: {
74
+ audience: string;
75
+ issuer: string;
76
+ }) => MaybePromise<string | undefined>);
77
+ /** Returns the code the user received, or `undefined` to give up. */
78
+ code: (parameters: {
79
+ /** Origin the attestation is for. */
80
+ audience: string;
81
+ /** Email address the code was sent to. */
82
+ email: string;
83
+ /** Issuer URL. */
84
+ issuer: string;
85
+ /** Code request ID. */
86
+ id: string;
87
+ /** When the code expires. */
88
+ expiresAt: Date;
89
+ /** 1 for the first prompt, higher after a rejected code. */
90
+ attempt: number;
91
+ /** Why the previous code was rejected. */
92
+ error?: Error | undefined;
93
+ }) => MaybePromise<string | undefined>;
94
+ /** Attestations obtained beforehand, such as from the issuer with curl. */
95
+ attestations?: readonly string[] | undefined;
96
+ /**
97
+ * Issuers the prover may send the email address to, such as `['https://identity.mpp.tempo.xyz']`.
98
+ *
99
+ * A server only names the issuer it wants; an untrusted one could relay a code
100
+ * and obtain an attestation for another server.
101
+ */
102
+ issuers: readonly string[];
103
+ /** Fetch used to call the issuer. @default globalThis.fetch */
104
+ fetch?: typeof globalThis.fetch | undefined;
105
+ };
106
+ }
107
+ /** An issuer rejected an email OTP request. */
108
+ export declare class EmailOtpError extends Error {
109
+ readonly name = "EmailOtpError";
110
+ /** HTTP status the issuer answered with, if any. */
111
+ readonly status: number | undefined;
112
+ constructor(message: string, options?: {
113
+ status?: number | undefined;
114
+ });
115
+ }
116
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,119 @@
1
+ import { unwrapFetch } from '../../../../client/internal/Fetch.js';
2
+ import { Constants } from '../Constants.js';
3
+ import { isIssuer } from '../internal/Attestation.js';
4
+ import * as Attestation from '../internal/Prover.js';
5
+ /**
6
+ * Asks an issuer to email a one-time code for `audience`.
7
+ *
8
+ * Returns the code request's `id`, which {@link verifyCode} exchanges, with the code, for an attestation.
9
+ */
10
+ export async function sendCode(parameters) {
11
+ const body = await post(parameters.issuer, Constants.otpPath, parameters.fetch, {
12
+ audience: parameters.audience,
13
+ email: parameters.email,
14
+ });
15
+ const expiresAt = date(body.expires_at);
16
+ if (typeof body.id !== 'string' || body.id === '' || !expiresAt)
17
+ throw new EmailOtpError('The issuer returned a malformed code request.');
18
+ return { expiresAt, id: body.id };
19
+ }
20
+ /** Exchanges an emailed one-time code for an email attestation. */
21
+ export async function verifyCode(parameters) {
22
+ const body = await post(parameters.issuer, Constants.verifyPath, parameters.fetch, {
23
+ code: parameters.code,
24
+ id: parameters.id,
25
+ });
26
+ const expiresAt = date(body.expires_at);
27
+ if (typeof body.attestation !== 'string' || body.attestation === '' || !expiresAt)
28
+ throw new EmailOtpError('The issuer returned a malformed attestation.');
29
+ return { attestation: body.attestation, expiresAt };
30
+ }
31
+ /** Parses an issuer timestamp, or returns `undefined` when it is not a valid date. */
32
+ function date(value) {
33
+ if (typeof value !== 'string')
34
+ return undefined;
35
+ const result = new Date(value);
36
+ return Number.isFinite(result.getTime()) ? result : undefined;
37
+ }
38
+ /**
39
+ * Creates a prover that verifies an email address when a server asks for one.
40
+ *
41
+ * When a server answers with `Identity-Attestation-Required: email;issuer="…"`,
42
+ * the prover asks the issuer to email a code to `email`, gets the code from
43
+ * `code` (such as a terminal prompt or a form), exchanges it for an
44
+ * attestation bound to the server's origin and sends the request again with it.
45
+ * Later requests to that origin reuse it until it expires.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const mppx = Mppx.create({
50
+ * identity: [
51
+ * EmailOtp.Client.prover({
52
+ * code: () => prompt('Code:'),
53
+ * email: 'me@example.com',
54
+ * issuers: ['https://issuer.example'],
55
+ * scope: '*',
56
+ * }),
57
+ * ],
58
+ * methods: [tempo({ account })],
59
+ * })
60
+ * ```
61
+ */
62
+ export function prover(config) {
63
+ return Attestation.prover({
64
+ attestations: config.attestations,
65
+ issuers: config.issuers,
66
+ scope: config.scope,
67
+ types: [Constants.type],
68
+ async acquire({ audience, issuer }) {
69
+ const email = typeof config.email === 'function' ? await config.email({ audience, issuer }) : config.email;
70
+ if (!email)
71
+ return undefined;
72
+ const request = await sendCode({ audience, email, fetch: config.fetch, issuer });
73
+ let error;
74
+ for (let attempt = 1; attempt <= Constants.codeAttempts; attempt++) {
75
+ const code = await config.code({ ...request, attempt, audience, email, error, issuer });
76
+ if (!code)
77
+ return undefined;
78
+ try {
79
+ return (await verifyCode({ code: code.trim(), fetch: config.fetch, id: request.id, issuer })).attestation;
80
+ }
81
+ catch (caught) {
82
+ // Only a rejected code is worth another try; other failures end the attempt.
83
+ if (!(caught instanceof EmailOtpError) || caught.status !== 400)
84
+ throw caught;
85
+ error = caught;
86
+ }
87
+ }
88
+ throw error;
89
+ },
90
+ });
91
+ }
92
+ /** An issuer rejected an email OTP request. */
93
+ export class EmailOtpError extends Error {
94
+ name = 'EmailOtpError';
95
+ /** HTTP status the issuer answered with, if any. */
96
+ status;
97
+ constructor(message, options = {}) {
98
+ super(message);
99
+ this.status = options.status;
100
+ }
101
+ }
102
+ async function post(issuer, path, fetch, body) {
103
+ // The address and code never go over plaintext HTTP, except to localhost.
104
+ if (!isIssuer(issuer))
105
+ throw new EmailOtpError('The issuer must be an https URL (http only on localhost).');
106
+ // The unwrapped fetch, so an issuer's 402 is never paid automatically.
107
+ const response = await unwrapFetch(fetch ?? globalThis.fetch)(`${issuer.replace(/\/+$/, '')}${path}`, {
108
+ body: JSON.stringify(body),
109
+ headers: { 'content-type': 'application/json' },
110
+ method: 'POST',
111
+ // Workers reject 'error'; a redirect is not ok, so it fails below.
112
+ redirect: 'manual',
113
+ });
114
+ const json = (await response.json().catch(() => ({})));
115
+ if (!response.ok)
116
+ throw new EmailOtpError(typeof json.error === 'string' ? json.error : `The issuer answered ${response.status}.`, { status: response.status });
117
+ return json;
118
+ }
119
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Email OTP identity: an issuer emails a one-time code and signs an attestation
3
+ * the client sends in `Identity-Attestation`.
4
+ *
5
+ * Limitation: the attestation format, its key lookup and the
6
+ * `Identity-Attestation` headers are internal to this extension. Another
7
+ * attestation type (phone, KYC) needs its own extension, or this one made
8
+ * generic, once a second issuer exists. For your own identity system, use
9
+ * `Identity.from` from `mppx/identity`.
10
+ */
11
+ /** Client helpers that verify an email address with a one-time code. */
12
+ export * as Client from './client/index.js';
13
+ /** Server helpers that require a verified email address. */
14
+ export * as Server from './server/index.js';
15
+ export * from './Constants.js';
16
+ export type * from './Types.js';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Email OTP identity: an issuer emails a one-time code and signs an attestation
3
+ * the client sends in `Identity-Attestation`.
4
+ *
5
+ * Limitation: the attestation format, its key lookup and the
6
+ * `Identity-Attestation` headers are internal to this extension. Another
7
+ * attestation type (phone, KYC) needs its own extension, or this one made
8
+ * generic, once a second issuer exists. For your own identity system, use
9
+ * `Identity.from` from `mppx/identity`.
10
+ */
11
+ /** Client helpers that verify an email address with a one-time code. */
12
+ export * as Client from './client/index.js';
13
+ /** Server helpers that require a verified email address. */
14
+ export * as Server from './server/index.js';
15
+ export * from './Constants.js';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,66 @@
1
+ import type * as Types from './Types.js';
2
+ /** A decoded, unverified attestation. */
3
+ export type Decoded = {
4
+ /** JWS protected header. */
5
+ header: {
6
+ alg?: unknown;
7
+ kid?: unknown;
8
+ typ?: unknown;
9
+ };
10
+ /** Unverified claims. */
11
+ claims: Partial<Types.Claims> & Record<string, unknown>;
12
+ /** The signed bytes: `base64url(header) + '.' + base64url(claims)`. */
13
+ signingInput: Uint8Array;
14
+ /** Signature bytes. */
15
+ signature: Uint8Array;
16
+ };
17
+ /**
18
+ * Signs attestation claims as a compact JWS (EdDSA over Ed25519).
19
+ *
20
+ * For issuers. `keyId` should be the RFC 7638 thumbprint of the public key
21
+ * published in the issuer's JSON Web Key Set.
22
+ */
23
+ export declare function sign(claims: Types.Claims, options: {
24
+ key: CryptoKey;
25
+ keyId: string;
26
+ }): Promise<string>;
27
+ /** Decodes an attestation without verifying it, or returns `undefined` if it is malformed. */
28
+ export declare function decode(token: string): Decoded | undefined;
29
+ /**
30
+ * Verifies an attestation's signature and claims.
31
+ *
32
+ * Checks the EdDSA algorithm and `typ`, the issuer, audience and type, and the
33
+ * `iat` and `exp` times (with `clockTolerance`), then the signature with the
34
+ * key `keyResolver` returns for the header's `kid`.
35
+ */
36
+ export declare function verify(token: string, options: verify.Options): Promise<{
37
+ status: 'valid';
38
+ claims: Types.Claims;
39
+ } | {
40
+ status: 'invalid';
41
+ reason: string;
42
+ unavailable?: true;
43
+ }>;
44
+ export declare namespace verify {
45
+ type Options = {
46
+ /** Accepted attestation type, such as `email`. */
47
+ type: string;
48
+ /** Trusted issuer URL. */
49
+ issuer: string;
50
+ /** Origin the attestation must be bound to. */
51
+ audience: string;
52
+ /** Resolves the issuer's public key by key ID. */
53
+ keyResolver: Types.KeyResolver;
54
+ /** Oldest accepted `iat`, in seconds before now. Defaults to the attestation's own `exp`. */
55
+ maxAge?: number | undefined;
56
+ /** Clock tolerance in seconds. @default 60 */
57
+ clockTolerance?: number | undefined;
58
+ /** Current Unix time in seconds, for tests. */
59
+ now?: number | undefined;
60
+ };
61
+ }
62
+ /** Splits an `Identity-Attestation` header value into its attestations. */
63
+ export declare function parseHeader(value: string | null): string[];
64
+ /** Accepts https issuers, and http only on localhost for development. */
65
+ export declare function isIssuer(value: string): boolean;
66
+ //# sourceMappingURL=Attestation.d.ts.map
@@ -0,0 +1,128 @@
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
+ const decoded = decode(token);
47
+ if (!decoded)
48
+ return invalid('The attestation is malformed.');
49
+ const { header, claims } = decoded;
50
+ if (header.alg !== Constants.algorithm)
51
+ return invalid('The attestation algorithm is not EdDSA.');
52
+ if (header.typ !== Constants.tokenType)
53
+ return invalid('The attestation type header is wrong.');
54
+ if (typeof header.kid !== 'string' || header.kid === '')
55
+ return invalid('The attestation has no key ID.');
56
+ if (claims.iss !== options.issuer)
57
+ return invalid('The attestation issuer is not trusted.');
58
+ if (claims.type !== options.type)
59
+ return invalid('The attestation type is not accepted.');
60
+ if (claims.aud !== options.audience)
61
+ return invalid('The attestation is for another audience.');
62
+ if (typeof claims.sub !== 'string' || claims.sub === '')
63
+ return invalid('The attestation has no subject.');
64
+ if (claims.jti !== undefined && typeof claims.jti !== 'string')
65
+ return invalid('The attestation ID is malformed.');
66
+ if (!isTime(claims.iat) || !isTime(claims.exp))
67
+ return invalid('The attestation times are malformed.');
68
+ const now = options.now ?? Math.floor(Date.now() / 1_000);
69
+ const tolerance = options.clockTolerance ?? Constants.clockTolerance;
70
+ if (claims.exp <= now - tolerance)
71
+ return invalid('The attestation has expired.');
72
+ if (claims.iat > now + tolerance)
73
+ return invalid('The attestation was issued in the future.');
74
+ if (options.maxAge !== undefined && now - claims.iat > options.maxAge + tolerance)
75
+ return invalid('The attestation is too old.');
76
+ let key;
77
+ try {
78
+ key = await options.keyResolver({ issuer: options.issuer, keyId: header.kid });
79
+ }
80
+ catch {
81
+ // The issuer's keys are unreachable, which says nothing about the token.
82
+ return { ...invalid('The attestation key could not be resolved.'), unavailable: true };
83
+ }
84
+ if (!key)
85
+ return invalid('No public key is available for the attestation key ID.');
86
+ let valid = false;
87
+ try {
88
+ valid = await crypto.subtle.verify({ name: 'Ed25519' }, key, decoded.signature, decoded.signingInput);
89
+ }
90
+ catch { }
91
+ if (!valid)
92
+ return invalid('The attestation signature is invalid.');
93
+ return { status: 'valid', claims: claims };
94
+ }
95
+ /** Splits an `Identity-Attestation` header value into its attestations. */
96
+ export function parseHeader(value) {
97
+ if (!value)
98
+ return [];
99
+ return value
100
+ .split(',')
101
+ .map((token) => token.trim())
102
+ .filter(Boolean);
103
+ }
104
+ function encode(value) {
105
+ return Base64.fromString(JSON.stringify(value), { pad: false, url: true });
106
+ }
107
+ function invalid(reason) {
108
+ return { status: 'invalid', reason };
109
+ }
110
+ function isObject(value) {
111
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
112
+ }
113
+ function isTime(value) {
114
+ // Bounded by the largest time a Date holds, so every accepted time converts to a valid Date.
115
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= maxTime;
116
+ }
117
+ /** Latest time, in Unix seconds, that a JavaScript Date can represent. */
118
+ const maxTime = 8_640_000_000_000;
119
+ /** Accepts https issuers, and http only on localhost for development. */
120
+ export function isIssuer(value) {
121
+ if (!URL.canParse(value))
122
+ return false;
123
+ const url = new URL(value);
124
+ if (url.protocol === 'https:')
125
+ return true;
126
+ return url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1');
127
+ }
128
+ //# sourceMappingURL=Attestation.js.map