@capybara-hq/kernel 0.1.0-rc.137 → 0.1.0-rc.139

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 (101) hide show
  1. package/bootstrap.json +31 -31
  2. package/dist/admin/extensions.controller.d.ts +5 -2
  3. package/dist/admin/extensions.controller.js +10 -1
  4. package/dist/admin/extensions.schemas.d.ts +4 -0
  5. package/dist/admin/extensions.schemas.js +9 -0
  6. package/dist/admin/health.service.d.ts +1 -1
  7. package/dist/admin/health.service.js +3 -3
  8. package/dist/catalog/catalog-content.d.ts +5 -7
  9. package/dist/catalog/catalog-items.js +1 -1
  10. package/dist/catalog/catalog-scope.service.js +5 -5
  11. package/dist/catalog/catalog.module.js +5 -4
  12. package/dist/catalog/catalog.service.d.ts +7 -1
  13. package/dist/catalog/catalog.service.js +19 -2
  14. package/dist/catalog/effect-work.d.ts +27 -0
  15. package/dist/catalog/effect-work.js +151 -0
  16. package/dist/catalog/jobs.d.ts +4 -1
  17. package/dist/catalog/jobs.js +14 -4
  18. package/dist/catalog/org-catalog.service.d.ts +2 -0
  19. package/dist/catalog/org-catalog.service.js +68 -12
  20. package/dist/catalog/org-intent.d.ts +4 -2
  21. package/dist/catalog/org-intent.js +25 -4
  22. package/dist/catalog/owned-items.d.ts +5 -1
  23. package/dist/catalog/owned-items.js +18 -3
  24. package/dist/catalog/plugin-import.d.ts +4 -2
  25. package/dist/catalog/plugin-import.js +10 -5
  26. package/dist/catalog/plugin-install.d.ts +17 -51
  27. package/dist/catalog/plugin-install.js +209 -235
  28. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  29. package/dist/catalog/plugin-upgrade.js +63 -34
  30. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  31. package/dist/catalog/scope-sync-workers.js +10 -26
  32. package/dist/catalog/scope-sync.d.ts +19 -114
  33. package/dist/catalog/scope-sync.js +220 -239
  34. package/dist/catalog/scope-writer.d.ts +10 -1
  35. package/dist/catalog/scope-writer.js +62 -4
  36. package/dist/catalog/template-connector-ensure.js +1 -1
  37. package/dist/catalog/unshare.js +1 -2
  38. package/dist/config/schema.d.ts +1 -1
  39. package/dist/config/schema.js +7 -4
  40. package/dist/db/kernel-schema.d.ts +18 -17
  41. package/dist/erasure/org-catalog.js +2 -2
  42. package/dist/erasure/org-rules.js +2 -2
  43. package/dist/extensions/admin-ops.d.ts +1 -1
  44. package/dist/extensions/admin-ops.js +1 -1
  45. package/dist/extensions/admin-view.d.ts +4 -1
  46. package/dist/extensions/admin-view.js +27 -11
  47. package/dist/extensions/bootstrap.d.ts +1 -1
  48. package/dist/extensions/bootstrap.js +2 -3
  49. package/dist/extensions/enabled.d.ts +159 -0
  50. package/dist/extensions/enabled.js +7 -0
  51. package/dist/extensions/host.d.ts +1 -0
  52. package/dist/extensions/host.js +5 -2
  53. package/dist/extensions/isolated/authorization.d.ts +8 -0
  54. package/dist/extensions/isolated/authorization.js +56 -11
  55. package/dist/extensions/isolated/broker.js +30 -11
  56. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  57. package/dist/extensions/isolated/engine-binds.js +82 -0
  58. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  59. package/dist/extensions/isolated/engine-policy.js +75 -0
  60. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  61. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  62. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  63. package/dist/extensions/isolated/engine-proxy.js +408 -0
  64. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  65. package/dist/extensions/isolated/engine-vaults.js +93 -0
  66. package/dist/extensions/isolated/lanes.d.ts +11 -3
  67. package/dist/extensions/isolated/lanes.js +43 -16
  68. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  69. package/dist/extensions/isolated/postgres-gate.js +6 -6
  70. package/dist/extensions/isolated/revision.d.ts +1 -1
  71. package/dist/extensions/isolated/revision.js +3 -2
  72. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  73. package/dist/extensions/isolated/sandbox.js +101 -117
  74. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  75. package/dist/extensions/lifecycle-topics.js +1 -0
  76. package/dist/extensions/lifecycle.js +23 -2
  77. package/dist/extensions/permission-view.d.ts +6 -1
  78. package/dist/inbox/platform-inbox.service.js +16 -27
  79. package/dist/infra/events/kernel-events.d.ts +4 -0
  80. package/dist/infra/outbox/registry.d.ts +3 -36
  81. package/dist/infra/outbox/registry.js +4 -49
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -1
  84. package/dist/orgs/org-lock.d.ts +3 -1
  85. package/dist/orgs/org-lock.js +3 -1
  86. package/dist/orgs/orgs.service.d.ts +3 -1
  87. package/dist/orgs/orgs.service.js +15 -8
  88. package/dist/overrides.d.ts +0 -3
  89. package/dist/overrides.js +0 -2
  90. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  91. package/dist/platform/ops/org-plugins.ops.js +5 -2
  92. package/dist/platform/ops/plugins.ops.js +11 -10
  93. package/dist/tools/registry.d.ts +1 -1
  94. package/dist/tools/registry.js +6 -2
  95. package/package.json +2 -2
  96. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  97. package/src/migrations/0232_contract_plugin_effect_schema.sql +49 -0
  98. package/dist/catalog/install-status.d.ts +0 -5
  99. package/dist/catalog/install-status.js +0 -5
  100. package/dist/catalog/scope-jobs.d.ts +0 -59
  101. package/dist/catalog/scope-jobs.js +0 -78
