@capybara-hq/kernel 0.1.0-rc.146 → 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 (168) 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 +15 -7
  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 +23 -0
  106. package/dist/extensions/permissions.controller.d.ts +35 -0
  107. package/dist/extensions/permissions.controller.js +98 -0
  108. package/dist/extensions/permissions.schemas.d.ts +288 -0
  109. package/dist/extensions/permissions.schemas.js +96 -0
  110. package/dist/extensions/permissions.service.d.ts +116 -0
  111. package/dist/extensions/permissions.service.js +428 -0
  112. package/dist/extensions/realm-retirement.d.ts +65 -0
  113. package/dist/extensions/realm-retirement.js +150 -0
  114. package/dist/extensions/revision-approvals.d.ts +58 -3
  115. package/dist/extensions/revision-approvals.js +135 -14
  116. package/dist/extensions/revision-review.d.ts +144 -0
  117. package/dist/extensions/revision-review.js +297 -0
  118. package/dist/extensions/revocation.js +3 -0
  119. package/dist/extensions/state.module.js +12 -0
  120. package/dist/git/run-end.d.ts +35 -7
  121. package/dist/git/run-end.js +87 -38
  122. package/dist/http/api.module.js +2 -0
  123. package/dist/identity/audit.d.ts +2 -1
  124. package/dist/identity/audit.js +4 -17
  125. package/dist/index.d.ts +4 -0
  126. package/dist/index.js +4 -0
  127. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  128. package/dist/infra/config/kernel-config.service.js +21 -0
  129. package/dist/infra/outbox/registry.d.ts +13 -0
  130. package/dist/infra/outbox/registry.js +8 -0
  131. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  132. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  133. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  134. package/dist/net/private-endpoint-preflight.js +417 -0
  135. package/dist/net/private-endpoints.d.ts +68 -0
  136. package/dist/net/private-endpoints.js +164 -0
  137. package/dist/net/public-address.d.ts +14 -0
  138. package/dist/net/public-address.js +15 -1
  139. package/dist/net/safe-fetch.d.ts +2 -1
  140. package/dist/net/safe-fetch.js +10 -3
  141. package/dist/overrides.d.ts +4 -0
  142. package/dist/overrides.js +2 -0
  143. package/dist/packages/official-publisher.d.ts +26 -1
  144. package/dist/packages/official-publisher.js +48 -1
  145. package/dist/packages/provenance.d.ts +11 -0
  146. package/dist/packages/provenance.js +24 -0
  147. package/dist/platform/exclusions.js +4 -4
  148. package/dist/platform/ops/automations.ops.js +1 -1
  149. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  150. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  151. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  152. package/dist/platform/platform-ops.module.d.ts +2 -1
  153. package/dist/platform/platform-ops.module.js +2 -0
  154. package/dist/platform/route-schemas.js +2 -0
  155. package/dist/retention/purge-batch.js +10 -14
  156. package/dist/runtime/maintenance.d.ts +4 -2
  157. package/dist/runtime/maintenance.js +16 -3
  158. package/dist/runtime/run-finish.d.ts +3 -3
  159. package/dist/runtime/run-finish.js +7 -3
  160. package/dist/sandbox/permission-availability.d.ts +17 -2
  161. package/dist/sandbox/permission-availability.js +22 -1
  162. package/dist/sandbox/permission-facts.js +7 -1
  163. package/dist/tools/builtins/sandbox/common.js +2 -0
  164. package/dist/tools/pipeline.d.ts +2 -1
  165. package/dist/tools/pipeline.js +7 -2
  166. package/package.json +4 -3
  167. package/src/migrations/0238_extension_usage.sql +40 -0
  168. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -0,0 +1,297 @@
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 { Inject, Injectable } from "@nestjs/common";
11
+ import semver from "semver";
12
+ import { ApiError } from "../errors.js";
13
+ import { audit } from "../identity/audit.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { TransactionHost } from "../infra/database/transaction-host.js";
16
+ import { Transactional } from "../infra/database/transactional.decorator.js";
17
+ import { executionDecision } from "./execution-realm.js";
18
+ import { deploymentConfigIsolatable } from "./isolated/admission.js";
19
+ import { IsolationStatusReader } from "./isolated/status.js";
20
+ import { permissionKeys } from "./permission-set.js";
21
+ import { grantPurposeRows, reviewDisplay, revisionReviewHash, } from "./review-hash.js";
22
+ import { scopeWider } from "./revision-approvals.js";
23
+ import { continuityProblem, ExtensionRevisionGrants, isLive, RevisionGrantError, } from "./revision-grants.js";
24
+ const sortedScope = (scope) => scope.mode === "named" ? { mode: "named", orgs: [...new Set(scope.orgs)].sort() } : scope;
25
+ /** The review of one revision. Pure. */
26
+ export function buildRevisionReview(input) {
27
+ const approvalScope = sortedScope(input.approvalScope);
28
+ const server = true;
29
+ const client = input.pkg.section.client !== undefined ? {} : undefined;
30
+ const configSchemaIsolatable = deploymentConfigIsolatable(input.pkg.section);
31
+ const decision = executionDecision({
32
+ keys: permissionKeys(input.set),
33
+ server,
34
+ client,
35
+ host: input.host,
36
+ configSchemaIsolatable,
37
+ });
38
+ const { rows } = grantPurposeRows(input.set, decision);
39
+ const { own, previous } = input;
40
+ const ownLive = own !== undefined && isLive(own.state);
41
+ const lower = previous !== undefined &&
42
+ semver.valid(input.revision.version) !== null &&
43
+ semver.valid(previous.revision.version) !== null &&
44
+ semver.lt(input.revision.version, previous.revision.version);
45
+ const problem =
46
+ // A revoked or retired revision comes back only through a fresh human review, never continuity
47
+ own !== undefined && !ownLive
48
+ ? `its grant is ${own.state}; only a new review restores it`
49
+ : ownLive && scopeWider(approvalScope, own.approvalScope)
50
+ ? `the live grant of this revision covers the ${own.approvalScope.mode} scope only; revoke it to review the ${approvalScope.mode} scope`
51
+ : // a rollback is served only under the selected revision's own grant, never continuity
52
+ lower
53
+ ? "a version below the approved one is a rollback: it needs its own grant"
54
+ : previous
55
+ ? continuityProblem(previous, {
56
+ purposes: rows,
57
+ realms: decision.fullAccess,
58
+ approvalScope,
59
+ publisher: input.publisher,
60
+ })
61
+ : "there is no approved revision to continue";
62
+ const consent = ownLive && !scopeWider(approvalScope, own.approvalScope)
63
+ ? { kind: "granted", generation: own.generation }
64
+ : problem === undefined
65
+ ? { kind: "continuity" }
66
+ : { kind: "review", reason: problem };
67
+ // The display shows the authority the confirm exercises: a continuation carries its source's
68
+ const authority = consent.kind === "continuity" && previous
69
+ ? previous.authority
70
+ : consent.kind === "granted" && own
71
+ ? own.authority
72
+ : (input.authority ?? "super_admin");
73
+ const display = reviewDisplay({
74
+ revision: input.revision,
75
+ set: input.set,
76
+ host: input.host,
77
+ server,
78
+ client,
79
+ configSchemaIsolatable,
80
+ approvalScope,
81
+ authority,
82
+ publisher: input.publisher,
83
+ evidenceDigest: input.evidenceDigest,
84
+ previous,
85
+ });
86
+ const blocked = display.missingPurposes.length > 0
87
+ ? `missing purposes: ${display.missingPurposes.join(", ")}; republish with purposes`
88
+ : !display.execution.confirmable
89
+ ? `unknown permission keys: ${display.unknownKeys.join(", ")}`
90
+ : undefined;
91
+ return {
92
+ revision: { ...input.revision },
93
+ publisher: input.publisher,
94
+ evidenceDigest: input.evidenceDigest ?? null,
95
+ preparedScope: approvalScope,
96
+ display,
97
+ hash: revisionReviewHash(display),
98
+ consent,
99
+ acknowledge: consent.kind === "review"
100
+ ? Object.keys(decision.fullAccess).sort()
101
+ : [],
102
+ ...(blocked !== undefined && { blocked }),
103
+ };
104
+ }
105
+ /**
106
+ * Checks a full-access acknowledgement sent with a confirm against the prepared review (1.3d).
107
+ * Absent is allowed until plan task 1.5a (the grant is skipped); present, it must name the
108
+ * review's hash and exactly the realms the review needs acknowledged, else 409
109
+ * `plugin.full_access_ack_invalid`.
110
+ */
111
+ export function checkAcknowledgement(review, ack) {
112
+ if (ack === undefined)
113
+ return;
114
+ const invalid = (why) => new ApiError("plugin.full_access_ack_invalid", `The full-access acknowledgement does not match this review: ${why}; review it again and acknowledge each realm`, [{ reason: why }]);
115
+ if (ack.reviewHash !== review.hash)
116
+ throw invalid("it was given for another review");
117
+ const given = [...new Set(ack.realms)].sort();
118
+ const needed = review.acknowledge;
119
+ const missing = needed.filter((realm) => !given.includes(realm));
120
+ const extra = given.filter((realm) => !needed.includes(realm));
121
+ if (missing.length > 0)
122
+ throw invalid(`full access for ${missing.join(", ")} is not acknowledged`);
123
+ if (extra.length > 0)
124
+ throw invalid(`${extra.join(", ")} needs no full-access acknowledgement`);
125
+ }
126
+ /** Prepare and confirm of revision reviews, and the grant a confirmation records. */
127
+ let RevisionReviews = class RevisionReviews {
128
+ kdb;
129
+ txHost;
130
+ grants;
131
+ isolation;
132
+ constructor(kdb, txHost, grants,
133
+ /** The host profile a review binds (plan task 1.4j): configured or not. */
134
+ isolation) {
135
+ this.kdb = kdb;
136
+ this.txHost = txHost;
137
+ this.grants = grants;
138
+ this.isolation = isolation;
139
+ }
140
+ /** The live grant of the install's approved revision, if any. */
141
+ async previousGrant(plugin) {
142
+ let approved;
143
+ try {
144
+ ({ approved } = await this.grants.installRevisions(plugin));
145
+ }
146
+ catch (err) {
147
+ // not installed yet: nothing to continue
148
+ if (err instanceof RevisionGrantError && err.code === "not_found")
149
+ return undefined;
150
+ throw err;
151
+ }
152
+ return approved ? this.grants.live(approved) : undefined;
153
+ }
154
+ /** The review of a revision as prepare shows it. */
155
+ async prepare(input) {
156
+ return buildRevisionReview({
157
+ ...input,
158
+ host: await this.isolation.reviewProfile(),
159
+ previous: await this.previousGrant(input.revision.plugin),
160
+ own: await this.grants.get(input.revision),
161
+ });
162
+ }
163
+ /**
164
+ * At confirm, in the confirm's transaction (under the extension's install lock): rechecks the
165
+ * prepared review against the current previous grant and host, then records the grant for the
166
+ * chosen scope. Returns `stale` when the review no longer holds; never throws for a grant that
167
+ * cannot be recorded in shadow mode (the outcome says why).
168
+ */
169
+ async confirm(input) {
170
+ const { prepared } = input;
171
+ const host = await this.isolation.reviewProfile();
172
+ const previous = await this.previousGrant(prepared.revision.plugin);
173
+ const own = await this.grants.get(prepared.revision);
174
+ const base = {
175
+ revision: prepared.revision,
176
+ pkg: input.pkg,
177
+ set: input.set,
178
+ host,
179
+ publisher: prepared.publisher,
180
+ evidenceDigest: prepared.evidenceDigest ?? undefined,
181
+ previous,
182
+ own,
183
+ authority: input.operator ? "operator" : "super_admin",
184
+ };
185
+ const again = buildRevisionReview({ ...base, approvalScope: prepared.preparedScope });
186
+ if (again.hash !== prepared.hash)
187
+ return "stale";
188
+ const chosen = buildRevisionReview({ ...base, approvalScope: input.approvalScope });
189
+ // A kept grant the person saw must still be there: revoked since prepare, the review is stale
190
+ // (checked at the prepared scope: a scope widened at confirm is a review its acknowledgement
191
+ // does not cover, skipped below, not a stale review)
192
+ if (prepared.consent.kind === "granted" && again.consent.kind !== "granted")
193
+ return "stale";
194
+ if (chosen.consent.kind === "granted") {
195
+ return { status: "kept", generation: chosen.consent.generation };
196
+ }
197
+ if (input.actor === null) {
198
+ if (!input.operator) {
199
+ return { status: "skipped", reason: "only a person's review records a grant" };
200
+ }
201
+ }
202
+ if (chosen.blocked !== undefined)
203
+ return { status: "skipped", reason: chosen.blocked };
204
+ const decision = executionDecision({
205
+ keys: permissionKeys(input.set),
206
+ server: true,
207
+ client: input.pkg.section.client !== undefined ? {} : undefined,
208
+ host,
209
+ configSchemaIsolatable: deploymentConfigIsolatable(input.pkg.section),
210
+ });
211
+ const { rows } = grantPurposeRows(input.set, decision);
212
+ const continuing = chosen.consent.kind === "continuity" && previous !== undefined;
213
+ // The acknowledgement binds the prepared hash; the scope chosen after it does not widen what
214
+ // full access reaches (org scope cannot confine it)
215
+ // A review grant needs every realm it confers acknowledged. The acknowledgement was checked
216
+ // against the prepared review; the scope chosen at confirm can still turn a continuation into
217
+ // a review (a wider scope), whose realms it then does not cover: no grant until 1.5a
218
+ if (!continuing) {
219
+ const acknowledged = new Set(input.ack?.realms ?? []);
220
+ const missing = chosen.acknowledge.filter((realm) => !acknowledged.has(realm));
221
+ if (missing.length > 0) {
222
+ return {
223
+ status: "skipped",
224
+ reason: `waits for an acknowledged review: full access for ${missing.join(", ")}`,
225
+ };
226
+ }
227
+ }
228
+ let grant;
229
+ try {
230
+ grant = await this.grants.record({
231
+ revision: prepared.revision,
232
+ purposes: rows,
233
+ realms: decision.fullAccess,
234
+ reviewHash: chosen.hash,
235
+ approvalScope: input.approvalScope,
236
+ source: continuing ? "continuity" : input.operator ? "operator_cli" : "review",
237
+ publisher: prepared.publisher,
238
+ ...(continuing && { continuedFrom: previous.revision }),
239
+ approvedBy: input.actor,
240
+ });
241
+ }
242
+ catch (err) {
243
+ if (err instanceof RevisionGrantError)
244
+ return { status: "skipped", reason: err.message };
245
+ throw err;
246
+ }
247
+ const fullAccess = Object.keys(grant.realms);
248
+ const detail = {
249
+ plugin: grant.revision.plugin,
250
+ version: grant.revision.version,
251
+ sha512: grant.revision.sha512,
252
+ generation: grant.generation,
253
+ reviewHash: grant.reviewHash,
254
+ realms: grant.realms,
255
+ authority: grant.authority,
256
+ publisherEvidence: grant.publisherEvidence,
257
+ };
258
+ if (continuing) {
259
+ if (fullAccess.length > 0) {
260
+ await audit(this.kdb.db, {
261
+ actorAccountId: input.actor,
262
+ ...(input.actorTokenId !== undefined && { actorTokenId: input.actorTokenId }),
263
+ action: "extension.full_access_continued",
264
+ target: grant.revision.plugin,
265
+ detail: { ...detail, continuedFrom: grant.continuedFrom },
266
+ });
267
+ }
268
+ return { status: "continued", generation: grant.generation, fullAccess };
269
+ }
270
+ await audit(this.kdb.db, {
271
+ actorAccountId: input.actor,
272
+ ...(input.actorTokenId !== undefined && { actorTokenId: input.actorTokenId }),
273
+ action: "extension.revision_granted",
274
+ target: grant.revision.plugin,
275
+ // the acknowledgement binds the prepared display; the grant binds the display with the scope
276
+ // chosen at confirm (org scope cannot confine full access), and the audit links the two
277
+ detail: {
278
+ ...detail,
279
+ acknowledged: input.ack?.realms ?? [],
280
+ acknowledgedReviewHash: input.ack?.reviewHash ?? null,
281
+ preparedReviewHash: prepared.hash,
282
+ },
283
+ });
284
+ return { status: "granted", generation: grant.generation };
285
+ }
286
+ };
287
+ __decorate([
288
+ Transactional({ propagation: "mandatory" })
289
+ ], RevisionReviews.prototype, "confirm", null);
290
+ RevisionReviews = __decorate([
291
+ Injectable(),
292
+ __param(0, Inject(KernelDb)),
293
+ __param(1, Inject(TransactionHost)),
294
+ __param(2, Inject(ExtensionRevisionGrants)),
295
+ __param(3, Inject(IsolationStatusReader))
296
+ ], RevisionReviews);
297
+ export { RevisionReviews };
@@ -152,6 +152,9 @@ let ExtensionRevocations = class ExtensionRevocations {
152
152
  registrations: view.registrations.filter((key) => !was.has(key)),
153
153
  capabilities: view.capabilities.filter((key) => !was.has(key)),
154
154
  fullAccess: view.fullAccess,
155
+ // the realms the grant reviewed: a full-access grant's revocation is surfaced in the orgs
156
+ // it affects (plan task 1.4c, `audit/full-access.ts`)
157
+ realms: after.realms,
155
158
  serving: view.serving,
156
159
  scope: after.approvalScope,
157
160
  purposesDigest: after.purposesDigest,
@@ -13,9 +13,12 @@ import { ExtensionApprovals } from "./approvals.js";
13
13
  import { ExtensionBlobs } from "./blobs.js";
14
14
  import { EffectiveConfigs } from "./effective-config.js";
15
15
  import { ExtensionInstalls } from "./installs.js";
16
+ import { IsolationStatusReader, ReplicaIsolationStore } from "./isolated/status.js";
17
+ import { REVIEWED_GRANTS } from "./isolated/tier.js";
16
18
  import { ExtensionRegistryModule } from "./registry.js";
17
19
  import { ExtensionRevisionApprovals } from "./revision-approvals.js";
18
20
  import { ExtensionRevisionGrants } from "./revision-grants.js";
21
+ import { RevisionReviews } from "./revision-review.js";
19
22
  /**
20
23
  * The extension state the model domain reads below the host: the install records with their
21
24
  * packages and approvals, and each extension's effective config per org. Apart from
@@ -42,6 +45,11 @@ ExtensionStateModule = __decorate([
42
45
  EffectiveConfigs,
43
46
  ExtensionRevisionGrants,
44
47
  ExtensionRevisionApprovals,
48
+ // 1.3b's tier admits a reviewed pin-only official revision through it (#1368)
49
+ { provide: REVIEWED_GRANTS, useExisting: ExtensionRevisionApprovals },
50
+ RevisionReviews,
51
+ ReplicaIsolationStore,
52
+ IsolationStatusReader,
45
53
  ],
46
54
  exports: [
47
55
  ExtensionRegistryModule,
@@ -51,6 +59,10 @@ ExtensionStateModule = __decorate([
51
59
  EffectiveConfigs,
52
60
  ExtensionRevisionGrants,
53
61
  ExtensionRevisionApprovals,
62
+ REVIEWED_GRANTS,
63
+ RevisionReviews,
64
+ ReplicaIsolationStore,
65
+ IsolationStatusReader,
54
66
  ],
55
67
  })
56
68
  ], ExtensionStateModule);
@@ -1,13 +1,27 @@
1
1
  import type { Redis } from "ioredis";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
3
5
  import type { KernelLogger } from "../log.js";
4
6
  import { GitTickets } from "./tickets.js";
5
7
  /**
6
8
  * What a run's end does for the git gateway (sandbox git credentials spec §9): revokes the run's
7
- * tickets and writes the `git.fetch` summaries. `RunFinish` calls it in `afterCommit` of the
8
- * transaction that set the terminal status (set first, then revoke: `GitTickets.resolve` already
9
- * refuses a run that is not active, so revocation is cleanup and defense in depth).
9
+ * tickets and writes the `git.fetch` summaries. `RunFinish` revokes in `afterCommit` of the
10
+ * transaction that set the terminal status (a hint: `GitTickets.resolve` already refuses a run that
11
+ * is not active, so revocation is cleanup and defense in depth), and owes the summaries in that
12
+ * transaction as a {@link GIT_FETCH_AUDIT_JOB} outbox job, so a crash after the commit never loses
13
+ * the audit.
10
14
  */
15
+ /** The maintenance job that writes a finished run's `git.fetch` summaries (outbox registry). */
16
+ export declare const GIT_FETCH_AUDIT_JOB = "git-fetch-audit";
17
+ /** One job per run (no `:`): a second owe of the same run's end is a no-op. */
18
+ export declare const gitFetchAuditJobId: (runId: string) => string;
19
+ /** What a {@link GIT_FETCH_AUDIT_JOB} job carries. */
20
+ export interface GitFetchAuditJobData {
21
+ runId: string;
22
+ }
23
+ /** Owes the run's fetch summaries in the caller's transaction (throws outside one). */
24
+ export declare function oweGitFetchAudit(outbox: Pick<OutboxService, "add">, runId: string, orgId: string): Promise<boolean>;
11
25
  /** The Redis hash of a run's fetch counters: fields `<host>/<repo>|n` and `<host>/<repo>|bytes`. */
12
26
  export declare const gitFetchKey: (runId: string) => string;
13
27
  /**
@@ -22,8 +36,22 @@ export declare class GitRunEnd {
22
36
  private readonly db;
23
37
  private readonly redis;
24
38
  private readonly log;
25
- constructor(tickets: Pick<GitTickets, "revokeRun">, db: KernelDb, redis: Redis, log: Pick<KernelLogger, "warn">);
26
- /** Run end: revokes the run's tickets and writes one `git.fetch` audit row per repository. */
27
- onRunFinished(runId: string): Promise<void>;
28
- private writeFetchSummaries;
39
+ readonly txHost: TransactionHost;
40
+ constructor(tickets: Pick<GitTickets, "revokeRun">, db: KernelDb, redis: Redis, log: Pick<KernelLogger, "warn">, txHost: TransactionHost);
41
+ /**
42
+ * Whether the run counted any fetch, read in its terminal transaction: only then is a summary
43
+ * owed. A failed read owes it anyway (the job finds nothing to write).
44
+ */
45
+ hasFetches(runId: string): Promise<boolean>;
46
+ /** Run end, after the commit: revokes the run's tickets (a hint whose loss is harmless). */
47
+ revokeTickets(runId: string): Promise<void>;
48
+ /**
49
+ * The {@link GIT_FETCH_AUDIT_JOB} body, in the run's org scope: one `git.fetch` audit row per
50
+ * repository from the run's counters, then the counters dropped. The rows commit before the
51
+ * delete, and a run that already has summaries gets none again, so a redelivery after a crash
52
+ * between the two writes no duplicate.
53
+ */
54
+ writeFetchSummaries(runId: string): Promise<void>;
55
+ /** The rows, committed in their own transaction before the caller drops the counters. */
56
+ private insertSummaries;
29
57
  }
