@capybara-hq/kernel 0.1.0-rc.127 → 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 (122) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/agents/readiness.service.d.ts +6 -0
  4. package/dist/agents/readiness.service.js +1 -1
  5. package/dist/automations/automations.service.js +15 -21
  6. package/dist/automations/effective-settings.d.ts +3 -9
  7. package/dist/automations/effective-settings.js +3 -5
  8. package/dist/automations/fire.js +0 -11
  9. package/dist/automations/grant-rules.d.ts +7 -10
  10. package/dist/automations/grant-rules.js +9 -18
  11. package/dist/automations/unattended.d.ts +1 -4
  12. package/dist/automations/unattended.js +0 -2
  13. package/dist/catalog/catalog-items.d.ts +7 -4
  14. package/dist/catalog/catalog-items.js +8 -7
  15. package/dist/catalog/catalog-scope.service.d.ts +3 -2
  16. package/dist/catalog/catalog-scope.service.js +5 -4
  17. package/dist/catalog/org-extension.controller.d.ts +1 -20
  18. package/dist/catalog/org-extension.controller.js +1 -48
  19. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  20. package/dist/catalog/org-extension.schemas.js +1 -17
  21. package/dist/config/schema.d.ts +12 -0
  22. package/dist/config/schema.js +16 -0
  23. package/dist/conversations/approval-profile.d.ts +8 -1
  24. package/dist/conversations/approval-profile.js +20 -0
  25. package/dist/conversations/conversations.service.d.ts +1 -1
  26. package/dist/conversations/conversations.service.js +8 -3
  27. package/dist/conversations/events.d.ts +25 -1
  28. package/dist/conversations/events.js +7 -2
  29. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  30. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  31. package/dist/conversations/permission-profiles.schemas.js +8 -0
  32. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  33. package/dist/conversations/permission-profiles.service.js +13 -1
  34. package/dist/db/kernel-schema.d.ts +21 -0
  35. package/dist/device-access/device-access.service.d.ts +4 -1
  36. package/dist/device-access/device-access.service.js +26 -7
  37. package/dist/device-access/viewer.d.ts +3 -1
  38. package/dist/device-access/viewer.js +18 -9
  39. package/dist/errors.d.ts +6 -0
  40. package/dist/errors.js +6 -0
  41. package/dist/extensions/admin-view.d.ts +1 -3
  42. package/dist/extensions/admin-view.js +5 -8
  43. package/dist/git/gateway.d.ts +8 -1
  44. package/dist/git/gateway.js +68 -11
  45. package/dist/git/git.module.d.ts +2 -3
  46. package/dist/git/git.module.js +4 -4
  47. package/dist/http/api.module.js +3 -3
  48. package/dist/identity/settings.d.ts +20 -5
  49. package/dist/identity/settings.js +52 -9
  50. package/dist/infra/config/kernel-config.service.js +4 -0
  51. package/dist/orgs/orgs.module.js +12 -1
  52. package/dist/orgs/orgs.schemas.js +3 -0
  53. package/dist/orgs/security-settings.service.d.ts +94 -0
  54. package/dist/orgs/security-settings.service.js +223 -0
  55. package/dist/orgs/settings.controller.d.ts +33 -0
  56. package/dist/orgs/settings.controller.js +41 -1
  57. package/dist/orgs/settings.service.d.ts +48 -63
  58. package/dist/orgs/settings.service.js +86 -103
  59. package/dist/platform/exclusions.js +1 -1
  60. package/dist/platform/operation.js +4 -0
  61. package/dist/platform/ops/admin.ops.js +18 -4
  62. package/dist/platform/ops/agents.ops.js +1 -1
  63. package/dist/platform/ops/connectors.ops.js +2 -2
  64. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  65. package/dist/platform/ops/extensions.ops.js +4 -131
  66. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  67. package/dist/platform/ops/org-settings.ops.js +76 -3
  68. package/dist/platform/ops/orgs.ops.js +2 -0
  69. package/dist/runtime/context/permission-profile.js +6 -0
  70. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  71. package/dist/runtime/subagents/dispatch.js +2 -1
  72. package/dist/runtime/subagents/messages.d.ts +3 -1
  73. package/dist/runtime/subagents/messages.js +9 -6
  74. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  75. package/dist/sandbox/device-sandbox-settings.js +64 -1
  76. package/dist/sandbox/device-sandbox.d.ts +9 -1
  77. package/dist/sandbox/device-sandbox.js +17 -2
  78. package/dist/sandbox/device-services.d.ts +26 -3
  79. package/dist/sandbox/device-services.js +95 -16
  80. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  81. package/dist/sandbox/loopback-grant-records.js +32 -5
  82. package/dist/sandbox/operation-authority.d.ts +3 -2
  83. package/dist/sandbox/operation-authority.js +21 -1
  84. package/dist/sandbox/operation-intents.js +5 -1
  85. package/dist/sandbox/permission-call-types.d.ts +2 -1
  86. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  87. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  88. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  89. package/dist/sandbox/permission-config-publication.js +27 -5
  90. package/dist/sandbox/permission-facts.d.ts +21 -2
  91. package/dist/sandbox/permission-facts.js +101 -9
  92. package/dist/sandbox/permission-transitions.d.ts +1 -1
  93. package/dist/sandbox/sandbox.service.d.ts +2 -2
  94. package/dist/sandbox/sandbox.service.js +7 -3
  95. package/dist/tools/admin-connectors.js +2 -2
  96. package/dist/tools/approvals.service.d.ts +7 -2
  97. package/dist/tools/approvals.service.js +39 -7
  98. package/dist/tools/builtin-names.d.ts +0 -6
  99. package/dist/tools/builtin-names.js +0 -11
  100. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  101. package/dist/tools/builtins/sandbox/index.js +3 -5
  102. package/dist/tools/connector-account-policies.js +7 -4
  103. package/dist/tools/connectors.controller.d.ts +0 -6
  104. package/dist/tools/connectors.schemas.d.ts +1 -8
  105. package/dist/tools/connectors.schemas.js +1 -4
  106. package/dist/tools/connectors.service.d.ts +3 -7
  107. package/dist/tools/connectors.service.js +29 -44
  108. package/dist/tools/drift.js +12 -4
  109. package/dist/tools/git-push-policy.d.ts +1 -4
  110. package/dist/tools/git-push-policy.js +4 -5
  111. package/dist/tools/org-tool-policies.d.ts +24 -0
  112. package/dist/tools/org-tool-policies.js +113 -0
  113. package/dist/tools/org-tool-switches.d.ts +5 -70
  114. package/dist/tools/org-tool-switches.js +13 -141
  115. package/dist/tools/pipeline.d.ts +11 -5
  116. package/dist/tools/pipeline.js +173 -38
  117. package/dist/tools/policy.d.ts +3 -7
  118. package/dist/tools/policy.js +29 -48
  119. package/dist/tools/registry.d.ts +5 -0
  120. package/dist/tools/registry.js +44 -13
  121. package/package.json +1 -1
  122. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -1,4 +1,6 @@
1
+ import { type DeviceProjectReach, type PermissionProfile } from "@capybara-hq/plugin-sdk";
1
2
  import { z } from "zod";
3
+ import { AllowedProfilesSchema } from "../conversations/permission-profiles.schemas.js";
2
4
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
5
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
6
  import type { KernelLogger } from "../log.js";
@@ -13,6 +15,29 @@ import type { DeviceNetworkMode, DeviceSandboxSettings } from "./device-sandbox.
13
15
  * admin console. An invalid stored value reads narrower with a warning (fail closed): `off`, and
14
16
  * the allowlist.
15
17
  */
18
+ export { AllowedProfilesSchema };
19
+ export declare const ProjectReachSchema: z.ZodEnum<{
20
+ machine: "machine";
21
+ paths: "paths";
22
+ workspace: "workspace";
23
+ }>;
24
+ export declare const DEVICES_ALLOWED_PROFILES_SETTING = "devicesAllowedProfiles";
25
+ export declare const DEVICES_PROJECT_REACH_SETTING = "devicesProjectReach";
26
+ export declare const DEFAULT_ALLOWED_PROFILES: ("approve-for-me" | "full-access" | "request-approval")[];
27
+ export declare const DEVICES_ALLOWED_PROFILES_PATCH: z.ZodObject<{
28
+ value: z.ZodNullable<z.ZodPipe<z.ZodArray<z.ZodEnum<{
29
+ "approve-for-me": "approve-for-me";
30
+ "full-access": "full-access";
31
+ "request-approval": "request-approval";
32
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>;
33
+ }, z.core.$strict>;
34
+ export declare const DEVICES_PROJECT_REACH_PATCH: z.ZodObject<{
35
+ ceiling: z.ZodNullable<z.ZodEnum<{
36
+ machine: "machine";
37
+ paths: "paths";
38
+ workspace: "workspace";
39
+ }>>;
40
+ }, z.core.$strict>;
16
41
  export type OutsideSandboxPermission = "allowed" | "off";
17
42
  /** The `deployment_settings` key of the super admin's outside-sandbox choice. */
18
43
  export declare const DEVICES_OUTSIDE_SANDBOX_SETTING = "devicesOutsideSandbox";
@@ -44,6 +69,8 @@ export type DevicesNetworkStored = z.infer<typeof DevicesNetworkStoredSchema>;
44
69
  export interface StoredDeviceSandbox {
45
70
  outsideSandbox: DevicesOutsideSandboxStored;
46
71
  network: DevicesNetworkStored;
72
+ allowedProfiles?: PermissionProfile[] | undefined;
73
+ projectReach?: DeviceProjectReach | undefined;
47
74
  }
48
75
  /**
49
76
  * A change of the stored outside-sandbox choice (`PUT /api/v1/admin/settings`
@@ -88,19 +115,35 @@ export interface DevicesNetworkView {
88
115
  ceiling: DeviceSandboxSource;
89
116
  };
90
117
  }
118
+ export interface AllowedProfilesView {
119
+ value: PermissionProfile[];
120
+ source: DeviceSandboxSource;
121
+ }
122
+ export interface ProjectReachView {
123
+ ceiling: DeviceProjectReach;
124
+ source: {
125
+ ceiling: DeviceSandboxSource;
126
+ };
127
+ }
91
128
  export interface DeviceSandboxSettingsView {
92
129
  outsideSandbox: DevicesOutsideSandboxView;
93
130
  network: DevicesNetworkView;
131
+ allowedProfiles: AllowedProfilesView;
132
+ projectReach: ProjectReachView;
94
133
  }
95
134
  /** The startup config's values and where each comes from (undefined: not set there). */
96
135
  export interface ConfiguredDeviceSandbox {
97
136
  outsideSandbox?: OutsideSandboxPermission | undefined;
98
137
  networkDefault?: DeviceNetworkMode | undefined;
99
138
  networkCeiling?: DeviceNetworkMode | undefined;
139
+ allowedProfiles?: PermissionProfile[] | undefined;
140
+ projectReach?: DeviceProjectReach | undefined;
100
141
  sources: {
101
142
  outsideSandbox?: ConfigSource | undefined;
102
143
  networkDefault?: ConfigSource | undefined;
103
144
  networkCeiling?: ConfigSource | undefined;
145
+ allowedProfiles?: ConfigSource | undefined;
146
+ projectReach?: ConfigSource | undefined;
104
147
  };
105
148
  }
106
149
  /**
@@ -138,6 +181,16 @@ export declare function readDeviceSandboxSettingsView(db: KernelSchemaDb, config
138
181
  /** The platform's effective device sandbox settings (the layer `effectiveDeviceSandbox` takes). */
139
182
  export declare function readDeviceSandboxSettings(db: KernelSchemaDb, config: Pick<KernelConfigService, "get" | "fieldSource">, log?: Pick<KernelLogger, "warn">): Promise<DeviceSandboxSettings>;
140
183
  export declare const OrgDeviceSandboxStoredSchema: z.ZodObject<{
184
+ allowedProfiles: z.ZodCatch<z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodEnum<{
185
+ "approve-for-me": "approve-for-me";
186
+ "full-access": "full-access";
187
+ "request-approval": "request-approval";
188
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>>;
189
+ projectReach: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
190
+ machine: "machine";
191
+ paths: "paths";
192
+ workspace: "workspace";
193
+ }>>>;
141
194
  outsideSandbox: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
142
195
  allowed: "allowed";
143
196
  off: "off";
@@ -173,4 +226,5 @@ export declare const OrgDeviceSandboxStoredSchema: z.ZodObject<{
173
226
  }, z.core.$strip>;
174
227
  /** Read the org's current choices. A missing choice follows the platform. */
175
228
  export declare function orgDeviceSandboxOf(raw: unknown): z.infer<typeof OrgDeviceSandboxStoredSchema>;
176
- export {};
229
+ export declare function effectiveAllowedProfiles(platform: readonly PermissionProfile[], org: readonly PermissionProfile[] | undefined): PermissionProfile[];
230
+ export declare function effectiveProjectReach(platform: DeviceProjectReach, org: DeviceProjectReach | undefined): DeviceProjectReach;
@@ -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.