@capybara-hq/kernel 0.1.0-rc.145 → 0.1.0-rc.147

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 (185) 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 +71 -0
  34. package/dist/catalog/provenance.js +112 -0
  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/create-ctx.d.ts +16 -0
  45. package/dist/ctx/create-ctx.js +269 -34
  46. package/dist/ctx/net.d.ts +5 -1
  47. package/dist/ctx/net.js +62 -12
  48. package/dist/db/kernel-schema.d.ts +31 -0
  49. package/dist/db/migrator.js +0 -36
  50. package/dist/dial-in/routes.js +1 -1
  51. package/dist/erasure/org-batches.js +1 -6
  52. package/dist/erasure/org-catalog.js +6 -2
  53. package/dist/erasure/org-rules.js +1 -0
  54. package/dist/erasure/org-worker.js +0 -13
  55. package/dist/errors.d.ts +6 -0
  56. package/dist/errors.js +6 -0
  57. package/dist/extensions/admin-ops.d.ts +14 -1
  58. package/dist/extensions/admin-ops.js +30 -3
  59. package/dist/extensions/admin-view.d.ts +21 -1
  60. package/dist/extensions/admin-view.js +43 -0
  61. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  62. package/dist/extensions/bootstrap-packages.js +1 -1
  63. package/dist/extensions/bootstrap-review.d.ts +251 -0
  64. package/dist/extensions/bootstrap-review.js +676 -0
  65. package/dist/extensions/bootstrap.d.ts +21 -1
  66. package/dist/extensions/bootstrap.js +72 -2
  67. package/dist/extensions/cli.d.ts +6 -0
  68. package/dist/extensions/cli.js +4 -0
  69. package/dist/extensions/enabled.d.ts +3 -0
  70. package/dist/extensions/execution-realm.d.ts +96 -0
  71. package/dist/extensions/execution-realm.js +141 -0
  72. package/dist/extensions/extensions.module.js +12 -0
  73. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  74. package/dist/extensions/full-access-disclosure.js +57 -0
  75. package/dist/extensions/grant-epoch.d.ts +9 -2
  76. package/dist/extensions/grant-epoch.js +13 -2
  77. package/dist/extensions/host.d.ts +96 -4
  78. package/dist/extensions/host.js +411 -33
  79. package/dist/extensions/installs.d.ts +18 -0
  80. package/dist/extensions/installs.js +28 -0
  81. package/dist/extensions/instance.d.ts +2 -0
  82. package/dist/extensions/instance.js +1 -0
  83. package/dist/extensions/isolated/admission.d.ts +23 -2
  84. package/dist/extensions/isolated/admission.js +32 -7
  85. package/dist/extensions/isolated/authorization.d.ts +8 -2
  86. package/dist/extensions/isolated/authorization.js +11 -3
  87. package/dist/extensions/isolated/broker.d.ts +3 -0
  88. package/dist/extensions/isolated/broker.js +50 -14
  89. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  90. package/dist/extensions/isolated/configured-package.js +2 -0
  91. package/dist/extensions/isolated/lanes.d.ts +44 -3
  92. package/dist/extensions/isolated/lanes.js +263 -80
  93. package/dist/extensions/isolated/metrics.d.ts +146 -0
  94. package/dist/extensions/isolated/metrics.js +304 -0
  95. package/dist/extensions/isolated/revision.d.ts +7 -1
  96. package/dist/extensions/isolated/revision.js +26 -5
  97. package/dist/extensions/isolated/rpc.d.ts +5 -0
  98. package/dist/extensions/isolated/rpc.js +7 -2
  99. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  100. package/dist/extensions/isolated/sandbox.js +50 -0
  101. package/dist/extensions/isolated/status.d.ts +79 -0
  102. package/dist/extensions/isolated/status.js +216 -0
  103. package/dist/extensions/isolated/tier.d.ts +127 -2
  104. package/dist/extensions/isolated/tier.js +266 -7
  105. package/dist/extensions/isolated/usage.d.ts +134 -0
  106. package/dist/extensions/isolated/usage.js +322 -0
  107. package/dist/extensions/ledger.d.ts +5 -0
  108. package/dist/extensions/ledger.js +16 -0
  109. package/dist/extensions/lifecycle.d.ts +42 -2
  110. package/dist/extensions/lifecycle.js +100 -4
  111. package/dist/extensions/org-config.js +11 -0
  112. package/dist/extensions/package.d.ts +14 -0
  113. package/dist/extensions/package.js +23 -0
  114. package/dist/extensions/permission-view.d.ts +2 -2
  115. package/dist/extensions/permissions.controller.d.ts +35 -0
  116. package/dist/extensions/permissions.controller.js +98 -0
  117. package/dist/extensions/permissions.schemas.d.ts +288 -0
  118. package/dist/extensions/permissions.schemas.js +96 -0
  119. package/dist/extensions/permissions.service.d.ts +116 -0
  120. package/dist/extensions/permissions.service.js +428 -0
  121. package/dist/extensions/realm-retirement.d.ts +65 -0
  122. package/dist/extensions/realm-retirement.js +150 -0
  123. package/dist/extensions/registry.d.ts +6 -0
  124. package/dist/extensions/registry.js +8 -0
  125. package/dist/extensions/review-hash.d.ts +114 -0
  126. package/dist/extensions/review-hash.js +145 -0
  127. package/dist/extensions/revision-approvals.d.ts +58 -3
  128. package/dist/extensions/revision-approvals.js +135 -14
  129. package/dist/extensions/revision-grants.d.ts +10 -0
  130. package/dist/extensions/revision-review.d.ts +144 -0
  131. package/dist/extensions/revision-review.js +297 -0
  132. package/dist/extensions/revocation-leases.d.ts +273 -0
  133. package/dist/extensions/revocation-leases.js +533 -0
  134. package/dist/extensions/revocation.d.ts +78 -0
  135. package/dist/extensions/revocation.js +205 -0
  136. package/dist/extensions/state.module.js +12 -0
  137. package/dist/git/run-end.d.ts +35 -7
  138. package/dist/git/run-end.js +87 -38
  139. package/dist/http/api.module.js +2 -0
  140. package/dist/identity/audit.d.ts +2 -1
  141. package/dist/identity/audit.js +4 -17
  142. package/dist/index.d.ts +10 -2
  143. package/dist/index.js +10 -2
  144. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  145. package/dist/infra/config/kernel-config.service.js +21 -0
  146. package/dist/infra/outbox/registry.d.ts +13 -0
  147. package/dist/infra/outbox/registry.js +8 -0
  148. package/dist/lifecycle/kernel-lifecycle.d.ts +27 -1
  149. package/dist/lifecycle/kernel-lifecycle.js +83 -22
  150. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  151. package/dist/net/private-endpoint-preflight.js +417 -0
  152. package/dist/net/private-endpoints.d.ts +68 -0
  153. package/dist/net/private-endpoints.js +164 -0
  154. package/dist/net/public-address.d.ts +14 -0
  155. package/dist/net/public-address.js +15 -1
  156. package/dist/net/safe-fetch.d.ts +2 -1
  157. package/dist/net/safe-fetch.js +10 -3
  158. package/dist/overrides.d.ts +9 -1
  159. package/dist/overrides.js +4 -0
  160. package/dist/packages/official-publisher.d.ts +65 -1
  161. package/dist/packages/official-publisher.js +171 -46
  162. package/dist/packages/provenance.d.ts +11 -0
  163. package/dist/packages/provenance.js +24 -0
  164. package/dist/platform/exclusions.js +4 -4
  165. package/dist/platform/ops/automations.ops.js +1 -1
  166. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  167. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  168. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  169. package/dist/platform/platform-ops.module.d.ts +2 -1
  170. package/dist/platform/platform-ops.module.js +2 -0
  171. package/dist/platform/route-schemas.js +2 -0
  172. package/dist/retention/purge-batch.js +10 -14
  173. package/dist/runtime/maintenance.d.ts +4 -2
  174. package/dist/runtime/maintenance.js +16 -3
  175. package/dist/runtime/run-finish.d.ts +3 -3
  176. package/dist/runtime/run-finish.js +7 -3
  177. package/dist/sandbox/permission-availability.d.ts +17 -2
  178. package/dist/sandbox/permission-availability.js +22 -1
  179. package/dist/sandbox/permission-facts.js +7 -1
  180. package/dist/tools/builtins/sandbox/common.js +2 -0
  181. package/dist/tools/pipeline.d.ts +2 -1
  182. package/dist/tools/pipeline.js +7 -2
  183. package/package.json +4 -3
  184. package/src/migrations/0238_extension_usage.sql +40 -0
  185. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,676 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { createHash } from "node:crypto";
