@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.
Files changed (104) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/inbound.d.ts +0 -25
  3. package/dist/channels/inbound.js +26 -1
  4. package/dist/channels/phrases.d.ts +28 -0
  5. package/dist/channels/phrases.js +28 -0
  6. package/dist/conversations/conversations.controller.d.ts +4 -1
  7. package/dist/conversations/conversations.controller.js +14 -2
  8. package/dist/conversations/conversations.service.d.ts +43 -3
  9. package/dist/conversations/conversations.service.js +93 -19
  10. package/dist/conversations/event-log.d.ts +3 -3
  11. package/dist/conversations/event-log.js +3 -3
  12. package/dist/conversations/events.d.ts +24 -0
  13. package/dist/conversations/events.js +69 -0
  14. package/dist/ctx/create-ctx.d.ts +26 -4
  15. package/dist/ctx/create-ctx.js +54 -34
  16. package/dist/db/kernel-schema.d.ts +20 -0
  17. package/dist/devices/conversation-devices.d.ts +57 -3
  18. package/dist/devices/conversation-devices.js +63 -11
  19. package/dist/devices/device-projects.service.d.ts +162 -0
  20. package/dist/devices/device-projects.service.js +503 -0
  21. package/dist/devices/devices.controller.d.ts +15 -2
  22. package/dist/devices/devices.controller.js +60 -3
  23. package/dist/devices/devices.module.js +15 -2
  24. package/dist/devices/devices.schemas.js +9 -1
  25. package/dist/devices/dto.d.ts +31 -0
  26. package/dist/devices/dto.js +38 -1
  27. package/dist/devices/working-root.d.ts +41 -0
  28. package/dist/devices/working-root.js +50 -0
  29. package/dist/errors.d.ts +39 -0
  30. package/dist/errors.js +39 -0
  31. package/dist/evals/run-replay.d.ts +9 -1
  32. package/dist/evals/run-replay.js +15 -1
  33. package/dist/extensions/permission-set.d.ts +7 -6
  34. package/dist/extensions/permission-set.js +9 -6
  35. package/dist/extensions/permission-view.d.ts +4 -4
  36. package/dist/extensions/permission-view.js +10 -5
  37. package/dist/http/app.d.ts +8 -2
  38. package/dist/http/app.js +12 -2
  39. package/dist/http/plugin-dispatch.d.ts +55 -18
  40. package/dist/http/plugin-dispatch.js +124 -29
  41. package/dist/http/plugin-route-access.d.ts +56 -0
  42. package/dist/http/plugin-route-access.js +192 -0
  43. package/dist/identity/auth.guard.d.ts +26 -12
  44. package/dist/identity/auth.guard.js +62 -33
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  48. package/dist/infra/throttler/throttler.guard.js +2 -1
  49. package/dist/kernel.module.js +3 -0
  50. package/dist/local-devices/local-device-provider.d.ts +37 -1
  51. package/dist/local-devices/local-device-provider.js +33 -0
  52. package/dist/local-devices/machines.d.ts +2 -1
  53. package/dist/local-devices/machines.js +4 -1
  54. package/dist/local-devices/policy-summary.js +1 -0
  55. package/dist/local-devices/relay.d.ts +2 -0
  56. package/dist/local-devices/relay.js +3 -1
  57. package/dist/local-devices/targets.d.ts +6 -1
  58. package/dist/local-devices/targets.js +14 -0
  59. package/dist/overrides.d.ts +7 -0
  60. package/dist/overrides.js +4 -0
  61. package/dist/platform/ops/agent-skills.ops.js +2 -1
  62. package/dist/platform/ops/devices.ops.d.ts +3 -1
  63. package/dist/platform/ops/devices.ops.js +136 -3
  64. package/dist/runtime/context/build.d.ts +3 -0
  65. package/dist/runtime/context/build.js +14 -0
  66. package/dist/runtime/context/compaction.js +2 -0
  67. package/dist/runtime/context/project-root.d.ts +43 -0
  68. package/dist/runtime/context/project-root.js +85 -0
  69. package/dist/runtime/model-call.js +25 -1
  70. package/dist/runtime/project/knowledge.d.ts +129 -0
  71. package/dist/runtime/project/knowledge.js +248 -0
  72. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  73. package/dist/runtime/project/knowledge.service.js +288 -0
  74. package/dist/runtime/run-worker.d.ts +5 -0
  75. package/dist/runtime/run-worker.js +27 -6
  76. package/dist/runtime/runtime.module.js +7 -0
  77. package/dist/sandbox/review/review.service.d.ts +14 -2
  78. package/dist/sandbox/review/review.service.js +2 -0
  79. package/dist/sandbox/review/rules.d.ts +6 -4
  80. package/dist/sandbox/review/rules.js +185 -62
  81. package/dist/sandbox/review/types.d.ts +14 -0
  82. package/dist/sandbox/sandbox.service.d.ts +16 -1
  83. package/dist/sandbox/sandbox.service.js +75 -3
  84. package/dist/skills/catalog.d.ts +6 -1
  85. package/dist/skills/catalog.js +18 -4
  86. package/dist/skills/invoke.d.ts +64 -2
  87. package/dist/skills/invoke.js +214 -6
  88. package/dist/skills/skills.module.js +5 -0
  89. package/dist/tools/approvals.service.d.ts +6 -0
  90. package/dist/tools/builtins/sandbox/bash.js +19 -4
  91. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  92. package/dist/tools/builtins/sandbox/common.js +69 -8
  93. package/dist/tools/builtins/sandbox/edit.js +2 -2
  94. package/dist/tools/builtins/sandbox/glob.js +3 -2
  95. package/dist/tools/builtins/sandbox/grep.js +2 -1
  96. package/dist/tools/builtins/sandbox/read.js +3 -3
  97. package/dist/tools/builtins/sandbox/write.js +2 -2
  98. package/dist/tools/builtins/skill-load.d.ts +47 -2
  99. package/dist/tools/builtins/skill-load.js +160 -2
  100. package/dist/tools/pipeline.d.ts +1 -1
  101. package/dist/tools/pipeline.js +53 -8
  102. package/dist/tools/registry.d.ts +6 -0
  103. package/package.json +3 -3
  104. package/src/migrations/0133_project_root.sql +30 -0
