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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/admin/extensions.controller.d.ts +0 -11
  2. package/dist/admin/extensions.controller.js +0 -28
  3. package/dist/admin/health.service.d.ts +25 -1
  4. package/dist/admin/health.service.js +50 -18
  5. package/dist/audit/full-access.d.ts +78 -0
  6. package/dist/audit/full-access.js +283 -0
  7. package/dist/automations/automations.service.d.ts +1 -0
  8. package/dist/automations/automations.service.js +3 -1
  9. package/dist/automations/calendar.js +3 -1
  10. package/dist/automations/grant-rules.d.ts +2 -1
  11. package/dist/automations/grant-rules.js +8 -1
  12. package/dist/automations/unattended.d.ts +13 -1
  13. package/dist/automations/unattended.js +13 -1
  14. package/dist/catalog/admin-catalog.controller.d.ts +8 -0
  15. package/dist/catalog/admin-catalog.controller.js +8 -2
  16. package/dist/catalog/admin-catalog.schemas.d.ts +10 -0
  17. package/dist/catalog/admin-catalog.schemas.js +8 -1
  18. package/dist/catalog/catalog-content.d.ts +6 -0
  19. package/dist/catalog/catalog-scope.service.d.ts +22 -2
  20. package/dist/catalog/catalog-scope.service.js +27 -3
  21. package/dist/catalog/catalog.service.js +19 -2
  22. package/dist/catalog/marketplaces.service.d.ts +1 -1
  23. package/dist/catalog/org-catalog.service.d.ts +8 -1
  24. package/dist/catalog/org-catalog.service.js +36 -3
  25. package/dist/catalog/platform-components.js +3 -2
  26. package/dist/catalog/platform-import-update.d.ts +2 -0
  27. package/dist/catalog/platform-import-update.js +8 -1
  28. package/dist/catalog/plugin-connectors.d.ts +11 -0
  29. package/dist/catalog/plugin-connectors.js +33 -0
  30. package/dist/catalog/plugin-import.d.ts +35 -15
  31. package/dist/catalog/plugin-import.js +110 -35
  32. package/dist/catalog/plugin-install.js +6 -0
  33. package/dist/catalog/provenance.d.ts +2 -0
  34. package/dist/catalog/provenance.js +5 -1
  35. package/dist/config/auto-approve.d.ts +16 -0
  36. package/dist/config/auto-approve.js +24 -0
  37. package/dist/config/capacity-presets.d.ts +243 -0
  38. package/dist/config/capacity-presets.js +195 -0
  39. package/dist/config/env.d.ts +2 -1
  40. package/dist/config/env.js +6 -1
  41. package/dist/config/load.js +15 -0
  42. package/dist/config/schema.d.ts +46 -9
  43. package/dist/config/schema.js +154 -30
  44. package/dist/ctx/net.d.ts +5 -1
  45. package/dist/ctx/net.js +62 -12
  46. package/dist/db/kernel-schema.d.ts +31 -0
  47. package/dist/db/migrator.js +0 -36
  48. package/dist/dial-in/routes.js +1 -1
  49. package/dist/erasure/org-batches.js +1 -6
  50. package/dist/erasure/org-catalog.js +6 -2
  51. package/dist/erasure/org-rules.js +1 -0
  52. package/dist/erasure/org-worker.js +0 -13
  53. package/dist/errors.d.ts +6 -0
  54. package/dist/errors.js +6 -0
  55. package/dist/extensions/admin-ops.d.ts +14 -1
  56. package/dist/extensions/admin-ops.js +30 -3
  57. package/dist/extensions/admin-view.d.ts +21 -1
  58. package/dist/extensions/admin-view.js +43 -0
  59. package/dist/extensions/bootstrap-packages.d.ts +5 -0
  60. package/dist/extensions/bootstrap-packages.js +1 -1
  61. package/dist/extensions/bootstrap-review.d.ts +251 -0
  62. package/dist/extensions/bootstrap-review.js +676 -0
  63. package/dist/extensions/bootstrap.d.ts +21 -1
  64. package/dist/extensions/bootstrap.js +72 -2
  65. package/dist/extensions/cli.d.ts +6 -0
  66. package/dist/extensions/cli.js +4 -0
  67. package/dist/extensions/enabled.d.ts +3 -0
  68. package/dist/extensions/extensions.module.js +9 -0
  69. package/dist/extensions/full-access-disclosure.d.ts +15 -0
  70. package/dist/extensions/full-access-disclosure.js +57 -0
  71. package/dist/extensions/grant-epoch.d.ts +5 -0
  72. package/dist/extensions/grant-epoch.js +9 -0
  73. package/dist/extensions/host.d.ts +71 -2
  74. package/dist/extensions/host.js +293 -27
  75. package/dist/extensions/installs.d.ts +18 -0
  76. package/dist/extensions/installs.js +28 -0
  77. package/dist/extensions/isolated/admission.d.ts +17 -2
  78. package/dist/extensions/isolated/admission.js +15 -7
  79. package/dist/extensions/isolated/authorization.d.ts +8 -2
  80. package/dist/extensions/isolated/authorization.js +11 -3
  81. package/dist/extensions/isolated/broker.d.ts +3 -0
  82. package/dist/extensions/isolated/broker.js +50 -14
  83. package/dist/extensions/isolated/configured-package.d.ts +5 -0
  84. package/dist/extensions/isolated/configured-package.js +2 -0
  85. package/dist/extensions/isolated/lanes.d.ts +44 -3
  86. package/dist/extensions/isolated/lanes.js +263 -80
  87. package/dist/extensions/isolated/metrics.d.ts +146 -0
  88. package/dist/extensions/isolated/metrics.js +304 -0
  89. package/dist/extensions/isolated/revision.d.ts +7 -1
  90. package/dist/extensions/isolated/revision.js +26 -5
  91. package/dist/extensions/isolated/rpc.d.ts +5 -0
  92. package/dist/extensions/isolated/rpc.js +7 -2
  93. package/dist/extensions/isolated/sandbox.d.ts +23 -0
  94. package/dist/extensions/isolated/sandbox.js +50 -0
  95. package/dist/extensions/isolated/status.d.ts +79 -0
  96. package/dist/extensions/isolated/status.js +216 -0
  97. package/dist/extensions/isolated/tier.d.ts +127 -2
  98. package/dist/extensions/isolated/tier.js +266 -7
  99. package/dist/extensions/isolated/usage.d.ts +134 -0
  100. package/dist/extensions/isolated/usage.js +322 -0
  101. package/dist/extensions/lifecycle.d.ts +42 -2
  102. package/dist/extensions/lifecycle.js +100 -4
  103. package/dist/extensions/org-config.js +11 -0
  104. package/dist/extensions/package.d.ts +14 -0
  105. package/dist/extensions/package.js +23 -0
  106. package/dist/extensions/permissions.controller.d.ts +35 -0
  107. package/dist/extensions/permissions.controller.js +98 -0
  108. package/dist/extensions/permissions.schemas.d.ts +288 -0
  109. package/dist/extensions/permissions.schemas.js +96 -0
  110. package/dist/extensions/permissions.service.d.ts +116 -0
  111. package/dist/extensions/permissions.service.js +428 -0
  112. package/dist/extensions/realm-retirement.d.ts +65 -0
  113. package/dist/extensions/realm-retirement.js +150 -0
  114. package/dist/extensions/revision-approvals.d.ts +58 -3
  115. package/dist/extensions/revision-approvals.js +135 -14
  116. package/dist/extensions/revision-review.d.ts +144 -0
  117. package/dist/extensions/revision-review.js +297 -0
  118. package/dist/extensions/revocation.js +3 -0
  119. package/dist/extensions/state.module.js +12 -0
  120. package/dist/git/run-end.d.ts +35 -7
  121. package/dist/git/run-end.js +87 -38
  122. package/dist/http/api.module.js +2 -0
  123. package/dist/identity/audit.d.ts +2 -1
  124. package/dist/identity/audit.js +4 -17
  125. package/dist/index.d.ts +4 -0
  126. package/dist/index.js +4 -0
  127. package/dist/infra/config/kernel-config.service.d.ts +6 -0
  128. package/dist/infra/config/kernel-config.service.js +21 -0
  129. package/dist/infra/outbox/registry.d.ts +13 -0
  130. package/dist/infra/outbox/registry.js +8 -0
  131. package/dist/lifecycle/kernel-lifecycle.d.ts +25 -1
  132. package/dist/lifecycle/kernel-lifecycle.js +73 -18
  133. package/dist/net/private-endpoint-preflight.d.ts +159 -0
  134. package/dist/net/private-endpoint-preflight.js +417 -0
  135. package/dist/net/private-endpoints.d.ts +68 -0
  136. package/dist/net/private-endpoints.js +164 -0
  137. package/dist/net/public-address.d.ts +14 -0
  138. package/dist/net/public-address.js +15 -1
  139. package/dist/net/safe-fetch.d.ts +2 -1
  140. package/dist/net/safe-fetch.js +10 -3
  141. package/dist/overrides.d.ts +4 -0
  142. package/dist/overrides.js +2 -0
  143. package/dist/packages/official-publisher.d.ts +26 -1
  144. package/dist/packages/official-publisher.js +48 -1
  145. package/dist/packages/provenance.d.ts +11 -0
  146. package/dist/packages/provenance.js +24 -0
  147. package/dist/platform/exclusions.js +4 -4
  148. package/dist/platform/ops/automations.ops.js +1 -1
  149. package/dist/platform/ops/catalog-admin.ops.js +25 -4
  150. package/dist/platform/ops/extension-permissions.ops.d.ts +11 -0
  151. package/dist/platform/ops/extension-permissions.ops.js +159 -0
  152. package/dist/platform/platform-ops.module.d.ts +2 -1
  153. package/dist/platform/platform-ops.module.js +2 -0
  154. package/dist/platform/route-schemas.js +2 -0
  155. package/dist/retention/purge-batch.js +10 -14
  156. package/dist/runtime/maintenance.d.ts +4 -2
  157. package/dist/runtime/maintenance.js +16 -3
  158. package/dist/runtime/run-finish.d.ts +3 -3
  159. package/dist/runtime/run-finish.js +7 -3
  160. package/dist/sandbox/permission-availability.d.ts +17 -2
  161. package/dist/sandbox/permission-availability.js +22 -1
  162. package/dist/sandbox/permission-facts.js +7 -1
  163. package/dist/tools/builtins/sandbox/common.js +2 -0
  164. package/dist/tools/pipeline.d.ts +2 -1
  165. package/dist/tools/pipeline.js +7 -2
  166. package/package.json +4 -3
  167. package/src/migrations/0238_extension_usage.sql +40 -0
  168. package/src/migrations/0239_extension_replica_isolation.sql +28 -0
