@guren/server 2.13.0 → 2.14.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 (45) hide show
  1. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  2. package/dist/agent/derive.d.ts +155 -0
  3. package/dist/agent/dispatch.d.ts +123 -0
  4. package/dist/agent/events.d.ts +80 -0
  5. package/dist/agent/redact.d.ts +55 -0
  6. package/dist/agent/scopes.d.ts +115 -0
  7. package/dist/auth/AuthManager.d.ts +64 -0
  8. package/dist/auth/RequestAuthContext.d.ts +3 -5
  9. package/dist/auth/TokenGuard.d.ts +61 -0
  10. package/dist/auth/api-token.d.ts +25 -5
  11. package/dist/auth/context.d.ts +24 -0
  12. package/dist/auth/index.d.ts +5 -2
  13. package/dist/auth/index.js +2 -2
  14. package/dist/auth/providers/UserProvider.d.ts +7 -0
  15. package/dist/auth/types.d.ts +6 -0
  16. package/dist/{auth-C7sVmYgc.js → auth-BSUc14CD.js} +313 -122
  17. package/dist/authorization/index.js +1 -1
  18. package/dist/authorization/middleware.d.ts +28 -1
  19. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  20. package/dist/broadcasting/index.js +1 -1
  21. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BxU-LIfF.js} +2 -45
  22. package/dist/context-DoD0c7J_.js +26 -0
  23. package/dist/http/middleware/auth.d.ts +2 -2
  24. package/dist/http/middleware/capabilities.d.ts +57 -0
  25. package/dist/http/middleware/csrf.d.ts +3 -0
  26. package/dist/http/request.d.ts +51 -2
  27. package/dist/index.d.ts +12 -3
  28. package/dist/index.js +1015 -84
  29. package/dist/internal/agent-preflight.d.ts +28 -0
  30. package/dist/internal/request.d.ts +19 -0
  31. package/dist/internal/request.js +2 -0
  32. package/dist/internal/route-path.d.ts +28 -0
  33. package/dist/internal/route-path.js +33 -0
  34. package/dist/internal/zod-compat.d.ts +201 -0
  35. package/dist/internal/zod-compat.js +193 -0
  36. package/dist/internal/zod-json-schema.d.ts +102 -0
  37. package/dist/internal/zod-json-schema.js +461 -0
  38. package/dist/mcp/create-mcp-server.d.ts +29 -0
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Controller.d.ts +46 -0
  41. package/dist/mvc/Router.d.ts +53 -0
  42. package/dist/request-CRVuIiQr.js +78 -0
  43. package/dist/runtime/index.js +5 -2
  44. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-BGfWbPYp.js} +1 -1
  45. package/package.json +17 -1
@@ -1,4 +1,66 @@
1
1
  import { t as HttpException } from "./HttpException-BkS3euNG.js";
