@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
@@ -25,7 +25,7 @@ import { MachinesService } from "../local-devices/machines.js";
25
25
  import { deviceFeaturesOf, localModeOf, localPolicyOf } from "../local-devices/policy-summary.js";
26
26
  import { readOrgSettings } from "../orgs/settings.service.js";
27
27
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
28
- import { effectiveDevicePolicy, readDeploymentDevicePolicy, } from "../sandbox/modes.js";
28
+ import { deviceNetwork, effectiveDevicePolicy, readDeploymentDevicePolicy, } from "../sandbox/modes.js";
29
29
  import { isInternalProvider, LOCAL_PROVIDER, SandboxProviders } from "../sandbox/providers.js";
30
30
  import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
31
31
  import { DeviceAccess, demotedProvider, deviceProvider, deviceUnavailable, inUseForDefault, } from "./access.js";
@@ -261,27 +261,29 @@ let DevicesService = class DevicesService {
261
261
  async updateIn(orgId, accountId, id, patch, actorTokenId) {
262
262
  const before = await this.lockOwn(orgId, accountId, id);
263
263
  if (patch.mode !== undefined) {
264
- // A cloud device's switch only narrows (auto → sandbox); a local device's mode lives on its
265
- // machine (auto mode spec §4.3).
264
+ // A cloud device's owner narrows it to sandbox or clears the choice to follow the org (auto
265
+ // mode spec §4.3, hardening D2); a local device's mode lives on its machine.
266
266
  if (before.source !== "cloud") {
267
267
  throw new ApiError("device.mode_on_device", "This device's mode is kept on its connected machine: switch to sandbox mode from the device page (sent to the machine) or run capybara-device mode sandbox there.");
268
268
  }
269
- if (before.mode !== "sandbox") {
270
- // `from` is the mode it ran at before, which may already be sandbox (the org turned it off)
271
- const effective = await this.sandbox.devicePolicy({ orgId, deviceId: id });
269
+ if ((before.mode ?? null) !== patch.mode) {
270
+ // `from` / `to` are the modes it runs at: the org may cap both at sandbox, and then the
271
+ // stored choice changes without a mode change, so nothing is audited
272
+ const from = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
272
273
  await this.db
273
274
  .updateTable("devices")
274
- .set({ mode: "sandbox", updated_at: sql `now()` })
275
+ .set({ mode: patch.mode, updated_at: sql `now()` })
275
276
  .where("id", "=", id)
276
277
  .execute();
277
- if (effective.mode !== "sandbox") {
278
+ const to = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
279
+ if (from !== to) {
278
280
  await audit(this.db.db, {
279
281
  actorAccountId: accountId,
280
282
  ...(actorTokenId !== undefined && { actorTokenId }),
281
283
  orgId,
282
284
  action: "device.mode_changed",
283
285
  target: id,
284
- detail: { from: effective.mode, to: "sandbox", by: accountId, via: "web" },
286
+ detail: { from, to, by: accountId, via: "web" },
285
287
  });
286
288
  }
287
289
  }
@@ -487,8 +489,13 @@ let DevicesService = class DevicesService {
487
489
  if (inUseForDefault(live) || current === undefined)
488
490
  return live.id;
489
491
  const former = await this.formerDefaults(orgId, accountId, current);
490
- if (!former.some((f) => f.holdsFiles))
491
- return live.id;
492
+ // Two unlocked reads: a swap committed between them leaves `live` demoted and the restored
493
+ // default out of `former`. Only a default still live after `former` is the answer; else
494
+ // the locked path decides.
495
+ if (!former.some((f) => f.holdsFiles)) {
496
+ if ((await this.defaultOf(orgId, accountId))?.id === live.id)
497
+ return live.id;
498
+ }
492
499
  }
493
500
  return this.insertDefault(orgId, accountId);
494
501
  }
@@ -766,9 +773,10 @@ let DevicesService = class DevicesService {
766
773
  readDeploymentDevicePolicy(this.db.db, this.config),
767
774
  ]);
768
775
  const summaryOf = (r) => r.source === "local" ? localPolicyOf(r.machine_local_policy) : null;
769
- /** The mode the device chose: its machine's report (local) or its switch (cloud, sandbox only). */
776
+ /** The mode the device chose: its machine's report (local) or its switch (cloud: sandbox, or null to follow the org). */
770
777
  const chosenOf = (r) => r.source === "local" ? localModeOf(r.machine_features, r.machine_local_policy) : r.mode;
771
778
  const policyOf = (r) => effectiveDevicePolicy(deployment, settings, chosenOf(r));
779
+ const sandboxNetwork = deviceNetwork(deployment, settings, "sandbox");
772
780
  // each device's limits and its instance's pending change
773
781
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
774
782
  const policy = policyOf(r);
@@ -827,6 +835,7 @@ let DevicesService = class DevicesService {
827
835
  pendingNextUse: perDevice.get(r.id)?.state.pendingNextUse ?? false,
828
836
  pendingFilesReset: perDevice.get(r.id)?.state.pendingFilesReset ?? false,
829
837
  recent: recent.get(r.id) ?? [],
838
+ sandboxNetwork,
830
839
  }, this.config.get().sandbox.limits.egress === "none"),
831
840
  // a local device's machine decides it; cloud devices have none in phase 2
832
841
  sessionIsolation: r.machine_session_isolation ?? false,
@@ -1030,6 +1039,7 @@ function modeChangeOf(action, at, d, by) {
1030
1039
  export function deviceModeViewOf(policy, settings, local, summary, extra,
1031
1040
  /** The platform kill switch (`sandbox.limits.egress: none`): the network is the platform's. */
1032
1041
  killSwitch = false) {
1042
+ const { sandboxNetwork, ...rest } = extra;
1033
1043
  const networkKind = local ? "allowlist" : policy.network.kind;
1034
1044
  const org = settings.cloudNetwork;
1035
1045
  // "org" only when the org supplied what is in effect: the kill switch always wins; auto mode
@@ -1064,6 +1074,7 @@ killSwitch = false) {
1064
1074
  allowedDomains: [...(summary?.allowedDomains ?? [])],
1065
1075
  }
1066
1076
  : null,
1067
- ...extra,
1077
+ sandboxNetwork: local ? null : { kind: sandboxNetwork.kind, hosts: [...sandboxNetwork.hosts] },
1078
+ ...rest,
1068
1079
  };
1069
1080
  }
@@ -8,14 +8,15 @@ export declare const DeviceParams: z.ZodObject<{
8
8
  id: z.ZodString;
9
9
  }, z.core.$strip>;
10
10
  /**
11
- * `PATCH /devices/:id`: a new name, and a cloud device's narrowing `mode` (`sandbox` only: auto
12
- * mode is never set from the web, auto mode spec §4.3). A local device's mode lives on its machine,
13
- * so the service refuses a `mode` for it (`device.mode_on_device`). The mode is a person's choice
14
- * in a web session: an API token gets `auth.session_required`.
11
+ * `PATCH /devices/:id`: a new name, and a cloud device's `mode`: `sandbox` narrows it, `null`
12
+ * follows the org and the platform again (auto when they allow it; hardening spec D2). `auto` is
13
+ * never stored. A local device's mode lives on its machine, so the service refuses a `mode` for it
14
+ * (`device.mode_on_device`). The mode is a person's choice in a web session: an API token gets
15
+ * `device.mode_requires_session`, and the Platform operation (`devices.rename`) omits it.
15
16
  */
16
17
  export declare const DevicePatchBody: z.ZodObject<{
17
18
  name: z.ZodOptional<z.ZodString>;
18
- mode: z.ZodOptional<z.ZodLiteral<"sandbox">>;
19
+ mode: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"sandbox">>>;
19
20
  }, z.core.$strict>;
20
21
  /**
21
22
  * `POST /devices/:id/policy` (network ask-to-allow spec §7; auto mode spec §4.1): the device
@@ -35,7 +36,7 @@ export declare class DeviceCreateBodyDto extends DeviceCreateBodyDto_base {
35
36
  }
36
37
  declare const DevicePatchBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
37
38
  name: z.ZodOptional<z.ZodString>;
38
- mode: z.ZodOptional<z.ZodLiteral<"sandbox">>;
39
+ mode: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"sandbox">>>;
39
40
  }, z.core.$strict>>;
40
41
  export declare class DevicePatchBodyDto extends DevicePatchBodyDto_base {
41
42
  }
@@ -7,13 +7,14 @@ export const DeviceName = z.string().trim().min(1).max(64);
7
7
  export const DeviceNameBody = z.object({ name: DeviceName }).strict();
8
8
  export const DeviceParams = z.object({ id: z.string().min(1).max(100) });
9
9
  /**
10
- * `PATCH /devices/:id`: a new name, and a cloud device's narrowing `mode` (`sandbox` only: auto
11
- * mode is never set from the web, auto mode spec §4.3). A local device's mode lives on its machine,
12
- * so the service refuses a `mode` for it (`device.mode_on_device`). The mode is a person's choice
13
- * in a web session: an API token gets `auth.session_required`.
10
+ * `PATCH /devices/:id`: a new name, and a cloud device's `mode`: `sandbox` narrows it, `null`
11
+ * follows the org and the platform again (auto when they allow it; hardening spec D2). `auto` is
12
+ * never stored. A local device's mode lives on its machine, so the service refuses a `mode` for it
13
+ * (`device.mode_on_device`). The mode is a person's choice in a web session: an API token gets
14
+ * `device.mode_requires_session`, and the Platform operation (`devices.rename`) omits it.
14
15
  */
15
16
  export const DevicePatchBody = z
16
- .object({ name: DeviceName.optional(), mode: z.literal("sandbox").optional() })
17
+ .object({ name: DeviceName.optional(), mode: z.literal("sandbox").nullable().optional() })
17
18
  .strict()
18
19
  .refine((b) => b.name !== undefined || b.mode !== undefined, {
19
20
  message: "Give at least one of name or mode",
package/dist/errors.d.ts CHANGED
@@ -334,7 +334,7 @@ export declare const ERROR_CODES: {
334
334
  readonly "attachment.too_many_pending": 429;
335
335
  readonly "sandbox.unavailable": 503;
336
336
  readonly "sandbox.busy": 409;
337
- /** A cloud sandbox provider refused an instance with the open public network (its `openEgress` is `off`). */
337
+ /** A cloud sandbox provider refused an instance with the open public network. */
338
338
  readonly "sandbox.open_network_refused": 409;
339
339
  /** A cloud sandbox provider failed to create a device's sandbox for another reason. */
340
340
  readonly "sandbox.create_failed": 502;
@@ -386,6 +386,11 @@ export declare const ERROR_CODES: {
386
386
  * (`capybara-device mode` or the device page's policy op), and a cloud device has none to choose.
387
387
  */
388
388
  readonly "device.mode_on_device": 409;
389
+ /**
390
+ * A cloud device's mode (`PATCH /devices/:id` `mode`, sandbox or null) sent with an API token:
391
+ * only its owner in a web session changes it (hardening spec D2, K4).
392
+ */
393
+ readonly "device.mode_requires_session": 403;
389
394
  /** Device sign-in (RFC 8628 style): the person has not approved the code yet; keep polling. */
390
395
  readonly "device_sign_in.authorization_pending": 400;
391
396
  /** Device sign-in: the program polls faster than the interval; add 5 seconds and keep polling. */
package/dist/errors.js CHANGED
@@ -334,7 +334,7 @@ export const ERROR_CODES = {
334
334
  "attachment.too_many_pending": 429,
335
335
  "sandbox.unavailable": 503,
336
336
  "sandbox.busy": 409,
337
- /** A cloud sandbox provider refused an instance with the open public network (its `openEgress` is `off`). */
337
+ /** A cloud sandbox provider refused an instance with the open public network. */
338
338
  "sandbox.open_network_refused": 409,
339
339
  /** A cloud sandbox provider failed to create a device's sandbox for another reason. */
340
340
  "sandbox.create_failed": 502,
@@ -386,6 +386,11 @@ export const ERROR_CODES = {
386
386
  * (`capybara-device mode` or the device page's policy op), and a cloud device has none to choose.
387
387
  */
388
388
  "device.mode_on_device": 409,
389
+ /**
390
+ * A cloud device's mode (`PATCH /devices/:id` `mode`, sandbox or null) sent with an API token:
391
+ * only its owner in a web session changes it (hardening spec D2, K4).
392
+ */
393
+ "device.mode_requires_session": 403,
389
394
  /** Device sign-in (RFC 8628 style): the person has not approved the code yet; keep polling. */
390
395
  "device_sign_in.authorization_pending": 400,
391
396
  /** Device sign-in: the program polls faster than the interval; add 5 seconds and keep polling. */
@@ -4,7 +4,7 @@ import { sameModel, selectionAt } from "../conversations/selection.js";
4
4
  import { ApiError } from "../errors.js";
5
5
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
6
6
  import { mediaRefs, planMedia, } from "../runtime/context/build.js";
7
- import { applyFit, clampOutput, planFit } from "../runtime/context/fit.js";
7
+ import { applyFit, estimateAfterFit, planFit, planningBounds, planSqueezedFit, sentOutputCap, } from "../runtime/context/fit.js";
8
8
  import { estimateTokens } from "../runtime/context/tokens.js";
9
9
  import { assembleModelRequest } from "../runtime/model-call.js";
10
10
  import { CHILD_REMOVED_TOOLS } from "../runtime/subagents/definition.js";
@@ -206,22 +206,32 @@ export function reconstructRequest(s, modelCallSeq, opts) {
206
206
  });
207
207
  const { request, meta, mediaTokens } = built;
208
208
  if (!baseline) {
209
- // The hard fit guard against the candidate's window (spec §4.9): clamp the output cap and the
210
- // reserve to that window, apply the fit the candidate would have used, and report
211
- // `context_fit` when the plan differs from the recorded one.
209
+ // The hard fit guard against the candidate's window (spec §4.9), as the runtime runs it: plan
210
+ // against the planning target `W - O_p - R_p` (squeezed to `W - 1 - R_p` when out of reach),
211
+ // apply the fit the candidate would have used, then clamp the output cap from the post-fit
212
+ // estimate keeping the reserve; report `context_fit` when the plan differs from the recorded
213
+ // one. A forced compaction the runtime would run first is not modelled (step replay writes
214
+ // nothing).
212
215
  const reserve = opts.reserveTokens ?? DEFAULT_RESERVE_TOKENS;
213
216
  const estimate = estimateTokens(request.messages, request.system, request.tools, mediaTokens);
214
- request.maxOutputTokens = clampOutput(opts.model.contextWindow, request.maxOutputTokens, estimate);
215
- const recomputed = planFit({
217
+ const output = request.maxOutputTokens;
218
+ const fitInput = {
216
219
  events: inputEvents(all, call),
217
220
  request,
218
221
  model: opts.model,
219
- maxOutputTokens: request.maxOutputTokens,
222
+ maxOutputTokens: output,
220
223
  reserveTokens: reserve,
221
224
  estimate,
222
- });
225
+ };
226
+ const { target } = planningBounds(opts.model.contextWindow, output, reserve);
227
+ let recomputed = planFit(fitInput);
228
+ if (recomputed !== null && estimateAfterFit(request, estimate, recomputed) > target) {
229
+ recomputed = planSqueezedFit(fitInput).plan;
230
+ }
223
231
  if (!samePlan(recomputed, rec.fit))
224
232
  drift.add("context_fit");
233
+ const after = recomputed === null ? estimate : estimateAfterFit(request, estimate, recomputed);
234
+ request.maxOutputTokens = sentOutputCap(opts.model.contextWindow, output, after, reserve);
225
235
  if (recomputed !== null) {
226
236
  request.messages = applyFit(request, recomputed).messages;
227
237
  }
@@ -132,7 +132,7 @@ export interface BootstrapResolveOptions {
132
132
  * Omitted or missing: no offline packages.
133
133
  */
134
134
  dir?: string;
135
- config: Pick<KernelConfig, "packages">;
135
+ config: Pick<KernelConfig, "packages" | "marketplaces" | "net">;
136
136
  signal?: AbortSignal;
137
137
  log?: Pick<Logger, "warn">;
138
138
  /** The npm download (default {@link fetchNpmPackage}; tests replace it). */
@@ -15,6 +15,7 @@ import { parseBootstrapManifest, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { sql } from "kysely";
17
17
  import semver from "semver";
18
+ import { marketplaceNetPolicy } from "../catalog/marketplace-fetch.js";
18
19
  import { otherNameOwner } from "../catalog/ownership.js";
19
20
  import { catalogPackageError } from "../catalog/plugin-import.js";
20
21
  import { PluginPackageError, readPluginPackage } from "../catalog/plugin-package.js";
@@ -181,7 +182,12 @@ export async function resolveBootstrapPackages(manifest, o) {
181
182
  const registry = registryOrigin(npmRegistry);
182
183
  const offlineHint = `to install offline, put the package tgz (npm pack ${e.npm}@${e.version}, any file name) in ${where}`;
183
184
  try {
184
- const r = await fetchPackage({ registry: npmRegistry, ...(npmToken !== undefined && { token: npmToken }), maxBytes }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
185
+ const r = await fetchPackage({
186
+ registry: npmRegistry,
187
+ ...(npmToken !== undefined && { token: npmToken }),
188
+ maxBytes,
189
+ net: marketplaceNetPolicy(o.config),
190
+ }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
185
191
  return r.bytes;
186
192
  }
187
193
  catch (err) {
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { SDK_VERSION } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { marketplaceNetPolicy } from "../catalog/marketplace-fetch.js";
13
14
  import { configFields } from "../config/fields.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { audit } from "../identity/audit.js";
@@ -221,6 +222,7 @@ let ExtensionInstalls = class ExtensionInstalls {
221
222
  const cfg = {
222
223
  registry: c.packages.npmRegistry,
223
224
  maxBytes: c.packages.maxBytes,
225
+ net: marketplaceNetPolicy(c),
224
226
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
225
227
  };
226
228
  const timeout = AbortSignal.timeout(NPM_TIMEOUT_MS);
@@ -262,6 +264,7 @@ let ExtensionInstalls = class ExtensionInstalls {
262
264
  const cfg = {
263
265
  registry: c.packages.npmRegistry,
264
266
  maxBytes: c.packages.maxBytes,
267
+ net: marketplaceNetPolicy(c),
265
268
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
266
269
  };
267
270
  const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
@@ -272,7 +275,7 @@ let ExtensionInstalls = class ExtensionInstalls {
272
275
  const cfg = {
273
276
  registry: c.packages.npmRegistry,
274
277
  maxBytes: c.packages.maxBytes,
275
- allowInsecureLoopback: c.marketplaces.allowInsecureLoopback,
278
+ net: marketplaceNetPolicy(c),
276
279
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
277
280
  };
278
281
  const timeout = AbortSignal.timeout(NPM_TIMEOUT_MS);
@@ -1,4 +1,4 @@
1
- import type { ExtensionManifest, ExtensionPermissions } from "@capybara-hq/plugin-sdk";
1
+ import type { ExtensionManifest, ExtensionPermissions, HttpAccess } from "@capybara-hq/plugin-sdk";
2
2
  /** 一个配置字段:点路径(根即叶子时为空串)与是否密钥。 */
3
3
  export interface PermissionConfigField {
4
4
  path: string;
@@ -25,7 +25,7 @@ export interface PermissionSet {
25
25
  http: {
26
26
  method: string;
27
27
  path: string;
28
- public: boolean;
28
+ access: HttpAccess;
29
29
  }[];
30
30
  tools: string[];
31
31
  hooks: string[];
@@ -107,10 +107,11 @@ export declare function buildPermissionSet(input: {
107
107
  warningsDigest?: string | undefined;
108
108
  }): PermissionSet;
109
109
  /**
110
- * 权限集合的稳定字符串键(排序),如 `provides:channel@1`、`config.org.secret:apiKey`、`table:todos`、
111
- * `permissions.tools:write`、`permissions.http.public:POST /events`、`ui.view:tasks`、`ui.embed:board`,
112
- * `permissions.client`, `ui.component:hud`.
113
- * 容忍旧快照缺字段(按空处理),快照格式演进时不会抛错。
110
+ * The stable string keys of a permission set (sorted), such as `provides:channel@1`,
111
+ * `config.org.secret:apiKey`, `table:todos`, `permissions.tools:write`,
112
+ * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
113
+ * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`.
114
+ * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
114
115
  */
115
116
  export declare function permissionKeys(set: PermissionSet): string[];
116
117
  /**
@@ -95,7 +95,7 @@ export function buildPermissionSet(input) {
95
95
  secrets: p.secrets === true,
96
96
  storage: p.storage === true,
97
97
  http: (p.http ?? [])
98
- .map((r) => ({ method: r.method, path: r.path, public: r.public === true }))
98
+ .map((r) => ({ method: r.method, path: r.path, access: r.access }))
99
99
  .sort((a, b) => cmp(`${a.method} ${a.path}`, `${b.method} ${b.path}`)),
100
100
  tools: sortedUnique(p.tools),
101
101
  hooks: sortedUnique(p.hooks),
@@ -122,10 +122,11 @@ export function buildPermissionSet(input) {
122
122
  };
123
123
  }
124
124
  /**
125
- * 权限集合的稳定字符串键(排序),如 `provides:channel@1`、`config.org.secret:apiKey`、`table:todos`、
126
- * `permissions.tools:write`、`permissions.http.public:POST /events`、`ui.view:tasks`、`ui.embed:board`,
127
- * `permissions.client`, `ui.component:hud`.
128
- * 容忍旧快照缺字段(按空处理),快照格式演进时不会抛错。
125
+ * The stable string keys of a permission set (sorted), such as `provides:channel@1`,
126
+ * `config.org.secret:apiKey`, `table:todos`, `permissions.tools:write`,
127
+ * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
128
+ * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`.
129
+ * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
129
130
  */
130
131
  export function permissionKeys(set) {
131
132
  const s = (set ?? {});
@@ -149,7 +150,9 @@ export function permissionKeys(set) {
149
150
  if (p.storage)
150
151
  keys.push("permissions.storage");
151
152
  for (const r of p.http ?? []) {
152
- keys.push(`permissions.http${r.public ? ".public" : ""}:${r.method} ${r.path}`);
153
+ // a snapshot from before route access has no `access`: its key matches no current key, so the
154
+ // extension waits for re-approval
155
+ keys.push(`permissions.http${r.access ? `.${r.access}` : ""}:${r.method} ${r.path}`);
153
156
  }
154
157
  for (const t of p.tools ?? [])
155
158
  keys.push(`permissions.tools:${t}`);
@@ -12,7 +12,7 @@ import type { ExtensionSource } from "./sources.js";
12
12
  export declare function reviewHash(set: PermissionSet, warnings?: readonly PackageWarning[]): string;
13
13
  /** 权限清单展示用的一组:按类别分组,`sensitive` 标出需要管理员特别留意的类别。 */
14
14
  export interface PermissionGroup {
15
- category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client";
15
+ category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client";
16
16
  /**
17
17
  * Sensitive category: secrets, public routes, tools, hooks, client components, client code; also
18
18
  * the "provides" group when it holds one of {@link SENSITIVE_EXTENSION_POINTS}, and the "UI" group
@@ -24,13 +24,13 @@ export interface PermissionGroup {
24
24
  entries: PermissionItem[];
25
25
  }
26
26
  /**
27
- * Sensitive reason codes (the UI translates them by code): secrets, public routes, tools, hooks,
28
- * embedded apps, client code and client components (client extensions spec §5.4: code that runs with
27
+ * Sensitive reason codes (the UI translates them by code): secrets, public routes, embed routes,
28
+ * tools, hooks, embedded apps, client code and client components (client extensions spec §5.4: code that runs with
29
29
  * full trust in members' browsers), and sensitive extension points
30
30
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
31
31
  * `-` replaced by `_`).
32
32
  */
33
- export type SensitiveReason = "secrets" | "public_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "migration_warnings";
33
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "migration_warnings";
34
34
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
35
35
  export interface PermissionItem {
36
36
  value: string;
@@ -41,6 +41,7 @@ const CLIENT_ITEM = "client code";
41
41
  const ALWAYS_SENSITIVE = new Set([
42
42
  "secrets",
43
43
  "publicRoutes",
44
+ "embedRoutes",
44
45
  "tools",
45
46
  "hooks",
46
47
  "components",
@@ -49,6 +50,7 @@ const ALWAYS_SENSITIVE = new Set([
49
50
  const CATEGORY_REASON = {
50
51
  secrets: "secrets",
51
52
  publicRoutes: "public_routes",
53
+ embedRoutes: "embed_routes",
52
54
  tools: "tools",
53
55
  hooks: "hooks",
54
56
  components: "ui_component",
@@ -74,6 +76,9 @@ function itemReason(category, item) {
74
76
  }
75
77
  return ALWAYS_SENSITIVE.has(category) ? CATEGORY_REASON[category] : undefined;
76
78
  }
79
+ /** Routes of the `http` group: member and admin (the kernel authenticates a person). */
80
+ const signedIn = (access) => access === "member" || access === "admin";
81
+ const routeItem = (r) => `${r.method} ${r.path} (${r.access})`;
77
82
  const itemOf = (category, value) => {
78
83
  const reason = itemReason(category, value);
79
84
  return reason === undefined ? { value, sensitive: false } : { value, sensitive: true, reason };
@@ -90,6 +95,7 @@ function keyItem(key) {
90
95
  const table = [
91
96
  ["provides:", "provides", ""],
92
97
  ["permissions.http.public:", "publicRoutes", ""],
98
+ ["permissions.http.embed:", "embedRoutes", ""],
93
99
  ["permissions.tools:", "tools", ""],
94
100
  ["permissions.hooks:", "hooks", ""],
95
101
  ["permissions.hooks.policy:", "hooks", "policy:"],
@@ -150,14 +156,13 @@ export function permissionGroups(set) {
150
156
  { category: "tables", items: set.tables },
151
157
  { category: "secrets", items: secretItems },
152
158
  { category: "storage", items: p.storage ? ["storage"] : [] },
153
- {
154
- category: "http",
155
- items: p.http.filter((r) => !r.public).map((r) => `${r.method} ${r.path}`),
156
- },
159
+ // routes show their access; public (no sign-in) and embed (embed token) are sensitive groups
160
+ { category: "http", items: p.http.filter((r) => signedIn(r.access)).map(routeItem) },
157
161
  {
158
162
  category: "publicRoutes",
159
- items: p.http.filter((r) => r.public).map((r) => `${r.method} ${r.path}`),
163
+ items: p.http.filter((r) => r.access === "public").map(routeItem),
160
164
  },
165
+ { category: "embedRoutes", items: p.http.filter((r) => r.access === "embed").map(routeItem) },
161
166
  { category: "tools", items: p.tools },
162
167
  { category: "hooks", items: [...p.hooks, ...(p.policyHooks ?? []).map((h) => `policy:${h}`)] },
163
168
  {
@@ -5,7 +5,7 @@ import type { InjectOptions, LightMyRequestResponse } from "fastify";
5
5
  import type { Route } from "../ctx/create-ctx.js";
6
6
  import type { GitGateway } from "../git/gateway.js";
7
7
  import { type GatewayRoutes } from "./gateway-routes.js";
8
- import { type PluginRouteTable } from "./plugin-dispatch.js";
8
+ import { type PluginRouteTable, type RouteAccessResolver } from "./plugin-dispatch.js";
9
9
  /** 内核 HTTP 的只读视图:进程内注入请求与列出路由(测试与元测试用)。 */
10
10
  export interface KernelHttp {
11
11
  inject(opts: InjectOptions): Promise<LightMyRequestResponse>;
@@ -37,6 +37,11 @@ export interface CreateHttpAppOptions {
37
37
  log: Logger;
38
38
  /** Whether `/plugins/*` is dispatched to extension routes. */
39
39
  servePlugins: boolean;
40
+ /**
41
+ * Resolves the caller of an extension route from its declared access; default the application's
42
+ * {@link PluginRouteAccess}, looked up on the first extension request.
43
+ */
44
+ routeAccess?: RouteAccessResolver;
40
45
  /**
41
46
  * Gateway-role routes (the channel webhook), registered only when given: the kernel passes them
42
47
  * when `roles` includes `gateway` (`serveGateway`).
@@ -82,7 +87,8 @@ export declare const ORG_PACKAGE_UPLOAD_ROUTES: ReadonlySet<string>;
82
87
  * and returns it uninitialized: `init()` is the caller's (it runs the start sequence), `close()`
83
88
  * closes only the HTTP server (the rest of the application is closed by the caller's shutdown).
84
89
  * Extension routes do not go through Nest: `/plugins/*` is dispatched in its own Fastify scope
85
- * (see plugin-dispatch.ts) and answers 404 until extensions are loaded. Unmatched kernel routes
90
+ * (see plugin-dispatch.ts), which checks each route's declared access before the body is read, and
91
+ * answers 404 until extensions are loaded. Unmatched kernel routes
86
92
  * answer the 404 error envelope as well.
87
93
  */
88
94
  export declare function createHttpApp(opts: CreateHttpAppOptions, app: NestFastifyApplication): Promise<KernelHttpApp>;
package/dist/http/app.js CHANGED
@@ -12,6 +12,7 @@ import { authorizeOrgAction } from "../orgs/org.guard.js";
12
12
  import { redactPath } from "./error.filter.js";
13
13
  import { registerGatewayRoutes } from "./gateway-routes.js";
14
14
  import { createPluginRouter, registerPluginDispatch, staticRouteTable, } from "./plugin-dispatch.js";
15
+ import { PluginRouteAccess } from "./plugin-route-access.js";
15
16
  /** The extension package upload route (Fastify route template). */
16
17
  export const EXTENSION_PACKAGE_UPLOAD_ROUTE = "/api/v1/admin/extensions/packages/file";
17
18
  /** The plugin package upload route of the catalog import (Fastify route template). */
@@ -82,7 +83,8 @@ const LARGE_BODY_LIMIT = 6 * 1024 * 1024;
82
83
  * and returns it uninitialized: `init()` is the caller's (it runs the start sequence), `close()`
83
84
  * closes only the HTTP server (the rest of the application is closed by the caller's shutdown).
84
85
  * Extension routes do not go through Nest: `/plugins/*` is dispatched in its own Fastify scope
85
- * (see plugin-dispatch.ts) and answers 404 until extensions are loaded. Unmatched kernel routes
86
+ * (see plugin-dispatch.ts), which checks each route's declared access before the body is read, and
87
+ * answers 404 until extensions are loaded. Unmatched kernel routes
86
88
  * answer the 404 error envelope as well.
87
89
  */
88
90
  export async function createHttpApp(opts, app) {
@@ -167,8 +169,16 @@ export async function createHttpApp(opts, app) {
167
169
  fastify.addContentTypeParser("application/octet-stream", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
168
170
  let table;
169
171
  let unwatch;
172
+ let routeAccess = opts.routeAccess;
173
+ const lazyRouteAccess = {
174
+ resolve: (...args) => {
175
+ if (routeAccess === undefined)
176
+ routeAccess = app.get(PluginRouteAccess, { strict: false });
177
+ return routeAccess.resolve(...args);
178
+ },
179
+ };
170
180
  const dispatch = opts.servePlugins
171
- ? await registerPluginDispatch(fastify, () => table, opts.log)
181
+ ? await registerPluginDispatch(fastify, () => table, opts.log, lazyRouteAccess)
172
182
  : undefined;
173
183
  if (opts.gateway)
174
184
  await registerGatewayRoutes(fastify, opts.gateway, opts.log);