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,556 @@
1
+ import type { Context as ContextType } from "../context/index.js";
2
+ import { Field } from "../form/index.js";
3
+ import { type JSX, jsx } from "../jsx/index.js";
4
+ import { Route } from "../route/index.js";
5
+ import { Schema } from "../schema/index.js";
6
+ import { Codec, Time, noStore } from "../util/index.js";
7
+ import { AuthData } from "./auth-data.js";
8
+ import { CBOR, COSE } from "./cbor.js";
9
+ import { etag, source } from "./client-source.js";
10
+ import { DER } from "./der.js";
11
+ import type { Auth } from "./index.js";
12
+ import { Issue } from "./issue.js";
13
+ import type { State } from "./state.js";
14
+ import { Storage } from "./storage.js";
15
+ import { Token } from "./token.js";
16
+
17
+ export namespace Passkey {
18
+ /**
19
+ * Composable authentication form with an accessible error component.
20
+ *
21
+ * @template Pattern Pattern of the route the form submits to
22
+ */
23
+ export type Component<Pattern extends string> = Route.Form<Pattern> & {
24
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
25
+ };
26
+ /**
27
+ * POST route contract retaining typed pathname parameters.
28
+ *
29
+ * @template Pattern Route pattern
30
+ */
31
+ export interface Post<Pattern extends string> extends Pick<
32
+ Route.Post,
33
+ "Fields"
34
+ > {
35
+ pattern: Pattern;
36
+ Form: Route.Form<Pattern>;
37
+ url: Route<Pattern>["url"];
38
+ }
39
+ /** Internal form configuration. */
40
+ export interface Options {
41
+ /** Fresh options URL; supplied by the configured handlers. */
42
+ readonly endpoint: string;
43
+ /** CSP nonce for strict nonce policies. */
44
+ readonly nonce?: string;
45
+ /** Form fields the ceremony is for, from `Passkey.fields`, checked when it starts. */
46
+ readonly fields?: string;
47
+ }
48
+ /** The ceremony a signed form may start. */
49
+ export type Expected = {
50
+ /** Path the form submits to */
51
+ action: string;
52
+ /** Form fields the ceremony is for, from `Passkey.fields` */
53
+ fields?: string;
54
+ } & (
55
+ | {
56
+ method: "register";
57
+ /** Name of the new passkey, at most 256 characters, not blank */
58
+ name: string;
59
+ }
60
+ | {
61
+ method: "login";
62
+ /** Credential IDs a login is limited to, for a user already known */
63
+ allow?: readonly string[];
64
+ }
65
+ );
66
+ }
67
+
68
+ /** ES256 passkeys with single-use, browser-bound ceremonies. */
69
+ export class Passkey {
70
+ /** Weak entity tag of the browser module */
71
+ static readonly #etag = etag;
72
+ /** Hidden fields the browser module fills, added to each ceremony route's own */
73
+ static readonly shape = {
74
+ credential: Field.hidden().json(Schema.unknown()),
75
+ ceremony: Field.hidden(),
76
+ };
77
+ static readonly #payload = Schema.object({
78
+ credential: Schema.unknown(),
79
+ ceremony: Schema.string(),
80
+ });
81
+ static readonly #bootstrap = Schema.object({
82
+ method: Schema.enum(["register", "login"]),
83
+ action: Schema.string(),
84
+ origin: Schema.string(),
85
+ browser: Schema.string(),
86
+ expiration: Schema.number().int(),
87
+ user: Schema.string().optional(),
88
+ fields: Schema.string().optional(),
89
+ });
90
+ static readonly #credential = Schema.object({
91
+ type: Schema.literal("public-key"),
92
+ id: Schema.string(),
93
+ rawId: Schema.string(),
94
+ });
95
+ static readonly #registration = Passkey.#credential.extend({
96
+ response: Schema.object({
97
+ clientDataJSON: Schema.string(),
98
+ attestationObject: Schema.string(),
99
+ }),
100
+ });
101
+ static readonly #assertion = Passkey.#credential.extend({
102
+ response: Schema.object({
103
+ clientDataJSON: Schema.string(),
104
+ authenticatorData: Schema.string(),
105
+ signature: Schema.string(),
106
+ // browsers leave it out, rather than send null, when there is none
107
+ userHandle: Schema.string().nullable().optional(),
108
+ }),
109
+ });
110
+ readonly #c: Auth.Context;
111
+ readonly #auth: State;
112
+
113
+ /** Create request-scoped passkey helpers. */
114
+ constructor(c: Auth.Context, auth: State) {
115
+ this.#c = c;
116
+ this.#auth = auth;
117
+ }
118
+
119
+ /**
120
+ * Create a form in the handler before returning JSX.
121
+ *
122
+ * @template Pattern Pattern of the route the form submits to
123
+ */
124
+ form<Pattern extends string>(
125
+ route: Passkey.Post<Pattern>,
126
+ method: "register" | "login",
127
+ options: Passkey.Options,
128
+ ) {
129
+ this.#origin();
130
+ const browser = this.#auth.browser(true);
131
+ const user = method === "register" ? crypto.randomUUID() : undefined;
132
+ noStore(this.#c.res.headers);
133
+ const Form: Passkey.Component<Pattern> = Object.assign(
134
+ (props: Parameters<Route.Form<Pattern>>[0]) =>
135
+ route.Form({
136
+ ...props,
137
+ children: [
138
+ props.children ?? [
139
+ route.Fields?.(),
140
+ jsx("button", {
141
+ children: method === "register" ? "Create account" : "Log in",
142
+ }),
143
+ ],
144
+ // A supplied Issue component takes precedence over this accessible fallback.
145
+ Form.Issue({ "data-passkey-fallback": true }),
146
+ async () =>
147
+ jsx("script", {
148
+ id: `passkey-${crypto.randomUUID()}`,
149
+ type: "module",
150
+ src: Passkey.client.url(),
151
+ nonce: options.nonce,
152
+ "data-passkey": method,
153
+ "data-endpoint": options.endpoint,
154
+ "data-bootstrap": await Token.seal(
155
+ this.#auth.options.secret,
156
+ "passkey",
157
+ JSON.stringify({
158
+ method,
159
+ // the form's own params, checked by its props type
160
+ action: route.url({ params: props.params } as never),
161
+ origin: this.#auth.options.origin,
162
+ browser,
163
+ expiration: Date.now() + Time.hour,
164
+ user,
165
+ fields: options.fields,
166
+ }),
167
+ ),
168
+ }),
169
+ jsx("noscript", {
170
+ children: "JavaScript is required for authentication.",
171
+ }),
172
+ ],
173
+ }),
174
+ {
175
+ Issue: (props: JSX.IntrinsicElements["p"]) =>
176
+ jsx("p", {
177
+ role: "status",
178
+ "aria-live": "polite",
179
+ ...props,
180
+ "data-passkey-error": true,
181
+ }),
182
+ },
183
+ );
184
+ return Form;
185
+ }
186
+
187
+ /** Dependency-free browser module, served as a normal same-origin JavaScript resource. */
188
+ static readonly client = Route.get("/_passkey/client.js").use((c) => {
189
+ c.res.headers.set("content-type", "text/javascript; charset=utf-8");
190
+ c.res.headers.set("x-content-type-options", "nosniff");
191
+ c.res.headers.set("cache-control", "no-cache");
192
+ c.res.headers.set("etag", Passkey.#etag);
193
+ if (
194
+ c.req.headers
195
+ .get("if-none-match")
196
+ ?.split(",")
197
+ .some(
198
+ (value) =>
199
+ value.trim() === "*" ||
200
+ value.trim().replace(/^W\//, "") === Passkey.#etag.slice(2),
201
+ )
202
+ ) {
203
+ c.res.status = 304;
204
+ c.res.body = null;
205
+ return;
206
+ }
207
+ c.res.body = source;
208
+ });
209
+
210
+ #origin() {
211
+ if (this.#c.url.origin !== this.#auth.options.origin)
212
+ throw new Issue("origin");
213
+ }
214
+
215
+ /** Validate a signed form and issue one fresh ceremony. */
216
+ static async issue(
217
+ c: Pick<ContextType, "url" | "res" | "text" | "json">,
218
+ auth: State,
219
+ token: string,
220
+ expected: Passkey.Expected,
221
+ ) {
222
+ const result = Schema.string()
223
+ .json(Passkey.#bootstrap)
224
+ .parse(await Token.open(auth.options.secret, "passkey", token));
225
+ if (result.issues) throw new Issue("bootstrap");
226
+ const bootstrap = result.data;
227
+ if (
228
+ c.url.origin !== auth.options.origin ||
229
+ bootstrap.origin !== auth.options.origin
230
+ )
231
+ throw new Issue("origin");
232
+ if (
233
+ !auth.browser() ||
234
+ bootstrap.browser !== auth.browser() ||
235
+ bootstrap.expiration <= Date.now()
236
+ )
237
+ return c.text("This page has expired. Reload and try again.", 410);
238
+ if (
239
+ bootstrap.method !== expected.method ||
240
+ bootstrap.action !== expected.action ||
241
+ // a page made for some fields, such as one consent request, starts only their ceremony
242
+ (bootstrap.fields !== undefined && bootstrap.fields !== expected.fields)
243
+ )
244
+ throw new Issue("bootstrap binding");
245
+ // the same method as the form's, checked above
246
+ const register = expected.method === "register";
247
+ if (
248
+ register &&
249
+ (!bootstrap.user || Codec.encode(bootstrap.user).length > 64)
250
+ )
251
+ throw new Issue("user");
252
+ const rp = new URL(auth.options.origin).hostname;
253
+ const ceremony = crypto.randomUUID();
254
+ const challenge = Token.random();
255
+ if (
256
+ (await auth.options.challenges.set(ceremony, {
257
+ challenge,
258
+ browser: bootstrap.browser,
259
+ method: bootstrap.method,
260
+ action: bootstrap.action,
261
+ origin: bootstrap.origin,
262
+ expiration: Date.now() + 2 * Time.minute,
263
+ ...(bootstrap.user ? { user: bootstrap.user } : {}),
264
+ ...(expected.fields ? { fields: expected.fields } : {}),
265
+ })) === false
266
+ ) {
267
+ return Issue.limited(c, 60);
268
+ }
269
+ noStore(c.res.headers);
270
+ if (register) {
271
+ c.json({
272
+ ceremony,
273
+ options: {
274
+ challenge,
275
+ rp: { id: rp, name: rp },
276
+ user: {
277
+ id: Codec.Base64Url.encode(Codec.encode(bootstrap.user!)),
278
+ name: expected.name,
279
+ displayName: expected.name,
280
+ },
281
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],
282
+ authenticatorSelection: {
283
+ residentKey: "required",
284
+ requireResidentKey: true,
285
+ userVerification: "required",
286
+ },
287
+ timeout: Time.minute,
288
+ attestation: "none",
289
+ } satisfies PublicKeyCredentialCreationOptionsJSON,
290
+ });
291
+ } else
292
+ c.json({
293
+ ceremony,
294
+ options: {
295
+ challenge,
296
+ rpId: rp,
297
+ timeout: Time.minute,
298
+ userVerification: "required",
299
+ // the picker offers only the user's passkeys
300
+ ...(expected.allow?.length && {
301
+ allowCredentials: expected.allow.map((id) => ({
302
+ type: "public-key" as const,
303
+ id,
304
+ })),
305
+ }),
306
+ } satisfies PublicKeyCredentialRequestOptionsJSON,
307
+ });
308
+ }
309
+
310
+ static #decode(value: string) {
311
+ if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)
312
+ throw new Issue("base64url");
313
+ const bytes = Codec.Base64Url.decode(value);
314
+ if (Codec.Base64Url.encode(bytes) !== value) throw new Issue("base64url");
315
+ return bytes;
316
+ }
317
+
318
+ static async #hash(value: Uint8Array<ArrayBuffer>) {
319
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", value));
320
+ }
321
+
322
+ static async #key(value: Uint8Array<ArrayBuffer>) {
323
+ try {
324
+ return await crypto.subtle.importKey(
325
+ "spki",
326
+ value,
327
+ { name: "ECDSA", namedCurve: "P-256" },
328
+ false,
329
+ ["verify"],
330
+ );
331
+ } catch (e) {
332
+ if (e instanceof DOMException) throw new Issue("public key");
333
+ throw e;
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Take the ceremony a credential answers, and check what both ceremonies share.
339
+ *
340
+ * @template T Credential the browser sends
341
+ * @param method Ceremony
342
+ * @param fields Form fields the ceremony was issued for, from `Passkey.fields`
343
+ * @param schema Credential the browser sends
344
+ * @returns The ceremony, the credential, and its client data
345
+ */
346
+ async #consume<
347
+ T extends {
348
+ id: string;
349
+ rawId: string;
350
+ response: { clientDataJSON: string };
351
+ },
352
+ >(
353
+ method: "register" | "login",
354
+ fields: string | undefined,
355
+ schema: Schema<T>,
356
+ ) {
357
+ this.#origin();
358
+ // a route's `c.data()` resolves to its parse result
359
+ const parsed = (await Issue.data(this.#c)) as { data?: unknown } | null;
360
+ const result = Passkey.#payload.parse(parsed?.data);
361
+ if (result.issues) throw new Issue("passkey request");
362
+ const state = await this.#auth.options.challenges.take(
363
+ result.data.ceremony,
364
+ );
365
+ if (!state || state.expiration <= Date.now())
366
+ throw new Issue("challenge (expired or consumed)");
367
+ if (!this.#auth.browser() || state.browser !== this.#auth.browser())
368
+ throw new Issue("browser");
369
+ if (
370
+ state.origin !== this.#auth.options.origin ||
371
+ state.method !== method ||
372
+ state.action !== this.#c.url.pathname
373
+ )
374
+ throw new Issue("challenge binding");
375
+ if (state.fields !== fields) throw new Issue("ceremony fields");
376
+ const credential = schema.parse(result.data.credential);
377
+ if (credential.issues) throw new Issue("credential response");
378
+ const client = this.#client(credential.data.response.clientDataJSON, state);
379
+ if (
380
+ !Passkey.#equal(
381
+ Passkey.#decode(credential.data.id),
382
+ Passkey.#decode(credential.data.rawId),
383
+ )
384
+ )
385
+ throw new Issue("credential ID");
386
+ return { state, credential: credential.data, client };
387
+ }
388
+
389
+ /** @returns The client data, verified for the ceremony */
390
+ #client(value: string, state: Storage.Challenge) {
391
+ let bytes: Uint8Array<ArrayBuffer>;
392
+ let json: string;
393
+ try {
394
+ bytes = Passkey.#decode(value);
395
+ json = Codec.decode(bytes);
396
+ } catch (error) {
397
+ // invalid UTF-8, sent by the client
398
+ if (error instanceof Issue) throw error;
399
+ throw new Issue("client data");
400
+ }
401
+ const result = Schema.string()
402
+ .json(
403
+ Schema.object({
404
+ type: Schema.literal(
405
+ state.method === "register" ? "webauthn.create" : "webauthn.get",
406
+ ),
407
+ origin: Schema.literal(this.#auth.options.origin),
408
+ challenge: Schema.literal(state.challenge),
409
+ crossOrigin: Schema.literal(false).optional(),
410
+ }),
411
+ )
412
+ .parse(json);
413
+ if (result.issues) throw new Issue("client data");
414
+ return bytes;
415
+ }
416
+
417
+ /** @returns Authenticator data, for this origin and a verified user */
418
+ async #data(bytes: Uint8Array) {
419
+ const data = AuthData.parse(bytes);
420
+ if (
421
+ !Passkey.#equal(
422
+ data.rpIdHash,
423
+ await Passkey.#hash(
424
+ Codec.encode(new URL(this.#auth.options.origin).hostname),
425
+ ),
426
+ )
427
+ )
428
+ throw new Issue("RP ID");
429
+ if (!(data.flags & 1) || !(data.flags & 4)) throw new Issue("user");
430
+ if (data.flags & 16 && !(data.flags & 8)) throw new Issue("backup flags");
431
+ return data;
432
+ }
433
+
434
+ static #equal(a: Uint8Array, b: Uint8Array) {
435
+ if (a.length !== b.length) return false;
436
+ let result = 0;
437
+ for (let i = 0; i < a.length; i++) result |= a[i]! ^ b[i]!;
438
+ return result === 0;
439
+ }
440
+
441
+ /** Digest canonical application values so field order cannot change the binding. */
442
+ static fields(value: unknown) {
443
+ // base64url SHA-256, like a stored token
444
+ return Storage.hash(
445
+ JSON.stringify(value, (_, value) =>
446
+ value && typeof value === "object" && !Array.isArray(value)
447
+ ? Object.fromEntries(
448
+ Object.entries(value).sort(([a], [b]) =>
449
+ a < b ? -1 : a > b ? 1 : 0,
450
+ ),
451
+ )
452
+ : value,
453
+ ),
454
+ );
455
+ }
456
+
457
+ /** Verify registration before persisting a new credential. */
458
+ async register(fields?: string) {
459
+ const { state, credential } = await this.#consume(
460
+ "register",
461
+ fields,
462
+ Passkey.#registration,
463
+ );
464
+ const data = await this.#data(
465
+ new CBOR(
466
+ Passkey.#decode(credential.response.attestationObject),
467
+ ).decodeAttestation(),
468
+ );
469
+ if (!data.attestedCredentialData || !state.user)
470
+ throw new Issue("credential data");
471
+ // the same as `rawId`, which the ceremony checked
472
+ if (
473
+ !Passkey.#equal(
474
+ Passkey.#decode(credential.id),
475
+ data.attestedCredentialData.credentialId,
476
+ )
477
+ )
478
+ throw new Issue("credential ID");
479
+ const key = COSE.toSPKI(data.attestedCredentialData.publicKey);
480
+ // Web Crypto validates that the P-256 point is on the curve before it is stored.
481
+ await Passkey.#key(key);
482
+ return {
483
+ id: credential.id,
484
+ user: state.user,
485
+ publicKey: Codec.Base64Url.encode(key),
486
+ counter: data.counter,
487
+ eligible: Boolean(data.flags & 8),
488
+ backedUp: Boolean(data.flags & 16),
489
+ };
490
+ }
491
+
492
+ /**
493
+ * Verify login and atomically update the credential.
494
+ *
495
+ * @param credentials Stored credentials
496
+ * @param fields Form fields the ceremony was issued for, from `Passkey.fields`
497
+ * @param user User the ceremony offered the passkeys of, such as when
498
+ * allowing an agent, whose authenticator may then leave out the user handle
499
+ * @returns The updated credential
500
+ */
501
+ async login(
502
+ credentials: Storage.Credentials,
503
+ fields?: string,
504
+ user?: string,
505
+ ) {
506
+ const { credential, client } = await this.#consume(
507
+ "login",
508
+ fields,
509
+ Passkey.#assertion,
510
+ );
511
+ const { response } = credential;
512
+ const stored = await credentials.get(credential.id);
513
+ if (!stored || stored.id !== credential.id) throw new Issue("credential");
514
+ const handle = response.userHandle;
515
+ // without a handle, only a passkey of the user identified before the
516
+ // ceremony, which offered theirs (WebAuthn, verifying an assertion)
517
+ if (
518
+ handle
519
+ ? !Passkey.#equal(Passkey.#decode(handle), Codec.encode(stored.user))
520
+ : stored.user !== user
521
+ )
522
+ throw new Issue("user handle");
523
+ const bytes = Passkey.#decode(response.authenticatorData);
524
+ const data = await this.#data(bytes);
525
+ if (data.attestedCredentialData) throw new Issue("assertion flags");
526
+ if (Boolean(data.flags & 8) !== stored.eligible)
527
+ throw new Issue("backup eligibility");
528
+ if (
529
+ !Number.isSafeInteger(stored.counter) ||
530
+ stored.counter < 0 ||
531
+ ((stored.counter || data.counter) && data.counter <= stored.counter)
532
+ )
533
+ throw new Issue("signature counter");
534
+ const hash = await Passkey.#hash(client);
535
+ const signed = new Uint8Array(bytes.length + hash.length);
536
+ signed.set(bytes);
537
+ signed.set(hash, bytes.length);
538
+ if (
539
+ !(await crypto.subtle.verify(
540
+ { name: "ECDSA", hash: "SHA-256" },
541
+ await Passkey.#key(Passkey.#decode(stored.publicKey)),
542
+ DER.unwrap(Passkey.#decode(response.signature)),
543
+ signed,
544
+ ))
545
+ )
546
+ throw new Issue("signature");
547
+ const updated = {
548
+ ...stored,
549
+ counter: data.counter,
550
+ backedUp: Boolean(data.flags & 16),
551
+ };
552
+ if (!(await credentials.update(updated, stored)))
553
+ throw new Issue("credential changed");
554
+ return updated;
555
+ }
556
+ }