@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.
@@ -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)
@@ -10,6 +10,7 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
10
10
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
11
11
  import { GIT_UPSTREAM_ORIGIN, type GitUpstreamOrigin } from "./git/gateway.js";
12
12
  import { GIT_IDENTITY_API_BASE, type GitIdentityApiBase } from "./git/identity.js";
13
+ import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
13
14
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
14
15
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
15
16
  import { OUTBOX_STRICT_CONFLICTS } from "./infra/outbox/outbox.service.js";
@@ -54,6 +55,7 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
54
55
  * direct call after a commit skipped by a crash);
55
56
  * - `DEVICE_POLICY_AFTER_CALL`: called after a device policy op's call, before its outcome is
56
57
  * recorded (throwing stands for a crash between the call and the resolve transaction);
58
+ * - `PLUGIN_PUBLIC_WRITE_LIMIT`: a lower limit for unsafe methods on `public` extension routes;
57
59
  * - `SCOPE_BACKSTOP_DELAY`: the delay of a confirmation's scope sync backstop (ruling R24);
58
60
  * - `APP_INTERCEPTOR`: one more global interceptor (a probe of the matched routes).
59
61
  */
@@ -81,6 +83,7 @@ interface KernelSeams {
81
83
  [OUTBOX_FAST_PATH_SETTLED]: (pass: Promise<void>) => void;
82
84
  [ENSURE_RUN_FAILS]: () => boolean;
83
85
  [SCOPE_BACKSTOP_DELAY]: number;
86
+ [PLUGIN_PUBLIC_WRITE_LIMIT]: number;
84
87
  [DEVICE_POLICY_AFTER_CALL]: (opId: string) => void;
85
88
  [APP_INTERCEPTOR]: NestInterceptor;
86
89
  }
package/dist/overrides.js CHANGED
@@ -8,6 +8,7 @@ import { USAGE_SUBSCRIBERS_CLOCK } from "./extensions/usage-subscribers.js";
8
8
  import { FILE_PREVIEW_TIMEOUT } from "./files/previewers.js";
9
9
  import { GIT_UPSTREAM_ORIGIN } from "./git/gateway.js";
10
10
  import { GIT_IDENTITY_API_BASE } from "./git/identity.js";
11
+ import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
11
12
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
12
13
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
13
14
  import { OUTBOX_STRICT_CONFLICTS } from "./infra/outbox/outbox.service.js";
@@ -47,6 +48,7 @@ const SEAM_TOKENS = [
47
48
  OUTBOX_FAST_PATH_SETTLED,
48
49
  ENSURE_RUN_FAILS,
49
50
  SCOPE_BACKSTOP_DELAY,
51
+ PLUGIN_PUBLIC_WRITE_LIMIT,
50
52
  DEVICE_POLICY_AFTER_CALL,
51
53
  APP_INTERCEPTOR,
52
54
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.31",
3
+ "version": "0.1.0-rc.32",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.22"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.23"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,7 +74,7 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/testing": "0.1.0-rc.18"
77
+ "@capybara-hq/testing": "0.1.0-rc.19"
78
78
  },
79
79
  "scripts": {
80
80
  "build": "tsc -b"