mppx 0.17.4 → 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.
- package/CHANGELOG.md +18 -0
- package/README.md +15 -0
- package/dist/cli/cli.js +141 -137
- package/dist/cli/stripe.d.ts +53 -0
- package/dist/cli/stripe.js +241 -0
- package/dist/client/Mppx.js +1 -0
- package/dist/extensions/identity/email-otp/Constants.d.ts +16 -0
- package/dist/extensions/identity/email-otp/Constants.js +16 -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 +116 -0
- package/dist/extensions/identity/email-otp/client/index.js +119 -0
- package/dist/extensions/identity/email-otp/index.d.ts +17 -0
- package/dist/extensions/identity/email-otp/index.js +16 -0
- package/dist/extensions/identity/email-otp/internal/Attestation.d.ts +66 -0
- package/dist/extensions/identity/email-otp/internal/Attestation.js +128 -0
- package/dist/extensions/identity/email-otp/internal/Constants.d.ts +20 -0
- package/dist/extensions/identity/email-otp/internal/Constants.js +20 -0
- package/dist/extensions/identity/email-otp/internal/Jwks.d.ts +30 -0
- package/dist/extensions/identity/email-otp/internal/Jwks.js +114 -0
- package/dist/extensions/identity/email-otp/internal/Prover.d.ts +46 -0
- package/dist/extensions/identity/email-otp/internal/Prover.js +168 -0
- package/dist/extensions/identity/email-otp/internal/Types.d.ts +48 -0
- package/dist/extensions/identity/email-otp/internal/Types.js +2 -0
- package/dist/extensions/identity/email-otp/internal/Verifier.d.ts +56 -0
- package/dist/extensions/identity/email-otp/internal/Verifier.js +116 -0
- package/dist/extensions/identity/email-otp/server/index.d.ts +48 -0
- package/dist/extensions/identity/email-otp/server/index.js +56 -0
- package/dist/extensions/identity/index.d.ts +2 -0
- package/dist/extensions/identity/index.js +2 -0
- package/dist/identity/Callback.d.ts +47 -0
- package/dist/identity/Callback.js +64 -0
- package/dist/identity/index.d.ts +1 -0
- package/dist/identity/index.js +1 -0
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/proxy/internal/Headers.js +2 -0
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Where a Stripe secret key came from, in resolution order. */
|
|
2
|
+
export type KeySource = 'flag' | 'env' | 'stripe-cli';
|
|
3
|
+
/** A resolved Stripe API key and its source. */
|
|
4
|
+
export type ResolvedKey = {
|
|
5
|
+
key: string;
|
|
6
|
+
source: KeySource;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Resolves the Stripe key for `mppx stripe address`: `--secret-key`, then `STRIPE_SECRET_KEY`,
|
|
10
|
+
* then the Stripe CLI's saved login for the current project.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolveKey(options: resolveKey.Options): ResolvedKey | undefined;
|
|
13
|
+
export declare namespace resolveKey {
|
|
14
|
+
type Options = readStripeCliKey.Options & {
|
|
15
|
+
/** Value of `--secret-key`. */
|
|
16
|
+
secretKey?: string | undefined;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reads the API key the Stripe CLI saved with `stripe login`, without running the CLI.
|
|
21
|
+
*
|
|
22
|
+
* Test mode keys live in `<config>/stripe/config.toml`. Live mode keys live in the OS keyring
|
|
23
|
+
* (service `StripeCLI`, account `<project>.live_mode_api_key`), or in `credentials.json` next to
|
|
24
|
+
* the config when no keyring was available.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readStripeCliKey(options: readStripeCliKey.Options): string | undefined;
|
|
27
|
+
export declare namespace readStripeCliKey {
|
|
28
|
+
type Options = {
|
|
29
|
+
/** Environment to read (default: `process.env`). */
|
|
30
|
+
env?: Record<string, string | undefined> | undefined;
|
|
31
|
+
/** Runs a system command and returns its stdout; replaced in tests. */
|
|
32
|
+
exec?: ((file: string, args: readonly string[]) => string) | undefined;
|
|
33
|
+
/** Read the live mode key instead of the test mode key. */
|
|
34
|
+
live?: boolean | undefined;
|
|
35
|
+
/** OS to read the keyring of (default: `process.platform`). */
|
|
36
|
+
platform?: NodeJS.Platform | undefined;
|
|
37
|
+
/** Stripe CLI project (`--project-name`); falls back to `STRIPE_PROJECT_NAME`, then `default`. */
|
|
38
|
+
projectName?: string | undefined;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
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
|
+
*/
|
|
47
|
+
export declare function writeEnvValue(file: string, key: string, value: string): void;
|
|
48
|
+
/**
|
|
49
|
+
* Gives a bare `--env` on `mppx stripe address` its default path, since incur flags can't take an
|
|
50
|
+
* optional value: `--env` last or followed by another flag becomes `--env .env`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function normalizeArgv(argv: readonly string[]): string[];
|
|
53
|
+
//# sourceMappingURL=stripe.d.ts.map
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import * as util from 'node:util';
|
|
6
|
+
/** The Stripe CLI's keyring service name (stripe-cli pkg/config KeyManagementService). */
|
|
7
|
+
const keyringService = 'StripeCLI';
|
|
8
|
+
/**
|
|
9
|
+
* Resolves the Stripe key for `mppx stripe address`: `--secret-key`, then `STRIPE_SECRET_KEY`,
|
|
10
|
+
* then the Stripe CLI's saved login for the current project.
|
|
11
|
+
*/
|
|
12
|
+
export function resolveKey(options) {
|
|
13
|
+
const env = options.env ?? process.env;
|
|
14
|
+
const flag = options.secretKey?.trim();
|
|
15
|
+
if (flag)
|
|
16
|
+
return { key: flag, source: 'flag' };
|
|
17
|
+
const fromEnv = env.STRIPE_SECRET_KEY?.trim();
|
|
18
|
+
if (fromEnv)
|
|
19
|
+
return { key: fromEnv, source: 'env' };
|
|
20
|
+
const fromCli = readStripeCliKey(options);
|
|
21
|
+
if (fromCli)
|
|
22
|
+
return { key: fromCli, source: 'stripe-cli' };
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Reads the API key the Stripe CLI saved with `stripe login`, without running the CLI.
|
|
27
|
+
*
|
|
28
|
+
* Test mode keys live in `<config>/stripe/config.toml`. Live mode keys live in the OS keyring
|
|
29
|
+
* (service `StripeCLI`, account `<project>.live_mode_api_key`), or in `credentials.json` next to
|
|
30
|
+
* the config when no keyring was available.
|
|
31
|
+
*/
|
|
32
|
+
export function readStripeCliKey(options) {
|
|
33
|
+
const env = options.env ?? process.env;
|
|
34
|
+
const directory = path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'stripe');
|
|
35
|
+
const project = options.projectName || env.STRIPE_PROJECT_NAME || 'default';
|
|
36
|
+
const profile = readProfile(path.join(directory, 'config.toml'), project);
|
|
37
|
+
if (!options.live)
|
|
38
|
+
return profile.test_mode_api_key || profile.secret_key || profile.api_key || undefined;
|
|
39
|
+
// Older CLIs kept the live key in config.toml; newer ones leave a redacted copy there.
|
|
40
|
+
const inConfig = profile.live_mode_api_key;
|
|
41
|
+
if (inConfig && !inConfig.includes('*'))
|
|
42
|
+
return inConfig;
|
|
43
|
+
const account = `${project}.live_mode_api_key`;
|
|
44
|
+
const fromFile = readJson(path.join(directory, 'credentials.json'))?.[account];
|
|
45
|
+
if (typeof fromFile === 'string' && fromFile)
|
|
46
|
+
return fromFile;
|
|
47
|
+
return readKeyring(account, options);
|
|
48
|
+
}
|
|
49
|
+
/** Reads a keyring entry with the OS's own tool (macOS `security`, Linux `secret-tool`). */
|
|
50
|
+
function readKeyring(account, options) {
|
|
51
|
+
const platform = options.platform ?? process.platform;
|
|
52
|
+
const exec = options.exec ?? execSystem;
|
|
53
|
+
const command = (() => {
|
|
54
|
+
if (platform === 'darwin')
|
|
55
|
+
return [
|
|
56
|
+
'security',
|
|
57
|
+
['find-generic-password', '-s', keyringService, '-a', account, '-w'],
|
|
58
|
+
];
|
|
59
|
+
if (platform === 'linux')
|
|
60
|
+
return ['secret-tool', ['lookup', 'service', keyringService, 'username', account]];
|
|
61
|
+
return undefined;
|
|
62
|
+
})();
|
|
63
|
+
if (!command)
|
|
64
|
+
return undefined;
|
|
65
|
+
try {
|
|
66
|
+
const value = exec(command[0], command[1]).trim();
|
|
67
|
+
// go-keyring stores macOS values base64-encoded behind this prefix.
|
|
68
|
+
const prefix = 'go-keyring-base64:';
|
|
69
|
+
if (value.startsWith(prefix))
|
|
70
|
+
return Buffer.from(value.slice(prefix.length), 'base64').toString('utf8') || undefined;
|
|
71
|
+
return value || undefined;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function execSystem(file, args) {
|
|
78
|
+
return execFileSync(file, args, {
|
|
79
|
+
encoding: 'utf8',
|
|
80
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
81
|
+
timeout: 3_000,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function readJson(file) {
|
|
85
|
+
try {
|
|
86
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Reads one profile's string values from the Stripe CLI's config.toml: the `[<project>]` table, or
|
|
94
|
+
* `[profiles.<project>]` in the CLI's newer layout. Handles only the flat string keys the CLI writes.
|
|
95
|
+
*/
|
|
96
|
+
function readProfile(file, project) {
|
|
97
|
+
let text;
|
|
98
|
+
try {
|
|
99
|
+
text = fs.readFileSync(file, 'utf8');
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
104
|
+
const tables = new Set([project, `profiles.${project}`]);
|
|
105
|
+
const values = {};
|
|
106
|
+
let current;
|
|
107
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
108
|
+
const line = raw.trim();
|
|
109
|
+
if (!line || line.startsWith('#'))
|
|
110
|
+
continue;
|
|
111
|
+
const table = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
|
|
112
|
+
if (table) {
|
|
113
|
+
current = table[1].replace(/["']/g, '').replace(/\s*\.\s*/g, '.');
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!current || !tables.has(current))
|
|
117
|
+
continue;
|
|
118
|
+
const pair = /^([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(line);
|
|
119
|
+
if (pair)
|
|
120
|
+
values[pair[1]] = pair[2] !== undefined ? pair[2].replace(/\\(.)/g, '$1') : pair[3];
|
|
121
|
+
}
|
|
122
|
+
return values;
|
|
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
|
+
*/
|
|
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');
|
|
153
|
+
const line = `${key}=${value}`;
|
|
154
|
+
if (!fs.existsSync(file))
|
|
155
|
+
return fs.writeFileSync(file, `${line}\n`, { mode: 0o600 });
|
|
156
|
+
const existing = fs.readFileSync(file, 'utf8');
|
|
157
|
+
const pattern = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
|
|
158
|
+
const { lines: kept, found } = replaceAssignments(existing.split('\n'), pattern, line);
|
|
159
|
+
const separator = existing === '' || existing.endsWith('\n') ? '' : '\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);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Gives a bare `--env` on `mppx stripe address` its default path, since incur flags can't take an
|
|
221
|
+
* optional value: `--env` last or followed by another flag becomes `--env .env`.
|
|
222
|
+
*/
|
|
223
|
+
export function normalizeArgv(argv) {
|
|
224
|
+
const command = argv.findIndex((token, i) => token === 'stripe' && argv[i + 1] === 'address');
|
|
225
|
+
if (command === -1)
|
|
226
|
+
return [...argv];
|
|
227
|
+
const result = argv.slice(0, command + 2);
|
|
228
|
+
for (let i = command + 2; i < argv.length; i++) {
|
|
229
|
+
const token = argv[i];
|
|
230
|
+
result.push(token);
|
|
231
|
+
if (token === '--') {
|
|
232
|
+
result.push(...argv.slice(i + 1));
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
const next = argv[i + 1];
|
|
236
|
+
if (token === '--env' && (next === undefined || next.startsWith('-')))
|
|
237
|
+
result.push('.env');
|
|
238
|
+
}
|
|
239
|
+
return result;
|
|
240
|
+
}
|
|
241
|
+
//# sourceMappingURL=stripe.js.map
|
package/dist/client/Mppx.js
CHANGED
|
@@ -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,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
|