@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
@@ -16,8 +16,8 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
17
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
18
18
  import { officialPublisherProofMode } from "../catalog/publisher-policy.js";
19
+ import { resolveCapacity } from "../config/capacity-presets.js";
19
20
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
20
- import { EXTENSION_CAPACITY_DEFAULTS } from "../config/schema.js";
21
21
  import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
22
22
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
23
23
  import { ExtensionEffects } from "../ctx/durable-effects.service.js";
@@ -35,7 +35,7 @@ import { INBOX_ITEMS_BACKEND } from "../inbox/token.js";
35
35
  import { waitWithin } from "../infra/close-within.js";
36
36
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
37
37
  import { KernelDb } from "../infra/database/kernel-db.js";
38
- import { withOrgScope } from "../infra/database/org-scope.js";
38
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
39
39
  import { LockService } from "../infra/lock/lock.service.js";
40
40
  import { KERNEL_LOGGER, KEYRING, REDIS, REDIS_SUBSCRIBER } from "../infra/tokens.js";
41
41
  import { KERNEL_APP_OPTIONS, KERNEL_FIXTURE_TRUST, } from "../lifecycle/tokens.js";
@@ -57,19 +57,22 @@ import { GrantEpoch, grantEpochReader, grantEpochReadTimeoutMs } from "./grant-e
57
57
  import { HookRegistry } from "./hooks.js";
58
58
  import { ExtensionInstalls } from "./installs.js";
59
59
  import { ImportTracker, importExtensionModule, ManifestMismatchError, matchesSection, setupInstance, warnUpgrades, } from "./instance.js";
60
- import { assertIsolatedSection, isolatedDeploymentSchema } from "./isolated/admission.js";
60
+ import { assertIsolatedSection, isolatedDeploymentSchema, } from "./isolated/admission.js";
61
61
  import { IsolatedInvocationGrants, readIsolatedGrant, } from "./isolated/authorization.js";
62
62
  import { readConfiguredExtensionPackage, stageConfiguredExtensionPackage, } from "./isolated/configured-package.js";
63
63
  import { IsolatedExtensionQuota } from "./isolated/lanes.js";
64
+ import { IsolationObserver, OrgLabels, observeGrantEpochLag } from "./isolated/metrics.js";
64
65
  import { isolatedRevision } from "./isolated/revision.js";
65
- import { sweepExtensionSandboxOrphans } from "./isolated/sandbox.js";
66
- import { publisherProofMissing, publisherProofRefusal, } from "./isolated/tier.js";
66
+ import { probeExtensionSandboxChecks, sweepExtensionSandboxOrphans, } from "./isolated/sandbox.js";
67
+ import { GrantReadError, isolatedSectionGrant, keepsServingAdmission, publisherProofMissing, publisherProofRefusal, shadowExecutionOf, } from "./isolated/tier.js";
68
+ import { ExtensionUsageCounters, ExtensionUsageFlusher } from "./isolated/usage.js";
67
69
  import { parseLoadGate } from "./org-levels.js";
68
70
  import { declaredDisplayName, permissionSetOfSection, readMigrationSql } from "./package.js";
69
71
  import { blockingKeys, computePermissionSet, SETUP_CHECK_KEY_PREFIX, UI_VIEW_KEY_PREFIX, } from "./permission-set.js";
70
72
  import { ExtensionRegistry } from "./registry.js";
71
73
  import { ExtensionResolveError, electSingleProviders, PROVIDER_CONFLICT, providerConflictMessage, resolveExtensions, } from "./resolve.js";
72
74
  import { ExtensionRevisionApprovals } from "./revision-approvals.js";
75
+ import { leaseStateOf, REVOCATION_ENFORCEMENT, RevisionLeases, RevocationPendingError, readGrantSurfaceBySha256, readGrantSurfacesBySha256, realmAfterRevocation, } from "./revocation-leases.js";
73
76
  import { ReplicaStatusStore, } from "./sources.js";
74
77
  import { PackageShaMismatchError, packageRootOf } from "./sync.js";
75
78
  export { deploymentConfigHash };
@@ -257,6 +260,11 @@ export function assertSecretsReachable(manifest) {
257
260
  }
258
261
  /** 按模块解析的插件(配置声明)的迁移目录:清单 `migrations` 相对模块所在目录。 */
259
262
  const migrationsDirOf = (m, dir) => m.migrations ? resolvePath(dir, m.migrations) : undefined;
