@guren/server 2.12.0 → 2.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
- package/dist/agent/derive.d.ts +155 -0
- package/dist/agent/dispatch.d.ts +123 -0
- package/dist/agent/events.d.ts +80 -0
- package/dist/agent/redact.d.ts +55 -0
- package/dist/agent/scopes.d.ts +115 -0
- package/dist/auth/AuthManager.d.ts +64 -0
- package/dist/auth/RequestAuthContext.d.ts +3 -5
- package/dist/auth/TokenGuard.d.ts +61 -0
- package/dist/auth/api-token.d.ts +25 -5
- package/dist/auth/context.d.ts +24 -0
- package/dist/auth/index.d.ts +5 -2
- package/dist/auth/index.js +2 -2
- package/dist/auth/providers/UserProvider.d.ts +7 -0
- package/dist/auth/types.d.ts +6 -0
- package/dist/{auth-C7sVmYgc.js → auth-BSUc14CD.js} +313 -122
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/middleware.d.ts +28 -1
- package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
- package/dist/broadcasting/index.js +1 -1
- package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BxU-LIfF.js} +2 -45
- package/dist/context-DoD0c7J_.js +26 -0
- package/dist/http/middleware/auth.d.ts +2 -2
- package/dist/http/middleware/capabilities.d.ts +57 -0
- package/dist/http/middleware/csrf.d.ts +3 -0
- package/dist/http/request.d.ts +51 -2
- package/dist/index.d.ts +12 -3
- package/dist/index.js +1015 -84
- package/dist/internal/agent-preflight.d.ts +28 -0
- package/dist/internal/request.d.ts +19 -0
- package/dist/internal/request.js +2 -0
- package/dist/internal/route-path.d.ts +28 -0
- package/dist/internal/route-path.js +33 -0
- package/dist/internal/zod-compat.d.ts +201 -0
- package/dist/internal/zod-compat.js +193 -0
- package/dist/internal/zod-json-schema.d.ts +102 -0
- package/dist/internal/zod-json-schema.js +461 -0
- package/dist/mcp/create-mcp-server.d.ts +29 -0
- package/dist/mcp/index.js +1 -1
- package/dist/mvc/Controller.d.ts +46 -0
- package/dist/mvc/Router.d.ts +53 -0
- package/dist/request-CRVuIiQr.js +78 -0
- package/dist/runtime/index.js +5 -2
- package/dist/{vite-manifest-BKuV1kfv.js → vite-manifest-BGfWbPYp.js} +1 -1
- package/package.json +17 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, r as formatValidationErrors, t as asRecord } from "./request-CRVuIiQr.js";
|
|
2
2
|
import { t as HttpException } from "./HttpException-BkS3euNG.js";
|
|
3
3
|
import { n as ValidationException } from "./errors-BgeOl_DC.js";
|
|
4
|
+
import { _ as setGate, a as withAuthorization, b as mergeCapabilities, c as Gate, d as can, f as cannot, h as getGate, i as resourceAbilityForMethod, l as Response$1, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize, v as AuthorizationException, x as stampCapabilities, y as capabilitiesOf } from "./authorization-CdfbCj8J.js";
|
|
4
5
|
import { t as trimSlashes } from "./trim-slashes-ZJ_VsY5s.js";
|
|
6
|
+
import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
|
|
5
7
|
import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-BVT813DO.js";
|
|
6
8
|
import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-D0Kc7-xc.js";
|
|
7
9
|
import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
8
|
-
import { A as sanitizeOAuthRedirect, B as
|
|
10
|
+
import { $ as SessionGuard, A as sanitizeOAuthRedirect, B as createBearerTokenMiddleware, C as createGitHubOAuthProviderConfig, D as exchangeOAuthCode, E as createOAuthState, F as AuthManager, G as parseApiToken, H as getApiTokenOrFail, I as TokenGuard, J as revokeApiToken, K as readBearerToken, L as API_TOKEN_KEY, M as hostMatchesAllowlist, N as isAppRelativePath, O as fetchOAuthUserProfile, P as normalizeRedirectTarget, Q as verifyApiToken, R as MemoryApiTokenStore, S as createDiscordOAuthProviderConfig, T as createOAuthManager, U as getUserApiTokens, V as getApiToken, W as hasBearerHeader, X as tokenCanAll, Y as tokenCan, Z as tokenCanAny, _ as MemoryOAuthStateStore, a as isEmailVerified, b as buildOAuthAuthorizeUrl, c as verifyEmailToken, ct as BaseUserProvider, d as completePasswordReset, dt as MemorySessionStore, f as createPasswordResetToken, ft as createSessionMiddleware, g as NodeHasher, h as AuthenticatableModel, i as createEmailVerificationToken, j as verifyOAuthState, k as parseOAuthRedirectUrl, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, pt as getSessionFromContext, q as revokeAllApiTokens, r as completeEmailVerification, s as requireVerifiedEmail, st as ModelUserProvider, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAUTH_SESSION_BINDING_KEY, w as createGoogleOAuthProviderConfig, x as buildOAuthRedirectUrl, y as OAuthManager, z as createApiToken } from "./auth-BSUc14CD.js";
|
|
11
|
+
import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-DoD0c7J_.js";
|
|
9
12
|
import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-CzrwKeDp.js";
|
|
10
13
|
import { r as isMcpEndpointEnabled } from "./endpoint-D-20PiHY.js";
|
|
11
14
|
import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-WsTX2ySN.js";
|
|
12
15
|
import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-mcWi7LCd.js";
|
|
13
|
-
import { _ as
|
|
14
|
-
import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BKuV1kfv.js";
|
|
16
|
+
import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BGfWbPYp.js";
|
|
15
17
|
import { r as isDocsViewerEnabled } from "./endpoint-D6GIqOpe.js";
|
|
16
18
|
import { t as jsx_runtime_exports } from "./jsx-runtime.js";
|
|
19
|
+
import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
|
|
17
20
|
import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as Event, i as JobProcessed, l as Listener, n as ApplicationStarted, o as RequestReceived, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as EventManager } from "./events-aIH_bWRx.js";
|
|
18
21
|
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "./cache-BYnZf2FR.js";
|
|
19
22
|
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-CXrRK85G.js";
|
|
20
23
|
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-DfEfSQEr.js";
|
|
21
24
|
import { a as DailyFileChannel, c as Logger, i as setLogManager, l as filterSensitiveData, n as createLogManager, o as FileChannel, r as getLogManager, s as ConsoleChannel, t as LogManager, u as LOG_LEVEL_PRIORITY } from "./logging-CPaRMuPP.js";
|
|
22
25
|
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-BGqmUNZ8.js";
|
|
26
|
+
import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-BxU-LIfF.js";
|
|
23
27
|
import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-DbIJ22KQ.js";
|
|
24
28
|
import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-DJtkkhiw.js";
|
|
25
29
|
import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-TLD9t0Q2.js";
|
|
@@ -104,32 +108,35 @@ function mountRoute(app, method, path, ...handlers) {
|
|
|
104
108
|
app.on(method, path, ...handlers);
|
|
105
109
|
}
|
|
106
110
|
//#endregion
|
|
107
|
-
//#region src/
|
|
111
|
+
//#region src/internal/agent-preflight.ts
|
|
108
112
|
/**
|
|
109
|
-
*
|
|
113
|
+
* The wire protocol of an agent preflight (RFC 0016 §5.4), in a leaf module
|
|
114
|
+
* so the two halves can share it without depending on each other.
|
|
110
115
|
*
|
|
111
|
-
*
|
|
112
|
-
* that
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
+
* `Router` mounts the seam that answers a preflight; `agent/dispatch` builds
|
|
117
|
+
* the request that asks for one and reads the answer back. Putting the names
|
|
118
|
+
* in either of those would make one import the other — today only
|
|
119
|
+
* `dispatch → Router` exists, and the day `Router` needs anything from
|
|
120
|
+
* `agent/` that becomes a cycle.
|
|
116
121
|
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
122
|
+
* Not exported from the package index: an external dispatcher asks for a
|
|
123
|
+
* preflight through `BuildToolRequestOptions.preflight`, and the header
|
|
124
|
+
* spelling is this seam's business, not published API.
|
|
120
125
|
*/
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
126
|
+
/** Request header asking the route for a verdict instead of an execution. */
|
|
127
|
+
const AGENT_PREFLIGHT_HEADER = "X-Guren-Agent-Preflight";
|
|
128
|
+
/**
|
|
129
|
+
* Response header marking a body as a preflight verdict rather than the
|
|
130
|
+
* route's own output.
|
|
131
|
+
*
|
|
132
|
+
* Load-bearing in two places that would otherwise mistake one for the other:
|
|
133
|
+
* a route's `output` schema validation (which would reject the verdict and
|
|
134
|
+
* turn it into a 500) and the MCP response mapping (which would advertise the
|
|
135
|
+
* verdict as the tool's `structuredContent`, so an SDK client validates it
|
|
136
|
+
* against the tool's output schema and throws). Both are answering the same
|
|
137
|
+
* question — "is this the route's result?" — so both read the same marker.
|
|
138
|
+
*/
|
|
139
|
+
const AGENT_PREFLIGHT_VERDICT_HEADER = "X-Guren-Agent-Preflight-Verdict";
|
|
133
140
|
//#endregion
|
|
134
141
|
//#region src/mvc/Router.ts
|
|
135
142
|
function normalizeModelBinding(binding) {
|
|
@@ -146,6 +153,19 @@ async function resolveModelBinding({ model, key }, value) {
|
|
|
146
153
|
return key === void 0 ? model.findOrFail(value) : model.findOrFail(value, key);
|
|
147
154
|
}
|
|
148
155
|
/**
|
|
156
|
+
* One immutable snapshot of agent metadata, taken when the metadata is
|
|
157
|
+
* attached and again when `definitions()` hands it out — so neither a caller
|
|
158
|
+
* mutating its options object after registration nor a consumer mutating a
|
|
159
|
+
* definition can change the agent metadata the router actually holds. The
|
|
160
|
+
* claim is scoped to this field: other definition fields (`schemas`, the
|
|
161
|
+
* spread OpenAPI metadata) alias the registry. Plain data end to end, so
|
|
162
|
+
* `structuredClone` keeps future nested fields covered without a
|
|
163
|
+
* hand-maintained field list.
|
|
164
|
+
*/
|
|
165
|
+
function cloneAgentMetadata(metadata) {
|
|
166
|
+
return structuredClone(metadata);
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
149
169
|
* Group scopes are unwound synchronously, so an `async` callback registers its
|
|
150
170
|
* routes after the scope has already been popped — silently dropping the
|
|
151
171
|
* prefix or middleware the group was opened with. The callback type says
|
|
@@ -297,12 +317,23 @@ var Router = class {
|
|
|
297
317
|
resource(path, controller, options = {}) {
|
|
298
318
|
const baseName = options.name ?? path.replace(/^\//u, "").replace(/\//gu, ".");
|
|
299
319
|
const paramName = options.param ?? "id";
|
|
300
|
-
const { only, except } = options;
|
|
301
|
-
|
|
320
|
+
const { only, except, agent } = options;
|
|
321
|
+
const registrable = /* @__PURE__ */ new Set();
|
|
322
|
+
for (const { method } of RESOURCE_ACTIONS) {
|
|
302
323
|
if (only && !only.includes(method)) continue;
|
|
303
324
|
if (except?.includes(method)) continue;
|
|
325
|
+
if (typeof controller.prototype[method] === "function") registrable.add(method);
|
|
326
|
+
}
|
|
327
|
+
if (agent) {
|
|
328
|
+
const orphaned = Object.keys(agent).filter((action) => agent[action] !== void 0 && !registrable.has(action));
|
|
329
|
+
if (orphaned.length > 0) throw new Error(`Router.resource('${path}'): agent metadata declared for ${orphaned.map((a) => `"${a}"`).join(", ")}, but no such route was registered (excluded via only/except, or missing from the controller). Agent metadata for a tool that cannot exist is a wiring mistake.`);
|
|
330
|
+
}
|
|
331
|
+
for (const { method, suffix, httpMethod } of RESOURCE_ACTIONS) {
|
|
332
|
+
if (!registrable.has(method)) continue;
|
|
304
333
|
const routePath = path + suffix.replace(":param", `:${paramName}`);
|
|
305
|
-
|
|
334
|
+
const builder = this[httpMethod](routePath, [controller, method]).name(`${baseName}.${method}`);
|
|
335
|
+
const agentMetadata = agent?.[method];
|
|
336
|
+
if (agentMetadata) builder.agent(agentMetadata);
|
|
306
337
|
}
|
|
307
338
|
return this;
|
|
308
339
|
}
|
|
@@ -312,17 +343,12 @@ var Router = class {
|
|
|
312
343
|
const handler = resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
|
|
313
344
|
const contractMiddleware = createContractValidationMiddleware(route);
|
|
314
345
|
const inlineMiddlewares = [...route.scopedMiddlewares, ...route.middlewares];
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
...resolvedMiddlewares,
|
|
322
|
-
...inlineMiddlewares,
|
|
323
|
-
handler
|
|
324
|
-
];
|
|
325
|
-
mountRoute(app, route.method, route.path, ...allMiddlewares);
|
|
346
|
+
const preflightMiddleware = createAgentPreflightMiddleware(route, () => this.aggregateCapabilities(route.routeMiddlewareNames, inlineMiddlewares));
|
|
347
|
+
const chain = [...resolvedMiddlewares, ...inlineMiddlewares];
|
|
348
|
+
if (contractMiddleware) chain.push(contractMiddleware);
|
|
349
|
+
if (preflightMiddleware) chain.push(preflightMiddleware);
|
|
350
|
+
chain.push(handler);
|
|
351
|
+
mountRoute(app, route.method, route.path, ...chain);
|
|
326
352
|
}
|
|
327
353
|
}
|
|
328
354
|
clear() {
|
|
@@ -337,12 +363,13 @@ var Router = class {
|
|
|
337
363
|
this.modelBindings.clear();
|
|
338
364
|
}
|
|
339
365
|
definitions() {
|
|
340
|
-
return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings }) => ({
|
|
366
|
+
return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent }) => ({
|
|
341
367
|
method,
|
|
342
368
|
path,
|
|
343
369
|
name,
|
|
344
370
|
schemas,
|
|
345
371
|
resource: serializeResourceHint(resource),
|
|
372
|
+
agent: agent ? cloneAgentMetadata(agent) : void 0,
|
|
346
373
|
middlewareNames: [...routeMiddlewareNames],
|
|
347
374
|
hasInlineMiddleware: middlewares.length > 0,
|
|
348
375
|
capabilities: this.aggregateCapabilities(routeMiddlewareNames, [...scopedMiddlewares, ...middlewares]),
|
|
@@ -405,26 +432,30 @@ var Router = class {
|
|
|
405
432
|
* thrown: `definitions()` must stay side-effect-free for introspection of
|
|
406
433
|
* routers that never mount (audit, codegen), and an unresolvable alias
|
|
407
434
|
* simply contributes no capabilities.
|
|
435
|
+
*
|
|
436
|
+
* This walks the chain; the rules for combining what it finds live with the
|
|
437
|
+
* capability type, in `mergeCapabilities`.
|
|
408
438
|
*/
|
|
409
|
-
aggregateCapabilities(names, inline, seen) {
|
|
439
|
+
aggregateCapabilities(names, inline, seen, seenStamps) {
|
|
410
440
|
const aggregated = {};
|
|
411
441
|
const visited = seen ?? /* @__PURE__ */ new Set();
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
if (!
|
|
415
|
-
|
|
442
|
+
const merged = seenStamps ?? /* @__PURE__ */ new Set();
|
|
443
|
+
const absorbStamp = (stamp) => {
|
|
444
|
+
if (!stamp || merged.has(stamp)) return;
|
|
445
|
+
merged.add(stamp);
|
|
446
|
+
mergeCapabilities(aggregated, stamp);
|
|
416
447
|
};
|
|
417
448
|
for (const name of names) {
|
|
418
449
|
if (visited.has(name)) continue;
|
|
419
450
|
visited.add(name);
|
|
420
451
|
const groupNames = this.middlewareGroups.get(name);
|
|
421
452
|
if (groupNames) {
|
|
422
|
-
|
|
453
|
+
mergeCapabilities(aggregated, this.aggregateCapabilities(groupNames, [], visited, merged));
|
|
423
454
|
continue;
|
|
424
455
|
}
|
|
425
|
-
|
|
456
|
+
absorbStamp(capabilitiesOf(this.middlewareAliases.get(name)));
|
|
426
457
|
}
|
|
427
|
-
for (const handler of inline)
|
|
458
|
+
for (const handler of inline) absorbStamp(capabilitiesOf(handler));
|
|
428
459
|
return aggregated;
|
|
429
460
|
}
|
|
430
461
|
resolveMiddlewareNames(names, seen) {
|
|
@@ -465,6 +496,7 @@ function applyRouteContract(route, options) {
|
|
|
465
496
|
deprecated: options.deprecated
|
|
466
497
|
};
|
|
467
498
|
if (options.bind) route.bindings = new Map(Object.entries(options.bind).map(([param, binding]) => [param, normalizeModelBinding(binding)]));
|
|
499
|
+
if (options.agent) route.agent = cloneAgentMetadata(options.agent);
|
|
468
500
|
}
|
|
469
501
|
var RouterMiddlewareGroupBuilder = class {
|
|
470
502
|
router;
|
|
@@ -513,14 +545,14 @@ function createRouteBuilder(route, namedRoutes) {
|
|
|
513
545
|
route.routeMiddlewareNames.push(...names);
|
|
514
546
|
route.middlewares.push(...handlers);
|
|
515
547
|
return this;
|
|
548
|
+
},
|
|
549
|
+
agent(metadata) {
|
|
550
|
+
if (route.agent) throw new Error(`Route ${route.method} ${route.path} already carries agent metadata (declared via route options or an earlier .agent() call). Declare it once.`);
|
|
551
|
+
route.agent = cloneAgentMetadata(metadata);
|
|
552
|
+
return this;
|
|
516
553
|
}
|
|
517
554
|
};
|
|
518
555
|
}
|
|
519
|
-
const PATH_PARAM_PATTERN = /(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu;
|
|
520
|
-
/** Param labels in path order, with constraints and modifiers dropped. */
|
|
521
|
-
function extractPathParamNames(path) {
|
|
522
|
-
return Array.from(path.matchAll(PATH_PARAM_PATTERN), (match) => match[2]);
|
|
523
|
-
}
|
|
524
556
|
function substituteParams(path, params) {
|
|
525
557
|
return path.replace(PATH_PARAM_PATTERN, (match, prefix, key) => {
|
|
526
558
|
if (!Object.prototype.hasOwnProperty.call(params, key)) return match;
|
|
@@ -533,7 +565,7 @@ function createContractHandler(path, options, handler) {
|
|
|
533
565
|
if (params instanceof Response) return params;
|
|
534
566
|
const query = parseRouteSegment(options.query, flattenRequestQueries(ctx), 422);
|
|
535
567
|
if (query instanceof Response) return query;
|
|
536
|
-
const payload = options.body ? await
|
|
568
|
+
const payload = options.body ? await parseRequestBody(ctx) : {};
|
|
537
569
|
const body = parseRouteSegment(options.body, payload, 422);
|
|
538
570
|
if (body instanceof Response) return body;
|
|
539
571
|
const result = await handler({
|
|
@@ -603,6 +635,67 @@ function throwOnInvalid(schema, data) {
|
|
|
603
635
|
const result = schema.safeParse(data);
|
|
604
636
|
if (!result.success) throw ValidationException.withMessages(formatValidationErrors(result.error));
|
|
605
637
|
}
|
|
638
|
+
/**
|
|
639
|
+
* The preflight seam: everything a request must pass before the handler runs,
|
|
640
|
+
* reported instead of executed.
|
|
641
|
+
*
|
|
642
|
+
* Mounted last, so the whole chain in front of it has already run — an
|
|
643
|
+
* unauthenticated call is a 401 and an unauthorized one a 403 from the real
|
|
644
|
+
* middleware, not from a second copy of the rule here. Reaching this point is
|
|
645
|
+
* itself the positive half of the verdict; what it adds is validating the
|
|
646
|
+
* contract the *tool advertised* and then stopping, so an agent can ask "would
|
|
647
|
+
* this be allowed" without the write happening.
|
|
648
|
+
*
|
|
649
|
+
* **Only routes declaring `.agent()` honour the header.** A non-agent route
|
|
650
|
+
* ignores it completely, so no ordinary endpoint changes behaviour on a header
|
|
651
|
+
* an arbitrary client can set; the surface is exactly what RFC 0016 defines.
|
|
652
|
+
*
|
|
653
|
+
* Body validation happens *here* rather than being left to the controller's
|
|
654
|
+
* `validateBody()`: the chain stops before the controller by construction, so
|
|
655
|
+
* the alternative is a verdict that silently never checked the body — the
|
|
656
|
+
* shape of the request an agent is most likely to get wrong. Reading the body
|
|
657
|
+
* is safe precisely because this branch does not call `next()`, so nothing
|
|
658
|
+
* downstream reads the stream after it.
|
|
659
|
+
*
|
|
660
|
+
* What it cannot check, it says. A route may authorize inside its action
|
|
661
|
+
* (`await this.authorize(...)`), which `guren check` accepts as satisfying the
|
|
662
|
+
* agent-route authorization rule — and which this seam structurally cannot
|
|
663
|
+
* reach, because the action never runs. So `allowed: true` means "passed
|
|
664
|
+
* everything that runs before the handler", and `unverified` names what a real
|
|
665
|
+
* call would still evaluate. Reporting a bare `allowed: true` for a route
|
|
666
|
+
* whose only authorization lives in its body would be the verdict claiming a
|
|
667
|
+
* check it never made.
|
|
668
|
+
*/
|
|
669
|
+
function createAgentPreflightMiddleware(route, capabilities) {
|
|
670
|
+
if (!route.agent) return null;
|
|
671
|
+
const schemas = route.schemas;
|
|
672
|
+
const unverified = capabilities().authorization === void 0 ? ["authorization"] : [];
|
|
673
|
+
return async (c, next) => {
|
|
674
|
+
if (c.req.header("X-Guren-Agent-Preflight") === void 0) return next();
|
|
675
|
+
const validated = [];
|
|
676
|
+
if (schemas?.params) {
|
|
677
|
+
throwOnInvalid(schemas.params, c.req.param());
|
|
678
|
+
validated.push("params");
|
|
679
|
+
}
|
|
680
|
+
if (schemas?.query) {
|
|
681
|
+
throwOnInvalid(schemas.query, flattenRequestQueries(c));
|
|
682
|
+
validated.push("query");
|
|
683
|
+
}
|
|
684
|
+
if (schemas?.body) {
|
|
685
|
+
throwOnInvalid(schemas.body, await parseRequestBody(c));
|
|
686
|
+
validated.push("body");
|
|
687
|
+
}
|
|
688
|
+
c.header(AGENT_PREFLIGHT_VERDICT_HEADER, "1");
|
|
689
|
+
return c.json({
|
|
690
|
+
preflight: true,
|
|
691
|
+
allowed: true,
|
|
692
|
+
route: route.name,
|
|
693
|
+
validated,
|
|
694
|
+
unverified,
|
|
695
|
+
message: "Preflight only: the request passed this route's middleware" + (validated.length > 0 ? ` and its ${validated.join(", ")} schema${validated.length > 1 ? "s" : ""}` : "") + ". The handler did not run, so nothing was created, changed, or deleted." + (unverified.length > 0 ? " No authorization middleware was found on this route, so any check inside the handler itself was not evaluated." : "")
|
|
696
|
+
});
|
|
697
|
+
};
|
|
698
|
+
}
|
|
606
699
|
function createContractValidationMiddleware(route) {
|
|
607
700
|
if (!isControllerAction(route.handler)) return null;
|
|
608
701
|
const schemas = route.schemas;
|
|
@@ -611,7 +704,8 @@ function createContractValidationMiddleware(route) {
|
|
|
611
704
|
if (schemas.params) throwOnInvalid(schemas.params, c.req.param());
|
|
612
705
|
if (schemas.query) throwOnInvalid(schemas.query, flattenRequestQueries(c));
|
|
613
706
|
await next();
|
|
614
|
-
|
|
707
|
+
const isSuccess = c.res !== void 0 && c.res.status >= 200 && c.res.status < 300;
|
|
708
|
+
if (schemas.output && isSuccess && c.res.headers.get("X-Guren-Agent-Preflight-Verdict") === null) {
|
|
615
709
|
let sourceBody;
|
|
616
710
|
let parsedBody;
|
|
617
711
|
try {
|
|
@@ -731,10 +825,13 @@ function serializeBindings(path, routeBindings, routerBindings) {
|
|
|
731
825
|
function serializeResourceHint(hint) {
|
|
732
826
|
if (hint === void 0) return;
|
|
733
827
|
if (typeof hint === "function") return hint.name || void 0;
|
|
828
|
+
if (typeof hint !== "object" || hint === null) return;
|
|
734
829
|
if (Array.isArray(hint)) {
|
|
735
830
|
const inner = serializeResourceHint(hint[0]);
|
|
736
831
|
return inner === void 0 ? void 0 : [inner];
|
|
737
832
|
}
|
|
833
|
+
const proto = Object.getPrototypeOf(hint);
|
|
834
|
+
if (proto !== Object.prototype && proto !== null) return;
|
|
738
835
|
const entries = [];
|
|
739
836
|
for (const [key, value] of Object.entries(hint)) {
|
|
740
837
|
const serialized = serializeResourceHint(value);
|
|
@@ -748,7 +845,7 @@ function isControllerAction(action) {
|
|
|
748
845
|
}
|
|
749
846
|
function isRouteContractOptions(value) {
|
|
750
847
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
751
|
-
return "params" in value || "query" in value || "body" in value || "output" in value || "resource" in value || "bind" in value || "name" in value || "middlewares" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
|
|
848
|
+
return "params" in value || "query" in value || "body" in value || "output" in value || "resource" in value || "bind" in value || "name" in value || "middlewares" in value || "agent" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
|
|
752
849
|
}
|
|
753
850
|
function joinPaths(prefixStack, path) {
|
|
754
851
|
const segments = [...prefixStack, path].filter(Boolean).map(trimSlashes).filter(Boolean);
|
|
@@ -942,6 +1039,36 @@ function isMcpEndpointRequest(path) {
|
|
|
942
1039
|
return path === "/_guren/mcp" && isMcpEndpointEnabled();
|
|
943
1040
|
}
|
|
944
1041
|
/**
|
|
1042
|
+
* A bearer-authenticated request that carries no cookies at all (RFC 0016
|
|
1043
|
+
* §3). CSRF defends cookie ambient authority — a browser attaching the
|
|
1044
|
+
* victim's cookies to a request the victim never made. A request that
|
|
1045
|
+
* authenticates by `Authorization: Bearer` and sends no `Cookie` header has
|
|
1046
|
+
* none to attach: the token is the client's own credential, deliberately
|
|
1047
|
+
* presented, and a browser cannot strip its cookies from a cross-site
|
|
1048
|
+
* request. Agent tool dispatch is the intended caller — it synthesizes
|
|
1049
|
+
* cookie-less bearer requests by construction.
|
|
1050
|
+
*
|
|
1051
|
+
* The predicate is the raw `Cookie` header, deliberately not the loaded
|
|
1052
|
+
* session. Ambient authority *requires a cookie*, so the header's absence is
|
|
1053
|
+
* proof by itself — independent of where this middleware sits relative to
|
|
1054
|
+
* the session mount. A session-based predicate reads as more precise and is
|
|
1055
|
+
* weaker on both edges: mounted before the session middleware it sees no
|
|
1056
|
+
* session and fails open for a cookie-carrying victim browser, and an
|
|
1057
|
+
* intermediate middleware that writes one value into a fresh session turns a
|
|
1058
|
+
* genuinely cookie-less client into a 403. Any cookie — even one this app
|
|
1059
|
+
* never reads — therefore keeps verification on; a bearer client that wants
|
|
1060
|
+
* the skip sends none, which is what every non-browser client does.
|
|
1061
|
+
*
|
|
1062
|
+
* Bearer detection is `hasBearerHeader`, the same predicate
|
|
1063
|
+
* `AuthManager.resolveGuardName` routes a request to the token guard by, so
|
|
1064
|
+
* this rule and token authentication cannot disagree about what a bearer
|
|
1065
|
+
* request is.
|
|
1066
|
+
*/
|
|
1067
|
+
function isBearerRequestWithoutCookies(ctx) {
|
|
1068
|
+
if (!hasBearerHeader(ctx)) return false;
|
|
1069
|
+
return ctx.req.header("Cookie") === void 0;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
945
1072
|
* Get the request's CSRF token.
|
|
946
1073
|
*
|
|
947
1074
|
* Signed token bound to the session when a stable one exists, otherwise a
|
|
@@ -1049,6 +1176,9 @@ async function getTokenFromRequest(ctx) {
|
|
|
1049
1176
|
* those sessions expire
|
|
1050
1177
|
* - Exempts the dev-only MCP endpoint while it is mounted, since agent
|
|
1051
1178
|
* clients cannot fetch a token first (it guards local-only access instead)
|
|
1179
|
+
* - Skips verification for `Authorization: Bearer` requests that carry no
|
|
1180
|
+
* cookies (RFC 0016) — token clients authenticate per request and hold no
|
|
1181
|
+
* cookie ambient authority for CSRF to defend
|
|
1052
1182
|
*
|
|
1053
1183
|
* `cookie: false` disables the `XSRF-TOKEN` cookie for apps that deliver the
|
|
1054
1184
|
* token themselves (meta tag / form field). Session-bound tokens still
|
|
@@ -1087,7 +1217,7 @@ function createCsrfMiddleware(options = {}) {
|
|
|
1087
1217
|
settleCookie(ctx);
|
|
1088
1218
|
return;
|
|
1089
1219
|
}
|
|
1090
|
-
if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path)) {
|
|
1220
|
+
if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path) || isBearerRequestWithoutCookies(ctx)) {
|
|
1091
1221
|
await next();
|
|
1092
1222
|
settleCookie(ctx);
|
|
1093
1223
|
return;
|
|
@@ -1137,7 +1267,7 @@ function getValidatedData(ctx) {
|
|
|
1137
1267
|
function validateRequest(schema, options = {}) {
|
|
1138
1268
|
const { onError, status = 422, fallbackMessage = "The provided data is invalid." } = options;
|
|
1139
1269
|
return async (ctx, next) => {
|
|
1140
|
-
const payload = await
|
|
1270
|
+
const payload = await parseRequestBody(ctx);
|
|
1141
1271
|
const result = schema.safeParse(payload);
|
|
1142
1272
|
if (!result.success) {
|
|
1143
1273
|
const errors = formatValidationErrors(result.error, fallbackMessage);
|
|
@@ -1164,7 +1294,7 @@ function validateRequestWith(schemaFactory, options = {}) {
|
|
|
1164
1294
|
const { onError, status = 422, fallbackMessage = "The provided data is invalid." } = options;
|
|
1165
1295
|
return async (ctx, next) => {
|
|
1166
1296
|
const schema = schemaFactory(ctx);
|
|
1167
|
-
const payload = await
|
|
1297
|
+
const payload = await parseRequestBody(ctx);
|
|
1168
1298
|
const result = schema.safeParse(payload);
|
|
1169
1299
|
if (!result.success) {
|
|
1170
1300
|
const errors = formatValidationErrors(result.error, fallbackMessage);
|
|
@@ -2040,7 +2170,6 @@ function jsonResponse(data, status = 200) {
|
|
|
2040
2170
|
}
|
|
2041
2171
|
//#endregion
|
|
2042
2172
|
//#region src/http/middleware/auth.ts
|
|
2043
|
-
const AUTH_CONTEXT_KEY = "guren:auth";
|
|
2044
2173
|
const TESTING_USER_HEADER = "x-testing-user";
|
|
2045
2174
|
function resolveTestingUser(ctx) {
|
|
2046
2175
|
if (!process.env.GUREN_TESTING) return null;
|
|
@@ -2081,13 +2210,10 @@ function attachAuthContext(contextFactory) {
|
|
|
2081
2210
|
await next();
|
|
2082
2211
|
};
|
|
2083
2212
|
}
|
|
2084
|
-
function resolveAuth(ctx) {
|
|
2085
|
-
return ctx.get(AUTH_CONTEXT_KEY);
|
|
2086
|
-
}
|
|
2087
2213
|
function requireAuthenticated(options = {}) {
|
|
2088
2214
|
const { redirectTo, status = 401, responseFactory } = options;
|
|
2089
2215
|
return stampCapabilities(async (ctx, next) => {
|
|
2090
|
-
const auth =
|
|
2216
|
+
const auth = getAuthContext(ctx);
|
|
2091
2217
|
if (!auth) throw new Error("Auth context has not been attached. Did you register the auth middleware?");
|
|
2092
2218
|
if (!await auth.check()) {
|
|
2093
2219
|
if (redirectTo) return ctx.redirect(redirectTo);
|
|
@@ -2100,7 +2226,7 @@ function requireAuthenticated(options = {}) {
|
|
|
2100
2226
|
function requireGuest(options = {}) {
|
|
2101
2227
|
const { redirectTo, status = 403, responseFactory } = options;
|
|
2102
2228
|
return stampCapabilities(async (ctx, next) => {
|
|
2103
|
-
const auth =
|
|
2229
|
+
const auth = getAuthContext(ctx);
|
|
2104
2230
|
if (!auth) throw new Error("Auth context has not been attached. Did you register the auth middleware?");
|
|
2105
2231
|
if (!await auth.guest()) {
|
|
2106
2232
|
if (redirectTo) return ctx.redirect(redirectTo);
|
|
@@ -3578,7 +3704,7 @@ var Application = class {
|
|
|
3578
3704
|
await this.providerManager.registerAll();
|
|
3579
3705
|
await this.options.boot?.(this.hono);
|
|
3580
3706
|
await this.mountRoutes();
|
|
3581
|
-
await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-
|
|
3707
|
+
await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BawsYjgN.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
|
|
3582
3708
|
await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-qFCaeiUv.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
|
|
3583
3709
|
await this.providerManager.bootAll();
|
|
3584
3710
|
}
|
|
@@ -3985,7 +4111,7 @@ var Controller = class {
|
|
|
3985
4111
|
* ```
|
|
3986
4112
|
*/
|
|
3987
4113
|
async file(name) {
|
|
3988
|
-
const value = (await this.
|
|
4114
|
+
const value = (await this.parseUploads())[name];
|
|
3989
4115
|
const candidate = Array.isArray(value) ? value[0] : value;
|
|
3990
4116
|
return candidate instanceof File && candidate.size > 0 ? candidate : null;
|
|
3991
4117
|
}
|
|
@@ -3994,11 +4120,43 @@ var Controller = class {
|
|
|
3994
4120
|
* Returns an empty array when none were uploaded.
|
|
3995
4121
|
*/
|
|
3996
4122
|
async files(name) {
|
|
3997
|
-
const value = (await this.
|
|
4123
|
+
const value = (await this.parseUploads())[name];
|
|
3998
4124
|
return (Array.isArray(value) ? value : value !== void 0 ? [value] : []).filter((item) => item instanceof File && item.size > 0);
|
|
3999
4125
|
}
|
|
4126
|
+
/**
|
|
4127
|
+
* The one multipart read behind {@link file} and {@link files}, guarded so a
|
|
4128
|
+
* body the parser cannot decode carries no files rather than crashing the
|
|
4129
|
+
* request: it reads as `{}`, which is the same answer both helpers already
|
|
4130
|
+
* give for a field that is simply absent — `null` and `[]`. Left to throw,
|
|
4131
|
+
* the parser's `TypeError` escaped as a 500 reporting the exception and a
|
|
4132
|
+
* stack, the defect {@link parseRequestBody} fixes for the validation paths.
|
|
4133
|
+
*
|
|
4134
|
+
* Deliberately *not* routed through `parseRequestBody()`, which looks like
|
|
4135
|
+
* the same rule and is not: it parses without `{ all: true }` and flattens a
|
|
4136
|
+
* repeated field to its first value, so sharing it would silently reduce
|
|
4137
|
+
* `files()` to one file per field. `{ all: true }` is the contract here, and
|
|
4138
|
+
* a malformed-body test cannot see its loss — hence the separate helper.
|
|
4139
|
+
*
|
|
4140
|
+
* try/catch rather than `.catch()`, for the reason given on the shared
|
|
4141
|
+
* fallback: `parseBody` may throw synchronously as well as reject, and only
|
|
4142
|
+
* one of those two shapes reaches a `.catch()`.
|
|
4143
|
+
*
|
|
4144
|
+
* It fails open in one direction, deliberately and for the same reason
|
|
4145
|
+
* {@link parseRequestBody} does: a body already consumed upstream reads as
|
|
4146
|
+
* "no upload" rather than throwing, so a middleware-ordering bug loses the
|
|
4147
|
+
* 500 that used to announce it. Telling that apart from a client's malformed
|
|
4148
|
+
* body means matching runtime-specific error codes, which answer differently
|
|
4149
|
+
* on Bun, Node and Workers.
|
|
4150
|
+
*/
|
|
4151
|
+
async parseUploads() {
|
|
4152
|
+
try {
|
|
4153
|
+
return await this.ctx.req.parseBody({ all: true });
|
|
4154
|
+
} catch {
|
|
4155
|
+
return {};
|
|
4156
|
+
}
|
|
4157
|
+
}
|
|
4000
4158
|
get auth() {
|
|
4001
|
-
const auth = this.ctx
|
|
4159
|
+
const auth = getAuthContext(this.ctx);
|
|
4002
4160
|
if (!auth) throw new Error("Controller auth helper requires the auth middleware. Make sure AuthServiceProvider is registered.");
|
|
4003
4161
|
return auth;
|
|
4004
4162
|
}
|
|
@@ -4057,7 +4215,7 @@ var Controller = class {
|
|
|
4057
4215
|
return getGate().forUser(await this.gateUser()).allows(ability, ...args);
|
|
4058
4216
|
}
|
|
4059
4217
|
async gateUser() {
|
|
4060
|
-
const auth = this.ctx
|
|
4218
|
+
const auth = getAuthContext(this.ctx);
|
|
4061
4219
|
if (!auth) return null;
|
|
4062
4220
|
return await auth.user();
|
|
4063
4221
|
}
|
|
@@ -4271,8 +4429,7 @@ var Controller = class {
|
|
|
4271
4429
|
* ```
|
|
4272
4430
|
*/
|
|
4273
4431
|
async validateBody(schema) {
|
|
4274
|
-
|
|
4275
|
-
return this.runValidation(schema, body);
|
|
4432
|
+
return this.runValidation(schema, await this.getRawBody());
|
|
4276
4433
|
}
|
|
4277
4434
|
/**
|
|
4278
4435
|
* Validate query parameters against a Zod-like schema.
|
|
@@ -4313,8 +4470,7 @@ var Controller = class {
|
|
|
4313
4470
|
* ```
|
|
4314
4471
|
*/
|
|
4315
4472
|
async validateBodySafe(schema) {
|
|
4316
|
-
|
|
4317
|
-
return this.runValidationSafe(schema, body);
|
|
4473
|
+
return this.runValidationSafe(schema, await this.getRawBody());
|
|
4318
4474
|
}
|
|
4319
4475
|
/**
|
|
4320
4476
|
* Validate query parameters against a Zod-like schema without throwing.
|
|
@@ -4352,14 +4508,32 @@ var Controller = class {
|
|
|
4352
4508
|
errors
|
|
4353
4509
|
};
|
|
4354
4510
|
}
|
|
4511
|
+
/**
|
|
4512
|
+
* The parsed body as sent: an array stays an array, a string stays a string.
|
|
4513
|
+
* Only validation reads it — a schema is what decides whether the shape is
|
|
4514
|
+
* acceptable, so narrowing first would make a non-object contract
|
|
4515
|
+
* unreachable.
|
|
4516
|
+
*
|
|
4517
|
+
* Memoized in a box rather than by truthiness: a body of `null`, `''`, `0`
|
|
4518
|
+
* or `false` is a parsed body, and re-reading the request would find the
|
|
4519
|
+
* stream consumed.
|
|
4520
|
+
*
|
|
4521
|
+
* No fallback of its own: an unparseable body already arrives here as `{}`
|
|
4522
|
+
* from {@link parseRequestBody}, which is what gives every dispatch path the
|
|
4523
|
+
* same answer. A second fallback here could only diverge from that one.
|
|
4524
|
+
*/
|
|
4525
|
+
async getRawBody() {
|
|
4526
|
+
if (this.parsedBody) return this.parsedBody.value;
|
|
4527
|
+
this.parsedBody = { value: await parseRequestBody(this.ctx) };
|
|
4528
|
+
return this.parsedBody.value;
|
|
4529
|
+
}
|
|
4530
|
+
/**
|
|
4531
|
+
* The record view of {@link getRawBody}, for the field-by-field helpers
|
|
4532
|
+
* (`input`, `only`, `except`, `has`). A non-object body has no field to
|
|
4533
|
+
* read, so it reads as `{}`.
|
|
4534
|
+
*/
|
|
4355
4535
|
async getBody() {
|
|
4356
|
-
|
|
4357
|
-
try {
|
|
4358
|
-
this.parsedBody = await parseRequestPayload(this.ctx);
|
|
4359
|
-
} catch {
|
|
4360
|
-
this.parsedBody = {};
|
|
4361
|
-
}
|
|
4362
|
-
return this.parsedBody;
|
|
4536
|
+
return asRecord(await this.getRawBody());
|
|
4363
4537
|
}
|
|
4364
4538
|
};
|
|
4365
4539
|
//#endregion
|
|
@@ -4436,6 +4610,763 @@ function viteAsset(entry, options = {}) {
|
|
|
4436
4610
|
return manifestAssetUrl(manifest, normalizedEntry);
|
|
4437
4611
|
}
|
|
4438
4612
|
//#endregion
|
|
4613
|
+
//#region src/agent/derive.ts
|
|
4614
|
+
/** HTTP methods whose semantics are read-only, per the MCP annotation defaults. */
|
|
4615
|
+
const READ_ONLY_METHODS = /* @__PURE__ */ new Set(["GET", "QUERY"]);
|
|
4616
|
+
/** HTTP methods that are idempotent whether or not they are read-only. */
|
|
4617
|
+
const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
|
|
4618
|
+
"GET",
|
|
4619
|
+
"QUERY",
|
|
4620
|
+
"PUT",
|
|
4621
|
+
"DELETE"
|
|
4622
|
+
]);
|
|
4623
|
+
/**
|
|
4624
|
+
* Derive the agent tools a set of route definitions exposes.
|
|
4625
|
+
*
|
|
4626
|
+
* @param definitions Registered routes, as `Router.definitions()` hands them out.
|
|
4627
|
+
*/
|
|
4628
|
+
function deriveAgentTools(definitions) {
|
|
4629
|
+
const tools = [];
|
|
4630
|
+
const warnings = [];
|
|
4631
|
+
const claimed = /* @__PURE__ */ new Map();
|
|
4632
|
+
for (const definition of definitions) {
|
|
4633
|
+
const agent = definition.agent;
|
|
4634
|
+
if (!agent) continue;
|
|
4635
|
+
const method = definition.method.toUpperCase();
|
|
4636
|
+
const where = `${method} ${definition.path}`;
|
|
4637
|
+
if (!definition.name) {
|
|
4638
|
+
warnings.push(`${where}: declares agent metadata but has no route name, so it is not exposed as a tool. Chain .name() on the route — the tool name is its identity.`);
|
|
4639
|
+
continue;
|
|
4640
|
+
}
|
|
4641
|
+
const routeName = definition.name;
|
|
4642
|
+
const toolName = agent.toolName ?? routeName;
|
|
4643
|
+
const existing = claimed.get(toolName);
|
|
4644
|
+
if (existing) {
|
|
4645
|
+
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.`);
|
|
4646
|
+
continue;
|
|
4647
|
+
}
|
|
4648
|
+
const toolWarnings = [];
|
|
4649
|
+
const readOnlyHint = agent.readOnlyHint ?? READ_ONLY_METHODS.has(method);
|
|
4650
|
+
const input = buildInputSchema(definition, method, toolWarnings);
|
|
4651
|
+
const tool = {
|
|
4652
|
+
toolName,
|
|
4653
|
+
routeName,
|
|
4654
|
+
method,
|
|
4655
|
+
path: definition.path,
|
|
4656
|
+
description: agent.description ?? definition.description ?? definition.summary,
|
|
4657
|
+
inputSchema: input.schema,
|
|
4658
|
+
inputSources: input.sources,
|
|
4659
|
+
inputBodyNested: input.nestedBody,
|
|
4660
|
+
outputSchema: buildOutputSchema(definition, method, toolWarnings),
|
|
4661
|
+
resource: definition.schemas?.output ? void 0 : definition.resource,
|
|
4662
|
+
annotations: {
|
|
4663
|
+
readOnlyHint,
|
|
4664
|
+
destructiveHint: agent.destructiveHint ?? !readOnlyHint,
|
|
4665
|
+
idempotentHint: agent.idempotentHint ?? IDEMPOTENT_METHODS.has(method)
|
|
4666
|
+
},
|
|
4667
|
+
authorization: deriveAuthorization(definition, method),
|
|
4668
|
+
approval: agent.approval,
|
|
4669
|
+
redact: agent.redact ? [...agent.redact] : void 0,
|
|
4670
|
+
expose: {
|
|
4671
|
+
mcp: agent.expose?.mcp ?? true,
|
|
4672
|
+
webMcp: agent.expose?.webMcp ?? true
|
|
4673
|
+
},
|
|
4674
|
+
warnings: toolWarnings
|
|
4675
|
+
};
|
|
4676
|
+
claimed.set(toolName, tool);
|
|
4677
|
+
tools.push(tool);
|
|
4678
|
+
for (const warning of toolWarnings) warnings.push(`${toolName}: ${warning}`);
|
|
4679
|
+
}
|
|
4680
|
+
return {
|
|
4681
|
+
tools,
|
|
4682
|
+
warnings
|
|
4683
|
+
};
|
|
4684
|
+
}
|
|
4685
|
+
function buildInputSchema(definition, method, warnings) {
|
|
4686
|
+
const label = `${method} ${definition.path}`;
|
|
4687
|
+
const merged = {
|
|
4688
|
+
properties: Object.create(null),
|
|
4689
|
+
required: /* @__PURE__ */ new Set(),
|
|
4690
|
+
owner: /* @__PURE__ */ new Map()
|
|
4691
|
+
};
|
|
4692
|
+
const pathParamNames = extractPathParamNames(definition.path);
|
|
4693
|
+
const paramsDetails = definition.schemas?.params ? readObjectSchema(definition.schemas.params, warnings, `${label} params`, "input") : void 0;
|
|
4694
|
+
if (paramsDetails) mergeProperties(merged, paramsDetails.properties, paramsDetails.required, "params", warnings);
|
|
4695
|
+
const supplements = Object.create(null);
|
|
4696
|
+
const supplementRequired = /* @__PURE__ */ new Set();
|
|
4697
|
+
for (const name of pathParamNames) {
|
|
4698
|
+
if (merged.owner.has(name)) continue;
|
|
4699
|
+
supplements[name] = { type: "string" };
|
|
4700
|
+
supplementRequired.add(name);
|
|
4701
|
+
}
|
|
4702
|
+
mergeProperties(merged, supplements, supplementRequired, "path", warnings);
|
|
4703
|
+
const queryDetails = definition.schemas?.query ? readObjectSchema(definition.schemas.query, warnings, `${label} query`, "input") : void 0;
|
|
4704
|
+
if (queryDetails) mergeProperties(merged, queryDetails.properties, queryDetails.required, "query", warnings);
|
|
4705
|
+
let nestedBody = false;
|
|
4706
|
+
const body = definition.schemas?.body ? toJsonSchema(definition.schemas.body, warnings, `${label} body`, "input") : void 0;
|
|
4707
|
+
if (body) {
|
|
4708
|
+
if (body.type === "object" && body.properties) mergeProperties(merged, body.properties, new Set(body.required ?? []), "body", warnings);
|
|
4709
|
+
else {
|
|
4710
|
+
mergeProperties(merged, { body }, /* @__PURE__ */ new Set(["body"]), "body", warnings);
|
|
4711
|
+
nestedBody = true;
|
|
4712
|
+
}
|
|
4713
|
+
}
|
|
4714
|
+
for (const name of pathParamNames) if (name in merged.properties) merged.required.add(name);
|
|
4715
|
+
const required = Array.from(merged.required);
|
|
4716
|
+
const sources = Object.create(null);
|
|
4717
|
+
for (const [name, source] of merged.owner) sources[name] = source;
|
|
4718
|
+
return {
|
|
4719
|
+
schema: {
|
|
4720
|
+
type: "object",
|
|
4721
|
+
properties: { ...merged.properties },
|
|
4722
|
+
...required.length > 0 ? { required } : {}
|
|
4723
|
+
},
|
|
4724
|
+
sources: { ...sources },
|
|
4725
|
+
nestedBody
|
|
4726
|
+
};
|
|
4727
|
+
}
|
|
4728
|
+
/**
|
|
4729
|
+
* Fold one source's properties into the merge. A collision replaces both the
|
|
4730
|
+
* property *and* its required-ness — carrying a losing source's `required`
|
|
4731
|
+
* forward would demand a key the advertised schema no longer describes.
|
|
4732
|
+
*/
|
|
4733
|
+
function mergeProperties(merged, properties, required, source, warnings) {
|
|
4734
|
+
for (const [name, schema] of Object.entries(properties)) {
|
|
4735
|
+
const previous = merged.owner.get(name);
|
|
4736
|
+
if (previous) warnings.push(`input key "${name}" is declared by both the ${previous} and the ${source} schema; the ${source} definition wins. Rename one — merged tool input has one namespace.`);
|
|
4737
|
+
merged.properties[name] = schema;
|
|
4738
|
+
merged.owner.set(name, source);
|
|
4739
|
+
merged.required.delete(name);
|
|
4740
|
+
if (required.has(name)) merged.required.add(name);
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
/**
|
|
4744
|
+
* The route's `output` schema, which is the only response shape validated at
|
|
4745
|
+
* runtime — so advertising it costs no new machinery. A `resource` hint is the
|
|
4746
|
+
* next rung of RFC 0016's ladder and is CLI-only: `definitions()` carries
|
|
4747
|
+
* class names, and the type text behind them exists solely in the CLI's AST
|
|
4748
|
+
* extraction.
|
|
4749
|
+
*/
|
|
4750
|
+
function buildOutputSchema(definition, method, warnings) {
|
|
4751
|
+
const output = definition.schemas?.output;
|
|
4752
|
+
if (!output) return void 0;
|
|
4753
|
+
return toJsonSchema(output, warnings, `${method} ${definition.path} response`, "output");
|
|
4754
|
+
}
|
|
4755
|
+
/**
|
|
4756
|
+
* The ability a route's middleware chain checks, when the stamped capability
|
|
4757
|
+
* says so unambiguously (RFC 0007's `MiddlewareCapabilities.authorization`).
|
|
4758
|
+
*
|
|
4759
|
+
* Everything else is omitted rather than guessed — `'any'`/`'mixed'`, several
|
|
4760
|
+
* abilities, an `abilityFor` callback that overrides the verb map, a custom
|
|
4761
|
+
* verb the map refuses, or a definition from a server old enough to carry no
|
|
4762
|
+
* capabilities at all. Absence means "undetermined", which is what lets
|
|
4763
|
+
* `guren check`'s "authn is not authz" rule fail closed on it instead of
|
|
4764
|
+
* reading a name that was never checked.
|
|
4765
|
+
*/
|
|
4766
|
+
function deriveAuthorization(definition, method) {
|
|
4767
|
+
const authorization = definition.capabilities?.authorization;
|
|
4768
|
+
if (!authorization) return void 0;
|
|
4769
|
+
if (authorization.resource) {
|
|
4770
|
+
if (!authorization.resource.fromMethodMap) return void 0;
|
|
4771
|
+
if (authorization.abilities.length > 0 || authorization.mode !== "all") return void 0;
|
|
4772
|
+
const ability = resourceAbilityForMethod(method);
|
|
4773
|
+
return ability ? { ability } : void 0;
|
|
4774
|
+
}
|
|
4775
|
+
if (authorization.abilities.length === 1 && authorization.mode === "all") return { ability: authorization.abilities[0] };
|
|
4776
|
+
}
|
|
4777
|
+
//#endregion
|
|
4778
|
+
//#region src/agent/dispatch.ts
|
|
4779
|
+
/** How many characters of a non-JSON response body survive into the result. */
|
|
4780
|
+
const TEXT_RESPONSE_CAP = 5e4;
|
|
4781
|
+
/**
|
|
4782
|
+
* The argument-level spelling of a preflight request (RFC 0016 §5.4), for a
|
|
4783
|
+
* surface whose callers pass flat arguments rather than dispatch options.
|
|
4784
|
+
*
|
|
4785
|
+
* No adapter strips it today: MCP does not offer preflight at all (see
|
|
4786
|
+
* `mapToolResponse` and the plugin), and the surfaces that do reach the seam
|
|
4787
|
+
* ask through `BuildToolRequestOptions.preflight`. A surface that adopts this
|
|
4788
|
+
* key owns the stripping — it is an instruction to the adapter, not a field of
|
|
4789
|
+
* any route's contract, and forwarding it would fail the very validation the
|
|
4790
|
+
* caller asked to rehearse.
|
|
4791
|
+
*/
|
|
4792
|
+
const PREFLIGHT_ARGUMENT = "_preflight";
|
|
4793
|
+
/**
|
|
4794
|
+
* Rebuild the HTTP request a tool call describes.
|
|
4795
|
+
*
|
|
4796
|
+
* The flat argument object is taken apart along `tool.inputSources` — the
|
|
4797
|
+
* derivation's own record of which contract each property came from — so a
|
|
4798
|
+
* POST route's `query` keys land in the query string where `validateQuery`
|
|
4799
|
+
* reads them, not in the body. Keys the derivation never advertised are
|
|
4800
|
+
* forwarded anyway (body for body-carrying methods, query otherwise): the
|
|
4801
|
+
* route's validator is the one place that rejects them, and dropping them
|
|
4802
|
+
* here would make this a second, quieter validator.
|
|
4803
|
+
*
|
|
4804
|
+
* GET and HEAD force everything into the query string whatever its source —
|
|
4805
|
+
* `Request` refuses a body on those methods, and a `body` schema on a GET
|
|
4806
|
+
* route is a contract defect this adapter cannot repair.
|
|
4807
|
+
*/
|
|
4808
|
+
function buildToolRequest(tool, args, options = {}) {
|
|
4809
|
+
const origin = options.origin ?? "http://localhost";
|
|
4810
|
+
const missing = [];
|
|
4811
|
+
const invalidPath = [];
|
|
4812
|
+
const pathOnly = /* @__PURE__ */ new Set();
|
|
4813
|
+
const path = tool.path.replace(PATH_PARAM_PATTERN, (_match, lead, name) => {
|
|
4814
|
+
const value = args[name];
|
|
4815
|
+
if (value === void 0) {
|
|
4816
|
+
missing.push(name);
|
|
4817
|
+
return `${lead}:${name}`;
|
|
4818
|
+
}
|
|
4819
|
+
const stringified = String(value);
|
|
4820
|
+
if (stringified === "." || stringified === "..") {
|
|
4821
|
+
invalidPath.push(name);
|
|
4822
|
+
return `${lead}:${name}`;
|
|
4823
|
+
}
|
|
4824
|
+
const source = sourceOf(tool, name);
|
|
4825
|
+
if (source === void 0 || source === "params" || source === "path") pathOnly.add(name);
|
|
4826
|
+
return `${lead}${encodeURIComponent(stringified)}`;
|
|
4827
|
+
});
|
|
4828
|
+
if (missing.length > 0) return { missing };
|
|
4829
|
+
if (invalidPath.length > 0) return { invalidPath };
|
|
4830
|
+
const method = tool.method;
|
|
4831
|
+
const bodyless = method === "GET" || method === "HEAD";
|
|
4832
|
+
const query = new URLSearchParams();
|
|
4833
|
+
const bodyEntries = [];
|
|
4834
|
+
for (const [key, value] of Object.entries(args)) {
|
|
4835
|
+
if (pathOnly.has(key) || value === void 0) continue;
|
|
4836
|
+
const source = sourceOf(tool, key);
|
|
4837
|
+
if (bodyless || source === "query" || source === "params" || source === "path" || tool.inputBodyNested && key !== "body") appendQueryValue(query, key, value);
|
|
4838
|
+
else bodyEntries.push([key, value]);
|
|
4839
|
+
}
|
|
4840
|
+
const headers = new Headers({
|
|
4841
|
+
Accept: "application/json",
|
|
4842
|
+
"X-Guren-Agent-Surface": "mcp"
|
|
4843
|
+
});
|
|
4844
|
+
if (options.authorization) headers.set("Authorization", options.authorization);
|
|
4845
|
+
if (options.preflight) headers.set(AGENT_PREFLIGHT_HEADER, "1");
|
|
4846
|
+
let body;
|
|
4847
|
+
if (!bodyless) {
|
|
4848
|
+
if (tool.inputBodyNested) {
|
|
4849
|
+
if (Object.hasOwn(args, "body")) body = JSON.stringify(args.body);
|
|
4850
|
+
} else if (bodyEntries.length > 0) body = JSON.stringify(accumulate(bodyEntries));
|
|
4851
|
+
}
|
|
4852
|
+
if (body !== void 0) headers.set("Content-Type", "application/json");
|
|
4853
|
+
const qs = query.toString();
|
|
4854
|
+
const url = `${origin}${path}${qs ? `?${qs}` : ""}`;
|
|
4855
|
+
return { request: new Request(url, {
|
|
4856
|
+
method,
|
|
4857
|
+
headers,
|
|
4858
|
+
body
|
|
4859
|
+
}) };
|
|
4860
|
+
}
|
|
4861
|
+
/**
|
|
4862
|
+
* The contract a property was declared under, or undefined if the derivation
|
|
4863
|
+
* never advertised it. `Object.hasOwn` rather than a plain read: a JSON
|
|
4864
|
+
* argument may legally be named `__proto__`, and `inputSources['__proto__']`
|
|
4865
|
+
* would otherwise resolve to `Object.prototype`, not undefined.
|
|
4866
|
+
*/
|
|
4867
|
+
function sourceOf(tool, name) {
|
|
4868
|
+
return Object.hasOwn(tool.inputSources, name) ? tool.inputSources[name] : void 0;
|
|
4869
|
+
}
|
|
4870
|
+
/** Primitives stringify; anything structured rides as JSON text. */
|
|
4871
|
+
function appendQueryValue(query, key, value) {
|
|
4872
|
+
if (Array.isArray(value)) {
|
|
4873
|
+
for (const element of value) query.append(key, serializeQueryScalar(element));
|
|
4874
|
+
return;
|
|
4875
|
+
}
|
|
4876
|
+
query.append(key, serializeQueryScalar(value));
|
|
4877
|
+
}
|
|
4878
|
+
function serializeQueryScalar(value) {
|
|
4879
|
+
if (value === null || typeof value !== "object") return String(value);
|
|
4880
|
+
return JSON.stringify(value);
|
|
4881
|
+
}
|
|
4882
|
+
/**
|
|
4883
|
+
* Null-prototype accumulator, spread back to plain: a JSON argument may
|
|
4884
|
+
* legally be named `__proto__`, and assigning that key on `{}` invokes the
|
|
4885
|
+
* prototype setter instead of defining the property — the same rule the
|
|
4886
|
+
* derivation and the redaction walk apply.
|
|
4887
|
+
*/
|
|
4888
|
+
function accumulate(entries) {
|
|
4889
|
+
const record = Object.create(null);
|
|
4890
|
+
for (const [key, value] of entries) record[key] = value;
|
|
4891
|
+
return { ...record };
|
|
4892
|
+
}
|
|
4893
|
+
/**
|
|
4894
|
+
* Whether the tool advertises an object output schema — the only kind MCP
|
|
4895
|
+
* lists, and therefore the only kind that obliges a success result to carry
|
|
4896
|
+
* `structuredContent`. A route whose `output` is an array or primitive is not
|
|
4897
|
+
* advertised as structured (MCP `outputSchema` must be an object), so its
|
|
4898
|
+
* results ride as text. `describeTool` and `mapToolResponse` must agree on
|
|
4899
|
+
* this exact predicate, or one advertises a schema the other cannot satisfy.
|
|
4900
|
+
*/
|
|
4901
|
+
function advertisesStructuredOutput(tool) {
|
|
4902
|
+
return tool.outputSchema?.type === "object";
|
|
4903
|
+
}
|
|
4904
|
+
/**
|
|
4905
|
+
* Map the application's response onto an MCP tool result (RFC 0016 §3.4).
|
|
4906
|
+
*
|
|
4907
|
+
* - 2xx JSON object → serialized text, plus `structuredContent` when the tool
|
|
4908
|
+
* advertises an object `outputSchema` (the one shape the route validated).
|
|
4909
|
+
* - 2xx Inertia page JSON → unwrapped to `page.props`, only for a tool with
|
|
4910
|
+
* no `outputSchema` — unwrap and schema are mutually exclusive by
|
|
4911
|
+
* derivation, so the advertised shape can never disagree with the result.
|
|
4912
|
+
* - 204 / 3xx → a status line naming the Location; not an error.
|
|
4913
|
+
* - 4xx / 5xx → `isError: true` carrying the exception handler's JSON body:
|
|
4914
|
+
* a 422's `{ message, errors }` is an application-level failure the agent
|
|
4915
|
+
* should read, not a protocol error.
|
|
4916
|
+
* - non-JSON → capped text.
|
|
4917
|
+
*
|
|
4918
|
+
* One MCP invariant overrides the table: a *non-error* result for a tool that
|
|
4919
|
+
* advertises an object `outputSchema` must carry `structuredContent`, or the
|
|
4920
|
+
* SDK client rejects it after the route has already run. A success response
|
|
4921
|
+
* that yields no object to put there (204, 3xx, non-JSON, a non-object body)
|
|
4922
|
+
* contradicts the route's own declared output, so it becomes an `isError`
|
|
4923
|
+
* result naming the mismatch — which the SDK exempts from the rule — rather
|
|
4924
|
+
* than a protocol fault the agent cannot interpret.
|
|
4925
|
+
*/
|
|
4926
|
+
async function mapToolResponse(tool, response) {
|
|
4927
|
+
const status = response.status;
|
|
4928
|
+
const structured = advertisesStructuredOutput(tool);
|
|
4929
|
+
if (status === 204 || status >= 300 && status < 400) {
|
|
4930
|
+
const location = response.headers.get("Location");
|
|
4931
|
+
const text = location ? `HTTP ${status} (Location: ${location})` : `HTTP ${status}`;
|
|
4932
|
+
if (structured) return inconsistentOutput(tool, text, status);
|
|
4933
|
+
return {
|
|
4934
|
+
content: [{
|
|
4935
|
+
type: "text",
|
|
4936
|
+
text
|
|
4937
|
+
}],
|
|
4938
|
+
status
|
|
4939
|
+
};
|
|
4940
|
+
}
|
|
4941
|
+
const raw = await response.text();
|
|
4942
|
+
if (status >= 400) return {
|
|
4943
|
+
content: [{
|
|
4944
|
+
type: "text",
|
|
4945
|
+
text: raw || `HTTP ${status}`
|
|
4946
|
+
}],
|
|
4947
|
+
isError: true,
|
|
4948
|
+
status
|
|
4949
|
+
};
|
|
4950
|
+
const parsed = parseJsonBody(response, raw);
|
|
4951
|
+
if (parsed === void 0) {
|
|
4952
|
+
const text = raw.length > TEXT_RESPONSE_CAP ? `${raw.slice(0, TEXT_RESPONSE_CAP)}… [truncated ${raw.length - TEXT_RESPONSE_CAP} characters]` : raw;
|
|
4953
|
+
if (structured) return inconsistentOutput(tool, `a non-JSON body (${text.slice(0, 200)})`, status);
|
|
4954
|
+
return {
|
|
4955
|
+
content: [{
|
|
4956
|
+
type: "text",
|
|
4957
|
+
text
|
|
4958
|
+
}],
|
|
4959
|
+
status
|
|
4960
|
+
};
|
|
4961
|
+
}
|
|
4962
|
+
if (response.headers.get("X-Guren-Agent-Preflight-Verdict") !== null) return {
|
|
4963
|
+
content: [{
|
|
4964
|
+
type: "text",
|
|
4965
|
+
text: JSON.stringify(parsed)
|
|
4966
|
+
}],
|
|
4967
|
+
status
|
|
4968
|
+
};
|
|
4969
|
+
const payload = unwrapInertiaProps(tool, response, parsed);
|
|
4970
|
+
if (structured && !isRecord(payload)) return inconsistentOutput(tool, `a ${Array.isArray(payload) ? "JSON array" : typeof payload} body`, status);
|
|
4971
|
+
const outcome = {
|
|
4972
|
+
content: [{
|
|
4973
|
+
type: "text",
|
|
4974
|
+
text: JSON.stringify(payload)
|
|
4975
|
+
}],
|
|
4976
|
+
status
|
|
4977
|
+
};
|
|
4978
|
+
if (structured && isRecord(payload)) outcome.structuredContent = payload;
|
|
4979
|
+
return outcome;
|
|
4980
|
+
}
|
|
4981
|
+
/**
|
|
4982
|
+
* A success response that cannot satisfy the tool's advertised object output
|
|
4983
|
+
* schema. Returned as an error result — the honest signal that the route and
|
|
4984
|
+
* its declared `output` disagree — which also sidesteps the SDK's
|
|
4985
|
+
* structuredContent requirement (errors are exempt).
|
|
4986
|
+
*/
|
|
4987
|
+
function inconsistentOutput(tool, detail, status) {
|
|
4988
|
+
return {
|
|
4989
|
+
content: [{
|
|
4990
|
+
type: "text",
|
|
4991
|
+
text: `The tool "${tool.toolName}" advertises an output schema, but the route returned ${detail} (HTTP ${status}) — no structured result could be produced.`
|
|
4992
|
+
}],
|
|
4993
|
+
isError: true,
|
|
4994
|
+
status
|
|
4995
|
+
};
|
|
4996
|
+
}
|
|
4997
|
+
function parseJsonBody(response, raw) {
|
|
4998
|
+
if (!(response.headers.get("Content-Type") ?? "").includes("json") || raw === "") return void 0;
|
|
4999
|
+
try {
|
|
5000
|
+
return JSON.parse(raw);
|
|
5001
|
+
} catch {
|
|
5002
|
+
return;
|
|
5003
|
+
}
|
|
5004
|
+
}
|
|
5005
|
+
function unwrapInertiaProps(tool, response, parsed) {
|
|
5006
|
+
if (tool.outputSchema) return parsed;
|
|
5007
|
+
if (response.headers.get("X-Inertia") !== "true") return parsed;
|
|
5008
|
+
if (!isRecord(parsed) || !("props" in parsed)) return parsed;
|
|
5009
|
+
return parsed.props;
|
|
5010
|
+
}
|
|
5011
|
+
function isRecord(value) {
|
|
5012
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5013
|
+
}
|
|
5014
|
+
//#endregion
|
|
5015
|
+
//#region src/agent/scopes.ts
|
|
5016
|
+
/**
|
|
5017
|
+
* The scope grammar an API token's `abilities` use to reach agent tools
|
|
5018
|
+
* (RFC 0016 §5.1).
|
|
5019
|
+
*
|
|
5020
|
+
* Four forms, and deliberately no more — a grammar an agent-facing consent
|
|
5021
|
+
* screen has to render is only useful if a human can read a scope and say
|
|
5022
|
+
* which tools it grants:
|
|
5023
|
+
*
|
|
5024
|
+
* - `tool:<name>` one tool, by exact name
|
|
5025
|
+
* - `tools:read` every tool whose resolved `readOnlyHint` is true
|
|
5026
|
+
* - `tools:*` every tool
|
|
5027
|
+
* - `tools:<prefix>.*` every tool named `<prefix>.…`
|
|
5028
|
+
*
|
|
5029
|
+
* **Only `tool:` / `tools:` entries are considered.** Every other ability an
|
|
5030
|
+
* `ApiToken` carries — including the store's default `['*']` — is ignored, so
|
|
5031
|
+
* it matches nothing. This is the fail-closed half of a deliberate split:
|
|
5032
|
+
*
|
|
5033
|
+
* - A token issued before agent tools existed, for an app's own API, holds
|
|
5034
|
+
* `['*']`. Reading that as "all agent tools" would silently hand every
|
|
5035
|
+
* already-issued token the whole agent surface the moment an app declares
|
|
5036
|
+
* its first `.agent()` route. Access to the agent surface is granted by an
|
|
5037
|
+
* explicit tool scope or not at all (default deny, RFC §5.1); `tools:*` is
|
|
5038
|
+
* the explicit way to say "everything".
|
|
5039
|
+
* - A malformed entry is likewise ignored here rather than throwing: this
|
|
5040
|
+
* module judges an already-issued token, and a token that cannot be parsed
|
|
5041
|
+
* must grant less, never more. Rejecting a bad scope belongs to the
|
|
5042
|
+
* *issuer* (`token:issue`, a later PR), which runs {@link parseToolScope}
|
|
5043
|
+
* over what it was asked for and refuses a `null`.
|
|
5044
|
+
*
|
|
5045
|
+
* Matching is case-sensitive and entries are not trimmed. A stored ability
|
|
5046
|
+
* with stray whitespace is an issuance bug; normalizing it here would make
|
|
5047
|
+
* the judge more permissive than the issuer, which is the wrong direction.
|
|
5048
|
+
*/
|
|
5049
|
+
/**
|
|
5050
|
+
* The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
|
|
5051
|
+
* `tools:<prefix>.*` scope has to stay inside — a scope that could not
|
|
5052
|
+
* possibly name a legal tool is not a scope.
|
|
5053
|
+
*
|
|
5054
|
+
* `packages/cli/src/agent-route-check.ts` holds the same pattern for the
|
|
5055
|
+
* check that fails a build over an illegal tool name. Collapsing the two onto
|
|
5056
|
+
* this export is a later change, not this one: the CLI reaches `@guren/server`
|
|
5057
|
+
* through `dist/`, so the collapse needs a built server and belongs with the
|
|
5058
|
+
* PR that does the build-order work.
|
|
5059
|
+
*
|
|
5060
|
+
* Note what the charset gives for free: `*` is not in it, so `tool:posts.*`
|
|
5061
|
+
* fails the test and needs no special case to be rejected.
|
|
5062
|
+
*/
|
|
5063
|
+
const AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
|
|
5064
|
+
/** `tool:` scope prefix, including the separator. */
|
|
5065
|
+
const SINGLE_PREFIX = "tool:";
|
|
5066
|
+
/** `tools:` scope prefix, including the separator. */
|
|
5067
|
+
const SET_PREFIX = "tools:";
|
|
5068
|
+
/** The reserved `tools:` word granting every read-only tool. */
|
|
5069
|
+
const READ_KEYWORD = "read";
|
|
5070
|
+
/** The reserved `tools:` word granting every tool. */
|
|
5071
|
+
const ALL_KEYWORD = "*";
|
|
5072
|
+
/** Wildcard suffix of a prefix scope, dot included. */
|
|
5073
|
+
const PREFIX_SUFFIX = ".*";
|
|
5074
|
+
/**
|
|
5075
|
+
* Parse one `abilities` entry.
|
|
5076
|
+
*
|
|
5077
|
+
* @returns The scope it denotes, or `null` for an entry that is not a tool
|
|
5078
|
+
* scope at all (`'*'`, an app's own ability name) and for one that is
|
|
5079
|
+
* malformed (`tools:`, `tools:.*`, `tools:*.store`, a prefix outside the
|
|
5080
|
+
* tool-name grammar). Callers cannot tell those apart on purpose: both mean
|
|
5081
|
+
* "grants no tool", and a judge that distinguished them would be inventing
|
|
5082
|
+
* a third answer for a two-valued question.
|
|
5083
|
+
*
|
|
5084
|
+
* Note the two reserved `tools:` words are matched before the wildcard form,
|
|
5085
|
+
* so a tool family literally named `read.…` is still reachable as
|
|
5086
|
+
* `tools:read.*`, while a tool named exactly `read` is reachable only as
|
|
5087
|
+
* `tool:read` — the reserved word wins its own spelling.
|
|
5088
|
+
*/
|
|
5089
|
+
function parseToolScope(entry) {
|
|
5090
|
+
if (entry.startsWith(SINGLE_PREFIX)) {
|
|
5091
|
+
const name = entry.slice(5);
|
|
5092
|
+
return AGENT_TOOL_NAME_PATTERN.test(name) ? {
|
|
5093
|
+
kind: "tool",
|
|
5094
|
+
name
|
|
5095
|
+
} : null;
|
|
5096
|
+
}
|
|
5097
|
+
if (!entry.startsWith(SET_PREFIX)) return null;
|
|
5098
|
+
const rest = entry.slice(6);
|
|
5099
|
+
if (rest === READ_KEYWORD) return { kind: "read" };
|
|
5100
|
+
if (rest === ALL_KEYWORD) return { kind: "all" };
|
|
5101
|
+
if (!rest.endsWith(PREFIX_SUFFIX)) return null;
|
|
5102
|
+
const prefix = rest.slice(0, -2);
|
|
5103
|
+
if (!AGENT_TOOL_NAME_PATTERN.test(prefix)) return null;
|
|
5104
|
+
return {
|
|
5105
|
+
kind: "prefix",
|
|
5106
|
+
prefix
|
|
5107
|
+
};
|
|
5108
|
+
}
|
|
5109
|
+
/** Whether one parsed scope covers a given tool. */
|
|
5110
|
+
function scopeAllowsTool(scope, tool) {
|
|
5111
|
+
switch (scope.kind) {
|
|
5112
|
+
case "tool": return scope.name === tool.name;
|
|
5113
|
+
case "read": return tool.readOnly;
|
|
5114
|
+
case "all": return true;
|
|
5115
|
+
case "prefix": return tool.name.startsWith(`${scope.prefix}.`);
|
|
5116
|
+
default: return scope;
|
|
5117
|
+
}
|
|
5118
|
+
}
|
|
5119
|
+
/**
|
|
5120
|
+
* Whether a token's abilities grant a tool. Any one entry suffices — scopes
|
|
5121
|
+
* are additive, and there is no deny form.
|
|
5122
|
+
*/
|
|
5123
|
+
function scopesAllowTool(abilities, tool) {
|
|
5124
|
+
for (const entry of abilities) {
|
|
5125
|
+
const scope = parseToolScope(entry);
|
|
5126
|
+
if (scope && scopeAllowsTool(scope, tool)) return true;
|
|
5127
|
+
}
|
|
5128
|
+
return false;
|
|
5129
|
+
}
|
|
5130
|
+
/**
|
|
5131
|
+
* The concrete tool names a token's abilities grant, for the surfaces that
|
|
5132
|
+
* have to show a human what a scope means: the OAuth consent screen, the
|
|
5133
|
+
* `token:issue` confirmation, and the issuance-time lint.
|
|
5134
|
+
*
|
|
5135
|
+
* Literally a filter over {@link scopesAllowTool}, and it must stay one. A
|
|
5136
|
+
* second matcher that walked entries and accumulated names is how a consent
|
|
5137
|
+
* screen comes to list a tool the dispatcher then denies — the two answers
|
|
5138
|
+
* have to be the same answer, not two implementations of one rule.
|
|
5139
|
+
*
|
|
5140
|
+
* @returns Names in the order the tools were given, so a caller controls the
|
|
5141
|
+
* display order by ordering its input.
|
|
5142
|
+
*/
|
|
5143
|
+
function expandToolScopes(abilities, tools) {
|
|
5144
|
+
return tools.filter((tool) => scopesAllowTool(abilities, tool)).map((tool) => tool.name);
|
|
5145
|
+
}
|
|
5146
|
+
//#endregion
|
|
5147
|
+
//#region src/agent/events.ts
|
|
5148
|
+
/**
|
|
5149
|
+
* The audit trail of the agent surface (RFC 0016 §5.2): every tool invocation
|
|
5150
|
+
* and every denial, as framework events, so an application forwards them
|
|
5151
|
+
* wherever it already forwards events instead of learning a second logging
|
|
5152
|
+
* API.
|
|
5153
|
+
*
|
|
5154
|
+
* Declarations only. Nothing here emits — the dispatch path does, once, at
|
|
5155
|
+
* the one place that knows the verdict — and nothing here redacts:
|
|
5156
|
+
* {@link AgentToolInvoked.arguments} is a *contract* that the emitter has
|
|
5157
|
+
* already run the arguments through `redactAgentArguments`. An event class
|
|
5158
|
+
* that redacted on construction would give a second, quieter redaction rule
|
|
5159
|
+
* beside the real one, and a listener has no way to tell a masked payload
|
|
5160
|
+
* from an unmasked one.
|
|
5161
|
+
*/
|
|
5162
|
+
/**
|
|
5163
|
+
* Emitted when an agent tool invocation completed — successfully or not.
|
|
5164
|
+
* `status` carries the HTTP status the dispatch resolved to, so an error
|
|
5165
|
+
* response is one of these rather than a separate event; a call that never
|
|
5166
|
+
* reached the handler is an {@link AgentToolDenied} instead.
|
|
5167
|
+
*/
|
|
5168
|
+
var AgentToolInvoked = class extends Event {
|
|
5169
|
+
principal;
|
|
5170
|
+
tool;
|
|
5171
|
+
status;
|
|
5172
|
+
durationMs;
|
|
5173
|
+
surface;
|
|
5174
|
+
/**
|
|
5175
|
+
* The invocation arguments **already redacted** by the emitter (see the
|
|
5176
|
+
* module header). Assigned in the body rather than declared as a
|
|
5177
|
+
* constructor parameter property: `arguments` is not a legal binding
|
|
5178
|
+
* identifier in strict mode, which every ES module is, though it is a
|
|
5179
|
+
* perfectly legal property name.
|
|
5180
|
+
*/
|
|
5181
|
+
arguments;
|
|
5182
|
+
constructor(principal, tool, redactedArguments, status, durationMs, surface) {
|
|
5183
|
+
super();
|
|
5184
|
+
this.principal = principal;
|
|
5185
|
+
this.tool = tool;
|
|
5186
|
+
this.status = status;
|
|
5187
|
+
this.durationMs = durationMs;
|
|
5188
|
+
this.surface = surface;
|
|
5189
|
+
this.arguments = redactedArguments;
|
|
5190
|
+
}
|
|
5191
|
+
};
|
|
5192
|
+
/**
|
|
5193
|
+
* Emitted when an agent tool invocation was refused. Carries no status or
|
|
5194
|
+
* duration: nothing ran, and {@link AgentToolDenialReason} is the finding.
|
|
5195
|
+
* `'approval'` covers a tool declaring `approval: 'required'` whose call
|
|
5196
|
+
* became a pending record instead of an execution.
|
|
5197
|
+
*/
|
|
5198
|
+
var AgentToolDenied = class extends Event {
|
|
5199
|
+
principal;
|
|
5200
|
+
tool;
|
|
5201
|
+
reason;
|
|
5202
|
+
surface;
|
|
5203
|
+
/** Redacted by the emitter, exactly as on {@link AgentToolInvoked}. */
|
|
5204
|
+
arguments;
|
|
5205
|
+
constructor(principal, tool, redactedArguments, reason, surface) {
|
|
5206
|
+
super();
|
|
5207
|
+
this.principal = principal;
|
|
5208
|
+
this.tool = tool;
|
|
5209
|
+
this.reason = reason;
|
|
5210
|
+
this.surface = surface;
|
|
5211
|
+
this.arguments = redactedArguments;
|
|
5212
|
+
}
|
|
5213
|
+
};
|
|
5214
|
+
//#endregion
|
|
5215
|
+
//#region src/agent/redact.ts
|
|
5216
|
+
/**
|
|
5217
|
+
* Argument masking for the agent audit trail (RFC 0016 §5.2).
|
|
5218
|
+
*
|
|
5219
|
+
* Agent tool arguments are logged by default, which is only safe if the
|
|
5220
|
+
* logging path masks the fields that must not be written down. Two sources,
|
|
5221
|
+
* unioned: a fixed list of sensitive key *fragments* every application gets
|
|
5222
|
+
* without asking, and the route's own `.agent({ redact })` metadata.
|
|
5223
|
+
*
|
|
5224
|
+
* The rule is deliberately blunt — a key matches when its lowercased name
|
|
5225
|
+
* *contains* a fragment, and that applies to the declared `redact` entries
|
|
5226
|
+
* too, not just the built-ins. So `redact: ['id']` also masks `userId`, and
|
|
5227
|
+
* the built-in `session` masks `sessionCount`. Over-redaction is the safe
|
|
5228
|
+
* direction for a log: a masked field that did not need masking costs a
|
|
5229
|
+
* debugging round trip, an unmasked credential costs a rotation.
|
|
5230
|
+
*
|
|
5231
|
+
* The walk is total for the same reason the derivation is: it runs while
|
|
5232
|
+
* *recording* what happened, including a denial taken before the route's own
|
|
5233
|
+
* validation, so it must not be the thing that throws. A cycle and a payload
|
|
5234
|
+
* nested past {@link MAX_DEPTH} both terminate with a marker.
|
|
5235
|
+
*/
|
|
5236
|
+
/**
|
|
5237
|
+
* The replacement written in place of a masked value. A string, so a redacted
|
|
5238
|
+
* record still serializes as JSON and reads the same in every sink.
|
|
5239
|
+
*/
|
|
5240
|
+
const AGENT_REDACTED = "[REDACTED]";
|
|
5241
|
+
/**
|
|
5242
|
+
* Written in place of a value that closes a cycle, so a self-referencing
|
|
5243
|
+
* argument object produces a finite record instead of throwing or hanging.
|
|
5244
|
+
* Distinct from {@link AGENT_REDACTED} on purpose: one says "we would not show
|
|
5245
|
+
* you", the other "there is nothing further here to show".
|
|
5246
|
+
*/
|
|
5247
|
+
const AGENT_CIRCULAR = "[Circular]";
|
|
5248
|
+
/**
|
|
5249
|
+
* Written in place of a value nested deeper than {@link MAX_DEPTH}.
|
|
5250
|
+
*/
|
|
5251
|
+
const AGENT_TRUNCATED = "[Truncated]";
|
|
5252
|
+
/**
|
|
5253
|
+
* How deep the walk goes before it stops descending.
|
|
5254
|
+
*
|
|
5255
|
+
* A cycle is not the only way an argument record ends recursion badly: a
|
|
5256
|
+
* deeply nested one ends it with a `RangeError`. That matters here more than
|
|
5257
|
+
* in an ordinary utility, because this is the *audit* path and a denial is
|
|
5258
|
+
* recorded before the route's own schema validation has run — an argument
|
|
5259
|
+
* payload that overflows the stack would throw inside the code writing the
|
|
5260
|
+
* record about it, suppressing the very `AgentToolDenied` that says a
|
|
5261
|
+
* hostile call arrived. Truncating keeps the record.
|
|
5262
|
+
*
|
|
5263
|
+
* Far past anything a tool input schema describes; a record this deep is
|
|
5264
|
+
* already unreadable in a log.
|
|
5265
|
+
*/
|
|
5266
|
+
const MAX_DEPTH = 64;
|
|
5267
|
+
/**
|
|
5268
|
+
* Key-name fragments masked in every application. Spelled in the normalized
|
|
5269
|
+
* form {@link normalizeKeyText} produces — lowercase, no separators — so
|
|
5270
|
+
* `Authorization`, `apiKey`, `API_KEY` and `x-api-key` are all covered by
|
|
5271
|
+
* their one entry.
|
|
5272
|
+
*/
|
|
5273
|
+
const DEFAULT_SENSITIVE_KEY_FRAGMENTS = [
|
|
5274
|
+
"password",
|
|
5275
|
+
"passphrase",
|
|
5276
|
+
"secret",
|
|
5277
|
+
"token",
|
|
5278
|
+
"apikey",
|
|
5279
|
+
"authorization",
|
|
5280
|
+
"credential",
|
|
5281
|
+
"cookie",
|
|
5282
|
+
"session"
|
|
5283
|
+
];
|
|
5284
|
+
/**
|
|
5285
|
+
* The form keys and fragments are compared in: lowercased, with separator
|
|
5286
|
+
* characters removed. `apiKey`, `api_key`, `api-key` and `X-Api-Key` are the
|
|
5287
|
+
* same name to a human reading a log, so they must be the same name to the
|
|
5288
|
+
* mask — a literal substring test lets the hyphenated spelling of a fragment
|
|
5289
|
+
* through, and header-shaped argument names (`x-api-key`) are exactly where
|
|
5290
|
+
* credentials live. Applied to declared `redact` entries too, so a route
|
|
5291
|
+
* author writes any spelling.
|
|
5292
|
+
*/
|
|
5293
|
+
function normalizeKeyText(text) {
|
|
5294
|
+
return text.toLowerCase().replace(/[-_\s]/gu, "");
|
|
5295
|
+
}
|
|
5296
|
+
/**
|
|
5297
|
+
* Mask the sensitive fields of an agent tool's arguments.
|
|
5298
|
+
*
|
|
5299
|
+
* Returns a deep copy: the input is never mutated, and a caller may keep
|
|
5300
|
+
* holding the unredacted original. The copy is deep only through the
|
|
5301
|
+
* structures this walks — plain objects and arrays. Anything else (a `Date`,
|
|
5302
|
+
* a `Map`, a `Set`, a class instance) is carried across as the *same
|
|
5303
|
+
* reference*, because copying it would need a rule per type and would still
|
|
5304
|
+
* get the exotic cases wrong; nothing below such a value is inspected, so a
|
|
5305
|
+
* credential hidden inside a class instance is masked only if the key holding
|
|
5306
|
+
* that instance matches. Tool arguments arrive as parsed JSON on every
|
|
5307
|
+
* surface, where this case does not occur; a caller synthesizing arguments in
|
|
5308
|
+
* process is the one that can hit it.
|
|
5309
|
+
*
|
|
5310
|
+
* @param args The invocation arguments. Walked as a record whatever its
|
|
5311
|
+
* prototype, so the return is always a fresh plain object.
|
|
5312
|
+
* @param redact Extra key fragments from the route's `.agent({ redact })`.
|
|
5313
|
+
*/
|
|
5314
|
+
function redactAgentArguments(args, redact) {
|
|
5315
|
+
if (args === null || typeof args !== "object") return {};
|
|
5316
|
+
const fragments = [...DEFAULT_SENSITIVE_KEY_FRAGMENTS];
|
|
5317
|
+
for (const entry of redact ?? []) {
|
|
5318
|
+
const fragment = normalizeKeyText(entry);
|
|
5319
|
+
if (fragment.length > 0) fragments.push(fragment);
|
|
5320
|
+
}
|
|
5321
|
+
return redactRecord(args, fragments, new WeakSet([args]), 0);
|
|
5322
|
+
}
|
|
5323
|
+
/** Whether a key name should have its value masked. */
|
|
5324
|
+
function isSensitiveKey(key, fragments) {
|
|
5325
|
+
const normalized = normalizeKeyText(key);
|
|
5326
|
+
return fragments.some((fragment) => normalized.includes(fragment));
|
|
5327
|
+
}
|
|
5328
|
+
/**
|
|
5329
|
+
* Copy one object's entries, masking sensitive keys.
|
|
5330
|
+
*
|
|
5331
|
+
* Accumulates on a null-prototype object: an argument named `__proto__`
|
|
5332
|
+
* survives `JSON.parse` as an own property, and assigning that key on a
|
|
5333
|
+
* plain `{}` invokes the prototype setter instead of defining a property —
|
|
5334
|
+
* the value would vanish from the record, and a crafted payload would be
|
|
5335
|
+
* reaching the prototype chain from inside the logging path. The result is
|
|
5336
|
+
* then spread onto a normal object so a consumer calling `hasOwnProperty` on
|
|
5337
|
+
* it works; spread *defines* own properties (`Object.assign` would assign
|
|
5338
|
+
* them, putting the `__proto__` hazard straight back).
|
|
5339
|
+
*/
|
|
5340
|
+
function redactRecord(source, fragments, ancestors, depth) {
|
|
5341
|
+
const accumulator = Object.create(null);
|
|
5342
|
+
for (const [key, value] of Object.entries(source)) accumulator[key] = isSensitiveKey(key, fragments) ? AGENT_REDACTED : redactValue(value, fragments, ancestors, depth + 1);
|
|
5343
|
+
return { ...accumulator };
|
|
5344
|
+
}
|
|
5345
|
+
/** Copy one value, masking the sensitive keys anywhere beneath it. */
|
|
5346
|
+
function redactValue(value, fragments, ancestors, depth) {
|
|
5347
|
+
if (value === null || typeof value !== "object") return value;
|
|
5348
|
+
if (!isWalkable(value)) return value;
|
|
5349
|
+
if (depth > MAX_DEPTH) return AGENT_TRUNCATED;
|
|
5350
|
+
if (ancestors.has(value)) return AGENT_CIRCULAR;
|
|
5351
|
+
ancestors.add(value);
|
|
5352
|
+
try {
|
|
5353
|
+
if (Array.isArray(value)) return value.map((element) => redactValue(element, fragments, ancestors, depth + 1));
|
|
5354
|
+
return redactRecord(value, fragments, ancestors, depth);
|
|
5355
|
+
} finally {
|
|
5356
|
+
ancestors.delete(value);
|
|
5357
|
+
}
|
|
5358
|
+
}
|
|
5359
|
+
/**
|
|
5360
|
+
* Whether a value is a structure this walks: an array, or an object with no
|
|
5361
|
+
* prototype or the plain one. Everything else is carried across by reference
|
|
5362
|
+
* (see {@link redactAgentArguments}).
|
|
5363
|
+
*/
|
|
5364
|
+
function isWalkable(value) {
|
|
5365
|
+
if (Array.isArray(value)) return true;
|
|
5366
|
+
const prototype = Object.getPrototypeOf(value);
|
|
5367
|
+
return prototype === null || prototype === Object.prototype;
|
|
5368
|
+
}
|
|
5369
|
+
//#endregion
|
|
4439
5370
|
//#region src/providers/OAuthServiceProvider.ts
|
|
4440
5371
|
/**
|
|
4441
5372
|
* Binds OAuthManager as a singleton in the container.
|
|
@@ -4877,7 +5808,7 @@ var FormRequest = class {
|
|
|
4877
5808
|
* true, because an unawaited call is a pending promise.
|
|
4878
5809
|
*/
|
|
4879
5810
|
async user() {
|
|
4880
|
-
return await this.ctx
|
|
5811
|
+
return await getAuthContext(this.ctx)?.user() ?? null;
|
|
4881
5812
|
}
|
|
4882
5813
|
/**
|
|
4883
5814
|
* Handle the form request: authorize, parse body, validate, return typed data.
|
|
@@ -8173,4 +9104,4 @@ var DefaultHasher = class {
|
|
|
8173
9104
|
//#region src/index.ts
|
|
8174
9105
|
ensureErrorStackTracePolyfill();
|
|
8175
9106
|
//#endregion
|
|
8176
|
-
export { API_TOKEN_KEY, AUTH_CONTEXT_KEY, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CursorPaginator, CustomCheck, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, 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, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, after, afterOrEqual, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildVerificationUrl, can, cannot, check as checkHash, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createApiToken, createApp, 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, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAppKey, deriveAppKeyring, detectLocaleMiddleware, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, 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, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, 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, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
|
|
9107
|
+
export { AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, AUTH_CONTEXT_KEY, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CursorPaginator, CustomCheck, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, 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, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PREFLIGHT_ARGUMENT, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, 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, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, check as checkHash, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createApiToken, createApp, 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, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, detectLocaleMiddleware, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, 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, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, 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, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
|