@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
@@ -7,7 +7,7 @@ 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 { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
10
+ import { EXTENSION_NAME_RE, narrowerProjectReach } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { applyPlatformAttributionPatch, PLATFORM_ATTRIBUTION_FIELDS, PLATFORM_ATTRIBUTION_PATCH, PLATFORM_ATTRIBUTION_SETTING, readStoredPlatformAttribution, resolvePlatformAttribution, } from "../attribution/platform-attribution.js";
@@ -19,8 +19,8 @@ import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
- import { applyDevicesNetworkPatch, applyDevicesOutsideSandboxPatch, configuredDeviceSandbox, DEVICES_NETWORK_PATCH, DEVICES_NETWORK_SETTING, DEVICES_OUTSIDE_SANDBOX_PATCH, DEVICES_OUTSIDE_SANDBOX_SETTING, orgDeviceSandboxOf, readDeviceSandboxSettingsView, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "../sandbox/device-sandbox-settings.js";
23
- import { devicesFollowingDefault, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
22
+ import { applyDevicesNetworkPatch, applyDevicesOutsideSandboxPatch, configuredDeviceSandbox, DEVICES_ALLOWED_PROFILES_PATCH, DEVICES_ALLOWED_PROFILES_SETTING, DEVICES_NETWORK_PATCH, DEVICES_NETWORK_SETTING, DEVICES_OUTSIDE_SANDBOX_PATCH, DEVICES_OUTSIDE_SANDBOX_SETTING, DEVICES_PROJECT_REACH_PATCH, DEVICES_PROJECT_REACH_SETTING, orgDeviceSandboxOf, readDeviceSandboxSettingsView, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "../sandbox/device-sandbox-settings.js";
23
+ import { devicesFollowingDefault, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
24
24
  import { EXTERNAL_SHARING_SETTING, ExternalSharingValue, HTML_CDN_ALLOWLIST_DEFAULT, HtmlCdnAllowlistSchema, readExternalSharing, readHtmlCdnAllowlist, readShareMaxExpiry, SHARE_MAX_EXPIRY_DEFAULT, SHARE_MAX_EXPIRY_SETTING, ShareMaxExpiryDays, } from "../shares/settings.js";
25
25
  import { assertPlatformDefaultEligible, lockThemeShared } from "../themes/theme-state.js";
26
26
  import { mergeArrangement, UiArrangementPatchSchema, UiArrangementSchema, } from "../ui/arrangement.js";
@@ -333,6 +333,8 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
333
333
  * startup config is read-only (409 `deployment.setting_readonly`).
334
334
  */
335
335
  devicesNetwork: DEVICES_NETWORK_PATCH.optional(),
336
+ devicesAllowedProfiles: DEVICES_ALLOWED_PROFILES_PATCH.optional(),
337
+ devicesProjectReach: DEVICES_PROJECT_REACH_PATCH.optional(),
336
338
  /**
337
339
  * The platform's default device provider (the `device-provider@1` extension that makes a
338
340
  * person's default device): `provider` replaced, null clears it (back to none). A value set in
@@ -575,6 +577,8 @@ let SettingsService = class SettingsService {
575
577
  ...settings,
576
578
  devicesOutsideSandbox: deviceSandbox.outsideSandbox,
577
579
  devicesNetwork: deviceSandbox.network,
580
+ devicesAllowedProfiles: deviceSandbox.allowedProfiles,
581
+ devicesProjectReach: deviceSandbox.projectReach,
578
582
  devicesDefaultProvider,
579
583
  attribution: this.attributionView(attribution),
580
584
  externalSharing,
@@ -615,6 +619,16 @@ let SettingsService = class SettingsService {
615
619
  async checkDeviceSandbox(patch, opts = {}) {
616
620
  const configured = configuredDeviceSandbox(this.config);
617
621
  const readonly = [
622
+ [
623
+ "devicesAllowedProfiles.value",
624
+ patch.devicesAllowedProfiles !== undefined,
625
+ configured.sources.allowedProfiles,
626
+ ],
627
+ [
628
+ "devicesProjectReach.ceiling",
629
+ patch.devicesProjectReach !== undefined,
630
+ configured.sources.projectReach,
631
+ ],
618
632
  [
619
633
  "devicesOutsideSandbox.permission",
620
634
  patch.devicesOutsideSandbox !== undefined,
@@ -637,6 +651,12 @@ let SettingsService = class SettingsService {
637
651
  }
638
652
  const stored = await readStoredDeviceSandbox(this.db.db, this.log);
639
653
  const next = {
654
+ allowedProfiles: patch.devicesAllowedProfiles === undefined
655
+ ? stored.allowedProfiles
656
+ : (patch.devicesAllowedProfiles.value ?? undefined),
657
+ projectReach: patch.devicesProjectReach === undefined
658
+ ? stored.projectReach
659
+ : (patch.devicesProjectReach.ceiling ?? undefined),
640
660
  outsideSandbox: patch.devicesOutsideSandbox === undefined
641
661
  ? stored.outsideSandbox
642
662
  : applyDevicesOutsideSandboxPatch(stored.outsideSandbox, patch.devicesOutsideSandbox),
@@ -651,6 +671,10 @@ let SettingsService = class SettingsService {
651
671
  if (patch.devicesNetwork?.default === "open" && next.network.ceiling === "allowlist")
652
672
  throw networkNotAllowed("The network default open is above the ceiling allowlist; set the default to allowlist too, or open the ceiling", "default");
653
673
  if (opts.onlyNarrows) {
674
+ if (after.allowedProfiles.value.some((profile) => !before.allowedProfiles.value.includes(profile)) ||
675
+ narrowerProjectReach(before.projectReach.ceiling, after.projectReach.ceiling) !==
676
+ after.projectReach.ceiling)
677
+ throw new ApiError("deployment.security_widen_not_allowed", "A super admin can widen device security settings in the web admin settings at /admin/settings.");
654
678
  if (patch.devicesOutsideSandbox !== undefined &&
655
679
  before.outsideSandbox.permission === "off" &&
656
680
  after.outsideSandbox.permission === "allowed")
@@ -819,7 +843,10 @@ let SettingsService = class SettingsService {
819
843
  }
820
844
  async lockFor(patch, actorAccountId) {
821
845
  await this.adminLock.lockAndAuthorize(actorAccountId);
822
- if (patch.devicesOutsideSandbox !== undefined || patch.devicesNetwork !== undefined)
846
+ if (patch.devicesOutsideSandbox !== undefined ||
847
+ patch.devicesNetwork !== undefined ||
848
+ patch.devicesAllowedProfiles !== undefined ||
849
+ patch.devicesProjectReach !== undefined)
823
850
  await this.ceilings.lock({}, "platform");
824
851
  }
825
852
  async write(patch, actorAccountId, actorTokenId, auditDetail, opts) {
@@ -907,9 +934,18 @@ let SettingsService = class SettingsService {
907
934
  // the stored shapes keep every field optional, so clearing one (null) writes it out
908
935
  let deviceSandboxChange;
909
936
  const writes = Object.entries(next);
910
- if (patch.devicesOutsideSandbox !== undefined || patch.devicesNetwork !== undefined) {
937
+ if (patch.devicesOutsideSandbox !== undefined ||
938
+ patch.devicesNetwork !== undefined ||
939
+ patch.devicesAllowedProfiles !== undefined ||
940
+ patch.devicesProjectReach !== undefined) {
911
941
  const r = await this.checkDeviceSandbox(patch, opts);
912
942
  deviceSandboxChange = { before: r.before, after: r.after };
943
+ if (patch.devicesAllowedProfiles !== undefined) {
944
+ writes.push([DEVICES_ALLOWED_PROFILES_SETTING, { value: r.next.allowedProfiles }]);
945
+ await this.ceilings.reconcileAllowedProfilesLocked({}, "platform", r.before.allowedProfiles.value, r.after.allowedProfiles.value);
946
+ }
947
+ if (patch.devicesProjectReach !== undefined)
948
+ writes.push([DEVICES_PROJECT_REACH_SETTING, { ceiling: r.next.projectReach }]);
913
949
  if (patch.devicesOutsideSandbox !== undefined)
914
950
  writes.push([DEVICES_OUTSIDE_SANDBOX_SETTING, r.next.outsideSandbox]);
915
951
  if (patch.devicesNetwork !== undefined)
@@ -921,7 +957,11 @@ let SettingsService = class SettingsService {
921
957
  (a.default === "allowlist" && b.default === "open");
922
958
  const networkChanged = r.before.network.default !== r.after.network.default ||
923
959
  r.before.network.ceiling !== r.after.network.ceiling;
924
- if (outsideChanged || networkChanged) {
960
+ const reachChanged = r.before.projectReach.ceiling !== r.after.projectReach.ceiling;
961
+ const reachTightened = reachChanged &&
962
+ narrowerProjectReach(r.before.projectReach.ceiling, r.after.projectReach.ceiling) ===
963
+ r.after.projectReach.ceiling;
964
+ if (outsideChanged || networkChanged || reachChanged) {
925
965
  // a network ceiling narrowed to the allowlist takes running open-network work
926
966
  const networkNarrowed = r.before.network.ceiling === "open" && r.after.network.ceiling === "allowlist";
927
967
  // a default narrowed to the allowlist takes it from the devices that follow it
@@ -931,16 +971,19 @@ let SettingsService = class SettingsService {
931
971
  r.after.network.default === "allowlist"
932
972
  ? await this.devicesFollowingPlatformDefault()
933
973
  : null;
934
- const narrows = outsideOff || networkNarrowed || following !== null;
974
+ const narrows = outsideOff || networkNarrowed || following !== null || reachTightened;
935
975
  await this.ceilings.publishLocked({}, "platform", !narrows
936
976
  ? false
937
977
  : (scope, row) => (needsOpenNetwork(scope) &&
938
978
  (networkNarrowed || following?.has(row.device_id) === true)) ||
939
- (outsideOff && needsFullCeiling(scope)),
979
+ (outsideOff && needsFullCeiling(scope)) ||
980
+ (reachTightened && reachNarrowed(scope, r.after.projectReach.ceiling)),
940
981
  // only a widening resets Full consent: a narrowing keeps what it covered
941
982
  (r.before.outsideSandbox.permission === "off" &&
942
983
  r.after.outsideSandbox.permission === "allowed") ||
943
- widened(r.before.network, r.after.network));
984
+ widened(r.before.network, r.after.network), reachTightened, r.after.allowedProfiles.value);
985
+ if (reachChanged && !reachTightened)
986
+ await this.ceilings.invalidateProjectReachWideningLocked(r.before.projectReach.ceiling, r.after.projectReach.ceiling, r.after.allowedProfiles.value);
944
987
  }
945
988
  }
946
989
  // the platform's attribution defaults: a field set in the startup config is read-only
@@ -54,6 +54,8 @@ const HOT_APPLIERS = {
54
54
  // The device sandbox settings reader reads these at every device use and settings read; a
55
55
  // change is published first (`PERMISSION_CONFIG_PATHS`).
56
56
  "devices.outsideSandbox": () => { },
57
+ "devices.allowedProfiles": () => { },
58
+ "devices.projectReach.ceiling": () => { },
57
59
  "devices.network.default": () => { },
58
60
  "devices.network.ceiling": () => { },
59
61
  // The default device provider is read live at every default device creation and settings read.
@@ -103,6 +105,8 @@ const HOT_APPLIERS = {
103
105
  */
104
106
  const PERMISSION_CONFIG_PATHS = [
105
107
  "devices.outsideSandbox",
108
+ "devices.allowedProfiles",
109
+ "devices.projectReach.ceiling",
106
110
  "devices.network.default",
107
111
  "devices.network.ceiling",
108
112
  ];
@@ -12,6 +12,7 @@ import { ExtensionsModule } from "../extensions/extensions.module.js";
12
12
  import { LifecycleHooksModule } from "../extensions/lifecycle-hooks.js";
13
13
  import { IdentityModule } from "../identity/identity.module.js";
14
14
  import { QueueModule } from "../infra/queue/queue.module.js";
15
+ import { PlatformModule } from "../platform/platform.module.js";
15
16
  import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
16
17
  import { RuntimeModule } from "../runtime/runtime.module.js";
17
18
  import { SandboxModule } from "../sandbox/sandbox.module.js";
@@ -23,6 +24,7 @@ import { OrgNetworkAllowancesModule } from "./network-allowances.service.js";
23
24
  import { Offboarding } from "./offboarding.js";
24
25
  import { OrgLockModule } from "./org-lock.js";
25
26
  import { OrgsService } from "./orgs.service.js";
27
+ import { OrgSecuritySettingsService } from "./security-settings.service.js";
26
28
  import { OrgSettingsModule } from "./settings.service.js";
27
29
  /**
28
30
  * Organizations: orgs, org settings, members, invitations, offboarding (its owed work goes through
@@ -39,6 +41,7 @@ OrgsModule = __decorate([
39
41
  EventLogModule,
40
42
  OrgLockModule,
41
43
  OrgSettingsModule,
44
+ PlatformModule,
42
45
  ExtensionsModule,
43
46
  // offboarding and the org delete record lifecycle hook deliveries
44
47
  LifecycleHooksModule,
@@ -56,10 +59,18 @@ OrgsModule = __decorate([
56
59
  QueueModule.registerQueue(MAINTENANCE_QUEUE_NAME),
57
60
  OrgNetworkAllowancesModule,
58
61
  ],
59
- providers: [OrgsService, MembersService, InvitationsService, Offboarding, DirectorySync],
62
+ providers: [
63
+ OrgsService,
64
+ MembersService,
65
+ InvitationsService,
66
+ Offboarding,
67
+ DirectorySync,
68
+ OrgSecuritySettingsService,
69
+ ],
60
70
  exports: [
61
71
  OrgLockModule,
62
72
  OrgSettingsModule,
73
+ OrgSecuritySettingsService,
63
74
  OrgsService,
64
75
  MembersService,
65
76
  InvitationsService,
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { INVITABLE_ROLES, MAX_INVITATION_HOURS } from "./invitations.service.js";
3
3
  import { ORG_ROLES } from "./roles.js";
4
+ import { OrgSecurityPatchSchema, OrgSecurityQuerySchema } from "./security-settings.service.js";
4
5
  import { OrgSettingsPatchSchema } from "./settings.service.js";
5
6
  export const OrgUpdateBody = z.object({
6
7
  name: z.string().min(1).max(100).optional(),
@@ -38,6 +39,8 @@ export const ORG_ROUTES = [
38
39
  { route: "GET /api/v1/orgs/:orgId/network-allowances" },
39
40
  ];
40
41
  export const ORG_SETTINGS_ROUTES = [
42
+ { route: "GET /api/v1/orgs/:orgId/settings/security", query: OrgSecurityQuerySchema },
43
+ { route: "PATCH /api/v1/orgs/:orgId/settings/security", body: OrgSecurityPatchSchema },
41
44
  { route: "GET /api/v1/orgs/:orgId/settings" },
42
45
  { route: "PATCH /api/v1/orgs/:orgId/settings", body: OrgSettingsPatchSchema },
43
46
  ];
@@ -0,0 +1,94 @@
1
+ import { z } from "zod";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { PlatformOperations } from "../platform/registry.js";
5
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
+ import { OrgToolSwitches } from "../tools/org-tool-switches.js";
7
+ import { ToolRegistry } from "../tools/registry.js";
8
+ import { OrgLock } from "./org-lock.js";
9
+ import { OrgSettingsService } from "./settings.service.js";
10
+ type ToolSource = "builtin" | "connector" | "extension" | "operation" | "unavailable";
11
+ export declare const OrgSecurityQuerySchema: z.ZodObject<{
12
+ cursor: z.ZodOptional<z.ZodString>;
13
+ limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
14
+ }, z.core.$strict>;
15
+ export declare const OrgSecurityPatchSchema: z.ZodObject<{
16
+ expectedRevision: z.ZodString;
17
+ confirmation: z.ZodOptional<z.ZodString>;
18
+ tools: z.ZodOptional<z.ZodArray<z.ZodObject<{
19
+ toolKey: z.ZodString;
20
+ policy: z.ZodEnum<{
21
+ allow: "allow";
22
+ ask: "ask";
23
+ deny: "deny";
24
+ }>;
25
+ unattendedPolicy: z.ZodEnum<{
26
+ allow: "allow";
27
+ ask: "ask";
28
+ deny: "deny";
29
+ }>;
30
+ }, z.core.$strict>>>;
31
+ gitPush: z.ZodOptional<z.ZodArray<z.ZodObject<{
32
+ target: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string | null, string>>, z.ZodString>;
33
+ denied: z.ZodBoolean;
34
+ }, z.core.$strict>>>;
35
+ allowedProfiles: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodArray<z.ZodEnum<{
36
+ "approve-for-me": "approve-for-me";
37
+ "full-access": "full-access";
38
+ "request-approval": "request-approval";
39
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>>;
40
+ projectReach: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
41
+ machine: "machine";
42
+ paths: "paths";
43
+ workspace: "workspace";
44
+ }>>>;
45
+ }, z.core.$strict>;
46
+ export type OrgSecurityQuery = z.infer<typeof OrgSecurityQuerySchema>;
47
+ export type OrgSecurityPatch = z.infer<typeof OrgSecurityPatchSchema>;
48
+ export declare class OrgSecuritySettingsService {
49
+ private readonly db;
50
+ readonly txHost: TransactionHost;
51
+ private readonly orgLock;
52
+ private readonly ceilings;
53
+ private readonly settings;
54
+ private readonly tools;
55
+ private readonly operations;
56
+ private readonly toolImpact;
57
+ constructor(db: KernelDb, txHost: TransactionHost, orgLock: OrgLock, ceilings: PermissionCeilingWrites, settings: OrgSettingsService, tools: ToolRegistry, operations: PlatformOperations, toolImpact: OrgToolSwitches);
58
+ private snapshot;
59
+ private toolSources;
60
+ view(orgId: string, query: OrgSecurityQuery): Promise<{
61
+ gitPushDenials: string[];
62
+ revision: string;
63
+ tools: {
64
+ toolKey: string;
65
+ source: ToolSource;
66
+ policy: import("../tools/org-tool-policies.js").OrgToolPolicy;
67
+ unattendedPolicy: import("../tools/org-tool-policies.js").OrgToolPolicy;
68
+ }[];
69
+ nextCursor: string | null;
70
+ allowedProfiles: {
71
+ configured: ("approve-for-me" | "full-access" | "request-approval")[] | null;
72
+ platform: import("@capybara-hq/plugin-sdk").PermissionProfile[];
73
+ effective: import("@capybara-hq/plugin-sdk").PermissionProfile[];
74
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
75
+ };
76
+ projectReach: {
77
+ configured: "machine" | "paths" | "workspace" | null;
78
+ platform: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
79
+ effective: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
80
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
81
+ limitingLayer: "org" | "platform";
82
+ };
83
+ }>;
84
+ update(orgId: string, patch: OrgSecurityPatch, actor: string, options: {
85
+ token?: string;
86
+ onlyNarrows?: boolean;
87
+ auditDetail?: Record<string, unknown>;
88
+ }): Promise<{
89
+ revision: string;
90
+ }>;
91
+ private lock;
92
+ private updateLocked;
93
+ }
94
+ export {};
@@ -0,0 +1,223 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { createHash } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { z } from "zod";
13
+ import { normalizeGitRepo } from "../automations/grant-rules.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { audit } from "../identity/audit.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { PlatformOperations } from "../platform/registry.js";
20
+ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
21
+ import { readOrgGitPushDenials, readOrgToolPolicies, writeOrgGitPushDenial, writeOrgToolPolicy, } from "../tools/org-tool-policies.js";
22
+ import { OrgToolSwitches } from "../tools/org-tool-switches.js";
23
+ import { ToolRegistry } from "../tools/registry.js";
24
+ import { OrgLock } from "./org-lock.js";
25
+ import { OrgSecurityCeilingsPatchSchema, OrgSettingsService } from "./settings.service.js";
26
+ const ToolKey = z.string().min(1).max(200);
27
+ const Policy = z.enum(["allow", "ask", "deny"]);
28
+ const POLICY_RANK = { allow: 0, ask: 1, deny: 2 };
29
+ const Revision = z.string().regex(/^[a-f0-9]{64}$/);
30
+ const GitTarget = z
31
+ .string()
32
+ .min(1)
33
+ .max(200)
34
+ .transform((value) => (value.trim() === "*" ? "*" : normalizeGitRepo(value)))
35
+ .pipe(z.string());
36
+ export const OrgSecurityQuerySchema = z
37
+ .object({
38
+ cursor: ToolKey.optional(),
39
+ limit: z.coerce.number().int().min(1).max(100).default(50),
40
+ })
41
+ .strict();
42
+ export const OrgSecurityPatchSchema = OrgSecurityCeilingsPatchSchema.extend({
43
+ expectedRevision: Revision,
44
+ confirmation: Revision.optional(),
45
+ tools: z
46
+ .array(z.object({ toolKey: ToolKey, policy: Policy, unattendedPolicy: Policy }).strict())
47
+ .max(100)
48
+ .optional(),
49
+ gitPush: z
50
+ .array(z.object({ target: GitTarget, denied: z.boolean() }).strict())
51
+ .max(100)
52
+ .optional(),
53
+ })
54
+ .strict()
55
+ .superRefine((input, ctx) => {
56
+ if (new Set(input.tools?.map(({ toolKey }) => toolKey)).size !== (input.tools?.length ?? 0))
57
+ ctx.addIssue({ code: "custom", path: ["tools"], message: "Each tool can be edited once" });
58
+ if (new Set(input.gitPush?.map(({ target }) => target)).size !== (input.gitPush?.length ?? 0))
59
+ ctx.addIssue({
60
+ code: "custom",
61
+ path: ["gitPush"],
62
+ message: "Each Git target can be edited once",
63
+ });
64
+ });
65
+ function digest(value) {
66
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
67
+ }
68
+ let OrgSecuritySettingsService = class OrgSecuritySettingsService {
69
+ db;
70
+ txHost;
71
+ orgLock;
72
+ ceilings;
73
+ settings;
74
+ tools;
75
+ operations;
76
+ toolImpact;
77
+ constructor(db, txHost, orgLock, ceilings, settings, tools, operations, toolImpact) {
78
+ this.db = db;
79
+ this.txHost = txHost;
80
+ this.orgLock = orgLock;
81
+ this.ceilings = ceilings;
82
+ this.settings = settings;
83
+ this.tools = tools;
84
+ this.operations = operations;
85
+ this.toolImpact = toolImpact;
86
+ }
87
+ async snapshot(orgId) {
88
+ const [ceilings, policies, gitPushDenials] = await Promise.all([
89
+ this.settings.securityCeilings(orgId),
90
+ readOrgToolPolicies(this.db.db, orgId),
91
+ readOrgGitPushDenials(this.db.db, orgId),
92
+ ]);
93
+ return {
94
+ ...ceilings,
95
+ policies,
96
+ gitPushDenials,
97
+ revision: digest([
98
+ ceilings,
99
+ policies.map((row) => [row.toolKey, row.rowRevision]),
100
+ gitPushDenials,
101
+ ]),
102
+ };
103
+ }
104
+ async toolSources(orgId) {
105
+ const catalog = await this.tools.securityCatalog(orgId);
106
+ const operations = this.operations.all();
107
+ const sources = new Map(catalog.map(({ toolKey, source }) => [toolKey, source]));
108
+ for (const { id } of operations)
109
+ sources.set(`Platform:${id}`, "operation");
110
+ return sources;
111
+ }
112
+ async view(orgId, query) {
113
+ const [{ policies, ...snapshot }, sources] = await Promise.all([
114
+ this.snapshot(orgId),
115
+ this.toolSources(orgId),
116
+ ]);
117
+ const rows = new Map(policies.map((row) => [row.toolKey, row]));
118
+ for (const { toolKey } of policies)
119
+ if (!sources.has(toolKey))
120
+ sources.set(toolKey, "unavailable");
121
+ const keys = [...sources.keys()]
122
+ .filter((key) => query.cursor === undefined || key > query.cursor)
123
+ .sort();
124
+ const page = keys.slice(0, query.limit);
125
+ return {
126
+ ...snapshot,
127
+ tools: page.map((toolKey) => ({
128
+ toolKey,
129
+ source: sources.get(toolKey) ?? "unavailable",
130
+ policy: rows.get(toolKey)?.policy ?? "allow",
131
+ unattendedPolicy: rows.get(toolKey)?.unattendedPolicy ?? "allow",
132
+ })),
133
+ nextCursor: keys.length > page.length ? (page.at(-1) ?? null) : null,
134
+ };
135
+ }
136
+ async update(orgId, patch, actor, options) {
137
+ return withOrderedLocks(() => this.lock(orgId, actor), () => this.updateLocked(orgId, patch, actor, options));
138
+ }
139
+ async lock(orgId, actor) {
140
+ await this.orgLock.lockAndAuthorize(orgId, actor, "org.update");
141
+ await this.ceilings.lock({ orgId }, "org");
142
+ }
143
+ async updateLocked(orgId, patch, actor, options) {
144
+ await this.lock(orgId, actor);
145
+ const before = await this.snapshot(orgId);
146
+ if (patch.expectedRevision !== before.revision)
147
+ throw new ApiError("org.security_revision_conflict", "Reload the organization security settings before saving");
148
+ const rows = new Map(before.policies.map((row) => [row.toolKey, row]));
149
+ if (options.onlyNarrows &&
150
+ (patch.tools?.some((row) => {
151
+ const old = rows.get(row.toolKey);
152
+ return (POLICY_RANK[row.policy] < POLICY_RANK[old?.policy ?? "allow"] ||
153
+ POLICY_RANK[row.unattendedPolicy] < POLICY_RANK[old?.unattendedPolicy ?? "allow"]);
154
+ }) ||
155
+ patch.gitPush?.some(({ target, denied }) => !denied && before.gitPushDenials.includes(target))))
156
+ throw new ApiError("org.security_widening_not_allowed", "Open /settings/security on the web to widen the organization security settings");
157
+ if (patch.tools?.length) {
158
+ const catalog = await this.toolSources(orgId);
159
+ for (const { toolKey } of patch.tools) {
160
+ if (!rows.has(toolKey) && !catalog.has(toolKey))
161
+ throw new ApiError("validation_failed", "Choose a canonical tool key from the security tool catalog", [{ path: "tools", toolKey }]);
162
+ }
163
+ }
164
+ const newlyDenied = patch.tools?.filter(({ toolKey, policy }) => policy === "deny" && rows.get(toolKey)?.policy !== "deny") ?? [];
165
+ if (newlyDenied.length) {
166
+ const affected = (await Promise.all(newlyDenied.map(async ({ toolKey }) => ({
167
+ toolKey,
168
+ agents: await this.toolImpact.affectedAgents(orgId, toolKey),
169
+ })))).filter(({ agents }) => agents.length > 0);
170
+ if (affected.length) {
171
+ const confirmation = digest([
172
+ orgId,
173
+ actor,
174
+ { ...patch, confirmation: undefined },
175
+ affected,
176
+ ]);
177
+ if (patch.confirmation !== confirmation)
178
+ throw new ApiError("org.security_confirmation_required", "Review the affected agents before denying these tools", [{ confirmation, affected }]);
179
+ }
180
+ }
181
+ await this.settings.updateSecurityCeilingsLocked(orgId, patch, actor, options.token, options.onlyNarrows === true, options.auditDetail);
182
+ for (const row of patch.tools ?? [])
183
+ await writeOrgToolPolicy(this.db.db, orgId, row, actor);
184
+ for (const { target, denied } of patch.gitPush ?? [])
185
+ await writeOrgGitPushDenial(this.db.db, orgId, target, denied, actor);
186
+ const after = await this.snapshot(orgId);
187
+ if (after.revision !== before.revision) {
188
+ await audit(this.db.db, {
189
+ actorAccountId: actor,
190
+ ...(options.token && { actorTokenId: options.token }),
191
+ orgId,
192
+ action: "org.security_updated",
193
+ target: orgId,
194
+ detail: {
195
+ before: before.revision,
196
+ after: after.revision,
197
+ tools: patch.tools,
198
+ gitPush: patch.gitPush,
199
+ ...options.auditDetail,
200
+ },
201
+ });
202
+ }
203
+ return { revision: after.revision };
204
+ }
205
+ };
206
+ __decorate([
207
+ Transactional({ propagation: "mandatory" })
208
+ ], OrgSecuritySettingsService.prototype, "lock", null);
209
+ __decorate([
210
+ Transactional()
211
+ ], OrgSecuritySettingsService.prototype, "updateLocked", null);
212
+ OrgSecuritySettingsService = __decorate([
213
+ Injectable(),
214
+ __param(0, Inject(KernelDb)),
215
+ __param(1, Inject(TransactionHost)),
216
+ __param(2, Inject(OrgLock)),
217
+ __param(3, Inject(PermissionCeilingWrites)),
218
+ __param(4, Inject(OrgSettingsService)),
219
+ __param(5, Inject(ToolRegistry)),
220
+ __param(6, Inject(PlatformOperations)),
221
+ __param(7, Inject(OrgToolSwitches))
222
+ ], OrgSecuritySettingsService);
223
+ export { OrgSecuritySettingsService };
@@ -1,5 +1,6 @@
1
1
  import { type Principal } from "../identity/principal.js";
2
2
  import { type OrgContext } from "./org.guard.js";
3
+ import { type OrgSecurityPatch, type OrgSecurityQuery, OrgSecuritySettingsService } from "./security-settings.service.js";
3
4
  import { type OrgSettingsPatch, type OrgSettingsResponse, OrgSettingsService } from "./settings.service.js";
4
5
  /** Organization settings, readable by members and writable by org admins. */
5
6
  export declare class OrgSettingsController {
@@ -8,3 +9,35 @@ export declare class OrgSettingsController {
8
9
  get(principal: Principal, org: OrgContext): Promise<OrgSettingsResponse>;
9
10
  update(principal: Principal, org: OrgContext, body: OrgSettingsPatch): Promise<OrgSettingsResponse>;
10
11
  }
12
+ /** Organization security ceilings require the organization admin role even for reads. */
13
+ export declare class OrgSecuritySettingsController {
14
+ private readonly security;
15
+ constructor(security: OrgSecuritySettingsService);
16
+ get(org: OrgContext, query: OrgSecurityQuery): Promise<{
17
+ gitPushDenials: string[];
18
+ revision: string;
19
+ tools: {
20
+ toolKey: string;
21
+ source: "builtin" | "connector" | "extension" | "operation" | "unavailable";
22
+ policy: import("../tools/org-tool-policies.js").OrgToolPolicy;
23
+ unattendedPolicy: import("../tools/org-tool-policies.js").OrgToolPolicy;
24
+ }[];
25
+ nextCursor: string | null;
26
+ allowedProfiles: {
27
+ configured: ("approve-for-me" | "full-access" | "request-approval")[] | null;
28
+ platform: import("@capybara-hq/plugin-sdk").PermissionProfile[];
29
+ effective: import("@capybara-hq/plugin-sdk").PermissionProfile[];
30
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
31
+ };
32
+ projectReach: {
33
+ configured: "machine" | "paths" | "workspace" | null;
34
+ platform: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
35
+ effective: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
36
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
37
+ limitingLayer: "org" | "platform";
38
+ };
39
+ }>;
40
+ update(principal: Principal, org: OrgContext, body: OrgSecurityPatch): Promise<{
41
+ revision: string;
42
+ }>;
43
+ }
@@ -10,8 +10,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Controller, Get, Inject, Patch } from "@nestjs/common";
11
11
  import { CurrentPrincipal, patTokenId, requireUser, } from "../identity/principal.js";
12
12
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
13
- import { ZBody } from "../infra/validation/zod-params.js";
13
+ import { ZBody, ZQuery } from "../infra/validation/zod-params.js";
14
14
  import { CurrentOrg, OrgAction } from "./org.guard.js";
15
+ import { OrgSecurityPatchSchema, OrgSecurityQuerySchema, OrgSecuritySettingsService, } from "./security-settings.service.js";
15
16
  import { OrgSettingsPatchSchema, OrgSettingsService, } from "./settings.service.js";
16
17
  class OrgSettingsPatchBody extends createZodDto(OrgSettingsPatchSchema, "OrgSettingsPatch") {
17
18
  }
@@ -54,3 +55,42 @@ OrgSettingsController = __decorate([
54
55
  __param(0, Inject(OrgSettingsService))
55
56
  ], OrgSettingsController);
56
57
  export { OrgSettingsController };
58
+ class OrgSecurityQueryDto extends createZodDto(OrgSecurityQuerySchema, "OrgSecurityQuery") {
59
+ }
60
+ class OrgSecurityPatchDto extends createZodDto(OrgSecurityPatchSchema, "OrgSecurityPatch") {
61
+ }
62
+ /** Organization security ceilings require the organization admin role even for reads. */
63
+ let OrgSecuritySettingsController = class OrgSecuritySettingsController {
64
+ security;
65
+ constructor(security) {
66
+ this.security = security;
67
+ }
68
+ get(org, query) {
69
+ return this.security.view(org.orgId, query);
70
+ }
71
+ update(principal, org, body) {
72
+ const user = requireUser(principal);
73
+ const token = patTokenId(user);
74
+ return this.security.update(org.orgId, body, user.account.id, {
75
+ ...(token !== undefined && { token, onlyNarrows: true }),
76
+ });
77
+ }
78
+ };
79
+ __decorate([
80
+ Get(),
81
+ OrgAction("org.update"),
82
+ __param(0, CurrentOrg()),
83
+ __param(1, ZQuery(OrgSecurityQueryDto))
84
+ ], OrgSecuritySettingsController.prototype, "get", null);
85
+ __decorate([
86
+ Patch(),
87
+ OrgAction("org.update"),
88
+ __param(0, CurrentPrincipal()),
89
+ __param(1, CurrentOrg()),
90
+ __param(2, ZBody(OrgSecurityPatchDto))
91
+ ], OrgSecuritySettingsController.prototype, "update", null);
92
+ OrgSecuritySettingsController = __decorate([
93
+ Controller("api/v1/orgs/:orgId/settings/security"),
94
+ __param(0, Inject(OrgSecuritySettingsService))
95
+ ], OrgSecuritySettingsController);
96
+ export { OrgSecuritySettingsController };