@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.
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.22";
191
+ readonly sdk: "0.1.0-rc.23";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1,10 +1,11 @@
1
- import { type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type Logger, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type HttpAccess, type Logger, type RouteCaller, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { Kysely } from "kysely";
4
4
  import { type RegisteredHook } from "../extensions/hooks.js";
5
5
  import { RegistrationLedger } from "../extensions/ledger.js";
6
6
  import type { LockService } from "../infra/lock/lock.service.js";
7
7
  import type { ModelEmbeddings } from "../models/embeddings.js";
8
+ import type { OrgRole } from "../orgs/roles.js";
8
9
  import type { HookRunner } from "../runtime/hook-calls.js";
9
10
  import type { EmbedTokens } from "../ui/embed-token.js";
10
11
  import { type UiActionHandler, type UiRender } from "../ui/registry.js";
@@ -41,11 +42,24 @@ export interface KernelDeps {
41
42
  debug?(msg: string, fields?: Record<string, unknown>): void;
42
43
  };
43
44
  }
44
- /** 插件 HTTP 路由;`path` 已含 `/plugins/<name>` 前缀。 */
45
+ /**
46
+ * What `ctx.ui.verifyEmbedToken` returns for a valid token: the signed claims, with an org
47
+ * token's `role` replaced by the caller's role at verification time.
48
+ */
49
+ export type VerifiedEmbedClaims = EmbedClaims;
50
+ /**
51
+ * An extension HTTP route as registered through `ctx.http.route`. `path` is the full mounted path:
52
+ * `/plugins/<name>/orgs/:orgId<path>` for `member` / `admin`, `/plugins/<name><path>` for `public`
53
+ * / `embed`. `verifyEmbed` is the extension's own `ctx.ui.verifyEmbedToken` (the dispatch checks
54
+ * an `embed` route's token with it).
55
+ */
45
56
  export type Route = {
57
+ plugin: string;
46
58
  method: "GET" | "POST" | "PUT" | "DELETE";
47
59
  path: string;
48
- handler: (req: Request) => Promise<Response>;
60
+ access: HttpAccess;
61
+ handler: (req: Request, caller: RouteCaller) => Promise<Response>;
62
+ verifyEmbed: (token: string) => Promise<VerifiedEmbedClaims | null>;
49
63
  };
50
64
  /** 插件经 `ctx.tools.register` 注册的工具。 */
