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

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 (51) hide show
  1. package/dist/agents/admin-agents.d.ts +20 -3
  2. package/dist/agents/admin-agents.js +38 -7
  3. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  4. package/dist/catalog/marketplace-fetch.js +7 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/provenance.d.ts +69 -0
  7. package/dist/catalog/provenance.js +108 -0
  8. package/dist/ctx/create-ctx.d.ts +16 -0
  9. package/dist/ctx/create-ctx.js +269 -34
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.js +2 -2
  12. package/dist/extensions/execution-realm.d.ts +96 -0
  13. package/dist/extensions/execution-realm.js +141 -0
  14. package/dist/extensions/extensions.module.js +3 -0
  15. package/dist/extensions/grant-epoch.d.ts +4 -2
  16. package/dist/extensions/grant-epoch.js +4 -2
  17. package/dist/extensions/host.d.ts +26 -3
  18. package/dist/extensions/host.js +135 -10
  19. package/dist/extensions/instance.d.ts +2 -0
  20. package/dist/extensions/instance.js +1 -0
  21. package/dist/extensions/isolated/admission.d.ts +6 -0
  22. package/dist/extensions/isolated/admission.js +17 -0
  23. package/dist/extensions/isolated/tier.d.ts +14 -0
  24. package/dist/extensions/isolated/tier.js +27 -0
  25. package/dist/extensions/ledger.d.ts +5 -0
  26. package/dist/extensions/ledger.js +16 -0
  27. package/dist/extensions/permission-view.d.ts +2 -2
  28. package/dist/extensions/publisher-proof.job.d.ts +39 -0
  29. package/dist/extensions/publisher-proof.job.js +160 -0
  30. package/dist/extensions/registry.d.ts +6 -0
  31. package/dist/extensions/registry.js +8 -0
  32. package/dist/extensions/review-hash.d.ts +114 -0
  33. package/dist/extensions/review-hash.js +145 -0
  34. package/dist/extensions/revision-grants.d.ts +10 -0
  35. package/dist/extensions/revocation-leases.d.ts +273 -0
  36. package/dist/extensions/revocation-leases.js +533 -0
  37. package/dist/extensions/revocation.d.ts +78 -0
  38. package/dist/extensions/revocation.js +202 -0
  39. package/dist/index.d.ts +6 -2
  40. package/dist/index.js +6 -2
  41. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  42. package/dist/lifecycle/kernel-lifecycle.js +24 -18
  43. package/dist/overrides.d.ts +5 -1
  44. package/dist/overrides.js +2 -0
  45. package/dist/packages/official-publisher.d.ts +44 -0
  46. package/dist/packages/official-publisher.js +147 -48
  47. package/dist/packages/provenance.d.ts +6 -0
  48. package/dist/packages/provenance.js +26 -9
  49. package/dist/platform/ops/admin-items.ops.js +1 -1
  50. package/dist/roles/worker.module.js +3 -0
  51. package/package.json +2 -2
