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,101 @@
1
+ import type { Context as ContextType } from "../context/index.js";
2
+ import { Field } from "../form/index.js";
3
+ import { type JSX } from "../jsx/index.js";
4
+ import { Route } from "../route/index.js";
5
+ import type { Auth } from "./index.js";
6
+ import type { State } from "./state.js";
7
+ import { Storage } from "./storage.js";
8
+ export declare namespace Passkey {
9
+ /**
10
+ * Composable authentication form with an accessible error component.
11
+ *
12
+ * @template Pattern Pattern of the route the form submits to
13
+ */
14
+ type Component<Pattern extends string> = Route.Form<Pattern> & {
15
+ Issue: (props: JSX.IntrinsicElements["p"]) => JSX.Element;
16
+ };
17
+ /**
18
+ * POST route contract retaining typed pathname parameters.
19
+ *
20
+ * @template Pattern Route pattern
21
+ */
22
+ interface Post<Pattern extends string> extends Pick<Route.Post, "Fields"> {
23
+ pattern: Pattern;
24
+ Form: Route.Form<Pattern>;
25
+ url: Route<Pattern>["url"];
26
+ }
27
+ /** Internal form configuration. */
28
+ interface Options {
29
+ /** Fresh options URL; supplied by the configured handlers. */
30
+ readonly endpoint: string;
31
+ /** CSP nonce for strict nonce policies. */
32
+ readonly nonce?: string;
33
+ /** Form fields the ceremony is for, from `Passkey.fields`, checked when it starts. */
34
+ readonly fields?: string;
35
+ }
36
+ /** The ceremony a signed form may start. */
37
+ type Expected = {
38
+ /** Path the form submits to */
39
+ action: string;
40
+ /** Form fields the ceremony is for, from `Passkey.fields` */
41
+ fields?: string;
42
+ } & ({
43
+ method: "register";
44
+ /** Name of the new passkey, at most 256 characters, not blank */
45
+ name: string;
46
+ } | {
47
+ method: "login";
48
+ /** Credential IDs a login is limited to, for a user already known */
49
+ allow?: readonly string[];
50
+ });
51
+ }
52
+ /** ES256 passkeys with single-use, browser-bound ceremonies. */
53
+ export declare class Passkey {
54
+ #private;
55
+ /** Hidden fields the browser module fills, added to each ceremony route's own */
56
+ static readonly shape: {
57
+ credential: Field.Instance<unknown, "input", "hidden", undefined, undefined>;
58
+ ceremony: Field.Instance<string, "input", "hidden", undefined, undefined>;
59
+ };
60
+ /** Create request-scoped passkey helpers. */
61
+ constructor(c: Auth.Context, auth: State);
62
+ /**
63
+ * Create a form in the handler before returning JSX.
64
+ *
65
+ * @template Pattern Pattern of the route the form submits to
66
+ */
67
+ form<Pattern extends string>(route: Passkey.Post<Pattern>, method: "register" | "login", options: Passkey.Options): Passkey.Component<Pattern>;
68
+ /** Dependency-free browser module, served as a normal same-origin JavaScript resource. */
69
+ static readonly client: Route.Used<Route.Get<"/_passkey/client.js", {}, Field.Shape>>;
70
+ /** Validate a signed form and issue one fresh ceremony. */
71
+ static issue(c: Pick<ContextType, "url" | "res" | "text" | "json">, auth: State, token: string, expected: Passkey.Expected): Promise<void>;
72
+ /** Digest canonical application values so field order cannot change the binding. */
73
+ static fields(value: unknown): Promise<string>;
74
+ /** Verify registration before persisting a new credential. */
75
+ register(fields?: string): Promise<{
76
+ id: string;
77
+ user: string;
78
+ publicKey: string;
79
+ counter: number;
80
+ eligible: boolean;
81
+ backedUp: boolean;
82
+ }>;
83
+ /**
84
+ * Verify login and atomically update the credential.
85
+ *
86
+ * @param credentials Stored credentials
87
+ * @param fields Form fields the ceremony was issued for, from `Passkey.fields`
88
+ * @param user User the ceremony offered the passkeys of, such as when
89
+ * allowing an agent, whose authenticator may then leave out the user handle
90
+ * @returns The updated credential
91
+ */
92
+ login(credentials: Storage.Credentials, fields?: string, user?: string): Promise<{
93
+ counter: number;
94
+ backedUp: boolean;
95
+ id: string;
96
+ user: string;
97
+ publicKey: string;
98
+ eligible: boolean;
99
+ }>;
100
+ }
101
+ //# sourceMappingURL=passkey.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passkey.d.ts","sourceRoot":"","sources":["../../src/auth/passkey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,qBAA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";
3
+ import { Route } from "../route/index.js";
4
+ import { Schema } from "../schema/index.js";
5
+ import { Codec, Time, noStore } from "../util/index.js";
6
+ import { AuthData } from "./auth-data.js";
7
+ import { CBOR, COSE } from "./cbor.js";
8
+ import { etag, source } from "./client-source.js";
9
+ import { DER } from "./der.js";
10
+ import { Issue } from "./issue.js";
11
+ import { Storage } from "./storage.js";
12
+ import { Token } from "./token.js";
13
+ /** ES256 passkeys with single-use, browser-bound ceremonies. */
14
+ export class Passkey {
15
+ /** Weak entity tag of the browser module */
16
+ static #etag = etag;
17
+ /** Hidden fields the browser module fills, added to each ceremony route's own */
18
+ static shape = {
19
+ credential: Field.hidden().json(Schema.unknown()),
20
+ ceremony: Field.hidden(),
21
+ };
22
+ static #payload = Schema.object({
23
+ credential: Schema.unknown(),
24
+ ceremony: Schema.string(),
25
+ });
26
+ static #bootstrap = Schema.object({
27
+ method: Schema.enum(["register", "login"]),
28
+ action: Schema.string(),
29
+ origin: Schema.string(),
30
+ browser: Schema.string(),
31
+ expiration: Schema.number().int(),
32
+ user: Schema.string().optional(),
33
+ fields: Schema.string().optional(),
34
+ });
35
+ static #credential = Schema.object({
36
+ type: Schema.literal("public-key"),
37
+ id: Schema.string(),
38
+ rawId: Schema.string(),
39
+ });
40
+ static #registration = Passkey.#credential.extend({
41
+ response: Schema.object({
42
+ clientDataJSON: Schema.string(),
43
+ attestationObject: Schema.string(),
44
+ }),
45
+ });
46
+ static #assertion = Passkey.#credential.extend({
47
+ response: Schema.object({
48
+ clientDataJSON: Schema.string(),
49
+ authenticatorData: Schema.string(),
50
+ signature: Schema.string(),
51
+ // browsers leave it out, rather than send null, when there is none
52
+ userHandle: Schema.string().nullable().optional(),
53
+ }),
54
+ });
55
+ #c;
56
+ #auth;
57
+ /** Create request-scoped passkey helpers. */
58
+ constructor(c, auth) {
59
+ this.#c = c;
60
+ this.#auth = auth;
61
+ }
62
+ /**
63
+ * Create a form in the handler before returning JSX.
64
+ *
65
+ * @template Pattern Pattern of the route the form submits to
66
+ */
67
+ form(route, method, options) {
68
+ this.#origin();
69
+ const browser = this.#auth.browser(true);
70
+ const user = method === "register" ? crypto.randomUUID() : undefined;
71
+ noStore(this.#c.res.headers);
72
+ const Form = Object.assign((props) => route.Form({
73
+ ...props,
74
+ children: [
75
+ props.children ?? [
76
+ route.Fields?.(),
77
+ jsx("button", {
78
+ children: method === "register" ? "Create account" : "Log in",
79
+ }),
80
+ ],
81
+ // A supplied Issue component takes precedence over this accessible fallback.
82
+ Form.Issue({ "data-passkey-fallback": true }),
83
+ async () => jsx("script", {
84
+ id: `passkey-${crypto.randomUUID()}`,
85
+ type: "module",
86
+ src: Passkey.client.url(),
87
+ nonce: options.nonce,
88
+ "data-passkey": method,
89
+ "data-endpoint": options.endpoint,
90
+ "data-bootstrap": await Token.seal(this.#auth.options.secret, "passkey", JSON.stringify({
91
+ method,
92
+ // the form's own params, checked by its props type
93
+ action: route.url({ params: props.params }),
94
+ origin: this.#auth.options.origin,
95
+ browser,
96
+ expiration: Date.now() + Time.hour,
97
+ user,
98
+ fields: options.fields,
99
+ })),
100
+ }),
101
+ jsx("noscript", {
102
+ children: "JavaScript is required for authentication.",
103
+ }),
104
+ ],
105
+ }), {
106
+ Issue: (props) => jsx("p", {
107
+ role: "status",
108
+ "aria-live": "polite",
109
+ ...props,
110
+ "data-passkey-error": true,
111
+ }),
112
+ });
113
+ return Form;
114
+ }
115
+ /** Dependency-free browser module, served as a normal same-origin JavaScript resource. */
116
+ static client = Route.get("/_passkey/client.js").use((c) => {
117
+ c.res.headers.set("content-type", "text/javascript; charset=utf-8");
118
+ c.res.headers.set("x-content-type-options", "nosniff");
119
+ c.res.headers.set("cache-control", "no-cache");
120
+ c.res.headers.set("etag", Passkey.#etag);
121
+ if (c.req.headers
122
+ .get("if-none-match")
123
+ ?.split(",")
124
+ .some((value) => value.trim() === "*" ||
125
+ value.trim().replace(/^W\//, "") === Passkey.#etag.slice(2))) {
126
+ c.res.status = 304;
127
+ c.res.body = null;
128
+ return;
129
+ }
130
+ c.res.body = source;
131
+ });
132
+ #origin() {
133
+ if (this.#c.url.origin !== this.#auth.options.origin)
134
+ throw new Issue("origin");
135
+ }
136
+ /** Validate a signed form and issue one fresh ceremony. */
137
+ static async issue(c, auth, token, expected) {
138
+ const result = Schema.string()
139
+ .json(Passkey.#bootstrap)
140
+ .parse(await Token.open(auth.options.secret, "passkey", token));
141
+ if (result.issues)
142
+ throw new Issue("bootstrap");
143
+ const bootstrap = result.data;
144
+ if (c.url.origin !== auth.options.origin ||
145
+ bootstrap.origin !== auth.options.origin)
146
+ throw new Issue("origin");
147
+ if (!auth.browser() ||
148
+ bootstrap.browser !== auth.browser() ||
149
+ bootstrap.expiration <= Date.now())
150
+ return c.text("This page has expired. Reload and try again.", 410);
151
+ if (bootstrap.method !== expected.method ||
152
+ bootstrap.action !== expected.action ||
153
+ // a page made for some fields, such as one consent request, starts only their ceremony
154
+ (bootstrap.fields !== undefined && bootstrap.fields !== expected.fields))
155
+ throw new Issue("bootstrap binding");
156
+ // the same method as the form's, checked above
157
+ const register = expected.method === "register";
158
+ if (register &&
159
+ (!bootstrap.user || Codec.encode(bootstrap.user).length > 64))
160
+ throw new Issue("user");
161
+ const rp = new URL(auth.options.origin).hostname;
162
+ const ceremony = crypto.randomUUID();
163
+ const challenge = Token.random();
164
+ if ((await auth.options.challenges.set(ceremony, {
165
+ challenge,
166
+ browser: bootstrap.browser,
167
+ method: bootstrap.method,
168
+ action: bootstrap.action,
169
+ origin: bootstrap.origin,
170
+ expiration: Date.now() + 2 * Time.minute,
171
+ ...(bootstrap.user ? { user: bootstrap.user } : {}),
172
+ ...(expected.fields ? { fields: expected.fields } : {}),
173
+ })) === false) {
174
+ return Issue.limited(c, 60);
175
+ }
176
+ noStore(c.res.headers);
177
+ if (register) {
178
+ c.json({
179
+ ceremony,
180
+ options: {
181
+ challenge,
182
+ rp: { id: rp, name: rp },
183
+ user: {
184
+ id: Codec.Base64Url.encode(Codec.encode(bootstrap.user)),
185
+ name: expected.name,
186
+ displayName: expected.name,
187
+ },
188
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }],
189
+ authenticatorSelection: {
190
+ residentKey: "required",
191
+ requireResidentKey: true,
192
+ userVerification: "required",
193
+ },
194
+ timeout: Time.minute,
195
+ attestation: "none",
196
+ },
197
+ });
198
+ }
199
+ else
200
+ c.json({
201
+ ceremony,
202
+ options: {
203
+ challenge,
204
+ rpId: rp,
205
+ timeout: Time.minute,
206
+ userVerification: "required",
207
+ // the picker offers only the user's passkeys
208
+ ...(expected.allow?.length && {
209
+ allowCredentials: expected.allow.map((id) => ({
210
+ type: "public-key",
211
+ id,
212
+ })),
213
+ }),
214
+ },
215
+ });
216
+ }
217
+ static #decode(value) {
218
+ if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1)
219
+ throw new Issue("base64url");
220
+ const bytes = Codec.Base64Url.decode(value);
221
+ if (Codec.Base64Url.encode(bytes) !== value)
222
+ throw new Issue("base64url");
223
+ return bytes;
224
+ }
225
+ static async #hash(value) {
226
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", value));
227
+ }
228
+ static async #key(value) {
229
+ try {
230
+ return await crypto.subtle.importKey("spki", value, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
231
+ }
232
+ catch (e) {
233
+ if (e instanceof DOMException)
234
+ throw new Issue("public key");
235
+ throw e;
236
+ }
237
+ }
238
+ /**
239
+ * Take the ceremony a credential answers, and check what both ceremonies share.
240
+ *
241
+ * @template T Credential the browser sends
242
+ * @param method Ceremony
243
+ * @param fields Form fields the ceremony was issued for, from `Passkey.fields`
244
+ * @param schema Credential the browser sends
245
+ * @returns The ceremony, the credential, and its client data
246
+ */
247
+ async #consume(method, fields, schema) {
248
+ this.#origin();
249
+ // a route's `c.data()` resolves to its parse result
250
+ const parsed = (await Issue.data(this.#c));
251
+ const result = Passkey.#payload.parse(parsed?.data);
252
+ if (result.issues)
253
+ throw new Issue("passkey request");
254
+ const state = await this.#auth.options.challenges.take(result.data.ceremony);
255
+ if (!state || state.expiration <= Date.now())
256
+ throw new Issue("challenge (expired or consumed)");
257
+ if (!this.#auth.browser() || state.browser !== this.#auth.browser())
258
+ throw new Issue("browser");
259
+ if (state.origin !== this.#auth.options.origin ||
260
+ state.method !== method ||
261
+ state.action !== this.#c.url.pathname)
262
+ throw new Issue("challenge binding");
263
+ if (state.fields !== fields)
264
+ throw new Issue("ceremony fields");
265
+ const credential = schema.parse(result.data.credential);
266
+ if (credential.issues)
267
+ throw new Issue("credential response");
268
+ const client = this.#client(credential.data.response.clientDataJSON, state);
269
+ if (!Passkey.#equal(Passkey.#decode(credential.data.id), Passkey.#decode(credential.data.rawId)))
270
+ throw new Issue("credential ID");
271
+ return { state, credential: credential.data, client };
272
+ }
273
+ /** @returns The client data, verified for the ceremony */
274
+ #client(value, state) {
275
+ let bytes;
276
+ let json;
277
+ try {
278
+ bytes = Passkey.#decode(value);
279
+ json = Codec.decode(bytes);
280
+ }
281
+ catch (error) {
282
+ // invalid UTF-8, sent by the client
283
+ if (error instanceof Issue)
284
+ throw error;
285
+ throw new Issue("client data");
286
+ }
287
+ const result = Schema.string()
288
+ .json(Schema.object({
289
+ type: Schema.literal(state.method === "register" ? "webauthn.create" : "webauthn.get"),
290
+ origin: Schema.literal(this.#auth.options.origin),
291
+ challenge: Schema.literal(state.challenge),
292
+ crossOrigin: Schema.literal(false).optional(),
293
+ }))
294
+ .parse(json);
295
+ if (result.issues)
296
+ throw new Issue("client data");
297
+ return bytes;
298
+ }
299
+ /** @returns Authenticator data, for this origin and a verified user */
300
+ async #data(bytes) {
301
+ const data = AuthData.parse(bytes);
302
+ if (!Passkey.#equal(data.rpIdHash, await Passkey.#hash(Codec.encode(new URL(this.#auth.options.origin).hostname))))
303
+ throw new Issue("RP ID");
304
+ if (!(data.flags & 1) || !(data.flags & 4))
305
+ throw new Issue("user");
306
+ if (data.flags & 16 && !(data.flags & 8))
307
+ throw new Issue("backup flags");
308
+ return data;
309
+ }
310
+ static #equal(a, b) {
311
+ if (a.length !== b.length)
312
+ return false;
313
+ let result = 0;
314
+ for (let i = 0; i < a.length; i++)
315
+ result |= a[i] ^ b[i];
316
+ return result === 0;
317
+ }
318
+ /** Digest canonical application values so field order cannot change the binding. */
319
+ static fields(value) {
320
+ // base64url SHA-256, like a stored token
321
+ return Storage.hash(JSON.stringify(value, (_, value) => value && typeof value === "object" && !Array.isArray(value)
322
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))
323
+ : value));
324
+ }
325
+ /** Verify registration before persisting a new credential. */
326
+ async register(fields) {
327
+ const { state, credential } = await this.#consume("register", fields, Passkey.#registration);
328
+ const data = await this.#data(new CBOR(Passkey.#decode(credential.response.attestationObject)).decodeAttestation());
329
+ if (!data.attestedCredentialData || !state.user)
330
+ throw new Issue("credential data");
331
+ // the same as `rawId`, which the ceremony checked
332
+ if (!Passkey.#equal(Passkey.#decode(credential.id), data.attestedCredentialData.credentialId))
333
+ throw new Issue("credential ID");
334
+ const key = COSE.toSPKI(data.attestedCredentialData.publicKey);
335
+ // Web Crypto validates that the P-256 point is on the curve before it is stored.
336
+ await Passkey.#key(key);
337
+ return {
338
+ id: credential.id,
339
+ user: state.user,
340
+ publicKey: Codec.Base64Url.encode(key),
341
+ counter: data.counter,
342
+ eligible: Boolean(data.flags & 8),
343
+ backedUp: Boolean(data.flags & 16),
344
+ };
345
+ }
346
+ /**
347
+ * Verify login and atomically update the credential.
348
+ *
349
+ * @param credentials Stored credentials
350
+ * @param fields Form fields the ceremony was issued for, from `Passkey.fields`
351
+ * @param user User the ceremony offered the passkeys of, such as when
352
+ * allowing an agent, whose authenticator may then leave out the user handle
353
+ * @returns The updated credential
354
+ */
355
+ async login(credentials, fields, user) {
356
+ const { credential, client } = await this.#consume("login", fields, Passkey.#assertion);
357
+ const { response } = credential;
358
+ const stored = await credentials.get(credential.id);
359
+ if (!stored || stored.id !== credential.id)
360
+ throw new Issue("credential");
361
+ const handle = response.userHandle;
362
+ // without a handle, only a passkey of the user identified before the
363
+ // ceremony, which offered theirs (WebAuthn, verifying an assertion)
364
+ if (handle
365
+ ? !Passkey.#equal(Passkey.#decode(handle), Codec.encode(stored.user))
366
+ : stored.user !== user)
367
+ throw new Issue("user handle");
368
+ const bytes = Passkey.#decode(response.authenticatorData);
369
+ const data = await this.#data(bytes);
370
+ if (data.attestedCredentialData)
371
+ throw new Issue("assertion flags");
372
+ if (Boolean(data.flags & 8) !== stored.eligible)
373
+ throw new Issue("backup eligibility");
374
+ if (!Number.isSafeInteger(stored.counter) ||
375
+ stored.counter < 0 ||
376
+ ((stored.counter || data.counter) && data.counter <= stored.counter))
377
+ throw new Issue("signature counter");
378
+ const hash = await Passkey.#hash(client);
379
+ const signed = new Uint8Array(bytes.length + hash.length);
380
+ signed.set(bytes);
381
+ signed.set(hash, bytes.length);
382
+ if (!(await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, await Passkey.#key(Passkey.#decode(stored.publicKey)), DER.unwrap(Passkey.#decode(response.signature)), signed)))
383
+ throw new Issue("signature");
384
+ const updated = {
385
+ ...stored,
386
+ counter: data.counter,
387
+ backedUp: Boolean(data.flags & 16),
388
+ };
389
+ if (!(await credentials.update(updated, stored)))
390
+ throw new Issue("credential changed");
391
+ return updated;
392
+ }
393
+ }
@@ -0,0 +1,49 @@
1
+ import { type Context as ContextType } from "../context/index.js";
2
+ import type { Auth } from "./index.js";
3
+ import type { Storage } from "./storage.js";
4
+ export declare namespace State {
5
+ /** Session persistence and signing configuration used by internal request state. */
6
+ type Options = Pick<Auth.Options, "secret" | "origin" | "idle" | "lifetime"> & Pick<Storage, "challenges" | "sessions">;
7
+ /** Internal capabilities needed for request-local authentication state. */
8
+ type Context = Pick<Auth.Context, "url" | "cookie" | "res">;
9
+ }
10
+ /** Internal authentication state for exactly one service and request. */
11
+ export declare class State {
12
+ #private;
13
+ /** Normalized authentication configuration. */
14
+ readonly options: {
15
+ challenges: Storage.Challenges;
16
+ sessions: Storage.Sessions;
17
+ lifetime: number;
18
+ idle: number;
19
+ secret: string | readonly [string, ...string[]];
20
+ origin: string;
21
+ };
22
+ /** Create authentication helpers for the current request. */
23
+ constructor(c: State.Context, options: State.Options);
24
+ /** Read a browser binding; create it only while preparing a form in the handler. */
25
+ browser(create?: boolean): string | undefined;
26
+ /** Read a non-expired, non-revoked session, renewing it while it is used. */
27
+ session(): Promise<ContextType.Session | null>;
28
+ /**
29
+ * Return to a local path after the next login, such as an agent's
30
+ * authorization request.
31
+ *
32
+ * @param path Local path with its query
33
+ */
34
+ remember(path: string): void;
35
+ /**
36
+ * @param fallback Destination without a remembered path
37
+ * @returns The remembered path, cleared, or the fallback
38
+ */
39
+ resume(fallback: string): string;
40
+ /** Replace the current session and issue a new signed, secure cookie. */
41
+ login(user: string): Promise<{
42
+ id: `${string}-${string}-${string}-${string}-${string}`;
43
+ user: string;
44
+ expiration: number;
45
+ }>;
46
+ /** Revoke the current session and expire its cookie. Always await this method. */
47
+ logout(): Promise<null>;
48
+ }
49
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/auth/state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,IAAI,WAAW,EAAS,MAAM,qBAAqB,CAAC;AAEzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAG5C,yBAAiB,KAAK,CAAC;IACtB,oFAAoF;IACpF,KAAY,OAAO,GAAG,IAAI,CACzB,IAAI,CAAC,OAAO,EACZ,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,UAAU,CACzC,GACA,IAAI,CAAC,OAAO,EAAE,YAAY,GAAG,UAAU,CAAC,CAAC;IAC1C,2EAA2E;IAC3E,KAAY,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GAAG,KAAK,CAAC,CAAC;CACnE;AAED,yEAAyE;AACzE,qBAAa,KAAK;;IAQjB,+CAA+C;IAC/C,QAAQ,CAAC,OAAO;;;;;;;MAAC;IAEjB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EASnD;IAeD,oFAAoF;IACpF,OAAO,CAAC,MAAM,UAAQ,sBAQrB;IA+ED,6EAA6E;IAC7E,OAAO,wCAEN;IAED;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,QAKpB;IAED;;;OAGG;IACH,MAAM,CAAC,QAAQ,EAAE,MAAM,UAYtB;IAED,yEAAyE;IACnE,KAAK,CAAC,IAAI,EAAE,MAAM;;;;OAqBvB;IAED,kFAAkF;IAC5E,MAAM,kBAOX;CACD"}