@capybara-hq/kernel 0.1.0-rc.33 → 0.1.0-rc.34

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.
@@ -19,6 +19,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { coversHost, orgCloudMode, orgEffectiveHosts, orgHostOutsideCeiling, } from "../sandbox/modes.js";
22
23
  import { readDevicesAutoMode, } from "../sandbox/platform-auto-mode.js";
23
24
  import { assertThemeOnIn } from "../themes/theme-state.js";
24
25
  import { IanaTimeZone } from "../time-zone.js";
@@ -35,9 +36,9 @@ import { OrgLock, OrgLockModule } from "./org-lock.js";
35
36
  * - `autoMode`: whether devices of the org may run in auto mode (auto mode spec §4.3); absent
36
37
  * follows the platform's `devices.autoMode`, and an invalid stored value reads as `off`
37
38
  * (narrower, never wider). Setting `allowed` while the platform is `off` is refused.
38
- * - `cloudNetwork`: the org's network for cloud devices (auto mode spec §4.3): `open` (any public
39
- * host; the default) or `allowlist` with `allowHosts` (the deployment's list when omitted). An
40
- * invalid stored value reads as `{ mode: "allowlist", allowHosts: [] }` (narrower, never wider).
39
+ * - `cloudNetwork`: the org's sandbox-mode network as a delta over the platform's allowlist (org
40
+ * egress ceiling spec §D1, {@link CloudNetworkSettingSchema}). An invalid stored value reads as
41
+ * `{ mode: "allowlist", base: "none" }`, the empty allowlist (narrower, never wider).
41
42
  * - `platformTool`: the `Platform` builtin for the whole org (Platform tool spec §3): `on`,
42
43
  * `read-only` (writes listed as unavailable) or `off` (default `on`).
43
44
  * - `timeZone`: the org's default time zone (IANA; absent = UTC) for senders without one of their
@@ -51,37 +52,48 @@ import { OrgLock, OrgLockModule } from "./org-lock.js";
51
52
  */
52
53
  /** The org cloud-network allowlist's host limit. */
53
54
  export const ORG_SANDBOX_ALLOW_HOSTS_MAX = 200;
55
+ /** One host list of the org's cloud network: at most {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} valid, unique hosts. */
56
+ const orgHostList = (name) => z
57
+ .array(z.string())
58
+ .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
59
+ .superRefine((hosts, ctx) => {
60
+ hosts.forEach((h, i) => {
61
+ for (const message of validateAllowHost(h)) {
62
+ ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
63
+ }
64
+ });
65
+ if (new Set(hosts).size !== hosts.length) {
66
+ ctx.addIssue({ code: "custom", message: `${name} must not contain duplicates` });
67
+ }
68
+ })
69
+ .optional();
54
70
  /**
55
- * The org's network for cloud devices (auto mode spec §4.3): `open` (any public host; loopback,
56
- * private and cloud metadata addresses are blocked outside the container) or `allowlist` with
57
- * `allowHosts`. `allowHosts` given **replaces** the deployment's list (the org may drop the presets
58
- * and add its own hosts); omitted, the deployment's `sandbox.limits.allowHosts` applies.
59
- * The host list is also the ceiling a local device in sandbox mode reaches (the device intersects
60
- * it with its own list), so narrowing it limits local sandbox devices too.
71
+ * The org's sandbox-mode network (org egress ceiling spec §D1), stored as a delta over the
72
+ * platform's `sandbox.limits.allowHosts`, never a copy of it, so platform changes keep reaching the
73
+ * org:
74
+ * - `mode`: the cloud network of a cloud device in sandbox mode, `open` (any public host; loopback,
75
+ * private and cloud metadata addresses are blocked outside the container) or `allowlist`; absent
76
+ * follows the platform's default (open). `sandbox.limits.orgHosts: within` makes it the allowlist.
77
+ * - `base`: `platform` (the default: start from the platform's list) or `none` (only the org's own
78
+ * hosts).
79
+ * - `extraHosts`: hosts the org adds (ignored outside the platform list under `within`).
80
+ * - `excludedHosts`: platform entries the org drops (exact entries; any host is accepted, since the
81
+ * platform may drop an entry later).
82
+ * The effective hosts ({@link orgEffectiveHosts} in `sandbox/modes.ts`) are also the ceiling a local
83
+ * device in sandbox mode reaches (the device intersects them with its own list).
61
84
  */
62
85
  export const CloudNetworkSettingSchema = z
63
86
  .object({
64
- mode: z.enum(["open", "allowlist"]),
65
- allowHosts: z
66
- .array(z.string())
67
- .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
68
- .superRefine((hosts, ctx) => {
69
- hosts.forEach((h, i) => {
70
- for (const message of validateAllowHost(h)) {
71
- ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
72
- }
73
- });
74
- if (new Set(hosts).size !== hosts.length) {
75
- ctx.addIssue({ code: "custom", message: "allowHosts must not contain duplicates" });
76
- }
77
- })
78
- .optional(),
87
+ mode: z.enum(["open", "allowlist"]).optional(),
88
+ base: z.enum(["platform", "none"]).optional(),
89
+ extraHosts: orgHostList("extraHosts"),
90
+ excludedHosts: orgHostList("excludedHosts"),
79
91
  })
80
92
  .strict();
81
93
  /** What an invalid stored `cloudNetwork` reads as: the allowlist with no host (never wider). */
82
94
  export const invalidCloudNetwork = () => ({
83
95
  mode: "allowlist",
84
- allowHosts: [],
96
+ base: "none",
85
97
  });
86
98
  /**
87
99
  * The org's auto-mode switch (auto mode spec §4.3): `allowed` or `off`; absent follows the
@@ -268,6 +280,28 @@ export function invalidStoredCloudNetwork(raw) {
268
280
  const v = asObject(raw).cloudNetwork;
269
281
  return v !== undefined && !CloudNetworkSettingSchema.safeParse(v).success;
270
282
  }
283
+ /**
284
+ * Whether `next` (absent: follow the platform) widens `prev` (spec §D3), both normalized (mode
285
+ * open, base platform, empty lists): the open mode where it was the allowlist; base none to
286
+ * platform; with base platform, dropping one of the stored exclusions; an extra host no stored
287
+ * extra covers. Over-strict on purpose: moving to base none with a platform entry as an extra is a
288
+ * narrowing these rules refuse (a token cannot pin a platform host the platform may drop later).
289
+ */
290
+ export function cloudNetworkWidens(prev, next) {
291
+ const mode = (v) => v?.mode ?? "open";
292
+ const base = (v) => v?.base ?? "platform";
293
+ if (mode(next) === "open" && mode(prev) !== "open")
294
+ return true;
295
+ if (base(next) === "platform" && base(prev) === "none")
296
+ return true;
297
+ if (base(next) === "platform") {
298
+ const kept = new Set(next?.excludedHosts ?? []);
299
+ if ((prev?.excludedHosts ?? []).some((h) => !kept.has(h)))
300
+ return true;
301
+ }
302
+ const prevExtra = (prev?.extraHosts ?? []).map((h) => h.toLowerCase());
303
+ return (next?.extraHosts ?? []).some((h) => !prevExtra.some((p) => coversHost(p, h.toLowerCase())));
304
+ }
271
305
  /** 组织设置服务:读取与修改(修改需 `org.update`,锁内实时复核角色,写审计)。 */
272
306
  let OrgSettingsService = class OrgSettingsService {
273
307
  db;
@@ -310,14 +344,27 @@ let OrgSettingsService = class OrgSettingsService {
310
344
  ]);
311
345
  return {
312
346
  autoMode,
313
- cloudNetwork: lim.egress === "none"
314
- ? { mode: "allowlist", allowHosts: [] }
315
- : { mode: "open", allowHosts: [...lim.allowHosts] },
347
+ cloudNetwork: {
348
+ allowHosts: [...lim.allowHosts],
349
+ orgHosts: lim.orgHosts,
350
+ off: lim.egress === "none",
351
+ },
316
352
  attribution,
317
353
  publicUrl: this.config.get().http.publicUrl !== undefined,
318
354
  compaction,
319
355
  };
320
356
  }
