@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
@@ -9,7 +9,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
10
  import type { KernelLogger } from "../log.js";
11
11
  import { type DeviceNetworkMode } from "../sandbox/device-sandbox.js";
12
- import { type DevicesNetworkView, type DevicesOutsideSandboxView } from "../sandbox/device-sandbox-settings.js";
12
+ import { type DeviceSandboxSettingsView, type DevicesNetworkView, type DevicesOutsideSandboxView } from "../sandbox/device-sandbox-settings.js";
13
13
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
14
14
  import { type ExternalSharingView } from "../shares/settings.js";
15
15
  import { type DeviceNetworkSetting } from "./device-network-setting.js";
@@ -23,9 +23,6 @@ import { type OrgRole } from "./roles.js";
23
23
  * (D11, default on).
24
24
  * - `locale`: the org's default language (`zh` / `en`, default en); the bot's fixed phrases in IM
25
25
  * follow it.
26
- * - `sandboxToolPolicy`: the default policy of the sandbox tools (M5 T8, default allow). With
27
- * `ask`, every tool but the read-only `Read` / `Glob` / `Grep` needs approval (read live at
28
- * execution). An invalid stored value reads as `ask` (narrower, never wider) and is logged.
29
26
  * - `wakeOnBackgroundTask`: the org's override of `runtime.wakeOnBackgroundTask` (absent follows
30
27
  * the deployment), see {@link effectiveWakeOnBackgroundTask}.
31
28
  * - `outsideSandbox`: whether devices of the org may be granted running a call outside their
