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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/automations/automations.service.js +15 -21
  4. package/dist/automations/effective-settings.d.ts +3 -9
  5. package/dist/automations/effective-settings.js +3 -5
  6. package/dist/automations/fire.js +0 -11
  7. package/dist/automations/grant-rules.d.ts +7 -10
  8. package/dist/automations/grant-rules.js +9 -18
  9. package/dist/automations/unattended.d.ts +1 -4
  10. package/dist/automations/unattended.js +0 -2
  11. package/dist/catalog/org-extension.controller.d.ts +1 -20
  12. package/dist/catalog/org-extension.controller.js +1 -48
  13. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  14. package/dist/catalog/org-extension.schemas.js +1 -17
  15. package/dist/config/schema.d.ts +12 -0
  16. package/dist/config/schema.js +16 -0
  17. package/dist/conversations/approval-profile.d.ts +8 -1
  18. package/dist/conversations/approval-profile.js +20 -0
  19. package/dist/conversations/conversations.service.d.ts +1 -1
  20. package/dist/conversations/conversations.service.js +8 -3
  21. package/dist/conversations/events.d.ts +25 -1
  22. package/dist/conversations/events.js +7 -2
  23. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  24. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  25. package/dist/conversations/permission-profiles.schemas.js +8 -0
  26. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  27. package/dist/conversations/permission-profiles.service.js +13 -1
  28. package/dist/db/kernel-schema.d.ts +21 -0
  29. package/dist/device-access/device-access.service.d.ts +4 -1
  30. package/dist/device-access/device-access.service.js +26 -7
  31. package/dist/device-access/viewer.d.ts +3 -1
  32. package/dist/device-access/viewer.js +18 -9
  33. package/dist/errors.d.ts +6 -0
  34. package/dist/errors.js +6 -0
  35. package/dist/git/gateway.d.ts +8 -1
  36. package/dist/git/gateway.js +68 -11
  37. package/dist/git/git.module.d.ts +2 -3
  38. package/dist/git/git.module.js +4 -4
  39. package/dist/http/api.module.js +3 -3
  40. package/dist/identity/settings.d.ts +20 -5
  41. package/dist/identity/settings.js +52 -9
  42. package/dist/infra/config/kernel-config.service.js +4 -0
  43. package/dist/orgs/orgs.module.js +12 -1
  44. package/dist/orgs/orgs.schemas.js +3 -0
  45. package/dist/orgs/security-settings.service.d.ts +94 -0
  46. package/dist/orgs/security-settings.service.js +223 -0
  47. package/dist/orgs/settings.controller.d.ts +33 -0
  48. package/dist/orgs/settings.controller.js +41 -1
  49. package/dist/orgs/settings.service.d.ts +48 -63
  50. package/dist/orgs/settings.service.js +86 -103
  51. package/dist/platform/exclusions.js +1 -1
  52. package/dist/platform/operation.js +4 -0
  53. package/dist/platform/ops/admin.ops.js +18 -4
  54. package/dist/platform/ops/connectors.ops.js +2 -2
  55. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  56. package/dist/platform/ops/extensions.ops.js +4 -131
  57. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  58. package/dist/platform/ops/org-settings.ops.js +76 -3
  59. package/dist/platform/ops/orgs.ops.js +2 -0
  60. package/dist/runtime/context/permission-profile.js +6 -0
  61. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  62. package/dist/runtime/subagents/dispatch.js +2 -1
  63. package/dist/runtime/subagents/messages.d.ts +3 -1
  64. package/dist/runtime/subagents/messages.js +9 -6
  65. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  66. package/dist/sandbox/device-sandbox-settings.js +64 -1
  67. package/dist/sandbox/device-sandbox.d.ts +9 -1
  68. package/dist/sandbox/device-sandbox.js +17 -2
  69. package/dist/sandbox/device-services.d.ts +26 -3
  70. package/dist/sandbox/device-services.js +95 -16
  71. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  72. package/dist/sandbox/loopback-grant-records.js +32 -5
  73. package/dist/sandbox/operation-authority.d.ts +3 -2
  74. package/dist/sandbox/operation-authority.js +21 -1
  75. package/dist/sandbox/operation-intents.js +5 -1
  76. package/dist/sandbox/permission-call-types.d.ts +2 -1
  77. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  78. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  79. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  80. package/dist/sandbox/permission-config-publication.js +27 -5
  81. package/dist/sandbox/permission-facts.d.ts +21 -2
  82. package/dist/sandbox/permission-facts.js +101 -9
  83. package/dist/sandbox/permission-transitions.d.ts +1 -1
  84. package/dist/sandbox/sandbox.service.d.ts +2 -2
  85. package/dist/sandbox/sandbox.service.js +7 -3
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/approvals.service.d.ts +7 -2
  88. package/dist/tools/approvals.service.js +39 -7
  89. package/dist/tools/builtin-names.d.ts +0 -6
  90. package/dist/tools/builtin-names.js +0 -11
  91. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  92. package/dist/tools/builtins/sandbox/index.js +3 -5
  93. package/dist/tools/connector-account-policies.js +7 -4
  94. package/dist/tools/connectors.controller.d.ts +0 -6
  95. package/dist/tools/connectors.schemas.d.ts +1 -8
  96. package/dist/tools/connectors.schemas.js +1 -4
  97. package/dist/tools/connectors.service.d.ts +3 -7
  98. package/dist/tools/connectors.service.js +29 -44
  99. package/dist/tools/drift.js +12 -4
  100. package/dist/tools/git-push-policy.d.ts +1 -4
  101. package/dist/tools/git-push-policy.js +4 -5
  102. package/dist/tools/org-tool-policies.d.ts +24 -0
  103. package/dist/tools/org-tool-policies.js +113 -0
  104. package/dist/tools/org-tool-switches.d.ts +5 -70
  105. package/dist/tools/org-tool-switches.js +13 -141
  106. package/dist/tools/pipeline.d.ts +11 -5
  107. package/dist/tools/pipeline.js +173 -38
  108. package/dist/tools/policy.d.ts +3 -7
  109. package/dist/tools/policy.js +29 -48
  110. package/dist/tools/registry.d.ts +5 -0
  111. package/dist/tools/registry.js +44 -13
  112. package/package.json +1 -1
  113. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -339,12 +339,16 @@ let ConversationsService = class ConversationsService {
339
339
  async create(orgId, accountId, agentId, pick = {}, opts) {
340
340
  await this.agents.get(orgId, agentId, accountId);
341
341
  const deviceId = await this.devices.forNew(orgId, accountId, pick);
342
+ const id = randomUUID();
343
+ await this.permissions.lockInitial(orgId, id, deviceId);
344
+ const profile = await this.permissions.defaultProfile(orgId);
342
345
  const project = await this.bindingFor(orgId, accountId, deviceId, pick.project);
343
346
  const row = await this.db
344
347
  .insertInto("conversations")
345
348
  .values({
346
- id: randomUUID(),
349
+ id,
347
350
  org_id: orgId,
351
+ permission_profile: profile,
348
352
  agent_id: agentId,
349
353
  account_id: accountId,
350
354
  device_id: deviceId,
@@ -429,8 +433,8 @@ let ConversationsService = class ConversationsService {
429
433
  // its own transaction: the caller notifies and publishes after the commit
430
434
  async createIn(conv, input, next, extra, invoked, internal) {
431
435
  const { id, orgId, accountId } = conv;
432
- if (internal.initialPermission)
433
- await this.permissions.lockInitial(orgId, id, conv.deviceId);
436
+ await this.permissions.lockInitial(orgId, id, conv.deviceId);
437
+ const profile = await this.permissions.defaultProfile(orgId);
434
438
  const project = await this.bindingFor(orgId, accountId, conv.deviceId, conv.project);
435
439
  // the project changed since its files were checked: the blocks would name another root
436
440
  if (extra.projectRoot !== undefined && extra.projectRoot !== project?.path) {
@@ -442,6 +446,7 @@ let ConversationsService = class ConversationsService {
442
446
  id,
443
447
  org_id: orgId,
444
448
  agent_id: conv.agentId,
449
+ permission_profile: profile,
445
450
  account_id: accountId,
446
451
  device_id: conv.deviceId,
447
452
  project_name: project?.name ?? null,
@@ -28,6 +28,10 @@ export declare const PermissionContextSandboxSchema: z.ZodObject<{
28
28
  hostsCount: z.ZodNumber;
29
29
  }, z.core.$strict>;
30
30
  outsideSandbox: z.ZodBoolean;
31
+ projectReach: z.ZodOptional<z.ZodEnum<{
32
+ paths: "paths";
33
+ workspace: "workspace";
34
+ }>>;
31
35
  outerNetwork: z.ZodDiscriminatedUnion<[z.ZodObject<{
32
36
  kind: z.ZodLiteral<"host-environment">;
33
37
  }, z.core.$strict>, z.ZodObject<{
@@ -51,6 +55,11 @@ export declare const PermissionContextV2Schema: z.ZodObject<{
51
55
  rootConversationId: z.ZodString;
52
56
  profileRevision: z.ZodNullable<z.ZodNumber>;
53
57
  selectedProfile: z.ZodNullable<z.ZodCustom<PermissionProfile, PermissionProfile>>;
58
+ allowedProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodEnum<{
59
+ "approve-for-me": "approve-for-me";
60
+ "full-access": "full-access";
61
+ "request-approval": "request-approval";
62
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>;
54
63
  effectiveProfile: z.ZodNullable<z.ZodCustom<PermissionProfile, PermissionProfile>>;
55
64
  execution: z.ZodEnum<{
56
65
  interactive: "interactive";
@@ -124,6 +133,10 @@ export declare const PermissionContextV2Schema: z.ZodObject<{
124
133
  hostsCount: z.ZodNumber;
125
134
  }, z.core.$strict>;
126
135
  outsideSandbox: z.ZodBoolean;
136
+ projectReach: z.ZodOptional<z.ZodEnum<{
137
+ paths: "paths";
138
+ workspace: "workspace";
139
+ }>>;
127
140
  outerNetwork: z.ZodDiscriminatedUnion<[z.ZodObject<{
128
141
  kind: z.ZodLiteral<"host-environment">;
129
142
  }, z.core.$strict>, z.ZodObject<{
@@ -174,7 +187,7 @@ export declare const GIT_ASK_MAX_REFS = 20;
174
187
  export declare const GIT_REF_MAX_CHARS = 255;
175
188
  /**
176
189
  * The longest `<owner>/<repo>` a git push ask carries (GitHub allows 39 + 100 characters): the
177
- * grant key `git:push:<owner>/<repo>` must fit an org's `forbiddenTools` entry (200 characters).
190
+ * grant key `git:push:<owner>/<repo>` retains its 200-character bound.
178
191
  */
179
192
  export declare const GIT_REPO_MAX_CHARS = 191;
180
193
  /** The longest deny reason (characters): the decision route's limit and `approval_decided.reason`'s. */
@@ -608,6 +621,11 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
608
621
  rootConversationId: z.ZodString;
609
622
  profileRevision: z.ZodNullable<z.ZodNumber>;
610
623
  selectedProfile: z.ZodNullable<z.ZodCustom<PermissionProfile, PermissionProfile>>;
624
+ allowedProfiles: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodEnum<{
625
+ "approve-for-me": "approve-for-me";
626
+ "full-access": "full-access";
627
+ "request-approval": "request-approval";
628
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>>;
611
629
  effectiveProfile: z.ZodNullable<z.ZodCustom<PermissionProfile, PermissionProfile>>;
612
630
  execution: z.ZodEnum<{
613
631
  interactive: "interactive";
@@ -681,6 +699,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
681
699
  hostsCount: z.ZodNumber;
682
700
  }, z.core.$strict>;
683
701
  outsideSandbox: z.ZodBoolean;
702
+ projectReach: z.ZodOptional<z.ZodEnum<{
703
+ paths: "paths";
704
+ workspace: "workspace";
705
+ }>>;
684
706
  outerNetwork: z.ZodDiscriminatedUnion<[z.ZodObject<{
685
707
  kind: z.ZodLiteral<"host-environment">;
686
708
  }, z.core.$strict>, z.ZodObject<{
@@ -808,6 +830,8 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
808
830
  actorAccountId: z.ZodNullable<z.ZodString>;
809
831
  reason: z.ZodOptional<z.ZodEnum<{
810
832
  "authority-changed": "authority-changed";
833
+ "org-profile-ceiling": "org-profile-ceiling";
834
+ "platform-profile-ceiling": "platform-profile-ceiling";
811
835
  user: "user";
812
836
  }>>;
813
837
  deviceId: z.ZodNullable<z.ZodString>;
@@ -5,6 +5,7 @@ import { AgentDefinitionSchema, DisabledSkillRef, DisabledToolRef, ModelRef, } f
5
5
  import { ORG_ROLES } from "../orgs/roles.js";
6
6
  import { coversHost } from "../sandbox/modes.js";
7
7
  import { TOOL_VIEW_DIFF_MAX_LINES, TOOL_VIEW_LINE_MAX_CHARS, TOOL_VIEW_PATH_MAX_CHARS, } from "../tools/view.js";
8
+ import { AllowedProfilesSchema } from "./permission-profiles.schemas.js";
8
9
  /** Code-point ordering is independent of the host locale and UTF-16 surrogate ordering. */
9
10
  export function permissionCodePointCompare(a, b) {
10
11
  const left = Array.from(a, (c) => c.codePointAt(0));
@@ -103,6 +104,7 @@ export const PermissionContextSandboxSchema = z
103
104
  })
104
105
  .strict(),
105
106
  outsideSandbox: z.boolean(),
107
+ projectReach: z.enum(["workspace", "paths"]).optional(),
106
108
  outerNetwork: z.discriminatedUnion("kind", [
107
109
  z.object({ kind: z.literal("host-environment") }).strict(),
108
110
  z.object({ kind: z.literal("none") }).strict(),
@@ -131,6 +133,7 @@ export const PermissionContextV2Schema = z
131
133
  rootConversationId: PermissionId,
132
134
  profileRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable(),
133
135
  selectedProfile: PermissionProfileSchema.nullable(),
136
+ allowedProfiles: AllowedProfilesSchema.optional(),
134
137
  effectiveProfile: PermissionProfileSchema.nullable(),
135
138
  execution: z.enum(["interactive", "scheduled"]),
136
139
  inherited: z.boolean(),
@@ -329,7 +332,7 @@ export const GIT_ASK_MAX_REFS = 20;
329
332
  export const GIT_REF_MAX_CHARS = 255;
330
333
  /**
331
334
  * The longest `<owner>/<repo>` a git push ask carries (GitHub allows 39 + 100 characters): the
332
- * grant key `git:push:<owner>/<repo>` must fit an org's `forbiddenTools` entry (200 characters).
335
+ * grant key `git:push:<owner>/<repo>` retains its 200-character bound.
333
336
  */
334
337
  export const GIT_REPO_MAX_CHARS = 191;
335
338
  /** The longest deny reason (characters): the decision route's limit and `approval_decided.reason`'s. */
@@ -857,7 +860,9 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
857
860
  oldProfile: z.enum(["request-approval", "approve-for-me", "full-access"]),
858
861
  newProfile: z.enum(["request-approval", "approve-for-me", "full-access"]),
859
862
  actorAccountId: z.string().nullable(),
860
- reason: z.enum(["user", "authority-changed"]).optional(),
863
+ reason: z
864
+ .enum(["user", "authority-changed", "platform-profile-ceiling", "org-profile-ceiling"])
865
+ .optional(),
861
866
  deviceId: z.string().nullable(),
862
867
  scopeRevision: z.string().nullable(),
863
868
  revision: z.number().int().nonnegative(),
@@ -66,6 +66,7 @@ export declare class PermissionProfilesController {
66
66
  get(org: OrgContext, p: Principal, { id }: z.infer<typeof PermissionGetParams>): Promise<{
67
67
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
68
68
  profile: import("@capybara-hq/plugin-sdk").PermissionProfile;
69
+ allowedProfiles: import("@capybara-hq/plugin-sdk").PermissionProfile[];
69
70
  revision: number;
70
71
  rootConversationId: string;
71
72
  deviceId: string | null;
@@ -76,6 +77,7 @@ export declare class PermissionProfilesController {
76
77
  scopeRevision: string | null;
77
78
  outsideSandboxCeiling: boolean;
78
79
  consentReach: {
80
+ projectReach?: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
79
81
  outsideSandbox: boolean;
80
82
  networkCeiling: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
81
83
  networkMode: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
@@ -93,6 +95,7 @@ export declare class PermissionProfilesController {
93
95
  scopeRevision: string;
94
96
  consentIdentity: string;
95
97
  consentReach: {
98
+ projectReach?: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
96
99
  outsideSandbox: boolean;
97
100
  networkCeiling: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
98
101
  networkMode: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
@@ -100,6 +103,7 @@ export declare class PermissionProfilesController {
100
103
  };
101
104
  sandbox: import("../sandbox/device-sandbox.js").DeviceSandbox;
102
105
  outsideSandboxCeiling: boolean;
106
+ allowedProfiles: import("@capybara-hq/plugin-sdk").PermissionProfile[];
103
107
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
104
108
  }>;
105
109
  first(org: OrgContext, p: Principal, body: z.infer<typeof FirstMessageBody>, reply: FastifyReply): Promise<{
@@ -4,6 +4,11 @@ export declare const PermissionProfileSchema: z.ZodEnum<{
4
4
  "full-access": "full-access";
5
5
  "request-approval": "request-approval";
6
6
  }>;
7
+ export declare const AllowedProfilesSchema: z.ZodPipe<z.ZodArray<z.ZodEnum<{
8
+ "approve-for-me": "approve-for-me";
9
+ "full-access": "full-access";
10
+ "request-approval": "request-approval";
11
+ }>>, z.ZodTransform<("approve-for-me" | "full-access" | "request-approval")[], ("approve-for-me" | "full-access" | "request-approval")[]>>;
7
12
  export declare const PermissionSelectionSchema: z.ZodObject<{
8
13
  profile: z.ZodEnum<{
9
14
  "approve-for-me": "approve-for-me";
@@ -5,6 +5,14 @@ export const PermissionProfileSchema = z.enum([
5
5
  "approve-for-me",
6
6
  "full-access",
7
7
  ]);
8
+ export const AllowedProfilesSchema = z
9
+ .array(PermissionProfileSchema)
10
+ .min(1)
11
+ .max(PermissionProfileSchema.options.length)
12
+ .refine((profiles) => profiles.includes("request-approval") && new Set(profiles).size === profiles.length, {
13
+ message: "Include Request approval and list each profile once",
14
+ })
15
+ .transform((profiles) => PermissionProfileSchema.options.filter((profile) => profiles.includes(profile)));
8
16
  export const PermissionSelectionSchema = z
9
17
  .object({
10
18
  profile: PermissionProfileSchema,
@@ -1,3 +1,4 @@
1
+ import type { PermissionProfile } from "@capybara-hq/plugin-sdk";
1
2
  import { DeviceAccess } from "../devices/access.js";
2
3
  import { KernelDb } from "../infra/database/kernel-db.js";
3
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -26,6 +27,7 @@ export declare class PermissionProfilesService {
26
27
  scopeRevision: string;
27
28
  consentIdentity: string;
28
29
  consentReach: {
30
+ projectReach?: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
29
31
  outsideSandbox: boolean;
30
32
  networkCeiling: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
31
33
  networkMode: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
@@ -33,11 +35,13 @@ export declare class PermissionProfilesService {
33
35
  };
34
36
  sandbox: import("../sandbox/device-sandbox.js").DeviceSandbox;
35
37
  outsideSandboxCeiling: boolean;
38
+ allowedProfiles: PermissionProfile[];
36
39
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
37
40
  }>;
38
41
  get(orgId: string, id: string, accountId: string): Promise<{
39
42
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
40
- profile: import("@capybara-hq/plugin-sdk").PermissionProfile;
43
+ profile: PermissionProfile;
44
+ allowedProfiles: PermissionProfile[];
41
45
  revision: number;
42
46
  rootConversationId: string;
43
47
  deviceId: string | null;
@@ -48,6 +52,7 @@ export declare class PermissionProfilesService {
48
52
  scopeRevision: string | null;
49
53
  outsideSandboxCeiling: boolean;
50
54
  consentReach: {
55
+ projectReach?: import("@capybara-hq/plugin-sdk").DeviceProjectReach;
51
56
  outsideSandbox: boolean;
52
57
  networkCeiling: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
53
58
  networkMode: "none" | import("../sandbox/device-sandbox.js").DeviceNetworkMode;
@@ -56,6 +61,8 @@ export declare class PermissionProfilesService {
56
61
  sandbox: import("../sandbox/device-sandbox.js").DeviceSandbox | null;
57
62
  startingWorkNotice: string;
58
63
  }>;
64
+ defaultProfile(orgId: string): Promise<PermissionProfile>;
65
+ private assertAllowed;
59
66
  /** Reserve the root ID and authority before resolving its project or inserting first-send state. */
60
67
  lockInitial(orgId: string, id: string, deviceId: string | null): Promise<void>;
61
68
  initialize(orgId: string, id: string, accountId: string, deviceId: string | null, projectPath: string | null, project: string | null, selection: PermissionSelection): Promise<ConversationEvent[]>;
@@ -47,6 +47,15 @@ let PermissionProfilesService = class PermissionProfilesService {
47
47
  async get(orgId, id, accountId) {
48
48
  return this.facts.peopleView(orgId, accountId, await this.store.readOwnedRoot(orgId, id, accountId));
49
49
  }
50
+ async defaultProfile(orgId) {
51
+ return (await this.facts.allowedProfiles(orgId)).includes("approve-for-me")
52
+ ? "approve-for-me"
53
+ : "request-approval";
54
+ }
55
+ async assertAllowed(orgId, profile) {
56
+ if (!(await this.facts.allowedProfiles(orgId)).includes(profile))
57
+ throw new ApiError("org.permission_profile_not_allowed", "This permission profile is not available in the organization. Choose an allowed profile.");
58
+ }
50
59
  /** Reserve the root ID and authority before resolving its project or inserting first-send state. */
51
60
  async lockInitial(orgId, id, deviceId) {
52
61
  const subject = { orgId, rootConversationId: id, ...(deviceId ? { deviceId } : {}) };
@@ -56,6 +65,8 @@ let PermissionProfilesService = class PermissionProfilesService {
56
65
  const subject = { orgId, rootConversationId: id, ...(deviceId ? { deviceId } : {}) };
57
66
  await this.locks.acquire(subject, { kind: "write", level: "root" });
58
67
  await this.epochs.readLocked(subject);
68
+ await this.assertAllowed(orgId, selection.profile);
69
+ const oldProfile = await this.defaultProfile(orgId);
59
70
  const consent = await this.consent(orgId, accountId, deviceId, projectPath, project, selection);
60
71
  await this.db
61
72
  .updateTable("conversations")
@@ -67,7 +78,7 @@ let PermissionProfilesService = class PermissionProfilesService {
67
78
  .where("org_id", "=", orgId)
68
79
  .execute();
69
80
  const detail = {
70
- oldProfile: "approve-for-me",
81
+ oldProfile,
71
82
  newProfile: selection.profile,
72
83
  actorAccountId: accountId,
73
84
  deviceId,
@@ -139,6 +150,7 @@ let PermissionProfilesService = class PermissionProfilesService {
139
150
  throw new ApiError("conflict", "The conversation binding changed; refresh and retry");
140
151
  if (row.permission_revision !== body.expectedRevision)
141
152
  throw new ApiError("conflict", "Permissions changed; refresh and retry");
153
+ await this.assertAllowed(orgId, body.profile);
142
154
  const consent = await this.consent(orgId, accountId, row.device_id, row.project_path, row.project_name, body);
143
155
  const epochs = await this.epochs.readLocked(subject);
144
156
  await this.epochs.bumpLocked("root", id, epochs.root ?? 0);
@@ -307,6 +307,23 @@ export interface OrgToolSwitchesTable {
307
307
  updated_by: string | null;
308
308
  updated_at: Ts;
309
309
  }
310
+ /** Organization policy for a canonical tool or named per-call key. */
311
+ export interface OrgToolPoliciesTable {
312
+ org_id: string;
313
+ tool_key: string;
314
+ policy: "allow" | "ask" | "deny";
315
+ unattended_policy: "allow" | "ask" | "deny";
316
+ row_revision: Generated<string>;
317
+ updated_by: string | null;
318
+ updated_at: Ts;
319
+ }
320
+ export interface OrgGitPushDenialsTable {
321
+ org_id: string;
322
+ /** A normalized owner/repository, or '*' for all repositories. */
323
+ target: string;
324
+ updated_by: string | null;
325
+ updated_at: Ts;
326
+ }
310
327
  /** 0145: an internal endpoint a super admin lets the org's extension requests reach. */
311
328
  export interface OrgNetworkAllowancesTable {
312
329
  id: string;
@@ -697,6 +714,8 @@ export interface ConnectorToolsTable {
697
714
  spec_hash: string;
698
715
  status: "enabled" | "disabled" | "pending_review";
699
716
  default_policy: "allow" | "ask" | "deny";
717
+ /** The baseline kept independently of a migrated connector admin override. */
718
+ declaration_policy: Generated<"allow" | "ask" | "deny" | null>;
700
719
  reviewed_at: TsNullable;
701
720
  /** 0013:工具来源(`resources` = 内核为支持 resources 的连接器补上的两个工具)。 */
702
721
  source: Generated<"connector" | "resources">;
@@ -1937,6 +1956,8 @@ export interface KernelDatabase {
1937
1956
  extension_org_configs: ExtensionOrgConfigsTable;
1938
1957
  extension_org_overrides: ExtensionOrgOverridesTable;
1939
1958
  org_tool_switches: OrgToolSwitchesTable;
1959
+ org_tool_policies: OrgToolPoliciesTable;
1960
+ org_git_push_denials: OrgGitPushDenialsTable;
1940
1961
  org_network_allowances: OrgNetworkAllowancesTable;
1941
1962
  audit_events: AuditEventsTable;
1942
1963
  secrets: SecretsTable;
@@ -1,4 +1,4 @@
1
- import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type SiteAccessAction, type SiteAccessAsk, type SiteGrantView, type ToolCallContext } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceAccessScope, type DeviceProjectReach, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type SiteAccessAction, type SiteAccessAsk, type SiteGrantView, type ToolCallContext } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { DeviceAccess } from "../devices/access.js";
4
4
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -32,6 +32,8 @@ export interface DeviceStreamTicket {
32
32
  rootConversationId: string;
33
33
  deviceId: string;
34
34
  providerName: string;
35
+ /** The ceiling under which the viewer was issued (absent at the default machine ceiling). */
36
+ projectReach?: DeviceProjectReach;
35
37
  service: string;
36
38
  extension: string;
37
39
  }
@@ -83,6 +85,7 @@ export declare class DeviceAccessService {
83
85
  /** A panel grant settles the agent's pending ask for the same port. */
84
86
  approvals: Pick<ApprovalsService, "settleLoopbackAsks">, site: DeviceSiteGrants);
85
87
  private get db();
88
+ private recordAuthorizedServiceLaunch;
86
89
  /**
87
90
  * Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
88
91
  * (never starts anything): a running service is kept with no review. A stopped one is
@@ -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 { randomBytes } from "node:crypto";
11
- import { DEVICE_SERVICE_ROLL_CHECK, DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, isLoopbackGrantHost, parseRollCheck, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_SERVICE_ROLL_CHECK, DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, isLoopbackGrantHost, narrowerProjectReach, parseRollCheck, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { unattendedRunOf } from "../automations/unattended.js";
@@ -139,6 +139,15 @@ let DeviceAccessService = class DeviceAccessService {
139
139
  get db() {
140
140
  return this.kdb.db;
141
141
  }
142
+ async recordAuthorizedServiceLaunch(call, deviceId, serviceId) {
143
+ await audit(this.db, {
144
+ actorAccountId: call.accountId,
145
+ orgId: call.orgId,
146
+ action: "device.service_launch_authorized",
147
+ target: deviceId,
148
+ detail: { serviceId },
149
+ });
150
+ }
142
151
  /**
143
152
  * Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
144
153
  * (never starts anything): a running service is kept with no review. A stopped one is
@@ -250,6 +259,9 @@ let DeviceAccessService = class DeviceAccessService {
250
259
  if (raced.state === "running" &&
251
260
  (await this.holdRoll(caller, use, providerSpec.name, name, digest, call.signal)))
252
261
  return raced;
262
+ // Record the reviewed launch before asking the provider. A ceiling writer can then refresh
263
+ // this service even if the caller stops after the device starts it and before recording success.
264
+ await this.recordAuthorizedServiceLaunch(call, use.deviceId, providerSpec.name);
253
265
  const started = await ensure(false);
254
266
  // a provider that reports the digest but kept the old files would have every later call
255
267
  // reviewed again for nothing: a broken provider, said as such
@@ -675,6 +687,7 @@ let DeviceAccessService = class DeviceAccessService {
675
687
  if (!this.providers.forDevice(d.provider)?.impl.openStream)
676
688
  throw new DeviceAccessError("capability_missing", "This device's provider cannot open streams to device services; choose a device on a provider that supports them.");
677
689
  const id = randomBytes(24).toString("base64url");
690
+ const projectReach = await this.services.projectReachCeiling(d.orgId, d.deviceId);
678
691
  const record = {
679
692
  orgId: d.orgId,
680
693
  accountId: scope.accountId,
@@ -682,6 +695,7 @@ let DeviceAccessService = class DeviceAccessService {
682
695
  rootConversationId: d.rootConversationId,
683
696
  deviceId: d.deviceId,
684
697
  providerName: d.provider,
698
+ ...(projectReach !== "machine" && { projectReach }),
685
699
  service,
686
700
  extension: caller.extension,
687
701
  };
@@ -721,12 +735,14 @@ let DeviceAccessService = class DeviceAccessService {
721
735
  return "revoked";
722
736
  try {
723
737
  const d = await this.scopedDevice({ extension: t.extension, services: [t.service], loopbackPorts: false }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
724
- return d.orgId === t.orgId &&
725
- d.rootConversationId === t.rootConversationId &&
726
- d.deviceId === t.deviceId &&
727
- d.provider === t.providerName
728
- ? "stands"
729
- : "revoked";
738
+ if (d.orgId !== t.orgId ||
739
+ d.rootConversationId !== t.rootConversationId ||
740
+ d.deviceId !== t.deviceId ||
741
+ d.provider !== t.providerName)
742
+ return "revoked";
743
+ const currentReach = await this.services.projectReachCeiling(d.orgId, d.deviceId);
744
+ const ticketReach = t.projectReach ?? "machine";
745
+ return narrowerProjectReach(currentReach, ticketReach) === ticketReach ? "stands" : "revoked";
730
746
  }
731
747
  catch (e) {
732
748
  if (e instanceof DeviceAccessError)
@@ -905,6 +921,9 @@ let DeviceAccessService = class DeviceAccessService {
905
921
  return rootConversationOf(this.db, conversationId);
906
922
  }
907
923
  };
924
+ __decorate([
925
+ Transactional({ propagation: "requires_new" })
926
+ ], DeviceAccessService.prototype, "recordAuthorizedServiceLaunch", null);
908
927
  __decorate([
909
928
  Transactional()
910
929
  ], DeviceAccessService.prototype, "grantInTx", null);
@@ -6,6 +6,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
6
  import { KernelDb } from "../infra/database/kernel-db.js";
7
7
  import { LockService } from "../infra/lock/lock.service.js";
8
8
  import type { KernelLogger } from "../log.js";
9
+ import { DeviceServices } from "../sandbox/device-services.js";
9
10
  import { SandboxService } from "../sandbox/sandbox.service.js";
10
11
  import { DeviceAccessService, type DeviceStreamTicket } from "./device-access.service.js";
11
12
  /**
@@ -189,6 +190,7 @@ export declare function parseTicketRecord(raw: unknown): DeviceStreamTicket | nu
189
190
  export declare class DeviceStreamViewers {
190
191
  private readonly access;
191
192
  private readonly sandbox;
193
+ private readonly services;
192
194
  private readonly gateway;
193
195
  private readonly handlers;
194
196
  private readonly kdb;
@@ -206,7 +208,7 @@ export declare class DeviceStreamViewers {
206
208
  pausedLimitMs: number;
207
209
  /** {@link VIEWER_RECHECK_MS} (a test seam). */
208
210
  recheckMs: number;
209
- constructor(access: Pick<DeviceAccessService, "takeTicket" | "ticketCheck">, sandbox: Pick<SandboxService, "holdForStream">, gateway: Pick<DialInGateway, "holdsLocally" | "holderAddress">, handlers: Pick<DialInHandlers, "forDevice">, kdb: KernelDb, locks: Pick<LockService, "lease">, keyring: Keyring, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "debug" | "warn">);
211
+ constructor(access: Pick<DeviceAccessService, "takeTicket" | "ticketCheck">, sandbox: Pick<SandboxService, "holdForStream">, services: Pick<DeviceServices, "withConfirmedReach">, gateway: Pick<DialInGateway, "holdsLocally" | "holderAddress">, handlers: Pick<DialInHandlers, "forDevice">, kdb: KernelDb, locks: Pick<LockService, "lease">, keyring: Keyring, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "debug" | "warn">);
210
212
  /** {@link verifyHopHeaders} under this kernel's keys, now. */
211
213
  verifyHop(ticketId: string, mac: unknown, at: unknown): boolean;
212
214
  /** How a viewer or hop socket is watched (`maxMessageBytes` for sockets carrying input). */
@@ -20,6 +20,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
20
20
  import { withOrgScope } from "../infra/database/org-scope.js";
21
21
  import { LockService } from "../infra/lock/lock.service.js";
22
22
  import { KERNEL_LOGGER, KEYRING } from "../infra/tokens.js";
23
+ import { DeviceServices } from "../sandbox/device-services.js";
23
24
  import { SandboxService } from "../sandbox/sandbox.service.js";
24
25
  import { DeviceAccessService } from "./device-access.service.js";
25
26
  /**
@@ -363,6 +364,9 @@ export function parseTicketRecord(raw) {
363
364
  for (const k of keys)
364
365
  if (typeof r[k] !== "string" || r[k] === "")
365
366
  return null;
367
+ const reach = r.projectReach;
368
+ if (reach !== undefined && reach !== "workspace" && reach !== "paths" && reach !== "machine")
369
+ return null;
366
370
  return {
367
371
  orgId: r.orgId,
368
372
  accountId: r.accountId,
@@ -370,6 +374,7 @@ export function parseTicketRecord(raw) {
370
374
  rootConversationId: r.rootConversationId,
371
375
  deviceId: r.deviceId,
372
376
  providerName: r.providerName,
377
+ ...(reach !== undefined && { projectReach: reach }),
373
378
  service: r.service,
374
379
  extension: r.extension,
375
380
  };
@@ -416,6 +421,7 @@ export function parseTicketRecord(raw) {
416
421
  let DeviceStreamViewers = class DeviceStreamViewers {
417
422
  access;
418
423
  sandbox;
424
+ services;
419
425
  gateway;
420
426
  handlers;
421
427
  kdb;
@@ -433,9 +439,10 @@ let DeviceStreamViewers = class DeviceStreamViewers {
433
439
  pausedLimitMs = VIEWER_PAUSED_LIMIT_MS;
434
440
  /** {@link VIEWER_RECHECK_MS} (a test seam). */
435
441
  recheckMs = VIEWER_RECHECK_MS;
436
- constructor(access, sandbox, gateway, handlers, kdb, locks, keyring, config, log) {
442
+ constructor(access, sandbox, services, gateway, handlers, kdb, locks, keyring, config, log) {
437
443
  this.access = access;
438
444
  this.sandbox = sandbox;
445
+ this.services = services;
439
446
  this.gateway = gateway;
440
447
  this.handlers = handlers;
441
448
  this.kdb = kdb;
@@ -675,7 +682,8 @@ let DeviceStreamViewers = class DeviceStreamViewers {
675
682
  let stream;
676
683
  try {
677
684
  // the provider knows the service by its id: the ticket's extension and service name
678
- stream = await hold.p.openStream(hold.h, { service: deviceServiceId(record.extension, record.service) }, hold.signal);
685
+ const service = deviceServiceId(record.extension, record.service);
686
+ stream = await this.services.withConfirmedReach(record.orgId, record.deviceId, service, hold.h, hold.p, hold.signal, () => hold.p.openStream(hold.h, { service }, hold.signal));
679
687
  }
680
688
  catch (err) {
681
689
  await hold.release();
@@ -844,13 +852,14 @@ DeviceStreamViewers = __decorate([
844
852
  Injectable(),
845
853
  __param(0, Inject(DeviceAccessService)),
846
854
  __param(1, Inject(SandboxService)),
847
- __param(2, Inject(DialInGateway)),
848
- __param(3, Inject(DialInHandlers)),
849
- __param(4, Inject(KernelDb)),
850
- __param(5, Inject(LockService)),
851
- __param(6, Inject(KEYRING)),
852
- __param(7, Inject(KernelConfigService)),
853
- __param(8, Inject(KERNEL_LOGGER))
855
+ __param(2, Inject(DeviceServices)),
856
+ __param(3, Inject(DialInGateway)),
857
+ __param(4, Inject(DialInHandlers)),
858
+ __param(5, Inject(KernelDb)),
859
+ __param(6, Inject(LockService)),
860
+ __param(7, Inject(KEYRING)),
861
+ __param(8, Inject(KernelConfigService)),
862
+ __param(9, Inject(KERNEL_LOGGER))
854
863
  ], DeviceStreamViewers);
855
864
  export { DeviceStreamViewers };
856
865
  const isElsewhere = (e) => typeof e === "object" &&
package/dist/errors.d.ts CHANGED
@@ -68,6 +68,11 @@ export declare const ERROR_CODES: {
68
68
  * through an API token or the Platform tool.
69
69
  */
70
70
  readonly "org.network_not_allowed": 400;
71
+ readonly "org.security_ceiling_not_allowed": 400;
72
+ readonly "org.security_widening_not_allowed": 403;
73
+ readonly "org.security_revision_conflict": 409;
74
+ readonly "org.security_confirmation_required": 409;
75
+ readonly "org.permission_profile_not_allowed": 400;
71
76
  /** The org's default device provider names an extension that is not a `device-provider@1` provider on in the org. */
72
77
  readonly "org.device_provider_not_available": 400;
73
78
  /** An org network allowance entry that is malformed, names a link-local address, or is over the cap. */
@@ -91,6 +96,7 @@ export declare const ERROR_CODES: {
91
96
  * token or the Platform tool.
92
97
  */
93
98
  readonly "deployment.network_not_allowed": 400;
99
+ readonly "deployment.security_widen_not_allowed": 400;
94
100
  /** Allowing external sharing at the platform level through an API token or the Platform tool. */
95
101
  readonly "deployment.external_sharing_not_allowed": 400;
96
102
  /**
package/dist/errors.js CHANGED
@@ -68,6 +68,11 @@ export const ERROR_CODES = {
68
68
  * through an API token or the Platform tool.
69
69
  */
70
70
  "org.network_not_allowed": 400,
71
+ "org.security_ceiling_not_allowed": 400,
72
+ "org.security_widening_not_allowed": 403,
73
+ "org.security_revision_conflict": 409,
74
+ "org.security_confirmation_required": 409,
75
+ "org.permission_profile_not_allowed": 400,
71
76
  /** The org's default device provider names an extension that is not a `device-provider@1` provider on in the org. */
72
77
  "org.device_provider_not_available": 400,
73
78
  /** An org network allowance entry that is malformed, names a link-local address, or is over the cap. */
@@ -91,6 +96,7 @@ export const ERROR_CODES = {
91
96
  * token or the Platform tool.
92
97
  */
93
98
  "deployment.network_not_allowed": 400,
99
+ "deployment.security_widen_not_allowed": 400,
94
100
  /** Allowing external sharing at the platform level through an API token or the Platform tool. */
95
101
  "deployment.external_sharing_not_allowed": 400,
96
102
  /**
@@ -3,7 +3,9 @@ import type { Redis } from "ioredis";
3
3
  import type { KernelConfig } from "../config/schema.js";
4
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
+ import { TransactionHost } from "../infra/database/transaction-host.js";
6
7
  import type { KernelLogger } from "../log.js";
8
+ import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
7
9
  import { Credentials } from "../tools/credentials.js";
8
10
  import { GitSources } from "./sources.js";
9
11
  import { GitTickets } from "./tickets.js";
@@ -62,18 +64,21 @@ export declare class GitGateway {
62
64
  private readonly sources;
63
65
  private readonly credentials;
64
66
  private readonly db;
67
+ readonly txHost: TransactionHost;
68
+ private readonly authority;
65
69
  private readonly redis;
66
70
  /** Read per request: `tools.git.*` is read live. */
67
71
  private readonly config;
68
72
  private readonly log;
69
73
  private readonly upstreamOrigin?;
70
- constructor(tickets: Pick<GitTickets, "resolve">, sources: Pick<GitSources, "sourcesFor">, credentials: Pick<Credentials, "gitAuthorization" | "gitUnauthorized">, db: KernelDb, redis: Redis,
74
+ constructor(tickets: Pick<GitTickets, "resolve">, sources: Pick<GitSources, "sourcesFor">, credentials: Pick<Credentials, "gitAuthorization" | "gitUnauthorized">, db: KernelDb, txHost: TransactionHost, authority: PermissionAuthorityLock, redis: Redis,
71
75
  /** Read per request: `tools.git.*` is read live. */
72
76
  config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "info" | "warn" | "debug">, upstreamOrigin?: GitUpstreamOrigin | undefined);
73
77
  /** `message` as git prints it from this gateway: with the platform name before it. */
74
78
  says(message: string): string;
75
79
  /** Handles one gateway request (the raw route's handler). */
76
80
  handle(req: FastifyRequest, reply: FastifyReply): Promise<void>;
81
+ private handleBound;
77
82
  /** The `git.push` audit row of a receive-pack and the run's fetch counters (best effort). */
78
83
  private afterRequest;
79
84
  /**
@@ -84,6 +89,8 @@ export declare class GitGateway {
84
89
  private acquireOrgSlot;
85
90
  private done;
86
91
  private relay;
92
+ /** Commit the push intent under the same authority lock as an org security edit. */
93
+ private admitPush;
87
94
  /** The push decision for this target (spec §7). */
88
95
  private decide;
89
96
  /**