357
+ /**
358
+ * The org's effective sandbox-mode network (spec §D3): the cloud network's mode and the hosts,
359
+ * from the platform's `sandbox.limits` and the org's stored delta.
360
+ */
361
+ effectiveNetwork(settings) {
362
+ const lim = this.config.get().sandbox.limits;
363
+ return {
364
+ mode: orgCloudMode(lim, settings.cloudNetwork),
365
+ hosts: orgEffectiveHosts(lim, settings.cloudNetwork),
366
+ };
367
+ }
321
368
  /** 组织实际生效的沙箱 cpu / 内存(只读;由超级管理员在部署设置里覆盖)。 */
322
369
  async sandboxLimits(orgId) {
323
370
  const lim = this.config.get().sandbox.limits;
@@ -339,7 +386,10 @@ let OrgSettingsService = class OrgSettingsService {
339
386
  throw new ApiError("org.not_found", "Organization not found");
340
387
  return this.parseStored(orgId, row.settings);
341
388
  }
342
- /** The refusals of {@link update} that need no read of the org (the Platform tool's precheck). */
389
+ /**
390
+ * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
391
+ * auto mode where the platform turned it off.
392
+ */
343
393
  async check(patch) {
344
394
  // turning auto mode on where the platform turned it off is wider than the platform allows
345
395
  if (patch.autoMode === "allowed") {
@@ -349,6 +399,29 @@ let OrgSettingsService = class OrgSettingsService {
349
399
  }
350
400
  }
351
401
  }
402
+ /**
403
+ * Under `sandbox.limits.orgHosts: within` (spec §D2), refuses what would widen past the platform
404
+ * ceiling compared with the stored value `before`: the open cloud network where the org did not
405
+ * store it, or an extra host outside the platform's allowlist that the org did not store. Stored
406
+ * values are sent back as they are (the PATCH replaces `cloudNetwork` whole) and have no effect
407
+ * under the ceiling (they are filtered on read), so they never block a write.
408
+ */
409
+ assertWithinCeiling(before, patch) {
410
+ const cn = patch.cloudNetwork;
411
+ if (cn == null)
412
+ return;
413
+ const lim = this.config.get().sandbox.limits;
414
+ if (lim.orgHosts !== "within")
415
+ return;
416
+ if (cn.mode === "open" && before.cloudNetwork?.mode !== "open") {
417
+ throw new ApiError("org.sandbox_egress_not_allowed", "The platform limits sandbox networks to its allowlist; the open cloud network is not available", [{ reason: "open_not_allowed" }]);
418
+ }
419
+ const stored = new Set(before.cloudNetwork?.extraHosts ?? []);
420
+ const outside = (cn.extraHosts ?? []).filter((h) => !stored.has(h) && orgHostOutsideCeiling(lim, h));
421
+ if (outside.length > 0) {
422
+ throw new ApiError("org.sandbox_egress_not_allowed", `The platform limits sandbox hosts to its allowlist; ask a super admin to add ${outside.join(", ")} to sandbox.limits.allowHosts`, [{ reason: "outside_ceiling", hosts: outside }]);
423
+ }
424
+ }
352
425
  async update(orgId, patch, actorAccountId, actorTokenId,
353
426
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
354
427
  auditDetail,
@@ -365,15 +438,9 @@ let OrgSettingsService = class OrgSettingsService {
365
438
  * never the Platform tool or an API token):
366
439
  * - `autoMode`: `allowed` where the organization runs `off` (an absent value follows the
367
440
  * platform); clearing it follows the platform too, never wider than the platform allows;
368
- * - `cloudNetwork`: `open` where the network is the allowlist, or a host the current allowlist
369
- * does not have (the deployment's `sandbox.limits.allowHosts` when the org gives none).
370
- * `cloudNetwork.allowHosts` is also the local sandbox-mode ceiling (`orgAllowedDomains` in
371
- * `sandbox/modes.ts` becomes `deviceLimits.localAllowedDomains`, which the device intersects
372
- * with its own list): an org with no `cloudNetwork` still caps its local devices at the
373
- * deployment's list, and an org whose network is `open` still caps them at its own `allowHosts`.
374
- * The host comparison therefore applies to both shapes, whatever the target mode: a patch may
375
- * only keep or lower the host set. Switching from `open` is a widening by itself, and the host
376
- * set must not grow even when the target stays `open` (spec §4.2, §4.3).
441
+ * - `cloudNetwork`: compared as stored deltas ({@link cloudNetworkWidens}), never as effective
442
+ * values: under the kill switch or the platform ceiling the effective values hide a widening
443
+ * that takes effect when the platform relaxes (org egress ceiling spec §D3).
377
444
  */
378
445
  async assertOnlyNarrows(before, patch) {
379
446
  if (patch.autoMode !== undefined) {
@@ -383,20 +450,9 @@ let OrgSettingsService = class OrgSettingsService {
383
450
  throw autoModeNotAllowed("Turning auto mode on needs a person in the organization settings.");
384
451
  }
385
452
  }
386
- if (patch.cloudNetwork !== undefined) {
387
- const lim = this.config.get().sandbox.limits;
388
- const defaultMode = lim.egress === "none" ? "allowlist" : "open";
389
- const defaultHosts = lim.egress === "none" ? [] : [...lim.allowHosts];
390
- const prev = before.cloudNetwork;
391
- const next = patch.cloudNetwork ?? undefined;
392
- const modeOf = (v) => v?.mode ?? defaultMode;
393
- const hostsOf = (v) => v?.allowHosts ?? defaultHosts;
394
- const nextMode = next?.mode ?? defaultMode;
395
- const widens = (nextMode === "open" && modeOf(prev) !== "open") ||
396
- !hostsOf(next).every((h) => hostsOf(prev).includes(h));
397
- if (widens) {
398
- throw new ApiError("org.sandbox_egress_not_allowed", "Widening the cloud network needs a person in the organization settings.");
399
- }
453
+ if (patch.cloudNetwork !== undefined &&
454
+ cloudNetworkWidens(before.cloudNetwork, patch.cloudNetwork ?? undefined)) {
455
+ throw new ApiError("org.sandbox_egress_not_allowed", "Widening the cloud network needs a person in the organization settings.");
400
456
  }
401
457
  }
402
458
  async updateIn(orgId, patch, actorAccountId, actorTokenId, auditDetail, opts) {
@@ -411,6 +467,7 @@ let OrgSettingsService = class OrgSettingsService {
411
467
  // again under the org lock: a hot config reload may have lowered the platform since
412
468
  await this.check(patch);
413
469
  // under the org lock, so the comparison is with the value the write replaces
470
+ this.assertWithinCeiling(before, patch);
414
471
  if (opts?.onlyNarrows)
415
472
  await this.assertOnlyNarrows(before, patch);
416
473
  const changes = Object.fromEntries(Object.entries(patch)
@@ -39,21 +39,25 @@ let OrgSettingsOperations = class OrgSettingsOperations {
39
39
  this.registry.register([
40
40
  defineOperation({
41
41
  id: "org-settings.get",
42
- description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), autoMode (allowed or off: whether the org's devices may run in auto mode; absent follows the deployment's switch, and the org may never exceed it), cloudNetwork (the network of a cloud device in sandbox mode: open, or allowlist with its hosts; open means any public host, while loopback, private and cloud metadata addresses stay blocked), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's auto-mode switch and cloud-network defaults, and the sandbox cpu / memory limits in effect.",
42
+ description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), autoMode (allowed or off: whether the org's devices may run in auto mode; absent follows the deployment's switch, and the org may never exceed it), cloudNetwork (the org's sandbox-mode network stored as a delta over the platform's allowlist: mode open or allowlist for a cloud device in sandbox mode, absent following the platform; base platform or none; extraHosts the org adds; excludedHosts platform hosts it drops; open means any public host, while loopback, private and cloud metadata addresses stay blocked), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's auto-mode switch and network (its allowlist, orgHosts: extend lets the org go beyond it, within makes it the ceiling, and off for the platform kill switch), effectiveNetwork (the mode and hosts the org's sandbox mode really gets), and the sandbox cpu / memory limits in effect.",
43
43
  input: z.object({}).strict(),
44
44
  example: {},
45
45
  authz: { orgAction: "org.read" },
46
46
  mirrors: ["GET /api/v1/orgs/:orgId/settings"],
47
47
  confirm: "read",
48
- run: async (_input, ctx) => ({
49
- settings: await this.settings.get(ctx.orgId),
50
- deployment: await this.settings.deployment(),
51
- sandboxLimits: await this.settings.sandboxLimits(ctx.orgId),
52
- }),
48
+ run: async (_input, ctx) => {
49
+ const settings = await this.settings.get(ctx.orgId);
50
+ return {
51
+ settings,
52
+ deployment: await this.settings.deployment(),
53
+ effectiveNetwork: this.settings.effectiveNetwork(settings),
54
+ sandboxLimits: await this.settings.sandboxLimits(ctx.orgId),
55
+ };
56
+ },
53
57
  }),
54
58
  defineOperation({
55
59
  id: "org-settings.update",
56
- description: "Change this org's settings (org admins). Give only the settings to change; null clears autoMode, cloudNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). autoMode (allowed or off; the platform must allow it) and cloudNetwork ({ mode: open | allowlist, allowHosts? }, replaced whole, hosts left out following the deployment's list) may only narrow the org's devices here: turning auto mode on where the org has it off, switching the cloud network from allowlist to open, or adding a network host is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org, so say so before asking; an org admin switches it back on in the web settings.",
60
+ description: "Change this org's settings (org admins). Give only the settings to change; null clears autoMode, cloudNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). autoMode (allowed or off; the platform must allow it) and cloudNetwork ({ mode?, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep) may only narrow the org's devices here: turning auto mode on where the org has it off, switching the cloud network from allowlist to open, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org, so say so before asking; an org admin switches it back on in the web settings.",
57
61
  input: OrgSettingsPatchSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
58
62
  message: "give at least one setting",
59
63
  }),
@@ -64,7 +68,7 @@ let OrgSettingsOperations = class OrgSettingsOperations {
64
68
  errors: [
65
69
  {
66
70
  code: "org.sandbox_egress_not_allowed",
67
- next: "Through this tool the org's cloud network may only be narrowed: the host list may keep or lose hosts, and an open network may become an allowlist of hosts that list already has, but no change may add a host or switch an allowlist back to open (the host list is the local sandbox-mode ceiling whatever the cloud mode). To widen it, ask an org admin to change it in the organization settings on the web.",
71
+ next: "Through this tool the org's cloud network may only be narrowed: it may drop extra hosts, exclude platform hosts, move base to none or switch open to allowlist, but never add an extra host, drop an exclusion or switch back to open (the hosts are the local sandbox-mode ceiling whatever the cloud mode). To widen it, ask an org admin to change it in the organization settings on the web. When the platform limits hosts to its allowlist (deployment.cloudNetwork.orgHosts within), a host outside it needs a super admin.",
68
72
  },
69
73
  {
70
74
  code: "org.auto_mode_not_allowed",
@@ -81,7 +85,9 @@ let OrgSettingsOperations = class OrgSettingsOperations {
81
85
  ],
82
86
  precheck: (i, ctx) => precheckBy(async () => {
83
87
  await this.settings.check(i);
84
- await this.settings.assertOnlyNarrows(await this.settings.get(ctx.orgId), i);
88
+ const before = await this.settings.get(ctx.orgId);
89
+ this.settings.assertWithinCeiling(before, i);
90
+ await this.settings.assertOnlyNarrows(before, i);
85
91
  }),
86
92
  summary: async (i, ctx) => {
87
93
  const { theme, ...rest } = i;
@@ -119,7 +125,11 @@ let OrgSettingsOperations = class OrgSettingsOperations {
119
125
  const note = input.platformTool === undefined
120
126
  ? undefined
121
127
  : PLATFORM_TOOL_NOTE[settings.platformTool];
122
- return { settings, ...(note !== undefined && { note }) };
128
+ return {
129
+ settings,
130
+ effectiveNetwork: this.settings.effectiveNetwork(settings),
131
+ ...(note !== undefined && { note }),
132
+ };
123
133
  },
124
134
  }),
125
135
  ]);
@@ -1,7 +1,7 @@
1
1
  import type { KernelConfig } from "../config/schema.js";
2
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
- import type { OrgSettings } from "../orgs/settings.service.js";
4
+ import type { CloudNetworkSetting, OrgSettings } from "../orgs/settings.service.js";
5
5
  import { type DevicesAutoMode } from "./platform-auto-mode.js";
6
6
  /**
7
7
  * Device modes (auto mode spec §4.1–§4.3): who may choose auto mode, and the network each mode
@@ -24,8 +24,33 @@ export interface DeviceNetwork {
24
24
  */
25
25
  export interface DeploymentDevicePolicy {
26
26
  autoMode: DevicesAutoMode;
27
- limits: Pick<KernelConfig["sandbox"]["limits"], "egress" | "allowHosts">;
27
+ limits: NetworkLimits;
28
28
  }
29
+ /**
30
+ * The platform's network fields (`sandbox.limits`): the kill switch, the allowlist and whether
31
+ * organizations may go beyond it (org egress ceiling spec §D2).
32
+ */
33
+ export type NetworkLimits = Pick<KernelConfig["sandbox"]["limits"], "egress" | "allowHosts" | "orgHosts">;
34
+ /** Whether the allowlist entry `pattern` admits `host` (`*.x.com`: subdomains, never the apex). */
35
+ export declare const coversHost: (pattern: string, host: string) => boolean;
36
+ /**
37
+ * Whether `host` is beyond the platform's ceiling: `sandbox.limits.orgHosts` is `within` and no
38
+ * entry of `sandbox.limits.allowHosts` covers it (a wildcard host is covered by a wider wildcard).
39
+ * Only a super admin can allow such a host.
40
+ */
41
+ export declare function orgHostOutsideCeiling(limits: NetworkLimits, host: string): boolean;
42
+ /**
43
+ * The org's effective allowlist (org egress ceiling spec §D1): empty under the kill switch; else
44
+ * the org's extras (only those inside the ceiling under `within`) on top of the platform's list
45
+ * minus the org's exclusions, or the extras alone when the org's base is `none`. The one place
46
+ * that combines the platform's hosts with the org's.
47
+ */
48
+ export declare function orgEffectiveHosts(limits: NetworkLimits, org: CloudNetworkSetting | undefined): string[];
49
+ /**
50
+ * The org's cloud network in sandbox mode (spec §D2): the allowlist under the kill switch or the
51
+ * platform ceiling (`orgHosts: within`), else the org's mode (open by default).
52
+ */
53
+ export declare function orgCloudMode(limits: NetworkLimits, org: CloudNetworkSetting | undefined): "open" | "allowlist";
29
54
  /**
30
55
  * The platform side of the policy, read live: the effective auto-mode switch and the
31
56
  * `sandbox.limits` network fields (in the caller's transaction when there is one).
@@ -52,27 +77,14 @@ export interface EffectiveDevicePolicy {
52
77
  }
53
78
  /** The mode the platform and the org allow: `auto` only when neither turns it off. */
54
79
  export declare function allowedDeviceMode(platform: DevicesAutoMode, org: OrgDeviceSettings["autoMode"]): SandboxMode;
55
- /**
56
- * The org's allowlist (the hosts a local device in sandbox mode may reach): the org's own list when
57
- * it gave one, else `sandbox.limits.allowHosts`; empty under the platform kill switch.
58
- */
80
+ /** The org's allowlist (the hosts a local device in sandbox mode may reach): {@link orgEffectiveHosts}. */
59
81
  export declare function orgAllowedDomains(deployment: DeploymentDevicePolicy, org: OrgDeviceSettings): string[];
60
82
  /**
61
- * The cloud network (auto mode spec §4.3): `open-public` in auto mode while the org's
62
- * `cloudNetwork` is `open` (the default), else the org's allowlist. `sandbox.limits.egress: none`
63
- * forces an empty allowlist (the platform kill switch, R20).
83
+ * The cloud network (auto mode spec §4.3): `open-public` in auto mode; in sandbox mode the org's
84
+ * cloud network ({@link orgCloudMode}). `sandbox.limits.egress: none` forces an empty allowlist
85
+ * (the platform kill switch, R20).
64
86
  */
65
87
  export declare function deviceNetwork(deployment: DeploymentDevicePolicy, org: OrgDeviceSettings, mode: SandboxMode): DeviceNetwork;
66
- /**
67
- * The org's sandbox-mode network, from the deployment default, the org's `cloudNetwork` choice and
68
- * the platform kill switch: `sandbox.limits.egress: "none"` forces an empty allowlist (R20, every
69
- * read); otherwise `open-public` when either says open, else the org's hosts over the deployment's
70
- * list.
71
- */
72
- export declare function orgSandboxNetwork(deployment: {
73
- mode: "open" | "allowlist";
74
- allowHosts: string[];
75
- }, org: OrgDeviceSettings["cloudNetwork"], egress?: "none" | "allowlist"): DeviceNetwork;
76
88
  /**
77
89
  * The effective device policy. `deviceMode` is the device's own choice (a local machine's
78
90
  * reported mode; null = follow the platform and the org). A stored mode the ceiling forbids is cut,
@@ -1,4 +1,41 @@
1
1
  import { readDevicesAutoMode } from "./platform-auto-mode.js";
2
+ /** Whether the allowlist entry `pattern` admits `host` (`*.x.com`: subdomains, never the apex). */
3
+ export const coversHost = (pattern, host) => pattern === host || (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));
4
+ /**
5
+ * Whether `host` is beyond the platform's ceiling: `sandbox.limits.orgHosts` is `within` and no
6
+ * entry of `sandbox.limits.allowHosts` covers it (a wildcard host is covered by a wider wildcard).
7
+ * Only a super admin can allow such a host.
8
+ */
9
+ export function orgHostOutsideCeiling(limits, host) {
10
+ if (limits.orgHosts !== "within")
11
+ return false;
12
+ const h = host.toLowerCase();
13
+ return !limits.allowHosts.some((p) => coversHost(p.toLowerCase(), h));
14
+ }
15
+ /**
16
+ * The org's effective allowlist (org egress ceiling spec §D1): empty under the kill switch; else
17
+ * the org's extras (only those inside the ceiling under `within`) on top of the platform's list
18
+ * minus the org's exclusions, or the extras alone when the org's base is `none`. The one place
19
+ * that combines the platform's hosts with the org's.
20
+ */
21
+ export function orgEffectiveHosts(limits, org) {
22
+ if (limits.egress === "none")
23
+ return [];
24
+ const extra = (org?.extraHosts ?? []).filter((h) => !orgHostOutsideCeiling(limits, h));
25
+ if (org?.base === "none")
26
+ return [...new Set(extra)];
27
+ const excluded = new Set(org?.excludedHosts ?? []);
28
+ return [...new Set([...limits.allowHosts.filter((h) => !excluded.has(h)), ...extra])];
29
+ }
30
+ /**
31
+ * The org's cloud network in sandbox mode (spec §D2): the allowlist under the kill switch or the
32
+ * platform ceiling (`orgHosts: within`), else the org's mode (open by default).
33
+ */
34
+ export function orgCloudMode(limits, org) {
35
+ if (limits.egress === "none" || limits.orgHosts === "within")
36
+ return "allowlist";
37
+ return org?.mode ?? "open";
38
+ }
2
39
  /**
3
40
  * The platform side of the policy, read live: the effective auto-mode switch and the
4
41
  * `sandbox.limits` network fields (in the caller's transaction when there is one).
@@ -11,19 +48,14 @@ export async function readDeploymentDevicePolicy(db, config) {
11
48
  export function allowedDeviceMode(platform, org) {
12
49
  return platform === "allowed" && org !== "off" ? "auto" : "sandbox";
13
50
  }
14
- /**
15
- * The org's allowlist (the hosts a local device in sandbox mode may reach): the org's own list when
16
- * it gave one, else `sandbox.limits.allowHosts`; empty under the platform kill switch.
17
- */
51
+ /** The org's allowlist (the hosts a local device in sandbox mode may reach): {@link orgEffectiveHosts}. */
18
52
  export function orgAllowedDomains(deployment, org) {
19
- if (deployment.limits.egress === "none")
20
- return [];
21
- return [...(org.cloudNetwork?.allowHosts ?? deployment.limits.allowHosts)];
53
+ return orgEffectiveHosts(deployment.limits, org.cloudNetwork);
22
54
  }
23
55
  /**
24
- * The cloud network (auto mode spec §4.3): `open-public` in auto mode while the org's
25
- * `cloudNetwork` is `open` (the default), else the org's allowlist. `sandbox.limits.egress: none`
26
- * forces an empty allowlist (the platform kill switch, R20).
56
+ * The cloud network (auto mode spec §4.3): `open-public` in auto mode; in sandbox mode the org's
57
+ * cloud network ({@link orgCloudMode}). `sandbox.limits.egress: none` forces an empty allowlist
58
+ * (the platform kill switch, R20).
27
59
  */
28
60
  export function deviceNetwork(deployment, org, mode) {
29
61
  if (deployment.limits.egress === "none")
@@ -31,24 +63,11 @@ export function deviceNetwork(deployment, org, mode) {
31
63
  // auto mode is 开放挡内网 whatever the org says; only sandbox mode applies `cloudNetwork`
32
64
  if (mode === "auto")
33
65
  return { kind: "open-public", hosts: [] };
34
- if ((org.cloudNetwork?.mode ?? "open") === "open") {
66
+ if (orgCloudMode(deployment.limits, org.cloudNetwork) === "open") {
35
67
  return { kind: "open-public", hosts: [] };
36
68
  }
37
69
  return { kind: "allowlist", hosts: orgAllowedDomains(deployment, org) };
38
70
  }
39
- /**
40
- * The org's sandbox-mode network, from the deployment default, the org's `cloudNetwork` choice and
41
- * the platform kill switch: `sandbox.limits.egress: "none"` forces an empty allowlist (R20, every
42
- * read); otherwise `open-public` when either says open, else the org's hosts over the deployment's
43
- * list.
44
- */
45
- export function orgSandboxNetwork(deployment, org, egress = "allowlist") {
46
- if (egress === "none")
47
- return { kind: "allowlist", hosts: [] };
48
- if ((org?.mode ?? deployment.mode) === "open")
49
- return { kind: "open-public", hosts: [] };
50
- return { kind: "allowlist", hosts: [...(org?.allowHosts ?? deployment.allowHosts)] };
51
- }
52
71
  /**
53
72
  * The effective device policy. `deviceMode` is the device's own choice (a local machine's
54
73
  * reported mode; null = follow the platform and the org). A stored mode the ceiling forbids is cut,
@@ -139,10 +139,13 @@ export declare const isInstance: (row: Pick<Row, "handle" | "created_at">, gone:
139
139
  * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
140
140
  * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
141
141
  * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
142
+ * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
143
+ * ceiling limits sandbox mode only, and auto mode (the default of every device) keeps the open
144
+ * network (org egress ceiling spec §D2). The admin console's runtime choice is not seen here.
142
145
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
143
146
  * nothing to tell.
144
147
  */
145
- export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "extensionConfig">, providerPlugin?: string): {
148
+ export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "extensionConfig"> & Partial<Pick<KernelConfig, "devices">>, providerPlugin?: string): {
146
149
  level: "warn";
147
150
  message: string;
148
151
  }[];
@@ -151,6 +151,9 @@ function tagged(impl, tag, actor, before) {
151
151
  * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
152
152
  * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
153
153
  * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
154
+ * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
155
+ * ceiling limits sandbox mode only, and auto mode (the default of every device) keeps the open
156
+ * network (org egress ceiling spec §D2). The admin console's runtime choice is not seen here.
154
157
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
155
158
  * nothing to tell.
156
159
  */
@@ -165,6 +168,14 @@ export function sandboxConfigWarnings(cfg, providerPlugin) {
165
168
  });
166
169
  }
167
170
  }
171
+ if (cfg.sandbox.limits.orgHosts === "within" &&
172
+ cfg.sandbox.limits.egress !== "none" &&
173
+ cfg.devices?.autoMode !== "off") {
174
+ out.push({
175
+ level: "warn",
176
+ message: "sandbox.limits.orgHosts is within but devices.autoMode is not off: the platform allowlist limits sandbox mode only; devices in auto mode (the default) still reach the open public network. Set devices.autoMode to off (or turn auto mode off in the admin console) for a hard ceiling",
177
+ });
178
+ }
168
179
  const run = cfg.runtime.maxRunSeconds;
169
180
  const cmd = cfg.sandbox.limits.maxCommandSeconds;
170
181
  if (run > 0 && run < cmd) {
@@ -51,6 +51,8 @@ export interface NetworkGrantContext {
51
51
  * command may reach in sandbox mode.
52
52
  */
53
53
  limits: Pick<SandboxLimits, "network">;
54
+ /** Whether a host is beyond the platform's ceiling (org egress ceiling spec §D2). */
55
+ outsideCeiling?: (host: string) => boolean;
54
56
  }
55
57
  /**
56
58
  * Why `host` cannot be one of a task's network grants (network ask-to-allow spec §8.1), or null
@@ -80,7 +80,9 @@ export function networkGrantRefusal(host, ctx) {
80
80
  if (!orgAllows(host, ctx.limits)) {
81
81
  return {
82
82
  code: "needs_admin",
83
- message: `${host} is not in the organization's network allowlist; only an organization admin can add it`,
83
+ message: ctx.outsideCeiling?.(host) === true
84
+ ? `${host} is not in the platform's network allowlist, which limits this organization; only a super admin can add it`
85
+ : `${host} is not in the organization's network allowlist; only an organization admin can add it`,
84
86
  };
85
87
  }
86
88
  return null;
@@ -113,6 +113,22 @@ export function tickerOf(t) {
113
113
  }
114
114
  /** How far back a DST transition can move a tick: longer than any gap (spec §5). */
115
115
  const TRANSITION_LOOKBACK_MS = 6 * 3600_000;
116
+ /**
117
+ * The cron library's search for the next date, or null when it gives up: it refuses to look more
118
+ * than a few years past the current date ("No execution date was found in the next 8 years"),
119
+ * which a yearly or Feb 29 expression reaches while the gap sample walks ahead. Any other error
120
+ * is thrown.
121
+ */
122
+ function nextOrNull(search) {
123
+ try {
124
+ return search();
125
+ }
126
+ catch (e) {
127
+ if (e instanceof Error && /No execution date was found/.test(e.message))
128
+ return null;
129
+ throw e;
130
+ }
131
+ }
116
132
  /**
117
133
  * {@link nextTick} for one trigger, with its `CronTime`s built once: callers that walk many ticks
118
134
  * (the gap sample, the catch-up enumeration) reuse one ticker instead of rebuilding per tick.
@@ -129,7 +145,10 @@ function ticker(t) {
129
145
  return (after) => {
130
146
  let cursor = after;
131
147
  for (let i = 0; i < 10; i++) {
132
- const tick = new Date(time.getNextDateFrom(cursor, t.timeZone).toMillis());
148
+ const next = nextOrNull(() => time.getNextDateFrom(cursor, t.timeZone).toMillis());
149
+ if (next === null)
150
+ return null;
151
+ const tick = new Date(next);
133
152
  const ms = tick.getTime();
134
153
  // CronTime moves a tick that falls in a DST gap to the next valid instant; the spec says a
135
154
  // skipped local time does not fire, so keep only ticks whose wall clock the expression
@@ -138,7 +157,7 @@ function ticker(t) {
138
157
  return tick;
139
158
  }
140
159
  const wall = localWallClock(tick, t.timeZone);
141
- if (wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis() === wall)
160
+ if (nextOrNull(() => wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis()) === wall)
142
161
  return tick;
143
162
  cursor = tick;
144
163
  }
@@ -27,6 +27,7 @@ import { orgAllows } from "../local-devices/network-grants.js";
27
27
  import { OrgLock } from "../orgs/org-lock.js";
28
28
  import { can, roleAtLeast } from "../orgs/roles.js";
29
29
  import { ProviderRegistry } from "../runtime/providers.js";
30
+ import { orgHostOutsideCeiling } from "../sandbox/modes.js";
30
31
  import { SandboxService } from "../sandbox/sandbox.service.js";
31
32
  import { isTimeZone } from "../time-zone.js";
32
33
  import { ToolRegistry } from "../tools/registry.js";
@@ -1111,7 +1112,8 @@ let ScheduledTasksService = class ScheduledTasksService {
1111
1112
  */
1112
1113
  async networkGrantContext(orgId) {
1113
1114
  const limits = await this.sandbox.ceilingLimits(orgId);
1114
- return { limits };
1115
+ const platform = this.config.get().sandbox.limits;
1116
+ return { limits, outsideCeiling: (h) => orgHostOutsideCeiling(platform, h) };
1115
1117
  }
1116
1118
  /**
1117
1119
  * The device a task's runs use, as far as the task tells: a `new` task's own device, a
@@ -44,6 +44,8 @@ export declare const localOnlyNote: (hosts: readonly string[]) => string;
44
44
  export declare const alwaysRefusedNote: (hosts: readonly string[]) => string;
45
45
  /** The org layer (spec §6.6): only an org admin can lift it. */
46
46
  export declare const orgLayerNote: (hosts: readonly string[]) => string;
47
+ /** An org-layer host beyond the platform's ceiling (org egress ceiling spec §D2): only a super admin. */
48
+ export declare const platformCeilingNote: (hosts: readonly string[]) => string;
47
49
  /** The address layer (spec §6.6): nobody can lift it. */
48
50
  export declare const addressLayerNote: (hosts: readonly string[]) => string;
49
51
  /**
@@ -63,6 +65,11 @@ export interface NetworkPlanContext {
63
65
  } | null;
64
66
  /** The scheduled task run the run serves (null / undefined: attended). */
65
67
  unattended: UnattendedRun | null | undefined;
68
+ /**
69
+ * Whether a host is beyond the platform's ceiling (`sandbox.limits.orgHosts: within`, org egress
70
+ * ceiling spec §D2): only a super admin can add it, so its note names the super admin.
71
+ */
72
+ outsideCeiling?: (host: string) => boolean;
66
73
  }
67
74
  /** What to do with a command's refused hosts. */
68
75
  export interface NetworkPlan {