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,56 @@
1
+ import { CBOR } from "./cbor.js";
2
+ import { Issue } from "./issue.js";
3
+
4
+ export namespace AuthData {
5
+ /** Parsed authenticator data and credential state. */
6
+ export interface Data {
7
+ rpIdHash: Uint8Array;
8
+ flags: number;
9
+ counter: number;
10
+ attestedCredentialData: AttestedCredentialData | null;
11
+ }
12
+ /** Attested ES256 credential. */
13
+ export interface AttestedCredentialData {
14
+ aaguid: Uint8Array;
15
+ credentialId: Uint8Array;
16
+ publicKey: Map<number, number | Uint8Array>;
17
+ }
18
+ }
19
+
20
+ /** Bounded parser for WebAuthn authenticator data. */
21
+ export class AuthData {
22
+ /** Parse the fixed header, optional attested credential, and optional extensions. */
23
+ static parse(data: Uint8Array) {
24
+ if (data.length < 37) throw new Issue("credential");
25
+ const view = new DataView(data.buffer, data.byteOffset, data.length);
26
+ const flags = data[32]!;
27
+ let end = 37;
28
+ let attestedCredentialData: AuthData.AttestedCredentialData | null = null;
29
+ if (flags & 64) {
30
+ if (data.length < 55) throw new Issue("credential");
31
+ const length = view.getUint16(53);
32
+ end = 55 + length;
33
+ if (!length || length > 1023 || end >= data.length)
34
+ throw new Issue("credential");
35
+ const cbor = new CBOR(data.subarray(end));
36
+ attestedCredentialData = {
37
+ aaguid: data.subarray(37, 53),
38
+ credentialId: data.subarray(55, end),
39
+ publicKey: cbor.decodeCOSEKey(),
40
+ };
41
+ end += cbor.offset;
42
+ }
43
+ if (flags & 128) {
44
+ const cbor = new CBOR(data.subarray(end));
45
+ cbor.decodeExtensions();
46
+ end += cbor.offset;
47
+ }
48
+ if (end !== data.length) throw new Issue("authenticator data length");
49
+ return {
50
+ rpIdHash: data.subarray(0, 32),
51
+ flags,
52
+ counter: view.getUint32(33),
53
+ attestedCredentialData,
54
+ };
55
+ }
56
+ }
@@ -0,0 +1,231 @@
1
+ import { Codec } from "../util/index.js";
2
+ import { Issue } from "./issue.js";
3
+
4
+ /** COSE (CBOR Object Signing and Encryption) key format utilities */
5
+ export class COSE {
6
+ /** Fixed SPKI header for an uncompressed P-256 point. */
7
+ static readonly #prefix = new Uint8Array([
8
+ 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
9
+ 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
10
+ 0x42, 0x00, 0x04,
11
+ ]);
12
+
13
+ /**
14
+ * Convert COSE public key to SPKI format.
15
+ *
16
+ * Only EC2 keys with P-256 curve (ES256, alg -7) are supported. This is the standard modern algorithm
17
+ * supported by virtually all platform authenticators (https://www.rfc-editor.org/rfc/rfc8152#section-8.1).
18
+ *
19
+ * @param cose - COSE key map with type, curve, and coordinates
20
+ * @returns SPKI encoded public key as bytes
21
+ * @throws Issue if key type, curve, or coordinates are invalid
22
+ */
23
+ static toSPKI(cose: Map<number, number | Uint8Array>) {
24
+ if (cose.get(1) !== 2) throw new Issue("COSE type");
25
+ if (cose.get(-1) !== 1) throw new Issue("COSE curve");
26
+ if (cose.get(3) !== -7) throw new Issue("COSE algorithm");
27
+
28
+ const x = cose.get(-2); // COSE label -2 = x coordinate
29
+ const y = cose.get(-3); // COSE label -3 = y coordinate
30
+
31
+ if (
32
+ !(x instanceof Uint8Array) ||
33
+ !(y instanceof Uint8Array) ||
34
+ x.length !== 32 ||
35
+ y.length !== 32
36
+ )
37
+ throw new Issue("COSE coordinates");
38
+
39
+ return new Uint8Array([...COSE.#prefix, ...x, ...y]);
40
+ }
41
+ }
42
+
43
+ export namespace CBOR {
44
+ export type Key = number | string;
45
+ export type Value =
46
+ number | string | boolean | null | Uint8Array | Map<Key, Value> | Value[];
47
+ }
48
+
49
+ /** CBOR (Concise Binary Object Representation) decoder for WebAuthn data */
50
+ export class CBOR {
51
+ /** Encoded data to decode */
52
+ readonly #data: Uint8Array;
53
+
54
+ /** Current read position in data */
55
+ #offset = 0;
56
+
57
+ /**
58
+ * Create a new CBOR instance
59
+ *
60
+ * @param data WebAuthn data
61
+ */
62
+ constructor(data: Uint8Array) {
63
+ if (data.length > 65536) throw new Issue("CBOR size");
64
+ this.#data = data;
65
+ }
66
+
67
+ /**
68
+ * Decode attestation object and extract authenticator data.
69
+ *
70
+ * Only supports fmt === "none", other formats may throw earlier depending on CBOR contents
71
+ *
72
+ * @returns Authenticator data bytes
73
+ * @throws Issue if CBOR structure is invalid
74
+ */
75
+ decodeAttestation() {
76
+ const value = this.#parseNext();
77
+
78
+ if (value instanceof Map) {
79
+ const authData = value.get("authData");
80
+
81
+ const statement = value.get("attStmt");
82
+ if (
83
+ value.get("fmt") === "none" &&
84
+ authData instanceof Uint8Array &&
85
+ statement instanceof Map &&
86
+ statement.size === 0 &&
87
+ this.#offset === this.#data.length
88
+ ) {
89
+ return authData;
90
+ }
91
+ }
92
+
93
+ throw new Issue("credential");
94
+ }
95
+
96
+ /**
97
+ * Decode COSE key from CBOR format.
98
+ *
99
+ * @returns COSE key map with numeric labels
100
+ * @throws Issue if CBOR structure is invalid
101
+ */
102
+ decodeCOSEKey() {
103
+ const value = this.#parseNext();
104
+
105
+ if (!(value instanceof Map)) {
106
+ throw new Issue("CBOR map");
107
+ }
108
+
109
+ const result = new Map<number, number | Uint8Array>();
110
+
111
+ for (const [k, v] of value) {
112
+ if (typeof k !== "number") {
113
+ throw new Issue("COSE labels");
114
+ }
115
+
116
+ if (typeof v !== "number" && !(v instanceof Uint8Array)) {
117
+ throw new Issue("COSE value");
118
+ }
119
+
120
+ result.set(k, v);
121
+ }
122
+
123
+ return result;
124
+ }
125
+
126
+ /** Bytes consumed by the last decoded value. */
127
+ get offset() {
128
+ return this.#offset;
129
+ }
130
+
131
+ /** Decode authenticator extensions as a CBOR map. */
132
+ decodeExtensions() {
133
+ const value = this.#parseNext();
134
+ if (
135
+ !(value instanceof Map) ||
136
+ [...value.keys()].some((key) => typeof key !== "string")
137
+ )
138
+ throw new Issue("CBOR extensions");
139
+ return value;
140
+ }
141
+
142
+ /**
143
+ * Read n bytes and advance offset.
144
+ *
145
+ * @param n - Number of bytes to read
146
+ * @returns Subarray of data
147
+ */
148
+ #read(n: number) {
149
+ const end = this.#offset + n;
150
+
151
+ if (end > this.#data.length) {
152
+ throw new Issue("CBOR stream");
153
+ }
154
+
155
+ return this.#data.subarray(this.#offset, (this.#offset = end));
156
+ }
157
+
158
+ /**
159
+ * Read a big-endian unsigned integer from n bytes.
160
+ *
161
+ * @param bytes - Number of bytes to read (1, 2, or 4)
162
+ * @returns Decoded unsigned integer
163
+ * @throws Issue if the stream ends first
164
+ */
165
+ #readUint(bytes: number) {
166
+ let value = 0;
167
+ for (const byte of this.#read(bytes)) value = value * 256 + byte;
168
+ return value;
169
+ }
170
+
171
+ /**
172
+ * Parse next CBOR value from stream.
173
+ *
174
+ * @returns Decoded value (primitives, Uint8Array, or Map)
175
+ * @throws Issue if stream is malformed
176
+ */
177
+ #parseNext(depth = 0): CBOR.Value {
178
+ if (depth > 8) throw new Issue("CBOR depth");
179
+
180
+ const initial = this.#read(1)[0]!;
181
+ const major = initial >> 5;
182
+ const minor = initial & 0x1f;
183
+
184
+ if (major === 7 && minor === 20) return false;
185
+ if (major === 7 && minor === 21) return true;
186
+ if (major === 7 && minor === 22) return null;
187
+
188
+ let length: number;
189
+ if (minor < 24) {
190
+ length = minor;
191
+ } else if (minor < 27) {
192
+ // 24, 25 and 26 are followed by 1, 2 and 4 bytes
193
+ length = this.#readUint(2 ** (minor - 24));
194
+ } else {
195
+ throw new Issue("CBOR length");
196
+ }
197
+
198
+ if (major === 0) return length;
199
+ if (major === 1) return -1 - length;
200
+ if (major === 2) return this.#read(length);
201
+ if (major === 3) {
202
+ try {
203
+ return Codec.decode(this.#read(length));
204
+ } catch {
205
+ throw new Issue("CBOR text");
206
+ }
207
+ }
208
+ if ((major === 4 || major === 5) && length > 128)
209
+ throw new Issue("CBOR entries");
210
+ if (major === 4)
211
+ return Array.from({ length }, () => this.#parseNext(depth + 1));
212
+ if (major === 5) {
213
+ const map = new Map<CBOR.Key, CBOR.Value>();
214
+
215
+ for (let i = 0; i < length; i++) {
216
+ const k = this.#parseNext(depth + 1);
217
+
218
+ if (typeof k !== "number" && typeof k !== "string") {
219
+ throw new Issue("CBOR key");
220
+ }
221
+
222
+ if (map.has(k)) throw new Issue("CBOR duplicate key");
223
+ map.set(k, this.#parseNext(depth + 1));
224
+ }
225
+
226
+ return map;
227
+ }
228
+
229
+ throw new Issue(`CBOR type ${major}`);
230
+ }
231
+ }
@@ -0,0 +1,3 @@
1
+ // Generated by scripts/client.js; edit client.ts instead.
2
+ export const source = "export function listen(e,t,n,r){let i=document.getElementById(e),a=i?.closest(`form`),o=i?.previousElementSibling,s=a?.querySelector(`[data-passkey-error]:not([data-passkey-fallback])`)??o;if(!(a instanceof HTMLFormElement)||!(s instanceof HTMLElement))return;s!==o&&o instanceof HTMLElement&&(o.hidden=!0);let c=e=>{let t=a.elements.namedItem(e);if(t instanceof HTMLInputElement)return t;let n=document.createElement(`input`);return n.type=`hidden`,n.name=e,a.append(n),n},l=c(`credential`),u=c(`ceremony`),d=!1,f=!1,p=!1,m,h=0,g,_=()=>`Too many requests. Try again in ${Math.ceil((h-Date.now())/1e3)} seconds.`,v=()=>{clearTimeout(g),g=void 0,d=f=p=!1,m=void 0,l.value=u.value=``,a.removeAttribute(`aria-busy`)},y=(e,t)=>{e instanceof HTMLElement&&`setCustomValidity`in e&&typeof e.setCustomValidity==`function`&&e.setCustomValidity(t)},b=e=>y(e.target,``);return a.addEventListener(`input`,b),a.addEventListener(`change`,b),a.addEventListener(`submit`,async e=>{if(!e.submitter?.hasAttribute(`formaction`)){if(f){p?m=e:e.preventDefault();return}if(e.preventDefault(),!d){if(h>Date.now()){s.textContent=_();return}d=!0,s.textContent=``,a.setAttribute(`aria-busy`,`true`);try{if(!window.PublicKeyCredential?.parseCreationOptionsFromJSON||!PublicKeyCredential.parseRequestOptionsFromJSON||!navigator.credentials)throw Error(`Passkeys are unavailable in this browser.`);let i=new FormData(a);i.delete(`credential`),i.delete(`ceremony`),i.set(`bootstrap`,t);let o=await fetch(n,{method:`POST`,body:i,credentials:`same-origin`,cache:`no-store`});if(o.status===429){let e=Date.now(),t=o.headers.get(`retry-after`)??`60`,n=/^\\d+$/.test(t)?e+Number(t)*1e3:Date.parse(t);throw h=Number.isNaN(n)?e+6e4:Math.min(e+36e5,Math.max(e+1e3,n)),Error(_())}if(o.status===422){let e=await o.json();if(Array.isArray(e.fields))for(let t of e.fields)typeof t==`string`&&y(a.elements.namedItem(t),`Check this field.`);throw a.reportValidity(),Error(`Check your registration details and try again.`)}if(o.status===410)throw Error(`This page has expired. Reload and try again.`);if(!o.ok)throw Error(`Could not start the passkey request. Try again.`);let c=await o.json();u.value=c.ceremony;let d=await(r===`register`?navigator.credentials.create({publicKey:PublicKeyCredential.parseCreationOptionsFromJSON(c.options)}):navigator.credentials.get({publicKey:PublicKeyCredential.parseRequestOptionsFromJSON(c.options)}));if(!(d instanceof PublicKeyCredential))throw Error(`No passkey was returned. Try again.`);l.value=JSON.stringify(d),f=!0,p=!0,m=void 0,HTMLFormElement.prototype.requestSubmit.call(a,e.submitter??void 0),p=!1,f=!!(m&&!m.defaultPrevented),f&&(g=setTimeout(()=>{v(),s.textContent=r===`register`?`If registration already completed, sign in; otherwise try again.`:`If sign-in did not finish, try again.`},12e4))}catch(e){v(),s.textContent=e instanceof DOMException&&e.name===`NotAllowedError`?`Passkey request canceled. Try again.`:e instanceof Error?e.message:`Could not complete the passkey request. Try again.`}finally{d=!1,p=!1,f||a.removeAttribute(`aria-busy`)}}}}),v}const t=new WeakMap,n=()=>document.querySelectorAll(`script[data-passkey]`),r=()=>{for(let r of n()){if(t.has(r))continue;let n=r.dataset.passkey;if(n===`register`||n===`login`){let i=listen(r.id,r.dataset.bootstrap??``,r.dataset.endpoint??``,n);i&&t.set(r,i)}}};typeof document<`u`&&(window.addEventListener(`pageshow`,e=>{if(e.persisted)for(let e of n())t.get(e)?.()}),r(),new MutationObserver(r).observe(document.documentElement,{childList:!0,subtree:!0}));";
3
+ export const etag = "W/\"c904f3541cdce47df6c6e44e6ae8fddaa56155055b2b65bc580de00ff3741e7b\"";
@@ -0,0 +1,205 @@
1
+ /** Attach the passkey protocol to one form. Served as a normal browser module. */
2
+ export function listen(
3
+ id: string,
4
+ bootstrap: string,
5
+ endpoint: string,
6
+ method: "register" | "login",
7
+ ) {
8
+ const script = document.getElementById(id);
9
+ const form = script?.closest("form");
10
+ // the accessible error component the form renders before the script
11
+ const fallback = script?.previousElementSibling;
12
+ const status =
13
+ form?.querySelector("[data-passkey-error]:not([data-passkey-fallback])") ??
14
+ fallback;
15
+ if (!(form instanceof HTMLFormElement) || !(status instanceof HTMLElement))
16
+ return;
17
+ if (status !== fallback && fallback instanceof HTMLElement)
18
+ fallback.hidden = true;
19
+
20
+ const hidden = (name: string) => {
21
+ const field = form.elements.namedItem(name);
22
+ if (field instanceof HTMLInputElement) return field;
23
+ const input = document.createElement("input");
24
+ input.type = "hidden";
25
+ input.name = name;
26
+ form.append(input);
27
+ return input;
28
+ };
29
+ const credential = hidden("credential");
30
+ const ceremony = hidden("ceremony");
31
+ let loading = false;
32
+ let submitting = false;
33
+ let finalizing = false;
34
+ let submitted: SubmitEvent | undefined;
35
+ let retry = 0;
36
+ let timer: ReturnType<typeof setTimeout> | undefined;
37
+ const limited = () =>
38
+ `Too many requests. Try again in ${Math.ceil((retry - Date.now()) / 1000)} seconds.`;
39
+ const reset = () => {
40
+ clearTimeout(timer);
41
+ timer = undefined;
42
+ loading = submitting = finalizing = false;
43
+ submitted = undefined;
44
+ credential.value = ceremony.value = "";
45
+ form.removeAttribute("aria-busy");
46
+ };
47
+ /** Mark a form field invalid, or valid again with an empty message */
48
+ const validity = (field: unknown, message: string) => {
49
+ if (
50
+ field instanceof HTMLElement &&
51
+ "setCustomValidity" in field &&
52
+ typeof field.setCustomValidity === "function"
53
+ )
54
+ field.setCustomValidity(message);
55
+ };
56
+ const clear = (e: Event) => validity(e.target, "");
57
+ form.addEventListener("input", clear);
58
+ form.addEventListener("change", clear);
59
+
60
+ form.addEventListener("submit", async (e) => {
61
+ // a button that submits elsewhere, such as Deny, needs no passkey
62
+ if (e.submitter?.hasAttribute("formaction")) return;
63
+ if (submitting) {
64
+ if (finalizing) submitted = e;
65
+ else e.preventDefault();
66
+ return;
67
+ }
68
+ e.preventDefault();
69
+ if (loading) return;
70
+ if (retry > Date.now()) {
71
+ status.textContent = limited();
72
+ return;
73
+ }
74
+ loading = true;
75
+ status.textContent = "";
76
+ form.setAttribute("aria-busy", "true");
77
+ try {
78
+ // checked before asking for options, which would spend a challenge
79
+ if (
80
+ !window.PublicKeyCredential?.parseCreationOptionsFromJSON ||
81
+ !PublicKeyCredential.parseRequestOptionsFromJSON ||
82
+ !navigator.credentials
83
+ )
84
+ throw new Error("Passkeys are unavailable in this browser.");
85
+ const data = new FormData(form);
86
+ data.delete("credential");
87
+ data.delete("ceremony");
88
+ data.set("bootstrap", bootstrap);
89
+ const res = await fetch(endpoint, {
90
+ method: "POST",
91
+ body: data,
92
+ credentials: "same-origin",
93
+ cache: "no-store",
94
+ });
95
+ if (res.status === 429) {
96
+ const now = Date.now();
97
+ const header = res.headers.get("retry-after") ?? "60";
98
+ const deadline = /^\d+$/.test(header)
99
+ ? now + Number(header) * 1000
100
+ : Date.parse(header);
101
+ retry = Number.isNaN(deadline)
102
+ ? now + 60000
103
+ : Math.min(now + 3600000, Math.max(now + 1000, deadline));
104
+ throw new Error(limited());
105
+ }
106
+ if (res.status === 422) {
107
+ const result: { fields?: unknown } = await res.json();
108
+ if (Array.isArray(result.fields))
109
+ for (const name of result.fields)
110
+ if (typeof name === "string")
111
+ validity(form.elements.namedItem(name), "Check this field.");
112
+ form.reportValidity();
113
+ throw new Error("Check your registration details and try again.");
114
+ }
115
+ if (res.status === 410)
116
+ throw new Error("This page has expired. Reload and try again.");
117
+ if (!res.ok)
118
+ throw new Error("Could not start the passkey request. Try again.");
119
+
120
+ // creation options for a registration, request options for a login
121
+ const json: { ceremony: string; options: unknown } = await res.json();
122
+ ceremony.value = json.ceremony;
123
+
124
+ const result = await (method === "register"
125
+ ? navigator.credentials.create({
126
+ publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(
127
+ json.options as PublicKeyCredentialCreationOptionsJSON,
128
+ ),
129
+ })
130
+ : navigator.credentials.get({
131
+ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(
132
+ json.options as PublicKeyCredentialRequestOptionsJSON,
133
+ ),
134
+ }));
135
+ if (!(result instanceof PublicKeyCredential))
136
+ throw new Error("No passkey was returned. Try again.");
137
+ credential.value = JSON.stringify(result);
138
+ submitting = true;
139
+ finalizing = true;
140
+ submitted = undefined;
141
+ // Preserve native validation, submit events, and the original submitter.
142
+ HTMLFormElement.prototype.requestSubmit.call(
143
+ form,
144
+ e.submitter ?? undefined,
145
+ );
146
+ finalizing = false;
147
+ // requestSubmit synchronously re-enters this listener; TypeScript cannot see that assignment.
148
+ // Validation may prevent the final event; another listener may cancel it.
149
+ submitting = Boolean(
150
+ submitted && !(submitted as SubmitEvent).defaultPrevented,
151
+ );
152
+ if (submitting)
153
+ timer = setTimeout(() => {
154
+ reset();
155
+ status.textContent =
156
+ method === "register"
157
+ ? "If registration already completed, sign in; otherwise try again."
158
+ : "If sign-in did not finish, try again.";
159
+ }, 120000);
160
+ } catch (error) {
161
+ reset();
162
+ status.textContent =
163
+ error instanceof DOMException && error.name === "NotAllowedError"
164
+ ? "Passkey request canceled. Try again."
165
+ : error instanceof Error
166
+ ? error.message
167
+ : "Could not complete the passkey request. Try again.";
168
+ } finally {
169
+ loading = false;
170
+ finalizing = false;
171
+ if (!submitting) form.removeAttribute("aria-busy");
172
+ }
173
+ });
174
+ return reset;
175
+ }
176
+
177
+ // Modules execute once per document. Observe streamed HTML and subsequent fragment navigation too.
178
+ const attached = new WeakMap<HTMLScriptElement, () => void>();
179
+ const scripts = () =>
180
+ document.querySelectorAll<HTMLScriptElement>("script[data-passkey]");
181
+ const scan = () => {
182
+ for (const script of scripts()) {
183
+ if (attached.has(script)) continue;
184
+ const method = script.dataset.passkey;
185
+ if (method === "register" || method === "login") {
186
+ const reset = listen(
187
+ script.id,
188
+ script.dataset.bootstrap ?? "",
189
+ script.dataset.endpoint ?? "",
190
+ method,
191
+ );
192
+ if (reset) attached.set(script, reset);
193
+ }
194
+ }
195
+ };
196
+ if (typeof document !== "undefined") {
197
+ window.addEventListener("pageshow", (e) => {
198
+ if (e.persisted) for (const script of scripts()) attached.get(script)?.();
199
+ });
200
+ scan();
201
+ new MutationObserver(scan).observe(document.documentElement, {
202
+ childList: true,
203
+ subtree: true,
204
+ });
205
+ }