@guren/server 2.33.0 → 2.34.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 (44) hide show
  1. package/dist/{Gate-COWQbA96.js → Gate-C252SwRR.js} +13 -5
  2. package/dist/{McpServiceProvider-BDDr-7lh.js → McpServiceProvider-CXOokGax.js} +1 -1
  3. package/dist/{Resource-LQT1L4j0.js → Resource-BBKaFgXf.js} +41 -30
  4. package/dist/agent/scopes.d.ts +7 -0
  5. package/dist/{api-token-BbgDEd6j.js → api-token-DJcqSybf.js} +186 -1
  6. package/dist/auth/AuthManager.d.ts +4 -1
  7. package/dist/auth/TokenGuard.d.ts +4 -1
  8. package/dist/auth/api-token.d.ts +11 -1
  9. package/dist/auth/index.js +2 -2
  10. package/dist/{auth-DRMeSwev.js → auth-Bj9uEHuC.js} +15 -23
  11. package/dist/authorization/Gate.d.ts +5 -4
  12. package/dist/authorization/index.js +2 -2
  13. package/dist/{authorization-DEHuBps5.js → authorization-C81TXOWD.js} +1 -1
  14. package/dist/broadcasting/index.js +1 -1
  15. package/dist/{broadcasting-CcevVE5Y.js → broadcasting-3pvO94xV.js} +2 -1
  16. package/dist/{dev-banner-CSjrSNZi.js → dev-banner-B_QaY29h.js} +1 -1
  17. package/dist/errors/ExceptionHandler.d.ts +2 -1
  18. package/dist/errors/debug-page.d.ts +1 -1
  19. package/dist/errors/redact-query-params.d.ts +16 -0
  20. package/dist/health/index.js +1 -1
  21. package/dist/{health-Bg0Xj3aD.js → health-Wi_05kkf.js} +2 -1
  22. package/dist/http/Application.d.ts +12 -0
  23. package/dist/index.js +54 -139
  24. package/dist/internal/agent-principal.d.ts +12 -3
  25. package/dist/internal/redact-query-params.d.ts +1 -0
  26. package/dist/internal/redact-query-params.js +2 -0
  27. package/dist/internal/testing.d.ts +2 -1
  28. package/dist/internal/testing.js +2 -2
  29. package/dist/lambda/index.js +3 -2
  30. package/dist/mcp/index.js +1 -1
  31. package/dist/mvc/Controller.d.ts +5 -5
  32. package/dist/mvc/inertia/InertiaEngine.d.ts +6 -0
  33. package/dist/notifications/index.js +1 -1
  34. package/dist/{notifications-R7Uj-aT7.js → notifications-DV5Yr6Fl.js} +2 -1
  35. package/dist/queue/index.js +1 -1
  36. package/dist/{queue-CO07wib_.js → queue-K4Bi6NRy.js} +17 -11
  37. package/dist/redact-query-params-Ba-sAfcP.js +106 -0
  38. package/dist/runtime/index.js +1 -1
  39. package/dist/{runtime-error-capture-DzllKc0d.js → runtime-error-capture-DLRXwp0d.js} +2 -2
  40. package/dist/{runtime-errors-D229wyoc.js → runtime-errors-Dh7nA2-p.js} +1 -1
  41. package/dist/scheduling/index.js +1 -1
  42. package/dist/{scheduling-DNV5tj44.js → scheduling-iLkx4gID.js} +2 -1
  43. package/dist/support/default-headers.d.ts +6 -0
  44. package/package.json +5 -1
@@ -74,6 +74,10 @@ function isPlainRecord(value) {
74
74
  const prototype = Object.getPrototypeOf(value);
75
75
  return prototype === Object.prototype || prototype === null;
76
76
  }
77
+ /** `[Model]` or `[Model, record]`, the model given as its class or a `gate.policy()` string key. */
78
+ function isPolicyTuple(value) {
79
+ return (value.length === 1 || value.length === 2) && (typeof value[0] === "function" || typeof value[0] === "string");
80
+ }
77
81
  /** Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404. */
78
82
  function denialToException(response) {
79
83
  const message = response.message ?? "This action is unauthorized.";
@@ -166,6 +170,7 @@ var Gate = class {
166
170
  return this.settle(user, ability, toAuthorizationResponse(result), args);
167
171
  }
168
172
  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}".`);
173
+ 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
174
  return this.settle(user, ability, Response.deny(), args);
170
175
  }