@@ -0,0 +1,141 @@
1
+ import { CLIENT_KEY, ISOLATED_CLIENT_REALM_AVAILABLE, ISOLATED_EXTENSION_POINTS, PERMISSION_REALM_FIT, PROVIDER_CONTRACTS, permissionCatalogMatches, } from "@capybara-hq/plugin-sdk";
2
+ import { fullAccessKey } from "./revision-grants.js";
3
+ export const HOST_NO_ISOLATION_KEY = "host.no-isolation";
4
+ const sorted = (keys) => [...new Set(keys)].sort();
5
+ /** The realm a key forces, or `undefined` when it fits isolation (or is the kernel's own). */
6
+ function forcedRealm(key) {
7
+ const matches = permissionCatalogMatches(key);
8
+ const [match] = matches;
9
+ if (!match || matches.length !== 1)
10
+ return "unknown";
11
+ const fit = PERMISSION_REALM_FIT[match.family];
12
+ switch (fit) {
13
+ case "isolated":
14
+ case "kernel":
15
+ return undefined;
16
+ case "server":
17
+ case "browser":
18
+ case "device":
19
+ return { realm: fit, forcingKey: key };
20
+ case "point": {
21
+ const point = match.declaration;
22
+ if (ISOLATED_EXTENSION_POINTS.includes(point))
23
+ return undefined;
24
+ const provided = match.family === "provides" || match.family === "provides.standard";
25
+ const contract = PROVIDER_CONTRACTS[point];
26
+ return {
27
+ realm: "server",
28
+ forcingKey: provided && contract ? contract.forcingKey : key,
29
+ };
30
+ }
31
+ }
32
+ }
33
+ /**
34
+ * The kernel's forcing key of a deployment config schema outside the isolated subset. The config
35
+ * field keys stay what they are (each fits isolation); the schema itself is what forces.
36
+ */
37
+ export const CONFIG_SCHEMA_UNSUPPORTED_KEY = "execution.config.unsupported";
38
+ export function executionDecision(input) {
39
+ const forcing = { server: [], browser: [], device: [] };
40
+ const unknownKeys = [];
41
+ // a schema outside the subset forces full access, whether or not it declares a field
42
+ if (input.configSchemaIsolatable === false)
43
+ forcing.server.push(CONFIG_SCHEMA_UNSUPPORTED_KEY);
44
+ for (const key of input.keys) {
45
+ const forced = forcedRealm(key);
46
+ if (forced === "unknown") {
47
+ unknownKeys.push(key);
48
+ forcing.server.push(key);
49
+ }
50
+ else if (forced) {
51
+ forcing[forced.realm].push(forced.forcingKey);
52
+ }
53
+ }
54
+ if (!input.server && input.client === undefined) {
55
+ return {
56
+ kind: "declarative",
57
+ server: { mode: "none" },
58
+ browser: { mode: "none" },
59
+ device: { mode: "none" },
60
+ fullAccess: {},
61
+ unknownKeys: sorted(unknownKeys),
62
+ confirmable: unknownKeys.length === 0,
63
+ };
64
+ }
65
+ let server = { mode: "none" };
66
+ if (input.server) {
67
+ const keys = sorted(forcing.server);
68
+ if (input.host === "not_configured") {
69
+ server = { mode: "full-access", forcingKeys: sorted([...keys, HOST_NO_ISOLATION_KEY]) };
70
+ }
71
+ else if (keys.length > 0) {
72
+ server = { mode: "full-access", forcingKeys: keys };
73
+ }
74
+ else if (input.host === "failing") {
75
+ server = { mode: "unavailable", reason: "isolation_unavailable" };
76
+ }
77
+ else {
78
+ server = { mode: "isolated" };
79
+ }
80
+ }
81
+ let browser = { mode: "none" };
82
+ if (input.client !== undefined) {
83
+ browser =
84
+ input.client.realm === "isolated" && ISOLATED_CLIENT_REALM_AVAILABLE
85
+ ? { mode: "isolated" }
86
+ : {
87
+ mode: "full-access",
88
+ forcingKeys: sorted(forcing.browser.length > 0 ? forcing.browser : [CLIENT_KEY]),
89
+ };
90
+ }
91
+ else if (forcing.browser.length > 0) {
92
+ // client declarations without a client entry still need the page's privileges to mean anything
93
+ browser = { mode: "full-access", forcingKeys: sorted(forcing.browser) };
94
+ }
95
+ const device = forcing.device.length > 0
96
+ ? { mode: "full-access", forcingKeys: sorted(forcing.device) }
97
+ : { mode: "none" };
98
+ const fullAccess = {};
99
+ for (const [realm, placement] of [
100
+ ["server", server],
101
+ ["browser", browser],
102
+ ["device", device],
103
+ ]) {
104
+ if (placement.mode === "full-access")
105
+ fullAccess[realm] = placement.forcingKeys;
106
+ }
107
+ return {
108
+ kind: "code",
109
+ server,
110
+ browser,
111
+ device,
112
+ fullAccess,
113
+ unknownKeys: sorted(unknownKeys),
114
+ confirmable: unknownKeys.length === 0,
115
+ };
116
+ }
117
+ /** The kernel-generated `execution.full-access:<realm>` keys a decision's grant must carry. */
118
+ export function fullAccessKeys(decision) {
119
+ return Object.keys(decision.fullAccess).map(fullAccessKey).sort();
120
+ }
121
+ /** A one-line summary for review lists and `capybara-plugin check`. */
122
+ export function describeExecution(decision) {
123
+ const unknown = decision.confirmable
124
+ ? ""
125
+ : `; unconfirmable: unknown ${decision.unknownKeys.join(", ")}`;
126
+ if (decision.kind === "declarative")
127
+ return `declarative only: no extension process${unknown}`;
128
+ const parts = [];
129
+ for (const realm of ["server", "browser", "device"]) {
130
+ const placement = decision[realm];
131
+ if (placement.mode === "none")
132
+ continue;
133
+ if (placement.mode === "isolated")
134
+ parts.push(`${realm}: isolated`);
135
+ else if (placement.mode === "unavailable")
136
+ parts.push(`${realm}: isolation unavailable`);
137
+ else
138
+ parts.push(`${realm}: full access (forced by ${placement.forcingKeys.join(", ")})`);
139
+ }
140
+ return `${parts.join("; ")}${unknown}`;
141
+ }
@@ -35,6 +35,7 @@ import { PluginIcons } from "./plugin-icons.js";
35
35
  import { ExtensionPointDefaults } from "./point-defaults.js";
36
36
  import { ExtensionPointServingModule } from "./point-serving.js";
37
37
  import { ExtensionRegistryModule } from "./registry.js";
