@capybara-hq/kernel 0.1.0-rc.143 → 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.
Files changed (134) hide show
  1. package/dist/admin/admin-agents.controller.d.ts +3 -5
  2. package/dist/admin/admin-agents.controller.js +1 -1
  3. package/dist/admin/admin-connectors.controller.d.ts +3 -5
  4. package/dist/admin/admin-connectors.controller.js +1 -1
  5. package/dist/admin/admin-items.schemas.d.ts +6 -6
  6. package/dist/admin/admin-items.schemas.js +5 -9
  7. package/dist/admin/admin.controller.d.ts +18 -12
  8. package/dist/admin/admin.controller.js +29 -15
  9. package/dist/admin/admin.schemas.d.ts +12 -3
  10. package/dist/admin/admin.schemas.js +17 -6
  11. package/dist/agents/admin-agents.d.ts +30 -11
  12. package/dist/agents/admin-agents.js +51 -16
  13. package/dist/automations/automations.controller.d.ts +9 -5
  14. package/dist/automations/automations.controller.js +21 -4
  15. package/dist/automations/automations.schemas.d.ts +19 -0
  16. package/dist/automations/automations.schemas.js +9 -0
  17. package/dist/automations/automations.service.d.ts +25 -8
  18. package/dist/automations/automations.service.js +40 -34
  19. package/dist/automations/store.d.ts +17 -0
  20. package/dist/automations/store.js +35 -0
  21. package/dist/catalog/admin-catalog.controller.d.ts +64 -2
  22. package/dist/catalog/admin-catalog.controller.js +17 -0
  23. package/dist/catalog/cli.js +2 -2
  24. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  25. package/dist/catalog/marketplace-fetch.js +7 -2
  26. package/dist/catalog/marketplaces.service.d.ts +1 -1
  27. package/dist/catalog/plugin-package.js +2 -1
  28. package/dist/client/client-access.service.js +29 -1
  29. package/dist/config/schema.d.ts +9 -0
  30. package/dist/config/schema.js +26 -0
  31. package/dist/ctx/create-ctx.d.ts +2 -19
  32. package/dist/ctx/create-ctx.js +3 -93
  33. package/dist/ctx/durable-relay.d.ts +2 -5
  34. package/dist/ctx/durable-relay.js +56 -29
  35. package/dist/db/extension-handoff-schema.js +5 -0
  36. package/dist/db/kernel-schema.d.ts +74 -0
  37. package/dist/erasure/account-batches.js +2 -0
  38. package/dist/erasure/account-residual.js +1 -0
  39. package/dist/erasure/org-catalog.js +8 -3
  40. package/dist/erasure/org-rules.js +1 -0
  41. package/dist/errors.d.ts +1 -1
  42. package/dist/errors.js +2 -2
  43. package/dist/evals/evals.schemas.d.ts +15 -5
  44. package/dist/evals/evals.schemas.js +17 -10
  45. package/dist/evals/runs.controller.d.ts +4 -12
  46. package/dist/evals/runs.controller.js +14 -11
  47. package/dist/evals/runs.service.d.ts +29 -25
  48. package/dist/evals/runs.service.js +73 -61
  49. package/dist/evals/trajectory.controller.d.ts +10 -6
  50. package/dist/evals/trajectory.controller.js +11 -4
  51. package/dist/evals/trajectory.service.d.ts +17 -9
  52. package/dist/evals/trajectory.service.js +52 -35
  53. package/dist/extensions/admin-ops.js +4 -3
  54. package/dist/extensions/blobs.d.ts +2 -0
  55. package/dist/extensions/blobs.js +11 -0
  56. package/dist/extensions/enabled.d.ts +5 -0
  57. package/dist/extensions/grant-epoch.d.ts +108 -0
  58. package/dist/extensions/grant-epoch.js +214 -0
  59. package/dist/extensions/host.d.ts +30 -10
  60. package/dist/extensions/host.js +162 -43
  61. package/dist/extensions/instance.d.ts +3 -3
  62. package/dist/extensions/instance.js +1 -1
  63. package/dist/extensions/isolated/authorization.d.ts +54 -2
  64. package/dist/extensions/isolated/authorization.js +148 -35
  65. package/dist/extensions/isolated/child-session.js +0 -1
  66. package/dist/extensions/isolated/revision.js +1 -1
  67. package/dist/extensions/isolated/tier.d.ts +14 -0
  68. package/dist/extensions/isolated/tier.js +27 -0
  69. package/dist/extensions/package-digest.job.d.ts +34 -0
  70. package/dist/extensions/package-digest.job.js +121 -0
  71. package/dist/extensions/package.js +10 -6
  72. package/dist/extensions/permission-set.d.ts +14 -78
  73. package/dist/extensions/permission-set.js +17 -143
  74. package/dist/extensions/permission-view.d.ts +13 -1
  75. package/dist/extensions/permission-view.js +20 -0
  76. package/dist/extensions/publisher-proof.job.d.ts +39 -0
  77. package/dist/extensions/publisher-proof.job.js +160 -0
  78. package/dist/extensions/registry.js +4 -1
  79. package/dist/extensions/resolve.d.ts +7 -8
  80. package/dist/extensions/resolve.js +7 -8
  81. package/dist/extensions/revision-approvals.d.ts +167 -0
  82. package/dist/extensions/revision-approvals.js +353 -0
  83. package/dist/extensions/revision-grants.d.ts +197 -0
  84. package/dist/extensions/revision-grants.js +584 -0
  85. package/dist/extensions/state.module.js +12 -1
  86. package/dist/identity/accounts.d.ts +10 -4
  87. package/dist/identity/accounts.js +18 -5
  88. package/dist/infra/database/extension-effect-key-lock.js +7 -0
  89. package/dist/infra/paging/paged-read.d.ts +34 -4
  90. package/dist/infra/paging/paged-read.js +38 -1
  91. package/dist/orgs/invitations.controller.d.ts +4 -7
  92. package/dist/orgs/invitations.controller.js +8 -5
  93. package/dist/orgs/invitations.service.d.ts +17 -3
  94. package/dist/orgs/invitations.service.js +35 -13
  95. package/dist/orgs/members.service.d.ts +35 -0
  96. package/dist/orgs/members.service.js +52 -3
  97. package/dist/orgs/orgs.controller.d.ts +11 -4
  98. package/dist/orgs/orgs.controller.js +25 -5
  99. package/dist/orgs/orgs.schemas.d.ts +14 -0
  100. package/dist/orgs/orgs.schemas.js +19 -2
  101. package/dist/orgs/orgs.service.d.ts +21 -1
  102. package/dist/orgs/orgs.service.js +40 -1
  103. package/dist/orgs/security-settings.service.d.ts +14 -6
  104. package/dist/orgs/security-settings.service.js +18 -13
  105. package/dist/orgs/settings.controller.d.ts +7 -4
  106. package/dist/packages/official-publisher.d.ts +5 -0
  107. package/dist/packages/official-publisher.js +24 -3
  108. package/dist/packages/provenance.d.ts +6 -0
  109. package/dist/packages/provenance.js +26 -9
  110. package/dist/platform/exclusions.js +15 -0
  111. package/dist/platform/ops/accounts.ops.js +7 -16
  112. package/dist/platform/ops/admin-items.ops.js +8 -8
  113. package/dist/platform/ops/automations.ops.js +6 -4
  114. package/dist/platform/ops/evals.ops.js +30 -15
  115. package/dist/platform/ops/org-settings.ops.js +2 -2
  116. package/dist/platform/ops/orgs.ops.js +44 -27
  117. package/dist/roles/worker.module.js +6 -0
  118. package/dist/runtime/step-log.d.ts +1 -1
  119. package/dist/runtime/step-log.js +5 -4
  120. package/dist/setup/kernel-checks.d.ts +3 -3
  121. package/dist/setup/kernel-checks.js +4 -4
  122. package/dist/setup/setup-check-registry.d.ts +16 -5
  123. package/dist/setup/setup-check-registry.js +11 -3
  124. package/dist/setup/setup-checks.service.d.ts +1 -2
  125. package/dist/setup/setup-checks.service.js +7 -6
  126. package/dist/tools/admin-connectors.d.ts +10 -8
  127. package/dist/tools/admin-connectors.js +12 -10
  128. package/dist/tools/builtins/automations.d.ts +1 -1
  129. package/dist/tools/builtins/automations.js +1 -1
  130. package/package.json +3 -3
  131. package/src/migrations/0234_extension_grant_epoch.sql +141 -0
  132. package/src/migrations/0235_extension_revision_grants.sql +166 -0
  133. package/src/migrations/0236_paged_table_idx.sql +33 -0
  134. package/src/migrations/0237_extension_handoff_health.sql +18 -0
