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
package/dist/auth.js ADDED
@@ -0,0 +1,699 @@
1
+ /**
2
+ * `createAuth`: everything a backend needs to sign people in, as plain functions over its database. The HTTP routes
3
+ * (`direct-auth/server`) are a thin layer over these, and an app that has its own router can call them directly.
4
+ *
5
+ * const auth = await createAuth({
6
+ * sql: await openSqlite("./auth.db"),
7
+ * issuer: "https://auth.example.com",
8
+ * keys: process.env.DIRECT_AUTH_SIGNING_KEYS,
9
+ * apple: { clientIds: ["com.example.app"] },
10
+ * google: { clientIds: ["123-abc.apps.googleusercontent.com"] },
11
+ * email: { send: resend({ apiKey, from: "Example <hello@example.com>" }) },
12
+ * sms: { send: twilio({ … }), countries: ["+598"] },
13
+ * app: "Example",
14
+ * });
15
+ * const r = await auth.signInWithApple({ idToken, nonce }); // { ok, user, tokens } or { ok: false, reason }
16
+ */
17
+ import { changeEmail, createGuest, deleteUserRows, getUser, identitiesOf, linkIdentity, listIdentities, resolveUser, staleGuests, unlinkIdentity, userOfIdentity, ownerOf, removePasskey, removePasswordHash, } from "./accounts.js";
18
+ import { bcryptCost, burnBcrypt, burnPassword, burnScrypt, defaultIterations, firebaseParams, hashPassword, maxIterations, movedKind, pbkdf2Iterations, topUp, verifyPassword } from "./passwords.js";
19
+ import { count, hit } from "./db/limits.js";
20
+ import { passkeys as passkeyStore } from "./passkeys.js";
21
+ import { appleRevoker } from "./providers/apple-revoke.js";
22
+ import { APPLE_ISSUER } from "./providers/apple.js";
23
+ import { remoteJwks } from "./jwks.js";
24
+ import { verifyJwt } from "./jwt.js";
25
+ import { checkCode, createCode, DEFAULT_LIMITS, pruneCodes } from "./codes.js";
26
+ import { hmac, hmacKey, sha256 } from "./crypto.js";
27
+ import { pruneLimits } from "./db/limits.js";
28
+ import { migrate } from "./db/schema.js";
29
+ import { withTables } from "./db/sql.js";
30
+ import { loadSigningKeys } from "./keys.js";
31
+ import { renderCode } from "./messages.js";
32
+ import { allowedPrefix, normalizePhone } from "./phone.js";
33
+ import { apple as appleVerifier } from "./providers/apple.js";
34
+ import { google as googleVerifier } from "./providers/google.js";
35
+ import { github as githubVerifier } from "./providers/github.js";
36
+ import { accessToken, checkAccessToken, createSession, revokeOtherSessions, liveSession, listSessions, refreshSession, revokeSession, revokeUserSessions, sessionOfRefresh, } from "./sessions.js";
37
+ import { fromBase64, utf8 } from "./base64.js";
38
+ const EMAIL = /^[^\s@<>()[\]\\,;:"]+@[^\s@<>()[\]\\,;:"]+\.[^\s@<>()[\]\\,;:"]+$/;
39
+ export function normalizeEmail(input) {
40
+ const e = input.trim().toLowerCase();
41
+ return e.length <= 254 && EMAIL.test(e) ? e : null;
42
+ }
43
+ export async function createAuth(o) {
44
+ if (!o.keys)
45
+ throw new Error("direct-auth: keys is missing (DIRECT_AUTH_SIGNING_KEYS: npx direct-auth init makes them)");
46
+ const keys = await loadSigningKeys(o.keys);
47
+ const sql = withTables(o.sql, o.tablePrefix ?? "auth_");
48
+ if (o.migrate !== false)
49
+ await migrate(sql);
50
+ const issuer = o.issuer.replace(/\/+$/, "");
51
+ const sessions = { ...o, issuer };
52
+ const limits = { ...DEFAULT_LIMITS, ...o.limits };
53
+ // The codes' HMAC key comes from the signing key, so there is no other secret to keep: a rotation only voids codes
54
+ // still waiting, which last ten minutes.
55
+ const codeKey = await hmacKey(utf8(`direct-auth codes ${keys.secret}`));
56
+ const apple = o.apple ? appleVerifier(o.apple) : null;
57
+ const revoker = o.apple?.revoke ? appleRevoker(o.apple.revoke) : null;
58
+ const appleJwks = o.apple ? o.apple.jwks ?? remoteJwks("https://appleid.apple.com/auth/keys", o.apple) : null;
59
+ const pk = o.passkeys ? passkeyStore(sql, o.passkeys) : null;
60
+ const google = o.google ? googleVerifier(o.google) : null;
61
+ const gh = o.github ? githubVerifier(o.github) : null;
62
+ if (o.sms && !o.sms.countries.length)
63
+ throw new Error("direct-auth: sms.countries is empty: say which calling codes SMS may go to");
64
+ /**
65
+ * A nonce works once: the token it came with can't be sent again (copied from a log, a proxy, another backend).
66
+ * Kept as a hash until the token would have expired anyway.
67
+ */
68
+ const spend = async (kind, value, until, now) => {
69
+ try {
70
+ await sql.run(`insert into {challenges} (id, kind, challenge, expires_at) values (?, ?, '', ?)`, [
71
+ `${kind}:${await sha256(value)}`,
72
+ kind,
73
+ Math.max(until, now + 60_000),
74
+ ]);
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ };
81
+ const tokenExp = (token, now) => {
82
+ try {
83
+ const exp = JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))).exp;
84
+ return typeof exp === "number" ? exp * 1000 : now + 3_600_000;
85
+ }
86
+ catch {
87
+ return now + 3_600_000;
88
+ }
89
+ };
90
+ // Supabase Auth's users waiting to be moved here: migrate's dry run leaves 'supabase_pending' in {meta}, and a
91
+ // finished move takes it out. Meanwhile a sign-in would make a second, empty account for one of them, and the move
92
+ // would hand it their address, so nobody is made. Nothing else turns this on (auth.users' rows alone never do).
93
+ // No note: asked again a minute later at most; a note: asked every time, so the move ends the wait at once.
94
+ let clearUntil = sql.dialect === "postgres" ? 0 : Infinity;
95
+ const migrationPending = async () => {
96
+ const now = Date.now();
97
+ if (now < clearUntil)
98
+ return false;
99
+ let waiting = false;
100
+ try {
101
+ waiting = (await sql.all(`select 1 as x from {meta} where key = 'supabase_pending'`)).length > 0;
102
+ }
103
+ catch {
104
+ // No {meta} readable: nothing waits.
105
+ }
106
+ if (!waiting)
107
+ clearUntil = now + 60_000;
108
+ return waiting;
109
+ };
110
+ const finish = async (r, c) => {
111
+ if (!r.ok)
112
+ return r;
113
+ if (await migrationPending())
114
+ return { ok: false, reason: "migration_pending" };
115
+ const now = c.now ?? Date.now();
116
+ const { user, created } = await resolveUser(sql, r.identity, now);
117
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
118
+ return { ok: true, user, tokens, created };
119
+ };
120
+ const startCode = async (channel, target, locale, c, prefix) => {
121
+ const conf = channel === "email" ? o.email : o.sms;
122
+ const made = await createCode(sql, codeKey, { channel, target, ip: c.ip, prefix, limits, options: conf, now: c.now });
123
+ if (!made.ok)
124
+ return made;
125
+ const message = renderCode({ channel, code: made.code, app: o.app, locale, minutes: made.minutes, domain: o.sms?.domain });
126
+ const sent = await conf.send({ channel, to: target, code: made.code, ...message, locale: locale ?? "en" });
127
+ return sent.ok ? { ok: true } : { ok: false, reason: "send_failed", detail: sent.reason };
128
+ };
129
+ const iterations = o.passwords?.iterations ?? defaultIterations();
130
+ // How long a password check takes must not say whether the address has an account. A check costs what its hash
131
+ // costs: PBKDF2 at its iteration count, or bcrypt (hashes moved from Supabase Auth, where every account has one,
132
+ // random for those who never set a password). So each PBKDF2 check is topped up to the highest count stored, and an
133
+ // address with no hash to check does the work of one that has: bcrypt or PBKDF2, picked for that address by a keyed
134
+ // hash in the proportion the stored hashes have, the same every time it's tried. Nobody pays for both.
135
+ // The proportions are read again every 10 minutes, and at once after a move (`supabase_moved` or `source_moved` in {meta}).
136
+ const decoyKey = await hmacKey(utf8(`direct-auth decoys ${keys.secret}`));
137
+ let stats;
138
+ const hashStats = async () => {
139
+ const marks = await sql.all(`select value from {meta} where key in ('supabase_moved', 'source_moved') order by key`);
140
+ const marker = marks.map((m) => m.value).join(",") || null;
141
+ if (stats && Date.now() - stats.at < 10 * 60_000 && stats.marker === marker)
142
+ return stats;
143
+ const [n] = await sql.all(`select sum(case when password_hash like '$2%' then 1 else 0 end) as b, sum(case when password_hash like '$pbkdf2-%' then 1 else 0 end) as p,
144
+ sum(case when password_hash like '$fbscrypt$%' then 1 else 0 end) as f, sum(case when password_hash like '$bascrypt$%' then 1 else 0 end) as a from {users}`);
145
+ const [one] = await sql.all(`select password_hash from {users} where password_hash like '$2%' limit 1`);
146
+ const [fire] = await sql.all(`select password_hash from {users} where password_hash like '$fbscrypt$%' limit 1`);
147
+ // The highest iteration count stored, in one row whatever the number of users: \`$pbkdf2-sha256$i=\` is 17
148
+ // characters, then the count's digits up to the next \`$\` (one column per length, as SQLite has no regex).
149
+ const digits = [1, 2, 3, 4, 5, 6, 7, 8, 9];
150
+ const [top9] = await sql.all(`select ${digits.map((d) => `max(case when substr(password_hash, ${18 + d}, 1) = '$' then cast(substr(password_hash, 18, ${d}) as integer) end) as i${d}`).join(", ")}
151
+ from {users} where password_hash like '$pbkdf2-sha256$i=%'`);
152
+ const b = Number(n?.b ?? 0);
153
+ const k = Number(n?.p ?? 0);
154
+ const fb = Number(n?.f ?? 0);
155
+ const ba = Number(n?.a ?? 0);
156
+ const all = b + k + fb + ba;
157
+ const top = Math.min(digits.reduce((m, d) => Math.max(m, Number(top9?.[`i${d}`] ?? 0) || 0), iterations), maxIterations());
158
+ stats = {
159
+ at: Date.now(),
160
+ marker,
161
+ bcryptShare: all ? b / all : 0,
162
+ bcryptCost: (one && bcryptCost(one.password_hash)) || 10,
163
+ topIterations: top,
164
+ firebaseShare: all ? fb / all : 0,
165
+ firebase: (fire && firebaseParams(fire.password_hash)) || { rounds: 8, memCost: 14 },
166
+ betterAuthShare: all ? ba / all : 0,
167
+ };
168
+ return stats;
169
+ };
170
+ const decoy = async (email, password, s) => {
171
+ const pick = fromBase64(await hmac(decoyKey, email));
172
+ const draw = ((pick[0] << 24) | (pick[1] << 16) | (pick[2] << 8) | pick[3]) >>> 0;
173
+ const at = draw / 2 ** 32;
174
+ if (at < s.bcryptShare)
175
+ await burnBcrypt(password, s.bcryptCost);
176
+ else if (at < s.bcryptShare + s.firebaseShare)
177
+ await burnScrypt(password, "firebase", s.firebase);
178
+ else if (at < s.bcryptShare + s.firebaseShare + s.betterAuthShare)
179
+ await burnScrypt(password, "better-auth");
180
+ else
181
+ await burnPassword(password, s.topIterations);
182
+ };
183
+ const minLength = o.passwords?.minLength ?? 8;
184
+ const passwordProblem = (p) => typeof p !== "string" || [...p].length < minLength ? "password_too_short" : p.length > 1024 ? "password_too_long" : null;
185
+ const checkApple = async (a, c) => {
186
+ if (!apple)
187
+ return { ok: false, reason: "apple_not_configured" };
188
+ const r = await apple.verify(a.idToken, { nonce: a.nonce, name: a.name, now: c.now });
189
+ const now = c.now ?? Date.now();
190
+ if (r.ok && a.nonce && !(await spend("nonce-apple", a.nonce, tokenExp(a.idToken, now), now)))
191
+ return { ok: false, reason: "apple_nonce_reused" };
192
+ return r;
193
+ };
194
+ /**
195
+ * The app's authorization code becomes Apple's refresh token, kept sealed for revoking at deletion. A failure here
196
+ * doesn't stop the sign-in: deleting the account asks the app for a new code instead.
197
+ */
198
+ const keepAppleToken = async (identity, a) => {
199
+ if (!revoker || !a.authorizationCode || !identity.clientId)
200
+ return;
201
+ const kept = await revoker.exchange(a.authorizationCode, identity.clientId, a.redirectUri);
202
+ if (kept.ok) {
203
+ await sql.run(`update {identities} set data = ? where provider = 'apple' and subject = ?`, [
204
+ JSON.stringify({ clientId: identity.clientId, token: kept.sealed }),
205
+ identity.subject,
206
+ ]);
207
+ }
208
+ };
209
+ // A code costs GitHub three calls: limited per IP, as a refresh is.
210
+ const checkGitHub = async (a, c) => {
211
+ if (!gh)
212
+ return { ok: false, reason: "github_not_configured" };
213
+ if (!a.code || a.code.length > 512)
214
+ return { ok: false, reason: "github_invalid_code" };
215
+ const now = c.now ?? Date.now();
216
+ // Per IP; with none known (no proxy header trusted), no shared bucket one caller could fill for everyone.
217
+ if (c.ip && !(await hit(sql, `github-ip:${c.ip}`, limits.githubPerIp, now)))
218
+ return { ok: false, reason: "rate_limited" };
219
+ return gh.exchange(a);
220
+ };
221
+ const checkGoogle = async (a, c) => {
222
+ if (!google)
223
+ return { ok: false, reason: "google_not_configured" };
224
+ const r = await google.verify(a.idToken, { nonce: a.nonce, now: c.now });
225
+ const now = c.now ?? Date.now();
226
+ if (r.ok && a.nonce && !(await spend("nonce-google", a.nonce, tokenExp(a.idToken, now), now)))
227
+ return { ok: false, reason: "google_nonce_reused" };
228
+ return r;
229
+ };
230
+ const checkEmailCode = async (a, c) => {
231
+ if (!o.email)
232
+ return { ok: false, reason: "email_not_configured" };
233
+ const email = normalizeEmail(a.email);
234
+ if (!email)
235
+ return { ok: false, reason: "invalid_email" };
236
+ const r = await checkCode(sql, codeKey, { channel: "email", target: email, code: a.code, options: o.email, ip: c.ip, limits, now: c.now });
237
+ return r.ok ? { ok: true, email } : r;
238
+ };
239
+ /** A new access token for the same session, saying what changed (`email`, `is_anonymous`). */
240
+ const reissue = async (userId, sessionId, now) => {
241
+ const user = await getUser(sql, userId);
242
+ if (!user)
243
+ return { ok: false, reason: "not_found" };
244
+ const access = await accessToken(keys, sessions, user, sessionId, now);
245
+ return { ok: true, user, accessToken: access.token, expiresIn: access.expiresIn };
246
+ };
247
+ return {
248
+ keys,
249
+ sql,
250
+ issuer,
251
+ /** The identity token an app got from Sign in with Apple, with the raw nonce it asked with, and the name Apple gave it the first time. */
252
+ async signInWithApple(a, c = {}) {
253
+ const r = await checkApple(a, c);
254
+ const signed = await finish(r, c);
255
+ if (signed.ok && r.ok)
256
+ await keepAppleToken(r.identity, a);
257
+ return signed;
258
+ },
259
+ async signInWithGoogle(a, c = {}) {
260
+ return finish(await checkGoogle(a, c), c);
261
+ },
262
+ /** GitHub: the code its redirect gave the app, the redirect URI, and the PKCE verifier the app made. */
263
+ async signInWithGitHub(a, c = {}) {
264
+ return finish(await checkGitHub(a, c), c);
265
+ },
266
+ /** A guest: an account with nothing to sign in with yet. Linking a way in later keeps its id. */
267
+ async signInAsGuest(a = {}, c = {}) {
268
+ if (!o.guests)
269
+ return { ok: false, reason: "guests_not_configured" };
270
+ const now = c.now ?? Date.now();
271
+ const allowed = c.ip ? await hit(sql, `guest-ip:${c.ip}`, limits.guestPerIp, now) : await hit(sql, "guest-no-ip", limits.guestWithoutIp, now);
272
+ if (!allowed)
273
+ return { ok: false, reason: "rate_limited" };
274
+ if (await migrationPending())
275
+ return { ok: false, reason: "migration_pending" };
276
+ const name = typeof a.name === "string" && a.name.trim() ? a.name.trim().slice(0, 100) : null;
277
+ const user = await createGuest(sql, name, now);
278
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
279
+ return { ok: true, user, tokens, created: true };
280
+ },
281
+ /**
282
+ * A guest moved from Supabase Auth, back on their device: the refresh token of the anonymous session the app kept
283
+ * from Supabase (the move stored its hash, for 180 days). It works once, for a user who is still a guest, and
284
+ * answers a session for that same user; anything else is `invalid_token`. Supabase Auth still trades a refresh
285
+ * token for a new one with its sign-ins off, so an old app that refreshed after the move holds a token the move
286
+ * never saw: one Supabase has and hasn't revoked counts too, while that user's claim waits.
287
+ */
288
+ async claimGuest(a, c = {}) {
289
+ const now = c.now ?? Date.now();
290
+ const allowed = c.ip ? await hit(sql, `guest-ip:${c.ip}`, limits.guestPerIp, now) : await hit(sql, "guest-no-ip", limits.guestWithoutIp, now);
291
+ if (!allowed)
292
+ return { ok: false, reason: "rate_limited" };
293
+ const token = typeof a.supabaseRefreshToken === "string" ? a.supabaseRefreshToken.slice(0, 1024) : "";
294
+ // Taken and spent in one statement: two claims at once, one session.
295
+ let [row] = await sql.all(`delete from {guest_claims} where hash = ? and expires_at > ? returning user_id`, [await sha256(token), now]);
296
+ if (!row && token && sql.dialect === "postgres") {
297
+ try {
298
+ const [rt] = await sql.all(`select user_id::text as user_id from auth.refresh_tokens where token = ? and not coalesce(revoked, false)`, [token]);
299
+ if (rt)
300
+ [row] = await sql.all(`delete from {guest_claims} where user_id = ? and expires_at > ? returning user_id`, [String(rt.user_id), now]);
301
+ }
302
+ catch {
303
+ // No auth.refresh_tokens here, or not readable by this role: only the tokens the move kept count.
304
+ }
305
+ }
306
+ // Once: whichever token it was, that user's other claims go too.
307
+ if (row)
308
+ await sql.run(`delete from {guest_claims} where user_id = ?`, [String(row.user_id)]);
309
+ const user = row ? await getUser(sql, String(row.user_id)) : null;
310
+ if (!user?.isGuest)
311
+ return { ok: false, reason: "invalid_token" };
312
+ await sql.run(`update {users} set last_sign_in_at = ?, updated_at = ? where id = ?`, [now, now, user.id]);
313
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
314
+ return { ok: true, user, tokens, created: false };
315
+ },
316
+ /**
317
+ * Email and password. Wrong address, wrong password, an account without one: all answer `invalid_credentials`,
318
+ * in the same time, so nobody learns which addresses have accounts.
319
+ */
320
+ async signInWithPassword(a, c = {}) {
321
+ if (!o.passwords)
322
+ return { ok: false, reason: "passwords_not_configured" };
323
+ const email = normalizeEmail(a.email);
324
+ if (!email)
325
+ return { ok: false, reason: "invalid_email" };
326
+ const now = c.now ?? Date.now();
327
+ // Tries per address from one IP, tightly; per address from anywhere, loosely (a day's worth), so someone else
328
+ // can't easily lock the owner out; per IP across addresses.
329
+ const checks = [[`password:${email}`, limits.passwordPerAccount]];
330
+ if (c.ip)
331
+ checks.unshift([`password-ip:${c.ip}`, limits.passwordPerIp], [`password-ip-account:${c.ip}:${email}`, limits.passwordPerIpAccount]);
332
+ for (const [k, l] of checks)
333
+ if ((await count(sql, k, l, now)) >= l.max)
334
+ return { ok: false, reason: "rate_limited" };
335
+ for (const [k, l] of checks)
336
+ if (!(await hit(sql, k, l, now)))
337
+ return { ok: false, reason: "rate_limited" };
338
+ if (typeof a.password !== "string" || a.password.length > 1024)
339
+ return { ok: false, reason: "invalid_credentials" };
340
+ // The account's address, or any other address it has proven (a reset by code works from each of them).
341
+ // One account, the same every time: the one signing in with the address (an email identity), then the one
342
+ // going by it.
343
+ const owner = await ownerOf(sql, "email", email);
344
+ const [row] = owner ? await sql.all(`select id, password_hash from {users} where id = ?`, [owner]) : [];
345
+ const s = await hashStats();
346
+ if (!row?.password_hash || (movedKind(row.password_hash) === null && pbkdf2Iterations(row.password_hash) === null)) {
347
+ await decoy(email, a.password, s);
348
+ return { ok: false, reason: "invalid_credentials" };
349
+ }
350
+ const r = await verifyPassword(a.password, row.password_hash, iterations);
351
+ const n = pbkdf2Iterations(row.password_hash);
352
+ if (n !== null)
353
+ await topUp(a.password, n, s.topIterations);
354
+ if (!r.ok)
355
+ return { ok: false, reason: "invalid_credentials" };
356
+ // A hash moved from elsewhere (bcrypt, scrypt), or made with fewer iterations: replaced now that the password is known.
357
+ if (r.rehash) {
358
+ const again = await hashPassword(a.password, iterations);
359
+ await sql.run(`update {users} set password_hash = ? where id = ? and password_hash = ?`, [again, row.id, row.password_hash]);
360
+ }
361
+ await sql.run(`update {users} set last_sign_in_at = ? where id = ?`, [now, row.id]);
362
+ const user = (await getUser(sql, row.id));
363
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
364
+ return { ok: true, user, tokens, created: false };
365
+ },
366
+ /**
367
+ * Signing up with a password, or resetting it: the code `startEmail` sent proves the address, then the password
368
+ * is set on its account (made if new) and every other session of it ends.
369
+ */
370
+ async setPasswordWithCode(a, c = {}) {
371
+ if (!o.passwords || !o.email)
372
+ return { ok: false, reason: "passwords_not_configured" };
373
+ const email = normalizeEmail(a.email);
374
+ if (!email)
375
+ return { ok: false, reason: "invalid_email" };
376
+ const weak = passwordProblem(a.password);
377
+ if (weak)
378
+ return { ok: false, reason: weak };
379
+ const r = await checkCode(sql, codeKey, { channel: "email", target: email, code: a.code, options: o.email, ip: c.ip, limits, now: c.now });
380
+ if (!r.ok)
381
+ return r;
382
+ if (await migrationPending())
383
+ return { ok: false, reason: "migration_pending" };
384
+ const now = c.now ?? Date.now();
385
+ const { user: found, created } = await resolveUser(sql, { provider: "email", subject: email, email, emailVerified: true }, now);
386
+ await sql.run(`update {users} set password_hash = ?, updated_at = ? where id = ?`, [await hashPassword(a.password, iterations), now, found.id]);
387
+ await revokeOtherSessions(sql, found.id, null, now);
388
+ const user = (await getUser(sql, found.id));
389
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
390
+ return { ok: true, user, tokens, created };
391
+ },
392
+ /** Sets or replaces the signed-in user's password (an address needed), and signs their other devices out. */
393
+ async setPassword(userId, sessionId, password, c = {}) {
394
+ if (!o.passwords)
395
+ return { ok: false, reason: "passwords_not_configured" };
396
+ const weak = passwordProblem(password);
397
+ if (weak)
398
+ return { ok: false, reason: weak };
399
+ const user = await getUser(sql, userId);
400
+ if (!user)
401
+ return { ok: false, reason: "not_found" };
402
+ if (!user.email)
403
+ return { ok: false, reason: "email_needed" };
404
+ const now = c.now ?? Date.now();
405
+ if (!(await hit(sql, `password-set:${userId}`, limits.passwordSetPerUser, now)))
406
+ return { ok: false, reason: "rate_limited" };
407
+ await sql.run(`update {users} set password_hash = ?, is_guest = 0, updated_at = ? where id = ?`, [await hashPassword(password, iterations), now, userId]);
408
+ await revokeOtherSessions(sql, userId, sessionId, now);
409
+ return reissue(userId, sessionId, now);
410
+ },
411
+ /** Removes the user's password, unless it is their last way in. */
412
+ async removePassword(userId, sessionId, c = {}) {
413
+ const r = await removePasswordHash(sql, userId, c.now ?? Date.now());
414
+ return r.ok ? reissue(userId, sessionId, c.now ?? Date.now()) : r;
415
+ },
416
+ /** Adds Sign in with Apple to the signed-in user (a guest becomes a full account, with the same id). */
417
+ async linkApple(userId, sessionId, a, c = {}) {
418
+ // Linking adds a way in to an account for good: only a token made for this request (its nonce) will do, never
419
+ // one replayed from elsewhere.
420
+ if (!a.nonce)
421
+ return { ok: false, reason: "nonce_needed" };
422
+ const r = await checkApple(a, c);
423
+ if (!r.ok)
424
+ return r;
425
+ const linked = await linkIdentity(sql, userId, r.identity, c.now);
426
+ if (!linked.ok)
427
+ return linked;
428
+ await keepAppleToken(r.identity, a);
429
+ return reissue(userId, sessionId, c.now ?? Date.now());
430
+ },
431
+ /** Adds GitHub to the signed-in account: a code made for this request (GitHub's codes work once, for ten minutes). */
432
+ async linkGitHub(userId, sessionId, a, c = {}) {
433
+ const r = await checkGitHub(a, c);
434
+ if (!r.ok)
435
+ return r;
436
+ const linked = await linkIdentity(sql, userId, r.identity, c.now);
437
+ return linked.ok ? reissue(userId, sessionId, c.now ?? Date.now()) : linked;
438
+ },
439
+ async linkGoogle(userId, sessionId, a, c = {}) {
440
+ if (!a.nonce)
441
+ return { ok: false, reason: "nonce_needed" };
442
+ const r = await checkGoogle(a, c);
443
+ if (!r.ok)
444
+ return r;
445
+ const linked = await linkIdentity(sql, userId, r.identity, c.now);
446
+ return linked.ok ? reissue(userId, sessionId, c.now ?? Date.now()) : linked;
447
+ },
448
+ /** Adds an address (proven by the code `startEmail` sent) to the signed-in user. */
449
+ async linkEmail(userId, sessionId, a, c = {}) {
450
+ const checked = await checkEmailCode(a, c);
451
+ if (!checked.ok)
452
+ return checked;
453
+ const linked = await linkIdentity(sql, userId, { provider: "email", subject: checked.email, email: checked.email, emailVerified: true }, c.now);
454
+ return linked.ok ? reissue(userId, sessionId, c.now ?? Date.now()) : linked;
455
+ },
456
+ /** Changes the signed-in user's address to one proven by a code: email sign-in and the password move to it. */
457
+ async changeEmail(userId, sessionId, a, c = {}) {
458
+ const checked = await checkEmailCode(a, c);
459
+ if (!checked.ok)
460
+ return checked;
461
+ const changed = await changeEmail(sql, userId, checked.email, c.now);
462
+ return changed.ok ? reissue(userId, sessionId, c.now ?? Date.now()) : changed;
463
+ },
464
+ /** Removes one of the user's ways in (`identities()`'s `id`), unless it is the last. An Apple one is revoked at Apple. */
465
+ async unlink(userId, sessionId, identityId, c = {}) {
466
+ const r = await unlinkIdentity(sql, userId, identityId);
467
+ if (!r.ok)
468
+ return r;
469
+ if (r.removed.provider === "apple" && revoker && r.removed.data?.token && r.removed.data.clientId) {
470
+ await revoker.revoke(r.removed.data.token, r.removed.data.clientId);
471
+ }
472
+ return reissue(userId, sessionId, c.now ?? Date.now());
473
+ },
474
+ /** Sends a code to an address. Answers the same whether or not someone has signed in with it. */
475
+ async startEmail(a, c = {}) {
476
+ if (!o.email)
477
+ return { ok: false, reason: "email_not_configured" };
478
+ const email = normalizeEmail(a.email);
479
+ if (!email)
480
+ return { ok: false, reason: "invalid_email" };
481
+ return startCode("email", email, a.locale, c);
482
+ },
483
+ async verifyEmail(a, c = {}) {
484
+ const r = await checkEmailCode(a, c);
485
+ if (!r.ok)
486
+ return r;
487
+ return finish({ ok: true, identity: { provider: "email", subject: r.email, email: r.email, emailVerified: true } }, c);
488
+ },
489
+ /** Sends a code by SMS, only to the calling codes `sms.countries` allows. */
490
+ async startSms(a, c = {}) {
491
+ if (!o.sms)
492
+ return { ok: false, reason: "sms_not_configured" };
493
+ const phone = normalizePhone(a.phone);
494
+ if (!phone)
495
+ return { ok: false, reason: "invalid_phone" };
496
+ const prefix = allowedPrefix(phone, o.sms.countries);
497
+ if (!prefix)
498
+ return { ok: false, reason: "country_not_allowed" };
499
+ return startCode("sms", phone, a.locale, c, prefix);
500
+ },
501
+ async verifySms(a, c = {}) {
502
+ if (!o.sms)
503
+ return { ok: false, reason: "sms_not_configured" };
504
+ const phone = normalizePhone(a.phone);
505
+ if (!phone)
506
+ return { ok: false, reason: "invalid_phone" };
507
+ const r = await checkCode(sql, codeKey, { channel: "sms", target: phone, code: a.code, options: o.sms, ip: c.ip, limits, now: c.now });
508
+ if (!r.ok)
509
+ return r;
510
+ return finish({ ok: true, identity: { provider: "phone", subject: phone, phone, emailVerified: false } }, c);
511
+ },
512
+ async refresh(refreshToken, c = {}) {
513
+ if (c.ip && !(await hit(sql, `refresh-ip:${c.ip}`, limits.refreshPerIp, c.now ?? Date.now())))
514
+ return { ok: false, reason: "rate_limited" };
515
+ return refreshSession(sql, keys, sessions, refreshToken, (id) => getUser(sql, id), c.now);
516
+ },
517
+ /** The access token's claims when this server signed it and it is still good. */
518
+ async verifyAccessToken(token, c = {}) {
519
+ return checkAccessToken(keys, sessions, token, c.now);
520
+ },
521
+ /**
522
+ * The access token's user, only while its session is still on: signed out (here or everywhere) ends it at once,
523
+ * where a check of the token alone would let it work until it expires. For routes that change the account.
524
+ */
525
+ async signedIn(token, c = {}) {
526
+ const r = await checkAccessToken(keys, sessions, token, c.now);
527
+ if (!r.ok || typeof r.claims.sub !== "string" || typeof r.claims.sid !== "string")
528
+ return null;
529
+ const live = await liveSession(sql, r.claims.sid, c.now);
530
+ if (!live || live.userId !== r.claims.sub)
531
+ return null;
532
+ return { userId: live.userId, sessionId: r.claims.sid, sessionCreatedAt: live.createdAt };
533
+ },
534
+ signOut: (sessionId, c = {}) => revokeSession(sql, sessionId, c.now),
535
+ /**
536
+ * Signs out with a refresh token (a web app's cookie): its session, or with `everywhere` every session of its
537
+ * user, which only the session's current token may do (an old copy of it ends nothing but its own session).
538
+ */
539
+ async signOutWithRefresh(refreshToken, everywhere = false, c = {}) {
540
+ const s = await sessionOfRefresh(sql, refreshToken, c.now);
541
+ if (!s)
542
+ return false;
543
+ if (everywhere && s.current)
544
+ await revokeUserSessions(sql, s.userId, c.now);
545
+ else
546
+ await revokeSession(sql, s.sessionId, c.now);
547
+ return true;
548
+ },
549
+ async signOutEverywhere(userId, c = {}) {
550
+ await revokeUserSessions(sql, userId, c.now);
551
+ },
552
+ getUser: (userId) => getUser(sql, userId),
553
+ identities: (userId) => listIdentities(sql, userId),
554
+ sessions: (userId, c = {}) => listSessions(sql, userId, c.now),
555
+ /**
556
+ * Deletes the user and everything here that was theirs, then the app's own `onDelete`. Sign in with Apple is
557
+ * revoked first when the server has Apple's key: with the token kept at sign-in, or with `appleAuthorizationCode`
558
+ * (a fresh Sign in with Apple) when none was kept, which is the case of accounts moved from elsewhere. Without
559
+ * either it answers `apple_code_needed` and deletes nothing.
560
+ */
561
+ async deleteUser(userId, a = {}) {
562
+ const user = await getUser(sql, userId);
563
+ if (!user)
564
+ return { ok: false, reason: "not_found" };
565
+ let appleRevoked = null;
566
+ const appleIds = revoker ? await identitiesOf(sql, userId, "apple") : [];
567
+ for (const id of appleIds) {
568
+ let r = null;
569
+ if (id.data?.token && id.data.clientId)
570
+ r = await revoker.revoke(id.data.token, id.data.clientId);
571
+ if ((!r || !r.ok) && a.appleAuthorizationCode) {
572
+ for (const clientId of id.data?.clientId ? [id.data.clientId] : o.apple.clientIds) {
573
+ r = await revoker.revokeCode(a.appleAuthorizationCode, clientId, a.redirectUri);
574
+ if (r.ok)
575
+ break;
576
+ }
577
+ }
578
+ if (!r)
579
+ return { ok: false, reason: "apple_code_needed" };
580
+ appleRevoked = (appleRevoked ?? true) && r.ok;
581
+ }
582
+ await deleteUserRows(sql, userId);
583
+ await o.onDelete?.(user);
584
+ return { ok: true, appleRevoked };
585
+ },
586
+ /**
587
+ * Apple's server-to-server notification (the `payload` Apple posts), checked against Apple's keys. A withdrawn
588
+ * consent or a deleted Apple account signs the user out everywhere and forgets that Apple sign-in.
589
+ */
590
+ async appleNotification(payload, c = {}) {
591
+ if (!appleJwks || !o.apple)
592
+ return { ok: false, reason: "apple_not_configured" };
593
+ // Apple's notices carry `iat` and `jti` but no `exp`: a day old at most, and each one once.
594
+ const r = await verifyJwt(payload, {
595
+ key: (kid, alg) => appleJwks.key(kid, alg),
596
+ issuer: APPLE_ISSUER,
597
+ audience: o.apple.clientIds,
598
+ algorithms: ["RS256"],
599
+ requireExp: false,
600
+ maxAge: 86_400,
601
+ now: c.now,
602
+ });
603
+ if (!r.ok)
604
+ return { ok: false, reason: `apple_${r.reason}` };
605
+ const now = c.now ?? Date.now();
606
+ if (typeof r.claims.jti === "string" && !(await spend("apple-notice", r.claims.jti, now + 2 * 86_400_000, now)))
607
+ return { ok: true, type: "duplicate" };
608
+ let event;
609
+ try {
610
+ event = typeof r.claims.events === "string" ? JSON.parse(r.claims.events) : r.claims.events;
611
+ }
612
+ catch {
613
+ return { ok: false, reason: "bad_request" };
614
+ }
615
+ if (!event?.type || !event.sub)
616
+ return { ok: false, reason: "bad_request" };
617
+ const userId = await userOfIdentity(sql, "apple", event.sub);
618
+ if (!userId)
619
+ return { ok: true, type: event.type };
620
+ if (event.type === "consent-revoked" || event.type === "account-delete") {
621
+ await revokeUserSessions(sql, userId, c.now);
622
+ await sql.run(`delete from {identities} where provider = 'apple' and subject = ?`, [event.sub]);
623
+ }
624
+ await o.onAppleNotice?.({ type: event.type, userId, subject: event.sub, email: event.email });
625
+ return { ok: true, type: event.type };
626
+ },
627
+ passkeys: {
628
+ async registrationOptions(userId, c = {}) {
629
+ if (!pk)
630
+ return { ok: false, reason: "passkeys_not_configured" };
631
+ const user = await getUser(sql, userId);
632
+ if (!user)
633
+ return { ok: false, reason: "not_found" };
634
+ return { ok: true, ...(await pk.registrationOptions(user, c.now)) };
635
+ },
636
+ /** A guest who adds a passkey becomes a full account. */
637
+ async register(userId, a, c = {}) {
638
+ if (!pk)
639
+ return { ok: false, reason: "passkeys_not_configured" };
640
+ const r = await pk.register(userId, a, c.now);
641
+ if (r.ok)
642
+ await sql.run(`update {users} set is_guest = 0 where id = ?`, [userId]);
643
+ return r;
644
+ },
645
+ async signInOptions(c = {}) {
646
+ if (!pk)
647
+ return { ok: false, reason: "passkeys_not_configured" };
648
+ return { ok: true, ...(await pk.signInOptions(c.now)) };
649
+ },
650
+ async signIn(a, c = {}) {
651
+ if (!pk)
652
+ return { ok: false, reason: "passkeys_not_configured" };
653
+ const r = await pk.signIn(a, c.now);
654
+ if (!r.ok)
655
+ return r;
656
+ const user = await getUser(sql, r.userId);
657
+ if (!user)
658
+ return { ok: false, reason: "passkey_unknown" };
659
+ const now = c.now ?? Date.now();
660
+ await sql.run(`update {users} set last_sign_in_at = ? where id = ?`, [now, user.id]);
661
+ const tokens = await createSession(sql, keys, sessions, user, c.userAgent, now);
662
+ return { ok: true, user, tokens, created: false };
663
+ },
664
+ list: (userId) => (pk ? pk.list(userId) : Promise.resolve([])),
665
+ /** Removes a passkey, unless it is the user's last way in (`last_way_in`). */
666
+ async remove(userId, id) {
667
+ if (!pk)
668
+ return { ok: false, reason: "not_found" };
669
+ return removePasskey(sql, userId, id);
670
+ },
671
+ },
672
+ /** OpenID discovery: what Supabase's Third-Party Auth (or any API) reads to trust these tokens. */
673
+ discovery() {
674
+ return {
675
+ issuer,
676
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
677
+ id_token_signing_alg_values_supported: ["ES256"],
678
+ subject_types_supported: ["public"],
679
+ response_types_supported: ["id_token"],
680
+ claims_supported: ["sub", "aud", "exp", "iat", "iss", "role", "email", "phone", "sid", "is_anonymous"],
681
+ };
682
+ },
683
+ jwks: () => ({ keys: keys.public }),
684
+ /** Clears spent codes, old counters and, with `guests.days`, guests nobody used for that long: once an hour is plenty. */
685
+ async prune(c = {}) {
686
+ await pruneCodes(sql, c.now);
687
+ await pruneLimits(sql, c.now);
688
+ await sql.run(`delete from {challenges} where expires_at < ?`, [c.now ?? Date.now()]);
689
+ await sql.run(`delete from {guest_claims} where expires_at < ?`, [c.now ?? Date.now()]);
690
+ if (o.guests?.days) {
691
+ for (const id of await staleGuests(sql, o.guests.days, c.now)) {
692
+ const user = await getUser(sql, id);
693
+ if (user && (await deleteUserRows(sql, id)))
694
+ await o.onDelete?.(user);
695
+ }
696
+ }
697
+ },
698
+ };
699
+ }