@guren/server 2.26.0 → 2.28.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 (69) hide show
  1. package/dist/{DocsViewerServiceProvider-CIRNHQ2I.js → DocsViewerServiceProvider-BMbcTYVw.js} +1 -1
  2. package/dist/{Gate-BL_zW82W.js → Gate-CYfoGQqh.js} +13 -2
  3. package/dist/{McpServiceProvider-B-LioPSz.js → McpServiceProvider-PGFPlYTy.js} +1 -1
  4. package/dist/{Resource-gki0_2B6.js → Resource-BhOua2OB.js} +26 -20
  5. package/dist/{ServiceProvider-DDW3MqQJ.js → ServiceProvider-G0YclITd.js} +60 -8
  6. package/dist/agent/dispatch.d.ts +4 -4
  7. package/dist/agent/public.js +1 -1
  8. package/dist/agent-request-Caj6bnbj.js +18 -0
  9. package/dist/auth/AuthManager.d.ts +4 -0
  10. package/dist/auth/email-verification.d.ts +2 -1
  11. package/dist/auth/index.js +1 -1
  12. package/dist/auth/password/describe-hasher.d.ts +11 -0
  13. package/dist/{auth-DiyWALZT.js → auth-DIugW0O-.js} +70 -4
  14. package/dist/authorization/Gate.d.ts +3 -2
  15. package/dist/authorization/index.js +2 -2
  16. package/dist/authorization/middleware.d.ts +8 -0
  17. package/dist/{authorization-E6X6Y-B6.js → authorization-CKOLYWvi.js} +17 -2
  18. package/dist/broadcasting/BroadcastManager.d.ts +23 -6
  19. package/dist/broadcasting/index.d.ts +1 -1
  20. package/dist/broadcasting/index.js +1 -1
  21. package/dist/broadcasting/types.d.ts +13 -1
  22. package/dist/{broadcasting-D0vMkKcq.js → broadcasting-N4cRV42s.js} +204 -33
  23. package/dist/cache/CacheManager.d.ts +5 -0
  24. package/dist/cache/TaggedCache.d.ts +2 -0
  25. package/dist/cache/index.js +1 -1
  26. package/dist/cache/pending-computations.d.ts +22 -0
  27. package/dist/cache/stores/FileStore.d.ts +1 -1
  28. package/dist/cache/stores/file-lock.d.ts +1 -0
  29. package/dist/{cache-DcnRufMe.js → cache-BlXopnH1.js} +179 -39
  30. package/dist/container/ServiceProvider.d.ts +27 -2
  31. package/dist/container/defineModule.d.ts +4 -5
  32. package/dist/container/definePlugin.d.ts +2 -0
  33. package/dist/dev-banner-bekDeLgL.js +51 -0
  34. package/dist/{dispatch-BAwzftws.js → dispatch-ENWpBxbE.js} +26 -4
  35. package/dist/driver-map-CkQc52j-.js +12 -0
  36. package/dist/host-port-t6wQFaRu.js +15 -0
  37. package/dist/hot-reload/testing.d.ts +2 -1
  38. package/dist/http/Application.d.ts +19 -1
  39. package/dist/http/dev-banner.d.ts +0 -8
  40. package/dist/http/host-port.d.ts +8 -0
  41. package/dist/http/middleware/force-https.d.ts +2 -1
  42. package/dist/http/middleware/index.d.ts +1 -0
  43. package/dist/http/middleware/session-manager.d.ts +5 -0
  44. package/dist/http/middleware/websocket-origin.d.ts +22 -0
  45. package/dist/http/public-assets.d.ts +6 -1
  46. package/dist/index.d.ts +5 -3
  47. package/dist/index.js +695 -235
  48. package/dist/internal/agent-request.d.ts +18 -0
  49. package/dist/internal/dispatched-request.d.ts +4 -0
  50. package/dist/internal/testing.js +2 -2
  51. package/dist/internal/zod-json-schema.js +1 -1
  52. package/dist/introspection/driver-map.d.ts +3 -0
  53. package/dist/introspection/flag.d.ts +12 -0
  54. package/dist/introspection/manifest.d.ts +17 -0
  55. package/dist/introspection/plain-json.d.ts +7 -0
  56. package/dist/introspection/types.d.ts +167 -0
  57. package/dist/mcp/index.js +1 -1
  58. package/dist/mvc/Controller.d.ts +3 -2
  59. package/dist/mvc/Router.d.ts +33 -0
  60. package/dist/providers/ConfigServiceProvider.d.ts +7 -0
  61. package/dist/queue/QueueManager.d.ts +3 -0
  62. package/dist/queue/index.js +1 -1
  63. package/dist/{queue-Bo4Q857L.js → queue-C8s3buYz.js} +5 -0
  64. package/dist/runtime/index.js +15 -2
  65. package/dist/storage/StorageManager.d.ts +5 -0
  66. package/dist/storage/index.js +1 -1
  67. package/dist/{storage-wFsUJHZW.js → storage-IlUesK2t.js} +13 -1
  68. package/dist/{vite-manifest-DlU94f3Z.js → vite-manifest-wPxfAzjW.js} +1 -57
  69. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import { n as ServiceProvider } from "./ServiceProvider-DDW3MqQJ.js";
