@capybara-hq/kernel 0.1.0-rc.53 → 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 (190) 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 +15 -1
  15. package/dist/config/schema.js +66 -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 +18 -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 +43 -19
  35. package/dist/errors.js +43 -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/http/api.module.js +8 -0
  44. package/dist/http/app.js +9 -0
  45. package/dist/http/meta.controller.d.ts +33 -0
  46. package/dist/http/meta.controller.js +72 -0
  47. package/dist/identity/app-auth.controller.d.ts +25 -0
  48. package/dist/identity/app-auth.controller.js +64 -0
  49. package/dist/identity/app-auth.d.ts +66 -0
  50. package/dist/identity/app-auth.js +203 -0
  51. package/dist/identity/app-auth.schemas.d.ts +47 -0
  52. package/dist/identity/app-auth.schemas.js +43 -0
  53. package/dist/identity/identity.module.d.ts +1 -1
  54. package/dist/identity/identity.module.js +4 -1
  55. package/dist/identity/settings.d.ts +45 -18
  56. package/dist/identity/settings.js +151 -51
  57. package/dist/infra/config/kernel-config.service.d.ts +1 -1
  58. package/dist/infra/config/kernel-config.service.js +19 -5
  59. package/dist/infra/outbox/registry.d.ts +14 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  62. package/dist/infra/throttler/named-throttlers.js +14 -2
  63. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  64. package/dist/local-devices/device-auth.controller.js +1 -1
  65. package/dist/local-devices/device-auth.d.ts +4 -4
  66. package/dist/local-devices/device-auth.js +1 -1
  67. package/dist/local-devices/device-policy.service.d.ts +18 -9
  68. package/dist/local-devices/device-policy.service.js +21 -61
  69. package/dist/local-devices/device-routes.d.ts +3 -1
  70. package/dist/local-devices/device-routes.js +15 -4
  71. package/dist/local-devices/instance-bindings.js +5 -2
  72. package/dist/local-devices/local-device-gateway.d.ts +2 -2
  73. package/dist/local-devices/local-device-gateway.js +3 -3
  74. package/dist/local-devices/local-device-provider.d.ts +4 -4
  75. package/dist/local-devices/local-device-provider.js +23 -9
  76. package/dist/local-devices/local-devices.module.d.ts +1 -1
  77. package/dist/local-devices/local-devices.module.js +1 -1
  78. package/dist/local-devices/machines.d.ts +40 -16
  79. package/dist/local-devices/machines.js +89 -61
  80. package/dist/local-devices/owner-report.d.ts +16 -14
  81. package/dist/local-devices/owner-report.js +24 -30
  82. package/dist/local-devices/owner-reports.js +26 -8
  83. package/dist/local-devices/policy-summary.d.ts +25 -44
  84. package/dist/local-devices/policy-summary.js +26 -71
  85. package/dist/local-devices/relay.d.ts +6 -6
  86. package/dist/local-devices/relay.js +10 -8
  87. package/dist/net/public-address.d.ts +1 -1
  88. package/dist/net/public-address.js +5 -2
  89. package/dist/orgs/device-network-setting.d.ts +82 -0
  90. package/dist/orgs/device-network-setting.js +142 -0
  91. package/dist/orgs/settings.service.d.ts +103 -66
  92. package/dist/orgs/settings.service.js +201 -137
  93. package/dist/overrides.d.ts +5 -1
  94. package/dist/overrides.js +2 -0
  95. package/dist/platform/exclusions.js +24 -1
  96. package/dist/platform/operation.js +2 -2
  97. package/dist/platform/ops/admin.ops.js +20 -11
  98. package/dist/platform/ops/devices.ops.js +70 -5
  99. package/dist/platform/ops/org-settings.ops.js +10 -6
  100. package/dist/platform/ops/orgs.ops.js +2 -1
  101. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  102. package/dist/platform/ops/platform-icons.ops.js +117 -0
  103. package/dist/platform/platform-ops.module.d.ts +2 -1
  104. package/dist/platform/platform-ops.module.js +3 -0
  105. package/dist/platform/route-schemas.js +3 -0
  106. package/dist/runtime/context/permission-profile.d.ts +17 -8
  107. package/dist/runtime/context/permission-profile.js +126 -45
  108. package/dist/runtime/maintenance.d.ts +5 -2
  109. package/dist/runtime/maintenance.js +15 -4
  110. package/dist/runtime/permission-context.service.d.ts +1 -1
  111. package/dist/runtime/permission-context.service.js +5 -3
  112. package/dist/runtime/project/knowledge.d.ts +5 -4
  113. package/dist/runtime/project/knowledge.js +2 -1
  114. package/dist/runtime/project/knowledge.service.js +16 -13
  115. package/dist/sandbox/cloud-permission-snapshot.js +22 -3
  116. package/dist/sandbox/device-sandbox-settings.d.ts +230 -0
  117. package/dist/sandbox/device-sandbox-settings.js +470 -0
  118. package/dist/sandbox/device-sandbox.d.ts +187 -0
  119. package/dist/sandbox/device-sandbox.js +236 -0
  120. package/dist/sandbox/held-operations.js +15 -7
  121. package/dist/sandbox/modes.d.ts +49 -24
  122. package/dist/sandbox/modes.js +27 -19
  123. package/dist/sandbox/operation-authority-types.d.ts +6 -5
  124. package/dist/sandbox/operation-authority-types.js +7 -8
  125. package/dist/sandbox/operation-authority.d.ts +23 -9
  126. package/dist/sandbox/operation-authority.js +179 -97
  127. package/dist/sandbox/permission-auto-grants.d.ts +42 -0
  128. package/dist/sandbox/permission-auto-grants.js +145 -0
  129. package/dist/sandbox/permission-call-grants.d.ts +12 -4
  130. package/dist/sandbox/permission-call-grants.js +84 -35
  131. package/dist/sandbox/permission-call-grants.module.js +10 -3
  132. package/dist/sandbox/permission-call-types.d.ts +39 -5
  133. package/dist/sandbox/permission-ceiling-writes.d.ts +29 -3
  134. package/dist/sandbox/permission-ceiling-writes.js +38 -4
  135. package/dist/sandbox/permission-config-publication.d.ts +44 -2
  136. package/dist/sandbox/permission-config-publication.js +230 -59
  137. package/dist/sandbox/permission-context-types.d.ts +2 -2
  138. package/dist/sandbox/permission-facts.d.ts +144 -15
  139. package/dist/sandbox/permission-facts.js +258 -70
  140. package/dist/sandbox/permission-runtime-reports.d.ts +5 -4
  141. package/dist/sandbox/permission-runtime-reports.js +19 -29
  142. package/dist/sandbox/review/classifier.d.ts +8 -0
  143. package/dist/sandbox/review/classifier.js +10 -0
  144. package/dist/sandbox/review/permission-candidate.d.ts +69 -5
  145. package/dist/sandbox/review/permission-candidate.js +153 -30
  146. package/dist/sandbox/review/review.service.d.ts +19 -3
  147. package/dist/sandbox/review/review.service.js +59 -11
  148. package/dist/sandbox/review/rules.js +23 -3
  149. package/dist/sandbox/sandbox.service.d.ts +29 -11
  150. package/dist/sandbox/sandbox.service.js +51 -26
  151. package/dist/skills/invoke.js +3 -2
  152. package/dist/themes/platform-icon-objects.d.ts +51 -0
  153. package/dist/themes/platform-icon-objects.js +113 -0
  154. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  155. package/dist/themes/platform-icon-public.controller.js +58 -0
  156. package/dist/themes/platform-icon.controller.d.ts +22 -0
  157. package/dist/themes/platform-icon.controller.js +65 -0
  158. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  159. package/dist/themes/platform-icon.schemas.js +53 -0
  160. package/dist/themes/platform-icon.service.d.ts +83 -0
  161. package/dist/themes/platform-icon.service.js +301 -0
  162. package/dist/themes/themes.module.d.ts +4 -1
  163. package/dist/themes/themes.module.js +9 -4
  164. package/dist/tools/approvals.service.d.ts +26 -116
  165. package/dist/tools/approvals.service.js +42 -346
  166. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  167. package/dist/tools/builtins/sandbox/bash.js +80 -28
  168. package/dist/tools/builtins/sandbox/common.d.ts +39 -14
  169. package/dist/tools/builtins/sandbox/common.js +47 -24
  170. package/dist/tools/builtins/sandbox/deliver.js +7 -4
  171. package/dist/tools/builtins/skill-load.d.ts +2 -2
  172. package/dist/tools/builtins/skill-load.js +4 -3
  173. package/dist/tools/device-op-resolver.d.ts +4 -10
  174. package/dist/tools/device-op-resolver.js +8 -19
  175. package/dist/tools/network-asks.d.ts +52 -15
  176. package/dist/tools/network-asks.js +55 -25
  177. package/dist/tools/pipeline.d.ts +26 -14
  178. package/dist/tools/pipeline.js +144 -61
  179. package/dist/tools/registry.d.ts +6 -0
  180. package/dist/tools/tools.module.js +1 -1
  181. package/package.json +4 -4
  182. package/src/migrations/0164_platform_icons.sql +10 -0
  183. package/src/migrations/0165_device_network_columns.sql +50 -0
  184. package/src/migrations/0166_permission_grant_full_access.sql +17 -0
  185. package/src/migrations/0167_device_network_backfill.sql +32 -0
  186. package/src/migrations/0168_binding_installed_connection.sql +6 -0
  187. package/dist/orgs/cloud-network-setting.d.ts +0 -33
  188. package/dist/orgs/cloud-network-setting.js +0 -47
  189. package/dist/sandbox/platform-full-access.d.ts +0 -110
  190. package/dist/sandbox/platform-full-access.js +0 -198
