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
@@ -1,23 +1,22 @@
1
1
  /** Media type utils */
2
2
  export class Mime {
3
- /** Mime type constants */
3
+ /**
4
+ * Mime type constants. Written out, since a static computed by calling
5
+ * other members is a side effect, which keeps the class in every bundle
6
+ * that imports this module.
7
+ */
4
8
  static type = {
5
- html: Mime.#text("html"),
6
- text: Mime.#text("plain"),
7
- json: Mime.#application("json"),
8
- stream: Mime.#application("octet-stream"),
9
+ html: "text/html",
10
+ md: "text/markdown",
11
+ text: "text/plain",
12
+ json: "application/json",
13
+ stream: "application/octet-stream",
9
14
  mp: "multipart/form-data",
10
15
  };
11
- static #text(type) {
12
- return `text/${type}`;
13
- }
14
- static #application(type) {
15
- return `application/${type}`;
16
- }
17
16
  static #markup = new Set([
18
- Mime.type.html,
19
- Mime.#text("xml"),
20
- Mime.#application("xml"),
17
+ "text/html",
18
+ "text/xml",
19
+ "application/xml",
21
20
  ]);
22
21
  /**
23
22
  * @param mime Media type
@@ -50,30 +49,70 @@ export class Header {
50
49
  loc: "location",
51
50
  origin: "origin",
52
51
  fetch: "sec-fetch-site",
52
+ accept: "accept",
53
+ vary: "vary",
53
54
  };
54
55
  /**
55
- * @param mime
56
- * @returns mime; charset=utf-8
56
+ * @template M Media type
57
+ * @param mime Media type
58
+ * @returns The media type with `; charset=utf-8`
57
59
  */
58
60
  static utf8(mime) {
59
61
  return `${mime}; charset=utf-8`;
60
62
  }
61
63
  /**
62
64
  * @param header header value to parse
63
- * @returns Base/first param
65
+ * @returns Base, trimmed and lowercase since media types ignore case, and its params
64
66
  */
65
67
  static shift(header) {
66
- const semi = header?.indexOf(";") ?? -1;
68
+ if (header === null)
69
+ return [null, null];
70
+ const semi = header.indexOf(";");
67
71
  return semi === -1
68
- ? [header, null]
69
- : [header.slice(0, semi), header.slice(semi)];
72
+ ? [header.trim().toLowerCase(), null]
73
+ : [header.slice(0, semi).trim().toLowerCase(), header.slice(semi)];
74
+ }
75
+ /**
76
+ * @param accept `Accept` header
77
+ * @param mime Media type to look for
78
+ * @param exact Ignore wildcard ranges
79
+ * @returns The quality the header gives the type, by its most specific match
80
+ */
81
+ static quality(accept, mime, exact) {
82
+ if (!accept)
83
+ return 0;
84
+ const [type] = mime.split("/");
85
+ let best = -1;
86
+ let q = 0;
87
+ for (const range of accept.split(",")) {
88
+ // trimmed and lowercase by `shift`
89
+ const [match, params] = Header.shift(range);
90
+ const score = match === mime
91
+ ? 2
92
+ : exact
93
+ ? -1
94
+ : match === `${type}/*`
95
+ ? 1
96
+ : match === "*/*"
97
+ ? 0
98
+ : -1;
99
+ if (score > best) {
100
+ best = score;
101
+ const quality = Number(Header.params(params?.slice(1) ?? "", true).q ?? 1);
102
+ q = Number.isNaN(quality) ? 0 : quality;
103
+ }
104
+ }
105
+ return q;
70
106
  }
71
107
  /**
72
108
  * @param header header value to parse
109
+ * @param insensitive Lowercase each key, a parameter's name is
110
+ * case-insensitive, a cookie's is not
73
111
  * @returns Map containing each key=value pair
74
112
  */
