@guren/server 2.37.1 → 2.38.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.
@@ -1,5 +1,5 @@
1
1
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
2
- import { n as createDocsViewerAccessGuard, r as isDocsViewerEnabled, t as DOCS_VIEWER_PATH } from "./endpoint-CTIzcagh.js";
2
+ import { n as createDocsViewerAccessGuard, r as isDocsViewerEnabled, t as DOCS_VIEWER_PATH } from "./endpoint-2CPw4Y_5.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import { dirname, join } from "node:path";
5
5
  import { readFile } from "node:fs/promises";
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
2
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
3
- import { a as DEV_CENTER_FEEDBACK_ROUTE, l as isMcpEndpointEnabled, n as RUNTIME_ERRORS_PATH, o as MCP_ENDPOINT_PATH, s as createMcpAccessGuard, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DLRXwp0d.js";
3
+ import { a as DEV_CENTER_FEEDBACK_ROUTE, l as isMcpEndpointEnabled, n as RUNTIME_ERRORS_PATH, o as MCP_ENDPOINT_PATH, s as createMcpAccessGuard, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-BMxBIeox.js";
4
4
  //#region src/mcp/McpServiceProvider.ts
5
5
  var McpServiceProvider_exports = /* @__PURE__ */ __exportAll({
6
6
  DEV_MCP_CLI_TOO_OLD: () => DEV_MCP_CLI_TOO_OLD,
@@ -0,0 +1,12 @@
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+ import { type DispatchedToolRoute } from '../internal/dispatched-request.js';
3
+ /** The 400 a dispatched tool call gets when a route other than its own would answer it. */
4
+ export declare function refuseMisroutedToolCall(c: Context, target: DispatchedToolRoute): Response;
5
+ /**
6
+ * Registered by `Application` ahead of every other handler. `Router.mount()` guards its own
7
+ * routes, but a route added straight to Hono (`hono.get()` in `createApp({ boot })`, which runs
8
+ * before the routes mount) carries no guard, so a dispatched request whose first matched route
9
+ * is one of those is refused here, before it runs. An `ALL` entry is passed over as middleware:
10
+ * Hono records `use()` and `all()` alike, so a `hono.all()` route ahead of the tool's is not seen.
11
+ */
12
+ export declare function guardDispatchedToolRoutes(): MiddlewareHandler;
@@ -1,2 +1,2 @@
1
- import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-CDNqcB3Q.js";
1
+ import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-CHW2ZHmh.js";
2
2
  export { PREFLIGHT_ARGUMENT, advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A channel pattern compiles to a `RegExp` without flags: `{param}` and `*` become
3
+ * `[^.]+`, `**` becomes `.+`, and the rest stays regex source, so a `.` is one code
4
+ * unit other than a line terminator and `\.` is a dot. The client picks the name, so a
5
+ * pattern with no other regex syntax is decided by a walk over reachable positions
6
+ * instead, in O(name length × pattern length), with the regex's answer; any other
7
+ * pattern is left to the backtracking regex.
8
+ */
9
+ /** Whether `name` matches `pattern`, or `undefined` when the pattern is not walkable. */
10
+ export declare function walkChannelPattern(pattern: string, name: string): boolean | undefined;
@@ -1,3 +1,3 @@
1
1
  import { l as broadcastChannelsOf, n as PresenceChannel, r as Channel, t as PrivateChannel, u as broadcastNameOf } from "../PrivateChannel-1krGz028.js";
2
- import { a as setBroadcastManager, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "../broadcasting-Bh6QoMpy.js";
2
+ import { a as setBroadcastManager, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "../broadcasting-Bk2K5oh2.js";
3
3
  export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, broadcastChannelsOf, broadcastNameOf, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -44,6 +44,95 @@ function createWebSocketOriginGuard(options = {}) {
44
44
  };
45
45
  }
46
46
  //#endregion
47
+ //#region src/broadcasting/channel-pattern.ts
48
+ /**
49
+ * A channel pattern compiles to a `RegExp` without flags: `{param}` and `*` become
50
+ * `[^.]+`, `**` becomes `.+`, and the rest stays regex source, so a `.` is one code
51
+ * unit other than a line terminator and `\.` is a dot. The client picks the name, so a
52
+ * pattern with no other regex syntax is decided by a walk over reachable positions
53
+ * instead, in O(name length × pattern length), with the regex's answer; any other
54
+ * pattern is left to the backtracking regex.
55
+ */
56
+ const VARIABLE = /\{[^}]+\}|\*\*|\*/y;
57
+ const OTHER_SYNTAX = /[\\^$+?()[\]{}|]/;
58
+ const LITERAL_ESCAPES = /* @__PURE__ */ new Set("^$\\.+?()[]|/");
59
+ const DOT = 46;
60
+ /** A literal unit an unescaped `.` leaves: any code unit but a line terminator. */
61
+ const ANY = -1;
62
+ function isSegmentUnit(code) {
63
+ return code !== DOT;
64
+ }
65
+ function isLineUnit(code) {
66
+ return code !== 10 && code !== 13 && code !== 8232 && code !== 8233;
67
+ }
68
+ /** `undefined` for a pattern holding regex syntax other than `.` and an identity escape. */
69
+ function parseChannelPattern(pattern) {
70
+ const parts = {
71
+ leading: [],
72
+ steps: []
73
+ };
74
+ let literal = parts.leading;
75
+ let position = 0;
76
+ while (position < pattern.length) {
77
+ VARIABLE.lastIndex = position;
78
+ const variable = VARIABLE.exec(pattern);
79
+ if (variable) {
80
+ literal = [];
81
+ parts.steps.push({
82
+ run: variable[0] === "**" ? isLineUnit : isSegmentUnit,
83
+ literal
84
+ });
85
+ position = VARIABLE.lastIndex;
86
+ continue;
87
+ }
88
+ const character = pattern[position];
89
+ if (character === "\\") {
90
+ const escaped = pattern[position + 1];
91
+ if (escaped === void 0 || !LITERAL_ESCAPES.has(escaped)) return void 0;
92
+ literal.push(escaped.charCodeAt(0));
93
+ position += 2;
94
+ continue;
95
+ }
96
+ if (OTHER_SYNTAX.test(character)) return void 0;
97
+ literal.push(character === "." ? ANY : character.charCodeAt(0));
98
+ position += 1;
99
+ }
100
+ return parts;
101
+ }
102
+ function literalAt(name, position, literal) {
103
+ for (let offset = 0; offset < literal.length; offset++) {
104
+ const code = literal[offset];
105
+ const unit = name.charCodeAt(position + offset);
106
+ if (code === ANY ? !isLineUnit(unit) : code !== unit) return false;
107
+ }
108
+ return true;
109
+ }
110
+ function afterLiteral(reach, name, literal) {
111
+ if (literal.length === 0) return reach;
112
+ const next = new Uint8Array(reach.length);
113
+ for (let position = 0; position + literal.length < reach.length; position++) if (reach[position] === 1 && literalAt(name, position, literal)) next[position + literal.length] = 1;
114
+ return next;
115
+ }
116
+ function afterRun(reach, name, accepts) {
117
+ const next = new Uint8Array(reach.length);
118
+ for (let position = 1; position < reach.length; position++) if ((reach[position - 1] === 1 || next[position - 1] === 1) && accepts(name.charCodeAt(position - 1))) next[position] = 1;
119
+ return next;
120
+ }
121
+ /** Whether `name` matches `pattern`, or `undefined` when the pattern is not walkable. */
122
+ function walkChannelPattern(pattern, name) {
123
+ const parts = parseChannelPattern(pattern);
124
+ if (parts === void 0) return void 0;
125
+ if (parts.leading.length > name.length || !literalAt(name, 0, parts.leading)) return false;
126
+ let reach = new Uint8Array(name.length + 1);
127
+ reach[parts.leading.length] = 1;
128
+ for (const step of parts.steps) {
129
+ reach = afterRun(reach, name, step.run);
130
+ reach = afterLiteral(reach, name, step.literal);
131
+ if (!reach.includes(1)) return false;
132
+ }
133
+ return reach[name.length] === 1;
134
+ }
135
+ //#endregion
47
136
  //#region src/broadcasting/drivers/MemoryDriver.ts
48
137
  /**
49
138
  * Keeps subscriptions and presence data in memory — for testing and
@@ -444,6 +533,8 @@ var BroadcastManager = class {
444
533
  return this.channelRegistrations.find((reg) => this.matchPattern(reg.pattern, channelName));
445
534
  }
446
535
  matchPattern(pattern, channelName) {
536
+ const walked = walkChannelPattern(pattern, channelName);
537
+ if (walked !== void 0) return walked;
447
538
  const regexPattern = pattern.replace(/\{[^}]+\}/g, "[^.]+").replace(/\*\*/g, ".+").replace(/\*/g, "[^.]+");
448
539
  return new RegExp(`^${regexPattern}$`).test(channelName);
449
540
  }
@@ -4,7 +4,7 @@ import chalk from "chalk";
4
4
  import figlet from "figlet";
5
5
  import standard from "figlet/importable-fonts/Standard.js";
6
6
  //#region package.json
7
- var version = "2.37.1";
7
+ var version = "2.38.0";
8
8
  //#endregion
9
9
  //#region src/http/dev-banner.ts
10
10
  var dev_banner_exports = /* @__PURE__ */ __exportAll({
@@ -19,25 +19,39 @@ const AGENT_PREFLIGHT_HEADER = "X-Guren-Agent-Preflight";
19
19
  const AGENT_PREFLIGHT_VERDICT_HEADER = "X-Guren-Agent-Preflight-Verdict";
20
20
  //#endregion
21
21
  //#region src/internal/dispatched-request.ts
22
- /**
23
- * Which `Request` objects the agent dispatcher built (RFC 0016 §3), keyed on
24
- * **object identity** like the principal seam in `agent-principal.ts`: a
25
- * request that crosses a socket arrives as a new object and carries nothing,
26
- * so seeing the mark means the request was handed to `app.fetch` in this
27
- * process. Not `isAgentToolRequest()` in `agent-request.ts`, whose header any
28
- * client can send: that one only picks the shape of a refusal.
29
- * Not exported from the package index.
30
- */
31
- const dispatched = /* @__PURE__ */ new WeakSet();
32
- /** Mark `request` as built by `buildToolRequest`, returning that same object. */
33
- function markDispatchedToolRequest(request) {
34
- dispatched.add(request);
22
+ const dispatched = /* @__PURE__ */ new WeakMap();
23
+ /** Mark `request` as built by `buildToolRequest` for `route`, returning that same object. */
24
+ function markDispatchedToolRequest(request, route) {
25
+ dispatched.set(request, {
26
+ method: route.method,
27
+ path: route.path,
28
+ name: route.name
29
+ });
35
30
  return request;
36
31
  }
37
32
  /** Whether this exact object was built by the dispatcher in this process. */
38
33
  function isDispatchedToolRequest(request) {
39
34
  return dispatched.has(request);
40
35
  }
36
+ /**
37
+ * The route this exact object was built for, or `undefined` for any other
38
+ * request. `Router.mount()` refuses it on every other route: a path parameter
39
+ * equal to an earlier route's literal segment would otherwise run a route the
40
+ * scope and approval gates never judged.
41
+ */
42
+ function readDispatchedToolRoute(request) {
43
+ return dispatched.get(request);
44
+ }
45
+ const routeEntries = /* @__PURE__ */ new WeakSet();
46
+ /** Record `handler` as the first handler of a route `Router.mount()` registered, returning it. */
47
+ function markRouterRouteEntry(handler) {
48
+ routeEntries.add(handler);
49
+ return handler;
50
+ }
51
+ /** Whether `handler` opens a route `Router.mount()` registered, which checks the dispatched route itself. */
52
+ function isRouterRouteEntry(handler) {
53
+ return typeof handler === "function" && routeEntries.has(handler);
54
+ }
41
55
  //#endregion
42
56
  //#region src/agent/dispatch.ts
43
57
  /** How many characters of a non-JSON response body survive into the result. */
@@ -118,7 +132,11 @@ function buildToolRequest(tool, args, options = {}) {
118
132
  method,
119
133
  headers,
120
134
  body
121
- })) };
135
+ }), {
136
+ method,
137
+ path: tool.path,
138
+ name: tool.routeName
139
+ }) };
122
140
  }
