@capybara-hq/kernel 0.1.0-rc.54 → 0.1.0-rc.55

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 (154) hide show
  1. package/dist/admin/admin.schemas.d.ts +11 -1
  2. package/dist/catalog/catalog.module.js +1 -1
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/catalog/requests.service.d.ts +5 -5
  5. package/dist/catalog/requests.service.js +9 -9
  6. package/dist/channels/cards.d.ts +4 -3
  7. package/dist/channels/cards.js +25 -16
  8. package/dist/channels/phrases.d.ts +15 -4
  9. package/dist/channels/phrases.js +15 -1
  10. package/dist/config/load.d.ts +26 -7
  11. package/dist/config/load.js +60 -9
  12. package/dist/config/permission-migration.d.ts +17 -9
  13. package/dist/config/permission-migration.js +60 -9
  14. package/dist/config/schema.d.ts +11 -1
  15. package/dist/config/schema.js +37 -11
  16. package/dist/conversations/events.d.ts +247 -5
  17. package/dist/conversations/events.js +127 -16
  18. package/dist/conversations/permission-profiles.controller.d.ts +12 -2
  19. package/dist/conversations/permission-profiles.service.d.ts +12 -2
  20. package/dist/conversations/permission-profiles.service.js +11 -4
  21. package/dist/db/kernel-schema.d.ts +8 -2
  22. package/dist/devices/device-projects.service.d.ts +1 -1
  23. package/dist/devices/device-projects.service.js +6 -6
  24. package/dist/devices/devices.controller.d.ts +10 -8
  25. package/dist/devices/devices.controller.js +14 -18
  26. package/dist/devices/devices.schemas.d.ts +5 -5
  27. package/dist/devices/devices.schemas.js +5 -5
  28. package/dist/devices/devices.service.d.ts +188 -175
  29. package/dist/devices/devices.service.js +284 -292
  30. package/dist/devices/dto.d.ts +43 -23
  31. package/dist/devices/dto.js +45 -49
  32. package/dist/devices/project-rules.d.ts +0 -10
  33. package/dist/devices/project-rules.js +0 -5
  34. package/dist/errors.d.ts +24 -19
  35. package/dist/errors.js +24 -19
  36. package/dist/evals/reconstruct.d.ts +12 -3
  37. package/dist/evals/reconstruct.js +10 -6
  38. package/dist/evals/recorded-permission-context.d.ts +6 -4
  39. package/dist/evals/recorded-permission-context.js +15 -9
  40. package/dist/evals/run-replay.d.ts +6 -1
  41. package/dist/evals/run-replay.js +7 -2
  42. package/dist/evals/worker.js +3 -1
  43. package/dist/identity/settings.d.ts +45 -18
  44. package/dist/identity/settings.js +151 -51
  45. package/dist/infra/config/kernel-config.service.d.ts +1 -1
  46. package/dist/infra/config/kernel-config.service.js +17 -5
  47. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  48. package/dist/local-devices/device-auth.controller.js +1 -1
  49. package/dist/local-devices/device-auth.d.ts +4 -4
  50. package/dist/local-devices/device-auth.js +1 -1
  51. package/dist/local-devices/device-policy.service.d.ts +18 -9
  52. package/dist/local-devices/device-policy.service.js +21 -61
  53. package/dist/local-devices/device-routes.d.ts +3 -1
  54. package/dist/local-devices/device-routes.js +15 -4
  55. package/dist/local-devices/instance-bindings.js +5 -2
  56. package/dist/local-devices/local-device-gateway.d.ts +2 -2
  57. package/dist/local-devices/local-device-gateway.js +3 -3
  58. package/dist/local-devices/local-device-provider.d.ts +4 -4
  59. package/dist/local-devices/local-device-provider.js +23 -9
  60. package/dist/local-devices/local-devices.module.d.ts +1 -1
  61. package/dist/local-devices/local-devices.module.js +1 -1
  62. package/dist/local-devices/machines.d.ts +40 -16
  63. package/dist/local-devices/machines.js +89 -61
  64. package/dist/local-devices/owner-report.d.ts +16 -14
  65. package/dist/local-devices/owner-report.js +24 -30
  66. package/dist/local-devices/owner-reports.js +26 -8
  67. package/dist/local-devices/policy-summary.d.ts +25 -44
  68. package/dist/local-devices/policy-summary.js +26 -71
  69. package/dist/local-devices/relay.d.ts +6 -6
  70. package/dist/local-devices/relay.js +10 -8
  71. package/dist/net/public-address.d.ts +1 -1
  72. package/dist/net/public-address.js +5 -2
  73. package/dist/orgs/device-network-setting.d.ts +82 -0
  74. package/dist/orgs/device-network-setting.js +142 -0
  75. package/dist/orgs/settings.service.d.ts +103 -66
  76. package/dist/orgs/settings.service.js +201 -137
  77. package/dist/overrides.d.ts +5 -1
  78. package/dist/overrides.js +2 -0
  79. package/dist/platform/exclusions.js +1 -1
  80. package/dist/platform/operation.js +1 -1
  81. package/dist/platform/ops/admin.ops.js +20 -11
  82. package/dist/platform/ops/devices.ops.js +70 -5
  83. package/dist/platform/ops/org-settings.ops.js +10 -6
  84. package/dist/platform/ops/orgs.ops.js +2 -1
  85. package/dist/runtime/context/permission-profile.d.ts +17 -8
  86. package/dist/runtime/context/permission-profile.js +126 -45
  87. package/dist/runtime/permission-context.service.d.ts +1 -1
  88. package/dist/runtime/permission-context.service.js +5 -3
  89. package/dist/runtime/project/knowledge.d.ts +5 -4
  90. package/dist/runtime/project/knowledge.js +2 -1
  91. package/dist/runtime/project/knowledge.service.js +16 -13
  92. package/dist/sandbox/cloud-permission-snapshot.js +22 -3
  93. package/dist/sandbox/device-sandbox-settings.d.ts +230 -0
  94. package/dist/sandbox/device-sandbox-settings.js +470 -0
  95. package/dist/sandbox/device-sandbox.d.ts +187 -0
  96. package/dist/sandbox/device-sandbox.js +236 -0
  97. package/dist/sandbox/held-operations.js +15 -7
  98. package/dist/sandbox/modes.d.ts +49 -24
  99. package/dist/sandbox/modes.js +27 -19
  100. package/dist/sandbox/operation-authority-types.d.ts +6 -5
  101. package/dist/sandbox/operation-authority-types.js +7 -8
  102. package/dist/sandbox/operation-authority.d.ts +23 -9
  103. package/dist/sandbox/operation-authority.js +179 -97
  104. package/dist/sandbox/permission-auto-grants.d.ts +42 -0
  105. package/dist/sandbox/permission-auto-grants.js +145 -0
  106. package/dist/sandbox/permission-call-grants.d.ts +12 -4
  107. package/dist/sandbox/permission-call-grants.js +84 -35
  108. package/dist/sandbox/permission-call-grants.module.js +10 -3
  109. package/dist/sandbox/permission-call-types.d.ts +39 -5
  110. package/dist/sandbox/permission-ceiling-writes.d.ts +29 -3
  111. package/dist/sandbox/permission-ceiling-writes.js +38 -4
  112. package/dist/sandbox/permission-config-publication.d.ts +44 -2
  113. package/dist/sandbox/permission-config-publication.js +230 -59
  114. package/dist/sandbox/permission-context-types.d.ts +2 -2
  115. package/dist/sandbox/permission-facts.d.ts +144 -15
  116. package/dist/sandbox/permission-facts.js +258 -70
  117. package/dist/sandbox/permission-runtime-reports.d.ts +5 -4
  118. package/dist/sandbox/permission-runtime-reports.js +19 -29
  119. package/dist/sandbox/review/classifier.d.ts +8 -0
  120. package/dist/sandbox/review/classifier.js +10 -0
  121. package/dist/sandbox/review/permission-candidate.d.ts +69 -5
  122. package/dist/sandbox/review/permission-candidate.js +153 -30
  123. package/dist/sandbox/review/review.service.d.ts +19 -3
  124. package/dist/sandbox/review/review.service.js +59 -11
  125. package/dist/sandbox/review/rules.js +23 -3
  126. package/dist/sandbox/sandbox.service.d.ts +29 -11
  127. package/dist/sandbox/sandbox.service.js +51 -26
  128. package/dist/skills/invoke.js +3 -2
  129. package/dist/tools/approvals.service.d.ts +26 -116
  130. package/dist/tools/approvals.service.js +42 -346
  131. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  132. package/dist/tools/builtins/sandbox/bash.js +80 -28
  133. package/dist/tools/builtins/sandbox/common.d.ts +39 -14
  134. package/dist/tools/builtins/sandbox/common.js +47 -24
  135. package/dist/tools/builtins/sandbox/deliver.js +7 -4
  136. package/dist/tools/builtins/skill-load.d.ts +2 -2
  137. package/dist/tools/builtins/skill-load.js +4 -3
  138. package/dist/tools/device-op-resolver.d.ts +4 -10
  139. package/dist/tools/device-op-resolver.js +8 -19
  140. package/dist/tools/network-asks.d.ts +52 -15
  141. package/dist/tools/network-asks.js +55 -25
  142. package/dist/tools/pipeline.d.ts +26 -14
  143. package/dist/tools/pipeline.js +144 -61
  144. package/dist/tools/registry.d.ts +6 -0
  145. package/dist/tools/tools.module.js +1 -1
  146. package/package.json +4 -4
  147. package/src/migrations/0165_device_network_columns.sql +50 -0
  148. package/src/migrations/0166_permission_grant_full_access.sql +17 -0
  149. package/src/migrations/0167_device_network_backfill.sql +32 -0
  150. package/src/migrations/0168_binding_installed_connection.sql +6 -0
  151. package/dist/orgs/cloud-network-setting.d.ts +0 -33
  152. package/dist/orgs/cloud-network-setting.js +0 -47
  153. package/dist/sandbox/platform-full-access.d.ts +0 -110
  154. package/dist/sandbox/platform-full-access.js +0 -198
