@guren/server 2.33.0 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{Gate-COWQbA96.js → Gate-BHyDcDKo.js} +58 -10
  2. package/dist/{HttpException-BlQ2yEmT.js → HttpException-2tfZGamp.js} +8 -2
  3. package/dist/{McpServiceProvider-BDDr-7lh.js → McpServiceProvider-CXOokGax.js} +1 -1
  4. package/dist/{Resource-LQT1L4j0.js → Resource-y-7zzZSB.js} +43 -32
  5. package/dist/agent/scopes.d.ts +7 -0
  6. package/dist/{api-token-BbgDEd6j.js → api-token-1-INqeVU.js} +187 -2
  7. package/dist/auth/AuthManager.d.ts +4 -1
  8. package/dist/auth/TokenGuard.d.ts +4 -1
  9. package/dist/auth/api-token.d.ts +11 -1
  10. package/dist/auth/index.js +2 -2
  11. package/dist/{auth-DRMeSwev.js → auth-CO9MlQNE.js} +16 -24
  12. package/dist/authorization/Gate.d.ts +9 -5
  13. package/dist/authorization/index.js +2 -2
  14. package/dist/{authorization-DEHuBps5.js → authorization-rxx6aprN.js} +1 -1
  15. package/dist/broadcasting/index.js +1 -1
  16. package/dist/{broadcasting-CcevVE5Y.js → broadcasting-D04a3R02.js} +3 -2
  17. package/dist/{context-af2n5abO.js → context--l2HdOhy.js} +1 -1
  18. package/dist/{dev-banner-CSjrSNZi.js → dev-banner-BUrHz-LF.js} +7 -3
  19. package/dist/errors/ExceptionHandler.d.ts +7 -2
  20. package/dist/errors/HttpException.d.ts +6 -0
  21. package/dist/errors/debug-page.d.ts +1 -1
  22. package/dist/errors/exceptions/NotFoundHttpException.d.ts +2 -0
  23. package/dist/errors/redact-query-params.d.ts +16 -0
  24. package/dist/errors/wants-html.d.ts +7 -0
  25. package/dist/{errors-JpkcCjjn.js → errors-C8neC8go.js} +1 -1
  26. package/dist/health/index.js +1 -1
  27. package/dist/{health-Bg0Xj3aD.js → health-Wi_05kkf.js} +2 -1
  28. package/dist/http/Application.d.ts +12 -0
  29. package/dist/http/dev-banner.d.ts +6 -1
  30. package/dist/http/middleware/csrf.d.ts +1 -1
  31. package/dist/http/middleware/redirect-safety.d.ts +8 -0
  32. package/dist/index.js +247 -275
  33. package/dist/internal/agent-principal.d.ts +12 -3
  34. package/dist/internal/redact-query-params.d.ts +1 -0
  35. package/dist/internal/redact-query-params.js +2 -0
  36. package/dist/internal/testing.d.ts +2 -1
  37. package/dist/internal/testing.js +4 -4
  38. package/dist/lambda/index.js +3 -2
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Controller.d.ts +5 -5
  41. package/dist/mvc/inertia/InertiaEngine.d.ts +6 -0
  42. package/dist/notifications/index.js +1 -1
  43. package/dist/{notifications-R7Uj-aT7.js → notifications-DV5Yr6Fl.js} +2 -1
  44. package/dist/providers/InertiaServiceProvider.d.ts +7 -0
  45. package/dist/queue/index.js +1 -1
  46. package/dist/{queue-CO07wib_.js → queue-K4Bi6NRy.js} +17 -11
  47. package/dist/redact-query-params-Ba-sAfcP.js +106 -0
  48. package/dist/runtime/index.js +1 -1
  49. package/dist/{runtime-error-capture-DzllKc0d.js → runtime-error-capture-DLRXwp0d.js} +2 -2
  50. package/dist/{runtime-errors-D229wyoc.js → runtime-errors-Dh7nA2-p.js} +1 -1
  51. package/dist/scheduling/index.js +1 -1
  52. package/dist/{scheduling-DNV5tj44.js → scheduling-iLkx4gID.js} +2 -1
  53. package/dist/support/default-headers.d.ts +6 -0
  54. package/package.json +5 -1