263
+ /**
264
+ * A pending status reason: the revision's grant could not be read (plan task 1.3b). It is retried
265
+ * at the next convergence; a serving revision keeps its tier instead.
266
+ */
267
+ export const GRANT_UNAVAILABLE = "grant_unavailable";
260
268
  /**
261
269
  * 由审阅过的静态清单拼出解析依赖、判定权限闸门用的清单(没有 setup 与配置 schema,不能用来加载)。
262
270
  * 闸门放行后导入的真实模块必须与静态清单一致({@link matchesSection}),两者在依赖解析上等价。
@@ -413,9 +421,21 @@ let ExtensionHost = class ExtensionHost {
413
421
  isolatedAuthority = new WeakMap();
414
422
  isolatedLanes = new WeakMap();
415
423
  isolatedGrants;
416
- /** This replica's view of the deployment grant epoch; polls only once an isolated grant was issued. */
424
+ /** The permission leases of this replica's instances (revocation, plan task 1.3e). */
425
+ revisionLeases;
426
+ /**
427
+ * This replica's view of the deployment grant epoch; polls once an isolated grant was issued or
428
+ * an instance with a package opened its permission lease.
429
+ */
417
430
  grantEpoch;
418
431
  epochReader;
432
+ /** Which orgs get their own label on the isolation metrics (the largest few). */
433
+ orgLabels;
434
+ /** This replica's isolated usage increments, flushed every 10 s once isolated work started. */
435
+ usageCounters = new ExtensionUsageCounters();
436
+ usageFlusher;
437
+ unobserveEpochLag;
438
+ capacityCache;
419
439
  executionTier = new Map();
420
440
  policyExpected = new Map();
421
441
  /**
@@ -550,7 +570,9 @@ let ExtensionHost = class ExtensionHost {
550
570
  * Shadow revision approvals (plan task 1.2b): reported at start, never refusing. Absent in a
551
571
  * hand-built host, which then reports nothing.
552
572
  */
553
- revisionApprovals) {
573
+ revisionApprovals,
574
+ /** Kernel tests only: enforce revocation before plan task 1.5a (`REVOCATION_ENFORCEMENT`). */
575
+ revocationEnforcement) {
554
576
  this.registry = registry;
555
577
  this.installs = installs;
556
578
  this.approvals = approvals;
@@ -574,8 +596,7 @@ let ExtensionHost = class ExtensionHost {
574
596
  config: () => ({ hooks: { timeoutMs: this.config.get().hooks.timeoutMs } }),
575
597
  log,
576
598
  });
577
- // Hand-built configs (tests, embedders) may leave the capacity object out.
578
- const capacity = { ...EXTENSION_CAPACITY_DEFAULTS, ...c.extensionHost.capacity };
599
+ const capacity = this.capacity();
579
600
  this.epochReader = grantEpochReader({
580
601
  url: c.db.url,
581
602
  readTimeoutMs: grantEpochReadTimeoutMs(capacity.grantEpochMaxAgeMs),
@@ -589,15 +610,84 @@ let ExtensionHost = class ExtensionHost {
589
610
  void this.isolatedGrants
590
611
  .epochChanged()
591
612
  .catch((err) => this.log.warn("isolated extension grant revalidation failed", { err }));
613
+ void this.revisionLeases
614
+ .epochChanged()
615
+ .catch((err) => this.log.warn("extension permission lease revalidation failed", { err }));
616
+ },
617
+ onSettleDeadline: () => {
618
+ this.isolatedGrants.fenceStale();
619
+ this.revisionLeases.fenceStale();
592
620
  },
593
- onSettleDeadline: () => this.isolatedGrants.fenceStale(),
594
621
  onExpired: () => {
595
622
  this.log.warn("isolated extension grants fenced: the grant epoch could not be read");
596
623
  this.isolatedGrants.fenceAll();
624
+ this.revisionLeases.fenceAll();
597
625
  },
598
626
  onFault: (err) => this.log.warn("reading the extension grant epoch failed", { err }),
599
627
  });
