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

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 (99) hide show
  1. package/dist/admin/extensions.controller.d.ts +5 -2
  2. package/dist/admin/extensions.controller.js +10 -1
  3. package/dist/admin/extensions.schemas.d.ts +4 -0
  4. package/dist/admin/extensions.schemas.js +9 -0
  5. package/dist/admin/health.service.d.ts +1 -1
  6. package/dist/admin/health.service.js +3 -3
  7. package/dist/catalog/catalog-content.d.ts +5 -7
  8. package/dist/catalog/catalog-items.js +1 -1
  9. package/dist/catalog/catalog-scope.service.js +5 -5
  10. package/dist/catalog/catalog.module.js +5 -4
  11. package/dist/catalog/catalog.service.d.ts +7 -1
  12. package/dist/catalog/catalog.service.js +19 -2
  13. package/dist/catalog/effect-work.d.ts +27 -0
  14. package/dist/catalog/effect-work.js +151 -0
  15. package/dist/catalog/jobs.d.ts +4 -1
  16. package/dist/catalog/jobs.js +14 -4
  17. package/dist/catalog/org-catalog.service.d.ts +2 -0
  18. package/dist/catalog/org-catalog.service.js +68 -12
  19. package/dist/catalog/org-intent.d.ts +4 -2
  20. package/dist/catalog/org-intent.js +25 -4
  21. package/dist/catalog/owned-items.d.ts +5 -1
  22. package/dist/catalog/owned-items.js +18 -3
  23. package/dist/catalog/plugin-import.d.ts +4 -2
  24. package/dist/catalog/plugin-import.js +10 -5
  25. package/dist/catalog/plugin-install.d.ts +17 -51
  26. package/dist/catalog/plugin-install.js +209 -235
  27. package/dist/catalog/plugin-upgrade.d.ts +8 -3
  28. package/dist/catalog/plugin-upgrade.js +63 -34
  29. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  30. package/dist/catalog/scope-sync-workers.js +10 -26
  31. package/dist/catalog/scope-sync.d.ts +19 -114
  32. package/dist/catalog/scope-sync.js +220 -239
  33. package/dist/catalog/scope-writer.d.ts +10 -1
  34. package/dist/catalog/scope-writer.js +62 -4
  35. package/dist/catalog/template-connector-ensure.js +1 -1
  36. package/dist/catalog/unshare.js +1 -2
  37. package/dist/config/schema.d.ts +1 -1
  38. package/dist/config/schema.js +7 -4
  39. package/dist/db/kernel-schema.d.ts +21 -5
  40. package/dist/erasure/org-catalog.js +2 -2
  41. package/dist/erasure/org-rules.js +2 -0
  42. package/dist/extensions/admin-ops.d.ts +1 -1
  43. package/dist/extensions/admin-ops.js +1 -1
  44. package/dist/extensions/admin-view.d.ts +4 -1
  45. package/dist/extensions/admin-view.js +27 -11
  46. package/dist/extensions/bootstrap.d.ts +1 -1
  47. package/dist/extensions/bootstrap.js +2 -3
  48. package/dist/extensions/enabled.d.ts +160 -0
  49. package/dist/extensions/enabled.js +7 -0
  50. package/dist/extensions/host.d.ts +1 -0
  51. package/dist/extensions/host.js +5 -2
  52. package/dist/extensions/isolated/authorization.d.ts +8 -0
  53. package/dist/extensions/isolated/authorization.js +56 -11
  54. package/dist/extensions/isolated/broker.js +30 -11
  55. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  56. package/dist/extensions/isolated/engine-binds.js +82 -0
  57. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  58. package/dist/extensions/isolated/engine-policy.js +75 -0
  59. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  60. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  61. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  62. package/dist/extensions/isolated/engine-proxy.js +408 -0
  63. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  64. package/dist/extensions/isolated/engine-vaults.js +93 -0
  65. package/dist/extensions/isolated/lanes.d.ts +11 -3
  66. package/dist/extensions/isolated/lanes.js +43 -16
  67. package/dist/extensions/isolated/postgres-gate.d.ts +1 -0
  68. package/dist/extensions/isolated/postgres-gate.js +6 -6
  69. package/dist/extensions/isolated/revision.d.ts +1 -1
  70. package/dist/extensions/isolated/revision.js +3 -2
  71. package/dist/extensions/isolated/sandbox.d.ts +10 -6
  72. package/dist/extensions/isolated/sandbox.js +101 -117
  73. package/dist/extensions/lifecycle-topics.d.ts +1 -0
  74. package/dist/extensions/lifecycle-topics.js +1 -0
  75. package/dist/extensions/lifecycle.js +23 -2
  76. package/dist/extensions/permission-view.d.ts +6 -1
  77. package/dist/inbox/platform-inbox.service.js +16 -27
  78. package/dist/infra/events/kernel-events.d.ts +4 -0
  79. package/dist/infra/outbox/registry.d.ts +3 -36
  80. package/dist/infra/outbox/registry.js +4 -49
  81. package/dist/infra/queue/queue-names.d.ts +1 -1
  82. package/dist/infra/queue/queue-names.js +1 -1
  83. package/dist/orgs/org-lock.d.ts +3 -1
  84. package/dist/orgs/org-lock.js +3 -1
  85. package/dist/orgs/orgs.service.d.ts +3 -1
  86. package/dist/orgs/orgs.service.js +15 -8
  87. package/dist/overrides.d.ts +0 -3
  88. package/dist/overrides.js +0 -2
  89. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  90. package/dist/platform/ops/org-plugins.ops.js +5 -2
  91. package/dist/platform/ops/plugins.ops.js +11 -10
  92. package/dist/tools/registry.d.ts +1 -1
  93. package/dist/tools/registry.js +6 -2
  94. package/package.json +2 -2
  95. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  96. package/dist/catalog/install-status.d.ts +0 -5
  97. package/dist/catalog/install-status.js +0 -5
  98. package/dist/catalog/scope-jobs.d.ts +0 -59
  99. package/dist/catalog/scope-jobs.js +0 -78
