@capybara-hq/kernel 0.1.0-rc.30 → 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.
Files changed (85) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplace-fetch.d.ts +5 -2
  3. package/dist/catalog/marketplace-fetch.js +4 -1
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/requests.service.d.ts +6 -5
  6. package/dist/catalog/requests.service.js +7 -6
  7. package/dist/config/load.d.ts +6 -0
  8. package/dist/config/load.js +26 -0
  9. package/dist/config/schema.js +5 -5
  10. package/dist/conversations/events.d.ts +10 -0
  11. package/dist/conversations/events.js +23 -1
  12. package/dist/ctx/create-ctx.d.ts +26 -4
  13. package/dist/ctx/create-ctx.js +54 -34
  14. package/dist/devices/devices.controller.js +3 -2
  15. package/dist/devices/devices.service.d.ts +17 -5
  16. package/dist/devices/devices.service.js +24 -13
  17. package/dist/devices/dto.d.ts +7 -6
  18. package/dist/devices/dto.js +6 -5
  19. package/dist/errors.d.ts +6 -1
  20. package/dist/errors.js +6 -1
  21. package/dist/evals/reconstruct.js +18 -8
  22. package/dist/extensions/bootstrap.d.ts +1 -1
  23. package/dist/extensions/bootstrap.js +7 -1
  24. package/dist/extensions/installs.js +4 -1
  25. package/dist/extensions/permission-set.d.ts +7 -6
  26. package/dist/extensions/permission-set.js +9 -6
  27. package/dist/extensions/permission-view.d.ts +4 -4
  28. package/dist/extensions/permission-view.js +10 -5
  29. package/dist/http/app.d.ts +8 -2
  30. package/dist/http/app.js +12 -2
  31. package/dist/http/plugin-dispatch.d.ts +55 -18
  32. package/dist/http/plugin-dispatch.js +124 -29
  33. package/dist/http/plugin-route-access.d.ts +56 -0
  34. package/dist/http/plugin-route-access.js +192 -0
  35. package/dist/identity/auth.guard.d.ts +26 -12
  36. package/dist/identity/auth.guard.js +62 -33
  37. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  38. package/dist/infra/throttler/named-throttlers.js +16 -0
  39. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  40. package/dist/infra/throttler/throttler.guard.js +2 -1
  41. package/dist/kernel.module.js +3 -0
  42. package/dist/lifecycle/kernel-lifecycle.js +1 -3
  43. package/dist/net/public-address.d.ts +14 -4
  44. package/dist/net/public-address.js +22 -12
  45. package/dist/net/safe-fetch.d.ts +2 -1
  46. package/dist/net/safe-fetch.js +16 -4
  47. package/dist/overrides.d.ts +3 -0
  48. package/dist/overrides.js +2 -0
  49. package/dist/packages/npm.d.ts +28 -9
  50. package/dist/packages/npm.js +30 -19
  51. package/dist/packages/provenance.d.ts +3 -1
  52. package/dist/packages/provenance.js +7 -3
  53. package/dist/platform/ops/devices.ops.js +1 -1
  54. package/dist/platform/ops/platform.ops.d.ts +3 -1
  55. package/dist/platform/ops/platform.ops.js +11 -13
  56. package/dist/runtime/context/build.d.ts +10 -1
  57. package/dist/runtime/context/build.js +44 -10
  58. package/dist/runtime/context/compaction.d.ts +27 -8
  59. package/dist/runtime/context/compaction.js +133 -58
  60. package/dist/runtime/context/fit.d.ts +54 -22
  61. package/dist/runtime/context/fit.js +116 -40
  62. package/dist/runtime/model-call.d.ts +0 -8
  63. package/dist/runtime/model-call.js +185 -83
  64. package/dist/sandbox/review/classifier.d.ts +2 -0
  65. package/dist/sandbox/review/classifier.js +12 -1
  66. package/dist/sandbox/review/index.d.ts +3 -3
  67. package/dist/sandbox/review/index.js +3 -3
  68. package/dist/sandbox/review/review.service.d.ts +12 -4
  69. package/dist/sandbox/review/review.service.js +88 -19
  70. package/dist/sandbox/review/rules.d.ts +6 -0
  71. package/dist/sandbox/review/rules.js +1013 -95
  72. package/dist/sandbox/review/types.d.ts +21 -4
  73. package/dist/sandbox/review/types.js +41 -5
  74. package/dist/sandbox/sandbox.service.d.ts +8 -7
  75. package/dist/sandbox/sandbox.service.js +16 -16
  76. package/dist/setup/kernel-checks.js +3 -2
  77. package/dist/setup/oauth-token-probe.d.ts +1 -8
  78. package/dist/setup/oauth-token-probe.js +0 -16
  79. package/dist/tools/builtins/sandbox/common.d.ts +1 -1
  80. package/dist/tools/builtins/sandbox/common.js +1 -1
  81. package/dist/tools/builtins/tool-search.js +4 -3
  82. package/dist/tools/oauth/discovery.d.ts +38 -16
  83. package/dist/tools/oauth/discovery.js +59 -33
  84. package/dist/tools/pipeline.js +17 -13
  85. package/package.json +3 -3