75
- static params(header) {
76
- const parsed = {};
113
+ static params(header, insensitive) {
114
+ // without a prototype, so a key such as "__proto__" is only a key
115
+ const parsed = Object.create(null);
77
116
  if (header) {
78
117
  const headerLength = header.length;
79
118
  for (let cursor = 0; cursor < headerLength;) {
@@ -89,15 +128,35 @@ export class Header {
89
128
  cursor = header.lastIndexOf(";", equal - 1) + 1;
90
129
  continue;
91
130
  }
92
- const key = header.slice(cursor, equal).trim();
131
+ let key = header.slice(cursor, equal).trim();
132
+ if (insensitive)
133
+ key = key.toLowerCase();
134
+ let value;
135
+ let quoted = false;
136
+ // a quoted value ends at its closing quote, it can contain ";"
137
+ let start = equal + 1;
138
+ while (header[start] === " " || header[start] === "\t")
139
+ start++;
140
+ if (header[start] === '"') {
141
+ quoted = true;
142
+ value = "";
143
+ let i = start + 1;
144
+ for (; i < headerLength && header[i] !== '"'; i++)
145
+ value += header[i] === "\\" ? (header[++i] ?? "") : header[i];
146
+ semi = header.indexOf(";", i);
147
+ if (semi === -1)
148
+ semi = headerLength;
149
+ }
150
+ else
151
+ value = header.slice(start, semi).trim();
152
+ // first value should take precedence
93
153
  if (!(key in parsed)) {
94
- // first value should take precedence
95
- let value = header.slice(equal + 1, semi).trim();
96
- if (value[0] === '"' && value[value.length - 1] === '"') {
97
- // remove quotes
98
- value = value.slice(1, -1);
154
+ if (quoted) {
155
+ // browsers escape only these in a quoted multipart filename,
156
+ // so other "%" are the name's own, like "100%41.txt"
157
+ value = value.replace(/%(22|0D|0A)/gi, (escape) => decodeURIComponent(escape));
99
158
  }
100
- if (value.includes("%")) {
159
+ else if (value.includes("%")) {
101
160
  // most values don't need to be decoded
102
161
  try {
103
162
  // cookies must be a simple string
@@ -115,6 +174,13 @@ export class Header {
115
174
  return parsed;
116
175
  }
117
176
  }
177
+ /**
178
+ * Keeps a response out of shared and browser caches, for one that is
179
+ * personal or used once.
180
+ *
181
+ * @param headers Response headers
182
+ */
183
+ export const noStore = (headers) => headers.set("cache-control", "no-store");
118
184
  /** Checksum util */
119
185
  export class Checksum {
120
186
  /**
@@ -155,6 +221,56 @@ export class Codec {
155
221
  static decode(bytes) {
156
222
  return Codec.#decoder.decode(bytes);
157
223
  }
224
+ /**
225
+ * Reads a body, cancelling it as soon as it exceeds the limit.
226
+ *
227
+ * @param body Body to read
228
+ * @param limit Largest size in bytes
229
+ * @returns The bytes, or `undefined` when the body is too large
230
+ */
231
+ static async read(body, limit) {
232
+ if (!body)
233
+ return new Uint8Array();
234
+ const reader = body.getReader();
235
+ /** The first chunk, the whole body when it is the only one, as most are */
236
+ let first;
237
+ /**
238
+ * A body of more chunks is copied in as they arrive, into memory that
239
+ * grows with what was sent and never past the limit, so it is not held
240
+ * twice at the end, as its chunks and as the bytes they are joined into
241
+ */
242
+ let buffer;
243
+ let size = 0;
244
+ for (;;) {
245
+ const { done, value } = await reader.read();
246
+ if (done)
247
+ break;
248
+ const end = size + value.length;
249
+ if (end > limit) {
250
+ await reader.cancel();
251
+ return;
252
+ }
253
+ if (!first)
254
+ first = value;
255
+ else {
256
+ // reserved once a second chunk arrives: it costs more than a small
257
+ // body takes to read, and a body of one chunk needs none
258
+ if (!buffer) {
259
+ buffer = new ArrayBuffer(0, { maxByteLength: limit });
260
+ buffer.resize(Math.min(limit, Math.max(end, size * 2)));
261
+ new Uint8Array(buffer).set(first);
262
+ }
263
+ else if (end > buffer.byteLength)
264
+ buffer.resize(Math.min(limit, Math.max(end, buffer.byteLength * 2)));
265
+ new Uint8Array(buffer, size).set(value);
266
+ }
267
+ size = end;
268
+ }
269
+ // a chunk read is the reader's own, so a body of one is not copied
270
+ return buffer
271
+ ? new Uint8Array(buffer, 0, size)
272
+ : (first ?? new Uint8Array());
273
+ }
158
274
  static Base64 = class Base64 {
159
275
  /**
160
276
  * Encodes bytes into a Base64 string.
@@ -163,7 +279,7 @@ export class Codec {
163
279
  * @returns Base64 string
164
280
  */
165
281
  static encode(bytes) {
166
- return btoa(String.fromCharCode(...bytes));
282
+ return bytes.toBase64();
167
283
  }
168
284
  /**
169
285
  * Decodes a Base64 string into bytes.
@@ -172,7 +288,7 @@ export class Codec {
172
288
  * @returns Decoded bytes
173
289
  */
174
290
  static decode(s) {
175
- return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
291
+ return Uint8Array.fromBase64(s);
176
292
  }
177
293
  };
178
294
  static Base64Url = class Base64Url {
@@ -183,9 +299,7 @@ export class Codec {
183
299
  * @returns Base64Url string
184
300
  */
185
301
  static encode(bytes) {
186
- return btoa(String.fromCharCode(...bytes))
187
- .replace(/[+/]/g, (c) => (c === "+" ? "-" : "_"))
188
- .replace(/=+$/, "");
302
+ return bytes.toBase64({ alphabet: "base64url", omitPadding: true });
189
303
  }
190
304
  /**
191
305
  * Decodes a Base64Url string into bytes.
@@ -194,8 +308,7 @@ export class Codec {
194
308
  * @returns Decoded bytes
195
309
  */
196
310
  static decode(s) {
197
- const b64 = s.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
198
- return Codec.Base64.decode(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
311
+ return Uint8Array.fromBase64(s, { alphabet: "base64url" });
199
312
  }
200
313
  };
201
314
  }
@@ -205,16 +318,18 @@ export class Method {
205
318
  static post = "POST";
206
319
  static head = "HEAD";
207
320
  }
321
+ // Each constant is written out: a static that reads another one is a side
322
+ // effect, which keeps the class in every bundle that imports this module.
208
323
  /** Byte size constants */
209
324
  export class Size {
210
325
  static kb = 1024;
211
- static mb = 1024 * Size.kb;
326
+ static mb = 1024 * 1024;
212
327
  }
213
328
  /** Times in milliseconds */
214
329
  export class Time {
215
330
  static second = 1000;
216
- static minute = 60 * Time.second;
217
- static hour = 60 * Time.minute;
218
- static day = 24 * Time.hour;
219
- static week = 7 * Time.day;
331
+ static minute = 60 * 1000;
332
+ static hour = 60 * 60 * 1000;
333
+ static day = 24 * 60 * 60 * 1000;
334
+ static week = 7 * 24 * 60 * 60 * 1000;
220
335
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ovr",
3
- "description": "The Streaming Framework",
4
- "version": "6.2.4",
3
+ "description": "Web apps anyone can use. Each route serves people a page and agents Markdown and MCP tools, with forms, Postgres, and passkey sign-in built in.",
4
+ "version": "7.0.0-next.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -39,10 +39,17 @@
39
39
  ],
40
40
  "scripts": {
41
41
  "check": "tsc",
42
- "dev": "tsc --watch -p tsconfig.build.json",
43
- "build": "tsc -p tsconfig.build.json && cp ../../LICENSE.md dist"
42
+ "dev": "node scripts/client.js --watch",
43
+ "build": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\" && node scripts/client.js && tsc -p tsconfig.build.json && cp ../../LICENSE.md dist"
44
44
  },
45
45
  "dependencies": {
46
46
  "@standard-schema/spec": "^1.1.0"
47
+ },
48
+ "devDependencies": {
49
+ "@electric-sql/pglite": "^0.5.10",
50
+ "@electric-sql/pglite-socket": "^0.2.13",
51
+ "@types/pg": "^8.23.1",
52
+ "pg": "^8.23.1",
53
+ "rolldown": "^1.2.1"
47
54
  }
48
55
  }
package/src/app/index.ts CHANGED
@@ -1,11 +1,69 @@
1
1
  import { Context } from "../context/index.js";
2
2
  import type { Middleware } from "../middleware/index.js";
3
- import type { Multipart } from "../multipart/index.js";
4
- import { Route } from "../route/index.js";
3
+ import {
4
+ Limit,
5
+ Malformed,
6
+ type Multipart,
7
+ Unsupported,
8
+ memory,
9
+ } from "../multipart/index.js";
10
+ import { Route, freeze } from "../route/index.js";
5
11
  import { Trie } from "../trie/index.js";
6
- import { Header, Method, type Util } from "../util/index.js";
12
+ import { Header, Method, Mime, type Util } from "../util/index.js";
13
+
14
+ /** Internal protocol for services that `app.use` mounts, such as `Auth`. */
15
+ export const mount = Symbol("mount");
16
+
17
+ /** Asks an authorization service for the routes agents sign in with, see `Mcp` */
18
+ export const agents = Symbol("agents");
19
+
20
+ /** Routes that accept cross-origin requests without cookies, such as OAuth endpoints. */
21
+ export const crossOrigin = new WeakSet<Route>();
22
+
23
+ /**
24
+ * Routes that run without the app's global middleware, such as an MCP
25
+ * endpoint, which makes its own request to the app for each call.
26
+ */
27
+ export const direct = new WeakSet<Route>();
7
28
 
8
29
  export namespace App {
30
+ /** What a service can use from the app it is mounted on. */
31
+ export interface Mount {
32
+ /** Every route the app has, including ones added later */
33
+ readonly routes: readonly Route[];
34
+
35
+ /** The app's request handler */
36
+ readonly fetch: App["fetch"];
37
+
38
+ /** Most memory a request body may take, the app's `multipart.memory` */
39
+ readonly memory: number;
40
+
41
+ /**
42
+ * @param method Request method
43
+ * @param pathname URL pathname
44
+ * @returns The route a request would run and its parameters, before
45
+ * running it
46
+ */
47
+ find(
48
+ method: string,
49
+ pathname: string,
50
+ ): { route: Route; params: Record<string, string> } | undefined;
51
+ }
52
+
53
+ /** A service that adds its routes and middleware to the app. */
54
+ export interface Service {
55
+ /**
56
+ * @param app The app the service is mounted on
57
+ * @returns Routes and global middleware to use
58
+ */
59
+ [mount](app: Mount): Util.DeepArray<Route | Middleware>;
60
+ }
61
+
62
+ /** Fetch options plus server-supplied connection metadata. */
63
+ export interface Fetch extends RequestInit {
64
+ /** Trusted socket peer or verified edge client IP. Never copy an arbitrary forwarded header. */
65
+ readonly ip?: string | undefined;
66
+ }
9
67
  export namespace Options {
10
68
  /** Trailing slash preference */
11
69
  export type TrailingSlash = "always" | "never" | "ignore";
@@ -19,7 +77,8 @@ export namespace App {
19
77
  * protection that checks the request's `method`, and its
20
78
  * [`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
21
79
  * and [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
22
- * headers.
80
+ * headers. Requests with neither header nor a `Cookie` are not from a
81
+ * browser and are allowed.
23
82
  *
24
83
  * More robust protection requires a stateful server or a database to store
25
84
  * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
@@ -41,9 +100,9 @@ export namespace App {
41
100
 
42
101
  /**
43
102
  * Multipart form data options
44
- * (overridden by options passed into `Context.form(options)`)
103
+ * (overridden by options passed into `Context.multipart(options)`)
45
104
  */
46
- readonly form?: Multipart.Options;
105
+ readonly multipart?: Multipart.Options;
47
106
  };
48
107
  }
49
108
 
@@ -52,9 +111,15 @@ export class App {
52
111
  /** Route trie */
53
112
  readonly #trie = new Trie();
54
113
 
114
+ /** Every route added, in order */
115
+ readonly #routes: Route[] = [];
116
+
55
117
  /** Global middleware */
56
118
  readonly #global: Middleware[] = [];
57
119
 
120
+ /** Routes by tool name, agents call each by its own */
121
+ readonly #tools = new Map<string, Route>();
122
+
58
123
  /** App options */
59
124
  readonly #options;
60
125
 
@@ -69,22 +134,45 @@ export class App {
69
134
  if (this.#options.csrf) this.#global.push(App.#csrf);
70
135
 
71
136
  if (this.#options.trailingSlash !== "ignore") {
72
- this.#global.push(App.#createTrailingSlash(this.#options.trailingSlash));
137
+ this.#global.push(this.#createTrailingSlash(this.#options.trailingSlash));
73
138
  }
74
139
  }
75
140
 
76
141
  /**
77
- * @param routes Route or middleware to use
142
+ * @param routes Routes, middleware, or services such as `Auth` to use
78
143
  * @returns `App` instance
79
144
  */
80
145
  use(
81
146
  ...routes: Util.DeepArray<
82
- Route | Middleware | Record<string, Route | Middleware>
147
+ Route | Middleware | App.Service | Record<string, Route | Middleware>
83
148
  >[]
84
149
  ) {
85
150
  for (const route of routes) {
86
151
  if (route instanceof Route) {
152
+ // final from here, so its tool name and middleware stay as checked
153
+ route[freeze]();
154
+ const { tool } = route;
155
+ if (tool) {
156
+ const other = this.#tools.get(tool.name);
157
+ if (other && other !== route)
158
+ throw new TypeError(
159
+ `Tool name "${tool.name}" is used by ${other.method} ${other.pattern} and ${route.method} ${route.pattern}, change one of their patterns.`,
160
+ );
161
+ this.#tools.set(tool.name, route);
162
+ }
163
+
87
164
  this.#trie.add(route);
165
+ this.#routes.push(route);
166
+ } else if (mount in route) {
167
+ this.use(
168
+ route[mount]({
169
+ routes: this.#routes,
170
+ fetch: this.fetch,
171
+ memory: this.#options.multipart?.memory ?? memory,
172
+ find: (method, pathname) =>
173
+ this.#find(method, pathname) ?? undefined,
174
+ }),
175
+ );
88
176
  } else if (Array.isArray(route)) {
89
177
  this.use(...route);
90
178
  } else if (typeof route === "function") {
@@ -106,38 +194,128 @@ export class App {
106
194
  * @param options [Options](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#options) to apply to the request
107
195
  * @returns Promise that resolves to the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to the request
108
196
  */
109
- readonly fetch = async (
110
- resource: RequestInfo | URL,
111
- options?: RequestInit,
112
- ) => {
197
+ readonly fetch = async (resource: RequestInfo | URL, options?: App.Fetch) => {
198
+ let init: RequestInit | undefined;
199
+ if (options)
200
+ for (const key in options) {
201
+ if (key === "ip") continue;
202
+ const { ip, ...rest } = options;
203
+ init = rest;
204
+ break;
205
+ }
113
206
  const c = new Context(
114
- resource instanceof Request && !options
207
+ resource instanceof Request && !init
115
208
  ? resource
116
- : new Request(resource, options),
209
+ : new Request(resource, init),
117
210
  this.#options,
211
+ options?.ip,
118
212
  );
119
213
 
120
- return Context.compose(
121
- Object.assign(
122
- c,
123
- // match
124
- this.#trie.find(
125
- // use GET for HEAD requests to find the correct route
126
- (c.req.method === Method.head ? Method.get : c.req.method) +
127
- c.url.pathname,
128
- ),
129
- ),
130
- this.#global.concat(c.route?.middleware ?? []),
131
- );
214
+ try {
215
+ return await Context.compose(
216
+ Object.assign(c, this.#find(c.req.method, c.url.pathname)),
217
+ // a route's body errors are answered before global middleware
218
+ // sees them, so middleware that catches errors gets only the app's
219
+ c.route
220
+ ? direct.has(c.route)
221
+ ? c.route.middleware
222
+ : [...this.#global, App.#body, ...c.route.middleware]
223
+ : this.#global,
224
+ );
225
+ } catch (error) {
226
+ // from global middleware that read the body itself
227
+ const answer = App.#mistake(error);
228
+ if (!answer) throw error;
229
+
230
+ // with the headers middleware set before it, such as for CORS
231
+ const headers = new Headers(c.res.headers);
232
+ headers.set(Header.name.type, Header.utf8(Mime.type.text));
233
+
234
+ return new Response(answer[1], { status: answer[0], headers });
235
+ }
132
236
  };
133
237
 
238
+ /**
239
+ * @param method Request method, GET finds the route for HEAD
240
+ * @param pathname URL pathname
241
+ * @returns The matched route and its decoded parameters
242
+ */
243
+ #find(method: string, pathname: string) {
244
+ const match = this.#trie.find(
245
+ (method === Method.head ? Method.get : method) + pathname,
246
+ );
247
+
248
+ if (match)
249
+ for (const name in match.params)
250
+ match.params[name] = App.#decode(match.params[name]!, name === "*");
251
+
252
+ return match;
253
+ }
254
+
255
+ /**
256
+ * @param error Error from reading a request body
257
+ * @returns The status and message for a body the client got wrong,
258
+ * `undefined` for any other error, which is the app's
259
+ */
260
+ static #mistake(error: unknown): [number, string] | undefined {
261
+ if (error instanceof Limit) return [413, error.message];
262
+ if (error instanceof Unsupported)
263
+ return [415, "Unsupported Media Type: send multipart/form-data"];
264
+ if (error instanceof Malformed)
265
+ return [400, `Bad Request: ${error.message}`];
266
+ }
267
+
268
+ /** Answers a body the client got wrong, where the route read it */
269
+ static async #body(c: Middleware.Context, next: Middleware.Next) {
270
+ try {
271
+ await next();
272
+ } catch (error) {
273
+ const answer = App.#mistake(error);
274
+ if (!answer) throw error;
275
+ c.text(answer[1], answer[0]);
276
+ }
277
+ }
278
+
279
+ /**
280
+ * @param value Matched parameter, as the URL encodes it
281
+ * @param wildcard The value is a wildcard's path
282
+ * @returns The decoded value, or the value as sent when it is malformed
283
+ */
284
+ static #decode(value: string, wildcard: boolean) {
285
+ // a wildcard is relative to its route, so `/files//etc/passwd` cannot
286
+ // make it an absolute path
287
+ if (wildcard) value = value.replace(/^\/+/, "");
288
+ if (!value.includes("%")) return value;
289
+
290
+ try {
291
+ if (!wildcard) return decodeURIComponent(value);
292
+
293
+ // a wildcard is a path, so encoded separators stay encoded and a
294
+ // request cannot add segments to it, such as `..%2Fsecret`
295
+ return value
296
+ .split(/(%2F|%5C)/i)
297
+ .map((part, i) => (i % 2 ? part : decodeURIComponent(part)))
298
+ .join("");
299
+ } catch {
300
+ return value;
301
+ }
302
+ }
303
+
134
304
  /** Basic CSRF middleware */
135
305
  static #csrf(c: Middleware.Context, next: Middleware.Next) {
306
+ const { headers, method } = c.req;
307
+ const site = headers.get(Header.name.fetch);
308
+ const origin = headers.get(Header.name.origin);
309
+
136
310
  if (
137
- c.req.method === Method.get ||
138
- c.req.method === Method.head ||
139
- c.req.headers.get(Header.name.fetch) === "same-origin" ||
140
- c.req.headers.get(Header.name.origin) === c.url.origin
311
+ method === Method.get ||
312
+ method === Method.head ||
313
+ site === "same-origin" ||
314
+ origin === c.url.origin ||
315
+ (c.route && crossOrigin.has(c.route)) ||
316
+ // browsers send at least one, so without cookies this is not a browser,
317
+ // for example an agent submitting a form
318
+ (site === null && origin === null && !headers.has(Header.name.cookie))
141
319
  ) {
142
320
  return next();
143
321
  }
@@ -145,22 +323,32 @@ export class App {
145
323
  c.text("Forbidden", 403);
146
324
  }
147
325
 
148
- /** @returns Trailing slash middleware */
149
- static #createTrailingSlash(mode: App.Options.TrailingSlash) {
326
+ /**
327
+ * Redirect a request no route matched to the other spelling of its path,
328
+ * with or without the trailing slash, when a route matches that.
329
+ *
330
+ * @returns Trailing slash middleware
331
+ */
332
+ #createTrailingSlash(mode: App.Options.TrailingSlash) {
150
333
  return async (c: Context, next: Middleware.Next) => {
151
334
  await next();
152
335
 
153
- if (c.res.status && c.res.status !== 404) return;
336
+ // a route answered, its handler has already run
337
+ if (c.route || (c.res.status && c.res.status !== 404)) return;
154
338
 
155
- const slash = c.url.pathname.endsWith("/");
339
+ const { pathname } = c.url;
340
+ const slash = pathname.endsWith("/");
341
+ const other =
342
+ mode === "always" && !slash
343
+ ? pathname + "/"
344
+ : mode === "never" && pathname !== "/" && slash
345
+ ? pathname.slice(0, -1)
346
+ : undefined;
156
347
 
157
- if (mode === "always" && !slash) {
158
- c.url.pathname += "/";
159
- c.redirect(c.url, 308);
160
- } else if (mode === "never" && c.url.pathname !== "/" && slash) {
161
- c.url.pathname = c.url.pathname.slice(0, -1);
162
- c.redirect(c.url, 308);
163
- }
348
+ if (!other || !this.#find(c.req.method, other)) return;
349
+
350
+ c.url.pathname = other;
351
+ c.redirect(c.url, 308);
164
352
  };
165
353
  }
166
354
  }