@@ -22,18 +22,17 @@ import { OutboxService } from "../infra/outbox/outbox.service.js";
22
22
  import { DevicePolicyService } from "../local-devices/device-policy.service.js";
23
23
  import { deviceLeaseKey } from "../local-devices/keys.js";
24
24
  import { MachinesService } from "../local-devices/machines.js";
25
- import { ownerFactsOf, ownerModeOf } from "../local-devices/owner-report.js";
25
+ import { ownerFactsOf } from "../local-devices/owner-report.js";
26
26
  import { deviceFeaturesOf, localPolicyOf } from "../local-devices/policy-summary.js";
27
- import { readOrgSettings } from "../orgs/settings.service.js";
27
+ import { hostGrantable } from "../sandbox/device-sandbox.js";
28
28
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
29
- import { cloudChosenMode, deviceNetwork, effectiveDevicePolicy, intersectNetworks, projectReachOf, readDeploymentDevicePolicy, } from "../sandbox/modes.js";
30
- import { permissionAvailabilityFor } from "../sandbox/permission-availability.js";
31
- import { needsFullCeiling, PermissionCeilingWrites, requiresFullExecution, } from "../sandbox/permission-ceiling-writes.js";
32
- import { readRuntimeReport } from "../sandbox/permission-runtime-reports.js";
33
- import { isInternalProvider, LOCAL_PROVIDER, providerForDevice, SandboxProviders, } from "../sandbox/providers.js";
29
+ import { coversHost, projectReachOf, } from "../sandbox/modes.js";
30
+ import { hostsNarrowed, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
31
+ import { cloudOwnNetwork, networkOfSandbox, PermissionFacts } from "../sandbox/permission-facts.js";
32
+ import { isInternalProvider, LOCAL_PROVIDER, SandboxProviders } from "../sandbox/providers.js";
34
33
  import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
35
34
  import { DeviceAccess, demotedProvider, deviceProvider, deviceUnavailable, inUseForDefault, } from "./access.js";
36
- /** How many recent mode and policy changes a device view lists. */
35
+ /** How many recent setting changes a device view lists. */
37
36
  export const RECENT_POLICY_CHANGES = 10;
38
37
  const isUniqueViolation = (e, constraint) => typeof e === "object" &&
39
38
  e !== null &&
@@ -61,11 +60,12 @@ let DevicesService = class DevicesService {
61
60
  machines;
62
61
  policies;
63
62
  ceilings;
63
+ facts;
64
64
  constructor(db, txHost, config, providers, sandbox, sandboxJobs,
65
65
  /** Owes a deleted device's destruction in the delete's transaction. */
66
66
  outbox, access, displayNames,
67
67
  /** Reads the device relay's lease (`online`). */
68
- locks, machines, policies, ceilings) {
68
+ locks, machines, policies, ceilings, facts) {
69
69
  this.db = db;
70
70
  this.txHost = txHost;
71
71
  this.config = config;
@@ -79,6 +79,7 @@ let DevicesService = class DevicesService {
79
79
  this.machines = machines;
80
80
  this.policies = policies;
81
81
  this.ceilings = ceilings;
82
+ this.facts = facts;
82
83
  }
83
84
  /**
84
85
  * The person's live devices in the org, the default first, then by creation. With a
@@ -254,131 +255,140 @@ let DevicesService = class DevicesService {
254
255
  await this.renameLocked(orgId, accountId, id, before, name, actorTokenId, auditDetail);
255
256
  }
256
257
  /**
257
- * `PATCH /devices/:id`: renames one of the person's live devices ({@link rename}) and narrows a
258
- * cloud device to sandbox mode, in one transaction. A local device's mode lives on its machine,
259
- * so a `mode` for it is refused (`device.mode_on_device`; {@link changePolicy}); auto mode is
260
- * never set from the web (auto mode spec §4.3). Callers make sure only a person in a session
261
- * changes a device.
258
+ * `PATCH /devices/:id`: renames one of the person's live devices ({@link rename}) and sets a
259
+ * cloud device's sandbox network ({@link networkLocked}), in one transaction. A network change
260
+ * takes the membership, the device row and the device's permission write lock as the ordered
261
+ * prelude (`withOrderedLocks`): inside a run's fence (`devices.set-network`) they follow the org
262
+ * row and precede the conversation rows. A local device's network lives on its machine
263
+ * (`device.ceiling_on_machine`). `narrowOnly` (an API token, the Platform tool): the network may
264
+ * only narrow, stored and effective.
262
265
  */
263
- async update(orgId, accountId, id, patch, actorTokenId) {
264
- await this.updateIn(orgId, accountId, id, patch, actorTokenId);
266
+ async update(orgId, accountId, id, patch, actorTokenId, opts = {}) {
267
+ if (patch.network !== undefined)
268
+ await withOrderedLocks(() => this.lockNetworkSubject(orgId, accountId, id), () => this.updateIn(orgId, accountId, id, patch, actorTokenId, opts));
269
+ else
270
+ await this.updateIn(orgId, accountId, id, patch, actorTokenId, opts);
265
271
  return this.get(orgId, accountId, id);
266
272
  }
267
- async updateIn(orgId, accountId, id, patch, actorTokenId) {
273
+ /** The prelude of a network change: the membership, the device row, the device's write lock. */
274
+ async lockNetworkSubject(orgId, accountId, id) {
275
+ await this.lockOwn(orgId, accountId, id);
276
+ await this.ceilings.lock({ orgId, deviceId: id }, "device");
277
+ }
278
+ async updateIn(orgId, accountId, id, patch, actorTokenId, opts) {
279
+ // held since the prelude for a network change (naming them again re-checks)
268
280
  const before = await this.lockOwn(orgId, accountId, id);
269
- if (patch.mode !== undefined) {
270
- await this.ceilings.lock({ orgId, deviceId: id }, "device");
271
- // A cloud device's owner narrows it to sandbox or clears the choice to follow the org (auto
272
- // mode spec §4.3, hardening D2); a local device's mode lives on its machine.
273
- if (before.source !== "cloud") {
274
- throw new ApiError("device.mode_on_device", "This device's owner ceiling is kept on its connected computer: narrow it from the device page, or run capybara-device ceiling set --full-access deny --project-reach workspace on that computer.");
275
- }
276
- if ((before.mode ?? null) !== patch.mode) {
277
- // `from` / `to` are the modes it runs at: the org may cap both at sandbox, and then the
278
- // stored choice changes without a mode change, so nothing is audited
279
- const from = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
280
- await this.db
281
- .updateTable("devices")
282
- .set({ mode: patch.mode, updated_at: sql `now()` })
283
- .where("id", "=", id)
284
- .execute();
285
- // B1: once snapshotted, the owner ceiling decides; sandbox narrows it, while clearing the
286
- // old switch never widens it (only a deliberate owner widening does)
287
- if (patch.mode === "sandbox")
288
- await this.db
289
- .updateTable("devices")
290
- .set({ owner_full_access: false })
291
- .where("id", "=", id)
292
- .where("owner_full_access", "=", true)
293
- .execute();
294
- const to = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
295
- await this.ceilings.publishLocked({ orgId, deviceId: id }, "device", to === "sandbox" ? needsFullCeiling : false, true);
296
- if (from !== to) {
297
- await audit(this.db.db, {
298
- actorAccountId: accountId,
299
- ...(actorTokenId !== undefined && { actorTokenId }),
300
- orgId,
301
- action: "device.mode_changed",
302
- target: id,
303
- detail: { from, to, by: accountId, via: "web" },
304
- });
305
- }
306
- }
307
- }
308
- if (patch.ownerCeiling !== undefined)
309
- await this.cloudOwnerCeilingLocked(orgId, accountId, id, before, patch, actorTokenId);
281
+ if (patch.network !== undefined)
282
+ await this.networkLocked(orgId, accountId, id, before, patch.network, actorTokenId, opts);
310
283
  if (patch.name !== undefined) {
311
- await this.renameLocked(orgId, accountId, id, before, patch.name, actorTokenId, undefined);
284
+ await this.renameLocked(orgId, accountId, id, before, patch.name, actorTokenId, opts.auditDetail);
312
285
  }
313
286
  }
314
287
  /**
315
- * B2 cloud owner ceiling (`PATCH ownerCeiling: {fullAccess}`), under the device authority
316
- * writer: a cloud device's explicit Full ceiling. Narrowing applies at once and revokes only Full
317
- * work; widening needs the person's explicit confirmation in a web session, is refused while
318
- * the platform or the org does not allow Full access, never touches the outer network, and
319
- * resets Full consent (conversations need fresh consent). A local device's ceiling is its
320
- * machine's (`device.mode_on_device`).
288
+ * Checks a cloud network change without writing anything and without locks (the Platform
289
+ * tool's precheck): the device is the person's live cloud device, and the change stays within
290
+ * the ceilings and, with `narrowOnly`, only narrows. Throws what {@link update} would; the
291
+ * write re-checks under its locks.
321
292
  */
322
- async cloudOwnerCeilingLocked(orgId, accountId, id, before, patch, actorTokenId) {
323
- const want = patch.ownerCeiling.fullAccess;
324
- await this.ceilings.lock({ orgId, deviceId: id }, "device");
293
+ async checkNetwork(orgId, accountId, id, network, narrowOnly) {
294
+ const row = await this.db
295
+ .selectFrom("devices")
296
+ .select(["source"])
297
+ .where("id", "=", id)
298
+ .where("org_id", "=", orgId)
299
+ .where("owner_kind", "=", "personal")
300
+ .where("owner_account_id", "=", accountId)
301
+ .where("deleted_at", "is", null)
302
+ .executeTakeFirst();
303
+ if (!row)
304
+ throw deviceNotFound();
305
+ await this.planNetwork(orgId, id, row, network, narrowOnly);
306
+ }
307
+ /**
308
+ * Decides a cloud network change (read only): the stored setting before and after, the
309
+ * effective device sandbox before and after (computed in memory from the patched setting), and
310
+ * whether it widens. Refuses, without writing: a local device (`device.ceiling_on_machine`),
311
+ * the open network above the ceilings or a host outside the org's list
312
+ * (`device.network_not_allowed`), and with `narrowOnly` a widening of the stored setting or of
313
+ * the effective network (`device.network_not_allowed`). Null when nothing changes.
314
+ */
315
+ async planNetwork(orgId, id, before, want, narrowOnly) {
325
316
  if (before.source !== "cloud")
326
- throw new ApiError("device.mode_on_device", "This device's owner ceiling is kept on its connected machine: narrow it from the device page or run capybara-device ceiling set there.");
317
+ throw new ApiError("device.ceiling_on_machine", "This device's sandbox network is kept on its connected machine: narrow it from the device page, or widen it on that machine with capybara-device ceiling set --network open or capybara-device policy add allowedDomains <host>.");
327
318
  const row = await this.db
328
319
  .selectFrom("devices")
329
- .select(["owner_full_access", "mode", "provider", "outer_network"])
320
+ .select(["network_mode", "network_hosts"])
330
321
  .where("id", "=", id)
331
322
  .executeTakeFirstOrThrow();
332
- // the explicit ceiling exists only once B1 snapshotted the device's old effective authority
333
- // and its outer network (under the exclusive lifecycle lease, which a request cannot take
334
- // inside its transaction): writing it first would pre-empt the snapshot and could leave the
335
- // outer network open, so the PATCH is refused until then (the old sandbox switch narrows)
336
- if (row.owner_full_access === null || row.outer_network === null)
337
- throw new ApiError("device.permission_not_migrated", "This device's permissions have not been migrated yet; switch it to sandbox mode to narrow it, and set its Full access ceiling once the migration has run");
338
- const current = cloudChosenMode(row) !== "sandbox";
339
- if (want === current)
323
+ const own = cloudOwnNetwork(row);
324
+ const from = { mode: own.networkMode, hosts: [...own.networkHosts] };
325
+ const to = {
326
+ mode: want.mode,
327
+ hosts: want.mode === "allowlist"
328
+ ? [...new Set((want.hosts ?? []).map((h) => h.toLowerCase()))].sort()
329
+ : [],
330
+ };
331
+ if (from.mode === to.mode && sameHosts(from.hosts, to.hosts))
332
+ return null;
333
+ const [prev, next] = await Promise.all([
334
+ this.facts.deviceSandboxFacts(orgId, id),
335
+ this.facts.deviceSandboxFacts(orgId, id, undefined, {
336
+ networkMode: to.mode,
337
+ networkHosts: to.hosts,
338
+ }),
339
+ ]);
340
+ if (to.mode === "open" && next.box.networkMode !== "open")
341
+ throw new ApiError("device.network_not_allowed", `The open network is not allowed for this device: ${networkLayerText(next.box.layer.network)} limits it to ${next.box.networkCeiling === "none" ? "no network" : "the allowlist"}`);
342
+ // a device's own list only narrows its org's hosts, whatever the network in effect now
343
+ const outside = to.hosts.filter((h) => !next.orgHosts.some((p) => coversHost(p.toLowerCase(), h)));
344
+ if (outside.length > 0)
345
+ throw new ApiError("device.network_not_allowed", `A device's host list only narrows its organization's hosts; an organization admin adds ${outside.join(", ")} to the organization's device network list`);
346
+ const widened = networkWidens(prev.box, next.box);
347
+ if (narrowOnly && (widened || storedNetworkWidens(from, to)))
348
+ throw new ApiError("device.network_not_allowed", "Through an API token or the Platform tool a device's network may only narrow (to allowlist, its own shorter host list, or none; never back to following the organization); its owner widens it on the device page");
349
+ return { from, to, next, widened };
350
+ }
351
+ /**
352
+ * A cloud device's sandbox network (approval-only profiles design, "Settings model"), under the
353
+ * device authority writer held since the prelude: its owner chooses `open`, `allowlist` (its
354
+ * org's hosts, narrowed by its own list: a device list never adds a host; an empty one follows
355
+ * the org's hosts), `none` (closed) or null (follow the org), in both directions within the
356
+ * org's and the platform's ceilings ({@link planNetwork}). The write and its publication are one
357
+ * transaction: a narrowing bumps the device epoch and revokes the admitted or started work it
358
+ * takes ({@link networkNarrowingRevokes}; the revocations are owed through the outbox) and keeps
359
+ * Full consent; a widening resets Full consent with a `permission_profile_changed` event.
360
+ * Audited `device.network_changed` (`via`: `web`, `token` for an API token, or the agent's).
361
+ */
362
+ async networkLocked(orgId, accountId, id, before, want, actorTokenId, opts) {
363
+ await this.ceilings.lock({ orgId, deviceId: id }, "device");
364
+ const plan = await this.planNetwork(orgId, id, before, want, opts.narrowOnly === true);
365
+ if (plan === null)
340
366
  return;
341
- if (want && !current) {
342
- if (patch.confirmWidening !== true)
343
- throw new ApiError("device.owner_ceiling_confirmation_required", "Widening a device's Full access ceiling needs explicit confirmation; conversations then need fresh Full consent");
344
- const policy = await this.sandbox.devicePolicy({ orgId, deviceId: id });
345
- if (policy.allowedMode !== "auto")
346
- throw new ApiError("device.full_access_not_allowed", "The platform or the organization does not allow Full access, so this device's ceiling cannot be widened");
347
- // M3: nor beyond what the provider can enforce (a report or a provider without Full)
348
- const provider = providerForDevice(this.providers, row.provider);
349
- let availability = permissionAvailabilityFor(provider?.impl);
350
- if (availability.state === "unprobed" && provider)
351
- availability = await readRuntimeReport(this.db.db, id, provider.plugin, provider.version);
352
- if (availability.state === "unsupported" ||
353
- (availability.state === "supported" && !availability.report.fullAccess))
354
- throw new ApiError("device.full_access_not_allowed", "This device's sandbox provider cannot run Full access, so its ceiling cannot be widened");
355
- }
367
+ const { from, to, next, widened } = plan;
356
368
  await this.db
357
369
  .updateTable("devices")
358
370
  .set({
359
- owner_full_access: want,
360
- // the old sandbox switch no longer decides once the explicit ceiling is set
361
- ...(want && { mode: null }),
371
+ network_mode: to.mode,
372
+ network_hosts: JSON.stringify(to.hosts),
362
373
  updated_at: sql `now()`,
363
374
  })
364
375
  .where("id", "=", id)
365
376
  .execute();
366
- if (want !== current) {
367
- await this.ceilings.publishLocked({ orgId, deviceId: id }, "device", want ? false : requiresFullExecution, true);
368
- await audit(this.db.db, {
369
- actorAccountId: accountId,
370
- ...(actorTokenId !== undefined && { actorTokenId }),
371
- orgId,
372
- action: "device.owner_ceiling_changed",
373
- target: id,
374
- detail: {
375
- from: { fullAccess: current },
376
- to: { fullAccess: want },
377
- by: accountId,
378
- via: "web",
379
- },
380
- });
381
- }
377
+ await this.ceilings.publishLocked({ orgId, deviceId: id }, "device", (scope, intent) => networkNarrowingRevokes(next, scope, intent), widened);
378
+ await audit(this.db.db, {
379
+ actorAccountId: accountId,
380
+ ...(actorTokenId !== undefined && { actorTokenId }),
381
+ orgId,
382
+ action: "device.network_changed",
383
+ target: id,
384
+ detail: {
385
+ from,
386
+ to,
387
+ by: accountId,
388
+ via: actorTokenId !== undefined ? "token" : "web",
389
+ ...opts.auditDetail,
390
+ },
391
+ });
382
392
  }
383
393
  /**
384
394
  * How far restricted work may root outside the device's workspace now (B2): a local machine's
@@ -400,42 +410,26 @@ let DevicesService = class DevicesService {
400
410
  return projectReachOf(row.source, policy, row.source === "local" ? ownerFactsOf(row).restrictedProjectReach : null);
401
411
  }
402
412
  /**
403
- * The mode a sandbox call in the device runs at now, for the model (`device_paths`, auto mode
404
- * spec §4.2): the effective policy for the mode it runs at (a local machine's derived mode,
405
- * failing closed; a cloud device's narrowing switch, else the allowed mode), its network, and a
406
- * cloud device's pending file-reset state (the mode and network its instance still runs with).
407
- * Null when the device is not a live device of the org.
413
+ * The level a sandbox call in the device runs at now, for the model (legacy `device_paths`, auto
414
+ * mode spec §4.2): the kernel-internal tier (`SandboxMode`: a local machine's owner permission to
415
+ * run outside the sandbox, failing closed) with its device sandbox network, and a cloud device's
416
+ * pending file-reset state (the tier and network its instance still runs with). Null when the
417
+ * device is not a live device of the org.
408
418
  */
409
419
  async modeLevel(orgId, deviceId) {
410
420
  const row = await this.db
411
- .selectFrom("devices as e")
412
- .leftJoin("device_machines as m", (j) => j.onRef("m.device_id", "=", "e.id").on("m.revoked_at", "is", null))
413
- .select([
414
- "e.source",
415
- "e.mode",
416
- "e.owner_full_access",
417
- "e.outer_network",
418
- "m.features",
419
- "m.local_policy",
420
- "m.owner_report",
421
- ])
422
- .where("e.id", "=", deviceId)
423
- .where("e.org_id", "=", orgId)
424
- .where("e.deleted_at", "is", null)
421
+ .selectFrom("devices")
422
+ .select(["source"])
423
+ .where("id", "=", deviceId)
424
+ .where("org_id", "=", orgId)
425
+ .where("deleted_at", "is", null)
425
426
  .executeTakeFirst();
426
427
  if (row === undefined)
427
428
  return null;
428
- const [deployment, settings] = await Promise.all([
429
- readDeploymentDevicePolicy(this.db.db, this.config),
430
- readOrgSettings(this.db.db, orgId),
431
- ]);
432
- // a local device's mode is derived fail-closed; a cloud device's switch (or its B1 owner
433
- // ceiling and outer network once snapshotted) only narrows it
434
- const chosen = row.source === "local" ? ownerModeOf(row) : cloudChosenMode(row);
435
- const policy = effectiveDevicePolicy(deployment, settings, chosen, row.source === "local" ? null : row.outer_network);
429
+ const policy = await this.sandbox.devicePolicy({ orgId, deviceId });
436
430
  let mode = policy.mode;
437
431
  let network = row.source === "local"
438
- ? { kind: "allowlist", hosts: [...policy.localAllowedDomains] }
432
+ ? networkOfSandbox(await this.facts.deviceSandbox(orgId, deviceId))
439
433
  : policy.network;
440
434
  if (row.source === "cloud") {
441
435
  const state = await this.sandbox.limitsState({ orgId, deviceId }, { policy });
@@ -533,14 +527,15 @@ let DevicesService = class DevicesService {
533
527
  await this.machines.revoke(orgId, accountId, id, actorTokenId);
534
528
  }
535
529
  /**
536
- * The owner changes one of their own devices' local policy (network ask-to-allow spec §7, §13
537
- * Q6; auto mode spec §4.1): sent to the machine with the `policy` op, which is the authority and
538
- * answers with the policy as written. Anyone but the owner gets `device.not_found`. The owner may
539
- * add or remove sandbox-mode hosts, and turn the sandbox back on (`mode: "sandbox"`); auto mode
540
- * is turned on only on the machine. The machine offline → `device.offline`; a cloud device or a
541
- * program without the `policyOpId` feature → `device.policy_unsupported`; the machine's refusal →
542
- * `device.policy_refused` with its message. Callers are human sessions only (no personal access
543
- * token, no service token, no Platform op).
530
+ * The owner narrows one of their own local devices' sandbox from the web (approval-only
531
+ * profiles design, "Settings model"): sent to the machine with the `policy` op, which is the
532
+ * authority and answers with the policy as written. Anyone but the owner gets
533
+ * `device.not_found`. The owner may remove hosts from the machine's allowlist and narrow its
534
+ * owner ceiling (no running outside the sandbox, the allowlist network, the workspace reach);
535
+ * widening happens on the machine only. The machine offline → `device.offline`; a cloud device
536
+ * or a program without the `policyOpId` feature → `device.policy_unsupported`; the machine's
537
+ * refusal → `device.policy_refused` with its message. Callers are human sessions only (no
538
+ * personal access token, no service token, no Platform op).
544
539
  */
545
540
  async changePolicy(orgId, account, id, change) {
546
541
  await this.access.usable(orgId, account.id, id);
@@ -548,9 +543,7 @@ let DevicesService = class DevicesService {
548
543
  orgId,
549
544
  deviceId: id,
550
545
  change: {
551
- ...(change.add !== undefined && { add: change.add }),
552
546
  ...(change.remove !== undefined && { remove: change.remove }),
553
- ...(change.mode !== undefined && { mode: change.mode }),
554
547
  ...(change.ownerCeiling !== undefined && { ownerCeiling: narrowOnly(change.ownerCeiling) }),
555
548
  },
556
549
  source: { accountId: account.id, accountName: account.displayName, via: "web" },
@@ -849,9 +842,8 @@ let DevicesService = class DevicesService {
849
842
  "e.source",
850
843
  "e.provider",
851
844
  "e.demoted_from_provider",
852
- "e.mode",
853
- "e.owner_full_access",
854
- "e.outer_network",
845
+ "e.network_mode",
846
+ "e.network_hosts",
855
847
  "e.permission_reconcile_required",
856
848
  "e.created_at",
857
849
  "m.id as machine_id",
@@ -902,36 +894,21 @@ let DevicesService = class DevicesService {
902
894
  const demotedProviders = [
903
895
  ...new Set(rows.flatMap((r) => (demoted.get(r.id) ? [demoted.get(r.id)] : []))),
904
896
  ];
905
- const [names, recent, settings, deployment] = await Promise.all([
897
+ const [names, recent] = await Promise.all([
906
898
  this.displayNames.many(demotedProviders),
907
- this.recentModeChanges(orgId, rows.map((r) => r.id)),
908
- readOrgSettings(this.db.db, orgId),
909
- readDeploymentDevicePolicy(this.db.db, this.config),
899
+ this.recentChanges(orgId, rows.map((r) => r.id)),
910
900
  ]);
911
- const summaryOf = (r) => r.source === "local" ? localPolicyOf(r.machine_local_policy) : null;
912
- /** The mode the device chose: its machine's report (local) or its switch (cloud: sandbox, or null to follow the org). */
913
- const chosenOf = (r) => r.source === "local"
914
- ? ownerModeOf({
915
- features: r.machine_features,
916
- local_policy: r.machine_local_policy,
917
- owner_report: r.machine_owner_report,
918
- })
919
- : cloudChosenMode(r);
920
- const policyOf = (r) => effectiveDevicePolicy(deployment, settings, chosenOf(r), r.source === "local" ? null : r.outer_network);
921
- // the network each mode gives a cloud device, within its outer network once snapshotted
922
- const sandboxNetwork = deviceNetwork(deployment, settings, "sandbox");
923
- const fullNetwork = deviceNetwork(deployment, settings, "auto");
924
- const within = (n, outer) => outer === null ? n : intersectNetworks(n, outer);
925
- // each device's limits and its instance's pending change
901
+ // each device's sandbox, limits and its instance's pending change
926
902
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
927
- const policy = policyOf(r);
928
- const [limits, state] = await Promise.all([
903
+ const policy = await this.sandbox.devicePolicy({ orgId, deviceId: r.id });
904
+ const [limits, state, facts] = await Promise.all([
929
905
  this.sandbox.deviceLimits({ orgId, deviceId: r.id }, { policy, source: r.source }),
930
906
  r.source === "cloud"
931
907
  ? this.sandbox.limitsState({ orgId, deviceId: r.id }, { policy })
932
908
  : { pendingNextUse: false, pendingFilesReset: false },
909
+ this.facts.deviceSandboxFacts(orgId, r.id),
933
910
  ]);
934
- return [r.id, { limits, state }];
911
+ return [r.id, { limits, state, box: facts.box }];
935
912
  })));
936
913
  const current = this.providers.cloud()?.plugin;
937
914
  // a local device is online while a replica holds its machine's connection lease
@@ -976,15 +953,14 @@ let DevicesService = class DevicesService {
976
953
  policy: localPolicyOf(r.machine_local_policy),
977
954
  }
978
955
  : null,
979
- mode: deviceModeViewOf(policyOf(r), settings, r.source === "local", summaryOf(r), {
956
+ sandbox: sandboxViewOf(perDevice.get(r.id)?.box, r.source === "local"
957
+ ? ownerFactsOf({ owner_report: r.machine_owner_report })
958
+ : cloudOwnNetwork(r), {
980
959
  pendingNextUse: perDevice.get(r.id)?.state.pendingNextUse ?? false,
981
960
  pendingFilesReset: perDevice.get(r.id)?.state.pendingFilesReset ?? false,
982
961
  recent: recent.get(r.id) ?? [],
983
- sandboxNetwork: within(sandboxNetwork, r.outer_network),
984
- fullNetwork: within(fullNetwork, r.outer_network),
985
- outerNetwork: r.source === "local" ? null : r.outer_network,
986
- }, this.config.get().sandbox.limits.egress === "none"),
987
- // a local device's machine decides it; cloud devices have none in phase 2
962
+ }),
963
+ // a local device's machine decides it; a cloud device has none
988
964
  ownerCeiling: ownerCeilingViewOf(r, online.get(r.id) ?? false),
989
965
  reconcileRequired: r.source === "cloud" && r.permission_reconcile_required,
990
966
  sessionIsolation: r.machine_session_isolation ?? false,
@@ -1001,12 +977,10 @@ let DevicesService = class DevicesService {
1001
977
  });
1002
978
  }
1003
979
  /**
1004
- * The last {@link RECENT_POLICY_CHANGES} mode and policy changes of each device in the org
1005
- * (audit rows `device.policy_changed`, `device.policy_unknown`, `device.policy_failed`,
1006
- * `device.mode_changed`, `device.owner_ceiling_changed`), newest first, with the deciding
1007
- * account's display name.
980
+ * The last {@link RECENT_POLICY_CHANGES} setting changes of each device in the org (audit rows
981
+ * {@link SETTING_CHANGE_ACTIONS}), newest first, with the deciding account's display name.
1008
982
  */
1009
- async recentModeChanges(orgId, deviceIds) {
983
+ async recentChanges(orgId, deviceIds) {
1010
984
  const out = new Map();
1011
985
  if (deviceIds.length === 0)
1012
986
  return out;
@@ -1021,7 +995,7 @@ let DevicesService = class DevicesService {
1021
995
  sql `row_number() OVER (PARTITION BY a.target ORDER BY a.at DESC, a.id DESC)`.as("n"),
1022
996
  ])
1023
997
  .where("a.org_id", "=", orgId)
1024
- .where("a.action", "in", [...MODE_CHANGE_ACTIONS])
998
+ .where("a.action", "in", [...SETTING_CHANGE_ACTIONS])
1025
999
  .where("a.target", "in", deviceIds);
1026
1000
  const rows = await this.db
1027
1001
  .selectFrom(ranked.as("r"))
@@ -1034,7 +1008,7 @@ let DevicesService = class DevicesService {
1034
1008
  if (r.target === null)
1035
1009
  continue;
1036
1010
  const list = out.get(r.target) ?? [];
1037
- list.push(modeChangeOf(r.action, r.at, (r.detail ?? {}), r.display_name ?? null));
1011
+ list.push(settingChangeOf(r.action, r.at, (r.detail ?? {}), r.display_name ?? null));
1038
1012
  out.set(r.target, list);
1039
1013
  }
1040
1014
  return out;
@@ -1071,7 +1045,7 @@ let DevicesService = class DevicesService {
1071
1045
  await this.lockMember(orgId, accountId);
1072
1046
  const row = await this.db
1073
1047
  .selectFrom("devices")
1074
- .select(["name", "is_default", "source", "mode"])
1048
+ .select(["name", "is_default", "source"])
1075
1049
  .where("id", "=", id)
1076
1050
  .where("org_id", "=", orgId)
1077
1051
  .where("owner_kind", "=", "personal")
@@ -1105,6 +1079,9 @@ __decorate([
1105
1079
  __decorate([
1106
1080
  Transactional()
1107
1081
  ], DevicesService.prototype, "renameIn", null);
1082
+ __decorate([
1083
+ Transactional({ propagation: "mandatory" })
1084
+ ], DevicesService.prototype, "lockNetworkSubject", null);
1108
1085
  __decorate([
1109
1086
  Transactional()
1110
1087
  ], DevicesService.prototype, "updateIn", null);
@@ -1134,7 +1111,8 @@ DevicesService = __decorate([
1134
1111
  __param(9, Inject(LockService)),
1135
1112
  __param(10, Inject(MachinesService)),
1136
1113
  __param(11, Inject(DevicePolicyService)),
1137
- __param(12, Inject(PermissionCeilingWrites))
1114
+ __param(12, Inject(PermissionCeilingWrites)),
1115
+ __param(13, Inject(PermissionFacts))
1138
1116
  ], DevicesService);
1139
1117
  export { DevicesService };
1140
1118
  /**
@@ -1146,63 +1124,132 @@ function refuseDeviceReset(env) {
1146
1124
  throw new ApiError("device.files_on_device", "This device's files are in a directory on its connected machine and cannot be reset from here. To start over, run capybara-device logout, then capybara-device login into this device, on that machine.");
1147
1125
  }
1148
1126
  }
1149
- /** A copy of `l` for a view (its lists not shared). */
1150
- const limitsView = (l) => ({
1151
- ...l,
1152
- network: { kind: l.network.kind, hosts: [...l.network.hosts] },
1153
- });
1154
- /** The audit actions a device's recent mode, policy and ceiling changes list. */
1155
- const MODE_CHANGE_ACTIONS = [
1127
+ /** A copy of `l` for a view (its lists not shared; the kernel-internal tier left out). */
1128
+ const limitsView = (l) => {
1129
+ const { mode: _kernelOnly, ...rest } = l;
1130
+ return { ...rest, network: { kind: l.network.kind, hosts: [...l.network.hosts] } };
1131
+ };
1132
+ const sameHosts = (a, b) => a.length === b.length && a.every((h, i) => h === b[i]);
1133
+ const NETWORK_RANK = { none: 0, allowlist: 1, open: 2 };
1134
+ /**
1135
+ * Whether the effective sandbox network widens from `a` to `b`: a wider mode, or an allowlist
1136
+ * gaining a host the previous one did not cover.
1137
+ */
1138
+ function networkWidens(a, b) {
1139
+ if (NETWORK_RANK[b.networkMode] !== NETWORK_RANK[a.networkMode])
1140
+ return NETWORK_RANK[b.networkMode] > NETWORK_RANK[a.networkMode];
1141
+ return (b.networkMode === "allowlist" &&
1142
+ b.hosts.some((h) => !a.hosts.some((p) => coversHost(p.toLowerCase(), h.toLowerCase()))));
1143
+ }
1144
+ const STORED_RANK = { none: 0, allowlist: 1, open: 2 };
1145
+ /**
1146
+ * Whether a cloud device's stored network setting widens from `a` to `b`, whatever the network in
1147
+ * effect now (a stored widening takes effect when a ceiling opens later): a wider mode, where
1148
+ * following the org (null) counts as wider than any explicit mode; or an explicit host list
1149
+ * replaced by none of its own (follow the org's hosts) or gaining a host.
1150
+ */
1151
+ export function storedNetworkWidens(a, b) {
1152
+ const rank = (m) => (m === null ? 3 : STORED_RANK[m]);
1153
+ if (rank(b.mode) !== rank(a.mode))
1154
+ return rank(b.mode) > rank(a.mode);
1155
+ if (b.mode !== "allowlist" || a.hosts.length === 0)
1156
+ return false;
1157
+ if (b.hosts.length === 0)
1158
+ return true;
1159
+ return b.hosts.some((h) => !a.hosts.some((p) => coversHost(p.toLowerCase(), h.toLowerCase())));
1160
+ }
1161
+ /**
1162
+ * What a cloud device's new network takes from admitted or started work (`next`: its sandbox
1163
+ * after the change): open-network work once it is no longer open, and allowlist work naming a host
1164
+ * its new hosts no longer cover, unless an independent grant the new per-call ceiling still allows
1165
+ * holds it (`hostsNarrowed`).
1166
+ */
1167
+ export function networkNarrowingRevokes(next, scope, intent) {
1168
+ if (next.box.networkMode === "open")
1169
+ return false;
1170
+ return (needsOpenNetwork(scope) ||
1171
+ hostsNarrowed(scope, intent, next.box.hosts, (host) => hostGrantable(next.hostCeiling, host)));
1172
+ }
1173
+ /** Who set a network ceiling, for an actionable refusal. */
1174
+ function networkLayerText(layer) {
1175
+ switch (layer) {
1176
+ case "platform":
1177
+ return "the platform (a super admin)";
1178
+ case "org":
1179
+ return "the organization (an org admin)";
1180
+ case "provider":
1181
+ return "its sandbox provider";
1182
+ default:
1183
+ return "its owner";
1184
+ }
1185
+ }
1186
+ /** The audit actions a device's recent setting changes list. */
1187
+ const SETTING_CHANGE_ACTIONS = [
1156
1188
  "device.policy_changed",
1157
1189
  "device.policy_unknown",
1158
1190
  "device.policy_failed",
1159
- "device.mode_changed",
1160
1191
  "device.owner_ceiling_changed",
1192
+ "device.network_changed",
1161
1193
  ];
1162
- const modeOrNull = (v) => (v === "auto" || v === "sandbox" ? v : null);
1163
1194
  /** One side of an audited ceiling change; null when the row does not carry a readable one. */
1164
1195
  function ceilingFactsOf(v) {
1165
1196
  if (typeof v !== "object" || v === null)
1166
1197
  return null;
1167
1198
  const o = v;
1168
- if (typeof o.fullAccess !== "boolean")
1199
+ // rows written before the rename carry the same fact as `fullAccess`
1200
+ const outside = typeof o.outsideSandbox === "boolean" ? o.outsideSandbox : o.fullAccess;
1201
+ if (typeof outside !== "boolean")
1169
1202
  return null;
1170
1203
  const reach = o.restrictedProjectReach;
1171
1204
  return {
1172
- fullAccess: o.fullAccess,
1205
+ outsideSandbox: outside,
1173
1206
  ...((reach === "workspace" || reach === "os-user") && { restrictedProjectReach: reach }),
1207
+ ...((o.network === "open" || o.network === "allowlist") && { network: o.network }),
1208
+ };
1209
+ }
1210
+ /** One side of an audited cloud network change. */
1211
+ function networkSettingOf(v) {
1212
+ const o = (typeof v === "object" && v !== null ? v : {});
1213
+ const mode = o.mode;
1214
+ return {
1215
+ mode: mode === "open" || mode === "allowlist" || mode === "none" ? mode : null,
1216
+ hosts: Array.isArray(o.hosts) ? o.hosts.filter((h) => typeof h === "string") : [],
1174
1217
  };
1175
1218
  }
1176
- /** One audit row of {@link MODE_CHANGE_ACTIONS} as a {@link DeviceModeChangeView}. */
1177
- function modeChangeOf(action, at, d, by) {
1219
+ /** One audit row of {@link SETTING_CHANGE_ACTIONS} as a {@link DeviceSettingChangeView}. */
1220
+ function settingChangeOf(action, at, d, by) {
1178
1221
  const hosts = (v) => Array.isArray(v) ? v.filter((h) => typeof h === "string") : [];
1179
- const base = { at: at.toISOString(), add: [], remove: [], mode: null, ceiling: null, by };
1222
+ const via = d.via === "im"
1223
+ ? "im"
1224
+ : d.via === "device"
1225
+ ? "device"
1226
+ : d.via === "token"
1227
+ ? "token"
1228
+ : d.via === "agent"
1229
+ ? "agent"
1230
+ : "web";
1231
+ const base = { at: at.toISOString(), add: [], remove: [], ceiling: null, network: null, by, via };
1180
1232
  if (action === "device.owner_ceiling_changed") {
1181
1233
  const to = ceilingFactsOf(d.to);
1182
1234
  return {
1183
1235
  ...base,
1184
1236
  kind: "ceiling",
1185
1237
  ceiling: to === null ? null : { from: ceilingFactsOf(d.from), to },
1186
- via: d.via === "im" ? "im" : d.via === "device" ? "device" : "web",
1187
1238
  outcome: "applied",
1188
1239
  };
1189
1240
  }
1190
- if (action === "device.mode_changed") {
1191
- const to = modeOrNull(d.to);
1241
+ if (action === "device.network_changed")
1192
1242
  return {
1193
1243
  ...base,
1194
- kind: "mode",
1195
- mode: to === null ? null : { ...(d.from !== undefined && { from: modeOrNull(d.from) }), to },
1196
- via: d.via === "im" ? "im" : d.via === "device" ? "device" : "web",
1244
+ kind: "network",
1245
+ network: { from: networkSettingOf(d.from), to: networkSettingOf(d.to) },
1197
1246
  outcome: "applied",
1198
1247
  };
1199
- }
1200
1248
  return {
1201
1249
  ...base,
1202
1250
  kind: "policy",
1203
1251
  add: hosts(d.add),
1204
1252
  remove: hosts(d.remove),
1205
- via: d.via === "im" ? "im" : d.via === "device" ? "device" : "web",
1206
1253
  outcome: action === "device.policy_unknown"
1207
1254
  ? "unknown"
1208
1255
  : action === "device.policy_failed"
@@ -1211,105 +1258,50 @@ function modeChangeOf(action, at, d, by) {
1211
1258
  };
1212
1259
  }
1213
1260
  /**
1214
- * The mode view of one device (auto mode spec §4.3): its effective policy with the mode its
1215
- * machine reported (`summary`, local devices only), the network and where it comes from, and the
1216
- * instance's pending change with the recent changes.
1261
+ * The sandbox view of one device: its effective {@link DeviceSandbox} with its own network setting
1262
+ * (`own`: a local machine's owner facts, a cloud device's stored choice) and the instance's pending
1263
+ * change with the recent changes.
1217
1264
  */
1218
- export function deviceModeViewOf(policy, settings, local, summary, extra,
1219
- /** The platform kill switch (`sandbox.limits.egress: none`): the network is the platform's. */
1220
- killSwitch = false) {
1221
- const { sandboxNetwork, fullNetwork, outerNetwork, ...rest } = extra;
1222
- const copy = (n) => local || n === null ? null : { kind: n.kind, hosts: [...n.hosts] };
1223
- const networkKind = local ? "allowlist" : policy.network.kind;
1224
- const org = settings.cloudNetwork;
1225
- // "org" only when the org supplied what is in effect: the kill switch always wins; auto mode
1226
- // ignores the org's network; a local device's list is the org's only when the org changed the
1227
- // platform's (its own base or a delta); a sandbox cloud device's kind is the org's when it
1228
- // matches the mode the org chose (the platform ceiling may force the allowlist)
1229
- const orgHosts = org?.base === "none" ||
1230
- (org?.extraHosts?.length ?? 0) > 0 ||
1231
- (org?.excludedHosts?.length ?? 0) > 0;
1232
- const source = killSwitch
1233
- ? "platform"
1234
- : local
1235
- ? policy.mode === "sandbox" && orgHosts
1236
- ? "org"
1237
- : "platform"
1238
- : policy.mode === "sandbox" &&
1239
- org?.mode !== undefined &&
1240
- (org.mode === "open" ? networkKind === "open-public" : networkKind === "allowlist")
1241
- ? "org"
1242
- : "platform";
1243
- const network = local
1244
- ? { kind: "allowlist", hosts: [...policy.localAllowedDomains], source }
1245
- : { kind: policy.network.kind, hosts: [...policy.network.hosts], source };
1265
+ export function sandboxViewOf(box, own, extra) {
1266
+ const local = "state" in own;
1246
1267
  return {
1247
- mode: policy.mode,
1248
- allowedMode: policy.allowedMode,
1249
- allowedBy: policy.allowedMode === "sandbox"
1250
- ? null
1251
- : settings.fullAccess === "allowed"
1252
- ? "org"
1253
- : "platform",
1254
- network,
1255
- local: local
1256
- ? {
1257
- reported: summary?.mode ?? null,
1258
- allowedDomains: [...(summary?.allowedDomains ?? [])],
1259
- }
1260
- : null,
1261
- sandboxNetwork: copy(sandboxNetwork),
1262
- fullNetwork: copy(fullNetwork),
1263
- outerNetwork: copy(outerNetwork),
1264
- ...rest,
1268
+ network: box.networkMode,
1269
+ networkCeiling: box.networkCeiling,
1270
+ hosts: [...box.hosts],
1271
+ ownNetwork: local ? (own.state === "missing" ? null : own.network) : own.networkMode,
1272
+ allowedDomains: local ? [...own.allowedDomains] : [...own.networkHosts],
1273
+ outsideSandbox: box.outsideSandbox,
1274
+ restrictedProjectReach: box.restrictedProjectReach,
1275
+ layer: { ...box.layer },
1276
+ ...extra,
1265
1277
  };
1266
1278
  }
1267
- /** The read-only owner ceiling view of a listed device row (B2). */
1279
+ /** The read-only owner ceiling view of a listed local device row. */
1268
1280
  function ownerCeilingViewOf(r, online) {
1269
- if (r.source === "cloud")
1270
- return r.owner_full_access === null
1271
- ? null
1272
- : {
1273
- state: "cloud",
1274
- revision: null,
1275
- sequence: null,
1276
- fullAccess: r.owner_full_access,
1277
- effectiveFullAccess: cloudChosenMode(r) !== "sandbox",
1278
- restrictedProjectReach: "workspace",
1279
- restrictedAllowedDomains: [],
1280
- observedAt: null,
1281
- stale: false,
1282
- };
1283
- if (r.machine_id === null)
1281
+ if (r.source === "cloud" || r.machine_id === null)
1284
1282
  return null;
1285
- const f = ownerFactsOf({
1286
- owner_report: r.machine_owner_report,
1287
- local_policy: r.machine_local_policy,
1288
- });
1283
+ const f = ownerFactsOf({ owner_report: r.machine_owner_report });
1289
1284
  return {
1290
1285
  state: f.state,
1291
1286
  revision: f.revision,
1292
1287
  sequence: f.sequence,
1293
- fullAccess: f.fullAccess,
1294
- // the mode admission derives (an old program without a report included), fail closed
1295
- effectiveFullAccess: ownerModeOf({
1296
- features: r.machine_features,
1297
- local_policy: r.machine_local_policy,
1298
- owner_report: r.machine_owner_report,
1299
- }) === "auto",
1288
+ outsideSandbox: f.outsideSandbox,
1289
+ network: f.network,
1290
+ allowedDomains: [...f.allowedDomains],
1300
1291
  restrictedProjectReach: f.restrictedProjectReach,
1301
- restrictedAllowedDomains: f.restrictedAllowedDomains,
1302
1292
  observedAt: f.observedAt,
1303
1293
  stale: !online || f.state !== "report",
1304
1294
  };
1305
1295
  }
1306
- /** The owner ceiling narrowing the web may send (B2): anything wider is refused, never sent. */
1296
+ /** The owner ceiling narrowing the web may send: anything wider is refused, never sent. */
1307
1297
  function narrowOnly(c) {
1308
- if ((c.fullAccess !== undefined && c.fullAccess !== false) ||
1298
+ if ((c.outsideSandbox !== undefined && c.outsideSandbox !== false) ||
1299
+ (c.network !== undefined && c.network !== "allowlist") ||
1309
1300
  (c.restrictedProjectReach !== undefined && c.restrictedProjectReach !== "workspace"))
1310
1301
  throw new ApiError("validation_failed", "The device page can only narrow a machine's owner ceiling; widen it on the machine with capybara-device ceiling set");
1311
1302
  return {
1312
- ...(c.fullAccess === false && { fullAccess: false }),
1303
+ ...(c.outsideSandbox === false && { outsideSandbox: false }),
1304
+ ...(c.network === "allowlist" && { network: "allowlist" }),
1313
1305
  ...(c.restrictedProjectReach === "workspace" && {
1314
1306
  restrictedProjectReach: "workspace",
1315
1307
  }),