51
65
  export type RegisteredTool = {
@@ -81,6 +95,13 @@ export interface ExtensionPointAccess {
81
95
  * required bootstrap plugins, see `extensions/enabled.ts`), not cached.
82
96
  */
83
97
  export declare function queryEnabledPlugins(db: Kysely<any>, orgId: string): Promise<Set<string>>;
98
+ /**
99
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
100
+ * org, the org not deleted, the account active and still a member; returns the role now, or
101
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
102
+ * route check (plugin-route-access.ts) both use it.
103
+ */
104
+ export declare function currentOrgRole(db: KernelDeps["db"], plugin: string, orgId: string, accountId: string): Promise<OrgRole | undefined>;
84
105
  /**
85
106
  * Whether the account is, right now, an active super admin (one query): what a platform embed
86
107
  * token and the platform refresh stream re-check.
@@ -139,7 +160,8 @@ export declare class LiveConfig {
139
160
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
140
161
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
141
162
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
142
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
163
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
164
+ * its mount, see {@link Route}); `tools.register` only names declared in
143
165
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
144
166
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
145
167
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -23,9 +23,12 @@ export async function queryEnabledPlugins(db, orgId) {
23
23
  return new Set(rows.map((r) => r.plugin));
24
24
  }
25
25
  /**
26
- * 嵌入令牌校验时的一条查询:插件在该组织启用、组织未删除、账号 active、仍是成员;返回此刻的角色,不满足返回 undefined。
26
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
27
+ * org, the org not deleted, the account active and still a member; returns the role now, or
28
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
29
+ * route check (plugin-route-access.ts) both use it.
27
30
  */
28
- async function currentEmbedRole(db, plugin, orgId, accountId) {
31
+ export async function currentOrgRole(db, plugin, orgId, accountId) {
29
32
  const row = await kernelDb(db)
30
33
  .selectFrom("memberships")
31
34
  .innerJoin("orgs", "orgs.id", "memberships.org_id")
@@ -180,7 +183,8 @@ export class LiveConfig {
180
183
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
181
184
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
182
185
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
183
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
186
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
187
+ * its mount, see {@link Route}); `tools.register` only names declared in
184
188
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
185
189
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
186
190
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -253,7 +257,8 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
253
257
  },
254
258
  }
255
259
  : undefined;
256
- const declaredRoutes = new Set((perms.http ?? []).map((r) => `${r.method} ${r.path}`));
260
+ // "METHOD path" -> the access the manifest declares for it (the approved manifest)
261
+ const declaredRoutes = new Map((perms.http ?? []).map((r) => [`${r.method} ${r.path}`, r.access]));
257
262
  const declaredTools = new Set(perms.tools ?? []);
258
263
  const declaredHooks = new Set(perms.hooks ?? []);
259
264
  const declaredPolicyHooks = new Set(perms.policyHooks ?? []);
@@ -268,6 +273,36 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
268
273
  const embedTokens = deps.embedTokens;
269
274
  const uiResolution = resolveUiSlots(manifest.ui);
270
275
  const uiSlots = new Map(uiResolution.resolved.map((r) => [r.contribution.id, r.slot]));
276
+ // `ctx.ui.verifyEmbedToken`, also every route record's `verifyEmbed`. Accepts only a token signed
277
+ // for this extension, unexpired and untampered (see ui/embed-token.ts); then one query checks the
278
+ // present: the extension still enabled in that org, the org not deleted, the account active and
279
+ // still a member (PG every time, never cached: tokens already issued stop working at once when the
280
+ // extension is switched off, the member leaves or the account is disabled). The returned role is
281
+ // the current one; a token whose current role is below the minRole of its contribution's slot is
282
+ // refused (A38, UI slots spec §7). A platform token: the contribution is a `platform.page` and the
283
+ // account is still an active super admin. A token of one scope never verifies for the other's
284
+ // slots. Anything else is null.
285
+ const verifyEmbedToken = async (token) => {
286
+ const claims = embedTokens.verify(token, name);
287
+ if (claims === null)
288
+ return null;
289
+ const slot = uiSlots.get(claims.contribution);
290
+ if (claims.scope === "platform") {
291
+ if (slot?.id !== "platform.page")
292
+ return null;
293
+ return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
294
+ }
295
+ if (claims.scope !== "org" || claims.orgId === undefined)
296
+ return null;
297
+ // the contribution's slot as loaded now: never `platform.page` through an org token, and the
298
+ // current role still meets the slot's minRole (a demoted caller's token stops working)
299
+ if (slot === undefined || slot.id === "platform.page")
300
+ return null;
301
+ const role = await currentOrgRole(deps.db, name, claims.orgId, claims.accountId);
302
+ if (role === undefined || !canUseSlot(slot, role))
303
+ return null;
304
+ return { ...claims, role };
305
+ };
271
306
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
272
307
  const platformUi = new Set([...uiSlots].filter(([, s]) => s.id === "platform.page").map(([id]) => id));
273
308
  /** 校验能力可取用(非 brokered、已在清单声明),返回其登记信息。 */
@@ -400,13 +435,23 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
400
435
  if (typeof path !== "string" || !path.startsWith("/")) {
401
436
  throw new Error(`plugin ${name}: route path "${path}" must start with "/"`);
402
437
  }
403
- if (!declaredRoutes.has(`${method} ${path}`))
404
- deny(`permissions.http ${method} ${path}`);
405
- const full = `/plugins/${name}${path}`;
438
+ const access = declaredRoutes.get(`${method} ${path}`);
439
+ if (access === undefined)
440
+ return deny(`permissions.http ${method} ${path}`);
441
+ const full = access === "member" || access === "admin"
442
+ ? `/plugins/${name}/orgs/:orgId${path}`
443
+ : `/plugins/${name}${path}`;
406
444
  if (routes.some((r) => r.method === method && r.path === full)) {
407
445
  throw new Error(`plugin ${name}: duplicate route ${method} ${path}`);
408
446
  }
409
- const route = { method, path: full, handler };
447
+ const route = {
448
+ plugin: name,
449
+ method,
450
+ path: full,
451
+ access,
452
+ handler,
453
+ verifyEmbed: verifyEmbedToken,
454
+ };
410
455
  routes.push(route);
411
456
  ledger.add({
412
457
  kind: "route",
@@ -568,32 +613,7 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
568
613
  ? conversationTopic(t.conversationId)
569
614
  : orgUiTopic(t.orgId), msg);
570
615
  },
571
- // 只认签给本插件、未过期、未篡改的令牌(见 ui/embed-token.ts);再用一条查询核对此刻:本插件仍在该组织
572
- // 启用、组织未删除、账号 active 且仍是成员(每次查 PG、不缓存:停用插件、离职、停用账号后已签出的令牌立即失效)。
573
- // 返回的 role 是此刻的角色;令牌在此刻的角色低于贡献所在位置的 minRole 时失效(A38, UI slots spec §7)。
574
- // A platform token: the contribution is a `platform.page` and the account is still an active
575
- // super admin. A token of one scope never verifies for the other's slots. 其余一律 null
576
- async verifyEmbedToken(token) {
577
- const claims = embedTokens.verify(token, name);
578
- if (claims === null)
579
- return null;
580
- const slot = uiSlots.get(claims.contribution);
581
- if (claims.scope === "platform") {
582
- if (slot?.id !== "platform.page")
583
- return null;
584
- return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
585
- }
586
- if (claims.scope !== "org" || claims.orgId === undefined)
587
- return null;
588
- // the contribution's slot as loaded now: never `platform.page` through an org token, and the
589
- // current role still meets the slot's minRole (a demoted caller's token stops working)
590
- if (slot === undefined || slot.id === "platform.page")
591
- return null;
592
- const role = await currentEmbedRole(deps.db, name, claims.orgId, claims.accountId);
593
- if (role === undefined || !canUseSlot(slot, role))
594
- return null;
595
- return { ...claims, role };
596
- },
616
+ verifyEmbedToken,
597
617
  },