@@ -37,8 +37,9 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
37
37
  *
38
38
  * `POST /api/v1/device/authorize` and `POST /api/v1/device/token` opt in to `device-authorize-ip`
39
39
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
40
- * credential: the device code is 32 random bytes). `POST …/guides/:guideId/checks/:checkId/run`
41
- * opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
40
+ * credential: the device code is 32 random bytes). `POST /api/v1/app-auth/token` opts in to
41
+ * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
42
+ * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
42
43
  *
43
44
  * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
44
45
  * methods on `public` extension routes (`PluginRouteAccess`).
@@ -151,6 +152,17 @@ export const NAMED_THROTTLERS = [
151
152
  message: "Too many device sign-in polls; try again later",
152
153
  getTracker: ip,
153
154
  },
155
+ // native-app sign-in code exchanges per client address (@Throttled like device-token-ip): 60.
156
+ // The code is 32 random bytes and dies at its first try, so this only bounds the load
157
+ {
158
+ name: "app-auth-token-ip",
159
+ group: "app-auth-token",
160
+ onSuccess: "clear",
161
+ limit: 60,
162
+ ttl: CREDENTIAL_WINDOW_MS,
163
+ message: "Too many app sign-in attempts; try again later",
164
+ getTracker: ip,
165
+ },
154
166
  // user codes tried per signed-in person (guessing another machine's code): 10, refunded on success
155
167
  {
156
168
  name: "device-code-account",
@@ -12,7 +12,7 @@ import { type DeviceAuthorizeBody, type DeviceConfirmBody, type DeviceTokenBody,
12
12
  * - `POST /authorize { name, os, arch, programVersion }` → `{ deviceCode, userCode,
13
13
  * verificationUri, verificationUriComplete, interval, expiresIn }` (`device-authorize-ip`);
14
14
  * - `POST /token { deviceCode }` → `{ credential, orgId, deviceId, connectUrl,
15
- * reconnectGraceSeconds, maxFrameBytes, fullAccess }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
15
+ * reconnectGraceSeconds, maxFrameBytes, outsideSandbox }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
16
16
  * `device_sign_in.denied` / `device_sign_in.expired` (`device-token-ip`).
17
17
  *
18
18
  * The person's routes need a web session (the confirmation page `/device`); each try of a user
@@ -24,7 +24,7 @@ const CODE_THROTTLER = ["device-code-account"];
24
24
  * - `POST /authorize { name, os, arch, programVersion }` → `{ deviceCode, userCode,
25
25
  * verificationUri, verificationUriComplete, interval, expiresIn }` (`device-authorize-ip`);
26
26
  * - `POST /token { deviceCode }` → `{ credential, orgId, deviceId, connectUrl,
27
- * reconnectGraceSeconds, maxFrameBytes, fullAccess }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
27
+ * reconnectGraceSeconds, maxFrameBytes, outsideSandbox }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
28
28
  * `device_sign_in.denied` / `device_sign_in.expired` (`device-token-ip`).
29
29
  *
30
30
  * The person's routes need a web session (the confirmation page `/device`); each try of a user
@@ -44,11 +44,11 @@ export interface DeviceGrant extends Grant {
44
44
  /** `devices.local.maxFrameBytes`: the program never sends a larger frame (ruling R26). */
45
45
  maxFrameBytes: number;
46
46
  /**
47
- * Whether the platform and the organization allow Full access now (`devices.fullAccess` and the
48
- * org's `fullAccess`): `off` makes `login` say that the org does not allow Full access, even
49
- * when the machine's owner ceiling does.
47
+ * Whether the platform and the organization allow running outside the sandbox now
48
+ * (`devices.outsideSandbox` and the org's `outsideSandbox`): `off` makes `login` say that the org
49
+ * does not allow it, even when the machine's owner ceiling does.
50
50
  */
51
- fullAccess: "allowed" | "off";
51
+ outsideSandbox: "allowed" | "off";
52
52
  }
53
53
  /** A user code as typed → `XXXX-XXXX`, or null when it cannot be one. */
54
54
  export declare function normalizeUserCode(input: string): string | null;
@@ -192,7 +192,7 @@ let DeviceAuthService = class DeviceAuthService {
192
192
  connectUrl,
193
193
  reconnectGraceSeconds: local.reconnectGraceSeconds,
194
194
  maxFrameBytes: local.maxFrameBytes,
195
- fullAccess: allowedDeviceMode(deployment.fullAccess, settings.fullAccess) === "auto"
195
+ outsideSandbox: allowedDeviceMode(deployment.fullAccess, settings.outsideSandbox) === "auto"
196
196
  ? "allowed"
197
197
  : "off",
198
198
  };
@@ -1,4 +1,4 @@
1
- import { type DeviceFeature, type DeviceLocalPolicySummary, type DevicePolicyArgs, type LegacyDevicePolicyArgs, type LegacyDevicePolicyStatus } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceFeature, type DeviceLocalPolicySummary, type DeviceOwnerCeilingNarrowing, type DevicePolicyArgs, type LegacyDevicePolicyArgs, type LegacyDevicePolicyStatus } from "@capybara-hq/plugin-sdk";
2
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -12,8 +12,17 @@ import { LocalDeviceRelay } from "./relay.js";
12
12
  export declare const POLICY_DEADLINE_MS = 30000;
13
13
  /** How long an op left `unknown` waits for the machine's hello to report it (from its intent). */
14
14
  export declare const UNKNOWN_OP_MS: number;
15
- /** A policy change as callers ask for it: the op id and the source are added here. */
16
- type PolicyChange = Omit<DevicePolicyArgs, "source" | "opId">;
15
+ /**
16
+ * A policy change as callers ask for it (the op id and the source are added here): narrowings
17
+ * only. Under device protocol 4 the deployment never widens a local device: its owner adds hosts,
18
+ * opens the network or allows running outside the sandbox on the machine.
19
+ */
20
+ export interface PolicyChange {
21
+ remove?: string[];
22
+ ownerCeiling?: DeviceOwnerCeilingNarrowing;
23
+ }
24
+ /** Who asked for a change, for the device's local audit line (never a network ask). */
25
+ export type PolicyChangeSource = Omit<LegacyDevicePolicyArgs["source"], "approvalId">;
17
26
  /**
18
27
  * Test seam (`KernelOverride`): called by {@link DevicePolicyService.send} right after the `policy`
19
28
  * op's call returned, before its outcome is recorded (by `apply` or a network ask's decision);
@@ -41,7 +50,7 @@ export interface PolicyIntent {
41
50
  opId: string;
42
51
  args: DevicePolicyArgs;
43
52
  /**
44
- * The staged (protocol 3) connection the op goes to, when the device's machine is connected
53
+ * The staged (protocol 4) connection the op goes to, when the device's machine is connected
45
54
  * over one: the op is sent as a v3 `policy` request fenced to it (not sent at all once it
46
55
  * changed), and its answer's owner report is recorded with its id. Absent: protocol 2.
47
56
  */
