@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133

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 (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -13,6 +13,7 @@ import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import semver from "semver";
15
15
  import { checkClientFiles } from "../client/client-files.js";
16
+ import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
16
17
  import { ApiError } from "../errors.js";
17
18
  import { ExtensionAdminOps } from "../extensions/admin-ops.js";
18
19
  import { ExtensionAdmin } from "../extensions/admin-view.js";
@@ -36,6 +37,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
36
37
  import { OutboxService } from "../infra/outbox/outbox.service.js";
37
38
  import { KERNEL_LOGGER } from "../infra/tokens.js";
38
39
  import { OrgLock } from "../orgs/org-lock.js";
40
+ import { sha512Hex } from "../packages/provenance.js";
39
41
  import { packagePath, packPackageTgz } from "../packages/tgz.js";
40
42
  import { checkSkillFiles, SkillArchiveError } from "../skills/package.js";
41
43
  import { StorageService } from "../storage/storage.service.js";
@@ -49,9 +51,11 @@ import { CLAUDE_MCP_CONNECTOR } from "./claude/mcp.js";
49
51
  import { item as reportItem, sortItems, } from "./claude/report.js";
50
52
  import { isClaudePluginTree, translateClaudePlugin } from "./claude/translate.js";
51
53
  import { CatalogItemLock } from "./locks.js";
54
+ import { requireMarketplacePublisher } from "./marketplace-fetch.js";
52
55
  import { assertNameFree, assertPackageFree, assertShareable, packageOwner, shareGate, usableBy, } from "./ownership.js";
53
56
  import { PlanStale, PlatformComponents } from "./platform-components.js";
54
57
  import { assertDeclarativeUpload, PluginPackageError, readPluginFiles, readPluginPackage, themeApiError, } from "./plugin-package.js";
58
+ import { OFFICIAL_MARKETPLACE_ID, officialPublisherProofMode } from "./publisher-policy.js";
55
59
  import { hasImportRequests, importRequestOf, resolveImportRequests } from "./request-rules.js";
56
60
  import { assertNameNotReserved } from "./reserved-names.js";
57
61
  import { oweScopeItem } from "./scope-jobs.js";
@@ -150,6 +154,7 @@ let PluginImport = class PluginImport {
150
154
  approveLock;
151
155
  itemLock;
152
156
  config;
157
+ extensionDbIdentity;
153
158
  installs;
154
159
  ops;
155
160
  admin;
@@ -171,7 +176,7 @@ let PluginImport = class PluginImport {
171
176
  /** The super admin lock (identity/super-admin.ts): joins the caller's transaction. */
172
177
  adminLock,
173
178
  /** The owner org's lock: an org upload re-checks its admin under it (ruling P3-7). */
174
- orgLock, installLock, approveLock, itemLock, config, storage, installs, ops, admin,
179
+ orgLock, installLock, approveLock, itemLock, config, extensionDbIdentity, storage, installs, ops, admin,
175
180
  /** Reads a package from the package store (confirm recomputes the permission set). */
176
181
  blobs,
177
182
  /** Config-declared names, loaded connectors and extension versions (the extension registry). */
@@ -187,6 +192,7 @@ let PluginImport = class PluginImport {
187
192
  this.approveLock = approveLock;
188
193
  this.itemLock = itemLock;
189
194
  this.config = config;
195
+ this.extensionDbIdentity = extensionDbIdentity;
190
196
  this.installs = installs;
191
197
  this.ops = ops;
192
198
  this.admin = admin;
@@ -393,7 +399,7 @@ let PluginImport = class PluginImport {
393
399
  let extension;
394
400
  if (ext) {
395
401
  extension = await this.reviewExtension(ext, await this.extensionState(m.name, packageName));
396
- await assertDowngradable(this.db, extension, ext.migrationSql);
402
+ await assertDowngradable(this.db, extension, ext.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
397
403
  }
398
404
  // Display files go to PG with the staging row; skills and templates need object storage, which a
399
405
  // bootstrap import never has (the object store may be a bootstrap plugin itself). A file that is
@@ -716,6 +722,30 @@ let PluginImport = class PluginImport {
716
722
  const src = row.source;
717
723
  if (input.reviewHash !== review.reviewHash)
718
724
  throw reviewStale(review);
725
+ const official = src.kind === "marketplace" && src.marketplaceId === OFFICIAL_MARKETPLACE_ID;
726
+ const requireProof = official && (await officialPublisherProofMode(this.db)) === "require";
727
+ if (official) {
728
+ const publisherProof = src.detail && "registry" in src.detail ? src.detail.publisherProof : undefined;
729
+ if (!staged.packageName ||
730
+ src.ref !== `${OFFICIAL_MARKETPLACE_ID}:${staged.packageName}@${staged.manifest.version}` ||
731
+ !src.integrity ||
732
+ sha512Hex(src.integrity) === undefined ||
733
+ canonicalJson(src) !== canonicalJson(review.source) ||
734
+ pluginReviewHash(review, staged.files) !== review.reviewHash) {
735
+ throw reviewStale(review);
736
+ }
737
+ if (requireProof) {
738
+ if (!publisherProof ||
739
+ publisherProof.revision.name !== staged.packageName ||
740
+ publisherProof.revision.version !== staged.manifest.version ||
741
+ publisherProof.revision.integrity !== src.integrity) {
742
+ throw reviewStale(review);
743
+ }
744
+ const verified = await requireMarketplacePublisher(this.config.get(), publisherProof.revision);
745
+ if (canonicalJson(verified) !== canonicalJson(publisherProof))
746
+ throw reviewStale(review);
747
+ }
748
+ }
719
749
  const manifest = staged.manifest;
720
750
  if (owner !== undefined)
721
751
  assertDeclarativeUpload(manifest);
@@ -725,7 +755,15 @@ let PluginImport = class PluginImport {
725
755
  // The platform components of the item's first usable version: planned and their files copied
726
756
  // (keyed by content) before the transaction, their rows written in it
727
757
  const prepared = staged.retry === true ? undefined : await this.prepareFirstVersion(staged, row.object_prefix);
728
- const committed = await this.commit(actor, { stagingId, review, staged, src, manifest, objectPrefix: row.object_prefix }, {
758
+ const committed = await this.commit(actor, {
759
+ stagingId,
760
+ review,
761
+ staged,
762
+ src,
763
+ manifest,
764
+ objectPrefix: row.object_prefix,
765
+ publisherRechecked: requireProof,
766
+ }, {
729
767
  scope,
730
768
  orgs: [...new Set(orgs ?? [])].sort(),
731
769
  ...(owner !== undefined && { owner, shareable: input.shareable ?? false }),
@@ -796,6 +834,14 @@ let PluginImport = class PluginImport {
796
834
  const { owner } = scope;
797
835
  await this.authorizeActor(actor, owner);
798
836
  const t = this.db;
837
+ // The settings writer takes the same super-admin lock. A staged pin-only import
838
+ // must be reviewed again if the platform switches to require before commit.
839
+ if (src.kind === "marketplace" &&
840
+ src.marketplaceId === OFFICIAL_MARKETPLACE_ID &&
841
+ !c.publisherRechecked &&
842
+ (await officialPublisherProofMode(t)) === "require") {
843
+ throw stale();
844
+ }
799
845
  // org-filter: ownStaging(owner) pins the row to the caller's org (org_id NULL for the platform)
800
846
  const used = await t
801
847
  .deleteFrom("plugin_import_staging")
@@ -850,7 +896,7 @@ let PluginImport = class PluginImport {
850
896
  // A foreseeable deploy failure (a downgrade to a version with unrun migrations) is refused
851
897
  // before anything is written
852
898
  if (now.action === "upgrade" && stored) {
853
- await assertDowngradable(t, now, stored.migrationSql);
899
+ await assertDowngradable(t, now, stored.migrationSql, this.extensionDbIdentity, this.config.get().db.connectTimeoutMs);
854
900
  }
855
901
  if (now.action === "install" || now.action === "upgrade") {
856
902
  previous = await this.approve(actor, review, staged, now, stored, opts);
@@ -930,6 +976,9 @@ let PluginImport = class PluginImport {
930
976
  licenseTruncated: staged.licenseTruncated === true,
931
977
  auditDetail: {
932
978
  stagingId,
979
+ ...(src.detail && "registry" in src.detail && src.detail.publisherProof
980
+ ? { publisherProof: src.detail.publisherProof }
981
+ : {}),
933
982
  scope: actual.scope,
934
983
  ...(actual.scope === "named" && { orgs: actual.orgs }),
935
984
  ...(now && { extension: { name: now.name, version: now.version, action: now.action } }),
@@ -1587,16 +1636,17 @@ PluginImport = __decorate([
1587
1636
  __param(4, Inject(PluginApproveLock)),
1588
1637
  __param(5, Inject(CatalogItemLock)),
1589
1638
  __param(6, Inject(KernelConfigService)),
1590
- __param(7, Inject(StorageService)),
1591
- __param(8, Inject(ExtensionInstalls)),
1592
- __param(9, Inject(ExtensionAdminOps)),
1593
- __param(10, Inject(ExtensionAdmin)),
1594
- __param(11, Inject(ExtensionBlobs)),
1595
- __param(12, Inject(ExtensionRegistry)),
1596
- __param(13, Inject(KERNEL_LOGGER)),
1597
- __param(14, Inject(TransactionHost)),
1598
- __param(15, Inject(PlatformComponents)),
1599
- __param(16, Inject(OutboxService))
1639
+ __param(7, Inject(ConfiguredExtensionDbIdentity)),
1640
+ __param(8, Inject(StorageService)),
1641
+ __param(9, Inject(ExtensionInstalls)),
1642
+ __param(10, Inject(ExtensionAdminOps)),
1643
+ __param(11, Inject(ExtensionAdmin)),
1644
+ __param(12, Inject(ExtensionBlobs)),
1645
+ __param(13, Inject(ExtensionRegistry)),
1646
+ __param(14, Inject(KERNEL_LOGGER)),
1647
+ __param(15, Inject(TransactionHost)),
1648
+ __param(16, Inject(PlatformComponents)),
1649
+ __param(17, Inject(OutboxService))
1600
1650
  ], PluginImport);
1601
1651
  export { PluginImport };
1602
1652
  /**
@@ -1656,6 +1706,9 @@ export function pluginReviewHash(r, files) {
1656
1706
  // so a template's auth / endpoint object would hash differently at confirm (plugin.review_stale
1657
1707
  // on every import of a plugin whose connector template has a non-trivial auth block).
1658
1708
  const canonical = canonicalJson([
1709
+ ...(r.source.detail && "registry" in r.source.detail && r.source.detail.publisherProof
1710
+ ? [r.source]
1711
+ : []),
1659
1712
  r.name,
1660
1713
  r.version,
1661
1714
  r.contentDigest,
@@ -1729,12 +1782,12 @@ function reviewClient(pkg) {
1729
1782
  * rule as `ExtensionAdminOps.install`: extension migrations are expand-only, a downgrade can only go
1730
1783
  * back to a version whose migrations have all run).
1731
1784
  */
1732
- async function assertDowngradable(db, p, migrationSql) {
1785
+ async function assertDowngradable(db, p, migrationSql, identity, connectTimeoutMs) {
1733
1786
  if (p.action !== "upgrade" || p.currentVersion === null)
1734
1787
  return;
1735
1788
  if (!semver.valid(p.currentVersion) || !semver.lt(p.version, p.currentVersion))
1736
1789
  return;
1737
- const unrun = await unrunMigrations(db, p.name, migrationSql);
1790
+ const unrun = await unrunMigrations(db, p.name, migrationSql, identity.resolve(p.name), connectTimeoutMs);
1738
1791
  if (unrun.length > 0) {
1739
1792
  throw new ApiError("extension.downgrade_unsupported", `The plugin's extension ${p.name} ${p.version} is older than the installed ${p.currentVersion}, and that version has migrations that were never run here (${unrun.join(", ")}); extension migrations only expand, so this downgrade is not possible`, unrun.map((file) => ({ file })));
1740
1793
  }
@@ -183,6 +183,10 @@ interface VersionRow extends CatalogVersionFiles {
183
183
  version: string;
184
184
  manifest: PluginManifest;
185
185
  extension_sha256: string | null;
186
+ source?: string;
187
+ source_ref?: string | null;
188
+ source_detail?: unknown;
189
+ integrity?: string | null;
186
190
  }
187
191
  /**
188
192
  * An update's target read from somewhere other than `catalog_item_versions`: an org upload's
@@ -315,6 +319,8 @@ export declare class PlatformPluginUpdater {
315
319
  updateAsOwner(orgId: string, actor: string, itemId: string, version: string, diffHash: string, opts?: {
316
320
  actorTokenId?: string;
317
321
  }): Promise<PlatformUpdateResult>;
322
+ /** Check ownership before widening the preview or update. The diff checks it again. */
323
+ private assertOwnedItem;
318
324
  /** The actor is an admin of the owner org (a read of the membership under the org row lock). */
319
325
  private authorizeOwner;
320
326
  /** Runs `f` holding the item's update lock (another update -> `plugin.install_in_progress`). */
@@ -350,6 +356,8 @@ export declare class PlatformPluginUpdater {
350
356
  private updateLocked;
351
357
  /** `plugin.platform_update_failed`, in a transaction of its own. */
352
358
  private auditFailure;
359
+ /** Checks a marketplace revision chosen directly from the stored version list. */
360
+ private verifyStoredPublisher;
353
361
  /**
354
362
  * The update's transaction (see the class comment): the super admin re-checked, the diff
355
363
  * recomputed under the item name's lock, then every write. Returns the diff it applied.
@@ -27,12 +27,14 @@ import { SuperAdminLock } from "../identity/super-admin.js";
27
27
  import { notifySharedUpdate } from "../inbox/org-notices.js";
28
28
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
29
29
  import { KernelDb } from "../infra/database/kernel-db.js";
30
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
30
31
  import { TransactionHost } from "../infra/database/transaction-host.js";
31
32
  import { Transactional } from "../infra/database/transactional.decorator.js";
32
33
  import { LockService } from "../infra/lock/lock.service.js";
33
34
  import { OutboxService } from "../infra/outbox/outbox.service.js";
34
35
  import { KERNEL_LOGGER } from "../infra/tokens.js";
35
36
  import { OrgLock } from "../orgs/org-lock.js";
37
+ import { sha512Hex } from "../packages/provenance.js";
36
38
  import { packagePath } from "../packages/tgz.js";
37
39
  import { StorageService } from "../storage/storage.service.js";
38
40
  import { assertNotPlatformDefault, pickedByIn, themesPreview, } from "../themes/theme-usage.js";
@@ -45,10 +47,12 @@ import { agentsUsing, clashingOrgSkills, clashingPlatformSkills, componentOn, co
45
47
  import { credentialKey } from "./credential-key.js";
46
48
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
47
49
  import { CatalogItemLock } from "./locks.js";
50
+ import { requireMarketplacePublisher } from "./marketplace-fetch.js";
48
51
  import { isUsable } from "./ownership.js";
49
52
  import { PlanStale, PlatformComponents } from "./platform-components.js";
50
53
  import { catalogSkillNames, PluginInstaller } from "./plugin-install.js";
51
54
  import { assertDeclarativeUpload } from "./plugin-package.js";
55
+ import { OFFICIAL_MARKETPLACE_ID, officialPublisherProofMode } from "./publisher-policy.js";
52
56
  import { wantedOn } from "./scope.js";
53
57
  import { PluginScopeSync } from "./scope-sync.js";
54
58
  import { oweTemplateConnectors } from "./template-connector-jobs.js";
@@ -207,10 +211,14 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
207
211
  if (staged !== undefined && staged.version !== version) {
208
212
  throw new Error(`internal: previewForOwner got the staged target of version ${staged.version} for version ${version}`);
209
213
  }
210
- const preview = await this.withGuideChanges(await this.diff(itemId, version, {
214
+ if (!UUID_RE.test(itemId))
215
+ throw itemNotFound();
216
+ await this.assertOwnedItem(orgId, itemId);
217
+ // org-filter: deployment-wide impact preview for this owned plugin across its subscribers.
218
+ const preview = await asPlatform("preview the owned plugin update across affected organizations", async () => this.withGuideChanges(await this.diff(itemId, version, {
211
219
  owner: { orgId },
212
220
  ...(staged !== undefined && { target: staged }),
213
- }));
221
+ })));
214
222
  // The owner sees the names of the orgs whose default a removed theme is (named like the other
215
223
  // orgs the preview mentions, P3-14 / P3-19), but people only of its own org: other orgs'
216
224
  // member counts were never disclosed to it. Display only: `diffHash` covers the full preview.
@@ -256,7 +264,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
256
264
  const live = new Set();
257
265
  for (const orgId of [...ids].sort()) {
258
266
  if (orgId === acting?.orgId) {
259
- await this.orgLock.lockAndAuthorize(orgId, acting.actor, "catalog.upload");
267
+ await withOrgScope(orgId, () => this.orgLock.lockAndAuthorize(orgId, acting.actor, "catalog.upload"));
260
268
  live.add(orgId);
261
269
  }
262
270
  else if (await this.orgLock.tryLock(orgId)) {
@@ -296,7 +304,23 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
296
304
  if (!UUID_RE.test(itemId))
297
305
  throw itemNotFound();
298
306
  await this.authorizeOwner(orgId, actor);
299
- return this.locked(itemId, () => this.updateLocked(actor, itemId, { version, diffHash }, opts, { orgId }));
307
+ await this.assertOwnedItem(orgId, itemId);
308
+ return this.locked(itemId, () => {
309
+ // org-filter: deployment-wide update of this owned plugin and its subscribers in one transaction.
310
+ return asPlatform("apply the owned plugin update across affected organizations", () => this.updateLocked(actor, itemId, { version, diffHash }, opts, { orgId }));
311
+ });
312
+ }
313
+ /** Check ownership before widening the preview or update. The diff checks it again. */
314
+ async assertOwnedItem(orgId, itemId) {
315
+ const item = await this.db
316
+ .selectFrom("catalog_items")
317
+ .select("id")
318
+ .where("id", "=", itemId)
319
+ .where("owner_org_id", "=", orgId)
320
+ .where("deleted_at", "is", null)
321
+ .executeTakeFirst();
322
+ if (!item)
323
+ throw itemNotFound();
300
324
  }
301
325
  /** The actor is an admin of the owner org (a read of the membership under the org row lock). */
302
326
  async authorizeOwner(orgId, actor) {
@@ -331,7 +355,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
331
355
  * the platform's import and update runs its import and this update under one hold.
332
356
  */
333
357
  async updateHeld(actor, itemId, input, opts = {}) {
334
- return this.updateLocked(actor, itemId, input, opts);
358
+ return this.updateLocked(actor, itemId, input, opts, undefined, true);
335
359
  }
336
360
  /**
337
361
  * Runs an update confirmed with the preview's `diffHash` (see the class comment). `actor`
@@ -343,13 +367,18 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
343
367
  throw itemNotFound();
344
368
  return this.locked(itemId, () => this.updateLocked(actor, itemId, input, opts));
345
369
  }
346
- async updateLocked(actor, itemId, input, opts, owner) {
370
+ async updateLocked(actor, itemId, input, opts, owner, verifiedDuringImport = false) {
347
371
  // Storage is read and written here, before any transaction (see the class comment)
348
372
  const checked = await this.diff(itemId, input.version, {
349
373
  ...(owner && { owner }),
350
374
  });
351
375
  if (checked.diffHash !== input.diffHash)
352
376
  throw stale();
377
+ // A combined import/update already rechecked the proof before approval. Bootstrap
378
+ // authorizes its own revision through the reviewed pin, without an attestation lookup.
379
+ const publisherProof = actor !== null && owner === undefined && !verifiedDuringImport
380
+ ? await this.verifyStoredPublisher(checked.to)
381
+ : undefined;
353
382
  const prepared = await this.platform.prepareSync(itemId, input.version);
354
383
  const ext = checked.extension;
355
384
  // The extension admin re-checks the actor: a super admin, or for an owner update the owner
@@ -392,6 +421,7 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
392
421
  contents: checked.contents,
393
422
  extension: ext,
394
423
  createOrgs: [...new Set(checked.creates.map((c) => c.orgId))],
424
+ ...(publisherProof !== undefined && { publisherProof }),
395
425
  }, prepared, owner);
396
426
  return {
397
427
  itemId,
@@ -472,6 +502,35 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
472
502
  detail: { name: diff.name, from: diff.from, to: diff.to.version, ...f },
473
503
  });
474
504
  }
505
+ /** Checks a marketplace revision chosen directly from the stored version list. */
506
+ async verifyStoredPublisher(to) {
507
+ const prefix = `${OFFICIAL_MARKETPLACE_ID}:`;
508
+ if (to.source !== "marketplace" || !to.source_ref?.startsWith(prefix))
509
+ return undefined;
510
+ const version = to.manifest.version;
511
+ const suffix = `@${version}`;
512
+ const name = to.source_ref.slice(prefix.length, -suffix.length);
513
+ if (!name ||
514
+ !to.source_ref.endsWith(suffix) ||
515
+ !to.integrity ||
516
+ sha512Hex(to.integrity) === undefined) {
517
+ throw new ApiError("marketplace.publisher_unverified", "The official marketplace revision has no exact npm identity");
518
+ }
519
+ if (to.extension_sha256 !== null) {
520
+ const bytes = await this.blobs.get(to.extension_sha256);
521
+ const actual = `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
522
+ if (to.integrity !== actual) {
523
+ throw new ApiError("marketplace.integrity_mismatch", "The stored revision does not match the marketplace SHA-512");
524
+ }
525
+ }
526
+ if ((await officialPublisherProofMode(this.db)) === "pin-only")
527
+ return undefined;
528
+ return requireMarketplacePublisher(this.config.get(), {
529
+ name,
530
+ version,
531
+ integrity: to.integrity,
532
+ });
533
+ }
475
534
  /**
476
535
  * The update's transaction (see the class comment): the super admin re-checked, the diff
477
536
  * recomputed under the item name's lock, then every write. Returns the diff it applied.
@@ -502,6 +561,24 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
502
561
  if (diff.diffHash !== input.diffHash)
503
562
  throw stale();
504
563
  const t = this.db;
564
+ if (pre.publisherProof !== undefined) {
565
+ const { revision } = pre.publisherProof;
566
+ if (diff.to.integrity !== revision.integrity ||
567
+ diff.to.source_ref !== `official:${revision.name}@${revision.version}`) {
568
+ throw stale();
569
+ }
570
+ await t
571
+ .updateTable("catalog_item_versions")
572
+ .set({
573
+ source_detail: JSON.stringify({
574
+ ...diff.to.source_detail,
575
+ publisherProof: pre.publisherProof,
576
+ }),
577
+ })
578
+ .where("item_id", "=", itemId)
579
+ .where("version", "=", input.version)
580
+ .execute();
581
+ }
505
582
  // The platform versions (files copied before the transaction; rows only here)
506
583
  try {
507
584
  await this.platform.applySyncIn(prepared);
@@ -731,7 +808,18 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
731
808
  const name = item.name;
732
809
  const versions = (await db
733
810
  .selectFrom("catalog_item_versions")
734
- .select(["version", "manifest", "object_prefix", "files", "extension_sha256", "applied_at"])
811
+ .select([
812
+ "version",
813
+ "manifest",
814
+ "object_prefix",
815
+ "files",
816
+ "extension_sha256",
817
+ "applied_at",
818
+ "source",
819
+ "source_ref",
820
+ "source_detail",
821
+ "integrity",
822
+ ])
735
823
  .where("item_id", "=", itemId)
736
824
  .execute());
737
825
  const to = o.target ?? versions.find((v) => v.version === version);
@@ -0,0 +1,9 @@
1
+ import { z } from "zod";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ export declare const OFFICIAL_MARKETPLACE_ID = "official";
4
+ export declare const OfficialPublisherProofMode: z.ZodEnum<{
5
+ "pin-only": "pin-only";
6
+ require: "require";
7
+ }>;
8
+ /** Only the platform deployment setting can opt out of publisher verification. */
9
+ export declare function officialPublisherProofMode(db: KernelSchemaDb): Promise<z.infer<typeof OfficialPublisherProofMode>>;
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ export const OFFICIAL_MARKETPLACE_ID = "official";
3
+ export const OfficialPublisherProofMode = z.enum(["require", "pin-only"]);
4
+ /** Only the platform deployment setting can opt out of publisher verification. */
5
+ export async function officialPublisherProofMode(db) {
6
+ const row = await db
7
+ .selectFrom("deployment_settings")
8
+ .select("value")
9
+ .where("key", "=", "officialPublisherProof")
10
+ .executeTakeFirst();
11
+ return OfficialPublisherProofMode.catch("require").parse(row?.value);
12
+ }
@@ -1,10 +1,11 @@
1
- // Turning 可共享 off on an org-owned item (ruling P3-25): an `optional` / `all` scope is narrowed, in
1
+ // Turning sharing off on an org-owned item (ruling P3-25): an `optional` / `all` scope is narrowed, in
2
2
  // the caller's transaction, to `named` = the owner plus every live org where the item is on right
3
3
  // now, so the orgs already associated keep it and no new org can see, switch on or request it
4
4
  // (§14.1 item 3). A `named` scope is left as it is: the gate in `requestable` and the writers
5
5
  // already holds back new orgs there.
6
6
  import { sql } from "kysely";
7
7
  import { audit } from "../identity/audit.js";
8
+ import { asPlatform } from "../infra/database/org-scope.js";
8
9
  import { componentOn, listedIn, loadScopeState, pluginFactsOf, switchOf, } from "./component-state.js";
9
10
  import { LIVE_INSTALL_STATUSES } from "./install-status.js";
10
11
  async function liveOrgIds(db) {
@@ -17,43 +18,46 @@ async function liveOrgIds(db) {
17
18
  * `catalog.scope_changed`; returns whether the scope changed (the caller enqueues the item's
18
19
  * scope sync after the commit).
19
20
  */
20
- // org-filter: unsharing narrows the item to every org where it is on now, so it reads and rewrites
21
- // the item's installs, switches and named list across orgs (keyed by the locked item id)
22
21
  export async function narrowItemOnUnshare(db, actor, item) {
23
- if (item.owner_org_id === null || item.scope === "named")
22
+ const ownerOrgId = item.owner_org_id;
23
+ if (ownerOrgId === null || item.scope === "named")
24
24
  return false;
25
- const live = new Set(await liveOrgIds(db));
26
- const installs = await db
27
- .selectFrom("plugin_installs")
28
- .select("org_id")
29
- .where("item_id", "=", item.id)
30
- .where("status", "in", [...LIVE_INSTALL_STATUSES])
31
- .execute();
32
- const switches = await db
33
- .selectFrom("catalog_item_org_switches")
34
- .select("org_id")
35
- .where("item_id", "=", item.id)
36
- .where("enabled", "=", true)
37
- .execute();
38
- const orgs = [
39
- ...new Set([
40
- item.owner_org_id,
41
- ...[...installs, ...switches].map((r) => r.org_id).filter((o) => live.has(o)),
42
- ]),
43
- ].sort();
44
- await db
45
- .updateTable("catalog_items")
46
- .set({
47
- scope: "named",
48
- updated_at: sql `now()`,
49
- })
50
- .where("id", "=", item.id)
51
- .execute();
52
- await db.deleteFrom("catalog_item_scope_orgs").where("item_id", "=", item.id).execute();
53
- await db
54
- .insertInto("catalog_item_scope_orgs")
55
- .values(orgs.map((org_id) => ({ item_id: item.id, org_id })))
56
- .execute();
25
+ // org-filter: deployment-wide reads and rewrite for the locked item's scope on unshare.
26
+ const orgs = await asPlatform("retain existing organizations on the unshared plugin", async () => {
27
+ const live = new Set(await liveOrgIds(db));
28
+ const installs = await db
29
+ .selectFrom("plugin_installs")
30
+ .select("org_id")
31
+ .where("item_id", "=", item.id)
32
+ .where("status", "in", [...LIVE_INSTALL_STATUSES])
33
+ .execute();
34
+ const switches = await db
35
+ .selectFrom("catalog_item_org_switches")
36
+ .select("org_id")
37
+ .where("item_id", "=", item.id)
38
+ .where("enabled", "=", true)
39
+ .execute();
40
+ const kept = [
41
+ ...new Set([
42
+ ownerOrgId,
43
+ ...[...installs, ...switches].map((r) => r.org_id).filter((o) => live.has(o)),
44
+ ]),
45
+ ].sort();
46
+ await db
47
+ .updateTable("catalog_items")
48
+ .set({
49
+ scope: "named",
50
+ updated_at: sql `now()`,
51
+ })
52
+ .where("id", "=", item.id)
53
+ .execute();
54
+ await db.deleteFrom("catalog_item_scope_orgs").where("item_id", "=", item.id).execute();
55
+ await db
56
+ .insertInto("catalog_item_scope_orgs")
57
+ .values(kept.map((org_id) => ({ item_id: item.id, org_id })))
58
+ .execute();
59
+ return kept;
60
+ });
57
61
  await audit(db, {
58
62
  ...(actor !== null && { actorAccountId: actor }),
59
63
  action: "catalog.scope_changed",
@@ -72,30 +76,34 @@ export async function narrowItemOnUnshare(db, actor, item) {
72
76
  * to `named` = owner + the live orgs where it is on now ({@link componentOn}). A component that
73
77
  * follows its plugin is narrowed with the plugin. Audits `component.scope_changed`.
74
78
  */
75
- // org-filter: unsharing narrows the component's whole named list to every org where it is on now
76
79
  export async function narrowComponentOnUnshare(db, actor, c) {
77
- if (c.ownerOrgId === null || c.scopeMode !== "own" || c.scope === "named")
80
+ const ownerOrgId = c.ownerOrgId;
81
+ if (ownerOrgId === null || c.scopeMode !== "own" || c.scope === "named")
78
82
  return false;
79
- const st = await loadScopeState(db, c.kind, [c]);
80
- const on = (await liveOrgIds(db)).filter((o) => componentOn(c, pluginFactsOf(st, c.itemId, o), listedIn(st, c.id, o), switchOf(st, c.id, o)));
81
- const orgs = [...new Set([c.ownerOrgId, ...on])].sort();
82
- await db
83
- .updateTable(TABLE[c.kind])
84
- .set({
85
- scope: "named",
86
- updated_at: sql `now()`,
87
- })
88
- .where("id", "=", c.id)
89
- .execute();
90
- await db
91
- .deleteFrom("component_scope_orgs")
92
- .where("kind", "=", c.kind)
93
- .where("component_id", "=", c.id)
94
- .execute();
95
- await db
96
- .insertInto("component_scope_orgs")
97
- .values(orgs.map((org_id) => ({ kind: c.kind, component_id: c.id, org_id })))
98
- .execute();
83
+ // org-filter: deployment-wide reads and rewrite for the locked component's scope on unshare.
84
+ const orgs = await asPlatform("retain existing organizations on the unshared component", async () => {
85
+ const st = await loadScopeState(db, c.kind, [c]);
86
+ const on = (await liveOrgIds(db)).filter((o) => componentOn(c, pluginFactsOf(st, c.itemId, o), listedIn(st, c.id, o), switchOf(st, c.id, o)));
87
+ const kept = [...new Set([ownerOrgId, ...on])].sort();
88
+ await db
89
+ .updateTable(TABLE[c.kind])
90
+ .set({
91
+ scope: "named",
92
+ updated_at: sql `now()`,
93
+ })
94
+ .where("id", "=", c.id)
95
+ .execute();
96
+ await db
97
+ .deleteFrom("component_scope_orgs")
98
+ .where("kind", "=", c.kind)
99
+ .where("component_id", "=", c.id)
100
+ .execute();
101
+ await db
102
+ .insertInto("component_scope_orgs")
103
+ .values(kept.map((org_id) => ({ kind: c.kind, component_id: c.id, org_id })))
104
+ .execute();
105
+ return kept;
106
+ });
99
107
  await audit(db, {
100
108
  ...(actor !== null && { actorAccountId: actor }),
101
109
  action: "component.scope_changed",
@@ -16,6 +16,7 @@ import { STALE_RECONCILE_PERIODS } from "../extensions/lifecycle-topics.js";
16
16
  import { CLIENT_EXTENSIONS_SETTING, parseClientExtensions, readClientExtensions, } from "../identity/settings.js";
17
17
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
18
18
  import { KernelDb } from "../infra/database/kernel-db.js";
19
+ import { asPlatform } from "../infra/database/org-scope.js";
19
20
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
21
  import { StorageService } from "../storage/storage.service.js";
21
22
  import { canUseSlot } from "../ui/registry.js";
@@ -182,7 +183,7 @@ let ClientAccess = class ClientAccess {
182
183
  */
183
184
  async fetchable(accountId, superAdmin, plugin, build) {
184
185
  const db = this.db.db;
185
- const row = await this.served(db)
186
+ const query = this.served(db)
186
187
  .where("i.name", "=", plugin)
187
188
  .where("b.package_sha256", "=", build)
188
189
  .select((eb) => [
@@ -210,8 +211,9 @@ let ClientAccess = class ClientAccess {
210
211
  .where("c.enabled", "=", true)),
211
212
  ])))
212
213
  .as("member"),
213
- ])
214
- .executeTakeFirst();
214
+ ]);
215
+ // org-filter: deployment-wide bundle access uses the authenticated account's memberships.
216
+ const row = await asPlatform("Check bundle access across the account's organizations", () => query.executeTakeFirst());
215
217
  if (row === undefined)
216
218
  return null;
217
219
  const kill = parseClientExtensions(row.kill ?? undefined, this.log);
@@ -69,6 +69,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
69
69
  url: z.ZodString;
70
70
  migrationUrl: z.ZodOptional<z.ZodString>;
71
71
  extensionsUrl: z.ZodOptional<z.ZodString>;
72
+ extensionPoolMax: z.ZodDefault<z.ZodNumber>;
72
73
  poolMax: z.ZodDefault<z.ZodNumber>;
73
74
  connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
74
75
  idleTimeoutMs: z.ZodDefault<z.ZodNumber>;