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

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.
@@ -1,5 +1,8 @@
1
+ import { PluginIcons } from "../extensions/plugin-icons.js";
1
2
  import { KernelDb } from "../infra/database/kernel-db.js";
2
3
  import { type Page } from "../infra/paging/paged-read.js";
4
+ import { type ConnectorSetup } from "../tools/connector-setup.js";
5
+ import { Credentials } from "../tools/credentials.js";
3
6
  import { AgentLookup, type AgentVisibility } from "./agent-lookup.js";
4
7
  import { type AgentDefinition } from "./definition.js";
5
8
  import type { AgentAvatarView } from "./profile.js";
@@ -56,7 +59,8 @@ export interface AdminAgentDetail extends AdminAgentRow {
56
59
  }[];
57
60
  /**
58
61
  * The org's live connectors it can use by name (tools default-on): every one but those whose
59
- * every tool it turns off. Never auth, credentials or a member's state.
62
+ * every tool it turns off, with their state and icon. Never auth, credentials or a member's
63
+ * state.
60
64
  */
61
65
  connectors: AdminAgentConnector[];
62
66
  }
@@ -65,6 +69,16 @@ export interface AdminAgentConnector {
65
69
  name: string;
66
70
  slug: string;
67
71
  status: "active" | "disabled";
72
+ /**
73
+ * Derived from key presence only, as on the org's connector routes: `needs_config` while the
74
+ * org input its auth needs (an OAuth client or an org credential) is absent.
75
+ */
76
+ setup: ConnectorSetup;
77
+ /**
78
+ * The icon it shows on the super admin's routes: its platform template's own icon, else its
79
+ * plugin's (`GET /api/v1/admin/catalog/...`), else null (a custom connector, or none).
80
+ */
81
+ icon: string | null;
68
82
  }