@@ -80,8 +89,9 @@ export type PolicyOpStatus = (LegacyDevicePolicyStatus & {
80
89
  outcome: "offline";
81
90
  };
82
91
  /**
83
- * Changes a local device's policy on its machine (network ask-to-allow spec §5.2; auto mode spec
84
- * §4.1: its sandbox-mode allowlist, and its mode back to `sandbox`): the kernel→device `policy`
92
+ * Narrows a local device's policy on its machine (approval-only profiles design, "Settings model":
93
+ * hosts removed, the network to the allowlist, no running outside the sandbox, the workspace
94
+ * reach): the kernel→device `policy`
85
95
  * op over the {@link LocalDeviceRelay}. The machine is the authority: it refuses what its owner
86
96
  * forbids, validates every host and answers with the policy as written, which the kernel then
87
97
  * keeps on the active machine's row (§5.4).
@@ -119,7 +129,7 @@ export declare class DevicePolicyService {
119
129
  orgId: string;
120
130
  deviceId: string;
121
131
  change: PolicyChange;
122
- source: LegacyDevicePolicyArgs["source"];
132
+ source: PolicyChangeSource;
123
133
  actorTokenId?: string;
124
134
  }): Promise<PolicyChangeOutcome>;
125
135
  /**
@@ -132,7 +142,7 @@ export declare class DevicePolicyService {
132
142
  orgId: string;
133
143
  deviceId: string;
134
144
  change: PolicyChange;
135
- source: LegacyDevicePolicyArgs["source"];
145
+ source: PolicyChangeSource;
136
146
  actorTokenId?: string;
137
147
  }): Promise<{
138
148
  intent: PolicyIntent;
@@ -201,4 +211,3 @@ export declare class DevicePolicyService {
201
211
  */
202
212
  private recordIntent;
203
213
  }
204
- export {};
@@ -53,8 +53,9 @@ const NOT_RECEIVED_MESSAGE = "The device's machine never received the policy cha
53
53
  const OWNER_CEILING_UNSUPPORTED_MESSAGE = "The device's capybara-device program cannot narrow its owner ceiling from the platform. Update capybara-device on the machine, or run capybara-device ceiling set there.";
54
54
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
55
55
  /**
56
- * Changes a local device's policy on its machine (network ask-to-allow spec §5.2; auto mode spec
57
- * §4.1: its sandbox-mode allowlist, and its mode back to `sandbox`): the kernel→device `policy`
56
+ * Narrows a local device's policy on its machine (approval-only profiles design, "Settings model":
57
+ * hosts removed, the network to the allowlist, no running outside the sandbox, the workspace
58
+ * reach): the kernel→device `policy`
58
59
  * op over the {@link LocalDeviceRelay}. The machine is the authority: it refuses what its owner
59
60
  * forbids, validates every host and answers with the policy as written, which the kernel then
60
61
  * keeps on the active machine's row (§5.4).
@@ -123,7 +124,7 @@ let DevicePolicyService = class DevicePolicyService {
123
124
  throw new Error("DevicePolicyService.begin() must not run inside a transaction: the intent is recorded " +
124
125
  "first, the policy op sent, then the outcome recorded in a transaction.");
125
126
  }
126
- assertHosts(input.change, input.source.approvalId !== undefined);
127
+ assertHosts(input.change);
127
128
  const device = await this.db
128
129
  .selectFrom("devices as e")
129
130
  .innerJoin("orgs as o", "o.id", "e.org_id")
@@ -157,14 +158,14 @@ let DevicePolicyService = class DevicePolicyService {
157
158
  throw e;
158
159
  return { outcome: offline() };
159
160
  }
160
- const change = connection ? stagedChange(input.change) : input.change;
161
+ const change = wireChange(input.change);
161
162
  // B2: an owner-ceiling narrowing needs a program that reports authenticated owner facts over
162
- // a staged connection; protocol 2 cannot express it (its `mode: sandbox` narrows both at once)
163
+ // a staged connection
163
164
  if (change.ownerCeiling !== undefined) {
164
165
  const row = connection
165
166
  ? await this.db
166
167
  .selectFrom("device_machines")
167
- .select(["owner_report", "local_policy"])
168
+ .select(["owner_report"])
168
169
  .where("id", "=", machine.id)
169
170
  .executeTakeFirst()
170
171
  : undefined;
@@ -402,8 +403,6 @@ let DevicePolicyService = class DevicePolicyService {
402
403
  }
403
404
  const live = row.revoked_at === null;
404
405
  const policy = result.outcome === "applied" ? result.policy : undefined;
405
- const modeBefore = localPolicyOf(row.local_policy)?.mode ?? null;
406
- const modeNow = policy !== undefined && live && policy.mode !== modeBefore ? policy.mode : undefined;
407
406
  await this.db
408
407
  .updateTable("device_machines")
409
408
  .set({
@@ -417,22 +416,15 @@ let DevicePolicyService = class DevicePolicyService {
417
416
  policy !== undefined &&
418
417
  live &&
419
418
  JSON.stringify(policy) !== JSON.stringify(localPolicyOf(row.local_policy)))
420
- await this.ceilings.publishLocked({ orgId: row.org_id, deviceId: row.device_id }, "device", (scope, intent) => ownerPolicyRevokes(policy, scope, intent.method, intent.granted_hosts), modeNow !== undefined);
419
+ await this.ceilings.publishLocked({ orgId: row.org_id, deviceId: row.device_id }, "device", (scope, intent) => ownerPolicyRevokes(policy, scope, intent.method, intent.granted_hosts), false);
421
420
  if (result.outcome === "applied") {
422
- if (op.add.length > 0 || op.remove.length > 0) {
421
+ if (op.remove.length > 0) {
423
422
  await auditOp("device.policy_changed", {
424
423
  ...(op.status === "unknown" && { late: true }),
425
424
  });
426
425
  }
427
- // a v3 answer's Full change is the owner report's, audited once by its writer
428
- // (`device.owner_ceiling_changed`): the summary's derived mode is not audited again
429
- if (modeNow !== undefined && !v3Report) {
430
- await auditOp("device.mode_changed", {
431
- from: modeBefore,
432
- to: modeNow,
433
- ...(op.status === "unknown" && { late: true }),
434
- });
435
- }
426
+ // the owner ceiling's change is the owner report's, audited once by its writer
427
+ // (`device.owner_ceiling_changed`)
436
428
  const stored = policy ?? (await this.machines.activeFor(row.device_id))?.localPolicy;
437
429
  return stored
438
430
  ? { applied: true, policy: stored }
@@ -503,15 +495,9 @@ let DevicePolicyService = class DevicePolicyService {
503
495
  const { change, source } = input;
504
496
  const op = {
505
497
  id: input.opId,
506
- add: change.add ?? [],
507
498
  remove: change.remove ?? [],
508
- ...(change.mode !== undefined && { mode: change.mode }),
509
499
  ...(change.ownerCeiling !== undefined && { ownerCeiling: change.ownerCeiling }),
510
- source: {
511
- accountId: source.accountId,
512
- via: source.via,
513
- approvalId: source.approvalId ?? null,
514
- },
500
+ source: { accountId: source.accountId, via: source.via },
515
501
  ...(input.actorTokenId !== undefined && { actorTokenId: input.actorTokenId }),
516
502
  status: "sent",
517
503
  sentAt: now,
@@ -576,22 +562,13 @@ DevicePolicyService = __decorate([
576
562
  ], DevicePolicyService);
577
563
  export { DevicePolicyService };
578
564
  /**
579
- * A change as a staged (v3) machine takes it: protocol 2's one narrowing (`mode: "sandbox"`, Full
580
- * access off and the project reach to the workspace at once) becomes the owner-ceiling narrowing
581
- * it stands for; the protocol 3 machine keeps its owner ceiling, not a daily mode. Never wider:
582
- * only `false` / `workspace` can come out of it (the frame parser refuses anything else).
565
+ * A change as the machine takes it (protocol 4): the hosts to remove and the owner-ceiling
566
+ * narrowing. Never wider: only narrowings come out of it (the frame parser refuses anything else).
583
567
  */
