@capybara-hq/kernel 0.1.0-rc.128 → 0.1.0-rc.129

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 (113) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/automations/automations.service.js +15 -21
  4. package/dist/automations/effective-settings.d.ts +3 -9
  5. package/dist/automations/effective-settings.js +3 -5
  6. package/dist/automations/fire.js +0 -11
  7. package/dist/automations/grant-rules.d.ts +7 -10
  8. package/dist/automations/grant-rules.js +9 -18
  9. package/dist/automations/unattended.d.ts +1 -4
  10. package/dist/automations/unattended.js +0 -2
  11. package/dist/catalog/org-extension.controller.d.ts +1 -20
  12. package/dist/catalog/org-extension.controller.js +1 -48
  13. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  14. package/dist/catalog/org-extension.schemas.js +1 -17
  15. package/dist/config/schema.d.ts +12 -0
  16. package/dist/config/schema.js +16 -0
  17. package/dist/conversations/approval-profile.d.ts +8 -1
  18. package/dist/conversations/approval-profile.js +20 -0
  19. package/dist/conversations/conversations.service.d.ts +1 -1
  20. package/dist/conversations/conversations.service.js +8 -3
  21. package/dist/conversations/events.d.ts +25 -1
  22. package/dist/conversations/events.js +7 -2
  23. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  24. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  25. package/dist/conversations/permission-profiles.schemas.js +8 -0
  26. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  27. package/dist/conversations/permission-profiles.service.js +13 -1
  28. package/dist/db/kernel-schema.d.ts +21 -0
  29. package/dist/device-access/device-access.service.d.ts +4 -1
  30. package/dist/device-access/device-access.service.js +26 -7
  31. package/dist/device-access/viewer.d.ts +3 -1
  32. package/dist/device-access/viewer.js +18 -9
  33. package/dist/errors.d.ts +6 -0
  34. package/dist/errors.js +6 -0
  35. package/dist/git/gateway.d.ts +8 -1
  36. package/dist/git/gateway.js +68 -11
  37. package/dist/git/git.module.d.ts +2 -3
  38. package/dist/git/git.module.js +4 -4
  39. package/dist/http/api.module.js +3 -3
  40. package/dist/identity/settings.d.ts +20 -5
  41. package/dist/identity/settings.js +52 -9
  42. package/dist/infra/config/kernel-config.service.js +4 -0
  43. package/dist/orgs/orgs.module.js +12 -1
  44. package/dist/orgs/orgs.schemas.js +3 -0
  45. package/dist/orgs/security-settings.service.d.ts +94 -0
  46. package/dist/orgs/security-settings.service.js +223 -0
  47. package/dist/orgs/settings.controller.d.ts +33 -0
  48. package/dist/orgs/settings.controller.js +41 -1
  49. package/dist/orgs/settings.service.d.ts +48 -63
  50. package/dist/orgs/settings.service.js +86 -103
  51. package/dist/platform/exclusions.js +1 -1
  52. package/dist/platform/operation.js +4 -0
  53. package/dist/platform/ops/admin.ops.js +18 -4
  54. package/dist/platform/ops/connectors.ops.js +2 -2
  55. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  56. package/dist/platform/ops/extensions.ops.js +4 -131
  57. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  58. package/dist/platform/ops/org-settings.ops.js +76 -3
  59. package/dist/platform/ops/orgs.ops.js +2 -0
  60. package/dist/runtime/context/permission-profile.js +6 -0
  61. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  62. package/dist/runtime/subagents/dispatch.js +2 -1
  63. package/dist/runtime/subagents/messages.d.ts +3 -1
  64. package/dist/runtime/subagents/messages.js +9 -6
  65. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  66. package/dist/sandbox/device-sandbox-settings.js +64 -1
  67. package/dist/sandbox/device-sandbox.d.ts +9 -1
  68. package/dist/sandbox/device-sandbox.js +17 -2
  69. package/dist/sandbox/device-services.d.ts +26 -3
  70. package/dist/sandbox/device-services.js +95 -16
  71. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  72. package/dist/sandbox/loopback-grant-records.js +32 -5
  73. package/dist/sandbox/operation-authority.d.ts +3 -2
  74. package/dist/sandbox/operation-authority.js +21 -1
  75. package/dist/sandbox/operation-intents.js +5 -1
  76. package/dist/sandbox/permission-call-types.d.ts +2 -1
  77. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  78. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  79. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  80. package/dist/sandbox/permission-config-publication.js +27 -5
  81. package/dist/sandbox/permission-facts.d.ts +21 -2
  82. package/dist/sandbox/permission-facts.js +101 -9
  83. package/dist/sandbox/permission-transitions.d.ts +1 -1
  84. package/dist/sandbox/sandbox.service.d.ts +2 -2
  85. package/dist/sandbox/sandbox.service.js +7 -3
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/approvals.service.d.ts +7 -2
  88. package/dist/tools/approvals.service.js +39 -7
  89. package/dist/tools/builtin-names.d.ts +0 -6
  90. package/dist/tools/builtin-names.js +0 -11
  91. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  92. package/dist/tools/builtins/sandbox/index.js +3 -5
  93. package/dist/tools/connector-account-policies.js +7 -4
  94. package/dist/tools/connectors.controller.d.ts +0 -6
  95. package/dist/tools/connectors.schemas.d.ts +1 -8
  96. package/dist/tools/connectors.schemas.js +1 -4
  97. package/dist/tools/connectors.service.d.ts +3 -7
  98. package/dist/tools/connectors.service.js +29 -44
  99. package/dist/tools/drift.js +12 -4
  100. package/dist/tools/git-push-policy.d.ts +1 -4
  101. package/dist/tools/git-push-policy.js +4 -5
  102. package/dist/tools/org-tool-policies.d.ts +24 -0
  103. package/dist/tools/org-tool-policies.js +113 -0
  104. package/dist/tools/org-tool-switches.d.ts +5 -70
  105. package/dist/tools/org-tool-switches.js +13 -141
  106. package/dist/tools/pipeline.d.ts +11 -5
  107. package/dist/tools/pipeline.js +173 -38
  108. package/dist/tools/policy.d.ts +3 -7
  109. package/dist/tools/policy.js +29 -48
  110. package/dist/tools/registry.d.ts +5 -0
  111. package/dist/tools/registry.js +44 -13
  112. package/package.json +1 -1
  113. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -1,5 +1,28 @@