@@ -76,12 +73,7 @@ export declare const OrgThemeSettingSchema: z.ZodObject<{
76
73
  export type OrgThemeSetting = z.infer<typeof OrgThemeSettingSchema>;
77
74
  /** The theme setting of an org that has none: follow the platform, personal picks allowed. */
78
75
  export declare const DEFAULT_ORG_THEME: OrgThemeSetting;
79
- /**
80
- * Org settings of automations (spec §9); every field reads leniently (invalid = default,
81
- * except `forbiddenTools`, which keeps its valid entries). A stored `forbiddenTools` that is not a
82
- * list (or a group that is not an object) reads as `[]` here, for display; enforcement checks
83
- * {@link invalidStoredForbiddenTools} and fails unattended runs instead (never wider).
84
- */
76
+ /** Organization automation settings with per-field defaults. */
85
77
  export declare const AutomationsSettingsSchema: z.ZodObject<{
86
78
  enabled: z.ZodCatch<z.ZodDefault<z.ZodBoolean>>;
87
79
  minIntervalMinutes: z.ZodCatch<z.ZodDefault<z.ZodNumber>>;
@@ -104,12 +96,11 @@ export declare const AutomationsSettingsSchema: z.ZodObject<{
104
96
  off: "off";
105
97
  }>>>;
106
98
  eventSourcesOff: z.ZodCatch<z.ZodPreprocess<z.ZodDefault<z.ZodArray<z.ZodString>>, unknown>>;
107
- forbiddenTools: z.ZodCatch<z.ZodPreprocess<z.ZodDefault<z.ZodArray<z.ZodString>>, unknown>>;
108
99
  }, z.core.$strip>;
109
100
  export type AutomationsSettings = z.infer<typeof AutomationsSettingsSchema>;
110
101
  /**
111
102
  * The PATCH form: a partial merge into the group (fields left out keep their stored value; see
112
- * `OrgSettingsService.update`). A field given replaces that field whole, `forbiddenTools` too.
103
+ * `OrgSettingsService.update`). A supplied field replaces that field.
113
104
  */
114
105
  export declare const AutomationsPatchSchema: z.ZodObject<{
115
106
  enabled: z.ZodOptional<z.ZodBoolean>;
@@ -133,7 +124,6 @@ export declare const AutomationsPatchSchema: z.ZodObject<{
133
124
  off: "off";
134
125
  }>>;
135
126
  eventSourcesOff: z.ZodOptional<z.ZodArray<z.ZodString>>;
136
- forbiddenTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
137
127
  }, z.core.$strict>;
138
128
  /**
139
129
  * The org's git gateway setting (sandbox git credentials spec §9): `enabled: false` switches the
@@ -179,15 +169,21 @@ export declare const OrgSettingsSchema: z.ZodObject<{
179
169
  en: "en";
180
170
  zh: "zh";
181
171
  }>>>;
182
- sandboxToolPolicy: z.ZodCatch<z.ZodDefault<z.ZodEnum<{
183
- allow: "allow";
184
- ask: "ask";
185
- }>>>;
186
172
  platformTool: z.ZodCatch<z.ZodDefault<z.ZodEnum<{
187
173
  off: "off";
188
174
  on: "on";
189
175
  "read-only": "read-only";
190
176
  }>>>;
177
+ allowedProfiles: z.ZodCatch<z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodEnum<{
178
+ "approve-for-me": "approve-for-me";
179
+ "full-access": "full-access";
180
+ "request-approval": "request-approval";
181
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>>;
182
+ projectReach: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
183
+ machine: "machine";
184
+ paths: "paths";
185
+ workspace: "workspace";
186
+ }>>>;
191
187
  outsideSandbox: z.ZodCatch<z.ZodOptional<z.ZodEnum<{
192
188
  allowed: "allowed";
193
189
  off: "off";
@@ -266,7 +262,6 @@ export declare const OrgSettingsSchema: z.ZodObject<{
266
262
  off: "off";
267
263
  }>>>;
268
264
  eventSourcesOff: z.ZodCatch<z.ZodPreprocess<z.ZodDefault<z.ZodArray<z.ZodString>>, unknown>>;
269
- forbiddenTools: z.ZodCatch<z.ZodPreprocess<z.ZodDefault<z.ZodArray<z.ZodString>>, unknown>>;
270
265
  }, z.core.$strip>>>;
271
266
  compaction: z.ZodCatch<z.ZodOptional<z.ZodObject<{
272
267
  enabled: z.ZodOptional<z.ZodBoolean>;
@@ -291,18 +286,21 @@ export declare const OrgSettingsSchema: z.ZodObject<{
291
286
  on: "on";
292
287
  }>>>;
293
288
  }, z.core.$strip>;
289
+ export declare const OrgSecurityCeilingsPatchSchema: z.ZodObject<{
290
+ allowedProfiles: z.ZodOptional<z.ZodNullable<z.ZodPipe<z.ZodArray<z.ZodEnum<{
291
+ "approve-for-me": "approve-for-me";
292
+ "full-access": "full-access";
293
+ "request-approval": "request-approval";
294
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>>;
295
+ projectReach: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
296
+ machine: "machine";
297
+ paths: "paths";
298
+ workspace: "workspace";
299
+ }>>>;
300
+ }, z.core.$strip>;
301
+ export type OrgSecurityCeilingsPatch = z.infer<typeof OrgSecurityCeilingsPatchSchema>;
294
302
  export type OrgSettings = z.infer<typeof OrgSettingsSchema>;
295
- /**
296
- * The settings as the responses carry them: {@link OrgSettings} plus
297
- * `automations.forbiddenToolsUnreadable: true` when the stored list cannot be read
298
- * ({@link invalidStoredForbiddenTools}; `forbiddenTools` then reads `[]`), so the settings page
299
- * says so and saves the list. Never stored.
300
- */
301
- export type OrgSettingsView = OrgSettings & {
302
- automations: OrgSettings["automations"] & {
303
- forbiddenToolsUnreadable?: true;
304
- };
305
- };
303
+ export type OrgSettingsView = OrgSettings;
306
304
  /** PATCH 体:只改给出的字段;未知字段 → 400。 */
307
305
  export declare const OrgSettingsPatchSchema: z.ZodObject<{
308
306
  toolSearch: z.ZodOptional<z.ZodEnum<{
@@ -313,10 +311,6 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
313
311
  en: "en";
314
312
  zh: "zh";
315
313
  }>>;
316
- sandboxToolPolicy: z.ZodOptional<z.ZodEnum<{
317
- allow: "allow";
318
- ask: "ask";
319
- }>>;
320
314
  platformTool: z.ZodOptional<z.ZodEnum<{
321
315
  off: "off";
322
316
  on: "on";
@@ -384,7 +378,6 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
384
378
  off: "off";
385
379
  }>>;
386
380
  eventSourcesOff: z.ZodOptional<z.ZodArray<z.ZodString>>;
387
- forbiddenTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
388
381
  }, z.core.$strict>>;
389
382
  compaction: z.ZodOptional<z.ZodNullable<z.ZodObject<{
390
383
  enabled: z.ZodOptional<z.ZodBoolean>;
@@ -434,6 +427,8 @@ export interface OrgEffectiveNetwork {
434
427
  }
435
428
  /** The deployment defaults the settings page shows for "follow the platform" (`GET` returns them). */
436
429
  export interface OrgSettingsDeployment {
430
+ allowedProfiles: DeviceSandboxSettingsView["allowedProfiles"];
431
+ projectReach: DeviceSandboxSettingsView["projectReach"];
437
432
  /** The platform's outside-sandbox ceiling and where it comes from. */
438
433
  outsideSandbox: DevicesOutsideSandboxView;
439
434
  /**
@@ -477,32 +472,8 @@ export interface OrgSettingsResponse {
477
472
  export declare function parseOrgSettings(raw: unknown): OrgSettings;
478
473
  /** The org's stored settings jsonb, read live; undefined when the org is missing or deleted. */
479
474
  export declare function readStoredOrgSettings(db: KernelSchemaDb, orgId: string): Promise<unknown>;
480
- /**
481
- * Reads the org settings (live from PG every time, so a change applies at once across replicas);
482
- * a missing or deleted org reads as the defaults. With `log`, an
483
- * unreadable security setting ({@link logUnreadableSecuritySettings}) is logged.
484
- */
485
- export declare function readOrgSettings(db: KernelSchemaDb, orgId: string,
486
- /** Per-call paths (the tool policy) log at debug; the settings reads and the fire warn. */
487
- log?: Pick<KernelLogger, "debug">): Promise<OrgSettings>;
488
- /** Whether a stored settings object holds a `sandboxToolPolicy` this version reads as `ask`. */
489
- export declare function invalidStoredSandboxToolPolicy(raw: unknown): boolean;
490
- /**
491
- * Whether the stored automation `forbiddenTools` cannot be read: the group or the field is
492
- * present but not an object / a list. Unattended runs of such an org fail
493
- * ({@link FORBIDDEN_TOOLS_UNREADABLE_ERROR}) rather than run with nothing forbidden. Invalid
494
- * entries inside a list are dropped instead (the valid ones stay forbidden).
495
- */
496
- export declare function invalidStoredForbiddenTools(raw: unknown): boolean;
497
- /** The refusal of an unattended run of an org whose `forbiddenTools` cannot be read. */
498
- export declare const FORBIDDEN_TOOLS_UNREADABLE_ERROR = "The organization's forbidden tool list for automations is unreadable, so this scheduled run cannot continue; an org admin must save the list again in the organization's automation settings.";
499
- /** The refusal of a new task grant while the org's `forbiddenTools` cannot be read. */
500
- export declare const FORBIDDEN_TOOLS_UNREADABLE_GRANT_ERROR = "The organization's forbidden tool list for automations is unreadable, so no tool can be approved for a task now; an org admin must save the list again in the organization's automation settings.";
501
- /**
502
- * Logs (through `log`, at the caller's level) the security settings a stored value reads narrower
503
- * than written, with the org id.
504
- */
505
- export declare function logUnreadableSecuritySettings(log: (msg: string, fields: Record<string, unknown>) => void, orgId: string, raw: unknown): void;
475
+ /** Reads the org settings live; a missing or deleted org reads as the defaults. */
476
+ export declare function readOrgSettings(db: KernelSchemaDb, orgId: string): Promise<OrgSettings>;
506
477
  /** Whether a stored settings object holds an `externalSharing` this version reads as `off`. */
507
478
  export declare function invalidStoredExternalSharing(raw: unknown): boolean;
508
479
  /** Whether a stored settings object holds a `promptSuggestions` this version reads as `off`. */
@@ -574,12 +545,26 @@ export declare class OrgSettingsService {
574
545
  strict: false;
575
546
  }): Pick<ExtensionPointDefaults, "providersFor">;
576
547
  } | undefined);
577
- /** Parses stored settings, warning when an invalid `outsideSandbox` narrows to `off`, an
578
- * invalid `deviceNetwork` to an empty allowlist, or a security setting reads narrower
579
- * ({@link logUnreadableSecuritySettings}, warn). */
548
+ /** Parses stored settings and warns when malformed network or capability fields narrow. */
580
549
  private parseStored;
581
550
  /** The deployment defaults (what "follow the platform" means on the settings page). */
582
551
  deployment(): Promise<OrgSettingsDeployment>;
552
+ securityCeilings(orgId: string): Promise<{
553
+ allowedProfiles: {
554
+ configured: ("approve-for-me" | "full-access" | "request-approval")[] | null;
555
+ platform: import("@capybara-hq/plugin-sdk").PermissionProfile[];
556
+ effective: import("@capybara-hq/plugin-sdk").PermissionProfile[];
557
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
558
+ };
559
+ projectReach: {
560
+ configured: "machine" | "paths" | "workspace" | null;
561
+ platform: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
562
+ effective: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
563
+ source: import("../sandbox/device-sandbox-settings.js").DeviceSandboxSource;
564
+ limitingLayer: "org" | "platform";
565
+ };
566
+ }>;
567
+ updateSecurityCeilingsLocked(orgId: string, patch: OrgSecurityCeilingsPatch, actor: string, token: string | undefined, onlyNarrows: boolean, auditDetail: Record<string, unknown> | undefined): Promise<void>;
583
568
  /** Whether prompt suggestions run for the org now: one read of the platform and of the org. */
584
569
  promptSuggestionsEnabled(orgId: string): Promise<boolean>;
585
570
  /**
@@ -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 { UI_CONTRIBUTION_KEY_RE } from "@capybara-hq/plugin-sdk";
10
+ import { narrowerProjectReach, UI_CONTRIBUTION_KEY_RE, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
12
12
  import { ModuleRef } from "@nestjs/core";
13
13
  import { z } from "zod";
@@ -23,10 +23,10 @@ import { TransactionHost, withOrderedLocks } from "../infra/database/transaction
23
23
  import { Transactional } from "../infra/database/transactional.decorator.js";
24
24
  import { KERNEL_LOGGER } from "../infra/tokens.js";
25
25
  import { hostGrantable, hostGrantCeiling, } from "../sandbox/device-sandbox.js";
26
- import { OrgDeviceSandboxStoredSchema, readDeviceSandboxSettingsView, } from "../sandbox/device-sandbox-settings.js";
26
+ import { AllowedProfilesSchema, effectiveAllowedProfiles, effectiveProjectReach, OrgDeviceSandboxStoredSchema, ProjectReachSchema, readDeviceSandboxSettingsView, } from "../sandbox/device-sandbox-settings.js";
27
27
  import { coversHost, orgCloudMode, orgEffectiveHosts, orgHostOutsideCeiling, } from "../sandbox/modes.js";
28
28
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
29
- import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
29
+ import { devicesFollowingDefault, hostsNarrowed, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
30
30
  import { readExternalSharing, readShareMaxExpiry, } from "../shares/settings.js";
31
31
  import { assertThemeOnIn } from "../themes/theme-state.js";
32
32
  import { IanaTimeZone } from "../time-zone.js";
@@ -42,9 +42,6 @@ import { can } from "./roles.js";
42
42
  * (D11, default on).
43
43
  * - `locale`: the org's default language (`zh` / `en`, default en); the bot's fixed phrases in IM
44
44
  * follow it.
45
- * - `sandboxToolPolicy`: the default policy of the sandbox tools (M5 T8, default allow). With
46
- * `ask`, every tool but the read-only `Read` / `Glob` / `Grep` needs approval (read live at
47
- * execution). An invalid stored value reads as `ask` (narrower, never wider) and is logged.
48
45
  * - `wakeOnBackgroundTask`: the org's override of `runtime.wakeOnBackgroundTask` (absent follows
49
46
  * the deployment), see {@link effectiveWakeOnBackgroundTask}.
50
47
  * - `outsideSandbox`: whether devices of the org may be granted running a call outside their
@@ -94,16 +91,9 @@ export const OrgThemeSettingSchema = z
94
91
  /** The theme setting of an org that has none: follow the platform, personal picks allowed. */
95
92
  export const DEFAULT_ORG_THEME = { id: null, personal: "allowed" };
96
93
  const posInt = (max, def) => z.number().int().min(1).max(max).default(def).catch(def);
97
- /** A stored `forbiddenTools` entry worth keeping: a tool key of the length the PATCH accepts. */
98
- const isForbiddenToolEntry = (v) => typeof v === "string" && v.length >= 1 && v.length <= 200;
99
94
  /** A stored `eventSourcesOff` entry worth keeping: an extension name of the length the PATCH accepts. */
100
95
  const isEventSourceEntry = (v) => typeof v === "string" && v.length >= 1 && v.length <= 214;
101
- /**
102
- * Org settings of automations (spec §9); every field reads leniently (invalid = default,
103
- * except `forbiddenTools`, which keeps its valid entries). A stored `forbiddenTools` that is not a
104
- * list (or a group that is not an object) reads as `[]` here, for display; enforcement checks
105
- * {@link invalidStoredForbiddenTools} and fails unattended runs instead (never wider).
106
- */
96
+ /** Organization automation settings with per-field defaults. */
107
97
  export const AutomationsSettingsSchema = z.object({
108
98
  enabled: z.boolean().default(true).catch(true),
109
99
  minIntervalMinutes: posInt(1_000_000, 60),
@@ -129,15 +119,10 @@ export const AutomationsSettingsSchema = z.object({
129
119
  eventSourcesOff: z
130
120
  .preprocess((v) => (Array.isArray(v) ? v.filter(isEventSourceEntry).slice(0, 200) : v), z.array(z.string()).max(200).default([]))
131
121
  .catch([]),
132
- // fail-safe: an invalid entry is dropped, the valid ones stay forbidden (never reset to []);
133
- // past the PATCH's 500 the list is truncated
134
- forbiddenTools: z
135
- .preprocess((v) => (Array.isArray(v) ? v.filter(isForbiddenToolEntry).slice(0, 500) : v), z.array(z.string()).max(500).default([]))
136
- .catch([]),
137
122
  });
138
123
  /**
139
124
  * The PATCH form: a partial merge into the group (fields left out keep their stored value; see
140
- * `OrgSettingsService.update`). A field given replaces that field whole, `forbiddenTools` too.
125
+ * `OrgSettingsService.update`). A supplied field replaces that field.
141
126
  */
142
127
  export const AutomationsPatchSchema = z
143
128
  .object({
@@ -155,7 +140,6 @@ export const AutomationsPatchSchema = z
155
140
  maxEventRunsPerSubjectPerHour: z.number().int().min(1).max(1_000_000),
156
141
  directedDefault: z.enum(["auto", "confirm", "off"]),
157
142
  eventSourcesOff: z.array(z.string().min(1).max(214)).max(200),
158
- forbiddenTools: z.array(z.string().min(1).max(200)).max(500),
159
143
  })
160
144
  .partial()
161
145
  .strict();
@@ -206,9 +190,10 @@ export const OrgSettingsSchema = z.object({
206
190
  toolSearch: z.enum(["on", "off"]).default("on").catch("on"),
207
191
  locale: z.enum(["zh", "en"]).default("en").catch("en"),
208
192
  /** Absent = `allow`; an invalid stored value reads as `ask` (narrower, never wider). */
209
- sandboxToolPolicy: z.enum(["allow", "ask"]).default("allow").catch("ask"),
210
193
  platformTool: z.enum(["on", "read-only", "off"]).default("on").catch("on"),
211
194
  /** The org's outside-sandbox ceiling; absent follows the platform. */
195
+ allowedProfiles: OrgDeviceSandboxStoredSchema.shape.allowedProfiles,
196
+ projectReach: OrgDeviceSandboxStoredSchema.shape.projectReach,
212
197
  outsideSandbox: OrgDeviceSandboxStoredSchema.shape.outsideSandbox,
213
198
  /** The org's device sandbox network; absent follows the platform. */
214
199
  deviceNetwork: OrgDeviceSandboxStoredSchema.shape.deviceNetwork,
@@ -246,19 +231,15 @@ export const OrgSettingsSchema = z.object({
246
231
  */
247
232
  promptSuggestions: PromptSuggestionsSetting.optional().catch("off"),
248
233
  });
249
- /** {@link OrgSettingsView} of `settings`, flagged from the stored value `raw`. */
250
- const viewOf = (settings, raw) => invalidStoredForbiddenTools(raw)
251
- ? {
252
- ...settings,
253
- automations: { ...settings.automations, forbiddenToolsUnreadable: true },
254
- }
255
- : settings;
234
+ export const OrgSecurityCeilingsPatchSchema = z.object({
235
+ allowedProfiles: AllowedProfilesSchema.nullable().optional(),
236
+ projectReach: ProjectReachSchema.nullable().optional(),
237
+ });
256
238
  /** PATCH 体:只改给出的字段;未知字段 → 400。 */
257
239
  export const OrgSettingsPatchSchema = z
258
240
  .object({
259
241
  toolSearch: z.enum(["on", "off"]).optional(),
260
242
  locale: z.enum(["zh", "en"]).optional(),
261
- sandboxToolPolicy: z.enum(["allow", "ask"]).optional(),
262
243
  platformTool: z.enum(["on", "read-only", "off"]).optional(),
263
244
  /**
264
245
  * The org's default device provider; null clears it (follow the platform). A provider that is
@@ -349,55 +330,9 @@ export async function readStoredOrgSettings(db, orgId) {
349
330
  .executeTakeFirst();
350
331
  return row?.settings;
351
332
  }
352
- /**
353
- * Reads the org settings (live from PG every time, so a change applies at once across replicas);
354
- * a missing or deleted org reads as the defaults. With `log`, an
355
- * unreadable security setting ({@link logUnreadableSecuritySettings}) is logged.
356
- */
357
- export async function readOrgSettings(db, orgId,
358
- /** Per-call paths (the tool policy) log at debug; the settings reads and the fire warn. */
359
- log) {
360
- const raw = await readStoredOrgSettings(db, orgId);
361
- if (log !== undefined) {
362
- logUnreadableSecuritySettings((msg, f) => log.debug(msg, f), orgId, raw);
363
- }
364
- return parseOrgSettings(raw);
365
- }
366
- /** Whether a stored settings object holds a `sandboxToolPolicy` this version reads as `ask`. */
367
- export function invalidStoredSandboxToolPolicy(raw) {
368
- const v = asObject(raw).sandboxToolPolicy;
369
- return v !== undefined && !OrgSettingsPatchSchema.shape.sandboxToolPolicy.safeParse(v).success;
370
- }
371
- /**
372
- * Whether the stored automation `forbiddenTools` cannot be read: the group or the field is
373
- * present but not an object / a list. Unattended runs of such an org fail
374
- * ({@link FORBIDDEN_TOOLS_UNREADABLE_ERROR}) rather than run with nothing forbidden. Invalid
375
- * entries inside a list are dropped instead (the valid ones stay forbidden).
376
- */
377
- export function invalidStoredForbiddenTools(raw) {
378
- const group = asObject(raw).automations;
379
- if (group === undefined)
380
- return false;
381
- if (group === null || typeof group !== "object" || Array.isArray(group))
382
- return true;
383
- const v = group.forbiddenTools;
384
- return v !== undefined && !Array.isArray(v);
385
- }
386
- /** The refusal of an unattended run of an org whose `forbiddenTools` cannot be read. */
387
- export const FORBIDDEN_TOOLS_UNREADABLE_ERROR = "The organization's forbidden tool list for automations is unreadable, so this scheduled run cannot continue; an org admin must save the list again in the organization's automation settings.";
388
- /** The refusal of a new task grant while the org's `forbiddenTools` cannot be read. */
389
- export const FORBIDDEN_TOOLS_UNREADABLE_GRANT_ERROR = "The organization's forbidden tool list for automations is unreadable, so no tool can be approved for a task now; an org admin must save the list again in the organization's automation settings.";
390
- /**
391
- * Logs (through `log`, at the caller's level) the security settings a stored value reads narrower
392
- * than written, with the org id.
393
- */
394
- export function logUnreadableSecuritySettings(log, orgId, raw) {
395
- if (invalidStoredSandboxToolPolicy(raw)) {
396
- log("org settings: stored sandboxToolPolicy is invalid; it reads as ask", { orgId });
397
- }
398
- if (invalidStoredForbiddenTools(raw)) {
399
- log("org settings: stored automations.forbiddenTools is unreadable; unattended runs fail until an org admin saves it again", { orgId });
400
- }
333
+ /** Reads the org settings live; a missing or deleted org reads as the defaults. */
334
+ export async function readOrgSettings(db, orgId) {
335
+ return parseOrgSettings(await readStoredOrgSettings(db, orgId));
401
336
  }
402
337
  const outsideSandboxNotAllowed = (message) => new ApiError("org.outside_sandbox_not_allowed", message);
403
338
  const networkNotAllowed = (message, field) => new ApiError("org.network_not_allowed", message, [{ path: `deviceNetwork.${field}` }]);
@@ -496,9 +431,7 @@ let OrgSettingsService = class OrgSettingsService {
496
431
  this.log = log;
497
432
  this.modules = modules;
498
433
  }
499
- /** Parses stored settings, warning when an invalid `outsideSandbox` narrows to `off`, an
500
- * invalid `deviceNetwork` to an empty allowlist, or a security setting reads narrower
501
- * ({@link logUnreadableSecuritySettings}, warn). */
434
+ /** Parses stored settings and warns when malformed network or capability fields narrow. */
502
435
  parseStored(orgId, raw) {
503
436
  if (invalidStoredOutsideSandbox(raw)) {
504
437
  this.log?.warn("org settings: stored outsideSandbox is invalid; it reads as off", { orgId });
@@ -516,9 +449,6 @@ let OrgSettingsService = class OrgSettingsService {
516
449
  orgId,
517
450
  });
518
451
  }
519
- const log = this.log;
520
- if (log !== undefined)
521
- logUnreadableSecuritySettings((m, f) => log.warn(m, f), orgId, raw);
522
452
  return parseOrgSettings(raw);
523
453
  }
524
454
  /** The deployment defaults (what "follow the platform" means on the settings page). */
@@ -535,6 +465,8 @@ let OrgSettingsService = class OrgSettingsService {
535
465
  ]);
536
466
  return {
537
467
  outsideSandbox: deviceSandbox.outsideSandbox,
468
+ allowedProfiles: deviceSandbox.allowedProfiles,
469
+ projectReach: deviceSandbox.projectReach,
538
470
  deviceNetwork: {
539
471
  ...deviceSandbox.network,
540
472
  allowHosts: [...lim.allowHosts],
@@ -550,6 +482,58 @@ let OrgSettingsService = class OrgSettingsService {
550
482
  promptSuggestions,
551
483
  };
552
484
  }
485
+ async securityCeilings(orgId) {
486
+ const [settings, platform] = await Promise.all([
487
+ this.get(orgId),
488
+ readDeviceSandboxSettingsView(this.db.db, this.config, this.log),
489
+ ]);
490
+ return {
491
+ allowedProfiles: {
492
+ configured: settings.allowedProfiles ?? null,
493
+ platform: platform.allowedProfiles.value,
494
+ effective: effectiveAllowedProfiles(platform.allowedProfiles.value, settings.allowedProfiles),
495
+ source: platform.allowedProfiles.source,
496
+ },
497
+ projectReach: {
498
+ configured: settings.projectReach ?? null,
499
+ platform: platform.projectReach.ceiling,
500
+ effective: effectiveProjectReach(platform.projectReach.ceiling, settings.projectReach),
501
+ source: platform.projectReach.source.ceiling,
502
+ limitingLayer: settings.projectReach !== undefined &&
503
+ narrowerProjectReach(platform.projectReach.ceiling, settings.projectReach) !==
504
+ platform.projectReach.ceiling
505
+ ? "org"
506
+ : "platform",
507
+ },
508
+ };
509
+ }
510
+ async updateSecurityCeilingsLocked(orgId, patch, actor, token, onlyNarrows, auditDetail) {
511
+ if (patch.allowedProfiles === undefined && patch.projectReach === undefined)
512
+ return;
513
+ const before = await this.securityCeilings(orgId);
514
+ const nextProfiles = patch.allowedProfiles ?? before.allowedProfiles.platform;
515
+ const nextReach = patch.projectReach ?? before.projectReach.platform;
516
+ if (patch.allowedProfiles?.some((profile) => !before.allowedProfiles.platform.includes(profile)) ||
517
+ (patch.projectReach != null &&
518
+ narrowerProjectReach(patch.projectReach, before.projectReach.platform) !==
519
+ patch.projectReach))
520
+ throw new ApiError("org.security_ceiling_not_allowed", "The organization security settings exceed the platform ceiling");
521
+ if (onlyNarrows &&
522
+ ((patch.allowedProfiles !== undefined &&
523
+ nextProfiles.some((profile) => !before.allowedProfiles.effective.includes(profile))) ||
524
+ (patch.projectReach !== undefined &&
525
+ narrowerProjectReach(nextReach, before.projectReach.effective) !== nextReach)))
526
+ throw new ApiError("org.security_widening_not_allowed", "Open /settings/security on the web to widen the organization security settings");
527
+ await this.updateIn(orgId, patch, actor, token, auditDetail, undefined);
528
+ if (patch.allowedProfiles !== undefined)
529
+ await this.ceilings.reconcileAllowedProfilesLocked({ orgId }, "org", before.allowedProfiles.effective, nextProfiles);
530
+ const previousReach = before.projectReach.effective;
531
+ const reachChanged = patch.projectReach !== undefined && nextReach !== previousReach;
532
+ const reachTightened = narrowerProjectReach(previousReach, nextReach) !== previousReach;
533
+ if (reachChanged) {
534
+ await this.ceilings.publishLocked({ orgId }, "org", (scope) => reachTightened && reachNarrowed(scope, nextReach), !reachTightened, reachTightened);
535
+ }
536
+ }
553
537
  /** Whether prompt suggestions run for the org now: one read of the platform and of the org. */
554
538
  async promptSuggestionsEnabled(orgId) {
555
539
  const [platform, row] = await Promise.all([
@@ -617,7 +601,7 @@ let OrgSettingsService = class OrgSettingsService {
617
601
  .executeTakeFirst();
618
602
  if (!row)
619
603
  throw new ApiError("org.not_found", "Organization not found");
620
- return viewOf(this.parseStored(orgId, row.settings), row.settings);
604
+ return this.parseStored(orgId, row.settings);
621
605
  }
622
606
  /**
623
607
  * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
@@ -796,6 +780,10 @@ let OrgSettingsService = class OrgSettingsService {
796
780
  if (Object.keys(after.uiArrangement).length === 0)
797
781
  delete after.uiArrangement;
798
782
  }
783
+ if (after.allowedProfiles === undefined)
784
+ delete after.allowedProfiles;
785
+ if (after.projectReach === undefined)
786
+ delete after.projectReach;
799
787
  if (after.outsideSandbox === undefined)
800
788
  delete after.outsideSandbox;
801
789
  if (after.deviceNetwork === undefined)
@@ -829,28 +817,20 @@ let OrgSettingsService = class OrgSettingsService {
829
817
  delete after.externalSharing;
830
818
  if (after.promptSuggestions === undefined)
831
819
  delete after.promptSuggestions;
832
- // saving an unreadable security setting writes it even when it equals what it read as
833
- const repairs = (invalidStoredForbiddenTools(stored) && patch.automations?.forbiddenTools !== undefined) ||
834
- (invalidStoredSandboxToolPolicy(stored) && patch.sandboxToolPolicy !== undefined);
835
- if (!repairs && sameSettings(before, after))
836
- return viewOf(before, stored);
820
+ if (sameSettings(before, after))
821
+ return before;
837
822
  // Lock order: the org row (orgLock above), then the theme's catalog item and its row FOR
838
823
  // SHARE (assertThemeOnIn), then the check, so no scope writer changes what it read first
839
824
  if (patch.theme?.id != null && patch.theme.id !== before.theme?.id) {
840
825
  await assertThemeOnIn(this.db.db, orgId, patch.theme.id);
841
826
  }
842
827
  // Preserve unknown settings and apply cleared optional fields.
843
- const { outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
828
+ const { allowedProfiles: _oldProfiles, projectReach: _oldReach, outsideSandbox: _oldOutside, deviceNetwork: _oldNetwork, deviceDefaultProvider: _oldDeviceProvider, wakeOnBackgroundTask: _oldWake, timeZone: _oldZone, theme: _oldTheme, uiArrangement: _oldArrangement, navigation: _oldNavigation, automations: _oldAutomations, compaction: _oldCompaction, promptCache: _oldPromptCache, externalSharing: _oldExternalSharing, promptSuggestions: _oldPromptSuggestions, ...rest } = stored;
844
829
  const written = { ...rest, ...after };
845
- // An unreadable forbiddenTools reads as [] for display only: a write that does not replace the
846
- // list keeps it unreadable (never healed to "nothing forbidden"); saving the list fixes it
847
- if (invalidStoredForbiddenTools(stored) && patch.automations?.forbiddenTools === undefined) {
848
- const group = asObject(stored.automations);
849
- written.automations = {
850
- ...after.automations,
851
- forbiddenTools: group.forbiddenTools ?? null,
852
- };
853
- }
830
+ written.automations =
831
+ patch.automations === undefined && Object.hasOwn(stored, "automations")
832
+ ? stored.automations
833
+ : { ...asObject(stored.automations), ...after.automations };
854
834
  await this.db
855
835
  .updateTable("orgs")
856
836
  .set({ settings: JSON.stringify(written) })
@@ -862,7 +842,7 @@ let OrgSettingsService = class OrgSettingsService {
862
842
  orgId,
863
843
  action: "org.settings_updated",
864
844
  target: orgId,
865
- detail: { before, after, ...(repairs && { repaired: true }), ...auditDetail },
845
+ detail: { before, after, ...auditDetail },
866
846
  });
867
847
  if (patch.outsideSandbox !== undefined || patch.deviceNetwork !== undefined) {
868
848
  // the consent reset follows the effective values as every reader sees them (re-read from
@@ -898,9 +878,12 @@ let OrgSettingsService = class OrgSettingsService {
898
878
  return hostsNarrowed(scope, row, orgHosts, (host) => hostGrantable(grantCeiling, host));
899
879
  }, resetConsent);
900
880
  }
901
- return viewOf(after, written);
881
+ return after;
902
882
  }
903
883
  };
884
+ __decorate([
885
+ Transactional({ propagation: "mandatory" })
886
+ ], OrgSettingsService.prototype, "updateSecurityCeilingsLocked", null);
904
887
  __decorate([
905
888
  Transactional({ propagation: "mandatory" })
906
889
  ], OrgSettingsService.prototype, "lockFor", null);
@@ -702,7 +702,7 @@ export const PLATFORM_EXCLUSIONS = [
702
702
  {
703
703
  route: "GET /api/v1/orgs/:orgId/tools/extensions",
704
704
  category: "internal",
705
- reason: "Display list of the agent form's tools picker; extensions.tools gives an agent the same facts",
705
+ reason: "Display list for the agent form's extension tool picker; org-security.get provides the policy catalog",
706
706
  },
707
707
  {
708
708
  route: "GET /api/v1/oauth/callback",
@@ -87,6 +87,10 @@ export const PLATFORM_DOMAINS = [
87
87
  id: "channels",
88
88
  description: "The org's channel connections (IM bots): list, read without credentials, change the binding, remove.",
89
89
  },
90
+ {
91
+ id: "org-security",
92
+ description: "Review and narrow organization tool rules and device security ceilings.",
93
+ },
90
94
  {
91
95
  id: "org-settings",
92
96
  description: "The org's settings (tool search, language, sandbox policy, the Platform tool switch, the default theme): read and change.",