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,383 @@
1
+ /**
2
+ * Passkeys (WebAuthn), checked with WebCrypto: registering one for a signed-in user, and signing in with one. The
3
+ * options and answers are WebAuthn's JSON forms (base64url), which browsers (`PublicKeyCredential.parseCreationOptionsFromJSON`,
4
+ * `toJSON()`), Android's Credential Manager and the iOS client all speak.
5
+ *
6
+ * Attestation is not asked for (`none`): a passkey is trusted as the key the user's device made, which is what
7
+ * sites do. What is checked: the challenge (once, five minutes), the origin, the relying party's ID hash, the user
8
+ * present flag (and verified, when asked), the signature, and the counter when the authenticator keeps one.
9
+ */
10
+ import { b64url, concat, fromBase64, fromUtf8, utf8 } from "./base64.js";
11
+ import { num } from "./db/sql.js";
12
+ import { randomToken } from "./crypto.js";
13
+ const FIVE_MINUTES = 5 * 60_000;
14
+ // --- CBOR, only as much as WebAuthn uses: maps, arrays, integers, byte and text strings, booleans ---
15
+ class Reader {
16
+ at = 0;
17
+ bytes;
18
+ constructor(bytes) {
19
+ this.bytes = bytes;
20
+ }
21
+ byte() {
22
+ if (this.at >= this.bytes.length)
23
+ throw new Error("cbor: ran out");
24
+ return this.bytes[this.at++];
25
+ }
26
+ length(info) {
27
+ if (info < 24)
28
+ return info;
29
+ if (info === 24)
30
+ return this.byte();
31
+ if (info === 25)
32
+ return (this.byte() << 8) | this.byte();
33
+ if (info === 26)
34
+ return ((this.byte() << 24) >>> 0) + ((this.byte() << 16) | (this.byte() << 8) | this.byte());
35
+ throw new Error("cbor: length too long");
36
+ }
37
+ read() {
38
+ const head = this.byte();
39
+ const major = head >> 5;
40
+ const info = head & 31;
41
+ switch (major) {
42
+ case 0:
43
+ return this.length(info);
44
+ case 1:
45
+ return -1 - this.length(info);
46
+ case 2: {
47
+ const n = this.length(info);
48
+ const out = this.bytes.slice(this.at, this.at + n);
49
+ if (out.length !== n)
50
+ throw new Error("cbor: ran out");
51
+ this.at += n;
52
+ return out;
53
+ }
54
+ case 3: {
55
+ const n = this.length(info);
56
+ const out = fromUtf8(this.bytes.subarray(this.at, this.at + n));
57
+ this.at += n;
58
+ return out;
59
+ }
60
+ case 4:
61
+ return Array.from({ length: this.length(info) }, () => this.read());
62
+ case 5: {
63
+ const map = new Map();
64
+ const n = this.length(info);
65
+ for (let i = 0; i < n; i += 1)
66
+ map.set(this.read(), this.read());
67
+ return map;
68
+ }
69
+ case 7:
70
+ if (info === 20)
71
+ return false;
72
+ if (info === 21)
73
+ return true;
74
+ if (info === 22)
75
+ return null;
76
+ throw new Error("cbor: unsupported simple value");
77
+ default:
78
+ throw new Error("cbor: unsupported type");
79
+ }
80
+ }
81
+ }
82
+ export function decodeCbor(bytes) {
83
+ const r = new Reader(bytes);
84
+ const value = r.read();
85
+ return { value, length: r.at };
86
+ }
87
+ function parseAuthData(data) {
88
+ if (data.length < 37)
89
+ throw new Error("authenticator data too short");
90
+ const flags = data[32];
91
+ const signCount = new DataView(data.buffer, data.byteOffset + 33, 4).getUint32(0);
92
+ const out = { rpIdHash: data.slice(0, 32), flags, signCount };
93
+ if (flags & 0x40) {
94
+ let at = 37 + 16;
95
+ const idLength = (data[at] << 8) | data[at + 1];
96
+ at += 2;
97
+ out.credentialId = data.slice(at, at + idLength);
98
+ at += idLength;
99
+ const { value } = decodeCbor(data.subarray(at));
100
+ if (!(value instanceof Map))
101
+ throw new Error("credential public key is not a map");
102
+ out.publicKey = value;
103
+ }
104
+ return out;
105
+ }
106
+ /** A COSE key as the JWK WebCrypto imports, and its algorithm: ES256 (-7) or RS256 (-257). */
107
+ export function coseToJwk(cose) {
108
+ const kty = cose.get(1);
109
+ const alg = cose.get(3);
110
+ if (kty === 2 && alg === -7 && cose.get(-1) === 1) {
111
+ return {
112
+ jwk: { kty: "EC", crv: "P-256", x: b64url(cose.get(-2)), y: b64url(cose.get(-3)) },
113
+ alg: -7,
114
+ };
115
+ }
116
+ if (kty === 3 && alg === -257) {
117
+ return { jwk: { kty: "RSA", n: b64url(cose.get(-1)), e: b64url(cose.get(-2)) }, alg: -257 };
118
+ }
119
+ throw new Error("unsupported passkey algorithm");
120
+ }
121
+ /** An ECDSA signature from DER (what authenticators give) to r and s side by side (what WebCrypto checks). */
122
+ export function derToRaw(der) {
123
+ if (der[0] !== 0x30)
124
+ throw new Error("not a DER signature");
125
+ let at = 2;
126
+ if (der[1] & 0x80)
127
+ at = 2 + (der[1] & 0x7f);
128
+ const part = () => {
129
+ if (der[at] !== 0x02)
130
+ throw new Error("not a DER integer");
131
+ const n = der[at + 1];
132
+ let v = der.subarray(at + 2, at + 2 + n);
133
+ at += 2 + n;
134
+ while (v.length > 32 && v[0] === 0)
135
+ v = v.subarray(1);
136
+ const out = new Uint8Array(32);
137
+ out.set(v, 32 - v.length);
138
+ return out;
139
+ };
140
+ return concat(part(), part());
141
+ }
142
+ const ALG = {
143
+ [-7]: { import: { name: "ECDSA", namedCurve: "P-256" }, verify: { name: "ECDSA", hash: "SHA-256" } },
144
+ [-257]: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verify: { name: "RSASSA-PKCS1-v1_5" } },
145
+ };
146
+ const sha256 = async (b) => new Uint8Array(await crypto.subtle.digest("SHA-256", b));
147
+ function equal(a, b) {
148
+ if (a.length !== b.length)
149
+ return false;
150
+ let d = 0;
151
+ for (let i = 0; i < a.length; i += 1)
152
+ d |= a[i] ^ b[i];
153
+ return d === 0;
154
+ }
155
+ function bytesOf(v) {
156
+ if (typeof v !== "string" || !/^[A-Za-z0-9_-]*={0,2}$/.test(v))
157
+ return null;
158
+ try {
159
+ return fromBase64(v);
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ }
165
+ export function passkeys(sql, o) {
166
+ const origins = o.origins?.length ? o.origins : [`https://${o.rpId}`];
167
+ const uv = o.userVerification ?? "preferred";
168
+ const newChallenge = async (kind, userId, now) => {
169
+ const id = crypto.randomUUID();
170
+ const challenge = randomToken(32);
171
+ await sql.batch([
172
+ [`delete from {challenges} where expires_at < ?`, [now]],
173
+ [`insert into {challenges} (id, kind, user_id, challenge, expires_at) values (?, ?, ?, ?, ?)`, [id, kind, userId, challenge, now + FIVE_MINUTES]],
174
+ ]);
175
+ return { id, challenge };
176
+ };
177
+ /** Takes the challenge (once: it is deleted whether the answer is good or not). */
178
+ const takeChallenge = async (id, kind, now) => {
179
+ if (typeof id !== "string")
180
+ return null;
181
+ const [row] = await sql.all(`select challenge, user_id, expires_at from {challenges} where id = ? and kind = ?`, [id, kind]);
182
+ if (!row)
183
+ return null;
184
+ const { changes } = await sql.run(`delete from {challenges} where id = ?`, [id]);
185
+ if (!changes || num(row.expires_at) < now)
186
+ return null;
187
+ return row;
188
+ };
189
+ /** clientDataJSON's checks, shared by both ceremonies. */
190
+ const checkClient = (raw, type, challenge) => {
191
+ let client;
192
+ try {
193
+ client = JSON.parse(fromUtf8(raw));
194
+ }
195
+ catch {
196
+ return "passkey_bad_request";
197
+ }
198
+ if (client.type !== type)
199
+ return "passkey_bad_request";
200
+ if (client.challenge?.replace(/=+$/, "") !== challenge)
201
+ return "passkey_challenge";
202
+ if (!client.origin || !origins.includes(client.origin))
203
+ return "passkey_origin";
204
+ return null;
205
+ };
206
+ const checkFlags = async (data) => {
207
+ if (!equal(data.rpIdHash, await sha256(utf8(o.rpId))))
208
+ return "passkey_rp";
209
+ if (!(data.flags & 0x01))
210
+ return "passkey_user_presence";
211
+ if (uv === "required" && !(data.flags & 0x04))
212
+ return "passkey_user_verification";
213
+ return null;
214
+ };
215
+ return {
216
+ async registrationOptions(user, now = Date.now()) {
217
+ const { id, challenge } = await newChallenge("register", user.id, now);
218
+ const existing = await sql.all(`select id, transports from {passkeys} where user_id = ?`, [user.id]);
219
+ const label = user.email ?? user.phone ?? user.name ?? user.id;
220
+ return {
221
+ challengeId: id,
222
+ options: {
223
+ rp: { id: o.rpId, name: o.rpName },
224
+ user: { id: b64url(utf8(user.id)), name: label, displayName: user.name ?? label },
225
+ challenge,
226
+ pubKeyCredParams: [
227
+ { type: "public-key", alg: -7 },
228
+ { type: "public-key", alg: -257 },
229
+ ],
230
+ timeout: FIVE_MINUTES,
231
+ attestation: "none",
232
+ authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: uv },
233
+ excludeCredentials: existing.map((p) => ({
234
+ type: "public-key",
235
+ id: p.id,
236
+ ...(p.transports ? { transports: JSON.parse(p.transports) } : {}),
237
+ })),
238
+ },
239
+ };
240
+ },
241
+ async register(userId, a, now = Date.now()) {
242
+ const c = a.credential;
243
+ const clientData = bytesOf(c?.response?.clientDataJSON);
244
+ const attestation = bytesOf(c?.response?.attestationObject);
245
+ if (!c || c.type !== "public-key" || !clientData || !attestation)
246
+ return { ok: false, reason: "passkey_bad_request" };
247
+ const row = await takeChallenge(a.challengeId, "register", now);
248
+ if (!row || row.user_id !== userId)
249
+ return { ok: false, reason: "passkey_challenge" };
250
+ const clientFailure = checkClient(clientData, "webauthn.create", row.challenge);
251
+ if (clientFailure)
252
+ return { ok: false, reason: clientFailure };
253
+ let data;
254
+ let key;
255
+ try {
256
+ const { value } = decodeCbor(attestation);
257
+ const authData = value.get("authData");
258
+ if (!(authData instanceof Uint8Array))
259
+ return { ok: false, reason: "passkey_bad_request" };
260
+ data = parseAuthData(authData);
261
+ if (!data.credentialId || !data.publicKey)
262
+ return { ok: false, reason: "passkey_bad_request" };
263
+ key = coseToJwk(data.publicKey);
264
+ await crypto.subtle.importKey("jwk", key.jwk, ALG[key.alg].import, false, ["verify"]);
265
+ }
266
+ catch {
267
+ return { ok: false, reason: "passkey_algorithm" };
268
+ }
269
+ const flagFailure = await checkFlags(data);
270
+ if (flagFailure)
271
+ return { ok: false, reason: flagFailure };
272
+ const id = b64url(data.credentialId);
273
+ const transports = Array.isArray(c.response?.transports) ? JSON.stringify(c.response.transports.filter((t) => typeof t === "string")) : null;
274
+ const name = typeof a.name === "string" && a.name.trim() ? a.name.trim().slice(0, 100) : null;
275
+ try {
276
+ await sql.run(`insert into {passkeys} (id, user_id, public_key, alg, sign_count, transports, name, created_at) values (?, ?, ?, ?, ?, ?, ?, ?)`, [id, userId, JSON.stringify(key.jwk), key.alg, data.signCount, transports, name, now]);
277
+ }
278
+ catch {
279
+ return { ok: false, reason: "passkey_exists" };
280
+ }
281
+ return { ok: true, passkey: { id, name, createdAt: now } };
282
+ },
283
+ async signInOptions(now = Date.now()) {
284
+ const { id, challenge } = await newChallenge("signin", null, now);
285
+ return { challengeId: id, options: { challenge, rpId: o.rpId, timeout: FIVE_MINUTES, userVerification: uv, allowCredentials: [] } };
286
+ },
287
+ /** The user a passkey answer signs in, when every check holds. */
288
+ async signIn(a, now = Date.now()) {
289
+ const c = a.credential;
290
+ const clientData = bytesOf(c?.response?.clientDataJSON);
291
+ const authData = bytesOf(c?.response?.authenticatorData);
292
+ const signature = bytesOf(c?.response?.signature);
293
+ if (!c || c.type !== "public-key" || typeof c.id !== "string" || !clientData || !authData || !signature) {
294
+ return { ok: false, reason: "passkey_bad_request" };
295
+ }
296
+ const row = await takeChallenge(a.challengeId, "signin", now);
297
+ if (!row)
298
+ return { ok: false, reason: "passkey_challenge" };
299
+ const clientFailure = checkClient(clientData, "webauthn.get", row.challenge);
300
+ if (clientFailure)
301
+ return { ok: false, reason: clientFailure };
302
+ const id = c.id.replace(/=+$/, "");
303
+ const [stored] = await sql.all(`select user_id, public_key, alg, sign_count from {passkeys} where id = ?`, [id]);
304
+ if (!stored)
305
+ return { ok: false, reason: "passkey_unknown" };
306
+ const handle = bytesOf(c.response?.userHandle);
307
+ if (handle && handle.length && !sameUser(handle, stored.user_id))
308
+ return { ok: false, reason: "passkey_unknown" };
309
+ let data;
310
+ try {
311
+ data = parseAuthData(authData);
312
+ }
313
+ catch {
314
+ return { ok: false, reason: "passkey_bad_request" };
315
+ }
316
+ const flagFailure = await checkFlags(data);
317
+ if (flagFailure)
318
+ return { ok: false, reason: flagFailure };
319
+ // A passkey moved from Supabase Auth keeps its COSE key (`cose:<base64url>`) until its first use here.
320
+ let jwk;
321
+ let alg = num(stored.alg);
322
+ let moved = false;
323
+ try {
324
+ if (stored.public_key.startsWith("cose:")) {
325
+ const { value } = decodeCbor(fromBase64(stored.public_key.slice(5)));
326
+ if (!(value instanceof Map))
327
+ throw new Error("not a COSE key");
328
+ ({ jwk, alg } = coseToJwk(value));
329
+ moved = true;
330
+ }
331
+ else {
332
+ jwk = JSON.parse(stored.public_key);
333
+ }
334
+ }
335
+ catch {
336
+ return { ok: false, reason: "passkey_algorithm" };
337
+ }
338
+ if (!ALG[alg])
339
+ return { ok: false, reason: "passkey_algorithm" };
340
+ let valid = false;
341
+ try {
342
+ const key = await crypto.subtle.importKey("jwk", jwk, ALG[alg].import, false, ["verify"]);
343
+ const signed = concat(authData, await sha256(clientData));
344
+ valid = await crypto.subtle.verify(ALG[alg].verify, key, alg === -7 ? derToRaw(signature) : signature, signed);
345
+ }
346
+ catch {
347
+ valid = false;
348
+ }
349
+ if (!valid)
350
+ return { ok: false, reason: "passkey_signature" };
351
+ // A counter that doesn't go up, when the authenticator keeps one, is a cloned key. Synced passkeys keep 0.
352
+ const before = num(stored.sign_count);
353
+ if ((data.signCount || before) && data.signCount <= before)
354
+ return { ok: false, reason: "passkey_counter" };
355
+ await sql.run(`update {passkeys} set sign_count = ?, last_used_at = ? where id = ?`, [data.signCount, now, id]);
356
+ if (moved)
357
+ await sql.run(`update {passkeys} set public_key = ?, alg = ? where id = ?`, [JSON.stringify(jwk), alg, id]);
358
+ return { ok: true, userId: stored.user_id };
359
+ },
360
+ async list(userId) {
361
+ const rows = await sql.all(`select id, name, created_at, last_used_at from {passkeys} where user_id = ? order by created_at`, [userId]);
362
+ return rows.map((r) => ({ id: r.id, name: r.name, createdAt: num(r.created_at), lastUsedAt: r.last_used_at === null ? null : num(r.last_used_at) }));
363
+ },
364
+ async remove(userId, id) {
365
+ return (await sql.run(`delete from {passkeys} where id = ? and user_id = ?`, [id, userId])).changes > 0;
366
+ },
367
+ };
368
+ }
369
+ /**
370
+ * Whether a passkey's user handle names this user. Here, and in Supabase Auth (GoTrue's `WebAuthnID()` is
371
+ * `[]byte(user.ID.String())`, internal/models/user.go), it is the id as text: the UUID's 36 characters. The 16 bytes
372
+ * of the UUID, and the text in capitals, without hyphens or in braces, are taken too: the same id, as other servers
373
+ * register it.
374
+ */
375
+ export function sameUser(handle, userId) {
376
+ const hex = (s) => s.toLowerCase().replace(/^urn:uuid:/, "").replace(/[{}-]/g, "");
377
+ const want = hex(userId);
378
+ if (!/^[0-9a-f]{32}$/.test(want))
379
+ return fromUtf8(handle) === userId;
380
+ if (handle.length === 16)
381
+ return Array.from(handle, (b) => b.toString(16).padStart(2, "0")).join("") === want;
382
+ return hex(fromUtf8(handle)) === want;
383
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Password hashes. New ones are PBKDF2-SHA256 with WebCrypto (`$pbkdf2-sha256$i=600000$<salt>$<hash>`, base64url,
3
+ * the iteration count inside, so a later default can raise it and old hashes still check). Hashes moved from
4
+ * Supabase Auth, Clerk and Auth0 are bcrypt (`$2a$10$…`), Firebase Auth's its modified scrypt
5
+ * (`$fbscrypt$r=8,m=14$<signer key>$<salt separator>$<salt>$<hash>`, standard base64, the project's parameters with
6
+ * each hash) and Better Auth's scrypt (`$bascrypt$<salt>$<key>`, hex); they are checked here, in plain TypeScript,
7
+ * and replaced with PBKDF2 the first time their owner signs in.
8
+ *
9
+ * Cloudflare Workers caps PBKDF2 at 100,000 iterations, so a hash made there uses that, and a Worker can't check a
10
+ * hash made elsewhere with more. Pick the count for the host that will check the hashes (`passwords.iterations`).
11
+ * A bcrypt check (cost 10, Supabase's) is about 80 ms of plain CPU: more than the Workers free plan's 10 ms a
12
+ * request, so a Worker checking moved hashes needs the paid plan (its limit is seconds). Elsewhere it gives way to
13
+ * other requests as it goes, every few milliseconds.
14
+ */
15
+ export declare const DEFAULT_ITERATIONS = 600000;
16
+ export declare const WORKERS_MAX_ITERATIONS = 100000;
17
+ /** The most iterations a check here can do: 100,000 on Workers (more throws there), no limit elsewhere. */
18
+ export declare function maxIterations(): number;
19
+ /** The iteration count new hashes get here: 600,000, or 100,000 on Workers. */
20
+ export declare function defaultIterations(): number;
21
+ export declare function hashPassword(password: string, iterations?: number): Promise<string>;
22
+ /** What kind of moved hash `stored` is: `bcrypt`, `firebase` or `better-auth`; null for PBKDF2 or anything else. */
23
+ export declare function movedKind(stored: string): "bcrypt" | "firebase" | "better-auth" | null;
24
+ /** Firebase's parameters in a moved hash (the same for a whole project), for checks that have no hash to check. */
25
+ export declare function firebaseParams(stored: string): {
26
+ rounds: number;
27
+ memCost: number;
28
+ } | null;
29
+ /**
30
+ * Whether `password` is the one `stored` was made from. `rehash` is true when the hash should be replaced (a bcrypt
31
+ * one, or fewer iterations than `iterations`). A hash this code can't read is simply not a match.
32
+ */
33
+ export declare function verifyPassword(password: string, stored: string, iterations?: number): Promise<{
34
+ ok: boolean;
35
+ rehash: boolean;
36
+ }>;
37
+ /** The work a check does when there is no hash to check against, so a missing account takes as long as a wrong password. */
38
+ export declare function burnPassword(password: string, iterations?: number): Promise<void>;
39
+ /** The work of checking a bcrypt hash of `cost`, done when there is none to check: see `burnPassword`. */
40
+ export declare function burnBcrypt(password: string, cost?: number): Promise<void>;
41
+ /** The work of checking a Firebase hash with these parameters, or a Better Auth one, done when there is none to check. */
42
+ export declare function burnScrypt(password: string, kind: "firebase" | "better-auth", p?: {
43
+ rounds: number;
44
+ memCost: number;
45
+ }): Promise<void>;
46
+ /** The cost of a bcrypt hash (10 in `$2a$10$…`), or null for another kind. */
47
+ export declare function bcryptCost(stored: string): number | null;
48
+ /** The iteration count of a PBKDF2 hash, or null for another kind. */
49
+ export declare function pbkdf2Iterations(stored: string): number | null;
50
+ /** PBKDF2 work on top of a check that did `done` iterations, so it costs `target` in all. */
51
+ export declare function topUp(password: string, done: number, target: number): Promise<void>;
52
+ /** A bcrypt hash of `password`, for tests and tools (new hashes here are PBKDF2). */
53
+ export declare function bcryptHash(password: string, cost?: number, salt?: Uint8Array<ArrayBuffer>): string;