direct-auth 0.0.0-stage → 0.1.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.
Files changed (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +486 -2
  3. package/dist/accounts.d.ts +118 -0
  4. package/dist/accounts.js +314 -0
  5. package/dist/apps.d.ts +85 -0
  6. package/dist/apps.js +449 -0
  7. package/dist/auth.d.ts +396 -0
  8. package/dist/auth.js +699 -0
  9. package/dist/base64.d.ts +20 -0
  10. package/dist/base64.js +45 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +463 -0
  13. package/dist/client.d.ts +170 -0
  14. package/dist/client.js +438 -0
  15. package/dist/codes.d.ts +81 -0
  16. package/dist/codes.js +91 -0
  17. package/dist/crypto.d.ts +11 -0
  18. package/dist/crypto.js +37 -0
  19. package/dist/d1.d.ts +2 -0
  20. package/dist/d1.js +2 -0
  21. package/dist/db/limits.d.ts +16 -0
  22. package/dist/db/limits.js +23 -0
  23. package/dist/db/schema.d.ts +25 -0
  24. package/dist/db/schema.js +136 -0
  25. package/dist/db/sql.d.ts +52 -0
  26. package/dist/db/sql.js +121 -0
  27. package/dist/dns.d.ts +48 -0
  28. package/dist/dns.js +133 -0
  29. package/dist/env.d.ts +39 -0
  30. package/dist/env.js +169 -0
  31. package/dist/index.d.ts +19 -0
  32. package/dist/index.js +14 -0
  33. package/dist/init.d.ts +134 -0
  34. package/dist/init.js +912 -0
  35. package/dist/jwks.d.ts +18 -0
  36. package/dist/jwks.js +63 -0
  37. package/dist/jwt.d.ts +90 -0
  38. package/dist/jwt.js +99 -0
  39. package/dist/keys.d.ts +33 -0
  40. package/dist/keys.js +54 -0
  41. package/dist/messages.d.ts +26 -0
  42. package/dist/messages.js +57 -0
  43. package/dist/migrate-cli.d.ts +82 -0
  44. package/dist/migrate-cli.js +564 -0
  45. package/dist/migrate.d.ts +99 -0
  46. package/dist/migrate.js +396 -0
  47. package/dist/node.d.ts +16 -0
  48. package/dist/node.js +63 -0
  49. package/dist/passkeys.d.ts +126 -0
  50. package/dist/passkeys.js +383 -0
  51. package/dist/passwords.d.ts +53 -0
  52. package/dist/passwords.js +326 -0
  53. package/dist/pgwire.d.ts +86 -0
  54. package/dist/pgwire.js +445 -0
  55. package/dist/phone.d.ts +11 -0
  56. package/dist/phone.js +18 -0
  57. package/dist/postgres.d.ts +2 -0
  58. package/dist/postgres.js +2 -0
  59. package/dist/providers/apple-revoke.d.ts +55 -0
  60. package/dist/providers/apple-revoke.js +113 -0
  61. package/dist/providers/apple.d.ts +28 -0
  62. package/dist/providers/apple.js +51 -0
  63. package/dist/providers/github.d.ts +28 -0
  64. package/dist/providers/github.js +67 -0
  65. package/dist/providers/google.d.ts +23 -0
  66. package/dist/providers/google.js +47 -0
  67. package/dist/providers/identity.d.ts +24 -0
  68. package/dist/providers/identity.js +3 -0
  69. package/dist/proxy.d.ts +19 -0
  70. package/dist/proxy.js +43 -0
  71. package/dist/records.d.ts +91 -0
  72. package/dist/records.js +264 -0
  73. package/dist/scrypt.d.ts +26 -0
  74. package/dist/scrypt.js +179 -0
  75. package/dist/senders/aws.d.ts +13 -0
  76. package/dist/senders/aws.js +47 -0
  77. package/dist/senders/dev.d.ts +6 -0
  78. package/dist/senders/dev.js +13 -0
  79. package/dist/senders/index.d.ts +5 -0
  80. package/dist/senders/index.js +4 -0
  81. package/dist/senders/mail.d.ts +26 -0
  82. package/dist/senders/mail.js +66 -0
  83. package/dist/senders/sms.d.ts +34 -0
  84. package/dist/senders/sms.js +69 -0
  85. package/dist/senders/smtp.d.ts +32 -0
  86. package/dist/senders/smtp.js +145 -0
  87. package/dist/senders/types.d.ts +31 -0
  88. package/dist/senders/types.js +25 -0
  89. package/dist/server.d.ts +67 -0
  90. package/dist/server.js +494 -0
  91. package/dist/sessions.d.ts +74 -0
  92. package/dist/sessions.js +146 -0
  93. package/dist/skill.d.ts +25 -0
  94. package/dist/skill.js +66 -0
  95. package/dist/sources.d.ts +138 -0
  96. package/dist/sources.js +931 -0
  97. package/dist/sqlite.d.ts +2 -0
  98. package/dist/sqlite.js +2 -0
  99. package/dist/stores/d1.d.ts +22 -0
  100. package/dist/stores/d1.js +23 -0
  101. package/dist/stores/postgres.d.ts +33 -0
  102. package/dist/stores/postgres.js +71 -0
  103. package/dist/stores/sqlite.d.ts +27 -0
  104. package/dist/stores/sqlite.js +55 -0
  105. package/dist/supabase.d.ts +71 -0
  106. package/dist/supabase.js +283 -0
  107. package/dist/tui.d.ts +178 -0
  108. package/dist/tui.js +537 -0
  109. package/package.json +90 -4
  110. package/skills/direct-auth/SKILL.md +101 -0
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The DNS records a setup needs, ready to copy: the sign-in's own address, and what mail from the codes' sender
3
+ * needs to land in the inbox. Each record is asked about over DNS-over-HTTPS (`present`), so the wizard can wait for
4
+ * them; on a domain at Cloudflare, with a token the person gives (Zone DNS Edit), they can be made from here
5
+ * (`cloudflare`). The token is only used for those calls: never printed, never written anywhere.
6
+ */
7
+ import { lookup } from "./dns.js";
8
+ import { base64 } from "./base64.js";
9
+ import { signAws } from "./senders/aws.js";
10
+ /** The records as aligned lines: type, name, value (priority before an MX's), and what for, dim. */
11
+ export function recordLines(records, o = {}) {
12
+ const dim = o.dim ?? ((s) => s);
13
+ const code = o.code ?? ((s) => s);
14
+ const type = Math.max(4, ...records.map((r) => r.type.length)) + 2;
15
+ const name = Math.max(4, ...records.map((r) => r.name.length)) + 2;
16
+ const head = `${"Type".padEnd(type)}${"Name".padEnd(name)}Value`;
17
+ const lines = [dim(head)];
18
+ for (const r of records) {
19
+ const value = r.type === "MX" ? `${r.priority ?? 10} ${r.value}` : r.value;
20
+ lines.push(`${r.type.padEnd(type)}${code(r.name.padEnd(name))}${value}`);
21
+ lines.push(dim(`${" ".repeat(type + name)}${r.why}`));
22
+ }
23
+ return lines;
24
+ }
25
+ const norm = (v) => v.trim().replace(/^"|"$/g, "").replace(/\.$/, "").toLowerCase();
26
+ /** Whether the record answers as it should over DNS-over-HTTPS. */
27
+ export async function present(r, f = fetch) {
28
+ const found = await lookup(r.name, r.type, f);
29
+ const want = norm(r.value);
30
+ if (r.match === "dmarc")
31
+ return found.some((v) => /^v=dmarc1\b/i.test(norm(v)));
32
+ if (r.match === "spf") {
33
+ const mechanism = want.split(/\s+/).find((m) => /^(include:|ip4:|ip6:|a:|mx)/.test(m));
34
+ return found.some((v) => /^v=spf1\b/i.test(norm(v)) && (!mechanism || norm(v).split(/\s+/).includes(mechanism)));
35
+ }
36
+ if (r.type === "MX")
37
+ return found.some((v) => norm(v).split(/\s+/).pop() === want);
38
+ if (r.type === "TXT")
39
+ return found.some((v) => norm(v).replace(/\s+/g, "") === want.replace(/\s+/g, ""));
40
+ return found.some((v) => norm(v) === want);
41
+ }
42
+ /** Which of the records aren't there yet. */
43
+ export async function missing(records, f = fetch) {
44
+ const out = [];
45
+ for (const r of records)
46
+ if (!(await present(r, f).catch(() => false)))
47
+ out.push(r);
48
+ return out;
49
+ }
50
+ /**
51
+ * Asked again every `everyMs` until all answer, or `timeoutMs` passes, or `stop()` says so; `tick` hears what is
52
+ * still missing each round. What is still missing at the end, or none.
53
+ */
54
+ export async function waitFor(records, o = {}) {
55
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
56
+ const until = Date.now() + (o.timeoutMs ?? 5 * 60_000);
57
+ let left = await missing(records, o.f);
58
+ while (left.length && Date.now() < until && !o.stop?.()) {
59
+ o.tick?.(left);
60
+ await sleep(o.everyMs ?? 10_000);
61
+ left = await missing(left, o.f);
62
+ }
63
+ return left;
64
+ }
65
+ const DMARC = (domain) => ({ type: "TXT", name: `_dmarc.${domain}`, value: "v=DMARC1; p=none", why: "DMARC: Gmail and Yahoo ask for one", match: "dmarc" });
66
+ /**
67
+ * What the mail sender needs on `domain`, asked of the sender itself where its API says (Resend, Mailgun, SendGrid,
68
+ * SES), or the parts that are always the same where it doesn't. `note` says what can't be known from here.
69
+ */
70
+ export async function mailRecords(sender, domain, env, f = fetch) {
71
+ const d = domain.toLowerCase();
72
+ const full = (name) => (name === "@" || name === "" ? d : name.endsWith(`.${d}`) || name === d ? name : `${name}.${d}`);
73
+ try {
74
+ switch (sender) {
75
+ case "resend": {
76
+ const headers = { authorization: `Bearer ${env.RESEND_API_KEY}` };
77
+ const list = (await (await f("https://api.resend.com/domains", { headers })).json());
78
+ const found = list.data?.find((x) => x.name === d);
79
+ if (!found)
80
+ return { records: [DMARC(d)], note: `${d} isn't in your Resend account yet: add it under Domains, and its records show here.` };
81
+ const one = (await (await f(`https://api.resend.com/domains/${found.id}`, { headers })).json());
82
+ const records = (one.records ?? []).map((r) => ({
83
+ type: r.type,
84
+ name: full(r.name),
85
+ value: r.value,
86
+ priority: r.priority,
87
+ why: r.record === "DKIM" ? "DKIM: Resend signs the mail" : r.type === "MX" ? "bounces come back to Resend" : "SPF: Resend may send for you",
88
+ match: /^v=spf1/i.test(r.value) ? "spf" : "exact",
89
+ }));
90
+ return { records: [...records, DMARC(d)] };
91
+ }
92
+ case "mailgun": {
93
+ const host = env.MAILGUN_REGION === "eu" ? "https://api.eu.mailgun.net" : "https://api.mailgun.net";
94
+ const md = env.MAILGUN_DOMAIN || d;
95
+ const r = await f(`${host}/v3/domains/${encodeURIComponent(md)}`, { headers: { authorization: `Basic ${base64(`api:${env.MAILGUN_API_KEY}`)}` } });
96
+ if (!r.ok)
97
+ return { records: [DMARC(d)], note: `Mailgun didn't answer for ${md} (${r.status}): its records are under Sending, Domains.` };
98
+ const body = (await r.json());
99
+ const records = (body.sending_dns_records ?? []).map((x) => ({
100
+ type: x.record_type,
101
+ name: x.name,
102
+ value: x.value,
103
+ why: x.record_type === "CNAME" ? "tracking links" : /^v=spf1/i.test(x.value) ? "SPF: Mailgun may send for you" : "DKIM: Mailgun signs the mail",
104
+ match: /^v=spf1/i.test(x.value) ? "spf" : "exact",
105
+ }));
106
+ return { records: [...records, DMARC(d)] };
107
+ }
108
+ case "sendgrid": {
109
+ const r = await f("https://api.sendgrid.com/v3/whitelabel/domains", { headers: { authorization: `Bearer ${env.SENDGRID_API_KEY}` } });
110
+ if (!r.ok)
111
+ return { records: [DMARC(d)], note: "SendGrid didn't list the domain (the key may lack Sender Authentication): its records are under Settings, Sender Authentication." };
112
+ const list = (await r.json());
113
+ const found = list.find((x) => x.domain === d);
114
+ if (!found)
115
+ return { records: [DMARC(d)], note: `${d} isn't authenticated in SendGrid yet: Settings, Sender Authentication, Authenticate Your Domain.` };
116
+ const records = Object.entries(found.dns).map(([k, x]) => ({
117
+ type: x.type.toUpperCase(),
118
+ name: x.host,
119
+ value: x.data,
120
+ why: k.startsWith("dkim") ? "DKIM: SendGrid signs the mail" : "SPF and bounces, through SendGrid",
121
+ }));
122
+ return { records: [...records, DMARC(d)] };
123
+ }
124
+ case "ses": {
125
+ const region = env.AWS_REGION ?? "us-east-1";
126
+ const url = `https://email.${region}.amazonaws.com/v2/email/identities/${encodeURIComponent(d)}`;
127
+ const creds = { region, accessKeyId: env.AWS_ACCESS_KEY_ID ?? "", secretAccessKey: env.AWS_SECRET_ACCESS_KEY ?? "", sessionToken: env.AWS_SESSION_TOKEN };
128
+ const headers = await signAws(creds, "ses", url, "", "application/json", new Date(), "GET");
129
+ const r = await f(url, { headers });
130
+ if (!r.ok)
131
+ return { records: [{ type: "TXT", name: d, value: "v=spf1 include:amazonses.com ~all", why: "SPF: SES may send for you", match: "spf" }, DMARC(d)], note: `SES didn't answer for ${d} (${r.status}): verify the domain in the SES console, and its DKIM records show here.` };
132
+ const body = (await r.json());
133
+ const dkim = (body.DkimAttributes?.Tokens ?? []).map((t) => ({ type: "CNAME", name: `${t}._domainkey.${d}`, value: `${t}.dkim.amazonses.com`, why: "DKIM: SES signs the mail" }));
134
+ return { records: [...dkim, { type: "TXT", name: d, value: "v=spf1 include:amazonses.com ~all", why: "SPF: SES may send for you", match: "spf" }, DMARC(d)] };
135
+ }
136
+ case "postmark":
137
+ return { records: [DMARC(d)], note: "Postmark's DKIM and Return-Path records are on its Sender Signatures page (a server token can't read them)." };
138
+ default:
139
+ return { records: [DMARC(d)], note: "Your mail server's own SPF and DKIM: from its setup." };
140
+ }
141
+ }
142
+ catch (error) {
143
+ return { records: [DMARC(d)], note: `The sender couldn't be asked for its records: ${error instanceof Error ? error.message : String(error)}.` };
144
+ }
145
+ }
146
+ /** The record that points the sign-in's address at a server of one's own. */
147
+ export function serverRecords(domain, ip) {
148
+ return [{ type: ip.includes(":") ? "AAAA" : "A", name: domain, value: ip, why: "the sign-in's address, at your server", match: "exact" }];
149
+ }
150
+ export class CloudflareError extends Error {
151
+ name = "CloudflareError";
152
+ }
153
+ export function cloudflare(token, f = fetch) {
154
+ const api = async (method, path, body) => {
155
+ const r = await f(`https://api.cloudflare.com/client/v4${path}`, {
156
+ method,
157
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
158
+ body: body === undefined ? undefined : JSON.stringify(body),
159
+ });
160
+ const json = (await r.json().catch(() => ({})));
161
+ if (!r.ok || !json.success)
162
+ throw new CloudflareError(json.errors?.map((e) => e.message).join("; ") || `Cloudflare answered ${r.status}`);
163
+ return json.result;
164
+ };
165
+ const content = (r) => (r.type === "TXT" && !/^".*"$/.test(r.value) ? `"${r.value}"` : r.value);
166
+ const payload = (r) => ({ type: r.type, name: r.name, content: content(r), ttl: 1, proxied: false, ...(r.type === "MX" ? { priority: r.priority ?? 10 } : {}) });
167
+ return {
168
+ async verify() {
169
+ try {
170
+ const r = await api("GET", "/user/tokens/verify");
171
+ return r.status === "active";
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ },
177
+ async zoneOf(name) {
178
+ const labels = name.toLowerCase().replace(/\.$/, "").split(".");
179
+ for (let i = 0; i < labels.length - 1; i += 1) {
180
+ const candidate = labels.slice(i).join(".");
181
+ const zones = await api("GET", `/zones?name=${encodeURIComponent(candidate)}`);
182
+ if (zones.length)
183
+ return { id: zones[0].id, name: zones[0].name };
184
+ }
185
+ return null;
186
+ },
187
+ list: (zone, type, name) => api("GET", `/zones/${zone}/dns_records?type=${type}&name=${encodeURIComponent(name)}`),
188
+ create: async (zone, r) => void (await api("POST", `/zones/${zone}/dns_records`, payload(r))),
189
+ update: async (zone, id, r) => void (await api("PUT", `/zones/${zone}/dns_records/${id}`, payload(r))),
190
+ };
191
+ }
192
+ /**
193
+ * What to do at Cloudflare to have `records`: those already right are left alone; a record of the same type and name
194
+ * with another value is replaced only for an exact one (an A, a CNAME, a DKIM key), and an SPF one gets the
195
+ * mechanism added; the rest are made.
196
+ */
197
+ export async function planCloudflare(cf, zone, records) {
198
+ const plan = [];
199
+ for (const r of records) {
200
+ const there = await cf.list(zone, r.type, r.name);
201
+ const values = there.map((x) => ({ id: x.id, v: norm(x.content) }));
202
+ if (r.match === "dmarc" && values.some((x) => /^v=dmarc1\b/.test(x.v))) {
203
+ plan.push({ record: r, action: "keep" });
204
+ continue;
205
+ }
206
+ if (r.match === "spf") {
207
+ const spf = values.find((x) => /^v=spf1\b/.test(x.v));
208
+ const mechanism = norm(r.value).split(/\s+/).find((m) => /^(include:|ip4:|ip6:)/.test(m));
209
+ if (spf && mechanism && !spf.v.split(/\s+/).includes(mechanism)) {
210
+ const merged = spf.v.replace(/\s+([~?+-]?all)$/, ` ${mechanism} $1`);
211
+ plan.push({ record: { ...r, value: merged.includes(mechanism) ? merged : `${spf.v} ${mechanism}` }, action: "update", id: spf.id });
212
+ continue;
213
+ }
214
+ if (spf) {
215
+ plan.push({ record: r, action: "keep" });
216
+ continue;
217
+ }
218
+ }
219
+ const want = norm(r.type === "MX" ? r.value : r.value);
220
+ if (values.some((x) => (r.type === "TXT" ? x.v.replace(/\s+/g, "") === want.replace(/\s+/g, "") : x.v === want))) {
221
+ plan.push({ record: r, action: "keep" });
222
+ continue;
223
+ }
224
+ const replaceable = (r.type === "A" || r.type === "AAAA" || r.type === "CNAME") && values.length === 1;
225
+ plan.push(replaceable ? { record: r, action: "update", id: values[0].id } : { record: r, action: "create" });
226
+ }
227
+ return plan;
228
+ }
229
+ /** Whether the domain's DNS is at Cloudflare: the zone's name servers, found walking up from `name`. */
230
+ export async function onCloudflare(name, f = fetch) {
231
+ const labels = name.toLowerCase().replace(/\.$/, "").split(".");
232
+ for (let i = 0; i < labels.length - 1; i += 1) {
233
+ const ns = await lookup(labels.slice(i).join("."), "NS", f).catch(() => []);
234
+ if (ns.length)
235
+ return ns.every((n) => /\.ns\.cloudflare\.com\.?$/i.test(n));
236
+ }
237
+ return false;
238
+ }
239
+ /**
240
+ * Whether the sign-in answers at its own address: the name resolves (over DNS-over-HTTPS, so a cache here doesn't
241
+ * fool it), and `<issuer>/.well-known/openid-configuration` says that issuer. What is wrong, or nothing.
242
+ */
243
+ export async function issuerProblem(issuer, f = fetch) {
244
+ const url = new URL(issuer);
245
+ if (url.hostname !== "localhost" && !/^[\d.]+$|:/.test(url.hostname)) {
246
+ const [a, aaaa, cname] = await Promise.all([lookup(url.hostname, "A", f), lookup(url.hostname, "AAAA", f), lookup(url.hostname, "CNAME", f)]).catch(() => [[], [], []]);
247
+ if (!a.length && !aaaa.length && !cname.length)
248
+ return `${url.hostname} has no DNS record yet`;
249
+ }
250
+ const at = `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
251
+ let r;
252
+ try {
253
+ r = await f(at, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
254
+ }
255
+ catch (error) {
256
+ return `${at} didn't answer (${error instanceof Error ? error.message : String(error)})`;
257
+ }
258
+ if (!r.ok)
259
+ return `${at} answered ${r.status}`;
260
+ const said = (await r.json().catch(() => ({}))).issuer;
261
+ if (said !== issuer)
262
+ return `${at} names another issuer: ${said ?? "none"}`;
263
+ return undefined;
264
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * scrypt (RFC 7914) in plain TypeScript, only to check password hashes moved from elsewhere: Firebase Auth's modified
3
+ * scrypt and Better Auth's scrypt. WebCrypto has no scrypt; PBKDF2-HMAC-SHA256, which scrypt starts and ends with, is
4
+ * WebCrypto's. The memory-hard middle gives way to other requests every few milliseconds, as the bcrypt check does.
5
+ *
6
+ * A check is 16 MB and about 50 to 100 ms of CPU for Firebase's defaults (N = 2^14, r = 8), 32 MB for Better Auth's
7
+ * (N = 2^14, r = 16): on Workers that needs the paid plan, like bcrypt. The hash is made PBKDF2 at that first sign-in.
8
+ */
9
+ /** How many scrypt computations hold their memory now (at most two). */
10
+ export declare const scryptRunning: () => number;
11
+ /** scrypt(password, salt, N, r, p) to `bytes` bytes. */
12
+ export declare function scrypt(password: Uint8Array, salt: Uint8Array, n: number, r: number, p: number, bytes: number): Promise<Uint8Array>;
13
+ /**
14
+ * Firebase Auth's modified scrypt: scrypt(password, salt ‖ salt separator, N = 2^memCost, r = rounds, p = 1, 64
15
+ * bytes); its first 32 bytes are an AES-256 key, and the hash is the project's signer key encrypted with it in CTR
16
+ * mode from a zero counter.
17
+ */
18
+ export declare function firebaseScrypt(password: string, o: {
19
+ salt: Uint8Array;
20
+ saltSeparator: Uint8Array;
21
+ signerKey: Uint8Array;
22
+ rounds: number;
23
+ memCost: number;
24
+ }): Promise<Uint8Array>;
25
+ /** Better Auth's scrypt: the password NFKC, the salt the hex text itself, N = 16384, r = 16, p = 1, 64 bytes. */
26
+ export declare function betterAuthScrypt(password: string, saltHex: string): Promise<Uint8Array>;
package/dist/scrypt.js ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * scrypt (RFC 7914) in plain TypeScript, only to check password hashes moved from elsewhere: Firebase Auth's modified
3
+ * scrypt and Better Auth's scrypt. WebCrypto has no scrypt; PBKDF2-HMAC-SHA256, which scrypt starts and ends with, is
4
+ * WebCrypto's. The memory-hard middle gives way to other requests every few milliseconds, as the bcrypt check does.
5
+ *
6
+ * A check is 16 MB and about 50 to 100 ms of CPU for Firebase's defaults (N = 2^14, r = 8), 32 MB for Better Auth's
7
+ * (N = 2^14, r = 16): on Workers that needs the paid plan, like bcrypt. The hash is made PBKDF2 at that first sign-in.
8
+ */
9
+ import { utf8 } from "./base64.js";
10
+ const pause = () => new Promise((resolve) => {
11
+ const g = globalThis;
12
+ if (typeof g.setImmediate === "function")
13
+ g.setImmediate(resolve);
14
+ else
15
+ setTimeout(resolve, 0);
16
+ });
17
+ async function pbkdf2(password, salt, bytes) {
18
+ const key = await crypto.subtle.importKey("raw", password, "PBKDF2", false, ["deriveBits"]);
19
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: salt, iterations: 1 }, key, bytes * 8));
20
+ }
21
+ const rotl = (a, b) => (a << b) | (a >>> (32 - b));
22
+ /** Salsa20/8 of `b` (16 words at `bi`), in place, xored with `x` first (BlockMix's step). */
23
+ function salsaXor(b, bi, x, xi, out, oi) {
24
+ let j0 = b[bi] ^ x[xi], j1 = b[bi + 1] ^ x[xi + 1], j2 = b[bi + 2] ^ x[xi + 2], j3 = b[bi + 3] ^ x[xi + 3];
25
+ let j4 = b[bi + 4] ^ x[xi + 4], j5 = b[bi + 5] ^ x[xi + 5], j6 = b[bi + 6] ^ x[xi + 6], j7 = b[bi + 7] ^ x[xi + 7];
26
+ let j8 = b[bi + 8] ^ x[xi + 8], j9 = b[bi + 9] ^ x[xi + 9], j10 = b[bi + 10] ^ x[xi + 10], j11 = b[bi + 11] ^ x[xi + 11];
27
+ let j12 = b[bi + 12] ^ x[xi + 12], j13 = b[bi + 13] ^ x[xi + 13], j14 = b[bi + 14] ^ x[xi + 14], j15 = b[bi + 15] ^ x[xi + 15];
28
+ let x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7;
29
+ let x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15;
30
+ for (let i = 0; i < 8; i += 2) {
31
+ x4 ^= rotl((x0 + x12) | 0, 7);
32
+ x8 ^= rotl((x4 + x0) | 0, 9);
33
+ x12 ^= rotl((x8 + x4) | 0, 13);
34
+ x0 ^= rotl((x12 + x8) | 0, 18);
35
+ x9 ^= rotl((x5 + x1) | 0, 7);
36
+ x13 ^= rotl((x9 + x5) | 0, 9);
37
+ x1 ^= rotl((x13 + x9) | 0, 13);
38
+ x5 ^= rotl((x1 + x13) | 0, 18);
39
+ x14 ^= rotl((x10 + x6) | 0, 7);
40
+ x2 ^= rotl((x14 + x10) | 0, 9);
41
+ x6 ^= rotl((x2 + x14) | 0, 13);
42
+ x10 ^= rotl((x6 + x2) | 0, 18);
43
+ x3 ^= rotl((x15 + x11) | 0, 7);
44
+ x7 ^= rotl((x3 + x15) | 0, 9);
45
+ x11 ^= rotl((x7 + x3) | 0, 13);
46
+ x15 ^= rotl((x11 + x7) | 0, 18);
47
+ x1 ^= rotl((x0 + x3) | 0, 7);
48
+ x2 ^= rotl((x1 + x0) | 0, 9);
49
+ x3 ^= rotl((x2 + x1) | 0, 13);
50
+ x0 ^= rotl((x3 + x2) | 0, 18);
51
+ x6 ^= rotl((x5 + x4) | 0, 7);
52
+ x7 ^= rotl((x6 + x5) | 0, 9);
53
+ x4 ^= rotl((x7 + x6) | 0, 13);
54
+ x5 ^= rotl((x4 + x7) | 0, 18);
55
+ x11 ^= rotl((x10 + x9) | 0, 7);
56
+ x8 ^= rotl((x11 + x10) | 0, 9);
57
+ x9 ^= rotl((x8 + x11) | 0, 13);
58
+ x10 ^= rotl((x9 + x8) | 0, 18);
59
+ x12 ^= rotl((x15 + x14) | 0, 7);
60
+ x13 ^= rotl((x12 + x15) | 0, 9);
61
+ x14 ^= rotl((x13 + x12) | 0, 13);
62
+ x15 ^= rotl((x14 + x13) | 0, 18);
63
+ }
64
+ out[oi] = (j0 + x0) | 0;
65
+ out[oi + 1] = (j1 + x1) | 0;
66
+ out[oi + 2] = (j2 + x2) | 0;
67
+ out[oi + 3] = (j3 + x3) | 0;
68
+ out[oi + 4] = (j4 + x4) | 0;
69
+ out[oi + 5] = (j5 + x5) | 0;
70
+ out[oi + 6] = (j6 + x6) | 0;
71
+ out[oi + 7] = (j7 + x7) | 0;
72
+ out[oi + 8] = (j8 + x8) | 0;
73
+ out[oi + 9] = (j9 + x9) | 0;
74
+ out[oi + 10] = (j10 + x10) | 0;
75
+ out[oi + 11] = (j11 + x11) | 0;
76
+ out[oi + 12] = (j12 + x12) | 0;
77
+ out[oi + 13] = (j13 + x13) | 0;
78
+ out[oi + 14] = (j14 + x14) | 0;
79
+ out[oi + 15] = (j15 + x15) | 0;
80
+ }
81
+ /** BlockMix with Salsa20/8: `input` (2r blocks at `ii`) into `out` (at `oi`), even blocks first, then odd. */
82
+ function blockMix(input, ii, out, oi, r) {
83
+ let head = oi;
84
+ let tail = oi + 16 * r;
85
+ // X starts as the last block.
86
+ const x = new Uint32Array(16);
87
+ x.set(input.subarray(ii + (2 * r - 1) * 16, ii + 2 * r * 16));
88
+ for (let i = 0; i < 2 * r; i += 1) {
89
+ const target = i % 2 === 0 ? head : tail;
90
+ salsaXor(input, ii + i * 16, x, 0, out, target);
91
+ x.set(out.subarray(target, target + 16));
92
+ if (i % 2 === 0)
93
+ head += 16;
94
+ else
95
+ tail += 16;
96
+ }
97
+ }
98
+ /**
99
+ * A check takes 128 · N · r bytes while it runs: 16 MB for Firebase's usual parameters, 32 MB for Better Auth's. A
100
+ * Worker's isolate has 128 MB, so at most two run at once in one; the others wait their turn.
101
+ */
102
+ const AT_ONCE = 2;
103
+ let running = 0;
104
+ const queue = [];
105
+ /** How many scrypt computations hold their memory now (at most two). */
106
+ export const scryptRunning = () => running;
107
+ /** scrypt(password, salt, N, r, p) to `bytes` bytes. */
108
+ export async function scrypt(password, salt, n, r, p, bytes) {
109
+ if (n < 2 || (n & (n - 1)) !== 0 || n > 2 ** 20 || r < 1 || r > 32 || p < 1 || p > 16)
110
+ throw new Error("scrypt: parameters out of range");
111
+ if (running < AT_ONCE)
112
+ running += 1;
113
+ else
114
+ await new Promise((go) => queue.push(go)); // handed the slot of one that ends
115
+ try {
116
+ return await mix(password, salt, n, r, p, bytes);
117
+ }
118
+ finally {
119
+ const next = queue.shift();
120
+ if (next)
121
+ next();
122
+ else
123
+ running -= 1;
124
+ }
125
+ }
126
+ async function mix(password, salt, n, r, p, bytes) {
127
+ const words = 32 * r;
128
+ const b = await pbkdf2(password, salt, p * 128 * r);
129
+ const b32 = new Uint32Array(p * words);
130
+ for (let i = 0; i < b32.length; i += 1)
131
+ b32[i] = b[i * 4] | (b[i * 4 + 1] << 8) | (b[i * 4 + 2] << 16) | (b[i * 4 + 3] << 24);
132
+ const v = new Uint32Array(n * words);
133
+ const t = new Uint32Array(words);
134
+ // Gives way roughly every few milliseconds.
135
+ const every = Math.max(1, Math.floor(16384 / r));
136
+ for (let k = 0; k < p; k += 1) {
137
+ const x = b32.subarray(k * words, (k + 1) * words);
138
+ v.set(x, 0);
139
+ for (let i = 0; i < n - 1; i += 1) {
140
+ blockMix(v, i * words, v, (i + 1) * words, r);
141
+ if (i % every === every - 1)
142
+ await pause();
143
+ }
144
+ blockMix(v, (n - 1) * words, x, 0, r);
145
+ for (let i = 0; i < n; i += 1) {
146
+ const j = x[words - 16] & (n - 1);
147
+ for (let w = 0; w < words; w += 1)
148
+ t[w] = x[w] ^ v[j * words + w];
149
+ blockMix(t, 0, x, 0, r);
150
+ if (i % every === every - 1)
151
+ await pause();
152
+ }
153
+ }
154
+ const out = new Uint8Array(b32.length * 4);
155
+ for (let i = 0; i < b32.length; i += 1) {
156
+ out[i * 4] = b32[i] & 255;
157
+ out[i * 4 + 1] = (b32[i] >>> 8) & 255;
158
+ out[i * 4 + 2] = (b32[i] >>> 16) & 255;
159
+ out[i * 4 + 3] = (b32[i] >>> 24) & 255;
160
+ }
161
+ return pbkdf2(password, out, bytes);
162
+ }
163
+ /**
164
+ * Firebase Auth's modified scrypt: scrypt(password, salt ‖ salt separator, N = 2^memCost, r = rounds, p = 1, 64
165
+ * bytes); its first 32 bytes are an AES-256 key, and the hash is the project's signer key encrypted with it in CTR
166
+ * mode from a zero counter.
167
+ */
168
+ export async function firebaseScrypt(password, o) {
169
+ const salt = new Uint8Array(o.salt.length + o.saltSeparator.length);
170
+ salt.set(o.salt);
171
+ salt.set(o.saltSeparator, o.salt.length);
172
+ const dk = await scrypt(utf8(password), salt, 2 ** o.memCost, o.rounds, 1, 64);
173
+ const key = await crypto.subtle.importKey("raw", dk.slice(0, 32), "AES-CTR", false, ["encrypt"]);
174
+ return new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CTR", counter: new Uint8Array(16), length: 64 }, key, o.signerKey));
175
+ }
176
+ /** Better Auth's scrypt: the password NFKC, the salt the hex text itself, N = 16384, r = 16, p = 1, 64 bytes. */
177
+ export async function betterAuthScrypt(password, saltHex) {
178
+ return scrypt(utf8(password.normalize("NFKC")), utf8(saltHex), 16384, 16, 1, 64);
179
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * AWS Signature Version 4 with WebCrypto, enough for the two calls the senders make (SES's SendEmail, SNS's Publish):
3
+ * a POST with a body, signed with an access key. No SDK.
4
+ */
5
+ export interface AwsCredentials {
6
+ region: string;
7
+ accessKeyId: string;
8
+ secretAccessKey: string;
9
+ /** For temporary credentials (a role's). */
10
+ sessionToken?: string;
11
+ }
12
+ /** The headers that sign a POST of `body` to `url` for `service`. */
13
+ export declare function signAws(c: AwsCredentials, service: string, url: string, body: string, contentType: string, now?: Date, method?: string): Promise<Record<string, string>>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * AWS Signature Version 4 with WebCrypto, enough for the two calls the senders make (SES's SendEmail, SNS's Publish):
3
+ * a POST with a body, signed with an access key. No SDK.
4
+ */
5
+ import { utf8 } from "../base64.js";
6
+ const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
7
+ const sha256 = async (s) => hex(await crypto.subtle.digest("SHA-256", utf8(s)));
8
+ async function hmac(key, s) {
9
+ const k = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
10
+ return crypto.subtle.sign("HMAC", k, utf8(s));
11
+ }
12
+ /** The headers that sign a POST of `body` to `url` for `service`. */
13
+ export async function signAws(c, service, url, body, contentType, now = new Date(), method = "POST") {
14
+ const u = new URL(url);
15
+ const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
16
+ const day = amzDate.slice(0, 8);
17
+ const payloadHash = await sha256(body);
18
+ const headers = {
19
+ "content-type": contentType,
20
+ host: u.host,
21
+ "x-amz-content-sha256": payloadHash,
22
+ "x-amz-date": amzDate,
23
+ ...(c.sessionToken ? { "x-amz-security-token": c.sessionToken } : {}),
24
+ };
25
+ const names = Object.keys(headers).sort();
26
+ const canonical = [
27
+ method,
28
+ u.pathname || "/",
29
+ u.searchParams.toString(),
30
+ ...names.map((n) => `${n}:${headers[n].trim()}`),
31
+ "",
32
+ names.join(";"),
33
+ payloadHash,
34
+ ].join("\n");
35
+ const scope = `${day}/${c.region}/${service}/aws4_request`;
36
+ const toSign = ["AWS4-HMAC-SHA256", amzDate, scope, await sha256(canonical)].join("\n");
37
+ let key = await hmac(utf8(`AWS4${c.secretAccessKey}`), day);
38
+ key = await hmac(key, c.region);
39
+ key = await hmac(key, service);
40
+ key = await hmac(key, "aws4_request");
41
+ const signature = hex(await hmac(key, toSign));
42
+ const { host: _host, ...rest } = headers;
43
+ return {
44
+ ...rest,
45
+ authorization: `AWS4-HMAC-SHA256 Credential=${c.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${signature}`,
46
+ };
47
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * For development: the code is written to the server's log instead of being sent. It refuses to run in production
3
+ * (`NODE_ENV=production`, or `DIRECT_AUTH_DEV` not set to 1), so a deployment never logs a working code.
4
+ */
5
+ import type { Sender } from "./types.ts";
6
+ export declare function devSender(env?: Record<string, string | undefined>, log?: (line: string) => void): Sender;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * For development: the code is written to the server's log instead of being sent. It refuses to run in production
3
+ * (`NODE_ENV=production`, or `DIRECT_AUTH_DEV` not set to 1), so a deployment never logs a working code.
4
+ */
5
+ export function devSender(env = globalThis.process?.env ?? {}, log = console.log) {
6
+ if (env.NODE_ENV === "production" || env.DIRECT_AUTH_DEV !== "1") {
7
+ throw new Error("devSender only runs with DIRECT_AUTH_DEV=1 and outside production");
8
+ }
9
+ return async (m) => {
10
+ log(`[direct-auth] ${m.channel} code for ${m.to}: ${m.code}`);
11
+ return { ok: true };
12
+ };
13
+ }
@@ -0,0 +1,5 @@
1
+ export { resend, postmark, mailgun, sendgrid, ses } from "./mail.ts";
2
+ export { twilio, vonage, sns, smsGateway } from "./sms.ts";
3
+ export { smtp, mime } from "./smtp.ts";
4
+ export { devSender } from "./dev.ts";
5
+ export type { Sender, Outgoing, SendResult } from "./types.ts";
@@ -0,0 +1,4 @@
1
+ export { resend, postmark, mailgun, sendgrid, ses } from "./mail.js";
2
+ export { twilio, vonage, sns, smsGateway } from "./sms.js";
3
+ export { smtp, mime } from "./smtp.js";
4
+ export { devSender } from "./dev.js";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Email senders for the codes, each one HTTP call to the provider's API. `from` is the sender as people will see it
3
+ * (`"Acme <hello@acme.com>"`), on a domain the provider has verified.
4
+ */
5
+ import { type AwsCredentials } from "./aws.ts";
6
+ import { type HttpOptions, type Sender } from "./types.ts";
7
+ export interface FromOptions extends HttpOptions {
8
+ from: string;
9
+ }
10
+ export declare function resend(o: FromOptions & {
11
+ apiKey: string;
12
+ }): Sender;
13
+ export declare function postmark(o: FromOptions & {
14
+ serverToken: string;
15
+ messageStream?: string;
16
+ }): Sender;
17
+ export declare function mailgun(o: FromOptions & {
18
+ apiKey: string;
19
+ domain: string;
20
+ region?: "us" | "eu";
21
+ }): Sender;
22
+ export declare function sendgrid(o: FromOptions & {
23
+ apiKey: string;
24
+ }): Sender;
25
+ /** Amazon SES (API v2), with an access key allowed `ses:SendEmail`. */
26
+ export declare function ses(o: FromOptions & AwsCredentials): Sender;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Email senders for the codes, each one HTTP call to the provider's API. `from` is the sender as people will see it
3
+ * (`"Acme <hello@acme.com>"`), on a domain the provider has verified.
4
+ */
5
+ import { signAws } from "./aws.js";
6
+ import { basic, form, post } from "./types.js";
7
+ export function resend(o) {
8
+ return (m) => post("https://api.resend.com/emails", {
9
+ headers: { authorization: `Bearer ${o.apiKey}`, "content-type": "application/json" },
10
+ body: JSON.stringify({ from: o.from, to: [m.to], subject: m.subject, text: m.text, html: m.html }),
11
+ }, o, "resend");
12
+ }
13
+ export function postmark(o) {
14
+ return (m) => post("https://api.postmarkapp.com/email", {
15
+ headers: { "x-postmark-server-token": o.serverToken, "content-type": "application/json", accept: "application/json" },
16
+ body: JSON.stringify({
17
+ From: o.from,
18
+ To: m.to,
19
+ Subject: m.subject,
20
+ TextBody: m.text,
21
+ HtmlBody: m.html,
22
+ MessageStream: o.messageStream ?? "outbound",
23
+ }),
24
+ }, o, "postmark");
25
+ }
26
+ export function mailgun(o) {
27
+ const host = o.region === "eu" ? "api.eu.mailgun.net" : "api.mailgun.net";
28
+ return (m) => post(`https://${host}/v3/${encodeURIComponent(o.domain)}/messages`, {
29
+ headers: { authorization: basic("api", o.apiKey), "content-type": "application/x-www-form-urlencoded" },
30
+ body: form({ from: o.from, to: m.to, subject: m.subject, text: m.text, html: m.html }),
31
+ }, o, "mailgun");
32
+ }
33
+ export function sendgrid(o) {
34
+ const from = /^(.*)<([^>]+)>\s*$/.exec(o.from);
35
+ const sender = from ? { email: from[2].trim(), name: from[1].trim().replace(/^"|"$/g, "") || undefined } : { email: o.from };
36
+ return (m) => post("https://api.sendgrid.com/v3/mail/send", {
37
+ headers: { authorization: `Bearer ${o.apiKey}`, "content-type": "application/json" },
38
+ body: JSON.stringify({
39
+ personalizations: [{ to: [{ email: m.to }] }],
40
+ from: sender,
41
+ subject: m.subject,
42
+ content: [
43
+ { type: "text/plain", value: m.text },
44
+ { type: "text/html", value: m.html },
45
+ ],
46
+ }),
47
+ }, o, "sendgrid");
48
+ }
49
+ /** Amazon SES (API v2), with an access key allowed `ses:SendEmail`. */
50
+ export function ses(o) {
51
+ const url = `https://email.${o.region}.amazonaws.com/v2/email/outbound-emails`;
52
+ return async (m) => {
53
+ const body = JSON.stringify({
54
+ FromEmailAddress: o.from,
55
+ Destination: { ToAddresses: [m.to] },
56
+ Content: {
57
+ Simple: {
58
+ Subject: { Data: m.subject, Charset: "UTF-8" },
59
+ Body: { Text: { Data: m.text, Charset: "UTF-8" }, Html: { Data: m.html, Charset: "UTF-8" } },
60
+ },
61
+ },
62
+ });
63
+ const headers = await signAws(o, "ses", url, body, "application/json");
64
+ return post(url, { headers, body }, o, "ses");
65
+ };
66
+ }