1
+ import { narrowerProjectReach, } from "@capybara-hq/plugin-sdk";
1
2
  import { z } from "zod";
3
+ import { AllowedProfilesSchema, PermissionProfileSchema, } from "../conversations/permission-profiles.schemas.js";
2
4
  import { DeviceNetworkSettingSchema, invalidDeviceNetwork, } from "../orgs/device-network-setting.js";
5
+ /**
6
+ * The platform's device sandbox settings (approval-only profiles design, "Settings model"): the
7
+ * outside-sandbox ceiling (`devices.outsideSandbox`) and the sandbox network's default and ceiling
8
+ * (`devices.network.default`, `devices.network.ceiling`). Each is both a startup config field and
9
+ * a deployment setting ({@link DEVICES_OUTSIDE_SANDBOX_SETTING}, {@link DEVICES_NETWORK_SETTING}),
10
+ * read live at every use: environment > config file / Nacos > the super admin's choice in the admin
11
+ * console > {@link DEVICE_SANDBOX_DEFAULTS}. A field set in the startup config is read-only in the
12
+ * admin console. An invalid stored value reads narrower with a warning (fail closed): `off`, and
13
+ * the allowlist.
14
+ */
15
+ export { AllowedProfilesSchema };
16
+ export const ProjectReachSchema = z.enum(["workspace", "paths", "machine"]);
17
+ export const DEVICES_ALLOWED_PROFILES_SETTING = "devicesAllowedProfiles";
18
+ export const DEVICES_PROJECT_REACH_SETTING = "devicesProjectReach";
19
+ export const DEFAULT_ALLOWED_PROFILES = PermissionProfileSchema.options;
20
+ export const DEVICES_ALLOWED_PROFILES_PATCH = z
21
+ .object({ value: AllowedProfilesSchema.nullable() })
22
+ .strict();
23
+ export const DEVICES_PROJECT_REACH_PATCH = z
24
+ .object({ ceiling: ProjectReachSchema.nullable() })
25
+ .strict();
3
26
  /** The `deployment_settings` key of the super admin's outside-sandbox choice. */
4
27
  export const DEVICES_OUTSIDE_SANDBOX_SETTING = "devicesOutsideSandbox";
5
28
  /** The `deployment_settings` key of the super admin's network choice. */
