@guren/server 2.14.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
- package/dist/agent/AgentApprovalRequested.d.ts +59 -0
- package/dist/agent/approval.d.ts +295 -0
- package/dist/agent/audit-emitter.d.ts +64 -0
- package/dist/agent/audit.d.ts +103 -0
- package/dist/agent/dispatch.d.ts +50 -8
- package/dist/agent/meta-tools.d.ts +62 -0
- package/dist/agent/public.d.ts +33 -0
- package/dist/agent/public.js +2 -0
- package/dist/auth/index.js +1 -1
- package/dist/auth/password/DefaultHasher.d.ts +18 -5
- package/dist/auth/password/PasswordHasher.d.ts +15 -0
- package/dist/auth/password/hash-format.d.ts +19 -0
- package/dist/{auth-BSUc14CD.js → auth-DkYoAPVn.js} +121 -32
- package/dist/broadcasting/index.js +1 -1
- package/dist/{broadcasting-BxU-LIfF.js → broadcasting-BwodCA4q.js} +1 -1
- package/dist/container/bindings.d.ts +19 -0
- package/dist/dispatch-erOS9epZ.js +285 -0
- package/dist/encryption/index.js +2 -2
- package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
- package/dist/http/dev-assets.d.ts +16 -0
- package/dist/http/public-assets.d.ts +10 -0
- package/dist/http/request.d.ts +88 -1
- package/dist/http/static-documents.d.ts +31 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +586 -333
- package/dist/internal/request.d.ts +15 -9
- package/dist/internal/request.js +2 -2
- package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
- package/dist/logging/daily-file-path.d.ts +24 -0
- package/dist/logging/index.d.ts +1 -0
- package/dist/logging/index.js +2 -2
- package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
- package/dist/mvc/Controller.d.ts +0 -26
- package/dist/{request-CRVuIiQr.js → request-CVQwpu2J.js} +56 -5
- package/dist/runtime/index.js +90 -14
- package/dist/{vite-manifest-BGfWbPYp.js → vite-manifest-w_RSOvQW.js} +1 -1
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -1,31 +1,32 @@
|
|
|
1
|
-
import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, r as formatValidationErrors, t as asRecord } from "./request-
|
|
1
|
+
import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, r as formatValidationErrors, t as asRecord } from "./request-CVQwpu2J.js";
|
|
2
2
|
import { t as HttpException } from "./HttpException-BkS3euNG.js";
|
|
3
3
|
import { n as ValidationException } from "./errors-BgeOl_DC.js";
|
|
4
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";
|
|
5
|
+
import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, s as AGENT_PREFLIGHT_VERDICT_HEADER, t as PREFLIGHT_ARGUMENT } from "./dispatch-erOS9epZ.js";
|
|
5
6
|
import { t as trimSlashes } from "./trim-slashes-ZJ_VsY5s.js";
|
|
6
7
|
import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
|
|
7
8
|
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";
|
|
8
9
|
import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-D0Kc7-xc.js";
|
|
9
10
|
import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
10
|
-
import {
|
|
11
|
+
import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as DefaultHasher, d as completePasswordReset, dt as AuthenticationException, f as createPasswordResetToken, ft as MemorySessionStore, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as NodeHasher, m as verifyPasswordResetToken, mt as getSessionFromContext, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as createSessionMiddleware, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as BaseUserProvider, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-DkYoAPVn.js";
|
|
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-C8aejmi8.js";
|
|
11
13
|
import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-DoD0c7J_.js";
|
|
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";
|
|
13
14
|
import { r as isMcpEndpointEnabled } from "./endpoint-D-20PiHY.js";
|
|
14
15
|
import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-WsTX2ySN.js";
|
|
15
16
|
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";
|
|
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-
|
|
17
|
+
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-w_RSOvQW.js";
|
|
17
18
|
import { r as isDocsViewerEnabled } from "./endpoint-D6GIqOpe.js";
|
|
18
19
|
import { t as jsx_runtime_exports } from "./jsx-runtime.js";
|
|
19
20
|
import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
|
|
20
21
|
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";
|
|
22
|
+
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";
|
|
21
23
|
import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "./cache-BYnZf2FR.js";
|
|
22
24
|
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";
|
|
23
25
|
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";
|
|
24
|
-
import { a as DailyFileChannel, c as Logger, i as setLogManager, l as
|
|
25
|
-
import { a as
|
|
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";
|
|
26
|
+
import { a as DailyFileChannel, c as matchDailyFileDate, d as Logger, f as filterSensitiveData, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, p as LOG_LEVEL_PRIORITY, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-B-kngi3q.js";
|
|
27
|
+
import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-BwodCA4q.js";
|
|
27
28
|
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";
|
|
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-
|
|
29
|
+
import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-D99Vmls3.js";
|
|
29
30
|
import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-TLD9t0Q2.js";
|
|
30
31
|
import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "./health-VWdWXRwh.js";
|
|
31
32
|
import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-CPiEdtQd.js";
|
|
@@ -108,36 +109,6 @@ function mountRoute(app, method, path, ...handlers) {
|
|
|
108
109
|
app.on(method, path, ...handlers);
|
|
109
110
|
}
|
|
110
111
|
//#endregion
|
|
111
|
-
//#region src/internal/agent-preflight.ts
|
|
112
|
-
/**
|
|
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.
|
|
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.
|
|
121
|
-
*
|
|
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.
|
|
125
|
-
*/
|
|
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";
|
|
140
|
-
//#endregion
|
|
141
112
|
//#region src/mvc/Router.ts
|
|
142
113
|
function normalizeModelBinding(binding) {
|
|
143
114
|
if (Array.isArray(binding)) {
|
|
@@ -692,7 +663,7 @@ function createAgentPreflightMiddleware(route, capabilities) {
|
|
|
692
663
|
route: route.name,
|
|
693
664
|
validated,
|
|
694
665
|
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
|
|
666
|
+
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. The route's own middleware did run, so any effect a middleware on this route has of its own has already happened." + (unverified.length > 0 ? " No authorization middleware was found on this route, so any check inside the handler itself was not evaluated." : "")
|
|
696
667
|
});
|
|
697
668
|
};
|
|
698
669
|
}
|
|
@@ -2450,7 +2421,7 @@ var ExceptionHandler = class {
|
|
|
2450
2421
|
*/
|
|
2451
2422
|
async reportException(error) {
|
|
2452
2423
|
if (this.shouldNotReport(error)) return;
|
|
2453
|
-
if (this.reporters.length === 0) console.error("Unhandled exception:", error);
|
|
2424
|
+
if (this.reporters.length === 0 && resolveExceptionStatus(error) >= 500) console.error("Unhandled exception:", error);
|
|
2454
2425
|
for (const reporter of this.reporters) try {
|
|
2455
2426
|
await reporter(error);
|
|
2456
2427
|
} catch (reporterError) {
|
|
@@ -2481,12 +2452,12 @@ var ExceptionHandler = class {
|
|
|
2481
2452
|
*/
|
|
2482
2453
|
renderDefaultException(error, ctx) {
|
|
2483
2454
|
const debug = this.shouldShowDetails();
|
|
2455
|
+
const statusCode = resolveExceptionStatus(error);
|
|
2484
2456
|
if (HttpException.isHttpException(error)) {
|
|
2485
|
-
const {
|
|
2486
|
-
if (this.wantsHtmlResponse(ctx) && !debug) return ctx.html(renderErrorPage(
|
|
2487
|
-
return ctx.json(body,
|
|
2457
|
+
const { body } = error.toResponse(debug);
|
|
2458
|
+
if (this.wantsHtmlResponse(ctx) && !debug) return ctx.html(renderErrorPage(statusCode, body.message), statusCode);
|
|
2459
|
+
return ctx.json(body, statusCode);
|
|
2488
2460
|
}
|
|
2489
|
-
const statusCode = "statusCode" in error && typeof error.statusCode === "number" ? error.statusCode : 500;
|
|
2490
2461
|
const body = { message: statusCode < 500 || debug ? error.message : "Internal Server Error" };
|
|
2491
2462
|
if (debug) {
|
|
2492
2463
|
body.exception = error.name;
|
|
@@ -2521,6 +2492,26 @@ var ExceptionHandler = class {
|
|
|
2521
2492
|
}
|
|
2522
2493
|
};
|
|
2523
2494
|
/**
|
|
2495
|
+
* The HTTP status an exception carries, or 500 when it names none.
|
|
2496
|
+
*
|
|
2497
|
+
* Duck-typed on `statusCode` rather than on `instanceof HttpException`, which
|
|
2498
|
+
* is what lets a foreign exception (`ModelNotFoundException` from
|
|
2499
|
+
* `@guren/orm`, crossing a package boundary) render as its own 404 rather than
|
|
2500
|
+
* a 500. `HttpException.isHttpException()` treats the same property as the
|
|
2501
|
+
* authority, so this reads what that check already required.
|
|
2502
|
+
*
|
|
2503
|
+
* One rule, read by both halves of the handler: what an exception is delivered
|
|
2504
|
+
* as and whether the fallback logger treats it as a server failure must be the
|
|
2505
|
+
* same number, or an exception could be sent as a 422 and reported as a crash.
|
|
2506
|
+
* That is why `renderDefaultException` takes the status from here rather than
|
|
2507
|
+
* from `toResponse()`, whose `status` a duck-typed implementation could spell
|
|
2508
|
+
* differently from its own `statusCode`.
|
|
2509
|
+
*/
|
|
2510
|
+
function resolveExceptionStatus(error) {
|
|
2511
|
+
const statusCode = error?.statusCode;
|
|
2512
|
+
return typeof statusCode === "number" ? statusCode : 500;
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2524
2515
|
* Create an exception handler.
|
|
2525
2516
|
*/
|
|
2526
2517
|
function createExceptionHandler(options) {
|
|
@@ -4111,7 +4102,7 @@ var Controller = class {
|
|
|
4111
4102
|
* ```
|
|
4112
4103
|
*/
|
|
4113
4104
|
async file(name) {
|
|
4114
|
-
const value = (await this.
|
|
4105
|
+
const value = (await parseRequestUploads(this.ctx))[name];
|
|
4115
4106
|
const candidate = Array.isArray(value) ? value[0] : value;
|
|
4116
4107
|
return candidate instanceof File && candidate.size > 0 ? candidate : null;
|
|
4117
4108
|
}
|
|
@@ -4120,41 +4111,9 @@ var Controller = class {
|
|
|
4120
4111
|
* Returns an empty array when none were uploaded.
|
|
4121
4112
|
*/
|
|
4122
4113
|
async files(name) {
|
|
4123
|
-
const value = (await this.
|
|
4114
|
+
const value = (await parseRequestUploads(this.ctx))[name];
|
|
4124
4115
|
return (Array.isArray(value) ? value : value !== void 0 ? [value] : []).filter((item) => item instanceof File && item.size > 0);
|
|
4125
4116
|
}
|
|
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
|
-
}
|
|
4158
4117
|
get auth() {
|
|
4159
4118
|
const auth = getAuthContext(this.ctx);
|
|
4160
4119
|
if (!auth) throw new Error("Controller auth helper requires the auth middleware. Make sure AuthServiceProvider is registered.");
|
|
@@ -4775,241 +4734,70 @@ function deriveAuthorization(definition, method) {
|
|
|
4775
4734
|
if (authorization.abilities.length === 1 && authorization.mode === "all") return { ability: authorization.abilities[0] };
|
|
4776
4735
|
}
|
|
4777
4736
|
//#endregion
|
|
4778
|
-
//#region src/agent/
|
|
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
|
-
}
|
|
4737
|
+
//#region src/agent/meta-tools.ts
|
|
4981
4738
|
/**
|
|
4982
|
-
*
|
|
4983
|
-
*
|
|
4984
|
-
*
|
|
4985
|
-
*
|
|
4739
|
+
* The names a protocol adapter may add to an application's tool catalogue on
|
|
4740
|
+
* its own, and which an application route therefore may not claim (RFC 0016
|
|
4741
|
+
* §5.4).
|
|
4742
|
+
*
|
|
4743
|
+
* This is the one rule, with two readers. `@guren/plugin-mcp` adds
|
|
4744
|
+
* `guren.preflight` to the catalogue it serves; `guren check` fails a route
|
|
4745
|
+
* whose `.agent()` tool name would collide with it. Restating the string in
|
|
4746
|
+
* either place is how the two drift: the check would keep passing a route
|
|
4747
|
+
* whose tool the endpoint has already shadowed, and `tools/list` would carry
|
|
4748
|
+
* two tools with one name — which an MCP client rejects wholesale, so the
|
|
4749
|
+
* collision costs the *entire* catalogue, not the one tool.
|
|
4750
|
+
*
|
|
4751
|
+
* It lives beside the derivation rather than in the plugin because the check
|
|
4752
|
+
* cannot import the plugin (the CLI does not depend on it, and an app that
|
|
4753
|
+
* never installs App MCP is still checked), and the plugin must not restate a
|
|
4754
|
+
* name the check is enforcing.
|
|
4755
|
+
*
|
|
4756
|
+
* The list stays deliberately short. Every entry is a name taken away from
|
|
4757
|
+
* applications, and the `guren.` prefix is not reserved wholesale for the
|
|
4758
|
+
* same reason: reserving a namespace nothing occupies fails routes over a
|
|
4759
|
+
* collision that does not exist.
|
|
4986
4760
|
*/
|
|
4987
|
-
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
|
|
5003
|
-
|
|
5004
|
-
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
|
|
5008
|
-
|
|
5009
|
-
|
|
5010
|
-
|
|
5011
|
-
|
|
5012
|
-
|
|
4761
|
+
/**
|
|
4762
|
+
* The preflight companion tool (RFC 0016 §5.4).
|
|
4763
|
+
*
|
|
4764
|
+
* Preflight cannot be an *argument* of the tool being checked on MCP: a tool
|
|
4765
|
+
* advertising an `outputSchema` must answer with `structuredContent`
|
|
4766
|
+
* conforming to it unless the result is an error, and a verdict conforms to
|
|
4767
|
+
* no route's output. So the verdict needs a tool of its own, with its own
|
|
4768
|
+
* output schema — one meta-tool for the whole catalogue, not one companion
|
|
4769
|
+
* per tool, which would double the catalogue against §5.5's own
|
|
4770
|
+
* catalogue-quality rule.
|
|
4771
|
+
*/
|
|
4772
|
+
const PREFLIGHT_TOOL_NAME = "guren.preflight";
|
|
4773
|
+
/**
|
|
4774
|
+
* The approval-status companion tool (RFC 0016 §5.4 item 4).
|
|
4775
|
+
*
|
|
4776
|
+
* A tool declaring `approval: 'required'` answers its first call with a
|
|
4777
|
+
* pending record rather than an execution, and the caller is handed a request
|
|
4778
|
+
* id. Something has to be able to say what became of that id, and it cannot be
|
|
4779
|
+
* the gated tool itself for the reason preflight cannot be an argument of one:
|
|
4780
|
+
* a status is not that route's output, and a tool advertising an `outputSchema`
|
|
4781
|
+
* may not answer with a different shape of success.
|
|
4782
|
+
*
|
|
4783
|
+
* A second meta-tool rather than a mode of the first: `guren.preflight`
|
|
4784
|
+
* rehearses a call and answers a verdict, this reads a record and answers its
|
|
4785
|
+
* state. Folding both under one name would mean one tool whose output schema
|
|
4786
|
+
* is the union of two unrelated shapes, which is the thing a schema is for
|
|
4787
|
+
* preventing.
|
|
4788
|
+
*/
|
|
4789
|
+
const APPROVAL_STATUS_TOOL_NAME = "guren.approval_status";
|
|
4790
|
+
/** Every meta-tool name an adapter may occupy. */
|
|
4791
|
+
const RESERVED_AGENT_TOOL_NAMES = [PREFLIGHT_TOOL_NAME, APPROVAL_STATUS_TOOL_NAME];
|
|
4792
|
+
/**
|
|
4793
|
+
* Whether a tool name belongs to the framework rather than the application.
|
|
4794
|
+
*
|
|
4795
|
+
* Case-sensitive, like every other comparison the tool-name grammar makes:
|
|
4796
|
+
* MCP tool names are matched literally, so `Guren.Preflight` is a different
|
|
4797
|
+
* tool and reserving it would take a name away for nothing.
|
|
4798
|
+
*/
|
|
4799
|
+
function isReservedAgentToolName(name) {
|
|
4800
|
+
return RESERVED_AGENT_TOOL_NAMES.includes(name);
|
|
5013
4801
|
}
|
|
5014
4802
|
//#endregion
|
|
5015
4803
|
//#region src/agent/scopes.ts
|
|
@@ -5279,7 +5067,10 @@ const DEFAULT_SENSITIVE_KEY_FRAGMENTS = [
|
|
|
5279
5067
|
"authorization",
|
|
5280
5068
|
"credential",
|
|
5281
5069
|
"cookie",
|
|
5282
|
-
"session"
|
|
5070
|
+
"session",
|
|
5071
|
+
"privatekey",
|
|
5072
|
+
"pwd",
|
|
5073
|
+
"jwt"
|
|
5283
5074
|
];
|
|
5284
5075
|
/**
|
|
5285
5076
|
* The form keys and fragments are compared in: lowercased, with separator
|
|
@@ -5367,6 +5158,488 @@ function isWalkable(value) {
|
|
|
5367
5158
|
return prototype === null || prototype === Object.prototype;
|
|
5368
5159
|
}
|
|
5369
5160
|
//#endregion
|
|
5161
|
+
//#region src/agent/audit.ts
|
|
5162
|
+
/**
|
|
5163
|
+
* Where an application's audit trail is written by default, relative to the
|
|
5164
|
+
* app root. `storage/logs/` is the convention `LogManager`'s own examples
|
|
5165
|
+
* already use, so an audit trail lands beside the application log rather than
|
|
5166
|
+
* inventing a second place to look.
|
|
5167
|
+
*/
|
|
5168
|
+
const DEFAULT_AGENT_AUDIT_PATH = "storage/logs/agent-audit.log";
|
|
5169
|
+
/**
|
|
5170
|
+
* Every surface, as a value. Written as a total map of the union so that
|
|
5171
|
+
* adding a surface to {@link AgentSurface} fails to compile here rather than
|
|
5172
|
+
* making {@link parseAuditRecord} silently reject records from it.
|
|
5173
|
+
*/
|
|
5174
|
+
const AGENT_SURFACES = {
|
|
5175
|
+
"mcp": true,
|
|
5176
|
+
"dev-mcp": true,
|
|
5177
|
+
"cli": true,
|
|
5178
|
+
"webmcp": true
|
|
5179
|
+
};
|
|
5180
|
+
/** Every denial reason, as a value, total over the union for the same reason. */
|
|
5181
|
+
const DENIAL_REASONS = {
|
|
5182
|
+
"auth": true,
|
|
5183
|
+
"scope": true,
|
|
5184
|
+
"approval": true,
|
|
5185
|
+
"rate-limit": true
|
|
5186
|
+
};
|
|
5187
|
+
/**
|
|
5188
|
+
* Derive the record for one audit event.
|
|
5189
|
+
*
|
|
5190
|
+
* `now` is a parameter rather than a `Date.now()` inside: the sink writing
|
|
5191
|
+
* this record also picks the dated file it lands in, and two clock reads can
|
|
5192
|
+
* disagree across a midnight boundary — a record stamped just before it,
|
|
5193
|
+
* filed just after. One read, used for both.
|
|
5194
|
+
*
|
|
5195
|
+
* The two events are told apart structurally, not with `instanceof`. The event
|
|
5196
|
+
* classes cross a package boundary that this repo resolves twice — `@guren/cli`
|
|
5197
|
+
* and the plugins reach `@guren/server` through its `dist`, a test inside
|
|
5198
|
+
* `packages/server` through `src` — so an `instanceof` here would answer
|
|
5199
|
+
* `false` for a genuine event constructed on the other side of that seam, and
|
|
5200
|
+
* would do it by mislabelling the record rather than by failing.
|
|
5201
|
+
*/
|
|
5202
|
+
function toAuditRecord(event, now) {
|
|
5203
|
+
const base = {
|
|
5204
|
+
ts: now.toISOString(),
|
|
5205
|
+
surface: event.surface,
|
|
5206
|
+
tool: event.tool,
|
|
5207
|
+
principal: event.principal,
|
|
5208
|
+
arguments: event.arguments
|
|
5209
|
+
};
|
|
5210
|
+
return "reason" in event ? {
|
|
5211
|
+
...base,
|
|
5212
|
+
outcome: "denied",
|
|
5213
|
+
reason: event.reason
|
|
5214
|
+
} : {
|
|
5215
|
+
...base,
|
|
5216
|
+
outcome: "invoked",
|
|
5217
|
+
status: event.status,
|
|
5218
|
+
durationMs: event.durationMs
|
|
5219
|
+
};
|
|
5220
|
+
}
|
|
5221
|
+
/**
|
|
5222
|
+
* Read one line of an audit file back, or `null` if it is not a record.
|
|
5223
|
+
*
|
|
5224
|
+
* The one parser on the read side. A caller that hand-rolled a second would be
|
|
5225
|
+
* the reader half of the drift this whole feature is built to avoid, and would
|
|
5226
|
+
* be the half that fails silently: a record it stops recognising reads as an
|
|
5227
|
+
* empty trail.
|
|
5228
|
+
*
|
|
5229
|
+
* Returning `null` rather than throwing is what makes the reader usable
|
|
5230
|
+
* against a file that is being appended to right now. The last line of such a
|
|
5231
|
+
* file is routinely a *partial* record — an append is not atomic — and a blank
|
|
5232
|
+
* line is what a file ends with. Neither is corruption, and neither should
|
|
5233
|
+
* take down a command whose whole job is to show what the earlier lines say.
|
|
5234
|
+
*
|
|
5235
|
+
* Extra keys are ignored, deliberately: the file sink writes through
|
|
5236
|
+
* `DailyFileChannel`, whose JSON format wraps the record in a log envelope
|
|
5237
|
+
* (`timestamp`, `level`, `message`). Tolerating that envelope is what lets the
|
|
5238
|
+
* sink reuse the channel's rotation and retention instead of reimplementing
|
|
5239
|
+
* both, and the record's own fields are unambiguous beside it.
|
|
5240
|
+
*/
|
|
5241
|
+
function parseAuditRecord(line) {
|
|
5242
|
+
if (line.trim() === "") return null;
|
|
5243
|
+
let parsed;
|
|
5244
|
+
try {
|
|
5245
|
+
parsed = JSON.parse(line);
|
|
5246
|
+
} catch {
|
|
5247
|
+
return null;
|
|
5248
|
+
}
|
|
5249
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
5250
|
+
const candidate = parsed;
|
|
5251
|
+
const ts = candidate.ts;
|
|
5252
|
+
const tool = candidate.tool;
|
|
5253
|
+
const surface = candidate.surface;
|
|
5254
|
+
if (typeof ts !== "string" || typeof tool !== "string") return null;
|
|
5255
|
+
if (typeof surface !== "string" || !Object.hasOwn(AGENT_SURFACES, surface)) return null;
|
|
5256
|
+
const base = {
|
|
5257
|
+
ts,
|
|
5258
|
+
tool,
|
|
5259
|
+
surface,
|
|
5260
|
+
principal: readPrincipal(candidate.principal),
|
|
5261
|
+
arguments: isRecord(candidate.arguments) ? candidate.arguments : {}
|
|
5262
|
+
};
|
|
5263
|
+
if (candidate.outcome === "invoked") {
|
|
5264
|
+
const { status, durationMs } = candidate;
|
|
5265
|
+
if (typeof status !== "number" || typeof durationMs !== "number") return null;
|
|
5266
|
+
return {
|
|
5267
|
+
...base,
|
|
5268
|
+
outcome: "invoked",
|
|
5269
|
+
status,
|
|
5270
|
+
durationMs
|
|
5271
|
+
};
|
|
5272
|
+
}
|
|
5273
|
+
if (candidate.outcome === "denied") {
|
|
5274
|
+
const reason = candidate.reason;
|
|
5275
|
+
if (typeof reason !== "string" || !Object.hasOwn(DENIAL_REASONS, reason)) return null;
|
|
5276
|
+
return {
|
|
5277
|
+
...base,
|
|
5278
|
+
outcome: "denied",
|
|
5279
|
+
reason
|
|
5280
|
+
};
|
|
5281
|
+
}
|
|
5282
|
+
return null;
|
|
5283
|
+
}
|
|
5284
|
+
/**
|
|
5285
|
+
* The principal of a record, or `null`.
|
|
5286
|
+
*
|
|
5287
|
+
* An unreadable principal is `null` rather than a rejected record: who made a
|
|
5288
|
+
* call is the field most likely to change shape over the life of a log, and
|
|
5289
|
+
* losing the whole line — the tool, the arguments, the outcome — to recover
|
|
5290
|
+
* nothing is the wrong trade for an audit trail.
|
|
5291
|
+
*/
|
|
5292
|
+
function readPrincipal(value) {
|
|
5293
|
+
if (!isRecord(value)) return null;
|
|
5294
|
+
const { kind, id, abilities } = value;
|
|
5295
|
+
if (kind !== "user" && kind !== "service") return null;
|
|
5296
|
+
if (typeof id !== "string" && typeof id !== "number") return null;
|
|
5297
|
+
const principal = {
|
|
5298
|
+
kind,
|
|
5299
|
+
id
|
|
5300
|
+
};
|
|
5301
|
+
if (Array.isArray(abilities)) principal.abilities = abilities.filter((ability) => typeof ability === "string");
|
|
5302
|
+
return principal;
|
|
5303
|
+
}
|
|
5304
|
+
function isRecord(value) {
|
|
5305
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
5306
|
+
}
|
|
5307
|
+
//#endregion
|
|
5308
|
+
//#region src/agent/audit-emitter.ts
|
|
5309
|
+
/**
|
|
5310
|
+
* The container service an application's audit emitter is published under
|
|
5311
|
+
* (`ServiceBindings['agent.audit']`).
|
|
5312
|
+
*
|
|
5313
|
+
* A constant rather than a literal at each site, because this is the first
|
|
5314
|
+
* binding written by one package and read by another that cannot import it:
|
|
5315
|
+
* `@guren/plugin-mcp` binds it, `@guren/cli` resolves it, and neither depends
|
|
5316
|
+
* on the other. Two literals that drifted would break the wiring *silently* —
|
|
5317
|
+
* the CLI would resolve nothing and record nothing, which reads exactly like
|
|
5318
|
+
* an application that configured no trail. That is the one failure this
|
|
5319
|
+
* feature exists to prevent, so it may not be spelled twice.
|
|
5320
|
+
*/
|
|
5321
|
+
const AGENT_AUDIT_BINDING = "agent.audit";
|
|
5322
|
+
/**
|
|
5323
|
+
* Build the function a surface calls for every invocation and denial.
|
|
5324
|
+
*
|
|
5325
|
+
* **The sink is called directly, not subscribed as a listener**, and that is
|
|
5326
|
+
* the whole reason this function exists rather than an `events.on(...)` pair.
|
|
5327
|
+
* `EventManager.emit` awaits its listeners in priority order inside a bare
|
|
5328
|
+
* `for` loop, so the first one to throw ends the loop and every listener after
|
|
5329
|
+
* it never runs. An unrelated application listener registered at a higher
|
|
5330
|
+
* priority would then silence the audit trail, and the only evidence an
|
|
5331
|
+
* operator would have of that is an empty file. A record of what agents did
|
|
5332
|
+
* cannot be contingent on what else the application happens to listen for.
|
|
5333
|
+
*
|
|
5334
|
+
* The events are still emitted, unchanged, for every consumer that
|
|
5335
|
+
* legitimately is a listener — RFC 0016 §5.2's "forward them wherever you
|
|
5336
|
+
* already forward events" is untouched.
|
|
5337
|
+
*
|
|
5338
|
+
* Neither half may fail the tool call it is recording, so both are caught. The
|
|
5339
|
+
* sink's failure is *warned* rather than swallowed: an audit sink dropping
|
|
5340
|
+
* records in silence is precisely the failure this feature exists to prevent.
|
|
5341
|
+
*/
|
|
5342
|
+
function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date()) {
|
|
5343
|
+
return (event) => {
|
|
5344
|
+
if (sink) try {
|
|
5345
|
+
Promise.resolve(sink(toAuditRecord(event, now()))).catch(warnSinkFailure);
|
|
5346
|
+
} catch (error) {
|
|
5347
|
+
warnSinkFailure(error);
|
|
5348
|
+
}
|
|
5349
|
+
events?.emit(event).catch((error) => {
|
|
5350
|
+
console.warn(`[guren] audit event listener failed: ${String(error)}`);
|
|
5351
|
+
});
|
|
5352
|
+
};
|
|
5353
|
+
}
|
|
5354
|
+
function warnSinkFailure(error) {
|
|
5355
|
+
console.warn(`[guren] agent audit sink failed, record dropped: ${String(error)}`);
|
|
5356
|
+
}
|
|
5357
|
+
//#endregion
|
|
5358
|
+
//#region src/agent/approval.ts
|
|
5359
|
+
/**
|
|
5360
|
+
* How long a pending request stays answerable by default: one hour.
|
|
5361
|
+
*
|
|
5362
|
+
* An approval is permission for one call *now*, not a standing grant. The
|
|
5363
|
+
* default is short for the reason the single-use rule exists — an approval
|
|
5364
|
+
* granted last month must not let a call through today — and an application
|
|
5365
|
+
* that wants longer says so.
|
|
5366
|
+
*/
|
|
5367
|
+
const DEFAULT_AGENT_APPROVAL_TTL_MS = 36e5;
|
|
5368
|
+
/**
|
|
5369
|
+
* The configuration key an adapter reads the queue out of, as a value.
|
|
5370
|
+
*
|
|
5371
|
+
* `guren check` fails a route declaring `approval: 'required'` in an app whose
|
|
5372
|
+
* `mcpPlugin({ … })` call carries no queue, and it finds that call by looking
|
|
5373
|
+
* for this key. The CLI cannot import `@guren/plugin-mcp` — it does not depend
|
|
5374
|
+
* on it, and an app that never installs App MCP is still checked — so without
|
|
5375
|
+
* this constant the check would restate the string and the two would drift:
|
|
5376
|
+
* renaming the option would leave the check passing every app, silently. Same
|
|
5377
|
+
* rule, two readers, as {@link file://./meta-tools.ts}.
|
|
5378
|
+
*/
|
|
5379
|
+
const AGENT_APPROVAL_CONFIG_KEY = "approvals";
|
|
5380
|
+
/**
|
|
5381
|
+
* A stable key for "the same caller".
|
|
5382
|
+
*
|
|
5383
|
+
* Kind and id only: a token's *abilities* are not part of the identity,
|
|
5384
|
+
* because a token rotated or re-scoped between the approval and the call is
|
|
5385
|
+
* still the same principal, and an approval a human granted should not
|
|
5386
|
+
* evaporate because an unrelated ability was added. The scope gate has already
|
|
5387
|
+
* run by the time this key is used, so the call's own authority is checked
|
|
5388
|
+
* regardless.
|
|
5389
|
+
*
|
|
5390
|
+
* The id's type is part of the key. `id: 5` and `id: '5'` are different
|
|
5391
|
+
* principals to every store that distinguishes them, and collapsing the two
|
|
5392
|
+
* here would let a service token named `"5"` spend a user 5 approval.
|
|
5393
|
+
*/
|
|
5394
|
+
function agentApprovalPrincipalKey(principal) {
|
|
5395
|
+
if (!principal) return "anonymous";
|
|
5396
|
+
return `${principal.kind}:${typeof principal.id === "number" ? "n" : "s"}:${principal.id}`;
|
|
5397
|
+
}
|
|
5398
|
+
/**
|
|
5399
|
+
* The canonical text of one call's arguments — the *only* rule for deciding
|
|
5400
|
+
* that two calls are the same call.
|
|
5401
|
+
*
|
|
5402
|
+
* One function, two readers: {@link agentApprovalFingerprint} hashes it when a
|
|
5403
|
+
* record is created and again when a call looks one up. A second
|
|
5404
|
+
* serialization is how approving `posts.destroy {id: 5}` comes to authorize
|
|
5405
|
+
* `{id: 9}` — the failure this whole binding exists to prevent — and it would
|
|
5406
|
+
* do it silently, because both sides would still produce *a* string.
|
|
5407
|
+
*
|
|
5408
|
+
* What it normalizes: object key order, at every depth. `{a: 1, b: 2}` and
|
|
5409
|
+
* `{b: 2, a: 1}` are the same call, nested or not.
|
|
5410
|
+
*
|
|
5411
|
+
* What it deliberately does **not** normalize, because each would make two
|
|
5412
|
+
* genuinely different calls match:
|
|
5413
|
+
*
|
|
5414
|
+
* - **Types.** `{id: 5}` and `{id: '5'}` are different calls. A route that
|
|
5415
|
+
* coerces them to the same value is coercing *after* the gate; the approver
|
|
5416
|
+
* saw one of the two written down.
|
|
5417
|
+
* - **Array order.** Order is meaning in a JSON array (`ids: [1, 2]` vs
|
|
5418
|
+
* `[2, 1]` may be the same call to one route and not to another) and the
|
|
5419
|
+
* framework cannot know which.
|
|
5420
|
+
* - **Absent vs. explicitly null.** A dropped key and `null` are different
|
|
5421
|
+
* inputs to a schema with a default.
|
|
5422
|
+
* - Unicode form, number spelling beyond what JSON already fixes, or
|
|
5423
|
+
* whitespace inside strings.
|
|
5424
|
+
*
|
|
5425
|
+
* Total over JSON, and deliberately *not* total over everything else: a value
|
|
5426
|
+
* JSON cannot carry throws rather than serializing to a placeholder. A
|
|
5427
|
+
* placeholder would make two distinct inputs canonicalize identically, which
|
|
5428
|
+
* is the one failure mode worse than refusing — and refusing is safe here,
|
|
5429
|
+
* because the gate turns a throw into a fail-closed refusal. Arguments reach
|
|
5430
|
+
* this function parsed from JSON-RPC, so no such value can occur in practice;
|
|
5431
|
+
* the rule is written down for the surface that one day passes one.
|
|
5432
|
+
*/
|
|
5433
|
+
function canonicalizeAgentApprovalInput(input) {
|
|
5434
|
+
return canonicalize(input);
|
|
5435
|
+
}
|
|
5436
|
+
function canonicalize(value) {
|
|
5437
|
+
if (value === null) return "null";
|
|
5438
|
+
switch (typeof value) {
|
|
5439
|
+
case "boolean": return value ? "true" : "false";
|
|
5440
|
+
case "number":
|
|
5441
|
+
if (!Number.isFinite(value)) throw new TypeError(`Agent approval arguments must be JSON: ${String(value)} is not a finite number.`);
|
|
5442
|
+
return JSON.stringify(value);
|
|
5443
|
+
case "string": return JSON.stringify(value);
|
|
5444
|
+
case "object": {
|
|
5445
|
+
if (Array.isArray(value)) return `[${value.map((entry) => canonicalize(entry)).join(",")}]`;
|
|
5446
|
+
const record = value;
|
|
5447
|
+
return `{${Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`).join(",")}}`;
|
|
5448
|
+
}
|
|
5449
|
+
default: throw new TypeError(`Agent approval arguments must be JSON: a value of type ${typeof value} cannot be fingerprinted, so no approval could be bound to it.`);
|
|
5450
|
+
}
|
|
5451
|
+
}
|
|
5452
|
+
/**
|
|
5453
|
+
* The fingerprint an approval is bound to: SHA-256 of
|
|
5454
|
+
* {@link canonicalizeAgentApprovalInput}, hex.
|
|
5455
|
+
*
|
|
5456
|
+
* Hashed rather than stored verbatim because the record persists and is shown
|
|
5457
|
+
* to a human, while these are the **raw** arguments — the ones the record's
|
|
5458
|
+
* own `input` field is redacted precisely to keep out of storage. The hash
|
|
5459
|
+
* binds the approval without keeping the secret.
|
|
5460
|
+
*
|
|
5461
|
+
* Async because `crypto.subtle` is: it is the one digest available unchanged
|
|
5462
|
+
* on every runtime the framework targets (Bun, Node, Workers), and the gate is
|
|
5463
|
+
* async already.
|
|
5464
|
+
*/
|
|
5465
|
+
async function agentApprovalFingerprint(input) {
|
|
5466
|
+
const bytes = new TextEncoder().encode(canonicalizeAgentApprovalInput(input));
|
|
5467
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
5468
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
5469
|
+
}
|
|
5470
|
+
/**
|
|
5471
|
+
* Derive a new pending record.
|
|
5472
|
+
*
|
|
5473
|
+
* `now` is a parameter for the reason `toAuditRecord`'s is: the caller that
|
|
5474
|
+
* creates a record also decides whether an existing one has expired, and two
|
|
5475
|
+
* clock reads can disagree — a record stamped a millisecond after the instant
|
|
5476
|
+
* its own expiry was measured against.
|
|
5477
|
+
*
|
|
5478
|
+
* The id comes from `crypto.randomUUID()` rather than a parameter, which is
|
|
5479
|
+
* not the same compromise: an id needs no seam to be testable, since the
|
|
5480
|
+
* caller reads it straight off the returned record, and threading one in from
|
|
5481
|
+
* every call site would invite two of them to generate ids differently.
|
|
5482
|
+
*/
|
|
5483
|
+
function buildAgentApprovalRequest(request, now) {
|
|
5484
|
+
const ttlMs = request.ttlMs ?? 36e5;
|
|
5485
|
+
return {
|
|
5486
|
+
id: crypto.randomUUID(),
|
|
5487
|
+
tool: request.tool,
|
|
5488
|
+
input: request.input,
|
|
5489
|
+
fingerprint: request.fingerprint,
|
|
5490
|
+
principal: request.principal,
|
|
5491
|
+
principalKey: agentApprovalPrincipalKey(request.principal),
|
|
5492
|
+
requestedAt: now.toISOString(),
|
|
5493
|
+
expiresAt: new Date(now.getTime() + ttlMs).toISOString(),
|
|
5494
|
+
status: "pending"
|
|
5495
|
+
};
|
|
5496
|
+
}
|
|
5497
|
+
/**
|
|
5498
|
+
* Whether a record has passed its expiry at `now`.
|
|
5499
|
+
*
|
|
5500
|
+
* An unparseable `expiresAt` counts as expired. The alternative — treating a
|
|
5501
|
+
* date the framework cannot read as "not expired yet" — is a store bug that
|
|
5502
|
+
* fails open into a permanent approval, and this is the one direction of error
|
|
5503
|
+
* that cannot be noticed from the outside.
|
|
5504
|
+
*/
|
|
5505
|
+
function agentApprovalExpiredAt(request, now) {
|
|
5506
|
+
const expiresAt = Date.parse(request.expiresAt);
|
|
5507
|
+
return Number.isNaN(expiresAt) || expiresAt <= now.getTime();
|
|
5508
|
+
}
|
|
5509
|
+
/**
|
|
5510
|
+
* The record's status as of `now`, with expiry applied.
|
|
5511
|
+
*
|
|
5512
|
+
* Expiry is derived here rather than filtered by the store on purpose: a store
|
|
5513
|
+
* that judged it would be a second copy of the rule, and the copy that fails
|
|
5514
|
+
* open — a store that forgets to compare, or compares in local time, hands out
|
|
5515
|
+
* an approval granted last month and nothing anywhere reports it. A resolved
|
|
5516
|
+
* record keeps its resolution: a rejection does not become an expiry, and an
|
|
5517
|
+
* approval that was already spent is reported by `consumedAt`, not by this.
|
|
5518
|
+
*/
|
|
5519
|
+
function agentApprovalStatusAt(request, now) {
|
|
5520
|
+
if (request.status === "rejected") return "rejected";
|
|
5521
|
+
if (agentApprovalExpiredAt(request, now)) return "expired";
|
|
5522
|
+
return request.status;
|
|
5523
|
+
}
|
|
5524
|
+
/**
|
|
5525
|
+
* Whether this record authorizes a call at `now`: approved, unexpired, and
|
|
5526
|
+
* not already spent.
|
|
5527
|
+
*
|
|
5528
|
+
* All three are checked here, in framework code, rather than trusted to the
|
|
5529
|
+
* store's query — see {@link AgentApprovalStore.findMatch}. `consumedAt` is
|
|
5530
|
+
* checked even though `findMatch` promises unconsumed records, because the
|
|
5531
|
+
* single-use guarantee must not rest on an application's SQL: the *atomic*
|
|
5532
|
+
* half of it is `consume`'s compare-and-set, and this is the cheap half.
|
|
5533
|
+
*/
|
|
5534
|
+
function agentApprovalUsableAt(request, now) {
|
|
5535
|
+
if (request.status !== "approved") return false;
|
|
5536
|
+
if (request.consumedAt !== void 0) return false;
|
|
5537
|
+
return !agentApprovalExpiredAt(request, now);
|
|
5538
|
+
}
|
|
5539
|
+
/**
|
|
5540
|
+
* Whether `principal` may be told anything at all about `request`.
|
|
5541
|
+
*
|
|
5542
|
+
* The scope rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads
|
|
5543
|
+
* the status only of a request it created. Without it the tool is a way to
|
|
5544
|
+
* enumerate other principals' pending actions — an agent could walk ids and
|
|
5545
|
+
* learn what a colleague is waiting to have approved, which is both the
|
|
5546
|
+
* content of the request and the fact that it exists.
|
|
5547
|
+
*
|
|
5548
|
+
* A record this returns `false` for must be answered *exactly* as an unknown
|
|
5549
|
+
* id is. Any difference between the two answers — a distinct message, a
|
|
5550
|
+
* different error shape, a slower path — is the enumeration the rule forbids,
|
|
5551
|
+
* reintroduced.
|
|
5552
|
+
*/
|
|
5553
|
+
function agentApprovalVisibleTo(request, principal) {
|
|
5554
|
+
return request.principalKey === agentApprovalPrincipalKey(principal);
|
|
5555
|
+
}
|
|
5556
|
+
//#endregion
|
|
5557
|
+
//#region src/agent/AgentApprovalRequested.ts
|
|
5558
|
+
/**
|
|
5559
|
+
* The notification an application sends its approvers when an agent tool call
|
|
5560
|
+
* becomes a pending approval request (RFC 0016 §5.4 item 4).
|
|
5561
|
+
*
|
|
5562
|
+
* A ready-made {@link Notification} rather than a message the adapter composes,
|
|
5563
|
+
* so "notify approvers through the existing notifications system" is one line
|
|
5564
|
+
* in an application's configuration:
|
|
5565
|
+
*
|
|
5566
|
+
* ```typescript
|
|
5567
|
+
* mcpPlugin({
|
|
5568
|
+
* approvals: {
|
|
5569
|
+
* store,
|
|
5570
|
+
* notify: (request) => notifications.sendToMany(admins, new AgentApprovalRequested(request)),
|
|
5571
|
+
* },
|
|
5572
|
+
* })
|
|
5573
|
+
* ```
|
|
5574
|
+
*
|
|
5575
|
+
* **Who the approvers are is never the framework's decision**, which is why
|
|
5576
|
+
* this class takes a request and not a recipient. The plugin hands the request
|
|
5577
|
+
* over; the application picks who hears about it, over which channels, with
|
|
5578
|
+
* whatever escalation it already has. An adapter that chose recipients would be
|
|
5579
|
+
* choosing them from a list it cannot see.
|
|
5580
|
+
*
|
|
5581
|
+
* Deliberately in its own module, and deliberately not imported by
|
|
5582
|
+
* `approval.ts`: the store interface and its derivations stay declaration-only
|
|
5583
|
+
* and free of the notifications subsystem, so a runtime that never notifies
|
|
5584
|
+
* never pulls it into the graph.
|
|
5585
|
+
*
|
|
5586
|
+
* Not queued (`shouldQueue` stays false). An approval request is answered by a
|
|
5587
|
+
* human in the next few minutes or it expires, and a queue worker that is
|
|
5588
|
+
* behind — or absent, which is the common case in the small deployments this
|
|
5589
|
+
* endpoint targets — turns "notify approvers" into "notify approvers
|
|
5590
|
+
* eventually", after the window closed.
|
|
5591
|
+
*/
|
|
5592
|
+
var AgentApprovalRequested = class extends Notification {
|
|
5593
|
+
request;
|
|
5594
|
+
constructor(request) {
|
|
5595
|
+
super();
|
|
5596
|
+
this.request = request;
|
|
5597
|
+
}
|
|
5598
|
+
/**
|
|
5599
|
+
* Mail and database by default — the two channels an application configures
|
|
5600
|
+
* first, and the pair that covers "tell someone now" and "there is a list of
|
|
5601
|
+
* things waiting". An application overrides by subclassing, exactly as it
|
|
5602
|
+
* would for any other notification.
|
|
5603
|
+
*/
|
|
5604
|
+
via(_notifiable) {
|
|
5605
|
+
return ["mail", "database"];
|
|
5606
|
+
}
|
|
5607
|
+
toMail(_notifiable) {
|
|
5608
|
+
const who = describePrincipal(this.request);
|
|
5609
|
+
return {
|
|
5610
|
+
subject: `Approval needed: ${this.request.tool}`,
|
|
5611
|
+
text: `${who} asked to run the agent tool "${this.request.tool}". Nothing has been executed.\n\nRequest id: ${this.request.id}\nRequested at: ${this.request.requestedAt}\nExpires at: ${this.request.expiresAt}\n\nArguments (sensitive fields masked):\n${JSON.stringify(this.request.input, null, 2)}\n`
|
|
5612
|
+
};
|
|
5613
|
+
}
|
|
5614
|
+
/**
|
|
5615
|
+
* The record's own fields, minus the fingerprint.
|
|
5616
|
+
*
|
|
5617
|
+
* The fingerprint is a hash of the *raw* arguments (see `approval.ts`), and
|
|
5618
|
+
* a database notification is read by more people, and kept longer, than the
|
|
5619
|
+
* approval store itself. It decides nothing an approver looks at: the
|
|
5620
|
+
* arguments they judge are `input`, already masked.
|
|
5621
|
+
*/
|
|
5622
|
+
toDatabase(_notifiable) {
|
|
5623
|
+
return {
|
|
5624
|
+
requestId: this.request.id,
|
|
5625
|
+
tool: this.request.tool,
|
|
5626
|
+
input: this.request.input,
|
|
5627
|
+
principal: this.request.principal,
|
|
5628
|
+
requestedAt: this.request.requestedAt,
|
|
5629
|
+
expiresAt: this.request.expiresAt
|
|
5630
|
+
};
|
|
5631
|
+
}
|
|
5632
|
+
toSlack(_notifiable) {
|
|
5633
|
+
return { text: `Approval needed: *${this.request.tool}* requested by ${describePrincipal(this.request)}. Nothing was executed. Request \`${this.request.id}\` expires at ${this.request.expiresAt}.` };
|
|
5634
|
+
}
|
|
5635
|
+
};
|
|
5636
|
+
/** The requester, in the vocabulary an approver reads rather than a key. */
|
|
5637
|
+
function describePrincipal(request) {
|
|
5638
|
+
const { principal } = request;
|
|
5639
|
+
if (!principal) return "An unidentified caller";
|
|
5640
|
+
return `${principal.kind === "service" ? "Service" : "User"} ${String(principal.id)}`;
|
|
5641
|
+
}
|
|
5642
|
+
//#endregion
|
|
5370
5643
|
//#region src/providers/OAuthServiceProvider.ts
|
|
5371
5644
|
/**
|
|
5372
5645
|
* Binds OAuthManager as a singleton in the container.
|
|
@@ -9081,27 +9354,7 @@ function renderEnvironmentSection() {
|
|
|
9081
9354
|
</section>`;
|
|
9082
9355
|
}
|
|
9083
9356
|
//#endregion
|
|
9084
|
-
//#region src/auth/password/DefaultHasher.ts
|
|
9085
|
-
/**
|
|
9086
|
-
* Runtime-detecting password hasher: uses Bun's native scrypt implementation
|
|
9087
|
-
* when running on Bun, and the Node.js crypto implementation otherwise
|
|
9088
|
-
* (e.g. AWS Lambda on the Node runtime). This is the hasher behind the
|
|
9089
|
-
* `Hash` export, so code written against `Hash` runs on both runtimes.
|
|
9090
|
-
*/
|
|
9091
|
-
var DefaultHasher = class {
|
|
9092
|
-
delegate;
|
|
9093
|
-
constructor() {
|
|
9094
|
-
this.delegate = typeof Bun !== "undefined" ? new ScryptHasher() : new NodeHasher();
|
|
9095
|
-
}
|
|
9096
|
-
hash(plain) {
|
|
9097
|
-
return this.delegate.hash(plain);
|
|
9098
|
-
}
|
|
9099
|
-
verify(hashed, plain) {
|
|
9100
|
-
return this.delegate.verify(hashed, plain);
|
|
9101
|
-
}
|
|
9102
|
-
};
|
|
9103
|
-
//#endregion
|
|
9104
9357
|
//#region src/index.ts
|
|
9105
9358
|
ensureErrorStackTracePolyfill();
|
|
9106
9359
|
//#endregion
|
|
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 };
|
|
9360
|
+
export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, 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, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, 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, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, 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, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, 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, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, 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, toAuditRecord, 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 };
|