@@ -0,0 +1,408 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createServer, request } from "node:http";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { stageBinds } from "./engine-binds.js";
6
+ import { ATTACH_QUERY, CONTAINER_ID, EXTENSION_ENGINE_API, EXTENSION_ENGINE_CAPACITY_CODE, EXTENSION_ENGINE_OWNER_HEADER, EXTENSION_ENGINE_REQUEST_TIMEOUT_MS, extensionContainerOptions, extensionEngineCapacityMessage, OWNER_ID, OWNER_LABEL, PROXY_OWNER_LABEL, SANDBOX_LABEL, SANDBOX_NAME, SANDBOX_PACKAGE_ROOT, SANDBOX_POSTGRES_DIR, SHA256, sandboxBind, } from "./engine-policy.js";
7
+ import { EngineVaults, MAX_ENGINE_VAULTS } from "./engine-vaults.js";
8
+ const MAX_CONCURRENT_LAUNCHES = 2;
9
+ const MAX_BODY = 16 * 1024;
10
+ const MAX_RESPONSE = 256 * 1024;
11
+ const MAX_INVENTORY_RESPONSE = 4 * 1024 * 1024;
12
+ const LIST_QUERY = new URLSearchParams({
13
+ all: "true",
14
+ filters: JSON.stringify({ label: [`${SANDBOX_LABEL}=1`], status: ["exited", "dead"] }),
15
+ }).toString();
16
+ const INVENTORY_QUERY = new URLSearchParams({
17
+ all: "true",
18
+ filters: JSON.stringify({ label: [`${SANDBOX_LABEL}=1`] }),
19
+ }).toString();
20
+ class Refused extends Error {
21
+ }
22
+ function refuse() {
23
+ throw new Refused("Engine request refused");
24
+ }
25
+ function ownerHash(req) {
26
+ const secret = req.headers[EXTENSION_ENGINE_OWNER_HEADER];
27
+ if (typeof secret !== "string" || !CONTAINER_ID.test(secret))
28
+ refuse();
29
+ return createHash("sha256").update(secret).digest("hex");
30
+ }
31
+ function requestPath(req) {
32
+ if (!req.url?.startsWith(`${EXTENSION_ENGINE_API}/`))
33
+ refuse();
34
+ return req.url.slice(EXTENSION_ENGINE_API.length);
35
+ }
36
+ async function bodyBytes(stream, limit) {
37
+ const chunks = [];
38
+ let size = 0;
39
+ for await (const chunk of stream) {
40
+ size += chunk.length;
41
+ if (size > limit)
42
+ refuse();
43
+ chunks.push(chunk);
44
+ }
45
+ return Buffer.concat(chunks);
46
+ }
47
+ function hasBody(req) {
48
+ return (req.headers["transfer-encoding"] !== undefined ||
49
+ (req.headers["content-length"] !== undefined && req.headers["content-length"] !== "0"));
50
+ }
51
+ async function launchBody(req) {
52
+ const length = req.headers["content-length"];
53
+ if (req.headers["content-type"] !== "application/json" ||
54
+ req.headers["transfer-encoding"] !== undefined ||
55
+ typeof length !== "string" ||
56
+ !/^[1-9][0-9]*$/.test(length) ||
57
+ Number(length) > MAX_BODY)
58
+ refuse();
59
+ try {
60
+ const text = (await bodyBytes(req, MAX_BODY)).toString("utf8");
61
+ const raw = JSON.parse(text);
62
+ const { digest, incarnation, postgresPort } = raw;
63
+ if (text !== JSON.stringify(raw) ||
64
+ typeof digest !== "string" ||
65
+ !CONTAINER_ID.test(digest) ||
66
+ typeof incarnation !== "string" ||
67
+ !OWNER_ID.test(incarnation) ||
68
+ (postgresPort !== undefined &&
69
+ (typeof postgresPort !== "string" ||
70
+ !/^[1-9][0-9]{0,4}$/.test(postgresPort) ||
71
+ Number(postgresPort) > 65535)) ||
72
+ !isDeepStrictEqual(raw, { digest, incarnation, ...(postgresPort && { postgresPort }) }))
73
+ refuse();
74
+ return { digest, incarnation, postgresPort };
75
+ }
76
+ catch {
77
+ refuse();
78
+ }
79
+ }
80
+ async function launch(options, req, owner, name, state) {
81
+ const { digest, incarnation, postgresPort } = await launchBody(req);
82
+ const prepared = await stageBinds(join(options.stateDirectory, "stage"), join(options.stateDirectory, "binds"), name, owner, digest, postgresPort, () => {
83
+ state.createdVault = true;
84
+ }).catch(() => refuse());
85
+ const mounts = [sandboxBind(prepared.pkg, SANDBOX_PACKAGE_ROOT)];
86
+ if (prepared.socket)
87
+ mounts.push(sandboxBind(prepared.socket, `${SANDBOX_POSTGRES_DIR}/.s.PGSQL.${postgresPort}`));
88
+ const container = extensionContainerOptions(options.image, mounts, incarnation);
89
+ await prepared.verify();
90
+ state.attempted = true;
91
+ const created = await docker(options, "POST", `/containers/create?name=${name}`, {
92
+ ...container,
93
+ Labels: { ...container.Labels, [PROXY_OWNER_LABEL]: owner },
94
+ });
95
+ if (created.status !== 201)
96
+ throw new Error("Engine create failed");
97
+ const { Id, Warnings } = JSON.parse(created.data.toString("utf8"));
98
+ if (!CONTAINER_ID.test(Id ?? "") || Warnings?.length)
99
+ throw new Error("Engine did not confirm isolated resources");
100
+ await prepared.verify();
101
+ const started = await docker(options, "POST", `/containers/${Id}/start`);
102
+ if (started.status !== 204)
103
+ throw new Error("Engine start failed");
104
+ return { status: 201, data: Buffer.from(JSON.stringify({ Id })) };
105
+ }
106
+ function docker(options, method, path, json, responseLimit = MAX_RESPONSE) {
107
+ const body = json === undefined ? undefined : Buffer.from(JSON.stringify(json));
108
+ return new Promise((resolve, reject) => {
109
+ const req = request({
110
+ socketPath: options.socket,
111
+ path: `${EXTENSION_ENGINE_API}${path}`,
112
+ method,
113
+ agent: false,
114
+ signal: AbortSignal.timeout(EXTENSION_ENGINE_REQUEST_TIMEOUT_MS),
115
+ ...(body && {
116
+ headers: { "Content-Type": "application/json", "Content-Length": body.length },
117
+ }),
118
+ }, async (res) => {
119
+ try {
120
+ const status = res.statusCode ?? 502;
121
+ resolve({ status, data: await bodyBytes(res, responseLimit) });
122
+ }
123
+ catch (error) {
124
+ reject(error);
125
+ }
126
+ });
127
+ req.on("error", reject);
128
+ req.end(body);
129
+ });
130
+ }
131
+ async function inspect(options, target) {
132
+ const response = await docker(options, "GET", `/containers/${target}/json`);
133
+ if (response.status === 404)
134
+ return undefined;
135
+ if (response.status !== 200)
136
+ throw new Error("Unable to verify sandbox");
137
+ const found = JSON.parse(response.data.toString("utf8"));
138
+ const labels = found?.Config?.Labels;
139
+ const owner = labels?.[PROXY_OWNER_LABEL];
140
+ if (!found?.Id ||
141
+ !CONTAINER_ID.test(found.Id) ||
142
+ !found.Name ||
143
+ !SANDBOX_NAME.test(found.Name.slice(1)) ||
144
+ found.Name[0] !== "/" ||
145
+ (CONTAINER_ID.test(target) ? found.Id !== target : found.Name !== `/${target}`) ||
146
+ found.Image !== options.image ||
147
+ labels?.[SANDBOX_LABEL] !== "1" ||
148
+ !OWNER_ID.test(labels[OWNER_LABEL] ?? "") ||
149
+ !owner ||
150
+ !CONTAINER_ID.test(owner))
151
+ refuse();
152
+ return {
153
+ id: found.Id,
154
+ name: found.Name.slice(1),
155
+ owner,
156
+ state: found.State?.Status,
157
+ };
158
+ }
159
+ function finish(res, outcome) {
160
+ res.writeHead(outcome.status, { "Content-Type": "application/json" });
161
+ res.end(outcome.status < 400 ? outcome.data : undefined);
162
+ }
163
+ async function listTerminal(options, path) {
164
+ const response = await docker(options, "GET", path, undefined, MAX_INVENTORY_RESPONSE);
165
+ if (response.status !== 200)
166
+ return response;
167
+ const all = JSON.parse(response.data.toString("utf8"));
168
+ const matching = all.filter((row) => CONTAINER_ID.test(row.Id ?? "") &&
169
+ row.ImageID === options.image &&
170
+ row.Names?.some((name) => name.startsWith("/") && SANDBOX_NAME.test(name.slice(1))) &&
171
+ row.Labels?.[SANDBOX_LABEL] === "1" &&
172
+ OWNER_ID.test(row.Labels[OWNER_LABEL] ?? "") &&
173
+ CONTAINER_ID.test(row.Labels[PROXY_OWNER_LABEL] ?? "") &&
174
+ (row.State === "exited" || row.State === "dead"));
175
+ const terminal = matching.map(({ Id, State, Labels }) => ({
176
+ Id,
177
+ State,
178
+ Labels: { [SANDBOX_LABEL]: "1", [OWNER_LABEL]: Labels?.[OWNER_LABEL] },
179
+ }));
180
+ return { status: response.status, data: Buffer.from(JSON.stringify(terminal)) };
181
+ }
182
+ async function startupInventory(options) {
183
+ try {
184
+ const result = await docker(options, "GET", `/containers/json?${INVENTORY_QUERY}`, undefined, MAX_INVENTORY_RESPONSE);
185
+ if (result.status !== 200)
186
+ throw new Error();
187
+ const rows = JSON.parse(result.data.toString("utf8"));
188
+ if (!Array.isArray(rows))
189
+ throw new Error();
190
+ const names = new Set();
191
+ for (const row of rows) {
192
+ if (!Array.isArray(row?.Names) || row.Names.some((name) => typeof name !== "string"))
193
+ throw new Error();
194
+ for (const name of row.Names) {
195
+ if (name.startsWith("/") && SANDBOX_NAME.test(name.slice(1)))
196
+ names.add(name.slice(1));
197
+ }
198
+ }
199
+ return names;
200
+ }
201
+ catch (cause) {
202
+ throw new Error("The extension Engine guard could not verify its startup inventory", { cause });
203
+ }
204
+ }
205
+ const INFO_FIELDS = [
206
+ "OSType",
207
+ "CgroupDriver",
208
+ "CgroupVersion",
209
+ "SecurityOptions",
210
+ "CpuCfsQuota",
211
+ "CpuCfsPeriod",
212
+ "MemoryLimit",
213
+ "SwapLimit",
214
+ "PidsLimit",
215
+ ];
216
+ function writeCapacity(res, kind, limit) {
217
+ res.writeHead(503, { "Content-Type": "application/json", Connection: "close" }).end(JSON.stringify({
218
+ code: EXTENSION_ENGINE_CAPACITY_CODE,
219
+ kind,
220
+ limit,
221
+ message: extensionEngineCapacityMessage(kind, limit),
222
+ }));
223
+ }
224
+ async function removeContainer(options, launching, removing, vaults, target, operation, owner, res) {
225
+ const name = SANDBOX_NAME.test(target) ? target : (await inspect(options, target))?.name;
226
+ if (!name) {
227
+ res.writeHead(404).end();
228
+ return;
229
+ }
230
+ if (launching.has(name) || removing.has(name)) {
231
+ res.writeHead(409).end();
232
+ return;
233
+ }
234
+ removing.add(name);
235
+ try {
236
+ // Inspect inside the lock so an old ID cannot authorize removal of a new name's vault.
237
+ const found = await inspect(options, target);
238
+ if (!found) {
239
+ if (target === name)
240
+ await vaults.remove(vaults.path(owner, name));
241
+ res.writeHead(404).end();
242
+ return;
243
+ }
244
+ const terminal = found.state === "exited" || found.state === "dead";
245
+ if (operation === "?v=true" ? !terminal : found.owner !== owner)
246
+ refuse();
247
+ const removed = await docker(options, "DELETE", `/containers/${found.id}${operation}`);
248
+ if (removed.status === 204 || removed.status === 404)
249
+ await vaults.remove(vaults.path(found.owner, name));
250
+ finish(res, removed);
251
+ }
252
+ finally {
253
+ removing.delete(name);
254
+ }
255
+ }
256
+ async function dispatch(options, launching, removing, vaults, req, res) {
257
+ const owner = ownerHash(req);
258
+ const path = requestPath(req);
259
+ const method = req.method;
260
+ const createPrefix = "/containers/create?name=";
261
+ if (method === "POST" &&
262
+ path.startsWith(createPrefix) &&
263
+ SANDBOX_NAME.test(path.slice(createPrefix.length))) {
264
+ const name = path.slice(createPrefix.length);
265
+ if (launching.has(name) || removing.has(name)) {
266
+ res.writeHead(409).end();
267
+ return;
268
+ }
269
+ const vault = vaults.path(owner, name);
270
+ const admission = vaults.reserve(vault);
271
+ if (admission === "held") {
272
+ res.writeHead(409).end();
273
+ return;
274
+ }
275
+ if (admission === "full") {
276
+ writeCapacity(res, "vaults", vaults.limit);
277
+ return;
278
+ }
279
+ if (launching.size >= MAX_CONCURRENT_LAUNCHES) {
280
+ vaults.release(vault);
281
+ writeCapacity(res, "launches", MAX_CONCURRENT_LAUNCHES);
282
+ return;
283
+ }
284
+ launching.add(name);
285
+ const state = { createdVault: false, attempted: false };
286
+ const outcome = await launch(options, req, owner, name, state).finally(async () => {
287
+ try {
288
+ if (!state.attempted) {
289
+ if (state.createdVault)
290
+ await vaults.remove(vault);
291
+ else
292
+ vaults.release(vault);
293
+ }
294
+ }
295
+ finally {
296
+ launching.delete(name);
297
+ }
298
+ });
299
+ finish(res, outcome);
300
+ return;
301
+ }
302
+ if (hasBody(req))
303
+ refuse();
304
+ if (method === "GET" && path === "/info") {
305
+ const result = await docker(options, method, path);
306
+ if (result.status !== 200)
307
+ finish(res, result);
308
+ else {
309
+ const info = JSON.parse(result.data.toString("utf8"));
310
+ const data = Buffer.from(JSON.stringify(Object.fromEntries(INFO_FIELDS.map((key) => [key, info[key]]))));
311
+ finish(res, { status: 200, data });
312
+ }
313
+ return;
314
+ }
315
+ if (method === "GET" && path === `/images/${encodeURIComponent(options.image)}/json`) {
316
+ finish(res, await docker(options, method, path));
317
+ return;
318
+ }
319
+ if (method === "GET" && path === `/containers/json?${LIST_QUERY}`) {
320
+ finish(res, await listTerminal(options, path));
321
+ return;
322
+ }
323
+ const match = /^\/containers\/([^/?]+)(\S*)$/.exec(path);
324
+ const target = match?.[1];
325
+ const operation = match?.[2];
326
+ if (!target || (!CONTAINER_ID.test(target) && !SANDBOX_NAME.test(target)))
327
+ refuse();
328
+ const ownedDelete = method === "DELETE" && operation === "?force=true&v=true";
329
+ const cleanTerminal = method === "DELETE" && CONTAINER_ID.test(target) && operation === "?v=true";
330
+ if (!ownedDelete && !cleanTerminal)
331
+ refuse();
332
+ await removeContainer(options, launching, removing, vaults, target, operation, owner, res);
333
+ }
334
+ async function attach(options, req, client, head) {
335
+ const owner = ownerHash(req);
336
+ const path = requestPath(req);
337
+ const match = /^\/containers\/([a-f0-9]{64})\/attach\?(.*)$/.exec(path);
338
+ const id = match?.[1];
339
+ if (req.method !== "POST" ||
340
+ hasBody(req) ||
341
+ !id ||
342
+ match?.[2] !== ATTACH_QUERY ||
343
+ req.headers.upgrade?.toLowerCase() !== "tcp")
344
+ refuse();
345
+ const found = await inspect(options, id);
346
+ if (!found || found.owner !== owner)
347
+ refuse();
348
+ if (client.destroyed)
349
+ return;
350
+ const upstream = request({
351
+ socketPath: options.socket,
352
+ path: `${EXTENSION_ENGINE_API}/containers/${found.id}/attach?${ATTACH_QUERY}`,
353
+ method: "POST",
354
+ agent: false,
355
+ headers: { Connection: "Upgrade", Upgrade: "tcp" },
356
+ });
357
+ const fail = () => client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
358
+ client.once("close", () => upstream.destroy());
359
+ upstream.on("error", fail);
360
+ upstream.setTimeout(EXTENSION_ENGINE_REQUEST_TIMEOUT_MS, () => upstream.destroy(new Error("Engine attach timed out")));
361
+ upstream.once("response", (res) => {
362
+ res.destroy();
363
+ fail();
364
+ });
365
+ upstream.once("upgrade", (res, stream, initial) => {
366
+ if (client.destroyed ||
367
+ res.statusCode !== 101 ||
368
+ res.headers.upgrade?.toLowerCase() !== "tcp") {
369
+ stream.destroy();
370
+ fail();
371
+ return;
372
+ }
373
+ stream.setTimeout(0);
374
+ stream.on("error", () => client.destroy());
375
+ stream.once("close", () => client.end());
376
+ client.once("close", () => stream.destroy());
377
+ client.write("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n");
378
+ if (initial.length)
379
+ client.write(initial);
380
+ if (head.length)
381
+ stream.write(head);
382
+ client.pipe(stream).pipe(client);
383
+ });
384
+ upstream.end();
385
+ }
386
+ export async function createEngineProxy(options, maxVaults = MAX_ENGINE_VAULTS) {
387
+ if (!SHA256.test(options.image) ||
388
+ ![options.socket, options.stateDirectory].every((path) => isAbsolute(path) && path !== "/"))
389
+ throw new Error("Invalid Engine proxy settings");
390
+ const vaults = new EngineVaults(options.stateDirectory, maxVaults);
391
+ await vaults.recover(await startupInventory(options));
392
+ const launching = new Set();
393
+ const removing = new Set();
394
+ const server = createServer({ requestTimeout: EXTENSION_ENGINE_REQUEST_TIMEOUT_MS, maxHeaderSize: 4096 }, (req, res) => {
395
+ void dispatch(options, launching, removing, vaults, req, res).catch((error) => {
396
+ if (!res.headersSent)
397
+ res.writeHead(error instanceof Refused ? 403 : 502, { Connection: "close" }).end();
398
+ });
399
+ });
400
+ server.maxRequestsPerSocket = 1;
401
+ server.on("upgrade", (req, stream, head) => {
402
+ stream.on("error", () => stream.destroy());
403
+ void attach(options, req, stream, head).catch(() => {
404
+ stream.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
405
+ });
406
+ });
407
+ return server;
408
+ }
@@ -0,0 +1,12 @@
1
+ export declare const MAX_ENGINE_VAULTS = 256;
2
+ export declare class EngineVaults {
3
+ private readonly stateDirectory;
4
+ readonly limit: number;
5
+ private readonly held;
6
+ constructor(stateDirectory: string, limit: number);
7
+ path(owner: string, name: string): string;
8
+ reserve(path: string): "held" | "full" | "reserved";
9
+ release(path: string): void;
10
+ remove(path: string): Promise<void>;
11
+ recover(engineNames: ReadonlySet<string>): Promise<void>;
12
+ }
@@ -0,0 +1,93 @@
1
+ import { lstat, readdir, rm, rmdir, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { protectedBind, protectedStage } from "./engine-binds.js";
4
+ import { CONTAINER_ID, EXTENSION_ENGINE_REQUEST_TIMEOUT_MS, SANDBOX_NAME, } from "./engine-policy.js";
5
+ const RECENT_VAULT_MS = 2 * EXTENSION_ENGINE_REQUEST_TIMEOUT_MS;
6
+ const STAGED_ARCHIVE_MAX_AGE_MS = 60 * 60 * 1000;
7
+ export const MAX_ENGINE_VAULTS = 256;
8
+ function unlessMissing(error) {
9
+ if (error.code !== "ENOENT")
10
+ throw error;
11
+ return undefined;
12
+ }
13
+ export class EngineVaults {
14
+ stateDirectory;
15
+ limit;
16
+ held = new Set();
17
+ constructor(stateDirectory, limit) {
18
+ this.stateDirectory = stateDirectory;
19
+ this.limit = limit;
20
+ }
21
+ path(owner, name) {
22
+ return join(this.stateDirectory, "binds", owner, name);
23
+ }
24
+ reserve(path) {
25
+ if (this.held.has(path))
26
+ return "held";
27
+ if (this.held.size >= this.limit)
28
+ return "full";
29
+ this.held.add(path);
30
+ return "reserved";
31
+ }
32
+ release(path) {
33
+ this.held.delete(path);
34
+ }
35
+ async remove(path) {
36
+ await rm(path, { recursive: true, force: true });
37
+ this.release(path);
38
+ }
39
+ async recover(engineNames) {
40
+ const root = join(this.stateDirectory, "binds");
41
+ await protectedBind(this.stateDirectory, "directory");
42
+ await protectedBind(root, "directory");
43
+ const staging = join(this.stateDirectory, "stage");
44
+ await protectedStage(staging);
45
+ const now = Date.now();
46
+ const abandoned = [];
47
+ const ownerDirectories = [];
48
+ for (const owner of await readdir(root)) {
49
+ if (!CONTAINER_ID.test(owner))
50
+ continue;
51
+ const directory = join(root, owner);
52
+ await protectedBind(directory, "directory");
53
+ ownerDirectories.push(directory);
54
+ for (const name of await readdir(directory)) {
55
+ if (!SANDBOX_NAME.test(name))
56
+ continue;
57
+ const path = this.path(owner, name);
58
+ const stat = await protectedBind(path, "directory");
59
+ // A name in the inventory or a recent create may still need its bind sources.
60
+ if (engineNames.has(name) || stat.mtimeMs >= now - RECENT_VAULT_MS)
61
+ this.held.add(path);
62
+ else
63
+ abandoned.push(path);
64
+ }
65
+ }
66
+ const expired = [];
67
+ for (const name of await readdir(staging)) {
68
+ if (!name.endsWith(".tgz"))
69
+ continue;
70
+ const sandbox = name.slice(0, -4);
71
+ if (!SANDBOX_NAME.test(sandbox))
72
+ continue;
73
+ const path = join(staging, name);
74
+ const stat = await lstat(path).catch(unlessMissing);
75
+ if (!stat)
76
+ continue;
77
+ if (!stat.isFile() || stat.nlink !== 1)
78
+ throw new Error("Unsafe staged extension archive");
79
+ if (!engineNames.has(sandbox) && stat.mtimeMs < now - STAGED_ARCHIVE_MAX_AGE_MS)
80
+ expired.push(path);
81
+ }
82
+ for (const path of abandoned)
83
+ await this.remove(path);
84
+ for (const directory of ownerDirectories) {
85
+ await rmdir(directory).catch((error) => {
86
+ if (error.code !== "ENOTEMPTY")
87
+ throw error;
88
+ });
89
+ }
90
+ for (const path of expired)
91
+ await unlink(path).catch(unlessMissing);
92
+ }
93
+ }
@@ -15,7 +15,7 @@ export interface Invocation {
15
15
  }
16
16
  export type BrokerCall = (method: string, args: unknown[], invocation: Invocation, signal: AbortSignal) => Promise<unknown>;
17
17
  export interface IsolatedLaneOptions {
18
- sandbox: Omit<ExtensionSandboxOptions, "signal">;
18
+ sandbox: Omit<ExtensionSandboxOptions, "signal" | "stagingDir" | "sandboxId">;
19
19
  entry: string;
20
20
  manifest: StaticExtensionManifest;
21
21
  configSchemas?: unknown;
@@ -41,6 +41,13 @@ interface ProcessIngress {
41
41
  interface ProcessLease extends ProcessIngress {
42
42
  release(): void;
43
43
  }
44
+ interface PendingRemoval {
45
+ remove(): Promise<void>;
46
+ release(): void;
47
+ delay: number;
48
+ timer?: ReturnType<typeof setTimeout> | undefined;
49
+ running: boolean;
50
+ }
44
51
  export declare class IsolatedExtensionQuota {
45
52
  private readonly processes;
46
53
  private calls;
@@ -49,8 +56,11 @@ export declare class IsolatedExtensionQuota {
49
56
  private readonly starts;
50
57
  private readonly retryTimers;
51
58
  private readonly available;
59
+ private readonly removals;
52
60
  private readonly crashes;
53
61
  watch(listener: () => void): () => void;
62
+ retryRemoval(remove: PendingRemoval["remove"], release: ProcessLease["release"]): void;
63
+ private scheduleRemoval;
54
64
  atCapacity(kind: ProcessKind): boolean;
55
65
  process(kind: ProcessKind): ProcessLease | undefined;
56
66
  call(): () => void;
@@ -64,7 +74,6 @@ export declare class IsolatedLanes {
64
74
  private readonly options;
65
75
  private readonly shutdown;
66
76
  private readonly lifetime;
67
- private readonly unwatch;
68
77
  private readonly lanes;
69
78
  private readonly waiting;
70
79
  private readonly waitingControl;
@@ -91,7 +100,6 @@ export declare class IsolatedLanes {
91
100
  private openControl;
92
101
  private removeControl;
93
102
  private admitControl;
94
- private retryRemoval;
95
103
  private start;
96
104
  /** Stop the admitted processes and PostgreSQL gates while their grant is revoked. */
97
105
  revokeOrg(orgId?: string): void;
@@ -56,13 +56,47 @@ export class IsolatedExtensionQuota {
56
56
  };
57
57
  retryTimers = {};
58
58
  available = new Set();
59
+ removals = new Set();
59
60
  crashes = new Map();
60
61
  watch(listener) {
61
62
  this.available.add(listener);
63
+ for (const removal of this.removals)
64
+ this.scheduleRemoval(removal);
62
65
  return () => {
63
66
  this.available.delete(listener);
67
+ if (this.available.size !== 0)
68
+ return;
69
+ for (const removal of this.removals) {
70
+ clearTimeout(removal.timer);
71
+ removal.timer = undefined;
72
+ }
64
73
  };
65
74
  }
75
+ retryRemoval(remove, release) {
76
+ // Retain the process charge across revisions. Retry only while a live supervisor can use it.
77
+ const removal = { remove, release, delay: CLEANUP_RETRY_MS, running: false };
78
+ this.removals.add(removal);
79
+ this.scheduleRemoval(removal);
80
+ }
81
+ scheduleRemoval(removal) {
82
+ if (this.available.size === 0 || removal.running || removal.timer)
83
+ return;
84
+ removal.timer = setTimeout(() => {
85
+ removal.timer = undefined;
86
+ removal.running = true;
87
+ void Promise.resolve()
88
+ .then(removal.remove)
89
+ .then(() => {
90
+ this.removals.delete(removal);
91
+ removal.release();
92
+ }, () => {
93
+ removal.running = false;
94
+ removal.delay = Math.min(removal.delay * 2, MAX_CLEANUP_RETRY_MS);
95
+ this.scheduleRemoval(removal);
96
+ });
97
+ }, removal.delay);
98
+ removal.timer.unref();
99
+ }
66
100
  atCapacity(kind) {
67
101
  return this.processes[kind] >= PROCESS_LIMITS[kind];
68
102
  }
@@ -176,7 +210,6 @@ export class IsolatedLanes {
176
210
  options;
177
211
  shutdown = new AbortController();
178
212
  lifetime;
179
- unwatch;
180
213
  lanes = new Map();
181
214
  waiting = new Map();
182
215
  waitingControl = [];
@@ -189,7 +222,10 @@ export class IsolatedLanes {
189
222
  constructor(options) {
190
223
  this.options = options;
191
224
  this.lifetime = AbortSignal.any([options.signal, this.shutdown.signal]);
192
- this.unwatch = options.quota.watch(() => this.schedule());
225
+ if (!this.lifetime.aborted) {
226
+ const unwatch = options.quota.watch(() => this.schedule());
227
+ this.lifetime.addEventListener("abort", unwatch, { once: true });
228
+ }
193
229
  }
194
230
  async register() {
195
231
  const lane = await this.openControl("registration");
@@ -487,17 +523,6 @@ export class IsolatedLanes {
487
523
  this.control = { orgId, stop, opening };
488
524
  admission.resolve(opening);
489
525
  }
490
- retryRemoval(remove, release, delay = CLEANUP_RETRY_MS) {
491
- // Keep the slot charged until the Engine confirms removal, even across a revision replacement.
492
- const retry = setTimeout(() => {
493
- void Promise.resolve()
494
- .then(remove)
495
- .then(release, () => {
496
- this.retryRemoval(remove, release, Math.min(delay * 2, MAX_CLEANUP_RETRY_MS));
497
- });
498
- }, delay);
499
- retry.unref();
500
- }
501
526
  async start(mode, orgId, end, admission, retiring, removed, lease) {
502
527
  const kind = mode === "registration" || mode === "setupCheck" ? "control" : "serving";
503
528
  const nonce = randomUUID();
@@ -534,6 +559,7 @@ export class IsolatedLanes {
534
559
  throw new IsolatedRpcError("refused");
535
560
  gate = await startPostgresGate({
536
561
  directory: this.options.socketDir,
562
+ sandboxId: nonce,
537
563
  upstreamSocket: postgresSocket,
538
564
  login: this.options.credential.login,
539
565
  database: this.options.credential.database,
@@ -542,6 +568,8 @@ export class IsolatedLanes {
542
568
  }
543
569
  const sandbox = await startExtensionSandbox({
544
570
  ...sandboxOptions,
571
+ stagingDir: this.options.socketDir,
572
+ sandboxId: nonce,
545
573
  ...(gate && { postgresSocket: gate.socket }),
546
574
  signal: admission,
547
575
  });
@@ -596,7 +624,7 @@ export class IsolatedLanes {
596
624
  catch {
597
625
  this.options.cleanupFault();
598
626
  await closeGate;
599
- this.retryRemoval(() => sandbox.close(), lease.release);
627
+ this.options.quota.retryRemoval(() => sandbox.close(), lease.release);
600
628
  }
601
629
  removed();
602
630
  });
@@ -639,7 +667,7 @@ export class IsolatedLanes {
639
667
  await gate?.close().catch(() => this.options.cleanupFault());
640
668
  if (error instanceof ExtensionSandboxUnconfirmedCleanupError) {
641
669
  this.options.cleanupFault();
642
- this.retryRemoval(error.retryRemove, lease.release);
670
+ this.options.quota.retryRemoval(error.retryRemove, lease.release);
643
671
  }
644
672
  else {
645
673
  lease.release();
@@ -678,7 +706,6 @@ export class IsolatedLanes {
678
706
  }
679
707
  async close() {
680
708
  this.shutdown.abort();
681
- this.unwatch();
682
709
  for (const queue of this.waiting.values()) {
683
710
  for (const admission of queue) {
684
711
  admission.cleanup();