1
+ import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
2
2
  import { n as createDocsViewerAccessGuard, r as isDocsViewerEnabled, t as DOCS_VIEWER_PATH } from "./endpoint-CTIzcagh.js";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash } from "node:crypto";
@@ -89,6 +89,15 @@ function toAuthorizationResponse(value) {
89
89
  if (isAuthorizationResponse(value)) return value;
90
90
  return value === true ? Response.allow() : Response.deny();
91
91
  }
92
+ /**
93
+ * An object literal or null-prototype object, the shape of an ORM record. A class
94
+ * instance or a tuple is not one, so an unresolved one still denies.
95
+ */
96
+ function isPlainRecord(value) {
97
+ if (typeof value !== "object" || value === null) return false;
98
+ const prototype = Object.getPrototypeOf(value);
99
+ return prototype === Object.prototype || prototype === null;
100
+ }
92
101
  /** Honours `denyWithStatus()` / `denyAsNotFound()` so a policy can hide a record as a 404. */
93
102
  function denialToException(response) {
94
103
  const message = response.message ?? "This action is unauthorized.";
@@ -180,6 +189,7 @@ var Gate = class {
180
189
  const result = await gate.callback(user, ...args);
181
190
  return this.settle(user, ability, toAuthorizationResponse(result), args);
182
191
  }
192
+ 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}".`);
183
193
  return this.settle(user, ability, Response.deny(), args);
184
194
  }
185
195
  async settle(user, ability, response, args) {
@@ -188,8 +198,9 @@ var Gate = class {
188
198
  }
189
199
  /**
190
200
  * The subject may be a class instance (policy resolved via its constructor)
191
- * or a `[ModelClass, record]` / `['key', record]` tuple — the tuple form is
192
- * required for plain ORM records, which carry no constructor information.
201
+ * or a `[ModelClass, record]` / `['key', record]` tuple. ORM records are plain
202
+ * objects with no constructor information, so they need the tuple: a plain
203
+ * record reaching no policy and no gate throws in `checkResponse()`.
193
204
  */
194
205
  async checkPolicy(ability, user, model, additionalArgs) {
195
206
  let policyKey;
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { n as ServiceProvider } from "./ServiceProvider-DDW3MqQJ.js";
2
+ import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
3
3
  import { n as createMcpAccessGuard, r as isMcpEndpointEnabled, t as MCP_ENDPOINT_PATH } from "./endpoint-Coq0K_6I.js";
4
4
  //#region src/mcp/McpServiceProvider.ts
5
5
  var McpServiceProvider_exports = /* @__PURE__ */ __exportAll({
@@ -4,11 +4,11 @@ import { n as ValidationException } from "./errors-JpkcCjjn.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 { h as warnDeprecatedSetter, m as warnDeprecatedGetter } from "./default-application-DWwscxfW.js";
7
- import { n as ServiceProvider } from "./ServiceProvider-DDW3MqQJ.js";
7
+ import { n as ServiceProvider } from "./ServiceProvider-G0YclITd.js";
8
8
  import { r as getAuthContext } from "./context-af2n5abO.js";
9
9
  import { o as getApiTokenOrFail } from "./api-token-BbgDEd6j.js";
10
10
  import { a as resolveI18n } from "./i18n-DmMKcbqj.js";
11
- import { d as resolveGate, g as tryGetRequestContainer } from "./Gate-BL_zW82W.js";
11
+ import { d as resolveGate, g as tryGetRequestContainer } from "./Gate-CYfoGQqh.js";
12
12
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
13
13
  import { getCookie } from "hono/cookie";
14
14
  import { isAbsolute, resolve } from "node:path";
@@ -608,8 +608,14 @@ function definePlugin(definition) {
608
608
  return definition.boot?.(this.container, config);
609
609
  }
610
610
  }
611
- Object.defineProperty(ConfiguredPluginProvider, "name", { value: className });
612
- return ConfiguredPluginProvider;
611
+ const introspect = definition.introspect;
612
+ const Provider = introspect === void 0 ? ConfiguredPluginProvider : class extends ConfiguredPluginProvider {
613
+ introspect() {
614
+ return introspect(this.container, config);
615
+ }
616
+ };
617
+ Object.defineProperty(Provider, "name", { value: className });
618
+ return Provider;
613
619
  };
614
620
  }
615
621
  //#endregion
@@ -626,24 +632,23 @@ function defineModule(definition) {
626
632
  };
627
633
  }