123
141
  /**
124
142
  * The contract a property was declared under, or undefined if the derivation
@@ -296,4 +314,4 @@ function isRecord(value) {
296
314
  return typeof value === "object" && value !== null && !Array.isArray(value);
297
315
  }
298
316
  //#endregion
299
- export { mapToolResponse as a, AGENT_PREFLIGHT_VERDICT_HEADER as c, describeBuildFailure as i, advertisesStructuredOutput as n, isDispatchedToolRequest as o, buildToolRequest as r, AGENT_PREFLIGHT_HEADER as s, PREFLIGHT_ARGUMENT as t };
317
+ export { mapToolResponse as a, markRouterRouteEntry as c, AGENT_PREFLIGHT_VERDICT_HEADER as d, describeBuildFailure as i, readDispatchedToolRoute as l, advertisesStructuredOutput as n, isDispatchedToolRequest as o, buildToolRequest as r, isRouterRouteEntry as s, PREFLIGHT_ARGUMENT as t, AGENT_PREFLIGHT_HEADER as u };
@@ -1,4 +1,4 @@
1
- import { t as createLoopbackGuard } from "./loopback-guard-CG8xB4v0.js";
1
+ import { t as createLoopbackGuard } from "./loopback-guard-BygAEGIE.js";
2
2
  //#region src/docs-viewer/endpoint.ts
3
3
  const DOCS_VIEWER_PATH = "/_guren/docs";
4
4
  /**
@@ -13,7 +13,7 @@ export type { Session, SessionData, SessionStore } from './session.js';
13
13
  export { requireAuthenticated, requireGuest, attachAuthContext, type AuthContext, type RequireAuthOptions, } from './auth.js';
14
14
  export { createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, XSRF_HEADER_NAME, XSRF_COOKIE_NAME, type CsrfOptions, type CookielessAuthEndpoints, } from './csrf.js';
15
15
  export { validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, type ValidationSchema, type ValidateRequestOptions, } from './validation.js';
16
- export { createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, type RateLimitOptions, type RateLimitStore, type RateLimitEntry, type RateLimitInfo, } from './rate-limit.js';
16
+ export { createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, resolveClientIp, type RateLimitOptions, type RateLimitStore, type TrustProxy, type RateLimitEntry, type RateLimitInfo, } from './rate-limit.js';
17
17
  export { createSecurityHeaders, type SecurityHeadersOptions, type HstsOptions, } from './security-headers.js';
18
18
  export { createCspMiddleware, getCspNonce, CSP_NONCE_KEY, type CspOptions, type CspDirectives, } from './csp.js';
19
19
  export { createHostAuthorizationMiddleware, type HostAuthorizationOptions, } from './host-authorization.js';
@@ -66,14 +66,31 @@ export interface RateLimitOptions {
66
66
  */