2
+ import { n as getAuthContext } from "./context-DoD0c7J_.js";
3
+ //#region src/http/middleware/capabilities.ts
4
+ /**
5
+ * Internal security-capability marker (RFC 0007).
6
+ *
7
+ * Built-in middleware factories stamp the handlers they return so tooling
8
+ * that holds the real function objects (the router registry, `guren audit`
9
+ * via route loading) can recognize what a handler enforces without name
10
+ * heuristics. `Symbol.for()` keeps the key identical across duplicated
11
+ * `@guren/server` copies in one process.
12
+ *
13
+ * Deliberately not part of the public API: nothing here is exported from
14
+ * the package root, and the shape may change in any release. A public
15
+ * `defineMiddleware` integration is future work in RFC 0007.
16
+ */
17
+ const CAPABILITIES = Symbol.for("guren.capabilities");
18
+ /**
19
+ * Fold one middleware's stamp into an accumulating aggregate, applying the
20
+ * rules the type above states: `'required'` beats `'guest-only'`; abilities
21
+ * union; two checks are a conjunction, so all-of + all-of stays `'all'` and
22
+ * anything else becomes `'mixed'`; `fromMethodMap` ANDs, since one
23
+ * non-authoritative check makes the verb map unusable for the whole chain.
24
+ *
25
+ * Mutates `into` and never `stamp` — nested objects and arrays are copied
26
+ * the first time they are taken, so a later merge cannot write back through
27
+ * the aggregate into a handler's stamp.
28
+ *
29
+ * Every call counts as an independent check. Folding the *same* stamp twice
30
+ * would read as two of them and degrade an `'any'` to `'mixed'`, so
31
+ * de-duplicating handlers that appear more than once in a chain is the
32
+ * caller's job.
33
+ */
34
+ function mergeCapabilities(into, stamp) {
35
+ const auth = stamp.authentication;
36
+ if (auth && (!into.authentication || auth.mode === "required")) into.authentication = { ...auth };
37
+ const authz = stamp.authorization;
38
+ if (!authz) return;
39
+ const current = into.authorization;
40
+ if (!current) {
41
+ into.authorization = {
42
+ abilities: [...authz.abilities],
43
+ mode: authz.mode,
44
+ ...authz.resource ? { resource: { ...authz.resource } } : {}
45
+ };
46
+ return;
47
+ }
48
+ for (const ability of authz.abilities) if (!current.abilities.includes(ability)) current.abilities.push(ability);
49
+ current.mode = current.mode === "all" && authz.mode === "all" ? "all" : "mixed";
50
+ if (authz.resource) current.resource = { fromMethodMap: (current.resource?.fromMethodMap ?? true) && authz.resource.fromMethodMap };
51
+ }
52
+ function stampCapabilities(handler, capabilities) {
53
+ Object.defineProperty(handler, CAPABILITIES, {
54
+ value: capabilities,
55
+ enumerable: false
56
+ });
57
+ return handler;
58
+ }
59
+ function capabilitiesOf(handler) {
60
+ if (typeof handler !== "function") return void 0;
61
+ return handler[CAPABILITIES];
62
+ }
63
+ //#endregion
2
64
  //#region src/errors/exceptions/AuthorizationException.ts
3
65
  /**
4
66
  * Authorization exception.
@@ -201,6 +263,8 @@ var Gate = class {
201
263
  async resolveUser(ctx) {
202
264
  if (this.currentUser !== null) return this.currentUser;
203
265
  if (this.userResolver) return this.userResolver(ctx);
266
+ const auth = getAuthContext(ctx);
267
+ if (auth && typeof auth.user === "function") return await auth.user() ?? null;
204
268
  return ctx.get("user") ?? null;
205
269
  }
206
270
  /**
@@ -505,38 +569,62 @@ function definePolicy(definition) {
505
569
  * // Multiple abilities (any)
506
570
  * app.get('/dashboard', authorizeMiddleware(['admin', 'moderator']), dashboardHandler)
507
571
  * ```
572
+ *
573
+ * An array argument is snapshotted at creation: mutating it afterwards
574
+ * changes neither what the middleware checks nor what it reports. A
575
+ * one-element array is treated exactly like the bare ability, denial message
576
+ * and status included. An empty array denies every request (`Gate.any([])` is
577
+ * false) and names no ability — fail-closed, so it is left to run rather than
578
+ * rejected.
508
579
  */
509
580
  function authorizeMiddleware(ability, modelResolver, options = {}) {
510
- return async (ctx, next) => {
581
+ const abilities = Array.isArray(ability) ? [...ability] : [ability];
582
+ const anyOf = abilities.length !== 1;
583
+ return stampCapabilities(async (ctx, next) => {
511
584
  const gate = getGate();
512
585
  const user = await gate.resolveUser(ctx);
513
586
  const gateForUser = gate.forUser(user);
514
- const abilities = Array.isArray(ability) ? ability : [ability];
515
587
  const model = modelResolver ? await modelResolver(ctx) : void 0;
516
- if (Array.isArray(ability)) {
588
+ if (anyOf) {
517
589
  if (!await gateForUser.any(abilities, model)) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
518
590
  } else {
519
- const response = await gateForUser.checkResponse(ability, user, model);
591
+ const response = await gateForUser.checkResponse(abilities[0], user, model);
520
592
  if (!response.allowed) throw denialToException(options.message ? {
521
593
  ...response,
522
594
  message: options.message
523
595
  } : response);
524
596
  }
525
597
  await next();
526
- };
598
+ }, { authorization: {
599
+ abilities,
600
+ mode: anyOf ? "any" : "all"
601
+ } });
527
602
  }
528
603
  /**
529
604
  * Middleware to authorize all given abilities.
605
+ *
606
+ * The array is snapshotted at creation, so mutating it afterwards changes
607
+ * neither what the middleware checks nor what it reports.
608
+ *
609
+ * @throws if no ability is given. `Gate.all([])` is vacuously true, so an
610
+ * empty list would mount a route that advertises authorization and enforces
611
+ * none — the fail-open shape RFC 0016's "authn is not authz" rule exists to
612
+ * catch. Refusing at creation surfaces it at boot rather than per request.
530
613
  */
531
- function authorizeAllMiddleware(abilities, modelResolver, options = {}) {
532
- return async (ctx, next) => {
614
+ function authorizeAllMiddleware(input, modelResolver, options = {}) {
615
+ const abilities = [...input];
616
+ if (abilities.length === 0) throw new Error("authorizeAllMiddleware() requires at least one ability: an empty list authorizes every request while claiming to authorize.");
617
+ return stampCapabilities(async (ctx, next) => {
533
618
  const gate = getGate();
534
619
  const user = await gate.resolveUser(ctx);
535
620
  const gateForUser = gate.forUser(user);
536
621
  const model = modelResolver ? await modelResolver(ctx) : void 0;
537
622
  if (!await gateForUser.all(abilities, model)) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
538
623
  await next();
539
- };
624
+ }, { authorization: {
625
+ abilities,
626
+ mode: "all"
627
+ } });
540
628
  }
541
629
  const RESOURCE_ABILITY_BY_METHOD = {
542
630
  GET: "view",
@@ -548,6 +636,20 @@ const RESOURCE_ABILITY_BY_METHOD = {
548
636
  DELETE: "delete"
549
637
  };
550
638
  /**
639
+ * The ability `authorizeResourceMiddleware` checks for an HTTP method, or
640
+ * `undefined` for a method it refuses to guess at (which the middleware
641
+ * denies). This is the single source of the verb → ability mapping: a
642
+ * consumer resolving a route's ability from its stamped
643
+ * `authorization.resource` capability calls this rather than restating the
644
+ * table, and may only do so when `resource.fromMethodMap` is true.
645
+ *
646
+ * Not re-exported from the package root — like the capability stamp itself
647
+ * (RFC 0007), this is an internal contract until a public consumer needs it.
648
+ */
649
+ function resourceAbilityForMethod(method) {
650
+ return RESOURCE_ABILITY_BY_METHOD[method.toUpperCase()];
651
+ }
652
+ /**
551
653
  * Middleware factory for resource authorization.
552
654
  * Automatically maps HTTP methods to policy abilities.
553
655
  *
@@ -570,9 +672,10 @@ const RESOURCE_ABILITY_BY_METHOD = {
570
672
  * ```
571
673
  */
572
674
  function authorizeResourceMiddleware(modelResolver, options = {}) {
573
- return async (ctx, next) => {
675
+ const abilityFor = options.abilityFor;
676
+ return stampCapabilities(async (ctx, next) => {
574
677
  const method = ctx.req.method.toUpperCase();
575
- const ability = options.abilityFor?.(method) ?? RESOURCE_ABILITY_BY_METHOD[method];
678
+ const ability = abilityFor?.(method) ?? resourceAbilityForMethod(method);
576
679
  if (ability === void 0) throw new AuthorizationException(options.message ?? "This action is unauthorized.");
577
680
  const gate = getGate();
578
681
  const user = await gate.resolveUser(ctx);
@@ -584,7 +687,11 @@ function authorizeResourceMiddleware(modelResolver, options = {}) {
584
687
  message: options.message
585
688
  } : response);
586
689
  await next();
587
- };
690
+ }, { authorization: {
691
+ abilities: [],
692
+ mode: "all",
693
+ resource: { fromMethodMap: abilityFor === void 0 }
694
+ } });
588
695
  }
589
696
  /**
590
697
  * Create a gate-aware context with authorization helpers.
@@ -607,4 +714,4 @@ function withAuthorization(gate) {
607
714
  };
608
715
  }
609
716
  //#endregion
610
- export { AuthorizationException as _, Policy as a, Response as c, cannot as d, createGate as f, setGate as g, isAuthorizationResponse as h, withAuthorization as i, authorize as l, getGate as m, authorizeMiddleware as n, definePolicy as o, defineGate as p, authorizeResourceMiddleware as r, Gate as s, authorizeAllMiddleware as t, can as u };
717
+ export { setGate as _, withAuthorization as a, mergeCapabilities as b, Gate as c, can as d, cannot as f, isAuthorizationResponse as g, getGate as h, resourceAbilityForMethod as i, Response as l, defineGate as m, authorizeMiddleware as n, Policy as o, createGate as p, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, authorize as u, AuthorizationException as v, stampCapabilities as x, capabilitiesOf as y };
@@ -1,2 +1,2 @@
1
- import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "../broadcasting-Dw-FhyjN.js";
1
+ import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "../broadcasting-BxU-LIfF.js";
2
2
  export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -1,49 +1,6 @@
1
+ import { a as parseRequestPayload } from "./request-CRVuIiQr.js";
1
2
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-WsTX2ySN.js";
2
3
  import { c as randomHex } from "./Random-DbIJ22KQ.js";
3
- //#region src/http/request.ts
4
- function isPlainObject(value) {
5
- return typeof value === "object" && value !== null && !Array.isArray(value);
6
- }
7
- /**
8
- * Parses the incoming request payload supporting both JSON bodies and form submissions.
9
- * Falls back to an empty object if the payload cannot be parsed.
10
- */
11
- async function parseRequestPayload(ctx) {
12
- if ((ctx.req.header("content-type") ?? "").includes("application/json")) {
13
- const body = await ctx.req.json().catch(() => ({}));
14
- return isPlainObject(body) ? body : {};
15
- }
16
- if (typeof ctx.req.parseBody === "function") {
17
- const form = await ctx.req.parseBody();
18
- return Object.fromEntries(Object.entries(form).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]));
19
- }
20
- return {};
21
- }
22
- /**
23
- * Collects query parameters preserving repeated keys as arrays while keeping
24
- * single occurrences as plain strings (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`,
25
- * `?page=2` → `{ page: '2' }`). Use this instead of `ctx.req.query()` when
26
- * feeding query data into validation schemas.
27
- */
28
- function flattenRequestQueries(ctx) {
29
- const queries = ctx.req.queries();
30
- const flat = {};
31
- for (const [key, values] of Object.entries(queries)) flat[key] = values.length === 1 ? values[0] : values;
32
- return flat;
33
- }
34
- /**
35
- * Converts a Zod-style validation error into a flat record usable by forms.
36
- */
37
- function formatValidationErrors(error, fallbackMessage = "The provided data is invalid.") {
38
- const errors = {};
39
- for (const issue of error.issues ?? []) {
40
- const field = issue.path?.[0];
41
- if (typeof field === "string" && !errors[field]) errors[field] = issue.message;
42
- }
43
- if (Object.keys(errors).length === 0) errors.message = fallbackMessage;
44
- return errors;
45
- }
46
- //#endregion
47
4
  //#region src/broadcasting/channels/Channel.ts
