@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
@@ -1,13 +1,18 @@
1
1
  import { z } from "zod";
2
2
  import type { KernelConfig } from "../config/schema.js";
3
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
7
  import type { KernelLogger } from "../log.js";
7
8
  import { PermissionCeilingWrites } from "./permission-ceiling-writes.js";
9
+ /**
10
+ * The current projection (version 3, approval-only profiles design): the platform's device sandbox
11
+ * inputs (`devices.outsideSandbox`, `devices.network.default` / `ceiling`) and the network limits.
12
+ */
8
13
  declare const ProjectionSchema: z.ZodObject<{
9
- version: z.ZodLiteral<2>;
10
- fullAccess: z.ZodDiscriminatedUnion<[z.ZodObject<{
14
+ version: z.ZodLiteral<3>;
15
+ outsideSandbox: z.ZodDiscriminatedUnion<[z.ZodObject<{
11
16
  kind: z.ZodLiteral<"deployment-setting">;
12
17
  }, z.core.$strict>, z.ZodObject<{
13
18
  kind: z.ZodLiteral<"configured">;
@@ -16,6 +21,26 @@ declare const ProjectionSchema: z.ZodObject<{
16
21
  off: "off";
17
22
  }>;
18
23
  }, z.core.$strict>], "kind">;
24
+ network: z.ZodObject<{
25
+ default: z.ZodDiscriminatedUnion<[z.ZodObject<{
26
+ kind: z.ZodLiteral<"deployment-setting">;
27
+ }, z.core.$strict>, z.ZodObject<{
28
+ kind: z.ZodLiteral<"configured">;
29
+ value: z.ZodEnum<{
30
+ allowlist: "allowlist";
31
+ open: "open";
32
+ }>;
33
+ }, z.core.$strict>], "kind">;
34
+ ceiling: z.ZodDiscriminatedUnion<[z.ZodObject<{
35
+ kind: z.ZodLiteral<"deployment-setting">;
36
+ }, z.core.$strict>, z.ZodObject<{
37
+ kind: z.ZodLiteral<"configured">;
38
+ value: z.ZodEnum<{
39
+ allowlist: "allowlist";
40
+ open: "open";
41
+ }>;
42
+ }, z.core.$strict>], "kind">;
43
+ }, z.core.$strict>;
19
44
  egress: z.ZodEnum<{
20
45
  allowlist: "allowlist";
21
46
  none: "none";
@@ -68,9 +93,26 @@ export declare class PermissionConfigPublication {
68
93
  publish(before: KernelConfig, next: KernelConfig): Promise<void>;
69
94
  /** Validates the stored publication with the algorithm of its own version. */
70
95
  private validateStored;
96
+ /**
97
+ * Converts the stored permission keys ({@link convertStoredPermissionKeys}) and, when the
98
+ * predecessor is an older publication (`pinDevices`), keeps every cloud device that ran on an
99
+ * allowlist on it: a device still following its org (`network_mode` NULL) whose old effective
100
+ * network was the allowlist (`sandbox.limits.orgHosts: within`, an org allowlist or an old off)
101
+ * gets `network_mode = 'allowlist'` with no hosts of its own (it follows its org's hosts), so
102
+ * the new model, where `orgHosts` limits hosts only, never opens it. The caller holds the
103
+ * platform write lock and the org rows.
104
+ */
105
+ private convertLocked;
71
106
  /** Compare-and-set of the publication row; the caller holds the platform write lock. */
72
107
  private replaceLocked;
73
108
  private publishLocked;
74
109
  assertCurrent(): Promise<void>;
75
110
  }
111
+ /**
112
+ * Copies a cloud device's B1 snapshot network into its own sandbox network while it has none
113
+ * (migrations 0165 and 0167, the snapshot writer): an allowlist with a non-empty list of strings
114
+ * stays that allowlist, an empty or unreadable one ran closed and becomes `none`; an open snapshot
115
+ * follows the org. Idempotent: only rows still following the org are written.
116
+ */
117
+ export declare function copyCloudSnapshotNetworks(db: KernelSchemaDb): Promise<void>;
76
118
  export {};
@@ -10,44 +10,62 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { createHash } from "node:crypto";
11
11
  import { SandboxScopeDeniedError, validateAllowHost } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
13
+ import { sql } from "kysely";
13
14
  import { z } from "zod";
14
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
16
  import { KernelDb } from "../infra/database/kernel-db.js";
16
17
  import { TransactionHost } from "../infra/database/transaction-host.js";
17
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
19
- import { CloudNetworkSettingSchema, invalidCloudNetwork } from "../orgs/cloud-network-setting.js";
20
- import { coversHost, orgEffectiveHosts } from "./modes.js";
21
- import { isExecutionMethod } from "./operation-authority-types.js";
22
- import { localMachineRoots, needsFullCeiling, needsWiderDeviceCeiling, PermissionCeilingWrites, } from "./permission-ceiling-writes.js";
23
- import { convertStoredPermissionKeys, lockOrgsWithStoredPermissionKeys, readStoredDevicesFullAccess, resolveDevicesFullAccess, } from "./platform-full-access.js";
24
- const FullAccessSource = z.discriminatedUnion("kind", [
20
+ import { hostGrantable, hostGrantCeiling } from "./device-sandbox.js";
21
+ import { convertStoredPermissionKeys, lockOrgsWithStoredPermissionKeys, orgDeviceSandboxOf, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "./device-sandbox-settings.js";
22
+ import { cloudChosenMode, coversHost, effectiveDevicePolicy, orgEffectiveHosts, } from "./modes.js";
23
+ import { cloudDevicesFollowingDefault, hostsNarrowed, localMachineRoots, needsFullCeiling, needsOpenNetwork, needsWiderDeviceCeiling, PermissionCeilingWrites, } from "./permission-ceiling-writes.js";
24
+ /** Whether a field comes from the startup config (with its value) or the deployment setting. */
25
+ const SettingSource = (value) => z.discriminatedUnion("kind", [
25
26
  z.object({ kind: z.literal("deployment-setting") }).strict(),
26
- z.object({ kind: z.literal("configured"), value: z.enum(["allowed", "off"]) }).strict(),
27
+ z.object({ kind: z.literal("configured"), value }).strict(),
27
28
  ]);
29
+ const PermissionSource = SettingSource(z.enum(["allowed", "off"]));
30
+ const NetworkSource = SettingSource(z.enum(["open", "allowlist"]));
28
31
  const AllowHosts = z
29
32
  .array(z
30
33
  .string()
31
34
  .max(253)
32
35
  .refine((host) => validateAllowHost(host).length === 0))
33
36
  .max(4096);
37
+ /**
38
+ * The current projection (version 3, approval-only profiles design): the platform's device sandbox
39
+ * inputs (`devices.outsideSandbox`, `devices.network.default` / `ceiling`) and the network limits.
40
+ */
34
41
  const ProjectionSchema = z
35
42
  .object({
36
- version: z.literal(2),
37
- fullAccess: FullAccessSource,
43
+ version: z.literal(3),
44
+ outsideSandbox: PermissionSource,
45
+ network: z.object({ default: NetworkSource, ceiling: NetworkSource }).strict(),
38
46
  egress: z.enum(["none", "allowlist"]),
39
47
  orgHosts: z.enum(["extend", "within"]),
40
48
  allowHosts: AllowHosts,
41
49
  })
42
50
  .strict();
43
51
  /**
44
- * The 6c projection released replicas published (version 1, no version field). It is read only to
45
- * convert it (B1): validated with its own canonical algorithm and exact fingerprint, never
46
- * published again.
52
+ * The B1 projection released replicas published (version 2, `fullAccess`). It is read only to
53
+ * convert it: validated with its own canonical algorithm and exact fingerprint, never published
54
+ * again.
47
55
  */
48
- const LegacyProjectionSchema = z
56
+ const V2ProjectionSchema = z
57
+ .object({
58
+ version: z.literal(2),
59
+ fullAccess: PermissionSource,
60
+ egress: z.enum(["none", "allowlist"]),
61
+ orgHosts: z.enum(["extend", "within"]),
62
+ allowHosts: AllowHosts,
63
+ })
64
+ .strict();
65
+ /** The 6c projection (version 1, no version field), read only to convert it like version 2. */
66
+ const V1ProjectionSchema = z
49
67
  .object({
50
- autoMode: FullAccessSource,
68
+ autoMode: PermissionSource,
51
69
  egress: z.enum(["none", "allowlist"]),
52
70
  orgHosts: z.enum(["extend", "within"]),
53
71
  allowHosts: AllowHosts,
@@ -58,47 +76,91 @@ const bounded = (projection) => {
58
76
  throw new SandboxScopeDeniedError("Permission configuration projection exceeds 64 KiB");
59
77
  return projection;
60
78
  };
79
+ const sortedHosts = (hosts) => [...new Set(hosts)].sort();
61
80
  /** Validated nonsecret winning config inputs; PG fallback is read separately under the writer lock. */
62
81
  export function parsePermissionConfigProjection(input) {
63
82
  const parsed = ProjectionSchema.parse(input);
64
83
  // the fixed property order is the canonical form the fingerprint hashes
84
+ return bounded({
85
+ version: 3,
86
+ outsideSandbox: parsed.outsideSandbox,
87
+ network: { default: parsed.network.default, ceiling: parsed.network.ceiling },
88
+ egress: parsed.egress,
89
+ orgHosts: parsed.orgHosts,
90
+ allowHosts: sortedHosts(parsed.allowHosts),
91
+ });
92
+ }
93
+ function parseV2Projection(input) {
94
+ const parsed = V2ProjectionSchema.parse(input);
65
95
  return bounded({
66
96
  version: 2,
67
97
  fullAccess: parsed.fullAccess,
68
98
  egress: parsed.egress,
69
99
  orgHosts: parsed.orgHosts,
70
- allowHosts: [...new Set(parsed.allowHosts)].sort(),
100
+ allowHosts: sortedHosts(parsed.allowHosts),
71
101
  });
72
102
  }
73
- function parseLegacyProjection(input) {
74
- const parsed = LegacyProjectionSchema.parse(input);
103
+ function parseV1Projection(input) {
104
+ const parsed = V1ProjectionSchema.parse(input);
75
105
  return bounded({
76
106
  autoMode: parsed.autoMode,
77
107
  egress: parsed.egress,
78
108
  orgHosts: parsed.orgHosts,
79
- allowHosts: [...new Set(parsed.allowHosts)].sort(),
109
+ allowHosts: sortedHosts(parsed.allowHosts),
80
110
  });
81
111
  }
82
- /** The version 2 projection that says exactly what a version 1 projection said. */
83
- const ofLegacy = (p) => ({
84
- version: 2,
85
- fullAccess: p.autoMode,
112
+ /**
113
+ * The version 3 projection that says exactly what an old one said, as `capybara config
114
+ * migrate-permissions` converts the config: the same outside-sandbox source, and a configured
115
+ * `off` also a configured allowlist network ceiling (an old off kept every device on the
116
+ * allowlist; never wider).
117
+ */
118
+ const ofOld = (permission, p) => ({
119
+ version: 3,
120
+ outsideSandbox: permission,
121
+ network: {
122
+ default: { kind: "deployment-setting" },
123
+ ceiling: permission.kind === "configured" && permission.value === "off"
124
+ ? { kind: "configured", value: "allowlist" }
125
+ : { kind: "deployment-setting" },
126
+ },
86
127
  egress: p.egress,
87
128
  orgHosts: p.orgHosts,
88
129
  allowHosts: p.allowHosts,
89
130
  });
90
131
  export function permissionConfigProjection(config) {
91
132
  const { egress, orgHosts, allowHosts } = config.sandbox.limits;
133
+ const source = (value) => value === undefined
134
+ ? { kind: "deployment-setting" }
135
+ : { kind: "configured", value };
92
136
  return parsePermissionConfigProjection({
93
- version: 2,
94
- fullAccess: config.devices.fullAccess === undefined
95
- ? { kind: "deployment-setting" }
96
- : { kind: "configured", value: config.devices.fullAccess },
137
+ version: 3,
138
+ outsideSandbox: source(config.devices.outsideSandbox),
139
+ network: {
140
+ default: source(config.devices.network.default),
141
+ ceiling: source(config.devices.network.ceiling),
142
+ },
97
143
  egress,
98
144
  orgHosts,
99
145
  allowHosts,
100
146
  });
101
147
  }
148
+ /** A configured value of the projection, or undefined when the deployment setting decides. */
149
+ const configuredOf = (s) => s.kind === "configured" ? s.value : undefined;
150
+ /** The projection as the settings reader's startup config input. */
151
+ const configuredView = (projection) => {
152
+ const fileSource = (s) => (s.kind === "configured" ? "file" : undefined);
153
+ return {
154
+ outsideSandbox: configuredOf(projection.outsideSandbox),
155
+ networkDefault: configuredOf(projection.network.default),
156
+ networkCeiling: configuredOf(projection.network.ceiling),
157
+ sources: {
158
+ outsideSandbox: fileSource(projection.outsideSandbox),
159
+ networkDefault: fileSource(projection.network.default),
160
+ networkCeiling: fileSource(projection.network.ceiling),
161
+ },
162
+ };
163
+ };
102
164
  const sha256 = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
103
165
  export function permissionProjectionFingerprint(projection) {
104
166
  return sha256(parsePermissionConfigProjection(projection));
@@ -176,11 +238,11 @@ let PermissionConfigPublication = class PermissionConfigPublication {
176
238
  const stored = this.validateStored(row);
177
239
  if (row.fingerprint === candidateHash)
178
240
  return { outcome: "matching", activeHash: candidateHash };
179
- // B1: a released version 1 publication that says exactly what this replica says converts
180
- // in place (format only: no epoch, no Full reset, no revocation)
241
+ // a released older publication that says exactly what this replica says converts in place
242
+ // (format only: no epoch, no Full reset, no revocation)
181
243
  if (stored.legacy && permissionProjectionFingerprint(stored.projection) === candidateHash) {
182
244
  await this.replaceLocked(row.fingerprint, projection);
183
- await convertStoredPermissionKeys(this.db.db, this.log);
245
+ await this.convertLocked(projection, true);
184
246
  return { outcome: "migrated", activeHash: candidateHash };
185
247
  }
186
248
  return { outcome: "mismatch", activeHash: row.fingerprint, candidateHash };
@@ -201,7 +263,7 @@ let PermissionConfigPublication = class PermissionConfigPublication {
201
263
  .executeTakeFirstOrThrow();
202
264
  if (inserted.fingerprint !== candidateHash)
203
265
  return { outcome: "mismatch", activeHash: inserted.fingerprint, candidateHash };
204
- await convertStoredPermissionKeys(this.db.db, this.log);
266
+ await this.convertLocked(projection, true);
205
267
  return { outcome: "initialized", activeHash: candidateHash };
206
268
  }
207
269
  /** CAS publication precedes exposing the new local config. Same-next replicas converge idempotently. */
@@ -221,16 +283,79 @@ let PermissionConfigPublication = class PermissionConfigPublication {
221
283
  validateStored(row) {
222
284
  const corrupt = () => new SandboxScopeDeniedError("Published permission projection does not match its fingerprint");
223
285
  const raw = row.projection;
224
- if (raw !== null && typeof raw === "object" && "version" in raw) {
286
+ const version = raw !== null && typeof raw === "object" && "version" in raw ? raw.version : undefined;
287
+ if (version === 3) {
225
288
  const projection = parsePermissionConfigProjection(raw);
226
289
  if (permissionProjectionFingerprint(projection) !== row.fingerprint)
227
290
  throw corrupt();
228
291
  return { fingerprint: row.fingerprint, projection, legacy: false };
229
292
  }
230
- const legacy = parseLegacyProjection(raw);
231
- if (sha256(legacy) !== row.fingerprint)
293
+ if (version === 2) {
294
+ const old = parseV2Projection(raw);
295
+ if (sha256(old) !== row.fingerprint)
296
+ throw corrupt();
297
+ return { fingerprint: row.fingerprint, projection: ofOld(old.fullAccess, old), legacy: true };
298
+ }
299
+ if (version !== undefined)
300
+ throw corrupt();
301
+ const old = parseV1Projection(raw);
302
+ if (sha256(old) !== row.fingerprint)
232
303
  throw corrupt();
233
- return { fingerprint: row.fingerprint, projection: ofLegacy(legacy), legacy: true };
304
+ return { fingerprint: row.fingerprint, projection: ofOld(old.autoMode, old), legacy: true };
305
+ }
306
+ /**
307
+ * Converts the stored permission keys ({@link convertStoredPermissionKeys}) and, when the
308
+ * predecessor is an older publication (`pinDevices`), keeps every cloud device that ran on an
309
+ * allowlist on it: a device still following its org (`network_mode` NULL) whose old effective
310
+ * network was the allowlist (`sandbox.limits.orgHosts: within`, an org allowlist or an old off)
311
+ * gets `network_mode = 'allowlist'` with no hosts of its own (it follows its org's hosts), so
312
+ * the new model, where `orgHosts` limits hosts only, never opens it. The caller holds the
313
+ * platform write lock and the org rows.
314
+ */
315
+ async convertLocked(projection, pinDevices) {
316
+ const configuredCeiling = configuredOf(projection.network.ceiling);
317
+ // a B1 snapshot an older replica wrote after migration 0167 becomes the device's own network
318
+ // at every activation, before anything reads it (as 0165 and 0167 copy it: never wider)
319
+ await copyCloudSnapshotNetworks(this.db.db);
320
+ if (pinDevices) {
321
+ const stored = await readStoredDeviceSandbox(this.db.db, this.log, configuredCeiling);
322
+ const view = resolveDeviceSandboxSettings(configuredView(projection), stored);
323
+ const deployment = {
324
+ fullAccess: view.outsideSandbox.permission,
325
+ limits: {
326
+ egress: projection.egress,
327
+ orgHosts: projection.orgHosts,
328
+ allowHosts: projection.allowHosts,
329
+ },
330
+ };
331
+ const devices = await this.db
332
+ .selectFrom("devices")
333
+ .select(["id", "org_id", "mode", "owner_full_access", "outer_network"])
334
+ .where("source", "=", "cloud")
335
+ .where("network_mode", "is", null)
336
+ .where("deleted_at", "is", null)
337
+ .orderBy("id")
338
+ .execute();
339
+ const orgIds = [...new Set(devices.map((d) => d.org_id))];
340
+ const orgSettings = new Map(orgIds.length === 0
341
+ ? []
342
+ : (await this.db
343
+ .selectFrom("orgs")
344
+ .select(["id", "settings"])
345
+ .where("id", "in", orgIds)
346
+ .execute()).map((o) => [o.id, o.settings]));
347
+ const pinned = devices
348
+ .filter((d) => effectiveDevicePolicy(deployment, orgDeviceSandboxOf(orgSettings.get(d.org_id)), cloudChosenMode(d), d.outer_network).network.kind === "allowlist")
349
+ .map((d) => d.id);
350
+ if (pinned.length > 0)
351
+ await this.db
352
+ .updateTable("devices")
353
+ .set({ network_mode: "allowlist", network_hosts: "[]" })
354
+ .where("id", "in", pinned)
355
+ .where("network_mode", "is", null)
356
+ .execute();
357
+ }
358
+ await convertStoredPermissionKeys(this.db.db, this.log, { configuredCeiling });
234
359
  }
235
360
  /** Compare-and-set of the publication row; the caller holds the platform write lock. */
236
361
  async replaceLocked(previous, next) {
@@ -260,30 +385,53 @@ let PermissionConfigPublication = class PermissionConfigPublication {
260
385
  if (row.fingerprint !== previous)
261
386
  throw new PermissionConfigActivationConflict(row.fingerprint, fingerprint);
262
387
  await this.replaceLocked(previous, next);
263
- // a version 1 predecessor converts its stored keys in this same transaction (B1)
264
- if (stored.legacy)
265
- await convertStoredPermissionKeys(this.db.db, this.log);
388
+ // the stored keys convert at every publication (old keys an old replica wrote meanwhile
389
+ // too); an older predecessor also pins its cloud devices, in this same transaction
390
+ await this.convertLocked(next, stored.legacy);
266
391
  // format only: the same semantics publish the new fingerprint (the barrier) and nothing else
267
392
  if (permissionProjectionFingerprint(before) === fingerprint)
268
393
  return "activated";
269
- const storedChoice = await readStoredDevicesFullAccess(this.db.db, this.log);
270
- const effective = (projection) => resolveDevicesFullAccess(projection.fullAccess.kind === "configured" ? projection.fullAccess.value : undefined, projection.fullAccess.kind === "configured" ? "file" : undefined, storedChoice).permission;
271
- const beforeMode = effective(before), nextMode = effective(next);
394
+ const storedChoice = await readStoredDeviceSandbox(this.db.db, this.log, configuredOf(next.network.ceiling));
395
+ const effective = (projection) => resolveDeviceSandboxSettings(configuredView(projection), storedChoice);
396
+ const beforeView = effective(before), nextView = effective(next);
397
+ const beforeMode = beforeView.outsideSandbox.permission, nextMode = nextView.outsideSandbox.permission;
398
+ // a network opened anywhere is a widening: consent given under the narrower network resets
399
+ const networkWidened = (beforeView.network.ceiling === "allowlist" && nextView.network.ceiling === "open") ||
400
+ (beforeView.network.default === "allowlist" && nextView.network.default === "open");
272
401
  const orgs = await this.db.selectFrom("orgs").select(["id", "settings"]).execute();
273
- const settings = new Map(orgs.map((org) => {
274
- const raw = org.settings?.cloudNetwork;
275
- const parsed = CloudNetworkSettingSchema.safeParse(raw);
276
- return [
277
- org.id,
278
- raw === undefined ? undefined : parsed.success ? parsed.data : invalidCloudNetwork(),
279
- ];
280
- }));
402
+ const settings = new Map(orgs.map((org) => [org.id, orgDeviceSandboxOf(org.settings).deviceNetwork]));
281
403
  const devices = await this.db.selectFrom("devices").select(["id", "source"]).execute();
282
404
  const machineRoots = await localMachineRoots(this.db.db);
283
405
  const sources = new Map(devices.map((device) => [device.id, device.source]));
284
- if (before.egress !== next.egress)
406
+ // the kill switch lifted is a widening for every cloud device (closing it only narrows)
407
+ if (before.egress === "none" && next.egress !== "none")
285
408
  await this.ceilings.invalidateDeviceConsentUnderPlatform(devices.filter((device) => device.source === "cloud").map((device) => device.id));
409
+ // a network ceiling narrowed to the allowlist, or closed by the kill switch, takes running
410
+ // open-network work
411
+ const networkNarrowed = (beforeView.network.ceiling === "open" && nextView.network.ceiling === "allowlist") ||
412
+ (before.egress !== "none" && next.egress === "none");
413
+ // a default narrowed to the allowlist takes it from the cloud devices following it
414
+ const following = !networkNarrowed &&
415
+ beforeView.network.default === "open" &&
416
+ nextView.network.default === "allowlist"
417
+ ? new Set([...(await cloudDevicesFollowingDefault(this.db.db))]
418
+ .filter(([, org]) => settings.get(org)?.default === undefined)
419
+ .map(([id]) => id))
420
+ : null;
421
+ // the per-call host list widened: hosts the platform list did not cover, or orgs allowed
422
+ // beyond it again (`within` to `extend`)
423
+ const hostsWidened = (before.orgHosts === "within" && next.orgHosts === "extend") ||
424
+ next.allowHosts.some((h) => !before.allowHosts.some((p) => coversHost(p.toLowerCase(), h.toLowerCase())));
425
+ const grantable = (orgId, host) => {
426
+ const org = settings.get(orgId);
427
+ const ceiling = nextView.network.ceiling === "allowlist" || org?.ceiling === "allowlist"
428
+ ? "allowlist"
429
+ : "open";
430
+ return hostGrantable(hostGrantCeiling({ boundary: "operation", networkMode: "allowlist", networkCeiling: ceiling }, next, org === undefined ? {} : { deviceNetwork: org }, null), host);
431
+ };
286
432
  await this.ceilings.publishLocked({}, "platform", (scope, row) => {
433
+ if (needsOpenNetwork(scope) && (networkNarrowed || following?.has(row.device_id) === true))
434
+ return true;
287
435
  // Full off also narrows restricted reach to the workspace (B2): running restricted work
288
436
  // outside a machine's roots goes with Full work, as the owner writer decides
289
437
  if (nextMode === "off" && needsWiderDeviceCeiling(scope, machineRoots.get(row.device_id)))
@@ -293,16 +441,10 @@ let PermissionConfigPublication = class PermissionConfigPublication {
293
441
  (sources.get(row.device_id) === "cloud" &&
294
442
  before.egress !== "none" &&
295
443
  next.egress === "none"));
296
- if (!isExecutionMethod(row.method) ||
297
- !("network" in scope) ||
298
- scope.network.kind !== "allowlist")
299
- return false;
300
- const hosts = orgEffectiveHosts(next, settings.get(row.org_id));
301
- return scope.network.hosts.some((host) => !hosts.some((pattern) => coversHost(pattern, host)) &&
302
- !(next.egress !== "none" &&
303
- next.orgHosts !== "within" &&
304
- row.granted_hosts.includes(host)));
305
- }, beforeMode !== nextMode);
444
+ return hostsNarrowed(scope, row, orgEffectiveHosts(next, settings.get(row.org_id)), (host) => next.egress !== "none" && grantable(row.org_id, host));
445
+ },
446
+ // only a widening resets Full consent: a narrowing keeps what the consent covered
447
+ (beforeMode === "off" && nextMode === "allowed") || networkWidened || hostsWidened);
306
448
  return "activated";
307
449
  }
308
450
  async assertCurrent() {
@@ -321,6 +463,9 @@ __decorate([
321
463
  __decorate([
322
464
  Transactional({ propagation: "requires_new" })
323
465
  ], PermissionConfigPublication.prototype, "publish", null);
466
+ __decorate([
467
+ Transactional({ propagation: "mandatory" })
468
+ ], PermissionConfigPublication.prototype, "convertLocked", null);
324
469
  __decorate([
325
470
  Transactional({ propagation: "mandatory" })
326
471
  ], PermissionConfigPublication.prototype, "replaceLocked", null);
@@ -337,3 +482,29 @@ PermissionConfigPublication = __decorate([
337
482
  __param(4, Inject(KERNEL_LOGGER))
338
483
  ], PermissionConfigPublication);
339
484
  export { PermissionConfigPublication };
485
+ /**
486
+ * Copies a cloud device's B1 snapshot network into its own sandbox network while it has none
487
+ * (migrations 0165 and 0167, the snapshot writer): an allowlist with a non-empty list of strings
488
+ * stays that allowlist, an empty or unreadable one ran closed and becomes `none`; an open snapshot
489
+ * follows the org. Idempotent: only rows still following the org are written.
490
+ */
491
+ export async function copyCloudSnapshotNetworks(db) {
492
+ const readable = sql `jsonb_typeof(outer_network -> 'hosts') = 'array'
493
+ AND NOT EXISTS (
494
+ SELECT 1 FROM jsonb_array_elements(outer_network -> 'hosts') AS h(v)
495
+ WHERE jsonb_typeof(h.v) <> 'string'
496
+ )`;
497
+ await db
498
+ .updateTable("devices")
499
+ .set({
500
+ network_mode: sql `CASE
501
+ WHEN ${readable} AND jsonb_array_length(outer_network -> 'hosts') > 0 THEN 'allowlist'
502
+ ELSE 'none' END`,
503
+ network_hosts: sql `CASE WHEN ${readable} THEN outer_network -> 'hosts'
504
+ ELSE '[]'::jsonb END`,
505
+ })
506
+ .where("source", "=", "cloud")
507
+ .where("network_mode", "is", null)
508
+ .where(sql `outer_network ->> 'kind' = 'allowlist'`)
509
+ .execute();
510
+ }
@@ -1,5 +1,5 @@
1
1
  import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
2
- import type { PermissionContextV1 } from "../conversations/events.js";
2
+ import type { PermissionContextV2 } from "../conversations/events.js";
3
3
  /**
4
4
  * The complete identity a recorded permission context is read for: the calling conversation, its
5
5
  * run and the run's actor. Kernel-private; shared by the authority projection below runtime and the
@@ -26,7 +26,7 @@ export interface HeldDeviceContextEvidence {
26
26
  workingRoot: string;
27
27
  }
28
28
  /** The outer boundary a recorded context reports, as the applied environment proves it. */
29
- export type AppliedOuterNetwork = NonNullable<PermissionContextV1["scope"]>["outerNetwork"];
29
+ export type AppliedOuterNetwork = NonNullable<PermissionContextV2["scope"]>["outerNetwork"];
30
30
  /**
31
31
  * The installed environment of a device's current instance, proved by its installed binding and
32
32
  * current runtime attestation (B1 adapter). Null from the reader means unproved: the context is