67
67
  now?: () => number;
68
68
  /**
69
- * Trust reverse-proxy headers for client IP, in order: `CF-Connecting-IP`,
70
- * `True-Client-IP`, `X-Real-IP`, first entry of `X-Forwarded-For`; falls back
71
- * to `server.requestIP()`. Enable ONLY behind a proxy that sets or strips
72
- * them, or clients spoof them to bypass limits. Ignored with a custom `keyGenerator`.
69
+ * Read the client IP from what a reverse proxy adds rather than from `server.requestIP()`.
70
+ * `true` is `{ hops: 1 }`. Enable ONLY when every request passes through that proxy, or
71
+ * clients send the header themselves to bypass limits. Ignored with a custom `keyGenerator`.
73
72
  * @default false
74
73
  */
75
- trustProxy?: boolean;
74
+ trustProxy?: TrustProxy;
76
75
  }
76
+ /**
77
+ * Which proxy-added value names the client. `{ hops: n }` is the `n`th `X-Forwarded-For` entry
78
+ * from the right: proxies append, so only the entries your own `n` proxies wrote are theirs.
79
+ * `{ header }` is one single-value header your proxy overwrites, such as `cf-connecting-ip`.
80
+ * A port on the value (`203.0.113.7:50001`, `[2001:db8::7]:50001`) is dropped. Absent, or with
81
+ * fewer entries than hops, the socket address is used.
82
+ */
83
+ export type TrustProxy = boolean | {
84
+ hops: number;
85
+ } | {
86
+ header: string;
87
+ };
88
+ /**
89
+ * The client IP a rate limiter keys on: the proxy-added value `trustProxy` names, else
90
+ * `server.requestIP()`, else `undefined` (tests, non-Bun runtimes, Lambda). For a custom
91
+ * `keyGenerator` that should read the same address the built-in one does.
92
+ */
93
+ export declare function resolveClientIp(ctx: Context, trustProxy?: TrustProxy): string | undefined;
77
94
  /**
78
95
  * Create a rate limiting middleware.
79
96
  * @example
package/dist/index.d.ts CHANGED
@@ -57,9 +57,9 @@ export { InertiaServiceProvider, AuthServiceProvider, OAuthServiceProvider, Even
57
57
  export { FormRequest } from './http/FormRequest.js';
58
58
  export { AuthManager, SessionGuard, TokenGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, Argon2Hasher, 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';
59
59
  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';
60
- export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, BUILT_IN_SESSION_DRIVERS, PER_PROCESS_SESSION_DRIVERS, 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, createWebSocketOriginGuard, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
60
+ export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, BUILT_IN_SESSION_DRIVERS, PER_PROCESS_SESSION_DRIVERS, 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, resolveClientIp, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createWebSocketOriginGuard, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
61
61
  export { AUTH_CONTEXT_KEY } from './http/middleware/auth.js';
62
- export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, SessionInlineCodec, CookieSessionStoreOptions, CookieSessionDriverOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, WebSocketOriginOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
62
+ export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, SessionInlineCodec, CookieSessionStoreOptions, CookieSessionDriverOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, TrustProxy, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, WebSocketOriginOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
63
63
  export { Validator, FieldValidator, createValidator, quickValidate, quickValidateOrThrow, required, nullable, requiredIf, requiredUnless, requiredWith, requiredWithout, string as stringRule, numeric, integer, boolean as booleanRule, array as arrayRule, object as objectRule, email as emailRule, url as urlRule, uuid as uuidRule, ip, ipv4, ipv6, json as jsonRule, alpha, alphaNum, alphaDash, regex, min, max, between, size, inValues, notIn, confirmed, same, different, date as dateRule, dateFormat, after, afterOrEqual, before, beforeOrEqual, startsWith, endsWith, file as fileRule, image as imageRule, mimes, maxFileSize, minFileSize, custom, unique, exists, } from './http/validation/index.js';
64
64
  export type { ValidationRule, RuleDefinition, ValidationResult, FileValidationOptions, ImageValidationOptions, ValidatorOptions, FileLike, } from './http/validation/index.js';
65
65
  export { Event, EventManager, createEventManager, createQueueEventDispatcher, Listener, RequestReceived, RequestFinished, UserAuthenticated, UserLoggedOut, JobProcessed, JobFailed, ApplicationStarted, ApplicationShutdown, } from './events/index.js';
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { i as setValidatedInput, n as getValidatedInput } from "./validated-inpu
4
4
  import { n as NOT_FOUND_MESSAGE, t as HttpException } from "./HttpException-2tfZGamp.js";
5
5
  import { n as ValidationException } from "./errors-C8neC8go.js";
6
6
  import { a as withAuthorization, c as capabilitiesOf, i as derivableAbility, l as mergeCapabilities, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as stampCapabilities } from "./authorization-rxx6aprN.js";
7
- import { a as mapToolResponse, c as AGENT_PREFLIGHT_VERDICT_HEADER, i as describeBuildFailure, n as advertisesStructuredOutput, o as isDispatchedToolRequest, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "./dispatch-CDNqcB3Q.js";
7
+ import { a as mapToolResponse, c as markRouterRouteEntry, d as AGENT_PREFLIGHT_VERDICT_HEADER, i as describeBuildFailure, l as readDispatchedToolRoute, n as advertisesStructuredOutput, o as isDispatchedToolRequest, r as buildToolRequest, s as isRouterRouteEntry, t as PREFLIGHT_ARGUMENT } from "./dispatch-CHW2ZHmh.js";
8
8
  import { t as trimSlashes } from "./trim-slashes-BLY9hKAa.js";
9
9
  import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
10
10
  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-DIUT1Yao.js";
@@ -24,13 +24,13 @@ import { n as getRequestContainer, r as tryGetRequestContainer, t as CONTAINER_C
24
24
  import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
25
25
  import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-Bi5U8N5P.js";
26
26
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
27
- import { c as isDevCenterFeedbackRequest, i as loadRuntimeErrorsModule, l as isMcpEndpointEnabled, r as captureRuntimeError, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DLRXwp0d.js";
27
+ import { c as isDevCenterFeedbackRequest, i as loadRuntimeErrorsModule, l as isMcpEndpointEnabled, r as captureRuntimeError, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-BMxBIeox.js";
28
28
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
29
- import { a as setBroadcastManager, c as createWebSocketOriginGuard, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "./broadcasting-Bh6QoMpy.js";
29
+ import { a as setBroadcastManager, c as createWebSocketOriginGuard, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "./broadcasting-Bk2K5oh2.js";
30
30
  import { c as tc, d as Translator, f as getPluralizationRule, i as getI18n, l as tryGetI18n, m as selectPluralForm, n as I18nManager, o as setI18n, p as pluralizationRules, r as createI18n, s as t, t as MemoryLoader, u as JsonLoader } from "./i18n-BShPpJZa.js";
31
31
  import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
32
32
  import { a as cannot, f as setGate, h as hasComposedMessage, i as can, l as getGate, m as NotFoundHttpException, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-BHyDcDKo.js";
33
- import { r as isDocsViewerEnabled } from "./endpoint-CTIzcagh.js";
33
+ import { r as isDocsViewerEnabled } from "./endpoint-2CPw4Y_5.js";
34
34
  import { c as isViteProduction, d as formatHostPort, f as isWildcardHost, i as clientManifestCandidates, l as loadViteManifest, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BdXRybeq.js";
35
35
  import { a as closeOwnedViteDevServer, c as registerBunTeardown, d as setActiveBunServer, f as stopActiveBunServer, i as adoptViteDevServer, l as releaseActiveBunServer, m as stopBunServerBounded, n as startViteDevServer, o as getGlobalState, p as stopActiveViteDevServer, s as hotReloadStopBound, t as readViteDevServerPort, u as reusableActiveViteDevServer } from "./vite-dev-server-Ag90otai.js";
36
36
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
@@ -38,7 +38,7 @@ import { a as NotificationManager, c as setNotificationManager, d as getNotifica
38
38
  import { a as RequestFinished, c as UserLoggedOut, d as EventManager, f as createEventManager, i as JobProcessed, l as createQueueEventDispatcher, n as ApplicationStarted, o as RequestReceived, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "./events-DW197Nur.js";
39
39
  import { a as getJob, d as resolveQueueDriver, f as setQueueDriver, l as registerJob, n as clearJobRegistry, o as getQueueDriver, r as clearQueueDriver, s as getRegisteredJobs, t as Job, u as resolveJobName } from "./Job-0Prk8k0z.js";
40
40
  import { a as processJob, c as RedisDriver$1, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver$1 } from "./queue-K4Bi6NRy.js";
41
- import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-D4AP4_Wd.js";
41
+ import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-zf30qXfp.js";
42
42
  import { a as LOG_LEVEL_PRIORITY, i as matchDailyFileDate, n as dailyFileDateStamp, r as dailyFilePath, t as DailyFileChannel } from "./DailyFileChannel-CTTPA0EF.js";
43
43
  import { a as FileChannel, i as setLogManager, n as createLogManager, o as ConsoleChannel, r as getLogManager, t as LogManager } from "./logging-Br9bZlaG.js";
44
44
  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-S0OvCuR8.js";
@@ -47,6 +47,7 @@ import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as Memory
47
47
  import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "./health-Wi_05kkf.js";
48
48
  import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, p as MemorySchedulerLock, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-iLkx4gID.js";
49
49
  import { Hono } from "hono";
50
+ import { matchedRoutes } from "hono/route";
50
51
  import { deleteCookie, getCookie } from "hono/cookie";
51
52
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
52
53
  import { join, resolve as resolve$1 } from "node:path";
@@ -66,6 +67,30 @@ function mountRoute(app, method, path, ...handlers) {
66
67
  app.on(method, path, ...handlers);
67
68
  }
68
69
  //#endregion
70
+ //#region src/agent/dispatched-route-guard.ts
71
+ /** The 400 a dispatched tool call gets when a route other than its own would answer it. */
72
+ function refuseMisroutedToolCall(c, target) {
73
+ return c.json({ message: `The tool call reached a different route than the tool's own (${target.method} ${target.path}), so nothing was run. A path parameter equal to another route's literal segment selects that route.` }, 400);
74
+ }
75
+ /**
76
+ * Registered by `Application` ahead of every other handler. `Router.mount()` guards its own
77
+ * routes, but a route added straight to Hono (`hono.get()` in `createApp({ boot })`, which runs
78
+ * before the routes mount) carries no guard, so a dispatched request whose first matched route
79
+ * is one of those is refused here, before it runs. An `ALL` entry is passed over as middleware:
80
+ * Hono records `use()` and `all()` alike, so a `hono.all()` route ahead of the tool's is not seen.
81
+ */
82
+ function guardDispatchedToolRoutes() {
83
+ return async function guardDispatchedToolRoutes(c, next) {
84
+ const target = readDispatchedToolRoute(c.req.raw);
85
+ if (target === void 0) return next();
86
+ for (const entry of matchedRoutes(c).slice(c.req.routeIndex + 1)) {
87
+ if (isRouterRouteEntry(entry.handler)) break;
88
+ if (entry.method !== "ALL") return refuseMisroutedToolCall(c, target);
89
+ }
90
+ return next();
91
+ };
92
+ }
93
+ //#endregion
69
94
  //#region src/mvc/prototype.ts