38
+ import { ExtensionRevocations } from "./revocation.js";
38
39
  import { SingleProviderGuard } from "./single-provider.js";
39
40
  import { ReplicaStatusStore } from "./sources.js";
40
41
  import { ExtensionStateModule } from "./state.module.js";
@@ -89,6 +90,7 @@ ExtensionsModule = __decorate([
89
90
  ExtensionEffects,
90
91
  ExtensionEffectKeys,
91
92
  ExtensionLifecycle,
93
+ ExtensionRevocations,
92
94
  ExtensionAdmin,
93
95
  ExtensionAdminOps,
94
96
  ExtensionDisplayNames,
@@ -112,6 +114,7 @@ ExtensionsModule = __decorate([
112
114
  ExtensionEffects,
113
115
  ExtensionEffectKeys,
114
116
  ExtensionLifecycle,
117
+ ExtensionRevocations,
115
118
  ExtensionAdmin,
116
119
  ExtensionAdminOps,
117
120
  ExtensionDisplayNames,
@@ -22,8 +22,10 @@
22
22
  * across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
23
23
  * every replica (api, worker and gateway alike) must read it itself. The read is a one-row
24
24
  * primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
25
- * the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
26
- * this replica and stops when the extension host closes.
25
+ * the source of truth stays in PostgreSQL. It runs once an isolated grant was requested on this
26
+ * replica or an instance with a package opened its permission lease (revocation, plan task 1.3e),
27
+ * and stops when the extension host closes. Each change revalidates the cached isolated grants
28
+ * with calls in flight and every permission lease (one grant read for all leases).
27
29
  */
28
30
  /** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
29
31
  export declare const REVOCATION_BOUND_MS = 5000;
@@ -25,8 +25,10 @@ import { KERNEL_APPLICATION_NAME } from "../db/pool.js";
25
25
  * across all replicas, on a worker, but the epoch guards each replica's own in-memory cache, so
26
26
  * every replica (api, worker and gateway alike) must read it itself. The read is a one-row
27
27
  * primary-key lookup and writes nothing, so a timer per replica carries no cross-replica state;
28
- * the source of truth stays in PostgreSQL. It runs only after an isolated grant was requested on
29
- * this replica and stops when the extension host closes.
28
+ * the source of truth stays in PostgreSQL. It runs once an isolated grant was requested on this
29
+ * replica or an instance with a package opened its permission lease (revocation, plan task 1.3e),
30
+ * and stops when the extension host closes. Each change revalidates the cached isolated grants
31
+ * with calls in flight and every permission lease (one grant read for all leases).
30
32
  */
31
33
  /** #1373: stale kernel admission or broker access ends at most 5 s after a revocation commits. */
32
34
  export const REVOCATION_BOUND_MS = 5_000;
@@ -39,10 +39,11 @@ import type { InflightTracker } from "./inflight.js";
39
39
  import { type DesiredExtension, ExtensionInstalls } from "./installs.js";
40
40
  import { type ExtensionInstance } from "./instance.js";
41
41
  import { type IsolatedRevocation } from "./isolated/authorization.js";
42
- import type { ExtensionTier } from "./isolated/tier.js";
42
+ import { type ExtensionTier } from "./isolated/tier.js";
43
43
  import { type PermissionSet } from "./permission-set.js";
44
44
  import { type ExtensionPointEntry, ExtensionRegistry } from "./registry.js";
45
45
  import { ExtensionRevisionApprovals } from "./revision-approvals.js";
46
+ import { type LeaseState } from "./revocation-leases.js";
46
47
  import { type ExtensionSource, ReplicaStatusStore } from "./sources.js";
47
48
  export { deploymentConfigHash };
48
49
  /**
@@ -216,7 +217,12 @@ export declare class ExtensionHost {
216
217
  private readonly isolatedAuthority;
217
218
  private readonly isolatedLanes;
218
219
  private readonly isolatedGrants;
219
- /** This replica's view of the deployment grant epoch; polls only once an isolated grant was issued. */
220
+ /** The permission leases of this replica's instances (revocation, plan task 1.3e). */
221
+ private readonly revisionLeases;
222
+ /**
223
+ * This replica's view of the deployment grant epoch; polls once an isolated grant was issued or
224
+ * an instance with a package opened its permission lease.
225
+ */
220
226
  private readonly grantEpoch;
221
227
  private readonly epochReader;
222
228
  private readonly executionTier;
@@ -378,7 +384,9 @@ export declare class ExtensionHost {
378
384
  * Shadow revision approvals (plan task 1.2b): reported at start, never refusing. Absent in a
379
385
  * hand-built host, which then reports nothing.
380
386
  */
381
- revisionApprovals?: Pick<ExtensionRevisionApprovals, "startGate"> | undefined);
387
+ revisionApprovals?: Pick<ExtensionRevisionApprovals, "startGate"> | undefined,
388
+ /** Kernel tests only: enforce revocation before plan task 1.5a (`REVOCATION_ENFORCEMENT`). */
389
+ revocationEnforcement?: boolean);
382
390
  /** The startup config's `extensionConfig` (file / Nacos merged with env). */
383
391
  private get extensionConfig();
384
392
  /** `extensionPermissions.autoApprove` (development and trials only; see `planApprovals`). */
@@ -471,6 +479,14 @@ export declare class ExtensionHost {
471
479
  /** 把一份已校验部署配置里的密钥值登记到日志打码。 */
472
480
  private reportSecrets;
473
481
  private tierOf;
482
+ /**
483
+ * The tier after a revocation (plan task 1.3e; enforced from task 1.5a, until then the leases
484
+ * only report it). A revision whose whole grant is revoked waits for a new review. A trusted
485
+ * (in-process) revision whose grant no longer serves server full access runs isolated when the
486
+ * remaining grant fits the sandbox and the package has an isolated form, and otherwise waits for
487
+ * a new review ({@link RevocationPendingError}: reported pending, not failed).
488
+ */
489
+ private afterRevocation;
474
490
  /**
475
491
  * Reconciles enabled installs from PostgreSQL at startup and during convergence. It removes
476
492
  * withdrawn revisions, verifies the tier, and prepares replacements in dependency order.
@@ -565,6 +581,13 @@ export declare class ExtensionHost {
565
581
  */
566
582
  activatePending(): Promise<string[]>;
567
583
  revokeIsolatedInvocations(scope: IsolatedRevocation): void;
584
+ /**
585
+ * A committed grant revocation (the local fence after the commit, or a sibling's hint): this
586
+ * replica's leases of the plugin revalidate now (plan task 1.3e).
587
+ */
588
+ fenceRevocation(plugin: string): Promise<void>;
589
+ /** The revocation decisions this replica's leases computed for a plugin's instances. */
590
+ revocationDecisions(plugin: string): LeaseState[];
568
591
  refreshIsolatedOrgIntent(orgId?: string): Promise<void>;
569
592
  revalidateIsolatedInvocations(): Promise<void>;
570
593
  /**
@@ -15,6 +15,7 @@ import { EXTENSION_POINT_CARDINALITY, extensionPointRefs, OBJECT_STORE_EXTENSION
15
15
  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
+ import { officialPublisherProofMode } from "../catalog/publisher-policy.js";
18
19
  import { changedPaths, configFields, getPath, secretValues, unreachableSecrets, } from "../config/fields.js";
19
20
  import { EXTENSION_CAPACITY_DEFAULTS } from "../config/schema.js";
20
21
  import { EXTERNAL_CONVERSATIONS_BACKEND } from "../conversations/external/token.js";
@@ -62,12 +63,14 @@ import { readConfiguredExtensionPackage, stageConfiguredExtensionPackage, } from
62
63
  import { IsolatedExtensionQuota } from "./isolated/lanes.js";
63
64
  import { isolatedRevision } from "./isolated/revision.js";
64
65
  import { sweepExtensionSandboxOrphans } from "./isolated/sandbox.js";
66
+ import { publisherProofMissing, publisherProofRefusal, } from "./isolated/tier.js";
65
67
  import { parseLoadGate } from "./org-levels.js";
66
68
  import { declaredDisplayName, permissionSetOfSection, readMigrationSql } from "./package.js";
67
69
  import { blockingKeys, computePermissionSet, SETUP_CHECK_KEY_PREFIX, UI_VIEW_KEY_PREFIX, } from "./permission-set.js";
68
70
  import { ExtensionRegistry } from "./registry.js";
69
71
  import { ExtensionResolveError, electSingleProviders, PROVIDER_CONFLICT, providerConflictMessage, resolveExtensions, } from "./resolve.js";
70
72
  import { ExtensionRevisionApprovals } from "./revision-approvals.js";
73
+ import { leaseStateOf, REVOCATION_ENFORCEMENT, RevisionLeases, RevocationPendingError, readGrantSurfaceBySha256, readGrantSurfacesBySha256, realmAfterRevocation, } from "./revocation-leases.js";
71
74
  import { ReplicaStatusStore, } from "./sources.js";
72
75
  import { PackageShaMismatchError, packageRootOf } from "./sync.js";
73
76
  export { deploymentConfigHash };
@@ -411,7 +414,12 @@ let ExtensionHost = class ExtensionHost {
411
414
  isolatedAuthority = new WeakMap();
412
415
  isolatedLanes = new WeakMap();
413
416
  isolatedGrants;
414
- /** This replica's view of the deployment grant epoch; polls only once an isolated grant was issued. */
417
+ /** The permission leases of this replica's instances (revocation, plan task 1.3e). */
418
+ revisionLeases;
419
+ /**
420
+ * This replica's view of the deployment grant epoch; polls once an isolated grant was issued or
421
+ * an instance with a package opened its permission lease.
422
+ */
415
423
  grantEpoch;
416
424
  epochReader;
417
425
  executionTier = new Map();
@@ -548,7 +556,9 @@ let ExtensionHost = class ExtensionHost {
548
556
  * Shadow revision approvals (plan task 1.2b): reported at start, never refusing. Absent in a
549
557
  * hand-built host, which then reports nothing.
550
558
  */
551
- revisionApprovals) {
559
+ revisionApprovals,
560
+ /** Kernel tests only: enforce revocation before plan task 1.5a (`REVOCATION_ENFORCEMENT`). */
561
+ revocationEnforcement) {
552
562
  this.registry = registry;
553
563
  this.installs = installs;
554
564
  this.approvals = approvals;
@@ -587,15 +597,54 @@ let ExtensionHost = class ExtensionHost {
587
597
  void this.isolatedGrants
588
598
  .epochChanged()
589
599
  .catch((err) => this.log.warn("isolated extension grant revalidation failed", { err }));
600
+ void this.revisionLeases
601
+ .epochChanged()
602
+ .catch((err) => this.log.warn("extension permission lease revalidation failed", { err }));
603
+ },
604
+ onSettleDeadline: () => {
605
+ this.isolatedGrants.fenceStale();
606
+ this.revisionLeases.fenceStale();
590
607
  },
591
- onSettleDeadline: () => this.isolatedGrants.fenceStale(),
592
608
  onExpired: () => {
593
609
  this.log.warn("isolated extension grants fenced: the grant epoch could not be read");
594
610
  this.isolatedGrants.fenceAll();
611
+ this.revisionLeases.fenceAll();
595
612
  },
596
613
  onFault: (err) => this.log.warn("reading the extension grant epoch failed", { err }),
597
614
  });
598
615
  this.isolatedGrants = new IsolatedInvocationGrants(this.grantEpoch, capacity.grantCacheEntries);
616
+ const grantReads = kernelDb(kdb.pool);
617
+ this.revisionLeases = new RevisionLeases({
618
+ epochs: this.grantEpoch,
619
+ // one query for every lease of a fence or epoch change
620
+ read: async (sha256s) => {
621
+ const grants = await readGrantSurfacesBySha256(grantReads, sha256s);
622
+ return new Map(sha256s.map((sha256) => [sha256, leaseStateOf(grants.get(sha256))]));
623
+ },
624
+ ...(revocationEnforcement === true && { enforce: true }),
625
+ onUnload: (plugin) => {
626
+ this.log.warn("extension grant revoked: unloading its generation", { plugin });
627
+ void this.converge().catch((err) => this.log.error("converging after a grant revocation failed", { plugin, err }));
628
+ },
629
+ onRestored: (plugin) => {
630
+ // withdrawn registrations come back only with a new setup
631
+ this.log.info("extension grant restored withdrawn keys: reloading it", { plugin });
632
+ void this.reload(plugin).catch((err) => this.log.error("reloading after a restored grant failed", { plugin, err }));
633
+ },
634
+ onFault: (plugin, err) => this.log.warn("reading an extension's revision grant failed", { plugin, err }),
635
+ // shadow mode until plan task 1.5a: what enforcement would do, logged and never enforced
636
+ onShadow: (plugin, decision) => this.log.warn("extension revocation computed (shadow mode, not enforced)", {
637
+ plugin,
638
+ ...("refusedCall" in decision
639
+ ? { wouldRefuseCall: decision.refusedCall }
640
+ : {
641
+ wouldWithdrawOrRefuse: decision.refused,
642
+ wouldUnloadInProcess: decision.lostServerFullAccess,
643
+ wouldUnload: decision.revoked,
644
+ status: decision.state.status,
645
+ }),
646
+ }),
647
+ });
599
648
  this.deps = {
600
649
  db: kdb.pool,
601
650
  dbUrl: c.db.url,
@@ -669,6 +718,8 @@ let ExtensionHost = class ExtensionHost {
669
718
  }
670
719
  },
671
720
  locks,
721
+ leases: this.revisionLeases,
722
+ registrationsChanged: (plugin) => this.registry.registrationsChanged(plugin),
672
723
  runWorkers: c.roles.includes("worker"),
673
724
  log,
674
725
  };
@@ -1000,10 +1051,39 @@ let ExtensionHost = class ExtensionHost {
1000
1051
  }
1001
1052
  tierOf(loader, revision, verifyBytes) {
1002
1053
  const fixtures = this.options[KERNEL_FIXTURE_TRUST];
1003
- if (fixtures === true || fixtures?.installDigests.includes(revision.sha256)) {
1004
- return Promise.resolve("trusted");
1054
+ const tier = fixtures === true || fixtures?.installDigests.includes(revision.sha256)
1055
+ ? Promise.resolve("trusted")
1056
+ : (loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated"));
1057
+ return tier.then((t) => (t === "refused" ? t : this.afterRevocation(revision, t)));
1058
+ }
1059
+ /**
1060
+ * The tier after a revocation (plan task 1.3e; enforced from task 1.5a, until then the leases
1061
+ * only report it). A revision whose whole grant is revoked waits for a new review. A trusted
1062
+ * (in-process) revision whose grant no longer serves server full access runs isolated when the
1063
+ * remaining grant fits the sandbox and the package has an isolated form, and otherwise waits for
1064
+ * a new review ({@link RevocationPendingError}: reported pending, not failed).
1065
+ */
1066
+ async afterRevocation(revision, tier) {
1067
+ if (!this.revisionLeases.enforced)
1068
+ return tier;
1069
+ const grant = await readGrantSurfaceBySha256(kernelDb(this.deps.db), revision.sha256);
1070
+ if (!grant)
1071
+ return tier;
1072
+ if (grant.state === "revoked") {
1073
+ throw new RevocationPendingError("The revision's grant was revoked; it waits for a new review");
1074
+ }
1075
+ if (tier !== "trusted" || !leaseStateOf(grant).realmsRevoked.includes("server"))
1076
+ return tier;
1077
+ if (realmAfterRevocation(grant, "server") === "isolated") {
1078
+ try {
1079
+ assertIsolatedSection(revision.section);
1080
+ return "isolated";
1081
+ }
1082
+ catch {
1083
+ throw new RevocationPendingError("Full access for the server realm was revoked and the package has no isolated form; it waits for a new review");
1084
+ }
1005
1085
  }
1006
- return loader.tier?.(revision, verifyBytes) ?? Promise.resolve("isolated");
1086
+ throw new RevocationPendingError("Full access for the server realm was revoked and the remaining grant still needs it; it waits for a new review");
1007
1087
  }
1008
1088
  /**
1009
1089
  * Reconciles enabled installs from PostgreSQL at startup and during convergence. It removes
@@ -1024,13 +1104,25 @@ let ExtensionHost = class ExtensionHost {
1024
1104
  const wanted = new Map();
1025
1105
  const tiers = new Map();
1026
1106
  const rejected = new Map();
1107
+ const rejectedActions = new Map();
1108
+ let proofMode;
1109
+ /** Revisions a revocation sends back to review: pending, not failed (plan task 1.3e). */
1110
+ const awaitingReview = new Map();
1027
1111
  for (const d of electAmong) {
1028
1112
  if (declared.has(d.name))
1029
1113
  continue;
1030
1114
  try {
1031
1115
  const tier = await this.tierOf(loader, d, false);
1032
1116
  if (tier === "refused") {
1033
- rejected.set(d.name, "The extension revision did not pass trust admission");
1117
+ if (publisherProofMissing(d)) {
1118
+ proofMode ??= await officialPublisherProofMode(kernelDb(this.deps.db));
1119
+ const refusal = publisherProofRefusal(proofMode);
1120
+ rejected.set(d.name, refusal.detail);
1121
+ rejectedActions.set(d.name, refusal.action);
1122
+ }
1123
+ else {
1124
+ rejected.set(d.name, "The extension revision did not pass trust admission");
1125
+ }
1034
1126
  continue;
1035
1127
  }
1036
1128
  if (tier === "isolated")
@@ -1038,7 +1130,10 @@ let ExtensionHost = class ExtensionHost {
1038
1130
  tiers.set(d.name, tier);
1039
1131
  }
1040
1132
  catch (error) {
1041
- rejected.set(d.name, errMsg(error));
1133
+ if (error instanceof RevocationPendingError)
1134
+ awaitingReview.set(d.name, error.message);
1135
+ else
1136
+ rejected.set(d.name, errMsg(error));
1042
1137
  }
1043
1138
  }
1044
1139
  // Single-provider election: of the enabled install records providing one single-provider
@@ -1100,11 +1195,26 @@ let ExtensionHost = class ExtensionHost {
1100
1195
  detail: null,
1101
1196
  });
1102
1197
  }
1198
+ for (const d of desired) {
1199
+ const waiting = awaitingReview.get(d.name);
1200
+ if (waiting === undefined)
1201
+ continue;
1202
+ await this.writeStatus({
1203
+ plugin: d.name,
1204
+ version: d.version,
1205
+ sha256: d.sha256,
1206
+ source: "install",
1207
+ state: "pending",
1208
+ reason: "approval",
1209
+ detail: waiting,
1210
+ });
1211
+ }
1103
1212
  for (const d of desired) {
1104
1213
  const detail = rejected.get(d.name);
1105
1214
  if (!detail)
1106
1215
  continue;
1107
- await this.reportAdmissionRefusal(d.name, d.sha256, detail, "Review the plugin revision and install a package eligible for this deployment.");
1216
+ await this.reportAdmissionRefusal(d.name, d.sha256, detail, rejectedActions.get(d.name) ??
1217
+ "Review the plugin revision and install a package eligible for this deployment.");
1108
1218
  await this.writeStatus({
1109
1219
  plugin: d.name,
1110
1220
  version: d.version,
@@ -1904,6 +2014,18 @@ let ExtensionHost = class ExtensionHost {
1904
2014
  this.isolatedLanes.get(instance)?.revokeOrg(scope.orgId);
1905
2015
  }
1906
2016
  }
2017
+ /**
2018
+ * A committed grant revocation (the local fence after the commit, or a sibling's hint): this
2019
+ * replica's leases of the plugin revalidate now (plan task 1.3e).
2020
+ */
2021
+ fenceRevocation(plugin) {
2022
+ return this.revisionLeases.fence(plugin);
2023
+ }
2024
+ /** The revocation decisions this replica's leases computed for a plugin's instances. */
2025
+ revocationDecisions(plugin) {
2026
+ // the computed decisions of every instance of the plugin on this replica
2027
+ return this.revisionLeases.statesOf(plugin);
2028
+ }
1907
2029
  refreshIsolatedOrgIntent(orgId) {
1908
2030
  return this.isolatedGrants.refreshOrgIntent(orgId);
1909
2031
  }
@@ -2231,6 +2353,7 @@ let ExtensionHost = class ExtensionHost {
2231
2353
  configHash: spec.configHash,
2232
2354
  permissions: spec.permissions,
2233
2355
  extensionDb,
2356
+ inProcess: !spec.isolated,
2234
2357
  onCtx: (c) => {
2235
2358
  if (c)
2236
2359
  ctx = c;
@@ -2957,6 +3080,8 @@ ExtensionHost = __decorate([
2957
3080
  __param(21, Inject(EXTENSION_NET_SEAMS)),
2958
3081
  __param(22, Inject(ConfiguredExtensionDbIdentity)),
2959
3082
  __param(23, Optional()),
2960
- __param(23, Inject(ExtensionRevisionApprovals))
3083
+ __param(23, Inject(ExtensionRevisionApprovals)),
3084
+ __param(24, Optional()),
3085
+ __param(24, Inject(REVOCATION_ENFORCEMENT))
2961
3086
  ], ExtensionHost);
2962
3087
  export { ExtensionHost };
@@ -166,6 +166,8 @@ export declare function setupInstance(deps: LoadDeps, manifest: ExtensionManifes
166
166
  /** 已建好 ctx、setup 进行中时回调(宿主据此在 close() 时立即关闭它)。 */
167
167
  onCtx?: (ctx: KernelExtensionContext | undefined) => void;
168
168
  extensionDb?: ReturnType<typeof extensionDbPool>;
169
+ /** The instance runs in the kernel process (default); false for an isolated instance. */
170
+ inProcess?: boolean;
169
171
  }): Promise<ExtensionInstance>;
170
172
  /**
171
173
  * 加载一个插件实例:import → defineExtension → 有包内静态清单(`section`)时与 {@link staticManifestOf} 核对
@@ -311,6 +311,7 @@ export async function setupInstance(deps, manifest, input) {
311
311
  const ctx = createExtensionContext(deps.kernel, manifest, live, deps.objectStore, {
312
312
  sha256: input.sha256,
313
313
  ...(input.extensionDb && { db: input.extensionDb }),
314
+ ...(input.inProcess !== undefined && { inProcess: input.inProcess }),
314
315
  });
315
316
  input.onCtx?.(ctx);
316
317
  try {
@@ -7,4 +7,10 @@ export declare function isTrustedPublisherRevision(proof: unknown, expected: Off
7
7
  export declare function isolatedDeploymentSchema(input: unknown): z.ZodType;
8
8
  /** The kernel must never compile executable or unbounded schema features from a child. */
9
9
  export declare function assertIsolatedToolSchema(input: unknown): void;
10
+ /**
11
+ * Whether the section's deployment config fits the isolated tier: the same rule
12
+ * {@link assertIsolatedSection} applies (a declarative schema in the bounded subset, or no config
13
+ * fields at all). The execution decision reads it as `configSchemaIsolatable`.
14
+ */
15
+ export declare function deploymentConfigIsolatable(section: PluginExtensionSection): boolean;
10
16
  export declare function assertIsolatedSection(section: PluginExtensionSection): void;
@@ -181,6 +181,23 @@ export function assertIsolatedToolSchema(input) {
181
181
  throw new Error("Unsupported isolated extension tool schema");
182
182
  }
183
183
  }
184
+ /**
185
+ * Whether the section's deployment config fits the isolated tier: the same rule
186
+ * {@link assertIsolatedSection} applies (a declarative schema in the bounded subset, or no config
187
+ * fields at all). The execution decision reads it as `configSchemaIsolatable`.
188
+ */
189
+ export function deploymentConfigIsolatable(section) {
190
+ const schema = section.configSchemas?.deployment;
191
+ if (schema === undefined)
192
+ return section.manifest.config.deployment.length === 0;
193
+ try {
194
+ isolatedDeploymentSchema(schema);
195
+ return true;
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ }
184
201
  export function assertIsolatedSection(section) {
185
202
  const { manifest, client } = section;
186
203
  const permissions = manifest.permissions;
@@ -2,5 +2,19 @@ import type { ExtensionBlobs } from "../blobs.js";
2
2
  import type { LoadedBootstrapManifest } from "../bootstrap-extra.js";
3
3
  import type { DesiredExtension } from "../installs.js";
4
4
  export type ExtensionTier = "trusted" | "isolated" | "refused";
5
+ export declare const PUBLISHER_PROOF_MISSING = "Publisher proof missing for this revision; upgrade it from the official marketplace";
6
+ /**
7
+ * The status detail and the log's action for {@link publisherProofMissing}. Under pin-only an
8
+ * upgrade records no proof either, so it is not advised there.
9
+ */
10
+ export declare function publisherProofRefusal(mode: "require" | "pin-only"): {
11
+ detail: string;
12
+ action: string;
13
+ };
14
+ /**
15
+ * An official-marketplace revision imported before the kernel recorded publisher proofs: the
16
+ * `extension-publisher-proof-recheck` worker job verifies and records it, or it stays refused.
17
+ */
18
+ export declare function publisherProofMissing(extension: DesiredExtension): boolean;
5
19
  /** Source, reviewed package revision and integrity jointly determine admission, never the plugin name. */
6
20
  export declare function installedExtensionTier(extension: DesiredExtension, builtin: () => Promise<LoadedBootstrapManifest>, blobs: Pick<ExtensionBlobs, "get">, verifyBytes: boolean): Promise<ExtensionTier>;
@@ -1,6 +1,33 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { OFFICIAL_MARKETPLACE_ID } from "../../catalog/publisher-policy.js";
3
3
  import { isTrustedPublisherRevision } from "./admission.js";
4
+ export const PUBLISHER_PROOF_MISSING = "Publisher proof missing for this revision; upgrade it from the official marketplace";
5
+ /**
6
+ * The status detail and the log's action for {@link publisherProofMissing}. Under pin-only an
7
+ * upgrade records no proof either, so it is not advised there.
8
+ */
9
+ export function publisherProofRefusal(mode) {
10
+ return mode === "pin-only"
11
+ ? {
12
+ detail: "Publisher proof missing for this revision; pin-only admission records none",
13
+ action: "Upgrades under pin-only record no proof either. Switch official publisher proof to require so the kernel verifies this revision, or keep it refused until the pin-only revision review admits it.",
14
+ }
15
+ : {
16
+ detail: PUBLISHER_PROOF_MISSING,
17
+ action: "The kernel rechecks the publisher attestations of this revision automatically (job extension-publisher-proof-recheck). If it stays refused, upgrade it from the official marketplace.",
18
+ };
19
+ }
20
+ /**
21
+ * An official-marketplace revision imported before the kernel recorded publisher proofs: the
22
+ * `extension-publisher-proof-recheck` worker job verifies and records it, or it stays refused.
23
+ */
24
+ export function publisherProofMissing(extension) {
25
+ const evidence = extension.catalogEvidence;
26
+ return (extension.source === "catalog" &&
27
+ (extension.marketplaceId ?? evidence?.marketplaceId) === OFFICIAL_MARKETPLACE_ID &&
28
+ evidence?.source === "marketplace" &&
29
+ evidence.proof == null);
30
+ }
4
31
  /** Source, reviewed package revision and integrity jointly determine admission, never the plugin name. */
5
32
  export async function installedExtensionTier(extension, builtin, blobs, verifyBytes) {
6
33
  if (extension.source === "bootstrap") {
@@ -25,6 +25,11 @@ export declare class RegistrationLedger {
25
25
  get sealed(): boolean;
26
26
  /** 封账:此后的登记立即撤销并抛错。 */
27
27
  seal(): void;
28
+ /**
29
+ * Takes every entry of one kind off the ledger and disposes it (newest first): the handles held
30
+ * under a revoked permission (plan task 1.3e). A failure goes to `onError`; the rest continue.
31
+ */
32
+ disposeKind(kind: RegistrationKind, onError: (r: Registration, e: unknown) => void): Promise<void>;
28
33
  /** 封账并按登记的倒序逐项撤销;单项失败交给 `onError`,继续其余各项。 */
29
34
  disposeAll(onError: (r: Registration, e: unknown) => void): Promise<void>;
30
35
  }