ovr 6.2.4 → 7.0.0-next.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 (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -0,0 +1,572 @@
1
+ import {
2
+ type Database,
3
+ owned,
4
+ referenced,
5
+ references,
6
+ } from "../database/index.js";
7
+ import { Schema } from "../schema/index.js";
8
+ import { Table } from "../table/index.js";
9
+ import { Codec, Time } from "../util/index.js";
10
+ import type { Auth } from "./index.js";
11
+
12
+ /**
13
+ * A value, or a promise of it, from storage.
14
+ *
15
+ * @template T Value
16
+ */
17
+ type Result<T> = T | Promise<T>;
18
+
19
+ export namespace Storage {
20
+ /** Server-side state for one WebAuthn ceremony. */
21
+ export interface Challenge {
22
+ readonly challenge: string;
23
+ readonly browser: string;
24
+ readonly method: "register" | "login";
25
+ readonly action: string;
26
+ readonly origin: string;
27
+ readonly expiration: number;
28
+ readonly user?: string;
29
+ /** SHA-256 base64url digest binding validated registration fields to the provider label. */
30
+ readonly fields?: string;
31
+ }
32
+
33
+ /** Single-use challenges shared by all instances. */
34
+ export interface Challenges {
35
+ /** Store until expiration. Return false when capacity is exhausted. */
36
+ set(id: string, challenge: Challenge): Result<void | boolean>;
37
+ /** Atomically return and delete an entry; concurrent calls have one winner. */
38
+ take(id: string): Result<Challenge | null | undefined>;
39
+ }
40
+
41
+ /** A stored session, with the time it started for its lifetime. */
42
+ export interface Session extends Auth.Session {
43
+ /** Sign-in time in milliseconds. */
44
+ readonly started: number;
45
+ }
46
+
47
+ /** Revocable sessions shared by all instances. */
48
+ export interface Sessions {
49
+ set(id: string, session: Session): Result<void>;
50
+ /** Return a session, or nothing if it has expired or been revoked. */
51
+ get(id: string): Result<Session | null | undefined>;
52
+ /** Move a session's expiration later, never earlier. */
53
+ renew(id: string, expiration: number): Result<void>;
54
+ delete(id: string): Result<void>;
55
+ }
56
+
57
+ /** OAuth client registered by an agent. */
58
+ /** OAuth authorization code or token, stored by its hash. */
59
+ export interface Token {
60
+ readonly kind: "code" | "access" | "refresh";
61
+ readonly user: string;
62
+ readonly client: string;
63
+ readonly resource: string;
64
+ readonly scope: string;
65
+ readonly expiration: number;
66
+ readonly redirect?: string;
67
+ readonly challenge?: string;
68
+ /** Hash of the code the token descends from, defaults to its own */
69
+ readonly family?: string;
70
+ }
71
+
72
+ /** Credential lookup and compare-and-swap updates. */
73
+ export interface Credentials {
74
+ get(id: string): Result<Auth.Credential | null | undefined>;
75
+ /** IDs of the user's credentials */
76
+ list(user: string): Result<readonly string[]>;
77
+ /** Save `credential` only if the record still matches `previous`. */
78
+ update(
79
+ credential: Auth.Credential,
80
+ previous: Auth.Credential,
81
+ ): Result<boolean>;
82
+ }
83
+ }
84
+
85
+ /** An exchange refused after it started writing, rolled back. */
86
+ class Refused extends Error {}
87
+
88
+ /** Authentication persistence in the application's Postgres database. */
89
+ export class Storage {
90
+ /** Registered passkeys. */
91
+ static readonly credentials = new Table("auth_credentials", {
92
+ id: Schema.string(),
93
+ user: Schema.string(),
94
+ publicKey: Schema.string(),
95
+ counter: Schema.number().int(),
96
+ eligible: Schema.boolean(),
97
+ backedUp: Schema.boolean(),
98
+ });
99
+
100
+ /** Revocable sessions. */
101
+ static readonly sessions = new Table("auth_sessions", {
102
+ id: Schema.string(),
103
+ user: Schema.string(),
104
+ expiration: Schema.number().int(),
105
+ started: Schema.number().int(),
106
+ });
107
+
108
+ /** Outstanding WebAuthn ceremonies. */
109
+ static readonly challenges = new Table("auth_challenges", {
110
+ id: Schema.string(),
111
+ challenge: Schema.string(),
112
+ browser: Schema.string(),
113
+ method: Schema.enum(["register", "login"]),
114
+ action: Schema.string(),
115
+ origin: Schema.string(),
116
+ expiration: Schema.number().int(),
117
+ user: Schema.string().nullable(),
118
+ fields: Schema.string().nullable(),
119
+ });
120
+
121
+ /** Authorization codes, access tokens, and refresh tokens, by hash. */
122
+ static readonly tokens = new Table("auth_tokens", {
123
+ id: Schema.string(),
124
+ // a used code or refresh token is kept as "spent" to detect replays
125
+ kind: Schema.enum(["code", "access", "refresh", "spent"]),
126
+ user: Schema.string(),
127
+ client: Schema.string(),
128
+ resource: Schema.string(),
129
+ scope: Schema.string(),
130
+ redirect: Schema.string().nullable(),
131
+ challenge: Schema.string().nullable(),
132
+ family: Schema.string(),
133
+ expiration: Schema.number().int(),
134
+ });
135
+
136
+ /**
137
+ * Migrations creating Auth's tables, by version. A version never changes,
138
+ * so its checksum stays valid; later changes ship as new versions.
139
+ * `database.migrate` applies them for a database with `Auth.tables`. User IDs
140
+ * are text, so they hold any ID `auth.login` accepts.
141
+ */
142
+ static readonly #migrations = [
143
+ {
144
+ id: "auth:1",
145
+ sql: `CREATE TABLE auth_credentials (
146
+ id text PRIMARY KEY,
147
+ "user" text NOT NULL,
148
+ "publicKey" text NOT NULL,
149
+ counter bigint NOT NULL,
150
+ eligible boolean NOT NULL,
151
+ "backedUp" boolean NOT NULL
152
+ );
153
+ CREATE INDEX auth_credentials_user ON auth_credentials ("user");
154
+
155
+ CREATE TABLE auth_sessions (
156
+ id text PRIMARY KEY,
157
+ "user" text NOT NULL,
158
+ started bigint NOT NULL,
159
+ expiration bigint NOT NULL
160
+ );
161
+ CREATE INDEX auth_sessions_user ON auth_sessions ("user");
162
+ CREATE INDEX auth_sessions_expiration ON auth_sessions (expiration);
163
+
164
+ CREATE TABLE auth_challenges (
165
+ id text PRIMARY KEY,
166
+ challenge text NOT NULL,
167
+ browser text NOT NULL,
168
+ method text NOT NULL,
169
+ action text NOT NULL,
170
+ origin text NOT NULL,
171
+ expiration bigint NOT NULL,
172
+ "user" text,
173
+ fields text
174
+ );
175
+ CREATE INDEX auth_challenges_expiration ON auth_challenges (expiration);
176
+ CREATE INDEX auth_challenges_browser ON auth_challenges (browser, expiration);
177
+
178
+ CREATE TABLE auth_tokens (
179
+ id text PRIMARY KEY,
180
+ kind text NOT NULL,
181
+ "user" text NOT NULL,
182
+ client text NOT NULL,
183
+ resource text NOT NULL,
184
+ scope text NOT NULL,
185
+ redirect text,
186
+ challenge text,
187
+ family text NOT NULL,
188
+ expiration bigint NOT NULL
189
+ );
190
+ CREATE INDEX auth_tokens_family ON auth_tokens (family);
191
+ CREATE INDEX auth_tokens_user ON auth_tokens ("user");
192
+ CREATE INDEX auth_tokens_expiration ON auth_tokens (expiration);`,
193
+ },
194
+ ] as const;
195
+
196
+ /** Tables whose rows belong to a user, and must reference the users table. */
197
+ static readonly owners = [
198
+ Storage.credentials,
199
+ Storage.sessions,
200
+ Storage.tokens,
201
+ ] as const;
202
+
203
+ static {
204
+ for (const table of [...Storage.owners, Storage.challenges])
205
+ owned.set(table, Storage.#migrations);
206
+
207
+ // deleting an account deletes what signs in as it, `database.check` verifies it
208
+ for (const table of Storage.owners)
209
+ referenced.set(table, { column: "user", by: "Auth" });
210
+ }
211
+
212
+ /**
213
+ * Outstanding ceremonies for one browser. There is no cap across browsers:
214
+ * cookies are free to mint, so any cap shared by all of them is one
215
+ * attacker's to fill, and the per-IP limit already bounds each network.
216
+ */
217
+ static readonly #capacity = 10;
218
+
219
+ /** One store per database, so instances share pruning. */
220
+ static readonly #stores = new WeakMap<Database, Storage>();
221
+
222
+ readonly #db: Database;
223
+ #pruned = 0;
224
+
225
+ /**
226
+ * @param db Database containing the authentication tables
227
+ */
228
+ constructor(db: Database) {
229
+ this.#db = db;
230
+ }
231
+
232
+ /**
233
+ * @param db Database containing the authentication tables
234
+ * @returns The database's store
235
+ */
236
+ static of(db: Database) {
237
+ return Storage.#stores.getOrInsertComputed(db, () => new Storage(db));
238
+ }
239
+
240
+ /** Remove expired sessions and challenges, at most once a minute. */
241
+ async #prune() {
242
+ const now = Date.now();
243
+
244
+ // either direction, so a clock moving back cannot stop pruning
245
+ if (Math.abs(now - this.#pruned) < Time.minute) return;
246
+
247
+ this.#pruned = now;
248
+ const tables: Table<string, any>[] = [Storage.challenges, Storage.sessions];
249
+ if (this.#oauth) tables.push(Storage.tokens);
250
+ for (const table of tables)
251
+ await this.#db.sql`DELETE FROM ${table} WHERE expiration <= ${now}`;
252
+ }
253
+
254
+ /** OAuth tables are in use, so their rows are pruned too */
255
+ #oauth = false;
256
+
257
+ /**
258
+ * @param token Code or token
259
+ * @returns SHA-256 hash to store it by
260
+ */
261
+ static async hash(token: string) {
262
+ return Codec.Base64Url.encode(
263
+ new Uint8Array(
264
+ await crypto.subtle.digest("SHA-256", Codec.encode(token)),
265
+ ),
266
+ );
267
+ }
268
+
269
+ readonly tokens = {
270
+ /**
271
+ * @param token Code or token, stored by its hash
272
+ * @param row Token data
273
+ */
274
+ set: async (token: string, row: Storage.Token) => {
275
+ this.#oauth = true;
276
+ await this.#prune();
277
+ await this.#insert(this.#db.sql, token, row);
278
+ },
279
+ /**
280
+ * Uses a code or refresh token once, in one transaction with the tokens
281
+ * it is exchanged for. Replaying a used one revokes its whole family.
282
+ *
283
+ * @param token Code or refresh token
284
+ * @param kind Kind of token
285
+ * @param exchange Checks the unexpired token, returns the tokens to issue in its family, or `undefined` to refuse
286
+ * @returns `true` if the tokens were issued
287
+ */
288
+ exchange: async (
289
+ token: string,
290
+ kind: "code" | "refresh",
291
+ exchange: (
292
+ row: Storage.Token,
293
+ ) => Promise<Record<string, Storage.Token> | undefined>,
294
+ ) => {
295
+ this.#oauth = true;
296
+ await this.#prune();
297
+ const id = await Storage.hash(token);
298
+
299
+ return this.#db
300
+ .sql(async (t) => {
301
+ const select = () =>
302
+ t.sql`SELECT * FROM ${Storage.tokens} WHERE id = ${id}`.parse(
303
+ Storage.tokens,
304
+ );
305
+ const [found] = await select();
306
+ if (!found) return false;
307
+
308
+ // one exchange per user at a time, so a replay or a disconnection
309
+ // waits for tokens being issued, and its snapshot, taken after the
310
+ // lock, includes them
311
+ await Storage.#lock(t.sql, Storage.tokens, found.user);
312
+ if (!(await this.#account(t.sql, found.user))) return false;
313
+
314
+ // read again under the lock, an exchange before it may have used it
315
+ const [row] = await select();
316
+ if (!row) return false;
317
+
318
+ if (row.kind !== kind) {
319
+ // stolen and used by someone else, so neither party keeps access
320
+ if (row.kind === "spent")
321
+ await t.sql`DELETE FROM ${Storage.tokens} WHERE family = ${row.family}`;
322
+ return false;
323
+ }
324
+
325
+ const used = Storage.#token([row]);
326
+ const issued = used && (await exchange(used));
327
+ if (!issued) return false;
328
+
329
+ for (const [value, issue] of Object.entries(issued))
330
+ await this.#insert(t.sql, value, { ...issue, family: row.family });
331
+
332
+ // kept as long as what it was exchanged for, so replaying it later
333
+ // still finds the family and revokes it
334
+ const until = Math.max(
335
+ row.expiration,
336
+ ...Object.values(issued).map((issue) => issue.expiration),
337
+ );
338
+ const spent = await t.sql`
339
+ UPDATE ${Storage.tokens} SET kind = 'spent', expiration = ${until}
340
+ WHERE id = ${id} AND kind = ${kind}
341
+ RETURNING id
342
+ `;
343
+ // deleted meanwhile, outside Auth, so nothing is issued
344
+ if (!spent.length) throw new Refused();
345
+
346
+ return true;
347
+ })
348
+ .catch((error: unknown) => {
349
+ if (
350
+ error instanceof Refused ||
351
+ // the account was deleted meanwhile, its tokens cascade with it
352
+ (error as { code?: unknown } | null)?.code === "23503"
353
+ )
354
+ return false;
355
+ throw error;
356
+ });
357
+ },
358
+ /**
359
+ * Disconnect one of a user's agents: its codes, access tokens, and
360
+ * refresh tokens, including ones an exchange is issuing at the same time.
361
+ *
362
+ * @param user User ID
363
+ * @param client Agent's client ID
364
+ */
365
+ revoke: async (user: string, client: string) => {
366
+ await this.#db.sql(async (t) => {
367
+ // waits for an exchange issuing this user's tokens, so the delete sees them
368
+ await Storage.#lock(t.sql, Storage.tokens, user);
369
+ await this.#account(t.sql, user);
370
+ const { columns } = Storage.tokens;
371
+ await t.sql`DELETE FROM ${Storage.tokens} WHERE ${columns.user} = ${user} AND ${columns.client} = ${client}`;
372
+ });
373
+ },
374
+ /**
375
+ * @param token Access token
376
+ * @returns The unexpired token
377
+ */
378
+ get: async (token: string) =>
379
+ Storage.#token(
380
+ await this.#db
381
+ .sql`SELECT * FROM ${Storage.tokens} WHERE id = ${await Storage.hash(token)} AND kind = 'access'`.parse(
382
+ Storage.tokens,
383
+ ),
384
+ ),
385
+ };
386
+
387
+ /**
388
+ * Lock the account's row before any of its tokens, the order deleting the
389
+ * account takes them in, so the two wait for each other instead of
390
+ * deadlocking, whenever the foreign key is checked. The users table is the
391
+ * one `new Auth()` registered for this database.
392
+ *
393
+ * @param sql Transaction's SQL tag
394
+ * @param user User ID
395
+ * @returns `false` when the account no longer exists
396
+ */
397
+ async #account(sql: Database.Tag, user: string) {
398
+ const users = references.get(this.#db)?.get(Storage.tokens);
399
+ if (!users) return true;
400
+
401
+ const rows =
402
+ await sql`SELECT 1 FROM ${users} WHERE ${users.columns.id} = ${user} FOR KEY SHARE`;
403
+
404
+ return rows.length > 0;
405
+ }
406
+
407
+ /**
408
+ * Serialize writing a table's rows for one key, until the transaction ends.
409
+ *
410
+ * @param sql Transaction's SQL tag
411
+ * @param table Table written to
412
+ * @param key What the rows are for, such as a user ID
413
+ */
414
+ static async #lock(
415
+ sql: Database.Tag,
416
+ table: Table<string, any>,
417
+ key: string,
418
+ ) {
419
+ await sql`SELECT pg_advisory_xact_lock(hashtext(${table.name}), hashtext(${key}))`;
420
+ }
421
+
422
+ /**
423
+ * @param sql SQL tag to insert with
424
+ * @param token Code or token, stored by its hash
425
+ * @param row Token data
426
+ */
427
+ async #insert(sql: Database.Tag, token: string, row: Storage.Token) {
428
+ const id = await Storage.hash(token);
429
+ await sql`INSERT INTO ${Storage.tokens} ${sql.values(Storage.tokens, {
430
+ redirect: null,
431
+ challenge: null,
432
+ ...row,
433
+ family: row.family ?? id,
434
+ id,
435
+ })}`;
436
+ }
437
+
438
+ /**
439
+ * @param rows Token rows
440
+ * @returns The first row unless it has expired
441
+ */
442
+ static #token([row]: Table.Row<(typeof Storage.tokens)["shape"]>[]) {
443
+ if (!row || row.expiration <= Date.now()) return;
444
+ // a spent token is never returned, its kind is checked first
445
+ return Storage.#present(row) as Storage.Token;
446
+ }
447
+
448
+ /**
449
+ * @param row Stored row
450
+ * @returns The row without its null columns, which records leave out
451
+ */
452
+ static #present(row: object) {
453
+ return Object.fromEntries(
454
+ Object.entries(row).filter(([, value]) => value !== null),
455
+ );
456
+ }
457
+
458
+ readonly challenges: Storage.Challenges = {
459
+ set: async (id, challenge) => {
460
+ await this.#prune();
461
+
462
+ const table = Storage.challenges;
463
+ const now = Date.now();
464
+
465
+ return this.#db.sql(async (t) => {
466
+ // one writer at a time for each browser, so its concurrent requests
467
+ // cannot share the last slot; the insert's snapshot is taken after the lock
468
+ await Storage.#lock(t.sql, table, challenge.browser);
469
+
470
+ const rows = await t.sql`
471
+ INSERT INTO ${table} (id, challenge, browser, method, action, origin, expiration, "user", fields)
472
+ SELECT ${id}, ${challenge.challenge}, ${challenge.browser}, ${challenge.method},
473
+ ${challenge.action}, ${challenge.origin}, ${challenge.expiration}::bigint,
474
+ ${challenge.user ?? null}, ${challenge.fields ?? null}
475
+ WHERE (
476
+ SELECT count(*) FROM ${table} WHERE browser = ${challenge.browser} AND expiration > ${now}
477
+ ) < ${Storage.#capacity}
478
+ RETURNING id
479
+ `;
480
+
481
+ return rows.length === 1;
482
+ });
483
+ },
484
+ take: async (id) => {
485
+ const [row] = await this.#db
486
+ .sql`DELETE FROM ${Storage.challenges} WHERE id = ${id} RETURNING *`.parse(
487
+ Storage.challenges,
488
+ );
489
+
490
+ if (!row) return;
491
+
492
+ const { id: _, ...challenge } = row;
493
+
494
+ return Storage.#present(challenge) as Storage.Challenge;
495
+ },
496
+ };
497
+
498
+ readonly sessions: Storage.Sessions = {
499
+ set: async (_, session) => {
500
+ await this.#prune();
501
+ await this.#db
502
+ .sql`INSERT INTO ${Storage.sessions} ${this.#db.sql.values(Storage.sessions, session)}`;
503
+ },
504
+ get: async (id) =>
505
+ (
506
+ await this.#db
507
+ .sql`SELECT * FROM ${Storage.sessions} WHERE id = ${id} AND expiration > ${Date.now()}`.parse(
508
+ Storage.sessions,
509
+ )
510
+ )[0],
511
+ renew: async (id, expiration) => {
512
+ const { columns } = Storage.sessions;
513
+ await this.#db.sql`
514
+ UPDATE ${Storage.sessions} SET ${this.#db.sql.set(Storage.sessions, { expiration })}
515
+ WHERE ${columns.id} = ${id} AND ${columns.expiration} < ${expiration}
516
+ `;
517
+ },
518
+ delete: async (id) => {
519
+ await this.#db.sql`DELETE FROM ${Storage.sessions} WHERE id = ${id}`;
520
+ },
521
+ };
522
+
523
+ readonly credentials: Storage.Credentials = {
524
+ get: async (id) =>
525
+ (
526
+ await this.#db
527
+ .sql`SELECT * FROM ${Storage.credentials} WHERE id = ${id}`.parse(
528
+ Storage.credentials,
529
+ )
530
+ )[0],
531
+ list: async (user) => {
532
+ const { columns } = Storage.credentials;
533
+ const rows = await this.#db
534
+ .sql`SELECT ${columns.id} FROM ${Storage.credentials} WHERE ${columns.user} = ${user}`.parse(
535
+ Schema.object({ id: Schema.string() }),
536
+ );
537
+ return rows.map((row) => row.id);
538
+ },
539
+ update: async (credential, previous) => {
540
+ const { columns } = Storage.credentials;
541
+ const rows = await this.#db.sql`
542
+ UPDATE ${Storage.credentials}
543
+ SET ${this.#db.sql.set(Storage.credentials, {
544
+ counter: credential.counter,
545
+ backedUp: credential.backedUp,
546
+ })}
547
+ WHERE ${columns.id} = ${previous.id} AND ${columns.user} = ${previous.user}
548
+ AND ${columns.publicKey} = ${previous.publicKey} AND ${columns.counter} = ${previous.counter}
549
+ AND ${columns.eligible} = ${previous.eligible} AND ${columns.backedUp} = ${previous.backedUp}
550
+ RETURNING id
551
+ `;
552
+
553
+ return rows.length === 1;
554
+ },
555
+ };
556
+
557
+ /**
558
+ * Create the account and its first credential in one transaction.
559
+ *
560
+ * @param create Application callback creating the account
561
+ * @param credential Verified credential
562
+ */
563
+ register(
564
+ create: (t: Database.Transaction, user: string) => Result<void>,
565
+ credential: Auth.Credential,
566
+ ) {
567
+ return this.#db.sql(async (t) => {
568
+ await create(t, credential.user);
569
+ await t.sql`INSERT INTO ${Storage.credentials} ${t.sql.values(Storage.credentials, credential)}`;
570
+ });
571
+ }
572
+ }
@@ -0,0 +1,67 @@
1
+ import { Codec } from "../util/index.js";
2
+ import type { Auth } from "./index.js";
3
+ import { Issue } from "./issue.js";
4
+
5
+ /** Internal integrity protection with explicit authentication purposes. */
6
+ export class Token {
7
+ static readonly #keys = new Map<string, Promise<CryptoKey>>();
8
+
9
+ static #key(secret: string) {
10
+ return Token.#keys.getOrInsertComputed(secret, () =>
11
+ crypto.subtle.importKey(
12
+ "raw",
13
+ Codec.encode(secret),
14
+ { name: "HMAC", hash: "SHA-256" },
15
+ false,
16
+ ["sign", "verify"],
17
+ ),
18
+ );
19
+ }
20
+
21
+ /** @returns A new random value of 256 bits, base64url, such as a challenge or code */
22
+ static random() {
23
+ return Codec.Base64Url.encode(crypto.getRandomValues(new Uint8Array(32)));
24
+ }
25
+
26
+ /** Seal a payload for exactly one authentication purpose. */
27
+ static async seal(
28
+ secret: Auth.Options["secret"],
29
+ purpose: "session" | "passkey" | "consent",
30
+ value: string,
31
+ ) {
32
+ const payload = `${purpose}:${value}`;
33
+ return `${payload}.${Codec.Base64Url.encode(new Uint8Array(await crypto.subtle.sign("HMAC", await Token.#key([secret].flat()[0]!), Codec.encode(payload))))}`;
34
+ }
35
+
36
+ /** Verify both integrity and purpose before exposing the payload. */
37
+ static async open(
38
+ secret: Auth.Options["secret"],
39
+ purpose: "session" | "passkey" | "consent",
40
+ token: string,
41
+ ) {
42
+ const dot = token.lastIndexOf(".");
43
+ if (dot > 0 && token.startsWith(`${purpose}:`)) {
44
+ try {
45
+ const text = token.slice(dot + 1);
46
+ const signature = Codec.Base64Url.decode(text);
47
+ // one spelling per signature, as it was issued
48
+ if (Codec.Base64Url.encode(signature) !== text)
49
+ throw new Issue("token");
50
+ const payload = Codec.encode(token.slice(0, dot));
51
+ for (const key of [secret].flat())
52
+ if (
53
+ await crypto.subtle.verify(
54
+ "HMAC",
55
+ await Token.#key(key),
56
+ signature,
57
+ payload,
58
+ )
59
+ )
60
+ return token.slice(purpose.length + 1, dot);
61
+ } catch {
62
+ // Malformed signatures are authentication failures.
63
+ }
64
+ }
65
+ throw new Issue("token");
66
+ }
67
+ }