600
- this.isolatedGrants = new IsolatedInvocationGrants(this.grantEpoch, capacity.grantCacheEntries);
628
+ this.isolatedGrants = new IsolatedInvocationGrants(this.grantEpoch, capacity.grantCacheEntries, () => performance.now(), capacity.grantFullRevalidationMs);
629
+ const grantReads = kernelDb(kdb.pool);
630
+ this.revisionLeases = new RevisionLeases({
631
+ epochs: this.grantEpoch,
632
+ // one query for every lease of a fence or epoch change
633
+ read: async (sha256s) => {
634
+ const grants = await readGrantSurfacesBySha256(grantReads, sha256s);
635
+ return new Map(sha256s.map((sha256) => [sha256, leaseStateOf(grants.get(sha256))]));
636
+ },
637
+ ...(revocationEnforcement === true && { enforce: true }),
638
+ onUnload: (plugin) => {
639
+ this.log.warn("extension grant revoked: unloading its generation", { plugin });
640
+ void this.converge().catch((err) => this.log.error("converging after a grant revocation failed", { plugin, err }));
641
+ },
642
+ onRestored: (plugin) => {
643
+ // withdrawn registrations come back only with a new setup
644
+ this.log.info("extension grant restored withdrawn keys: reloading it", { plugin });
645
+ void this.reload(plugin).catch((err) => this.log.error("reloading after a restored grant failed", { plugin, err }));
646
+ },
647
+ onFault: (plugin, err) => this.log.warn("reading an extension's revision grant failed", { plugin, err }),
648
+ // shadow mode until plan task 1.5a: what enforcement would do, logged and never enforced
649
+ onShadow: (plugin, decision) => this.log.warn("extension revocation computed (shadow mode, not enforced)", {
650
+ plugin,
651
+ ...("refusedCall" in decision
652
+ ? { wouldRefuseCall: decision.refusedCall }
653
+ : {
654
+ wouldWithdrawOrRefuse: decision.refused,
655
+ wouldUnloadInProcess: decision.lostServerFullAccess,
656
+ wouldUnload: decision.revoked,
657
+ status: decision.state.status,
658
+ }),
659
+ }),
660
+ });
661
+ this.unobserveEpochLag = observeGrantEpochLag(() => this.grantEpoch.lagSeconds());
662
+ this.orgLabels = new OrgLabels({
663
+ limits: () => ({
664
+ minMembers: this.config.get().metrics?.orgLabelMinMembers ?? 1_000,
665
+ maxOrgs: this.config.get().metrics?.orgLabelMaxOrgs ?? 20,
666
+ }),
667
+ read: (minMembers, maxOrgs) => asPlatform("pick the org labels of the isolation metrics", async () => {
668
+ const rows = await kernelDb(this.deps.db)
669
+ .selectFrom("memberships")
670
+ .innerJoin("orgs", "orgs.id", "memberships.org_id")
671
+ .where("orgs.deleted_at", "is", null)
672
+ // Guests are not members for sizing: they do not make an org large.
673
+ .where("memberships.role", "!=", "guest")
674
+ .select(["memberships.org_id as orgId", (eb) => eb.fn.countAll().as("members")])
675
+ .groupBy("memberships.org_id")
676
+ .having((eb) => eb.fn.countAll(), ">=", minMembers)
677
+ .orderBy("members", "desc")
678
+ .orderBy("memberships.org_id")
679
+ .limit(maxOrgs)
680
+ .execute();
681
+ return rows.map((row) => ({ orgId: row.orgId, members: Number(row.members) }));
682
+ }),
683
+ onError: (err) => this.log.warn("reading the isolation metrics org labels failed", { err }),
684
+ });
685
+ this.usageFlusher = new ExtensionUsageFlusher({
686
+ db: kdb.pool,
687
+ counters: this.usageCounters,
688
+ onError: (err) => this.log.warn("flushing isolated extension usage failed", { err }),
689
+ onDropped: (detail) => this.log.warn("isolated extension usage increments were dropped", detail),
690
+ });
601
691
  this.deps = {
602
692
  db: kdb.pool,
603
693
  dbUrl: c.db.url,
@@ -671,6 +761,8 @@ let ExtensionHost = class ExtensionHost {
671
761
  }
672
762
  },
673
763
  locks,
764
+ leases: this.revisionLeases,
765
+ registrationsChanged: (plugin) => this.registry.registrationsChanged(plugin),
674
766
  runWorkers: c.roles.includes("worker"),
675
767
  log,
676
768
  };
@@ -772,6 +864,8 @@ let ExtensionHost = class ExtensionHost {
772
864
  await sweepExtensionSandboxOrphans(isolation.engineUrl).catch(() => {
773
865
  this.log.error("Could not sweep exited isolated extension sandboxes");
774
866
  });
867
+ // off the startup path: the probe can take up to the Engine deadline
868
+ void this.probeIsolation();
775
869
  }
776
870
  const entries = await importEntries(p.config ?? [], this.resolveFrom, this.options[KERNEL_FIXTURE_TRUST] !== undefined, this.config.get().packages.maxBytes, this.config.get().extensionHost.dir);
777
871
  for (const { manifest, isolated } of entries) {
@@ -860,6 +954,110 @@ let ExtensionHost = class ExtensionHost {
860
954
  });
861
955
  }
862
956
  }