@@ -145,6 +145,13 @@ export function isLinkLocalAddress(ip) {
145
145
  export function isLoopbackOrUnspecifiedAddress(ip) {
146
146
  return inTable(ip, loopbackOrUnspecified);
147
147
  }
148
+ const loopbackOnly = new BlockList();
149
+ loopbackOnly.addSubnet("127.0.0.0", 8, "ipv4");
150
+ loopbackOnly.addAddress("::1", "ipv6");
151
+ /** Loopback only (`127.0.0.0/8`, `::1`, embedded forms included), never unspecified. */
152
+ export function isLoopbackAddress(ip) {
153
+ return inTable(ip, loopbackOnly);
154
+ }
148
155
  /** A hostname normalized for comparison: lower case, no IPv6 brackets, no trailing dots. */
149
156
  export function normalizeHost(host) {
150
157
  let h = host.trim().toLowerCase();
@@ -312,12 +319,19 @@ export async function resolvePublic(host, policy, lookup = defaultLookup, origin
312
319
  throw new NetDeniedError("net.dns_failed", h, `Cannot resolve ${h}.`);
313
320
  }
314
321
  const ex = exemptions(h, policy, origin);
322
+ // a private endpoint alias exempts exactly its origin (see NetPolicy.privateEndpoint)
323
+ const alias = policy.privateEndpoint !== undefined && origin === policy.privateEndpoint.origin
324
+ ? policy.privateEndpoint
325
+ : undefined;
315
326
  // extension requests never reach the kernel's own host, whatever the exemptions
316
327
  const ownHost = (a) => policy.extension !== undefined &&
317
328
  !policy.allowInsecureLoopback &&
329
+ !(alias?.allowLoopback === true && isLoopbackAddress(a)) &&
318
330
  isLoopbackOrUnspecifiedAddress(a);
319
331
  const refused = (a) => isForbiddenAddress(a) &&
320
- (isLinkLocalAddress(a) || ownHost(a) || (!ex.all && !allowedBy(ex.cidrs, a)));
332
+ (isLinkLocalAddress(a) ||
333
+ ownHost(a) ||
334
+ (alias === undefined && !ex.all && !allowedBy(ex.cidrs, a)));
321
335
  if (addrs.some(refused)) {
322
336
  const hint = policy.extension?.privateHint ??
323
337
  "add the hostname to net.allowPrivateHosts to allow an internal host";
@@ -11,7 +11,8 @@ import { type LookupFn, type NetPolicy } from "./public-address.js";
11
11
  * - with `policy.proxy` (`net.httpsProxy`), an https URL whose host is not loopback and not in
12
12
  * `noProxy` tunnels through the proxy (`proxy.ts`) instead: the host is not resolved locally
13
13
  * (the proxy resolves it and owns SSRF protection for the resolved address), but an IP-literal
14
- * host is still checked against the private ranges and `allowPrivateHosts`;
14
+ * host is still checked against the private ranges and `allowPrivateHosts`; an origin a
15
+ * `net.privateEndpoints` alias admitted (`policy.privateEndpoint`) never uses the proxy;
15
16
  * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`,
16
17
  * or, with `redirects: "return"`, returned to the caller as is (its body unread);
17
18
  * - with `maxBytes`, a declared or streamed body over the limit is {@link NetBodyTooLargeError}.
@@ -13,7 +13,8 @@ import { hostEntryExempts, isLoopbackHost, NetDeniedError, normalizeHost, resolv
13
13
  * - with `policy.proxy` (`net.httpsProxy`), an https URL whose host is not loopback and not in
14
14
  * `noProxy` tunnels through the proxy (`proxy.ts`) instead: the host is not resolved locally
15
15
  * (the proxy resolves it and owns SSRF protection for the resolved address), but an IP-literal
16
- * host is still checked against the private ranges and `allowPrivateHosts`;
16
+ * host is still checked against the private ranges and `allowPrivateHosts`; an origin a
17
+ * `net.privateEndpoints` alias admitted (`policy.privateEndpoint`) never uses the proxy;
17
18
  * - redirects are never followed: a 3xx (other than 304) is {@link NetDeniedError} `net.redirect`,
18
19
  * or, with `redirects: "return"`, returned to the caller as is (its body unread);
19
20
  * - with `maxBytes`, a declared or streamed body over the limit is {@link NetBodyTooLargeError}.
@@ -154,8 +155,11 @@ async function safeFetchOnce(url, init, policy, opts) {
154
155
  throw new NetDeniedError("net.insecure_url", "", "The URL is not valid.");
155
156
  }
156
157
  const host = normalizeHost(target.hostname);
158
+ // a net.privateEndpoints alias admitted this exact origin (ctx.net): direct, http if configured
159
+ const aliased = policy.privateEndpoint?.origin === target.origin;
157
160
  const insecureOk = target.protocol === "http:" &&
158
- ((policy.allowInsecureLoopback && isLoopbackHost(host)) ||
161
+ (aliased ||
162
+ (policy.allowInsecureLoopback && isLoopbackHost(host)) ||
159
163
  policy.trustedOrigins.some((o) => originOf(o) === target.origin));
160
164
  if (target.protocol !== "https:" && !insecureOk) {
161
165
  // an extension request to a host the org allows only as a host entry (https only): name the
@@ -164,12 +168,15 @@ async function safeFetchOnce(url, init, policy, opts) {
164
168
  target.protocol === "http:" &&
165
169
  hostEntryExempts(host, policy)
166
170
  ? ` ${host} is allowed for the organization over https only; to allow plain http, ask a super admin to allow the origin ${target.origin}.`
167
- : "";
171
+ : policy.extension?.insecureHint !== undefined && target.protocol === "http:"
172
+ ? ` If it is an internal endpoint: ${policy.extension.insecureHint}.`
173
+ : "";
168
174
  throw new NetDeniedError("net.insecure_url", host, `The URL must use https (${host}).${hint}`);
169
175
  }
170
176
  const proxy = policy.proxy;
171
177
  const proxied = proxy !== undefined &&
172
178
  target.protocol === "https:" &&
179
+ !aliased &&
173
180
  !isLoopbackHost(host) &&
174
181
  !bypassesProxy(host, proxy.noProxy);
175
182
  // getaddrinfo cannot be cancelled: stop waiting for it when the caller gives up
@@ -19,6 +19,7 @@ import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
19
19
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
20
20
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
21
21
  import type { KernelQueueName } from "./infra/queue/queue-names.js";
22
+ import { BROKERED_ENDPOINT_PINS_SEAM, type BrokeredEndpointPin } from "./net/private-endpoint-preflight.js";
22
23
  import { PUSH_SEND_TIMEOUT_MS } from "./push/delivery.js";
23
24
  import { PROJECT_KNOWLEDGE_TIMEOUT, type ProjectKnowledgeTimeouts } from "./runtime/project/knowledge.service.js";
24
25
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
@@ -69,6 +70,8 @@ import { EMBED_TOKEN_CLOCK } from "./ui/embed-token.js";
69
70
  * - `PLUGIN_PUBLIC_WRITE_LIMIT`: a lower limit for unsafe methods on `public` extension routes;
70
71
  * - `EXTENSION_NET_SEAMS`: `ctx.net`'s DNS and dispatcher (a hostname resolving to a private address
71
72
  * served by a loopback fake);
73
+ * - `BROKERED_ENDPOINT_PINS_SEAM`: the brokered pins the bootstrap's private endpoint preflight
74
+ * checks (a fixture plugin standing in for object-store-s3's ctx.net build);
72
75
  * - `APP_INTERCEPTOR`: one more global interceptor (a probe of the matched routes);
73
76
  * - `TOOL_WATCH_TIMINGS`: shorter watched-wait poll timings (interval, watcher timeout);
74
77
  * - `PERMISSION_AUTO_GRANT_HOOKS`: a barrier after a Full access auto-grant's precheck (two
@@ -105,6 +108,7 @@ interface KernelSeams {
105
108
  [BACKGROUND_STOP_ATTEMPT_MS]: () => number;
106
109
  [PLUGIN_PUBLIC_WRITE_LIMIT]: number;
107
110
  [EXTENSION_NET_SEAMS]: ExtensionNetSeams;
111
+ [BROKERED_ENDPOINT_PINS_SEAM]: readonly BrokeredEndpointPin[];
108
112
  [APP_INTERCEPTOR]: NestInterceptor;
109
113
  [PERMISSION_AUTO_GRANT_HOOKS]: PermissionAutoGrantHooks;
110
114
  [TOOL_WATCH_TIMINGS]: Partial<ToolWatchTimings>;
package/dist/overrides.js CHANGED
@@ -16,6 +16,7 @@ import { PLUGIN_PUBLIC_WRITE_LIMIT } from "./http/plugin-route-access.js";
16
16
  import { OUTBOX_DISPATCH_FAILS } from "./infra/outbox/outbox.dispatcher.js";
17
17
  import { OUTBOX_FAST_PATH_SETTLED } from "./infra/outbox/outbox.module.js";
18
18
  import { PRESENCE_INTERVAL_MS } from "./infra/presence/replica-presence.js";
19
+ import { BROKERED_ENDPOINT_PINS_SEAM, } from "./net/private-endpoint-preflight.js";
19
20
  import { PUSH_SEND_TIMEOUT_MS } from "./push/delivery.js";
20
21
  import { PROJECT_KNOWLEDGE_TIMEOUT, } from "./runtime/project/knowledge.service.js";
21
22
  import { LIST_MODELS_TIMEOUT } from "./runtime/providers.js";
@@ -59,6 +60,7 @@ const SEAM_TOKENS = [
59
60
  BACKGROUND_STOP_ATTEMPT_MS,
60
61
  PLUGIN_PUBLIC_WRITE_LIMIT,
61
62
  EXTENSION_NET_SEAMS,
63
+ BROKERED_ENDPOINT_PINS_SEAM,
62
64
  APP_INTERCEPTOR,
63
65
  PERMISSION_AUTO_GRANT_HOOKS,
64
66
  TOOL_WATCH_TIMINGS,
@@ -1,5 +1,5 @@
1
1
  import type { NpmFetchConfig } from "./npm.js";
2
- import { type Provenance } from "./provenance.js";
2
+ import { type Provenance, type ProvenanceResult } from "./provenance.js";
3
3
  declare const POLICY_VERSION = 1;
4
4
  export interface OfficialNpmRevision {
5
5
  name: string;
@@ -53,6 +53,31 @@ export declare function verifyPublisher(body: unknown, revision: OfficialNpmRevi
53
53
  export declare function officialPublisherProblem(verified: VerifiedPublisher): string | undefined;
54
54
  /** Checks both signatures, transparency evidence and publisher identity with the bundled roots. */
55
55
  export declare function verifyOfficialPublisher(body: unknown, revision: OfficialNpmRevision): OfficialPublisherProof;
56
+ /**
57
+ * The official release workflow's certificate claims, without the per-build commit: what an
58
+ * official proof ({@link verifyOfficialPublisher}) established, for normalizing its publisher
59
+ * identity without the attestation bundle.
60
+ */
61
+ export declare const OFFICIAL_PUBLISHER_CERTIFICATE: Readonly<Omit<PublisherCertificate, "commit">>;
62
+ /** The result of {@link fetchPublisherAttestation}: verified, or why not. */
63
+ export type PublisherAttestation = {
64
+ ok: true;
65
+ verified: VerifiedPublisher;
66
+ } | {
67
+ ok: false;
68
+ reason: string;
69
+ transient: boolean;
70
+ };
71
+ /**
72
+ * One fetch of a revision's attestations for both its review: the display-only provenance and
73
+ * the publisher verified as any GitHub Actions publisher ({@link verifyPublisher}). Never throws:
74
+ * a missing, unreadable or unverifiable attestation is `ok: false` (transient for a network or
75
+ * registry hiccup). Integrity was checked by the caller.
76
+ */
77
+ export declare function fetchAttestationEvidence(cfg: NpmFetchConfig, revision: OfficialNpmRevision, signal?: AbortSignal): Promise<{
78
+ provenance: ProvenanceResult;
79
+ attestation: PublisherAttestation;
80
+ }>;
56
81
  /** Uses the same bounded registry client as the review's display-only provenance. */
57
82
  export declare function fetchOfficialPublisher(cfg: NpmFetchConfig, revision: OfficialNpmRevision, signal?: AbortSignal): Promise<OfficialPublisherProof>;
58
83
  /** A failed publisher check; `transient` failures (network, timeout, 5xx) may pass on a retry soon. */
@@ -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, isTransientAttestationsFailure, PROVENANCE_TIMEOUT_MS, SLSA_PROVENANCE_V1, sha512Hex, } from "./provenance.js";
8
+ import { fetchNpmAttestations, fetchProvenanceWithBody, 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";
@@ -222,6 +222,53 @@ export function verifyOfficialPublisher(body, revision) {
222
222
  policyVersion: POLICY_VERSION,
223
223
  };
224
224
  }
225
+ /**
226
+ * The official release workflow's certificate claims, without the per-build commit: what an
227
+ * official proof ({@link verifyOfficialPublisher}) established, for normalizing its publisher
228
+ * identity without the attestation bundle.
229
+ */
230
+ export const OFFICIAL_PUBLISHER_CERTIFICATE = Object.freeze({
231
+ issuer: GITHUB_ISSUER,
232
+ identity: WORKFLOW_IDENTITY,
233
+ repository: REPOSITORY,
234
+ repositoryId: REPOSITORY_ID,
235
+ ownerId: OWNER_ID,
236
+ workflow: WORKFLOW,
237
+ ref: MAIN_REF,
238
+ });
239
+ /**
240
+ * One fetch of a revision's attestations for both its review: the display-only provenance and
241
+ * the publisher verified as any GitHub Actions publisher ({@link verifyPublisher}). Never throws:
242
+ * a missing, unreadable or unverifiable attestation is `ok: false` (transient for a network or
243
+ * registry hiccup). Integrity was checked by the caller.
244
+ */
245
+ export async function fetchAttestationEvidence(cfg, revision, signal) {
246
+ const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
247
+ const got = await fetchProvenanceWithBody(cfg, revision.name, revision.version, signal ? AbortSignal.any([signal, timeout]) : timeout, { integrity: revision.integrity });
248
+ if (got.body === undefined) {
249
+ const reason = got.provenance.checked ? "no attestations" : got.provenance.reason;
250
+ return {
251
+ provenance: got.provenance,
252
+ attestation: { ok: false, reason, transient: got.transient === true },
253
+ };
254
+ }
255
+ try {
256
+ return {
257
+ provenance: got.provenance,
258
+ attestation: { ok: true, verified: verifyPublisher(got.body, revision) },
259
+ };
260
+ }
261
+ catch (e) {
262
+ return {
263
+ provenance: got.provenance,
264
+ attestation: {
265
+ ok: false,
266
+ reason: e instanceof Error ? e.message : String(e),
267
+ transient: false,
268
+ },
269
+ };
270
+ }
271
+ }
225
272
  /** Uses the same bounded registry client as the review's display-only provenance. */
226
273
  export async function fetchOfficialPublisher(cfg, revision, signal) {
227
274
  const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
@@ -51,6 +51,17 @@ export declare function sha512Hex(integrity: string): string | undefined;
51
51
  export declare function fetchProvenance(cfg: NpmFetchConfig, name: string, version: string, signal: AbortSignal, opts?: {
52
52
  integrity?: string;
53
53
  }): Promise<ProvenanceResult>;
54
+ /**
55
+ * {@link fetchProvenance} that also returns the attestations answer it parsed, for the caller to
56
+ * verify the publisher from the same fetch. Never throws.
57
+ */
58
+ export declare function fetchProvenanceWithBody(cfg: NpmFetchConfig, name: string, version: string, signal: AbortSignal, opts?: {
59
+ integrity?: string;
60
+ }): Promise<{
61
+ provenance: ProvenanceResult;
62
+ body?: unknown;
63
+ transient?: boolean;
64
+ }>;
54
65
  /** Fetches bounded attestation evidence without accepting it as publisher proof. */
55
66
  export declare function fetchNpmAttestations(cfg: NpmFetchConfig, name: string, version: string, signal: AbortSignal): Promise<unknown>;
56
67
  /**
@@ -60,6 +60,30 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
60
60
  return notChecked(e instanceof NpmAttestationsError ? e.message : `cannot read the attestations: ${errMsg(e)}`);
61
61
  }
62
62
  }
63
+ /**
64
+ * {@link fetchProvenance} that also returns the attestations answer it parsed, for the caller to
65
+ * verify the publisher from the same fetch. Never throws.
66
+ */
67
+ export async function fetchProvenanceWithBody(cfg, name, version, signal, opts = {}) {
68
+ let body;
69
+ try {
70
+ body = await fetchNpmAttestations(cfg, name, version, signal);
71
+ }
72
+ catch (e) {
73
+ return {
74
+ provenance: notChecked(e instanceof NpmAttestationsError
75
+ ? e.message
76
+ : `cannot read the attestations: ${errMsg(e)}`),
77
+ transient: isTransientAttestationsFailure(e),
78
+ };
79
+ }
80
+ try {
81
+ return { provenance: parseAttestations(body, opts.integrity), body };
82
+ }
83
+ catch (e) {
84
+ return { provenance: notChecked(`cannot read the attestations: ${errMsg(e)}`), body };
85
+ }
86
+ }
63
87
  /** Fetches bounded attestation evidence without accepting it as publisher proof. */
64
88
  export async function fetchNpmAttestations(cfg, name, version, signal) {
65
89
  if (!NPM_NAME_RE.test(name) || name.length > 214 || !SEMVER_RE.test(version)) {
@@ -61,9 +61,9 @@ export const PLATFORM_EXCLUSIONS = [
61
61
  reason: "Delivers other orgs' config copies of an extension (which differ, which secrets each holds) to the super admin's browser; an agent works in its own org",
62
62
  },
63
63
  {
64
- route: "POST /api/v1/admin/extensions/:name/approve",
64
+ route: "POST /api/v1/admin/extension-permissions/:name/approve",
65
65
  category: "human-only",
66
- reason: "Approves an extension's permission manifest, a trust decision",
66
+ reason: "Human security consent: a person approves an extension revision's permission review, full access included with one acknowledgement per realm; refused unattended",
67
67
  },
68
68
  {
69
69
  route: "POST /api/v1/admin/extensions/:name/install",
@@ -145,12 +145,12 @@ export const PLATFORM_EXCLUSIONS = [
145
145
  {
146
146
  route: "POST /api/v1/admin/catalog/imports/:stagingId/confirm",
147
147
  category: "human-only",
148
- reason: "Confirms an import review, an approval decision by the super admin",
148
+ reason: "Human security consent: confirms an import review and its revision's permissions, full access with one acknowledgement per realm",
149
149
  },
150
150
  {
151
151
  route: "POST /api/v1/admin/catalog/imports/:stagingId/update",
152
152
  category: "human-only",
153
- reason: "Confirms an import review together with the platform update it applies, an approval decision by the super admin",
153
+ reason: "Human security consent: confirms an import review and its revision's permissions together with the platform update it applies, full access with one acknowledgement per realm",
154
154
  },
155
155
  {
156
156
  route: "GET /api/v1/admin/catalog/items/:id/icon",
@@ -488,7 +488,7 @@ let AutomationsOperations = class AutomationsOperations {
488
488
  }),
489
489
  defineOperation({
490
490
  id: "automations.runs",
491
- description: "A task's run history, latest first (default 50, at most 200): each tick with its status, skip reason, error, conversation and the tools refused for lack of an approval. Takes the id from automations.list.",
491
+ description: "A task's run history, latest first (default 50, at most 200): each tick with its status, skip reason, error, conversation and the tools refused for lack of an approval (automations.grants-add can approve those). An entry `review:<command|write|read>` is a call the command review held: it always needs a person and is never grantable. Takes the id from automations.list.",
492
492
  input: RunsQuery.extend({ automationId: Id }).strict(),
493
493
  example: { automationId: EXAMPLE_ID },
494
494
  authz: { orgAction: "automations.use" },
@@ -469,7 +469,7 @@ let CatalogAdminOperations = class CatalogAdminOperations {
469
469
  }),
470
470
  defineOperation({
471
471
  id: "plugins.set-scope",
472
- description: "Change where a platform plugin is on (super admin), for every org at once: pass the scope (and orgs for named) and the scopeHash plugins.scope-preview returned for that same target. Orgs that lose it have it removed by the scope sync; a preview that is out of date is refused.",
472
+ description: "Change where a platform plugin is on (super admin), for every org at once: pass the scope (and orgs for named) and the scopeHash plugins.scope-preview returned for that same target. Orgs that lose it have it removed by the scope sync; a preview that is out of date is refused. This operation only narrows: a scope reaching orgs the current one does not is not applied (applied: false) and you widen it yourself in the admin console, where it opens.",
473
473
  input: z.object({ itemId: ItemId, ...CatalogScopeBody.shape }).strict(),
474
474
  example: {
475
475
  itemId: "3f1c2a9e-5b7d-4e21-9c0a-1d2e3f4a5b6c",
@@ -550,10 +550,31 @@ let CatalogAdminOperations = class CatalogAdminOperations {
550
550
  scope: input.scope,
551
551
  ...(input.orgs !== undefined && { orgs: input.orgs }),
552
552
  };
553
- return {
554
- item: await this.withoutPluginNames(input.itemId, target, () => this.scope.setScope(ctx.actorAccountId, input.itemId, { ...target, scopeHash: input.scopeHash }, { auditDetail: viaAgent("plugins.set-scope", ctx) })),
555
- };
553
+ try {
554
+ return {
555
+ applied: true,
556
+ item: await this.withoutPluginNames(input.itemId, target, () => this.scope.setScope(ctx.actorAccountId, input.itemId, { ...target, scopeHash: input.scopeHash },
557
+ // the Platform tool only narrows; widening is the person's, on the web
558
+ { auditDetail: viaAgent("plugins.set-scope", ctx), onlyNarrows: true })),
559
+ };
560
+ }
561
+ catch (e) {
562
+ if (e instanceof ApiError && e.code === "plugin.scope_widening_not_allowed") {
563
+ return { applied: false, code: e.code, message: e.message };
564
+ }
565
+ throw e;
566
+ }
556
567
  },
568
+ handoff: (input, result) => result?.applied === false
569
+ ? {
570
+ kind: "handoff",
571
+ title: {
572
+ zh: "在管理后台扩大插件范围",
573
+ en: "Widen the plugin's scope in the admin console",
574
+ },
575
+ target: { type: "link", url: `/admin/plugins/${encodeURIComponent(input.itemId)}` },
576
+ }
577
+ : null,
557
578
  }),
558
579
  defineOperation({
559
580
  id: "plugins.set-disabled",
@@ -0,0 +1,11 @@
1
+ import { type OnModuleInit } from "@nestjs/common";
2
+ import { ExtensionPermissions } from "../../extensions/permissions.service.js";
3
+ import { KernelDb } from "../../infra/database/kernel-db.js";
4
+ import { PlatformOperations } from "../registry.js";
5
+ export declare class ExtensionPermissionOperations implements OnModuleInit {
6
+ private readonly registry;
7
+ private readonly permissions;
8
+ private readonly kdb;
9
+ constructor(registry: PlatformOperations, permissions: ExtensionPermissions, kdb: KernelDb);
10
+ onModuleInit(): void;
11
+ }
@@ -0,0 +1,159 @@
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 { z } from "zod";
12
+ import { PermissionNamePathParams, PermissionRevokeBody, } from "../../extensions/permissions.schemas.js";
13
+ import { ExtensionPermissions, permissionConfirmUrl, } from "../../extensions/permissions.service.js";
14
+ import { KernelDb } from "../../infra/database/kernel-db.js";
15
+ import { defineOperation } from "../operation.js";
16
+ import { PlatformOperations } from "../registry.js";
17
+ import { assertExtensionNotOtherOrgs, otherOrgExtensions } from "./other-orgs.js";
18
+ /**
19
+ * Platform operations of the extension permission routes (plan task 1.4a) and the isolation
20
+ * status (1.4j). Reading, reviewing and revoking only narrow or show; approving is a human
21
+ * security consent: no operation, the review hands off to the web confirm page.
22
+ */
23
+ const NameInput = PermissionNamePathParams.strict();
24
+ const EXAMPLE = { name: "model-anthropic" };
25
+ let ExtensionPermissionOperations = class ExtensionPermissionOperations {
26
+ registry;
27
+ permissions;
28
+ kdb;
29
+ constructor(registry, permissions, kdb) {
30
+ this.registry = registry;
31
+ this.permissions = permissions;
32
+ this.kdb = kdb;
33
+ }
34
+ onModuleInit() {
35
+ this.registry.register([
36
+ defineOperation({
37
+ id: "extensions.permission-inventory",
38
+ description: "List every installed extension's permission state on the platform (super admin): its revision, the shadow decision (granted, partially revoked, missing a grant, waiting for an acknowledged review, needs republishing with purposes...), its revision grant with the serving and withdrawn keys and full-access realms, the approved and candidate revisions, and where each replica would run it. Other orgs' own extensions are only counted.",
39
+ input: z.object({}).strict(),
40
+ example: {},
41
+ authz: { superAdmin: true },
42
+ mirrors: ["GET /api/v1/admin/extension-permissions"],
43
+ confirm: "read",
44
+ run: async (_input, ctx) => {
45
+ const [inventory, theirs] = await Promise.all([
46
+ this.permissions.inventory(),
47
+ otherOrgExtensions(this.kdb.db, ctx.orgId),
48
+ ]);
49
+ return {
50
+ ...inventory,
51
+ entries: inventory.entries.filter((e) => !theirs.has(e.plugin)),
52
+ otherOrgExtensions: inventory.entries.filter((e) => theirs.has(e.plugin)).length,
53
+ };
54
+ },
55
+ }),
56
+ defineOperation({
57
+ id: "extensions.permission-review",
58
+ description: "Read the permission review of an installed extension's current revision (super admin): every permission with its risk and purpose, what changed since its approval, where it runs and which realms need full access, the publisher evidence, and whether approving re-consents or continues the approved grant. Approving is done by a person on the web confirm page this hands off to; this operation never approves.",
59
+ input: NameInput,
60
+ example: EXAMPLE,
61
+ authz: { superAdmin: true },
62
+ mirrors: ["GET /api/v1/admin/extension-permissions/:name/review"],
63
+ confirm: "read",
64
+ errors: [
65
+ {
66
+ code: "extension.not_found",
67
+ next: "Check the extension name with extensions.permission-inventory.",
68
+ },
69
+ {
70
+ code: "extension.permission_review_unavailable",
71
+ next: "Retry shortly; if it persists, the admin console shows why the package cannot be read.",
72
+ },
73
+ ],
74
+ run: async (input, ctx) => {
75
+ await assertExtensionNotOtherOrgs(this.kdb.db, input.name, ctx.orgId);
76
+ return this.permissions.review(input.name);
77
+ },
78
+ handoff: (input, result) => {
79
+ const review = result;
80
+ if (!review)
81
+ return null;
82
+ return {
83
+ kind: "handoff",
84
+ title: {
85
+ zh: "审阅并确认扩展权限",
86
+ en: "Review and confirm the extension's permissions",
87
+ },
88
+ target: { type: "link", url: permissionConfirmUrl(input.name) },
89
+ };
90
+ },
91
+ }),
92
+ defineOperation({
93
+ id: "extensions.revoke-permissions",
94
+ description: "Revoke permissions of an installed extension revision's grant on the platform (super admin): listed keys (a realm's full access is its execution.full-access:<realm> key) or the whole grant. Revoking only narrows; restoring needs a new review by a person. Until the enforcing cutover the result says enforced: false and the extension keeps running as before: disable it (extensions.platform-disable) to stop it now.",
95
+ input: z.object({ name: NameInput.shape.name, ...PermissionRevokeBody.shape }).strict(),
96
+ example: {
97
+ name: "model-anthropic",
98
+ revision: { version: "1.0.0", sha512: "0".repeat(128) },
99
+ keys: ["execution.full-access:browser"],
100
+ },
101
+ authz: { superAdmin: true },
102
+ mirrors: ["POST /api/v1/admin/extension-permissions/:name/revoke"],
103
+ confirm: "platform",
104
+ summary: (i) => ({
105
+ zh: i.keys
106
+ ? `撤回扩展 ${i.name} ${i.revision.version} 的权限:${i.keys.join("、")}`
107
+ : `撤回扩展 ${i.name} ${i.revision.version} 的全部授权`,
108
+ en: i.keys
109
+ ? `Revoke ${i.keys.join(", ")} from extension ${i.name} ${i.revision.version}`
110
+ : `Revoke the whole grant of extension ${i.name} ${i.revision.version}`,
111
+ }),
112
+ errors: [
113
+ {
114
+ code: "extension.permission_keys_unknown",
115
+ next: "Read extensions.permission-inventory for the revision's serving keys.",
116
+ },
117
+ {
118
+ code: "extension.permission_grant_not_found",
119
+ next: "The revision has no live grant; read extensions.permission-inventory.",
120
+ },
121
+ ],
122
+ run: async ({ name, ...body }, ctx) => {
123
+ await assertExtensionNotOtherOrgs(this.kdb.db, name, ctx.orgId);
124
+ return this.permissions.revoke(ctx.actorAccountId, name, body);
125
+ },
126
+ }),
127
+ defineOperation({
128
+ id: "extensions.isolation-status",
129
+ description: "Read the platform's extension isolation status (super admin): not configured, or each replica's isolation supervisor checks (Engine guard reachable, Engine runtime, runtime image, PostgreSQL socket) with the first failure, the plugins a failing supervisor pauses, and the private endpoints isolated plugins cannot reach. Not configured, nothing is probed.",
130
+ input: z.object({}).strict(),
131
+ example: {},
132
+ authz: { superAdmin: true },
133
+ mirrors: ["GET /api/v1/admin/extension-isolation"],
134
+ confirm: "read",
135
+ run: async (_input, ctx) => {
136
+ const [status, theirs] = await Promise.all([
137
+ this.permissions.isolationStatus(),
138
+ otherOrgExtensions(this.kdb.db, ctx.orgId),
139
+ ]);
140
+ if (status.state === "not_configured")
141
+ return status;
142
+ // another org's own extensions are never named in this org's conversation
143
+ return {
144
+ ...status,
145
+ paused: status.paused.filter((p) => !theirs.has(p.plugin)),
146
+ privateEndpointGaps: status.privateEndpointGaps.filter((g) => !theirs.has(g.plugin)),
147
+ };
148
+ },
149
+ }),
150
+ ]);
151
+ }
152
+ };
153
+ ExtensionPermissionOperations = __decorate([
154
+ Injectable(),
155
+ __param(0, Inject(PlatformOperations)),
156
+ __param(1, Inject(ExtensionPermissions)),
157
+ __param(2, Inject(KernelDb))
158
+ ], ExtensionPermissionOperations);
159
+ export { ExtensionPermissionOperations };
@@ -14,6 +14,7 @@ import { ConnectorsOperations } from "./ops/connectors.ops.js";
14
14
  import { ConversationsOperations } from "./ops/conversations.ops.js";
15
15
  import { DevicesOperations } from "./ops/devices.ops.js";
16
16
  import { EvalsOperations } from "./ops/evals.ops.js";
17
+ import { ExtensionPermissionOperations } from "./ops/extension-permissions.ops.js";
17
18
  import { ExtensionsOperations } from "./ops/extensions.ops.js";
18
19
  import { ExtensionsAdminOperations } from "./ops/extensions-admin.ops.js";
19
20
  import { FilesOperations } from "./ops/files.ops.js";
@@ -38,7 +39,7 @@ import { UiOperations } from "./ops/ui.ops.js";
38
39
  * One provider per domain, each taking `PlatformOperations` as its first constructor argument:
39
40
  * the parity test in `tools/checks` builds the operations from it without a Nest app.
40
41
  */
41
- export declare const PLATFORM_OPERATION_PROVIDERS: readonly [typeof PlatformOperationsProvider, typeof SkillsOperations, typeof AgentsOperations, typeof AgentTemplatesOperations, typeof PluginsOperations, typeof MarketplacesOperations, typeof RequestsOperations, typeof ConnectorsOperations, typeof ExtensionsOperations, typeof ConversationsOperations, typeof ComponentsOperations, typeof AccountsOperations, typeof OrgsOperations, typeof AdminOperations, typeof CatalogAdminOperations, typeof OrgPluginsOperations, typeof ExtensionsAdminOperations, typeof ModelsOperations, typeof InboxOperations, typeof ApprovalsOperations, typeof ChannelsOperations, typeof OrgSettingsOperations, typeof EvalsOperations, typeof BackgroundOperations, typeof PreviewersOperations, typeof DevicesOperations, typeof AgentSkillsOperations, typeof ThemesOperations, typeof SetupOperations, typeof UiOperations, typeof AdminItemsOperations, typeof AutomationsOperations, typeof OutboxOperations, typeof SharesOperations, typeof PlatformIconsOperations, typeof FilesOperations];
42
+ export declare const PLATFORM_OPERATION_PROVIDERS: readonly [typeof PlatformOperationsProvider, typeof SkillsOperations, typeof AgentsOperations, typeof AgentTemplatesOperations, typeof PluginsOperations, typeof MarketplacesOperations, typeof RequestsOperations, typeof ConnectorsOperations, typeof ExtensionsOperations, typeof ConversationsOperations, typeof ComponentsOperations, typeof AccountsOperations, typeof OrgsOperations, typeof AdminOperations, typeof CatalogAdminOperations, typeof OrgPluginsOperations, typeof ExtensionsAdminOperations, typeof ExtensionPermissionOperations, typeof ModelsOperations, typeof InboxOperations, typeof ApprovalsOperations, typeof ChannelsOperations, typeof OrgSettingsOperations, typeof EvalsOperations, typeof BackgroundOperations, typeof PreviewersOperations, typeof DevicesOperations, typeof AgentSkillsOperations, typeof ThemesOperations, typeof SetupOperations, typeof UiOperations, typeof AdminItemsOperations, typeof AutomationsOperations, typeof OutboxOperations, typeof SharesOperations, typeof PlatformIconsOperations, typeof FilesOperations];
42
43
  /**
43
44
  * The `Platform` tool's operations (ruling P2): one provider per domain, each registering its
44
45
  * operations into `PlatformOperations` from `onModuleInit`. It imports the domain modules, which
@@ -45,6 +45,7 @@ import { ConnectorsOperations } from "./ops/connectors.ops.js";
45
45
  import { ConversationsOperations } from "./ops/conversations.ops.js";
46
46
  import { DevicesOperations } from "./ops/devices.ops.js";
47
47
  import { EvalsOperations } from "./ops/evals.ops.js";
48
+ import { ExtensionPermissionOperations } from "./ops/extension-permissions.ops.js";
48
49
  import { ExtensionsOperations } from "./ops/extensions.ops.js";
49
50
  import { ExtensionsAdminOperations } from "./ops/extensions-admin.ops.js";
50
51
  import { FilesOperations } from "./ops/files.ops.js";
@@ -90,6 +91,7 @@ export const PLATFORM_OPERATION_PROVIDERS = [
90
91
  CatalogAdminOperations,
91
92
  OrgPluginsOperations,
92
93
  ExtensionsAdminOperations,
94
+ ExtensionPermissionOperations,
93
95
  ModelsOperations,
94
96
  // Task 9: inbox and pending reads
95
97
  InboxOperations,
@@ -21,6 +21,7 @@ import { CHANNEL_ROUTES } from "../channels/channels.schemas.js";
21
21
  import { CONVERSATION_ROUTES } from "../conversations/conversations.schemas.js";
22
22
  import { DEVICE_ROUTES } from "../devices/devices.schemas.js";
23
23
  import { EVAL_ROUTES } from "../evals/evals.schemas.js";
24
+ import { PERMISSION_ROUTES } from "../extensions/permissions.schemas.js";
24
25
  import { EXTENSION_POINT_ROUTES } from "../extensions/point-defaults.schemas.js";
25
26
  import { FILE_ROUTES } from "../files/library.schemas.js";
26
27
  import { FILE_PREVIEWER_ROUTES } from "../files/previewers.schemas.js";
@@ -61,6 +62,7 @@ export const ROUTE_SCHEMAS = [
61
62
  ...ORG_ROUTES,
62
63
  // Task 8: admin catalog, extensions, marketplaces, models, org uploads
63
64
  ...ADMIN_EXTENSION_ROUTES,
65
+ ...PERMISSION_ROUTES,
64
66
  ...ORG_PLUGIN_UPLOAD_ROUTES,
65
67
  ...EXTENSION_POINT_ROUTES,
66
68
  ...ORG_MODEL_ROUTES,
@@ -26,14 +26,12 @@ async function leafOf(db, { orgId, conversationId }) {
26
26
  return rows[0];
27
27
  }
28
28
  function eventBatch(db, orgId, leaf) {
29
- // Use the parent and (conversation_id, seq) throughout the event ownership expansion.
30
29
  return db
31
- .selectFrom("conversation_events as e")
32
- .innerJoin("conversations as c", "c.id", "e.conversation_id")
33
- .select(["e.seq", "e.type", "e.created_at"])
34
- .where("e.conversation_id", "=", leaf)
35
- .where("c.org_id", "=", orgId)
36
- .orderBy("e.seq")
30
+ .selectFrom("conversation_events")
31
+ .select(["seq", "type", "created_at"])
32
+ .where("conversation_id", "=", leaf)
33
+ .where("org_id", "=", orgId)
34
+ .orderBy("seq")
37
35
  .limit(PURGE_BATCH_SIZE)
38
36
  .execute();
39
37
  }
@@ -111,13 +109,11 @@ async function obligationsCleared(db, orgId, id) {
111
109
  }
112
110
  async function removeEventBatch(db, orgId, leaf, events) {
113
111
  const removed = await db
114
- .deleteFrom("conversation_events as e")
115
- .using("conversations as c")
116
- .whereRef("c.id", "=", "e.conversation_id")
117
- .where("c.org_id", "=", orgId)
118
- .where("e.conversation_id", "=", leaf.id)
119
- .where("e.seq", "in", events.map((e) => e.seq))
120
- .returning(["e.created_at", "e.type"])
112
+ .deleteFrom("conversation_events")
113
+ .where("org_id", "=", orgId)
114
+ .where("conversation_id", "=", leaf.id)
115
+ .where("seq", "in", events.map((e) => e.seq))
116
+ .returning(["created_at", "type"])
121
117
  .execute();
122
118
  if (leaf.kind === "eval")
123
119
  return;