@guren/server 2.14.0 → 2.15.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 (38) hide show
  1. package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
  2. package/dist/agent/AgentApprovalRequested.d.ts +59 -0
  3. package/dist/agent/approval.d.ts +295 -0
  4. package/dist/agent/audit-emitter.d.ts +64 -0
  5. package/dist/agent/audit.d.ts +103 -0
  6. package/dist/agent/dispatch.d.ts +50 -8
  7. package/dist/agent/meta-tools.d.ts +62 -0
  8. package/dist/agent/public.d.ts +33 -0
  9. package/dist/agent/public.js +2 -0
  10. package/dist/auth/index.js +1 -1
  11. package/dist/auth/password/DefaultHasher.d.ts +18 -5
  12. package/dist/auth/password/PasswordHasher.d.ts +15 -0
  13. package/dist/auth/password/hash-format.d.ts +19 -0
  14. package/dist/{auth-BSUc14CD.js → auth-DkYoAPVn.js} +121 -32
  15. package/dist/broadcasting/index.js +1 -1
  16. package/dist/{broadcasting-BxU-LIfF.js → broadcasting-BwodCA4q.js} +1 -1
  17. package/dist/container/bindings.d.ts +19 -0
  18. package/dist/dispatch-erOS9epZ.js +285 -0
  19. package/dist/encryption/index.js +2 -2
  20. package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
  21. package/dist/http/dev-assets.d.ts +16 -0
  22. package/dist/http/public-assets.d.ts +10 -0
  23. package/dist/http/request.d.ts +88 -1
  24. package/dist/http/static-documents.d.ts +31 -0
  25. package/dist/index.d.ts +11 -3
  26. package/dist/index.js +586 -333
  27. package/dist/internal/request.d.ts +15 -9
  28. package/dist/internal/request.js +2 -2
  29. package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
  30. package/dist/logging/daily-file-path.d.ts +24 -0
  31. package/dist/logging/index.d.ts +1 -0
  32. package/dist/logging/index.js +2 -2
  33. package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
  34. package/dist/mvc/Controller.d.ts +0 -26
  35. package/dist/{request-CRVuIiQr.js → request-CVQwpu2J.js} +56 -5
  36. package/dist/runtime/index.js +90 -14
  37. package/dist/{vite-manifest-BGfWbPYp.js → vite-manifest-w_RSOvQW.js} +1 -1
  38. package/package.json +6 -2
@@ -1,19 +1,25 @@
1
1
  /**
2
- * The one request-body parsing rule: which content types are read, how a
3
- * repeated form field collapses, and what an unreadable body falls back to.
2
+ * The one set of request-reading rules: which content types are read, how a
3
+ * repeated form field collapses, what an unreadable body falls back to, how a
4
+ * multipart upload is pulled off the request, and how repeated query
5
+ * parameters flatten for a validation schema.
4
6
  *
5
- * `@guren/testing`'s controller mock reads it through this subpath so a
6
- * mocked controller and a real one cannot disagree about a body. The mock
7
+ * `@guren/testing`'s controller mock reads them through this subpath so a
8
+ * mocked controller and a real one cannot disagree about a request. The mock
7
9
  * holds a `Request` rather than a Hono context, so it adapts — it wraps the
8
10
  * request in a `HonoRequest` and calls straight into these — rather than
9
- * reimplementing the decision. A second copy is how the two came to disagree
11
+ * reimplementing the decisions. A second copy is how the two came to disagree
10
12
  * on an uppercase media type, on a `;`-parameterized one, and on a repeated
11
13
  * `field[]`.
12
14
  *
15
+ * `parseRequestUploads` is here for the same reason. It is deliberately not
16
+ * `parseRequestBody` under another name — its own doc comment owns why, and is
17
+ * the one place that argument is written out.
18
+ *
13
19
  * Internal by the rules in `contributing/api-stability.md` — reachable only
14
20
  * through a deep import under `internal/`, never re-exported from an index.
15
- * `parseRequestPayload` beside it *is* public and stays exported from the
16
- * package root; this subpath exists for the two that are not.
21
+ * `parseRequestPayload` beside them *is* public and stays exported from the
22
+ * package root; this subpath exists for the ones that are not.
17
23
  */
18
- export { parseRequestBody, asRecord } from '../http/request.js';
19
- export type { RequestBodyContext } from '../http/request.js';
24
+ export { parseRequestBody, parseRequestUploads, asRecord, flattenRequestQueries, } from '../http/request.js';
25
+ export type { RequestBodyContext, RequestQueryContext, RequestUploads, RequestUploadsContext, } from '../http/request.js';
@@ -1,2 +1,2 @@
1
- import { i as parseRequestBody, t as asRecord } from "../request-CRVuIiQr.js";
2
- export { asRecord, parseRequestBody };
1
+ import { i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, t as asRecord } from "../request-CVQwpu2J.js";
2
+ export { asRecord, flattenRequestQueries, parseRequestBody, parseRequestUploads };
@@ -11,8 +11,6 @@ export declare class DailyFileChannel implements LogChannel {
11
11
  log(entry: LogEntry): void;
12
12
  private write;
13
13
  private rotate;
14
- private getFilePath;
15
- private getDateString;
16
14
  private ensureDirectory;
17
15
  private cleanup;
18
16
  private format;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The `YYYY-MM-DD` stamp a file rotated at `date` carries.
3
+ *
4
+ * UTC, from the ISO form, because the rotation boundary has to be the same
5
+ * instant for every process appending to the same directory — a fleet split
6
+ * across time zones would otherwise write two different files for one day and
7
+ * roll over at as many moments as it has zones.
8
+ */
9
+ export declare function dailyFileDateStamp(date: Date): string;
10
+ /** The dated file a base path rotates to on `date`. */
11
+ export declare function dailyFilePath(basePath: string, date: Date): string;
12
+ /**
13
+ * The date stamp of `fileName` if it is one of `basePath`'s dated files, and
14
+ * `null` if it is anything else in the same directory.
15
+ *
16
+ * The inverse of {@link dailyFilePath}, and the reason a caller listing a
17
+ * directory does not need to know the shape it is matching. The base path's
18
+ * own name and extension are escaped before they enter the pattern: a log
19
+ * called `app.v1.log` parses to the name `app.v1`, whose dots would otherwise
20
+ * match any character and let a *different* app's files into another's
21
+ * rotation set — which, for the cleanup that consumes this, means deleting
22
+ * them.
23
+ */
24
+ export declare function matchDailyFileDate(basePath: string, fileName: string): string | null;
@@ -3,6 +3,7 @@ export { LOG_LEVEL_PRIORITY } from './types.js';
3
3
  export { Logger, filterSensitiveData } from './Logger.js';
4
4
  export type { LoggerOptions } from './Logger.js';
5
5
  export { LogManager, createLogManager, setLogManager, getLogManager, } from './LogManager.js';
6
+ export { dailyFileDateStamp, dailyFilePath, matchDailyFileDate } from './daily-file-path.js';
6
7
  export { ConsoleChannel } from './channels/ConsoleChannel.js';
7
8
  export { FileChannel } from './channels/FileChannel.js';
8
9
  export { DailyFileChannel } from './channels/DailyFileChannel.js';
@@ -1,2 +1,2 @@
1
- import { a as DailyFileChannel, c as Logger, i as setLogManager, l as filterSensitiveData, n as createLogManager, o as FileChannel, r as getLogManager, s as ConsoleChannel, t as LogManager, u as LOG_LEVEL_PRIORITY } from "../logging-CPaRMuPP.js";
2
- export { ConsoleChannel, DailyFileChannel, FileChannel, LOG_LEVEL_PRIORITY, LogManager, Logger, createLogManager, filterSensitiveData, getLogManager, setLogManager };
1
+ import { a as DailyFileChannel, c as matchDailyFileDate, d as Logger, f as filterSensitiveData, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, p as LOG_LEVEL_PRIORITY, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "../logging-B-kngi3q.js";
2
+ export { ConsoleChannel, DailyFileChannel, FileChannel, LOG_LEVEL_PRIORITY, LogManager, Logger, createLogManager, dailyFileDateStamp, dailyFilePath, filterSensitiveData, getLogManager, matchDailyFileDate, setLogManager };
@@ -268,6 +268,59 @@ var FileChannel = class {
268
268
  close() {}
269
269
  };
270
270
  //#endregion
271
+ //#region src/logging/daily-file-path.ts
272
+ /**
273
+ * The one rule for what a daily-rotated log file is called: `dir/name-YYYY-MM-DD.ext`.
274
+ *
275
+ * {@link DailyFileChannel} names the file it appends to through this module,
276
+ * and the agent audit reader behind `guren tool:log` decides which files to
277
+ * read through the same one. A second copy of the rule is how a writer and a
278
+ * reader drift apart, and the drift is silent in the worst direction: the
279
+ * writer keeps appending, the reader stops recognising, and what the operator
280
+ * sees is an empty audit trail rather than an error.
281
+ *
282
+ * Naming only — nothing here touches the filesystem. The reader has to tell
283
+ * "this directory does not exist" apart from "this directory could not be
284
+ * read", and a helper that swallowed the difference on its behalf would put
285
+ * that distinction back out of reach.
286
+ */
287
+ /**
288
+ * The `YYYY-MM-DD` stamp a file rotated at `date` carries.
289
+ *
290
+ * UTC, from the ISO form, because the rotation boundary has to be the same
291
+ * instant for every process appending to the same directory — a fleet split
292
+ * across time zones would otherwise write two different files for one day and
293
+ * roll over at as many moments as it has zones.
294
+ */
295
+ function dailyFileDateStamp(date) {
296
+ return date.toISOString().slice(0, 10);
297
+ }
298
+ /** The dated file a base path rotates to on `date`. */
299
+ function dailyFilePath(basePath, date) {
300
+ const { dir, name, ext } = path$1.parse(basePath);
301
+ return path$1.join(dir, `${name}-${dailyFileDateStamp(date)}${ext}`);
302
+ }
303
+ /**
304
+ * The date stamp of `fileName` if it is one of `basePath`'s dated files, and
305
+ * `null` if it is anything else in the same directory.
306
+ *
307
+ * The inverse of {@link dailyFilePath}, and the reason a caller listing a
308
+ * directory does not need to know the shape it is matching. The base path's
309
+ * own name and extension are escaped before they enter the pattern: a log
310
+ * called `app.v1.log` parses to the name `app.v1`, whose dots would otherwise
311
+ * match any character and let a *different* app's files into another's
312
+ * rotation set — which, for the cleanup that consumes this, means deleting
313
+ * them.
314
+ */
315
+ function matchDailyFileDate(basePath, fileName) {
316
+ const { name, ext } = path$1.parse(basePath);
317
+ return new RegExp(`^${escapeRegExp(name)}-(\\d{4}-\\d{2}-\\d{2})${escapeRegExp(ext)}$`, "u").exec(fileName)?.[1] ?? null;
318
+ }
319
+ /** Every character with meaning inside a regular expression, made literal. */
320
+ function escapeRegExp(text) {
321
+ return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
322
+ }
323
+ //#endregion
271
324
  //#region src/logging/channels/DailyFileChannel.ts
272
325
  /**
273
326
  * Daily rotating file log channel.
@@ -287,43 +340,33 @@ var DailyFileChannel = class {
287
340
  }
288
341
  log(entry) {
289
342
  if (LOG_LEVEL_PRIORITY[entry.level] > this.minLevel) return;
290
- const dateStr = this.getDateString(entry.timestamp);
291
- if (this.currentDate !== dateStr) this.rotate(dateStr);
343
+ const dateStr = dailyFileDateStamp(entry.timestamp);
344
+ if (this.currentDate !== dateStr) this.rotate(entry.timestamp, dateStr);
292
345
  const line = this.format(entry) + "\n";
293
346
  this.write(line);
294
347
  }
295
348
  write(data) {
296
349
  if (this.currentFilePath) fs.appendFileSync(this.currentFilePath, data);
297
350
  }
298
- rotate(dateStr) {
351
+ rotate(date, dateStr) {
299
352
  this.currentDate = dateStr;
300
- this.currentFilePath = this.getFilePath(dateStr);
353
+ this.currentFilePath = dailyFilePath(this.config.path, date);
301
354
  this.ensureDirectory(this.currentFilePath);
302
355
  this.cleanup();
303
356
  }
304
- getFilePath(dateStr) {
305
- const { dir, name, ext } = path$1.parse(this.config.path);
306
- return path$1.join(dir, `${name}-${dateStr}${ext}`);
307
- }
308
- getDateString(date) {
309
- return date.toISOString().split("T")[0];
310
- }
311
357
  ensureDirectory(filePath) {
312
358
  const dir = path$1.dirname(filePath);
313
359
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
314
360
  }
315
361
  cleanup() {
316
- const { dir, name, ext } = path$1.parse(this.config.path);
362
+ const dir = path$1.dirname(this.config.path);
317
363
  if (!fs.existsSync(dir)) return;
318
364
  const files = fs.readdirSync(dir);
319
- const pattern = new RegExp(`^${name}-(\\d{4}-\\d{2}-\\d{2})${ext.replace(".", "\\.")}$`);
320
365
  const cutoff = /* @__PURE__ */ new Date();
321
366
  cutoff.setDate(cutoff.getDate() - (this.config.days ?? 14));
322
367
  for (const file of files) {
323
- const match = file.match(pattern);
324
- if (match) {
325
- if (new Date(match[1]) < cutoff) fs.unlinkSync(path$1.join(dir, file));
326
- }
368
+ const stamp = matchDailyFileDate(this.config.path, file);
369
+ if (stamp !== null && new Date(stamp) < cutoff) fs.unlinkSync(path$1.join(dir, file));
327
370
  }
328
371
  }
329
372
  format(entry) {
@@ -515,4 +558,4 @@ function getLogManager() {
515
558
  return globalLogManager;
516
559
  }
517
560
  //#endregion
518
- export { DailyFileChannel as a, Logger as c, setLogManager as i, filterSensitiveData as l, createLogManager as n, FileChannel as o, getLogManager as r, ConsoleChannel as s, LogManager as t, LOG_LEVEL_PRIORITY as u };
561
+ export { DailyFileChannel as a, matchDailyFileDate as c, Logger as d, filterSensitiveData as f, setLogManager as i, FileChannel as l, createLogManager as n, dailyFileDateStamp as o, LOG_LEVEL_PRIORITY as p, getLogManager as r, dailyFilePath as s, LogManager as t, ConsoleChannel as u };
@@ -169,32 +169,6 @@ export declare class Controller {
169
169
  * Returns an empty array when none were uploaded.
170
170
  */
171
171
  protected files(name: string): Promise<File[]>;
172
- /**
173
- * The one multipart read behind {@link file} and {@link files}, guarded so a
174
- * body the parser cannot decode carries no files rather than crashing the
175
- * request: it reads as `{}`, which is the same answer both helpers already
176
- * give for a field that is simply absent — `null` and `[]`. Left to throw,
177
- * the parser's `TypeError` escaped as a 500 reporting the exception and a
178
- * stack, the defect {@link parseRequestBody} fixes for the validation paths.
179
- *
180
- * Deliberately *not* routed through `parseRequestBody()`, which looks like
181
- * the same rule and is not: it parses without `{ all: true }` and flattens a
182
- * repeated field to its first value, so sharing it would silently reduce
183
- * `files()` to one file per field. `{ all: true }` is the contract here, and
184
- * a malformed-body test cannot see its loss — hence the separate helper.
185
- *
186
- * try/catch rather than `.catch()`, for the reason given on the shared
187
- * fallback: `parseBody` may throw synchronously as well as reject, and only
188
- * one of those two shapes reaches a `.catch()`.
189
- *
190
- * It fails open in one direction, deliberately and for the same reason
191
- * {@link parseRequestBody} does: a body already consumed upstream reads as
192
- * "no upload" rather than throwing, so a middleware-ordering bug loses the
193
- * 500 that used to announce it. Telling that apart from a client's malformed
194
- * body means matching runtime-specific error codes, which answer differently
195
- * on Bun, Node and Workers.
196
- */
197
- private parseUploads;
198
172
  protected get auth(): AuthContext;
199
173
  protected make<K extends keyof ServiceBindings>(key: K): ServiceBindings[K];
200
174
  protected make<T>(key: string): T;
@@ -37,6 +37,51 @@ async function parseRequestBody(ctx) {
37
37
  return {};
38
38
  }
39
39
  /**
40
+ * The one multipart read behind `Controller.file()` and `Controller.files()`,
41
+ * guarded so a body the parser cannot decode carries no files rather than
42
+ * crashing the request: it reads as `{}`, which is the same answer both helpers
43
+ * already give for a field that is simply absent — `null` and `[]`. Left to
44
+ * throw, the parser's `TypeError` escaped as a 500 reporting the exception and
45
+ * a stack, the defect {@link parseRequestBody} fixes for the validation paths.
46
+ *
47
+ * Deliberately *not* routed through {@link parseRequestBody}, which looks like
48
+ * the same rule and is not: it parses without `{ all: true }` and flattens a
49
+ * repeated field to its first value, so sharing it would silently reduce
50
+ * `files()` to one file per field. `{ all: true }` is the contract here, and a
51
+ * malformed-body test cannot see its loss — hence the separate function.
52
+ *
53
+ * There is no media-type gate, deliberately: Hono decides the media type inside
54
+ * `parseBody()`, having lowercased it first. A caller that gates before calling
55
+ * — or that reads uploads through `Request.formData()`, whose handling of the
56
+ * media type is not Hono's — answers `null` for an uppercase
57
+ * `MULTIPART/FORM-DATA` body this returns the file for.
58
+ *
59
+ * That was measured on Bun 1.3.14, and the host half of it has already moved:
60
+ * Bun 1.4.0 accepts the same header `1.3.14` rejects, and Node always did. The
61
+ * divergence is therefore a property of *where the media type is decided*, not
62
+ * of any one runtime — which is the argument for deciding it in one place, and
63
+ * why `@guren/testing`'s controller mock reaches this function rather than
64
+ * restating it.
65
+ *
66
+ * try/catch rather than `.catch()`, for the reason given on the shared
67
+ * fallback: `parseBody` may throw synchronously as well as reject, and only one
68
+ * of those two shapes reaches a `.catch()`.
69
+ *
70
+ * It fails open in one direction, deliberately and for the same reason
71
+ * {@link parseRequestBody} does: a body already consumed upstream reads as
72
+ * "no upload" rather than throwing, so a middleware-ordering bug loses the 500
73
+ * that used to announce it. Telling that apart from a client's malformed body
74
+ * means matching runtime-specific error codes, which answer differently on Bun,
75
+ * Node and Workers.
76
+ */
77
+ async function parseRequestUploads(ctx) {
78
+ try {
79
+ return await ctx.req.parseBody({ all: true });
80
+ } catch {
81
+ return {};
82
+ }
83
+ }
84
+ /**
40
85
  * The record-shaped view of {@link parseRequestBody}, for callers that read the
41
86
  * payload field by field (`payload.channel`, per-field validation rules,
42
87
  * `Controller.input()`/`only()`/`except()`/`has()`). A body that is not a plain
@@ -55,12 +100,18 @@ function asRecord(body) {
55
100
  * single occurrences as plain strings (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`,
56
101
  * `?page=2` → `{ page: '2' }`). Use this instead of `ctx.req.query()` when
57
102
  * feeding query data into validation schemas.
103
+ *
104
+ * Materialized with `Object.fromEntries`, never by assigning into an object
105
+ * literal — the same rule, and for the same reason, as the form branch of
106
+ * {@link parseRequestBody} above. Query keys are attacker-controlled, and
107
+ * `flat['__proto__'] = …` hits `Object.prototype`'s inherited setter instead
108
+ * of defining a field: `?__proto__=one` silently vanished before reaching the
109
+ * schema, and `?__proto__=one&__proto__=two` set the returned record's own
110
+ * prototype to that array. Hono hands over a null-prototype object, so the
111
+ * key arrives here intact; only this last step could lose it.
58
112
  */
59
113
  function flattenRequestQueries(ctx) {
60
- const queries = ctx.req.queries();
61
- const flat = {};
62
- for (const [key, values] of Object.entries(queries)) flat[key] = values.length === 1 ? values[0] : values;
63
- return flat;
114
+ return Object.fromEntries(Object.entries(ctx.req.queries()).map(([key, values]) => [key, values.length === 1 ? values[0] : values]));
64
115
  }
65
116
  /**
66
117
  * Converts a Zod-style validation error into a flat record usable by forms.
@@ -75,4 +126,4 @@ function formatValidationErrors(error, fallbackMessage = "The provided data is i
75
126
  return errors;
76
127
  }
77
128
  //#endregion
78
- export { parseRequestPayload as a, parseRequestBody as i, flattenRequestQueries as n, formatValidationErrors as r, asRecord as t };
129
+ export { parseRequestPayload as a, parseRequestBody as i, flattenRequestQueries as n, parseRequestUploads as o, formatValidationErrors as r, asRecord as t };
@@ -1,11 +1,12 @@
1
1
  import { n as trimTrailingSlashes } from "../trim-slashes-ZJ_VsY5s.js";
2
- import { n as hash } from "../Hash-CzrwKeDp.js";
3
- import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-BGfWbPYp.js";
2
+ import { n as hash } from "../Hash-C8aejmi8.js";
3
+ import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-w_RSOvQW.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { realpath } from "node:fs/promises";
6
6
  import { dirname, extname, join, resolve, sep } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { serveStatic } from "hono/bun";
9
+ import { getMimeType } from "hono/utils/mime";
9
10
  //#region src/support/contained-path.ts
10
11
  /**
11
12
  * Is `candidate` a path strictly below `root`, judged lexically?
@@ -48,6 +49,69 @@ async function canonicalize(path) {
48
49
  }
49
50
  }
50
51
  //#endregion
52
+ //#region src/http/static-documents.ts
53
+ /**
54
+ * The one rule for "a browser would render this as a document in the serving
55
+ * origin". A file the app merely *stores* under `public/` — an upload keeping
56
+ * its original extension, most of all — otherwise becomes script running as
57
+ * the app: same cookies, same session, same CSRF token.
58
+ *
59
+ * A denylist rather than the attachments engine's `INLINE_CONTENT_TYPES`
60
+ * allowlist, because these mounts also serve the app's own build output. An
61
+ * allowlist here would have to enumerate every asset type a project can ship,
62
+ * and would break a deployment the first time it shipped one that was missed.
63
+ * Everything absent from this set — scripts, stylesheets, fonts, images,
64
+ * media, PDFs — is inert when navigated to, and stays inline.
65
+ */
66
+ const DOCUMENT_CONTENT_TYPES = /* @__PURE__ */ new Set([
67
+ "text/html",
68
+ "text/xml",
69
+ "application/xml",
70
+ "text/xsl"
71
+ ]);
72
+ /**
73
+ * Judged on the media type alone. Both inputs this module reads are
74
+ * parameterised — Hono's `getMimeType` returns `text/html; charset=utf-8`, and
75
+ * so does a hand-written `contentTypeMap` entry — so comparing the header
76
+ * verbatim is precisely how the check stops matching while still looking
77
+ * present.
78
+ */
79
+ function rendersAsDocument(contentType) {
80
+ if (!contentType) return false;
81
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
82
+ return DOCUMENT_CONTENT_TYPES.has(mediaType) || mediaType.endsWith("+xml");
83
+ }
84
+ /**
85
+ * Neutralizes a served document by turning it into a download.
86
+ *
87
+ * `Content-Disposition: attachment` is honoured for navigations and ignored
88
+ * for subresource loads, which is what makes it usable on a general asset
89
+ * route: `<img src="/logo.svg">`, `<link rel="icon">` and CSS `url()` keep
90
+ * working unchanged, while `/logo.svg` opened directly is downloaded instead
91
+ * of rendered. An `<iframe>` or `<object>` *is* a navigation, so an SVG or
92
+ * HTML page embedded that way stops rendering — which is the same mechanism
93
+ * as the fix, not an exception to it. `nosniff` rides along for the types a
94
+ * browser would otherwise promote on its own.
95
+ */
96
+ function applyDocumentDisposition(headers, contentType) {
97
+ if (!rendersAsDocument(contentType)) return;
98
+ headers.set("Content-Disposition", "attachment");
99
+ headers.set("X-Content-Type-Options", "nosniff");
100
+ }
101
+ /**
102
+ * The {@link import('hono/bun').serveStatic} form of
103
+ * {@link applyDocumentDisposition}, for use as its `onFound` hook.
104
+ *
105
+ * Keyed on the same `getMimeType(path)` the middleware itself used a line
106
+ * earlier to set `Content-Type`, rather than on the extension: the two agree
107
+ * by construction only while they read the same function.
108
+ */
109
+ function guardStaticDocument(path, ctx) {
110
+ if (!rendersAsDocument(getMimeType(path))) return;
111
+ ctx.header("Content-Disposition", "attachment");
112
+ ctx.header("X-Content-Type-Options", "nosniff");
113
+ }
114
+ //#endregion
51
115
  //#region src/http/public-assets.ts
52
116
  const DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
53
117
  const DEFAULT_EXTENSIONS = [
@@ -84,7 +148,7 @@ function registerRootPublicAssets(app, publicDir, config) {
84
148
  console.warn("Root public asset serving is only available when running on Bun; skipping registration.");
85
149
  return;
86
150
  }
87
- const { extensions, cacheControlHeader, routePrefix, contentTypeMap } = normalized;
151
+ const { extensions, cacheControlHeader, routePrefix, contentTypeMap, inlineDocuments } = normalized;
88
152
  const normalizedPrefix = routePrefix ? trimTrailingSlashes(routePrefix) || "/" : void 0;
89
153
  app.hono.use(async (ctx, next) => {
90
154
  const path = ctx.req.path;
@@ -99,10 +163,12 @@ function registerRootPublicAssets(app, publicDir, config) {
99
163
  const file = Bun.file(candidatePath);
100
164
  if (!await file.exists()) return next();
101
165
  if (!await isRealPathWithin(publicDir, candidatePath)) return next();
166
+ const contentType = contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream";
102
167
  const headers = new Headers({
103
168
  "Cache-Control": cacheControlHeader,
104
- "Content-Type": contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream"
169
+ "Content-Type": contentType
105
170
  });
171
+ if (!inlineDocuments) applyDocumentDisposition(headers, contentType);
106
172
  return new Response(file, { headers });
107
173
  });
108
174
  }
@@ -110,14 +176,16 @@ function normalizeConfig(config) {
110
176
  if (config === false) return;
111
177
  if (config === void 0 || config === true) return {
112
178
  extensions: new Set(DEFAULT_EXTENSIONS),
113
- cacheControlHeader: DEFAULT_CACHE_CONTROL
179
+ cacheControlHeader: DEFAULT_CACHE_CONTROL,
180
+ inlineDocuments: false
114
181
  };
115
182
  if (!(config.enabled ?? true)) return;
116
183
  return {
117
184
  extensions: new Set((config.extensions && config.extensions.length > 0 ? config.extensions : DEFAULT_EXTENSIONS).map((ext) => normalizeExtension(ext))),
118
185
  cacheControlHeader: config.cacheControlHeader ?? DEFAULT_CACHE_CONTROL,
119
186
  routePrefix: config.routePrefix,
120
- contentTypeMap: config.contentTypeMap
187
+ contentTypeMap: config.contentTypeMap,
188
+ inlineDocuments: config.inlineDocuments ?? false
121
189
  };
122
190
  }
123
191
  function normalizeExtension(value) {
@@ -200,7 +268,8 @@ function registerDevAssets(app, options) {
200
268
  const cssRewrite = createStaticRewrite(cssRoute);
201
269
  app.use(cssRoute, serveStatic({
202
270
  root: cssDir,
203
- rewriteRequestPath: cssRewrite
271
+ rewriteRequestPath: cssRewrite,
272
+ onFound: options.inlineDocuments ? void 0 : guardStaticDocument
204
273
  }));
205
274
  }
206
275
  if (options.inertiaClient !== false) {
@@ -221,7 +290,8 @@ function registerDevAssets(app, options) {
221
290
  const rewriteRequestPath = createStaticRewrite(publicRoute);
222
291
  app.use(publicRoute, serveStatic({
223
292
  root: publicDir,
224
- rewriteRequestPath
293
+ rewriteRequestPath,
294
+ onFound: options.inlineDocuments ? void 0 : guardStaticDocument
225
295
  }));
226
296
  if (options.favicon !== false) app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
227
297
  registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
@@ -292,10 +362,13 @@ async function transpileFile(fsPath, transpile, containmentRoot) {
292
362
  } });
293
363
  }
294
364
  const body = await file.arrayBuffer();
295
- return new Response(body, { headers: {
296
- "Content-Type": file.type || "application/octet-stream",
365
+ const contentType = file.type || "application/octet-stream";
366
+ const headers = new Headers({
367
+ "Content-Type": contentType,
297
368
  "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
298
- } });
369
+ });
370
+ applyDocumentDisposition(headers, contentType);
371
+ return new Response(body, { headers });
299
372
  }
300
373
  function buildCandidatePaths(fsPath) {
301
374
  if (extname(fsPath)) return [fsPath];
@@ -355,7 +428,8 @@ function configureInertiaAssets(app, options) {
355
428
  app.use(publicRoute, serveStatic({
356
429
  root: publicDir,
357
430
  rewriteRequestPath,
358
- onFound: (_path, ctx) => {
431
+ onFound: (path, ctx) => {
432
+ if (!options.inlineDocuments) guardStaticDocument(path, ctx);
359
433
  if (ctx.req.path.startsWith(hashedAssetsPrefix)) ctx.header("Cache-Control", "public, max-age=31536000, immutable");
360
434
  }
361
435
  }));
@@ -397,10 +471,12 @@ function registerBuiltInertiaClient(app, inertiaClientDir, inertiaClientPath) {
397
471
  if (!await file.exists()) return ctx.notFound();
398
472
  if (containmentRoot && !await isRealPathWithin(containmentRoot, targetPath)) return ctx.notFound();
399
473
  const contentType = file.type || "application/javascript; charset=utf-8";
400
- return new Response(file, { headers: {
474
+ const headers = new Headers({
401
475
  "Content-Type": contentType,
402
476
  "Cache-Control": "public, max-age=31536000"
403
- } });
477
+ });
478
+ applyDocumentDisposition(headers, contentType);
479
+ return new Response(file, { headers });
404
480
  });
405
481
  }
406
482
  function autoConfigureInertiaAssets(app, options) {
@@ -40,7 +40,7 @@ function parseImportMap(value, options = {}) {
40
40
  const DEFAULT_DEV_STYLES_ENTRY = "/resources/css/app.css";
41
41
  //#endregion
42
42
  //#region package.json
43
- var version = "2.14.0";
43
+ var version = "2.15.0";
44
44
  //#endregion
45
45
  //#region src/http/dev-banner.ts
46
46
  figlet.parseFont("Standard", standard);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.14.0",
3
+ "version": "2.15.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "MIT",
@@ -94,6 +94,10 @@
94
94
  "types": "./dist/mcp/index.d.ts",
95
95
  "default": "./dist/mcp/index.js"
96
96
  },
97
+ "./agent": {
98
+ "types": "./dist/agent/public.d.ts",
99
+ "default": "./dist/agent/public.js"
100
+ },
97
101
  "./lambda": {
98
102
  "types": "./dist/lambda/index.d.ts",
99
103
  "default": "./dist/lambda/index.js"
@@ -138,7 +142,7 @@
138
142
  "test": "bun test"
139
143
  },
140
144
  "dependencies": {
141
- "@guren/orm": "^2.6.1",
145
+ "@guren/orm": "^2.6.2",
142
146
  "@modelcontextprotocol/sdk": "^1.30.0",
143
147
  "chalk": "^5.3.0",
144
148
  "consola": "^3.4.2",