@@ -146,6 +146,13 @@ export function enabledExtensionsByOrg(db, plugins) {
146
146
  .where("enabled_org.deleted_at", "is", null)
147
147
  .where(({ exists, ref }) => exists(enabledExtensionsQuery(db, ref("enabled_org.id"), ref("requested.plugin"))));
148
148
  }
149
+ /** The enabled organization totals for a bounded page of extension names. */
150
+ export function extensionOrgCountsQuery(db, names) {
151
+ return db
152
+ .selectFrom(enabledExtensionsByOrg(db, names).as("en"))
153
+ .select(["en.plugin", (eb) => eb.fn.countAll().as("n")])
154
+ .groupBy("en.plugin");
155
+ }
149
156
  /** Whether the extension has committed intent in the org. Execution checks remain at the caller. */
150
157
  export async function isExtensionEnabled(db, orgId, plugin) {
151
158
  const { enabled } = await db
@@ -538,6 +538,7 @@ export declare class ExtensionHost {
538
538
  */
539
539
  activatePending(): Promise<string[]>;
540
540
  revokeIsolatedInvocations(scope: IsolatedRevocation): void;
541
+ refreshIsolatedOrgIntent(orgId?: string): Promise<void>;
541
542
  revalidateIsolatedInvocations(): Promise<void>;
542
543
  /**
543
544
  * Publish approved policy expectations before doing work that might leave a handler temporarily
@@ -729,7 +729,7 @@ let ExtensionHost = class ExtensionHost {
729
729
  this.installLoader = p.installs;
730
730
  const isolation = this.config.get().extensionHost.isolation;
731
731
  if (isolation) {
732
- await sweepExtensionSandboxOrphans(isolation.dockerSocket).catch(() => {
732
+ await sweepExtensionSandboxOrphans(isolation.engineUrl).catch(() => {
733
733
  this.log.error("Could not sweep exited isolated extension sandboxes");
734
734
  });
735
735
  }
@@ -1794,6 +1794,9 @@ let ExtensionHost = class ExtensionHost {
1794
1794
  this.isolatedLanes.get(instance)?.revokeOrg(scope.orgId);
1795
1795
  }
1796
1796
  }
1797
+ refreshIsolatedOrgIntent(orgId) {
1798
+ return this.isolatedGrants.refreshOrgIntent(orgId);
1799
+ }
1797
1800
  revalidateIsolatedInvocations() {
1798
1801
  return this.isolatedGrants.revalidate();
1799
1802
  }
@@ -2059,7 +2062,7 @@ let ExtensionHost = class ExtensionHost {
2059
2062
  section: spec.isolated.section,
2060
2063
  identity,
2061
2064
  sandbox: {
2062
- dockerSocket: isolation.dockerSocket,
2065
+ engineUrl: isolation.engineUrl,
2063
2066
  image: isolation.image,
2064
2067
  postgresSocket: isolation.postgresSocket,
2065
2068
  packageRoot: spec.isolated.root,
@@ -26,11 +26,19 @@ interface CachedGrant {
26
26
  /** Replica-local cache of authority checked against deployment and org state. */
27
27
  export declare class IsolatedInvocationGrants {
28
28
  private readonly instances;
29
+ private readonly rechecks;
29
30
  private revalidating;
30
31
  issue({ plugin, orgId }: IsolatedRevocation, check: CachedGrant["check"], onRevoked: CachedGrant["onRevoked"] | undefined, instance: AbortSignal): Promise<IsolatedInvocationGrant | undefined>;
31
32
  revoke({ plugin, orgId }: IsolatedRevocation): void;
33
+ /**
34
+ * A committed catalog change can alter eligibility through dependency edges. Fence the old
35
+ * snapshot for every affected org grant, then close only the lanes that lose eligibility.
36
+ */
37
+ refreshOrgIntent(orgId?: string): Promise<void>;
32
38
  /** Recheck retained grants, including idle lanes, when periodic reconciliation fires. */
33
39
  revalidate(): Promise<void>;
40
+ private retained;
41
+ private runRechecks;
34
42
  private revalidateRetained;
35
43
  private validate;
36
44
  }
@@ -33,6 +33,7 @@ const REVALIDATION_BATCH = 8;
33
33
  /** Replica-local cache of authority checked against deployment and org state. */
34
34
  export class IsolatedInvocationGrants {
35
35
  instances = new Map();
36
+ rechecks = new Map();
36
37
  revalidating;
37
38
  async issue({ plugin, orgId }, check, onRevoked, instance) {
38
39
  if (instance.aborted)
@@ -75,8 +76,9 @@ export class IsolatedInvocationGrants {
75
76
  };
76
77
  }
77
78
  orgs.set(orgId, entry);
78
- if (Date.now() >= entry.checkedUntil && !(await this.validate(orgs, orgId, entry))) {
79
- return undefined;
79
+ while (Date.now() >= entry.checkedUntil) {
80
+ if (!(await this.validate(orgs, orgId, entry)))
81
+ return undefined;
80
82
  }
81
83
  if (entry.abort.signal.aborted)
82
84
  return undefined;
@@ -104,31 +106,73 @@ export class IsolatedInvocationGrants {
104
106
  }
105
107
  }
106
108
  }
109
+ /**
110
+ * A committed catalog change can alter eligibility through dependency edges. Fence the old
111
+ * snapshot for every affected org grant, then close only the lanes that lose eligibility.
112
+ */
113
+ refreshOrgIntent(orgId) {
114
+ for (const grant of this.retained()) {
115
+ if (grant.orgId === undefined || (orgId !== undefined && orgId !== grant.orgId))
116
+ continue;
117
+ grant.entry.checkedUntil = 0;
118
+ delete grant.entry.pending;
119
+ this.rechecks.set(grant.entry, grant);
120
+ }
121
+ return this.runRechecks();
122
+ }
107
123
  /** Recheck retained grants, including idle lanes, when periodic reconciliation fires. */
108
124
  revalidate() {
125
+ for (const grant of this.retained()) {
126
+ if (grant.entry.checkedUntil > 0)
127
+ this.rechecks.set(grant.entry, grant);
128
+ }
129
+ return this.runRechecks();
130
+ }
131
+ *retained() {
132
+ for (const { orgs } of this.instances.values()) {
133
+ for (const [orgId, entry] of orgs)
134
+ yield { orgs, orgId, entry };
135
+ }
136
+ }
137
+ runRechecks() {
109
138
  this.revalidating ??= this.revalidateRetained().finally(() => {
110
139
  this.revalidating = undefined;
140
+ if (this.rechecks.size > 0)
141
+ return this.runRechecks();
111
142
  });
112
143
  return this.revalidating;
113
144
  }
114
145
  async revalidateRetained() {
115
- const entries = [...this.instances.values()].flatMap(({ orgs }) => [...orgs].map(([orgId, entry]) => ({ orgs, orgId, entry })));
116
- for (let i = 0; i < entries.length; i += REVALIDATION_BATCH) {
117
- await Promise.all(entries.slice(i, i + REVALIDATION_BATCH).map(({ orgs, orgId, entry }) => {
118
- if (entry.checkedUntil === 0 || orgs.get(orgId) !== entry)
119
- return false;
120
- return this.validate(orgs, orgId, entry);
121
- }));
146
+ while (this.rechecks.size > 0) {
147
+ const batch = [];
148
+ for (const { orgs, orgId, entry } of this.rechecks.values()) {
149
+ this.rechecks.delete(entry);
150
+ if (orgs.get(orgId) !== entry)
151
+ continue;
152
+ batch.push(this.validate(orgs, orgId, entry));
153
+ if (batch.length === REVALIDATION_BATCH)
154
+ break;
155
+ }
156
+ await Promise.all(batch);
122
157
  }
123
158
  }
124
159
  validate(orgs, orgId, entry) {
160
+ if (entry.abort.signal.aborted || orgs.get(orgId) !== entry)
161
+ return Promise.resolve(false);
125
162
  if (entry.pending)
126
163
  return entry.pending;
164
+ this.rechecks.delete(entry);
127
165
  const checkedUntil = Date.now() + GRANT_TTL_MS;
128
- entry.pending = Promise.resolve()
166
+ const pending = Promise.resolve()
129
167
  .then(entry.check)
130
168
  .catch(() => false)
131
169
  .then((allowed) => {
170
+ if (entry.pending !== pending) {
171
+ // A catalog hint superseded this query. Share the next decision or reuse it if complete.
172
+ if (entry.abort.signal.aborted || orgs.get(orgId) !== entry)
173
+ return false;
174
+ return entry.checkedUntil > Date.now() || this.validate(orgs, orgId, entry);
175
+ }
132
176
  delete entry.pending;
133
177
  if (entry.abort.signal.aborted)
134
178
  return false;
@@ -141,6 +185,7 @@ export class IsolatedInvocationGrants {
141
185
  entry.onRevoked();
142
186
  return false;
143
187
  });
144
- return entry.pending;
188
+ entry.pending = pending;
189
+ return pending;
145
190
  }
146
191
  }
@@ -29,12 +29,20 @@ const LOG_METHODS = {
29
29
  "log.error": "error",
30
30
  };
31
31
  const ACKNOWLEDGED_WRITES = new Set([
32
+ "bus.publish",
33
+ "inbox.post",
34
+ "inbox.resolve",
32
35
  "kv.set",
33
36
  "kv.del",
34
37
  "kv.incr",
38
+ "outbox.add",
39
+ "outbox.stage",
40
+ "queue.add",
35
41
  "storage.delete",
36
42
  "storage.deletePrefix",
37
43
  "storage.finishPut",
44
+ "triggers.emit",
45
+ "ui.invalidate",
38
46
  ]);
39
47
  class Handles {
40
48
  owners = new WeakMap();
@@ -183,9 +191,10 @@ export function createIsolatedBroker(options) {
183
191
  throw error;
184
192
  }
185
193
  };
194
+ const isCurrent = (signal) => !signal.aborted && options.current();
186
195
  const fetch = async (urlValue, initValue, org, signal) => {
187
196
  const url = new URL(string(urlValue));
188
- if (!(await options.network(url, org)) || signal.aborted)
197
+ if (!(await options.network(url, org)) || !isCurrent(signal))
189
198
  return refuse();
190
199
  const init = requestInit.parse(initValue);
191
200
  return ctx.net.fetch(url.href, {
@@ -295,16 +304,10 @@ export function createIsolatedBroker(options) {
295
304
  own(org, record(input).orgId);
296
305
  return modelResult(() => call(ctx.models.generateImage.bind(ctx.models), [{ ...record(input), signal }]), scope);
297
306
  },
298
- "net.fetch": async ([url, init, requested], org, scope, signal) => {
307
+ "net.fetch": ([url, init, requested], org, _scope, signal) => {
299
308
  if (requested !== undefined && requested !== null)
300
309
  own(org, record(requested).orgId ?? org);
301
- const response = await fetch(url, init, org, signal);
302
- return {
303
- status: response.status,
304
- statusText: response.statusText,
305
- headers: [...response.headers],
306
- ...(response.body && { stream: openReader(scope, response.body) }),
307
- };
310
+ return fetch(url, init, org, signal);
308
311
  },
309
312
  "storage.get": async ([supplied, key, opts], org, scope, signal) => {
310
313
  own(org, supplied);
@@ -401,7 +404,7 @@ export function createIsolatedBroker(options) {
401
404
  const org = scope.orgId;
402
405
  const name = method.slice("broker.".length);
403
406
  const run = async () => {
404
- if (!options.current() || signal.aborted)
407
+ if (!isCurrent(signal))
405
408
  return refuse();
406
409
  if (Object.hasOwn(LOG_METHODS, name)) {
407
410
  const [message] = args;
@@ -415,6 +418,7 @@ export function createIsolatedBroker(options) {
415
418
  break;
416
419
  loggedAt.delete(loggedOrg);
417
420
  }
421
+ loggedAt.delete(org);
418
422
  if (loggedAt.size >= LOG_ORGS_PER_WINDOW)
419
423
  return;
420
424
  loggedAt.set(org, now);
@@ -443,9 +447,24 @@ export function createIsolatedBroker(options) {
443
447
  const result = await (org === undefined
444
448
  ? asPlatform("Dispatch an isolated deployment callback", run)
445
449
  : withOrgScope(org, run));
450
+ if (name === "net.fetch") {
451
+ const response = result;
452
+ if (!isCurrent(signal) || scope.signal?.aborted) {
453
+ // The request was sent under a live grant. Acknowledge it without handing over its body
454
+ // or potentially sensitive response headers after revocation.
455
+ void response.body?.cancel().catch(() => { });
456
+ return { status: response.status, statusText: "", headers: [] };
457
+ }
458
+ return {
459
+ status: response.status,
460
+ statusText: response.statusText,
461
+ headers: [...response.headers],
462
+ ...(response.body && { stream: openReader(scope, response.body) }),
463
+ };
464
+ }
446
465
  // The scope was checked before dispatch. Reporting a completed write as refused can cause
447
466
  // the caller to repeat it. Reads and live handles still require current authority.
448
- if (!ACKNOWLEDGED_WRITES.has(name) && (!options.current() || signal.aborted))
467
+ if (!ACKNOWLEDGED_WRITES.has(name) && !isCurrent(signal))
449
468
  return refuse();
450
469
  return result;
451
470
  };
@@ -0,0 +1,9 @@
1
+ export declare const MAX_STAGED_ARCHIVE: number;
2
+ export declare const MAX_STAGED_UNPACKED: number;
3
+ export declare function protectedBind(path: string, kind: "directory" | "socket"): Promise<import("node:fs").Stats>;
4
+ export declare function protectedStage(path: string): Promise<void>;
5
+ export declare function stageBinds(staging: string, binds: string, name: string, owner: string, digest: string, postgresPort: string | undefined, onVaultCreated: () => void): Promise<{
6
+ pkg: string;
7
+ socket: string | undefined;
8
+ verify: () => Promise<void>;
9
+ }>;
@@ -0,0 +1,82 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { chmod, lstat, mkdir, mkdtemp, open, realpath, rename } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { extractExtensionPackage } from "../package.js";
6
+ export const MAX_STAGED_ARCHIVE = 64 * 1024 * 1024;
7
+ export const MAX_STAGED_UNPACKED = 96 * 1024 * 1024;
8
+ export async function protectedBind(path, kind) {
9
+ const entry = await lstat(path);
10
+ if ((kind === "directory" ? !entry.isDirectory() : !entry.isSocket()) ||
11
+ (kind === "directory"
12
+ ? entry.uid !== process.getuid?.() || (entry.mode & 0o022) !== 0
13
+ : entry.nlink !== 1) ||
14
+ (await realpath(path)) !== path)
15
+ throw new Error("Unsafe extension bind");
16
+ return entry;
17
+ }
18
+ export async function protectedStage(path) {
19
+ const stage = await lstat(path);
20
+ if (!stage.isDirectory() || stage.uid !== process.getuid?.() || (await realpath(path)) !== path)
21
+ throw new Error("Unsafe extension staging directory");
22
+ }
23
+ export async function stageBinds(staging, binds, name, owner, digest, postgresPort, onVaultCreated) {
24
+ await protectedBind(join(binds, ".."), "directory");
25
+ await protectedBind(binds, "directory");
26
+ await protectedStage(staging);
27
+ const archive = await open(join(staging, `${name}.tgz`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
28
+ let bytes;
29
+ try {
30
+ const stat = await archive.stat();
31
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_STAGED_ARCHIVE)
32
+ throw new Error("Invalid staged extension archive");
33
+ bytes = Buffer.alloc(stat.size);
34
+ const result = await archive.read({ buffer: bytes, length: bytes.length });
35
+ if (result.bytesRead !== bytes.length ||
36
+ createHash("sha256").update(bytes).digest("hex") !== digest)
37
+ throw new Error("Invalid staged extension archive digest");
38
+ }
39
+ finally {
40
+ await archive.close();
41
+ }
42
+ const ownerDir = join(binds, owner);
43
+ await mkdir(ownerDir, { recursive: true, mode: 0o755 });
44
+ await protectedBind(ownerDir, "directory");
45
+ const directory = join(ownerDir, name);
46
+ await mkdir(directory, { mode: 0o755 });
47
+ onVaultCreated();
48
+ const temporary = await mkdtemp(join(directory, ".package-"));
49
+ const pkg = join(directory, digest);
50
+ await extractExtensionPackage(bytes, temporary, {
51
+ maxBytes: MAX_STAGED_ARCHIVE,
52
+ maxUnpackedBytes: MAX_STAGED_UNPACKED,
53
+ });
54
+ await chmod(temporary, 0o755);
55
+ await rename(temporary, pkg);
56
+ let lane;
57
+ let socket;
58
+ if (postgresPort) {
59
+ const stage = join(staging, `.pg-${name.slice(-36)}.${postgresPort}`);
60
+ lane = join(directory, `.pg-${name.slice(-36)}`);
61
+ await mkdir(lane, { mode: 0o755 });
62
+ socket = join(lane, `.s.PGSQL.${postgresPort}`);
63
+ await protectedBind(stage, "socket");
64
+ // Only the vault directory owns the socket name. The inode keeps the listener's identity.
65
+ await rename(stage, socket);
66
+ await protectedBind(socket, "socket");
67
+ }
68
+ const verify = async () => {
69
+ for (const path of [
70
+ join(binds, ".."),
71
+ binds,
72
+ ownerDir,
73
+ directory,
74
+ pkg,
75
+ ...(lane ? [lane] : []),
76
+ ])
77
+ await protectedBind(path, "directory");
78
+ if (socket)
79
+ await protectedBind(socket, "socket");
80
+ };
81
+ return { pkg, socket, verify };
82
+ }
@@ -0,0 +1,85 @@
1
+ export declare const EXTENSION_ENGINE_REQUEST_TIMEOUT_MS = 10000;
2
+ export declare const EXTENSION_ENGINE_CAPACITY_CODE = "extension_sandbox_capacity";
3
+ export type ExtensionEngineCapacityKind = "launches" | "vaults";
4
+ export declare function extensionEngineCapacityMessage(kind: ExtensionEngineCapacityKind, limit: number): string;
5
+ export declare const EXTENSION_ENGINE_API = "/v1.44";
6
+ export declare const EXTENSION_ENGINE_OWNER_HEADER = "x-capybara-extension-owner";
7
+ export declare const ATTACH_QUERY = "stream=true&stdin=true&stdout=true&stderr=true";
8
+ export declare const SANDBOX_PACKAGE_ROOT = "/app/extension";
9
+ export declare const SANDBOX_POSTGRES_DIR = "/run/extension-postgres";
10
+ export declare const SANDBOX_LABEL = "com.capybara.extension-sandbox";
11
+ export declare const OWNER_LABEL = "com.capybara.extension-sandbox.owner";
12
+ export declare const PROXY_OWNER_LABEL = "com.capybara.extension-sandbox.proxy-owner";
13
+ export declare const OWNER_ID: RegExp;
14
+ export declare const CONTAINER_ID: RegExp;
15
+ export declare const SANDBOX_NAME: RegExp;
16
+ export declare const SHA256: RegExp;
17
+ export declare const POSTGRES_SOCKET: RegExp;
18
+ export declare function sandboxBind(source: string, target: string): {
19
+ Type: string;
20
+ Source: string;
21
+ Target: string;
22
+ ReadOnly: boolean;
23
+ BindOptions: {
24
+ NonRecursive: boolean;
25
+ Propagation: string;
26
+ };
27
+ };
28
+ export declare function extensionContainerOptions(image: string, mounts: ReturnType<typeof sandboxBind>[], owner: string): {
29
+ Image: string;
30
+ User: string;
31
+ Hostname: string;
32
+ WorkingDir: string;
33
+ Entrypoint: string[];
34
+ Labels: {
35
+ "com.capybara.extension-sandbox": string;
36
+ "com.capybara.extension-sandbox.owner": string;
37
+ };
38
+ Cmd: never[];
39
+ Env: never[];
40
+ Healthcheck: {
41
+ Test: string[];
42
+ };
43
+ OpenStdin: boolean;
44
+ StdinOnce: boolean;
45
+ AttachStdin: boolean;
46
+ AttachStdout: boolean;
47
+ AttachStderr: boolean;
48
+ Tty: boolean;
49
+ HostConfig: {
50
+ AutoRemove: boolean;
51
+ NetworkMode: string;
52
+ IpcMode: string;
53
+ CgroupnsMode: string;
54
+ ReadonlyRootfs: boolean;
55
+ Privileged: boolean;
56
+ Init: boolean;
57
+ CapDrop: string[];
58
+ SecurityOpt: string[];
59
+ Memory: number;
60
+ MemorySwap: number;
61
+ NanoCpus: number;
62
+ PidsLimit: number;
63
+ Ulimits: {
64
+ Name: string;
65
+ Soft: number;
66
+ Hard: number;
67
+ }[];
68
+ LogConfig: {
69
+ Type: string;
70
+ };
71
+ Tmpfs: {
72
+ "/tmp": string;
73
+ };
74
+ Mounts: {
75
+ Type: string;
76
+ Source: string;
77
+ Target: string;
78
+ ReadOnly: boolean;
79
+ BindOptions: {
80
+ NonRecursive: boolean;
81
+ Propagation: string;
82
+ };
83
+ }[];
84
+ };
85
+ };
@@ -0,0 +1,75 @@
1
+ export const EXTENSION_ENGINE_REQUEST_TIMEOUT_MS = 10_000;
2
+ export const EXTENSION_ENGINE_CAPACITY_CODE = "extension_sandbox_capacity";
3
+ export function extensionEngineCapacityMessage(kind, limit) {
4
+ return kind === "vaults"
5
+ ? `Extension sandbox capacity reached (${limit})`
6
+ : `Concurrent extension sandbox launch capacity reached (${limit})`;
7
+ }
8
+ export const EXTENSION_ENGINE_API = "/v1.44";
9
+ export const EXTENSION_ENGINE_OWNER_HEADER = "x-capybara-extension-owner";
10
+ export const ATTACH_QUERY = "stream=true&stdin=true&stdout=true&stderr=true";
11
+ export const SANDBOX_PACKAGE_ROOT = "/app/extension";
12
+ export const SANDBOX_POSTGRES_DIR = "/run/extension-postgres";
13
+ export const SANDBOX_LABEL = "com.capybara.extension-sandbox";
14
+ export const OWNER_LABEL = "com.capybara.extension-sandbox.owner";
15
+ export const PROXY_OWNER_LABEL = "com.capybara.extension-sandbox.proxy-owner";
16
+ export const OWNER_ID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
17
+ export const CONTAINER_ID = /^[a-f0-9]{64}$/;
18
+ export const SANDBOX_NAME = /^capybara-extension-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
19
+ export const SHA256 = /^sha256:[a-f0-9]{64}$/;
20
+ export const POSTGRES_SOCKET = /^\.s\.PGSQL\.([1-9][0-9]{0,4})$/;
21
+ const MEMORY_BYTES = 192 * 1024 * 1024;
22
+ const NANO_CPUS = 500_000_000;
23
+ const PROCESS_LIMIT = 32;
24
+ const FD_LIMIT = 128;
25
+ const SANDBOX_USER = "10001:10001";
26
+ export function sandboxBind(source, target) {
27
+ return {
28
+ Type: "bind",
29
+ Source: source,
30
+ Target: target,
31
+ ReadOnly: true,
32
+ BindOptions: { NonRecursive: true, Propagation: "rprivate" },
33
+ };
34
+ }
35
+ export function extensionContainerOptions(image, mounts, owner) {
36
+ return {
37
+ Image: image,
38
+ User: SANDBOX_USER,
39
+ Hostname: "extension",
40
+ WorkingDir: SANDBOX_PACKAGE_ROOT,
41
+ Entrypoint: ["/usr/local/bin/node", "/app/sandbox-entry.mjs"],
42
+ Labels: { [SANDBOX_LABEL]: "1", [OWNER_LABEL]: owner },
43
+ Cmd: [],
44
+ Env: [],
45
+ Healthcheck: { Test: ["NONE"] },
46
+ OpenStdin: true,
47
+ StdinOnce: true,
48
+ AttachStdin: true,
49
+ AttachStdout: true,
50
+ AttachStderr: true,
51
+ Tty: false,
52
+ HostConfig: {
53
+ AutoRemove: true,
54
+ NetworkMode: "none",
55
+ IpcMode: "none",
56
+ CgroupnsMode: "private",
57
+ ReadonlyRootfs: true,
58
+ Privileged: false,
59
+ Init: false,
60
+ CapDrop: ["ALL"],
61
+ SecurityOpt: ["no-new-privileges=true", "seccomp=builtin"],
62
+ Memory: MEMORY_BYTES,
63
+ MemorySwap: MEMORY_BYTES,
64
+ NanoCpus: NANO_CPUS,
65
+ PidsLimit: PROCESS_LIMIT,
66
+ Ulimits: [
67
+ { Name: "nofile", Soft: FD_LIMIT, Hard: FD_LIMIT },
68
+ { Name: "core", Soft: 0, Hard: 0 },
69
+ ],
70
+ LogConfig: { Type: "none" },
71
+ Tmpfs: { "/tmp": "rw,noexec,nosuid,nodev,size=16777216,mode=1777" },
72
+ Mounts: mounts,
73
+ },
74
+ };
75
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import { createEngineProxy } from "./engine-proxy.js";
3
+ const { EXTENSION_ENGINE_SOCKET: socket, EXTENSION_ENGINE_SOCKET_GID: socketGroup, EXTENSION_RUNTIME_IMAGE_ID: image, EXTENSION_ENGINE_STATE_DIRECTORY: stateDirectory, } = process.env;
4
+ const gid = Number(socketGroup);
5
+ if (!/^[1-9][0-9]*$/.test(socketGroup ?? "") ||
6
+ !Number.isSafeInteger(gid) ||
7
+ !process.getgroups?.().includes(gid) ||
8
+ process.getuid?.() === 0) {
9
+ throw new Error("The extension Engine guard requires a non-root identity and a non-zero socket group");
10
+ }
11
+ const engineSocket = socket ? await lstat(socket) : undefined;
12
+ if (!socket ||
13
+ !engineSocket?.isSocket() ||
14
+ engineSocket.gid !== gid ||
15
+ !image ||
16
+ !stateDirectory ||
17
+ (await realpath(stateDirectory)) !== stateDirectory) {
18
+ throw new Error("The extension Engine guard requires a socket, immutable image ID and a real staging and bind directory");
19
+ }
20
+ (await createEngineProxy({ socket, image, stateDirectory })).listen(2376);
@@ -0,0 +1,7 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ export interface EngineProxyOptions {
3
+ socket: string;
4
+ image: string;
5
+ stateDirectory: string;
6
+ }
7
+ export declare function createEngineProxy(options: EngineProxyOptions, maxVaults?: number): Promise<import("node:http").Server<typeof IncomingMessage, typeof ServerResponse>>;