957
+ /**
958
+ * This replica's isolation supervisor as last observed (plan task 1.3b): `not_configured`
959
+ * without `extensionHost.isolation`; otherwise `available` only after the Engine answered
960
+ * ({@link probeIsolation}), `failing` when it did not. Configuration alone is never readiness.
961
+ */
962
+ isolationState;
963
+ hostIsolation() {
964
+ if (!this.config.get().extensionHost.isolation)
965
+ return "not_configured";
966
+ return this.isolationState ?? "failing";
967
+ }
968
+ /**
969
+ * Probes the isolation supervisor with the same read-only Engine and image checks a sandbox start
970
+ * runs (Linux, cgroup v2, the mandatory security options, the local runtime image): the positive
971
+ * readiness signal host-reason retirement waits for. Called at load and on each periodic
972
+ * convergence, so the reported state may lag a failure by one period (reporting only: a sandbox
973
+ * start runs the checks again and fails closed).
974
+ */
975
+ async probeIsolation() {
976
+ const isolation = this.config.get().extensionHost.isolation;
977
+ if (!isolation) {
978
+ this.isolationState = undefined;
979
+ this.lastProbe = undefined;
980
+ return "not_configured";
981
+ }
982
+ const result = await probeExtensionSandboxChecks(isolation);
983
+ this.lastProbe = { result, at: new Date() };
984
+ this.isolationState = result.ok ? "available" : "failing";
985
+ return this.isolationState;
986
+ }
987
+ /** The last probe with its named checks (plan task 1.4j), undefined before any or unconfigured. */
988
+ lastProbe;
989
+ /**
990
+ * What this replica records for the isolation status projection (`ReplicaIsolationStore`): its
991
+ * last probe and the shadow placements of its last convergence.
992
+ */
993
+ isolationRecord() {
994
+ return { probe: this.lastProbe, shadow: this.executions };
995
+ }
996
+ /**
997
+ * The newest grant of each install's revision, or undefined when the read failed: a revision
998
+ * already serving then keeps its admission (a read error is never a refusal), and any other
999
+ * revision is admitted as without a grant (today's admission).
1000
+ */
1001
+ async grantSurfaces(desired) {
1002
+ try {
1003
+ return await readGrantSurfacesBySha256(kernelDb(this.deps.db), desired.map((d) => d.sha256));
1004
+ }
1005
+ catch (err) {
1006
+ this.log.warn("reading extension revision grants for admission failed", { err });
1007
+ return undefined;
1008
+ }
1009
+ }
1010
+ /** The last shadow execution report logged by this replica (log de-duplication, not state). */
1011
+ lastExecutionReport;
1012
+ /** The shadow execution decisions of the last convergence on this replica (for the inventory). */
1013
+ executions = [];
1014
+ /** This replica's shadow execution decisions of the installs it last converged. */
1015
+ shadowExecutions() {
1016
+ return this.executions;
1017
+ }
1018
+ /**
1019
+ * Shadow mode (plan task 1.3b, rollout fence until 1.5a): where each admitted install would run
1020
+ * under the execution-realm decision and whether its grant covers the forcing keys, including
1021
+ * the kernel's `host.no-isolation` on a host without isolation. Logged when it changes; never
1022
+ * refuses or moves a revision: the legacy tier governs.
1023
+ */
1024
+ reportShadowExecution(desired, tiers, grants) {
1025
+ try {
1026
+ const host = this.hostIsolation();
1027
+ const executions = [];
1028
+ for (const d of desired) {
1029
+ const tier = tiers.get(d.name);
1030
+ if (tier === undefined || tier === "refused")
1031
+ continue;
1032
+ executions.push(shadowExecutionOf(d, tier, host, grants.get(d.sha256)));
1033
+ }
1034
+ this.executions = executions;
1035
+ const notable = executions.filter((e) => e.diverges || e.hostReasonRetired || e.retireHostReason);
1036
+ const report = notable.map((e) => ({
1037
+ plugin: `${e.plugin}@${e.version}`,
1038
+ legacy: e.legacy,
1039
+ would: e.would,
1040
+ uncovered: e.uncovered,
1041
+ ...(e.hostReasonRetired && {
1042
+ hostReasonRetired: "host.no-isolation was retired when isolation was available; it is not restored, the revision needs a new review",
1043
+ }),
1044
+ ...(e.retireHostReason && { retireHostReason: true }),
1045
+ }));
1046
+ const digest = JSON.stringify({ host, report });
1047
+ if (digest === this.lastExecutionReport)
1048
+ return;
1049
+ this.lastExecutionReport = digest;
1050
+ if (report.length > 0) {
1051
+ this.log.info("shadow execution realms: the enforcing cutover would place these differently", {
1052
+ host,
1053
+ revisions: report,
1054
+ });
1055
+ }
1056
+ }
1057
+ catch (err) {
1058
+ this.log.warn("shadow execution decisions failed", { err });
1059
+ }
1060
+ }
863
1061
  /** The last shadow report logged by this replica (a log de-duplication, not state). */