584
- function stagedChange(change) {
585
- if (change.mode !== "sandbox")
586
- return change;
587
- const { mode: _narrowed, ...rest } = change;
568
+ function wireChange(change) {
588
569
  return {
589
- ...rest,
590
- ownerCeiling: {
591
- ...change.ownerCeiling,
592
- fullAccess: false,
593
- restrictedProjectReach: "workspace",
594
- },
570
+ ...(change.remove !== undefined && { remove: change.remove }),
571
+ ...(change.ownerCeiling !== undefined && { ownerCeiling: change.ownerCeiling }),
595
572
  };
596
573
  }
597
574
  const offline = () => ({
@@ -604,17 +581,9 @@ const unsupported = () => ({
604
581
  reason: "unsupported",
605
582
  message: UNSUPPORTED_MESSAGE,
606
583
  });
607
- /** The audit detail of an op's change and source (every `device.policy_*` / `device.mode_*` row). */
584
+ /** The audit detail of an op's change and source (every `device.policy_*` row). */
608
585
  function changeDetail(op) {
609
- return {
610
- opId: op.id,
611
- add: op.add,
612
- remove: op.remove,
613
- ...(op.mode !== undefined && { mode: op.mode }),
614
- by: op.source.accountId,
615
- via: op.source.via,
616
- approvalId: op.source.approvalId,
617
- };
586
+ return { opId: op.id, remove: op.remove, by: op.source.accountId, via: op.source.via };
618
587
  }
619
588
  /** The machine's pending ops with the fields `patch` merged into the op `opId`. */
620
589
  const withOp = (opId, patch) => sql `(
@@ -626,18 +595,9 @@ const withoutOp = (opId) => sql `(
626
595
  SELECT coalesce(jsonb_agg(e), '[]'::jsonb) FROM jsonb_array_elements(pending_policy_ops) e
627
596
  WHERE e->>'id' <> ${opId}
628
597
  )`;
629
- /**
630
- * Hosts the platform may send: an approval's `add` takes exact hosts only (a card never grants a
631
- * wildcard); the owner's own change on the device page (no approval) may add a wildcard (spec §7);
632
- * `remove` takes any valid entry (narrowing, a wildcard too).
633
- */
634
- function assertHosts(change, fromApproval) {
598
+ /** Hosts the platform may send: `remove` takes any valid entry (narrowing, a wildcard too). */
599
+ function assertHosts(change) {
635
600
  const bad = (h) => typeof h !== "string" || validateAllowHost(h).length > 0;
636
- for (const h of change.add ?? []) {
637
- if (bad(h) || (fromApproval && h.startsWith("*."))) {
638
- throw new Error(`not an exact host to add to a device policy: ${JSON.stringify(h)}`);
639
- }
640
- }
641
601
  for (const h of change.remove ?? []) {
642
602
  if (bad(h))
643
603
  throw new Error(`not a host to remove from a device policy: ${JSON.stringify(h)}`);
@@ -26,7 +26,9 @@ export declare function isWebSocketUpgrade(req: FastifyRequest): boolean;
26
26
  * `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
27
27
  * CSRF check applies; the route checks the machine credential itself, before the upgrade (401
28
28
  * `device.credential_invalid`), then the protocol header (426 `device.program_outdated`): only
29
- * {@link DEVICE_PROTOCOL_VERSION} (3) is served; a protocol 2 program must update.
29
+ * {@link DEVICE_PROTOCOL_VERSION} (4) is served; an older program (protocol 3 among them) must
30
+ * update. A newer program reads the kernel's protocol in the message and asks for the deployment
31
+ * to be upgraded instead.
30
32
  * Must be called before Nest `app.init()`, on the root instance.
31
33
  *
32
34
  * `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
@@ -37,7 +37,9 @@ function bearer(req) {
37
37
  * `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
38
38
  * CSRF check applies; the route checks the machine credential itself, before the upgrade (401
39
39
  * `device.credential_invalid`), then the protocol header (426 `device.program_outdated`): only
40
- * {@link DEVICE_PROTOCOL_VERSION} (3) is served; a protocol 2 program must update.
40
+ * {@link DEVICE_PROTOCOL_VERSION} (4) is served; an older program (protocol 3 among them) must
41
+ * update. A newer program reads the kernel's protocol in the message and asks for the deployment
42
+ * to be upgraded instead.
41
43
  * Must be called before Nest `app.init()`, on the root instance.
42
44
  *
43
45
  * `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the
@@ -71,11 +73,20 @@ export async function registerDeviceConnectRoute(fastify, opts) {
71
73
  .code(401)
72
74
  .send(errorBody("device.credential_invalid", "The machine credential is unknown or revoked. Run capybara-device logout, then capybara-device login."));
73
75
  }
74
- if (req.headers[DEVICE_PROTOCOL_HEADER] !== String(DEVICE_PROTOCOL_VERSION)) {
76
+ const spoken = req.headers[DEVICE_PROTOCOL_HEADER];
77
+ if (spoken !== String(DEVICE_PROTOCOL_VERSION)) {
78
+ // the program's own protocol, named only when it is a plain number (header input)
79
+ const number = typeof spoken === "string" && /^[0-9]{1,3}$/.test(spoken) ? Number(spoken) : null;
80
+ const theirs = number !== null
81
+ ? `this capybara-device protocol ${number}`
82
+ : "this capybara-device an older protocol";
83
+ // a newer program than this deployment: the deployment is the one to upgrade
84
+ const fix = number !== null && number > DEVICE_PROTOCOL_VERSION
85
+ ? "This deployment is older than the program; ask the platform's super admin to upgrade Capybara, or install the capybara-device release that matches this deployment."
86
+ : "Update capybara-device on the machine (npm install -g @capybara-hq/device@next), then start it again.";
75
87
  return reply
76
88
  .code(426)
77
- .send(errorBody("device.program_outdated", `This kernel speaks device protocol ${DEVICE_PROTOCOL_VERSION}. ` +
78
- "Update capybara-device."));
89
+ .send(errorBody("device.program_outdated", `This kernel speaks device protocol ${DEVICE_PROTOCOL_VERSION}, ${theirs}. ${fix}`));
79
90
  }
80
91
  credentials.set(req, cred);
81
92
  },
@@ -114,9 +114,11 @@ let LocalInstanceBindings = class LocalInstanceBindings {
114
114
  if (availability.state === "supported")
115
115
  return availability.report;
116
116
  return {
117
- version: 1,
117
+ version: 2,
118
+ boundary: "operation",
118
119
  restricted: null,
119
- fullAccess: false,
120
+ network: { openPublic: false, allowlist: false, perOperationHosts: false },
121
+ outsideSandbox: false,
120
122
  background: false,
121
123
  unavailableReason: availability.state === "unsupported"
122
124
  ? availability.reason
@@ -277,6 +279,7 @@ let LocalInstanceBindings = class LocalInstanceBindings {
277
279
  machine_id: machineId,
278
280
  runtime_identity: JSON.stringify(identity),
279
281
  installed_at: sql `now()`,
282
+ installed_connection_id: connectionId,
280
283
  })
281
284
  .where("device_id", "=", deviceId)
282
285
  .where("instance_generation", "=", request.instanceGeneration)
@@ -131,8 +131,8 @@ export declare class LocalDeviceGateway {
131
131
  /** Who a `Bearer` machine credential stands for, or null (checked before the upgrade). */
132
132
  authenticate(credential: string): Promise<MachineIdentity | null>;
133
133
  /**
134
- * Serves one upgraded socket of a machine until it closes (protocol 3 only: the route refused any
135
- * other header with 426, and a hello that is not protocol 3 closes 4400). The credential is
134
+ * Serves one upgraded socket of a machine until it closes (protocol 4 only: the route refused any
135
+ * other header with 426, and a hello that is not protocol 4 closes 4400). The credential is
136
136
  * checked again here, with the socket paused, so a credential revoked since the upgrade check
137
137
  * never gets a connection.
138
138
  */
@@ -178,7 +178,7 @@ class DeviceConnection {
178
178
  async onFrame(text) {
179
179
  let frame;
180
180
  try {
181
- // protocol 3 only: a protocol 2 hello (or any frame that is not protocol 3, such as a hello
181
+ // protocol 4 only: an older hello (or any frame that is not protocol 4, such as a hello
182
182
  // whose protocol differs from the upgrade header's) fails the strict parse and closes 4400
183
183
  frame = parseDeviceFrame(text, "device", this.effectiveCap ?? this.gw.maxFrameBytes());
184
184
  if (this.effectiveCap !== undefined && this.gw.maxFrameBytes() < this.effectiveCap)
@@ -634,8 +634,8 @@ let LocalDeviceGateway = class LocalDeviceGateway {
634
634
  return this.machines.authenticate(credential);
635
635
  }
636
636
  /**
637
- * Serves one upgraded socket of a machine until it closes (protocol 3 only: the route refused any
638
- * other header with 426, and a hello that is not protocol 3 closes 4400). The credential is
637
+ * Serves one upgraded socket of a machine until it closes (protocol 4 only: the route refused any
638
+ * other header with 426, and a hello that is not protocol 4 closes 4400). The credential is
639
639
  * checked again here, with the socket paused, so a credential revoked since the upgrade check
640
640
  * never gets a connection.
641
641
  */
@@ -18,7 +18,7 @@ export declare const FRAME_ENVELOPE_BYTES: number;
18
18
  export { projectsUnsupported } from "../devices/errors.js";
19
19
  /** The most raw bytes whose base64 plus {@link FRAME_ENVELOPE_BYTES} fit in `maxFrameBytes`. */
20
20
  export declare const maxReadBytes: (maxFrameBytes: number) => number;
21
- /** What the staged provider sends through: the relay's protocol 3 call and the attested support. */
21
+ /** What the staged provider sends through: the relay's protocol 4 call and the attested support. */
22
22
  export interface StagedDeviceTransport {
23
23
  call(deviceId: string, op: DeviceOperation, args: Record<string, unknown>, opts: {
24
24
  deadlineMs: number;
@@ -60,12 +60,12 @@ export declare class LocalDeviceProvider implements SandboxProvider {
60
60
  private readonly callGrants?;
61
61
  readonly concurrentExec: true;
62
62
  readonly sessionIsolation = false;
63
- constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits">, config: Pick<KernelConfigService, "get">, callGrants?: PermissionCallGrants | undefined);
63
+ constructor(relay: LocalDeviceRelay, targets: Pick<DeviceTargets, "orgOf" | "machineRoots">, sandbox: Pick<SandboxService, "devicePolicy" | "deviceLimits" | "hostGrantCeiling">, config: Pick<KernelConfigService, "get">, callGrants?: PermissionCallGrants | undefined);
64
64
  /**
65
- * The `@local` provider as the staged (protocol 3) registration hands it out
65
+ * The `@local` provider as the staged (protocol 4) registration hands it out
66
66
  * (`LocalDevicesModule`): the protocol 2 lifecycle methods that send no frame (file system,
67
67
  * resume, suspend, destroy), the v3 operation adapter ({@link stagedOperations}), `create` as a
68
- * protocol 3 request, no raw protocol 2 call and no broad kill. Dormant until the protocol gate
68
+ * protocol 4 request, no raw protocol 2 call and no broad kill. Dormant until the protocol gate
69
69
  * selects it.
70
70
  *
71
71
  * The raw methods (`exec`, `readFile`, `writeFile`, `stat`, `list`, `scan`) refuse before
@@ -10,9 +10,11 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { parseDeviceFrame, parseOperationResult, parseSandboxBrowseScope, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxPermissionUnsupportedError, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
+ import { hostGrantable } from "../sandbox/device-sandbox.js";
14
+ import { providerLimits } from "../sandbox/modes.js";
13
15
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
14
16
  import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
15
- import { grantsWithin, relayer } from "./network-grants.js";
17
+ import { relayer } from "./network-grants.js";
16
18
  import { deviceOffline, LocalDeviceRelay } from "./relay.js";
17
19
  import { DeviceTargets, sameRoots } from "./targets.js";
18
20
  /** Extra time the machine gets beyond a command's own timeout (spawn, output, the trip back). */
@@ -34,7 +36,7 @@ const NAME_PREFIX = "cap-device-";
34
36
  * an admitted operation scope; there is no raw fallback).
35
37
  */
36
38
  const refuseRaw = (method) => async (..._args) => {
37
- throw new SandboxPermissionUnsupportedError(`${method} without an operation scope is not available on a protocol 3 device; run it through an admitted operation scope`);
39
+ throw new SandboxPermissionUnsupportedError(`${method} without an operation scope is not available on a protocol 4 device; run it through an admitted operation scope`);
38
40
  };
39
41
  /** The device id of a `cap-device-<deviceId>` name; undefined for any other name. */
40
42
  export const deviceIdOfName = (name) => name.startsWith(NAME_PREFIX) && name.length > NAME_PREFIX.length
@@ -68,10 +70,10 @@ let LocalDeviceProvider = class LocalDeviceProvider {
68
70
  this.callGrants = callGrants;
69
71
  }
70
72
  /**
71
- * The `@local` provider as the staged (protocol 3) registration hands it out
73
+ * The `@local` provider as the staged (protocol 4) registration hands it out
72
74
  * (`LocalDevicesModule`): the protocol 2 lifecycle methods that send no frame (file system,
73
75
  * resume, suspend, destroy), the v3 operation adapter ({@link stagedOperations}), `create` as a
74
- * protocol 3 request, no raw protocol 2 call and no broad kill. Dormant until the protocol gate
76
+ * protocol 4 request, no raw protocol 2 call and no broad kill. Dormant until the protocol gate
75
77
  * selects it.
76
78
  *
77
79
  * The raw methods (`exec`, `readFile`, `writeFile`, `stat`, `list`, `scan`) refuse before
@@ -135,10 +137,22 @@ let LocalDeviceProvider = class LocalDeviceProvider {
135
137
  if (!this.callGrants)
136
138
  throw new Error("Admitted execution authority is unavailable; check the device operation configuration");
137
139
  const original = await this.callGrants.forExecution(scope.operationId, deviceId, method, scope, input);
138
- const grants = grantsWithin(original, limits);
140
+ // explicit hosts are checked against the per-call host ceiling (the org's hard allowlist
141
+ // ceiling and exclusions, the owner's list), never against the sandbox's own allowlist
142
+ const ceiling = await this.sandbox.hostGrantCeiling({ orgId, deviceId });
143
+ const ceilingNetwork = ceiling.kind === "any"
144
+ ? { kind: "open-public", hosts: [] }
145
+ : { kind: "allowlist", hosts: [...ceiling.hosts] };
146
+ const kept = original?.hosts.filter((host) => hostGrantable(ceiling, host)) ?? [];
147
+ const grants = original && kept.length ? { ...original, hosts: kept } : undefined;
139
148
  if (original?.hosts.some((host) => !grants?.hosts.includes(host)))
140
149
  throw new Error("Current organization limits refuse the admitted explicit hosts; review the operation again");
141
- return { limits, ...(grants === undefined ? {} : { grants }) };
150
+ // the wire carries resources and the device sandbox network only: the mode tier is
151
+ // kernel-internal
152
+ return {
153
+ wire: { limits: providerLimits(limits), ...(grants === undefined ? {} : { grants }) },
154
+ ceiling: { network: ceilingNetwork },
155
+ };
142
156
  };
143
157
  const background = {
144
158
  start: async (h, input, args) => {
@@ -147,7 +161,7 @@ let LocalDeviceProvider = class LocalDeviceProvider {
147
161
  const { signal, instanceGeneration: _generation, ...rest } = args;
148
162
  const authority = await execArgs(h.id, scope, "backgroundStart", rest);
149
163
  signal.throwIfAborted();
150
- return parseOperationResult("backgroundStart", await transport.call(h.id, "backgroundStart", { scope, ...rest, ...authority }, { deadlineMs: args.timeoutMs + EXEC_DEADLINE_MARGIN_MS, signal }));
164
+ return parseOperationResult("backgroundStart", await transport.call(h.id, "backgroundStart", { scope, ...rest, ...authority.wire }, { deadlineMs: args.timeoutMs + EXEC_DEADLINE_MARGIN_MS, signal }));
151
165
  },
152
166
  status: async (h, ref, signal) => parseOperationResult("backgroundStatus", await transport.call(h.id, "backgroundStatus", { ref }, { deadlineMs: OP_DEADLINE_MS, signal })),
153
167
  readOutput: async (h, ref, opts) => {
@@ -198,14 +212,14 @@ let LocalDeviceProvider = class LocalDeviceProvider {
198
212
  const authority = await execArgs(h.id, scope, "exec", rest);
199
213
  const combined = AbortSignal.any([signal, callSignal]);
200
214
  combined.throwIfAborted();
201
- const result = parseOperationResult("exec", await transport.call(h.id, "exec", { scope, ...rest, ...authority }, { deadlineMs: args.timeoutMs + EXEC_DEADLINE_MARGIN_MS, signal: combined }));
215
+ const result = parseOperationResult("exec", await transport.call(h.id, "exec", { scope, ...rest, ...authority.wire }, { deadlineMs: args.timeoutMs + EXEC_DEADLINE_MARGIN_MS, signal: combined }));
202
216
  // the kernel's own layer for the machine's report, as on protocol 2: a host the org
203
217
  // does not allow is `org` (only an admin can lift it), never a question to the owner
204
218
  if (result.network?.blocked === undefined)
205
219
  return result;
206
220
  return {
207
221
  ...result,
208
- network: { blocked: relayer(result.network.blocked, authority.limits) },
222
+ network: { blocked: relayer(result.network.blocked, authority.ceiling) },
209
223
  };
210
224
  },
211
225
  };
@@ -20,7 +20,7 @@ export declare class LocalDevicesModule implements OnModuleInit {
20
20
  onModuleInit(): void;
21
21
  }
22
22
  /**
23
- * The `@local` registration: the protocol 3 provider ({@link LocalDeviceProvider.staged}: scoped
23
+ * The `@local` registration: the protocol 4 provider ({@link LocalDeviceProvider.staged}: scoped
24
24
  * operations, no broad kill) with its instance binder, which binds every committed generation
25
25
  * before shared use (B-8).
26
26
  */
@@ -82,7 +82,7 @@ LocalDevicesModule = __decorate([
82
82
  ], LocalDevicesModule);
83
83
  export { LocalDevicesModule };
84
84
  /**
85
- * The `@local` registration: the protocol 3 provider ({@link LocalDeviceProvider.staged}: scoped
85
+ * The `@local` registration: the protocol 4 provider ({@link LocalDeviceProvider.staged}: scoped
86
86
  * operations, no broad kill) with its instance binder, which binds every committed generation
87
87
  * before shared use (B-8).
88
88
  */