70
95
  const PROTOTYPE_HANDLER = Symbol.for("guren.prototype.handler");
71
96
  const prototype = Object.freeze({ [PROTOTYPE_HANDLER]: true });
@@ -437,6 +462,7 @@ var Router = class {
437
462
  if (contractMiddleware) chain.push(contractMiddleware);
438
463
  if (preflightMiddleware) chain.push(preflightMiddleware);
439
464
  chain.push(handler);
465
+ chain[0] = markRouterRouteEntry(guardDispatchedRoute(route, chain[0]));
440
466
  return {
441
467
  route,
442
468
  chain
@@ -816,6 +842,23 @@ function throwOnInvalid(schema, data) {
816
842
  return result.data;
817
843
  }
818
844
  /**
845
+ * `first`, refusing a request `buildToolRequest` built for another route (RFC 0016 §3):
846
+ * a path value equal to an earlier route's literal segment (`new` on `/posts/:id`,
847
+ * behind `/posts/new`) would run a route the scope and approval gates never judged.
848
+ * The refusal calls neither `first` nor `next()`, which would run this route's rest. Any
849
+ * other request reaches `first` as Hono called it; `length` and `name` are kept for `hono/dev`.
850
+ */
851
+ function guardDispatchedRoute(route, first) {
852
+ const guarded = function(c, next) {
853
+ const target = readDispatchedToolRoute(c.req.raw);
854
+ if (target === void 0 || target.method === route.method.toUpperCase() && target.path === route.path && target.name === route.name) return first.call(this, c, next);
855
+ return Promise.resolve(refuseMisroutedToolCall(c, target));
856
+ };
857
+ Object.defineProperty(guarded, "length", { value: first.length });
858
+ Object.defineProperty(guarded, "name", { value: first.name });
859
+ return guarded;
860
+ }
861
+ /**
819
862
  * The preflight seam: what a request must pass before the handler, reported
820
863
  * instead of executed. Mounted last, so the chain in front really ran; only
821
864
  * `.agent()` routes honour the header. An inline handler's contract is checked
@@ -1700,25 +1743,63 @@ var MemoryRateLimitStore = class extends BaseMemoryStore {
1700
1743
  }
1701
1744
  };
1702
1745
  let defaultKeyGeneratorWarned = false;
1703
- const PROXY_IP_HEADERS = [
1746
+ const UNREAD_PROXY_HEADERS = [
1704
1747
  "cf-connecting-ip",
1705
1748
  "true-client-ip",
1706
1749
  "x-real-ip"
1707
1750
  ];
1708
- function clientIpFromProxyHeaders(ctx) {
1709
- for (const header of PROXY_IP_HEADERS) {
1710
- const value = ctx.req.header(header)?.trim();
1711
- if (value) return value;
1712
- }
1713
- const forwardedFor = ctx.req.header("x-forwarded-for");
1714
- if (forwardedFor) {
1715
- const first = forwardedFor.split(",")[0]?.trim();
1716
- if (first) return first;
1751
+ let unreadProxyHeaderWarned = false;
1752
+ const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9a-z]+$/;
1753
+ function proxySource(trustProxy) {
1754
+ if (trustProxy === false) return void 0;
1755
+ if (trustProxy === true) return { hops: 1 };
1756
+ if ("hops" in trustProxy) {
1757
+ if (!Number.isInteger(trustProxy.hops) || trustProxy.hops < 1) throw new TypeError(`trustProxy.hops must be a positive integer, got ${String(trustProxy.hops)}.`);
1758
+ return { hops: trustProxy.hops };
1759
+ }
1760
+ const header = typeof trustProxy.header === "string" ? trustProxy.header.trim().toLowerCase() : "";
1761
+ if (header === "") throw new TypeError("trustProxy.header must name a request header.");
1762
+ if (!HEADER_NAME.test(header)) throw new TypeError(`trustProxy.header must be a valid header name, got ${JSON.stringify(trustProxy.header)}.`);
1763
+ if (header === "x-forwarded-for") throw new TypeError("trustProxy.header cannot be x-forwarded-for, a list clients add to; use trustProxy: { hops } for it.");
1764
+ return { header };
1765
+ }
1766
+ function withoutPort(address) {
1767
+ if (address.startsWith("[")) {
1768
+ const close = address.indexOf("]");
1769
+ return close > 1 ? address.slice(1, close) : address;
1770
+ }
1771
+ const colon = address.indexOf(":");
1772
+ return colon > 0 && colon === address.lastIndexOf(":") ? address.slice(0, colon) : address;
1773
+ }
1774
+ function proxyClientIp(ctx, source) {
1775
+ const address = proxyValue(ctx, source);
1776
+ return address ? withoutPort(address) || void 0 : void 0;
1777
+ }
1778
+ function proxyValue(ctx, source) {
1779
+ if ("header" in source) return ctx.req.header(source.header)?.trim() || void 0;
1780
+ if (!unreadProxyHeaderWarned && UNREAD_PROXY_HEADERS.some((name) => ctx.req.header(name) !== void 0)) {
1781
+ unreadProxyHeaderWarned = true;
1782
+ console.warn("[guren] Rate limiter: trustProxy keys on the X-Forwarded-For entries your proxies append and does not read CF-Connecting-IP, True-Client-IP or X-Real-IP, which a client can send. If your proxy overwrites one of them, pass trustProxy: { header: 'cf-connecting-ip' }; behind two proxies, trustProxy: { hops: 2 }. See: https://guren.dev/docs/guides/rate-limiting");
1783
+ }
1784
+ const entries = (ctx.req.header("x-forwarded-for") ?? "").split(",").map((entry) => entry.trim());
1785
+ if (entries.length < source.hops) return void 0;
1786
+ return entries[entries.length - source.hops] || void 0;
1787
+ }
1788
+ function socketAddress(ctx) {
1789
+ const env = ctx.env;
1790
+ if (env?.server && typeof env.server.requestIP === "function") {
1791
+ const info = env.server.requestIP(ctx.req.raw);
1792
+ if (info?.address) return info.address;
1717
1793
  }
1718
- return null;
1719
1794
  }
1720
- function proxyAwareKeyGenerator(ctx) {
1721
- return clientIpFromProxyHeaders(ctx) ?? defaultKeyGenerator(ctx);
1795
+ /**
1796
+ * The client IP a rate limiter keys on: the proxy-added value `trustProxy` names, else
1797
+ * `server.requestIP()`, else `undefined` (tests, non-Bun runtimes, Lambda). For a custom
1798
+ * `keyGenerator` that should read the same address the built-in one does.
1799
+ */
1800
+ function resolveClientIp(ctx, trustProxy) {
1801
+ const source = proxySource(trustProxy ?? false);
1802
+ return (source ? proxyClientIp(ctx, source) : void 0) ?? socketAddress(ctx);
1722
1803
  }
1723
1804
  /**
1724
1805
  * Per-client limiting via Bun's `server.requestIP()`. Where that is unavailable
@@ -1726,12 +1807,9 @@ function proxyAwareKeyGenerator(ctx) {
1726
1807
  * over-restrictive but safe — production should supply a custom `keyGenerator`.
1727
1808
  * Proxy headers are not trusted by default; they are spoofable on direct deploys.
1728
1809
  */
1729
- function defaultKeyGenerator(ctx) {
1730
- const env = ctx.env;
1731
- if (env?.server && typeof env.server.requestIP === "function") {
1732
- const info = env.server.requestIP(ctx.req.raw);
1733
- if (info?.address) return info.address;
1734
- }
1810
+ function defaultKeyGenerator(ctx, source) {
1811
+ const address = (source ? proxyClientIp(ctx, source) : void 0) ?? socketAddress(ctx);
1812
+ if (address) return address;
1735
1813
  if (!defaultKeyGeneratorWarned) {
1736
1814
  defaultKeyGeneratorWarned = true;
1737
1815
  console.warn("[guren] Rate limiter: could not determine client IP via server.requestIP(). Falling back to shared per-route bucket (__shared__:METHOD:PATH). For per-client limiting, supply a custom keyGenerator option. See: https://guren.dev/docs/guides/rate-limiting");
@@ -1749,6 +1827,9 @@ function getDefaultStore() {
1749
1827
  if (!defaultStore) defaultStore = new MemoryRateLimitStore();
1750
1828
  return defaultStore;
1751
1829
  }
1830
+ function keyGeneratorFor(source) {
1831
+ return source ? (ctx) => defaultKeyGenerator(ctx, source) : (ctx) => defaultKeyGenerator(ctx);
1832
+ }
1752
1833
  /**
1753
1834
  * Create a rate limiting middleware.
1754
1835
  * @example
@@ -1757,7 +1838,7 @@ function getDefaultStore() {
1757
1838
  * ```
1758
1839
  */
1759
1840
  function createRateLimitMiddleware(options = {}) {
1760
- const { limit = 100, windowMs = 6e4, trustProxy = false, keyGenerator = trustProxy ? proxyAwareKeyGenerator : defaultKeyGenerator, store = options.now ? new MemoryRateLimitStore(0, options.now) : getDefaultStore(), skip, onRateLimited, headers = true, message = "Too many requests, please try again later.", statusCode = 429, keyPrefix = "rl:", now = () => Date.now() } = options;
1841
+ const { limit = 100, windowMs = 6e4, trustProxy = false, keyGenerator = keyGeneratorFor(proxySource(trustProxy)), store = options.now ? new MemoryRateLimitStore(0, options.now) : getDefaultStore(), skip, onRateLimited, headers = true, message = "Too many requests, please try again later.", statusCode = 429, keyPrefix = "rl:", now = () => Date.now() } = options;
1761
1842
  return async (ctx, next) => {
1762
1843
  if (skip && await skip(ctx)) return next();
1763
1844
  const baseKey = await keyGenerator(ctx);
@@ -3239,6 +3320,11 @@ function deriveAgentTools(definitions) {
3239
3320
  const tools = [];
3240
3321
  const warnings = [];
3241
3322
  const claimed = /* @__PURE__ */ new Map();
3323
+ const routeKeys = /* @__PURE__ */ new Map();
3324
+ for (const definition of definitions) {
3325
+ const key = dispatchKey(definition);
3326
+ routeKeys.set(key, (routeKeys.get(key) ?? 0) + 1);
3327
+ }
3242
3328
  for (const definition of definitions) {
3243
3329
  const agent = definition.agent;
3244
3330
  if (!agent) continue;
@@ -3254,6 +3340,10 @@ function deriveAgentTools(definitions) {
3254
3340
  }
3255
3341
  const routeName = definition.name;
3256
3342
  const toolName = agent.toolName ?? routeName;
3343
+ if ((routeKeys.get(dispatchKey(definition)) ?? 0) > 1) {
3344
+ warnings.push(`${toolName}: ${where} (route "${routeName}") shares its method, path and name with another route, so a tool call could not tell them apart and it is not exposed. Give one of them a distinct name.`);
3345
+ continue;
3346
+ }
3257
3347
  const existing = claimed.get(toolName);
3258
3348
  if (existing) {
3259
3349
  warnings.push(`${toolName}: ${where} (route "${routeName}") claims a tool name already derived from ${existing.method} ${existing.path} (route "${existing.routeName}") — the later route is not exposed. Give one of them a distinct agent toolName.`);
@@ -3426,6 +3516,9 @@ function deriveAgentToolUi(declared) {
3426
3516
  visibility: Array.from(new Set(visibility))
3427
3517
  };
3428
3518
  }
3519
+ function dispatchKey(definition) {
3520
+ return `${definition.method.toUpperCase()} ${definition.path} ${definition.name ?? ""}`;
3521
+ }
3429
3522
  //#endregion
3430
3523
  //#region src/introspection/plain-json.ts
3431
3524
  /**
@@ -3711,7 +3804,7 @@ let devBanner;
3711
3804
  */
3712
3805
  async function loadDevBanner() {
3713
3806
  if (typeof process === "undefined") return devBanner;
3714
- if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-DV_Xjsw8.js").then((n) => n.n);
3807
+ if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-Xs_6yqeA.js").then((n) => n.n);
3715
3808
  return devBanner;
3716
3809
  }
3717
3810
  /**
@@ -3972,8 +4065,8 @@ var Application = class {
3972
4065
  this.bootSequence ??= new BootSequence([
3973
4066
  () => this.options.boot?.(this.hono),
3974
4067
  () => this.mountRoutes(),
3975
- () => this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BOeQyt7u.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?"),
3976
- () => this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-DzrxQoYh.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?"),
4068
+ () => this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-D-xP6jdi.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?"),
4069
+ () => this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-D9cILya-.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?"),
3977
4070
  () => this.providerManager.bootAll(),
3978
4071
  () => this.warnOnUnconfiguredAuth()
3979
4072
  ]);
@@ -4000,6 +4093,7 @@ var Application = class {
4000
4093
  ctx.set(CONTAINER_CONTEXT_KEY, container);
4001
4094
  return next();
4002
4095
  });
4096
+ this.hono.use("*", guardDispatchedToolRoutes());
4003
4097
  const { securityHeaders } = this.options;
4004
4098
  if (securityHeaders !== false) this.hono.use("*", createSecurityHeaders(securityHeaders ?? {}));
4005
4099
  this.mountHostAuthorization();
@@ -7893,4 +7987,4 @@ function defineStorageConfig(resolve) {
7893
7987
  //#region src/index.ts
7894
7988
  ensureErrorStackTracePolyfill();
7895
7989
  //#endregion
7896
- export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BUILT_IN_SESSION_DRIVERS, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CONTAINER_CONTEXT_KEY, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, Env, EnvSchema, EnvValidationError, EnvVar, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySchedulerLock, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PORTABLE_AGENT_TOOL_NAME_PATTERN, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, always, ambientBinding, ambientContainer, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, broadcastChannelsOf, broadcastNameOf, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, clearQueueDriver, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentCallBudget, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueEventDispatcher, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, createWebSocketOriginGuard, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defaultApplication, defaultContainer, defer, defineCacheConfig, defineConfig, defineEnv, defineFactory, defineGate, defineHttpConfig, defineMailConfig, defineMiddleware, defineModule, defineOAuthConfig, definePlugin, definePolicy, defineQueueConfig, defineStorageConfig, deriveAgentToolUi, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestContainer, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isAlwaysProp, isDeferredProp, isDue, isDueInTimezone, isEmailVerified, isIntrospecting, isLiveProp, isRawEnvKey, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, live, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, prototype, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, recordEnvReads, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetDefaultApplication, resetRateLimit, resolve, resolveAgentAuditSink, resolveJobName, resolveNotifiableType, resolveOptional, resolveQueueDriver, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, tryGetRequestContainer, unique, url as urlRule, urlSafeToken, useAsDefaultApplication, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
7990
+ export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BUILT_IN_SESSION_DRIVERS, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CONTAINER_CONTEXT_KEY, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, Env, EnvSchema, EnvValidationError, EnvVar, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySchedulerLock, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PORTABLE_AGENT_TOOL_NAME_PATTERN, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, always, ambientBinding, ambientContainer, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, broadcastChannelsOf, broadcastNameOf, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, clearQueueDriver, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentCallBudget, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueEventDispatcher, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, createWebSocketOriginGuard, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defaultApplication, defaultContainer, defer, defineCacheConfig, defineConfig, defineEnv, defineFactory, defineGate, defineHttpConfig, defineMailConfig, defineMiddleware, defineModule, defineOAuthConfig, definePlugin, definePolicy, defineQueueConfig, defineStorageConfig, deriveAgentToolUi, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestContainer, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isAlwaysProp, isDeferredProp, isDue, isDueInTimezone, isEmailVerified, isIntrospecting, isLiveProp, isRawEnvKey, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, live, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, prototype, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, recordEnvReads, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetDefaultApplication, resetRateLimit, resolve, resolveAgentAuditSink, resolveClientIp, resolveJobName, resolveNotifiableType, resolveOptional, resolveQueueDriver, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, tryGetRequestContainer, unique, url as urlRule, urlSafeToken, useAsDefaultApplication, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
@@ -1,4 +1,30 @@
1
- /** Mark `request` as built by `buildToolRequest`, returning that same object. */
2
- export declare function markDispatchedToolRequest(request: Request): Request;
1
+ /**
2
+ * Which `Request` objects the agent dispatcher built (RFC 0016 §3), keyed on
3
+ * **object identity** like the principal seam in `agent-principal.ts`: a
4
+ * request that crosses a socket arrives as a new object and carries nothing,
5
+ * so seeing the mark means the request was handed to `app.fetch` in this
6
+ * process. Not `isAgentToolRequest()` in `agent-request.ts`, whose header any
7
+ * client can send: that one only picks the shape of a refusal.
8
+ * Not exported from the package index.
9
+ */
10
+ /** The route a dispatched request was built for, as `Router.definitions()` names it. */
11
+ export interface DispatchedToolRoute {
12
+ method: string;
13
+ path: string;
14
+ name: string;
15
+ }
16
+ /** Mark `request` as built by `buildToolRequest` for `route`, returning that same object. */
17
+ export declare function markDispatchedToolRequest(request: Request, route: DispatchedToolRoute): Request;
3
18
  /** Whether this exact object was built by the dispatcher in this process. */
4
19
  export declare function isDispatchedToolRequest(request: Request): boolean;
20
+ /**
21
+ * The route this exact object was built for, or `undefined` for any other
22
+ * request. `Router.mount()` refuses it on every other route: a path parameter
23
+ * equal to an earlier route's literal segment would otherwise run a route the
24
+ * scope and approval gates never judged.
25
+ */
26
+ export declare function readDispatchedToolRoute(request: Request): DispatchedToolRoute | undefined;
27
+ /** Record `handler` as the first handler of a route `Router.mount()` registered, returning it. */
28
+ export declare function markRouterRouteEntry<T extends object>(handler: T): T;
29
+ /** Whether `handler` opens a route `Router.mount()` registered, which checks the dispatched route itself. */
30
+ export declare function isRouterRouteEntry(handler: unknown): boolean;
@@ -65,4 +65,4 @@ function createLoopbackGuard(resource) {
65
65
  };
66
66
  }
67
67
  //#endregion
68
- export { createLoopbackGuard as t };
68
+ export { isLoopbackAddress as n, createLoopbackGuard as t };
@@ -1,2 +1,2 @@
1
- import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "../mail-D4AP4_Wd.js";
1
+ import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "../mail-zf30qXfp.js";
2
2
  export { LogTransport, Mail, MailManager, MemoryTransport, ResendTransport, SmtpTransport, createMailManager, getMailManager, mail, setMailManager };
@@ -71,7 +71,8 @@ export interface SmtpTransportOptions {
71
71
  /**
72
72
  * Fail the send when the server does not upgrade with STARTTLS, rather than continue in cleartext.
73
73
  * Without it, an on-path attacker can strip STARTTLS from the EHLO reply and read `auth`.
74
- * @default false
74
+ * Set `false` for a relay you reach over a network you control that takes `auth` without STARTTLS.
75
+ * @default true when `auth` has a user or password, `secure` is off and `host` is not localhost, 127.x or ::1
75
76
  */
76
77
  requireTLS?: boolean;
77
78
  /** Node TLS options for the connection, such as `ca` for a relay on a private CA. */
@@ -1,9 +1,40 @@
1
1
  import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
2
2
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter, i as bindAmbient, n as ambientBinding } from "./default-application-s9SE-Er7.js";
3
+ import { n as isLoopbackAddress } from "./loopback-guard-BygAEGIE.js";
3
4
  import { c as pinnedQueueDriver, d as resolveQueueDriver, i as enqueueJob, l as registerJob, t as Job } from "./Job-0Prk8k0z.js";
4
5
  import { t as parseMailAddress } from "./address-D0Iq-XIH.js";
5
6
  import nodemailer from "nodemailer";
6
7
  //#region src/mail/transports/SmtpTransport.ts
8
+ /**
9
+ * Whether a stripped STARTTLS would put credentials on the network in cleartext. A host on this
10
+ * machine is left out, since a local mail catcher speaks no TLS; `'localhost'` is nodemailer's
11
+ * own fallback for an empty host.
12
+ */
13
+ function sendsCredentialsOffHost(options) {
14
+ if (options.secure || !(options.auth?.user || options.auth?.pass)) return false;
15
+ const host = (options.host || "localhost").toLowerCase();
16
+ return host !== "localhost" && !isLoopbackAddress(canonicalAddress(host));
17
+ }
18
+ /**
19
+ * An IP literal as the WHATWG URL parser writes it (`0:0:0:0:0:0:0:1` as `::1`, `127.1` as
20
+ * `127.0.0.1`), with an IPv4-mapped IPv6 address back in dotted form; any other host unchanged.
21
+ */
22
+ function canonicalAddress(host) {
23
+ const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
24
+ let hostname;
25
+ try {
26
+ hostname = new URL(`http://${bare.includes(":") ? `[${bare}]` : bare}/`).hostname;
27
+ } catch {
28
+ return host;
29
+ }
30
+ if (!hostname.startsWith("[")) return hostname;
31
+ const address = hostname.slice(1, -1);
32
+ const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(address);
33
+ if (!mapped) return address;
34
+ const high = Number.parseInt(mapped[1], 16);
35
+ const low = Number.parseInt(mapped[2], 16);
36
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
37
+ }
7
38
  /** Format an email address for nodemailer. */
8
39
  function formatAddress(addr) {
9
40
  if (addr.name) {
@@ -21,7 +52,7 @@ var SmtpTransport = class {
21
52
  host: options.host,
22
53
  port: options.port ?? 587,
23
54
  secure: options.secure ?? false,
24
- requireTLS: options.requireTLS ?? false,
55
+ requireTLS: options.requireTLS ?? sendsCredentialsOffHost(options),
25
56
  tls: options.tls,
26
57
  auth: options.auth,
27
58
  pool: options.pool ?? true,
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as McpServiceProvider } from "../McpServiceProvider-BOeQyt7u.js";
1
+ import { t as McpServiceProvider } from "../McpServiceProvider-D-xP6jdi.js";
2
2
  export { McpServiceProvider };
@@ -4,7 +4,7 @@ import { n as hash } from "../Hash-D2DFd8xX.js";
4
4
  import { a as getManifestCss, c as isViteProduction, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-BdXRybeq.js";
5
5
  import { n as startViteDevServer } from "../vite-dev-server-Ag90otai.js";
6
6
  import { n as isRealPathWithin, t as isPathWithin } from "../contained-path-DOVauNQC.js";
7
- import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-DV_Xjsw8.js";
7
+ import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-Xs_6yqeA.js";
8
8
  import { createRequire } from "node:module";
9
9
  import { dirname, extname, join, resolve } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
@@ -1,5 +1,5 @@
1
1
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
2
- import { t as createLoopbackGuard } from "./loopback-guard-CG8xB4v0.js";
2
+ import { t as createLoopbackGuard } from "./loopback-guard-BygAEGIE.js";
3
3
  //#region src/mcp/endpoint.ts
4
4
  const MCP_ENDPOINT_PATH = "/_guren/mcp";
5
5
  /** Where the Dev Center saves a plan review's feedback (RFC 0030 §8), its one write route. */
@@ -46,7 +46,7 @@ let loading;
46
46
  * a call no define can settle. `tests/mcp/runtime-errors.test.ts` pins the form.
47
47
  */
48
48
  function loadRuntimeErrorsModule() {
49
- if (typeof process !== "undefined" && process.env.NODE_ENV !== "production" && isMcpEndpointEnabled()) return loading ??= import("./runtime-errors-Dh7nA2-p.js");
49
+ if (typeof process !== "undefined" && process.env.NODE_ENV !== "production" && isMcpEndpointEnabled()) return loading ??= import("./runtime-errors-JYzoOvb7.js");
50
50
  }
51
51
  /** Only ExceptionHandler calls this, after applying its dontReport policy. */
52
52
  function captureRuntimeError(error, ctx, status) {
@@ -1,7 +1,7 @@
1
1
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
2
- import { n as RUNTIME_ERRORS_PATH, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DLRXwp0d.js";
3
- import { realpathSync, statSync } from "node:fs";
2
+ import { n as RUNTIME_ERRORS_PATH, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-BMxBIeox.js";
4
3
  import { routePath } from "hono/route";
4
+ import { realpathSync, statSync } from "node:fs";
5
5
  //#region src/mcp/runtime-errors.ts
6
6
  var RuntimeErrorBuffer = class {
7
7
  root;
@@ -376,7 +376,7 @@ function ensurePrototype(config, options) {
376
376
  output.entryFileNames ??= options.entryFileNames;
377
377
  output.chunkFileNames ??= options.chunkFileNames;
378
378
  output.assetFileNames ??= options.assetFileNames;
379
- output.manualChunks ??= createDefaultManualChunks(root);
379
+ applyManualChunks(output, root, options.manualChunks);
380
380
  config.build.rollupOptions.output = output;
381
381
  return {
382
382
  root,
@@ -505,29 +505,41 @@ function ensureBuild(config, options, root, env) {
505
505
  if (output.entryFileNames === void 0) output.entryFileNames = options.entryFileNames;
506
506
  if (output.chunkFileNames === void 0) output.chunkFileNames = options.chunkFileNames;
507
507
  if (output.assetFileNames === void 0) output.assetFileNames = options.assetFileNames;
508
- if (!isSsrBuild && output.manualChunks === void 0) output.manualChunks = createDefaultManualChunks(root);
508
+ if (!isSsrBuild) applyManualChunks(output, root, options.manualChunks);
509
509
  config.build.rollupOptions.output = output;
510
510
  }
511
511
  /** `@guren/inertia-client`'s prototype entry (src or dist) and the Hono router it alone imports. */
512
512
  const PROTOTYPE_RUNTIME_MODULE = /\/inertia-client\/(?:src|dist)\/prototype(?:-[^/]+)?\.[jt]sx?$|\/node_modules\/hono\/dist\/router\//u;
513
- function createDefaultManualChunks(root) {
513
+ function applyManualChunks(output, root, custom) {
514
+ if (output.manualChunks !== void 0) {
515
+ if (custom) console.warn("[guren] The `manualChunks` plugin option is unused: `build.rollupOptions.output.manualChunks` is set and decides every chunk. Remove one of the two.");
516
+ return;
517
+ }
518
+ output.manualChunks = createManualChunks(root, custom);
519
+ }
520
+ function createManualChunks(root, custom) {
514
521
  const normalizedRoot = root.replace(/\\/gu, "/");
515
522
  return (id) => {
516
523
  const normalizedId = id.replace(/\\/gu, "/");
517
- if (PROTOTYPE_RUNTIME_MODULE.test(normalizedId)) return;
518
- if (normalizedId.includes("/packages/inertia-client/")) return "inertia-vendor";
519
- if (normalizedId.includes("/packages/core/") || normalizedId.includes("/packages/server/") || normalizedId.includes("/packages/orm/")) return "framework-vendor";
520
- if (!normalizedId.includes("/node_modules/")) {
521
- if (normalizedId.startsWith(normalizedRoot)) return;
522
- if (normalizedId.includes("/packages/")) return "framework-vendor";
523
- return;
524
- }
525
- if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/u.test(normalizedId)) return "react-vendor";
526
- if (/[\\/]node_modules[\\/]@inertiajs[\\/]/u.test(normalizedId) || /[\\/]node_modules[\\/](axios|qs|lodash-es|lodash)[\\/]/u.test(normalizedId)) return "inertia-vendor";
527
- if (/[\\/]node_modules[\\/](@guren|hono)[\\/]/u.test(normalizedId)) return "framework-vendor";
528
- return "vendor";
524
+ const chosen = custom?.(normalizedId);
525
+ if (chosen !== void 0) return chosen ?? void 0;
526
+ return defaultManualChunk(normalizedId, normalizedRoot);
529
527
  };
530
528
  }
529
+ function defaultManualChunk(normalizedId, normalizedRoot) {
530
+ if (PROTOTYPE_RUNTIME_MODULE.test(normalizedId)) return;
531
+ if (normalizedId.includes("/packages/inertia-client/")) return "inertia-vendor";
532
+ if (normalizedId.includes("/packages/core/") || normalizedId.includes("/packages/server/") || normalizedId.includes("/packages/orm/")) return "framework-vendor";
533
+ if (!normalizedId.includes("/node_modules/")) {
534
+ if (normalizedId.startsWith(normalizedRoot)) return;
535
+ if (normalizedId.includes("/packages/")) return "framework-vendor";
536
+ return;
537
+ }
538
+ if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/u.test(normalizedId)) return "react-vendor";
539
+ if (/[\\/]node_modules[\\/]@inertiajs[\\/]/u.test(normalizedId) || /[\\/]node_modules[\\/](axios|qs|lodash-es|lodash)[\\/]/u.test(normalizedId)) return "inertia-vendor";
540
+ if (/[\\/]node_modules[\\/](@guren|hono)[\\/]/u.test(normalizedId)) return "framework-vendor";
541
+ return "vendor";
542
+ }
531
543
  function resolveBuildOutputDirectory(root, outDir) {
532
544
  return path.isAbsolute(outDir) ? outDir : path.resolve(root, outDir);
533
545
  }
@@ -26,11 +26,22 @@ export interface GurenVitePluginOptions {
26
26
  chunkFileNames?: string;
27
27
  /** Rollup naming pattern for extracted assets (defaults to `[name]-[hash][extname]`). */
28
28
  assetFileNames?: string;
29
+ /**
30
+ * Chooses a module's chunk ahead of the built-in vendor grouping, for the client
31
+ * and prototype builds. Unused when `build.rollupOptions.output.manualChunks` is set.
32
+ */
33
+ manualChunks?: GurenManualChunks;
29
34
  /** Prototype mode (`vite --mode prototype`, RFC 0021): the static, server-less build. */
30
35
  prototype?: GurenPrototypeOptions;
31
36
  /** MCP App mode (`vite build --mode mcp-app`, RFC 0038): one inlined document per `.agent({ ui })` page. */
32
37
  mcpApp?: GurenMcpAppOptions;
33
38
  }
39
+ /**
40
+ * `id` is the module's path with forward slashes. Return a chunk name, `null` to
41
+ * name no chunk (the bundler splits the module by how it is imported), or
42
+ * `undefined` to keep the built-in grouping.
43
+ */
44
+ export type GurenManualChunks = (id: string) => string | null | undefined;
34
45
  export interface GurenPrototypeOptions {
35
46
  /** Vite `base` for a build hosted under a subpath (a GitHub project page, a preview URL). Defaults to `/`. */
36
47
  base?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.37.1",
3
+ "version": "2.38.0",
4
4
  "description": "HTTP layer of the Guren framework, on Hono: routing, controllers, middleware, auth, sessions, queues and the AWS Lambda adapter. Applications import it through @guren/core.",
5
5
  "keywords": [
6
6
  "guren",
@@ -172,7 +172,7 @@
172
172
  "test": "bun test"
173
173
  },
174
174
  "dependencies": {
175
- "@guren/orm": "^2.16.1",
175
+ "@guren/orm": "^2.17.0",
176
176
  "chalk": "^5.3.0",
177
177
  "consola": "^3.4.2",
178
178
  "figlet": "^1.7.0",