@capybara-hq/kernel 0.1.0-rc.146 → 0.1.0-rc.148

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 (172) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +2 -0
  34. package/dist/catalog/provenance.js +5 -1
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/net.d.ts +5 -1
  45. package/dist/ctx/net.js +62 -12
  46. package/dist/db/kernel-schema.d.ts +31 -0
  47. package/dist/db/migrator.js +0 -36
  48. package/dist/dial-in/routes.js +1 -1
  49. package/dist/erasure/org-batches.js +1 -6
  50. package/dist/erasure/org-catalog.js +6 -2
  51. package/dist/erasure/org-rules.js +1 -0
  52. package/dist/erasure/org-worker.js +0 -13
  53. package/dist/errors.d.ts +6 -0
  54. package/dist/errors.js +6 -0
  55. package/dist/extensions/admin-ops.d.ts +14 -1
  56. package/dist/extensions/admin-ops.js +30 -3
  57. package/dist/extensions/admin-view.d.ts +21 -1
  58. package/dist/extensions/admin-view.js +43 -0
  59. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  60. package/dist/extensions/bootstrap-packages.js +1 -1
  61. package/dist/extensions/bootstrap-review.d.ts +251 -0
  62. package/dist/extensions/bootstrap-review.js +676 -0
  63. package/dist/extensions/bootstrap.d.ts +21 -1
  64. package/dist/extensions/bootstrap.js +72 -2
  65. package/dist/extensions/cli.d.ts +6 -0
  66. package/dist/extensions/cli.js +4 -0
  67. package/dist/extensions/enabled.d.ts +3 -0
  68. package/dist/extensions/extensions.module.js +9 -0
  69. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  70. package/dist/extensions/full-access-disclosure.js +57 -0
  71. package/dist/extensions/grant-epoch.d.ts +5 -0
  72. package/dist/extensions/grant-epoch.js +9 -0
  73. package/dist/extensions/host.d.ts +71 -2
  74. package/dist/extensions/host.js +293 -27
  75. package/dist/extensions/installs.d.ts +18 -0
  76. package/dist/extensions/installs.js +28 -0
  77. package/dist/extensions/isolated/admission.d.ts +17 -2
  78. package/dist/extensions/isolated/admission.js +18 -8
  79. package/dist/extensions/isolated/authorization.d.ts +8 -2
  80. package/dist/extensions/isolated/authorization.js +11 -3
  81. package/dist/extensions/isolated/broker.d.ts +3 -0
  82. package/dist/extensions/isolated/broker.js +50 -14
  83. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  84. package/dist/extensions/isolated/configured-package.js +2 -0
  85. package/dist/extensions/isolated/lanes.d.ts +44 -3
  86. package/dist/extensions/isolated/lanes.js +263 -80
  87. package/dist/extensions/isolated/metrics.d.ts +146 -0
  88. package/dist/extensions/isolated/metrics.js +304 -0
  89. package/dist/extensions/isolated/revision.d.ts +7 -1
  90. package/dist/extensions/isolated/revision.js +26 -5
  91. package/dist/extensions/isolated/rpc.d.ts +5 -0
  92. package/dist/extensions/isolated/rpc.js +7 -2
  93. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  94. package/dist/extensions/isolated/sandbox.js +50 -0
  95. package/dist/extensions/isolated/status.d.ts +79 -0
  96. package/dist/extensions/isolated/status.js +216 -0
  97. package/dist/extensions/isolated/tier.d.ts +127 -2
  98. package/dist/extensions/isolated/tier.js +266 -7
  99. package/dist/extensions/isolated/usage.d.ts +134 -0
  100. package/dist/extensions/isolated/usage.js +322 -0
  101. package/dist/extensions/lifecycle.d.ts +42 -2
  102. package/dist/extensions/lifecycle.js +100 -4
  103. package/dist/extensions/org-config.js +11 -0
  104. package/dist/extensions/package.d.ts +14 -0
  105. package/dist/extensions/package.js +24 -3
  106. package/dist/extensions/permission-set.d.ts +12 -3
  107. package/dist/extensions/permission-set.js +5 -5
  108. package/dist/extensions/permission-view.d.ts +12 -5
  109. package/dist/extensions/permission-view.js +23 -2
  110. package/dist/extensions/permissions.controller.d.ts +35 -0
  111. package/dist/extensions/permissions.controller.js +98 -0
  112. package/dist/extensions/permissions.schemas.d.ts +288 -0
  113. package/dist/extensions/permissions.schemas.js +96 -0
  114. package/dist/extensions/permissions.service.d.ts +116 -0
  115. package/dist/extensions/permissions.service.js +428 -0
  116. package/dist/extensions/realm-retirement.d.ts +65 -0
  117. package/dist/extensions/realm-retirement.js +150 -0
  118. package/dist/extensions/revision-approvals.d.ts +58 -3
  119. package/dist/extensions/revision-approvals.js +135 -14
  120. package/dist/extensions/revision-review.d.ts +144 -0
  121. package/dist/extensions/revision-review.js +297 -0
  122. package/dist/extensions/revocation.js +3 -0
  123. package/dist/extensions/state.module.js +12 -0
  124. package/dist/git/run-end.d.ts +35 -7
  125. package/dist/git/run-end.js +87 -38
  126. package/dist/http/api.module.js +2 -0
  127. package/dist/identity/audit.d.ts +2 -1
  128. package/dist/identity/audit.js +4 -17
  129. package/dist/index.d.ts +6 -2
  130. package/dist/index.js +6 -2
  131. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  132. package/dist/infra/config/kernel-config.service.js +21 -0
  133. package/dist/infra/outbox/registry.d.ts +13 -0
  134. package/dist/infra/outbox/registry.js +8 -0
  135. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  136. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  137. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  138. package/dist/net/private-endpoint-preflight.js +417 -0
  139. package/dist/net/private-endpoints.d.ts +68 -0
  140. package/dist/net/private-endpoints.js +164 -0
  141. package/dist/net/public-address.d.ts +14 -0
  142. package/dist/net/public-address.js +15 -1
  143. package/dist/net/safe-fetch.d.ts +2 -1
  144. package/dist/net/safe-fetch.js +10 -3
  145. package/dist/overrides.d.ts +4 -0
  146. package/dist/overrides.js +2 -0
  147. package/dist/packages/official-publisher.d.ts +26 -1
  148. package/dist/packages/official-publisher.js +48 -1
  149. package/dist/packages/provenance.d.ts +11 -0
  150. package/dist/packages/provenance.js +24 -0
  151. package/dist/platform/exclusions.js +4 -4
  152. package/dist/platform/ops/automations.ops.js +1 -1
  153. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  154. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  155. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  156. package/dist/platform/platform-ops.module.d.ts +2 -1
  157. package/dist/platform/platform-ops.module.js +2 -0
  158. package/dist/platform/route-schemas.js +2 -0
  159. package/dist/retention/purge-batch.js +10 -14
  160. package/dist/runtime/maintenance.d.ts +4 -2
  161. package/dist/runtime/maintenance.js +16 -3
  162. package/dist/runtime/run-finish.d.ts +3 -3
  163. package/dist/runtime/run-finish.js +7 -3
  164. package/dist/sandbox/permission-availability.d.ts +17 -2
  165. package/dist/sandbox/permission-availability.js +22 -1
  166. package/dist/sandbox/permission-facts.js +7 -1
  167. package/dist/tools/builtins/sandbox/common.js +2 -0
  168. package/dist/tools/pipeline.d.ts +2 -1
  169. package/dist/tools/pipeline.js +7 -2
  170. package/package.json +4 -3
  171. package/src/migrations/0238_extension_usage.sql +40 -0
  172. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,96 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The shared schemas of the extension permission routes (extension permission model spec,
4
+ * "Review, updates and provenance", "Revocation, audit and people"; plan tasks 1.4a and 1.4j).
5
+ * Requests are zod schemas, used by the controller and by the Platform operations (the parity
6
+ * test compares them); responses are the exported view types. The web (1.4d / 1.4e / 1.4k) and
7
+ * the CLI (1.4f) build against both.
8
+ *
9
+ * Routes (all super admin):
10
+ * - `GET /api/v1/admin/extension-permissions`: the inventory, one {@link PermissionInventoryEntry}
11
+ * per install record ({@link PermissionInventory}).
12
+ * - `GET /api/v1/admin/extension-permissions/:name/review`: the permission review of the
13
+ * install's current revision ({@link PermissionReviewView}). Its Platform operation returns a
14
+ * handoff link card to the web confirm page.
15
+ * - `POST /api/v1/admin/extension-permissions/:name/approve`: a person confirms that review
16
+ * ({@link PermissionApproveBody}), full access included with one acknowledgement per realm. It
17
+ * is a `human security consent` exclusion of the Platform tool and is refused unattended. Returns
18
+ * {@link PermissionApproveResult}.
19
+ * - `POST /api/v1/admin/extension-permissions/:name/revoke`: revokes keys of a revision's grant,
20
+ * or the whole grant ({@link PermissionRevokeBody}); revocation only narrows, so the Platform
21
+ * tool may do it. Returns {@link PermissionRevokeResult}.
22
+ * - `GET /api/v1/admin/extension-isolation`: the isolation status ({@link IsolationStatus}).
23
+ *
24
+ * The catalog import and import-and-update confirms take the same
25
+ * {@link FullAccessAcknowledgementBody} (`catalog/admin-catalog.schemas.ts`).
26
+ */
27
+ /** An extension name as the routes take it (`@Param`). */
28
+ export const PermissionNamePathParams = z.object({ name: z.string().min(1).max(64) });
29
+ const Realm = z.enum(["server", "browser", "device"]);
30
+ /** `review:v1:<sha256 hex>`, the hash of a revision's permission review (1.2e). */
31
+ const ReviewHash = z.string().regex(/^review:v1:[0-9a-f]{64}$/);
32
+ /** One exact revision of the named extension: its version and the archive's lowercase sha512. */
33
+ export const PermissionRevisionBody = z
34
+ .object({
35
+ version: z.string().min(1).max(256),
36
+ sha512: z.string().regex(/^[0-9a-f]{128}$/),
37
+ })
38
+ .strict();
39
+ /**
40
+ * One explicit acknowledgement per realm whose full access a permission review confers, bound to
41
+ * that review's hash (plan task 1.3d): `reviewHash` is the review's `hash`, `realms` exactly its
42
+ * `acknowledge`. A wrong one is refused (409 `plugin.full_access_ack_invalid`).
43
+ */
44
+ export const FullAccessAcknowledgementBody = z
45
+ .object({
46
+ reviewHash: z.string().min(1).max(128),
47
+ realms: z.array(Realm).max(3),
48
+ })
49
+ .strict();
50
+ /**
51
+ * `POST …/:name/approve`: confirms the review `GET …/:name/review` returned for `revision`. The
52
+ * install must still run that revision and the review must still hash to `reviewHash` (else 409
53
+ * `extension.permission_review_stale`). A review that confers full access records its revision
54
+ * grant only with `fullAccessAcknowledgement` naming exactly its realms: a wrong one is refused
55
+ * (409 `plugin.full_access_ack_invalid`), a missing one returns 200 with the grant `skipped`
56
+ * (shadow mode; refused from plan task 1.5a). The legacy approval is written either way until 1.5a.
57
+ */
58
+ export const PermissionApproveBody = z
59
+ .object({
60
+ revision: PermissionRevisionBody,
61
+ reviewHash: ReviewHash,
62
+ fullAccessAcknowledgement: FullAccessAcknowledgementBody.optional(),
63
+ })
64
+ .strict();
65
+ /**
66
+ * `POST …/:name/revoke`: revokes `keys` of the revision's live grant (a realm's full access is its
67
+ * `execution.full-access:<realm>` key), or the whole grant without `keys`. Unknown or unrevocable
68
+ * keys -> 409 `extension.permission_keys_unknown`; no live grant -> 404
69
+ * `extension.permission_grant_not_found`.
70
+ */
71
+ export const PermissionRevokeBody = z
72
+ .object({
73
+ revision: PermissionRevisionBody,
74
+ keys: z.array(z.string().min(1).max(512)).min(1).max(200).optional(),
75
+ /** Shown in the audit. */
76
+ reason: z.string().min(1).max(500).optional(),
77
+ })
78
+ .strict();
79
+ export const PERMISSION_ROUTES = [
80
+ { route: "GET /api/v1/admin/extension-permissions" },
81
+ {
82
+ route: "GET /api/v1/admin/extension-permissions/:name/review",
83
+ params: PermissionNamePathParams,
84
+ },
85
+ {
86
+ route: "POST /api/v1/admin/extension-permissions/:name/approve",
87
+ params: PermissionNamePathParams,
88
+ body: PermissionApproveBody,
89
+ },
90
+ {
91
+ route: "POST /api/v1/admin/extension-permissions/:name/revoke",
92
+ params: PermissionNamePathParams,
93
+ body: PermissionRevokeBody,
94
+ },
95
+ { route: "GET /api/v1/admin/extension-isolation" },
96
+ ];
@@ -0,0 +1,116 @@
1
+ import { SuperAdminLock } from "../identity/super-admin.js";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { ExtensionAdmin } from "./admin-view.js";
6
+ import { ExtensionBlobs } from "./blobs.js";
7
+ import { ExtensionInstalls } from "./installs.js";
8
+ import { IsolationStatusReader } from "./isolated/status.js";
9
+ import { PluginInstallLock } from "./locks.js";
10
+ import type { IsolationStatus, PermissionApproveResult, PermissionGrantSummary, PermissionInventory, PermissionReviewView, PermissionRevokeResult } from "./permissions.schemas.js";
11
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
12
+ import { ExtensionRevisionGrants, type RevisionGrant } from "./revision-grants.js";
13
+ import { type FullAccessAcknowledgement, RevisionReviews } from "./revision-review.js";
14
+ import { ExtensionRevocations } from "./revocation.js";
15
+ /**
16
+ * The extension permission routes (extension permission model plan task 1.4a; spec "Review,
17
+ * updates and provenance", "Revocation, audit and people") and the isolation status (1.4j): the
18
+ * inventory of every install record, the review of an install's current revision, a person's
19
+ * approval of it (a revision grant, full access with one acknowledgement per realm), revocation
20
+ * of keys or a whole grant, and the deployment-wide isolation status.
21
+ *
22
+ * Shadow mode until plan task 1.5a: an approval records the revision grant and also writes the
23
+ * legacy snapshot, which keeps governing admission; a revocation changes the grant (its leases
24
+ * enforce from 1.5a, 1.3e).
25
+ */
26
+ /** The web page where a person confirms the installed revision's permission review. */
27
+ export declare const permissionConfirmUrl: (name: string) => string;
28
+ export declare function grantSummary(grant: RevisionGrant): PermissionGrantSummary;
29
+ export declare class ExtensionPermissions {
30
+ private readonly kdb;
31
+ readonly txHost: TransactionHost;
32
+ private readonly config;
33
+ private readonly installs;
34
+ private readonly blobs;
35
+ private readonly grants;
36
+ private readonly approvals;
37
+ private readonly reviews;
38
+ private readonly revocations;
39
+ private readonly isolation;
40
+ private readonly installLock;
41
+ /** The legacy snapshot an approval still writes until 1.5a. */
42
+ private readonly admin;
43
+ /** Approve and revoke re-check the super admin under the role lock. */
44
+ private readonly adminLock;
45
+ constructor(kdb: KernelDb, txHost: TransactionHost, config: KernelConfigService, installs: ExtensionInstalls, blobs: Pick<ExtensionBlobs, "get">, grants: ExtensionRevisionGrants, approvals: Pick<ExtensionRevisionApprovals, "decisions">, reviews: RevisionReviews, revocations: ExtensionRevocations, isolation: IsolationStatusReader, installLock: PluginInstallLock,
46
+ /** The legacy snapshot an approval still writes until 1.5a. */
47
+ admin: Pick<ExtensionAdmin, "legacySubject" | "writeLegacyApproval" | "notifyApproved">,
48
+ /** Approve and revoke re-check the super admin under the role lock. */
49
+ adminLock: SuperAdminLock);
50
+ /** Every install record with its shadow decision, grants and shadow placements. */
51
+ inventory(): Promise<PermissionInventory>;
52
+ /**
53
+ * The permission review of the install's current revision; `operator`: as the operator approves
54
+ * it from the CLI (`capybara extensions approve`, authority `operator`).
55
+ */
56
+ review(name: string, opts?: {
57
+ operator?: boolean;
58
+ }): Promise<PermissionReviewView>;
59
+ /**
60
+ * A person approves the review of the install's current revision: the revision grant (full
61
+ * access needs `ack`), then the legacy snapshot until 1.5a. The revision must still be the one
62
+ * reviewed and the review must still hash the same, else 409 `extension.permission_review_stale`.
63
+ */
64
+ approve(actor: string, name: string, body: {
65
+ revision: {
66
+ version: string;
67
+ sha512: string;
68
+ };
69
+ reviewHash: string;
70
+ fullAccessAcknowledgement?: FullAccessAcknowledgement | undefined;
71
+ }, opts?: {
72
+ actorTokenId?: string;
73
+ }): Promise<PermissionApproveResult>;
74
+ /**
75
+ * The operator approves the review `review(name, { operator: true })` printed, from the CLI: an
76
+ * `operator_cli` revision grant under the same checks (the revision, the review hash, one
77
+ * acknowledgement per full-access realm). The CLI writes the legacy snapshot itself.
78
+ */
79
+ approveAsOperator(name: string, body: {
80
+ revision: {
81
+ version: string;
82
+ sha512: string;
83
+ };
84
+ reviewHash: string;
85
+ fullAccessAcknowledgement?: FullAccessAcknowledgement | undefined;
86
+ },
87
+ /** The CLI's legacy snapshot write, run in the grant's transaction (it joins it). */
88
+ legacy?: () => Promise<unknown>): Promise<PermissionApproveResult["grant"]>;
89
+ private approveIn;
90
+ /** Revokes keys of a revision's live grant, or the whole grant. */
91
+ revoke(actor: string, name: string, body: {
92
+ revision: {
93
+ version: string;
94
+ sha512: string;
95
+ };
96
+ keys?: string[] | undefined;
97
+ reason?: string | undefined;
98
+ }, opts?: {
99
+ actorTokenId?: string;
100
+ }): Promise<PermissionRevokeResult>;
101
+ /** The revocation under the super admin re-check, in one transaction. */
102
+ private revokeIn;
103
+ /** The deployment-wide isolation status. Not configured: only that, nothing probed or read. */
104
+ isolationStatus(): Promise<IsolationStatus>;
105
+ private prepare;
106
+ /** The install's current revision, read for a review (outside any transaction). */
107
+ private installed;
108
+ /** The catalog item's scope; an install outside the catalog is deployment-wide (`all`). */
109
+ private itemScope;
110
+ /**
111
+ * The installed revision's publisher evidence as the catalog recorded it: the official proof
112
+ * (the official identity), an official revision under the pin-only policy (`pin_only`, #1368),
113
+ * else `none` (the review shows it; continuity needs a verified publisher).
114
+ */
115
+ private publisherOf;
116
+ }
@@ -0,0 +1,428 @@
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 { SDK_VERSION } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { officialPublisherIdentity } from "../catalog/provenance.js";
13
+ import { OFFICIAL_MARKETPLACE_ID, officialPublisherProofMode, } from "../catalog/publisher-policy.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { SuperAdminLock } from "../identity/super-admin.js";
16
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
+ import { KernelDb } from "../infra/database/kernel-db.js";
18
+ import { asPlatform } from "../infra/database/org-scope.js";
19
+ import { TransactionHost } from "../infra/database/transaction-host.js";
20
+ import { Transactional } from "../infra/database/transactional.decorator.js";
21
+ import { readDeploymentPrivateEndpointGaps } from "../net/private-endpoint-preflight.js";
22
+ import { ExtensionAdmin } from "./admin-view.js";
23
+ import { ExtensionBlobs } from "./blobs.js";
24
+ import { ExtensionInstalls } from "./installs.js";
25
+ import { IsolationStatusReader } from "./isolated/status.js";
26
+ import { PluginInstallLock } from "./locks.js";
27
+ import { permissionSetOfPackage, readExtensionPackage, reviewPackageClient, } from "./package.js";
28
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
29
+ import { ExtensionRevisionGrants, effectiveRealms, RevisionGrantError, } from "./revision-grants.js";
30
+ import { checkAcknowledgement, RevisionReviews, } from "./revision-review.js";
31
+ import { ExtensionRevocations } from "./revocation.js";
32
+ import { REVOCATION_ENFORCED, revocationView } from "./revocation-leases.js";
33
+ /**
34
+ * The extension permission routes (extension permission model plan task 1.4a; spec "Review,
35
+ * updates and provenance", "Revocation, audit and people") and the isolation status (1.4j): the
36
+ * inventory of every install record, the review of an install's current revision, a person's
37
+ * approval of it (a revision grant, full access with one acknowledgement per realm), revocation
38
+ * of keys or a whole grant, and the deployment-wide isolation status.
39
+ *
40
+ * Shadow mode until plan task 1.5a: an approval records the revision grant and also writes the
41
+ * legacy snapshot, which keeps governing admission; a revocation changes the grant (its leases
42
+ * enforce from 1.5a, 1.3e).
43
+ */
44
+ /** The web page where a person confirms the installed revision's permission review. */
45
+ export const permissionConfirmUrl = (name) => `/admin/plugins/extensions/${encodeURIComponent(name)}/permissions`;
46
+ const notFound = (name) => new ApiError("extension.not_found", `Extension ${name} is not installed`);
47
+ const unavailable = (name, why) => new ApiError("extension.permission_review_unavailable", `The permission review of extension ${name} is not available: ${why}`);
48
+ const stale = (name) => new ApiError("extension.permission_review_stale", `The permission review of extension ${name} is out of date (its revision, the approved grant, the host isolation or the scope changed); review it again`);
49
+ export function grantSummary(grant) {
50
+ const view = revocationView(grant);
51
+ return {
52
+ generation: grant.generation,
53
+ state: grant.state,
54
+ source: grant.source,
55
+ authority: grant.authority,
56
+ publisherEvidence: grant.publisherEvidence,
57
+ approvalScope: {
58
+ mode: grant.approvalScope.mode,
59
+ orgs: grant.approvalScope.mode === "named" ? [...grant.approvalScope.orgs] : [],
60
+ },
61
+ realms: grant.state === "revoked" || grant.state === "retired" ? {} : effectiveRealms(grant),
62
+ serving: view.serving,
63
+ withdrawn: view.withdrawn,
64
+ reviewHash: grant.reviewHash,
65
+ approvedBy: grant.approvedBy,
66
+ approvedAt: grant.approvedAt.toISOString(),
67
+ };
68
+ }
69
+ let ExtensionPermissions = class ExtensionPermissions {
70
+ kdb;
71
+ txHost;
72
+ config;
73
+ installs;
74
+ blobs;
75
+ grants;
76
+ approvals;
77
+ reviews;
78
+ revocations;
79
+ isolation;
80
+ installLock;
81
+ admin;
82
+ adminLock;
83
+ constructor(kdb, txHost, config, installs, blobs, grants, approvals, reviews, revocations, isolation, installLock,
84
+ /** The legacy snapshot an approval still writes until 1.5a. */
85
+ admin,
86
+ /** Approve and revoke re-check the super admin under the role lock. */
87
+ adminLock) {
88
+ this.kdb = kdb;
89
+ this.txHost = txHost;
90
+ this.config = config;
91
+ this.installs = installs;
92
+ this.blobs = blobs;
93
+ this.grants = grants;
94
+ this.approvals = approvals;
95
+ this.reviews = reviews;
96
+ this.revocations = revocations;
97
+ this.isolation = isolation;
98
+ this.installLock = installLock;
99
+ this.admin = admin;
100
+ this.adminLock = adminLock;
101
+ }
102
+ /** Every install record with its shadow decision, grants and shadow placements. */
103
+ async inventory() {
104
+ const db = this.kdb.db;
105
+ const rows = await db
106
+ .selectFrom("extension_installs as i")
107
+ .innerJoin("extension_packages as p", "p.sha256", "i.sha256")
108
+ .select([
109
+ "i.name",
110
+ "i.version",
111
+ "i.source",
112
+ "i.required",
113
+ "i.catalog_item_id",
114
+ "i.approved_version",
115
+ "i.approved_sha512",
116
+ "i.approved_generation",
117
+ "i.candidate_version",
118
+ "i.candidate_sha512",
119
+ "p.sha512",
120
+ ])
121
+ .orderBy("i.name")
122
+ .execute();
123
+ const decisions = new Map((await this.approvals.decisions()).map((d) => [d.revision.plugin, d]));
124
+ const executions = await this.isolation.shadowExecutions();
125
+ const entries = [];
126
+ for (const row of rows) {
127
+ const decision = decisions.get(row.name);
128
+ if (!decision)
129
+ continue;
130
+ const own = row.sha512 === null
131
+ ? undefined
132
+ : await this.grants.get({ plugin: row.name, version: row.version, sha512: row.sha512 });
133
+ const approvedIsOther = row.approved_version !== null &&
134
+ row.approved_sha512 !== null &&
135
+ row.approved_generation !== null &&
136
+ row.approved_sha512 !== row.sha512;
137
+ entries.push({
138
+ plugin: row.name,
139
+ revision: { version: row.version, sha512: row.sha512 },
140
+ source: row.source,
141
+ catalogItemId: row.catalog_item_id,
142
+ required: row.required,
143
+ status: decision.status,
144
+ decision,
145
+ grant: own ? grantSummary(own) : null,
146
+ approved: approvedIsOther
147
+ ? {
148
+ version: row.approved_version,
149
+ sha512: row.approved_sha512,
150
+ generation: row.approved_generation,
151
+ }
152
+ : null,
153
+ candidate: row.candidate_version !== null && row.candidate_sha512 !== null
154
+ ? { version: row.candidate_version, sha512: row.candidate_sha512 }
155
+ : null,
156
+ executions: executions.get(row.name) ?? [],
157
+ });
158
+ }
159
+ return {
160
+ entries,
161
+ missingRequired: entries
162
+ .filter((e) => e.required && !e.decision.wouldServe)
163
+ .map((e) => e.plugin),
164
+ };
165
+ }
166
+ /**
167
+ * The permission review of the install's current revision; `operator`: as the operator approves
168
+ * it from the CLI (`capybara extensions approve`, authority `operator`).
169
+ */
170
+ async review(name, opts = {}) {
171
+ const installed = await this.installed(name);
172
+ const review = await this.prepare(installed, opts.operator === true);
173
+ const client = reviewPackageClient(installed.pkg);
174
+ return {
175
+ plugin: name,
176
+ revision: { version: installed.revision.version, sha512: installed.revision.sha512 },
177
+ review: {
178
+ hash: review.hash,
179
+ consent: review.consent,
180
+ acknowledge: review.acknowledge,
181
+ ...(review.blocked !== undefined && { blocked: review.blocked }),
182
+ display: review.display,
183
+ },
184
+ confirmUrl: permissionConfirmUrl(name),
185
+ ...(client !== undefined && { clientFiles: client.files }),
186
+ isolation: await this.isolation.deployment(),
187
+ };
188
+ }
189
+ /**
190
+ * A person approves the review of the install's current revision: the revision grant (full
191
+ * access needs `ack`), then the legacy snapshot until 1.5a. The revision must still be the one
192
+ * reviewed and the review must still hash the same, else 409 `extension.permission_review_stale`.
193
+ */
194
+ async approve(actor, name, body, opts = {}) {
195
+ const installed = await this.installed(name);
196
+ if (installed.revision.version !== body.revision.version ||
197
+ installed.revision.sha512 !== body.revision.sha512) {
198
+ throw stale(name);
199
+ }
200
+ const prepared = await this.prepare(installed, false);
201
+ if (prepared.hash !== body.reviewHash)
202
+ throw stale(name);
203
+ checkAcknowledgement(prepared, body.fullAccessAcknowledgement);
204
+ const legacy = await this.admin.legacySubject(name);
205
+ if (!legacy) {
206
+ throw unavailable(name, "it has no legacy approval to write here (a configured extension of the same name takes precedence, or its stored package cannot be read)");
207
+ }
208
+ // one transaction: the super admin re-checked, the revision grant and, until 1.5a, the legacy
209
+ // snapshot that governs admission
210
+ const grant = await this.approveIn(actor, installed, prepared, body.fullAccessAcknowledgement, opts, false, legacy);
211
+ await this.admin.notifyApproved(name);
212
+ return {
213
+ plugin: name,
214
+ revision: { version: installed.revision.version, sha512: installed.revision.sha512 },
215
+ grant,
216
+ };
217
+ }
218
+ /**
219
+ * The operator approves the review `review(name, { operator: true })` printed, from the CLI: an
220
+ * `operator_cli` revision grant under the same checks (the revision, the review hash, one
221
+ * acknowledgement per full-access realm). The CLI writes the legacy snapshot itself.
222
+ */
223
+ async approveAsOperator(name, body,
224
+ /** The CLI's legacy snapshot write, run in the grant's transaction (it joins it). */
225
+ legacy) {
226
+ const installed = await this.installed(name);
227
+ if (installed.revision.version !== body.revision.version ||
228
+ installed.revision.sha512 !== body.revision.sha512) {
229
+ throw stale(name);
230
+ }
231
+ const prepared = await this.prepare(installed, true);
232
+ if (prepared.hash !== body.reviewHash)
233
+ throw stale(name);
234
+ checkAcknowledgement(prepared, body.fullAccessAcknowledgement);
235
+ return this.approveIn(null, installed, prepared, body.fullAccessAcknowledgement, {}, true, undefined, legacy);
236
+ }
237
+ async approveIn(actor, installed, prepared, ack, opts, operator = false, legacy, operatorLegacy) {
238
+ const name = installed.revision.plugin;
239
+ // still a super admin, under the lock the role changes take (the operator has no account)
240
+ if (actor !== null)
241
+ await this.adminLock.lockAndAuthorize(actor);
242
+ // the same lock as an install: the revision cannot move while its grant is recorded
243
+ await this.installLock.lock(name);
244
+ const now = await this.kdb.db
245
+ .selectFrom("extension_installs")
246
+ .select("sha256")
247
+ .where("name", "=", name)
248
+ .executeTakeFirst();
249
+ if (now?.sha256 !== installed.sha256)
250
+ throw stale(name);
251
+ const outcome = await this.reviews.confirm({
252
+ actor,
253
+ actorTokenId: opts.actorTokenId,
254
+ prepared,
255
+ pkg: installed.pkg,
256
+ set: installed.set,
257
+ approvalScope: installed.approvalScope,
258
+ ack,
259
+ operator,
260
+ });
261
+ if (outcome === "stale")
262
+ throw stale(name);
263
+ if (legacy && actor !== null) {
264
+ await this.admin.writeLegacyApproval(actor, name, legacy, opts.actorTokenId, () => stale(name));
265
+ }
266
+ if (operatorLegacy)
267
+ await operatorLegacy();
268
+ return outcome;
269
+ }
270
+ /** Revokes keys of a revision's live grant, or the whole grant. */
271
+ async revoke(actor, name, body, opts = {}) {
272
+ const revision = { plugin: name, ...body.revision };
273
+ const by = {
274
+ accountId: actor,
275
+ ...(opts.actorTokenId !== undefined && { tokenId: opts.actorTokenId }),
276
+ ...(body.reason !== undefined && { reason: body.reason }),
277
+ };
278
+ let outcome;
279
+ try {
280
+ outcome = await this.revokeIn(actor, revision, body.keys, by);
281
+ }
282
+ catch (err) {
283
+ if (err instanceof RevisionGrantError) {
284
+ if (err.code === "unknown_keys") {
285
+ throw new ApiError("extension.permission_keys_unknown", err.message);
286
+ }
287
+ if (err.code === "not_found" || err.code === "terminal" || err.code === "not_live") {
288
+ throw new ApiError("extension.permission_grant_not_found", `Extension ${name} ${body.revision.version} has no live grant to revoke`);
289
+ }
290
+ if (err.code === "invalid")
291
+ throw new ApiError("validation_failed", err.message);
292
+ throw new ApiError("extension.permission_review_stale", `The grant of extension ${name} ${body.revision.version} changed while it was being revoked; read the inventory and revoke again`);
293
+ }
294
+ throw err;
295
+ }
296
+ return {
297
+ plugin: name,
298
+ revision: body.revision,
299
+ grant: grantSummary(outcome.grant),
300
+ withdrawn: outcome.withdrawn,
301
+ fullAccess: outcome.view.fullAccess,
302
+ enforced: REVOCATION_ENFORCED,
303
+ };
304
+ }
305
+ /** The revocation under the super admin re-check, in one transaction. */
306
+ async revokeIn(actor, revision, keys, by) {
307
+ await this.adminLock.lockAndAuthorize(actor);
308
+ return keys
309
+ ? this.revocations.revokeKeys(revision, keys, by)
310
+ : this.revocations.revoke(revision, by);
311
+ }
312
+ /** The deployment-wide isolation status. Not configured: only that, nothing probed or read. */
313
+ async isolationStatus() {
314
+ const { state, replicas, paused } = await this.isolation.replicas();
315
+ if (state === "not_configured")
316
+ return { state };
317
+ // org-filter: deployment-wide: the installed brokered pins and enabled extensions' config
318
+ const privateEndpointGaps = await asPlatform("read the private endpoint gaps", () => readDeploymentPrivateEndpointGaps(this.kdb.db, this.config.get()));
319
+ return { state, replicas, paused, privateEndpointGaps };
320
+ }
321
+ prepare(installed, operator) {
322
+ return this.reviews.prepare({
323
+ revision: installed.revision,
324
+ pkg: installed.pkg,
325
+ set: installed.set,
326
+ approvalScope: installed.approvalScope,
327
+ publisher: installed.publisher,
328
+ authority: operator ? "operator" : "super_admin",
329
+ });
330
+ }
331
+ /** The install's current revision, read for a review (outside any transaction). */
332
+ async installed(name) {
333
+ const db = this.kdb.db;
334
+ const row = await db
335
+ .selectFrom("extension_installs as i")
336
+ .innerJoin("extension_packages as p", "p.sha256", "i.sha256")
337
+ .select(["i.version", "i.sha256", "i.catalog_item_id", "p.sha512"])
338
+ .where("i.name", "=", name)
339
+ .executeTakeFirst();
340
+ if (!row)
341
+ throw notFound(name);
342
+ if (row.sha512 === null) {
343
+ throw unavailable(name, "its package digest is not recorded yet; retry shortly");
344
+ }
345
+ let pkg;
346
+ try {
347
+ pkg = await readExtensionPackage(await this.blobs.get(row.sha256), {
348
+ maxBytes: this.config.get().packages.maxBytes,
349
+ hostSdkVersion: SDK_VERSION,
350
+ });
351
+ }
352
+ catch {
353
+ throw unavailable(name, "its stored package cannot be read");
354
+ }
355
+ return {
356
+ revision: { plugin: name, version: row.version, sha512: row.sha512 },
357
+ sha256: row.sha256,
358
+ pkg,
359
+ set: permissionSetOfPackage(pkg),
360
+ approvalScope: await this.itemScope(row.catalog_item_id),
361
+ publisher: await this.publisherOf(name),
362
+ };
363
+ }
364
+ /** The catalog item's scope; an install outside the catalog is deployment-wide (`all`). */
365
+ async itemScope(itemId) {
366
+ if (itemId === null)
367
+ return { mode: "all" };
368
+ const item = await this.kdb.db
369
+ .selectFrom("catalog_items")
370
+ .select("scope")
371
+ .where("id", "=", itemId)
372
+ .executeTakeFirst();
373
+ if (item === undefined)
374
+ return { mode: "all" };
375
+ if (item.scope !== "named")
376
+ return { mode: item.scope };
377
+ // org-filter: deployment-wide: the item's whole named list (spans orgs), keyed by its id
378
+ const orgs = await asPlatform("read the named scope of an install's catalog item", () => this.kdb.db
379
+ .selectFrom("catalog_item_scope_orgs")
380
+ .select("org_id")
381
+ .where("item_id", "=", itemId)
382
+ .orderBy("org_id")
383
+ .execute());
384
+ return { mode: "named", orgs: orgs.map((r) => r.org_id) };
385
+ }
386
+ /**
387
+ * The installed revision's publisher evidence as the catalog recorded it: the official proof
388
+ * (the official identity), an official revision under the pin-only policy (`pin_only`, #1368),
389
+ * else `none` (the review shows it; continuity needs a verified publisher).
390
+ */
391
+ async publisherOf(name) {
392
+ const install = (await this.installs.desired()).find((d) => d.name === name);
393
+ const evidence = install?.catalogEvidence;
394
+ const official = (install?.marketplaceId ?? evidence?.marketplaceId) === OFFICIAL_MARKETPLACE_ID &&
395
+ evidence?.source === "marketplace";
396
+ if (!official)
397
+ return { evidence: "none" };
398
+ if (evidence.proof != null) {
399
+ return { evidence: "verified", identity: officialPublisherIdentity() };
400
+ }
401
+ return (await officialPublisherProofMode(this.kdb.db)) === "pin-only"
402
+ ? { evidence: "pin_only" }
403
+ : { evidence: "none" };
404
+ }
405
+ };
406
+ __decorate([
407
+ Transactional()
408
+ ], ExtensionPermissions.prototype, "approveIn", null);
409
+ __decorate([
410
+ Transactional()
411
+ ], ExtensionPermissions.prototype, "revokeIn", null);
412
+ ExtensionPermissions = __decorate([
413
+ Injectable(),
414
+ __param(0, Inject(KernelDb)),
415
+ __param(1, Inject(TransactionHost)),
416
+ __param(2, Inject(KernelConfigService)),
417
+ __param(3, Inject(ExtensionInstalls)),
418
+ __param(4, Inject(ExtensionBlobs)),
419
+ __param(5, Inject(ExtensionRevisionGrants)),
420
+ __param(6, Inject(ExtensionRevisionApprovals)),
421
+ __param(7, Inject(RevisionReviews)),
422
+ __param(8, Inject(ExtensionRevocations)),
423
+ __param(9, Inject(IsolationStatusReader)),
424
+ __param(10, Inject(PluginInstallLock)),
425
+ __param(11, Inject(ExtensionAdmin)),
426
+ __param(12, Inject(SuperAdminLock))
427
+ ], ExtensionPermissions);
428
+ export { ExtensionPermissions };