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