@capybara-hq/kernel 0.1.0-rc.31 → 0.1.0-rc.32

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.
@@ -3,7 +3,7 @@ import FindMyWay from "find-my-way";
3
3
  import { ApiError, ERROR_CODES, errorBody } from "../errors.js";
4
4
  import { ACCESS_COOKIE, REFRESH_COOKIE } from "../identity/cookies.js";
5
5
  import { codeForStatus, redactPath } from "./error.filter.js";
6
- /** 插件路由都在此前缀下(ctx.http.route 已加 `/plugins/<name>` 前缀)。 */
6
+ /** Every extension route lives under this prefix (`ctx.http.route` adds `/plugins/<name>`). */
7
7
  export const PLUGIN_PREFIX = "/plugins/";
8
8
  /** 固定的路由列表(测试与只挂一次的调用方):版本不变、没有不可用的插件。 */
9
9
  export function staticRouteTable(routes) {
@@ -16,19 +16,28 @@ export function pluginOfPath(path) {
16
16
  const name = path.slice(PLUGIN_PREFIX.length).split("/", 1)[0];
17
17
  return name === undefined || name === "" ? undefined : name;
18
18
  }
19
- /** 用 find-my-way 建立插件路由表,路径语法与 Fastify 相同;路径不在 `/plugins/` 下时抛错。 */
19
+ /**
20
+ * Builds the extension route table with find-my-way (the same path syntax as Fastify); throws for
21
+ * a path outside `/plugins/`.
22
+ */
20
23
  export function createPluginRouter(routes) {
21
24
  const router = FindMyWay();
22
25
  for (const r of routes) {
23
26
  if (!r.path.startsWith(PLUGIN_PREFIX)) {
24
27
  throw new Error(`plugin route ${r.method} ${r.path} is outside ${PLUGIN_PREFIX}`);
25
28
  }
26
- router.on(r.method, r.path, () => { }, { handler: r.handler });
29
+ router.on(r.method, r.path, () => { }, { route: r });
27
30
  }
31
+ const lookup = (m, path) => {
32
+ const found = router.find(m, path);
33
+ const route = found?.store?.route;
34
+ return found && route
35
+ ? { route, params: { ...found.params } }
36
+ : undefined;
37
+ };
28
38
  return {
29
39
  find(method, path) {
30
- const lookup = (m) => router.find(m, path)?.store?.handler;
31
- return lookup(method) ?? (method === "HEAD" ? lookup("GET") : undefined);
40
+ return lookup(method, path) ?? (method === "HEAD" ? lookup("GET", path) : undefined);
32
41
  },
33
42
  };
34
43
  }
@@ -36,21 +45,34 @@ export function createPluginRouter(routes) {
36
45
  * Registers `/plugins/*` in its own encapsulated scope and hands each request to the extension handler
37
46
  * as a Web `Request`: the scope removes the default parsers and takes every content type as a raw
38
47
  * Buffer, so the body the extension gets is the bytes the client sent.
39
- * - The extension belongs to this deployment but is not in the registry (revoked and so on) -> 503
40
- * `extension.unavailable`; when an extension instance is revoked or replaced, the `req.signal` of
41
- * that extension's in-progress requests is aborted (`abortPlugin`, triggered by the route source's
42
- * `onChange`);
43
- * - not mounted or no match -> 404 `not_found`; HEAD without its own route is handled as GET, with no
44
- * body in the response.
45
- * - A `Request` that cannot be built (e.g. a malformed Host) -> 400 `validation_failed`, not logged as
46
- * an error.
48
+ * Before the body is read (the scope's `onRequest` hook), in this order:
49
+ * - the extension belongs to this deployment but is not in the registry (revoked and so on) -> 503
50
+ * `extension.unavailable` (its routes are gone, so their access is unknown);
51
+ * The gate reads the plugin segment decoded (the router decodes too); a malformed escape -> 400
52
+ * `validation_failed`;
53
+ * - not mounted or no match -> 404 `not_found`; HEAD without its own route uses the GET record
54
+ * (its access and params) and answers with no body; a `public` / `embed` record matching the
55
+ * org mount `/plugins/<plugin>/orgs[/...]` (decoded) counts as no match;
56
+ * - the matched record's access is resolved by `access` (authentication, authorization, effective
57
+ * config, the public write throttle, see plugin-route-access.ts): an `ApiError` answers its
58
+ * status and envelope, any other failure is logged and answers 500 `internal`. A refusal never
59
+ * reaches the handler. The match and the caller are kept per request (a WeakMap entry).
60
+ * Then the handler stage:
61
+ * - the handler gets `(webReq, caller)`; the Web request carries no kernel credential (`cap_at` /
62
+ * `cap_rt` cookies and an `Authorization` header with a `cap_pat_` / `cap_svc_` token are
63
+ * removed; an embed token stays);
64
+ * - when an extension instance is revoked or replaced, the `req.signal` of that extension's
65
+ * in-progress requests is aborted (`abortPlugin`, triggered by the route source's `onChange`);
66
+ * - a `Request` that cannot be built (e.g. a malformed Host) -> 400 `validation_failed`, not
67
+ * logged as an error;
47
68
  * - `req.signal` aborts only when the client disconnects before the response is written (not on
48
69
  * normal completion); long-lived handlers use it to unsubscribe;
49
70
  * - a throwing handler is logged (path redacted with `redactPath`) and returns 500 `internal` (the
50
71
  * error message is not echoed), except a `model.hook_denied` `ApiError` that escaped from
51
72
  * `ctx.models.embed` (an organization policy hook denied the call, spec B §5.4): a deliberate
52
73
  * outcome, not a failure, so it answers 403 `model.hook_denied` with a generic message (the
53
- * routes are unauthenticated: the policy extension's name and reason are not echoed).
74
+ * policy extension's name and reason are not echoed: the route's caller, possibly anonymous, is
75
+ * not the org admin who configured the policy).
54
76
  * - Fastify's own errors (a body over 1 MiB and so on) are mapped to the error envelope by the
55
77
  * scope's error handler: 4xx by the common error code table (413 `payload_too_large`, 415
56
78
  * `unsupported_media_type` and so on), 5xx are logged and return `internal`.
@@ -62,11 +84,11 @@ export function createPluginRouter(routes) {
62
84
  * .agents/skills/writing-extensions "Extension route matching semantics").
63
85
  * Must be called before Nest `app.init()`.
64
86
  */
65
- export async function registerPluginDispatch(fastify, getTable, log) {
66
- /** 进行中的请求 → 所属插件(停机时全部中止;插件实例变化时只中止该插件的)。 */
87
+ export async function registerPluginDispatch(fastify, getTable, log, access) {
88
+ /** In-progress request -> its extension (all aborted at shutdown; one extension's when it changes). */
67
89
  const inFlight = new Map();
68
90
  let stopping = false;
69
- // 按路由来源的版本缓存路由表(插件撤销 / 替换时版本变化才重建)
91
+ // the route table, cached per route source revision (rebuilt when an extension is revoked / replaced)
70
92
  let cached;
71
93
  const routerOf = (table) => {
72
94
  const revision = table.revision();
@@ -75,23 +97,53 @@ export async function registerPluginDispatch(fastify, getTable, log) {
75
97
  }
76
98
  return cached.router;
77
99
  };
78
- const handler = async (req, reply) => {
100
+ /** What `onRequest` established for a request the handler stage may serve. */
101
+ const resolved = new WeakMap();
102
+ const authorize = async (req, reply) => {
79
103
  const path = req.url.split("?")[0];
104
+ // the router matches decoded paths (`/plugins/%70/x` is `/plugins/p/x`), so the gate and the
105
+ // org-mount guard read them decoded too; a malformed escape matches nothing
106
+ const decoded = safeDecode(path);
107
+ const rawPlugin = pluginOfPath(path);
108
+ const plugin = rawPlugin === undefined ? undefined : safeDecode(rawPlugin);
109
+ if (decoded === undefined || (rawPlugin !== undefined && plugin === undefined)) {
110
+ return reply.code(400).send(errorBody("validation_failed", "Malformed request"));
111
+ }
80
112
  const table = getTable();
81
- const plugin = pluginOfPath(path);
82
113
  if (table && plugin !== undefined && (await table.unavailable(plugin))) {
83
114
  return reply
84
115
  .code(503)
85
116
  .send(errorBody("extension.unavailable", `Extension ${plugin} is not available right now`));
86
117
  }
87
- const pluginHandler = table ? routerOf(table).find(req.method, path) : undefined;
88
- if (!pluginHandler) {
118
+ const match = table ? routerOf(table).find(req.method, path) : undefined;
119
+ if (!match || catchesOrgMount(match.route, decoded)) {
89
120
  return reply.code(404).send(errorBody("not_found", `Route ${req.method} ${path} not found`));
90
121
  }
91
- // 只在响应写完之前连接就关了(客户端断开)时中止 `req.signal`:长连接(SSE)的 handler 据此退订、收尾。
92
- // 正常写完后的 close 不中止(writableFinished 为 true)。
122
+ let caller;
123
+ try {
124
+ caller = await access.resolve(match.route, req, reply, match.params);
125
+ }
126
+ catch (err) {
127
+ if (err instanceof ApiError) {
128
+ return reply.code(err.status).send(errorBody(err.code, err.message, err.details));
129
+ }
130
+ log.error("plugin route access failed", { method: req.method, path: redactPath(path), err });
131
+ return reply.code(500).send(errorBody("internal", "Internal error"));
132
+ }
133
+ resolved.set(req, { route: match.route, caller });
134
+ };
135
+ const handler = async (req, reply) => {
136
+ const path = req.url.split("?")[0];
137
+ const entry = resolved.get(req);
138
+ // onRequest answered every request it did not resolve; this is only a guard
139
+ if (!entry)
140
+ return reply.code(500).send(errorBody("internal", "Internal error"));
141
+ const { route, caller } = entry;
142
+ // Abort `req.signal` only when the connection closes before the response is written (the
143
+ // client disconnected): long-lived handlers (SSE) unsubscribe on it. A close after a finished
144
+ // response does not abort (writableFinished is true).
93
145
  const ac = new AbortController();
94
- inFlight.set(ac, plugin ?? "");
146
+ inFlight.set(ac, route.plugin);
95
147
  if (stopping)
96
148
  ac.abort();
97
149
  reply.raw.once("close", () => {
@@ -108,7 +160,7 @@ export async function registerPluginDispatch(fastify, getTable, log) {
108
160
  }
109
161
  let res;
110
162
  try {
111
- res = await pluginHandler(webReq);
163
+ res = await route.handler(webReq, caller);
112
164
  }
113
165
  catch (err) {
114
166
  if (err instanceof ApiError && err.code === "model.hook_denied") {
@@ -149,6 +201,8 @@ export async function registerPluginDispatch(fastify, getTable, log) {
149
201
  log.error("plugin request failed", { method: req.method, path: redactPath(req.url), err });
150
202
  return reply.code(status >= 500 ? status : 500).send(errorBody("internal", "Internal error"));
151
203
  });
204
+ // the gate, the match and the access check run before the body is read
205
+ scope.addHook("onRequest", authorize);
152
206
  scope.all(`${PLUGIN_PREFIX}*`, handler);
153
207
  });
154
208
  return {
@@ -164,10 +218,31 @@ export async function registerPluginDispatch(fastify, getTable, log) {
164
218
  },
165
219
  };
166
220
  }
221
+ /** `decodeURIComponent`, or undefined for a malformed escape. */
222
+ function safeDecode(s) {
223
+ try {
224
+ return decodeURIComponent(s);
225
+ }
226
+ catch {
227
+ return undefined;
228
+ }
229
+ }
230
+ /**
231
+ * Defence in depth: `/plugins/<plugin>/orgs[/...]` belongs to the org mount of `member` / `admin`
232
+ * routes (the SDK keeps every declared path out of `/orgs/`), so a `public` / `embed` record
233
+ * that matches it anyway (a `/*` or `/:a/:b/...` pattern) is treated as no match.
234
+ */
235
+ function catchesOrgMount(route, decodedPath) {
236
+ if (route.access === "member" || route.access === "admin")
237
+ return false;
238
+ const mount = `${PLUGIN_PREFIX}${route.plugin}/orgs`;
239
+ return decodedPath === mount || decodedPath.startsWith(`${mount}/`);
240
+ }
167
241
  const KERNEL_COOKIES = new Set([ACCESS_COOKIE, REFRESH_COOKIE]);
168
242
  /**
169
- * 从 Cookie 头里去掉内核会话 Cookie(`cap_at` / `cap_rt`):插件 handler 不经内核鉴权,
170
- * 拿到这两个 Cookie 就能冒充用户调内核 API。全部去掉后返回 undefined(不传 Cookie 头)。
243
+ * Removes the kernel session cookies (`cap_at` / `cap_rt`) from a Cookie header: with them an
244
+ * extension handler could call the kernel API as the user. Returns undefined when nothing is left
245
+ * (no Cookie header is passed on).
171
246
  */
172
247
  export function stripKernelCookies(cookie) {
173
248
  const kept = cookie
@@ -177,8 +252,22 @@ export function stripKernelCookies(cookie) {
177
252
  return kept.length > 0 ? kept.join("; ") : undefined;
178
253
  }
179
254
  /**
180
- * Fastify 请求 → Web `Request`:数组头用 `, ` 合并(`set-cookie` 逐条保留);GET / HEAD 不带 body;
181
- * Cookie 头去掉内核会话 Cookie;`signal` 在响应写完之前客户端断开时中止。
255
+ * A kernel API token anywhere in an Authorization value (`Bearer cap_pat_…`, a bare token, a quoted
256
+ * or comma / `=` separated one, ...): matched as a substring, never by its position.
257
+ */
258
+ const KERNEL_TOKEN_RE = /cap_(pat|svc)_/i;
259
+ /**
260
+ * An `Authorization` header value as the extension handler may see it: undefined (dropped) when it
261
+ * carries a kernel API token (`cap_pat_` / `cap_svc_`), which would let the extension call the
262
+ * kernel API as its owner; anything else (an embed token, a webhook signature) is kept.
263
+ */
264
+ export function stripKernelAuthorization(value) {
265
+ return KERNEL_TOKEN_RE.test(value) ? undefined : value;
266
+ }
267
+ /**
268
+ * Fastify request -> Web `Request`: array headers joined with `, ` (`set-cookie` kept one by one);
269
+ * no body for GET / HEAD; kernel credentials removed (session cookies, an Authorization header
270
+ * with a kernel token); `signal` aborts when the client disconnects before the response is written.
182
271
  */
183
272
  function toWebRequest(req, signal) {
184
273
  const headers = new Headers();
@@ -191,6 +280,12 @@ function toWebRequest(req, signal) {
191
280
  headers.set(name, kept);
192
281
  continue;
193
282
  }
283
+ if (name === "authorization") {
284
+ const kept = stripKernelAuthorization(Array.isArray(value) ? value.join(", ") : value);
285
+ if (kept !== undefined)
286
+ headers.set(name, kept);
287
+ continue;
288
+ }
194
289
  if (Array.isArray(value)) {
195
290
  if (name === "set-cookie")
196
291
  for (const v of value)
@@ -0,0 +1,56 @@
1
+ import type { RouteCaller } from "@capybara-hq/plugin-sdk";
2
+ import { type ThrottlerStorage } from "@nestjs/throttler";
3
+ import type { FastifyReply, FastifyRequest } from "fastify";
4
+ import { type Route } from "../ctx/create-ctx.js";
5
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
+ import { EffectiveConfigs } from "../extensions/effective-config.js";
7
+ import { AccountsService } from "../identity/accounts.js";
8
+ import { ApiTokenService } from "../identity/api-tokens.js";
9
+ import { KernelDb } from "../infra/database/kernel-db.js";
10
+ import { type OrgRole } from "../orgs/roles.js";
11
+ import type { RouteAccessResolver } from "./plugin-dispatch.js";
12
+ /** Optional provider: the public write limit instead of the `plugin-public-write` throttler's (tests). */
13
+ export declare const PLUGIN_PUBLIC_WRITE_LIMIT: unique symbol;
14
+ /**
15
+ * The org role of a person for an extension `member` / `admin` route, in one query (the same as
16
+ * an embed token's live check): the extension enabled in the org, the org not deleted, the account
17
+ * active and a member. Undefined when any of that fails.
18
+ */
19
+ export declare function orgRouteMember(db: KernelSchemaDb, plugin: string, orgId: string, accountId: string): Promise<OrgRole | undefined>;
20
+ /**
21
+ * The kernel's access check for extension routes (spec 2026-11-15-extension-route-auth):
22
+ * - `public`: anyone; POST / PUT / DELETE count against `plugin-public-write` per extension and
23
+ * client IP (Redis, fail-open like every plain per-route limit), over it 429 `rate_limited`
24
+ * with `retry-after`.
25
+ * - `embed`: an embed token of this extension as `Authorization: Bearer` (not a `cap_` kernel
26
+ * token) or `?token=`, verified by the route's own `verifyEmbed` (signature, TTL, scope, live
27
+ * membership, slot role, extension enabled); missing or invalid -> 401 `auth.required`. An org
28
+ * token also needs a valid effective config (409 `extension.needs_config`; 503
29
+ * `extension.unavailable` when the extension is not running on this replica).
30
+ * - `member` / `admin`: a personal API token only (`authenticatePersonalToken`; a cookie is no
31
+ * credential); not a member, the extension off, or the org gone -> 404 `org.not_found`; a role
32
+ * below `member` / `admin` -> 403 `forbidden`; an invalid effective config -> 409 (503 when the
33
+ * extension is not running on this replica).
34
+ * Everything is read live (PG / Redis) per request; nothing is kept in the process.
35
+ */
36
+ export declare class PluginRouteAccess implements RouteAccessResolver {
37
+ private readonly kdb;
38
+ private readonly accounts;
39
+ private readonly tokens;
40
+ private readonly effective;
41
+ private readonly throttle;
42
+ private readonly publicWriteLimit;
43
+ constructor(kdb: KernelDb, accounts: AccountsService, tokens: ApiTokenService, effective: Pick<EffectiveConfigs, "get">, throttle: ThrottlerStorage, publicWriteLimit?: number);
44
+ resolve(route: Route, req: FastifyRequest, reply: FastifyReply, params: Record<string, string>): Promise<RouteCaller>;
45
+ private throttlePublicWrite;
46
+ private embed;
47
+ private member;
48
+ /**
49
+ * The extension's effective config for the org; 503 `extension.unavailable` when the extension
50
+ * is not running on this replica (not a configuration problem), else 409 `extension.needs_config`.
51
+ */
52
+ private config;
53
+ }
54
+ /** The one {@link PluginRouteAccess}: the HTTP side resolves it lazily for the plugin dispatch. */
55
+ export declare class PluginRouteAccessModule {
56
+ }
@@ -0,0 +1,192 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
11
+ import { getStorageToken } from "@nestjs/throttler";
12
+ import { currentOrgRole } from "../ctx/create-ctx.js";
13
+ import { ApiError } from "../errors.js";
14
+ import { EffectiveConfigs, NEEDS_CONFIG_REASON } from "../extensions/effective-config.js";
15
+ import { ExtensionStateModule } from "../extensions/state.module.js";
16
+ import { AccountsService } from "../identity/accounts.js";
17
+ import { ApiTokenService } from "../identity/api-tokens.js";
18
+ import { authenticatePersonalToken } from "../identity/auth.guard.js";
19
+ import { IdentityModule } from "../identity/identity.module.js";
20
+ import { KernelDb } from "../infra/database/kernel-db.js";
21
+ import { NAMED_THROTTLERS, throttlerKey } from "../infra/throttler/named-throttlers.js";
22
+ import { roleAtLeast } from "../orgs/roles.js";
23
+ /** Optional provider: the public write limit instead of the `plugin-public-write` throttler's (tests). */
24
+ export const PLUGIN_PUBLIC_WRITE_LIMIT = Symbol("PLUGIN_PUBLIC_WRITE_LIMIT");
25
+ /** The named throttler of unsafe methods on `public` extension routes (per extension and client IP). */
26
+ const PUBLIC_WRITE = (() => {
27
+ const t = NAMED_THROTTLERS.find((x) => x.name === "plugin-public-write");
28
+ if (!t)
29
+ throw new Error('named throttler "plugin-public-write" is missing');
30
+ return t;
31
+ })();
32
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
33
+ const BEARER_RE = /^Bearer\s+(\S+)$/i;
34
+ /**
35
+ * The org role of a person for an extension `member` / `admin` route, in one query (the same as
36
+ * an embed token's live check): the extension enabled in the org, the org not deleted, the account
37
+ * active and a member. Undefined when any of that fails.
38
+ */
39
+ export function orgRouteMember(db, plugin, orgId, accountId) {
40
+ return currentOrgRole(db, plugin, orgId, accountId);
41
+ }
42
+ const authRequired = () => new ApiError("auth.required", "Authentication required");
43
+ /**
44
+ * The kernel's access check for extension routes (spec 2026-11-15-extension-route-auth):
45
+ * - `public`: anyone; POST / PUT / DELETE count against `plugin-public-write` per extension and
46
+ * client IP (Redis, fail-open like every plain per-route limit), over it 429 `rate_limited`
47
+ * with `retry-after`.
48
+ * - `embed`: an embed token of this extension as `Authorization: Bearer` (not a `cap_` kernel
49
+ * token) or `?token=`, verified by the route's own `verifyEmbed` (signature, TTL, scope, live
50
+ * membership, slot role, extension enabled); missing or invalid -> 401 `auth.required`. An org
51
+ * token also needs a valid effective config (409 `extension.needs_config`; 503
52
+ * `extension.unavailable` when the extension is not running on this replica).
53
+ * - `member` / `admin`: a personal API token only (`authenticatePersonalToken`; a cookie is no
54
+ * credential); not a member, the extension off, or the org gone -> 404 `org.not_found`; a role
55
+ * below `member` / `admin` -> 403 `forbidden`; an invalid effective config -> 409 (503 when the
56
+ * extension is not running on this replica).
57
+ * Everything is read live (PG / Redis) per request; nothing is kept in the process.
58
+ */
59
+ let PluginRouteAccess = class PluginRouteAccess {
60
+ kdb;
61
+ accounts;
62
+ tokens;
63
+ effective;
64
+ throttle;
65
+ publicWriteLimit;
66
+ constructor(kdb, accounts, tokens, effective, throttle, publicWriteLimit = PUBLIC_WRITE.limit) {
67
+ this.kdb = kdb;
68
+ this.accounts = accounts;
69
+ this.tokens = tokens;
70
+ this.effective = effective;
71
+ this.throttle = throttle;
72
+ this.publicWriteLimit = publicWriteLimit;
73
+ }
74
+ async resolve(route, req, reply, params) {
75
+ switch (route.access) {
76
+ case "public":
77
+ await this.throttlePublicWrite(route, req, reply);
78
+ return { access: "public" };
79
+ case "embed":
80
+ return this.embed(route, req);
81
+ case "member":
82
+ case "admin":
83
+ return this.member(route, req, params);
84
+ }
85
+ }
86
+ async throttlePublicWrite(route, req, reply) {
87
+ if (SAFE_METHODS.has(req.method.toUpperCase()))
88
+ return;
89
+ const tracker = `${route.plugin}:${req.ip}`;
90
+ const r = await this.throttle.increment(throttlerKey(PUBLIC_WRITE.name, tracker), PUBLIC_WRITE.ttl, this.publicWriteLimit, 0, PUBLIC_WRITE.name);
91
+ if (!r.isBlocked)
92
+ return;
93
+ reply.header("retry-after", String(r.timeToBlockExpire));
94
+ throw new ApiError(PUBLIC_WRITE.code ?? "rate_limited", PUBLIC_WRITE.message);
95
+ }
96
+ async embed(route, req) {
97
+ const token = embedToken(req);
98
+ if (token === undefined)
99
+ throw authRequired();
100
+ const claims = await route.verifyEmbed(token);
101
+ if (claims === null)
102
+ throw authRequired();
103
+ if (claims.scope === "platform") {
104
+ return {
105
+ access: "embed",
106
+ scope: "platform",
107
+ accountId: claims.accountId,
108
+ role: "superAdmin",
109
+ contribution: claims.contribution,
110
+ exp: claims.exp,
111
+ };
112
+ }
113
+ const config = await this.config(claims.orgId, route.plugin);
114
+ return {
115
+ access: "embed",
116
+ scope: "org",
117
+ orgId: claims.orgId,
118
+ accountId: claims.accountId,
119
+ role: claims.role,
120
+ contribution: claims.contribution,
121
+ ...(claims.conversationId !== undefined && { conversationId: claims.conversationId }),
122
+ exp: claims.exp,
123
+ config,
124
+ };
125
+ }
126
+ async member(route, req, params) {
127
+ const account = await authenticatePersonalToken(req, {
128
+ accounts: this.accounts,
129
+ tokens: this.tokens,
130
+ });
131
+ const orgId = params.orgId ?? "";
132
+ const role = orgId === "" ? undefined : await orgRouteMember(this.kdb.db, route.plugin, orgId, account.id);
133
+ if (role === undefined)
134
+ throw new ApiError("org.not_found", "Organization not found");
135
+ const min = route.access === "admin" ? "admin" : "member";
136
+ if (!roleAtLeast(role, min)) {
137
+ throw new ApiError("forbidden", "Insufficient organization role");
138
+ }
139
+ const config = await this.config(orgId, route.plugin);
140
+ return {
141
+ access: route.access === "admin" ? "admin" : "member",
142
+ orgId,
143
+ accountId: account.id,
144
+ role,
145
+ config,
146
+ };
147
+ }
148
+ /**
149
+ * The extension's effective config for the org; 503 `extension.unavailable` when the extension
150
+ * is not running on this replica (not a configuration problem), else 409 `extension.needs_config`.
151
+ */
152
+ async config(orgId, plugin) {
153
+ const effective = await this.effective.get(orgId, plugin);
154
+ if (!effective.ok) {
155
+ if (effective.notRunning) {
156
+ throw new ApiError("extension.unavailable", `Extension ${plugin} is not available right now`);
157
+ }
158
+ throw new ApiError("extension.needs_config", `Extension ${plugin} ${NEEDS_CONFIG_REASON}`);
159
+ }
160
+ return effective.config;
161
+ }
162
+ };
163
+ PluginRouteAccess = __decorate([
164
+ Injectable(),
165
+ __param(0, Inject(KernelDb)),
166
+ __param(1, Inject(AccountsService)),
167
+ __param(2, Inject(ApiTokenService)),
168
+ __param(3, Inject(EffectiveConfigs)),
169
+ __param(4, Inject(getStorageToken())),
170
+ __param(5, Optional()),
171
+ __param(5, Inject(PLUGIN_PUBLIC_WRITE_LIMIT))
172
+ ], PluginRouteAccess);
173
+ export { PluginRouteAccess };
174
+ /** The embed token of a request: `Authorization: Bearer` unless it is a kernel token, else `?token=`. */
175
+ function embedToken(req) {
176
+ const bearer = BEARER_RE.exec(req.headers.authorization ?? "")?.[1];
177
+ if (bearer !== undefined && !bearer.startsWith("cap_"))
178
+ return bearer;
179
+ const q = req.query?.token;
180
+ return typeof q === "string" && q !== "" ? q : undefined;
181
+ }
182
+ /** The one {@link PluginRouteAccess}: the HTTP side resolves it lazily for the plugin dispatch. */
183
+ let PluginRouteAccessModule = class PluginRouteAccessModule {
184
+ };
185
+ PluginRouteAccessModule = __decorate([
186
+ Module({
187
+ imports: [IdentityModule, ExtensionStateModule],
188
+ providers: [PluginRouteAccess],
189
+ exports: [PluginRouteAccess],
190
+ })
191
+ ], PluginRouteAccessModule);
192
+ export { PluginRouteAccessModule };
@@ -1,7 +1,7 @@
1
1
  import { type CanActivate, type ExecutionContext } from "@nestjs/common";
2
2
  import { Reflector } from "@nestjs/core";
3
3
  import type { FastifyRequest } from "fastify";
4
- import { AccountsService } from "./accounts.js";
4
+ import { type Account, AccountsService } from "./accounts.js";
5
5
  import { ApiTokenService } from "./api-tokens.js";
6
6
  import { type Principal } from "./principal.js";
7
7
  import { SessionService } from "./sessions.js";
@@ -27,17 +27,31 @@ export declare function authorizeSuperAdmin(req: FastifyRequest, s: AuthServices
27
27
  */
28
28
  export declare function authenticateOrgUploader(req: FastifyRequest, s: AuthServices): Promise<Principal>;
29
29
  /**
30
- * 全局守卫(`APP_GUARD`),默认拒绝:
31
- * 1. `Authorization: Bearer cap_pat_…|cap_svc_…` → API 令牌;个人令牌再实时读账号状态。不做 CSRF 检查。
32
- * 2. 否则 Cookie `cap_at` → 会话 access token(Redis 吊销标记作快速路径,再以 PG `sessions.revoked_at` 为准,
33
- * 与账号读取合并为一条查询)→ 实时判断账号状态;非安全方法要求 CSRF 头。
34
- * 3. 都没有:`@Public` 放行,否则 `auth.required`。`@Public` 路由上凭据无效(`ApiError`)按无凭据处理
35
- * (便于登出 / 刷新);PG / Redis 故障等其他异常照常抛出。
36
- * 4. 路由约束:service principal 只能访问 `@AllowService` 路由(否则 `forbidden`);
37
- * `@SessionOnly` 要求 Web 会话:个人令牌 → `auth.session_required`,服务令牌(即使路由经 `@OrgAction`
38
- * 隐含 `@AllowService`)→ `forbidden`;`@SuperAdmin` 要求超级管理员(`forbidden`)。
39
- * 5. `@Public` 路由的非安全方法无论是否带 Cookie 都要求 CSRF 头。
40
- * 账号状态每个请求都从 PG 实时读取,不在进程内缓存。插件路由 `/plugins/*` 不经过 Nest,不受此守卫约束。
30
+ * Before the body is read, for an extension `member` / `admin` route (plugin-route-access.ts): only
31
+ * a personal API token (`Authorization: Bearer cap_pat_…`) authenticates; a session cookie is
32
+ * ignored (no credential), so no CSRF check applies. No or an unknown token -> `auth.required`; a
33
+ * service token -> `forbidden`; a disabled account -> `auth.account_disabled`; one that must change
34
+ * its password -> `auth.password_change_required`. Returns the account, read live from PG.
35
+ */
36
+ export declare function authenticatePersonalToken(req: FastifyRequest, s: Pick<AuthServices, "accounts" | "tokens">): Promise<Account>;
37
+ /**
38
+ * The global guard (`APP_GUARD`), deny by default:
39
+ * 1. `Authorization: Bearer cap_pat_…|cap_svc_…` -> an API token; a personal token then reads the
40
+ * account state live. No CSRF check.
41
+ * 2. Otherwise the `cap_at` cookie -> a session access token (the Redis revocation marker as the
42
+ * fast path, then PG `sessions.revoked_at` decides, in one query with the account read) -> the
43
+ * account state live; unsafe methods need the CSRF header.
44
+ * 3. Neither: `@Public` passes, otherwise `auth.required`. On a `@Public` route an invalid
45
+ * credential (`ApiError`) counts as none (so logout / refresh work); other failures (PG / Redis
46
+ * down) are thrown as usual.
47
+ * 4. Route constraints: a service principal reaches only `@AllowService` routes (else
48
+ * `forbidden`); `@SessionOnly` needs a web session: a personal token -> `auth.session_required`,
49
+ * a service token (even where `@OrgAction` implies `@AllowService`) -> `forbidden`;
50
+ * `@SuperAdmin` needs a super admin (`forbidden`).
51
+ * 5. Unsafe methods of `@Public` routes need the CSRF header, cookie or not.
52
+ * The account state is read live from PG on every request, never cached in the process.
53
+ * Extension routes `/plugins/*` do not go through Nest or this guard: the plugin dispatch
54
+ * authenticates them by their declared access (plugin-route-access.ts, personal tokens only).
41
55
  */
42
56
  export declare class AuthGuard implements CanActivate {
43
57
  private readonly reflector;