628
634
  /**
629
- * Runs a module's route registrar, applying its `prefix` via `router.group()`.
630
- * Shared by `Application.mountRoutes()` and the CLI's route loader, so both see
631
- * the same route set. `router.group()`'s callback is synchronous (prefix
632
- * pushed, callback run, prefix popped), so route calls made after an `await`
633
- * inside an async prefixed registrar run with the prefix already popped.
635
+ * Runs a module's route registrar under its `prefix` and names the module on each route it added.
636
+ * Shared by `Application.mountRoutes()` and the CLI's route loader, so both see the same route set.
637
+ * `router.group()`'s callback is synchronous, so route calls made after an `await` inside an
638
+ * async prefixed registrar run with the prefix already popped (and still carry the module).
634
639
  */
635
640
  async function mountModuleRoutes(router, gurenModule) {
636
641
  const registrar = gurenModule.routes;
637
642
  if (!registrar) return;
638
- if (!gurenModule.prefix) {
639
- await registrar(router);
640
- return;
641
- }
642
- let pending = void 0;
643
- router.group(gurenModule.prefix, (grouped) => {
644
- pending = registrar(grouped);
645
- });
646
- await pending;
643
+ const start = router.routeCount;
644
+ if (gurenModule.prefix) {
645
+ let pending = void 0;
646
+ router.group(gurenModule.prefix, (grouped) => {
647
+ pending = registrar(grouped);
648
+ });
649
+ await pending;
650
+ } else await registrar(router);
651
+ router.assignModule(start, gurenModule.name);
647
652
  }
648
653
  //#endregion
649
654
  //#region src/http/middleware/detect-locale.ts