864
1062
  lastShadowReport;
865
1063
  /**
@@ -1002,10 +1200,72 @@ let ExtensionHost = class ExtensionHost {
1002
1200
  }
1003
1201
  tierOf(loader, revision, verifyBytes) {
1004
1202
  const fixtures = this.options[KERNEL_FIXTURE_TRUST];
1005
- if (fixtures === true || fixtures?.installDigests.includes(revision.sha256)) {
1006
- return Promise.resolve("trusted");
1203
+ // Shadow mode (plan task 1.3b, until 1.5a): a pin-only revision is placed by its grant at
1204
+ // admission only. While its generation serves, a grant change (a retired host reason, a
1205
+ // revoked realm or grant) moves or refuses nothing; 1.3e's afterRevocation does that once
1206
+ // enforcing. Its bytes were verified at admission and a package sha256 never changes.
1207
+ const serving = this.servingTier(revision);
1208
+ // An extra-manifest pin placed by its grant (#1371) likewise keeps its serving tier
1209
+ const cause = publisherProofMissing(revision)
1210
+ ? "pin_only_grant"
1211
+ : revision.source === "bootstrap"
1212
+ ? "extra_pin_grant"
1213
+ : undefined;
1214
+ if (cause !== undefined &&
1215
+ keepsServingAdmission({ serving, enforced: this.revisionLeases.enforced, cause })) {
1216
+ return Promise.resolve(serving);
1007
1217
  }
1008
- return loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated");
1218
+ const tier = fixtures === true || fixtures?.installDigests.includes(revision.sha256)
1219
+ ? Promise.resolve("trusted")
1220
+ : (loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated"));
1221
+ return tier.then((t) => (t === "refused" ? t : this.afterRevocation(revision, t)));
1222
+ }
1223
+ /**
1224
+ * What the isolated admission of an instance start takes from its grant. In shadow mode the
1225
+ * activation's decision (a reload reuses it; a grant change is reported, not enforced); once
1226
+ * enforcing (task 1.5a) the grant is read again, so a reload follows a revoked browser realm.
1227
+ */
1228
+ async isolatedGrantFor(spec) {
1229
+ const isolated = spec.isolated;
1230
+ if (!isolated || !this.revisionLeases.enforced || !spec.sha256)
1231
+ return isolated?.grant;
1232
+ const grant = await readGrantSurfaceBySha256(kernelDb(this.deps.db), spec.sha256);
1233
+ return isolatedSectionGrant({ name: spec.manifest.name, version: spec.manifest.version, section: isolated.section }, grant);
1234
+ }
1235
+ /** The tier this replica serves the exact revision in, or undefined when it does not serve it. */
1236
+ servingTier(revision) {
1237
+ return this.registry.current(revision.name)?.sha256 === revision.sha256
1238
+ ? this.executionTier.get(revision.name)
1239
+ : undefined;
1240
+ }
1241
+ /**
1242
+ * The tier after a revocation (plan task 1.3e; enforced from task 1.5a, until then the leases
1243
+ * only report it). A revision whose whole grant is revoked waits for a new review. A trusted
1244
+ * (in-process) revision whose grant no longer serves server full access runs isolated when the
1245
+ * remaining grant fits the sandbox and the package has an isolated form, and otherwise waits for
1246
+ * a new review ({@link RevocationPendingError}: reported pending, not failed).
1247
+ */
1248
+ async afterRevocation(revision, tier) {
1249
+ if (!this.revisionLeases.enforced)
1250
+ return tier;
1251
+ const grant = await readGrantSurfaceBySha256(kernelDb(this.deps.db), revision.sha256);
1252
+ if (!grant)
1253
+ return tier;
1254
+ if (grant.state === "revoked") {
1255
+ throw new RevocationPendingError("The revision's grant was revoked; it waits for a new review");
1256
+ }
1257
+ if (tier !== "trusted" || !leaseStateOf(grant).realmsRevoked.includes("server"))
1258
+ return tier;
1259
+ if (realmAfterRevocation(grant, "server") === "isolated") {
1260
+ try {
1261
+ assertIsolatedSection(revision.section, isolatedSectionGrant(revision, grant));
1262
+ return "isolated";
1263
+ }
1264
+ catch {
1265
+ throw new RevocationPendingError("Full access for the server realm was revoked and the package has no isolated form; it waits for a new review");
1266
+ }
1267
+ }
1268
+ throw new RevocationPendingError("Full access for the server realm was revoked and the remaining grant still needs it; it waits for a new review");
1009
1269
  }
1010
1270
  /**
1011
1271
  * Reconciles enabled installs from PostgreSQL at startup and during convergence. It removes
@@ -1028,6 +1288,11 @@ let ExtensionHost = class ExtensionHost {
1028
1288
  const rejected = new Map();
1029
1289
  const rejectedActions = new Map();
1030
1290
  let proofMode;
1291
+ /** Revisions a revocation sends back to review: pending, not failed (plan task 1.3e). */
1292
+ const awaitingReview = new Map();
1293
+ /** Revisions whose grant could not be read: they wait for the next convergence. */
1294
+ const grantUnavailable = new Set();
1295
+ const grantsBySha = await this.grantSurfaces(electAmong);
1031
1296
  for (const d of electAmong) {
1032
1297
  if (declared.has(d.name))
1033
1298
  continue;
@@ -1045,14 +1310,42 @@ let ExtensionHost = class ExtensionHost {
1045
1310
  }
1046
1311
  continue;
1047
1312
  }
1048
- if (tier === "isolated")
1049
- assertIsolatedSection(d.section);
1313
+ // A serving revision keeps its isolated admission when the grant read failed (a read
1314
+ // error is no refusal) and, in shadow mode, when its grant changed (the browser realm
1315
+ // revoked): reported now, enforced from task 1.5a.
1316
+ const serving = this.servingTier(d);
1317
+ const keep = serving === tier &&
1318
+ keepsServingAdmission({
1319
+ serving,
1320
+ tier,
1321
+ enforced: this.revisionLeases.enforced,
1322
+ cause: grantsBySha === undefined ? "grant_read_failed" : "browser_grant",
1323
+ });
1324
+ if (tier === "isolated" && !keep) {
1325
+ assertIsolatedSection(d.section, isolatedSectionGrant(d, grantsBySha?.get(d.sha256)));
1326
+ }
1050
1327
  tiers.set(d.name, tier);
1051
1328
  }
1052
1329
  catch (error) {
1053
- rejected.set(d.name, errMsg(error));
1330
+ const serving = this.servingTier(d);
1331
+ const keep = error instanceof GrantReadError &&
1332
+ keepsServingAdmission({
1333
+ serving,
1334
+ enforced: this.revisionLeases.enforced,
1335
+ cause: "grant_read_failed",
1336
+ });
1337
+ if (keep)
1338
+ tiers.set(d.name, serving);
1339
+ else if (error instanceof GrantReadError)
1340
+ grantUnavailable.add(d.name);
1341
+ else if (error instanceof RevocationPendingError)
1342
+ awaitingReview.set(d.name, error.message);
1343
+ else
1344
+ rejected.set(d.name, errMsg(error));
1054
1345
  }
1055
1346
  }
1347
+ if (grantsBySha)
1348
+ this.reportShadowExecution(electAmong, tiers, grantsBySha);
1056
1349
  // Single-provider election: of the enabled install records providing one single-provider
1057
1350
  // extension point, only the earliest enabled is loaded (desired() order: enabled_at, install
1058
1351
  // time, name). Decided from PG alone, never from what loaded here, so every replica and every
@@ -1112,6 +1405,33 @@ let ExtensionHost = class ExtensionHost {
1112
1405
  detail: null,
1113
1406
  });
1114
1407
  }