@@ -8,16 +8,36 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
11
12
  import { audit } from "../identity/audit.js";
12
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
13
16
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
17
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
14
18
  import { GitTickets } from "./tickets.js";
15
19
  /**
16
20
  * What a run's end does for the git gateway (sandbox git credentials spec §9): revokes the run's
17
- * tickets and writes the `git.fetch` summaries. `RunFinish` calls it in `afterCommit` of the
18
- * transaction that set the terminal status (set first, then revoke: `GitTickets.resolve` already
19
- * refuses a run that is not active, so revocation is cleanup and defense in depth).
21
+ * tickets and writes the `git.fetch` summaries. `RunFinish` revokes in `afterCommit` of the
22
+ * transaction that set the terminal status (a hint: `GitTickets.resolve` already refuses a run that
23
+ * is not active, so revocation is cleanup and defense in depth), and owes the summaries in that
24
+ * transaction as a {@link GIT_FETCH_AUDIT_JOB} outbox job, so a crash after the commit never loses
25
+ * the audit.
20
26
  */
27
+ /** The maintenance job that writes a finished run's `git.fetch` summaries (outbox registry). */
28
+ export const GIT_FETCH_AUDIT_JOB = "git-fetch-audit";
29
+ /** One job per run (no `:`): a second owe of the same run's end is a no-op. */
30
+ export const gitFetchAuditJobId = (runId) => `git-fetch-audit-${runId}`;
31
+ /** Owes the run's fetch summaries in the caller's transaction (throws outside one). */
32
+ export function oweGitFetchAudit(outbox, runId, orgId) {
33
+ return outbox.add({
34
+ queue: MAINTENANCE_QUEUE_NAME,
35
+ name: GIT_FETCH_AUDIT_JOB,
36
+ jobId: gitFetchAuditJobId(runId),
37
+ data: { runId },
38
+ orgId,
39
+ });
40
+ }
21
41
  /** The Redis hash of a run's fetch counters: fields `<host>/<repo>|n` and `<host>/<repo>|bytes`. */
