@capybara-hq/kernel 0.1.0-rc.31 → 0.1.0-rc.33
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.
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/inbound.d.ts +0 -25
- package/dist/channels/inbound.js +26 -1
- package/dist/channels/phrases.d.ts +28 -0
- package/dist/channels/phrases.js +28 -0
- package/dist/conversations/conversations.controller.d.ts +4 -1
- package/dist/conversations/conversations.controller.js +14 -2
- package/dist/conversations/conversations.service.d.ts +43 -3
- package/dist/conversations/conversations.service.js +93 -19
- package/dist/conversations/event-log.d.ts +3 -3
- package/dist/conversations/event-log.js +3 -3
- package/dist/conversations/events.d.ts +24 -0
- package/dist/conversations/events.js +69 -0
- package/dist/ctx/create-ctx.d.ts +26 -4
- package/dist/ctx/create-ctx.js +54 -34
- package/dist/db/kernel-schema.d.ts +20 -0
- package/dist/devices/conversation-devices.d.ts +57 -3
- package/dist/devices/conversation-devices.js +63 -11
- package/dist/devices/device-projects.service.d.ts +162 -0
- package/dist/devices/device-projects.service.js +503 -0
- package/dist/devices/devices.controller.d.ts +15 -2
- package/dist/devices/devices.controller.js +60 -3
- package/dist/devices/devices.module.js +15 -2
- package/dist/devices/devices.schemas.js +9 -1
- package/dist/devices/dto.d.ts +31 -0
- package/dist/devices/dto.js +38 -1
- package/dist/devices/working-root.d.ts +41 -0
- package/dist/devices/working-root.js +50 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +39 -0
- package/dist/evals/run-replay.d.ts +9 -1
- package/dist/evals/run-replay.js +15 -1
- package/dist/extensions/permission-set.d.ts +7 -6
- package/dist/extensions/permission-set.js +9 -6
- package/dist/extensions/permission-view.d.ts +4 -4
- package/dist/extensions/permission-view.js +10 -5
- package/dist/http/app.d.ts +8 -2
- package/dist/http/app.js +12 -2
- package/dist/http/plugin-dispatch.d.ts +55 -18
- package/dist/http/plugin-dispatch.js +124 -29
- package/dist/http/plugin-route-access.d.ts +56 -0
- package/dist/http/plugin-route-access.js +192 -0
- package/dist/identity/auth.guard.d.ts +26 -12
- package/dist/identity/auth.guard.js +62 -33
- package/dist/infra/throttler/named-throttlers.d.ts +3 -0
- package/dist/infra/throttler/named-throttlers.js +16 -0
- package/dist/infra/throttler/throttler.guard.d.ts +2 -1
- package/dist/infra/throttler/throttler.guard.js +2 -1
- package/dist/kernel.module.js +3 -0
- package/dist/local-devices/local-device-provider.d.ts +37 -1
- package/dist/local-devices/local-device-provider.js +33 -0
- package/dist/local-devices/machines.d.ts +2 -1
- package/dist/local-devices/machines.js +4 -1
- package/dist/local-devices/policy-summary.js +1 -0
- package/dist/local-devices/relay.d.ts +2 -0
- package/dist/local-devices/relay.js +3 -1
- package/dist/local-devices/targets.d.ts +6 -1
- package/dist/local-devices/targets.js +14 -0
- package/dist/overrides.d.ts +7 -0
- package/dist/overrides.js +4 -0
- package/dist/platform/ops/agent-skills.ops.js +2 -1
- package/dist/platform/ops/devices.ops.d.ts +3 -1
- package/dist/platform/ops/devices.ops.js +136 -3
- package/dist/runtime/context/build.d.ts +3 -0
- package/dist/runtime/context/build.js +14 -0
- package/dist/runtime/context/compaction.js +2 -0
- package/dist/runtime/context/project-root.d.ts +43 -0
- package/dist/runtime/context/project-root.js +85 -0
- package/dist/runtime/model-call.js +25 -1
- package/dist/runtime/project/knowledge.d.ts +129 -0
- package/dist/runtime/project/knowledge.js +248 -0
- package/dist/runtime/project/knowledge.service.d.ts +85 -0
- package/dist/runtime/project/knowledge.service.js +288 -0
- package/dist/runtime/run-worker.d.ts +5 -0
- package/dist/runtime/run-worker.js +27 -6
- package/dist/runtime/runtime.module.js +7 -0
- package/dist/sandbox/review/review.service.d.ts +14 -2
- package/dist/sandbox/review/review.service.js +2 -0
- package/dist/sandbox/review/rules.d.ts +6 -4
- package/dist/sandbox/review/rules.js +185 -62
- package/dist/sandbox/review/types.d.ts +14 -0
- package/dist/sandbox/sandbox.service.d.ts +16 -1
- package/dist/sandbox/sandbox.service.js +75 -3
- package/dist/skills/catalog.d.ts +6 -1
- package/dist/skills/catalog.js +18 -4
- package/dist/skills/invoke.d.ts +64 -2
- package/dist/skills/invoke.js +214 -6
- package/dist/skills/skills.module.js +5 -0
- package/dist/tools/approvals.service.d.ts +6 -0
- package/dist/tools/builtins/sandbox/bash.js +19 -4
- package/dist/tools/builtins/sandbox/common.d.ts +36 -6
- package/dist/tools/builtins/sandbox/common.js +69 -8
- package/dist/tools/builtins/sandbox/edit.js +2 -2
- package/dist/tools/builtins/sandbox/glob.js +3 -2
- package/dist/tools/builtins/sandbox/grep.js +2 -1
- package/dist/tools/builtins/sandbox/read.js +3 -3
- package/dist/tools/builtins/sandbox/write.js +2 -2
- package/dist/tools/builtins/skill-load.d.ts +47 -2
- package/dist/tools/builtins/skill-load.js +160 -2
- package/dist/tools/pipeline.d.ts +1 -1
- package/dist/tools/pipeline.js +53 -8
- package/dist/tools/registry.d.ts +6 -0
- package/package.json +3 -3
- package/src/migrations/0133_project_root.sql +30 -0
|
@@ -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,
|
|
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
|
-
|
|
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(
|
|
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
|
{
|
package/dist/http/app.d.ts
CHANGED
|
@@ -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)
|
|
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)
|
|
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
|
-
/**
|
|
4
|
+
/** Every extension route lives under this prefix (`ctx.http.route` adds `/plugins/<name>`). */
|
|
5
5
|
export declare const PLUGIN_PREFIX = "/plugins/";
|
|
6
|
-
/**
|
|
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):
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
69
|
-
*
|
|
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;
|
|
@@ -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
|
-
/**
|
|
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
|
-
/**
|
|
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, () => { }, {
|
|
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
|
-
|
|
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
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
|
88
|
-
if (!
|
|
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
|
-
|
|
92
|
-
|
|
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
|
|
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
|
-
*
|
|
170
|
-
*
|
|
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
|
-
*
|
|
181
|
-
*
|
|
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
|
+
}
|