@guren/server 2.33.0 → 2.35.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 (54) hide show
  1. package/dist/{Gate-COWQbA96.js → Gate-BHyDcDKo.js} +58 -10
  2. package/dist/{HttpException-BlQ2yEmT.js → HttpException-2tfZGamp.js} +8 -2
  3. package/dist/{McpServiceProvider-BDDr-7lh.js → McpServiceProvider-CXOokGax.js} +1 -1
  4. package/dist/{Resource-LQT1L4j0.js → Resource-y-7zzZSB.js} +43 -32
  5. package/dist/agent/scopes.d.ts +7 -0
  6. package/dist/{api-token-BbgDEd6j.js → api-token-1-INqeVU.js} +187 -2
  7. package/dist/auth/AuthManager.d.ts +4 -1
  8. package/dist/auth/TokenGuard.d.ts +4 -1
  9. package/dist/auth/api-token.d.ts +11 -1
  10. package/dist/auth/index.js +2 -2
  11. package/dist/{auth-DRMeSwev.js → auth-CO9MlQNE.js} +16 -24
  12. package/dist/authorization/Gate.d.ts +9 -5
  13. package/dist/authorization/index.js +2 -2
  14. package/dist/{authorization-DEHuBps5.js → authorization-rxx6aprN.js} +1 -1
  15. package/dist/broadcasting/index.js +1 -1
  16. package/dist/{broadcasting-CcevVE5Y.js → broadcasting-D04a3R02.js} +3 -2
  17. package/dist/{context-af2n5abO.js → context--l2HdOhy.js} +1 -1
  18. package/dist/{dev-banner-CSjrSNZi.js → dev-banner-BUrHz-LF.js} +7 -3
  19. package/dist/errors/ExceptionHandler.d.ts +7 -2
  20. package/dist/errors/HttpException.d.ts +6 -0
  21. package/dist/errors/debug-page.d.ts +1 -1
  22. package/dist/errors/exceptions/NotFoundHttpException.d.ts +2 -0
  23. package/dist/errors/redact-query-params.d.ts +16 -0
  24. package/dist/errors/wants-html.d.ts +7 -0
  25. package/dist/{errors-JpkcCjjn.js → errors-C8neC8go.js} +1 -1
  26. package/dist/health/index.js +1 -1
  27. package/dist/{health-Bg0Xj3aD.js → health-Wi_05kkf.js} +2 -1
  28. package/dist/http/Application.d.ts +12 -0
  29. package/dist/http/dev-banner.d.ts +6 -1
  30. package/dist/http/middleware/csrf.d.ts +1 -1
  31. package/dist/http/middleware/redirect-safety.d.ts +8 -0
  32. package/dist/index.js +247 -275
  33. package/dist/internal/agent-principal.d.ts +12 -3
  34. package/dist/internal/redact-query-params.d.ts +1 -0
  35. package/dist/internal/redact-query-params.js +2 -0
  36. package/dist/internal/testing.d.ts +2 -1
  37. package/dist/internal/testing.js +4 -4
  38. package/dist/lambda/index.js +3 -2
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Controller.d.ts +5 -5
  41. package/dist/mvc/inertia/InertiaEngine.d.ts +6 -0
  42. package/dist/notifications/index.js +1 -1
  43. package/dist/{notifications-R7Uj-aT7.js → notifications-DV5Yr6Fl.js} +2 -1
  44. package/dist/providers/InertiaServiceProvider.d.ts +7 -0
  45. package/dist/queue/index.js +1 -1
  46. package/dist/{queue-CO07wib_.js → queue-K4Bi6NRy.js} +17 -11
  47. package/dist/redact-query-params-Ba-sAfcP.js +106 -0
  48. package/dist/runtime/index.js +1 -1
  49. package/dist/{runtime-error-capture-DzllKc0d.js → runtime-error-capture-DLRXwp0d.js} +2 -2
  50. package/dist/{runtime-errors-D229wyoc.js → runtime-errors-Dh7nA2-p.js} +1 -1
  51. package/dist/scheduling/index.js +1 -1
  52. package/dist/{scheduling-DNV5tj44.js → scheduling-iLkx4gID.js} +2 -1
  53. package/dist/support/default-headers.d.ts +6 -0
  54. package/package.json +5 -1
package/dist/index.js CHANGED
@@ -1,48 +1,49 @@
1
- import { C as setInertiaSsrRenderer, D as isDeferredProp, E as isAlwaysProp, O as ensureErrorStackTracePolyfill, S as setInertiaDocument, T as defer, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as always } from "./Resource-LQT1L4j0.js";
1
+ import { A as ensureErrorStackTracePolyfill, C as setInertiaDocument, D as defer, E as always, O as isAlwaysProp, a as renderDocument, b as inertia, c as getRequestLocale, d as mountModuleRoutes, f as definePlugin, g as shareInertiaProps, h as setInertiaSharedProps, i as Controller, k as isDeferredProp, l as getRequestTranslator, m as resolveSharedInertiaProps, n as Resource, o as LOCALE_CONTEXT_KEY, p as getInertiaSharedPropsResolver, r as collect, s as detectLocaleMiddleware, t as JsonResource, u as defineModule, w as setInertiaSsrRenderer } from "./Resource-y-7zzZSB.js";
2
2
  import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, r as formatValidationErrors } from "./request-CLOYytGP.js";
3
3
  import { i as setValidatedInput, n as getValidatedInput } from "./validated-input-D84J8wcC.js";
4
- import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
5
- import { n as ValidationException } from "./errors-JpkcCjjn.js";
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-DEHuBps5.js";
4
+ import { n as NOT_FOUND_MESSAGE, t as HttpException } from "./HttpException-2tfZGamp.js";
5
+ import { n as ValidationException } from "./errors-C8neC8go.js";
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
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-ENWpBxbE.js";
8
8
  import { i as trimSlashes } from "./contained-path-BkNSBljW.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";
11
11
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
12
- import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as normalizeRedirectTarget, G as installAgentPrincipal, H as NodeHasher, I as AuthManager, J as createSessionMiddleware, K as readAgentPrincipal, L as DEFAULT_PROVIDER, M as jsonResponse, N as hostMatchesAllowlist, O as parseOAuthRedirectUrl, P as isAppRelativePath, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, V as DefaultHasher, W as BaseUserProvider, X as getSessionFromContext, Y as defaultCookieSecure, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, j as defineMiddleware, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, q as MemorySessionStore, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "./auth-DRMeSwev.js";
12
+ import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as normalizeRedirectTarget, G as MemorySessionStore, H as NodeHasher, I as AuthManager, J as getSessionFromContext, K as createSessionMiddleware, L as DEFAULT_PROVIDER, M as jsonResponse, N as hostMatchesAllowlist, O as parseOAuthRedirectUrl, P as isAppRelativePath, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, V as DefaultHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, j as defineMiddleware, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, q as defaultCookieSecure, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "./auth-CO9MlQNE.js";
13
13
  import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
14
14
  import { t as warnOnce } from "./warn-once-p-IlMjra.js";
15
15
  import { a as defaultApplication, c as resolve, d as createContainer, f as getContainer, g as warnDeprecatedSetter, h as warnDeprecatedGetter, i as bindAmbient, l as useAsDefaultApplication, m as warnDeprecated, n as ambientBinding, o as defaultContainer, p as setContainer, r as ambientContainer, s as resetDefaultApplication, t as adoptDefaultApplication, u as Container } from "./default-application-s9SE-Er7.js";
16
16
  import { n as ServiceProvider, t as ProviderManager } from "./ServiceProvider-G0YclITd.js";
17
- import { o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
17
+ import { C as scopesAllowTool, M as markAgentDispatch, N as readAgentPrincipal, S as parseToolScope, _ as tokenCanAny, a as getApiToken, b as classifyRegistrationScope, c as hasBearerHeader, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, j as installAgentPrincipal, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, x as expandToolScopes, y as AGENT_TOOL_NAME_PATTERN } from "./api-token-1-INqeVU.js";
18
+ import { o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context--l2HdOhy.js";
18
19
  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-D2DFd8xX.js";
19
- import { _ as verifyApiToken, a as getApiToken, c as hasBearerHeader, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAny, h as tokenCanAll, i as createBearerTokenMiddleware, l as parseApiToken, m as tokenCan, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken } from "./api-token-BbgDEd6j.js";
20
+ import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
21
+ import { n as getRequestContainer, r as tryGetRequestContainer, t as CONTAINER_CONTEXT_KEY } from "./request-container-BbuH0JJy.js";
20
22
  import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
21
23
  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";
22
24
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
23
- import { c as isDevCenterFeedbackRequest, i as loadRuntimeErrorsModule, l as isMcpEndpointEnabled, r as captureRuntimeError, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DzllKc0d.js";
25
+ import { c as isDevCenterFeedbackRequest, i as loadRuntimeErrorsModule, l as isMcpEndpointEnabled, r as captureRuntimeError, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DLRXwp0d.js";
24
26
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
25
- import { a as setBroadcastManager, c as PresenceChannel, d as createWebSocketOriginGuard, 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-CcevVE5Y.js";
27
+ import { a as setBroadcastManager, c as PresenceChannel, d as createWebSocketOriginGuard, 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-D04a3R02.js";
26
28
  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";
27
- import { n as getRequestContainer, r as tryGetRequestContainer, t as CONTAINER_CONTEXT_KEY } from "./request-container-BbuH0JJy.js";
28
29
  import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
29
- import { a as cannot, f as setGate, i as can, l as getGate, n as Response$1, o as createGate, p as AuthorizationException, r as authorize, s as defineGate, t as Gate } from "./Gate-COWQbA96.js";
30
+ 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";
30
31
  import { r as isDocsViewerEnabled } from "./endpoint-CTIzcagh.js";
31
32
  import { n as isWildcardHost, t as formatHostPort } from "./host-port-t6wQFaRu.js";
32
33
  import { C as stopBunServerBounded, S as stopActiveViteDevServer, _ as registerBunTeardown, b as setActiveBunServer, c as isViteProduction, d as startViteDevServer, g as hotReloadStopBound, h as getGlobalState, i as clientManifestCandidates, l as loadViteManifest, m as closeOwnedViteDevServer, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as adoptViteDevServer, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl, v as releaseActiveBunServer, x as stopActiveBunServer, y as reusableActiveViteDevServer } from "./vite-manifest-DO0pU1vm.js";
33
34
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
34
35
  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, p as Event, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as Listener } from "./events-B6gfJkCH.js";
35
- import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-R7Uj-aT7.js";
36
+ import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-DV5Yr6Fl.js";
36
37
  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";
37
- 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-CO07wib_.js";
38
+ 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";
38
39
  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-BQ2y2U5c.js";
39
40
  import { a as LOG_LEVEL_PRIORITY, i as matchDailyFileDate, n as dailyFileDateStamp, r as dailyFilePath, t as DailyFileChannel } from "./DailyFileChannel-CTTPA0EF.js";
40
41
  import { a as FileChannel, i as setLogManager, n as createLogManager, o as ConsoleChannel, r as getLogManager, t as LogManager } from "./logging-Br9bZlaG.js";
41
42
  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";
42
43
  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-BS-FGkqS.js";
43
44
  import { a as LocalDriver, i as S3Driver, n as createStorageManager, r as MemoryDriver$2, t as StorageManager } from "./storage-YPbsV9ju.js";
44
- 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-Bg0Xj3aD.js";
45
- 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-DNV5tj44.js";
45
+ 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";
46
+ 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";
46
47
  import { Hono } from "hono";
47
48
  import { deleteCookie, getCookie } from "hono/cookie";
48
49
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
@@ -1224,6 +1225,105 @@ var SessionManager = class {
1224
1225
  }
1225
1226
  };
1226
1227
  //#endregion
1228
+ //#region src/errors/error-page.ts
1229
+ function escapeHtml$1(value) {
1230
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1231
+ }
1232
+ /** Production error page: no stack traces or internal details are exposed. */
1233
+ function renderErrorPage(statusCode, message) {
1234
+ const title = STATUS_TITLES[statusCode] ?? "Error";
1235
+ return `<!DOCTYPE html>
1236
+ <html lang="en">
1237
+ <head>
1238
+ <meta charset="utf-8">
1239
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1240
+ <title>${statusCode} ${title}</title>
1241
+ <style>
1242
+ /* Guren UI's tokens (github.com/gurenjs/guren-ui); the link home is the screen's one crimson fill. */
1243
+ :root {
1244
+ color-scheme: light;
1245
+ --g-page: #ffffff; --g-heading: #111827; --g-text-2: #4b5563; --g-muted: #6b7280;
1246
+ --g-accent: #db1b1b; --g-accent-down: #b91c1c; --g-on-accent: #fff5f5;
1247
+ }
1248
+ @media (prefers-color-scheme: dark) {
1249
+ :root { color-scheme: dark; --g-page: #1a1a2e; --g-heading: #e0def4; --g-text-2: #aeabc9; --g-muted: #8d89a7; }
1250
+ }
1251
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1252
+ body {
1253
+ font-family: 'Noto Sans JP', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
1254
+ min-height: 100vh;
1255
+ display: flex;
1256
+ align-items: center;
1257
+ justify-content: center;
1258
+ background: var(--g-page);
1259
+ color: var(--g-heading);
1260
+ -webkit-font-smoothing: antialiased;
1261
+ }
1262
+ .container { text-align: center; padding: 2rem; }
1263
+ .status { font: 700 6rem/1 'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace; color: var(--g-muted); }
1264
+ .title { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.01em; margin-top: 1rem; }
1265
+ .description { color: var(--g-text-2); margin-top: 0.5rem; max-width: 28rem; }
1266
+ .home-link {
1267
+ display: inline-block; margin-top: 2rem; padding: 8px 16px;
1268
+ background: var(--g-accent); color: var(--g-on-accent); border-radius: 8px;
1269
+ text-decoration: none; font-size: 13.5px; font-weight: 700;
1270
+ }
1271
+ .home-link:hover { background: var(--g-accent-down); }
1272
+ .home-link:focus-visible { outline: 2px solid var(--g-accent); outline-offset: 2px; }
1273
+ </style>
1274
+ </head>
1275
+ <body>
1276
+ <main class="container">
1277
+ <div class="status">${statusCode}</div>
1278
+ <h1 class="title">${title}</h1>
1279
+ <p class="description">${escapeHtml$1(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
1280
+ <a href="/" class="home-link">Go Home</a>
1281
+ </main>
1282
+ </body>
1283
+ </html>`;
1284
+ }
1285
+ const STATUS_TITLES = {
1286
+ 400: "Bad Request",
1287
+ 401: "Unauthorized",
1288
+ 403: "Forbidden",
1289
+ 404: "Not Found",
1290
+ 405: "Method Not Allowed",
1291
+ 408: "Request Timeout",
1292
+ 419: "Page Expired",
1293
+ 422: "Unprocessable Entity",
1294
+ 429: "Too Many Requests",
1295
+ 500: "Server Error",
1296
+ 502: "Bad Gateway",
1297
+ 503: "Service Unavailable",
1298
+ 504: "Gateway Timeout"
1299
+ };
1300
+ const STATUS_DESCRIPTIONS = {
1301
+ 400: "The request could not be understood by the server.",
1302
+ 401: "You need to sign in to access this page.",
1303
+ 403: "You do not have permission to access this page.",
1304
+ 404: "The page you are looking for could not be found.",
1305
+ 405: "The request method is not supported for this page.",
1306
+ 419: "Your session has expired. Please refresh and try again.",
1307
+ 422: "The submitted data was invalid.",
1308
+ 429: "You are making too many requests. Please slow down.",
1309
+ 500: "Something went wrong on our end. Please try again later.",
1310
+ 502: "The server received an invalid response from an upstream server.",
1311
+ 503: "The service is temporarily unavailable. Please try again later.",
1312
+ 504: "The server did not receive a timely response from an upstream server."
1313
+ };
1314
+ //#endregion
1315
+ //#region src/errors/wants-html.ts
1316
+ /**
1317
+ * A browser navigation: it accepts HTML and is not an Inertia visit, an XHR or a
1318
+ * JSON caller, each of which needs a JSON payload. `ExceptionHandler` and the
1319
+ * CSRF middleware both answer an HTML page by this one rule.
1320
+ */
1321
+ function wantsHtmlResponse(ctx) {
1322
+ if (!ctx?.req?.header) return false;
1323
+ const accept = ctx.req.header("accept") ?? "";
1324
+ return !(accept.includes("application/json") || ctx.req.header("x-requested-with") === "XMLHttpRequest" || ctx.req.header("x-inertia") === "true") && accept.includes("text/html");
1325
+ }
1326
+ //#endregion
1227
1327
  //#region src/http/middleware/csrf.ts
1228
1328
  const CSRF_TOKEN_KEY = "_csrf_token";
1229
1329
  const CSRF_HEADER_NAME = "X-CSRF-TOKEN";
@@ -1236,6 +1336,9 @@ const DEFAULT_PROTECTED_METHODS = [
1236
1336
  "PATCH",
1237
1337
  "DELETE"
1238
1338
  ];
1339
+ /** Laravel's "Page Expired"; `renderErrorPage()` titles it so, where a 403 page would read "Forbidden". */
1340
+ const CSRF_PAGE_EXPIRED_STATUS = 419;
1341
+ const CSRF_PAGE_EXPIRED_MESSAGE = "This form expired before it was sent. Go back, reload the page and submit the form again.";
1239
1342
  const CSRF_CONTEXT_KEY = "guren:csrf-token";
1240
1343
  const CSRF_PURPOSE = "csrf";
1241
1344
  function createCsrfSigner() {
@@ -1425,12 +1528,24 @@ function createCsrfMiddleware(options = {}, cookielessAuthEndpoints) {
1425
1528
  }
1426
1529
  if (!verifyCsrfToken(ctx, await getTokenFromRequest(ctx))) {
1427
1530
  if (onError) return onError(ctx);
1428
- return jsonResponse({ message: "CSRF token mismatch" }, 403);
1531
+ return csrfMismatchResponse(ctx);
1429
1532
  }
1430
1533
  await next();
1431
1534
  settleCookie(ctx);
1432
1535
  };
1433
1536
  }
1537
+ /**
1538
+ * A form posted before the page hydrated carries no header token, and a browser
1539
+ * would show the JSON as the page. Every other caller keeps the 403 JSON, whose
1540
+ * message `@guren/testing`'s `withCsrf()` hint and the docs quote.
1541
+ */
1542
+ function csrfMismatchResponse(ctx) {
1543
+ if (!wantsHtmlResponse(ctx)) return jsonResponse({ message: "CSRF token mismatch" }, 403);
1544
+ return new Response(renderErrorPage(CSRF_PAGE_EXPIRED_STATUS, CSRF_PAGE_EXPIRED_MESSAGE), {
1545
+ status: CSRF_PAGE_EXPIRED_STATUS,
1546
+ headers: { "Content-Type": "text/html; charset=UTF-8" }
1547
+ });
1548
+ }
1434
1549
  function setXsrfCookie(ctx, token, options = {}) {
1435
1550
  const { path = "/", secure = defaultCookieSecure(), sameSite = "Lax" } = options;
1436
1551
  ctx.header("Set-Cookie", `${XSRF_COOKIE_NAME}=${encodeURIComponent(token)}; Path=${path}; SameSite=${sameSite}${secure ? "; Secure" : ""}`, { append: true });
@@ -1939,6 +2054,24 @@ function isSafeRedirectUrl(url, requestUrl, allowedHosts = []) {
1939
2054
  return false;
1940
2055
  }
1941
2056
  }
2057
+ /**
2058
+ * The path of a `Referer` on one of `acceptedHosts` (as `URL.host` spells them,
2059
+ * port included), for redirecting back, or `fallback`. A relative Referer resolves
2060
+ * against `requestUrl`. The scheme is not compared: behind a TLS-terminating proxy
2061
+ * the request reads `http:` while the browser's Referer reads `https:`. Only the
2062
+ * path and query are kept, so the browser stays on its own origin.
2063
+ */
2064
+ function sameHostRefererPath(referer, requestUrl, acceptedHosts, fallback = "/") {
2065
+ if (!referer) return fallback;
2066
+ try {
2067
+ const target = new URL(referer, requestUrl);
2068
+ if (target.protocol !== "http:" && target.protocol !== "https:" || !acceptedHosts.includes(target.host)) return fallback;
2069
+ const pathname = normalizeRedirectTarget(target.pathname);
2070
+ return isAppRelativePath(pathname) ? `${pathname}${target.search}` : fallback;
2071
+ } catch {
2072
+ return fallback;
2073
+ }
2074
+ }
1942
2075
  //#endregion
1943
2076
  //#region src/http/middleware/force-https.ts
1944
2077
  /**
@@ -2124,96 +2257,10 @@ var AuthServiceProvider = class extends ServiceProvider {
2124
2257
  }
2125
2258
  };
2126
2259
  //#endregion
2127
- //#region src/errors/error-page.ts
2128
- function escapeHtml$1(value) {
2129
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2130
- }
2131
- /** Production error page: no stack traces or internal details are exposed. */
2132
- function renderErrorPage(statusCode, message) {
2133
- const title = STATUS_TITLES[statusCode] ?? "Error";
2134
- return `<!DOCTYPE html>
2135
- <html lang="en">
2136
- <head>
2137
- <meta charset="utf-8">
2138
- <meta name="viewport" content="width=device-width, initial-scale=1">
2139
- <title>${statusCode} ${title}</title>
2140
- <style>
2141
- /* Guren UI's tokens (github.com/gurenjs/guren-ui); the link home is the screen's one crimson fill. */
2142
- :root {
2143
- color-scheme: light;
2144
- --g-page: #ffffff; --g-heading: #111827; --g-text-2: #4b5563; --g-line-strong: #d1d5db;
2145
- --g-accent: #db1b1b; --g-accent-down: #b91c1c; --g-on-accent: #fff5f5;
2146
- }
2147
- @media (prefers-color-scheme: dark) {
2148
- :root { color-scheme: dark; --g-page: #1a1a2e; --g-heading: #e0def4; --g-text-2: #908caa; --g-line-strong: #3d3d5c; }
2149
- }
2150
- * { margin: 0; padding: 0; box-sizing: border-box; }
2151
- body {
2152
- font-family: 'Noto Sans JP', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
2153
- min-height: 100vh;
2154
- display: flex;
2155
- align-items: center;
2156
- justify-content: center;
2157
- background: var(--g-page);
2158
- color: var(--g-heading);
2159
- -webkit-font-smoothing: antialiased;
2160
- }
2161
- .container { text-align: center; padding: 2rem; }
2162
- .status { font: 700 6rem/1 'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace; color: var(--g-line-strong); }
2163
- .title { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.01em; margin-top: 1rem; }
2164
- .description { color: var(--g-text-2); margin-top: 0.5rem; max-width: 28rem; }
2165
- .home-link {
2166
- display: inline-block; margin-top: 2rem; padding: 8px 16px;
2167
- background: var(--g-accent); color: var(--g-on-accent); border-radius: 8px;
2168
- text-decoration: none; font-size: 13.5px; font-weight: 700;
2169
- }
2170
- .home-link:hover { background: var(--g-accent-down); }
2171
- .home-link:focus-visible { outline: 2px solid var(--g-accent); outline-offset: 2px; }
2172
- </style>
2173
- </head>
2174
- <body>
2175
- <div class="container">
2176
- <div class="status">${statusCode}</div>
2177
- <h1 class="title">${title}</h1>
2178
- <p class="description">${escapeHtml$1(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
2179
- <a href="/" class="home-link">Go Home</a>
2180
- </div>
2181
- </body>
2182
- </html>`;
2183
- }
2184
- const STATUS_TITLES = {
2185
- 400: "Bad Request",
2186
- 401: "Unauthorized",
2187
- 403: "Forbidden",
2188
- 404: "Not Found",
2189
- 405: "Method Not Allowed",
2190
- 408: "Request Timeout",
2191
- 419: "Page Expired",
2192
- 422: "Unprocessable Entity",
2193
- 429: "Too Many Requests",
2194
- 500: "Server Error",
2195
- 502: "Bad Gateway",
2196
- 503: "Service Unavailable",
2197
- 504: "Gateway Timeout"
2198
- };
2199
- const STATUS_DESCRIPTIONS = {
2200
- 400: "The request could not be understood by the server.",
2201
- 401: "You need to sign in to access this page.",
2202
- 403: "You do not have permission to access this page.",
2203
- 404: "The page you are looking for could not be found.",
2204
- 405: "The request method is not supported for this page.",
2205
- 419: "Your session has expired. Please refresh and try again.",
2206
- 422: "The submitted data was invalid.",
2207
- 429: "You are making too many requests. Please slow down.",
2208
- 500: "Something went wrong on our end. Please try again later.",
2209
- 502: "The server received an invalid response from an upstream server.",
2210
- 503: "The service is temporarily unavailable. Please try again later.",
2211
- 504: "The server did not receive a timely response from an upstream server."
2212
- };
2213
- //#endregion
2214
2260
  //#region src/errors/debug-page.ts
2215
2261
  /** Development-only error page: exposes the stack trace and request details. */
2216
- function renderDebugPage(error, request) {
2262
+ function renderDebugPage(thrown, request) {
2263
+ const error = redactQueryParams(thrown);
2217
2264
  const errorName = error.name || "Error";
2218
2265
  const errorMessage = escapeHtml(error.message || "An unknown error occurred");
2219
2266
  const stackFrames = parseStackTrace(error.stack ?? "");
@@ -2234,7 +2281,7 @@ function renderDebugPage(error, request) {
2234
2281
  --g-font-sans: 'Noto Sans JP', ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
2235
2282
  --g-font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
2236
2283
  --g-page: #ffffff; --g-panel: #ffffff; --g-raised: #fffafa; --g-line: #e5e7eb; --g-line-strong: #d1d5db;
2237
- --g-heading: #111827; --g-text: #1f2937; --g-text-2: #4b5563; --g-muted: #9ca3af;
2284
+ --g-heading: #111827; --g-text: #1f2937; --g-text-2: #4b5563; --g-muted: #6b7280;
2238
2285
  --g-danger: #b91c1c; --g-danger-chip: #f23a3a; --g-danger-tint: #fff1f2; --g-accent: #db1b1b;
2239
2286
  --g-shadow-card: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
2240
2287
  }
@@ -2242,7 +2289,7 @@ function renderDebugPage(error, request) {
2242
2289
  :root {
2243
2290
  color-scheme: dark;
2244
2291
  --g-page: #1a1a2e; --g-panel: #1e1e34; --g-raised: #232340; --g-line: #2e2e4a; --g-line-strong: #3d3d5c;
2245
- --g-heading: #e0def4; --g-text: #e0def4; --g-text-2: #908caa; --g-muted: #6e6a86;
2292
+ --g-heading: #e0def4; --g-text: #e0def4; --g-text-2: #aeabc9; --g-muted: #8d89a7;
2246
2293
  --g-danger: #ffa5a5; --g-danger-tint: rgba(242, 58, 58, 0.12);
2247
2294
  --g-shadow-card: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2);
2248
2295
  }
@@ -2270,8 +2317,8 @@ function renderDebugPage(error, request) {
2270
2317
  .stack-frames { display: flex; flex-direction: column; gap: 2px; }
2271
2318
  .frame { padding: 0.6rem 0.75rem; border-radius: 8px; cursor: default; transition: background 0.15s; }
2272
2319
  .frame:hover { background: var(--g-raised); }
2273
- .frame.vendor { opacity: 0.5; }
2274
- .frame.vendor:hover { opacity: 0.75; }
2320
+ /* Dimmed by color: an opacity fades this text under the 4.5:1 that small text needs. */
2321
+ .frame.vendor .frame-method, .frame.vendor .frame-location { color: var(--g-muted); }
2275
2322
  .frame-header { display: flex; align-items: center; gap: 0.75rem; font-size: 0.875rem; }
2276
2323
  .frame-index { color: var(--g-muted); font: 500 0.75rem var(--g-font-mono); min-width: 2rem; flex-shrink: 0; }
2277
2324
  .frame-method { color: var(--g-heading); font-family: var(--g-font-mono); font-weight: 500; }
@@ -2297,17 +2344,19 @@ function renderDebugPage(error, request) {
2297
2344
  </head>
2298
2345
  <body>
2299
2346
  <div class="container">
2300
- <header class="error-header">
2301
- <div class="status-badge">${statusCode}</div>
2302
- <div class="error-info">
2303
- <h1 class="error-class">${escapeHtml(errorName)}</h1>
2304
- <p class="error-message">${errorMessage}</p>
2305
- </div>
2306
- </header>
2347
+ <main>
2348
+ <header class="error-header">
2349
+ <div class="status-badge">${statusCode}</div>
2350
+ <div class="error-info">
2351
+ <h1 class="error-class">${escapeHtml(errorName)}</h1>
2352
+ <p class="error-message">${errorMessage}</p>
2353
+ </div>
2354
+ </header>
2307
2355
 
2308
- ${stackSection}
2309
- ${requestSection}
2310
- ${environmentSection}
2356
+ ${stackSection}
2357
+ ${requestSection}
2358
+ ${environmentSection}
2359
+ </main>
2311
2360
 
2312
2361
  <footer class="footer">
2313
2362
  <p>Guren Framework &mdash; Debug Error Page</p>
@@ -2527,7 +2576,9 @@ var ExceptionHandler = class {
2527
2576
  if (this.options.debug !== void 0) return this.options.debug;
2528
2577
  return process.env.NODE_ENV !== "production";
2529
2578
  }
2530
- async handle(error, ctx) {
2579
+ /** Reporters and renderers receive the error with SQL bound parameters redacted. */
2580
+ async handle(thrown, ctx) {
2581
+ const error = redactQueryParams(thrown);
2531
2582
  if (!this.shouldNotReport(error)) captureRuntimeError(error, ctx, resolveExceptionStatus(error));
2532
2583
  await this.reportException(error);
2533
2584
  return this.renderException(error, ctx);
@@ -2538,7 +2589,7 @@ var ExceptionHandler = class {
2538
2589
  for (const reporter of this.reporters) try {
2539
2590
  await reporter(error);
2540
2591
  } catch (reporterError) {
2541
- console.error("Exception reporter failed:", reporterError);
2592
+ console.error("Exception reporter failed:", redactQueryParams(reporterError));
2542
2593
  }
2543
2594
  }
2544
2595
  shouldNotReport(error) {
@@ -2557,26 +2608,34 @@ var ExceptionHandler = class {
2557
2608
  renderDefaultException(error, ctx) {
2558
2609
  const debug = this.shouldShowDetails();
2559
2610
  const statusCode = resolveExceptionStatus(error);
2611
+ const replacement = !debug && statusCode === 404 && hasComposedNotFoundMessage(error) ? NOT_FOUND_MESSAGE : void 0;
2560
2612
  let body;
2561
- if (HttpException.isHttpException(error)) body = error.toResponse(debug).body;
2562
- else {
2563
- body = { message: statusCode < 500 || debug ? error.message : "Internal Server Error" };
2613
+ if (HttpException.isHttpException(error)) {
2614
+ body = error.toResponse(debug).body;
2615
+ if (replacement !== void 0 && body.message === error.message) body = {
2616
+ ...body,
2617
+ message: replacement
2618
+ };
2619
+ } else {
2620
+ body = { message: replacement ?? (statusCode < 500 || debug ? error.message : "Internal Server Error") };
2564
2621
  if (debug) {
2565
2622
  body.exception = error.name;
2566
2623
  body.stack = error.stack;
2567
2624
  }
2568
2625
  }
2569
2626
  if (this.wantsHtmlResponse(ctx)) {
2570
- const html = debug && statusCode >= 500 ? renderDebugPage(error, ctx.req.raw) : renderErrorPage(statusCode, body.message);
2627
+ const html = debug && statusCode >= 500 ? renderDebugPage(error, ctx.req.raw) : renderErrorPage(statusCode, statusCode === 404 && body.message === "Not Found" ? void 0 : body.message);
2571
2628
  return ctx.html(html, statusCode);
2572
2629
  }
2573
2630
  return ctx.json(body, statusCode);
2574
2631
  }
2575
- /** False for Inertia, XHR and JSON callers, which need a JSON payload. */
2632
+ /**
2633
+ * False for Inertia, XHR and JSON callers, which need a JSON payload. The CSRF
2634
+ * middleware picks its page by `wants-html.ts` directly, so an override here
2635
+ * does not change what a rejected form post answers.
2636
+ */
2576
2637
  wantsHtmlResponse(ctx) {
2577
- if (!ctx?.req?.header) return false;
2578
- const accept = ctx.req.header("accept") ?? "";
2579
- return !(accept.includes("application/json") || ctx.req.header("x-requested-with") === "XMLHttpRequest" || ctx.req.header("x-inertia") === "true") && accept.includes("text/html");
2638
+ return wantsHtmlResponse(ctx);
2580
2639
  }
2581
2640
  middleware() {
2582
2641
  return async (ctx, next) => {
@@ -2591,6 +2650,14 @@ var ExceptionHandler = class {
2591
2650
  }
2592
2651
  };
2593
2652
  /**
2653
+ * A 404 message the framework wrote from the record rather than one a developer
2654
+ * chose: the ORM's `findOrFail()` (by name and `modelName`, since it crosses a
2655
+ * package boundary), a `NotFoundHttpException.for*()`, or none at all.
2656
+ */
2657
+ function hasComposedNotFoundMessage(error) {
2658
+ return hasComposedMessage(error) || error.name === "ModelNotFoundException" && typeof error.modelName === "string" || error.message === "";
2659
+ }
2660
+ /**
2594
2661
  * The HTTP status an exception carries, or 500 when it names none. Duck-typed
2595
2662
  * on `statusCode` rather than `instanceof`, so a foreign exception crossing a
2596
2663
  * package boundary (`ModelNotFoundException` from `@guren/orm`) still renders
@@ -2626,7 +2693,7 @@ function getExceptionHandler() {
2626
2693
  return handler;
2627
2694
  }
2628
2695
  function abort(statusCode, message, errors) {
2629
- throw new HttpException(statusCode, message ?? "Error", errors);
2696
+ throw new HttpException(statusCode, message ?? (statusCode === 404 ? "Not Found" : "Error"), errors);
2630
2697
  }
2631
2698
  function abortIf(condition, statusCode, message) {
2632
2699
  if (condition) abort(statusCode, message);
@@ -2635,28 +2702,6 @@ function abortUnless(condition, statusCode, message) {
2635
2702
  if (!condition) abort(statusCode, message);
2636
2703
  }
2637
2704
  //#endregion
2638
- //#region src/errors/exceptions/NotFoundHttpException.ts
2639
- /** 404: the requested resource could not be found. */
2640
- var NotFoundHttpException = class NotFoundHttpException extends HttpException {
2641
- resourceType;
2642
- resourceId;
2643
- constructor(message = "Not Found", resourceType, resourceId) {
2644
- super(404, message);
2645
- this.name = "NotFoundHttpException";
2646
- this.resourceType = resourceType;
2647
- this.resourceId = resourceId;
2648
- }
2649
- static forModel(model, id) {
2650
- return new NotFoundHttpException(`${model} with ID ${id} not found.`, model, id);
2651
- }
2652
- static forRoute(path) {
2653
- return new NotFoundHttpException(`Route ${path} not found.`, "Route");
2654
- }
2655
- static forResource(resource) {
2656
- return new NotFoundHttpException(`${resource} not found.`, resource);
2657
- }
2658
- };
2659
- //#endregion
2660
2705
  //#region src/errors/exceptions/MethodNotAllowedException.ts
2661
2706
  /** 405: the HTTP method is not allowed for the route. */
2662
2707
  var MethodNotAllowedException = class MethodNotAllowedException extends HttpException {
@@ -2932,7 +2977,7 @@ var InertiaServiceProvider = class extends ServiceProvider {
2932
2977
  }, 422);
2933
2978
  const flattened = {};
2934
2979
  for (const [key, messages] of Object.entries(error.errors ?? {})) flattened[key] = messages[0] ?? "";
2935
- const headers = { Location: ctx.req.header("Referer") ?? "/" };
2980
+ const headers = { Location: sameHostRefererPath(ctx.req.header("Referer"), ctx.req.url, this.refererHosts(ctx.req.url)) };
2936
2981
  const session = getSessionFromContext(ctx);
2937
2982
  if (session) session.flash("errors", flattened);
2938
2983
  else headers["Set-Cookie"] = validationErrorsSetCookie(flattened);
@@ -2943,6 +2988,21 @@ var InertiaServiceProvider = class extends ServiceProvider {
2943
2988
  });
2944
2989
  }
2945
2990
  /**
2991
+ * The request's host, and the one `APP_URL` names (what `config/http.ts`'s host
2992
+ * authorization and the auth scaffold's links key on): a proxy that does not
2993
+ * forward `Host` hands the app its upstream address instead. `X-Forwarded-Host`
2994
+ * is not read, since no app-wide trusted-proxy setting says when it is genuine.
2995
+ */
2996
+ refererHosts(requestUrl) {
2997
+ const hosts = [new URL(requestUrl).host];
2998
+ const appUrl = this.container.makeOptional("env")?.APP_URL ?? (typeof process === "undefined" ? void 0 : process.env.APP_URL);
2999
+ if (typeof appUrl !== "string" || appUrl.trim() === "") return hosts;
3000
+ try {
3001
+ hosts.push(new URL(appUrl.trim()).host);
3002
+ } catch {}
3003
+ return hosts;
3004
+ }
3005
+ /**
2946
3006
  * Auto-inject flashed `errors` into shared props. Scoped to this app's
2947
3007
  * container so a second Application booted in the same process keeps its
2948
3008
  * own registrations.
@@ -3565,7 +3625,7 @@ let devBanner;
3565
3625
  */
3566
3626
  async function loadDevBanner() {
3567
3627
  if (typeof process === "undefined") return devBanner;
3568
- if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-CSjrSNZi.js").then((n) => n.n);
3628
+ if (process.env.NODE_ENV !== "production") devBanner ??= await import("./dev-banner-BUrHz-LF.js").then((n) => n.n);
3569
3629
  return devBanner;
3570
3630
  }
3571
3631
  /**
@@ -3594,6 +3654,7 @@ var Application = class {
3594
3654
  disposeBunTeardown;
3595
3655
  autoSessionAttached = false;
3596
3656
  cookielessAuthPaths = /* @__PURE__ */ new Set();
3657
+ agentEndpointPaths = /* @__PURE__ */ new Set();
3597
3658
  /** {@link configDefinitions} with where each was listed, which ConfigServiceProvider's errors name. */
3598
3659
  configEntries;
3599
3660
  routeRegistration;
@@ -3617,6 +3678,7 @@ var Application = class {
3617
3678
  this.container = new Container();
3618
3679
  this.router = new Router();
3619
3680
  this.authManager = new AuthManager({ hasher: options.auth?.hasher });
3681
+ this.authManager.setAgentEndpoints(() => this.agentEndpointPaths);
3620
3682
  this.providerManager = new ProviderManager(this.container);
3621
3683
  this.mountSecurityDefaults();
3622
3684
  this.container.instance("app", this);
@@ -3695,9 +3757,9 @@ var Application = class {
3695
3757
  * after `mountRoutes()` — at `register` the collision check sees no routes.
3696
3758
  */
3697
3759
  declareCookielessAuthPath(path) {
3698
- const collision = this.router.definitions().find((route) => route.path === path);
3760
+ const collision = this.routeAt(path);
3699
3761
  if (collision) {
3700
- console.warn(`[guren] Refusing to exempt "${path}" from CSRF verification: the application already routes ${collision.method} ${path}${collision.name ? ` (${collision.name})` : ""}, which is registered first and answers there. Mount the declaring endpoint on a path of its own — as it stands it is unreachable, and exempting the path would disarm CSRF for the route that does answer.`);
3762
+ console.warn(`[guren] Refusing to exempt "${path}" from CSRF verification: the application already routes ${collision}, which is registered first and answers there. Mount the declaring endpoint on a path of its own — as it stands it is unreachable, and exempting the path would disarm CSRF for the route that does answer.`);
3701
3763
  return;
3702
3764
  }
3703
3765
  this.cookielessAuthPaths.add(path);
@@ -3706,6 +3768,29 @@ var Application = class {
3706
3768
  getCookielessAuthPaths() {
3707
3769
  return this.cookielessAuthPaths;
3708
3770
  }
3771
+ /**
3772
+ * Asserts that the endpoint at `path` judges `tool:` / `tools:` scopes itself,
3773
+ * so a tools-only token authenticates there (through app-wide auth middleware
3774
+ * in front of it) and nowhere else. Call from `boot`, after `mountRoutes()`.
3775
+ * Only an app route at exactly this path is detected: a parameterised or
3776
+ * wildcard route registered ahead of the endpoint would answer here unseen.
3777
+ */
3778
+ declareAgentEndpoint(path) {
3779
+ const collision = this.routeAt(path);
3780
+ if (collision) {
3781
+ console.warn(`[guren] Refusing to accept tools-only tokens at "${path}": the application already routes ${collision}, which is registered first and answers there and checks no tool scope.`);
3782
+ return;
3783
+ }
3784
+ this.agentEndpointPaths.add(path);
3785
+ }
3786
+ /** Matched by exact pathname — see {@link declareAgentEndpoint}. */
3787
+ getAgentEndpointPaths() {
3788
+ return this.agentEndpointPaths;
3789
+ }
3790
+ routeAt(path) {
3791
+ const route = this.router.definitions().find((definition) => definition.path === path);
3792
+ return route ? `${route.method} ${path}${route.name ? ` (${route.name})` : ""}` : void 0;
3793
+ }
3709
3794
  async mountRoutes() {
3710
3795
  await this.registerRoutes();
3711
3796
  await this.preparePrototypeRoutes();
@@ -3801,7 +3886,7 @@ var Application = class {
3801
3886
  this.bootSequence ??= new BootSequence([
3802
3887
  () => this.options.boot?.(this.hono),
3803
3888
  () => this.mountRoutes(),
3804
- () => this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BDDr-7lh.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?"),
3889
+ () => this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-CXOokGax.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @guren/cli installed?"),
3805
3890
  () => this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-BVPZjwQp.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?"),
3806
3891
  () => this.providerManager.bootAll(),
3807
3892
  () => this.warnOnUnconfiguredAuth()
@@ -3962,7 +4047,8 @@ var Application = class {
3962
4047
  if (shouldLogBanner) this.logDevServerBanner({
3963
4048
  hostname: boundHostname,
3964
4049
  port: boundPort,
3965
- assetsUrl: resolvedAssetsUrl ?? "http://localhost:5173"
4050
+ assetsUrl: resolvedAssetsUrl ?? "http://localhost:5173",
4051
+ assetServer: startedViteHere || reusableVite ? "managed" : "external"
3966
4052
  });
3967
4053
  else if (typeof process !== "undefined" && process.env.NODE_ENV === "production") console.info(`[guren] Listening on http://${formatHostPort(boundHostname, boundPort)}`);
3968
4054
  return address;
@@ -4123,120 +4209,6 @@ function isReservedAgentToolName(name) {
4123
4209
  return RESERVED_AGENT_TOOL_NAMES.includes(name);
4124
4210
  }
4125
4211
  //#endregion
4126
- //#region src/agent/scopes.ts
4127
- /**
4128
- * The scope grammar an API token's `abilities` use to reach agent tools
4129
- * (RFC 0016 §5.1). Four forms, so a human can read a scope on a consent screen:
4130
- * `tool:<name>`, `tools:read` (every tool whose resolved `readOnlyHint` is
4131
- * true), `tools:*`, `tools:<prefix>.*`. **Only `tool:` / `tools:` entries are
4132
- * considered**, so the store's default `['*']` grants no tool (default deny). A
4133
- * malformed entry is ignored, not thrown: this module judges an issued token and
4134
- * must grant less, never more; rejecting belongs to the issuer, which refuses a
4135
- * `null` from {@link parseToolScope}. Case-sensitive and untrimmed, for the same reason.
4136
- */
4137
- /**
4138
- * The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
4139
- * `tools:<prefix>.*` scope must stay inside. `*` is not in the charset, so
4140
- * `tool:posts.*` is rejected with no special case.
4141
- */
4142
- const AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
4143
- /** `tool:` scope prefix, including the separator. */
4144
- const SINGLE_PREFIX = "tool:";
4145
- /** `tools:` scope prefix, including the separator. */
4146
- const SET_PREFIX = "tools:";
4147
- /** The reserved `tools:` word granting every read-only tool. */
4148
- const READ_KEYWORD = "read";
4149
- /** The reserved `tools:` word granting every tool. */
4150
- const ALL_KEYWORD = "*";
4151
- /** Wildcard suffix of a prefix scope, dot included. */
4152
- const PREFIX_SUFFIX = ".*";
4153
- /**
4154
- * Parse one `abilities` entry. The two reserved `tools:` words are matched
4155
- * before the wildcard form, so a family named `read.…` is still reachable as
4156
- * `tools:read.*` while a tool named exactly `read` is only `tool:read`.
4157
- * @returns The scope, or `null` for both a non-tool entry and a malformed one
4158
- * (`tools:`, `tools:.*`, `tools:*.store`): both mean "grants no tool", on purpose.
4159
- */
4160
- function parseToolScope(entry) {
4161
- if (entry.startsWith(SINGLE_PREFIX)) {
4162
- const name = entry.slice(5);
4163
- return AGENT_TOOL_NAME_PATTERN.test(name) ? {
4164
- kind: "tool",
4165
- name
4166
- } : null;
4167
- }
4168
- if (!entry.startsWith(SET_PREFIX)) return null;
4169
- const rest = entry.slice(6);
4170
- if (rest === READ_KEYWORD) return { kind: "read" };
4171
- if (rest === ALL_KEYWORD) return { kind: "all" };
4172
- if (!rest.endsWith(PREFIX_SUFFIX)) return null;
4173
- const prefix = rest.slice(0, -2);
4174
- if (!AGENT_TOOL_NAME_PATTERN.test(prefix)) return null;
4175
- return {
4176
- kind: "prefix",
4177
- prefix
4178
- };
4179
- }
4180
- /**
4181
- * Judge one `scopes` entry of an agent registration.
4182
- *
4183
- * @param entry The scope as written in the config.
4184
- */
4185
- function classifyRegistrationScope(entry) {
4186
- const scope = parseToolScope(entry);
4187
- if (scope?.kind === "tool" || scope?.kind === "read") return {
4188
- allowed: true,
4189
- scope
4190
- };
4191
- if (scope?.kind === "all") return {
4192
- allowed: false,
4193
- reason: "wildcard",
4194
- message: `"${entry}" grants every tool the application has, including every tool it grows later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools as tool:<name> entries, or use tools:read if the agent only reads.`
4195
- };
4196
- if (scope?.kind === "prefix") return {
4197
- allowed: false,
4198
- reason: "prefix",
4199
- message: `"${entry}" grants every tool in the ${scope.prefix}.* family, including ones added later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools it needs as tool:<name> entries.`
4200
- };
4201
- const suggestion = AGENT_TOOL_NAME_PATTERN.test(entry) ? ` Did you mean "tool:${entry}"?` : "";
4202
- return {
4203
- allowed: false,
4204
- reason: "not-a-tool-scope",
4205
- message: `"${entry}" is not a tool scope, so it grants nothing. The registration grammar is tool:<name> for one tool by exact name, or tools:read for every read-only tool.` + suggestion
4206
- };
4207
- }
4208
- /** Whether one parsed scope covers a given tool. */
4209
- function scopeAllowsTool(scope, tool) {
4210
- switch (scope.kind) {
4211
- case "tool": return scope.name === tool.name;
4212
- case "read": return tool.readOnly;
4213
- case "all": return true;
4214
- case "prefix": return tool.name.startsWith(`${scope.prefix}.`);
4215
- default: return scope;
4216
- }
4217
- }
4218
- /**
4219
- * Whether a token's abilities grant a tool. Any one entry suffices — scopes
4220
- * are additive, and there is no deny form.
4221
- */
4222
- function scopesAllowTool(abilities, tool) {
4223
- for (const entry of abilities) {
4224
- const scope = parseToolScope(entry);
4225
- if (scope && scopeAllowsTool(scope, tool)) return true;
4226
- }
4227
- return false;
4228
- }
4229
- /**
4230
- * The concrete tool names a token's abilities grant, for the surfaces that show
4231
- * a human what a scope means: the OAuth consent screen, the `token:issue`
4232
- * confirmation, the issuance-time lint. Literally a filter over
4233
- * {@link scopesAllowTool}, and it must stay one: a second matcher is how a
4234
- * consent screen comes to list a tool the dispatcher then denies. Order of `tools`.
4235
- */
4236
- function expandToolScopes(abilities, tools) {
4237
- return tools.filter((tool) => scopesAllowTool(abilities, tool)).map((tool) => tool.name);
4238
- }
4239
- //#endregion
4240
4212
  //#region src/agent/events.ts
4241
4213
  /**
4242
4214
  * The audit trail of the agent surface (RFC 0016 §5.2): every tool invocation
@@ -5072,10 +5044,10 @@ function createAgentInvocationPipeline(options) {
5072
5044
  outcome
5073
5045
  };
5074
5046
  }
5075
- const request = options.handoff === "seam" && options.principal ? installAgentPrincipal(built.request, {
5047
+ const request = markAgentDispatch(options.handoff === "seam" && options.principal ? installAgentPrincipal(built.request, {
5076
5048
  principal: options.principal,
5077
5049
  abilities: options.abilities
5078
- }) : built.request;
5050
+ }) : built.request);
5079
5051
  const outcome = await mapToolResponse(tool, await options.app.fetch(request, options.env, options.executionCtx));
5080
5052
  record.invoked(audited, auditArgs, outcome.status, elapsed(startedAt));
5081
5053
  return {
@@ -5467,7 +5439,7 @@ var Validator = class Validator {
5467
5439
  async validateOrThrow(data) {
5468
5440
  const result = await this.validate(data);
5469
5441
  if (!result.success) {
5470
- const { ValidationException } = await import("./errors-JpkcCjjn.js").then((n) => n.t);
5442
+ const { ValidationException } = await import("./errors-C8neC8go.js").then((n) => n.t);
5471
5443
  throw new ValidationException(result.errors);
5472
5444
  }
5473
5445
  return result.data;
@@ -6869,7 +6841,7 @@ var Command = class {
6869
6841
  const result = await this.handle();
6870
6842
  return typeof result === "number" ? result : 0;
6871
6843
  } catch (error) {
6872
- if (error instanceof Error) this.error(error.message);
6844
+ if (error instanceof Error) this.error(redactQueryParams(error).message);
6873
6845
  return 1;
6874
6846
  }
6875
6847
  }