22
42
  export const gitFetchKey = (runId) => `git-fetch:${runId}`;
23
43
  /**
@@ -35,63 +55,88 @@ export async function recordGitFetch(redis, runId, host, repo, bytes, countReque
35
55
  m.hincrby(key, `${field}|bytes`, Math.max(0, Math.round(bytes)));
36
56
  await m.expire(key, FETCH_COUNTER_TTL_SECONDS).exec();
37
57
  }
38
- /** Reads and deletes a hash in one step, so a summary is written once. */
39
- const TAKE_HASH = `
40
- local all = redis.call('HGETALL', KEYS[1])
41
- redis.call('DEL', KEYS[1])
42
- return all
43
- `;
44
58
  let GitRunEnd = class GitRunEnd {
45
59
  tickets;
46
60
  db;
47
61
  redis;
48
62
  log;
49
- constructor(tickets, db, redis, log) {
63
+ txHost;
64
+ constructor(tickets, db, redis, log, txHost) {
50
65
  this.tickets = tickets;
51
66
  this.db = db;
52
67
  this.redis = redis;
53
68
  this.log = log;
69
+ this.txHost = txHost;
54
70
  }
55
- /** Run end: revokes the run's tickets and writes one `git.fetch` audit row per repository. */
56
- async onRunFinished(runId) {
57
- // both steps always run: a failing revocation must not lose the summaries, nor the reverse
58
- const results = await Promise.allSettled([
59
- this.tickets.revokeRun(runId),
60
- this.writeFetchSummaries(runId),
61
- ]);
62
- for (const r of results) {
63
- if (r.status === "rejected") {
64
- this.log.warn("git run end failed", {
65
- runId,
66
- error: r.reason instanceof Error ? r.reason.name : "unknown",
67
- });
68
- }
71
+ /**
72
+ * Whether the run counted any fetch, read in its terminal transaction: only then is a summary
73
+ * owed. A failed read owes it anyway (the job finds nothing to write).
74
+ */
75
+ async hasFetches(runId) {
76
+ try {
77
+ return (await this.redis.exists(gitFetchKey(runId))) === 1;
78
+ }
79
+ catch {
80
+ return true;
81
+ }
82
+ }
83
+ /** Run end, after the commit: revokes the run's tickets (a hint whose loss is harmless). */
84
+ async revokeTickets(runId) {
85
+ try {
86
+ await this.tickets.revokeRun(runId);
87
+ }
88
+ catch (err) {
89
+ this.log.warn("git ticket revocation at run end failed", {
90
+ runId,
91
+ error: err instanceof Error ? err.name : "unknown",
92
+ });
69
93
  }
70
94
  }
95
+ /**
96
+ * The {@link GIT_FETCH_AUDIT_JOB} body, in the run's org scope: one `git.fetch` audit row per
97
+ * repository from the run's counters, then the counters dropped. The rows commit before the
98
+ * delete, and a run that already has summaries gets none again, so a redelivery after a crash
99
+ * between the two writes no duplicate.
100
+ */
71
101
  async writeFetchSummaries(runId) {
72
- const flat = (await this.redis.eval(TAKE_HASH, 1, gitFetchKey(runId)));
102
+ const key = gitFetchKey(runId);
103
+ const flat = Object.entries(await this.redis.hgetall(key));
73
104
  if (flat.length === 0)
74
105
  return;
106
+ await this.insertSummaries(runId, flat);
107
+ await this.redis.del(key);
108
+ }
109
+ /** The rows, committed in their own transaction before the caller drops the counters. */
110
+ async insertSummaries(runId, fields) {
111
+ const run = await this.db
112
+ .selectFrom("runs")
113
+ .innerJoin("conversations", "conversations.id", "runs.conversation_id")
114
+ .select(["runs.conversation_id", "runs.trigger_account_id", "conversations.org_id"])
115
+ .where("runs.id", "=", runId)
116
+ .executeTakeFirst();
117
+ if (run === undefined)
118
+ return;
119
+ const written = await this.db
120
+ .selectFrom("audit_events")
121
+ .select("id")
122
+ .where("org_id", "=", run.org_id)
123
+ .where("action", "=", "git.fetch")
124
+ .where(sql `detail->>'runId'`, "=", runId)
125
+ .limit(1)
126
+ .executeTakeFirst();
127
+ if (written !== undefined)
128
+ return;
75
129
  const perRepo = new Map();
76
- for (let i = 0; i + 1 < flat.length; i += 2) {
77
- const field = String(flat[i]);
130
+ for (const [field, value] of fields) {
78
131
  const cut = field.lastIndexOf("|");
79
132
  const target = field.slice(0, cut);
80
133
  const entry = perRepo.get(target) ?? { count: 0, bytes: 0 };
81
134
  if (field.slice(cut + 1) === "n")
82
- entry.count = Number(flat[i + 1]);
135
+ entry.count = Number(value);
83
136
  else
84
- entry.bytes = Number(flat[i + 1]);
137
+ entry.bytes = Number(value);
85
138
  perRepo.set(target, entry);
86
139
  }
87
- const run = await this.db.db
88
- .selectFrom("runs")
89
- .innerJoin("conversations", "conversations.id", "runs.conversation_id")
90
- .select(["runs.conversation_id", "runs.trigger_account_id", "conversations.org_id"])
91
- .where("runs.id", "=", runId)
92
- .executeTakeFirst();
93
- if (run === undefined)
94
- return;
95
140
  for (const [target, { count, bytes }] of perRepo) {
96
141
  const slash = target.indexOf("/");
97
142
  await audit(this.db.db, {
@@ -111,11 +156,15 @@ let GitRunEnd = class GitRunEnd {
111
156
  }
112
157
  }
113
158
  };
159
+ __decorate([
160
+ Transactional({ propagation: "requires_new" })
161
+ ], GitRunEnd.prototype, "insertSummaries", null);
114
162
  GitRunEnd = __decorate([
115
163
  Injectable(),
116
164
  __param(0, Inject(GitTickets)),
117
165
  __param(1, Inject(KernelDb)),
118
166
  __param(2, Inject(REDIS)),
119
- __param(3, Inject(KERNEL_LOGGER))
167
+ __param(3, Inject(KERNEL_LOGGER)),
168
+ __param(4, Inject(TransactionHost))
120
169
  ], GitRunEnd);
121
170
  export { GitRunEnd };
@@ -55,6 +55,7 @@ import { EvalRunsController } from "../evals/runs.controller.js";
55
55
  import { EvalSetsController } from "../evals/sets.controller.js";
56
56
  import { TrajectoryController } from "../evals/trajectory.controller.js";
57
57
  import { ExtensionsModule } from "../extensions/extensions.module.js";
58
+ import { ExtensionPermissionsController } from "../extensions/permissions.controller.js";
58
59
  import { ExtensionPointDefaultsController } from "../extensions/point-defaults.controller.js";
59
60
  import { FilesModule } from "../files/files.module.js";
60
61
  import { LibraryFilesController } from "../files/library.controller.js";
@@ -151,6 +152,7 @@ const CONTROLLERS = [
151
152
  AdminOrgNetworkController,
152
153
  AdminLoginSourcesController,
153
154
  AdminExtensionsController,
155
+ ExtensionPermissionsController,
154
156
  AdminCatalogController,
155
157
  AdminComponentsController,
156
158
  MarketplacesController,
@@ -2,7 +2,8 @@ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
2
  /**
3
3
  * Writes one audit event (`action` is dotted lower-case English, e.g. `org.member.role_changed`)
4
4
  * through `db`: a service passes `this.db.db` (`KernelDb`: the context's transaction or the pool),
5
- * so the event commits or rolls back with the write it records.
5
+ * so the event commits or rolls back with the write it records. A full-access event is also copied
6
+ * into every org it affects (`audit/full-access.ts`, plan task 1.4c).
6
7
  */
7
8
  export declare function audit(db: KernelSchemaDb, e: {
8
9
  /** The acting account; absent or null for the kernel itself (a job such as the scope sync). */
@@ -1,23 +1,10 @@
1
- import { asPlatform } from "../infra/database/org-scope.js";
1
+ import { writeAuditEvent } from "../audit/full-access.js";
2
2
  /**
3
3
  * Writes one audit event (`action` is dotted lower-case English, e.g. `org.member.role_changed`)
4
4
  * through `db`: a service passes `this.db.db` (`KernelDb`: the context's transaction or the pool),
5
- * so the event commits or rolls back with the write it records.
5
+ * so the event commits or rolls back with the write it records. A full-access event is also copied
6
+ * into every org it affects (`audit/full-access.ts`, plan task 1.4c).
6
7
  */
7
8
  export async function audit(db, e) {
8
- const query = db.insertInto("audit_events").values({
9
- actor_account_id: e.actorAccountId ?? null,
10
- actor_token_id: e.actorTokenId ?? null,
11
- org_id: e.orgId ?? null,
12
- action: e.action,
13
- target: e.target ?? null,
14
- detail: JSON.stringify(e.detail ?? {}),
15
- });
16
- if (e.orgId === undefined) {
17
- // org-filter: deployment-wide audit events have no org and may originate inside an org call.
18
- await asPlatform("Record an audit event without an org", () => query.execute());
19
- }
20
- else {
21
- await query.execute();
22
- }
9
+ await writeAuditEvent(db, e);
23
10
  }