@@ -27,17 +27,41 @@ export async function readIsolatedGrant(db, grant) {
27
27
  const snapshot = await query.executeTakeFirst();
28
28
  return snapshotCovers(snapshot, permissions);
29
29
  }
30
- const MAX_GRANTS_PER_INSTANCE = 128;
31
- const GRANT_TTL_MS = 60_000;
30
+ /** A grant checked at the current epoch is still rechecked after this long (backstop only). */
31
+ export const GRANT_FULL_REVALIDATION_MS = 5 * 60_000;
32
32
  const REVALIDATION_BATCH = 8;
33
- /** Replica-local cache of authority checked against deployment and org state. */
33
+ const IN_FLIGHT_RECHECK_BATCH = 64;
34
+ /**
35
+ * Replica-local cache of authority checked against deployment and org state.
36
+ *
37
+ * A cached grant is valid only while it was checked at the current grant epoch and the epoch was
38
+ * read successfully within its maximum age. When the epoch cannot be confirmed, new admissions
39
+ * wait for a fresh read and are refused if it fails (fail closed). Bus hints still fence affected
40
+ * grants at once; the epoch covers hints that never arrive.
41
+ */
34
42
  export class IsolatedInvocationGrants {
43
+ epochs;
44
+ capacity;
45
+ now;
35
46
  instances = new Map();
36
47
  rechecks = new Map();
48
+ /** Every cached grant across instances, least recently used first. */
49
+ lru = new Map();
37
50
  revalidating;
51
+ constructor(epochs, capacity, now = () => performance.now()) {
52
+ this.epochs = epochs;
53
+ this.capacity = capacity;
54
+ this.now = now;
55
+ }
38
56
  async issue({ plugin, orgId }, check, onRevoked, instance) {
39
57
  if (instance.aborted)
40
58
  return undefined;
59
+ this.epochs.start();
60
+ // No await when the epoch is fresh: the grant entry must exist before a revocation can race it.
61
+ if (this.epochs.fresh() === undefined) {
62
+ if ((await this.epochs.ensureFresh()) === undefined || instance.aborted)
63
+ return undefined;
64
+ }
41
65
  let bucket = this.instances.get(instance);
42
66
  if (!bucket) {
43
67
  bucket = { plugin, orgs: new Map() };
@@ -45,8 +69,11 @@ export class IsolatedInvocationGrants {
45
69
  this.instances.set(instance, bucket);
46
70
  instance.addEventListener("abort", () => {
47
71
  this.instances.delete(instance);
48
- for (const grant of orgs.values())
72
+ for (const grant of orgs.values()) {
73
+ this.lru.delete(grant);
74
+ this.rechecks.delete(grant);
49
75
  grant.abort.abort();
76
+ }
50
77
  orgs.clear();
51
78
  }, { once: true });
52
79
  }
@@ -54,34 +81,38 @@ export class IsolatedInvocationGrants {
54
81
  let entry = orgs.get(orgId);
55
82
  if (entry) {
56
83
  // Move it to the back so an idle least recently used grant is the first eviction candidate.
57
- orgs.delete(orgId);
84
+ this.lru.delete(entry);
58
85
  }
59
86
  else {
60
- if (orgs.size >= MAX_GRANTS_PER_INSTANCE) {
61
- for (const [key, idle] of orgs) {
62
- if (idle.calls !== 0 || idle.pending)
63
- continue;
64
- orgs.delete(key);
65
- break;
66
- }
67
- if (orgs.size >= MAX_GRANTS_PER_INSTANCE)
68
- return undefined;
69
- }
87
+ if (this.lru.size >= this.capacity && !this.evictIdle())
88
+ return undefined;
70
89
  entry = {
71
90
  abort: new AbortController(),
72
91
  check,
73
92
  onRevoked: onRevoked ?? (() => { }),
74
- checkedUntil: 0,
93
+ epoch: undefined,
94
+ checkedAt: Number.NEGATIVE_INFINITY,
75
95
  calls: 0,
96
+ admitting: 0,
76
97
  };
98
+ orgs.set(orgId, entry);
77
99
  }
78
- orgs.set(orgId, entry);
79
- while (Date.now() >= entry.checkedUntil) {
80
- if (!(await this.validate(orgs, orgId, entry)))
81
- return undefined;
100
+ this.lru.set(entry, { orgs, orgId, entry });
101
+ entry.admitting += 1;
102
+ try {
103
+ for (;;) {
104
+ const epoch = this.epochs.fresh() ?? (await this.epochs.ensureFresh());
105
+ if (epoch === undefined || entry.abort.signal.aborted)
106
+ return undefined;
107
+ if (this.valid(entry, epoch))
108
+ break;
109
+ if (!(await this.validate(orgs, orgId, entry)))
110
+ return undefined;
111
+ }
112
+ }
113
+ finally {
114
+ entry.admitting -= 1;
82
115
  }
83
- if (entry.abort.signal.aborted)
84
- return undefined;
85
116
  const call = new AbortController();
86
117
  entry.calls += 1;
87
118
  return {
@@ -101,7 +132,7 @@ export class IsolatedInvocationGrants {
101
132
  for (const [key, entry] of bucket.orgs) {
102
133
  if (orgId !== undefined && orgId !== key)
103
134
  continue;
104
- bucket.orgs.delete(key);
135
+ this.drop(bucket.orgs, key, entry);
105
136
  entry.abort.abort();
106
137
  }
107
138
  }
@@ -114,7 +145,7 @@ export class IsolatedInvocationGrants {
114
145
  for (const grant of this.retained()) {
115
146
  if (grant.orgId === undefined || (orgId !== undefined && orgId !== grant.orgId))
116
147
  continue;
117
- grant.entry.checkedUntil = 0;
148
+ grant.entry.epoch = undefined;
118
149
  delete grant.entry.pending;
119
150
  this.rechecks.set(grant.entry, grant);
120
151
  }
@@ -123,11 +154,71 @@ export class IsolatedInvocationGrants {
123
154
  /** Recheck retained grants, including idle lanes, when periodic reconciliation fires. */
124
155
  revalidate() {
125
156
  for (const grant of this.retained()) {
126
- if (grant.entry.checkedUntil > 0)
157
+ if (grant.entry.epoch !== undefined)
127
158
  this.rechecks.set(grant.entry, grant);
128
159
  }
129
160
  return this.runRechecks();
130
161
  }
162
+ /**
163
+ * The grant epoch advanced: some committed change may have revoked any cached grant. Every
164
+ * entry is stale for admission already ({@link valid} compares epochs), so idle entries are
165
+ * rechecked lazily by their next admission or the periodic reconcile. Entries with calls in
166
+ * flight are rechecked now, all together, so a call whose grant is gone is aborted quickly;
167
+ * {@link fenceStale} aborts the ones still unconfirmed at the settle deadline.
168
+ */
169
+ async epochChanged() {
170
+ const inFlight = [...this.retained()].filter(({ entry }) => entry.calls > 0);
171
+ for (let start = 0; start < inFlight.length; start += IN_FLIGHT_RECHECK_BATCH) {
172
+ await Promise.all(inFlight.slice(start, start + IN_FLIGHT_RECHECK_BATCH).map(({ orgs, orgId, entry }) => {
173
+ // A check started before the change cannot confirm the new epoch: supersede it.
174
+ delete entry.pending;
175
+ return this.validate(orgs, orgId, entry);
176
+ }));
177
+ }
178
+ }
179
+ /**
180
+ * The settle deadline after an epoch change: abort calls whose grant was not confirmed at the
181
+ * current epoch, so no call outlives a revocation by more than the bound. Lanes stay up; the
182
+ * next admission checks PostgreSQL again.
183
+ */
184
+ fenceStale() {
185
+ const epoch = this.epochs.fresh();
186
+ for (const { orgs, orgId, entry } of [...this.retained()]) {
187
+ if (entry.calls === 0 || (epoch !== undefined && this.valid(entry, epoch)))
188
+ continue;
189
+ this.drop(orgs, orgId, entry);
190
+ entry.abort.abort();
191
+ }
192
+ }
193
+ /**
194
+ * The epoch has not been confirmed for the whole revocation bound. Fence every cached grant:
195
+ * in-flight calls are cancelled and the next admission checks PostgreSQL again. Lanes stay up,
196
+ * because nothing is known to be revoked.
197
+ */
198
+ fenceAll() {
199
+ this.revoke({});
200
+ }
201
+ valid(entry, epoch) {
202
+ return (entry.pending === undefined &&
203
+ entry.epoch === epoch &&
204
+ this.now() - entry.checkedAt < GRANT_FULL_REVALIDATION_MS);
205
+ }
206
+ evictIdle() {
207
+ for (const { orgs, orgId, entry } of this.lru.values()) {
208
+ if (entry.calls !== 0 || entry.admitting !== 0 || entry.pending)
209
+ continue;
210
+ this.drop(orgs, orgId, entry);
211
+ entry.abort.abort();
212
+ return true;
213
+ }
214
+ return false;
215
+ }
216
+ drop(orgs, orgId, entry) {
217
+ if (orgs.get(orgId) === entry)
218
+ orgs.delete(orgId);
219
+ this.lru.delete(entry);
220
+ this.rechecks.delete(entry);
221
+ }
131
222
  *retained() {
132
223
  for (const { orgs } of this.instances.values()) {
133
224
  for (const [orgId, entry] of orgs)
@@ -162,29 +253,51 @@ export class IsolatedInvocationGrants {
162
253
  if (entry.pending)
163
254
  return entry.pending;
164
255
  this.rechecks.delete(entry);
165
- const checkedUntil = Date.now() + GRANT_TTL_MS;
166
- const pending = Promise.resolve()
167
- .then(entry.check)
168
- .catch(() => false)
169
- .then((allowed) => {
256
+ const run = async (epoch) => {
257
+ // The epoch is captured before the query starts. A revocation committed after the query's
258
+ // snapshot advances the epoch past this value, so the result is never trusted beyond it.
259
+ const checkedAt = this.now();
260
+ let failed = false;
261
+ const allowed = epoch !== undefined &&
262
+ (await Promise.resolve()
263
+ .then(entry.check)
264
+ .catch(() => {
265
+ failed = true;
266
+ return false;
267
+ }));
170
268
  if (entry.pending !== pending) {
171
269
  // A catalog hint superseded this query. Share the next decision or reuse it if complete.
172
270
  if (entry.abort.signal.aborted || orgs.get(orgId) !== entry)
173
271
  return false;
174
- return entry.checkedUntil > Date.now() || this.validate(orgs, orgId, entry);
272
+ const current = this.epochs.fresh();
273
+ return ((current !== undefined && this.valid(entry, current)) || this.validate(orgs, orgId, entry));
175
274
  }
176
275
  delete entry.pending;
177
276
  if (entry.abort.signal.aborted)
178
277
  return false;
278
+ if (epoch === undefined) {
279
+ // The epoch could not be confirmed: refuse this admission but keep the lane, since
280
+ // nothing is known to be revoked.
281
+ entry.epoch = undefined;
282
+ return false;
283
+ }
179
284
  if (allowed) {
180
- entry.checkedUntil = checkedUntil;
285
+ entry.epoch = epoch;
286
+ entry.checkedAt = checkedAt;
181
287
  return true;
182
288
  }
183
- orgs.delete(orgId);
289
+ // Denied or not checkable: fence the grant (calls abort, the next admission checks again).
290
+ // Only a decision that denies retires the lanes; a failed query (a transient database error
291
+ // during any catalog write's recheck) is not a revocation.
292
+ this.drop(orgs, orgId, entry);
184
293
  entry.abort.abort();
185
- entry.onRevoked();
294
+ if (!failed)
295
+ entry.onRevoked();
186
296
  return false;
187
- });
297
+ };
298
+ // Start the query in this tick when the epoch is fresh, so concurrent callers coalesce on it.
299
+ const known = this.epochs.fresh();
300
+ const pending = known !== undefined ? run(known) : this.epochs.ensureFresh().then(run);
188
301
  entry.pending = pending;
189
302
  return pending;
190
303
  }
@@ -153,7 +153,6 @@ export function createChildSession(root, send) {
153
153
  get secrets() {
154
154
  return noGroup();
155
155
  },
156
- extensionPoints: { get: unsupported, list: unsupported },
157
156
  log: { info: logFor("info"), warn: logFor("warn"), error: logFor("error") },
158
157
  kv: {
159
158
  get: (key) => broker("kv", "get", [key]),
@@ -214,7 +214,7 @@ export async function isolatedRevision(options) {
214
214
  key: manifest.name,
215
215
  dispose: () => instance.close(),
216
216
  });
217
- const descriptors = callbackList(await instance.register(), section.manifest.permissions.tools ?? []);
217
+ const descriptors = callbackList(await instance.register(), manifest.permissions?.tools ?? []);
218
218
  for (const descriptor of descriptors) {
219
219
  await bind(ctx, instance, descriptor, options.effective, options.authorize, options.roles, options.quota);
220
220
  }
@@ -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,34 @@
1
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { LockService } from "../infra/lock/lock.service.js";
4
+ import type { KernelLogger } from "../log.js";
5
+ import { ExtensionBlobs } from "./blobs.js";
6
+ export declare const PACKAGE_SHA512_BACKFILL_JOB = "extension-package-sha512-backfill";
7
+ /** Packages read per page, and pages per tick: each read is a full archive, bounded by `packages.maxBytes`. */
8
+ export declare const PACKAGE_SHA512_BACKFILL_BATCH = 50;
9
+ /**
10
+ * Fills `extension_packages.sha512` for packages stored before migration 0235 (plan task 1.2b), so
11
+ * every install resolves its revision grant by `(version, sha512)`. New packages get it at ingest.
12
+ *
13
+ * Idempotent and once per tick across replicas (`@LockedInterval`, worker role): each row is
14
+ * written only while still NULL, from bytes `ExtensionBlobs.get` verified against the sha256. A
15
+ * package whose bytes cannot be read stays NULL and is retried on the next tick; the shadow
16
+ * decision reports it as an unknown digest meanwhile. Once every row is filled a tick is one empty
17
+ * query.
18
+ */
19
+ export declare class PackageDigestBackfillJob {
20
+ private readonly kdb;
21
+ private readonly blobs;
22
+ readonly config: KernelConfigService;
23
+ readonly lockService: LockService;
24
+ readonly log: KernelLogger;
25
+ constructor(kdb: KernelDb, blobs: Pick<ExtensionBlobs, "get">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
26
+ backfill(stop?: AbortSignal): Promise<void>;
27
+ /** One pass of the backfill (the locked tick runs it); returns what it filled and could not. */
28
+ fill(stop?: AbortSignal,
29
+ /** Tests only: the cursor the tick starts at (random otherwise). */
30
+ start?: string): Promise<{
31
+ filled: number;
32
+ failed: number;
33
+ }>;
34
+ }
@@ -0,0 +1,121 @@
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 { randomBytes } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { LockService } from "../infra/lock/lock.service.js";
15
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
16
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
+ import { ExtensionBlobs, packageSha512 } from "./blobs.js";
18
+ export const PACKAGE_SHA512_BACKFILL_JOB = "extension-package-sha512-backfill";
19
+ /** Packages read per page, and pages per tick: each read is a full archive, bounded by `packages.maxBytes`. */
20
+ export const PACKAGE_SHA512_BACKFILL_BATCH = 50;
21
+ const PACKAGE_SHA512_BACKFILL_PAGES = 4;
22
+ const PACKAGE_SHA512_BACKFILL_PERIOD_MS = 10 * 60_000;
23
+ /**
24
+ * Fills `extension_packages.sha512` for packages stored before migration 0235 (plan task 1.2b), so
25
+ * every install resolves its revision grant by `(version, sha512)`. New packages get it at ingest.
26
+ *
27
+ * Idempotent and once per tick across replicas (`@LockedInterval`, worker role): each row is
28
+ * written only while still NULL, from bytes `ExtensionBlobs.get` verified against the sha256. A
29
+ * package whose bytes cannot be read stays NULL and is retried on the next tick; the shadow
30
+ * decision reports it as an unknown digest meanwhile. Once every row is filled a tick is one empty
31
+ * query.
32
+ */
33
+ let PackageDigestBackfillJob = class PackageDigestBackfillJob {
34
+ kdb;
35
+ blobs;
36
+ config;
37
+ lockService;
38
+ log;
39
+ constructor(kdb, blobs, config, lockService, log) {
40
+ this.kdb = kdb;
41
+ this.blobs = blobs;
42
+ this.config = config;
43
+ this.lockService = lockService;
44
+ this.log = log;
45
+ }
46
+ async backfill(stop) {
47
+ await this.fill(stop);
48
+ }
49
+ /** One pass of the backfill (the locked tick runs it); returns what it filled and could not. */
50
+ async fill(stop,
51
+ /** Tests only: the cursor the tick starts at (random otherwise). */
52
+ start = randomBytes(32).toString("hex")) {
53
+ let filled = 0;
54
+ let failed = 0;
55
+ // Each tick starts at a random point of the sha256 order and wraps around, so packages whose
56
+ // bytes cannot be read never use up every tick's budget ahead of the same rows: every row is
57
+ // reached within a few ticks however many are unreadable.
58
+ const budget = PACKAGE_SHA512_BACKFILL_BATCH * PACKAGE_SHA512_BACKFILL_PAGES;
59
+ let read = 0;
60
+ for (const half of ["after", "upto"]) {
61
+ let after = half === "after" ? start : "";
62
+ while (read < budget && !stop?.aborted) {
63
+ const limit = Math.min(PACKAGE_SHA512_BACKFILL_BATCH, budget - read);
64
+ let query = this.kdb.db
65
+ .selectFrom("extension_packages")
66
+ .select("sha256")
67
+ .where("sha512", "is", null)
68
+ .where("sha256", ">", after);
69
+ if (half === "upto")
70
+ query = query.where("sha256", "<=", start);
71
+ const rows = await query.orderBy("sha256").limit(limit).execute();
72
+ for (const { sha256 } of rows) {
73
+ if (stop?.aborted)
74
+ break;
75
+ after = sha256;
76
+ read += 1;
77
+ let sha512;
78
+ try {
79
+ sha512 = packageSha512(await this.blobs.get(sha256));
80
+ }
81
+ catch (err) {
82
+ failed += 1;
83
+ this.log.warn("cannot read a stored extension package to record its sha512", {
84
+ sha256,
85
+ err,
86
+ });
87
+ continue;
88
+ }
89
+ const result = await this.kdb.db
90
+ .updateTable("extension_packages")
91
+ .set({ sha512 })
92
+ .where("sha256", "=", sha256)
93
+ .where("sha512", "is", null)
94
+ .executeTakeFirst();
95
+ if (result.numUpdatedRows > 0n)
96
+ filled += 1;
97
+ }
98
+ if (rows.length < limit)
99
+ break;
100
+ }
101
+ }
102
+ if (filled > 0 || failed > 0) {
103
+ this.log.info("extension package sha512 backfill", { filled, failed });
104
+ }
105
+ return { filled, failed };
106
+ }
107
+ };
108
+ __decorate([
109
+ LockedInterval(PACKAGE_SHA512_BACKFILL_JOB, () => PACKAGE_SHA512_BACKFILL_PERIOD_MS, {
110
+ runOnStart: true,
111
+ })
112
+ ], PackageDigestBackfillJob.prototype, "backfill", null);
113
+ PackageDigestBackfillJob = __decorate([
114
+ Injectable(),
115
+ __param(0, Inject(KernelDb)),
116
+ __param(1, Inject(ExtensionBlobs)),
117
+ __param(2, Inject(KernelConfigService)),
118
+ __param(3, Inject(LockService)),
119
+ __param(4, Inject(KERNEL_LOGGER))
120
+ ], PackageDigestBackfillJob);
121
+ export { PackageDigestBackfillJob };
@@ -1,13 +1,13 @@
1
1
  import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { dirname, join, posix, relative, resolve as resolvePath } from "node:path";
3
- import { checkEntryImports, isSafePackagePath, PLUGIN_MANIFEST_FILE, parsePluginManifest, } from "@capybara-hq/plugin-sdk";
3
+ import { checkEntryImports, isSafePackagePath, PLUGIN_MANIFEST_FILE, parsePluginManifest, staticPermissionDeclarations, } from "@capybara-hq/plugin-sdk";
4
4
  import { init as lexerInit, parse as lexerParse } from "es-module-lexer";
5
5
  import { PluginPackageError, readPluginPackage, withoutRemovedManifestFields, } from "../catalog/plugin-package.js";
6
6
  import { pluginSchemaName } from "../ctx/create-ctx.js";
7
7
  import { MIGRATION_FILE_RE } from "../db/migrator.js";
8
8
  import { ApiError } from "../errors.js";
9
9
  import { HOST_ZOD_VERSION, PACKAGE_TGZ_LIMITS, PackageTgzError, packagePath, unpackPackageTgz, } from "../packages/tgz.js";
10
- import { buildPermissionSet, parseCreatedTables } from "./permission-set.js";
10
+ import { buildPermissionSet, FULL_ACCESS_UNSUPPORTED, parseCreatedTables, } from "./permission-set.js";
11
11
  import { migrationWarnings, warningsDigest } from "./permission-view.js";
12
12
  /**
13
13
  * Reading and validating an extension package: a plugin tgz (`readPluginPackage`,
@@ -137,6 +137,8 @@ export async function readExtensionPackage(bytes, opts) {
137
137
  `plugin ${manifest.name} has no extension (no "extension" in ${PLUGIN_MANIFEST_FILE}); import it into the catalog instead`,
138
138
  ], "extension.no_extension");
139
139
  }
140
+ if (ext.manifest.permissions.fullAccess !== undefined)
141
+ throw new ExtensionPackageError([FULL_ACCESS_UNSUPPORTED]);
140
142
  await lexerInit;
141
143
  const issues = checkModuleGraph(packagePath(ext.entry), files);
142
144
  const migrationSql = [];
@@ -179,16 +181,18 @@ export function permissionSetOfPackage(p) {
179
181
  */
180
182
  export function permissionSetOfSection(section, migrationSql) {
181
183
  const m = section.manifest;
184
+ const declaration = staticPermissionDeclarations(m);
182
185
  const schema = pluginSchemaName(m.name);
183
186
  const tables = migrationSql.flatMap((f) => parseCreatedTables(f.sql, schema));
184
187
  const strip = (fs) => fs.map((f) => ({ path: f.path, secret: f.secret }));
185
188
  return buildPermissionSet({
186
- provides: m.provides,
187
- requires: m.requires,
188
- optional: m.optional,
189
+ provides: declaration.provides,
190
+ requires: declaration.requires,
191
+ optional: declaration.optional,
189
192
  config: { deployment: strip(m.config.deployment) },
190
193
  tables,
191
- permissions: m.permissions,
194
+ permissions: declaration.permissions,
195
+ purposes: declaration.purposes,
192
196
  warningsDigest: warningsDigest(migrationWarnings(migrationSql, m.name)),
193
197
  });
194
198
  }