@ngrok/app-server 0.3.2 → 0.3.3

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 (57) hide show
  1. package/README.md +51 -15
  2. package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
  3. package/dist/build-id-B0448vZH.js.map +1 -0
  4. package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
  5. package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
  6. package/dist/cli.js +2 -2
  7. package/dist/client-browser.js +1 -1
  8. package/dist/client.js +1 -1
  9. package/dist/{create-server-kzZWd_Lo.d.ts → create-server-D4-nVOVJ.d.ts} +50 -13
  10. package/dist/{create-server-D0De6R7Q.js → create-server-jMl2ltHD.js} +572 -522
  11. package/dist/create-server-jMl2ltHD.js.map +1 -0
  12. package/dist/{entry-DuGgSKeB.d.ts → entry-BPrgE_6K.d.ts} +39 -3
  13. package/dist/entry-D9H4LA9c.js +351 -0
  14. package/dist/entry-D9H4LA9c.js.map +1 -0
  15. package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
  16. package/dist/index.d.ts +5 -15
  17. package/dist/index.js +3 -3
  18. package/dist/{load-entry-Bodyd2Ok.js → load-entry-D7r0mjEp.js} +3 -3
  19. package/dist/{load-entry-Bodyd2Ok.js.map → load-entry-D7r0mjEp.js.map} +1 -1
  20. package/dist/node-vite.d.ts +1 -1
  21. package/dist/node.d.ts +1 -1
  22. package/dist/react-router-vite.d.ts +1 -1
  23. package/dist/react-router.d.ts +3 -2
  24. package/dist/react-router.js +31 -2
  25. package/dist/react-router.js.map +1 -1
  26. package/dist/{serve-caOkS3o5.js → serve-E0hSGe6_.js} +2 -2
  27. package/dist/{serve-caOkS3o5.js.map → serve-E0hSGe6_.js.map} +1 -1
  28. package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
  29. package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
  30. package/dist/{start-DREqYrZh.js → start-CifYPRq1.js} +33 -5
  31. package/dist/start-CifYPRq1.js.map +1 -0
  32. package/dist/tanstack-start-vite.d.ts +1 -1
  33. package/dist/tanstack-start.d.ts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +2 -2
  36. package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
  37. package/dist/{types-CEvzAmcn.d.ts → types-j29vspx_.d.ts} +15 -1
  38. package/dist/vercel-pages.d.ts +32 -0
  39. package/dist/vercel-pages.js +54 -0
  40. package/dist/vercel-pages.js.map +1 -0
  41. package/dist/vercel-vite.d.ts +30 -9
  42. package/dist/vercel-vite.js +160 -17
  43. package/dist/vercel-vite.js.map +1 -1
  44. package/dist/vercel.d.ts +2 -2
  45. package/dist/vercel.js +1 -1
  46. package/dist/{vite-tTxVimP6.js → vite-BDREIgiH.js} +44 -19
  47. package/dist/vite-BDREIgiH.js.map +1 -0
  48. package/dist/vite.d.ts +1 -1
  49. package/dist/vite.js +1 -1
  50. package/package.json +1 -1
  51. package/dist/build-id-C6sYO9Yp.js.map +0 -1
  52. package/dist/build-manifest-UDNk81Ce.js.map +0 -1
  53. package/dist/create-server-D0De6R7Q.js.map +0 -1
  54. package/dist/entry-UDsxuqBC.js +0 -116
  55. package/dist/entry-UDsxuqBC.js.map +0 -1
  56. package/dist/start-DREqYrZh.js.map +0 -1
  57. package/dist/vite-tTxVimP6.js.map +0 -1
@@ -1,15 +1,424 @@
1
1
  import { r as withRequestContext } from "./request-context-BtQ87VYb.js";
