@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
@@ -1,6 +1,10 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { OFFICIAL_MARKETPLACE_ID } from "../../catalog/publisher-policy.js";
3
- import { isTrustedPublisherRevision } from "./admission.js";
3
+ import { executionDecision, HOST_NO_ISOLATION_KEY, } from "../execution-realm.js";
4
+ import { permissionSetOfSection } from "../package.js";
5
+ import { permissionKeys } from "../permission-set.js";
6
+ import { EXECUTION_REALMS, effectiveKeys, effectiveRealms, fullAccessKey, isLive, } from "../revision-grants.js";
7
+ import { deploymentConfigIsolatable, isTrustedPublisherRevision, } from "./admission.js";
4
8
  export const PUBLISHER_PROOF_MISSING = "Publisher proof missing for this revision; upgrade it from the official marketplace";
5
9
  /**
6
10
  * The status detail and the log's action for {@link publisherProofMissing}. Under pin-only an
@@ -28,8 +32,118 @@ export function publisherProofMissing(extension) {
28
32
  evidence?.source === "marketplace" &&
29
33
  evidence.proof == null);
30
34
  }
31
- /** Source, reviewed package revision and integrity jointly determine admission, never the plugin name. */
32
- export async function installedExtensionTier(extension, builtin, blobs, verifyBytes) {
35
+ /** The Nest token under which the {@link ReviewedGrants} implementation is provided. */
36
+ export const REVIEWED_GRANTS = Symbol("REVIEWED_GRANTS");
37
+ /** The grant sources made by a human; only they admit a proofless revision. */
38
+ const HUMAN_SOURCES = new Set([
39
+ "review",
40
+ "operator_cli",
41
+ "operator_config",
42
+ ]);
43
+ /**
44
+ * Reading the proof mode or the revision's grant failed: not a refusal. A serving revision keeps
45
+ * its tier; any other waits for the next convergence with its own status reason.
46
+ */
47
+ export class GrantReadError extends Error {
48
+ constructor(cause) {
49
+ super("The revision's grant could not be read", { cause });
50
+ this.name = "GrantReadError";
51
+ }
52
+ }
53
+ /** The lowercase hex sha512 of an SRI `sha512-<base64>` integrity, or undefined when malformed. */
54
+ export function sha512HexOfIntegrity(integrity) {
55
+ const match = /^sha512-([A-Za-z0-9+/]{86}==)$/.exec(integrity);
56
+ return match?.[1] ? Buffer.from(match[1], "base64").toString("hex") : undefined;
57
+ }
58
+ const integrityOf = (bytes) => `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
59
+ /**
60
+ * An official revision recorded without a publisher proof, admitted under pin-only by its own
61
+ * human-reviewed grant: the grant's evidence is `pin_only`, the deployment's mode is pin-only and
62
+ * the bytes match the recorded integrity (a mismatch always refuses). Execution follows the grant,
63
+ * never the publisher: in process only while the grant covers server full access, otherwise the
64
+ * isolated tier (whose admission then checks the section).
65
+ */
66
+ async function pinOnlyTier(extension, pinOnly, blobs, verifyBytes) {
67
+ const evidence = extension.catalogEvidence;
68
+ if (!evidence?.integrity || !evidence.npmName || evidence.version !== extension.version) {
69
+ return "refused";
70
+ }
71
+ const sha512 = sha512HexOfIntegrity(evidence.integrity);
72
+ if (sha512 === undefined)
73
+ return "refused";
74
+ const revision = { plugin: extension.name, version: extension.version, sha512 };
75
+ let mode;
76
+ let grant;
77
+ try {
78
+ mode = await pinOnly.mode();
79
+ grant = mode === "pin-only" ? await pinOnly.reviewedGrant(revision) : undefined;
80
+ }
81
+ catch (err) {
82
+ throw new GrantReadError(err);
83
+ }
84
+ // the lookup is checked, never taken on trust: this exact revision, live, made by a human
85
+ if (mode !== "pin-only" ||
86
+ !grant ||
87
+ !isLive(grant.state) ||
88
+ grant.revision.plugin !== revision.plugin ||
89
+ grant.revision.version !== revision.version ||
90
+ grant.revision.sha512 !== revision.sha512 ||
91
+ !HUMAN_SOURCES.has(grant.source) ||
92
+ grant.publisherEvidence !== "pin_only") {
93
+ return "refused";
94
+ }
95
+ if (verifyBytes && integrityOf(await blobs.get(extension.sha256)) !== evidence.integrity) {
96
+ return "refused";
97
+ }
98
+ // placed by the grant at admission only: once serving, the host keeps its tier until task 1.5a
99
+ // enforces moves (1.3e's afterRevocation)
100
+ return effectiveRealms(grant).server ? "trusted" : "isolated";
101
+ }
102
+ /**
103
+ * An extra-manifest npm pin (#1371, a distribution's Google sign-in) follows the marketplace
104
+ * activation path: reviewed under the same contract (`capybara bootstrap review`), it runs in
105
+ * process only under the live human-reviewed grant of its exact revision covering server full
106
+ * access (`capybara bootstrap approve`, a preseed), its bytes checked against the pinned sha512;
107
+ * otherwise it stays isolated. The grant is read from PostgreSQL, so activation stays offline. A
108
+ * failed read is a {@link GrantReadError}, never a refusal. Placed at admission only: a serving
109
+ * pin keeps its tier until task 1.5a enforces moves ({@link keepsServingAdmission}); a host reason
110
+ * retired by task 1.3b's retirement is gone from {@link effectiveRealms}.
111
+ */
112
+ async function extraPinTier(extension, pin, grants, blobs, verifyBytes) {
113
+ const sha512 = sha512HexOfIntegrity(pin.integrity);
114
+ if (sha512 === undefined)
115
+ return "refused";
116
+ const revision = { plugin: pin.name, version: pin.version, sha512 };
117
+ let grant;
118
+ try {
119
+ grant = await grants.reviewedGrant(revision);
120
+ }
121
+ catch (err) {
122
+ throw new GrantReadError(err);
123
+ }
124
+ if (!grant ||
125
+ !isLive(grant.state) ||
126
+ grant.revision.plugin !== revision.plugin ||
127
+ grant.revision.version !== revision.version ||
128
+ grant.revision.sha512 !== revision.sha512 ||
129
+ !HUMAN_SOURCES.has(grant.source) ||
130
+ !effectiveRealms(grant).server) {
131
+ return "isolated";
132
+ }
133
+ if (verifyBytes && integrityOf(await blobs.get(extension.sha256)) !== pin.integrity) {
134
+ return "refused";
135
+ }
136
+ return "trusted";
137
+ }
138
+ /**
139
+ * Source, reviewed package revision and integrity jointly determine admission, never the plugin
140
+ * name. `pinOnly` (absent in the CLI) admits a proofless official revision a human reviewed under
141
+ * pin-only (see {@link PinOnlyAdmission}); `extraPins` places an extra-manifest npm pin under its
142
+ * reviewed full-access grant ({@link extraPinTier}).
143
+ */
144
+ export async function installedExtensionTier(extension, builtin, blobs, verifyBytes, pinOnly,
145
+ /** The grant lookup an extra-manifest npm pin is placed by (#1371); absent: it stays isolated. */
146
+ extraPins) {
33
147
  if (extension.source === "bootstrap") {
34
148
  const manifest = await builtin();
35
149
  const extra = new Set(manifest.extra?.plugins);
@@ -39,11 +153,14 @@ export async function installedExtensionTier(extension, builtin, blobs, verifyBy
39
153
  return "refused";
40
154
  if (!verifyBytes)
41
155
  return "trusted";
42
- const bytes = await blobs.get(extension.sha256);
43
- return `sha512-${createHash("sha512").update(bytes).digest("base64")}` === pin.integrity
156
+ return integrityOf(await blobs.get(extension.sha256)) === pin.integrity
44
157
  ? "trusted"
45
158
  : "refused";
46
159
  }
160
+ const extraPin = manifest.plugins.find((entry) => entry.name === extension.name);
161
+ if (extraPins && extraPin?.source === "npm" && extraPin.version === extension.version) {
162
+ return extraPinTier(extension, extraPin, extraPins, blobs, verifyBytes);
163
+ }
47
164
  return "isolated";
48
165
  }
49
166
  const evidence = extension.catalogEvidence;
@@ -51,6 +168,9 @@ export async function installedExtensionTier(extension, builtin, blobs, verifyBy
51
168
  if (extension.source !== "catalog" || marketplace !== OFFICIAL_MARKETPLACE_ID) {
52
169
  return "isolated";
53
170
  }
171
+ if (pinOnly && publisherProofMissing(extension)) {
172
+ return pinOnlyTier(extension, pinOnly, blobs, verifyBytes);
173
+ }
54
174
  if (!evidence ||
55
175
  evidence.source !== "marketplace" ||
56
176
  evidence.version !== extension.version ||
@@ -65,8 +185,147 @@ export async function installedExtensionTier(extension, builtin, blobs, verifyBy
65
185
  }
66
186
  if (!verifyBytes)
67
187
  return "trusted";
68
- const bytes = await blobs.get(extension.sha256);
69
- return `sha512-${createHash("sha512").update(bytes).digest("base64")}` === evidence.integrity
188
+ return integrityOf(await blobs.get(extension.sha256)) === evidence.integrity
70
189
  ? "trusted"
71
190
  : "refused";
72
191
  }
192
+ /** The forcing keys each full-access realm of a live grant still covers. */
193
+ function coveredForcing(grant) {
194
+ if (!grant || !isLive(grant.state))
195
+ return {};
196
+ const serving = new Set(effectiveKeys(grant));
197
+ const out = {};
198
+ for (const realm of EXECUTION_REALMS) {
199
+ const forcing = grant.realms[realm];
200
+ if (!forcing || !serving.has(fullAccessKey(realm)))
201
+ continue;
202
+ const retired = new Set(grant.retiredForcing[realm] ?? []);
203
+ out[realm] = forcing.filter((key) => !retired.has(key));
204
+ }
205
+ return out;
206
+ }
207
+ /**
208
+ * Per full-access realm of a decision, the forcing keys a grant does not cover: its realm key must
209
+ * still serve and each forcing key must be reviewed and not retired. Empty when the grant covers
210
+ * every realm. The single realm-coverage rule (the shadow execution decision, and the revision
211
+ * approvals' shadow decision of plan task 1.3a).
212
+ */
213
+ export function uncoveredForcing(decision, grant) {
214
+ const covered = coveredForcing(grant);
215
+ const uncovered = {};
216
+ for (const realm of EXECUTION_REALMS) {
217
+ const forcing = decision.fullAccess[realm];
218
+ if (!forcing)
219
+ continue;
220
+ const have = new Set(covered[realm] ?? []);
221
+ const missing = forcing.filter((key) => !have.has(key));
222
+ if (missing.length > 0)
223
+ uncovered[realm] = missing;
224
+ }
225
+ return uncovered;
226
+ }
227
+ /**
228
+ * The shadow execution decision of one installed revision (plan task 1.3b; rollout fence "shadow
229
+ * mode until 1.5a"): computed and reported, never refused. `keys` are the revision's canonical
230
+ * permission keys; `grant` is its newest grant generation (any state), if any.
231
+ */
232
+ export function shadowExecution(input) {
233
+ const { section, grant, host } = input;
234
+ const decision = executionDecision({
235
+ keys: input.keys,
236
+ server: true,
237
+ ...(section.client !== undefined && { client: {} }),
238
+ host,
239
+ configSchemaIsolatable: deploymentConfigIsolatable(section),
240
+ });
241
+ const uncovered = uncoveredForcing(decision, grant);
242
+ const live = grant !== undefined && isLive(grant.state);
243
+ const serverForcing = live ? (grant.realms.server ?? []) : [];
244
+ const retiredServer = grant?.retiredForcing.server ?? [];
245
+ const hostReasonRetired = host !== "available" &&
246
+ retiredServer.includes(HOST_NO_ISOLATION_KEY) &&
247
+ (decision.fullAccess.server ?? []).includes(HOST_NO_ISOLATION_KEY);
248
+ const retireHostReason = host === "available" &&
249
+ serverForcing.includes(HOST_NO_ISOLATION_KEY) &&
250
+ !retiredServer.includes(HOST_NO_ISOLATION_KEY);
251
+ let would;
252
+ if (decision.kind === "declarative")
253
+ would = "declarative";
254
+ else if (decision.server.mode === "unavailable")
255
+ would = "unavailable";
256
+ else if (Object.keys(uncovered).length > 0)
257
+ would = "pending_review";
258
+ else if (decision.server.mode === "full-access")
259
+ would = "in_process";
260
+ else if (decision.server.mode === "isolated")
261
+ would = "isolated";
262
+ else
263
+ would = "client_only";
264
+ const legacyPlacement = input.legacy === "trusted" ? "in_process" : "isolated";
265
+ return {
266
+ plugin: input.plugin,
267
+ version: input.version,
268
+ legacy: input.legacy,
269
+ host,
270
+ decision,
271
+ ...(live && { generation: grant.generation }),
272
+ uncovered,
273
+ hostReasonRetired,
274
+ retireHostReason,
275
+ would,
276
+ diverges: would !== legacyPlacement,
277
+ };
278
+ }
279
+ /** {@link shadowExecution} for an installed revision, its keys read from its reviewed section. */
280
+ export function shadowExecutionOf(extension, legacy, host, grant) {
281
+ return shadowExecution({
282
+ plugin: extension.name,
283
+ version: extension.version,
284
+ legacy,
285
+ section: extension.section,
286
+ // Migration-derived keys (own tables, warning digests) fit isolation, so the section's
287
+ // declarations decide the realms without reading the migration SQL.
288
+ keys: permissionKeys(permissionSetOfSection(extension.section, [])),
289
+ host,
290
+ grant,
291
+ });
292
+ }
293
+ /**
294
+ * What the isolated admission takes from a revision's newest grant: whether its live grant covers
295
+ * every browser forcing key of the revision (its client entry beside an isolated server).
296
+ */
297
+ export function isolatedSectionGrant(extension, grant) {
298
+ if (extension.section.client === undefined || !grant || !isLive(grant.state))
299
+ return {};
300
+ const shadow = shadowExecutionOf(extension, "isolated", "available", grant);
301
+ return {
302
+ browserFullAccess: shadow.decision.browser.mode === "full-access" && shadow.uncovered.browser === undefined,
303
+ };
304
+ }
305
+ /**
306
+ * Whether a convergence keeps the admission of a revision this replica already serves (`serving`,
307
+ * its current tier; undefined when it does not serve this exact revision). Shadow mode until task
308
+ * 1.5a: a grant change is reported, never acted on.
309
+ * - `pin_only_grant`: a pin-only revision's grant changed (a retired host reason, a revoked realm or
310
+ * grant); kept until enforcing, when 1.3e's afterRevocation moves or refuses it.
311
+ * - `browser_grant`: the browser realm beside an isolated server is no longer covered; kept in the
312
+ * same tier until enforcing.
313
+ * - `extra_pin_grant`: a bootstrap-source revision (an extra-manifest pin placed by its grant,
314
+ * #1371) whose grant changed (revoked, a host reason retired); kept until enforcing. A built-in
315
+ * pin's placement depends only on its exact revision, so keeping it changes nothing.
316
+ * - `grant_read_failed`: the grant could not be read; always kept (a read error is no refusal).
317
+ */
318
+ export function keepsServingAdmission(input) {
319
+ const { serving, enforced } = input;
320
+ if (serving === undefined || serving === "refused")
321
+ return false;
322
+ switch (input.cause) {
323
+ case "grant_read_failed":
324
+ return true;
325
+ case "pin_only_grant":
326
+ case "extra_pin_grant":
327
+ return !enforced;
328
+ case "browser_grant":
329
+ return !enforced && serving === input.tier;
330
+ }
331
+ }
@@ -0,0 +1,134 @@
1
+ import { type Kysely } from "kysely";
2
+ import type { KernelSchemaDb } from "../../db/kernel-schema.js";
3
+ /**
4
+ * Isolated extension usage counters (isolation capacity spec 2026-12-04, §7 "Usage counters";
5
+ * plan task 1.2c): invocations, busy lane time, stream frames, broker callbacks by family and
6
+ * `ctx.net` bytes out and in per (org, plugin), in hourly buckets of `capybara.extension_usage`.
7
+ * Work with no org (deployment mode) is not metered here; the metrics cover it.
8
+ *
9
+ * A replica-local timer flushes this replica's own in-process increments, as AGENTS.md
10
+ * "Multi-replica discipline" allows when the flush is:
11
+ * - **idempotent:** each batch is one statement that records its id in `extension_usage_batches`
12
+ * and adds its rows (`amount = amount + EXCLUDED.amount`, rows sorted by key so two replicas
13
+ * lock shared rows in the same order). Replicas writing the same bucket never overwrite each
14
+ * other, and a batch whose outcome is unknown is retried with its id and counts once;
15
+ * - **bounded:** at most {@link MAX_KEYS} keys are held between flushes, and at most
16
+ * {@link MAX_UNCONFIRMED_BATCHES} batches ({@link MAX_UNCONFIRMED_ROWS} rows) wait for a retry;
17
+ * past either cap the oldest increments are dropped with a warning;
18
+ * - **stopped on shutdown:** the extension host's close stops the timer and makes one last
19
+ * flush, cut off after {@link USAGE_FINAL_FLUSH_TIMEOUT_MS};
20
+ * - **lossy within a stated window:** a crash loses the increments since the last flush, at most
21
+ * one interval ({@link USAGE_FLUSH_INTERVAL_MS}, 10 s). While PostgreSQL is unreachable the
22
+ * unflushed backlog grows up to the caps above (about {@link MAX_UNCONFIRMED_BATCHES} intervals
23
+ * for a busy replica) and a crash then loses that backlog; a batch still failing after an hour
24
+ * is dropped. These are capacity and usage-trend counters, not a ledger.
25
+ *
26
+ * Why not `@LockedInterval`: a locked interval runs once per tick across all replicas, so only one
27
+ * replica would flush and every other replica's counters would never reach PostgreSQL. Each
28
+ * replica (api, worker and gateway alike) runs isolated calls and must flush its own increments;
29
+ * the timer carries no cross-replica state, and the source of truth is the table.
30
+ */
31
+ export declare const USAGE_FLUSH_INTERVAL_MS = 10000;
32
+ /** The last flush on shutdown gives up after this long (the batch is then lost). */
33
+ export declare const USAGE_FINAL_FLUSH_TIMEOUT_MS = 5000;
34
+ /** Distinct (org, plugin, hour, counter) keys held between flushes, against a runaway. */
35
+ export declare const MAX_KEYS = 100000;
36
+ /** Batches kept for a retry while PostgreSQL fails; the oldest go first past the cap. */
37
+ export declare const MAX_UNCONFIRMED_BATCHES = 360;
38
+ /** Rows across those batches; the oldest batches go first past the cap. */
39
+ export declare const MAX_UNCONFIRMED_ROWS = 200000;
40
+ export type UsageCounter = "invocations" | "busy_lane_ms" | "stream_frames" | "net_bytes_out" | "net_bytes_in" | `broker.${string}`;
41
+ export interface UsageIncrement {
42
+ orgId: string;
43
+ plugin: string;
44
+ /** Start of the hour, ISO 8601. */
45
+ hour: string;
46
+ counter: UsageCounter;
47
+ amount: number;
48
+ }
49
+ export declare function hourOf(at: number): string;
50
+ /** This replica's increments since the last flush, summed per (org, plugin, hour, counter). */
51
+ export declare class ExtensionUsageCounters {
52
+ private readonly now;
53
+ private pending;
54
+ private readonly checkpoints;
55
+ private dropped;
56
+ constructor(now?: () => number);
57
+ add(orgId: string, plugin: string, counter: UsageCounter, amount: number): void;
58
+ /** A function that books work still running (busy lanes) before each {@link take}. */
59
+ onCheckpoint(checkpoint: () => void): () => void;
60
+ /** Books running work, then hands over and clears everything counted so far. */
61
+ take(): {
62
+ increments: UsageIncrement[];
63
+ dropped: number;
64
+ };
65
+ }
66
+ /**
67
+ * Applies one batch: records its id and adds every increment, in one statement (one transaction).
68
+ * A batch id already recorded adds nothing. Rows of an org deleted since are skipped.
69
+ */
70
+ export declare function applyUsageBatch(db: Kysely<unknown> | KernelSchemaDb, id: string, increments: readonly UsageIncrement[]): Promise<boolean>;
71
+ export interface UsageFlusherOptions {
72
+ db: Kysely<unknown> | KernelSchemaDb;
73
+ counters: ExtensionUsageCounters;
74
+ intervalMs?: number;
75
+ onError?: (err: unknown) => void;
76
+ onDropped?: (detail: {
77
+ rows: number;
78
+ amount?: number;
79
+ }) => void;
80
+ now?: () => number;
81
+ }
82
+ /** Flushes one replica's {@link ExtensionUsageCounters} every interval; see the module comment. */
83
+ export declare class ExtensionUsageFlusher {
84
+ private readonly options;
85
+ /** Batches taken but not yet confirmed applied, retried in order with their ids. */
86
+ private readonly unconfirmed;
87
+ private timer;
88
+ private flushing;
89
+ private running;
90
+ private lastSweep;
91
+ private readonly inOwnContext;
92
+ constructor(options: UsageFlusherOptions);
93
+ start(): void;
94
+ /**
95
+ * Graceful shutdown: stops the timer, then one last flush of everything counted, cut off after
96
+ * `timeoutMs` (what is still unflushed then is lost and reported).
97
+ */
98
+ stop(timeoutMs?: number): Promise<void>;
99
+ /** One flush; concurrent callers share it. Never rejects. */
100
+ flush(): Promise<void>;
101
+ private now;
102
+ private flushOnce;
103
+ /** Drops the oldest unconfirmed batches beyond the batch and row caps, with a warning. */
104
+ private capUnconfirmed;
105
+ /** Batches waiting for a retry (tests and diagnostics). */
106
+ get pendingBatches(): number;
107
+ private schedule;
108
+ }
109
+ /** Forgets applied batch ids older than a day (deployment state, no org). */
110
+ export declare function sweepUsageBatches(db: Kysely<unknown> | KernelSchemaDb): Promise<void>;
111
+ export interface ExtensionUsageRow {
112
+ orgId: string;
113
+ plugin: string;
114
+ /** Start of the hour. */
115
+ hour: Date;
116
+ invocations: number;
117
+ busyLaneSeconds: number;
118
+ streamFrames: number;
119
+ netBytesOut: number;
120
+ netBytesIn: number;
121
+ /** Broker callbacks by family (`kv`, `net`, `storage`, ...). */
122
+ brokerCallbacks: Record<string, number>;
123
+ }
124
+ /**
125
+ * The read seam for saturation views (plan task 4.2d) and a later chargeback: usage rows in
126
+ * `[from, to)` by org, plugin and hour. It reads under the caller's scope: an org scope sees that
127
+ * org's rows (RLS); a deployment-wide view calls it inside `asPlatform`.
128
+ */
129
+ export declare function readExtensionUsage(db: KernelSchemaDb, filter: {
130
+ from: Date;
131
+ to: Date;
132
+ orgId?: string;
133
+ plugin?: string;
134
+ }): Promise<ExtensionUsageRow[]>;