@@ -97,7 +120,11 @@ export function resolveDeviceSandboxSettings(configured, stored) {
97
120
  const outside = pick(configured.outsideSandbox, configured.sources.outsideSandbox, stored.outsideSandbox.permission, DEVICE_SANDBOX_DEFAULTS.outsideSandbox);
98
121
  const ceiling = pick(configured.networkCeiling, configured.sources.networkCeiling, stored.network.ceiling, DEVICE_SANDBOX_DEFAULTS.network.ceiling);
99
122
  const def = pick(configured.networkDefault, configured.sources.networkDefault, stored.network.default, DEVICE_SANDBOX_DEFAULTS.network.default);
123
+ const profiles = pick(configured.allowedProfiles, configured.sources.allowedProfiles, stored.allowedProfiles, [...DEFAULT_ALLOWED_PROFILES]);
124
+ const reach = pick(configured.projectReach, configured.sources.projectReach, stored.projectReach, "machine");
100
125
  return {
126
+ allowedProfiles: profiles,
127
+ projectReach: { ceiling: reach.value, source: { ceiling: reach.source } },
101
128
  outsideSandbox: { permission: outside.value, source: outside.source },
102
129
  network: {
103
130
  default: ceiling.value === "allowlist" ? "allowlist" : def.value,
@@ -109,6 +136,8 @@ export function resolveDeviceSandboxSettings(configured, stored) {
109
136
  /** The plain settings of a view. */
110
137
  export const deviceSandboxSettingsOf = (view) => ({
111
138
  outsideSandbox: view.outsideSandbox.permission,
139
+ allowedProfiles: view.allowedProfiles.value,
140
+ projectReach: view.projectReach.ceiling,
112
141
  network: { default: view.network.default, ceiling: view.network.ceiling },
113
142
  });
114
143
  /** The startup config's values and sources. */
@@ -119,10 +148,14 @@ export function configuredDeviceSandbox(config) {
119
148
  outsideSandbox: d?.outsideSandbox,
120
149
  networkDefault: d?.network?.default,
121
150
  networkCeiling: d?.network?.ceiling,
151
+ allowedProfiles: d?.allowedProfiles,
152
+ projectReach: d?.projectReach?.ceiling,
122
153
  sources: {
123
154
  outsideSandbox: config.fieldSource("devices.outsideSandbox"),
124
155
  networkDefault: config.fieldSource("devices.network.default"),
125
156
  networkCeiling: config.fieldSource("devices.network.ceiling"),
157
+ allowedProfiles: config.fieldSource("devices.allowedProfiles"),
158
+ projectReach: config.fieldSource("devices.projectReach.ceiling"),
126
159
  },
127
160
  };
128
161
  }
@@ -131,12 +164,34 @@ export async function readStoredDeviceSandbox(db, log) {
131
164
  const rows = await db
132
165
  .selectFrom("deployment_settings")
133
166
  .select(["key", "value"])
134
- .where("key", "in", [DEVICES_OUTSIDE_SANDBOX_SETTING, DEVICES_NETWORK_SETTING])
167
+ .where("key", "in", [
168
+ DEVICES_OUTSIDE_SANDBOX_SETTING,
169
+ DEVICES_NETWORK_SETTING,
170
+ DEVICES_ALLOWED_PROFILES_SETTING,
171
+ DEVICES_PROJECT_REACH_SETTING,
172
+ ])
135
173
  .execute();
136
174
  const values = new Map(rows.map((row) => [row.key, row.value]));
175
+ const stored = (key, schema, fallback) => {
176
+ if (!values.has(key))
177
+ return undefined;
178
+ const parsed = schema.safeParse(values.get(key));
179
+ if (parsed.success)
180
+ return parsed.data;
181
+ log?.warn("invalid deployment setting; using its narrowest value", { key });
182
+ return fallback;
183
+ };
137
184
  return {
138
185
  outsideSandbox: parseStoredDevicesOutsideSandbox(values.get(DEVICES_OUTSIDE_SANDBOX_SETTING), log),
139
186
  network: parseStoredDevicesNetwork(values.get(DEVICES_NETWORK_SETTING), log),
187
+ allowedProfiles: stored(DEVICES_ALLOWED_PROFILES_SETTING, z
188
+ .object({ value: AllowedProfilesSchema.optional() })
189
+ .strict()
190
+ .transform(({ value }) => value), ["request-approval"]),
191
+ projectReach: stored(DEVICES_PROJECT_REACH_SETTING, z
192
+ .object({ ceiling: ProjectReachSchema.optional() })
193
+ .strict()
194
+ .transform(({ ceiling }) => ceiling), "workspace"),
140
195
  };
141
196
  }
142
197
  /**
@@ -153,6 +208,8 @@ export async function readDeviceSandboxSettings(db, config, log) {
153
208
  }
154
209
  const asObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
155
210
  export const OrgDeviceSandboxStoredSchema = z.object({
211
+ allowedProfiles: AllowedProfilesSchema.optional().catch(["request-approval"]),
212
+ projectReach: ProjectReachSchema.optional().catch("workspace"),
156
213
  outsideSandbox: Permission.optional().catch("off"),
157
214
  deviceNetwork: DeviceNetworkSettingSchema.catch(invalidDeviceNetwork)
158
215
  .transform((network) => (Object.keys(network).length > 0 ? network : undefined))
@@ -162,3 +219,9 @@ export const OrgDeviceSandboxStoredSchema = z.object({
162
219
  export function orgDeviceSandboxOf(raw) {
163
220
  return OrgDeviceSandboxStoredSchema.parse(asObject(raw));
164
221
  }
222
+ export function effectiveAllowedProfiles(platform, org) {
223
+ return org === undefined ? [...platform] : platform.filter((profile) => org.includes(profile));
224
+ }
225
+ export function effectiveProjectReach(platform, org) {
226
+ return org === undefined ? platform : narrowerProjectReach(platform, org);
227
+ }
@@ -1,4 +1,4 @@
1
- import type { SandboxBoundary, SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceProjectReach, type PermissionProfile, type SandboxBoundary, type SandboxPermissionSupport } from "@capybara-hq/plugin-sdk";
2
2
  /**
3
3
  * The device sandbox (approval-only profiles design, "Settings model"): one pure function computes
4
4
  * the effective scope boundary, sandbox network and outside-sandbox ceiling of a device from the
@@ -28,6 +28,8 @@ export declare const deviceSideLayer: (layer: DeviceSandboxLayer | null | undefi
28
28
  export interface DeviceSandboxSettings {
29
29
  /** `devices.outsideSandbox`: whether any device may be granted escalation outside the sandbox. */
30
30
  outsideSandbox: "allowed" | "off";
31
+ allowedProfiles?: readonly PermissionProfile[];
32
+ projectReach?: DeviceProjectReach;
31
33
  network: {
32
34
  /** `devices.network.default`: the mode a device follows when nothing narrower chooses. */
33
35
  default: DeviceNetworkMode;
@@ -48,6 +50,7 @@ export interface DeviceSandboxPlatformLayer {
48
50
  /** The org layer: absent fields follow the platform. */
49
51
  export interface DeviceSandboxOrgLayer {
50
52
  outsideSandbox?: "allowed" | "off";
53
+ projectReach?: DeviceProjectReach | undefined;
51
54
  deviceNetwork?: {
52
55
  default?: DeviceNetworkMode | undefined;
53
56
  ceiling?: DeviceNetworkMode | undefined;
@@ -117,7 +120,11 @@ export interface DeviceSandbox {
117
120
  layer: {
118
121
  network: DeviceSandboxLayer | null;
119
122
  outsideSandbox: DeviceSandboxLayer | null;
123
+ outsideSandboxReason?: "reach";
124
+ projectReach?: "platform" | "org";
120
125
  };
126
+ /** Omitted at the default machine ceiling. */
127
+ projectReach?: DeviceProjectReach;
121
128
  }
122
129
  /**
123
130
  * The hosts of `a` the list `b` covers and the hosts of `b` that `a` covers (wildcards included),
@@ -210,6 +217,7 @@ export declare function deviceListAddRefusal(host: string, box: Pick<DeviceSandb
210
217
  * fingerprint"): running outside, the network ceiling and mode and the per-call host ceiling.
211
218
  */
212
219
  export interface ConsentReach {
220
+ projectReach?: DeviceProjectReach;
213
221
  outsideSandbox: boolean;
214
222
  networkCeiling: DeviceNetworkMode | "none";
215
223
  networkMode: DeviceNetworkMode | "none";
@@ -1,3 +1,4 @@
1
+ import { narrowerProjectReach, } from "@capybara-hq/plugin-sdk";
1
2
  import { coversHost, orgEffectiveHosts } from "./modes.js";
2
3
  /**
3
4
  * Whether a ceiling's layer is the device's side (its provider, or the owner of the machine it
@@ -45,7 +46,7 @@ export function orgHostsOf(platform, org) {
45
46
  export function effectiveDeviceSandbox(platform, org, device, provider) {
46
47
  const instance = provider.boundary === "instance";
47
48
  // running outside the sandbox: the first layer that forbids it names the ceiling
48
- const outsideLayer = platform.settings.outsideSandbox !== "allowed"
49
+ const independentOutsideLayer = platform.settings.outsideSandbox !== "allowed"
49
50
  ? "platform"
50
51
  : org.outsideSandbox === "off"
51
52
  ? "org"
@@ -54,6 +55,10 @@ export function effectiveDeviceSandbox(platform, org, device, provider) {
54
55
  : !provider.outsideSandbox
55
56
  ? (provider.limitedBy?.outsideSandbox ?? "provider")
56
57
  : null;
58
+ const platformReach = platform.settings.projectReach ?? "machine";
59
+ const projectReach = narrowerProjectReach(platformReach, org.projectReach ?? "machine");
60
+ const reachLayer = projectReach === "machine" ? null : projectReach === platformReach ? "platform" : "org";
61
+ const outsideLayer = independentOutsideLayer ?? reachLayer;
57
62
  // the network ceiling: platform, then org, then what the provider can enforce
58
63
  let ceiling;
59
64
  let networkLayer = null;
@@ -106,7 +111,14 @@ export function effectiveDeviceSandbox(platform, org, device, provider) {
106
111
  outsideSandbox: outsideLayer === null,
107
112
  perCallHosts: !instance && provider.network.perOperationHosts,
108
113
  loopbackPorts: outsideLayer === null && provider.network.loopbackPorts === true,
109
- layer: { network: networkLayer, outsideSandbox: outsideLayer },
114
+ ...(reachLayer && { projectReach }),
115
+ layer: {
116
+ network: networkLayer,
117
+ outsideSandbox: outsideLayer,
118
+ ...(reachLayer && { projectReach: reachLayer }),
119
+ ...(reachLayer &&
120
+ independentOutsideLayer === null && { outsideSandboxReason: "reach" }),
121
+ },
110
122
  };
111
123
  }
112
124
  /**
@@ -219,6 +231,9 @@ const MODE_RANK = { none: 0, allowlist: 1, open: 2 };
219
231
  * of any dimension needs a new one (Full access would otherwise auto-approve more).
220
232
  */
221
233
  export function reachWithin(now, consented) {
234
+ const projectReach = now.projectReach ?? "machine";
235
+ if (narrowerProjectReach(projectReach, consented.projectReach ?? "machine") !== projectReach)
236
+ return false;
222
237
  if (now.outsideSandbox && !consented.outsideSandbox)
223
238
  return false;
224
239
  if (MODE_RANK[now.networkCeiling] > MODE_RANK[consented.networkCeiling])
@@ -1,8 +1,12 @@
1
- import { type DeviceServiceSpec, type DeviceServiceStatus } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceProjectReach, type DeviceServiceSpec, type DeviceServiceStatus, type SandboxHandle } from "@capybara-hq/plugin-sdk";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
2
3
  import { LockService } from "../infra/lock/lock.service.js";
3
4
  import { LoopbackLivePorts } from "./loopback-live-ports.js";
5
+ import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
6
+ import { PermissionAuthorityLock } from "./permission-authority-lock.js";
7
+ import { PermissionConfigPublication } from "./permission-config-publication.js";
4
8
  import { PermissionFacts } from "./permission-facts.js";
5
- import { SandboxService } from "./sandbox.service.js";
9
+ import { type DeviceServiceMethods, SandboxService } from "./sandbox.service.js";
6
10
  import type { SandboxUseContext } from "./use-context.js";
7
11
  /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
8
12
  export declare const POST_APPLY_ENSURE_TIMEOUT_MS = 30000;
@@ -38,7 +42,17 @@ export declare class DeviceServices {
38
42
  private readonly loopback;
39
43
  private readonly locks;
40
44
  private readonly facts;
41
- constructor(sandbox: SandboxService, loopback: Pick<LoopbackLivePorts, "livePorts">, locks: Pick<LockService, "run">, facts: Pick<PermissionFacts, "deviceSandboxFacts">);
45
+ private readonly serviceTransactions;
46
+ private readonly authority;
47
+ private readonly epochs;
48
+ private readonly publication;
49
+ constructor(sandbox: SandboxService, loopback: Pick<LoopbackLivePorts, "livePorts">, locks: Pick<LockService, "run">, facts: Pick<PermissionFacts, "deviceSandboxFacts" | "projectReachAuthority">, serviceTransactions: Pick<TransactionHost, "run">, authority: Pick<PermissionAuthorityLock, "acquire">, epochs: Pick<PermissionAuthorityEpochStore, "readLocked">, publication: Pick<PermissionConfigPublication, "assertCurrent">);
50
+ private atServiceAdmission;
51
+ /**
52
+ * Starts the admitted operation at the authority boundary without carrying the PG transaction
53
+ * into the provider. The boxed promise is awaited only after the shared locks release.
54
+ */
55
+ private dispatch;
42
56
  /**
43
57
  * Runs `send` with the service's live loopback ports under the (device, service) set lock: the
44
58
  * set is read after the lock is taken and the send finishes before it is released, so the
@@ -81,6 +95,15 @@ export declare class DeviceServices {
81
95
  * null without a running instance.
82
96
  */
83
97
  private ifRunningEnsure;
98
+ projectReachCeiling(orgId: string, deviceId: string): Promise<DeviceProjectReach>;
99
+ private readReachAdmission;
100
+ /**
101
+ * Proves the held service's reach, then admits the actual request or stream under that same
102
+ * authority. A concurrent writer can win while the proof runs. Its epoch or ceiling differs at
103
+ * admission, so the provider does not receive this use. The default machine ceiling is checked
104
+ * at both boundaries too.
105
+ */
106
+ withConfirmedReach<T>(orgId: string, deviceId: string, name: string, h: SandboxHandle, p: Pick<DeviceServiceMethods, "ensureService">, signal: AbortSignal, send: () => Promise<T>): Promise<T>;
84
107
  /**
85
108
  * One request to the service's socket; resolves its answer (throws when it is not running).
86
109
  * A request is a use of the device: a suspended instance is resumed. With `ifRunning` it never
@@ -9,10 +9,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { DEVICE_SERVICE_ID_RE, DeviceAccessError, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
+ import { runOutsideTransaction, TransactionHost } from "../infra/database/transaction-host.js";
12
13
  import { LockService } from "../infra/lock/lock.service.js";
13
14
  import { knownLoopbackRefusal } from "./loopback-grant-records.js";
14
15
  import { LoopbackLivePorts } from "./loopback-live-ports.js";
15
- import { PermissionFacts } from "./permission-facts.js";
16
+ import { PermissionAuthorityEpochStore } from "./permission-authority-epochs.js";
17
+ import { PermissionAuthorityLock } from "./permission-authority-lock.js";
18
+ import { PermissionConfigPublication } from "./permission-config-publication.js";
19
+ import { PermissionFacts, permissionScopeHash } from "./permission-facts.js";
16
20
  import { SandboxService } from "./sandbox.service.js";
17
21
  /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
18
22
  export const POST_APPLY_ENSURE_TIMEOUT_MS = 30_000;
@@ -48,11 +52,37 @@ let DeviceServices = class DeviceServices {
48
52
  loopback;
49
53
  locks;
50
54
  facts;
51
- constructor(sandbox, loopback, locks, facts) {
55
+ serviceTransactions;
56
+ authority;
57
+ epochs;
58
+ publication;
59
+ constructor(sandbox, loopback, locks, facts, serviceTransactions, authority, epochs, publication) {
52
60
  this.sandbox = sandbox;
53
61
  this.loopback = loopback;
54
62
  this.locks = locks;
55
63
  this.facts = facts;
64
+ this.serviceTransactions = serviceTransactions;
65
+ this.authority = authority;
66
+ this.epochs = epochs;
67
+ this.publication = publication;
68
+ }
69
+ atServiceAdmission(orgId, deviceId, read) {
70
+ const subject = { orgId, deviceId };
71
+ return runOutsideTransaction(() => this.serviceTransactions.run(async () => {
72
+ await this.authority.acquire(subject, { kind: "admit" });
73
+ await this.publication.assertCurrent();
74
+ return read(subject);
75
+ }, { propagation: "requires_new" }));
76
+ }
77
+ /**
78
+ * Starts the admitted operation at the authority boundary without carrying the PG transaction
79
+ * into the provider. The boxed promise is awaited only after the shared locks release.
80
+ */
81
+ dispatch(signal, send) {
82
+ signal.throwIfAborted();
83
+ const pending = runOutsideTransaction(send);
84
+ void pending.catch(() => { });
85
+ return { pending };
56
86
  }
57
87
  /**
58
88
  * Runs `send` with the service's live loopback ports under the (device, service) set lock: the
@@ -60,12 +90,23 @@ let DeviceServices = class DeviceServices {
60
90
  * sends reach the device in the order their sets were read. A lost lock aborts the send. The
61
91
  * opts carry `loopbackPorts` only for a non-empty set the device sandbox admits (see the class).
62
92
  */
63
- withLoopbackSet(orgId, deviceId, name, signal, send) {
93
+ withLoopbackSet(orgId, deviceId, name, handle, signal, send) {
64
94
  return this.locks.run(`loopback-set-${deviceId}-${name}`, { ttlMs: LOOPBACK_SET_LOCK_TTL_MS, waitMs: LOOPBACK_SET_LOCK_WAIT_MS, signal }, async (held) => {
65
- const ports = await this.loopback.livePorts(orgId, deviceId, name);
66
- const admitted = ports.length > 0 &&
67
- knownLoopbackRefusal(await this.facts.deviceSandboxFacts(orgId, deviceId)) === null;
68
- return send(admitted ? { loopbackPorts: ports } : {}, AbortSignal.any([signal, held.lost]));
95
+ const combined = AbortSignal.any([signal, held.lost]);
96
+ const { pending } = await this.atServiceAdmission(orgId, deviceId, async () => {
97
+ const ports = await this.loopback.livePorts(orgId, deviceId, name);
98
+ const device = await this.facts.deviceSandboxFacts(orgId, deviceId);
99
+ const admitted = ports.length > 0 && knownLoopbackRefusal(device) === null;
100
+ const ceiling = device.box.projectReach;
101
+ const projectReach = ceiling === undefined
102
+ ? undefined
103
+ : await this.facts.projectReachAuthority(orgId, deviceId, ceiling, handle);
104
+ return this.dispatch(combined, () => send({
105
+ ...(admitted && { loopbackPorts: ports }),
106
+ ...(projectReach !== undefined && { projectReach }),
107
+ }, combined));
108
+ });
109
+ return pending;
69
110
  });
70
111
  }
71
112
  /**
@@ -79,7 +120,7 @@ let DeviceServices = class DeviceServices {
79
120
  return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => {
80
121
  const ensure = p.ensureService;
81
122
  // read under the use and the set lock, so a grant committed before it is in the set
82
- return this.withLoopbackSet(use.orgId, use.deviceId, spec.name, sig, (loopback, s) => opts.ifRunning === true
123
+ return this.withLoopbackSet(use.orgId, use.deviceId, spec.name, h, sig, (loopback, s) => opts.ifRunning === true
83
124
  ? ensure(h, nameOnlySpec(spec.name), s, { ifRunning: true, ...loopback })
84
125
  : ensure(h, spec, s, loopback));
85
126
  }, signal);
@@ -129,10 +170,42 @@ let DeviceServices = class DeviceServices {
129
170
  const r = await this.sandbox.ifRunning(deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
130
171
  requireServices(p);
131
172
  const ensure = p.ensureService;
132
- return this.withLoopbackSet(orgId, deviceId, name, sig, (loopback, s) => ensure(h, nameOnlySpec(name), s, { ifRunning: true, ...loopback }));
173
+ return this.withLoopbackSet(orgId, deviceId, name, h, sig, (loopback, s) => ensure(h, nameOnlySpec(name), s, { ifRunning: true, ...loopback }));
133
174
  }, signal);
134
175
  return r.kind === "ran" ? r.value : null;
135
176
  }
177
+ async projectReachCeiling(orgId, deviceId) {
178
+ return (await this.facts.deviceSandboxFacts(orgId, deviceId)).box.projectReach ?? "machine";
179
+ }
180
+ async readReachAdmission(orgId, deviceId) {
181
+ const ceiling = await this.projectReachCeiling(orgId, deviceId);
182
+ const vector = await this.epochs.readLocked({ orgId, deviceId });
183
+ return { ceiling, revision: permissionScopeHash({ ceiling, vector }) };
184
+ }
185
+ /**
186
+ * Proves the held service's reach, then admits the actual request or stream under that same
187
+ * authority. A concurrent writer can win while the proof runs. Its epoch or ceiling differs at
188
+ * admission, so the provider does not receive this use. The default machine ceiling is checked
189
+ * at both boundaries too.
190
+ */
191
+ async withConfirmedReach(orgId, deviceId, name, h, p, signal, send) {
192
+ const initial = await this.atServiceAdmission(orgId, deviceId, () => this.readReachAdmission(orgId, deviceId));
193
+ if (initial.ceiling !== "machine") {
194
+ if (!p.ensureService)
195
+ throw new DeviceAccessError("capability_missing", "The provider cannot verify the running service's project reach.");
196
+ const ensure = p.ensureService.bind(p);
197
+ const status = await this.withLoopbackSet(orgId, deviceId, name, h, signal, (authority, s) => ensure(h, nameOnlySpec(name), s, { ifRunning: true, ...authority }));
198
+ if (status.state !== "running")
199
+ throw notRunning();
200
+ }
201
+ const { pending } = await this.atServiceAdmission(orgId, deviceId, async () => {
202
+ const current = await this.readReachAdmission(orgId, deviceId);
203
+ if (current.revision !== initial.revision)
204
+ throw new DeviceAccessError("not_running", "Device service authority changed. Retry with its current settings.");
205
+ return this.dispatch(signal, send);
206
+ });
207
+ return pending;
208
+ }
136
209
  /**
137
210
  * One request to the service's socket; resolves its answer (throws when it is not running).
138
211
  * A request is a use of the device: a suspended instance is resumed. With `ifRunning` it never
@@ -144,10 +217,12 @@ let DeviceServices = class DeviceServices {
144
217
  assertServiceName(name);
145
218
  if (opts.ifRunning === true)
146
219
  return this.requestIfRunning(use, name, body, timeoutMs, signal);
147
- return this.sandbox.withDeviceServices(use, requireServices, (h, p, sig) => p.serviceRequest(h, name, body, {
148
- timeoutMs,
149
- signal: sig,
150
- }), signal);
220
+ return this.sandbox.withDeviceServices(use, requireServices, async (h, p, sig) => {
221
+ return this.withConfirmedReach(use.orgId, use.deviceId, name, h, p, sig, () => p.serviceRequest(h, name, body, {
222
+ timeoutMs,
223
+ signal: sig,
224
+ }));
225
+ }, signal);
151
226
  }
152
227
  async requestIfRunning(use, name, body, timeoutMs, signal) {
153
228
  const current = await this.sandbox.currentInstance(use.deviceId);
@@ -160,10 +235,10 @@ let DeviceServices = class DeviceServices {
160
235
  if (st !== null && st.state !== "running")
161
236
  throw notRunning();
162
237
  }
163
- return p.serviceRequest(h, name, body, {
238
+ return this.withConfirmedReach(use.orgId, use.deviceId, name, h, p, sig, () => p.serviceRequest(h, name, body, {
164
239
  timeoutMs,
165
240
  signal: sig,
166
- });
241
+ }));
167
242
  }, signal);
168
243
  if (r.kind !== "ran")
169
244
  throw notRunning();
@@ -205,7 +280,11 @@ DeviceServices = __decorate([
205
280
  __param(0, Inject(SandboxService)),
206
281
  __param(1, Inject(LoopbackLivePorts)),
207
282
  __param(2, Inject(LockService)),
208
- __param(3, Inject(PermissionFacts))
283
+ __param(3, Inject(PermissionFacts)),
284
+ __param(4, Inject(TransactionHost)),
285
+ __param(5, Inject(PermissionAuthorityLock)),
286
+ __param(6, Inject(PermissionAuthorityEpochStore)),
287
+ __param(7, Inject(PermissionConfigPublication))
209
288
  ], DeviceServices);
210
289
  export { DeviceServices };
211
290
  /**
@@ -101,14 +101,15 @@ export declare function oweRefresh(outbox: Pick<OutboxService, "add">, target: L
101
101
  * Owes one refresh per (device, service) with live grants under the subject, in the caller's
102
102
  * transaction (a ceiling publication, `PermissionCeilingWrites.publishLocked`): every org at the
103
103
  * platform level, the org's, the device's, or the root conversation's grants. Returns how many it
104
- * owed. The job decides whether the ceiling now refuses and revokes then.
104
+ * owed. The job decides whether the ceiling now refuses and revokes then. A narrowed project reach
105
+ * also refreshes services known from their launch records, even without a live port grant.
105
106
  */
106
107
  export declare function oweLoopbackRefreshes(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, under: {
107
108
  level: "platform" | "org" | "device" | "root";
108
109
  orgId?: string;
109
110
  deviceId?: string;
110
111
  rootConversationId?: string;
111
- }, change: string): Promise<number>;
112
+ }, change: string, refreshStartedServices?: boolean): Promise<number>;
112
113
  /**
113
114
  * Revokes a deleted device's live grants (reason `revoked`, audited with `cause: "device-deleted"`)
114
115
  * and owes their refreshes, in the caller's transaction (the device's deletion or its owner's
@@ -1,4 +1,4 @@
1
- import { DeviceAccessError, LOOPBACK_DATABASE_PORTS, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
1
+ import { DEVICE_SERVICE_ID_RE, DeviceAccessError, LOOPBACK_DATABASE_PORTS, LOOPBACK_MAX_PORTS_PER_SERVICE, } from "@capybara-hq/plugin-sdk";
2
2
  import { sql } from "kysely";
3
3
  import { audit } from "../identity/audit.js";
4
4
  import { asPlatform } from "../infra/database/org-scope.js";
@@ -131,9 +131,10 @@ export async function oweRefresh(outbox, target, change) {
131
131
  * Owes one refresh per (device, service) with live grants under the subject, in the caller's
132
132
  * transaction (a ceiling publication, `PermissionCeilingWrites.publishLocked`): every org at the
133
133
  * platform level, the org's, the device's, or the root conversation's grants. Returns how many it
134
- * owed. The job decides whether the ceiling now refuses and revokes then.
134
+ * owed. The job decides whether the ceiling now refuses and revokes then. A narrowed project reach
135
+ * also refreshes services known from their launch records, even without a live port grant.
135
136
  */
136
- export async function oweLoopbackRefreshes(db, outbox, under, change) {
137
+ export async function oweLoopbackRefreshes(db, outbox, under, change, refreshStartedServices = false) {
137
138
  const need = (v) => {
138
139
  if (!v)
139
140
  throw new Error(`A ${under.level} loopback refresh needs its subject`);
@@ -167,9 +168,35 @@ export async function oweLoopbackRefreshes(db, outbox, under, change) {
167
168
  .orderBy("device_id")
168
169
  .orderBy("service_id")
169
170
  .execute();
170
- for (const r of rows)
171
+ if (refreshStartedServices && (under.level === "org" || under.level === "platform")) {
172
+ // The audit rows supply identifiers only. The ifRunning job proves liveness and re-reads
173
+ // current authority; an audit of a service that has since stopped starts nothing.
174
+ const readStarted = async () => {
175
+ let started = db
176
+ .selectFrom("audit_events as a")
177
+ .innerJoin("device_instances as i", (j) => j.onRef("i.org_id", "=", "a.org_id").onRef("i.device_id", "=", "a.target"))
178
+ .innerJoin("devices as d", (j) => j.onRef("d.org_id", "=", "i.org_id").onRef("d.id", "=", "i.device_id"))
179
+ .select(["i.org_id", "i.device_id", sql `a.detail->>'serviceId'`.as("service_id")])
180
+ .where("a.action", "in", ["device.service_started", "device.service_launch_authorized"])
181
+ .where("i.status", "=", "running")
182
+ .where("d.deleted_at", "is", null)
183
+ .distinct();
184
+ if (under.level === "org")
185
+ started = started.where("i.org_id", "=", need(under.orgId));
186
+ return started.execute();
187
+ };
188
+ const started = under.level === "platform"
189
+ ? // org-filter: deployment-wide: platform reach can narrow services in every org.
190
+ await asPlatform("platform reach ceiling changed for device services", readStarted)
191
+ : await readStarted();
192
+ for (const row of started)
193
+ if (typeof row.service_id === "string" && DEVICE_SERVICE_ID_RE.test(row.service_id))
194
+ rows.push(row);
195
+ }
196
+ const targets = new Map(rows.map((r) => [`${r.org_id}/${r.device_id}/${r.service_id}`, r]));
197
+ for (const [, r] of [...targets].sort(([a], [b]) => a.localeCompare(b)))
171
198
  await oweRefresh(outbox, { orgId: r.org_id, deviceId: r.device_id, serviceId: r.service_id }, change);
172
- return rows.length;
199
+ return targets.size;
173
200
  }
174
201
  /**
175
202
  * Revokes a deleted device's live grants (reason `revoked`, audited with `cause: "device-deleted"`)
@@ -1,4 +1,4 @@
1
- import { type PermissionProfile, type SandboxActor, type SandboxBoundary, type SandboxBrowseScope, type SandboxOperationScope } from "@capybara-hq/plugin-sdk";
1
+ import { type PermissionProfile, type ProjectReachAuthority, type SandboxActor, type SandboxBoundary, type SandboxBrowseScope, type SandboxOperationScope } from "@capybara-hq/plugin-sdk";
2
2
  import { type PermissionContextV2 } from "../conversations/events.js";
3
3
  import { PermissionProfileStore } from "../conversations/permission-profile-store.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -36,6 +36,7 @@ export interface PermissionScopeFacts {
36
36
  /** The provider's boundary: an `instance` device's scope is its whole filesystem. */
37
37
  boundary: SandboxBoundary;
38
38
  outsideSandboxCeiling: boolean;
39
+ projectReach?: ProjectReachAuthority;
39
40
  /**
40
41
  * An approved per-call sandbox escalation of this exact call (its immutable call grant): the
41
42
  * operation runs outside the sandbox, within the device's outside-sandbox ceiling, under any
@@ -80,7 +81,7 @@ export declare class SandboxOperationAuthority {
80
81
  accountId: string;
81
82
  }, signal: AbortSignal, narrow?: {
82
83
  readRoots: readonly string[];
83
- }): Promise<SandboxBrowseScope>;
84
+ }, preflight?: boolean): Promise<SandboxBrowseScope>;
84
85
  /**
85
86
  * The one actor liveness predicate of owner browsing, the recorded permission context and the
86
87
  * managed device context writer: an active account that is still a member of a live org.
@@ -21,6 +21,7 @@ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database
21
21
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
22
  import { narrowReadRoots } from "./browse-roots.js";
23
23
  import { hostGrantable } from "./device-sandbox.js";
24
+ import { DEFAULT_ALLOWED_PROFILES } from "./device-sandbox-settings.js";
24
25
  import { KernelReadUnsupported, kernelReadCovering, kernelReadRoute, } from "./kernel-read.js";
25
26
  import { coversHost } from "./modes.js";
26
27
  import { NetworkGrants } from "./network-grants.js";
@@ -103,6 +104,7 @@ export function intersectPermissionScope(f) {
103
104
  profile: f.profile,
104
105
  actor: f.actor,
105
106
  tag: f.tag,
107
+ ...(f.projectReach !== undefined && { projectReach: f.projectReach }),
106
108
  filesystem: escalated
107
109
  ? { kind: "device" }
108
110
  : f.boundary === "instance"
@@ -152,7 +154,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
152
154
  * that lie inside the owner's ceiling ({@link narrowReadRoots}), never wider; when none does the
153
155
  * browse is refused (`device.project_outside_mode`).
154
156
  */
155
- async resolveBrowse(ctx, signal, narrow) {
157
+ async resolveBrowse(ctx, signal, narrow, preflight = false) {
156
158
  signal.throwIfAborted();
157
159
  await this.locks.acquire({ orgId: ctx.orgId, deviceId: ctx.deviceId }, { kind: "admit" });
158
160
  await this.publication.assertCurrent();
@@ -170,6 +172,9 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
170
172
  throw new ApiError("device.project_outside_mode", "The project lies outside what the device lets its owner browse; remove it and add it again from a directory under the device's base");
171
173
  const operationId = randomUUID();
172
174
  const vector = await this.epochs.readLocked({ orgId: ctx.orgId, deviceId: ctx.deviceId });
175
+ const projectReach = preflight
176
+ ? undefined
177
+ : await this.facts.projectReachAuthority(ctx.orgId, ctx.deviceId, scope.projectReach);
173
178
  return parseSandboxBrowseScope({
174
179
  operationId,
175
180
  deviceId: ctx.deviceId,
@@ -177,6 +182,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
177
182
  admitBeforeMs: Date.now() + 30000,
178
183
  ceilingRevision: permissionScopeHash(vector),
179
184
  readRoots,
185
+ ...(projectReach !== undefined && { projectReach }),
180
186
  tag: operationId,
181
187
  });
182
188
  }
@@ -440,6 +446,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
440
446
  network: isExecutionMethod(operation) ? (f.network ?? "none") : "none",
441
447
  boundary: f.boundary ?? "operation",
442
448
  outsideSandboxCeiling: f.outsideSandboxCeiling,
449
+ ...(f.projectReach !== undefined && { projectReach: f.projectReach }),
443
450
  ...(escalated ? { escalated: true } : {}),
444
451
  });
445
452
  }
@@ -528,6 +535,9 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
528
535
  })
529
536
  : null;
530
537
  const vector = await this.epochs.readLocked(subject);
538
+ const projectReach = withheld
539
+ ? undefined
540
+ : await this.facts.projectReachAuthority(ctx.orgId, ctx.deviceId, sandbox.projectReach);
531
541
  signal.throwIfAborted();
532
542
  if (!view.scopeRevision)
533
543
  throw new ApiError("forbidden", "Device permission scope is unavailable");
@@ -550,6 +560,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
550
560
  network: sandboxNetworkOf(sandbox, applied?.outerNetwork),
551
561
  boundary: sandbox.boundary,
552
562
  outsideSandboxCeiling: view.outsideSandboxCeiling,
563
+ ...(projectReach !== undefined && { projectReach }),
553
564
  // the view keeps Full access only while its consent covers the device's ceilings
554
565
  fullConsent: view.profile === "full-access",
555
566
  unattended,
@@ -761,9 +772,13 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
761
772
  scope: null,
762
773
  });
763
774
  const { view, access } = await this.facts.viewWithAccess(input.orgId, input.accountId, root);
775
+ const profileCeiling = view.allowedProfiles.length !== DEFAULT_ALLOWED_PROFILES.length
776
+ ? { allowedProfiles: view.allowedProfiles }
777
+ : {};
764
778
  if (root.device_id === null || access === "no-device")
765
779
  return parse({
766
780
  ...header,
781
+ ...profileCeiling,
767
782
  profileRevision: root.permission_revision,
768
783
  selectedProfile: root.permission_profile,
769
784
  effectiveProfile: null,
@@ -808,6 +823,7 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
808
823
  const effectiveProfile = scheduled ? "request-approval" : view.profile;
809
824
  const known = {
810
825
  ...header,
826
+ ...profileCeiling,
811
827
  profileRevision: root.permission_revision,
812
828
  selectedProfile: root.permission_profile,
813
829
  effectiveProfile,
@@ -833,6 +849,8 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
833
849
  holderConversationId: input.conversationId,
834
850
  runId: input.runId,
835
851
  });
852
+ if (base.sandbox.projectReach !== undefined)
853
+ await this.facts.projectReachAuthority(input.orgId, deviceId, base.sandbox.projectReach);
836
854
  }
837
855
  catch (error) {
838
856
  if (!(error instanceof ApiError))
@@ -886,6 +904,8 @@ let SandboxOperationAuthority = class SandboxOperationAuthority {
886
904
  network: { kind: network.kind, hostsCount: hosts.length },
887
905
  // an instance boundary has no outside: its instance is the outermost boundary
888
906
  outsideSandbox: box.boundary === "operation" && box.outsideSandbox,
907
+ ...(box.projectReach &&
908
+ box.projectReach !== "machine" && { projectReach: box.projectReach }),
889
909
  outerNetwork: applied.outerNetwork,
890
910
  // a host is granted per call only where each operation carries its own network (an
891
911
  // operation boundary whose provider reports `perOperationHosts`)