2
2
  import { a as replaceResponse, o as withHeaderHook, r as hookedHeaders, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
3
- import { o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
3
+ import { c as presenceHeaders, l as presenceHeadersOf, o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
4
4
  import { i as requestLogger, r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
5
5
  import { n as finishResponse, r as onResponseSent } from "./response-edge-Bc1-C_Cx.js";
6
+ import { r as manifestKey } from "./build-manifest-DBMWe3Lx.js";
6
7
  import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-7_gToa8R.js";
7
8
  import { i as isFilePath$1, n as findStaticFile, o as staticResponse, s as withVary, t as contentType } from "./static-files-Beju9riB.js";
8
- import { n as manifestKey } from "./build-manifest-UDNk81Ce.js";
9
9
  import { Hono } from "hono";
10
- import { HTTPException } from "hono/http-exception";
11
- import { matchedRoutes } from "hono/route";
12
10
  import { getPath } from "hono/utils/url";
11
+ import { matchedRoutes } from "hono/route";
12
+ import { HTTPException } from "hono/http-exception";
13
+
14
+ // src/core/prefers-markdown.ts
15
+ /** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */
16
+ const QVALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
17
+ /** The charset of each answer that a caller of {@link prefersMarkdown} sends. */
18
+ const CHARSET = "utf-8";
19
+ /**
20
+ * The parts of `value` between each `separator`. Why a scan, not `split`: a
21
+ * quoted parameter value can hold a `,` or a `;`.
22
+ */
23
+ function splitOutsideQuotes(value, separator) {
24
+ const parts = [];
25
+ let part = "";
26
+ let quoted = false;
27
+ let escaped = false;
28
+ for (const character of value) if (!quoted && character === separator) {
29
+ parts.push(part);
30
+ part = "";
31
+ } else {
32
+ if (escaped) escaped = false;
33
+ else if (quoted && character === "\\") escaped = true;
34
+ else if (character === "\"") quoted = !quoted;
35
+ part += character;
36
+ }
37
+ parts.push(part);
38
+ return parts;
39
+ }
40
+ /** The parameters of a media range, by lowercase name, with quotes removed. */
41
+ function parameterMap(parameters) {
42
+ return new Map(parameters.map((parameter) => {
43
+ const index = parameter.indexOf("=");
44
+ const name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();
45
+ const value = index === -1 ? "" : parameter.slice(index + 1).trim();
46
+ return [name, /^".*"$/su.test(value) ? value.slice(1, -1).replaceAll(/\\(?<character>.)/gsu, "$<character>") : value];
47
+ }));
48
+ }
49
+ /**
50
+ * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC
51
+ * 9110 default. Why a malformed `q` also counts as 1: the client still named
52
+ * the media type.
53
+ */
54
+ function mediaRanges(accept) {
55
+ return splitOutsideQuotes(accept, ",").map((entry) => {
56
+ const [type = "", ...parameters] = splitOutsideQuotes(entry, ";");
57
+ const parameterValues = parameterMap(parameters);
58
+ const quality = parameterValues.get("q") ?? "1";
59
+ return {
60
+ type: type.trim().toLowerCase(),
61
+ quality: QVALUE.test(quality) ? Number(quality) : 1,
62
+ charset: parameterValues.get("charset")?.toLowerCase()
63
+ };
64
+ });
65
+ }
66
+ /**
67
+ * The `q` of an answer of `type` in UTF-8, from the most specific ranges with
68
+ * that type, or `undefined` when no range matches it. A range with
69
+ * `charset=utf-8` is more specific than a range with no charset. A range with
70
+ * another charset does not match. Other parameters, such as `variant`, do not
71
+ * change the match.
72
+ */
73
+ function qualityOf(ranges, type) {
74
+ const matches = ranges.filter((range) => range.type === type && (range.charset == null || range.charset === CHARSET));
75
+ const withCharset = matches.filter((range) => range.charset === CHARSET);
76
+ const specific = withCharset.length > 0 ? withCharset : matches;
77
+ return specific.length === 0 ? void 0 : Math.max(...specific.map((range) => range.quality));
78
+ }
79
+ /**
80
+ * Whether a request asks for markdown before HTML, per
81
+ * https://acceptmarkdown.com. Use it to choose between the HTML and the
82
+ * markdown answer for one URL.
83
+ *
84
+ * The rules:
85
+ *
86
+ * - Only an explicit `text/markdown` range counts for markdown. A wildcard,
87
+ * such as `*\/*` or `text/*`, never selects markdown, so a browser and a
88
+ * client with no `Accept` get HTML.
89
+ * - `text/markdown;q=0` refuses markdown.
90
+ * - The `q` of markdown must be equal to or higher than the `q` of HTML. The
91
+ * `q` of HTML comes from the most specific range that matches it:
92
+ * `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
93
+ * the client named it.
94
+ * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
95
+ * than a range with no charset, and a range with another charset does not
96
+ * match. Other parameters, such as `variant`, do not change the match.
97
+ * - Media types and parameter names are not case-sensitive. A quoted
98
+ * parameter value can hold a `,` or a `;`.
99
+ *
100
+ * When the answer for a URL depends on this function, send `Vary: Accept` on
101
+ * both the HTML and the markdown answer. Else a shared cache can give the
102
+ * markdown to a browser.
103
+ *
104
+ * @example
105
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
106
+ * // => true
107
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
108
+ * // => false
109
+ */
110
+ function prefersMarkdown(request) {
111
+ const accept = request.headers.get("Accept");
112
+ if (accept == null || !/markdown/iu.test(accept)) return false;
113
+ const ranges = mediaRanges(accept);
114
+ const markdown = qualityOf(ranges, "text/markdown") ?? 0;
115
+ const html = qualityOf(ranges, "text/html") ?? qualityOf(ranges, "text/*") ?? qualityOf(ranges, "*/*") ?? 0;
116
+ return markdown > 0 && markdown >= html;
117
+ }
118
+
119
+ // src/core/safe-local-path.ts
120
+ /**
121
+ * Whether `value` is a safe same-origin path for a `Location` header. The
122
+ * value starts with one `/`, the next character is not `/` or `\`, and each
123
+ * character is printable ASCII (0x20 to 0x7E).
124
+ *
125
+ * The check stops these attacks:
126
+ *
127
+ * - An open redirect: `//evil.com`, `/\evil.com`, and `https://evil.com` go to
128
+ * another host. A browser reads `/\` as `//`.
129
+ * - A scheme that does not navigate, such as `javascript:` or `data:`.
130
+ * - A control character, such as CR or LF, that splits the response.
131
+ *
132
+ * Why strict: a short allow list is easy to audit. The check rejects some safe
133
+ * values, such as a path with raw UTF-8. Percent-encode the path first.
134
+ *
135
+ * Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.
136
+ *
137
+ * @example
138
+ * isSafeLocalPath("/components/button?tab=props"); // => true
139
+ * isSafeLocalPath("//evil.com/foo"); // => false
140
+ * isSafeLocalPath("/café"); // => false
141
+ */
142
+ function isSafeLocalPath(value) {
143
+ return /^\/(?![/\\])/u.test(value) && !/[^\u0020-\u007E]/u.test(value);
144
+ }
145
+
146
+ // src/core/plugins/trailing-slash.ts
147
+ /** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */
148
+ function isFilePath(path) {
149
+ return path.slice(path.lastIndexOf("/") + 1).includes(".");
150
+ }
151
+ /** `path` with no trailing slashes. Why a scan, not `/\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */
152
+ function trimTrailingSlashes(path) {
153
+ let end = path.length;
154
+ while (end > 0 && path[end - 1] === "/") end -= 1;
155
+ return path.slice(0, end);
156
+ }
157
+ /** The URL path in `mode`, or the path unchanged when `mode` keeps it. */
158
+ function canonicalPath(path, mode) {
159
+ const trimmed = trimTrailingSlashes(path);
160
+ if (trimmed === "") return "/";
161
+ if (mode === "never") return trimmed;
162
+ if (mode === "always") return `${trimmed}/`;
163
+ return path;
164
+ }
165
+ /**
166
+ * Whether one of the app's own Hono routes matches the request. Why the
167
+ * path: the plugins and the framework match at `/*`, and Hono matches a
168
+ * route path strictly, so a redirect would move the request off its route.
169
+ */
170
+ function hasAppRoute(context) {
171
+ return matchedRoutes(context).some((route) => route.path !== "/*");
172
+ }
173
+ /** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */
174
+ async function isStaticFile(files, path) {
175
+ return (await findStaticFile(files, path))?.path === path;
176
+ }
177
+ /**
178
+ * Sends a 308 from a page URL to the same URL in `mode`, so each page has one
179
+ * URL. It applies to rendered and prerendered pages, because the server cannot
180
+ * tell which paths have a route. The redirect keeps the query string.
181
+ *
182
+ * It sends no redirect for `/`, a method other than GET or HEAD, a data
183
+ * request of the framework, a path that one of the app's own Hono routes
184
+ * matches, such as `app.get("/livez")`, or a path that already has the
185
+ * mode's form. `always` adds no slash to a file in the client build, such as
186
+ * `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.
187
+ *
188
+ * Set the same mode in the framework's router when it has one. Else the two
189
+ * redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`
190
+ * back to `/x`. For TanStack Start, check the mode against the router with
191
+ * `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router
192
+ * has no trailing-slash option, so it answers both forms itself.
193
+ *
194
+ * @example
195
+ * createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
196
+ */
197
+ function trailingSlash({ mode }) {
198
+ let stage;
199
+ return {
200
+ name: "trailing-slash",
201
+ setup: (info) => {
202
+ if (mode === "preserve") return;
203
+ stage = async (context, next) => {
204
+ const { method } = context.req;
205
+ if (method !== "GET" && method !== "HEAD" || info.isDataRequest(context.req.path) || hasAppRoute(context)) return next();
206
+ const url = new URL(context.req.url);
207
+ const path = canonicalPath(url.pathname, mode);
208
+ const location = `${path}${url.search}`;
209
+ if (path === url.pathname || !isSafeLocalPath(location)) return next();
210
+ if (mode === "always" && (isFilePath(context.req.path) || await isStaticFile(info.files, context.req.path))) return next();
211
+ return context.redirect(location, 308);
212
+ };
213
+ },
214
+ middleware: async (context, next) => stage == null ? next() : stage(context, next)
215
+ };
216
+ }
217
+
218
+ // src/core/plugins/static.ts
219
+ const IMMUTABLE = "public, max-age=31536000, immutable";
220
+ /** The requests that the dev server answered. */
221
+ const devServerAnswers = /* @__PURE__ */ new WeakSet();
222
+ /**
223
+ * Whether the dev server answered the request, such as for a source module.
224
+ * Why: the access log writes no line for such a request, because one page
225
+ * load in development makes hundreds of them.
226
+ *
227
+ * @example
228
+ * await next();
229
+ * if (answeredByDevServer(context)) return;
230
+ */
231
+ function answeredByDevServer(context) {
232
+ return devServerAnswers.has(context);
233
+ }
234
+ /**
235
+ * Serves the hashed files under Vite's `build.assetsDir`, `/assets/` by
236
+ * default, with a one-year immutable cache. The `appServer` Vite plugin
237
+ * records the directory. A missing asset gets a plain 404 with
238
+ * `Cache-Control: no-store`, not a rendered page. In development, the dev
239
+ * server serves the source modules, the HMR client, and the CSS here instead.
240
+ *
241
+ * @example
242
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
243
+ */
244
+ function assets() {
245
+ let stage;
246
+ return {
247
+ name: "assets",
248
+ setup: (info) => {
249
+ if (info.mode === "development") {
250
+ const { devServer } = info;
251
+ stage = async (context, next) => {
252
+ let passed = false;
253
+ const answer = await devServer(context, async () => {
254
+ passed = true;
255
+ await next();
256
+ });
257
+ if (!passed) devServerAnswers.add(context);
258
+ return answer;
259
+ };
260
+ return;
261
+ }
262
+ const { files, contentTypes, assetsPath } = info;
263
+ stage = async (context, next) => {
264
+ const { method, path } = context.req;
265
+ if (!path.startsWith(assetsPath) || method !== "GET" && method !== "HEAD") return next();
266
+ const file = await findStaticFile(files, path);
267
+ if (file == null) return context.text("Not Found", 404, { "Cache-Control": "no-store" });
268
+ return staticResponse(context, {
269
+ files,
270
+ file,
271
+ headers: { "Cache-Control": IMMUTABLE },
272
+ contentTypes
273
+ });
274
+ };
275
+ },
276
+ middleware: async (context, next) => stage == null ? next() : stage(context, next)
277
+ };
278
+ }
279
+ const REVALIDATE = "public, max-age=0, must-revalidate";
280
+ const ONE_HOUR = "public, max-age=3600, stale-while-revalidate=86400";
281
+ /**
282
+ * The default markdown twin of a page: `/docs/button.md` for `/docs/button`,
283
+ * and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends
284
+ * it to another file or to the framework, so the page's twin does not match
285
+ * its answer.
286
+ */
287
+ function defaultTwinOf(path, rewritten) {
288
+ return rewritten === path ? `${trimTrailingSlashes(path) || "/index"}.md` : void 0;
289
+ }
290
+ /** The file of the markdown twin of the request, or `undefined` when the page has none. */
291
+ async function findTwin(files, context, { twinOf, rewritten }) {
292
+ const twinPath = twinOf?.(context.req.path, rewritten, context);
293
+ const file = twinPath == null ? void 0 : await findStaticFile(files, twinPath);
294
+ return twinPath == null || file == null ? void 0 : {
295
+ path: twinPath,
296
+ file
297
+ };
298
+ }
299
+ /** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */
300
+ function varyOnAccept(context) {
301
+ const vary = withVary(context.res.headers.get("Vary"), "Accept");
302
+ if (vary != null) writableHeaders(context).set("Vary", vary);
303
+ }
304
+ /**
305
+ * The percent-encoded URL path for a decoded path, so it holds no space,
306
+ * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a
307
+ * newline, which a file name can hold.
308
+ */
309
+ function urlPath(path) {
310
+ return new URL(path.replaceAll(/[\t\n\r]/gu, (character) => encodeURIComponent(character)), "http://localhost").pathname;
311
+ }
312
+ /** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */
313
+ function linkToTwin(context, twinPath) {
314
+ writableHeaders(context).append("Link", `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`);
315
+ }
316
+ /**
317
+ * The development stage of `markdownTwins`. The client build has no twins
318
+ * then, so a request that prefers markdown gets the framework's answer for
319
+ * the twin's URL: the route that prerenders the twin. A twin path that is not
320
+ * in `prerenderedPaths`, an error, or an answer that is not markdown sends the
321
+ * request on for the HTML.
322
+ */
323
+ function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
324
+ return async (context, next) => {
325
+ const { method, path } = context.req;
326
+ const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.(path, context) ?? path, context) : void 0;
327
+ if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
328
+ const url = new URL(context.req.url);
329
+ url.pathname = urlPath(twinPath);
330
+ if (getPath(new Request(url)) !== twinPath) return next();
331
+ const { headers, signal } = context.req.raw;
332
+ const twin = new Request(url, {
333
+ method,
334
+ headers,
335
+ signal
336
+ });
337
+ const response = await context.env.framework.fetch(twin, context);
338
+ const markdown = response.headers.get("Content-Type")?.toLowerCase().startsWith("text/markdown") === true;
339
+ if (response.status !== 304 && !(response.ok && markdown)) {
340
+ await response.body?.cancel();
341
+ return next();
342
+ }
343
+ context.res = response;
344
+ varyOnAccept(context);
345
+ };
346
+ }
347
+ /** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */
348
+ function twinOfOption(markdownTwins) {
349
+ if (markdownTwins === true) return defaultTwinOf;
350
+ if (markdownTwins == null || markdownTwins === false) return;
351
+ const { twinOf } = markdownTwins;
352
+ return (path, _rewritten, context) => twinOf(path, context);
353
+ }
354
+ /**
355
+ * Serves the client build: prerendered pages at their own URL with a 200,
356
+ * plus every other file in it. It sends no redirect. The `trailingSlash`
357
+ * plugin does. Each response gets
358
+ * the headers its loader sent at build time (the `appServer` Vite plugin
359
+ * captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304
360
+ * for a matching `If-None-Match`. A GET with one byte range gets a 206. A path
361
+ * with no file goes on to the framework. In development, only
362
+ * `markdownTwins` runs.
363
+ *
364
+ * At startup, it warns about each prerendered path that has no file.
365
+ *
366
+ * @example
367
+ * prerendered({
368
+ * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
369
+ * });
370
+ */
371
+ function prerendered(options = {}) {
372
+ let stage;
373
+ return {
374
+ name: "prerendered",
375
+ setup: async (info) => {
376
+ const twinOf = twinOfOption(options.markdownTwins);
377
+ if (info.mode === "development") {
378
+ const paths = info.prerenderedPaths;
379
+ stage = twinOf == null ? void 0 : developmentTwins(twinOf, options, paths == null ? void 0 : new Set(paths));
380
+ return;
381
+ }
382
+ const { files, contentTypes, capturedHeaders } = info;
383
+ const missing = [];
384
+ for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
385
+ if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
386
+ const cacheControl = options.cacheControl ?? ((path) => {
387
+ const type = contentType(path, contentTypes);
388
+ return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
389
+ });
390
+ const serve = async (context, path, file) => {
391
+ context.env.onServedFile?.(file.path);
392
+ const value = cacheControl(file.path);
393
+ const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
394
+ for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.(path, context)]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
395
+ return staticResponse(context, {
396
+ files,
397
+ file,
398
+ headers: Object.fromEntries(headers),
399
+ contentTypes
400
+ });
401
+ };
402
+ stage = async (context, next) => {
403
+ const { method } = context.req;
404
+ if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
405
+ const rewritten = options.rewrite?.(context.req.path, context) ?? context.req.path;
406
+ const twin = await findTwin(files, context, {
407
+ twinOf,
408
+ rewritten
409
+ });
410
+ const preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : void 0;
411
+ const path = preferred?.path ?? rewritten;
412
+ const file = preferred?.file ?? await findStaticFile(files, path);
413
+ if (file == null) await next();
414
+ else context.res = await serve(context, path, file);
415
+ if (twin != null) varyOnAccept(context);
416
+ if (twin != null && preferred == null) linkToTwin(context, twin.path);
417
+ };
418
+ },
419
+ middleware: async (context, next) => stage == null ? next() : stage(context, next)
420
+ };
421
+ }
13
422
 
14
423
  // src/core/plugins/access-log.ts
15
424
  /**
@@ -36,6 +445,13 @@ function loggedReferer(referer, { redact }) {
36
445
  * logs the response that leaves the server, after each stage. A listener
37
446
  * with an `edge`, such as the node listener, counts the bytes.
38
447
  *
448
+ * - A 5xx line has the level `error`, and each other line has the level `info`.
449
+ * - A line has `http.route` when the framework adapter gives the route
450
+ * pattern that it matched, such as `/domains/:domainId`.
451
+ * - In development, a request that Vite answers, such as a source module,
452
+ * gets no line.
453
+ * - A request of the build's check of the CDN pages gets no line.
454
+ *
39
455
  * @example
40
456
  * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
41
457
  * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
@@ -48,10 +464,11 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
48
464
  await (serverTiming ? withHeaderHook(context, next, (headers) => {
49
465
  if (headers.get("Content-Type")?.startsWith("text/html") ?? false) headers.append("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`);
50
466
  }) : next());
467
+ if (answeredByDevServer(context) || context.env?.onServedFile != null) return;
51
468
  onResponseSent(context, (sent) => {
52
469
  const line = lineAttributes(context, sent, started);
53
470
  try {
54
- context.get("logger").info("request", attributes == null ? line : {
471
+ context.get("logger")[sent.status >= 500 ? "error" : "info"]("request", attributes == null ? line : {
55
472
  ...line,
56
473
  ...attributes(context, sent)
57
474
  });
@@ -82,6 +499,8 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
82
499
  "network.bytes_written": bytes,
83
500
  duration: Math.round((performance.now() - started) * 1e6)
84
501
  };
502
+ const route = context.get("routePattern");
503
+ if (route != null) line["http.route"] = route;
85
504
  if (aborted) line["http.client_aborted"] = true;
86
505
  return line;
87
506
  }
@@ -257,21 +676,33 @@ function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
257
676
 
258
677
  // src/core/plugins/noindex.ts
259
678
  /**
260
- * Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search
261
- * engine does not index a preview deploy. Turn it on from the environment
262
- * with the `noindex` option of `defaultPlugins()`, which puts it before the
263
- * static stages, so it also sees prerendered pages.
679
+ * Sets `X-Robots-Tag: noindex, nofollow` on each response, or on each
680
+ * response to a request with no `unlessHeader`, so a search engine does not
681
+ * index a preview deploy.
682
+ *
683
+ * The `noindex` option of `defaultPlugins()` puts it
684
+ * before the static stages, so it also sees prerendered pages.
264
685
  *
265
686
  * @example
266
687
  * defaultPlugins({ noindex: process.env.PREVIEW === "1" });
688
+ * defaultPlugins({ noindex: { unlessHeader: "x-ngrok-edge" } });
267
689
  */
268
- function noindex() {
269
- return optionPlugin("noindex", {
690
+ function noindex(options) {
691
+ const unlessHeader = options?.unlessHeader;
692
+ const plugin = optionPlugin("noindex", {
270
693
  name: "noindex",
271
- middleware: async (context, next) => withHeaderHook(context, next, (response) => {
272
- response.set("X-Robots-Tag", "noindex, nofollow");
273
- })
694
+ middleware: async (context, next) => {
695
+ const hidden = unlessHeader == null || context.req.header(unlessHeader) == null;
696
+ await withHeaderHook(context, next, (response) => {
697
+ if (hidden) response.set("X-Robots-Tag", "noindex, nofollow");
698
+ if (unlessHeader != null) {
699
+ const vary = withVary(response.get("Vary"), unlessHeader);
700
+ if (vary != null) response.set("Vary", vary);
701
+ }
702
+ });
703
+ }
274
704
  });
705
+ return unlessHeader == null ? plugin : presenceHeaders([unlessHeader], plugin);
275
706
  }
276
707
 
277
708
  // src/core/plugins/private-documents.ts
@@ -300,108 +731,9 @@ function privateDocuments() {
300
731
  setup: (info) => {
301
732
  ({isDataRequest} = info);
302
733
  },
303
- middleware: async (context, next) => withHeaderHook(context, next, (headers) => {
304
- if (!headers.has("Cache-Control") && ((headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path))) headers.set("Cache-Control", "private, no-cache");
305
- })
306
- };
307
- }
308
-
309
- // src/core/safe-local-path.ts
310
- /**
311
- * Whether `value` is a safe same-origin path for a `Location` header. The
312
- * value starts with one `/`, the next character is not `/` or `\`, and each
313
- * character is printable ASCII (0x20 to 0x7E).
314
- *
315
- * The check stops these attacks:
316
- *
317
- * - An open redirect: `//evil.com`, `/\evil.com`, and `https://evil.com` go to
318
- * another host. A browser reads `/\` as `//`.
319
- * - A scheme that does not navigate, such as `javascript:` or `data:`.
320
- * - A control character, such as CR or LF, that splits the response.
321
- *
322
- * Why strict: a short allow list is easy to audit. The check rejects some safe
323
- * values, such as a path with raw UTF-8. Percent-encode the path first.
324
- *
325
- * Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.
326
- *
327
- * @example
328
- * isSafeLocalPath("/components/button?tab=props"); // => true
329
- * isSafeLocalPath("//evil.com/foo"); // => false
330
- * isSafeLocalPath("/café"); // => false
331
- */
332
- function isSafeLocalPath(value) {
333
- return /^\/(?![/\\])/u.test(value) && !/[^\u0020-\u007E]/u.test(value);
334
- }
335
-
336
- // src/core/plugins/trailing-slash.ts
337
- /** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */
338
- function isFilePath(path) {
339
- return path.slice(path.lastIndexOf("/") + 1).includes(".");
340
- }
341
- /** `path` with no trailing slashes. Why a scan, not `/\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */
342
- function trimTrailingSlashes(path) {
343
- let end = path.length;
344
- while (end > 0 && path[end - 1] === "/") end -= 1;
345
- return path.slice(0, end);
346
- }
347
- /** The URL path in `mode`, or the path unchanged when `mode` keeps it. */
348
- function canonicalPath(path, mode) {
349
- const trimmed = trimTrailingSlashes(path);
350
- if (trimmed === "") return "/";
351
- if (mode === "never") return trimmed;
352
- if (mode === "always") return `${trimmed}/`;
353
- return path;
354
- }
355
- /**
356
- * Whether one of the app's own Hono routes matches the request. Why the
357
- * path: the plugins and the framework match at `/*`, and Hono matches a
358
- * route path strictly, so a redirect would move the request off its route.
359
- */
360
- function hasAppRoute(context) {
361
- return matchedRoutes(context).some((route) => route.path !== "/*");
362
- }
363
- /** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */
364
- async function isStaticFile(files, path) {
365
- return (await findStaticFile(files, path))?.path === path;
366
- }
367
- /**
368
- * Sends a 308 from a page URL to the same URL in `mode`, so each page has one
369
- * URL. It applies to rendered and prerendered pages, because the server cannot
370
- * tell which paths have a route. The redirect keeps the query string.
371
- *
372
- * It sends no redirect for `/`, a method other than GET or HEAD, a data
373
- * request of the framework, a path that one of the app's own Hono routes
374
- * matches, such as `app.get("/livez")`, or a path that already has the
375
- * mode's form. `always` adds no slash to a file in the client build, such as
376
- * `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.
377
- *
378
- * Set the same mode in the framework's router when it has one. Else the two
379
- * redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`
380
- * back to `/x`. For TanStack Start, check the mode against the router with
381
- * `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router
382
- * has no trailing-slash option, so it answers both forms itself.
383
- *
384
- * @example
385
- * createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
386
- */
387
- function trailingSlash({ mode }) {
388
- let stage;
389
- return {
390
- name: "trailing-slash",
391
- setup: (info) => {
392
- if (mode === "preserve") return;
393
- stage = async (context, next) => {
394
- const { method } = context.req;
395
- if (method !== "GET" && method !== "HEAD" || info.isDataRequest(context.req.path) || hasAppRoute(context)) return next();
396
- const url = new URL(context.req.url);
397
- const path = canonicalPath(url.pathname, mode);
398
- const location = `${path}${url.search}`;
399
- if (path === url.pathname || !isSafeLocalPath(location)) return next();
400
- if (mode === "always" && (isFilePath(context.req.path) || await isStaticFile(info.files, context.req.path))) return next();
401
- return context.redirect(location, 308);
402
- };
403
- },
404
- middleware: async (context, next) => stage == null ? next() : stage(context, next)
734
+ middleware: async (context, next) => withHeaderHook(context, next, (headers) => {
735
+ if (!headers.has("Cache-Control") && ((headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path))) headers.set("Cache-Control", "private, no-cache");
736
+ })
405
737
  };
406
738
  }
407
739
 
@@ -560,9 +892,10 @@ const DEFAULT_SECURITY_HEADERS = {
560
892
  * - `Cross-Origin-Opener-Policy: same-origin`
561
893
  * - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
562
894
  *
563
- * A response that has a header keeps its own value. The exception is
564
- * `Content-Security-Policy`, which has no default: the plugin adds a set
565
- * value as a second policy, and a browser enforces both.
895
+ * `Content-Security-Policy` and `Permissions-Policy` have no default. A
896
+ * response that has a header keeps its own value. The exception is
897
+ * `Content-Security-Policy`: the plugin adds a set value as a second policy,
898
+ * and a browser enforces both.
566
899
  * `defaultPlugins()` puts it before the static stages, so it also sees
567
900
  * prerendered pages.
568
901
  *
@@ -571,429 +904,145 @@ const DEFAULT_SECURITY_HEADERS = {
571
904
  * securityHeaders: {
572
905
  * headers: {
573
906
  * "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
574
- * "Content-Security-Policy": "frame-ancestors 'none'",
575
- * },
576
- * },
577
- * });
578
- */
579
- function securityHeaders({ headers = {} } = {}) {
580
- const values = Object.entries({
581
- ...DEFAULT_SECURITY_HEADERS,
582
- ...headers
583
- }).filter((entry) => typeof entry[1] === "string").map(([name, value]) => [name, oneLine(value)]);
584
- return {
585
- name: "security-headers",
586
- middleware: async (context, next) => {
587
- const isHttps = context.req.url.startsWith("https:");
588
- await withHeaderHook(context, next, (response) => {
589
- for (const [name, value] of values) if (name === "Content-Security-Policy") response.append(name, value);
590
- else if (!response.has(name) && (name !== "Strict-Transport-Security" || isHttps)) response.set(name, value);
591
- });
592
- }
593
- };
594
- }
595
- /**
596
- * `value` on one line. Why: a header value cannot hold a line break, and a
597
- * policy written over several lines treats each run of whitespace as one space.
598
- */
599
- function oneLine(value) {
600
- return value.replaceAll(/\s+/gu, " ").trim();
601
- }
602
- /** A new random nonce: 16 bytes in base64. */
603
- function randomNonce() {
604
- return btoa(String.fromCodePoint(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
605
- }
606
- /**
607
- * Sets the `Content-Security-Policy` from `policy` on each HTML document. The
608
- * policy trusts the document's scripts, and only them:
609
- *
610
- * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce
611
- * for each request. The app reads the nonce from `requestContext()` and
612
- * gives it to the framework's render, so each inline script gets it.
613
- * - A prerendered document gets `'self'` and the hash of each of its inline
614
- * scripts, which the Vite plugin records. Its file has one nonce for every
615
- * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,
616
- * unlike a nonce, does not carry to the imports of an inline module script.
617
- *
618
- * The `contentSecurityPolicy` option of `defaultPlugins()` takes these
619
- * options, and puts the plugin before the static stages, so it sees the
620
- * prerendered documents. A response that has a `Content-Security-Policy`
621
- * keeps it.
622
- *
623
- * @example
624
- * defaultPlugins({
625
- * contentSecurityPolicy: {
626
- * policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
627
- * },
628
- * });
629
- */
630
- function contentSecurityPolicy({ policy }) {
631
- let scriptHashes = /* @__PURE__ */ new Map();
632
- return optionPlugin("contentSecurityPolicy", {
633
- name: "content-security-policy",
634
- setup: (info) => {
635
- ({scriptHashes} = info);
636
- },
637
- middleware: async (context, next) => {
638
- const nonce = randomNonce();
639
- context.set("cspNonce", nonce);
640
- await withHeaderHook(context, next, (headers) => {
641
- const file = context.get("staticDocument");
642
- const hashes = context.get("documentScriptHashes") ?? (file == null ? void 0 : scriptHashes.get(file) ?? []);
643
- if (headers.has("Content-Security-Policy") || hashes == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
644
- const scriptSrc = hashes == null ? `'nonce-${nonce}' 'strict-dynamic'` : ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
645
- headers.set("Content-Security-Policy", oneLine(policy(scriptSrc, context)));
646
- });
647
- }
648
- });
649
- }
650
-
651
- // src/core/plugins/request-id.ts
652
- /** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */
653
- const VALID_ID = /^[\w\-=]{1,255}$/u;
654
- /** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */
655
- const TRACEPARENT = /^(?<version>[\da-f]{2})-(?<traceId>[\da-f]{32})-(?<spanId>[\da-f]{16})-[\da-f]{2}(?<rest>-.*)?$/u;
656
- /**
657
- * The trace IDs of a valid W3C `traceparent` header, else `undefined`. A
658
- * version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.
659
- *
660
- * @example
661
- * parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
662
- * // => { traceId: "4bf92f3577b34da6a3ce929d0e0e4736", spanId: "00f067aa0ba902b7" }
663
- */
664
- function parseTraceparent(header) {
665
- const groups = TRACEPARENT.exec(header?.trim() ?? "")?.groups;
666
- if (groups?.version == null || groups.traceId == null || groups.spanId == null || groups.version === "ff" || groups.version === "00" && groups.rest != null || /^0+$/u.test(groups.traceId) || /^0+$/u.test(groups.spanId)) return;
667
- return {
668
- traceId: groups.traceId,
669
- spanId: groups.spanId
670
- };
671
- }
672
- /** The log attributes for the trace IDs. */
673
- function traceAttributes({ traceId, spanId }, { datadog }) {
674
- return {
675
- trace_id: traceId,
676
- span_id: spanId,
677
- ...datadog ? {
678
- "dd.trace_id": BigInt(`0x${traceId.slice(16)}`).toString(),
679
- "dd.span_id": BigInt(`0x${spanId}`).toString()
680
- } : {}
681
- };
682
- }
683
- /**
684
- * Gives each request an ID: a valid incoming header (up to 255 word
685
- * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
686
- * every log line, and into the framework's context.
687
- *
688
- * A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log
689
- * line of the request.
690
- *
691
- * @example
692
- * const app = createServer({ plugins: [requestId()] });
693
- * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
694
- * response.headers.get("X-Request-Id"); // => "abc-123"
695
- */
696
- function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}) {
697
- return {
698
- name: "request-id",
699
- middleware: async (context, next) => {
700
- const trace = parseTraceparent(context.req.header("traceparent"));
701
- if (trace != null) context.set("logAttributes", {
702
- ...context.get("logAttributes"),
703
- ...traceAttributes(trace, { datadog: datadogTraceIds })
704
- });
705
- const incoming = context.req.header(headerName);
706
- const id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();
707
- context.set("requestId", id);
708
- await withHeaderHook(context, next, (headers) => {
709
- headers.set(headerName, id);
710
- });
711
- }
712
- };
713
- }
714
-
715
- // src/core/prefers-markdown.ts
716
- /** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */
717
- const QVALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
718
- /** The charset of each answer that a caller of {@link prefersMarkdown} sends. */
719
- const CHARSET = "utf-8";
720
- /**
721
- * The parts of `value` between each `separator`. Why a scan, not `split`: a
722
- * quoted parameter value can hold a `,` or a `;`.
723
- */
724
- function splitOutsideQuotes(value, separator) {
725
- const parts = [];
726
- let part = "";
727
- let quoted = false;
728
- let escaped = false;
729
- for (const character of value) if (!quoted && character === separator) {
730
- parts.push(part);
731
- part = "";
732
- } else {
733
- if (escaped) escaped = false;
734
- else if (quoted && character === "\\") escaped = true;
735
- else if (character === "\"") quoted = !quoted;
736
- part += character;
737
- }
738
- parts.push(part);
739
- return parts;
740
- }
741
- /** The parameters of a media range, by lowercase name, with quotes removed. */
742
- function parameterMap(parameters) {
743
- return new Map(parameters.map((parameter) => {
744
- const index = parameter.indexOf("=");
745
- const name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();
746
- const value = index === -1 ? "" : parameter.slice(index + 1).trim();
747
- return [name, /^".*"$/su.test(value) ? value.slice(1, -1).replaceAll(/\\(?<character>.)/gsu, "$<character>") : value];
748
- }));
749
- }
750
- /**
751
- * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC
752
- * 9110 default. Why a malformed `q` also counts as 1: the client still named
753
- * the media type.
754
- */
755
- function mediaRanges(accept) {
756
- return splitOutsideQuotes(accept, ",").map((entry) => {
757
- const [type = "", ...parameters] = splitOutsideQuotes(entry, ";");
758
- const parameterValues = parameterMap(parameters);
759
- const quality = parameterValues.get("q") ?? "1";
760
- return {
761
- type: type.trim().toLowerCase(),
762
- quality: QVALUE.test(quality) ? Number(quality) : 1,
763
- charset: parameterValues.get("charset")?.toLowerCase()
764
- };
765
- });
766
- }
767
- /**
768
- * The `q` of an answer of `type` in UTF-8, from the most specific ranges with
769
- * that type, or `undefined` when no range matches it. A range with
770
- * `charset=utf-8` is more specific than a range with no charset. A range with
771
- * another charset does not match. Other parameters, such as `variant`, do not
772
- * change the match.
773
- */
774
- function qualityOf(ranges, type) {
775
- const matches = ranges.filter((range) => range.type === type && (range.charset == null || range.charset === CHARSET));
776
- const withCharset = matches.filter((range) => range.charset === CHARSET);
777
- const specific = withCharset.length > 0 ? withCharset : matches;
778
- return specific.length === 0 ? void 0 : Math.max(...specific.map((range) => range.quality));
779
- }
780
- /**
781
- * Whether a request asks for markdown before HTML, per
782
- * https://acceptmarkdown.com. Use it to choose between the HTML and the
783
- * markdown answer for one URL.
784
- *
785
- * The rules:
786
- *
787
- * - Only an explicit `text/markdown` range counts for markdown. A wildcard,
788
- * such as `*\/*` or `text/*`, never selects markdown, so a browser and a
789
- * client with no `Accept` get HTML.
790
- * - `text/markdown;q=0` refuses markdown.
791
- * - The `q` of markdown must be equal to or higher than the `q` of HTML. The
792
- * `q` of HTML comes from the most specific range that matches it:
793
- * `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
794
- * the client named it.
795
- * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
796
- * than a range with no charset, and a range with another charset does not
797
- * match. Other parameters, such as `variant`, do not change the match.
798
- * - Media types and parameter names are not case-sensitive. A quoted
799
- * parameter value can hold a `,` or a `;`.
800
- *
801
- * When the answer for a URL depends on this function, send `Vary: Accept` on
802
- * both the HTML and the markdown answer. Else a shared cache can give the
803
- * markdown to a browser.
804
- *
805
- * @example
806
- * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
807
- * // => true
808
- * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
809
- * // => false
810
- */
811
- function prefersMarkdown(request) {
812
- const accept = request.headers.get("Accept");
813
- if (accept == null || !/markdown/iu.test(accept)) return false;
814
- const ranges = mediaRanges(accept);
815
- const markdown = qualityOf(ranges, "text/markdown") ?? 0;
816
- const html = qualityOf(ranges, "text/html") ?? qualityOf(ranges, "text/*") ?? qualityOf(ranges, "*/*") ?? 0;
817
- return markdown > 0 && markdown >= html;
818
- }
819
-
820
- // src/core/plugins/static.ts
821
- const IMMUTABLE = "public, max-age=31536000, immutable";
822
- /**
823
- * Serves the hashed files under `/assets/` with a one-year immutable cache.
824
- * A missing asset gets a plain 404 with `Cache-Control: no-store`, not a
825
- * rendered page. In development, the dev server serves the source modules,
826
- * the HMR client, and the CSS here instead.
827
- *
828
- * @example
829
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
907
+ * "Content-Security-Policy": "frame-ancestors 'none'",
908
+ * "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
909
+ * },
910
+ * },
911
+ * });
830
912
  */
831
- function assets() {
832
- let stage;
913
+ function securityHeaders({ headers = {} } = {}) {
914
+ const values = Object.entries({
915
+ ...DEFAULT_SECURITY_HEADERS,
916
+ ...headers
917
+ }).filter((entry) => typeof entry[1] === "string").map(([name, value]) => [name, oneLine(value)]);
833
918
  return {
834
- name: "assets",
835
- setup: (info) => {
836
- if (info.mode === "development") {
837
- stage = info.devServer;
838
- return;
839
- }
840
- const { files, contentTypes } = info;
841
- stage = async (context, next) => {
842
- const { method, path } = context.req;
843
- if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
844
- const file = await findStaticFile(files, path);
845
- if (file == null) return context.text("Not Found", 404, { "Cache-Control": "no-store" });
846
- return staticResponse(context, {
847
- files,
848
- file,
849
- headers: { "Cache-Control": IMMUTABLE },
850
- contentTypes
851
- });
852
- };
853
- },
854
- middleware: async (context, next) => stage == null ? next() : stage(context, next)
919
+ name: "security-headers",
920
+ middleware: async (context, next) => {
921
+ const isHttps = context.req.url.startsWith("https:");
922
+ await withHeaderHook(context, next, (response) => {
923
+ for (const [name, value] of values) if (name === "Content-Security-Policy") response.append(name, value);
924
+ else if (!response.has(name) && (name !== "Strict-Transport-Security" || isHttps)) response.set(name, value);
925
+ });
926
+ }
855
927
  };
856
928
  }
857
- const REVALIDATE = "public, max-age=0, must-revalidate";
858
- const ONE_HOUR = "public, max-age=3600, stale-while-revalidate=86400";
859
929
  /**
860
- * The default markdown twin of a page: `/docs/button.md` for `/docs/button`,
861
- * and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends
862
- * it to another file or to the framework, so the page's twin does not match
863
- * its answer.
930
+ * `value` on one line. Why: a header value cannot hold a line break, and a
931
+ * policy written over several lines treats each run of whitespace as one space.
864
932
  */
865
- function defaultTwinOf(path, rewritten) {
866
- return rewritten === path ? `${trimTrailingSlashes(path) || "/index"}.md` : void 0;
867
- }
868
- /** The file of the markdown twin of the request, or `undefined` when the page has none. */
869
- async function findTwin(files, context, { twinOf, rewritten }) {
870
- const twinPath = twinOf?.(context.req.path, rewritten, context);
871
- const file = twinPath == null ? void 0 : await findStaticFile(files, twinPath);
872
- return twinPath == null || file == null ? void 0 : {
873
- path: twinPath,
874
- file
875
- };
933
+ function oneLine(value) {
934
+ return value.replaceAll(/\s+/gu, " ").trim();
876
935
  }
877
- /** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */
878
- function varyOnAccept(context) {
879
- const vary = withVary(context.res.headers.get("Vary"), "Accept");
880
- if (vary != null) writableHeaders(context).set("Vary", vary);
936
+ /** A new random nonce: 16 bytes in base64. */
937
+ function randomNonce() {
938
+ return btoa(String.fromCodePoint(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
881
939
  }
882
940
  /**
883
- * The percent-encoded URL path for a decoded path, so it holds no space,
884
- * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a
885
- * newline, which a file name can hold.
941
+ * Sets the `Content-Security-Policy` from `policy` on each HTML document. The
942
+ * policy trusts the document's scripts, and only them:
943
+ *
944
+ * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce
945
+ * for each request. The app reads the nonce from `requestContext()` and
946
+ * gives it to the framework's render, so each inline script gets it.
947
+ * - A prerendered document gets `'self'` and the hash of each of its inline
948
+ * scripts, which the Vite plugin records. Its file has one nonce for every
949
+ * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,
950
+ * unlike a nonce, does not carry to the imports of an inline module script.
951
+ *
952
+ * The `contentSecurityPolicy` option of `defaultPlugins()` takes these
953
+ * options, and puts the plugin before the static stages, so it sees the
954
+ * prerendered documents. A response that has a `Content-Security-Policy`
955
+ * keeps it.
956
+ *
957
+ * @example
958
+ * defaultPlugins({
959
+ * contentSecurityPolicy: {
960
+ * policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
961
+ * },
962
+ * });
886
963
  */
887
- function urlPath(path) {
888
- return new URL(path.replaceAll(/[\t\n\r]/gu, (character) => encodeURIComponent(character)), "http://localhost").pathname;
889
- }
890
- /** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */
891
- function linkToTwin(context, twinPath) {
892
- writableHeaders(context).append("Link", `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`);
964
+ function contentSecurityPolicy({ policy }) {
965
+ let scriptHashes = /* @__PURE__ */ new Map();
966
+ return optionPlugin("contentSecurityPolicy", {
967
+ name: "content-security-policy",
968
+ setup: (info) => {
969
+ ({scriptHashes} = info);
970
+ },
971
+ middleware: async (context, next) => {
972
+ const nonce = randomNonce();
973
+ context.set("cspNonce", nonce);
974
+ await withHeaderHook(context, next, (headers) => {
975
+ const file = context.get("staticDocument");
976
+ const hashes = context.get("documentScriptHashes") ?? (file == null ? void 0 : scriptHashes.get(file) ?? []);
977
+ if (headers.has("Content-Security-Policy") || hashes == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
978
+ const scriptSrc = hashes == null ? `'nonce-${nonce}' 'strict-dynamic'` : ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
979
+ headers.set("Content-Security-Policy", oneLine(policy(scriptSrc, context)));
980
+ });
981
+ }
982
+ });
893
983
  }
984
+
985
+ // src/core/plugins/request-id.ts
986
+ /** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */
987
+ const VALID_ID = /^[\w\-=]{1,255}$/u;
988
+ /** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */
989
+ const TRACEPARENT = /^(?<version>[\da-f]{2})-(?<traceId>[\da-f]{32})-(?<spanId>[\da-f]{16})-[\da-f]{2}(?<rest>-.*)?$/u;
894
990
  /**
895
- * The development stage of `markdownTwins`. The client build has no twins
896
- * then, so a request that prefers markdown gets the framework's answer for
897
- * the twin's URL: the route that prerenders the twin. A twin path that is not
898
- * in `prerenderedPaths`, an error, or an answer that is not markdown sends the
899
- * request on for the HTML.
991
+ * The trace IDs of a valid W3C `traceparent` header, else `undefined`. A
992
+ * version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.
993
+ *
994
+ * @example
995
+ * parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
996
+ * // => { traceId: "4bf92f3577b34da6a3ce929d0e0e4736", spanId: "00f067aa0ba902b7" }
900
997
  */
901
- function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
902
- return async (context, next) => {
903
- const { method, path } = context.req;
904
- const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.(path, context) ?? path, context) : void 0;
905
- if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
906
- const url = new URL(context.req.url);
907
- url.pathname = urlPath(twinPath);
908
- if (getPath(new Request(url)) !== twinPath) return next();
909
- const { headers, signal } = context.req.raw;
910
- const twin = new Request(url, {
911
- method,
912
- headers,
913
- signal
914
- });
915
- const response = await context.env.framework.fetch(twin, context);
916
- const markdown = response.headers.get("Content-Type")?.toLowerCase().startsWith("text/markdown") === true;
917
- if (response.status !== 304 && !(response.ok && markdown)) {
918
- await response.body?.cancel();
919
- return next();
920
- }
921
- context.res = response;
922
- varyOnAccept(context);
998
+ function parseTraceparent(header) {
999
+ const groups = TRACEPARENT.exec(header?.trim() ?? "")?.groups;
1000
+ if (groups?.version == null || groups.traceId == null || groups.spanId == null || groups.version === "ff" || groups.version === "00" && groups.rest != null || /^0+$/u.test(groups.traceId) || /^0+$/u.test(groups.spanId)) return;
1001
+ return {
1002
+ traceId: groups.traceId,
1003
+ spanId: groups.spanId
923
1004
  };
924
1005
  }
925
- /** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */
926
- function twinOfOption(markdownTwins) {
927
- if (markdownTwins === true) return defaultTwinOf;
928
- if (markdownTwins == null || markdownTwins === false) return;
929
- const { twinOf } = markdownTwins;
930
- return (path, _rewritten, context) => twinOf(path, context);
1006
+ /** The log attributes for the trace IDs. */
1007
+ function traceAttributes({ traceId, spanId }, { datadog }) {
1008
+ return {
1009
+ trace_id: traceId,
1010
+ span_id: spanId,
1011
+ ...datadog ? {
1012
+ "dd.trace_id": BigInt(`0x${traceId.slice(16)}`).toString(),
1013
+ "dd.span_id": BigInt(`0x${spanId}`).toString()
1014
+ } : {}
1015
+ };
931
1016
  }
932
1017
  /**
933
- * Serves the client build: prerendered pages at their own URL with a 200,
934
- * plus every other file in it. It sends no redirect. The `trailingSlash`
935
- * plugin does. Each response gets
936
- * the headers its loader sent at build time (the `appServer` Vite plugin
937
- * captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304
938
- * for a matching `If-None-Match`. A GET with one byte range gets a 206. A path
939
- * with no file goes on to the framework. In development, only
940
- * `markdownTwins` runs.
1018
+ * Gives each request an ID: a valid incoming header (up to 255 word
1019
+ * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
1020
+ * every log line, and into the framework's context.
941
1021
  *
942
- * At startup, it warns about each prerendered path that has no file.
1022
+ * A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log
1023
+ * line of the request.
943
1024
  *
944
1025
  * @example
945
- * prerendered({
946
- * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
947
- * });
1026
+ * const app = createServer({ plugins: [requestId()] });
1027
+ * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
1028
+ * response.headers.get("X-Request-Id"); // => "abc-123"
948
1029
  */
949
- function prerendered(options = {}) {
950
- let stage;
1030
+ function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}) {
951
1031
  return {
952
- name: "prerendered",
953
- setup: async (info) => {
954
- const twinOf = twinOfOption(options.markdownTwins);
955
- if (info.mode === "development") {
956
- const paths = info.prerenderedPaths;
957
- stage = twinOf == null ? void 0 : developmentTwins(twinOf, options, paths == null ? void 0 : new Set(paths));
958
- return;
959
- }
960
- const { files, contentTypes, capturedHeaders } = info;
961
- const missing = [];
962
- for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
963
- if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
964
- const cacheControl = options.cacheControl ?? ((path) => {
965
- const type = contentType(path, contentTypes);
966
- return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
1032
+ name: "request-id",
1033
+ middleware: async (context, next) => {
1034
+ const trace = parseTraceparent(context.req.header("traceparent"));
1035
+ if (trace != null) context.set("logAttributes", {
1036
+ ...context.get("logAttributes"),
1037
+ ...traceAttributes(trace, { datadog: datadogTraceIds })
967
1038
  });
968
- const serve = async (context, path, file) => {
969
- const value = cacheControl(file.path);
970
- const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
971
- for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.(path, context)]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
972
- return staticResponse(context, {
973
- files,
974
- file,
975
- headers: Object.fromEntries(headers),
976
- contentTypes
977
- });
978
- };
979
- stage = async (context, next) => {
980
- const { method } = context.req;
981
- if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
982
- const rewritten = options.rewrite?.(context.req.path, context) ?? context.req.path;
983
- const twin = await findTwin(files, context, {
984
- twinOf,
985
- rewritten
986
- });
987
- const preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : void 0;
988
- const path = preferred?.path ?? rewritten;
989
- const file = preferred?.file ?? await findStaticFile(files, path);
990
- if (file == null) await next();
991
- else context.res = await serve(context, path, file);
992
- if (twin != null) varyOnAccept(context);
993
- if (twin != null && preferred == null) linkToTwin(context, twin.path);
994
- };
995
- },
996
- middleware: async (context, next) => stage == null ? next() : stage(context, next)
1039
+ const incoming = context.req.header(headerName);
1040
+ const id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();
1041
+ context.set("requestId", id);
1042
+ await withHeaderHook(context, next, (headers) => {
1043
+ headers.set(headerName, id);
1044
+ });
1045
+ }
997
1046
  };
998
1047
  }
999
1048
 
@@ -1195,7 +1244,7 @@ function defaultPlugins(options = {}) {
1195
1244
  streamingCompress(),
1196
1245
  ...options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)],
1197
1246
  ...maxBytes === false ? [] : [bodyLimit({ maxBytes })],
1198
- ...options.noindex === true ? [noindex()] : [],
1247
+ ...options.noindex == null || options.noindex === false ? [] : [options.noindex === true ? noindex() : noindex(options.noindex)],
1199
1248
  ...options.buildId === false ? [] : [buildId(options.buildId)],
1200
1249
  ...options.contentSecurityPolicy == null ? [] : [contentSecurityPolicy(options.contentSecurityPolicy)],
1201
1250
  ...options.env == null ? [] : [options.env],
@@ -1333,6 +1382,7 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
1333
1382
  let stoppingPlugins;
1334
1383
  const internals = {
1335
1384
  logger,
1385
+ presenceHeaders: presenceHeadersOf(plugins),
1336
1386
  setRequestStore: (store) => {
1337
1387
  requestStore = store;
1338
1388
  },
@@ -1415,5 +1465,5 @@ function serverInternals(app) {
1415
1465
  return appInternals.get(app);
1416
1466
  }
1417
1467
 
1418
- export { abortShutdownSignal as _, streamingCompress as a, accessLog as b, prefersMarkdown as c, securityHeaders as d, redirects as f, health as g, noindex as h, withForwardedProto as i, requestId as l, privateDocuments as m, defaultPlugins as n, assets as o, trailingSlash as p, serverInternals as r, prerendered as s, createServer as t, contentSecurityPolicy as u, shutdownSignal as v, bodyLimit as y };
1419
- //# sourceMappingURL=create-server-D0De6R7Q.js.map
1468
+ export { assets as _, streamingCompress as a, prefersMarkdown as b, securityHeaders as c, noindex as d, health as f, accessLog as g, bodyLimit as h, withForwardedProto as i, redirects as l, shutdownSignal as m, defaultPlugins as n, requestId as o, abortShutdownSignal as p, serverInternals as r, contentSecurityPolicy as s, createServer as t, privateDocuments as u, prerendered as v, trailingSlash as y };
1469
+ //# sourceMappingURL=create-server-jMl2ltHD.js.map