@@ -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;
@@ -24,32 +24,37 @@ function requireCsrf(req) {
24
24
  throw new ApiError("auth.csrf", `Missing ${CSRF_HEADER} header`);
25
25
  }
26
26
  }
27
- /** 解析凭据;无凭据返回 undefined,凭据无效抛对应的 ApiError。 */
28
- async function resolvePrincipal(req, s) {
27
+ /**
28
+ * The API token of an `Authorization: Bearer` header as a principal: a service token, or a
29
+ * personal token with its account read live (disabled -> `auth.account_disabled`). Undefined
30
+ * without a Bearer header; an unknown token or a missing account -> `auth.required`. Shared by
31
+ * {@link resolvePrincipal} and {@link authenticatePersonalToken}.
32
+ */
33
+ async function resolveBearer(req, s) {
29
34
  const bearer = BEARER_RE.exec(req.headers.authorization ?? "")?.[1];
30
- if (bearer !== undefined) {
31
- const rec = await s.tokens.authenticate(bearer);
32
- if (!rec)
33
- throw new ApiError("auth.required", "Authentication required");
34
- if (rec.kind === "service") {
35
- return {
36
- principal: {
37
- kind: "service",
38
- tokenId: rec.id,
39
- orgId: rec.orgId,
40
- role: rec.role,
41
- },
42
- cookie: false,
43
- };
44
- }
45
- const account = await s.accounts.get(rec.accountId);
46
- if (!account)
47
- throw new ApiError("auth.required", "Authentication required");
35
+ if (bearer === undefined)
36
+ return undefined;
37
+ const rec = await s.tokens.authenticate(bearer);
38
+ if (!rec)
39
+ throw new ApiError("auth.required", "Authentication required");
40
+ if (rec.kind === "service") {
48
41
  return {
49
- principal: { kind: "user", account: requireActive(account), via: "pat", tokenId: rec.id },
50
- cookie: false,
42
+ kind: "service",
43
+ tokenId: rec.id,
44
+ orgId: rec.orgId,
45
+ role: rec.role,
51
46
  };
52
47
  }
48
+ const account = await s.accounts.get(rec.accountId);
49
+ if (!account)
50
+ throw new ApiError("auth.required", "Authentication required");
51
+ return { kind: "user", account: requireActive(account), via: "pat", tokenId: rec.id };
52
+ }
53
+ /** Resolves the credentials: undefined without any, the matching ApiError when they are invalid. */
54
+ async function resolvePrincipal(req, s) {
55
+ const viaToken = await resolveBearer(req, s);
56
+ if (viaToken !== undefined)
57
+ return { principal: viaToken, cookie: false };
53
58
  const at = req.cookies[ACCESS_COOKIE];
54
59
  if (at) {
55
60
  // 一条查询同时完成吊销检查与账号读取
@@ -101,17 +106,41 @@ export async function authenticateOrgUploader(req, s) {
101
106
  return resolved.principal;
102
107
  }
103
108
  /**
104
- * 全局守卫(`APP_GUARD`),默认拒绝:
105
- * 1. `Authorization: Bearer cap_pat_…|cap_svc_…` → API 令牌;个人令牌再实时读账号状态。不做 CSRF 检查。
106
- * 2. 否则 Cookie `cap_at` → 会话 access token(Redis 吊销标记作快速路径,再以 PG `sessions.revoked_at` 为准,
107
- * 与账号读取合并为一条查询)→ 实时判断账号状态;非安全方法要求 CSRF 头。
108
- * 3. 都没有:`@Public` 放行,否则 `auth.required`。`@Public` 路由上凭据无效(`ApiError`)按无凭据处理
109
- * (便于登出 / 刷新);PG / Redis 故障等其他异常照常抛出。
110
- * 4. 路由约束:service principal 只能访问 `@AllowService` 路由(否则 `forbidden`);
111
- * `@SessionOnly` 要求 Web 会话:个人令牌 → `auth.session_required`,服务令牌(即使路由经 `@OrgAction`
112
- * 隐含 `@AllowService`)→ `forbidden`;`@SuperAdmin` 要求超级管理员(`forbidden`)。
113
- * 5. `@Public` 路由的非安全方法无论是否带 Cookie 都要求 CSRF 头。
114
- * 账号状态每个请求都从 PG 实时读取,不在进程内缓存。插件路由 `/plugins/*` 不经过 Nest,不受此守卫约束。
109
+ * Before the body is read, for an extension `member` / `admin` route (plugin-route-access.ts): only
110
+ * a personal API token (`Authorization: Bearer cap_pat_…`) authenticates; a session cookie is
111
+ * ignored (no credential), so no CSRF check applies. No or an unknown token -> `auth.required`; a
112
+ * service token -> `forbidden`; a disabled account -> `auth.account_disabled`; one that must change
113
+ * its password -> `auth.password_change_required`. Returns the account, read live from PG.
114
+ */
115
+ export async function authenticatePersonalToken(req, s) {
116
+ const p = await resolveBearer(req, s);
117
+ if (p === undefined)
118
+ throw new ApiError("auth.required", "Authentication required");
119
+ if (p.kind === "service") {
120
+ throw new ApiError("forbidden", "Service tokens cannot access this endpoint");
121
+ }
122
+ if (p.account.mustChangePassword)
123
+ throw passwordChangeRequired();
124
+ return p.account;
125
+ }
126
+ /**
127
+ * The global guard (`APP_GUARD`), deny by default:
128
+ * 1. `Authorization: Bearer cap_pat_…|cap_svc_…` -> an API token; a personal token then reads the
129
+ * account state live. No CSRF check.
130
+ * 2. Otherwise the `cap_at` cookie -> a session access token (the Redis revocation marker as the
131
+ * fast path, then PG `sessions.revoked_at` decides, in one query with the account read) -> the
132
+ * account state live; unsafe methods need the CSRF header.
133
+ * 3. Neither: `@Public` passes, otherwise `auth.required`. On a `@Public` route an invalid
134
+ * credential (`ApiError`) counts as none (so logout / refresh work); other failures (PG / Redis
135
+ * down) are thrown as usual.
136
+ * 4. Route constraints: a service principal reaches only `@AllowService` routes (else
137
+ * `forbidden`); `@SessionOnly` needs a web session: a personal token -> `auth.session_required`,
138
+ * a service token (even where `@OrgAction` implies `@AllowService`) -> `forbidden`;
139
+ * `@SuperAdmin` needs a super admin (`forbidden`).
140
+ * 5. Unsafe methods of `@Public` routes need the CSRF header, cookie or not.
141
+ * The account state is read live from PG on every request, never cached in the process.
142
+ * Extension routes `/plugins/*` do not go through Nest or this guard: the plugin dispatch
143
+ * authenticates them by their declared access (plugin-route-access.ts, personal tokens only).
115
144
  */
116
145
  let AuthGuard = class AuthGuard {
117
146
  reflector;
@@ -37,6 +37,9 @@ export interface NamedThrottler {
37
37
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
38
38
  * credential: the device code is 32 random bytes). `POST …/guides/:guideId/checks/:checkId/run`
39
39
  * opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
40
+ *
41
+ * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
42
+ * methods on `public` extension routes (`PluginRouteAccess`).
40
43
  */
41
44
  export declare const NAMED_THROTTLERS: readonly NamedThrottler[];
42
45
  /** The storage key of a named throttler's counter for a tracker (shared by the guard and success paths). */
@@ -38,6 +38,9 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
38
38
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
39
39
  * credential: the device code is 32 random bytes). `POST …/guides/:guideId/checks/:checkId/run`
40
40
  * opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
41
+ *
42
+ * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
43
+ * methods on `public` extension routes (`PluginRouteAccess`).
41
44
  */
42
45
  export const NAMED_THROTTLERS = [
43
46
  // (login, IP): 10; an attacker filling one login from one IP leaves the owner's other IPs alone (R25)
@@ -181,6 +184,19 @@ export const NAMED_THROTTLERS = [
181
184
  code: "rate_limited",
182
185
  getTracker: (req) => sha256(principalAccountId(req)),
183
186
  },
187
+ // unsafe methods (POST / PUT / DELETE) on `public` extension routes, per extension and client
188
+ // address: 300 a minute (extension route access spec). Counted by the plugin dispatch before the
189
+ // body is read (PluginRouteAccess, fail-open like @Throttled); group and onSuccess are unused
190
+ {
191
+ name: "plugin-public-write",
192
+ group: "plugin-public-write",
193
+ onSuccess: "clear",
194
+ limit: 300,
195
+ ttl: 60_000,
196
+ message: "Too many requests to this extension route; try again in a minute",
197
+ code: "rate_limited",
198
+ getTracker: (req) => `${req.url.split("/")[2] ?? ""}:${ip(req)}`,
199
+ },
184
200
  ];
185
201
  /** The storage key of a named throttler's counter for a tracker (shared by the guard and success paths). */
186
202
  export const throttlerKey = (name, tracker) => sha256(`${name}:${tracker}`);
@@ -6,7 +6,8 @@ export declare function selectedThrottlers(context: ExecutionContext): readonly
6
6
  /**
7
7
  * Opts a route (or controller) in to the named throttlers `names` (see `NAMED_THROTTLERS`).
8
8
  * Throttling is per-route opt-in because the kernel limits only credential-checking routes today;
9
- * health, SSE and extension routes stay unlimited.
9
+ * health and SSE stay unlimited; extension routes are limited by the plugin dispatch itself
10
+ * (public writes only).
10
11
  */
11
12
  export declare const Throttled: (...names: string[]) => <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
12
13
  /**
@@ -22,7 +22,8 @@ export function selectedThrottlers(context) {
22
22
  /**
23
23
  * Opts a route (or controller) in to the named throttlers `names` (see `NAMED_THROTTLERS`).
24
24
  * Throttling is per-route opt-in because the kernel limits only credential-checking routes today;
25
- * health, SSE and extension routes stay unlimited.
25
+ * health and SSE stay unlimited; extension routes are limited by the plugin dispatch itself
26
+ * (public writes only).
26
27
  */
27
28
  export const Throttled = (...names) => {
28
29
  for (const n of names) {
@@ -14,6 +14,7 @@ import { TitlesModule } from "./conversations/titles.js";
14
14
  import { ExtensionsModule } from "./extensions/extensions.module.js";
15
15
  import { ApiModule } from "./http/api.module.js";
16
16
  import { ErrorFilterModule } from "./http/error-filter.module.js";
17
+ import { PluginRouteAccessModule } from "./http/plugin-route-access.js";
17
18
  import { IdentityModule } from "./identity/identity.module.js";
18
19
  import { CacheModule } from "./infra/cache/cache.module.js";
19
20
  import { ConfigModule } from "./infra/config/config.module.js";
@@ -118,6 +119,8 @@ let KernelModule = KernelModule_1 = class KernelModule {
118
119
  TitlesModule,
119
120
  UsageReportModule,
120
121
  ChannelsModule,
122
+ // the access check of extension routes (the plugin dispatch, api and gateway roles)
123
+ PluginRouteAccessModule,
121
124
  // client extensions: the client builds stored with extension packages
122
125
  ClientModule,
123
126
  // the @local sandbox provider, registered on every role (any replica may relay to a machine)
@@ -1,4 +1,5 @@
1
1
  import type { ExecResult, FileSystemHandle, SandboxHandle, SandboxLimits, SandboxProvider, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
+ import { ApiError } from "../errors.js";
2
3
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
4
  import type { KernelLogger } from "../log.js";
4
5
  import { SandboxService } from "../sandbox/sandbox.service.js";
@@ -17,6 +18,11 @@ export declare const OP_DEADLINE_MS = 30000;
17
18
  export declare const FRAME_ENVELOPE_BYTES: number;
18
19
  /** The most raw bytes whose base64 plus {@link FRAME_ENVELOPE_BYTES} fit in `maxFrameBytes`. */
19
20
  export declare const maxReadBytes: (maxFrameBytes: number) => number;
21
+ /**
22
+ * The device offers no projects (project root §4.1): a local machine whose `capybara-device`
23
+ * does not announce `projects`, or a cloud provider without `list` / `scan`.
24
+ */
25
+ export declare const projectsUnsupported: (local: boolean) => ApiError;
20
26
  /**
21
27
  * The refusal of a command on a machine whose local policy is auto mode while the organization (or
22
28
  * the platform) allows only sandbox mode (auto mode spec §4.3): re-checked at every exec, so a
@@ -54,7 +60,7 @@ export declare class LocalDeviceProvider implements SandboxProvider {
54
60
  private readonly log;
55
61
  readonly concurrentExec: true;
56
62
  readonly sessionIsolation = false;
57
- constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, grants: Pick<NetworkGrants, "forExec" | "reportedMode">, log: Pick<KernelLogger, "warn">);
63
+ constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots" | "machineFeatures">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, grants: Pick<NetworkGrants, "forExec" | "reportedMode">, log: Pick<KernelLogger, "warn">);
58
64
  createFileSystem(args: {
59
65
  name: string;
60
66
  limits: SandboxLimits;
@@ -106,6 +112,36 @@ export declare class LocalDeviceProvider implements SandboxProvider {
106
112
  size: number;
107
113
  isDir: boolean;
108
114
  } | null>;
115
+ /**
116
+ * Lists one directory on the machine (the `list` op, project root §4.1), read in the mode the
117
+ * kernel's current ceiling gives. A machine that did not announce `projects` throws
118
+ * `device.projects_unsupported` (never null, which would read as "does not exist").
119
+ */
120
+ list(h: SandboxHandle, path: string, opts: {
121
+ limit: number;
122
+ limits: Pick<SandboxLimits, "mode">;
123
+ signal: AbortSignal;
124
+ }): Promise<{
125
+ entries: {
126
+ name: string;
127
+ isDir: boolean;
128
+ }[];
129
+ truncated: boolean;
130
+ } | null>;
131
+ /**
132
+ * Looks for project-like directories under `base` on the machine (the `scan` op, project root
133
+ * §4.1), read in the mode the kernel's current ceiling gives. A machine that did not announce
134
+ * `projects` throws `device.projects_unsupported`.
135
+ */
136
+ scan(h: SandboxHandle, base: string, opts: {
137
+ limits: Pick<SandboxLimits, "mode">;
138
+ signal: AbortSignal;
139
+ }): Promise<{
140
+ path: string;
141
+ suggestedName: string;
142
+ }[]>;
143
+ /** The kernel never sends `list` or `scan` to a machine that did not announce `projects`. */
144
+ private requireProjects;
109
145
  /**
110
146
  * The device's org and the limits of one exec now (ruling R27): the effective policy's
111
147
  * `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
@@ -28,6 +28,13 @@ export const FRAME_ENVELOPE_BYTES = 64 * 1024;
28
28
  /** The most raw bytes whose base64 plus {@link FRAME_ENVELOPE_BYTES} fit in `maxFrameBytes`. */
29
29
  export const maxReadBytes = (maxFrameBytes) => Math.max(0, Math.floor((maxFrameBytes - FRAME_ENVELOPE_BYTES) / 4) * 3);
30
30
  const NAME_PREFIX = "cap-device-";
31
+ /**
32
+ * The device offers no projects (project root §4.1): a local machine whose `capybara-device`
33
+ * does not announce `projects`, or a cloud provider without `list` / `scan`.
34
+ */
35
+ export const projectsUnsupported = (local) => new ApiError("device.projects_unsupported", local
36
+ ? "This device's capybara-device does not support projects; update capybara-device on that machine and reconnect it."
37
+ : "This device's sandbox provider does not support projects; its conversations work without one.");
31
38
  /**
32
39
  * The refusal of a command on a machine whose local policy is auto mode while the organization (or
33
40
  * the platform) allows only sandbox mode (auto mode spec §4.3): re-checked at every exec, so a
@@ -167,6 +174,32 @@ let LocalDeviceProvider = class LocalDeviceProvider {
167
174
  async stat(h, path, signal) {
168
175
  return this.relay.call(h.id, "stat", { path }, { deadlineMs: OP_DEADLINE_MS, signal });
169
176
  }
177
+ /**
178
+ * Lists one directory on the machine (the `list` op, project root §4.1), read in the mode the
179
+ * kernel's current ceiling gives. A machine that did not announce `projects` throws
180
+ * `device.projects_unsupported` (never null, which would read as "does not exist").
181
+ */
182
+ async list(h, path, opts) {
183
+ await this.requireProjects(h.id);
184
+ opts.signal.throwIfAborted();
185
+ return this.relay.call(h.id, "list", { path, limit: opts.limit, limits: { mode: opts.limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
186
+ }
187
+ /**
188
+ * Looks for project-like directories under `base` on the machine (the `scan` op, project root
189
+ * §4.1), read in the mode the kernel's current ceiling gives. A machine that did not announce
190
+ * `projects` throws `device.projects_unsupported`.
191
+ */
192
+ async scan(h, base, opts) {
193
+ await this.requireProjects(h.id);
194
+ opts.signal.throwIfAborted();
195
+ return this.relay.call(h.id, "scan", { base, limits: { mode: opts.limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
196
+ }
197
+ /** The kernel never sends `list` or `scan` to a machine that did not announce `projects`. */
198
+ async requireProjects(deviceId) {
199
+ if (!(await this.targets.machineFeatures(deviceId)).includes("projects")) {
200
+ throw projectsUnsupported(true);
201
+ }
202
+ }
170
203
  /**
171
204
  * The device's org and the limits of one exec now (ruling R27): the effective policy's
172
205
  * `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
@@ -95,7 +95,8 @@ export declare class MachinesService {
95
95
  * device's mode and sandbox-mode allowlist; a change of what the owner sets, made on the machine
96
96
  * while it was away, is audited `device.policy_changed` / `device.mode_changed`
97
97
  * ({@link reportedPolicy}). The outcomes of its recent policy ops (`recentOps`) backfill the
98
- * platform's ops still pending on the row ({@link backfillOps}).
98
+ * platform's ops still pending on the row ({@link backfillOps}). The owner's home directory
99
+ * (`home`) replaces the stored one too (null when the hello has none).
99
100
  */
100
101
  recordHello(machineId: string, hello: DeviceHello, rawPolicy?: unknown): Promise<void>;
101
102
  /**
@@ -166,7 +166,8 @@ let MachinesService = class MachinesService {
166
166
  * device's mode and sandbox-mode allowlist; a change of what the owner sets, made on the machine
167
167
  * while it was away, is audited `device.policy_changed` / `device.mode_changed`
168
168
  * ({@link reportedPolicy}). The outcomes of its recent policy ops (`recentOps`) backfill the
169
- * platform's ops still pending on the row ({@link backfillOps}).
169
+ * platform's ops still pending on the row ({@link backfillOps}). The owner's home directory
170
+ * (`home`) replaces the stored one too (null when the hello has none).
170
171
  */
171
172
  async recordHello(machineId, hello, rawPolicy = hello.policy) {
172
173
  const self = await this.db
@@ -224,6 +225,8 @@ let MachinesService = class MachinesService {
224
225
  session_isolation: hello.sessionIsolation,
225
226
  features: deviceFeaturesOf(hello.features),
226
227
  local_policy: jsonOrNull(policy),
228
+ // the base of an auto-mode project's relative path (project root §4.2); absent: unknown
229
+ home: hello.home ?? null,
227
230
  last_seen_at: sql `now()`,
228
231
  })
229
232
  .where("id", "=", machineId)
@@ -3,6 +3,7 @@ const KNOWN_FEATURES = [
3
3
  "policyOp",
4
4
  "policyOpId",
5
5
  "mode",
6
+ "projects",
6
7
  ];
7
8
  /**
8
9
  * The known features in `v` (a hello's `features` or the stored column), in a fixed order and
@@ -12,6 +12,8 @@ export declare const deviceOffline: () => ApiError;
12
12
  * with `details: [{ reason: "machine_revoked" }]`, so the tools tell the model what to ask for.
13
13
  */
14
14
  export declare const machineRevoked: () => ApiError;
15
+ /** The text a machine's `policy` refusal reaches the model with. */
16
+ export declare const POLICY_REFUSAL_PREFIX = "Refused by the machine's local policy: ";
15
17
  /** The text a machine's `error` result reaches the model with (ruling R28). */
16
18
  export declare const ON_MACHINE_PREFIX = "On the connected machine: ";
17
19
  /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
@@ -24,6 +24,8 @@ export const deviceOffline = () => new ApiError("device.offline", "The machine o
24
24
  * with `details: [{ reason: "machine_revoked" }]`, so the tools tell the model what to ask for.
25
25
  */
26
26
  export const machineRevoked = () => new ApiError("device.forbidden", "The machine of this local device was disconnected. Run capybara-device logout, then capybara-device login on it, or pick another device.", [{ reason: "machine_revoked" }]);
27
+ /** The text a machine's `policy` refusal reaches the model with. */
28
+ export const POLICY_REFUSAL_PREFIX = "Refused by the machine's local policy: ";
27
29
  /** The text a machine's `error` result reaches the model with (ruling R28). */
28
30
  export const ON_MACHINE_PREFIX = "On the connected machine: ";
29
31
  /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
@@ -355,7 +357,7 @@ let LocalDeviceRelay = class LocalDeviceRelay {
355
357
  case "fs_gone":
356
358
  throw new FileSystemGoneError(message);
357
359
  case "policy":
358
- throw new ToolError(`Refused by the machine's local policy: ${message}`);
360
+ throw new ToolError(`${POLICY_REFUSAL_PREFIX}${message}`);
359
361
  default:
360
362
  throw new ToolError(`${ON_MACHINE_PREFIX}${message}`);
361
363
  }
@@ -1,4 +1,4 @@
1
- import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
1
+ import type { DeviceFeature, SandboxRoots } from "@capybara-hq/plugin-sdk";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  /**
4
4
  * Whether a local device can still be served: `active` (live and an unrevoked machine),
@@ -25,4 +25,9 @@ export declare class DeviceTargets {
25
25
  * active machine, or none reported yet).
26
26
  */
27
27
  machineRoots(deviceId: string): Promise<SandboxRoots | null>;
28
+ /**
29
+ * The features the device's active machine announced in its last hello (known ones only);
30
+ * empty without an active machine.
31
+ */
32
+ machineFeatures(deviceId: string): Promise<DeviceFeature[]>;
28
33
  }