@guren/server 2.23.2 → 2.24.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 (72) hide show
  1. package/dist/DailyFileChannel-CTTPA0EF.js +114 -0
  2. package/dist/{DocsViewerServiceProvider-DWnlXx_y.js → DocsViewerServiceProvider-CIRNHQ2I.js} +2 -2
  3. package/dist/{authorization-0mCGUFoI.js → Gate-Cn1E6JnO.js} +3 -217
  4. package/dist/{Job-BVvaY-7p.js → Job-BVRCYuVY.js} +4 -10
  5. package/dist/McpServiceProvider-B-LioPSz.js +43 -0
  6. package/dist/Resource-BJhY4aF8.js +1035 -0
  7. package/dist/{loopback-guard-DT9gHF0F.js → ServiceProvider-DDW3MqQJ.js} +10 -68
  8. package/dist/agent/audit-file.d.ts +3 -0
  9. package/dist/agent/audit-sink.d.ts +16 -0
  10. package/dist/agent/call-budget.d.ts +22 -0
  11. package/dist/agent/events.d.ts +6 -6
  12. package/dist/api-token-BbgDEd6j.js +298 -0
  13. package/dist/audit-file-DocumbCr.js +29 -0
  14. package/dist/auth/index.js +2 -1
  15. package/dist/auth/oauth/index.d.ts +7 -0
  16. package/dist/{auth-D_W1cJp3.js → auth-vFeem6uM.js} +14 -300
  17. package/dist/authorization/index.js +2 -1
  18. package/dist/authorization-BsMTG8P1.js +217 -0
  19. package/dist/broadcasting/index.js +1 -1
  20. package/dist/{broadcasting-DVfG2vgN.js → broadcasting-6o_CCfF0.js} +2 -1
  21. package/dist/config/define.d.ts +50 -0
  22. package/dist/config/env-reads.d.ts +12 -0
  23. package/dist/config/env.d.ts +122 -0
  24. package/dist/container/Container.d.ts +13 -2
  25. package/dist/container/ServiceProvider.d.ts +7 -0
  26. package/dist/container/bindings.d.ts +8 -0
  27. package/dist/{default-application-Chbrul_m.js → default-application-CMuAAsdf.js} +20 -31
  28. package/dist/deprecate-rL8jNpKX.js +31 -0
  29. package/dist/encryption/index.js +1 -1
  30. package/dist/{encryption-BRjZnshr.js → encryption-_GiNb0Ol.js} +2 -1
  31. package/dist/{endpoint-BXipU2Jj.js → endpoint-CTIzcagh.js} +1 -1
  32. package/dist/{endpoint-Dsw3Acvq.js → endpoint-Coq0K_6I.js} +1 -1
  33. package/dist/events/index.js +1 -1
  34. package/dist/{events-CaJKZ2qk.js → events-swsyfCzt.js} +1 -1
  35. package/dist/http/Application.d.ts +22 -0
  36. package/dist/http/vite-manifest.d.ts +5 -1
  37. package/dist/i18n/index.js +1 -1
  38. package/dist/i18n/injected-translations.d.ts +8 -0
  39. package/dist/i18n/loaders/JsonLoader.d.ts +3 -2
  40. package/dist/{i18n-DRo1g0AN.js → i18n-0bOJqFpX.js} +5 -3
  41. package/dist/index.d.ts +11 -0
  42. package/dist/index.js +526 -1075
  43. package/dist/inertia-defaults-BjrcT7za.js +30 -0
  44. package/dist/internal/request.d.ts +4 -3
  45. package/dist/internal/request.js +2 -1
  46. package/dist/internal/testing.d.ts +17 -0
  47. package/dist/internal/testing.js +6 -0
  48. package/dist/lambda/index.js +1 -1
  49. package/dist/logging/index.js +2 -1
  50. package/dist/{logging-CXotojgW.js → logging-DshkpIkj.js} +4 -113
  51. package/dist/loopback-guard-CG8xB4v0.js +68 -0
  52. package/dist/mail/index.js +1 -1
  53. package/dist/{mail-zMjQimaJ.js → mail-CQlxrjYp.js} +4 -2
  54. package/dist/mcp/McpServiceProvider.d.ts +21 -4
  55. package/dist/mcp/create-mcp-server.d.ts +6 -0
  56. package/dist/mcp/index.js +434 -1
  57. package/dist/mvc/Controller.d.ts +11 -1
  58. package/dist/mvc/Router.d.ts +6 -0
  59. package/dist/mvc/inertia/InertiaEngine.d.ts +2 -0
  60. package/dist/mvc/validated-input.d.ts +55 -0
  61. package/dist/notifications/index.js +1 -1
  62. package/dist/{notifications-BLid0Y6M.js → notifications-DmyJZGM2.js} +3 -2
  63. package/dist/providers/ConfigServiceProvider.d.ts +19 -0
  64. package/dist/queue/index.js +2 -2
  65. package/dist/{queue-IdJjqbyJ.js → queue-CdwHlFXE.js} +1 -1
  66. package/dist/resolve-optional-ax6gPWTp.js +9 -0
  67. package/dist/runtime/index.js +2 -1
  68. package/dist/support/redirect-target.d.ts +5 -1
  69. package/dist/validated-input-D84J8wcC.js +25 -0
  70. package/dist/{vite-manifest-2p0IRIcy.js → vite-manifest-DAqhhZZ9.js} +7 -32
  71. package/package.json +6 -2
  72. package/dist/McpServiceProvider-BvJRcDOm.js +0 -458
@@ -20,6 +20,9 @@ var ServiceProvider = class {
20
20
  return this.constructor.deferred;
21
21
  }
22
22
  };
23
+ function isBindingOwner(provider) {
24
+ return typeof provider.ownedBindings === "function";
25
+ }
23
26
  /**
24
27
  * Provider manager for registering and booting providers.
25
28
  */
@@ -31,6 +34,7 @@ var ProviderManager = class {
31
34
  deferredProviders = /* @__PURE__ */ new Map();
32
35
  /** Per service, the boot of an already-activated deferred provider, so a later loadDeferredProvider() awaits that boot */
33
36
  deferredActivations = /* @__PURE__ */ new Map();
37
+ bindingOwners = [];
34
38
  allBooted = false;
35
39
  constructor(container) {
36
40
  this.container = container;
@@ -53,9 +57,14 @@ var ProviderManager = class {
53
57
  async registerAll() {
54
58
  for (const provider of this.providers) if (!this.registered.has(provider)) {
55
59
  await provider.register();
60
+ this.assertOwnedBindingsKept(provider);
56
61
  this.registered.add(provider);
62
+ if (isBindingOwner(provider)) this.bindingOwners.push(provider);
57
63
  }
58
64
  }
65
+ assertOwnedBindingsKept(provider) {
66
+ 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.`);
67
+ }
59
68
  async bootAll() {
60
69
  for (const provider of this.providers) if (!this.booted.has(provider) && this.registered.has(provider)) {
61
70
  await provider.boot?.();
@@ -103,71 +112,4 @@ var ProviderManager = class {
103
112
  }
104
113
  };
105
114
  //#endregion
106
- //#region src/http/middleware/loopback-guard.ts
107
- const LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "[::1]"]);
108
- const LOOPBACK_IPV4 = /^127\.\d+\.\d+\.\d+$/;
109
- /**
110
- * Whether an `Origin` header value belongs to the developer's own machine.
111
- * Only a web page's request carries one; restricting it to loopback blocks
112
- * cross-site requests and DNS rebinding (an attacker's domain resolving to
113
- * 127.0.0.1 so the browser skips preflight). A *negative* filter only: any
114
- * non-browser client sets the header with one flag, so never use it to satisfy the peer check.
115
- */
116
- function isLoopbackOrigin(origin) {
117
- try {
118
- const { hostname } = new URL(origin);
119
- return LOOPBACK_HOSTNAMES.has(hostname) || LOOPBACK_IPV4.test(hostname);
120
- } catch {
121
- return false;
122
- }
123
- }
124
- /**
125
- * Whether a socket peer address belongs to this machine.
126
- *
127
- * Bun reports IPv4-mapped peers as `::ffff:127.0.0.1`, so unwrap that prefix
128
- * before matching.
129
- */
130
- function isLoopbackAddress(address) {
131
- const normalized = address.startsWith("::ffff:") ? address.slice(7) : address;
132
- return normalized === "::1" || LOOPBACK_IPV4.test(normalized);
133
- }
134
- /**
135
- * The peer address of the current request, when the runtime exposes one.
136
- * `Bun.serve` passes `{ server }` through Hono's env, wired by
137
- * `Application.listen()`; proxy headers are attacker-controlled and ignored.
138
- * `undefined` means "the runtime did not say", not "remote": no `server` in env
139
- * (Node, Vercel's `app.fetch(request)`, in-process tests), or `requestIP()` null (closed or non-TCP socket).
140
- */
141
- function clientAddress(ctx) {
142
- const env = ctx.env;
143
- if (typeof env?.server?.requestIP !== "function") return;
144
- return env.server.requestIP(ctx.req.raw)?.address;
145
- }
146
- /**
147
- * Whether the operator accepted serving these endpoints on a runtime that
148
- * cannot report the socket peer.
149
- *
150
- * Read per request, and written in the plain `process.env.X` form for the
151
- * same bundler reason as the endpoint gates (see `mcp/endpoint.ts`).
152
- */
153
- function allowsUnverifiedPeer() {
154
- return typeof process !== "undefined" && process.env.GUREN_ALLOW_UNVERIFIED_PEER === "1";
155
- }
156
- /**
157
- * Restricts an endpoint to the developer's own machine. `resource` names the
158
- * endpoint in the 403 body (e.g. "the MCP endpoint"). The two denials say
159
- * different things on purpose: a present non-loopback peer is a remote caller,
160
- * a peer the runtime never reported is a deployment the guard cannot vouch for.
161
- */
162
- function createLoopbackGuard(resource) {
163
- return async (ctx, next) => {
164
- const origin = ctx.req.header("origin");
165
- if (origin !== void 0 && !isLoopbackOrigin(origin)) return ctx.json({ message: `Forbidden: cross-origin request to ${resource}` }, 403);
166
- const address = clientAddress(ctx);
167
- if (address !== void 0 && !isLoopbackAddress(address)) return ctx.json({ message: `Forbidden: remote request to ${resource}` }, 403);
168
- if (address === void 0 && !allowsUnverifiedPeer()) return ctx.json({ message: `Forbidden: this runtime does not report the peer address, so ${resource} cannot confirm the request came from this machine. Serve the app with Application.listen() on Bun, or set GUREN_ALLOW_UNVERIFIED_PEER=1 to accept requests from anywhere the process is reachable.` }, 403);
169
- await next();
170
- };
171
- }
172
- //#endregion
173
- export { ProviderManager as n, ServiceProvider as r, createLoopbackGuard as t };
115
+ export { ServiceProvider as n, ProviderManager as t };
@@ -0,0 +1,3 @@
1
+ import type { AgentAuditRecord } from './audit.js';
2
+ /** Appends one record per line, in the shape {@link import('./audit').parseAuditRecord} reads back. */
3
+ export declare function createFileAuditSink(filePath: string, days: number | undefined): (record: AgentAuditRecord) => void;
@@ -0,0 +1,16 @@
1
+ import type { AgentAuditSink } from './audit-emitter.js';
2
+ /**
3
+ * `file` is a *base* path: the trail lands in `agent-audit-YYYY-MM-DD.log`
4
+ * beside it, rotated daily, `days` of them kept. A `sink` replaces the file.
5
+ */
6
+ export type AgentAuditConfig = {
7
+ file?: string;
8
+ days?: number;
9
+ } | {
10
+ sink: AgentAuditSink;
11
+ };
12
+ /**
13
+ * `{ file }` is built behind a dynamic `import()` so an application that
14
+ * configured its own `sink` never evaluates the filesystem module.
15
+ */
16
+ export declare function resolveAgentAuditSink(config: AgentAuditConfig): Promise<AgentAuditSink>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A sliding 60-second call budget: the per-caller meter a surface puts at the
3
+ * pipeline's one seam (RFC 0017 §4). It reads nothing of the call, so it is
4
+ * assignable to `AgentInterposition` and also callable for a check that
5
+ * never enters the pipeline, such as an approval status read.
6
+ */
7
+ import type { AgentInvocationDenial } from './pipeline.js';
8
+ export interface AgentCallBudgetOptions {
9
+ /** Calls admitted per sliding minute. A whole number of at least 1. */
10
+ callsPerMinute: number;
11
+ /** Milliseconds since the epoch. Defaults to `Date.now`. */
12
+ now?: () => number;
13
+ /** The denial's text, told to the caller that exhausted the budget. */
14
+ message: (callsPerMinute: number) => string;
15
+ }
16
+ /** Spends one call: a denial when the window is full, `undefined` when the call may proceed. */
17
+ export type AgentCallBudget = () => AgentInvocationDenial | undefined;
18
+ /**
19
+ * One meter per returned function: share the function to share the budget.
20
+ * Throws on a limit that is not a whole number of at least 1.
21
+ */
22
+ export declare function createAgentCallBudget(options: AgentCallBudgetOptions): AgentCallBudget;
@@ -21,13 +21,13 @@ export interface AgentPrincipal {
21
21
  abilities?: string[];
22
22
  }
23
23
  /**
24
- * The protocol surface an invocation arrived on: `'mcp'` the application's own
25
- * endpoint, `'dev-mcp'` the development one, `'cli'` a `guren tool:call`,
26
- * `'webmcp'` an in-browser session call, `'durable'` an agent the application
27
- * hosts itself (RFC 0017 §4). Every consumer enumerates these as a *total* map,
28
- * so adding one fails to compile rather than silently failing to parse.
24
+ * The protocol surface an invocation arrived on: `'mcp'` the app's endpoint, `'dev-mcp'`
25
+ * the development one, `'cli'` a `guren tool:call`, `'webmcp'` an in-browser session,
26
+ * `'durable'` an agent the app hosts (RFC 0017 §4), `'in-process'` `@guren/plugin-ai`
27
+ * (RFC 0029 §2.3). Every consumer enumerates these as a *total* map, so adding one
28
+ * fails to compile rather than silently failing to parse.
29
29
  */
30
- export type AgentSurface = 'mcp' | 'dev-mcp' | 'cli' | 'webmcp' | 'durable';
30
+ export type AgentSurface = 'mcp' | 'dev-mcp' | 'cli' | 'webmcp' | 'durable' | 'in-process';
31
31
  /**
32
32
  * Emitted when an agent tool invocation completed — successfully or not.
33
33
  * `status` carries the HTTP status the dispatch resolved to, so an error
@@ -0,0 +1,298 @@
1
+ import { a as setResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
2
+ import { isOptionalExpiryPast } from "./support/expiry.js";
3
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
+ //#region src/auth/utils.ts
5
+ function hashToken(token, algorithm = "sha256") {
6
+ return createHash(algorithm).update(token).digest("hex");
7
+ }
8
+ function generateToken(length = 32) {
9
+ return randomBytes(length).toString("hex");
10
+ }
11
+ /** Generate a random ID (16 bytes = 32 hex chars). */
12
+ function generateId() {
13
+ return randomBytes(16).toString("hex");
14
+ }
15
+ /**
16
+ * Timing-safe comparison of two hex strings. Non-hex or odd-length input is
17
+ * rejected rather than compared: `Buffer.from(x, 'hex')` stops at the first
18
+ * invalid pair, so 'zzzz' and 'yyyy' would both decode to nothing and compare
19
+ * equal. Use `secureStringCompare` for values that are not hex.
20
+ */
21
+ function secureCompare(a, b) {
22
+ if (a.length !== b.length) return false;
23
+ const bufA = Buffer.from(a, "hex");
24
+ const bufB = Buffer.from(b, "hex");
25
+ if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
26
+ return timingSafeEqual(bufA, bufB);
27
+ }
28
+ /** Timing-safe comparison for arbitrary strings — unlike secureCompare, not hex-only. */
29
+ function secureStringCompare(a, b) {
30
+ const bufA = Buffer.from(a, "utf8");
31
+ const bufB = Buffer.from(b, "utf8");
32
+ if (bufA.length !== bufB.length) return false;
33
+ return timingSafeEqual(bufA, bufB);
34
+ }
35
+ function buildTokenUrl(baseUrl, token, email) {
36
+ const url = new URL(baseUrl);
37
+ url.searchParams.set("token", token);
38
+ if (email) url.searchParams.set("email", email);
39
+ return url.toString();
40
+ }
41
+ function parseTokenUrl(url) {
42
+ try {
43
+ const parsed = new URL(url);
44
+ return {
45
+ token: parsed.searchParams.get("token"),
46
+ email: parsed.searchParams.get("email")
47
+ };
48
+ } catch {
49
+ return {
50
+ token: null,
51
+ email: null
52
+ };
53
+ }
54
+ }
55
+ //#endregion
56
+ //#region src/auth/api-token.ts
57
+ /**
58
+ * In-memory token store for testing.
59
+ * Do NOT use in production - tokens will be lost on restart.
60
+ */
61
+ var MemoryApiTokenStore = class {
62
+ tokens = /* @__PURE__ */ new Map();
63
+ byHash = /* @__PURE__ */ new Map();
64
+ async store(token) {
65
+ this.tokens.set(token.id, token);
66
+ this.byHash.set(token.hashedToken, token.id);
67
+ }
68
+ async findByHashedToken(hashedToken) {
69
+ const id = this.byHash.get(hashedToken);
70
+ if (!id) return null;
71
+ return this.tokens.get(id) ?? null;
72
+ }
73
+ async findByUserId(userId) {
74
+ const userIdStr = String(userId);
75
+ return Array.from(this.tokens.values()).filter((t) => String(t.userId) === userIdStr);
76
+ }
77
+ async delete(id) {
78
+ const token = this.tokens.get(id);
79
+ if (token) {
80
+ this.byHash.delete(token.hashedToken);
81
+ this.tokens.delete(id);
82
+ }
83
+ }
84
+ async deleteForUser(userId) {
85
+ const userIdStr = String(userId);
86
+ for (const [id, token] of this.tokens.entries()) if (String(token.userId) === userIdStr) {
87
+ this.byHash.delete(token.hashedToken);
88
+ this.tokens.delete(id);
89
+ }
90
+ }
91
+ async updateLastUsed(id, timestamp) {
92
+ const token = this.tokens.get(id);
93
+ if (token) token.lastUsedAt = timestamp;
94
+ }
95
+ clear() {
96
+ this.tokens.clear();
97
+ this.byHash.clear();
98
+ }
99
+ get size() {
100
+ return this.tokens.size;
101
+ }
102
+ };
103
+ /**
104
+ * Create a new API token.
105
+ */
106
+ async function createApiToken(store, options) {
107
+ const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
108
+ const id = generateId();
109
+ const plainToken = generateToken(tokenLength);
110
+ const hashedToken = hashToken(plainToken);
111
+ const now = /* @__PURE__ */ new Date();
112
+ const token = {
113
+ id,
114
+ name,
115
+ hashedToken,
116
+ userId,
117
+ abilities,
118
+ lastUsedAt: null,
119
+ expiresAt: expiresIn == null ? null : new Date(now.getTime() + expiresIn),
120
+ createdAt: now
121
+ };
122
+ await store.store(token);
123
+ return {
124
+ plainTextToken: `${id}|${plainToken}`,
125
+ token
126
+ };
127
+ }
128
+ /**
129
+ * Parse a plain text token into its components.
130
+ */
131
+ function parseApiToken(plainTextToken) {
132
+ const parts = plainTextToken.split("|");
133
+ if (parts.length !== 2) return null;
134
+ const [id, token] = parts;
135
+ if (!id || !token) return null;
136
+ return {
137
+ id,
138
+ token
139
+ };
140
+ }
141
+ /**
142
+ * Extract the bearer token from an Authorization header. The one parsing rule
143
+ * shared by `createBearerTokenMiddleware`, `TokenGuard` and `hasBearerHeader`.
144
+ * `\S` keeps the match linear — `\s+(.+)` backtracks quadratically when a
145
+ * trailing newline makes `$` unreachable, on a pre-authentication header — and
146
+ * makes an all-whitespace token "not a bearer request", so CSRF is not skipped.
147
+ */
148
+ function readBearerToken(header) {
149
+ if (!header) return null;
150
+ const match = header.match(/^Bearer\s+(\S.*)$/i);
151
+ return match ? match[1] : null;
152
+ }
153
+ /**
154
+ * The one answer to "is this request bearer-authenticated?", shared by
155
+ * `AuthManager.resolveGuardName` and the CSRF skip for cookie-less bearer
156
+ * requests, which must classify a request identically.
157
+ */
158
+ function hasBearerHeader(ctx) {
159
+ return readBearerToken(ctx.req.header("Authorization")) !== null;
160
+ }
161
+ /**
162
+ * Verify an API token and return the associated user ID.
163
+ */
164
+ async function verifyApiToken(plainTextToken, store, options = {}) {
165
+ const { updateLastUsed = true } = options;
166
+ const parsed = parseApiToken(plainTextToken);
167
+ if (!parsed) return null;
168
+ const hashedToken = hashToken(parsed.token);
169
+ const token = await store.findByHashedToken(hashedToken);
170
+ if (!token) return null;
171
+ if (token.id !== parsed.id) return null;
172
+ if (isOptionalExpiryPast(token.expiresAt)) return null;
173
+ if (!secureCompare(token.hashedToken, hashedToken)) return null;
174
+ if (updateLastUsed) await store.updateLastUsed(token.id, /* @__PURE__ */ new Date());
175
+ return {
176
+ token,
177
+ userId: token.userId,
178
+ abilities: token.abilities
179
+ };
180
+ }
181
+ /**
182
+ * Check if a token has a specific ability.
183
+ */
184
+ function tokenCan(token, ability) {
185
+ if (token.abilities.includes("*")) return true;
186
+ return token.abilities.includes(ability);
187
+ }
188
+ /**
189
+ * Check if a token has all specified abilities.
190
+ */
191
+ function tokenCanAll(token, abilities) {
192
+ if (token.abilities.includes("*")) return true;
193
+ return abilities.every((ability) => token.abilities.includes(ability));
194
+ }
195
+ /**
196
+ * Check if a token has any of the specified abilities.
197
+ */
198
+ function tokenCanAny(token, abilities) {
199
+ if (token.abilities.includes("*")) return true;
200
+ return abilities.some((ability) => token.abilities.includes(ability));
201
+ }
202
+ /**
203
+ * Revoke (delete) an API token.
204
+ */
205
+ async function revokeApiToken(id, store) {
206
+ await store.delete(id);
207
+ }
208
+ /**
209
+ * Revoke all API tokens for a user.
210
+ */
211
+ async function revokeAllApiTokens(userId, store) {
212
+ await store.deleteForUser(userId);
213
+ }
214
+ /**
215
+ * Get all API tokens for a user.
216
+ */
217
+ async function getUserApiTokens(userId, store) {
218
+ return store.findByUserId(userId);
219
+ }
220
+ /**
221
+ * Context key for storing the authenticated token.
222
+ */
223
+ const API_TOKEN_KEY = "guren:api-token";
224
+ /**
225
+ * Revoke the token a request presented, and clear it from the request context
226
+ * so `getApiToken()` / `getApiTokenOrFail()` cannot succeed after a logout on
227
+ * the same request. The slot is cleared whether or not a token still verified.
228
+ */
229
+ async function revokePresentedToken(ctx, tokenId, store) {
230
+ if (tokenId) await revokeApiToken(tokenId, store);
231
+ ctx.set(API_TOKEN_KEY, void 0);
232
+ }
233
+ /**
234
+ * Create middleware that authenticates requests using Bearer tokens.
235
+ * @example
236
+ * ```ts
237
+ * app.use('/api/*', createBearerTokenMiddleware({ store, abilities: ['posts:delete'] }))
238
+ * ```
239
+ */
240
+ function createBearerTokenMiddleware(options) {
241
+ const { store, loadUser, abilities, onUnauthorized, onForbidden, headerName = "Authorization", updateLastUsed = true } = options;
242
+ return async (ctx, next) => {
243
+ const authHeader = ctx.req.header(headerName);
244
+ if (!authHeader) {
245
+ if (onUnauthorized) return onUnauthorized(ctx);
246
+ return ctx.json({ error: "Authentication required" }, 401);
247
+ }
248
+ const plainTextToken = readBearerToken(authHeader);
249
+ if (!plainTextToken) {
250
+ if (onUnauthorized) return onUnauthorized(ctx);
251
+ return ctx.json({ error: "Invalid authorization format" }, 401);
252
+ }
253
+ const result = await verifyApiToken(plainTextToken, store, { updateLastUsed });
254
+ if (!result) {
255
+ if (onUnauthorized) return onUnauthorized(ctx);
256
+ return ctx.json({ error: "Invalid or expired token" }, 401);
257
+ }
258
+ if (abilities && abilities.length > 0) {
259
+ if (!tokenCanAll(result.token, abilities)) {
260
+ if (onForbidden) return onForbidden(ctx, abilities);
261
+ return ctx.json({
262
+ error: "Token lacks required abilities",
263
+ required: abilities
264
+ }, 403);
265
+ }
266
+ }
267
+ ctx.set(API_TOKEN_KEY, result);
268
+ if (loadUser) {
269
+ const user = await loadUser(result.userId);
270
+ ctx.set("guren:user", user);
271
+ setResolvedPrincipal(ctx, {
272
+ user,
273
+ id: result.userId,
274
+ revoke: () => revokePresentedToken(ctx, result.token.id, store)
275
+ });
276
+ if (!getAuthContext(ctx)) ctx.set(AUTH_CONTEXT_KEY, createPrincipalAuthContext(ctx));
277
+ }
278
+ return next();
279
+ };
280
+ }
281
+ /**
282
+ * Get the authenticated API token from the request context.
283
+ */
284
+ function getApiToken(ctx) {
285
+ return ctx.get(API_TOKEN_KEY);
286
+ }
287
+ /**
288
+ * Get the authenticated API token from the request context, or throw.
289
+ *
290
+ * @throws {AuthenticationException} When no token is present in the context.
291
+ */
292
+ function getApiTokenOrFail(ctx) {
293
+ const result = getApiToken(ctx);
294
+ if (!result) throw new AuthenticationException("Unauthenticated.");
295
+ return result;
296
+ }
297
+ //#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 };
@@ -0,0 +1,29 @@
1
+ import { t as DailyFileChannel } from "./DailyFileChannel-CTTPA0EF.js";
2
+ //#region src/agent/audit-file.ts
3
+ /**
4
+ * The file half of the agent audit sink: JSONL appended through
5
+ * `DailyFileChannel`, which already owns rotation, the `days` retention sweep,
6
+ * directory creation and the line format — a second appender would be a second
7
+ * rotation rule. Reached only through the dynamic `import()` in `./audit-sink`,
8
+ * so an application with its own sink never constructs the filesystem channel.
9
+ */
10
+ /** Appends one record per line, in the shape {@link import('./audit').parseAuditRecord} reads back. */
11
+ function createFileAuditSink(filePath, days) {
12
+ const channel = new DailyFileChannel({
13
+ driver: "daily",
14
+ path: filePath,
15
+ format: "json",
16
+ level: "debug",
17
+ days
18
+ });
19
+ return (record) => {
20
+ channel.log({
21
+ level: "info",
22
+ message: "agent.audit",
23
+ timestamp: new Date(record.ts),
24
+ context: { ...record }
25
+ });
26
+ };
27
+ }
28
+ //#endregion
29
+ export { createFileAuditSink };
@@ -1,2 +1,3 @@
1
- import { $ as SessionGuard, A as verifyOAuthState, B as createBearerTokenMiddleware, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, G as parseApiToken, H as getApiTokenOrFail, I as TokenGuard, J as revokeApiToken, K as readBearerToken, L as API_TOKEN_KEY, O as parseOAuthRedirectUrl, P as AuthManager, Q as verifyApiToken, R as MemoryApiTokenStore, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as getUserApiTokens, V as getApiToken, X as tokenCanAll, Y as tokenCan, Z as tokenCanAny, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, dt as BaseUserProvider, et as buildTokenUrl, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as parseTokenUrl, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as NodeHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as generateToken, o as parseVerificationUrl, ot as secureStringCompare, p as parsePasswordResetUrl, q as revokeAllApiTokens, r as completeEmailVerification, rt as hashToken, s as requireVerifiedEmail, st as ModelUserProvider, t as MemoryEmailVerificationStore, tt as generateId, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createApiToken } from "../auth-D_W1cJp3.js";
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-vFeem6uM.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";
2
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 };
@@ -80,6 +80,12 @@ export interface OAuthStateStore {
80
80
  * callbacks with the same state both pass verification.
81
81
  */
82
82
  consume?(stateHash: string): Promise<OAuthStatePayload | null>;
83
+ /**
84
+ * Sweep every state whose expiration has passed. Optional: a store that
85
+ * expires its own entries (Redis keys, the in-memory map) implements
86
+ * nothing here and `pruneExpiredStates()` skips it.
87
+ */
88
+ deleteExpired?(now: Date): Promise<void>;
83
89
  }
84
90
  export interface OAuthStateConfig {
85
91
  expiresIn?: number;
@@ -170,6 +176,7 @@ export declare class OAuthManager {
170
176
  constructor(options?: OAuthManagerOptions);
171
177
  registerProvider(name: string, config: OAuthProviderConfig): void;
172
178
  providerNames(): string[];
179
+ pruneExpiredStates(now?: Date): Promise<void>;
173
180
  getProvider(name: string): OAuthProviderConfig;
174
181
  authorize(providerName: string, options?: OAuthAuthorizeOptions): Promise<{
175
182
  url: string;