1408
+ for (const d of desired) {
1409
+ if (!grantUnavailable.has(d.name))
1410
+ continue;
1411
+ await this.writeStatus({
1412
+ plugin: d.name,
1413
+ version: d.version,
1414
+ sha256: d.sha256,
1415
+ source: "install",
1416
+ state: "pending",
1417
+ reason: GRANT_UNAVAILABLE,
1418
+ detail: "The revision's grant could not be read; retried at the next convergence",
1419
+ });
1420
+ }
1421
+ for (const d of desired) {
1422
+ const waiting = awaitingReview.get(d.name);
1423
+ if (waiting === undefined)
1424
+ continue;
1425
+ await this.writeStatus({
1426
+ plugin: d.name,
1427
+ version: d.version,
1428
+ sha256: d.sha256,
1429
+ source: "install",
1430
+ state: "pending",
1431
+ reason: "approval",
1432
+ detail: waiting,
1433
+ });
1434
+ }
1115
1435
  for (const d of desired) {
1116
1436
  const detail = rejected.get(d.name);
1117
1437
  if (!detail)
@@ -1142,16 +1462,29 @@ let ExtensionHost = class ExtensionHost {
1142
1462
  else if (current?.sha256 === d.sha256) {
1143
1463
  continue;
1144
1464
  }
1145
- if (tier === "trusted") {
1465
+ // a pin-only revision (no publisher proof) is verified whatever tier its grant gives it
1466
+ if (tier === "trusted" || publisherProofMissing(d)) {
1146
1467
  let verified = "refused";
1147
1468
  try {
1148
1469
  verified = await this.tierOf(loader, d, true);
1149
1470
  }
1150
- catch {
1471
+ catch (error) {
1472
+ if (error instanceof GrantReadError) {
1473
+ await this.writeStatus({
1474
+ plugin: d.name,
1475
+ version: d.version,
1476
+ sha256: d.sha256,
1477
+ source: "install",
1478
+ state: "pending",
1479
+ reason: GRANT_UNAVAILABLE,
1480
+ detail: "The revision's grant could not be read; retried at the next convergence",
1481
+ });
1482
+ continue;
1483
+ }
1151
1484
  // The refusal below reports the failed integrity check without logging verifier internals.
1152
1485
  }
1153
- if (verified !== "trusted") {
1154
- const detail = "The trusted extension package did not match its verified integrity";
1486
+ if (verified !== tier) {
1487
+ const detail = "The extension package did not match its verified integrity";
1155
1488
  await this.reportAdmissionRefusal(d.name, d.sha256, detail, "Check publisher verification and reimport the verified package.");
1156
1489
  await this.writeStatus({
1157
1490
  plugin: d.name,
@@ -1169,7 +1502,9 @@ let ExtensionHost = class ExtensionHost {
1169
1502
  if (c)
1170
1503
  candidates.push(c);
1171
1504
  }
1172
- // 与生效的插件一起解析依赖:被替换的旧实例在新的被接受之前仍算提供方;解析不过的反复重试直到没有新的能加进来
1505
+ // Resolve dependencies together with the serving extensions: a replaced old instance still
1506
+ // counts as a provider until its replacement is accepted; candidates that fail to resolve are
1507
+ // retried until no new one can be added
1173
1508
  const accepted = [];
1174
1509
  const base = () => {
1175
1510
  const replaced = new Set(accepted.map((a) => a.d.name));
@@ -1259,7 +1594,13 @@ let ExtensionHost = class ExtensionHost {
1259
1594
  const isolated = tiers.get(m.name) === "isolated";
1260
1595
  const a = {
1261
1596
  manifest: c.manifest,
1262
- ...(isolated && { isolated: { root: c.root, section: c.d.section } }),
1597
+ ...(isolated && {
1598
+ isolated: {
1599
+ root: c.root,
1600
+ section: c.d.section,
1601
+ grant: isolatedSectionGrant(c.d, grantsBySha?.get(c.d.sha256)),
1602
+ },
1603
+ }),
1263
1604
  source: "install",
1264
1605
  optionalBootstrap: c.d.source === "bootstrap" && !c.d.required,
1265
1606
  sha256: c.d.sha256,
@@ -1650,7 +1991,7 @@ let ExtensionHost = class ExtensionHost {
1650
1991
  }
1651
1992
  if (a.isolated && decision.action !== "pending") {
1652
1993
  try {
1653
- assertIsolatedSection(a.isolated.section);
1994
+ assertIsolatedSection(a.isolated.section, a.isolated.grant);
1654
1995
  manifest = isolatedManifestOf(a.isolated.section);
1655
1996
  }
1656
1997
  catch (error) {
@@ -1917,6 +2258,18 @@ let ExtensionHost = class ExtensionHost {
1917
2258
  this.isolatedLanes.get(instance)?.revokeOrg(scope.orgId);
1918
2259
  }
1919
2260
  }
2261
+ /**
2262
+ * A committed grant revocation (the local fence after the commit, or a sibling's hint): this
2263
+ * replica's leases of the plugin revalidate now (plan task 1.3e).
2264
+ */
2265
+ fenceRevocation(plugin) {
2266
+ return this.revisionLeases.fence(plugin);
2267
+ }
2268
+ /** The revocation decisions this replica's leases computed for a plugin's instances. */
2269
+ revocationDecisions(plugin) {
2270
+ // the computed decisions of every instance of the plugin on this replica
2271
+ return this.revisionLeases.statesOf(plugin);
2272
+ }
1920
2273
  refreshIsolatedOrgIntent(orgId) {
1921
2274
  return this.isolatedGrants.refreshOrgIntent(orgId);
1922
2275
  }
@@ -2145,9 +2498,12 @@ let ExtensionHost = class ExtensionHost {
2145
2498
  throw new Error("The isolated extension supervisor is not configured");
2146
2499
  let quota = this.quota.get(name);
2147
2500
  if (!quota) {
2148
- quota = new IsolatedExtensionQuota();
2501
+ quota = new IsolatedExtensionQuota(() => this.capacity());
2149
2502
  this.quota.set(name, quota);
2150
2503
  }
2504
+ this.usageFlusher.start();
2505
+ const revision = spec.sha256 ?? spec.entryUrl;
2506
+ const observer = new IsolationObserver(name, revision, this.orgLabels.label, this.usageCounters);
2151
2507
  const modules = this.modules;
2152
2508
  const db = kernelDb(this.deps.db);
2153
2509
  const current = () => active !== undefined &&
@@ -2171,8 +2527,10 @@ let ExtensionHost = class ExtensionHost {
2171
2527
  const declared = spec.manifest.permissions?.network ?? [];
2172
2528
  manifest = await isolatedRevision({
2173
2529
  manifest,
2174
- revision: spec.sha256 ?? spec.entryUrl,
2530
+ revision,
2531
+ observer,
2175
2532
  section: spec.isolated.section,
2533
+ grant: await this.isolatedGrantFor(spec),
2176
2534
  identity,
2177
2535
  sandbox: {
2178
2536
  engineUrl: isolation.engineUrl,
@@ -2187,13 +2545,15 @@ let ExtensionHost = class ExtensionHost {
2187
2545
  onLanes: (value) => {
2188
2546
  lanes = value;
2189
2547
  },
2190
- onCrash: (retryAfterMs) => {
2191
- this.log.warn("Isolated extension sandbox exited unexpectedly", {
2192
- plugin: name,
2193
- retryAfterMs,
2194
- });
2548
+ onCrash: (retryAfterMs, cause) => {
2549
+ const exited = cause === "exited";
2550
+ this.log.warn(exited
2551
+ ? "Isolated extension sandbox exited unexpectedly"
2552
+ : "Isolated extension sandbox failed to start", { plugin: name, retryAfterMs });
2195
2553
  void this.status
2196
- .note(name, `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`)
2554
+ .note(name, exited
2555
+ ? `Isolated sandbox crashed. Retry is delayed by ${retryAfterMs} ms.`
2556
+ : `Isolated sandbox failed to start. Retry is delayed by ${retryAfterMs} ms.`)
2197
2557
  .catch(() => { });
2198
2558
  },
2199
2559
  cleanupFault: () => {
@@ -2244,6 +2604,7 @@ let ExtensionHost = class ExtensionHost {
2244
2604
  configHash: spec.configHash,
2245
2605
  permissions: spec.permissions,
2246
2606
  extensionDb,
2607
+ inProcess: !spec.isolated,
2247
2608
  onCtx: (c) => {
2248
2609
  if (c)
2249
2610
  ctx = c;
@@ -2905,6 +3266,7 @@ let ExtensionHost = class ExtensionHost {
2905
3266
  async close(opts = {}) {
2906
3267
  this.closed = true;
2907
3268
  this.grantEpoch.stop();
3269
+ this.unobserveEpochLag();
2908
3270
  await this.epochReader
2909
3271
  .close()
2910
3272
  .catch((err) => this.log.warn("closing the grant epoch connection failed", { err }));
@@ -2940,6 +3302,20 @@ let ExtensionHost = class ExtensionHost {
2940
3302
  this.log.error("plugin close failed", { plugin: inst.name, err: e });
2941
3303
  }
2942
3304
  }
3305
+ // Every isolated call has ended: book and flush this replica's last usage increments.
3306
+ await this.usageFlusher.stop();
3307
+ }
3308
+ /**
3309
+ * The resolved `extensionHost.capacity` (preset plus explicit fields), read at every isolated
3310
+ * admission and lane start so hot fields apply at once. Invalid fields fell back to the preset
3311
+ * when the config was parsed; the config service logs them.
3312
+ */
3313
+ capacity() {
3314
+ const from = this.config.get().extensionHost?.capacity;
3315
+ if (this.capacityCache?.from !== from || this.capacityCache === undefined) {
3316
+ this.capacityCache = { from, limits: resolveCapacity(from) };
3317
+ }
3318
+ return this.capacityCache.limits;
2943
3319
  }
2944
3320
  };
2945
3321
  ExtensionHost = __decorate([
@@ -2970,6 +3346,8 @@ ExtensionHost = __decorate([
2970
3346
  __param(21, Inject(EXTENSION_NET_SEAMS)),
2971
3347
  __param(22, Inject(ConfiguredExtensionDbIdentity)),
2972
3348
  __param(23, Optional()),
2973
- __param(23, Inject(ExtensionRevisionApprovals))
3349
+ __param(23, Inject(ExtensionRevisionApprovals)),
3350
+ __param(24, Optional()),
3351
+ __param(24, Inject(REVOCATION_ENFORCEMENT))
2974
3352
  ], ExtensionHost);
2975
3353
  export { ExtensionHost };