@@ -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)
@@ -37,7 +37,6 @@ import { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA } from "../kernel.js";
37
37
  import { GatewayRole } from "../roles/gateway-role.js";
38
38
  import { WorkerRole } from "../roles/worker-role.js";
39
39
  import { UsageReporter } from "../runtime/usage-report.js";
40
- import { readDevicesAutoMode } from "../sandbox/platform-auto-mode.js";
41
40
  import { sandboxConfigWarnings } from "../sandbox/sandbox.service.js";
42
41
  import { warnLegacyToolKeys } from "../tools/legacy-data.js";
43
42
  import { KERNEL_APP_OPTIONS } from "./tokens.js";
@@ -248,8 +247,7 @@ let KernelLifecycle = class KernelLifecycle {
248
247
  .list("sandbox")
249
248
  .find((x) => x.capability === SANDBOX_EXTENSION_POINT);
250
249
  if (sandboxEntry !== undefined) {
251
- const autoAllowed = (await readDevicesAutoMode(this.kdb.db, this.configService, this.log)).mode === "allowed";
252
- for (const w of sandboxConfigWarnings(cfg(), sandboxEntry.plugin, autoAllowed)) {
250
+ for (const w of sandboxConfigWarnings(cfg(), sandboxEntry.plugin)) {
253
251
  this.log[w.level](w.message);
254
252
  }
255
253
  }
@@ -16,7 +16,11 @@ export type NetPolicy = {
16
16
  * name that resolves there (an attacker's name could point into the range).
17
17
  */
18
18
  allowPrivateHosts: string[];
19
- /** Origins configured by the admin (the npm registry): their hosts may resolve to private addresses. */
19
+ /**
20
+ * Origins configured by the admin (the npm registry): a request to exactly such an origin
21
+ * (scheme, host and port) may resolve to private addresses, and an origin configured as
22
+ * `http://` may be fetched over http. The same host on another port or scheme is not trusted.
23
+ */
20
24
  trustedOrigins: string[];
21
25
  /**
22
26
  * `net.httpsProxy` / `net.noProxy`: https downloads tunnel through this proxy (see `proxy.ts`);
@@ -36,7 +40,11 @@ export type NetDeniedCode = "net.private_address" | "net.dns_failed" | "net.redi
36
40
  export declare class NetDeniedError extends Error {
37
41
  readonly code: NetDeniedCode;
38
42
  readonly host: string;
39
- constructor(code: NetDeniedCode, host: string, message: string);
43
+ /** The HTTP status of a refused redirect (`net.redirect`). */
44
+ readonly status?: number | undefined;
45
+ constructor(code: NetDeniedCode, host: string, message: string,
46
+ /** The HTTP status of a refused redirect (`net.redirect`). */
47
+ status?: number | undefined);
40
48
  }
41
49
  /** The shortest prefix an `allowPrivateHosts` CIDR may have, per family. */
42
50
  export declare const MIN_CIDR_PREFIX: {
@@ -54,7 +62,9 @@ export declare function privateHostEntryProblem(entry: string): string | null;
54
62
  export declare function isPrivateHostEntry(entry: string): boolean;
55
63
  /**
56
64
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
57
- * after checking that each is public or exempt by `policy`. Throws {@link NetDeniedError}
65
+ * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
66
+ * only when it equals a `policy.trustedOrigins` entry does that trust apply (without it, trusted
67
+ * origins exempt nothing). Throws {@link NetDeniedError}
58
68
  * `net.dns_failed` (no answer) or `net.private_address` (some address is private and not exempt).
59
69
  */
60
- export declare function resolvePublic(host: string, policy: NetPolicy, lookup?: LookupFn): Promise<string[]>;
70
+ export declare function resolvePublic(host: string, policy: NetPolicy, lookup?: LookupFn, origin?: string): Promise<string[]>;
@@ -140,10 +140,14 @@ export function isLoopbackHost(host) {
140
140
  export class NetDeniedError extends Error {
141
141
  code;
142
142
  host;
143
- constructor(code, host, message) {
143
+ status;
144
+ constructor(code, host, message,
145
+ /** The HTTP status of a refused redirect (`net.redirect`). */
146
+ status) {
144
147
  super(message);
145
148
  this.code = code;
146
149
  this.host = host;
150
+ this.status = status;
147
151
  this.name = "NetDeniedError";
148
152
  }
149
153
  }
@@ -187,7 +191,7 @@ export function privateHostEntryProblem(entry) {
187
191
  export function isPrivateHostEntry(entry) {
188
192
  return privateHostEntryProblem(entry) === null;
189
193
  }
190
- function exemptions(host, policy) {
194
+ function exemptions(host, policy, origin) {
191
195
  const cidrs = new BlockList();
192
196
  let all = false;
193
197
  const literal = isIP(host) !== 0;
@@ -214,13 +218,17 @@ function exemptions(host, policy) {
214
218
  all = true;
215
219
  }
216
220
  }
217
- for (const origin of policy.trustedOrigins) {
218
- try {
219
- if (normalizeHost(new URL(origin).hostname) === host)
220
- all = true;
221
- }
222
- catch {
223
- // an unparseable origin trusts nothing
221
+ // a trusted origin exempts that exact origin (scheme, host and port), never its host on
222
+ // another port or scheme: a manifest URL there is judged like any other host
223
+ if (origin !== undefined) {
224
+ for (const trusted of policy.trustedOrigins) {
225
+ try {
226
+ if (new URL(trusted).origin === origin)
227
+ all = true;
228
+ }
229
+ catch {
230
+ // an unparseable origin trusts nothing
231
+ }
224
232
  }
225
233
  }
226
234
  return { all, cidrs };
@@ -242,10 +250,12 @@ function allowedBy(cidrs, ip) {
242
250
  }
243
251
  /**
244
252
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
245
- * after checking that each is public or exempt by `policy`. Throws {@link NetDeniedError}
253
+ * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
254
+ * only when it equals a `policy.trustedOrigins` entry does that trust apply (without it, trusted
255
+ * origins exempt nothing). Throws {@link NetDeniedError}
246
256
  * `net.dns_failed` (no answer) or `net.private_address` (some address is private and not exempt).
247
257
  */
248
- export async function resolvePublic(host, policy, lookup = defaultLookup) {
258
+ export async function resolvePublic(host, policy, lookup = defaultLookup, origin) {
249
259
  const h = normalizeHost(host);
250
260
  let addrs;
251
261
  if (isIP(h) !== 0) {
@@ -261,7 +271,7 @@ export async function resolvePublic(host, policy, lookup = defaultLookup) {
261
271
  if (addrs.length === 0)
262
272
  throw new NetDeniedError("net.dns_failed", h, `Cannot resolve ${h}.`);
263
273
  }
264
- const ex = exemptions(h, policy);
274
+ const ex = exemptions(h, policy, origin);
265
275
  const refused = (a) => isForbiddenAddress(a) && (isLinkLocalAddress(a) || (!ex.all && !allowedBy(ex.cidrs, a)));
266
276
  if (addrs.some(refused)) {
267
277
  throw new NetDeniedError("net.private_address", h, addrs.some(isLinkLocalAddress)
@@ -2,7 +2,8 @@ import { Agent } from "undici";
2
2
  import { type LookupFn, type NetPolicy } from "./public-address.js";
3
3
  /**
4
4
  * `fetch` for URLs that come from a marketplace or an admin (spec §5.1):
5
- * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing);
5
+ * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing), or
6
+ * to exactly a `trustedOrigins` origin the admin configured as http (an internal npm registry);
6
7
  * - the host is resolved once by {@link resolvePublic} and the connection goes to the checked
7
8
  * addresses: a per-request undici `Agent` whose `connect.lookup` answers only those addresses,
8
9
  * so there is no second DNS lookup (no rebinding), while the Host header and TLS SNI keep the
@@ -4,7 +4,8 @@ import { bypassesProxy, proxyAgent } from "./proxy.js";
4
4
  import { isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from "./public-address.js";
5
5
  /**
6
6
  * `fetch` for URLs that come from a marketplace or an admin (spec §5.1):
7
- * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing);
7
+ * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing), or
8
+ * to exactly a `trustedOrigins` origin the admin configured as http (an internal npm registry);
8
9
  * - the host is resolved once by {@link resolvePublic} and the connection goes to the checked
9
10
  * addresses: a per-request undici `Agent` whose `connect.lookup` answers only those addresses,
10
11
  * so there is no second DNS lookup (no rebinding), while the Host header and TLS SNI keep the
@@ -47,6 +48,15 @@ export function pinnedAgent(ips, tls = {}) {
47
48
  connect: { lookup: pinnedLookup(ips), ...(tls.ca !== undefined && { ca: tls.ca }) },
48
49
  });
49
50
  }
51
+ /** The origin of a configured URL; null when it does not parse (it then trusts nothing). */
52
+ function originOf(url) {
53
+ try {
54
+ return new URL(url).origin;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
50
60
  const NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);
51
61
  function capBody(body, maxBytes) {
52
62
  let seen = 0;
@@ -69,7 +79,9 @@ export async function safeFetch(url, init, policy, opts = {}) {
69
79
  throw new NetDeniedError("net.insecure_url", "", "The URL is not valid.");
70
80
  }
71
81
  const host = normalizeHost(target.hostname);
72
- const insecureOk = policy.allowInsecureLoopback && target.protocol === "http:" && isLoopbackHost(host);
82
+ const insecureOk = target.protocol === "http:" &&
83
+ ((policy.allowInsecureLoopback && isLoopbackHost(host)) ||
84
+ policy.trustedOrigins.some((o) => originOf(o) === target.origin));
73
85
  if (target.protocol !== "https:" && !insecureOk) {
74
86
  throw new NetDeniedError("net.insecure_url", host, `The URL must use https (${host}).`);
75
87
  }
@@ -89,7 +101,7 @@ export async function safeFetch(url, init, policy, opts = {}) {
89
101
  try {
90
102
  // behind the proxy only an IP literal is checked here (no lookup); the proxy resolves names
91
103
  if (!proxied || isIP(host) !== 0) {
92
- ips = await Promise.race([resolvePublic(host, policy, opts.lookup), aborted]);
104
+ ips = await Promise.race([resolvePublic(host, policy, opts.lookup, target.origin), aborted]);
93
105
  }
94
106
  }
95
107
  finally {
@@ -116,7 +128,7 @@ export async function safeFetch(url, init, policy, opts = {}) {
116
128
  void agent.close().catch(() => { });
117
129
  if (res.status >= 300 && res.status < 400 && res.status !== 304) {
118
130
  await res.body?.cancel().catch(() => { });
119
- throw new NetDeniedError("net.redirect", host, `${host} responded with a redirect (${res.status}); redirects are not followed.`);
131
+ throw new NetDeniedError("net.redirect", host, `${host} responded with a redirect (${res.status}); redirects are not followed.`, res.status);
120
132
  }
121
133
  const max = opts.maxBytes;
122
134
  if (max !== undefined) {
@@ -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
  ];
@@ -1,11 +1,20 @@
1
+ import { type LookupFn, type NetPolicy } from "../net/public-address.js";
1
2
  /**
2
- * 从 npm registry 下载插件包(D14 / C21 / C26)。registry 地址来自配置(可信),但它返回的内容一律当作外部输入:
3
- * - 不跟随重定向(3xx 直接失败):否则 registry 的一次重定向就能把下载(连同令牌)引到任意地址;
4
- * - 元数据与 tarball 都边读边计数,超过上限立即中止;
5
- * - 没有 `opts` 时 tarball 必须与 registry 同源(令牌只发往该源),并按 packument 的 `dist.integrity`
6
- * (sha512 SRI)校验;给了 `opts.expectedIntegrity`(清单引入,T24)时只认它;
7
- * - `opts.tarballUrl`(清单直接给出的下载地址)必须是 https,测试里可经 `allowInsecureLoopback` 允许回环 http,
8
- * 且必须同时给出 `expectedIntegrity`;不会带 registry 令牌。
3
+ * Downloads plugin packages from an npm registry (D14 / C21 / C26). The registry URL comes from
4
+ * the config (trusted), but whatever it returns is external input:
5
+ * - every request goes through `packages/kernel/src/net` ({@link safeFetch}) under `cfg.net`
6
+ * (the kernel passes `marketplaceNetPolicy`: the registry's origin is trusted, any other host
7
+ * must resolve to public addresses unless `marketplaces.allowPrivateHosts` exempts it, https
8
+ * tunnels through `net.httpsProxy`, and the connection is pinned to the checked address);
9
+ * - redirects are never followed (a 3xx fails): one registry redirect could otherwise send the
10
+ * download (and the token) anywhere;
11
+ * - metadata and tarball are counted while read and aborted past their caps;
12
+ * - without `opts` the tarball must be on the registry's origin (the only origin the token goes
13
+ * to) and is verified against the packument's `dist.integrity` (sha512 SRI); with
14
+ * `opts.expectedIntegrity` (marketplace imports, T24) only that integrity counts;
15
+ * - `opts.tarballUrl` (a download URL the marketplace gives) must be https (loopback http in tests
16
+ * under `net.allowInsecureLoopback`), needs `expectedIntegrity`, and never gets the registry
17
+ * token unless it is on the registry's origin.
9
18
  */
10
19
  /** 下载或校验失败(HTTP 层映射为 `packages.npm_failed`,502)。消息为英文,不含令牌。 */
11
20
  export declare class NpmFetchError extends Error {
@@ -28,13 +37,23 @@ export interface NpmFetchConfig {
28
37
  registry: string;
29
38
  token?: string;
30
39
  maxBytes: number;
31
- /** 只供测试:允许 `opts.tarballUrl` 用回环地址上的 http。 */
32
- allowInsecureLoopback?: boolean;
40
+ /**
41
+ * The network rules of every request (`marketplaceNetPolicy` in the kernel, which trusts the
42
+ * registry's origin). `allowInsecureLoopback` also lets `opts.tarballUrl` use loopback http.
43
+ */
44
+ net: NetPolicy;
45
+ /** Tests only: replaces the DNS lookup. */
46
+ lookup?: LookupFn;
33
47
  }
34
48
  /** 回环地址(`localhost`、`127.*`、`::1`)。 */
35
49
  export declare const isLoopback: (host: string) => boolean;
36
50
  /** 读响应体,累计超过 `max` 立即取消并抛 `onTooLarge()`。 */
37
51
  export declare function readCapped(res: Response, max: number, onTooLarge: () => Error): Promise<Buffer>;
52
+ /**
53
+ * One GET through {@link safeFetch} under `cfg.net` (no redirects, the network rules); a refusal,
54
+ * a network error or a non-2xx answer is an {@link NpmFetchError} with an English message.
55
+ */
56
+ export declare function npmGet(cfg: Pick<NpmFetchConfig, "net" | "lookup">, url: URL, headers: Record<string, string>, signal: AbortSignal, what: string): Promise<Response>;
38
57
  /**
39
58
  * 下载 `name@version`(`version` 可以是精确版本、dist-tag 或范围,缺省 `latest`),返回 tgz 字节、解析出的版本与
40
59
  * 实际校验所用的 integrity。失败抛 {@link NpmFetchError}(含 {@link IntegrityMismatchError})或