69
83
  export interface AdminAgentListQuery {
70
84
  orgId?: string | undefined;
@@ -83,7 +97,9 @@ export interface AdminAgentListQuery {
83
97
  export declare class AdminAgents {
84
98
  private readonly db;
85
99
  private readonly lookup;
86
- constructor(db: KernelDb, lookup: AgentLookup);
100
+ private readonly credentials;
101
+ private readonly icons;
102
+ constructor(db: KernelDb, lookup: AgentLookup, credentials: Pick<Credentials, "orgInputs">, icons: Pick<PluginIcons, "ofTemplatesOrItems">);
87
103
  /**
88
104
  * One page of every live org's live agents, filtered, newest first (`created_at`, then id), by
89
105
  * page number without a snapshot (table pagination spec §2.3: agents are edited in place).
@@ -100,7 +116,8 @@ export declare class AdminAgents {
100
116
  private skillsOff;
101
117
  /**
102
118
  * The org's live connectors by name, minus those the agent turns off as a whole: `tools: "all"`,
103
- * or a list naming every tool the connector has (a connector without tools stays listed).
119
+ * or a list naming every tool the connector has (a connector without tools stays listed). Each
120
+ * with its derived setup state and its icon on the admin routes (one lookup each for all).
104
121
  */
105
122
  private connectorsOf;
106
123
  /** The list columns of live agents in live orgs. */
@@ -11,10 +11,13 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { escapeLike } from "../conversations/conversations.service.js";
13
13
  import { ApiError } from "../errors.js";
14
+ import { PluginIcons } from "../extensions/plugin-icons.js";
14
15
  import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
15
16
  import { KernelDb } from "../infra/database/kernel-db.js";
16
17
  import { assertReadablePage, cappedCount, PAGED_TOTAL_CAP, pageOf, pageOffset, } from "../infra/paging/paged-read.js";
17
18
  import { agentSkills, builtinSkillIds, builtinSkillPlugins, linkedCopyIds, skillIdsOf, usableSkillVersions, } from "../skills/usable.js";
19
+ import { connectorSetups } from "../tools/connector-setup.js";
20
+ import { Credentials } from "../tools/credentials.js";
18
21
  import { AgentLookup } from "./agent-lookup.js";
19
22
  import { avatarView } from "./avatar-view.js";
20
23
  import { skillDisabled, } from "./definition.js";
@@ -27,9 +30,13 @@ const notFound = () => new ApiError("agent.not_found", "Agent not found");
27
30
  let AdminAgents = class AdminAgents {
28
31
  db;
29
32
  lookup;
30
- constructor(db, lookup) {
33
+ credentials;
34
+ icons;
35
+ constructor(db, lookup, credentials, icons) {
31
36
  this.db = db;
32
37
  this.lookup = lookup;
38
+ this.credentials = credentials;
39
+ this.icons = icons;
33
40
  }
34
41
  /**
35
42
  * One page of every live org's live agents, filtered, newest first (`created_at`, then id), by
@@ -147,12 +154,21 @@ let AdminAgents = class AdminAgents {
147
154
  }
148
155
  /**
149
156
  * The org's live connectors by name, minus those the agent turns off as a whole: `tools: "all"`,
150
- * or a list naming every tool the connector has (a connector without tools stays listed).
157
+ * or a list naming every tool the connector has (a connector without tools stays listed). Each
158
+ * with its derived setup state and its icon on the admin routes (one lookup each for all).
151
159
  */
152
160
  async connectorsOf(orgId, disabled) {
153
161
  const rows = await this.db
154
162
  .selectFrom("connectors as c")
155
- .select(["c.id", "c.name", "c.slug", "c.status"])
163
+ .select([
164
+ "c.id",
165
+ "c.name",
166
+ "c.slug",
167
+ "c.status",
168
+ "c.auth",
169
+ "c.platform_template_id",
170
+ "c.catalog_item_id",
171
+ ])
156
172
  .select(sql `coalesce((SELECT array_agg(t.name) FROM capybara.connector_tools t
157
173
  WHERE t.connector_id = c.id), '{}')`.as("tools"))
158
174
  .where("c.org_id", "=", orgId)
@@ -178,9 +194,22 @@ let AdminAgents = class AdminAgents {
178
194
  return true;
179
195
  return tools.length > 0 && tools.every((t) => off.has(t));
180
196
  };
181
- return rows
182
- .filter((r) => !allOff(r.id, r.tools))
183
- .map((r) => ({ id: r.id, name: r.name, slug: r.slug, status: r.status }));
197
+ const listed = rows.filter((r) => !allOff(r.id, r.tools));
198
+ const [setups, icons] = await Promise.all([
199
+ connectorSetups(this.credentials, orgId, listed.map((r) => ({ id: r.id, auth: r.auth }))),
200
+ this.icons.ofTemplatesOrItems(listed.map((r) => ({
201
+ templateId: r.platform_template_id ?? null,
202
+ itemId: r.catalog_item_id ?? null,
203
+ })), { kind: "admin" }),
204
+ ]);
205
+ return listed.map((r, i) => ({
206
+ id: r.id,
207
+ name: r.name,
208
+ slug: r.slug,
209
+ status: r.status,
210
+ setup: setups.get(r.id) ?? "needs_config",
211
+ icon: icons[i] ?? null,
212
+ }));
184
213
  }
185
214
  /** The list columns of live agents in live orgs. */
186
215
  rows() {
@@ -214,7 +243,9 @@ let AdminAgents = class AdminAgents {
214
243
  AdminAgents = __decorate([
215
244
  Injectable(),
216
245
  __param(0, Inject(KernelDb)),
217
- __param(1, Inject(AgentLookup))
246
+ __param(1, Inject(AgentLookup)),
247
+ __param(2, Inject(Credentials)),
248
+ __param(3, Inject(PluginIcons))
218
249
  ], AdminAgents);
219
250
  export { AdminAgents };
220
251
  function toRow(r, skillsOff) {
@@ -3,6 +3,8 @@ import type { KernelConfig } from "../config/schema.js";
3
3
  import { type LookupFn, NetDeniedError, type NetPolicy } from "../net/public-address.js";
4
4
  import { type OfficialNpmRevision, type OfficialPublisherProof } from "../packages/official-publisher.js";
5
5
  export declare function requireMarketplacePublisher(config: Pick<KernelConfig, "packages" | "marketplaces" | "net">, revision: OfficialNpmRevision, signal?: AbortSignal): Promise<OfficialPublisherProof>;
6
+ /** Whether a {@link requireMarketplacePublisher} failure was a network or registry hiccup. */
7
+ export declare function publisherCheckTransient(error: unknown): boolean;
6
8
  /**
7
9
  * Fetching a marketplace manifest `marketplace.json` (C26, spec §5.2) and a marketplace's archive
8
10
  * sources. The URLs come from a super admin or the config, but responses are always hostile
@@ -4,7 +4,7 @@ import { ApiError } from "../errors.js";
4
4
  import { NetDeniedError } from "../net/public-address.js";
5
5
  import { describeFetchError, safeFetch } from "../net/safe-fetch.js";
6
6
  import { isLoopback, readCapped } from "../packages/npm.js";
7
- import { fetchOfficialPublisher, } from "../packages/official-publisher.js";
7
+ import { fetchOfficialPublisher, OfficialPublisherError, } from "../packages/official-publisher.js";
8
8
  export async function requireMarketplacePublisher(config, revision, signal) {
9
9
  try {
10
10
  return await fetchOfficialPublisher({
@@ -16,9 +16,14 @@ export async function requireMarketplacePublisher(config, revision, signal) {
16
16
  }
17
17
  catch (error) {
18
18
  const reason = error instanceof Error ? error.message : String(error);
19
- throw new ApiError("marketplace.publisher_unverified", `Cannot verify the official publisher for ${revision.name}@${revision.version}: ${reason}`);
19
+ throw new ApiError("marketplace.publisher_unverified", `Cannot verify the official publisher for ${revision.name}@${revision.version}: ${reason}`, undefined, { cause: error });
20
20
  }
21
21
  }
22
+ /** Whether a {@link requireMarketplacePublisher} failure was a network or registry hiccup. */
23
+ export function publisherCheckTransient(error) {
24
+ const cause = error instanceof Error ? error.cause : undefined;
25
+ return cause instanceof OfficialPublisherError && cause.transient;
26
+ }
22
27
  /**
23
28
  * The API error for a refused download, or undefined when the refusal is not one of the two
24
29
  * marketplace codes (an invalid URL or a DNS failure is an ordinary fetch failure).
package/dist/errors.d.ts CHANGED
@@ -803,7 +803,7 @@ export type ErrorCode = keyof typeof ERROR_CODES;
803
803
  export declare class ApiError extends Error {
804
804
  readonly code: ErrorCode;
805
805
  readonly details?: unknown[] | undefined;
806
- constructor(code: ErrorCode, message: string, details?: unknown[] | undefined);
806
+ constructor(code: ErrorCode, message: string, details?: unknown[] | undefined, options?: ErrorOptions);
807
807
  get status(): number;
808
808
  }
809
809
  /** 错误信封的 body。 */
package/dist/errors.js CHANGED
@@ -802,8 +802,8 @@ export const ERROR_CODES = {
802
802
  export class ApiError extends Error {
803
803
  code;
804
804
  details;
805
- constructor(code, message, details) {
806
- super(message);
805
+ constructor(code, message, details, options) {
806
+ super(message, options);
807
807
  this.code = code;
808
808
  this.details = details;
809
809
  this.name = "ApiError";
@@ -39,7 +39,7 @@ 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";
@@ -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,6 +63,7 @@ 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";
@@ -1024,13 +1026,23 @@ let ExtensionHost = class ExtensionHost {
1024
1026
  const wanted = new Map();
1025
1027
  const tiers = new Map();
1026
1028
  const rejected = new Map();
1029
+ const rejectedActions = new Map();
1030
+ let proofMode;
1027
1031
  for (const d of electAmong) {
1028
1032
  if (declared.has(d.name))
1029
1033
  continue;
1030
1034
  try {
1031
1035
  const tier = await this.tierOf(loader, d, false);
1032
1036
  if (tier === "refused") {
1033
- rejected.set(d.name, "The extension revision did not pass trust admission");
1037
+ if (publisherProofMissing(d)) {
1038
+ proofMode ??= await officialPublisherProofMode(kernelDb(this.deps.db));
1039
+ const refusal = publisherProofRefusal(proofMode);
1040
+ rejected.set(d.name, refusal.detail);
1041
+ rejectedActions.set(d.name, refusal.action);
1042
+ }
1043
+ else {
1044
+ rejected.set(d.name, "The extension revision did not pass trust admission");
1045
+ }
1034
1046
  continue;
1035
1047
  }
1036
1048
  if (tier === "isolated")
@@ -1104,7 +1116,8 @@ let ExtensionHost = class ExtensionHost {
1104
1116
  const detail = rejected.get(d.name);
1105
1117
  if (!detail)
1106
1118
  continue;
1107
- await this.reportAdmissionRefusal(d.name, d.sha256, detail, "Review the plugin revision and install a package eligible for this deployment.");
1119
+ await this.reportAdmissionRefusal(d.name, d.sha256, detail, rejectedActions.get(d.name) ??
1120
+ "Review the plugin revision and install a package eligible for this deployment.");
1108
1121
  await this.writeStatus({
1109
1122
  plugin: d.name,
1110
1123
  version: d.version,
@@ -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") {
@@ -0,0 +1,39 @@
1
+ import type { ExtensionContext } from "@capybara-hq/plugin-sdk";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { LockService } from "../infra/lock/lock.service.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ export declare const PUBLISHER_PROOF_RECHECK_JOB = "extension-publisher-proof-recheck";
7
+ /**
8
+ * A definite failure (no provenance, another signer, digest or name) is not fetched again before
9
+ * this long: the registry's answer rarely changes. A transient one (network, timeout, 5xx) is
10
+ * retried on the next tick.
11
+ */
12
+ export declare const PUBLISHER_PROOF_RETRY_MS: number;
13
+ /**
14
+ * Records the publisher proof of installed official-marketplace revisions imported before the
15
+ * kernel recorded one (kernel rc.165 made it an admission condition). Admission itself never
16
+ * fetches: this worker job (`@LockedInterval`, once per tick across replicas, run at start) fetches
17
+ * the npm publish and workflow attestations of exactly `name@version`, verifies them with the same
18
+ * code an import uses against the bundled trust root and the recorded integrity, and writes the
19
+ * proof into the revision's `source_detail` in one conditional statement (only while still
20
+ * missing, so a concurrent upgrade or a second run changes nothing). Every replica then admits the
21
+ * revision on its next convergence. A revision that cannot be verified (no attestations, other
22
+ * signer, other digest) keeps being refused with the "publisher proof missing" reason; the failure
23
+ * is recorded and retried after {@link PUBLISHER_PROOF_RETRY_MS}, a network or registry hiccup on
24
+ * the next tick. Under the super admin's pin-only choice nothing is fetched.
25
+ */
26
+ export declare class PublisherProofRecheckJob {
27
+ private readonly kdb;
28
+ private readonly bus;
29
+ readonly config: KernelConfigService;
30
+ readonly lockService: LockService;
31
+ readonly log: KernelLogger;
32
+ constructor(kdb: KernelDb, bus: Pick<ExtensionContext["bus"], "publish">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
33
+ recheck(stop?: AbortSignal): Promise<void>;
34
+ /** One pass (the locked tick runs it); returns how many proofs it recorded and how many failed. */
35
+ run(stop?: AbortSignal): Promise<{
36
+ recorded: number;
37
+ failed: number;
38
+ }>;
39
+ }
@@ -0,0 +1,160 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { publisherCheckTransient, requireMarketplacePublisher, } from "../catalog/marketplace-fetch.js";
13
+ import { OFFICIAL_MARKETPLACE_ID, officialPublisherProofMode, } from "../catalog/publisher-policy.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { LockService } from "../infra/lock/lock.service.js";
17
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
18
+ import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
19
+ import { PLUGINS_RECONCILE_TOPIC } from "./lifecycle-topics.js";
20
+ export const PUBLISHER_PROOF_RECHECK_JOB = "extension-publisher-proof-recheck";
21
+ const PUBLISHER_PROOF_RECHECK_PERIOD_MS = 15 * 60_000;
22
+ /**
23
+ * A definite failure (no provenance, another signer, digest or name) is not fetched again before
24
+ * this long: the registry's answer rarely changes. A transient one (network, timeout, 5xx) is
25
+ * retried on the next tick.
26
+ */
27
+ export const PUBLISHER_PROOF_RETRY_MS = 6 * 60 * 60_000;
28
+ /** Revisions checked per tick (each is one bounded attestation fetch). */
29
+ const PUBLISHER_PROOF_BATCH = 20;
30
+ /**
31
+ * Records the publisher proof of installed official-marketplace revisions imported before the
32
+ * kernel recorded one (kernel rc.165 made it an admission condition). Admission itself never
33
+ * fetches: this worker job (`@LockedInterval`, once per tick across replicas, run at start) fetches
34
+ * the npm publish and workflow attestations of exactly `name@version`, verifies them with the same
35
+ * code an import uses against the bundled trust root and the recorded integrity, and writes the
36
+ * proof into the revision's `source_detail` in one conditional statement (only while still
37
+ * missing, so a concurrent upgrade or a second run changes nothing). Every replica then admits the
38
+ * revision on its next convergence. A revision that cannot be verified (no attestations, other
39
+ * signer, other digest) keeps being refused with the "publisher proof missing" reason; the failure
40
+ * is recorded and retried after {@link PUBLISHER_PROOF_RETRY_MS}, a network or registry hiccup on
41
+ * the next tick. Under the super admin's pin-only choice nothing is fetched.
42
+ */
43
+ let PublisherProofRecheckJob = class PublisherProofRecheckJob {
44
+ kdb;
45
+ bus;
46
+ config;
47
+ lockService;
48
+ log;
49
+ constructor(kdb, bus, config, lockService, log) {
50
+ this.kdb = kdb;
51
+ this.bus = bus;
52
+ this.config = config;
53
+ this.lockService = lockService;
54
+ this.log = log;
55
+ }
56
+ async recheck(stop) {
57
+ await this.run(stop);
58
+ }
59
+ /** One pass (the locked tick runs it); returns how many proofs it recorded and how many failed. */
60
+ async run(stop) {
61
+ const db = this.kdb.db;
62
+ if ((await officialPublisherProofMode(db)) === "pin-only")
63
+ return { recorded: 0, failed: 0 };
64
+ const now = Date.now();
65
+ const rows = await db
66
+ .selectFrom("extension_installs")
67
+ .innerJoin("catalog_items", "catalog_items.id", "extension_installs.catalog_item_id")
68
+ .innerJoin("catalog_item_versions as revision", (join) => join
69
+ .onRef("revision.item_id", "=", "catalog_items.id")
70
+ .onRef("revision.extension_sha256", "=", "extension_installs.sha256")
71
+ .onRef("revision.version", "=", "extension_installs.version"))
72
+ .select([
73
+ "revision.item_id",
74
+ "revision.version",
75
+ "revision.integrity",
76
+ "catalog_items.package_name",
77
+ ])
78
+ .where("extension_installs.source", "=", "catalog")
79
+ .where("catalog_items.marketplace_id", "=", OFFICIAL_MARKETPLACE_ID)
80
+ .where("revision.source", "=", "marketplace")
81
+ .where("revision.integrity", "is not", null)
82
+ .where("catalog_items.package_name", "is not", null)
83
+ .where(sql `NOT (coalesce(revision.source_detail, '{}'::jsonb) ? 'publisherProof')`)
84
+ .where(sql `coalesce(revision.source_detail -> 'publisherProofCheck' ->> 'retryAt', '') <= ${new Date(now).toISOString()}`)
85
+ .orderBy("revision.item_id")
86
+ .limit(PUBLISHER_PROOF_BATCH)
87
+ .execute();
88
+ let recorded = 0;
89
+ let failed = 0;
90
+ for (const row of rows) {
91
+ if (stop?.aborted)
92
+ break;
93
+ const revision = {
94
+ name: row.package_name,
95
+ version: row.version,
96
+ integrity: row.integrity,
97
+ };
98
+ let detail;
99
+ try {
100
+ detail = {
101
+ publisherProof: await requireMarketplacePublisher(this.config.get(), revision, stop),
102
+ };
103
+ recorded += 1;
104
+ }
105
+ catch (err) {
106
+ if (stop?.aborted)
107
+ break;
108
+ failed += 1;
109
+ const reason = err instanceof Error ? err.message : String(err);
110
+ const transient = publisherCheckTransient(err);
111
+ this.log.warn("cannot verify the official publisher of an installed revision", {
112
+ plugin: revision.name,
113
+ version: revision.version,
114
+ reason,
115
+ transient,
116
+ });
117
+ const failedAt = Date.now();
118
+ detail = {
119
+ publisherProofCheck: {
120
+ failedAt: new Date(failedAt).toISOString(),
121
+ reason,
122
+ transient,
123
+ retryAt: new Date(transient ? failedAt : failedAt + PUBLISHER_PROOF_RETRY_MS).toISOString(),
124
+ },
125
+ };
126
+ }
127
+ // One conditional statement is its own transaction: nothing else is written with it, and the
128
+ // condition keeps a proof an upgrade or another pass recorded meanwhile.
129
+ await db
130
+ .updateTable("catalog_item_versions")
131
+ .set({
132
+ source_detail: sql `(coalesce(source_detail, '{}'::jsonb) - 'publisherProofCheck') || ${JSON.stringify(detail)}::jsonb`,
133
+ })
134
+ .where("item_id", "=", row.item_id)
135
+ .where("version", "=", row.version)
136
+ .where("integrity", "=", revision.integrity)
137
+ .where(sql `NOT (coalesce(source_detail, '{}'::jsonb) ? 'publisherProof')`)
138
+ .execute();
139
+ }
140
+ if (recorded > 0) {
141
+ this.log.info("recorded official publisher proofs of installed revisions", { recorded });
142
+ await this.bus.publish(PLUGINS_RECONCILE_TOPIC, {});
143
+ }
144
+ return { recorded, failed };
145
+ }
146
+ };
147
+ __decorate([
148
+ LockedInterval(PUBLISHER_PROOF_RECHECK_JOB, () => PUBLISHER_PROOF_RECHECK_PERIOD_MS, {
149
+ runOnStart: true,
150
+ })
151
+ ], PublisherProofRecheckJob.prototype, "recheck", null);
152
+ PublisherProofRecheckJob = __decorate([
153
+ Injectable(),
154
+ __param(0, Inject(KernelDb)),
155
+ __param(1, Inject(KERNEL_BUS)),
156
+ __param(2, Inject(KernelConfigService)),
157
+ __param(3, Inject(LockService)),
158
+ __param(4, Inject(KERNEL_LOGGER))
159
+ ], PublisherProofRecheckJob);
160
+ export { PublisherProofRecheckJob };
@@ -16,4 +16,9 @@ export interface OfficialPublisherProof extends Provenance {
16
16
  export declare function verifyOfficialPublisher(body: unknown, revision: OfficialNpmRevision): OfficialPublisherProof;
17
17
  /** Uses the same bounded registry client as the review's display-only provenance. */
18
18
  export declare function fetchOfficialPublisher(cfg: NpmFetchConfig, revision: OfficialNpmRevision, signal?: AbortSignal): Promise<OfficialPublisherProof>;
19
+ /** A failed publisher check; `transient` failures (network, timeout, 5xx) may pass on a retry soon. */
20
+ export declare class OfficialPublisherError extends Error {
21
+ readonly transient: boolean;
22
+ constructor(cause: unknown, transient: boolean);
23
+ }
19
24
  export {};
@@ -5,7 +5,7 @@ import { toSignedEntity, toTrustMaterial, Verifier } from "@sigstore/verify";
5
5
  import { z } from "zod";
6
6
  import { canonicalJson } from "../tools/canonical-json.js";
7
7
  import npmPublishKeys from "./npm-publish-keys.json" with { type: "json" };
8
- import { fetchNpmAttestations, PROVENANCE_TIMEOUT_MS, SLSA_PROVENANCE_V1, sha512Hex, } from "./provenance.js";
8
+ import { fetchNpmAttestations, isTransientAttestationsFailure, PROVENANCE_TIMEOUT_MS, SLSA_PROVENANCE_V1, sha512Hex, } from "./provenance.js";
9
9
  import trustedRoot from "./sigstore-trusted-root.json" with { type: "json" };
10
10
  const NPM_PUBLISH = "https://github.com/npm/attestation/tree/main/specs/publish/v0.1";
11
11
  const REGISTRY = "https://registry.npmjs.org";
@@ -147,6 +147,27 @@ export function verifyOfficialPublisher(body, revision) {
147
147
  /** Uses the same bounded registry client as the review's display-only provenance. */
148
148
  export async function fetchOfficialPublisher(cfg, revision, signal) {
149
149
  const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
150
- const attestations = await fetchNpmAttestations(cfg, revision.name, revision.version, signal ? AbortSignal.any([signal, timeout]) : timeout);
151
- return verifyOfficialPublisher(attestations, revision);
150
+ let attestations;
151
+ try {
152
+ attestations = await fetchNpmAttestations(cfg, revision.name, revision.version, signal ? AbortSignal.any([signal, timeout]) : timeout);
153
+ }
154
+ catch (e) {
155
+ throw new OfficialPublisherError(e, isTransientAttestationsFailure(e));
156
+ }
157
+ try {
158
+ return verifyOfficialPublisher(attestations, revision);
159
+ }
160
+ catch (e) {
161
+ // Verification is deterministic for the fetched evidence: another signer, digest or name.
162
+ throw new OfficialPublisherError(e, false);
163
+ }
164
+ }
165
+ /** A failed publisher check; `transient` failures (network, timeout, 5xx) may pass on a retry soon. */
166
+ export class OfficialPublisherError extends Error {
167
+ transient;
168
+ constructor(cause, transient) {
169
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
170
+ this.transient = transient;
171
+ this.name = "OfficialPublisherError";
172
+ }
152
173
  }
@@ -35,6 +35,12 @@ export type ProvenanceResult = Provenance | ProvenanceNotChecked;
35
35
  export declare const SLSA_PROVENANCE_V1 = "https://slsa.dev/provenance/v1";
36
36
  /** Provenance must not hold up an import: a slow registry gives "not checked". */
37
37
  export declare const PROVENANCE_TIMEOUT_MS = 15000;
38
+ /**
39
+ * Whether a {@link fetchNpmAttestations} failure may pass on a retry soon (timeouts, network
40
+ * errors, other HTTP statuses than 404) rather than being the registry's answer (no provenance, an
41
+ * invalid name, a malformed or oversized body).
42
+ */
43
+ export declare function isTransientAttestationsFailure(e: unknown): boolean;
38
44
  /** The hex sha512 of a `sha512-<base64>` integrity (undefined for anything else). */
39
45
  export declare function sha512Hex(integrity: string): string | undefined;
40
46
  /**
@@ -11,6 +11,25 @@ const NPM_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
11
11
  const SEMVER_RE = /^[0-9A-Za-z.+-]{1,256}$/;
12
12
  const COMMIT_RE = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
13
13
  class NpmAttestationsError extends Error {
14
+ transient;
15
+ constructor(message,
16
+ /** A network or registry hiccup worth retrying soon; false for the registry's definite answers. */
17
+ transient, options) {
18
+ super(message, options);
19
+ this.transient = transient;
20
+ }
21
+ }
22
+ class AttestationsTooLarge extends Error {
23
+ }
24
+ /**
25
+ * Whether a {@link fetchNpmAttestations} failure may pass on a retry soon (timeouts, network
26
+ * errors, other HTTP statuses than 404) rather than being the registry's answer (no provenance, an
27
+ * invalid name, a malformed or oversized body).
28
+ */
29
+ export function isTransientAttestationsFailure(e) {
30
+ if (e instanceof NpmAttestationsError)
31
+ return e.transient;
32
+ return !(e instanceof SyntaxError || e instanceof AttestationsTooLarge);
14
33
  }
15
34
  const notChecked = (reason) => ({ checked: false, reason });
16
35
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
@@ -44,7 +63,7 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
44
63
  /** Fetches bounded attestation evidence without accepting it as publisher proof. */
45
64
  export async function fetchNpmAttestations(cfg, name, version, signal) {
46
65
  if (!NPM_NAME_RE.test(name) || name.length > 214 || !SEMVER_RE.test(version)) {
47
- throw new NpmAttestationsError("not a valid npm package name and version");
66
+ throw new NpmAttestationsError("not a valid npm package name and version", false);
48
67
  }
49
68
  try {
50
69
  const registry = new URL(cfg.registry.endsWith("/") ? cfg.registry : `${cfg.registry}/`);
@@ -58,20 +77,18 @@ export async function fetchNpmAttestations(cfg, name, version, signal) {
58
77
  }, cfg.net, cfg.lookup !== undefined ? { lookup: cfg.lookup } : {});
59
78
  if (!res.ok) {
60
79
  await res.body?.cancel().catch(() => { });
61
- throw new NpmAttestationsError(res.status === 404
62
- ? "the registry has no provenance for this version"
63
- : `the registry answered HTTP ${res.status} for the attestations`);
80
+ throw res.status === 404
81
+ ? new NpmAttestationsError("the registry has no provenance for this version", false)
82
+ : new NpmAttestationsError(`the registry answered HTTP ${res.status} for the attestations`, true);
64
83
  }
65
- const raw = await readCapped(res, MAX_ATTESTATION_BYTES, () => new Error("the attestations are too large"));
84
+ const raw = await readCapped(res, MAX_ATTESTATION_BYTES, () => new AttestationsTooLarge("the attestations are too large"));
66
85
  return JSON.parse(raw.toString("utf8"));
67
86
  }
68
87
  catch (e) {
69
88
  if (signal.aborted)
70
- throw new NpmAttestationsError("the registry did not answer in time", { cause: e });
89
+ throw new NpmAttestationsError("the registry did not answer in time", true, { cause: e });
71
90
  if (e instanceof NetDeniedError) {
72
- throw new NpmAttestationsError(`the network rules refused the attestations: ${e.message}`, {
73
- cause: e,
74
- });
91
+ throw new NpmAttestationsError(`the network rules refused the attestations: ${e.message}`, true, { cause: e });
75
92
  }
76
93
  throw e;
77
94
  }
@@ -96,7 +96,7 @@ let AdminItemsOperations = class AdminItemsOperations {
96
96
  }),
97
97
  defineOperation({
98
98
  id: "admin.agent-get",
99
- description: "Read one agent of this org as the admin console shows it (super admin): its definition with the instructions in full, members, profile with quick action labels, versions count, the skills and connectors it has by name, and how many of the org's skills it turns off (skillsOff). Never its conversations or credentials.",
99
+ description: "Read one agent of this org as the admin console shows it (super admin): its definition with the instructions in full, members, profile with quick action labels, versions count, the skills it has by name and the connectors with their status, setup state and icon, and how many of the org's skills it turns off (skillsOff). Never its conversations or credentials.",
100
100
  input: AgentIdInput,
101
101
  example: { agentId: "7c1a5b0e-9a53-4c6b-8d64-2f5a1b0c3e77" },
102
102
  authz: { superAdmin: true },
@@ -36,6 +36,7 @@ import { ExtensionsModule } from "../extensions/extensions.module.js";
36
36
  import { PluginsReconcileJob } from "../extensions/lifecycle.js";
37
37
  import { LifecycleHookWorkersModule } from "../extensions/lifecycle-hooks.js";
38
38
  import { PackageDigestBackfillJob } from "../extensions/package-digest.job.js";
39
+ import { PublisherProofRecheckJob } from "../extensions/publisher-proof.job.js";
39
40
  import { BlobSweepModule } from "../files/blob-sweep.job.js";
40
41
  import { FileDraftCleanupJob } from "../files/draft-cleanup.job.js";
41
42
  import { FileLibraryKickoffJob } from "../files/hash-job.js";
@@ -168,6 +169,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
168
169
  CatalogJobs,
169
170
  // sha512 of packages stored before migration 0235 (extension permission model plan 1.2b)
170
171
  PackageDigestBackfillJob,
172
+ // publisher proofs of official revisions imported before they were recorded (rc.165)
173
+ PublisherProofRecheckJob,
171
174
  DirectoryScanJob,
172
175
  PluginsReconcileJob,
173
176
  GatewayCheckJob,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.144",
3
+ "version": "0.1.0-rc.145",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {