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,882 @@
1
+ import { crossOrigin, direct } from "../app/index.js";
2
+ import type { Context } from "../context/index.js";
3
+ import { Field } from "../form/index.js";
4
+ import { jsx } from "../jsx/index.js";
5
+ import { Limiter, network } from "../limiter/index.js";
6
+ import type { Middleware } from "../middleware/index.js";
7
+ import { Route } from "../route/index.js";
8
+ import { Codec, Header, Time, noStore } from "../util/index.js";
9
+ import type { Auth } from "./index.js";
10
+ import { Issue } from "./issue.js";
11
+ import { Metadata } from "./metadata.js";
12
+ import { Passkey } from "./passkey.js";
13
+ import type { State } from "./state.js";
14
+ import { Storage } from "./storage.js";
15
+ import { Token } from "./token.js";
16
+
17
+ /** Authorization request waiting for the user's approval */
18
+ type Pending = {
19
+ readonly client: string;
20
+ readonly name: string;
21
+ readonly redirect: string;
22
+ /** The request named `redirect`, so the code exchange must name it too */
23
+ readonly named: boolean;
24
+ readonly challenge: string;
25
+ readonly resource: string;
26
+ readonly state: string | null;
27
+ readonly user: string;
28
+ readonly expiration: number;
29
+ };
30
+
31
+ /** Agent from its client ID metadata document */
32
+ type Client = {
33
+ readonly id: string;
34
+ readonly name: string;
35
+ readonly redirects: readonly string[];
36
+ };
37
+
38
+ /** OAuth endpoint paths */
39
+ const paths = {
40
+ metadata: "/.well-known/oauth-authorization-server",
41
+ authorize: "/oauth/authorize",
42
+ approve: "/oauth/approve",
43
+ deny: "/oauth/deny",
44
+ prompt: "/_passkey/options/approve",
45
+ token: "/oauth/token",
46
+ } as const;
47
+
48
+ /** Lifetimes */
49
+ const lifetime = {
50
+ consent: 10 * Time.minute,
51
+ code: Time.minute,
52
+ access: Time.hour,
53
+ refresh: 30 * Time.day,
54
+ };
55
+
56
+ /** Largest request body */
57
+ const limit = 16 * 1024;
58
+
59
+ /** Client ID metadata document downloads */
60
+ const downloads = {
61
+ /** Downloads at once, per instance */
62
+ concurrent: 16,
63
+ /** Downloads at once for one client IP, per instance */
64
+ each: 2,
65
+ /** How long a client ID without a document is remembered */
66
+ missing: Time.minute,
67
+ /** Agents kept after they are found, per instance */
68
+ cached: 1000,
69
+ /** How long a found agent is kept */
70
+ lifetime: 5 * Time.minute,
71
+ /**
72
+ * How long a found agent's document is used when a new download is
73
+ * refused or fails for now, short since its redirects could have changed
74
+ */
75
+ stale: Time.hour,
76
+ };
77
+
78
+ /**
79
+ * OAuth 2.1 authorization server for agents. The user signs in with a passkey
80
+ * and approves the agent on the app's consent page; the agent receives tokens.
81
+ *
82
+ * @param options Auth options
83
+ * @param storage Auth storage
84
+ * @param state Request state
85
+ * @returns Endpoints, the consent form, and bearer token verification
86
+ */
87
+ export function oauth(
88
+ options: Auth.Options<any>,
89
+ storage: Storage,
90
+ state: (c: State.Context) => State,
91
+ resources: ReadonlySet<string>,
92
+ ) {
93
+ const { origin } = options;
94
+ const page = options.page ?? "/login";
95
+ const consent = options.consent ?? "/connect";
96
+
97
+ /**
98
+ * @param name Name of the limit, for this origin
99
+ * @param limit Requests a minute
100
+ * @param key What the limit counts, the client IP by default
101
+ * @returns The limit, shared by every instance through the database
102
+ */
103
+ const minute = (
104
+ name: string,
105
+ limit: number,
106
+ key?: Pick<Limiter.Options, "key">,
107
+ ) =>
108
+ new Limiter(`auth:${name}:${origin}`, {
109
+ limit,
110
+ interval: Time.minute,
111
+ database: options.database,
112
+ ...key,
113
+ });
114
+
115
+ const limiter = minute("tokens", 60);
116
+
117
+ /** Authorization requests, by IP, each can download a document */
118
+ const authorizations = minute("authorize", 30);
119
+
120
+ /**
121
+ * Downloads from each document host by each client IP, so one client
122
+ * cannot spend a host's downloads for everyone
123
+ */
124
+ const hosts = minute("metadata", 10);
125
+
126
+ /** Downloads from each document host in all, so the server cannot flood one */
127
+ const ceiling = minute("metadata-hosts", 300, { key: () => "hosts" });
128
+
129
+ /** Agents found recently, by client ID */
130
+ const found = new Map<
131
+ string,
132
+ { client: Client; expiration: number; stale: number }
133
+ >();
134
+
135
+ /** Client IDs without a valid document, until when, by client ID */
136
+ const missing = new Map<string, number>();
137
+
138
+ /**
139
+ * @param map Agents found, or client IDs without a document
140
+ * @param id Client ID
141
+ * @param value What is known about it
142
+ */
143
+ const remember = <T>(map: Map<string, T>, id: string, value: T) => {
144
+ // the oldest is forgotten first
145
+ if (map.size >= downloads.cached) map.delete(map.keys().next().value!);
146
+ map.set(id, value);
147
+ };
148
+
149
+ /** Downloads in progress, by client ID */
150
+ const pending = new Map<string, Promise<Client | null | undefined>>();
151
+
152
+ /** Downloads in progress, by client IP, so one cannot take every slot */
153
+ const active = new Map<string, number>();
154
+
155
+ /**
156
+ * Finds an agent, downloading its document at most once at a time.
157
+ *
158
+ * @param c Request context
159
+ * @param id Client ID
160
+ * @returns The agent, `undefined` if it is unknown, or `null` if downloads are limited or failing for now
161
+ */
162
+ const agent = async (c: Context, id: string | null) => {
163
+ const url = id ? identify(id) : undefined;
164
+ if (!id || !url) return;
165
+
166
+ const now = Date.now();
167
+ let known = found.get(id);
168
+ if (known && known.expiration > now) return known.client;
169
+ if (known && known.stale <= now) {
170
+ found.delete(id);
171
+ known = undefined;
172
+ }
173
+ if ((missing.get(id) ?? 0) > now) return;
174
+ missing.delete(id);
175
+
176
+ // a download refused or failing for now serves an agent found before
177
+ // from its last document, so floods of other client IDs or a passing
178
+ // outage cannot lock it out
179
+ const refused = () => known?.client ?? null;
180
+
181
+ let download = pending.get(id);
182
+ if (!download) {
183
+ // a client's network, so rotating IPv6 addresses do not add slots
184
+ const ip = network(c.ip) ?? "";
185
+ const slots = () =>
186
+ pending.size < downloads.concurrent &&
187
+ (active.get(ip) ?? 0) < downloads.each;
188
+ if (!slots()) return refused();
189
+
190
+ // each request's own share, before it starts a download others may
191
+ // join, so one client's refusal is never another's
192
+ if ((await hosts.check(c, url.host)) !== true) return refused();
193
+
194
+ download = pending.get(id);
195
+ if (!download) {
196
+ if (!slots()) return refused();
197
+ active.set(ip, (active.get(ip) ?? 0) + 1);
198
+
199
+ download = (async () => {
200
+ if ((await ceiling.check(c, url.host)) !== true) return null;
201
+
202
+ const client = await find(id, url);
203
+ // a failure that may pass keeps what is known, and is not remembered
204
+ if (client === null) return null;
205
+
206
+ // a found agent is added again as the newest, or forgotten
207
+ found.delete(id);
208
+ const now = Date.now();
209
+ if (client)
210
+ remember(found, id, {
211
+ client,
212
+ expiration: now + downloads.lifetime,
213
+ stale: now + downloads.stale,
214
+ });
215
+ else remember(missing, id, now + downloads.missing);
216
+ return client;
217
+ })().finally(() => {
218
+ pending.delete(id);
219
+ const left = (active.get(ip) ?? 1) - 1;
220
+ if (left) active.set(ip, left);
221
+ else active.delete(ip);
222
+ });
223
+
224
+ pending.set(id, download);
225
+ }
226
+ }
227
+
228
+ const client = await download;
229
+ return client === null ? refused() : client;
230
+ };
231
+
232
+ /** Public endpoints that browser-based agents call from their own origin */
233
+ const cors: Middleware = async (c, next) => {
234
+ noStore(c.res.headers);
235
+ c.res.headers.set("access-control-allow-origin", "*");
236
+ c.res.headers.set(
237
+ "access-control-allow-headers",
238
+ "authorization, content-type, mcp-protocol-version",
239
+ );
240
+ c.res.headers.set("access-control-allow-methods", "GET, POST, OPTIONS");
241
+ if (c.req.method === "OPTIONS") {
242
+ c.res.status = 204;
243
+ return;
244
+ }
245
+ return next();
246
+ };
247
+
248
+ /**
249
+ * @param c Request context
250
+ * @param scope Part of the flow the request is for
251
+ * @returns `true` when the limit of authorization requests admits it, otherwise answers it
252
+ */
253
+ const authorizing = async (
254
+ c: Limiter.Context & Pick<Context, "text">,
255
+ scope?: string,
256
+ ) => {
257
+ if ((await authorizations.check(c, scope)) === true) return true;
258
+ c.text("Too many requests. Try again later.", 429);
259
+ return false;
260
+ };
261
+
262
+ const admit = async (c: Context, limiter: Limiter) => {
263
+ // an unavailable limiter throws to the app, it never skips the limit
264
+ if ((await limiter.check(c)) === true) return true;
265
+ c.json({ error: "temporarily_unavailable" }, 429);
266
+ return false;
267
+ };
268
+
269
+ const fail = (
270
+ c: Context,
271
+ error: string,
272
+ description?: string,
273
+ status = 400,
274
+ ) =>
275
+ c.json(
276
+ { error, ...(description ? { error_description: description } : {}) },
277
+ status,
278
+ );
279
+
280
+ /** @returns Body parameters, bounded in size */
281
+ const body = async (c: Context) => {
282
+ const bytes = await Codec.read(c.req.body, limit);
283
+ if (!bytes) return;
284
+ try {
285
+ return Codec.decode(bytes);
286
+ } catch {
287
+ return;
288
+ }
289
+ };
290
+
291
+ const routes: Route[] = [];
292
+
293
+ /**
294
+ * The endpoints an agent signs in through are, like the MCP endpoint, the
295
+ * way in and not pages of the app: they run without the app's global
296
+ * middleware, so a check for a session there cannot turn an agent away
297
+ * before it has signed in. Auth's own check of the host is global
298
+ * middleware too, so these routes make it themselves, first.
299
+ */
300
+ const host: Middleware = (c, next) => {
301
+ if (c.url.origin === origin) return next();
302
+ noStore(c.res.headers);
303
+ return c.text("Misdirected Request", 421);
304
+ };
305
+
306
+ /**
307
+ * @param route Endpoint an agent or its user's browser requests to sign in
308
+ * @returns The route, outside the app's global middleware
309
+ */
310
+ const outside = (route: Route) => {
311
+ direct.add(route);
312
+ routes.push(route);
313
+ return route;
314
+ };
315
+
316
+ const cross = (route: Route) => {
317
+ // browsers send the preflight cross-site too, without credentials
318
+ const preflight = new Route("OPTIONS", route.pattern).use(host, cors);
319
+ crossOrigin.add(route).add(preflight);
320
+ outside(route);
321
+ outside(preflight);
322
+ return route;
323
+ };
324
+
325
+ /** Accepts only requests from the app's own pages, the consent form's */
326
+ const same = (
327
+ c: Pick<Context, "req" | "res" | "text">,
328
+ next: Middleware.Next,
329
+ ) => {
330
+ noStore(c.res.headers);
331
+ if (
332
+ c.req.headers.get(Header.name.fetch) === "same-origin" ||
333
+ c.req.headers.get(Header.name.origin) === origin
334
+ )
335
+ return next();
336
+ return c.text("Forbidden", 403);
337
+ };
338
+
339
+ /** @returns `true` for a passkey or form that could not be verified */
340
+ const unverified = (error: unknown) =>
341
+ error instanceof Issue ||
342
+ (typeof error === "object" && error !== null && "issues" in error);
343
+
344
+ /**
345
+ * @param c Request context
346
+ * @param request Sealed authorization request
347
+ * @returns The request, `null` when another user decides, or `undefined` when it is invalid or expired
348
+ */
349
+ const read = async (c: State.Context, request: string | null) => {
350
+ if (!request) return;
351
+ let pending: Pending;
352
+ try {
353
+ pending = JSON.parse(
354
+ await Token.open(options.secret, "consent", request),
355
+ ) as Pending;
356
+ } catch (error) {
357
+ if (!(error instanceof Issue) && !(error instanceof SyntaxError))
358
+ throw error;
359
+ return;
360
+ }
361
+ if (pending.expiration <= Date.now()) return;
362
+
363
+ const session = await state(c).session();
364
+ return session?.user === pending.user ? pending : null;
365
+ };
366
+
367
+ /**
368
+ * @param c Request context
369
+ * @param request Sealed authorization request
370
+ * @returns The request, or `undefined` after responding when it expired or another user decides
371
+ */
372
+ const asked = async (
373
+ c: State.Context & Pick<Context, "text">,
374
+ request: string | null,
375
+ ) => {
376
+ const pending = await read(c, request);
377
+ if (pending === undefined)
378
+ return void c.text("The request expired. Try connecting again.", 400);
379
+ if (!pending) return void c.text("Forbidden", 403);
380
+
381
+ return pending;
382
+ };
383
+
384
+ /**
385
+ * @param c Request context
386
+ * @param pending The request
387
+ * @param params Code or error for the agent
388
+ */
389
+ const back = (
390
+ c: Pick<Context, "redirect">,
391
+ pending: Pending,
392
+ params: Record<string, string>,
393
+ ) => {
394
+ const url = new URL(pending.redirect);
395
+ for (const [name, value] of Object.entries(params))
396
+ url.searchParams.set(name, value);
397
+ if (pending.state !== null) url.searchParams.set("state", pending.state);
398
+ url.searchParams.set("iss", origin);
399
+ return c.redirect(url, 303);
400
+ };
401
+
402
+ /** Starts the passkey prompt for allowing an agent */
403
+ const prompt = Route.post(paths.prompt)
404
+ // the consent form's fields, the request is the one the passkey confirms
405
+ .fields({ request: Field.hidden(), bootstrap: Field.hidden() })
406
+ .use(same, async (c) => {
407
+ if (!(await authorizing(c, "approve"))) return;
408
+
409
+ const failed = () => c.text("Authentication failed. Try again.", 400);
410
+ const input = await Issue.data(c);
411
+ if (!input || input.issues) return failed();
412
+
413
+ const pending = await asked(c, input.data.request);
414
+ if (!pending) return;
415
+
416
+ try {
417
+ await Passkey.issue(c, state(c), input.data.bootstrap, {
418
+ method: "login",
419
+ action: paths.approve,
420
+ fields: await Passkey.fields({ request: input.data.request }),
421
+ // only the asked user's passkeys can allow it
422
+ allow: await storage.credentials.list(pending.user),
423
+ });
424
+ } catch (error) {
425
+ if (!unverified(error)) throw error;
426
+ return failed();
427
+ }
428
+ });
429
+
430
+ /**
431
+ * Allows the agent. The user confirms with their passkey, so a script or
432
+ * agent driving a signed-in browser cannot allow it for them.
433
+ */
434
+ const approve = Route.post(paths.approve)
435
+ .fields({ request: Field.hidden(), ...Passkey.shape })
436
+ .use(same, async (c) => {
437
+ const failed = () =>
438
+ c.text("Your passkey could not be verified. Try again.", 400);
439
+ const result = await Issue.data(c);
440
+ if (!result || result.issues) return failed();
441
+
442
+ const pending = await asked(c, result.data.request);
443
+ if (!pending) return;
444
+
445
+ let credential;
446
+ try {
447
+ // a passkey confirms the request it was asked for, not another
448
+ credential = await new Passkey(c, state(c)).login(
449
+ storage.credentials,
450
+ await Passkey.fields({ request: result.data.request }),
451
+ // the prompt offered only this user's passkeys
452
+ pending.user,
453
+ );
454
+ } catch (error) {
455
+ if (!unverified(error)) throw error;
456
+ return failed();
457
+ }
458
+ // the passkey of the user who was asked
459
+ if (credential.user !== pending.user) return c.text("Forbidden", 403);
460
+
461
+ const code = Token.random();
462
+ await storage.tokens.set(code, {
463
+ kind: "code",
464
+ user: pending.user,
465
+ client: pending.client,
466
+ resource: pending.resource,
467
+ scope: "",
468
+ // compared at the exchange only when the request named it (OAuth 2.1)
469
+ ...(pending.named && { redirect: pending.redirect }),
470
+ challenge: pending.challenge,
471
+ expiration: Date.now() + lifetime.code,
472
+ });
473
+
474
+ return back(c, pending, { code });
475
+ });
476
+
477
+ /** Denies the agent, which needs no passkey */
478
+ const deny = Route.post(paths.deny)
479
+ // the consent form's fields, the passkey inputs are empty
480
+ .fields({
481
+ request: Field.hidden(),
482
+ credential: Field.hidden().optional(),
483
+ ceremony: Field.hidden().optional(),
484
+ })
485
+ .use(same, async (c) => {
486
+ const result = await Issue.data(c);
487
+ const pending = await asked(
488
+ c,
489
+ !result || result.issues ? null : result.data.request,
490
+ );
491
+ if (!pending) return;
492
+
493
+ return back(c, pending, { error: "access_denied" });
494
+ });
495
+
496
+ // authorization server metadata, RFC 8414
497
+ cross(
498
+ Route.get(paths.metadata).use(host, cors, (c) =>
499
+ c.json({
500
+ issuer: origin,
501
+ authorization_endpoint: origin + paths.authorize,
502
+ token_endpoint: origin + paths.token,
503
+ response_types_supported: ["code"],
504
+ grant_types_supported: ["authorization_code", "refresh_token"],
505
+ code_challenge_methods_supported: ["S256"],
506
+ token_endpoint_auth_methods_supported: ["none"],
507
+ client_id_metadata_document_supported: true,
508
+ authorization_response_iss_parameter_supported: true,
509
+ }),
510
+ ),
511
+ );
512
+
513
+ // the user's browser, which may be signed out: this remembers the request,
514
+ // sends them to sign in, and resumes
515
+ outside(
516
+ Route.get(paths.authorize).use(host, async (c) => {
517
+ noStore(c.res.headers);
518
+ const query = c.url.searchParams;
519
+
520
+ if (!(await authorizing(c))) return;
521
+
522
+ const client = await agent(c, query.get("client_id"));
523
+ if (client === null)
524
+ return c.text("Could not load the agent. Try again later.", 503);
525
+ if (!client) return c.text("Unknown client.", 400);
526
+
527
+ const redirect = match(client.redirects, query.get("redirect_uri"));
528
+ if (!redirect) return c.text("Invalid redirect URI.", 400);
529
+
530
+ // answered here, not redirected: any client can publish a document
531
+ // with any callback, which would make this origin an open redirector
532
+ const error = (code: string, description: string) =>
533
+ c.text(`${description} (${code})`, 400);
534
+
535
+ if (query.get("response_type") !== "code")
536
+ return error("unsupported_response_type", "Use the code flow.");
537
+
538
+ const challenge = query.get("code_challenge");
539
+ if (
540
+ query.get("code_challenge_method") !== "S256" ||
541
+ !challenge ||
542
+ !/^[\w-]{43}$/.test(challenge)
543
+ )
544
+ return error("invalid_request", "PKCE with S256 is required.");
545
+
546
+ // tokens are bound to the resource the agent will use them with
547
+ const resource = query.get("resource");
548
+ if (!resource) return error("invalid_target", "Resource is required.");
549
+ let target: URL;
550
+ try {
551
+ target = new URL(resource);
552
+ } catch {
553
+ return error("invalid_target", "Invalid resource.");
554
+ }
555
+ // exactly an endpoint that accepts these tokens, such as an MCP endpoint
556
+ if (!resources.has(target.href) || target.href !== resource)
557
+ return error("invalid_target", "Unknown resource.");
558
+
559
+ // a token grants everything the user can do, there are no narrower scopes
560
+ if (query.get("scope"))
561
+ return error("invalid_scope", "Scopes are not supported.");
562
+
563
+ const session = await state(c).session();
564
+ if (!session) {
565
+ // come back here after logging in
566
+ state(c).remember(c.url.pathname + c.url.search);
567
+ return c.redirect(page, 303);
568
+ }
569
+
570
+ const url = new URL(consent, origin);
571
+ url.searchParams.set(
572
+ "request",
573
+ await Token.seal(
574
+ options.secret,
575
+ "consent",
576
+ JSON.stringify({
577
+ client: client.id,
578
+ name: client.name,
579
+ redirect,
580
+ named: query.has("redirect_uri"),
581
+ challenge,
582
+ resource,
583
+ state: query.get("state"),
584
+ user: session.user,
585
+ expiration: Date.now() + lifetime.consent,
586
+ } satisfies Pending),
587
+ ),
588
+ );
589
+
590
+ return c.redirect(url, 303);
591
+ }),
592
+ );
593
+
594
+ // the signed-in user's own form posts, which stay the app's requests
595
+ routes.push(prompt, approve, deny);
596
+
597
+ cross(
598
+ Route.post(paths.token).use(host, cors, async (c) => {
599
+ if (!(await admit(c, limiter))) return;
600
+
601
+ const text = await body(c);
602
+ if (text === undefined) return fail(c, "invalid_request");
603
+ const params = new URLSearchParams(text);
604
+
605
+ // agents are public clients, one that authenticates expects a check
606
+ // that is not made
607
+ const scheme = c.req.headers.get("authorization")?.split(" ")[0];
608
+ if (
609
+ scheme ||
610
+ ["client_secret", "client_assertion", "client_assertion_type"].some(
611
+ (name) => params.has(name),
612
+ )
613
+ ) {
614
+ if (scheme) c.res.headers.set("www-authenticate", scheme);
615
+ return fail(
616
+ c,
617
+ "invalid_client",
618
+ "Client authentication is not supported",
619
+ scheme ? 401 : 400,
620
+ );
621
+ }
622
+
623
+ const grant = params.get("grant_type");
624
+ const client = params.get("client_id");
625
+ const resource = params.get("resource");
626
+
627
+ const code = grant === "authorization_code";
628
+ if (!code && grant !== "refresh_token")
629
+ return fail(c, "unsupported_grant_type");
630
+
631
+ const access = Token.random();
632
+ const refresh = Token.random();
633
+ let error = "invalid_grant";
634
+ /** How long the access token lasts, shorter near the grant's end */
635
+ let expires = lifetime.access;
636
+
637
+ // codes and refresh tokens are used once, refresh tokens rotate
638
+ const issued = await storage.tokens.exchange(
639
+ params.get(code ? "code" : "refresh_token") ?? "",
640
+ code ? "code" : "refresh",
641
+ async (token) => {
642
+ if (token.client !== client) return;
643
+ if (code) {
644
+ const verifier = params.get("code_verifier") ?? "";
645
+ if (
646
+ (token.redirect !== undefined &&
647
+ token.redirect !== params.get("redirect_uri")) ||
648
+ !/^[\w.~-]{43,128}$/.test(verifier) ||
649
+ // base64url SHA-256, as PKCE S256 uses
650
+ (await Storage.hash(verifier)) !== token.challenge
651
+ )
652
+ return;
653
+ }
654
+ if (resource !== token.resource) {
655
+ error = "invalid_target";
656
+ return;
657
+ }
658
+
659
+ const now = Date.now();
660
+ // a grant lasts from its approval, refreshing replaces its tokens but
661
+ // never extends it, then the user connects the agent again
662
+ const end = code ? now + lifetime.refresh : token.expiration;
663
+ expires = Math.min(lifetime.access, end - now);
664
+ const row = {
665
+ user: token.user,
666
+ client: token.client,
667
+ resource: token.resource,
668
+ scope: token.scope,
669
+ };
670
+
671
+ return {
672
+ [access]: { ...row, kind: "access", expiration: now + expires },
673
+ [refresh]: { ...row, kind: "refresh", expiration: end },
674
+ };
675
+ },
676
+ );
677
+ if (!issued) return fail(c, error);
678
+
679
+ c.json({
680
+ access_token: access,
681
+ token_type: "Bearer",
682
+ expires_in: Math.floor(expires / Time.second),
683
+ refresh_token: refresh,
684
+ });
685
+ }),
686
+ );
687
+
688
+ return {
689
+ routes,
690
+
691
+ /**
692
+ * @param c Request context
693
+ * @returns The authorization request on the consent page, with its form
694
+ */
695
+ async consent(c: Auth.Context): Promise<Auth.Consent | null> {
696
+ // the page grants access, so other sites cannot frame it to trick a click
697
+ c.res.headers.set("x-frame-options", "DENY");
698
+ c.res.headers.append("content-security-policy", "frame-ancestors 'none'");
699
+
700
+ const request = c.url.searchParams.get("request");
701
+ const pending = await read(c, request);
702
+ if (!pending) return null;
703
+ // the page's passkey prompt is for this request only
704
+ const Form = new Passkey(c, state(c)).form(approve, "login", {
705
+ endpoint: prompt.url(),
706
+ fields: await Passkey.fields({ request }),
707
+ });
708
+
709
+ return {
710
+ client: { id: pending.client, name: pending.name },
711
+ redirect: new URL(pending.redirect).host || pending.redirect,
712
+ Form: (props) =>
713
+ Form({
714
+ ...props,
715
+ children: [
716
+ jsx("input", {
717
+ type: "hidden",
718
+ name: "request",
719
+ value: request!,
720
+ }),
721
+ props.children ?? [
722
+ jsx("button", { children: "Allow" }),
723
+ jsx("button", { formaction: deny.url(), children: "Deny" }),
724
+ ],
725
+ ],
726
+ }),
727
+ };
728
+ },
729
+
730
+ /**
731
+ * @param c Request context
732
+ * @param resource Resource the token must be issued for
733
+ * @returns Session for the user the token acts for
734
+ */
735
+ async bearer(
736
+ c: Pick<Context, "req">,
737
+ resource: string,
738
+ ): Promise<Auth.Session | null> {
739
+ const token = /^Bearer\s+([\w.~+/-]+=*)$/i.exec(
740
+ c.req.headers.get("authorization") ?? "",
741
+ )?.[1];
742
+ if (!token) return null;
743
+
744
+ const row = await storage.tokens.get(token);
745
+ if (!row || row.resource !== resource) return null;
746
+
747
+ return {
748
+ id: await Storage.hash(token),
749
+ user: row.user,
750
+ expiration: row.expiration,
751
+ };
752
+ },
753
+ };
754
+ }
755
+
756
+ /**
757
+ * @param uri Redirect URI an agent registers
758
+ * @returns `true` if it is HTTPS, a loopback address, or an app's own scheme
759
+ */
760
+ function redirectable(uri: unknown) {
761
+ if (typeof uri !== "string" || uri.length > 2000) return false;
762
+ try {
763
+ const url = new URL(uri);
764
+ if (!plain(url)) return false;
765
+ if (url.protocol === "https:") return true;
766
+ if (url.protocol === "http:") return loopback(url.hostname);
767
+ return ![
768
+ "javascript:",
769
+ "data:",
770
+ "file:",
771
+ "blob:",
772
+ "vbscript:",
773
+ "about:",
774
+ ].includes(url.protocol);
775
+ } catch {
776
+ return false;
777
+ }
778
+ }
779
+
780
+ /** @returns `true` for a URL without a fragment or credentials */
781
+ function plain(url: URL) {
782
+ return !url.hash && !url.username && !url.password;
783
+ }
784
+
785
+ /** @returns `true` for loopback hosts */
786
+ function loopback(host: string) {
787
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]";
788
+ }
789
+
790
+ /**
791
+ * @param redirects Registered redirect URIs
792
+ * @param uri Requested redirect URI
793
+ * @returns The redirect URI to use, any port is allowed for loopback addresses
794
+ */
795
+ function match(redirects: readonly string[], uri: string | null) {
796
+ if (uri === null) return redirects.length === 1 ? redirects[0] : undefined;
797
+ if (redirects.includes(uri)) return uri;
798
+
799
+ try {
800
+ const url = new URL(uri);
801
+ if (url.protocol !== "http:" || !loopback(url.hostname)) return;
802
+ for (const redirect of redirects) {
803
+ const registered = new URL(redirect);
804
+ registered.port = url.port;
805
+ if (registered.href === url.href) return uri;
806
+ }
807
+ } catch {
808
+ return;
809
+ }
810
+ }
811
+
812
+ /**
813
+ * @param id Client ID
814
+ * @returns The URL of the agent's client ID metadata document
815
+ */
816
+ function identify(id: string) {
817
+ if (!id.startsWith("https://")) return;
818
+
819
+ let url: URL;
820
+ try {
821
+ url = new URL(id);
822
+ } catch {
823
+ return;
824
+ }
825
+ if (url.pathname === "/" || !plain(url)) return;
826
+ // exactly as written, so the ID shown reads as the origin it is, unlike
827
+ // `https://evil.example\@good.example/`, which a URL parses as evil.example
828
+ if (url.href !== id) return;
829
+
830
+ return url;
831
+ }
832
+
833
+ /**
834
+ * Fetches a client ID metadata document, the agent's ID is its URL.
835
+ *
836
+ * @param id Client ID
837
+ * @param url Client ID, parsed
838
+ * @returns The client, `undefined` if it has no valid document, or `null`
839
+ * if the download failed for now
840
+ */
841
+ async function find(id: string, url: URL): Promise<Client | null | undefined> {
842
+ const metadata = (await Metadata.fetch(url)) as Record<
843
+ string,
844
+ unknown
845
+ > | null;
846
+ if (metadata === null) return null;
847
+ const redirects = metadata?.redirect_uris;
848
+ if (
849
+ metadata?.client_id !== id ||
850
+ !Array.isArray(redirects) ||
851
+ !redirects.length ||
852
+ !redirects.every(redirectable)
853
+ )
854
+ return;
855
+
856
+ // agents are public clients here: one that declares only other ways to
857
+ // authenticate, or other grants, is not treated as one that asked for less
858
+ const methods = [
859
+ metadata.token_endpoint_auth_method,
860
+ metadata.token_endpoint_auth_methods_supported,
861
+ ]
862
+ .flat()
863
+ .filter((method) => method !== undefined);
864
+ const offers = (declared: unknown, ours: string) =>
865
+ declared === undefined ||
866
+ (Array.isArray(declared) && declared.includes(ours));
867
+ if (
868
+ (methods.length && !methods.includes("none")) ||
869
+ !offers(metadata.grant_types, "authorization_code") ||
870
+ !offers(metadata.response_types, "code")
871
+ )
872
+ return;
873
+
874
+ return {
875
+ id,
876
+ name:
877
+ typeof metadata.client_name === "string" && metadata.client_name.trim()
878
+ ? metadata.client_name.trim().slice(0, 100)
879
+ : url.host,
880
+ redirects,
881
+ };
882
+ }