11
+ import { resolve as resolvePath } from "node:path";
12
+ import { PLUGIN_MANIFEST_FILE, SDK_VERSION } from "@capybara-hq/plugin-sdk";
13
+ import { Inject, Injectable } from "@nestjs/common";
14
+ import { audit } from "../identity/audit.js";
15
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { asPlatform } from "../infra/database/org-scope.js";
18
+ import { TransactionHost } from "../infra/database/transaction-host.js";
19
+ import { Transactional } from "../infra/database/transactional.decorator.js";
20
+ import { XactLock } from "../infra/database/xact-lock.js";
21
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { unpackPackageTgz } from "../packages/tgz.js";
23
+ import { canonicalJson } from "../tools/canonical-json.js";
24
+ import { ExtensionBlobs } from "./blobs.js";
25
+ import { resolveBootstrapPackages, scanOfflineDir } from "./bootstrap-packages.js";
26
+ import { deploymentConfigIsolatable } from "./isolated/admission.js";
27
+ import { readConfiguredExtensionPackage } from "./isolated/configured-package.js";
28
+ import { ExtensionPackageError, permissionSetOfPackage, readExtensionPackage, } from "./package.js";
29
+ import { reviewDisplay, revisionReviewHash } from "./review-hash.js";
30
+ import { ExtensionRevisionApprovals } from "./revision-approvals.js";
31
+ import { ExtensionRevisionGrants, isLive, RevisionGrantError, } from "./revision-grants.js";
32
+ /**
33
+ * The bootstrap review (extension permission model spec, "Bootstrap and offline installs"; plan
34
+ * task 1.3c). One batch covers every bootstrap pin of the merged manifest (built-in and extra
35
+ * entries, required, builtin and optional) and every config-declared extension (the archive the
36
+ * `extensions` config list captures). Each revision with an extension gets the same reviewed
37
+ * display as a catalog review (`review-hash.ts`: rows, purposes, realms and forcing keys, scope,
38
+ * operator authority, pin-only publisher evidence, the previous approval), and the batch hash binds
39
+ * the exact ordered batch, each revision's identity and display hash, and the host profile.
40
+ *
41
+ * - `capybara bootstrap review` shows it; `--print-review` prints the hash and the
42
+ * `bootstrap.approvedReviews` entry an operator can preseed.
43
+ * - `capybara bootstrap approve --review-hash <hash>` exchanges the hash for the revision grants in
44
+ * one transaction (source `operator_cli`, a fresh human review: it may reopen a revoked or retired
45
+ * revision). A hash that no longer matches the recomputed review is refused as stale.
46
+ * - A matching `bootstrap.approvedReviews` preseed does the same with source `operator_config`
47
+ * (never reviving a revoked or retired revision), from `capybara bootstrap approve` without a hash
48
+ * and from the kernel start; audited as operator (config).
49
+ * - `extensionPermissions.autoApprove` (outside production only, `config/auto-approve.ts`) grants
50
+ * the batch at start with source `auto`, logging a banner that names the revisions and realms.
51
+ * - The start gate computes "missing required approval" (a required pin, a config-declared
52
+ * extension or a required install without a live grant of its own). Shadow mode until plan task
53
+ * 1.5a: it is logged with the batch hash and the approve command, and never refuses.
54
+ *
55
+ * The batch hash is deployment-specific where approvals exist: each display binds its previous
56
+ * approval (the live grant of the install's approved revision, else of another revision of the
57
+ * plugin). A preseed hash published
58
+ * for a release (plan task 1.3f) therefore matches deployments without such a grant (fresh
59
+ * installs); an existing deployment recomputes it (`--print-review`, the P1.4 runbook).
60
+ *
61
+ * The review reads static archives only: the package store in PostgreSQL, the offline directory,
62
+ * then (the CLI only) npm or git, so it works without an object store and offline.
63
+ */
64
+ /** Bump when the batch's shape or the meaning of a field changes. */
65
+ export const BOOTSTRAP_REVIEW_CONTRACT = 1;
66
+ export class BootstrapReviewError extends Error {
67
+ code;
68
+ constructor(code, message) {
69
+ super(message);
70
+ this.code = code;
71
+ this.name = "BootstrapReviewError";
72
+ }
73
+ }
74
+ const SOURCE = {
75
+ cli: "operator_cli",
76
+ config: "operator_config",
77
+ auto: "auto",
78
+ };
79
+ const AUTHORITY = {
80
+ cli: "operator",
81
+ config: "operator",
82
+ auto: "auto",
83
+ };
84
+ /** `sha512-<base64>` (a pin's integrity) as lowercase hex. */
85
+ export function integrityHex(integrity) {
86
+ return Buffer.from(integrity.replace(/^sha512-/, ""), "base64").toString("hex");
87
+ }
88
+ /** The approval scope of a batch revision's grant. */
89
+ function scopeOf(input) {
90
+ return { mode: input.scope };
91
+ }
92
+ /** The reviewed display of one revision with an extension, under the given authority. */
93
+ export function bootstrapRevisionDisplay(input, o) {
94
+ const { section } = input.artifact.pkg;
95
+ return reviewDisplay({
96
+ revision: { plugin: input.name, version: input.version, sha512: input.sha512 },
97
+ set: permissionSetOfPackage(input.artifact.pkg),
98
+ host: o.host,
99
+ server: true,
100
+ client: section.client !== undefined ? {} : undefined,
101
+ configSchemaIsolatable: deploymentConfigIsolatable(section),
102
+ approvalScope: o.approvalScope ?? scopeOf(input),
103
+ authority: o.authority,
104
+ // A pin is checked against its sha512 offline; a config archive has no publisher at all
105
+ publisher: { evidence: input.origin === "config" ? "none" : "pin_only" },
106
+ previous: o.previous,
107
+ });
108
+ }
109
+ /** The batch inputs of the manifest's pins, from what was read of each (by name). */
110
+ function pinInputs(pins, extra, read, missingProblem) {
111
+ return pins.map((e) => ({
112
+ name: e.name,
113
+ version: e.version,
114
+ origin: extra.has(e.name) ? "extra" : "manifest",
115
+ required: e.required,
116
+ builtin: e.required || e.builtin === true,
117
+ scope: e.required || e.builtin === true ? "all" : (e.scope ?? "optional"),
118
+ sha512: integrityHex(e.integrity),
119
+ artifact: read.get(e.name) ?? { kind: "unavailable", problem: missingProblem },
120
+ }));
121
+ }
122
+ /**
123
+ * The batch inputs of a manifest's pins from their archives (by entry name), without a database:
124
+ * what a fresh deployment's review reads (plan task 1.3f, the release-time preseed). An archive
125
+ * whose sha512 is not its pin's is refused like a missing one.
126
+ */
127
+ export async function bootstrapPinInputs(manifest, archives, maxBytes) {
128
+ const read = new Map();
129
+ for (const e of manifest.plugins) {
130
+ const bytes = archives.get(e.name);
131
+ if (!bytes)
132
+ continue;
133
+ read.set(e.name, createHash("sha512").update(bytes).digest("hex") === integrityHex(e.integrity)
134
+ ? await classifyBootstrapArchive(e, bytes, maxBytes)
135
+ : { kind: "unavailable", problem: "the archive does not match its pinned sha512" });
136
+ }
137
+ return pinInputs(manifest.plugins, new Set(manifest.extra?.plugins), read, "the archive was not given");
138
+ }
139
+ /**
140
+ * The review of a fresh deployment (no grants, no previous approval), without a database: its
141
+ * hash is the one {@link BootstrapReviewService.review} computes for the same inputs and host on
142
+ * a deployment where no pinned plugin has a live grant on another revision. The
143
+ * release publishes it as the quickstart's `bootstrap.approvedReviews` preseed (plan task 1.3f).
144
+ */
145
+ export function freshBootstrapReview(inputs, host) {
146
+ const entries = inputs.map((input) => {
147
+ const base = {
148
+ name: input.name,
149
+ version: input.version,
150
+ sha512: input.sha512,
151
+ origin: input.origin,
152
+ required: input.required,
153
+ builtin: input.builtin,
154
+ scope: input.scope,
155
+ };
156
+ const { artifact } = input;
157
+ if (artifact.kind === "declarative")
158
+ return { ...base, status: "declarative" };
159
+ if (artifact.kind === "unavailable") {
160
+ return { ...base, status: "unavailable", problem: artifact.problem };
161
+ }
162
+ const display = bootstrapRevisionDisplay({ ...input, artifact }, { host, authority: "operator", previous: undefined });
163
+ const status = ungrantedStatus(display);
164
+ return { ...base, status, display, reviewHash: revisionReviewHash(display) };
165
+ });
166
+ return {
167
+ hash: bootstrapBatchHash(host, entries),
168
+ host,
169
+ entries,
170
+ complete: entries.every((e) => e.status !== "unavailable"),
171
+ };
172
+ }
173
+ /** The status of a reviewed revision without a grant of its own (the live and fresh reviews share it). */
174
+ function ungrantedStatus(display) {
175
+ return display.missingPurposes.length > 0
176
+ ? "missing_purposes"
177
+ : !display.execution.confirmable
178
+ ? "unconfirmable"
179
+ : "approvable";
180
+ }
181
+ /** The batch hash: the ordered batch, each revision's identity and display hash, the host. */
182
+ export function bootstrapBatchHash(host, entries) {
183
+ const body = canonicalJson({
184
+ contract: BOOTSTRAP_REVIEW_CONTRACT,
185
+ host,
186
+ entries: entries.map((e) => ({
187
+ name: e.name,
188
+ version: e.version,
189
+ sha512: e.sha512,
190
+ origin: e.origin,
191
+ required: e.required,
192
+ builtin: e.builtin,
193
+ scope: e.scope,
194
+ // what was read, never the grant state: approving does not change the batch
195
+ kind: e.status === "declarative"
196
+ ? "declarative"
197
+ : e.status === "unavailable"
198
+ ? "unavailable"
199
+ : "extension",
200
+ reviewHash: e.reviewHash ?? null,
201
+ // a revoked or retired grant is part of what the operator reviews again
202
+ terminal: e.terminal ?? null,
203
+ })),
204
+ });
205
+ return `bootstrap:v${BOOTSTRAP_REVIEW_CONTRACT}:${createHash("sha256").update(body).digest("hex")}`;
206
+ }
207
+ /** The pin's archive read as an extension, a declarative plugin, or unavailable. */
208
+ export async function classifyBootstrapArchive(e, bytes, maxBytes) {
209
+ try {
210
+ return {
211
+ kind: "extension",
212
+ pkg: await readExtensionPackage(bytes, { maxBytes, hostSdkVersion: SDK_VERSION }),
213
+ };
214
+ }
215
+ catch (err) {
216
+ if (err instanceof ExtensionPackageError && err.code === "extension.no_extension") {
217
+ return { kind: "declarative" };
218
+ }
219
+ // A git tree without plugin.json (a Claude Code plugin) is translated on import and carries
220
+ // no extension: extension code needs a plugin.json. Any other problem (a malformed manifest,
221
+ // an incompatible SDK) leaves the revision unreviewable, never declarative.
222
+ if (e.source === "git" && err instanceof ExtensionPackageError) {
223
+ const files = await unpackPackageTgz(bytes, { maxBytes }).catch(() => undefined);
224
+ if (files && !files.some((f) => f.path === PLUGIN_MANIFEST_FILE)) {
225
+ return { kind: "declarative" };
226
+ }
227
+ }
228
+ return { kind: "unavailable", problem: err instanceof Error ? err.message : String(err) };
229
+ }
230
+ }
231
+ let BootstrapReviewService = class BootstrapReviewService {
232
+ kdb;
233
+ txHost;
234
+ xactLock;
235
+ grants;
236
+ approvals;
237
+ blobs;
238
+ config;
239
+ log;
240
+ constructor(kdb, txHost, xactLock, grants, approvals, blobs, config, log) {
241
+ this.kdb = kdb;
242
+ this.txHost = txHost;
243
+ this.xactLock = xactLock;
244
+ this.grants = grants;
245
+ this.approvals = approvals;
246
+ this.blobs = blobs;
247
+ this.config = config;
248
+ this.log = log;
249
+ }
250
+ /** The host profile the review is computed for: whether the isolation supervisor is configured. */
251
+ host() {
252
+ return this.config.get().extensionHost.isolation ? "available" : "not_configured";
253
+ }
254
+ /**
255
+ * Reads the batch's archives: the bootstrap pins (the package store, then the offline `dir`,
256
+ * then npm or git when `network`) and the config-declared archives (`declared`; resolved against
257
+ * `resolveFrom`). Nothing is written; an archive that cannot be read is `unavailable`.
258
+ */
259
+ async collect(o) {
260
+ const cfg = this.config.get();
261
+ const maxBytes = cfg.packages.maxBytes;
262
+ const declared = [];
263
+ if (o.declared) {
264
+ const from = resolvePath(o.resolveFrom ?? process.cwd());
265
+ for (const spec of cfg.extensions) {
266
+ try {
267
+ const snapshot = await readConfiguredExtensionPackage(spec, from, maxBytes);
268
+ declared.push({
269
+ name: snapshot.review.section.name,
270
+ version: snapshot.review.section.version,
271
+ origin: "config",
272
+ required: true,
273
+ builtin: true,
274
+ scope: "all",
275
+ sha512: snapshot.sha512,
276
+ artifact: { kind: "extension", pkg: snapshot.review },
277
+ });
278
+ }
279
+ catch (err) {
280
+ // Without the archive there is no revision to name: it stays in the batch as
281
+ // unavailable (named by its config entry), so the review is incomplete and the gate
282
+ // names it
283
+ declared.push({
284
+ name: spec,
285
+ version: "?",
286
+ origin: "config",
287
+ required: true,
288
+ builtin: true,
289
+ scope: "all",
290
+ sha512: "",
291
+ artifact: {
292
+ kind: "unavailable",
293
+ problem: `the config-declared archive cannot be read: ${err instanceof Error ? err.message : String(err)}`,
294
+ },
295
+ });
296
+ }
297
+ }
298
+ }
299
+ const declaredNames = new Set(declared.map((d) => d.name));
300
+ // A pin named like a config-declared extension is not installed: config wins
301
+ const pins = (o.manifest?.plugins ?? []).filter((e) => !declaredNames.has(e.name));
302
+ const extra = new Set(o.manifest?.extra?.plugins);
303
+ const read = new Map();
304
+ const missing = [];
305
+ const offline = o.dir !== undefined ? await scanOfflineDir(o.dir, maxBytes, this.log) : new Map();
306
+ for (const e of pins) {
307
+ const stored = await this.storedArtifact(e, maxBytes);
308
+ if (stored) {
309
+ read.set(e.name, stored);
310
+ continue;
311
+ }
312
+ const bytes = offline.get(e.integrity);
313
+ if (bytes)
314
+ read.set(e.name, await classifyBootstrapArchive(e, bytes, maxBytes));
315
+ else
316
+ missing.push(e);
317
+ }
318
+ if (missing.length > 0 && o.network && o.manifest) {
319
+ const failed = new Map();
320
+ const got = await resolveBootstrapPackages({ ...o.manifest, plugins: missing }, {
321
+ config: cfg,
322
+ log: this.log,
323
+ ...(o.signal !== undefined && { signal: o.signal }),
324
+ soft: () => true,
325
+ failed,
326
+ });
327
+ for (const e of missing) {
328
+ const bytes = got.get(e.name);
329
+ if (bytes)
330
+ read.set(e.name, await classifyBootstrapArchive(e, bytes, maxBytes));
331
+ else {
332
+ read.set(e.name, {
333
+ kind: "unavailable",
334
+ problem: failed.get(e.name)?.message ?? "the package could not be obtained",
335
+ });
336
+ }
337
+ }
338
+ }
339
+ const out = pinInputs(pins, extra, read, `not in the package store or the bootstrap directory${o.network ? "" : " (run capybara bootstrap review)"}`);
340
+ return [...out, ...declared];
341
+ }
342
+ /**
343
+ * A pin already in PostgreSQL: an extension package stored with this sha512 (its bytes from the
344
+ * package store), or a declarative catalog version imported with this integrity.
345
+ */
346
+ async storedArtifact(e, maxBytes) {
347
+ const db = this.kdb.db;
348
+ const pkg = await db
349
+ .selectFrom("extension_packages")
350
+ .select("sha256")
351
+ .where("sha512", "=", integrityHex(e.integrity))
352
+ .executeTakeFirst();
353
+ if (pkg) {
354
+ try {
355
+ const bytes = await this.blobs.get(pkg.sha256);
356
+ // the column is not trusted: the bytes must hash to the pin
357
+ if (createHash("sha512").update(bytes).digest("hex") !== integrityHex(e.integrity)) {
358
+ return undefined;
359
+ }
360
+ return await classifyBootstrapArchive(e, bytes, maxBytes);
361
+ }
362
+ catch {
363
+ return undefined;
364
+ }
365
+ }
366
+ // org-filter: deployment-wide: bootstrap pins are platform catalog versions.
367
+ const version = await asPlatform("read the catalog version of a bootstrap pin", () => db
368
+ .selectFrom("catalog_item_versions as v")
369
+ .innerJoin("catalog_items as i", "i.id", "v.item_id")
370
+ .select("v.extension_sha256")
371
+ .where("i.name", "=", e.name)
372
+ .where("i.owner_org_id", "is", null)
373
+ .where("v.version", "=", e.version)
374
+ .where("v.integrity", "=", e.integrity)
375
+ .executeTakeFirst());
376
+ return version && version.extension_sha256 === null ? { kind: "declarative" } : undefined;
377
+ }
378
+ /** The review of the collected batch against the grants as they are now (reads only). */
379
+ async review(inputs) {
380
+ const host = this.host();
381
+ const entries = [];
382
+ for (const input of inputs)
383
+ entries.push(await this.entry(input, host, "operator"));
384
+ return {
385
+ hash: bootstrapBatchHash(host, entries),
386
+ host,
387
+ entries,
388
+ complete: entries.every((e) => e.status !== "unavailable"),
389
+ };
390
+ }
391
+ async entry(input, host, authority) {
392
+ const base = {
393
+ name: input.name,
394
+ version: input.version,
395
+ sha512: input.sha512,
396
+ origin: input.origin,
397
+ required: input.required,
398
+ builtin: input.builtin,
399
+ scope: input.scope,
400
+ };
401
+ const { artifact } = input;
402
+ if (artifact.kind === "declarative")
403
+ return { ...base, status: "declarative" };
404
+ if (artifact.kind === "unavailable") {
405
+ return { ...base, status: "unavailable", problem: artifact.problem };
406
+ }
407
+ const revision = { plugin: input.name, version: input.version, sha512: input.sha512 };
408
+ const display = bootstrapRevisionDisplay({ ...input, artifact }, { host, authority, previous: await this.previous(revision) });
409
+ const reviewHash = revisionReviewHash(display);
410
+ const live = await this.grants.live(revision);
411
+ if (live)
412
+ return { ...base, status: "granted", display, reviewHash, generation: live.generation };
413
+ const newest = await this.grants.get(revision);
414
+ if (newest) {
415
+ return {
416
+ ...base,
417
+ status: "revoked",
418
+ display,
419
+ reviewHash,
420
+ terminal: { generation: newest.generation, state: newest.state },
421
+ };
422
+ }
423
+ const status = ungrantedStatus(display);
424
+ return { ...base, status, display, reviewHash };
425
+ }
426
+ /** The live grant of the install's approved revision when that is another revision. */
427
+ /**
428
+ * The previous approval a revision's display binds: the live grant of the install's approved
429
+ * revision when that is another revision, else the newest live grant of another revision of the
430
+ * plugin. Bootstrap pins are granted without being promoted (and installs from before the grant
431
+ * store have no approved revision), so without the fallback an upgraded pin would review like a
432
+ * fresh one and match the release's fresh-deployment preseed (plan task 1.3f).
433
+ */
434
+ async previous(revision) {
435
+ const isThis = (r) => r.version === revision.version && r.sha512 === revision.sha512;
436
+ const row = await this.kdb.db
437
+ .selectFrom("extension_installs")
438
+ .select(["approved_version", "approved_sha512"])
439
+ .where("name", "=", revision.plugin)
440
+ .executeTakeFirst();
441
+ if (row?.approved_version && row.approved_sha512) {
442
+ const approved = { version: row.approved_version, sha512: row.approved_sha512 };
443
+ if (!isThis(approved)) {
444
+ const live = await this.grants.live({ plugin: revision.plugin, ...approved });
445
+ if (live)
446
+ return live;
447
+ }
448
+ }
449
+ // newest approval first
450
+ return (await this.grants.forPlugin(revision.plugin)).find((g) => isLive(g.state) && !isThis(g.revision));
451
+ }
452
+ /**
453
+ * Exchanges the batch hash for the revision grants, in one transaction: the review is computed
454
+ * again inside it (the grants and previous approvals as they are now), a hash that differs is
455
+ * refused as stale, and every approvable revision is granted and audited
456
+ * (`extension.permissions_approved`, actor operator). `cli` may reopen a revoked or retired
457
+ * revision (a fresh human review); `config` (a preseed) never does.
458
+ */
459
+ async approve(inputs, hash, via) {
460
+ // One batch approval at a time: replicas applying the same preseed do not audit twice
461
+ await this.xactLock.lock("capybara.bootstrap-approve");
462
+ const review = await this.review(inputs);
463
+ if (!review.complete) {
464
+ throw new BootstrapReviewError("incomplete", `Some archives could not be read (${review.entries
465
+ .filter((e) => e.status === "unavailable")
466
+ .map((e) => e.name)
467
+ .join(", ")}): put them in the bootstrap directory (bootstrap.dir) and review again`);
468
+ }
469
+ if (review.hash !== hash) {
470
+ throw new BootstrapReviewError("stale", `The review hash ${hash} is stale: the bootstrap review is now ${review.hash}. Run \`capybara bootstrap review\` and approve what it shows`);
471
+ }
472
+ return this.grantAll(review, inputs, via);
473
+ }
474
+ /**
475
+ * `extensionPermissions.autoApprove` (outside production only): grants every grantable revision
476
+ * of the batch with source `auto`, each with its own display under the `auto` authority, in one
477
+ * transaction.
478
+ */
479
+ async autoApprove(inputs) {
480
+ await this.xactLock.lock("capybara.bootstrap-approve");
481
+ const host = this.host();
482
+ const entries = [];
483
+ for (const input of inputs)
484
+ entries.push(await this.entry(input, host, "auto"));
485
+ const review = { hash: bootstrapBatchHash(host, entries), host, entries, complete: true };
486
+ return this.grantAll(review, inputs, "auto");
487
+ }
488
+ async grantAll(review, inputs, via) {
489
+ const granted = [];
490
+ const skipped = [];
491
+ const byName = new Map(inputs.map((i) => [`${i.origin}:${i.name}`, i]));
492
+ for (const e of review.entries) {
493
+ const input = byName.get(`${e.origin}:${e.name}`);
494
+ const grantable = e.status === "approvable" || (e.status === "revoked" && via === "cli");
495
+ if (!grantable || !input || !e.display || !e.reviewHash) {
496
+ if (e.status !== "granted" && e.status !== "declarative") {
497
+ skipped.push({ name: e.name, version: e.version, reason: skipReason(e, via) });
498
+ }
499
+ continue;
500
+ }
501
+ const revision = { plugin: e.name, version: e.version, sha512: e.sha512 };
502
+ let grant;
503
+ try {
504
+ grant = await this.grants.record({
505
+ revision,
506
+ purposes: e.display.rows.map(({ key, zh, en }) => ({ key, zh, en })),
507
+ realms: e.display.execution.realms,
508
+ reviewHash: e.reviewHash,
509
+ approvalScope: scopeOf(input),
510
+ source: SOURCE[via],
511
+ publisher: { evidence: e.origin === "config" ? "none" : "pin_only" },
512
+ approvedBy: null,
513
+ });
514
+ }
515
+ catch (err) {
516
+ if (err instanceof RevisionGrantError && err.code !== "invalid") {
517
+ skipped.push({ name: e.name, version: e.version, reason: err.message });
518
+ continue;
519
+ }
520
+ throw err;
521
+ }
522
+ await audit(this.kdb.db, {
523
+ action: "extension.permissions_approved",
524
+ target: e.name,
525
+ detail: {
526
+ version: e.version,
527
+ sha512: e.sha512,
528
+ generation: grant.generation,
529
+ source: grant.source,
530
+ authority: grant.authority,
531
+ // who approved: the operator through the CLI or the deployment config, or autoApprove
532
+ actor: via === "auto" ? "auto" : `operator (${via})`,
533
+ batchHash: review.hash,
534
+ reviewHash: e.reviewHash,
535
+ realms: grant.realms,
536
+ keys: grant.keys,
537
+ },
538
+ });
539
+ granted.push({ name: e.name, version: e.version, generation: grant.generation });
540
+ }
541
+ return { hash: review.hash, granted, skipped };
542
+ }
543
+ /**
544
+ * The kernel start's step (shadow mode until plan task 1.5a). Reads the batch without network,
545
+ * applies a matching `bootstrap.approvedReviews` preseed (operator config), grants the batch when
546
+ * `autoApprove` is on (with the banner), then computes the start gate and logs a missing required
547
+ * approval with the batch hash and the command. Never throws and never refuses the start.
548
+ */
549
+ async atStart(o) {
550
+ let granted = 0;
551
+ try {
552
+ const inputs = await this.collect({ ...o, network: false });
553
+ let review = await this.review(inputs);
554
+ const cfg = this.config.get();
555
+ const pending = () => review.entries.some((e) => e.status === "approvable");
556
+ const preseeded = cfg.bootstrap.approvedReviews;
557
+ if (review.complete && pending() && preseeded.includes(review.hash)) {
558
+ const done = await asPlatform("apply the bootstrap review preseed", () => this.approve(inputs, review.hash, "config"));
559
+ granted += done.granted.length;
560
+ this.log.info("bootstrap review: preseeded approval applied (operator config)", {
561
+ hash: review.hash,
562
+ granted: done.granted.map((g) => `${g.name}@${g.version}`),
563
+ ...(done.skipped.length > 0 && { skipped: done.skipped }),
564
+ });
565
+ review = withGranted(review, done);
566
+ }
567
+ else if (preseeded.length > 0 && !preseeded.includes(review.hash)) {
568
+ // A preseed that matches nothing is never silent (plan task 1.3f): a warning while
569
+ // something is pending or required is missing, else a note (nothing left to approve)
570
+ const missing = (await this.gate(review)).missingRequired.length > 0;
571
+ this.log[pending() || missing ? "warn" : "info"]("bootstrap review: no hash in bootstrap.approvedReviews matches this deployment's review; the preseed is stale and nothing was approved from it", {
572
+ preseeded,
573
+ ...(review.complete && { hash: review.hash }),
574
+ command: review.complete
575
+ ? `capybara bootstrap approve --review-hash ${review.hash}`
576
+ : "capybara bootstrap review",
577
+ });
578
+ }
579
+ if (cfg.extensionPermissions.autoApprove && pending()) {
580
+ const done = await asPlatform("auto-approve the bootstrap batch", () => this.autoApprove(inputs));
581
+ granted += done.granted.length;
582
+ if (done.granted.length > 0) {
583
+ this.log.warn("extensionPermissions.autoApprove is ON: these revisions were granted without review, full access included; never enable this in production", {
584
+ granted: done.granted.map((g) => {
585
+ const realms = review.entries.find((e) => e.name === g.name)?.display?.execution
586
+ .realms;
587
+ return `${g.name}@${g.version}${realms && Object.keys(realms).length > 0 ? ` (full access: ${Object.keys(realms).join(", ")})` : ""}`;
588
+ }),
589
+ });
590
+ }
591
+ review = withGranted(review, done);
592
+ }
593
+ const gate = await this.gate(review);
594
+ if (gate.missingRequired.length > 0) {
595
+ this.log.warn("missing required approval (shadow mode, not enforced): the enforcing start gate would refuse to serve", {
596
+ missingRequired: gate.missingRequired,
597
+ ...(gate.hash !== undefined && { hash: gate.hash }),
598
+ command: gate.command,
599
+ });
600
+ }
601
+ return { ...gate, granted };
602
+ }
603
+ catch (err) {
604
+ this.log.warn("bootstrap review: the shadow start gate could not be computed", { err });
605
+ return undefined;
606
+ }
607
+ }
608
+ /** The start gate's facts (shadow mode: shown and logged, never refused). */
609
+ async gate(review) {
610
+ const missing = new Set(review.entries
611
+ .filter((e) => (e.required || e.origin === "config") &&
612
+ e.status !== "granted" &&
613
+ e.status !== "declarative")
614
+ .map((e) => `${e.name}@${e.version}`));
615
+ const installs = await this.approvals.startGate();
616
+ for (const d of installs.missingRequired) {
617
+ missing.add(`${d.revision.plugin}@${d.revision.version}`);
618
+ }
619
+ const command = review.complete
620
+ ? `capybara bootstrap approve --review-hash ${review.hash}`
621
+ : "capybara bootstrap review";
622
+ return {
623
+ missingRequired: [...missing].sort(),
624
+ ...(review.complete && { hash: review.hash }),
625
+ command,
626
+ };
627
+ }
628
+ };
629
+ __decorate([
630
+ Transactional()
631
+ ], BootstrapReviewService.prototype, "approve", null);
632
+ __decorate([
633
+ Transactional()
634
+ ], BootstrapReviewService.prototype, "autoApprove", null);
635
+ __decorate([
636
+ Transactional({ propagation: "mandatory" })
637
+ ], BootstrapReviewService.prototype, "grantAll", null);
638
+ BootstrapReviewService = __decorate([
639
+ Injectable(),
640
+ __param(0, Inject(KernelDb)),
641
+ __param(1, Inject(TransactionHost)),
642
+ __param(2, Inject(XactLock)),
643
+ __param(3, Inject(ExtensionRevisionGrants)),
644
+ __param(4, Inject(ExtensionRevisionApprovals)),
645
+ __param(5, Inject(ExtensionBlobs)),
646
+ __param(6, Inject(KernelConfigService)),
647
+ __param(7, Inject(KERNEL_LOGGER))
648
+ ], BootstrapReviewService);
649
+ export { BootstrapReviewService };
650
+ /** The review after an approval granted some of its revisions (no second review is computed). */
651
+ function withGranted(review, done) {
652
+ const granted = new Map(done.granted.map((g) => [`${g.name}@${g.version}`, g.generation]));
653
+ return {
654
+ ...review,
655
+ entries: review.entries.map((e) => {
656
+ const generation = granted.get(`${e.name}@${e.version}`);
657
+ return generation === undefined ? e : { ...e, status: "granted", generation };
658
+ }),
659
+ };
660
+ }
661
+ function skipReason(e, via) {
662
+ switch (e.status) {
663
+ case "missing_purposes":
664
+ return `Republish with purposes: ${e.display?.missingPurposes.join(", ")}`;
665
+ case "unconfirmable":
666
+ return `unknown permission keys: ${e.display?.unknownKeys.join(", ")}`;
667
+ case "revoked":
668
+ return via === "cli"
669
+ ? "its grant was revoked or retired"
670
+ : "its grant was revoked or retired; only `capybara bootstrap approve --review-hash` restores it";
671
+ case "unavailable":
672
+ return e.problem ?? "the archive could not be read";
673
+ default:
674
+ return e.status;
675
+ }
676
+ }