@@ -1,6 +1,42 @@
1
- import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
1
+ import { n as NOT_FOUND_MESSAGE, t as HttpException } from "./HttpException-2tfZGamp.js";
2
2
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter, i as bindAmbient, n as ambientBinding } from "./default-application-s9SE-Er7.js";
3
- import { r as getAuthContext } from "./context-af2n5abO.js";
3
+ import { r as getAuthContext } from "./context--l2HdOhy.js";
4
+ //#region src/errors/exceptions/NotFoundHttpException.ts
5
+ /**
6
+ * Set, non-enumerable, by the `for*()` constructors, whose message the framework
7
+ * wrote from the record. Registry-keyed so a second copy of the package reads it;
8
+ * no public field marks it, since the constructor takes a developer's message too.
9
+ */
10
+ const COMPOSED_MESSAGE = Symbol.for("guren.notFound.composedMessage");
11
+ function composed(error) {
12
+ Object.defineProperty(error, COMPOSED_MESSAGE, { value: true });
13
+ return error;
14
+ }
15
+ /** Whether a `for*()` constructor wrote `error`'s message, which the exception handler replaces outside debug. */
16
+ function hasComposedMessage(error) {
17
+ return error[COMPOSED_MESSAGE] === true;
18
+ }
19
+ /** 404: the requested resource could not be found. */
20
+ var NotFoundHttpException = class NotFoundHttpException extends HttpException {
21
+ resourceType;
22
+ resourceId;
23
+ constructor(message = NOT_FOUND_MESSAGE, resourceType, resourceId) {
24
+ super(404, message);
25
+ this.name = "NotFoundHttpException";
26
+ this.resourceType = resourceType;
27
+ this.resourceId = resourceId;
28
+ }
29
+ static forModel(model, id) {
30
+ return composed(new NotFoundHttpException(`${model} with ID ${id} not found.`, model, id));
31
+ }
32
+ static forRoute(path) {
33
+ return composed(new NotFoundHttpException(`Route ${path} not found.`, "Route"));
34
+ }
35
+ static forResource(resource) {
36
+ return composed(new NotFoundHttpException(`${resource} not found.`, resource));
37
+ }
38
+ };
39
+ //#endregion
4
40
  //#region src/errors/exceptions/AuthorizationException.ts
5
41
  /** 403: the user is authenticated but not allowed to perform the action. */
6
42
  var AuthorizationException = class AuthorizationException extends HttpException {
@@ -48,7 +84,7 @@ const Response = {
48
84
  denyAsNotFound(message) {
49
85
  return {
50
86
  allowed: false,
51
- message: message ?? "Not found.",
87
+ message: message ?? "Not Found",
52
88
  status: 404
53
89
  };
54
90
  }
@@ -74,10 +110,18 @@ function isPlainRecord(value) {
74
110
  const prototype = Object.getPrototypeOf(value);
75
111
  return prototype === Object.prototype || prototype === null;
76
112
  }
77
- /** Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404. */
113
+ /** `[Model]` or `[Model, record]`, the model given as its class or a `gate.policy()` string key. */
114
+ function isPolicyTuple(value) {
115
+ return (value.length === 1 || value.length === 2) && (typeof value[0] === "function" || typeof value[0] === "string");
116
+ }
117
+ /**
118
+ * Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404.
119
+ * A 404 is a `NotFoundHttpException`, so a renderer registered for missing records renders it too.
120
+ */
78
121
  function denialToException(response) {
79
122
  const message = response.message ?? "This action is unauthorized.";
80
123
  const status = response.status;
124
+ if (status === 404) return new NotFoundHttpException(message);
81
125
  if (typeof status === "number" && status !== 403) return new HttpException(status, message);
82
126
  return new AuthorizationException(message);
83
127
  }
@@ -166,6 +210,7 @@ var Gate = class {
166
210
  return this.settle(user, ability, toAuthorizationResponse(result), args);
167
211
  }
168
212
  if (isPlainRecord(model)) throw new Error(`No policy resolved for a plain record in the "${ability}" check; pass [Model, record] so the gate can find the model's policy, or define a gate for "${ability}".`);
213
+ if (Array.isArray(model) && !isPolicyTuple(model)) throw new Error(`The "${ability}" check was given an array of ${model.length} that names no policy; pass [Model, record] for a record, Model or [Model] for an ability with no record, or define a gate for "${ability}".`);
169
214
  return this.settle(user, ability, Response.deny(), args);
170
215
  }
171
216
  async settle(user, ability, response, args) {
@@ -173,18 +218,21 @@ var Gate = class {
173
218
  return response;
174
219
  }
175
220
  /**
176
- * The subject may be a class instance (policy resolved via its constructor)
177
- * or a `[ModelClass, record]` / `['key', record]` tuple. ORM records are plain
178
- * objects with no constructor information, so they need the tuple: a plain
179
- * record reaching no policy and no gate throws in `checkResponse()`.
221
+ * The subject may be a class instance (policy resolved via its constructor),
222
+ * a `[ModelClass, record]` / `['key', record]` tuple, or the bare class or
223
+ * `[ModelClass]` for an ability with no record. ORM records are plain objects,
224
+ * so they need the tuple: a plain record or any other array reaching no policy
225
+ * and no gate throws in `checkResponse()`.
180
226
  */
181
227
  async checkPolicy(ability, user, model, additionalArgs) {
182
228
  let policyKey;
183
229
  let subject = model;
184
230
  let hasSubject = true;
185
- if (Array.isArray(model) && model.length === 2 && (typeof model[0] === "function" || typeof model[0] === "string")) {
231
+ if (Array.isArray(model)) {
232
+ if (!isPolicyTuple(model)) return;
186
233
  policyKey = model[0];
187
234
  subject = model[1];
235
+ hasSubject = model.length === 2;
188
236
  } else if (typeof model === "function") {
189
237
  policyKey = model;
190
238
  hasSubject = false;
@@ -267,4 +315,4 @@ async function authorize(ability, ...args) {
267
315
  return resolveGate().authorize(ability, ...args);
268
316
  }
269
317
  //#endregion
270
- export { cannot as a, denialToException as c, resolveGate as d, setGate as f, can as i, getGate as l, Response as n, createGate as o, AuthorizationException as p, authorize as r, defineGate as s, Gate as t, isAuthorizationResponse as u };
318
+ export { cannot as a, denialToException as c, resolveGate as d, setGate as f, hasComposedMessage as h, can as i, getGate as l, NotFoundHttpException as m, Response as n, createGate as o, AuthorizationException as p, authorize as r, defineGate as s, Gate as t, isAuthorizationResponse as u };
@@ -1,4 +1,10 @@
1
1
  //#region src/errors/HttpException.ts
2
+ /**
3
+ * The one 404 message the framework writes itself: `HttpException.notFound()`,
4
+ * `NotFoundHttpException`, `denyAsNotFound()`, `abort(404)`, and what the exception
5
+ * handler puts in place of a message naming a record outside debug.
6
+ */
7
+ const NOT_FOUND_MESSAGE = "Not Found";
2
8
  /** Base HTTP exception class. */
3
9
  var HttpException = class HttpException extends Error {
4
10
  statusCode;
@@ -42,7 +48,7 @@ var HttpException = class HttpException extends Error {
42
48
  static forbidden(message = "Forbidden") {
43
49
  return new HttpException(403, message);
44
50
  }
45
- static notFound(message = "Not Found") {
51
+ static notFound(message = NOT_FOUND_MESSAGE) {
46
52
  return new HttpException(404, message);
47
53
  }
48
54
  static methodNotAllowed(message = "Method Not Allowed") {
@@ -81,4 +87,4 @@ var HttpException = class HttpException extends Error {
81
87
  }
82
88
  };
83
89
  //#endregion
84
- export { HttpException as t };
90
+ export { NOT_FOUND_MESSAGE as n, HttpException as t };
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
2
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
3
- import { a as DEV_CENTER_FEEDBACK_ROUTE, l as isMcpEndpointEnabled, n as RUNTIME_ERRORS_PATH, o as MCP_ENDPOINT_PATH, s as createMcpAccessGuard, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DzllKc0d.js";
3
+ import { a as DEV_CENTER_FEEDBACK_ROUTE, l as isMcpEndpointEnabled, n as RUNTIME_ERRORS_PATH, o as MCP_ENDPOINT_PATH, s as createMcpAccessGuard, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-DLRXwp0d.js";
4
4
  //#region src/mcp/McpServiceProvider.ts
5
5
  var McpServiceProvider_exports = /* @__PURE__ */ __exportAll({
6
6
  DEV_MCP_CLI_TOO_OLD: () => DEV_MCP_CLI_TOO_OLD,
@@ -1,16 +1,16 @@
1
1
  import { i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, t as asRecord } from "./request-CLOYytGP.js";
2
2
  import { n as getValidatedInput, r as readValidatedInput } from "./validated-input-D84J8wcC.js";
3
- import { n as ValidationException } from "./errors-JpkcCjjn.js";
3
+ import { n as ValidationException } from "./errors-C8neC8go.js";
4
4
  import { n as parseImportMap, t as DEFAULT_DEV_STYLES_ENTRY } from "./inertia-defaults-BjrcT7za.js";
5
5
  import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
6
6
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter } from "./default-application-s9SE-Er7.js";
7
7
  import { n as initialPageElement, t as INITIAL_PAGE_SELECTOR } from "./initial-page-U637q3gO.js";
8
8
  import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
9
- import { r as getAuthContext } from "./context-af2n5abO.js";
10
- import { o as getApiTokenOrFail } from "./api-token-BbgDEd6j.js";
11
- import { a as resolveI18n } from "./i18n-BShPpJZa.js";
9
+ import { o as getApiTokenOrFail } from "./api-token-1-INqeVU.js";
10
+ import { r as getAuthContext } from "./context--l2HdOhy.js";
12
11
  import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
13
- import { d as resolveGate } from "./Gate-COWQbA96.js";
12
+ import { a as resolveI18n } from "./i18n-BShPpJZa.js";
13
+ import { d as resolveGate } from "./Gate-BHyDcDKo.js";
14
14
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
15
15
  import { getCookie } from "hono/cookie";
16
16
  import { isAbsolute, resolve } from "node:path";
@@ -180,6 +180,18 @@ async function resolveInertiaProps(input, partial) {
180
180
  } : { props };
181
181
  }
182
182
  //#endregion
183
+ //#region src/support/default-headers.ts
184
+ /**
185
+ * The caller's headers with each default set only where the caller named none. Header
186
+ * names are case-insensitive, so a caller's `content-type` replaces `Content-Type`
187
+ * rather than joining it; spreading a `Headers` or a pair list would drop it.
188
+ */
189
+ function withDefaultHeaders(init, defaults) {
190
+ const headers = new Headers(init);
191
+ for (const [name, value] of Object.entries(defaults)) if (!headers.has(name)) headers.set(name, value);
192
+ return headers;
193
+ }
194
+ //#endregion
183
195
  //#region src/mvc/inertia/InertiaEngine.ts
184
196
  ensureErrorStackTracePolyfill();
185
197
  let documentOptions;
@@ -232,6 +244,19 @@ async function inertia(component, props, options = {}) {
232
244
  */
233
245
  const INERTIA_VARY = "Accept, X-Inertia, X-Inertia-Partial-Component, X-Inertia-Partial-Data, X-Inertia-Partial-Except";
234
246
  /**
247
+ * Adds each {@link INERTIA_VARY} token the response's `Vary` does not list yet, so a
248
+ * caller's own `Vary` extends the engine's rather than replacing it. `*` already
249
+ * varies on everything and is left alone.
250
+ */
251
+ function mergeInertiaVary(headers) {
252
+ const current = headers.get("Vary")?.trim() ?? "";
253
+ const listed = current.split(",").map((token) => token.trim().toLowerCase()).filter(Boolean);
254
+ if (listed.includes("*")) return headers;
255
+ const missing = INERTIA_VARY.split(", ").filter((token) => !listed.includes(token.toLowerCase()));
256
+ if (missing.length > 0) headers.set("Vary", [...current ? [current] : [], ...missing].join(", "));
257
+ return headers;
258
+ }
259
+ /**
235
260
  * {@link inertia} plus the page it sent, for a caller that records the props
236
261
  * actually resolved (`Controller.inertia()`'s response marker). The version
237
262
  * check runs before any prop resolves: a 409 must not run a lazy prop's query.
@@ -262,13 +287,11 @@ async function renderInertia(component, props, options = {}) {
262
287
  page,
263
288
  response: new Response(body, {
264
289
  status: options.status ?? 200,
265
- headers: {
290
+ headers: mergeInertiaVary(withDefaultHeaders(options.headers, {
266
291
  "Content-Type": wantsJson ? "application/json; charset=utf-8" : "text/html; charset=utf-8",
267
292
  "X-Inertia": "true",
268
- Vary: INERTIA_VARY,
269
- ...versionHeader,
270
- ...options.headers
271
- }
293
+ ...versionHeader
294
+ }))
272
295
  })
273
296
  };
274
297
  }
@@ -865,11 +888,11 @@ var Controller = class {
865
888
  return this.apiToken().userId;
866
889
  }
867
890
  /**
868
- * Authorize the current user (or guest) for an ability; throws
869
- * AuthorizationException (403) when denied. ORM records are plain objects
870
- * with no constructor information, so pass the model class alongside the
871
- * record: `await this.authorize('update', [Post, post])`. A bare record that
872
- * resolves no policy and no gate throws an Error rather than denying.
891
+ * Authorize the current user (or guest) for an ability; throws AuthorizationException
892
+ * (403) when denied. An ORM record is a plain object, so pass its class beside it:
893
+ * `this.authorize('update', [Post, post])`; an ability with no record takes `Post`
894
+ * or `[Post]`. A bare record or another array that resolves no policy and no gate
895
+ * throws an Error rather than denying.
873
896
  */
874
897
  async authorize(ability, ...args) {
875
898
  await this.#resolveGate().forUser(await this.gateUser()).authorize(ability, ...args);
@@ -955,19 +978,13 @@ var Controller = class {
955
978
  json(data, init = {}) {
956
979
  return new Response(JSON.stringify(data), {
957
980
  ...init,
958
- headers: {
959
- "Content-Type": "application/json; charset=utf-8",
960
- ...init.headers
961
- }
981
+ headers: withDefaultHeaders(init.headers, { "Content-Type": "application/json; charset=utf-8" })
962
982
  });
963
983
  }
964
984
  text(body, init = {}) {
965
985
  return new Response(body, {
966
986
  ...init,
967
- headers: {
968
- "Content-Type": "text/plain; charset=utf-8",
969
- ...init.headers
970
- }
987
+ headers: withDefaultHeaders(init.headers, { "Content-Type": "text/plain; charset=utf-8" })
971
988
  });
972
989
  }
973
990
  redirect(url, options = {}) {
@@ -976,10 +993,7 @@ var Controller = class {
976
993
  const { status = defaultStatus, headers } = options;
977
994
  return new Response(null, {
978
995
  status,
979
- headers: {
980
- Location: url,
981
- ...headers
982
- }
996
+ headers: withDefaultHeaders(headers, { Location: url })
983
997
  });
984
998
  }
985
999
  noContent() {
@@ -999,10 +1013,7 @@ var Controller = class {
999
1013
  return new Response(JSON.stringify(data), {
1000
1014
  status,
1001
1015
  ...init,
1002
- headers: {
1003
- "Content-Type": "application/json; charset=utf-8",
1004
- ...init.headers
1005
- }
1016
+ headers: withDefaultHeaders(init.headers, { "Content-Type": "application/json; charset=utf-8" })
1006
1017
  });
1007
1018
  }
1008
1019
  /** Get an input value; body values take precedence over query parameters. */
@@ -1173,4 +1184,4 @@ var JsonResource = class extends Resource {
1173
1184
  }
1174
1185
  };
1175
1186
  //#endregion
1176
- export { setInertiaSsrRenderer as C, isDeferredProp as D, isAlwaysProp as E, ensureErrorStackTracePolyfill as O, setInertiaDocument as S, defer as T, INERTIA_VARY as _, renderDocument as a, inertia as b, getRequestLocale as c, mountModuleRoutes as d, definePlugin as f, shareInertiaProps as g, setInertiaSharedProps as h, Controller as i, getRequestTranslator as l, resolveSharedInertiaProps as m, Resource as n, LOCALE_CONTEXT_KEY as o, getInertiaSharedPropsResolver as p, collect as r, detectLocaleMiddleware as s, JsonResource as t, defineModule as u, acceptsJson as v, always as w, serializePage as x, buildInertiaPage as y };
1187
+ export { ensureErrorStackTracePolyfill as A, setInertiaDocument as C, defer as D, always as E, isAlwaysProp as O, serializePage as S, withDefaultHeaders as T, INERTIA_VARY as _, renderDocument as a, inertia as b, getRequestLocale as c, mountModuleRoutes as d, definePlugin as f, shareInertiaProps as g, setInertiaSharedProps as h, Controller as i, isDeferredProp as k, getRequestTranslator as l, resolveSharedInertiaProps as m, Resource as n, LOCALE_CONTEXT_KEY as o, getInertiaSharedPropsResolver as p, collect as r, detectLocaleMiddleware as s, JsonResource as t, defineModule as u, acceptsJson as v, setInertiaSsrRenderer as w, mergeInertiaVary as x, buildInertiaPage as y };
@@ -52,6 +52,13 @@ export interface ScopedTool {
52
52
  * (`tools:`, `tools:.*`, `tools:*.store`): both mean "grants no tool", on purpose.
53
53
  */
54
54
  export declare function parseToolScope(entry: string): ParsedToolScope | null;
55
+ /**
56
+ * Whether a token's abilities are all `tool:` / `tools:` entries, malformed ones
57
+ * included: such a token was issued for agent tools, and its scopes are judged
58
+ * only by the tool pipeline, so it must not authenticate an ordinary request.
59
+ * An empty list is not agent-only, since it was not issued for tools either.
60
+ */
61
+ export declare function grantsOnlyAgentTools(abilities: readonly string[]): boolean;
55
62
  /**
56
63
  * The scope forms a **registration** may declare (RFC 0017 §3): the narrower
57
64
  * half of the grammar above, because a registration grants an *unattended*
@@ -1,6 +1,40 @@
1
- import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
1
+ import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context--l2HdOhy.js";
2
2
  import { isOptionalExpiryPast } from "./support/expiry.js";
3
+ import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
3
4
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
5
+ //#region src/internal/agent-principal.ts
6
+ const installed = /* @__PURE__ */ new WeakMap();
7
+ /**
8
+ * Mark `request` as carrying `principal`, returning that same object — a copy
9
+ * would key the map on something the auth context never sees. Returning it is
10
+ * what makes the identity requirement hard to get wrong at a call site:
11
+ * `app.fetch(installAgentPrincipal(request, installed), env, ctx)`. Callers
12
+ * reach this through the pipeline's `handoff: 'seam'`, and the reader not at all.
13
+ */
14
+ function installAgentPrincipal(request, value) {
15
+ installed.set(request, value);
16
+ return request;
17
+ }
18
+ /** The principal installed on this exact request object, or `undefined`. */
19
+ function readAgentPrincipal(request) {
20
+ return installed.get(request);
21
+ }
22
+ const dispatched = /* @__PURE__ */ new WeakSet();
23
+ /**
24
+ * Mark `request` as a tool call the pipeline scope-gated, returning that same
25
+ * object: a token granting only agent tools authenticates such a request and no
26
+ * other. Not `markDispatchedToolRequest()`, which `buildToolRequest` sets for
27
+ * un-gated callers too (`guren tool:call`, `TestApp.agent()`, plugin-webmcp).
28
+ */
29
+ function markAgentDispatch(request) {
30
+ dispatched.add(request);
31
+ return request;
32
+ }
33
+ /** Whether the pipeline dispatched this exact request object. */
34
+ function isAgentDispatch(request) {
35
+ return dispatched.has(request);
36
+ }
37
+ //#endregion
4
38
  //#region src/auth/utils.ts
5
39
  function hashToken(token, algorithm = "sha256") {
6
40
  return createHash(algorithm).update(token).digest("hex");
@@ -53,6 +87,129 @@ function parseTokenUrl(url) {
53
87
  }
54
88
  }
55
89
  //#endregion
90
+ //#region src/agent/scopes.ts
91
+ /**
92
+ * The scope grammar an API token's `abilities` use to reach agent tools
93
+ * (RFC 0016 §5.1). Four forms, so a human can read a scope on a consent screen:
94
+ * `tool:<name>`, `tools:read` (every tool whose resolved `readOnlyHint` is
95
+ * true), `tools:*`, `tools:<prefix>.*`. **Only `tool:` / `tools:` entries are
96
+ * considered**, so the store's default `['*']` grants no tool (default deny). A
97
+ * malformed entry is ignored, not thrown: this module judges an issued token and
98
+ * must grant less, never more; rejecting belongs to the issuer, which refuses a
99
+ * `null` from {@link parseToolScope}. Case-sensitive and untrimmed, for the same reason.
100
+ */
101
+ /**
102
+ * The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
103
+ * `tools:<prefix>.*` scope must stay inside. `*` is not in the charset, so
104
+ * `tool:posts.*` is rejected with no special case.
105
+ */
106
+ const AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
107
+ /** `tool:` scope prefix, including the separator. */
108
+ const SINGLE_PREFIX = "tool:";
109
+ /** `tools:` scope prefix, including the separator. */
110
+ const SET_PREFIX = "tools:";
111
+ /** The reserved `tools:` word granting every read-only tool. */
112
+ const READ_KEYWORD = "read";
113
+ /** The reserved `tools:` word granting every tool. */
114
+ const ALL_KEYWORD = "*";
115
+ /** Wildcard suffix of a prefix scope, dot included. */
116
+ const PREFIX_SUFFIX = ".*";
117
+ /**
118
+ * Parse one `abilities` entry. The two reserved `tools:` words are matched
119
+ * before the wildcard form, so a family named `read.…` is still reachable as
120
+ * `tools:read.*` while a tool named exactly `read` is only `tool:read`.
121
+ * @returns The scope, or `null` for both a non-tool entry and a malformed one
122
+ * (`tools:`, `tools:.*`, `tools:*.store`): both mean "grants no tool", on purpose.
123
+ */
124
+ function parseToolScope(entry) {
125
+ if (entry.startsWith(SINGLE_PREFIX)) {
126
+ const name = entry.slice(5);
127
+ return AGENT_TOOL_NAME_PATTERN.test(name) ? {
128
+ kind: "tool",
129
+ name
130
+ } : null;
131
+ }
132
+ if (!entry.startsWith(SET_PREFIX)) return null;
133
+ const rest = entry.slice(6);
134
+ if (rest === READ_KEYWORD) return { kind: "read" };
135
+ if (rest === ALL_KEYWORD) return { kind: "all" };
136
+ if (!rest.endsWith(PREFIX_SUFFIX)) return null;
137
+ const prefix = rest.slice(0, -2);
138
+ if (!AGENT_TOOL_NAME_PATTERN.test(prefix)) return null;
139
+ return {
140
+ kind: "prefix",
141
+ prefix
142
+ };
143
+ }
144
+ /**
145
+ * Whether a token's abilities are all `tool:` / `tools:` entries, malformed ones
146
+ * included: such a token was issued for agent tools, and its scopes are judged
147
+ * only by the tool pipeline, so it must not authenticate an ordinary request.
148
+ * An empty list is not agent-only, since it was not issued for tools either.
149
+ */
150
+ function grantsOnlyAgentTools(abilities) {
151
+ return abilities.length > 0 && abilities.every((entry) => entry.startsWith(SINGLE_PREFIX) || entry.startsWith(SET_PREFIX));
152
+ }
153
+ /**
154
+ * Judge one `scopes` entry of an agent registration.
155
+ *
156
+ * @param entry The scope as written in the config.
157
+ */
158
+ function classifyRegistrationScope(entry) {
159
+ const scope = parseToolScope(entry);
160
+ if (scope?.kind === "tool" || scope?.kind === "read") return {
161
+ allowed: true,
162
+ scope
163
+ };
164
+ if (scope?.kind === "all") return {
165
+ allowed: false,
166
+ reason: "wildcard",
167
+ message: `"${entry}" grants every tool the application has, including every tool it grows later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools as tool:<name> entries, or use tools:read if the agent only reads.`
168
+ };
169
+ if (scope?.kind === "prefix") return {
170
+ allowed: false,
171
+ reason: "prefix",
172
+ message: `"${entry}" grants every tool in the ${scope.prefix}.* family, including ones added later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools it needs as tool:<name> entries.`
173
+ };
174
+ const suggestion = AGENT_TOOL_NAME_PATTERN.test(entry) ? ` Did you mean "tool:${entry}"?` : "";
175
+ return {
176
+ allowed: false,
177
+ reason: "not-a-tool-scope",
178
+ message: `"${entry}" is not a tool scope, so it grants nothing. The registration grammar is tool:<name> for one tool by exact name, or tools:read for every read-only tool.` + suggestion
179
+ };
180
+ }
181
+ /** Whether one parsed scope covers a given tool. */
182
+ function scopeAllowsTool(scope, tool) {
183
+ switch (scope.kind) {
184
+ case "tool": return scope.name === tool.name;
185
+ case "read": return tool.readOnly;
186
+ case "all": return true;
187
+ case "prefix": return tool.name.startsWith(`${scope.prefix}.`);
188
+ default: return scope;
189
+ }
190
+ }
191
+ /**
192
+ * Whether a token's abilities grant a tool. Any one entry suffices — scopes
193
+ * are additive, and there is no deny form.
194
+ */
195
+ function scopesAllowTool(abilities, tool) {
196
+ for (const entry of abilities) {
197
+ const scope = parseToolScope(entry);
198
+ if (scope && scopeAllowsTool(scope, tool)) return true;
199
+ }
200
+ return false;
201
+ }
202
+ /**
203
+ * The concrete tool names a token's abilities grant, for the surfaces that show
204
+ * a human what a scope means: the OAuth consent screen, the `token:issue`
205
+ * confirmation, the issuance-time lint. Literally a filter over
206
+ * {@link scopesAllowTool}, and it must stay one: a second matcher is how a
207
+ * consent screen comes to list a tool the dispatcher then denies. Order of `tools`.
208
+ */
209
+ function expandToolScopes(abilities, tools) {
210
+ return tools.filter((tool) => scopesAllowTool(abilities, tool)).map((tool) => tool.name);
211
+ }
212
+ //#endregion
56
213
  //#region src/auth/api-token.ts
57
214
  /**
58
215
  * In-memory token store for testing.
@@ -159,6 +316,26 @@ function hasBearerHeader(ctx) {
159
316
  return readBearerToken(ctx.req.header("Authorization")) !== null;
160
317
  }
161
318
  /**
319
+ * Whether a verified token may authenticate this request. A token granting only
320
+ * agent tools (`tool:` / `tools:` abilities) answers for the tool calls the
321
+ * pipeline dispatched after judging its scopes, and for a request to an endpoint
322
+ * that judges them itself (the MCP endpoint, reached through app-wide auth
323
+ * middleware); never for a request a client sent straight to a route.
324
+ */
325
+ function tokenAuthenticatesRequest(verified, ctx, agentEndpoints) {
326
+ if (!grantsOnlyAgentTools(verified.abilities)) return true;
327
+ if (isAgentDispatch(ctx.req.raw)) return true;
328
+ const path = requestPathname(ctx);
329
+ return path !== void 0 && (agentEndpoints?.().has(path) ?? false);
330
+ }
331
+ function requestPathname(ctx) {
332
+ try {
333
+ return new URL(ctx.req.url).pathname;
334
+ } catch {
335
+ return;
336
+ }
337
+ }
338
+ /**
162
339
  * Verify an API token and return the associated user ID.
163
340
  */
164
341
  async function verifyApiToken(plainTextToken, store, options = {}) {
@@ -230,6 +407,10 @@ async function revokePresentedToken(ctx, tokenId, store) {
230
407
  if (tokenId) await revokeApiToken(tokenId, store);
231
408
  ctx.set(API_TOKEN_KEY, void 0);
232
409
  }
410
+ function appAgentEndpoints(ctx) {
411
+ const app = tryGetRequestContainer(ctx)?.makeOptional("app");
412
+ return app?.getAgentEndpointPaths ? () => app.getAgentEndpointPaths() : void 0;
413
+ }
233
414
  /**
234
415
  * Create middleware that authenticates requests using Bearer tokens.
235
416
  * @example
@@ -255,6 +436,10 @@ function createBearerTokenMiddleware(options) {
255
436
  if (onUnauthorized) return onUnauthorized(ctx);
256
437
  return ctx.json({ error: "Invalid or expired token" }, 401);
257
438
  }
439
+ if (!tokenAuthenticatesRequest(result, ctx, appAgentEndpoints(ctx))) {
440
+ if (onUnauthorized) return onUnauthorized(ctx);
441
+ return ctx.json({ error: "This token only grants agent tools" }, 401);
442
+ }
258
443
  if (abilities && abilities.length > 0) {
259
444
  if (!tokenCanAll(result.token, abilities)) {
260
445
  if (onForbidden) return onForbidden(ctx, abilities);
@@ -295,4 +480,4 @@ function getApiTokenOrFail(ctx) {
295
480
  return result;
296
481
  }
297
482
  //#endregion
298
- export { secureCompare as C, parseTokenUrl as S, verifyApiToken as _, getApiToken as a, generateToken as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAny as g, tokenCanAll as h, createBearerTokenMiddleware as i, parseApiToken as l, tokenCan as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, buildTokenUrl as v, secureStringCompare as w, hashToken as x, generateId as y };
483
+ export { secureStringCompare as A, scopesAllowTool as C, hashToken as D, generateToken as E, markAgentDispatch as M, readAgentPrincipal as N, parseTokenUrl as O, parseToolScope as S, generateId as T, tokenCanAny as _, getApiToken as a, classifyRegistrationScope as b, hasBearerHeader as c, revokeAllApiTokens as d, revokeApiToken as f, tokenCanAll as g, tokenCan as h, createBearerTokenMiddleware as i, installAgentPrincipal as j, secureCompare as k, parseApiToken as l, tokenAuthenticatesRequest as m, MemoryApiTokenStore as n, getApiTokenOrFail as o, revokePresentedToken as p, createApiToken as r, getUserApiTokens as s, API_TOKEN_KEY as t, readBearerToken as u, verifyApiToken as v, buildTokenUrl as w, expandToolScopes as x, AGENT_TOOL_NAME_PATTERN as y };
@@ -1,7 +1,7 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { Model, PlainObject } from '@guren/orm';
3
3
  import { type ModelUserProviderOptions } from './providers/ModelUserProvider.js';
4
- import { type ApiTokenStore } from './api-token.js';
4
+ import { type AgentEndpointPaths, type ApiTokenStore } from './api-token.js';
5
5
  import type { PasswordHasher } from './password/PasswordHasher.js';
6
6
  import type { AuthEntry } from '../introspection/types.js';
7
7
  import type { AttachContextOptions, AuthContext, AuthManagerContract, AuthManagerOptions, AuthCredentials, Guard, GuardContext, GuardFactory, ProviderFactory, UserProvider } from './types.js';
@@ -24,6 +24,7 @@ export declare class AuthManager implements AuthManagerContract {
24
24
  private tokenGuard;
25
25
  private apiTokenStore;
26
26
  private apiTokenOptions;
27
+ private agentEndpoints?;
27
28
  private readonly passwordHasher;
28
29
  constructor(options?: AuthManagerOptions);
29
30
  /**
@@ -76,6 +77,8 @@ export declare class AuthManager implements AuthManagerContract {
76
77
  * @param guardName - Defaults to 'web'
77
78
  */
78
79
  useModel(model: typeof Model<PlainObject>, options?: Partial<ModelUserProviderOptions>, providerName?: string, guardName?: string): void;
80
+ /** Where a tools-only token is accepted besides a pipeline dispatch; `Application` passes its {@link Application.declareAgentEndpoint} paths. */
81
+ setAgentEndpoints(endpoints: AgentEndpointPaths): void;
79
82
  /**
80
83
  * Register a bearer-token guard backed by an ApiTokenStore and enable
81
84
  * header-based guard selection: requests carrying `Authorization: Bearer`
@@ -1,7 +1,7 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { AuthCredentials, Guard, UserProvider } from './types.js';
3
3
  import type { Session } from '../http/middleware/index.js';
4
- import { type ApiTokenStore } from './api-token.js';
4
+ import { type AgentEndpointPaths, type ApiTokenStore } from './api-token.js';
5
5
  export interface TokenGuardOptions<User = unknown> {
6
6
  store: ApiTokenStore;
7
7
  ctx: Context;
@@ -12,6 +12,8 @@ export interface TokenGuardOptions<User = unknown> {
12
12
  provider?: UserProvider<User>;
13
13
  /** Update the token's lastUsedAt on successful verification. Default true. */
14
14
  updateLastUsed?: boolean;
15
+ /** Endpoints that judge tool scopes themselves, where a tools-only token is accepted. */
16
+ agentEndpoints?: AgentEndpointPaths;
15
17
  }
16
18
  /**
17
19
  * Bearer-token Guard (RFC 0016 Phase 0). Credential flows (`attempt`,
@@ -24,6 +26,7 @@ export declare class TokenGuard<User = unknown> implements Guard<User> {
24
26
  private readonly store;
25
27
  private readonly provider?;
26
28
  private readonly updateLastUsed;
29
+ private readonly agentEndpoints?;
27
30
  private verification?;
28
31
  private resolvedUser?;
29
32
  constructor(options: TokenGuardOptions<User>);
@@ -104,6 +104,16 @@ export interface VerifiedApiToken {
104
104
  userId: string | number;
105
105
  abilities: string[];
106
106
  }
107
+ /** The paths whose own endpoint judges tool scopes; `Application` supplies its declared ones. */
108
+ export type AgentEndpointPaths = () => ReadonlySet<string>;
109
+ /**
110
+ * Whether a verified token may authenticate this request. A token granting only
111
+ * agent tools (`tool:` / `tools:` abilities) answers for the tool calls the
112
+ * pipeline dispatched after judging its scopes, and for a request to an endpoint
113
+ * that judges them itself (the MCP endpoint, reached through app-wide auth
114
+ * middleware); never for a request a client sent straight to a route.
115
+ */
116
+ export declare function tokenAuthenticatesRequest(verified: VerifiedApiToken, ctx: Context, agentEndpoints?: AgentEndpointPaths): boolean;
107
117
  /**
108
118
  * Verify an API token and return the associated user ID.
109
119
  */
@@ -156,7 +166,7 @@ export declare function revokePresentedToken(ctx: Context, tokenId: string | und
156
166
  export interface BearerTokenMiddlewareOptions {
157
167
  store: ApiTokenStore;
158
168
  loadUser?: (userId: string | number) => Promise<unknown>;
159
- /** Required abilities. Any valid token is accepted when unset. */
169
+ /** Required abilities. Unset, any valid token is accepted except one granting only agent tools. */
160
170
  abilities?: string[];
161
171
  onUnauthorized?: (ctx: Context) => Response | Promise<Response>;
162
172
  onForbidden?: (ctx: Context, required: string[]) => Response | Promise<Response>;
@@ -1,3 +1,3 @@
1
- import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-DRMeSwev.js";
2
- import { C as secureCompare, S as parseTokenUrl, _ as verifyApiToken, a as getApiToken, b as generateToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAny, h as tokenCanAll, i as createBearerTokenMiddleware, l as parseApiToken, m as tokenCan, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as buildTokenUrl, w as secureStringCompare, x as hashToken, y as generateId } from "../api-token-BbgDEd6j.js";
1
+ import { A as verifyOAuthState, B as ModelUserProvider, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as NodeHasher, I as AuthManager, O as parseOAuthRedirectUrl, R as TokenGuard, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as ScryptHasher, W as BaseUserProvider, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, p as parsePasswordResetUrl, r as completeEmailVerification, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as SessionGuard } from "../auth-CO9MlQNE.js";
2
+ import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, T as generateId, _ as tokenCanAny, a as getApiToken, d as revokeAllApiTokens, f as revokeApiToken, g as tokenCanAll, h as tokenCan, i as createBearerTokenMiddleware, k as secureCompare, l as parseApiToken, n as MemoryApiTokenStore, o as getApiTokenOrFail, r as createApiToken, s as getUserApiTokens, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "../api-token-1-INqeVU.js";
3
3
  export { API_TOKEN_KEY, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };