@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
@@ -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`)
@@ -443,6 +443,7 @@ let SandboxOperationIntents = class SandboxOperationIntents {
443
443
  const fresh = await this.authority.resolveKernelRead(ctx, read, method, input.path, new AbortController().signal);
444
444
  const admitted = parseSandboxOperationScope(row.scope);
445
445
  if (permissionScopeHash(fresh.filesystem) !== permissionScopeHash(admitted.filesystem) ||
446
+ permissionScopeHash(fresh.projectReach) !== permissionScopeHash(admitted.projectReach) ||
446
447
  fresh.profileRevision !== admitted.profileRevision ||
447
448
  fresh.ceilingRevision !== admitted.ceilingRevision)
448
449
  denied("Authority changed before the kernel read was dispatched");
@@ -477,7 +478,8 @@ let SandboxOperationIntents = class SandboxOperationIntents {
477
478
  const fresh = await this.authority.resolveBrowse(ctx, new AbortController().signal, {
478
479
  readRoots: admitted.readRoots,
479
480
  });
480
- if (JSON.stringify(fresh.readRoots) !== JSON.stringify(admitted.readRoots))
481
+ if (JSON.stringify(fresh.readRoots) !== JSON.stringify(admitted.readRoots) ||
482
+ permissionScopeHash(fresh.projectReach) !== permissionScopeHash(admitted.projectReach))
481
483
  denied("Authority changed before the browse was dispatched");
482
484
  await this.db
483
485
  .updateTable("sandbox_operation_intents")
@@ -544,6 +546,8 @@ let SandboxOperationIntents = class SandboxOperationIntents {
544
546
  permissionScopeHash(parseSandboxOperationScope(r.scope).filesystem) ||
545
547
  permissionScopeHash(fresh.network) !==
546
548
  permissionScopeHash(parseSandboxOperationScope(r.scope).network) ||
549
+ permissionScopeHash(fresh.projectReach) !==
550
+ permissionScopeHash(parseSandboxOperationScope(r.scope).projectReach) ||
547
551
  fresh.ceilingRevision !== r.scope.ceilingRevision ||
548
552
  fresh.profileRevision !== parseSandboxOperationScope(r.scope).profileRevision)
549
553
  throw new PermissionAdmissionStale("Authority changed before admission; refresh this pending method only");
@@ -1,4 +1,4 @@
1
- import type { PermissionProfile } from "@capybara-hq/plugin-sdk";
1
+ import type { PermissionProfile, ProjectReachAuthority } from "@capybara-hq/plugin-sdk";
2
2
  import type { HostGrantCeiling } from "./device-sandbox.js";
3
3
  import type { EffectiveDevicePolicy } from "./modes.js";
4
4
  import type { PermissionAvailabilityCause } from "./permission-availability.js";
@@ -98,6 +98,7 @@ export type PermissionCandidateResult = {
98
98
  message: string;
99
99
  };
100
100
  export type PermissionReviewSnapshot = Readonly<Omit<PermissionCallBinding, "toolKey" | "specHash" | "callInputHash" | "resolvedInputHash"> & {
101
+ projectReach?: ProjectReachAuthority;
101
102
  baseWriteDirectories: readonly string[];
102
103
  baseHosts: readonly string[];
103
104
  workingRoot: string;
@@ -1,6 +1,7 @@
1
- import type { SandboxBrowseScope, SandboxOperationScope } from "@capybara-hq/plugin-sdk";
2
- import type { Selectable } from "kysely";
1
+ import { type DeviceProjectReach, type PermissionProfile, type SandboxBrowseScope, type SandboxOperationScope } from "@capybara-hq/plugin-sdk";
2
+ import { type Selectable } from "kysely";
3
3
  import type { KernelSchemaDb, SandboxOperationIntentsTable } from "../db/kernel-schema.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -15,12 +16,18 @@ export declare class PermissionCeilingWrites {
15
16
  private readonly locks;
16
17
  private readonly epochs;
17
18
  private readonly outbox;
18
- constructor(transitions: PermissionTransitions, db: KernelDb, txHost: TransactionHost, locks: PermissionAuthorityLock, epochs: PermissionAuthorityEpochStore, outbox: OutboxService);
19
+ private readonly config?;
20
+ constructor(transitions: PermissionTransitions, db: KernelDb, txHost: TransactionHost, locks: PermissionAuthorityLock, epochs: PermissionAuthorityEpochStore, outbox: OutboxService, config?: Pick<KernelConfigService, "get" | "fieldSource"> | undefined);
19
21
  lock(subject: AuthoritySubject, level: "platform" | "org" | "device" | "root"): Promise<void>;
20
22
  /** The platform writer excludes every descendant; only these environments changed Full reach. */
21
- invalidateDeviceConsentUnderPlatform(deviceIds: readonly string[]): Promise<void>;
22
- publishLocked(subject: AuthoritySubject, level: "platform" | "org" | "device" | "root", revoke?: boolean | ((scope: SandboxOperationScope | SandboxBrowseScope, row: Selectable<SandboxOperationIntentsTable>) => boolean), invalidateFullConsent?: boolean): Promise<void>;
23
+ invalidateDeviceConsentUnderPlatform(deviceIds: readonly string[], platformProfiles?: readonly PermissionProfile[]): Promise<void>;
24
+ publishLocked(subject: AuthoritySubject, level: "platform" | "org" | "device" | "root", revoke?: boolean | ((scope: SandboxOperationScope | SandboxBrowseScope, row: Selectable<SandboxOperationIntentsTable>) => boolean), invalidateFullConsent?: boolean, refreshStartedServices?: boolean, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
25
+ /** Full access consent only grows where the org inherits the widened platform reach. */
26
+ invalidateProjectReachWideningLocked(before: DeviceProjectReach, after: DeviceProjectReach, platformProfiles?: readonly PermissionProfile[]): Promise<void>;
27
+ /** Selected profiles removed by an org or platform ceiling reset before the writer commits. */
28
+ reconcileAllowedProfilesLocked(subject: AuthoritySubject, level: "platform" | "org", before: readonly PermissionProfile[], after: readonly PermissionProfile[]): Promise<void>;
23
29
  private resetRoot;
30
+ private fallbackProfile;
24
31
  }
25
32
  /**
26
33
  * The narrowings a ceiling write publishes (approval-only profiles design, "Ceiling writes"), each
@@ -54,3 +61,5 @@ export declare function devicesFollowingDefault(db: KernelSchemaDb, orgId?: stri
54
61
  * per-call ceiling still allows (`grantable`). Native methods and other networks reach no host.
55
62
  */
56
63
  export declare function hostsNarrowed(scope: SandboxOperationScope | SandboxBrowseScope, row: Pick<Selectable<SandboxOperationIntentsTable>, "method" | "granted_hosts">, orgHosts: readonly string[], grantable: (host: string) => boolean): boolean;
64
+ /** A scope admitted under a wider reach must drain before narrower work is dispatched. */
65
+ export declare function reachNarrowed(scope: SandboxOperationScope | SandboxBrowseScope, next: DeviceProjectReach): boolean;
@@ -7,11 +7,16 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Inject, Injectable } from "@nestjs/common";
10
+ import { narrowerProjectReach, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
11
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { asPlatform } from "../infra/database/org-scope.js";
12
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
13
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
14
18
  import { OutboxService } from "../infra/outbox/outbox.service.js";
19
+ import { effectiveAllowedProfiles, effectiveProjectReach, orgDeviceSandboxOf, readDeviceSandboxSettingsView, } from "./device-sandbox-settings.js";
15
20
  import { oweLoopbackRefreshes } from "./loopback-grant-records.js";
16
21
  import { coversHost } from "./modes.js";
17
22
  import { isExecutionMethod, isFullExecutionScope, usesOpenNetwork, } from "./operation-authority-types.js";
@@ -31,19 +36,21 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
31
36
  locks;
32
37
  epochs;
33
38
  outbox;
34
- constructor(transitions, db, txHost, locks, epochs, outbox) {
39
+ config;
40
+ constructor(transitions, db, txHost, locks, epochs, outbox, config) {
35
41
  this.transitions = transitions;
36
42
  this.db = db;
37
43
  this.txHost = txHost;
38
44
  this.locks = locks;
39
45
  this.epochs = epochs;
40
46
  this.outbox = outbox;
47
+ this.config = config;
41
48
  }
42
49
  async lock(subject, level) {
43
50
  await this.locks.acquire(subject, { kind: "write", level });
44
51
  }
45
52
  /** The platform writer excludes every descendant; only these environments changed Full reach. */
46
- async invalidateDeviceConsentUnderPlatform(deviceIds) {
53
+ async invalidateDeviceConsentUnderPlatform(deviceIds, platformProfiles) {
47
54
  this.locks.assertHeld("platform", "platform", true);
48
55
  for (const id of deviceIds)
49
56
  await this.db
@@ -67,10 +74,10 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
67
74
  .forUpdate()
68
75
  .execute();
69
76
  for (const root of roots)
70
- await this.resetRoot(root, {}, "platform");
77
+ await this.resetRoot(root, {}, "platform", undefined, platformProfiles);
71
78
  }
72
79
  }
73
- async publishLocked(subject, level, revoke = true, invalidateFullConsent = false) {
80
+ async publishLocked(subject, level, revoke = true, invalidateFullConsent = false, refreshStartedServices = false, platformProfiles) {
74
81
  const id = level === "platform"
75
82
  ? "platform"
76
83
  : level === "org"
@@ -102,7 +109,7 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
102
109
  if (level === "root")
103
110
  roots = roots.where("id", "=", required(subject.rootConversationId));
104
111
  for (const root of await roots.orderBy("org_id").orderBy("id").forUpdate().execute())
105
- await this.resetRoot(root, subject, level);
112
+ await this.resetRoot(root, subject, level, undefined, platformProfiles);
106
113
  }
107
114
  // every revoking writer may have narrowed the outside-sandbox ceiling: the refresh of each
108
115
  // live loopback grant set under the subject decides, and revokes the grants it now refuses
@@ -114,7 +121,7 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
114
121
  ...(subject.rootConversationId !== undefined && {
115
122
  rootConversationId: subject.rootConversationId,
116
123
  }),
117
- }, `c${level}-${id}-${epoch}`);
124
+ }, `c${level}-${id}-${epoch}`, refreshStartedServices);
118
125
  if (!revoke)
119
126
  return;
120
127
  // Acknowledged background starts stay revocable by every actual revoking writer (deletion is
@@ -163,12 +170,82 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
163
170
  });
164
171
  }
165
172
  }
166
- async resetRoot(root, subject, level) {
173
+ /** Full access consent only grows where the org inherits the widened platform reach. */
174
+ async invalidateProjectReachWideningLocked(before, after, platformProfiles) {
175
+ if (narrowerProjectReach(before, after) === after)
176
+ return;
177
+ this.locks.assertHeld("platform", "platform", true);
178
+ // org-filter: deployment-wide: the platform reach ceiling applies to devices of every org.
179
+ await asPlatform("invalidate consent for wider project reach", async () => {
180
+ const rows = await this.db
181
+ .selectFrom("devices as d")
182
+ .innerJoin("orgs as o", "o.id", "d.org_id")
183
+ .select(["d.id", "o.settings"])
184
+ .where("o.deleted_at", "is", null)
185
+ .where("d.deleted_at", "is", null)
186
+ .execute();
187
+ await this.invalidateDeviceConsentUnderPlatform(rows
188
+ .filter(({ settings }) => {
189
+ const reach = orgDeviceSandboxOf(settings).projectReach;
190
+ return effectiveProjectReach(before, reach) !== effectiveProjectReach(after, reach);
191
+ })
192
+ .map(({ id }) => id), platformProfiles);
193
+ });
194
+ }
195
+ /** Selected profiles removed by an org or platform ceiling reset before the writer commits. */
196
+ async reconcileAllowedProfilesLocked(subject, level, before, after) {
197
+ this.locks.assertHeld(level, level === "platform" ? "platform" : required(subject.orgId), true);
198
+ const removed = before.filter((profile) => !after.includes(profile));
199
+ if (removed.length === 0)
200
+ return;
201
+ const roots = this.db
202
+ .selectFrom("conversations")
203
+ .selectAll()
204
+ .where("parent_conversation_id", "is", null);
205
+ const resetRoots = async (query) => {
206
+ for (const root of await query.orderBy("org_id").orderBy("id").forUpdate().execute())
207
+ await this.resetRoot(root, subject, level, "request-approval");
208
+ };
209
+ if (level === "org") {
210
+ await resetRoots(roots
211
+ .where("org_id", "=", required(subject.orgId))
212
+ .where("permission_profile", "in", removed));
213
+ return;
214
+ }
215
+ // org-filter: deployment-wide: only the platform writer can remove profiles across orgs.
216
+ await asPlatform("reconcile permission profiles across orgs", async () => {
217
+ const orgs = await this.db
218
+ .selectFrom("orgs")
219
+ .select(["id", "settings"])
220
+ .where("deleted_at", "is", null)
221
+ .execute();
222
+ const orgProfiles = orgs.map(({ id, settings }) => ({
223
+ id,
224
+ profiles: orgDeviceSandboxOf(settings).allowedProfiles,
225
+ }));
226
+ const affected = removed
227
+ .map((profile) => ({
228
+ profile,
229
+ orgIds: orgProfiles
230
+ .filter(({ profiles }) => profiles === undefined || profiles.includes(profile))
231
+ .map(({ id }) => id),
232
+ }))
233
+ .filter(({ orgIds }) => orgIds.length > 0);
234
+ if (affected.length === 0)
235
+ return;
236
+ await resetRoots(roots.where((eb) => eb.or(affected.map(({ profile, orgIds }) => eb.and([
237
+ eb("permission_profile", "=", profile),
238
+ eb("org_id", "=", sql `ANY(${orgIds}::text[])`),
239
+ ])))));
240
+ });
241
+ }
242
+ async resetRoot(root, subject, level, forcedProfile, platformProfiles) {
243
+ const profile = forcedProfile ?? (await this.fallbackProfile(root.org_id, platformProfiles));
167
244
  const revision = root.permission_revision + 1;
168
245
  await this.db
169
246
  .updateTable("conversations")
170
247
  .set({
171
- permission_profile: "approve-for-me",
248
+ permission_profile: profile,
172
249
  permission_consent: null,
173
250
  permission_revision: revision,
174
251
  })
@@ -179,14 +256,33 @@ let PermissionCeilingWrites = class PermissionCeilingWrites {
179
256
  orgId: root.org_id,
180
257
  rootConversationId: root.id,
181
258
  deviceId: root.device_id,
182
- oldProfile: "full-access",
183
- newProfile: "approve-for-me",
259
+ oldProfile: root.permission_profile,
260
+ newProfile: profile,
184
261
  revision,
185
262
  scopeRevision: null,
186
263
  actorAccountId: null,
187
- reason: "authority-changed",
264
+ reason: forcedProfile !== undefined
265
+ ? level === "platform"
266
+ ? "platform-profile-ceiling"
267
+ : "org-profile-ceiling"
268
+ : "authority-changed",
188
269
  }, { subject, level });
189
270
  }
271
+ async fallbackProfile(orgId, platformProfiles) {
272
+ if (platformProfiles === undefined) {
273
+ if (this.config === undefined)
274
+ throw new Error("Profile changes require the kernel config");
275
+ platformProfiles = (await readDeviceSandboxSettingsView(this.db.db, this.config))
276
+ .allowedProfiles.value;
277
+ }
278
+ const org = await this.db
279
+ .selectFrom("orgs")
280
+ .select("settings")
281
+ .where("id", "=", orgId)
282
+ .executeTakeFirst();
283
+ const profiles = effectiveAllowedProfiles(platformProfiles, orgDeviceSandboxOf(org?.settings).allowedProfiles);
284
+ return profiles.includes("approve-for-me") ? "approve-for-me" : "request-approval";
285
+ }
190
286
  };
191
287
  __decorate([
192
288
  Transactional({ propagation: "mandatory" })
@@ -197,6 +293,12 @@ __decorate([
197
293
  __decorate([
198
294
  Transactional({ propagation: "mandatory" })
199
295
  ], PermissionCeilingWrites.prototype, "publishLocked", null);
296
+ __decorate([
297
+ Transactional({ propagation: "mandatory" })
298
+ ], PermissionCeilingWrites.prototype, "invalidateProjectReachWideningLocked", null);
299
+ __decorate([
300
+ Transactional({ propagation: "mandatory" })
301
+ ], PermissionCeilingWrites.prototype, "reconcileAllowedProfilesLocked", null);
200
302
  PermissionCeilingWrites = __decorate([
201
303
  Injectable(),
202
304
  __param(0, Inject(PermissionTransitions)),
@@ -204,7 +306,9 @@ PermissionCeilingWrites = __decorate([
204
306
  __param(2, Inject(TransactionHost)),
205
307
  __param(3, Inject(PermissionAuthorityLock)),
206
308
  __param(4, Inject(PermissionAuthorityEpochStore)),
207
- __param(5, Inject(OutboxService))
309
+ __param(5, Inject(OutboxService)),
310
+ __param(6, Optional()),
311
+ __param(6, Inject(KernelConfigService))
208
312
  ], PermissionCeilingWrites);
209
313
  export { PermissionCeilingWrites };
210
314
  /** Work on the open public network: what a network ceiling narrowed to `allowlist` takes away. */
@@ -243,3 +347,8 @@ export function hostsNarrowed(scope, row, orgHosts, grantable) {
243
347
  return scope.network.hosts.some((host) => !orgHosts.some((pattern) => coversHost(pattern.toLowerCase(), host.toLowerCase())) &&
244
348
  !(row.granted_hosts.includes(host) && grantable(host)));
245
349
  }
350
+ /** A scope admitted under a wider reach must drain before narrower work is dispatched. */
351
+ export function reachNarrowed(scope, next) {
352
+ const previous = scope.projectReach?.ceiling ?? "machine";
353
+ return previous !== next && narrowerProjectReach(previous, next) === next;
354
+ }
@@ -20,6 +20,16 @@ declare const ProjectionSchema: z.ZodObject<{
20
20
  off: "off";
21
21
  }>;
22
22
  }, z.core.$strict>], "kind">;
23
+ allowedProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodEnum<{
24
+ "approve-for-me": "approve-for-me";
25
+ "full-access": "full-access";
26
+ "request-approval": "request-approval";
27
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>;
28
+ projectReach: z.ZodOptional<z.ZodEnum<{
29
+ machine: "machine";
30
+ paths: "paths";
31
+ workspace: "workspace";
32
+ }>>;
23
33
  network: z.ZodObject<{
24
34
  default: z.ZodDiscriminatedUnion<[z.ZodObject<{
25
35
  kind: z.ZodLiteral<"deployment-setting">;
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash } from "node:crypto";
11
- import { SandboxScopeDeniedError, validateAllowHost } from "@capybara-hq/plugin-sdk";
11
+ import { narrowerProjectReach, SandboxScopeDeniedError, validateAllowHost, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
13
13
  import { z } from "zod";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -18,9 +18,9 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
18
18
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
20
  import { hostGrantable, hostGrantCeiling } from "./device-sandbox.js";
21
- import { orgDeviceSandboxOf, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "./device-sandbox-settings.js";
21
+ import { AllowedProfilesSchema, orgDeviceSandboxOf, ProjectReachSchema, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "./device-sandbox-settings.js";
22
22
  import { coversHost, orgEffectiveHosts } from "./modes.js";
23
- import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, } from "./permission-ceiling-writes.js";
23
+ import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "./permission-ceiling-writes.js";
24
24
  /** Whether a field comes from the startup config (with its value) or the deployment setting. */
25
25
  const SettingSource = (value) => z.discriminatedUnion("kind", [
26
26
  z.object({ kind: z.literal("deployment-setting") }).strict(),
@@ -42,6 +42,8 @@ const ProjectionSchema = z
42
42
  .object({
43
43
  version: z.literal(3),
44
44
  outsideSandbox: PermissionSource,
45
+ allowedProfiles: AllowedProfilesSchema.optional(),
46
+ projectReach: ProjectReachSchema.optional(),
45
47
  network: z.object({ default: NetworkSource, ceiling: NetworkSource }).strict(),
46
48
  egress: z.enum(["none", "allowlist"]),
47
49
  orgHosts: z.enum(["extend", "within"]),
@@ -61,6 +63,8 @@ export function parsePermissionConfigProjection(input) {
61
63
  return bounded({
62
64
  version: 3,
63
65
  outsideSandbox: parsed.outsideSandbox,
66
+ ...(parsed.allowedProfiles !== undefined && { allowedProfiles: parsed.allowedProfiles }),
67
+ ...(parsed.projectReach !== undefined && { projectReach: parsed.projectReach }),
64
68
  network: { default: parsed.network.default, ceiling: parsed.network.ceiling },
65
69
  egress: parsed.egress,
66
70
  orgHosts: parsed.orgHosts,
@@ -75,6 +79,12 @@ export function permissionConfigProjection(config) {
75
79
  return parsePermissionConfigProjection({
76
80
  version: 3,
77
81
  outsideSandbox: source(config.devices.outsideSandbox),
82
+ ...(config.devices.allowedProfiles !== undefined && {
83
+ allowedProfiles: config.devices.allowedProfiles,
84
+ }),
85
+ ...(config.devices.projectReach?.ceiling !== undefined && {
86
+ projectReach: config.devices.projectReach.ceiling,
87
+ }),
78
88
  network: {
79
89
  default: source(config.devices.network.default),
80
90
  ceiling: source(config.devices.network.ceiling),
@@ -91,10 +101,14 @@ const configuredView = (projection) => {
91
101
  const fileSource = (s) => (s.kind === "configured" ? "file" : undefined);
92
102
  return {
93
103
  outsideSandbox: configuredOf(projection.outsideSandbox),
104
+ allowedProfiles: projection.allowedProfiles,
105
+ projectReach: projection.projectReach,
94
106
  networkDefault: configuredOf(projection.network.default),
95
107
  networkCeiling: configuredOf(projection.network.ceiling),
96
108
  sources: {
97
109
  outsideSandbox: fileSource(projection.outsideSandbox),
110
+ allowedProfiles: projection.allowedProfiles === undefined ? undefined : "file",
111
+ projectReach: projection.projectReach === undefined ? undefined : "file",
98
112
  networkDefault: fileSource(projection.network.default),
99
113
  networkCeiling: fileSource(projection.network.ceiling),
100
114
  },
@@ -251,6 +265,10 @@ let PermissionConfigPublication = class PermissionConfigPublication {
251
265
  const storedChoice = await readStoredDeviceSandbox(this.db.db, this.log);
252
266
  const effective = (projection) => resolveDeviceSandboxSettings(configuredView(projection), storedChoice);
253
267
  const beforeView = effective(before), nextView = effective(next);
268
+ await this.ceilings.reconcileAllowedProfilesLocked({}, "platform", beforeView.allowedProfiles.value, nextView.allowedProfiles.value);
269
+ const beforeReach = beforeView.projectReach.ceiling;
270
+ const nextReach = nextView.projectReach.ceiling;
271
+ const reachTightened = beforeReach !== nextReach && narrowerProjectReach(beforeReach, nextReach) === nextReach;
254
272
  const beforeMode = beforeView.outsideSandbox.permission, nextMode = nextView.outsideSandbox.permission;
255
273
  // a network opened anywhere is a widening: consent given under the narrower network resets
256
274
  const networkWidened = (beforeView.network.ceiling === "allowlist" && nextView.network.ceiling === "open") ||
@@ -260,7 +278,7 @@ let PermissionConfigPublication = class PermissionConfigPublication {
260
278
  // the kill switch lifted is a widening for every device (closing it only narrows)
261
279
  // org-filter: platform publication: the kill switch is deployment-wide, every org's devices
262
280
  if (before.egress === "none" && next.egress !== "none")
263
- await this.ceilings.invalidateDeviceConsentUnderPlatform((await this.db.selectFrom("devices").select("id").execute()).map((device) => device.id));
281
+ await this.ceilings.invalidateDeviceConsentUnderPlatform((await this.db.selectFrom("devices").select("id").execute()).map((device) => device.id), nextView.allowedProfiles.value);
264
282
  // a network ceiling narrowed to the allowlist, or closed by the kill switch, takes running
265
283
  // open-network work
266
284
  const networkNarrowed = (beforeView.network.ceiling === "open" && nextView.network.ceiling === "allowlist") ||
@@ -285,6 +303,8 @@ let PermissionConfigPublication = class PermissionConfigPublication {
285
303
  return hostGrantable(hostGrantCeiling({ boundary: "operation", networkMode: "allowlist", networkCeiling: ceiling }, next, org === undefined ? {} : { deviceNetwork: org }), host);
286
304
  };
287
305
  await this.ceilings.publishLocked({}, "platform", (scope, row) => {
306
+ if (reachTightened && reachNarrowed(scope, nextReach))
307
+ return true;
288
308
  if (needsOpenNetwork(scope) &&
289
309
  (networkNarrowed || following?.has(row.device_id) === true))
290
310
  return true;
@@ -294,7 +314,9 @@ let PermissionConfigPublication = class PermissionConfigPublication {
294
314
  return hostsNarrowed(scope, row, orgEffectiveHosts(next, settings.get(row.org_id)), (host) => next.egress !== "none" && grantable(row.org_id, host));
295
315
  },
296
316
  // only a widening resets Full consent: a narrowing keeps what the consent covered
297
- (beforeMode === "off" && nextMode === "allowed") || networkWidened || hostsWidened);
317
+ (beforeMode === "off" && nextMode === "allowed") || networkWidened || hostsWidened, reachTightened, nextView.allowedProfiles.value);
318
+ if (beforeReach !== nextReach && !reachTightened)
319
+ await this.ceilings.invalidateProjectReachWideningLocked(beforeReach, nextReach, nextView.allowedProfiles.value);
298
320
  return "activated";
299
321
  });
300
322
  }
@@ -1,4 +1,4 @@
1
- import { type PermissionProfile } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceProjectReach, type PermissionProfile, type ProjectReachAuthority, type SandboxHandle } from "@capybara-hq/plugin-sdk";
2
2
  import type { PermissionRoot } from "../conversations/permission-profile-store.js";
3
3
  import { DeviceAccess } from "../devices/access.js";
4
4
  import { type DeviceProjectScope } from "../devices/project-rules.js";
@@ -10,7 +10,9 @@ import { type DeviceNetwork, type EffectiveDevicePolicy } from "./modes.js";
10
10
  import { type PermissionAvailability } from "./permission-availability.js";
11
11
  import type { AppliedEnvironment, AppliedOuterNetwork } from "./permission-context-types.js";
12
12
  import { DeviceProviders } from "./providers.js";
13
- type Scope = DeviceProjectScope;
13
+ type Scope = DeviceProjectScope & {
14
+ projectReach?: DeviceProjectReach;
15
+ };
14
16
  /**
15
17
  * What decides the working root of a call (project root spec §4.3), read the same way for a
16
18
  * sandbox tool and for the command review, so both decide the same root.
@@ -102,6 +104,7 @@ export declare class PermissionFacts {
102
104
  /** Where its provider applies new limits (`limitsApplyAt`; absent: at its instance). */
103
105
  limitsApplyAt: "fileSystem" | "instance" | undefined;
104
106
  reach: {
107
+ projectReach?: DeviceProjectReach;
105
108
  outsideSandbox: boolean;
106
109
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
107
110
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;
@@ -115,6 +118,12 @@ export declare class PermissionFacts {
115
118
  * narrow it further.
116
119
  */
117
120
  orgHostGrantCeiling(orgId: string): Promise<HostGrantCeiling>;
121
+ /**
122
+ * The provider's own generation binds a restricted ceiling on dial-in work. The provider
123
+ * negotiates the wire feature against its live owner report and refuses before forwarding if
124
+ * the connected program cannot enforce it. Instance-confined providers need no wire grant.
125
+ */
126
+ projectReachAuthority(orgId: string, deviceId: string, ceiling: DeviceProjectReach | undefined, held?: SandboxHandle): Promise<ProjectReachAuthority | undefined>;
118
127
  /** Stored binding only; projectScope supplies the live owner and deletion checks. */
119
128
  readProject(orgId: string, deviceId: string, name: string): Promise<{
120
129
  name: string;
@@ -181,6 +190,7 @@ export declare class PermissionFacts {
181
190
  scopeRevision: string;
182
191
  consentIdentity: string;
183
192
  consentReach: {
193
+ projectReach?: DeviceProjectReach;
184
194
  outsideSandbox: boolean;
185
195
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
186
196
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;
@@ -203,6 +213,7 @@ export declare class PermissionFacts {
203
213
  scopeRevision: string;
204
214
  consentIdentity: string;
205
215
  consentReach: {
216
+ projectReach?: DeviceProjectReach;
206
217
  outsideSandbox: boolean;
207
218
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
208
219
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;
@@ -210,10 +221,13 @@ export declare class PermissionFacts {
210
221
  };
211
222
  sandbox: DeviceSandbox;
212
223
  outsideSandboxCeiling: boolean;
224
+ allowedProfiles: PermissionProfile[];
213
225
  availability: PermissionAvailability;
214
226
  }>;
227
+ allowedProfiles(orgId: string): Promise<PermissionProfile[]>;
215
228
  view(orgId: string, accountId: string, row: PermissionRoot): Promise<{
216
229
  profile: PermissionProfile;
230
+ allowedProfiles: PermissionProfile[];
217
231
  revision: number;
218
232
  rootConversationId: string;
219
233
  deviceId: string | null;
@@ -226,6 +240,7 @@ export declare class PermissionFacts {
226
240
  outsideSandboxCeiling: boolean;
227
241
  /** What an Auto consent confirmed now records (the confirmation names exactly this). */
228
242
  consentReach: {
243
+ projectReach?: DeviceProjectReach;
229
244
  outsideSandbox: boolean;
230
245
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
231
246
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;
@@ -242,6 +257,7 @@ export declare class PermissionFacts {
242
257
  peopleView(orgId: string, accountId: string, row: PermissionRoot): Promise<{
243
258
  availability: PermissionAvailability;
244
259
  profile: PermissionProfile;
260
+ allowedProfiles: PermissionProfile[];
245
261
  revision: number;
246
262
  rootConversationId: string;
247
263
  deviceId: string | null;
@@ -253,6 +269,7 @@ export declare class PermissionFacts {
253
269
  outsideSandboxCeiling: boolean;
254
270
  /** What an Auto consent confirmed now records (the confirmation names exactly this). */
255
271
  consentReach: {
272
+ projectReach?: DeviceProjectReach;
256
273
  outsideSandbox: boolean;
257
274
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
258
275
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;
@@ -272,6 +289,7 @@ export declare class PermissionFacts {
272
289
  previewed: boolean;
273
290
  view: {
274
291
  profile: PermissionProfile;
292
+ allowedProfiles: PermissionProfile[];
275
293
  revision: number;
276
294
  rootConversationId: string;
277
295
  deviceId: string | null;
@@ -284,6 +302,7 @@ export declare class PermissionFacts {
284
302
  outsideSandboxCeiling: boolean;
285
303
  /** What an Auto consent confirmed now records (the confirmation names exactly this). */
286
304
  consentReach: {
305
+ projectReach?: DeviceProjectReach;
287
306
  outsideSandbox: boolean;
288
307
  networkCeiling: "none" | import("./device-sandbox.js").DeviceNetworkMode;
289
308
  networkMode: "none" | import("./device-sandbox.js").DeviceNetworkMode;