@@ -861,12 +866,13 @@ var Controller = class {
861
866
  * Authorize the current user (or guest) for an ability; throws
862
867
  * AuthorizationException (403) when denied. ORM records are plain objects
863
868
  * with no constructor information, so pass the model class alongside the
864
- * record: `await this.authorize('update', [Post, post])`.
869
+ * record: `await this.authorize('update', [Post, post])`. A bare record that
870
+ * resolves no policy and no gate throws an Error rather than denying.
865
871
  */
866
872
  async authorize(ability, ...args) {
867
873
  await this.#resolveGate().forUser(await this.gateUser()).authorize(ability, ...args);
868
874
  }
869
- /** Check an ability without throwing: `await this.can('update', [Post, post])`. */
875
+ /** Check an ability, answering a denial with `false` rather than a 403: `await this.can('update', [Post, post])`. */
870
876
  async can(ability, ...args) {
871
877
  return this.#resolveGate().forUser(await this.gateUser()).allows(ability, ...args);
872
878
  }
@@ -23,6 +23,12 @@ var ServiceProvider = class {
23
23
  function isBindingOwner(provider) {
24
24
  return typeof provider.ownedBindings === "function";
25
25
  }
26
+ function isManifestWarningSource(provider) {
27
+ return typeof provider.manifestWarnings === "function";
28
+ }
29
+ function describeError(error) {
30
+ return error instanceof Error ? error.message : String(error);
31
+ }
26
32
  /**
27
33
  * Provider manager for registering and booting providers.
28
34
  */
@@ -36,31 +42,77 @@ var ProviderManager = class {
36
42
  deferredActivations = /* @__PURE__ */ new Map();
37
43
  bindingOwners = [];
38
44
  allBooted = false;
45
+ /** Every provider in registration order, deferred ones included, with where it came from. */
46
+ origins = /* @__PURE__ */ new Map();
39
47
  constructor(container) {
40
48
  this.container = container;
41
49
  }
42
- register(providerOrClass) {
50
+ /** `origin` is internal: `Application` passes it for the manifest (RFC 0026). */
51
+ register(providerOrClass, origin = { source: "app.register" }) {
43
52
  if (this.allBooted) {
44
53
  const name = providerOrClass instanceof ServiceProvider ? providerOrClass.constructor.name : providerOrClass.name;
45
54
  throw new Error(`Cannot register provider "${name}" after bootAll() has been called. Register all providers before booting the application.`);
46
55
  }
47
56
  const provider = providerOrClass instanceof ServiceProvider ? providerOrClass : new providerOrClass(this.container);
48
57
  if (provider.isDeferred() && provider.provides().length === 0) throw new Error(`Deferred provider "${provider.constructor.name}" must declare at least one service in "provides", otherwise it can never be loaded.`);
58
+ if (this.origins.has(provider)) return this;
59
+ this.origins.set(provider, origin);
49
60
  if (provider.isDeferred()) for (const service of provider.provides()) this.deferredProviders.set(service, provider);
50
61
  else this.providers.push(provider);
51
62
  return this;
52
63
  }
53
- registerMany(providers) {
54
- for (const provider of providers) this.register(provider);
64
+ /** `origin` is internal, as on {@link register}. */
65
+ registerMany(providers, origin) {
66
+ for (const provider of providers) this.register(provider, origin);
55
67
  return this;
56
68
  }
57
69
  async registerAll() {
58
- for (const provider of this.providers) if (!this.registered.has(provider)) {
59
- await provider.register();
60
- this.assertOwnedBindingsKept(provider);
61
- this.registered.add(provider);
62
- if (isBindingOwner(provider)) this.bindingOwners.push(provider);
70
+ for (const provider of this.providers) if (!this.registered.has(provider)) await this.registerOne(provider, () => provider.register());
71
+ }
72
+ async registerOne(provider, run) {
73
+ await run();
74
+ this.assertOwnedBindingsKept(provider);
75
+ this.registered.add(provider);
76
+ if (isBindingOwner(provider)) this.bindingOwners.push(provider);
77
+ }
78
+ /**
79
+ * @internal `registerAll()` for introspection (RFC 0026 §2): `introspect()` where a
80
+ * provider has one, and a throw is recorded rather than stopping the rest.
81
+ * Deferred providers are reported `skipped`; they register only after boot.
82
+ */
83
+ async registerAllForIntrospection() {
84
+ const outcomes = /* @__PURE__ */ new Map();
85
+ for (const provider of this.providers) {
86
+ if (this.registered.has(provider)) {
87
+ outcomes.set(provider, { register: "ran" });
88
+ continue;
89
+ }
90
+ const hook = provider.introspect;
91
+ try {
92
+ await this.registerOne(provider, hook ? () => hook.call(provider) : () => provider.register());
93
+ outcomes.set(provider, { register: hook ? "introspect-hook" : "ran" });
94
+ } catch (error) {
95
+ outcomes.set(provider, {
96
+ register: "threw",
97
+ error: describeError(error)
98
+ });
99
+ }
63
100
  }
101
+ return [...this.origins].map(([provider, origin]) => ({
102
+ name: provider.constructor.name,
103
+ source: origin.source,
104
+ ...origin.module === void 0 ? {} : { module: origin.module },
105
+ deferred: provider.isDeferred(),
106
+ provides: [...provider.provides()],
107
+ ...outcomes.get(provider) ?? { register: "skipped" }
108
+ }));
109
+ }
110
+ /** @internal Findings registered providers hold for the manifest, each named after its provider. */
111
+ manifestWarnings() {
112
+ return this.providers.filter((provider) => this.registered.has(provider)).filter(isManifestWarningSource).flatMap((provider) => provider.manifestWarnings().map((warning) => ({
113
+ ...warning,
114
+ provider: provider.constructor.name
115
+ })));
64
116
  }
65
117
  assertOwnedBindingsKept(provider) {
66
118
  for (const owner of this.bindingOwners) for (const [key, { binding, source }] of owner.ownedBindings()) if (this.container.bindingOf(key) !== binding) throw new Error(`[guren] "${key}" is configured twice: ${source} and ${provider.constructor.name}.register(). Keep one.`);
@@ -28,10 +28,10 @@ export interface BuildToolRequestOptions {
28
28
  preflight?: boolean;
29
29
  /**
30
30
  * Which protocol surface the call arrived on, announced as
31
- * `X-Guren-Agent-Surface`; defaults to `'mcp'`. Informational and write-only
32
- * here — it borrows the audit trail's vocabulary ({@link AgentSurface}), but
33
- * the trail's own `surface` comes from the adapter. Nothing may authorize on
34
- * it: any client sets any header it likes.
31
+ * `X-Guren-Agent-Surface`; defaults to `'mcp'`. The audit trail's own `surface`
32
+ * comes from the adapter, not from here. The auth guards read its presence to
33
+ * refuse with JSON rather than a redirect; nothing may authorize on it, since
34
+ * any client sets any header it likes.
35
35
  */
36
36
  surface?: AgentSurface;
37
37
  }
@@ -1,2 +1,2 @@
1
- import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-BAwzftws.js";
1
+ import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, t as PREFLIGHT_ARGUMENT } from "../dispatch-ENWpBxbE.js";
2
2
  export { PREFLIGHT_ARGUMENT, advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse };
@@ -0,0 +1,18 @@
1
+ //#region src/internal/agent-request.ts
2
+ /**
3
+ * How a request says it is an agent tool call (RFC 0016 §3), in a leaf module
4
+ * so the dispatcher that writes the header and the auth middlewares that read
5
+ * it share one spelling. Not exported from the package index.
6
+ *
7
+ * Read only to choose the *shape* of a refusal: a tool caller cannot follow a
8
+ * redirect, so a guard answers it with JSON instead. Nothing may authorize on
9
+ * it, since any client can send it and gets no more than a JSON refusal.
10
+ */
11
+ /** Request header naming the protocol surface a tool call arrived on. */
12
+ const AGENT_SURFACE_HEADER = "X-Guren-Agent-Surface";
13
+ /** Whether the request was built by the agent dispatcher (`buildToolRequest`). */
14
+ function isAgentToolRequest(ctx) {
15
+ return ctx.req?.header(AGENT_SURFACE_HEADER) !== void 0;
16
+ }
17
+ //#endregion
18
+ export { isAgentToolRequest as n, AGENT_SURFACE_HEADER as t };
@@ -3,6 +3,7 @@ import type { Model, PlainObject } from '@guren/orm';
3
3
  import { type ModelUserProviderOptions } from './providers/ModelUserProvider.js';
4
4
  import { type ApiTokenStore } from './api-token.js';
5
5
  import type { PasswordHasher } from './password/PasswordHasher.js';
6
+ import type { AuthEntry } from '../introspection/types.js';
6
7
  import type { AttachContextOptions, AuthContext, AuthManagerContract, AuthManagerOptions, AuthCredentials, Guard, GuardContext, GuardFactory, ProviderFactory, UserProvider } from './types.js';
7
8
  /** The guard and provider names an app gets without naming either: `createApp()` registers them, `useModel()` fills them. */
8
9
  export declare const DEFAULT_GUARD = "web";
@@ -34,6 +35,7 @@ export declare class AuthManager implements AuthManagerContract {
34
35
  hasher(): PasswordHasher;
35
36
  registerGuard<User>(name: string, factory: GuardFactory<User>): void;
36
37
  registerProvider<User>(name: string, factory: ProviderFactory<User>): void;
38
+ private setProvider;
37
39
  /** The guard `useTokens()` registered, or null. On this class rather than the contract, like `getApiTokenOptions()`. */
38
40
  getTokenGuard(): string | null;
39
41
  /** Whether a provider factory is registered under `name`; `getProvider()` throws where this is false. */
@@ -98,5 +100,7 @@ export declare class AuthManager implements AuthManagerContract {
98
100
  * rather than `AuthManagerContract`, which describes what a *request* needs.
99
101
  */
100
102
  getApiTokenStore(): ApiTokenStore | undefined;
103
+ /** Guards and providers as registered, constructing no provider (RFC 0026 §1). */
104
+ describe(): AuthEntry;
101
105
  }
102
106
  export type { AuthCredentials } from './types.js';
@@ -1,3 +1,4 @@
1
+ import { type HeaderReader } from '../internal/agent-request.js';
1
2
  import { buildTokenUrl, parseTokenUrl } from './utils.js';
2
3
  /**
3
4
  * Email verification token data stored in the backing store. Only the opaque
@@ -108,4 +109,4 @@ export declare function requireVerifiedEmail(options?: {
108
109
  }): (ctx: {
109
110
  get: <T = unknown>(key: string) => T;
110
111
  redirect: (url: string) => Response;
111
- }, next: () => Promise<void>) => Promise<Response | undefined>;
112
+ } & HeaderReader, next: () => Promise<void>) => Promise<Response | undefined>;
@@ -1,3 +1,3 @@
1
- import { A as verifyOAuthState, B as NodeHasher, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, H as BaseUserProvider, I as TokenGuard, L as SessionGuard, O as parseOAuthRedirectUrl, P as AuthManager, R as ModelUserProvider, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as ScryptHasher, _ 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 } from "../auth-DiyWALZT.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-DIugW0O-.js";
2
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";
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 };
@@ -0,0 +1,11 @@
1
+ import type { PasswordHasher } from './PasswordHasher.js';
2
+ /** What introspection reports of a hasher (RFC 0026 §1): the format it writes, and whether writing needs `Bun.password`. */
3
+ export interface PasswordHasherDescription {
4
+ algorithm: 'scrypt' | 'argon2' | 'bcrypt' | null;
5
+ requiresBun: boolean | null;
6
+ }
7
+ /**
8
+ * Matched by exact constructor, so a subclass (which may override `hash()`) or an
9
+ * app's own `PasswordHasher` reads as unknown rather than as the class it extends.
10
+ */
11
+ export declare function describePasswordHasher(hasher: PasswordHasher): PasswordHasherDescription;
@@ -4,6 +4,7 @@ import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as Authenticati
4
4
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
5
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
6
  import { isExpired } from "./support/expiry.js";
7
+ import { n as isAgentToolRequest } from "./agent-request-Caj6bnbj.js";
7
8
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
8
9
  import { createHmac, timingSafeEqual } from "node:crypto";
9
10
  import { Model } from "@guren/orm";
@@ -1069,6 +1070,32 @@ var TokenGuard = class {
1069
1070
  }
1070
1071
  session() {}
1071
1072
  };
1073
+ //#endregion
1074
+ //#region src/auth/password/describe-hasher.ts
1075
+ /**
1076
+ * Matched by exact constructor, so a subclass (which may override `hash()`) or an
1077
+ * app's own `PasswordHasher` reads as unknown rather than as the class it extends.
1078
+ */
1079
+ function describePasswordHasher(hasher) {
1080
+ switch (hasher.constructor) {
1081
+ case DefaultHasher: return {
1082
+ algorithm: hasher.algorithm,
1083
+ requiresBun: hasher.algorithm === "argon2"
1084
+ };
1085
+ case NodeHasher: return {
1086
+ algorithm: "scrypt",
1087
+ requiresBun: false
1088
+ };
1089
+ case ScryptHasher: return {
1090
+ algorithm: hasher.algorithm === "bcrypt" ? "bcrypt" : "argon2",
1091
+ requiresBun: true
1092
+ };
1093
+ default: return {
1094
+ algorithm: null,
1095
+ requiresBun: null
1096
+ };
1097
+ }
1098
+ }
1072
1099
  const DEFAULT_PROVIDER = "users";
1073
1100
  /**
1074
1101
  * The guard name an unqualified lookup resolves to on a request the pipeline
@@ -1103,7 +1130,13 @@ var AuthManager = class {
1103
1130
  this.guards.set(name, { factory });
1104
1131
  }
1105
1132
  registerProvider(name, factory) {
1106
- this.providers.set(name, { factory });
1133
+ this.setProvider(name, factory);
1134
+ }
1135
+ setProvider(name, factory, description) {
1136
+ this.providers.set(name, {
1137
+ factory,
1138
+ ...description ? { description } : {}
1139
+ });
1107
1140
  }
1108
1141
  /** The guard `useTokens()` registered, or null. On this class rather than the contract, like `getApiTokenOptions()`. */
1109
1142
  getTokenGuard() {
@@ -1217,7 +1250,12 @@ var AuthManager = class {
1217
1250
  hasher
1218
1251
  };
1219
1252
  bindPasswordHasher(model, hasher);
1220
- this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
1253
+ this.setProvider(providerName, () => new ModelUserProvider(model, defaultOptions), {
1254
+ kind: "model",
1255
+ model: model.name,
1256
+ hasher: hasher.constructor.name,
1257
+ ...describePasswordHasher(hasher)
1258
+ });
1221
1259
  this.registerGuard(guardName, ({ session, manager }) => {
1222
1260
  return new SessionGuard({
1223
1261
  provider: manager.getProvider(providerName),
@@ -1268,6 +1306,23 @@ var AuthManager = class {
1268
1306
  getApiTokenStore() {
1269
1307
  return this.apiTokenStore ?? void 0;
1270
1308
  }
1309
+ /** Guards and providers as registered, constructing no provider (RFC 0026 §1). */
1310
+ describe() {
1311
+ const providers = {};
1312
+ for (const [name, entry] of this.providers) providers[name] = entry.description ? { ...entry.description } : {
1313
+ kind: "custom",
1314
+ hasher: null,
1315
+ algorithm: null,
1316
+ requiresBun: null
1317
+ };
1318
+ return {
1319
+ guards: this.guardNames(),
1320
+ defaultGuard: this.defaultGuard,
1321
+ hasher: this.passwordHasher.constructor.name,
1322
+ ...describePasswordHasher(this.passwordHasher),
1323
+ providers
1324
+ };
1325
+ }
1271
1326
  };
1272
1327
  //#endregion
1273
1328
  //#region src/support/redirect-target.ts
@@ -1297,6 +1352,17 @@ function hostMatchesAllowlist(target, allowedHosts) {
1297
1352
  return false;
1298
1353
  }
1299
1354
  //#endregion
1355
+ //#region src/http/middleware/index.ts
1356
+ function defineMiddleware(handler) {
1357
+ return handler;
1358
+ }
1359
+ function jsonResponse(data, status = 200) {
1360
+ return new Response(JSON.stringify(data), {
1361
+ status,
1362
+ headers: { "Content-Type": "application/json; charset=utf-8" }
1363
+ });
1364
+ }
1365
+ //#endregion
1300
1366
  //#region src/auth/oauth/index.ts
1301
1367
  /** Session key holding the per-browser bindings between authorize and callback. */
1302
1368
  const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
@@ -2026,9 +2092,9 @@ function requireVerifiedEmail(options = {}) {
2026
2092
  return async (ctx, next) => {
2027
2093
  if (!isEmailVerified(await (options.getUser ?? (async (c) => {
2028
2094
  return await getAuthContext(c)?.user() ?? null;
2029
- }))(ctx))) return ctx.redirect(redirectTo);
2095
+ }))(ctx))) return isAgentToolRequest(ctx) ? jsonResponse({ message: "Email address is not verified" }, 403) : ctx.redirect(redirectTo);
2030
2096
  await next();
2031
2097
  };
2032
2098
  }
2033
2099
  //#endregion
2034
- export { verifyOAuthState as A, NodeHasher as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, DEFAULT_PROVIDER as F, MemorySessionStore as G, BaseUserProvider as H, TokenGuard as I, getSessionFromContext as J, createSessionMiddleware as K, SessionGuard as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, ModelUserProvider as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, installAgentPrincipal as U, ScryptHasher as V, readAgentPrincipal 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, hostMatchesAllowlist 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, DefaultHasher as z };
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 };
@@ -36,8 +36,9 @@ export declare class Gate {
36
36
  protected settle(user: AuthUser | null, ability: string, response: AuthorizationResponse, args: unknown[]): Promise<AuthorizationResponse>;
37
37
  /**
38
38
  * The subject may be a class instance (policy resolved via its constructor)
39
- * or a `[ModelClass, record]` / `['key', record]` tuple — the tuple form is
40
- * required for plain ORM records, which carry no constructor information.
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()`.
41
42
  */
42
43
  protected checkPolicy(ability: string, user: AuthUser | null, model: unknown, additionalArgs: unknown[]): Promise<boolean | AuthorizationResponse | undefined>;
43
44
  protected getPolicyInstance(policyClass: PolicyClass): Policy;
@@ -1,3 +1,3 @@
1
- import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-E6X6Y-B6.js";
2
- import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-BL_zW82W.js";
1
+ import { a as withAuthorization, n as authorizeMiddleware, o as Policy, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware } from "../authorization-CKOLYWvi.js";
2
+ import { a as cannot, f as setGate, i as can, l as getGate, n as Response, o as createGate, r as authorize, s as defineGate, t as Gate, u as isAuthorizationResponse } from "../Gate-CYfoGQqh.js";
3
3
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };
@@ -2,6 +2,7 @@ import type { Context } from '../http/Application.js';
2
2
  import type { Middleware } from '../http/middleware/index.js';
3
3
  import type { AuthorizeOptions, AuthorizeResourceOptions } from './types.js';
4
4
  import { Gate } from './Gate.js';
5
+ import { type MiddlewareCapabilities } from '../http/middleware/capabilities.js';
5
6
  /**
6
7
  * Middleware to authorize an ability. An array argument is snapshotted at
7
8
  * creation, and a one-element array behaves exactly like the bare ability.
@@ -24,6 +25,13 @@ export declare function authorizeAllMiddleware(input: string[], modelResolver?:
24
25
  * contract (RFC 0007): not re-exported from the package root.
25
26
  */
26
27
  export declare function resourceAbilityForMethod(method: string): string | undefined;
28
+ /**
29
+ * The ability an authorization stamp checks when it says so unambiguously,
30
+ * else undefined, meaning undetermined. A resource check resolves through the
31
+ * verb map, so only with the route's method. The one rule for agent tools and
32
+ * the introspection manifest (RFC 0016 §4, RFC 0026 §3). Internal contract (RFC 0007).
33
+ */
34
+ export declare function derivableAbility(authorization: MiddlewareCapabilities['authorization'], method?: string): string | undefined;
27
35
  /**
28
36
  * Maps HTTP methods to policy abilities. A method outside the built-in mapping
29
37
  * (a custom verb via `router.on()`) is denied with a 403 rather than downgraded
@@ -1,4 +1,4 @@
1
- import { c as denialToException, d as resolveGate, g as tryGetRequestContainer, n as Response, p as AuthorizationException } from "./Gate-BL_zW82W.js";
1
+ import { c as denialToException, d as resolveGate, g as tryGetRequestContainer, n as Response, p as AuthorizationException } from "./Gate-CYfoGQqh.js";
2
2
  //#region src/http/middleware/capabilities.ts
3
3
  /**
4
4
  * Internal security-capability marker (RFC 0007): built-in middleware
@@ -168,6 +168,21 @@ function resourceAbilityForMethod(method) {
168
168
  return RESOURCE_ABILITY_BY_METHOD[method.toUpperCase()];
169
169
  }
170
170
  /**
171
+ * The ability an authorization stamp checks when it says so unambiguously,
172
+ * else undefined, meaning undetermined. A resource check resolves through the
173
+ * verb map, so only with the route's method. The one rule for agent tools and
174
+ * the introspection manifest (RFC 0016 §4, RFC 0026 §3). Internal contract (RFC 0007).
175
+ */
176
+ function derivableAbility(authorization, method) {
177
+ if (!authorization) return void 0;
178
+ if (authorization.resource) {
179
+ if (!authorization.resource.fromMethodMap || method === void 0) return void 0;
180
+ if (authorization.abilities.length > 0 || authorization.mode !== "all") return void 0;
181
+ return resourceAbilityForMethod(method);
182
+ }
183
+ return authorization.abilities.length === 1 && authorization.mode === "all" ? authorization.abilities[0] : void 0;
184
+ }
185
+ /**
171
186
  * Maps HTTP methods to policy abilities. A method outside the built-in mapping
172
187
  * (a custom verb via `router.on()`) is denied with a 403 rather than downgraded
173
188
  * to `view`: guessing would let a view-only user reach a mutating handler. Map
@@ -214,4 +229,4 @@ function withAuthorization(gate) {
214
229
  };
215
230
  }
216
231
  //#endregion
217
- export { withAuthorization as a, capabilitiesOf as c, resourceAbilityForMethod as i, mergeCapabilities as l, authorizeMiddleware as n, Policy as o, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, stampCapabilities as u };
232
+ export { withAuthorization as a, capabilitiesOf as c, derivableAbility as i, mergeCapabilities as l, authorizeMiddleware as n, Policy as o, authorizeResourceMiddleware as r, definePolicy as s, authorizeAllMiddleware as t, stampCapabilities as u };
@@ -1,4 +1,4 @@
1
- import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent } from './types.js';
1
+ import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent } from './types.js';
2
2
  import { Channel, PrivateChannel, PresenceChannel } from './channels/index.js';
3
3
  import type { Middleware } from '../http/middleware/index.js';
4
4
  /** Broadcast manager for real-time event broadcasting. */
@@ -30,9 +30,21 @@ export declare class BroadcastManager {
30
30
  id: string | number;
31
31
  info?: Record<string, unknown>;
32
32
  } | null>;
33
+ private filterAuthorizedChannels;
33
34
  protected findChannelRegistration(channelName: string): ChannelRegistration | undefined;
34
35
  protected matchPattern(pattern: string, channelName: string): boolean;
35
36
  sseMiddleware(options?: SSEMiddlewareOptions): Middleware;
37
+ /**
38
+ * A route that upgrades to a WebSocket carrying broadcast events, the socket
39
+ * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
40
+ * Frames are JSON. The server sends `{ event, data }`, first `connected` with
41
+ * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
42
+ * channel }`, answered by a `subscription` event, and anything else is ignored.
43
+ */
44
+ webSocketMiddleware(options?: WebSocketMiddlewareOptions): Middleware;
45
+ private handleWebSocketMessage;
46
+ /** The one answer `POST /broadcasting/auth` and a socket's `subscribe` both give. */
47
+ private authorizeAndAttach;
36
48
  authMiddleware(options?: AuthMiddlewareOptions): Middleware;
37
49
  subscribeClient(clientId: string, channel: string): boolean;
38
50
  /**
@@ -56,6 +68,11 @@ export declare class BroadcastManager {
56
68
  userId?: string | number;
57
69
  }): string;
58
70
  removeWebSocketClient(clientId: string): boolean;
71
+ /**
72
+ * Subscribes without authorizing, like `subscribeClient()`: for a channel the
73
+ * server chose. Put a channel the client named through `authorize()` first,
74
+ * as `webSocketMiddleware()` and `authMiddleware()` do.
75
+ */
59
76
  subscribeWebSocketClient(clientId: string, channel: string): boolean;
60
77
  unsubscribeWebSocketClient(clientId: string, channel: string): boolean;
61
78
  getWebSocketClient(clientId: string): WebSocketClient | undefined;
@@ -65,11 +82,11 @@ export declare class BroadcastManager {
65
82
  getClients(): SSEClient[];
66
83
  getChannelClients(channel: string): SSEClient[];
67
84
  /**
68
- * Close every SSE connection this manager holds. Each owns a ping timer that
69
- * is only cleared on stream cancel or request abort, and `Bun.serve().stop()`
70
- * waits for in-flight requests while an SSE response never finishes — so on a
71
- * hot reload the timers would go on pinging. `getClients()` is a snapshot: a
72
- * `close()` reaching another client would drop it from a live iteration.
85
+ * Close every SSE and WebSocket connection this manager holds. Each SSE stream
86
+ * owns a ping timer that is only cleared on stream cancel or request abort, and
87
+ * `Bun.serve().stop()` waits for in-flight requests while an SSE response never
88
+ * finishes — so on a hot reload the timers would go on pinging. Both lists are
89
+ * snapshots: a `close()` reaching another client would drop it mid-iteration.
73
90
  */
74
91
  disconnectAll(): void;
75
92
  protected generateClientId(prefix?: 'sse' | 'ws'): string;
@@ -1,4 +1,4 @@
1
- export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, } from './types.js';
1
+ export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, } from './types.js';
2
2
  export { BroadcastManager, setBroadcastManager, getBroadcastManager, createBroadcastManager, } from './BroadcastManager.js';
3
3
  export { createTypedBroadcaster, } from './typed.js';
4
4
  export type { TypedBroadcaster, TypedChannelHandle, TypedPrivateChannelHandle, TypedPresenceChannelHandle, } from './typed.js';
@@ -1,2 +1,2 @@
1
- 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-D0vMkKcq.js";
1
+ 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-N4cRV42s.js";
2
2
  export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };