@guren/server 2.13.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 (68) hide show
  1. package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
  2. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  3. package/dist/agent/AgentApprovalRequested.d.ts +59 -0
  4. package/dist/agent/approval.d.ts +295 -0
  5. package/dist/agent/audit-emitter.d.ts +64 -0
  6. package/dist/agent/audit.d.ts +103 -0
  7. package/dist/agent/derive.d.ts +155 -0
  8. package/dist/agent/dispatch.d.ts +165 -0
  9. package/dist/agent/events.d.ts +80 -0
  10. package/dist/agent/meta-tools.d.ts +62 -0
  11. package/dist/agent/public.d.ts +33 -0
  12. package/dist/agent/public.js +2 -0
  13. package/dist/agent/redact.d.ts +55 -0
  14. package/dist/agent/scopes.d.ts +115 -0
  15. package/dist/auth/AuthManager.d.ts +64 -0
  16. package/dist/auth/RequestAuthContext.d.ts +3 -5
  17. package/dist/auth/TokenGuard.d.ts +61 -0
  18. package/dist/auth/api-token.d.ts +25 -5
  19. package/dist/auth/context.d.ts +24 -0
  20. package/dist/auth/index.d.ts +5 -2
  21. package/dist/auth/index.js +2 -2
  22. package/dist/auth/password/DefaultHasher.d.ts +18 -5
  23. package/dist/auth/password/PasswordHasher.d.ts +15 -0
  24. package/dist/auth/password/hash-format.d.ts +19 -0
  25. package/dist/auth/providers/UserProvider.d.ts +7 -0
  26. package/dist/auth/types.d.ts +6 -0
  27. package/dist/{auth-C7sVmYgc.js → auth-DkYoAPVn.js} +431 -151
  28. package/dist/authorization/index.js +1 -1
  29. package/dist/authorization/middleware.d.ts +28 -1
  30. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  31. package/dist/broadcasting/index.js +1 -1
  32. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BwodCA4q.js} +2 -45
  33. package/dist/container/bindings.d.ts +19 -0
  34. package/dist/context-DoD0c7J_.js +26 -0
  35. package/dist/dispatch-erOS9epZ.js +285 -0
  36. package/dist/encryption/index.js +2 -2
  37. package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
  38. package/dist/http/dev-assets.d.ts +16 -0
  39. package/dist/http/middleware/auth.d.ts +2 -2
  40. package/dist/http/middleware/capabilities.d.ts +57 -0
  41. package/dist/http/middleware/csrf.d.ts +3 -0
  42. package/dist/http/public-assets.d.ts +10 -0
  43. package/dist/http/request.d.ts +139 -3
  44. package/dist/http/static-documents.d.ts +31 -0
  45. package/dist/index.d.ts +21 -4
  46. package/dist/index.js +1302 -118
  47. package/dist/internal/agent-preflight.d.ts +28 -0
  48. package/dist/internal/request.d.ts +25 -0
  49. package/dist/internal/request.js +2 -0
  50. package/dist/internal/route-path.d.ts +28 -0
  51. package/dist/internal/route-path.js +33 -0
  52. package/dist/internal/zod-compat.d.ts +201 -0
  53. package/dist/internal/zod-compat.js +193 -0
  54. package/dist/internal/zod-json-schema.d.ts +102 -0
  55. package/dist/internal/zod-json-schema.js +461 -0
  56. package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
  57. package/dist/logging/daily-file-path.d.ts +24 -0
  58. package/dist/logging/index.d.ts +1 -0
  59. package/dist/logging/index.js +2 -2
  60. package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
  61. package/dist/mcp/create-mcp-server.d.ts +29 -0
  62. package/dist/mcp/index.js +1 -1
  63. package/dist/mvc/Controller.d.ts +20 -0
  64. package/dist/mvc/Router.d.ts +53 -0
  65. package/dist/request-CVQwpu2J.js +129 -0
  66. package/dist/runtime/index.js +94 -15
  67. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-w_RSOvQW.js} +1 -1
  68. package/package.json +22 -2
@@ -1,2 +1,2 @@
1
- import { a as Policy, c as Response, d as cannot, f as createGate, g as setGate, h as isAuthorizationResponse, i as withAuthorization, l as authorize, m as getGate, n as authorizeMiddleware, o as definePolicy, p as defineGate, r as authorizeResourceMiddleware, s as Gate, t as authorizeAllMiddleware, u as can } from "../authorization-Dbcuc5ZK.js";
1
+ import { _ as setGate, a as withAuthorization, c as Gate, d as can, f as cannot, g as isAuthorizationResponse, h as getGate, l as Response, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize } from "../authorization-CdfbCj8J.js";
2
2
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
@@ -16,12 +16,39 @@ import { Gate } from './Gate.js';
16
16
  * // Multiple abilities (any)
17
17
  * app.get('/dashboard', authorizeMiddleware(['admin', 'moderator']), dashboardHandler)
18
18
  * ```
19
+ *
20
+ * An array argument is snapshotted at creation: mutating it afterwards
21
+ * changes neither what the middleware checks nor what it reports. A
22
+ * one-element array is treated exactly like the bare ability, denial message
23
+ * and status included. An empty array denies every request (`Gate.any([])` is
24
+ * false) and names no ability — fail-closed, so it is left to run rather than
25
+ * rejected.
19
26
  */
20
27
  export declare function authorizeMiddleware(ability: string | string[], modelResolver?: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
21
28
  /**
22
29
  * Middleware to authorize all given abilities.
30
+ *
31
+ * The array is snapshotted at creation, so mutating it afterwards changes
32
+ * neither what the middleware checks nor what it reports.
33
+ *
34
+ * @throws if no ability is given. `Gate.all([])` is vacuously true, so an
35
+ * empty list would mount a route that advertises authorization and enforces
36
+ * none — the fail-open shape RFC 0016's "authn is not authz" rule exists to
37
+ * catch. Refusing at creation surfaces it at boot rather than per request.
38
+ */
39
+ export declare function authorizeAllMiddleware(input: string[], modelResolver?: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
40
+ /**
41
+ * The ability `authorizeResourceMiddleware` checks for an HTTP method, or
42
+ * `undefined` for a method it refuses to guess at (which the middleware
43
+ * denies). This is the single source of the verb → ability mapping: a
44
+ * consumer resolving a route's ability from its stamped
45
+ * `authorization.resource` capability calls this rather than restating the
46
+ * table, and may only do so when `resource.fromMethodMap` is true.
47
+ *
48
+ * Not re-exported from the package root — like the capability stamp itself
49
+ * (RFC 0007), this is an internal contract until a public consumer needs it.
23
50
  */
24
- export declare function authorizeAllMiddleware(abilities: string[], modelResolver?: (ctx: Context) => unknown | Promise<unknown>, options?: AuthorizeOptions): Middleware;
51
+ export declare function resourceAbilityForMethod(method: string): string | undefined;
25
52
  /**
26
53
  * Middleware factory for resource authorization.
27
54
  * Automatically maps HTTP methods to policy abilities.
@@ -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-BwodCA4q.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-CVQwpu2J.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 };
@@ -18,6 +18,7 @@ import type { Scheduler } from '../scheduling/index.js';
18
18
  import type { Gate } from '../authorization/Gate.js';
19
19
  import type { ExceptionHandler } from '../errors/index.js';
20
20
  import type { SharedInertiaPropsRegistry } from '../mvc/inertia/shared.js';
21
+ import type { AgentAuditEmitter } from '../agent/audit-emitter.js';
21
22
  /**
22
23
  * Type-safe service binding map.
23
24
  *
@@ -51,5 +52,23 @@ export interface ServiceBindings {
51
52
  gate: Gate;
52
53
  /** Bound lazily on the first `shareInertiaProps(fn, container)` call. */
53
54
  'inertia.sharedProps': SharedInertiaPropsRegistry;
55
+ /**
56
+ * How an agent surface records what it did (RFC 0016 §5.2). Bound by
57
+ * `@guren/plugin-mcp` at boot, and absent when no MCP plugin is registered
58
+ * — the key is declared here, where every other service name is, so that a
59
+ * surface resolving it and the plugin binding it spell one string.
60
+ *
61
+ * The binding is the *emitter*, not the sink: a second caller that resolved
62
+ * a sink would have to build its own emitter around it, and the two would
63
+ * then differ on the questions the emitter answers — whether a sink failure
64
+ * warns, whether the events are emitted beside it. One emitter per
65
+ * application means every surface's records reach the same place the same
66
+ * way.
67
+ *
68
+ * An interface key cannot be a constant, so the *runtime* spelling of this
69
+ * name lives once in `AGENT_AUDIT_BINDING`, which both the writing and the
70
+ * reading package import. Rename here and there together.
71
+ */
72
+ 'agent.audit': AgentAuditEmitter;
54
73
  'exception.handler': ExceptionHandler;
55
74
  }
@@ -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 };
@@ -0,0 +1,285 @@
1
+ import { PATH_PARAM_PATTERN } from "./internal/route-path.js";
2
+ //#region src/internal/agent-preflight.ts
3
+ /**
4
+ * The wire protocol of an agent preflight (RFC 0016 §5.4), in a leaf module
5
+ * so the two halves can share it without depending on each other.
6
+ *
7
+ * `Router` mounts the seam that answers a preflight; `agent/dispatch` builds
8
+ * the request that asks for one and reads the answer back. Putting the names
9
+ * in either of those would make one import the other — today only
10
+ * `dispatch → Router` exists, and the day `Router` needs anything from
11
+ * `agent/` that becomes a cycle.
12
+ *
13
+ * Not exported from the package index: an external dispatcher asks for a
14
+ * preflight through `BuildToolRequestOptions.preflight`, and the header
15
+ * spelling is this seam's business, not published API.
16
+ */
17
+ /** Request header asking the route for a verdict instead of an execution. */
18
+ const AGENT_PREFLIGHT_HEADER = "X-Guren-Agent-Preflight";
19
+ /**
20
+ * Response header marking a body as a preflight verdict rather than the
21
+ * route's own output.
22
+ *
23
+ * Load-bearing in two places that would otherwise mistake one for the other:
24
+ * a route's `output` schema validation (which would reject the verdict and
25
+ * turn it into a 500) and the MCP response mapping (which would advertise the
26
+ * verdict as the tool's `structuredContent`, so an SDK client validates it
27
+ * against the tool's output schema and throws). Both are answering the same
28
+ * question — "is this the route's result?" — so both read the same marker.
29
+ */
30
+ const AGENT_PREFLIGHT_VERDICT_HEADER = "X-Guren-Agent-Preflight-Verdict";
31
+ //#endregion
32
+ //#region src/agent/dispatch.ts
33
+ /** How many characters of a non-JSON response body survive into the result. */
34
+ const TEXT_RESPONSE_CAP = 5e4;
35
+ /**
36
+ * The argument-level spelling of a preflight request (RFC 0016 §5.4), for a
37
+ * surface whose callers pass flat arguments rather than dispatch options.
38
+ *
39
+ * No adapter strips it today, because none accepts it. Every surface that
40
+ * reaches the seam asks through `BuildToolRequestOptions.preflight` instead:
41
+ * `guren tool:call` and `@guren/testing` from their own flags, and MCP from
42
+ * the `guren.preflight` companion tool, which takes the target tool's name
43
+ * and arguments rather than smuggling a directive through them (RFC 0016
44
+ * §5.4 — a verdict conforms to no route's output schema, so it needs a tool
45
+ * of its own). A surface that adopts this key owns the stripping — it is an
46
+ * instruction to the adapter, not a field of any route's contract, and
47
+ * forwarding it would fail the very validation the caller asked to rehearse.
48
+ */
49
+ const PREFLIGHT_ARGUMENT = "_preflight";
50
+ /**
51
+ * The agent-facing diagnosis of a {@link ToolRequestBuildFailure}.
52
+ *
53
+ * One function rather than a string per adapter: the same tool is reachable
54
+ * from several surfaces (App MCP, WebMCP, `guren tool:call`), and an agent
55
+ * that reads a different diagnosis depending on which one it reached would
56
+ * be debugging the client instead of its own call.
57
+ */
58
+ function describeBuildFailure(failure) {
59
+ if ("missing" in failure) return `Missing required path parameter(s): ${failure.missing.join(", ")}.`;
60
+ return `Path parameter(s) ${failure.invalidPath.join(", ")} may not be "." or ".." — a dot-segment would resolve to a different route than the one authorized.`;
61
+ }
62
+ /**
63
+ * Rebuild the HTTP request a tool call describes.
64
+ *
65
+ * The flat argument object is taken apart along `tool.inputSources` — the
66
+ * derivation's own record of which contract each property came from — so a
67
+ * POST route's `query` keys land in the query string where `validateQuery`
68
+ * reads them, not in the body. Keys the derivation never advertised are
69
+ * forwarded anyway (body for body-carrying methods, query otherwise): the
70
+ * route's validator is the one place that rejects them, and dropping them
71
+ * here would make this a second, quieter validator.
72
+ *
73
+ * GET and HEAD force everything into the query string whatever its source —
74
+ * `Request` refuses a body on those methods, and a `body` schema on a GET
75
+ * route is a contract defect this adapter cannot repair.
76
+ */
77
+ function buildToolRequest(tool, args, options = {}) {
78
+ const origin = options.origin ?? "http://localhost";
79
+ const missing = [];
80
+ const invalidPath = [];
81
+ const pathOnly = /* @__PURE__ */ new Set();
82
+ const path = tool.path.replace(PATH_PARAM_PATTERN, (_match, lead, name) => {
83
+ const value = args[name];
84
+ if (value === void 0) {
85
+ missing.push(name);
86
+ return `${lead}:${name}`;
87
+ }
88
+ const stringified = String(value);
89
+ if (stringified === "." || stringified === "..") {
90
+ invalidPath.push(name);
91
+ return `${lead}:${name}`;
92
+ }
93
+ const source = sourceOf(tool, name);
94
+ if (source === void 0 || source === "params" || source === "path") pathOnly.add(name);
95
+ return `${lead}${encodeURIComponent(stringified)}`;
96
+ });
97
+ if (missing.length > 0) return { missing };
98
+ if (invalidPath.length > 0) return { invalidPath };
99
+ const method = tool.method;
100
+ const bodyless = method === "GET" || method === "HEAD";
101
+ const query = new URLSearchParams();
102
+ const bodyEntries = [];
103
+ for (const [key, value] of Object.entries(args)) {
104
+ if (pathOnly.has(key) || value === void 0) continue;
105
+ const source = sourceOf(tool, key);
106
+ if (bodyless || source === "query" || source === "params" || source === "path" || tool.inputBodyNested && key !== "body") appendQueryValue(query, key, value);
107
+ else bodyEntries.push([key, value]);
108
+ }
109
+ const headers = new Headers({
110
+ Accept: "application/json",
111
+ "X-Guren-Agent-Surface": options.surface ?? "mcp"
112
+ });
113
+ if (options.authorization) headers.set("Authorization", options.authorization);
114
+ if (options.preflight) headers.set(AGENT_PREFLIGHT_HEADER, "1");
115
+ let body;
116
+ if (!bodyless) {
117
+ if (tool.inputBodyNested) {
118
+ if (Object.hasOwn(args, "body")) body = JSON.stringify(args.body);
119
+ } else if (bodyEntries.length > 0) body = JSON.stringify(accumulate(bodyEntries));
120
+ }
121
+ if (body !== void 0) headers.set("Content-Type", "application/json");
122
+ const qs = query.toString();
123
+ const url = `${origin}${path}${qs ? `?${qs}` : ""}`;
124
+ return { request: new Request(url, {
125
+ method,
126
+ headers,
127
+ body
128
+ }) };
129
+ }
130
+ /**
131
+ * The contract a property was declared under, or undefined if the derivation
132
+ * never advertised it. `Object.hasOwn` rather than a plain read: a JSON
133
+ * argument may legally be named `__proto__`, and `inputSources['__proto__']`
134
+ * would otherwise resolve to `Object.prototype`, not undefined.
135
+ */
136
+ function sourceOf(tool, name) {
137
+ return Object.hasOwn(tool.inputSources, name) ? tool.inputSources[name] : void 0;
138
+ }
139
+ /** Primitives stringify; anything structured rides as JSON text. */
140
+ function appendQueryValue(query, key, value) {
141
+ if (Array.isArray(value)) {
142
+ for (const element of value) query.append(key, serializeQueryScalar(element));
143
+ return;
144
+ }
145
+ query.append(key, serializeQueryScalar(value));
146
+ }
147
+ function serializeQueryScalar(value) {
148
+ if (value === null || typeof value !== "object") return String(value);
149
+ return JSON.stringify(value);
150
+ }
151
+ /**
152
+ * Null-prototype accumulator, spread back to plain: a JSON argument may
153
+ * legally be named `__proto__`, and assigning that key on `{}` invokes the
154
+ * prototype setter instead of defining the property — the same rule the
155
+ * derivation and the redaction walk apply.
156
+ */
157
+ function accumulate(entries) {
158
+ const record = Object.create(null);
159
+ for (const [key, value] of entries) record[key] = value;
160
+ return { ...record };
161
+ }
162
+ /**
163
+ * Whether the tool advertises an object output schema — the only kind MCP
164
+ * lists, and therefore the only kind that obliges a success result to carry
165
+ * `structuredContent`. A route whose `output` is an array or primitive is not
166
+ * advertised as structured (MCP `outputSchema` must be an object), so its
167
+ * results ride as text. `describeTool` and `mapToolResponse` must agree on
168
+ * this exact predicate, or one advertises a schema the other cannot satisfy.
169
+ */
170
+ function advertisesStructuredOutput(tool) {
171
+ return tool.outputSchema?.type === "object";
172
+ }
173
+ /**
174
+ * Map the application's response onto an MCP tool result (RFC 0016 §3.4).
175
+ *
176
+ * - 2xx JSON object → serialized text, plus `structuredContent` when the tool
177
+ * advertises an object `outputSchema` (the one shape the route validated).
178
+ * - 2xx Inertia page JSON → unwrapped to `page.props`, only for a tool with
179
+ * no `outputSchema` — unwrap and schema are mutually exclusive by
180
+ * derivation, so the advertised shape can never disagree with the result.
181
+ * - 204 / 3xx → a status line naming the Location; not an error.
182
+ * - 4xx / 5xx → `isError: true` carrying the exception handler's JSON body:
183
+ * a 422's `{ message, errors }` is an application-level failure the agent
184
+ * should read, not a protocol error.
185
+ * - non-JSON → capped text.
186
+ *
187
+ * One MCP invariant overrides the table: a *non-error* result for a tool that
188
+ * advertises an object `outputSchema` must carry `structuredContent`, or the
189
+ * SDK client rejects it after the route has already run. A success response
190
+ * that yields no object to put there (204, 3xx, non-JSON, a non-object body)
191
+ * contradicts the route's own declared output, so it becomes an `isError`
192
+ * result naming the mismatch — which the SDK exempts from the rule — rather
193
+ * than a protocol fault the agent cannot interpret.
194
+ */
195
+ async function mapToolResponse(tool, response) {
196
+ const status = response.status;
197
+ const structured = advertisesStructuredOutput(tool);
198
+ if (status === 204 || status >= 300 && status < 400) {
199
+ const location = response.headers.get("Location");
200
+ const text = location ? `HTTP ${status} (Location: ${location})` : `HTTP ${status}`;
201
+ if (structured) return inconsistentOutput(tool, text, status);
202
+ return {
203
+ content: [{
204
+ type: "text",
205
+ text
206
+ }],
207
+ status
208
+ };
209
+ }
210
+ const raw = await response.text();
211
+ if (status >= 400) return {
212
+ content: [{
213
+ type: "text",
214
+ text: raw || `HTTP ${status}`
215
+ }],
216
+ isError: true,
217
+ status
218
+ };
219
+ const parsed = parseJsonBody(response, raw);
220
+ if (parsed === void 0) {
221
+ const text = raw.length > TEXT_RESPONSE_CAP ? `${raw.slice(0, TEXT_RESPONSE_CAP)}… [truncated ${raw.length - TEXT_RESPONSE_CAP} characters]` : raw;
222
+ if (structured) return inconsistentOutput(tool, `a non-JSON body (${text.slice(0, 200)})`, status);
223
+ return {
224
+ content: [{
225
+ type: "text",
226
+ text
227
+ }],
228
+ status
229
+ };
230
+ }
231
+ if (response.headers.get("X-Guren-Agent-Preflight-Verdict") !== null) return {
232
+ content: [{
233
+ type: "text",
234
+ text: JSON.stringify(parsed)
235
+ }],
236
+ status,
237
+ preflightVerdict: true
238
+ };
239
+ const payload = unwrapInertiaProps(tool, response, parsed);
240
+ if (structured && !isRecord(payload)) return inconsistentOutput(tool, `a ${Array.isArray(payload) ? "JSON array" : typeof payload} body`, status);
241
+ const outcome = {
242
+ content: [{
243
+ type: "text",
244
+ text: JSON.stringify(payload)
245
+ }],
246
+ status
247
+ };
248
+ if (structured && isRecord(payload)) outcome.structuredContent = payload;
249
+ return outcome;
250
+ }
251
+ /**
252
+ * A success response that cannot satisfy the tool's advertised object output
253
+ * schema. Returned as an error result — the honest signal that the route and
254
+ * its declared `output` disagree — which also sidesteps the SDK's
255
+ * structuredContent requirement (errors are exempt).
256
+ */
257
+ function inconsistentOutput(tool, detail, status) {
258
+ return {
259
+ content: [{
260
+ type: "text",
261
+ text: `The tool "${tool.toolName}" advertises an output schema, but the route returned ${detail} (HTTP ${status}) — no structured result could be produced.`
262
+ }],
263
+ isError: true,
264
+ status
265
+ };
266
+ }
267
+ function parseJsonBody(response, raw) {
268
+ if (!(response.headers.get("Content-Type") ?? "").includes("json") || raw === "") return void 0;
269
+ try {
270
+ return JSON.parse(raw);
271
+ } catch {
272
+ return;
273
+ }
274
+ }
275
+ function unwrapInertiaProps(tool, response, parsed) {
276
+ if (tool.outputSchema) return parsed;
277
+ if (response.headers.get("X-Inertia") !== "true") return parsed;
278
+ if (!isRecord(parsed) || !("props" in parsed)) return parsed;
279
+ return parsed.props;
280
+ }
281
+ function isRecord(value) {
282
+ return typeof value === "object" && value !== null && !Array.isArray(value);
283
+ }
284
+ //#endregion
285
+ export { mapToolResponse as a, describeBuildFailure as i, advertisesStructuredOutput as n, AGENT_PREFLIGHT_HEADER as o, buildToolRequest as r, AGENT_PREFLIGHT_VERDICT_HEADER as s, PREFLIGHT_ARGUMENT as t };
@@ -1,5 +1,5 @@
1
1
  import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "../MessageSigner-Bd25ZJAV.js";
2
- import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "../Hash-CzrwKeDp.js";
2
+ import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "../Hash-C8aejmi8.js";
3
3
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "../Random-DbIJ22KQ.js";
4
- import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-DJtkkhiw.js";
4
+ import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "../encryption-D99Vmls3.js";
5
5
  export { Encrypter, MessageSigner, check, createEncrypter, decrypt, deriveAppKey, deriveAppKeyring, encodeDerivedKey, encrypt, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getAppKeyringFromEnv, getEncrypter, hash, hashPassword, hmac, md5, needsRehash, normalizeAppKey, parseAppKey, parsePreviousAppKeys, pick, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, sample, secureCompare, setEncrypter, sha256, sha512, shuffle, signUrl, urlSafeToken, uuid, verifyHmac, verifyPassword, verifySignedUrl };