171
176
  async settle(user, ability, response, args) {
@@ -173,18 +178,21 @@ var Gate = class {
173
178
  return response;
174
179
  }
175
180
  /**
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()`.
181
+ * The subject may be a class instance (policy resolved via its constructor),
182
+ * a `[ModelClass, record]` / `['key', record]` tuple, or the bare class or
183
+ * `[ModelClass]` for an ability with no record. ORM records are plain objects,
184
+ * so they need the tuple: a plain record or any other array reaching no policy
185
+ * and no gate throws in `checkResponse()`.
180
186
  */
181
187
  async checkPolicy(ability, user, model, additionalArgs) {
182
188
  let policyKey;
183
189
  let subject = model;
184
190
  let hasSubject = true;
185
- if (Array.isArray(model) && model.length === 2 && (typeof model[0] === "function" || typeof model[0] === "string")) {
191
+ if (Array.isArray(model)) {
192
+ if (!isPolicyTuple(model)) return;
186
193
  policyKey = model[0];
187
194
  subject = model[1];
195
+ hasSubject = model.length === 2;
188
196
  } else if (typeof model === "function") {
189
197
  policyKey = model;
190
198
  hasSubject = false;
@@ -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,
@@ -6,11 +6,11 @@ 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 { o as getApiTokenOrFail } from "./api-token-DJcqSybf.js";
9
10
  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";
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-C252SwRR.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
1
  import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.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-Bj9uEHuC.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-DJcqSybf.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 };
@@ -1,8 +1,9 @@
1
1
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-DIUT1Yao.js";
2
2
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
3
+ import { A as secureStringCompare, D as hashToken, E as generateToken, N as readAgentPrincipal, O as parseTokenUrl, T as generateId, c as hasBearerHeader, k as secureCompare, l as parseApiToken, m as tokenAuthenticatesRequest, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "./api-token-DJcqSybf.js";
3
4
  import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as AuthenticationException, r as getAuthContext } from "./context-af2n5abO.js";
4
5
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
5
- import { C as secureCompare, S as parseTokenUrl, _ as verifyApiToken, b as generateToken, c as hasBearerHeader, l as parseApiToken, p as revokePresentedToken, 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";
6
+ import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
6
7
  import { isExpired } from "./support/expiry.js";
7
8
  import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
8
9
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
@@ -361,24 +362,6 @@ function getSessionFromContext(ctx) {
361
362
  return ctx.get(SESSION_CONTEXT_KEY);
362
363
  }
363
364
  //#endregion
364
- //#region src/internal/agent-principal.ts
365
- const installed = /* @__PURE__ */ new WeakMap();
366
- /**
367
- * Mark `request` as carrying `principal`, returning that same object — a copy
368
- * would key the map on something the auth context never sees. Returning it is
369
- * what makes the identity requirement hard to get wrong at a call site:
370
- * `app.fetch(installAgentPrincipal(request, installed), env, ctx)`. Callers
371
- * reach this through the pipeline's `handoff: 'seam'`, and the reader not at all.
372
- */
373
- function installAgentPrincipal(request, value) {
374
- installed.set(request, value);
375
- return request;
376
- }
377
- /** The principal installed on this exact request object, or `undefined`. */
378
- function readAgentPrincipal(request) {
379
- return installed.get(request);
380
- }
381
- //#endregion
382
365
  //#region src/auth/providers/UserProvider.ts
383
366
  /**
384
367
  * Run a user record through the provider's optional `sanitize` before it leaves
@@ -984,7 +967,7 @@ var SessionGuard = class {
984
967
  try {
985
968
  await this.provider.rehashPasswordIfRequired?.(user, credentials);
986
969
  } catch (error) {
987
- console.warn(`[guren] Rehashing the password for user ${this.describeUser(user)} failed; the login continues.`, error);
970
+ console.warn(`[guren] Rehashing the password for user ${this.describeUser(user)} failed; the login continues.`, redactQueryParams(error));
988
971
  }
989
972
  return user;
990
973
  }
@@ -1013,6 +996,7 @@ var TokenGuard = class {
1013
996
  store;
1014
997
  provider;
1015
998
  updateLastUsed;
999
+ agentEndpoints;
1016
1000
  verification;
1017
1001
  resolvedUser;
1018
1002
  constructor(options) {
@@ -1020,6 +1004,7 @@ var TokenGuard = class {
1020
1004
  this.store = options.store;
1021
1005
  this.provider = options.provider;
1022
1006
  this.updateLastUsed = options.updateLastUsed ?? true;
1007
+ this.agentEndpoints = options.agentEndpoints;
1023
1008
  }
1024
1009
  verify() {
1025
1010
  if (!this.verification) this.verification = (async () => {
@@ -1027,7 +1012,8 @@ var TokenGuard = class {
1027
1012
  if (!plainTextToken) return null;
1028
1013
  const existing = this.ctx.get(API_TOKEN_KEY);
1029
1014
  if (existing && existing.token.id === parseApiToken(plainTextToken)?.id) return existing;
1030
- const result = await verifyApiToken(plainTextToken, this.store, { updateLastUsed: this.updateLastUsed });
1015
+ const verified = await verifyApiToken(plainTextToken, this.store, { updateLastUsed: this.updateLastUsed });
1016
+ const result = verified && tokenAuthenticatesRequest(verified, this.ctx, this.agentEndpoints) ? verified : null;
1031
1017
  if (result) this.ctx.set(API_TOKEN_KEY, result);
1032
1018
  return result;
1033
1019
  })();
@@ -1112,6 +1098,7 @@ var AuthManager = class {
1112
1098
  tokenGuard = null;
1113
1099
  apiTokenStore = null;
1114
1100
  apiTokenOptions = {};
1101
+ agentEndpoints;
1115
1102
  passwordHasher;
1116
1103
  constructor(options = {}) {
1117
1104
  this.defaultGuard = options.defaultGuard ?? "web";
@@ -1264,6 +1251,10 @@ var AuthManager = class {
1264
1251
  });
1265
1252
  this.setDefaultGuard(guardName);
1266
1253
  }
1254
+ /** Where a tools-only token is accepted besides a pipeline dispatch; `Application` passes its {@link Application.declareAgentEndpoint} paths. */
1255
+ setAgentEndpoints(endpoints) {
1256
+ this.agentEndpoints = endpoints;
1257
+ }
1267
1258
  /**
1268
1259
  * Register a bearer-token guard backed by an ApiTokenStore and enable
1269
1260
  * header-based guard selection: requests carrying `Authorization: Bearer`
@@ -1279,7 +1270,8 @@ var AuthManager = class {
1279
1270
  store,
1280
1271
  ctx,
1281
1272
  provider: options.provider ? manager.getProvider(options.provider) : void 0,
1282
- updateLastUsed: options.updateLastUsed
1273
+ updateLastUsed: options.updateLastUsed,
1274
+ agentEndpoints: this.agentEndpoints
1283
1275
  });
1284
1276
  });
1285
1277
  this.tokenGuard = guardName;
@@ -2097,4 +2089,4 @@ function requireVerifiedEmail(options = {}) {
2097
2089
  };
2098
2090
  }
2099
2091
  //#endregion
2100
- export { verifyOAuthState as A, ModelUserProvider as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, normalizeRedirectTarget as F, installAgentPrincipal as G, NodeHasher as H, AuthManager as I, createSessionMiddleware as J, readAgentPrincipal as K, DEFAULT_PROVIDER as L, jsonResponse as M, hostMatchesAllowlist as N, parseOAuthRedirectUrl as O, isAppRelativePath as P, TokenGuard as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, ScryptHasher as U, DefaultHasher as V, BaseUserProvider as W, getSessionFromContext as X, defaultCookieSecure as Y, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, buildOAuthRedirectUrl as b, verifyEmailToken as c, completePasswordReset as d, createPasswordResetToken as f, MemoryOAuthStateStore as g, AuthenticatableModel as h, createEmailVerificationToken as i, defineMiddleware as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, verifyPasswordResetToken as m, buildVerificationUrl as n, parseVerificationUrl as o, parsePasswordResetUrl as p, MemorySessionStore as q, completeEmailVerification as r, requireVerifiedEmail as s, MemoryEmailVerificationStore as t, buildPasswordResetUrl as u, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, SessionGuard as z };
2092
+ export { verifyOAuthState as A, ModelUserProvider as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, normalizeRedirectTarget as F, MemorySessionStore as G, NodeHasher as H, AuthManager as I, getSessionFromContext as J, createSessionMiddleware as K, DEFAULT_PROVIDER as L, jsonResponse as M, hostMatchesAllowlist as N, parseOAuthRedirectUrl as O, isAppRelativePath as P, TokenGuard as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, ScryptHasher as U, DefaultHasher as V, BaseUserProvider as W, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, buildOAuthRedirectUrl as b, verifyEmailToken as c, completePasswordReset as d, createPasswordResetToken as f, MemoryOAuthStateStore as g, AuthenticatableModel as h, createEmailVerificationToken as i, defineMiddleware as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, verifyPasswordResetToken as m, buildVerificationUrl as n, parseVerificationUrl as o, parsePasswordResetUrl as p, defaultCookieSecure as q, completeEmailVerification as r, requireVerifiedEmail as s, MemoryEmailVerificationStore as t, buildPasswordResetUrl as u, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, SessionGuard as z };
@@ -35,10 +35,11 @@ export declare class Gate {
35
35
  checkResponse(ability: string, user: AuthUser | null, ...args: unknown[]): Promise<AuthorizationResponse>;
36
36
  protected settle(user: AuthUser | null, ability: string, response: AuthorizationResponse, args: unknown[]): Promise<AuthorizationResponse>;
37
37
  /**
38
- * The subject may be a class instance (policy resolved via its constructor)
39
- * or a `[ModelClass, record]` / `['key', record]` tuple. ORM records are plain
40
- * objects with no constructor information, so they need the tuple: a plain
41
- * record reaching no policy and no gate throws in `checkResponse()`.
38
+ * The subject may be a class instance (policy resolved via its constructor),
39
+ * a `[ModelClass, record]` / `['key', record]` tuple, or the bare class or
40
+ * `[ModelClass]` for an ability with no record. ORM records are plain objects,
41
+ * so they need the tuple: a plain record or any other array reaching no policy
42
+ * and no gate throws in `checkResponse()`.
42
43
  */
43
44
  protected checkPolicy(ability: string, user: AuthUser | null, model: unknown, additionalArgs: unknown[]): Promise<boolean | AuthorizationResponse | undefined>;
44
45
  protected getPolicyInstance(policyClass: PolicyClass): Policy;