598
618
  provide(extensionPoint, impl) {
599
619
  if (!manifest.provides.includes(extensionPoint)) {
@@ -1,4 +1,4 @@
1
- import type { ExtensionManifest, ExtensionPermissions } from "@capybara-hq/plugin-sdk";
1
+ import type { ExtensionManifest, ExtensionPermissions, HttpAccess } from "@capybara-hq/plugin-sdk";
2
2
  /** 一个配置字段:点路径(根即叶子时为空串)与是否密钥。 */
3
3
  export interface PermissionConfigField {
4
4
  path: string;
@@ -25,7 +25,7 @@ export interface PermissionSet {
25
25
  http: {
26
26
  method: string;
27
27
  path: string;
28
- public: boolean;
28
+ access: HttpAccess;
29
29
  }[];
30
30
  tools: string[];
31
31
  hooks: string[];
@@ -107,10 +107,11 @@ export declare function buildPermissionSet(input: {
107
107
  warningsDigest?: string | undefined;
108
108
  }): PermissionSet;
109
109
  /**
110
- * 权限集合的稳定字符串键(排序),如 `provides:channel@1`、`config.org.secret:apiKey`、`table:todos`、
111
- * `permissions.tools:write`、`permissions.http.public:POST /events`、`ui.view:tasks`、`ui.embed:board`,
112
- * `permissions.client`, `ui.component:hud`.
113
- * 容忍旧快照缺字段(按空处理),快照格式演进时不会抛错。
110
+ * The stable string keys of a permission set (sorted), such as `provides:channel@1`,
111
+ * `config.org.secret:apiKey`, `table:todos`, `permissions.tools:write`,
112
+ * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
113
+ * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`.
114
+ * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
114
115
  */
115
116
  export declare function permissionKeys(set: PermissionSet): string[];
116
117
  /**
@@ -95,7 +95,7 @@ export function buildPermissionSet(input) {
95
95
  secrets: p.secrets === true,
96
96
  storage: p.storage === true,
97
97
  http: (p.http ?? [])
98
- .map((r) => ({ method: r.method, path: r.path, public: r.public === true }))
98
+ .map((r) => ({ method: r.method, path: r.path, access: r.access }))
99
99
  .sort((a, b) => cmp(`${a.method} ${a.path}`, `${b.method} ${b.path}`)),
100
100
  tools: sortedUnique(p.tools),
101
101
  hooks: sortedUnique(p.hooks),
@@ -122,10 +122,11 @@ export function buildPermissionSet(input) {
122
122
  };
123
123
  }
124
124
  /**
125
- * 权限集合的稳定字符串键(排序),如 `provides:channel@1`、`config.org.secret:apiKey`、`table:todos`、
126
- * `permissions.tools:write`、`permissions.http.public:POST /events`、`ui.view:tasks`、`ui.embed:board`,
127
- * `permissions.client`, `ui.component:hud`.
128
- * 容忍旧快照缺字段(按空处理),快照格式演进时不会抛错。
125
+ * The stable string keys of a permission set (sorted), such as `provides:channel@1`,
126
+ * `config.org.secret:apiKey`, `table:todos`, `permissions.tools:write`,
127
+ * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
128
+ * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`.
129
+ * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
129
130
  */
130
131
  export function permissionKeys(set) {
131
132
  const s = (set ?? {});
@@ -149,7 +150,9 @@ export function permissionKeys(set) {
149
150
  if (p.storage)
150
151
  keys.push("permissions.storage");
151
152
  for (const r of p.http ?? []) {
152
- keys.push(`permissions.http${r.public ? ".public" : ""}:${r.method} ${r.path}`);
153
+ // a snapshot from before route access has no `access`: its key matches no current key, so the
154
+ // extension waits for re-approval
155
+ keys.push(`permissions.http${r.access ? `.${r.access}` : ""}:${r.method} ${r.path}`);
153
156
  }
154
157
  for (const t of p.tools ?? [])
155
158
  keys.push(`permissions.tools:${t}`);
@@ -12,7 +12,7 @@ import type { ExtensionSource } from "./sources.js";
12
12
  export declare function reviewHash(set: PermissionSet, warnings?: readonly PackageWarning[]): string;
13
13
  /** 权限清单展示用的一组:按类别分组,`sensitive` 标出需要管理员特别留意的类别。 */
14
14
  export interface PermissionGroup {
15
- category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client";
15
+ category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client";
16
16
  /**
17
17
  * Sensitive category: secrets, public routes, tools, hooks, client components, client code; also
18
18
  * the "provides" group when it holds one of {@link SENSITIVE_EXTENSION_POINTS}, and the "UI" group
@@ -24,13 +24,13 @@ export interface PermissionGroup {
24
24
  entries: PermissionItem[];
25
25
  }
26
26
  /**
27
- * Sensitive reason codes (the UI translates them by code): secrets, public routes, tools, hooks,
28
- * embedded apps, client code and client components (client extensions spec §5.4: code that runs with
27
+ * Sensitive reason codes (the UI translates them by code): secrets, public routes, embed routes,
28
+ * tools, hooks, embedded apps, client code and client components (client extensions spec §5.4: code that runs with
29
29
  * full trust in members' browsers), and sensitive extension points
30
30
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
31
31
  * `-` replaced by `_`).
32
32
  */
33
- export type SensitiveReason = "secrets" | "public_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "migration_warnings";
33
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "migration_warnings";
34
34
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
35
35
  export interface PermissionItem {
36
36
  value: string;
@@ -41,6 +41,7 @@ const CLIENT_ITEM = "client code";
41
41
  const ALWAYS_SENSITIVE = new Set([
42
42
  "secrets",
43
43
  "publicRoutes",
44
+ "embedRoutes",
44
45
  "tools",
45
46
  "hooks",
46
47
  "components",
@@ -49,6 +50,7 @@ const ALWAYS_SENSITIVE = new Set([
49
50
  const CATEGORY_REASON = {
50
51
  secrets: "secrets",
51
52
  publicRoutes: "public_routes",
53
+ embedRoutes: "embed_routes",
52
54
  tools: "tools",
53
55
  hooks: "hooks",
54
56
  components: "ui_component",
@@ -74,6 +76,9 @@ function itemReason(category, item) {
74
76
  }
75
77
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
76
78
  }
79
+ /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
80
+ const signedIn = (access) => access === "member" || access === "admin";
81
+ const routeItem = (r) => `${r.method} ${r.path} (${r.access})`;
77
82
  const itemOf = (category, value) => {
78
83
  const reason = itemReason(category, value);
79
84
  return reason === undefined ? { value, sensitive: false } : { value, sensitive: true, reason };
@@ -90,6 +95,7 @@ function keyItem(key) {
90
95
  const table = [
91
96
  ["provides:", "provides", ""],
92
97
  ["permissions.http.public:", "publicRoutes", ""],
98
+ ["permissions.http.embed:", "embedRoutes", ""],
93
99
  ["permissions.tools:", "tools", ""],
94
100
  ["permissions.hooks:", "hooks", ""],
95
101
  ["permissions.hooks.policy:", "hooks", "policy:"],
@@ -150,14 +156,13 @@ export function permissionGroups(set) {
150
156
  { category: "tables", items: set.tables },
151
157
  { category: "secrets", items: secretItems },
152
158
  { category: "storage", items: p.storage ? ["storage"] : [] },
153
- {
154
- category: "http",
155
- items: p.http.filter((r) => !r.public).map((r) => `${r.method} ${r.path}`),
156
- },
159
+ // routes show their access; public (no sign-in) and embed (embed token) are sensitive groups
160
+ { category: "http", items: p.http.filter((r) => signedIn(r.access)).map(routeItem) },
157
161
  {
158
162
  category: "publicRoutes",
159
- items: p.http.filter((r) => r.public).map((r) => `${r.method} ${r.path}`),
163
+ items: p.http.filter((r) => r.access === "public").map(routeItem),
160
164
  },
165
+ { category: "embedRoutes", items: p.http.filter((r) => r.access === "embed").map(routeItem) },
161
166
  { category: "tools", items: p.tools },
162
167
  { category: "hooks", items: [...p.hooks, ...(p.policyHooks ?? []).map((h) => `policy:${h}`)] },
163
168
  {
@@ -5,7 +5,7 @@ import type { InjectOptions, LightMyRequestResponse } from "fastify";
5
5
  import type { Route } from "../ctx/create-ctx.js";
6
6
  import type { GitGateway } from "../git/gateway.js";
7
7
  import { type GatewayRoutes } from "./gateway-routes.js";
8
- import { type PluginRouteTable } from "./plugin-dispatch.js";
8
+ import { type PluginRouteTable, type RouteAccessResolver } from "./plugin-dispatch.js";
9
9
  /** 内核 HTTP 的只读视图:进程内注入请求与列出路由(测试与元测试用)。 */
10
10
  export interface KernelHttp {
11
11
  inject(opts: InjectOptions): Promise<LightMyRequestResponse>;
@@ -37,6 +37,11 @@ export interface CreateHttpAppOptions {
37
37
  log: Logger;
38
38
  /** Whether `/plugins/*` is dispatched to extension routes. */
39
39
  servePlugins: boolean;
40
+ /**
41
+ * Resolves the caller of an extension route from its declared access; default the application's
42
+ * {@link PluginRouteAccess}, looked up on the first extension request.
43
+ */
44
+ routeAccess?: RouteAccessResolver;
40
45
  /**
41
46
  * Gateway-role routes (the channel webhook), registered only when given: the kernel passes them
42
47
  * when `roles` includes `gateway` (`serveGateway`).
@@ -82,7 +87,8 @@ export declare const ORG_PACKAGE_UPLOAD_ROUTES: ReadonlySet<string>;
82
87
  * and returns it uninitialized: `init()` is the caller's (it runs the start sequence), `close()`
83
88
  * closes only the HTTP server (the rest of the application is closed by the caller's shutdown).
84
89
  * Extension routes do not go through Nest: `/plugins/*` is dispatched in its own Fastify scope
85
- * (see plugin-dispatch.ts) and answers 404 until extensions are loaded. Unmatched kernel routes
90
+ * (see plugin-dispatch.ts), which checks each route's declared access before the body is read, and
91
+ * answers 404 until extensions are loaded. Unmatched kernel routes
86
92
  * answer the 404 error envelope as well.
87
93
  */
88
94
  export declare function createHttpApp(opts: CreateHttpAppOptions, app: NestFastifyApplication): Promise<KernelHttpApp>;
package/dist/http/app.js CHANGED
@@ -12,6 +12,7 @@ import { authorizeOrgAction } from "../orgs/org.guard.js";
12
12
  import { redactPath } from "./error.filter.js";
13
13
  import { registerGatewayRoutes } from "./gateway-routes.js";
14
14
  import { createPluginRouter, registerPluginDispatch, staticRouteTable, } from "./plugin-dispatch.js";
15
+ import { PluginRouteAccess } from "./plugin-route-access.js";
15
16
  /** The extension package upload route (Fastify route template). */
16
17
  export const EXTENSION_PACKAGE_UPLOAD_ROUTE = "/api/v1/admin/extensions/packages/file";
17
18
  /** The plugin package upload route of the catalog import (Fastify route template). */
@@ -82,7 +83,8 @@ const LARGE_BODY_LIMIT = 6 * 1024 * 1024;
82
83
  * and returns it uninitialized: `init()` is the caller's (it runs the start sequence), `close()`
83
84
  * closes only the HTTP server (the rest of the application is closed by the caller's shutdown).
84
85
  * Extension routes do not go through Nest: `/plugins/*` is dispatched in its own Fastify scope
85
- * (see plugin-dispatch.ts) and answers 404 until extensions are loaded. Unmatched kernel routes
86
+ * (see plugin-dispatch.ts), which checks each route's declared access before the body is read, and
87
+ * answers 404 until extensions are loaded. Unmatched kernel routes
86
88
  * answer the 404 error envelope as well.
87
89
  */
88
90
  export async function createHttpApp(opts, app) {
@@ -167,8 +169,16 @@ export async function createHttpApp(opts, app) {
167
169
  fastify.addContentTypeParser("application/octet-stream", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
168
170
  let table;
169
171
  let unwatch;
172
+ let routeAccess = opts.routeAccess;
173
+ const lazyRouteAccess = {
174
+ resolve: (...args) => {
175
+ if (routeAccess === undefined)
176
+ routeAccess = app.get(PluginRouteAccess, { strict: false });
177
+ return routeAccess.resolve(...args);
178
+ },
179
+ };
170
180
  const dispatch = opts.servePlugins
171
- ? await registerPluginDispatch(fastify, () => table, opts.log)
181
+ ? await registerPluginDispatch(fastify, () => table, opts.log, lazyRouteAccess)
172
182
  : undefined;
173
183
  if (opts.gateway)
174
184
  await registerGatewayRoutes(fastify, opts.gateway, opts.log);
@@ -1,11 +1,25 @@
1
- import type { Logger } from "@capybara-hq/plugin-sdk";
2
- import type { FastifyInstance } from "fastify";
1
+ import type { Logger, RouteCaller } from "@capybara-hq/plugin-sdk";
2
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
3
3
  import type { Route } from "../ctx/create-ctx.js";
4
- /** 插件路由都在此前缀下(ctx.http.route 已加 `/plugins/<name>` 前缀)。 */
4
+ /** Every extension route lives under this prefix (`ctx.http.route` adds `/plugins/<name>`). */
5
5
  export declare const PLUGIN_PREFIX = "/plugins/";
6
- /** 插件路由表:按方法与路径(不含查询串)找到插件 handler;HEAD 没有专门路由时按 GET 匹配。 */
6
+ /**
7
+ * The extension route table: the route record matching a method and path (no query string) with
8
+ * its path parameters; HEAD without a route of its own matches the GET record (its access too).
9
+ */
7
10
  export interface PluginRouter {
8
- find(method: string, path: string): Route["handler"] | undefined;
11
+ find(method: string, path: string): {
12
+ route: Route;
13
+ params: Record<string, string>;
14
+ } | undefined;
15
+ }
16
+ /**
17
+ * Resolves the caller of an extension route from its declared access (`PluginRouteAccess`), run
18
+ * in the plugin scope's `onRequest` hook: throws an `ApiError` on refusal, never reads the body.
19
+ * `reply` only takes headers (a 429's `retry-after`).
20
+ */
21
+ export interface RouteAccessResolver {
22
+ resolve(route: Route, req: FastifyRequest, reply: FastifyReply, params: Record<string, string>): Promise<RouteCaller>;
9
23
  }
10
24
  /**
11
25
  * The live source of extension routes (C17): routes change as extension instances are revoked /
@@ -28,27 +42,43 @@ export interface PluginRouteTable {
28
42
  export declare function staticRouteTable(routes: Route[]): PluginRouteTable;
29
43
  /** 路径里的插件名(`/plugins/<name>/...` 的 `<name>`);不在插件前缀下返回 undefined。 */
30
44
  export declare function pluginOfPath(path: string): string | undefined;
31
- /** 用 find-my-way 建立插件路由表,路径语法与 Fastify 相同;路径不在 `/plugins/` 下时抛错。 */
45
+ /**
46
+ * Builds the extension route table with find-my-way (the same path syntax as Fastify); throws for
47
+ * a path outside `/plugins/`.
48
+ */
32
49
  export declare function createPluginRouter(routes: Route[]): PluginRouter;
33
50
  /**
34
51
  * Registers `/plugins/*` in its own encapsulated scope and hands each request to the extension handler
35
52
  * as a Web `Request`: the scope removes the default parsers and takes every content type as a raw
36
53
  * Buffer, so the body the extension gets is the bytes the client sent.
37
- * - The extension belongs to this deployment but is not in the registry (revoked and so on) -> 503
38
- * `extension.unavailable`; when an extension instance is revoked or replaced, the `req.signal` of
39
- * that extension's in-progress requests is aborted (`abortPlugin`, triggered by the route source's
40
- * `onChange`);
41
- * - not mounted or no match -> 404 `not_found`; HEAD without its own route is handled as GET, with no
42
- * body in the response.
43
- * - A `Request` that cannot be built (e.g. a malformed Host) -> 400 `validation_failed`, not logged as
44
- * an error.
54
+ * Before the body is read (the scope's `onRequest` hook), in this order:
55
+ * - the extension belongs to this deployment but is not in the registry (revoked and so on) -> 503
56
+ * `extension.unavailable` (its routes are gone, so their access is unknown);
57
+ * The gate reads the plugin segment decoded (the router decodes too); a malformed escape -> 400
58
+ * `validation_failed`;
59
+ * - not mounted or no match -> 404 `not_found`; HEAD without its own route uses the GET record
60
+ * (its access and params) and answers with no body; a `public` / `embed` record matching the
61
+ * org mount `/plugins/<plugin>/orgs[/...]` (decoded) counts as no match;
62
+ * - the matched record's access is resolved by `access` (authentication, authorization, effective
63
+ * config, the public write throttle, see plugin-route-access.ts): an `ApiError` answers its
64
+ * status and envelope, any other failure is logged and answers 500 `internal`. A refusal never
65
+ * reaches the handler. The match and the caller are kept per request (a WeakMap entry).
66
+ * Then the handler stage:
67
+ * - the handler gets `(webReq, caller)`; the Web request carries no kernel credential (`cap_at` /
68
+ * `cap_rt` cookies and an `Authorization` header with a `cap_pat_` / `cap_svc_` token are
69
+ * removed; an embed token stays);
70
+ * - when an extension instance is revoked or replaced, the `req.signal` of that extension's
71
+ * in-progress requests is aborted (`abortPlugin`, triggered by the route source's `onChange`);
72
+ * - a `Request` that cannot be built (e.g. a malformed Host) -> 400 `validation_failed`, not
73
+ * logged as an error;
45
74
  * - `req.signal` aborts only when the client disconnects before the response is written (not on
46
75
  * normal completion); long-lived handlers use it to unsubscribe;
47
76
  * - a throwing handler is logged (path redacted with `redactPath`) and returns 500 `internal` (the
48
77
  * error message is not echoed), except a `model.hook_denied` `ApiError` that escaped from
49
78
  * `ctx.models.embed` (an organization policy hook denied the call, spec B §5.4): a deliberate
50
79
  * outcome, not a failure, so it answers 403 `model.hook_denied` with a generic message (the
51
- * routes are unauthenticated: the policy extension's name and reason are not echoed).
80
+ * policy extension's name and reason are not echoed: the route's caller, possibly anonymous, is
81
+ * not the org admin who configured the policy).
52
82
  * - Fastify's own errors (a body over 1 MiB and so on) are mapped to the error envelope by the
53
83
  * scope's error handler: 4xx by the common error code table (413 `payload_too_large`, 415
54
84
  * `unsupported_media_type` and so on), 5xx are logged and return `internal`.
@@ -60,12 +90,19 @@ export declare function createPluginRouter(routes: Route[]): PluginRouter;
60
90
  * .agents/skills/writing-extensions "Extension route matching semantics").
61
91
  * Must be called before Nest `app.init()`.
62
92
  */
63
- export declare function registerPluginDispatch(fastify: FastifyInstance, getTable: () => PluginRouteTable | undefined, log: Logger): Promise<{
93
+ export declare function registerPluginDispatch(fastify: FastifyInstance, getTable: () => PluginRouteTable | undefined, log: Logger, access: RouteAccessResolver): Promise<{
64
94
  abortAll(): void;
65
95
  abortPlugin(plugin: string): void;
66
96
  }>;
67
97
  /**
68
- * 从 Cookie 头里去掉内核会话 Cookie(`cap_at` / `cap_rt`):插件 handler 不经内核鉴权,
69
- * 拿到这两个 Cookie 就能冒充用户调内核 API。全部去掉后返回 undefined(不传 Cookie 头)。
98
+ * Removes the kernel session cookies (`cap_at` / `cap_rt`) from a Cookie header: with them an
99
+ * extension handler could call the kernel API as the user. Returns undefined when nothing is left
100
+ * (no Cookie header is passed on).
70
101
  */
71
102
  export declare function stripKernelCookies(cookie: string): string | undefined;
103
+ /**
104
+ * An `Authorization` header value as the extension handler may see it: undefined (dropped) when it
105
+ * carries a kernel API token (`cap_pat_` / `cap_svc_`), which would let the extension call the
106
+ * kernel API as its owner; anything else (an embed token, a webhook signature) is kept.
107
+ */
108
+ export declare function stripKernelAuthorization(value: string): string | undefined;