48
5
  /**
49
6
  * Base broadcast channel.
@@ -1052,4 +1009,4 @@ function wrapChannel(name, channel) {
1052
1009
  };
1053
1010
  }
1054
1011
  //#endregion
1055
- export { setBroadcastManager as a, PresenceChannel as c, flattenRequestQueries as d, formatValidationErrors as f, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, parseRequestPayload as p, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };
1012
+ export { setBroadcastManager as a, PresenceChannel as c, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };
@@ -0,0 +1,26 @@
1
+ //#region src/auth/context.ts
2
+ /**
3
+ * Context key the framework auth context is stored under.
4
+ *
5
+ * Lives here rather than in `http/middleware/auth` so that `auth/` modules can
6
+ * import it without reaching back into the middleware layer. The middleware
7
+ * re-exports it, and it stays a public root export.
8
+ */
9
+ const AUTH_CONTEXT_KEY = "guren:auth";
10
+ /**
11
+ * Read the framework auth context off a request context.
12
+ *
13
+ * The lookup and its cast, in one place — nothing more. `ctx.get` returns
14
+ * arbitrary values for unknown keys (test doubles and exotic contexts
15
+ * included), so the cast is a claim, not a check. A caller whose behavior
16
+ * turns on the value really being an auth context probes the member it is
17
+ * about to call; `Gate.resolveUser` does exactly that, because a stray value
18
+ * there decides whether the legacy `ctx.get('user')` fallback runs. Probing
19
+ * here instead would reject contexts that `requireAuthenticated` and
20
+ * `requireGuest` can use — they only ever read `check()` / `guest()`.
21
+ */
22
+ function getAuthContext(ctx) {
23
+ return ctx.get(AUTH_CONTEXT_KEY);
24
+ }
25
+ //#endregion
26
+ export { getAuthContext as n, AUTH_CONTEXT_KEY as t };
@@ -1,13 +1,13 @@
1
1
  import type { Context, MiddlewareHandler } from 'hono';
2
2
  import type { AuthContext } from '../../auth/types.js';
3
+ import { AUTH_CONTEXT_KEY, getAuthContext } from '../../auth/context.js';
3
4
  export type { AuthContext } from '../../auth/types.js';
4
5
  export interface RequireAuthOptions {
5
6
  redirectTo?: string;
6
7
  status?: number;
7
8
  responseFactory?: () => Response;
8
9
  }
9
- declare const AUTH_CONTEXT_KEY = "guren:auth";
10
10
  export declare function attachAuthContext(contextFactory: (ctx: Context) => AuthContext): MiddlewareHandler;
11
11
  export declare function requireAuthenticated(options?: RequireAuthOptions): MiddlewareHandler;
12
12
  export declare function requireGuest(options?: RequireAuthOptions): MiddlewareHandler;
13
- export { AUTH_CONTEXT_KEY };
13
+ export { AUTH_CONTEXT_KEY, getAuthContext };
@@ -14,9 +14,66 @@ import type { MiddlewareHandler } from 'hono';
14
14
  */
15
15
  export declare const CAPABILITIES: unique symbol;
16
16
  export interface MiddlewareCapabilities {
17
+ /**
18
+ * Authentication enforced by the chain. `'required'` beats `'guest-only'`
19
+ * when a chain somehow carries both.
20
+ */
17
21
  authentication?: {
18
22
  mode: 'required' | 'guest-only';
19
23
  };
24
+ /**
25
+ * Authorization enforced by the chain (RFC 0016 §4): what makes
26
+ * route → ability derivable without reading controller bodies.
27
+ *
28
+ * - `abilities` — the ability names checked, in the order the chain
29
+ * checks them. Empty when every check derives its ability at request
30
+ * time (see `resource`), and also for the degenerate
31
+ * `authorizeMiddleware([])`, which denies every request.
32
+ * - `mode` — how they combine. `'all'` every listed ability must pass,
33
+ * `'any'` at least one must. A list of exactly one normalizes to
34
+ * `'all'`, because any-of one ability *is* that ability — and the
35
+ * middleware treats it that way at runtime too, down to the denial
36
+ * message. So `'any'` means either two or more alternatives, or the
37
+ * degenerate empty list that denies every request. `'mixed'` means the
38
+ * chain carries more than one check and the conjunction of them is not
39
+ * expressible as either: authorization is present, but the ability is
40
+ * *not* cleanly derivable, and a consumer must treat it as undetermined
41
+ * rather than picking a name out of `abilities`. A single derivable
42
+ * ability is `abilities.length === 1` with `mode: 'all'` and no
43
+ * `resource`.
44
+ * - `resource` — present when a check resolves its ability from the
45
+ * request method (`authorizeResourceMiddleware`). `fromMethodMap: true`
46
+ * means the built-in verb map decides, so a consumer holding the
47
+ * route's method resolves the ability through
48
+ * `resourceAbilityForMethod()` in `../../authorization/middleware`.
49
+ * `false` means an `abilityFor` callback overrides that map and the
50
+ * real ability is unknowable statically — fail closed, do not fall
51
+ * back to the verb map.
52
+ */
53
+ authorization?: {
54
+ abilities: string[];
55
+ mode: 'all' | 'any' | 'mixed';
56
+ resource?: {
57
+ fromMethodMap: boolean;
58
+ };
59
+ };
20
60
  }
61
+ /**
62
+ * Fold one middleware's stamp into an accumulating aggregate, applying the
63
+ * rules the type above states: `'required'` beats `'guest-only'`; abilities
64
+ * union; two checks are a conjunction, so all-of + all-of stays `'all'` and
65
+ * anything else becomes `'mixed'`; `fromMethodMap` ANDs, since one
66
+ * non-authoritative check makes the verb map unusable for the whole chain.
67
+ *
68
+ * Mutates `into` and never `stamp` — nested objects and arrays are copied
69
+ * the first time they are taken, so a later merge cannot write back through
70
+ * the aggregate into a handler's stamp.
71
+ *
72
+ * Every call counts as an independent check. Folding the *same* stamp twice
73
+ * would read as two of them and degrade an `'any'` to `'mixed'`, so
74
+ * de-duplicating handlers that appear more than once in a chain is the
75
+ * caller's job.
76
+ */
77
+ export declare function mergeCapabilities(into: MiddlewareCapabilities, stamp: MiddlewareCapabilities): void;
21
78
  export declare function stampCapabilities(handler: MiddlewareHandler, capabilities: MiddlewareCapabilities): MiddlewareHandler;
22
79
  export declare function capabilitiesOf(handler: unknown): MiddlewareCapabilities | undefined;
@@ -94,6 +94,9 @@ export declare function verifyCsrfToken(ctx: Context, token: string | undefined)
94
94
  * those sessions expire
95
95
  * - Exempts the dev-only MCP endpoint while it is mounted, since agent
96
96
  * clients cannot fetch a token first (it guards local-only access instead)
97
+ * - Skips verification for `Authorization: Bearer` requests that carry no
98
+ * cookies (RFC 0016) — token clients authenticate per request and hold no
99
+ * cookie ambient authority for CSRF to defend
97
100
  *
98
101
  * `cookie: false` disables the `XSRF-TOKEN` cookie for apps that deliver the
99
102
  * token themselves (meta tag / form field). Session-bound tokens still
@@ -1,9 +1,58 @@
1
+ import type { HonoRequest } from 'hono';
1
2
  import type { Context } from './Application.js';
2
3
  /**
3
- * Parses the incoming request payload supporting both JSON bodies and form submissions.
4
- * Falls back to an empty object if the payload cannot be parsed.
4
+ * What {@link parseRequestBody} actually reads: three members off `ctx.req`,
5
+ * not a whole Hono context.
6
+ *
7
+ * Declared structurally because the difference is load bearing. `parseBody` is
8
+ * optional here, which is what makes the `typeof` guard below meaningful — a
9
+ * real `Context` always carries one, so against `Context` that guard reads as
10
+ * dead code. It is not: `@guren/testing`'s controller mock reaches this parser
11
+ * through a `HonoRequest` built from a plain `Request`, and this is the
12
+ * declaration that lets it do so without casting its way past the signature.
13
+ *
14
+ * Narrowing a parameter accepts strictly more callers, so every existing one —
15
+ * `Router`, `Controller`, the validation middleware, `FormRequest`,
16
+ * `BroadcastManager` — keeps passing a real `Context` unchanged.
17
+ */
18
+ export interface RequestBodyContext {
19
+ req: Pick<HonoRequest, 'header' | 'json'> & Partial<Pick<HonoRequest, 'parseBody'>>;
20
+ }
21
+ /**
22
+ * Parses the incoming request body and returns the parsed value as-is: a JSON
23
+ * array stays an array, a JSON string stays a string. Use this wherever the
24
+ * result is handed to a schema and *that* decides the shape — a route
25
+ * contract's `body`, `Controller.validateBody()`, `validateRequest()`.
26
+ *
27
+ * Falls back to an empty object when the body cannot be parsed (malformed
28
+ * JSON, a form body the parser cannot decode, an empty POST, an unsupported
29
+ * content type). That fallback is load bearing: an all-optional object schema
30
+ * has to keep passing on an empty body, which `undefined` would break. The
31
+ * cost is that a non-object schema sees `{}` there and fails validation,
32
+ * rather than receiving nothing.
33
+ *
34
+ * The fallback does not distinguish whose fault the failure was: a body the
35
+ * client could never have sent correctly and a body already consumed upstream
36
+ * (middleware reading `ctx.req.raw` directly, bypassing Hono's cache) both read
37
+ * as `{}` here. That is deliberate — the JSON branch above has always behaved
38
+ * this way, and telling the two apart means matching runtime-specific error
39
+ * codes, which would answer differently on Bun, Node and Workers. A parser
40
+ * error is a poor signal for a middleware-ordering bug either way.
41
+ *
42
+ * Form submissions have no non-object shape to preserve, so they normalize to
43
+ * a record exactly as {@link parseRequestPayload} does.
44
+ */
45
+ export declare function parseRequestBody(ctx: RequestBodyContext): Promise<unknown>;
46
+ /**
47
+ * The record-shaped view of {@link parseRequestBody}, for callers that read the
48
+ * payload field by field (`payload.channel`, per-field validation rules,
49
+ * `Controller.input()`/`only()`/`except()`/`has()`). A body that is not a plain
50
+ * object — an array, a string, `null` — becomes `{}`, because there is no
51
+ * field to read on one.
5
52
  */
6
53
  export declare function parseRequestPayload(ctx: Context): Promise<Record<string, unknown>>;
54
+ /** Narrow a parsed body to the record view described on {@link parseRequestPayload}. */
55
+ export declare function asRecord(body: unknown): Record<string, unknown>;
7
56
  /**
8
57
  * Collects query parameters preserving repeated keys as arrays while keeping
9
58
  * single occurrences as plain strings (`?tag=a&tag=b` → `{ tag: ['a', 'b'] }`,
package/dist/index.d.ts CHANGED
@@ -9,7 +9,16 @@ export type { FC, PropsWithChildren } from 'hono/jsx';
9
9
  export { viteAsset } from './http/vite-assets.js';
10
10
  export type { ViteAssetOptions } from './http/vite-assets.js';
11
11
  export { Router } from './mvc/Router.js';
12
- export type { BindableModel, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
12
+ export type { BindableModel, AgentRouteMetadata, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
13
+ export { deriveAgentTools } from './agent/derive.js';
14
+ export type { AgentToolInputSource, AgentToolSchema, DeriveAgentToolsResult, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './agent/derive.js';
15
+ export { advertisesStructuredOutput, buildToolRequest, mapToolResponse, PREFLIGHT_ARGUMENT, } from './agent/dispatch.js';
16
+ export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, } from './agent/dispatch.js';
17
+ export { AGENT_TOOL_NAME_PATTERN, expandToolScopes, parseToolScope, scopesAllowTool, } from './agent/scopes.js';
18
+ export type { ParsedToolScope, ScopedTool } from './agent/scopes.js';
19
+ export { AgentToolDenied, AgentToolInvoked } from './agent/events.js';
20
+ export type { AgentPrincipal, AgentSurface, AgentToolDenialReason } from './agent/events.js';
21
+ export { AGENT_REDACTED, redactAgentArguments } from './agent/redact.js';
13
22
  export { ViewEngine } from './mvc/ViewEngine.js';
14
23
  export { inertia, setInertiaSsrRenderer, setInertiaDocument } from './mvc/inertia/InertiaEngine.js';
15
24
  export { setInertiaSharedProps, getInertiaSharedPropsResolver, shareInertiaProps } from './mvc/inertia/shared.js';
@@ -17,8 +26,8 @@ export type { InertiaDocumentContext, InertiaDocumentOptions, InertiaOptions, In
17
26
  export type { SharedInertiaPropsResolver, InertiaSharedProps, ResolvedSharedInertiaProps, SharedPropsContainer, } from './mvc/inertia/shared.js';
18
27
  export { InertiaServiceProvider, AuthServiceProvider, OAuthServiceProvider, EventServiceProvider, CacheServiceProvider, QueueServiceProvider, MailServiceProvider, LogServiceProvider, I18nServiceProvider, NotificationServiceProvider, BroadcastServiceProvider, EncryptionServiceProvider, StorageServiceProvider, HealthServiceProvider, SchedulingServiceProvider, AuthorizationServiceProvider, ErrorServiceProvider, } from './providers/index.js';
19
28
  export { FormRequest } from './http/FormRequest.js';
20
- export { AuthManager, SessionGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, ScryptHasher, createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, createApiToken, parseApiToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, } from './auth/index.js';
21
- export type { AuthContext as AuthRuntimeContext, AuthCredentials, AuthManagerOptions, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, DefaultSanitizedKeys, Sanitized, PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, ApiToken, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './auth/index.js';
29
+ export { AuthManager, SessionGuard, TokenGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, ScryptHasher, createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, } from './auth/index.js';
30
+ export type { AuthContext as AuthRuntimeContext, AuthCredentials, AuthManagerOptions, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, DefaultSanitizedKeys, Sanitized, PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, ApiToken, ApiTokenGuardOptions, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, VerifiedApiToken, TokenGuardOptions, OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './auth/index.js';
22
31
  export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
23
32
  export { AUTH_CONTEXT_KEY } from './http/middleware/auth.js';
24
33
  export type { Middleware, Session, SessionData, SessionStore, AuthContext, RequireAuthOptions, CsrfOptions, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';