@capybara-hq/kernel 0.1.0-rc.136 → 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 (203) hide show
  1. package/dist/admin/audit-log.service.d.ts +96 -12
  2. package/dist/admin/audit-log.service.js +508 -44
  3. package/dist/admin/audit-targets.d.ts +17 -0
  4. package/dist/admin/audit-targets.js +84 -0
  5. package/dist/admin/audit.controller.d.ts +12 -9
  6. package/dist/admin/audit.controller.js +29 -8
  7. package/dist/admin/audit.schemas.d.ts +20 -4
  8. package/dist/admin/audit.schemas.js +42 -17
  9. package/dist/admin/extensions.controller.d.ts +5 -2
  10. package/dist/admin/extensions.controller.js +10 -1
  11. package/dist/admin/extensions.schemas.d.ts +4 -0
  12. package/dist/admin/extensions.schemas.js +9 -0
  13. package/dist/admin/health.service.d.ts +1 -1
  14. package/dist/admin/health.service.js +3 -3
  15. package/dist/agents/templates.js +3 -10
  16. package/dist/app.d.ts +3 -1
  17. package/dist/app.js +1 -0
  18. package/dist/automations/automations.service.js +4 -5
  19. package/dist/catalog/catalog-content.d.ts +6 -8
  20. package/dist/catalog/catalog-content.js +17 -22
  21. package/dist/catalog/catalog-items.d.ts +5 -10
  22. package/dist/catalog/catalog-items.js +27 -51
  23. package/dist/catalog/catalog-scope.service.d.ts +4 -2
  24. package/dist/catalog/catalog-scope.service.js +109 -145
  25. package/dist/catalog/catalog.module.js +7 -4
  26. package/dist/catalog/catalog.service.d.ts +10 -4
  27. package/dist/catalog/catalog.service.js +52 -10
  28. package/dist/catalog/cli.js +17 -0
  29. package/dist/catalog/component-promotion.js +8 -4
  30. package/dist/catalog/component-scope.service.d.ts +3 -1
  31. package/dist/catalog/component-scope.service.js +101 -140
  32. package/dist/catalog/component-state.d.ts +10 -8
  33. package/dist/catalog/component-state.js +42 -30
  34. package/dist/catalog/dependency-edges.d.ts +25 -0
  35. package/dist/catalog/dependency-edges.js +125 -0
  36. package/dist/catalog/effect-work.d.ts +27 -0
  37. package/dist/catalog/effect-work.js +151 -0
  38. package/dist/catalog/jobs.d.ts +4 -1
  39. package/dist/catalog/jobs.js +14 -4
  40. package/dist/catalog/org-catalog.service.d.ts +5 -1
  41. package/dist/catalog/org-catalog.service.js +101 -106
  42. package/dist/catalog/org-intent.d.ts +45 -0
  43. package/dist/catalog/org-intent.js +205 -0
  44. package/dist/catalog/owned-items.d.ts +6 -2
  45. package/dist/catalog/owned-items.js +27 -32
  46. package/dist/catalog/ownership.d.ts +2 -3
  47. package/dist/catalog/ownership.js +10 -28
  48. package/dist/catalog/platform-components.d.ts +3 -1
  49. package/dist/catalog/platform-components.js +9 -1
  50. package/dist/catalog/plugin-import.d.ts +4 -2
  51. package/dist/catalog/plugin-import.js +22 -21
  52. package/dist/catalog/plugin-install.d.ts +19 -54
  53. package/dist/catalog/plugin-install.js +221 -271
  54. package/dist/catalog/plugin-upgrade.d.ts +10 -5
  55. package/dist/catalog/plugin-upgrade.js +80 -67
  56. package/dist/catalog/request-rules.js +20 -8
  57. package/dist/catalog/scope-orgs.js +2 -7
  58. package/dist/catalog/scope-state.d.ts +6 -6
  59. package/dist/catalog/scope-state.js +24 -43
  60. package/dist/catalog/scope-sync-workers.d.ts +7 -11
  61. package/dist/catalog/scope-sync-workers.js +10 -26
  62. package/dist/catalog/scope-sync.d.ts +19 -116
  63. package/dist/catalog/scope-sync.js +228 -275
  64. package/dist/catalog/scope-writer.d.ts +87 -0
  65. package/dist/catalog/scope-writer.js +239 -0
  66. package/dist/catalog/template-connector-ensure.js +1 -1
  67. package/dist/catalog/unshare.js +9 -43
  68. package/dist/channels/connections.service.js +6 -6
  69. package/dist/channels/supervisor.js +3 -7
  70. package/dist/client/client-access.service.js +2 -12
  71. package/dist/config/schema.d.ts +6 -0
  72. package/dist/config/schema.js +32 -1
  73. package/dist/ctx/create-ctx.d.ts +2 -2
  74. package/dist/ctx/create-ctx.js +2 -60
  75. package/dist/ctx/guard-db.d.ts +6 -0
  76. package/dist/ctx/guard-db.js +55 -0
  77. package/dist/db/extension-handoff-schema.d.ts +1 -1
  78. package/dist/db/extension-handoff-schema.js +48 -10
  79. package/dist/db/extension-schema-transfer.js +5 -2
  80. package/dist/db/kernel-schema.d.ts +32 -6
  81. package/dist/device-access/host-services.d.ts +2 -2
  82. package/dist/device-access/host-services.js +5 -6
  83. package/dist/erasure/org-catalog.js +2 -2
  84. package/dist/erasure/org-rules.js +7 -0
  85. package/dist/extensions/admin-ops.d.ts +10 -6
  86. package/dist/extensions/admin-ops.js +53 -9
  87. package/dist/extensions/admin-view.d.ts +4 -1
  88. package/dist/extensions/admin-view.js +27 -14
  89. package/dist/extensions/bootstrap.d.ts +1 -1
  90. package/dist/extensions/bootstrap.js +6 -4
  91. package/dist/extensions/cli.js +1 -0
  92. package/dist/extensions/effective-config.js +1 -4
  93. package/dist/extensions/enabled.d.ts +183 -29
  94. package/dist/extensions/enabled.js +148 -62
  95. package/dist/extensions/host.d.ts +65 -45
  96. package/dist/extensions/host.js +446 -128
  97. package/dist/extensions/installs.d.ts +9 -0
  98. package/dist/extensions/installs.js +23 -0
  99. package/dist/extensions/isolated/admission.d.ts +10 -0
  100. package/dist/extensions/isolated/admission.js +206 -0
  101. package/dist/extensions/isolated/authorization.d.ts +45 -0
  102. package/dist/extensions/isolated/authorization.js +191 -0
  103. package/dist/extensions/isolated/broker.d.ts +15 -0
  104. package/dist/extensions/isolated/broker.js +471 -0
  105. package/dist/extensions/isolated/child-protocol.d.ts +84 -0
  106. package/dist/extensions/isolated/child-protocol.js +21 -0
  107. package/dist/extensions/isolated/child-registration.d.ts +22 -0
  108. package/dist/extensions/isolated/child-registration.js +152 -0
  109. package/dist/extensions/isolated/child-session.d.ts +6 -0
  110. package/dist/extensions/isolated/child-session.js +343 -0
  111. package/dist/extensions/isolated/child-streams.d.ts +4 -0
  112. package/dist/extensions/isolated/child-streams.js +142 -0
  113. package/dist/extensions/isolated/child.d.ts +1 -0
  114. package/dist/extensions/isolated/child.js +10 -0
  115. package/dist/extensions/isolated/configured-package.d.ts +15 -0
  116. package/dist/extensions/isolated/configured-package.js +73 -0
  117. package/dist/extensions/isolated/engine-binds.d.ts +9 -0
  118. package/dist/extensions/isolated/engine-binds.js +82 -0
  119. package/dist/extensions/isolated/engine-policy.d.ts +85 -0
  120. package/dist/extensions/isolated/engine-policy.js +75 -0
  121. package/dist/extensions/isolated/engine-proxy-main.d.ts +1 -0
  122. package/dist/extensions/isolated/engine-proxy-main.js +20 -0
  123. package/dist/extensions/isolated/engine-proxy.d.ts +7 -0
  124. package/dist/extensions/isolated/engine-proxy.js +408 -0
  125. package/dist/extensions/isolated/engine-vaults.d.ts +12 -0
  126. package/dist/extensions/isolated/engine-vaults.js +93 -0
  127. package/dist/extensions/isolated/lanes.d.ts +108 -0
  128. package/dist/extensions/isolated/lanes.js +726 -0
  129. package/dist/extensions/isolated/postgres-gate.d.ts +15 -0
  130. package/dist/extensions/isolated/postgres-gate.js +255 -0
  131. package/dist/extensions/isolated/revision.d.ts +32 -0
  132. package/dist/extensions/isolated/revision.js +359 -0
  133. package/dist/extensions/isolated/rpc-frame.d.ts +50 -0
  134. package/dist/extensions/isolated/rpc-frame.js +193 -0
  135. package/dist/extensions/isolated/rpc.d.ts +66 -0
  136. package/dist/extensions/isolated/rpc.js +314 -0
  137. package/dist/extensions/isolated/sandbox.d.ts +39 -0
  138. package/dist/extensions/isolated/sandbox.js +356 -0
  139. package/dist/extensions/isolated/tier.d.ts +6 -0
  140. package/dist/extensions/isolated/tier.js +45 -0
  141. package/dist/extensions/ledger.d.ts +1 -1
  142. package/dist/extensions/lifecycle-topics.d.ts +2 -0
  143. package/dist/extensions/lifecycle-topics.js +2 -0
  144. package/dist/extensions/lifecycle.d.ts +3 -1
  145. package/dist/extensions/lifecycle.js +53 -5
  146. package/dist/extensions/locks.d.ts +2 -0
  147. package/dist/extensions/locks.js +7 -0
  148. package/dist/extensions/org-config.d.ts +17 -27
  149. package/dist/extensions/org-config.js +114 -129
  150. package/dist/extensions/permission-view.d.ts +6 -1
  151. package/dist/extensions/plugin-guides.d.ts +5 -10
  152. package/dist/extensions/plugin-guides.js +18 -37
  153. package/dist/extensions/plugin-icons.d.ts +3 -21
  154. package/dist/extensions/plugin-icons.js +9 -44
  155. package/dist/extensions/plugin-items.d.ts +10 -30
  156. package/dist/extensions/plugin-items.js +32 -73
  157. package/dist/extensions/source-intent.d.ts +14 -0
  158. package/dist/extensions/source-intent.js +77 -0
  159. package/dist/inbox/platform-inbox.service.js +16 -27
  160. package/dist/index.d.ts +2 -1
  161. package/dist/index.js +2 -1
  162. package/dist/infra/database/database.module.js +6 -1
  163. package/dist/infra/database/kernel-db.d.ts +3 -1
  164. package/dist/infra/database/kernel-db.js +4 -0
  165. package/dist/infra/events/kernel-events.d.ts +4 -0
  166. package/dist/infra/outbox/registry.d.ts +3 -36
  167. package/dist/infra/outbox/registry.js +4 -49
  168. package/dist/infra/paging/paged-read.d.ts +56 -0
  169. package/dist/infra/paging/paged-read.js +78 -0
  170. package/dist/infra/queue/queue-names.d.ts +1 -1
  171. package/dist/infra/queue/queue-names.js +1 -1
  172. package/dist/kernel.d.ts +3 -2
  173. package/dist/kernel.js +21 -2
  174. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  175. package/dist/lifecycle/kernel-lifecycle.js +22 -12
  176. package/dist/lifecycle/tokens.d.ts +8 -0
  177. package/dist/lifecycle/tokens.js +2 -0
  178. package/dist/orgs/directory-sync.js +1 -4
  179. package/dist/orgs/org-lock.d.ts +3 -1
  180. package/dist/orgs/org-lock.js +3 -1
  181. package/dist/orgs/orgs.service.d.ts +3 -1
  182. package/dist/orgs/orgs.service.js +15 -8
  183. package/dist/overrides.d.ts +0 -3
  184. package/dist/overrides.js +0 -2
  185. package/dist/platform/ops/admin.ops.js +14 -3
  186. package/dist/platform/ops/extensions-admin.ops.js +20 -3
  187. package/dist/platform/ops/org-plugins.ops.js +5 -2
  188. package/dist/platform/ops/orgs.ops.js +13 -3
  189. package/dist/platform/ops/plugins.ops.js +11 -10
  190. package/dist/setup/setup-checks.service.js +3 -2
  191. package/dist/skills/usable.js +41 -30
  192. package/dist/themes/theme-state.js +3 -3
  193. package/dist/tools/registry.d.ts +2 -2
  194. package/dist/tools/registry.js +7 -3
  195. package/package.json +2 -2
  196. package/src/migrations/0228_extension_org_switches.sql +56 -0
  197. package/src/migrations/0229_catalog_dependency_edges.sql +17 -0
  198. package/src/migrations/0230_audit_filter_idx.sql +18 -0
  199. package/src/migrations/0231_plugin_effect_work.sql +171 -0
  200. package/dist/catalog/install-status.d.ts +0 -6
  201. package/dist/catalog/install-status.js +0 -6
  202. package/dist/catalog/scope-jobs.d.ts +0 -59
  203. 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
+ }
@@ -0,0 +1,108 @@
1
+ import type { StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
+ import { type RpcBudget } from "./rpc.js";
3
+ import { type ExtensionSandboxOptions } from "./sandbox.js";
4
+ export declare const MAX_ISOLATED_LANES = 4;
5
+ export type ServingRole = "api" | "worker" | "gateway";
6
+ type InvocationMode = "org" | "deployment" | "setupCheck";
7
+ export interface Invocation {
8
+ orgId?: string | undefined;
9
+ mode: InvocationMode;
10
+ role?: ServingRole;
11
+ config?: unknown;
12
+ signal?: AbortSignal | undefined;
13
+ toolCall?: unknown;
14
+ cleanup?: Set<() => Promise<unknown> | undefined>;
15
+ }
16
+ export type BrokerCall = (method: string, args: unknown[], invocation: Invocation, signal: AbortSignal) => Promise<unknown>;
17
+ export interface IsolatedLaneOptions {
18
+ sandbox: Omit<ExtensionSandboxOptions, "signal" | "stagingDir" | "sandboxId">;
19
+ entry: string;
20
+ manifest: StaticExtensionManifest;
21
+ configSchemas?: unknown;
22
+ credential: {
23
+ login: string;
24
+ url: string;
25
+ database: string;
26
+ };
27
+ socketDir: string;
28
+ rls: "off" | "scoped" | "enforce";
29
+ signal: AbortSignal;
30
+ broker: BrokerCall;
31
+ quota: IsolatedExtensionQuota;
32
+ revision: string;
33
+ onCrash?: ((retryAfterMs: number) => void) | undefined;
34
+ cleanupFault: () => void;
35
+ }
36
+ type ProcessKind = "serving" | "control";
37
+ interface ProcessIngress {
38
+ budget: RpcBudget;
39
+ requestBudget: RpcBudget;
40
+ }
41
+ interface ProcessLease extends ProcessIngress {
42
+ release(): void;
43
+ }
44
+ interface PendingRemoval {
45
+ remove(): Promise<void>;
46
+ release(): void;
47
+ delay: number;
48
+ timer?: ReturnType<typeof setTimeout> | undefined;
49
+ running: boolean;
50
+ }
51
+ export declare class IsolatedExtensionQuota {
52
+ private readonly processes;
53
+ private calls;
54
+ private readonly services;
55
+ private readonly preflights;
56
+ private readonly starts;
57
+ private readonly retryTimers;
58
+ private readonly available;
59
+ private readonly removals;
60
+ private readonly crashes;
61
+ watch(listener: () => void): () => void;
62
+ retryRemoval(remove: PendingRemoval["remove"], release: ProcessLease["release"]): void;
63
+ private scheduleRemoval;
64
+ atCapacity(kind: ProcessKind): boolean;
65
+ process(kind: ProcessKind): ProcessLease | undefined;
66
+ call(): () => void;
67
+ admitPreflight(orgId?: string, role?: ServingRole, setupCheck?: boolean): () => void;
68
+ service(kind: ProcessKind): () => void;
69
+ inBackoff(revision: string): boolean;
70
+ crashed(revision: string): number;
71
+ }
72
+ /** Owns only this revision's authenticated pipes, lanes and live invocation handles. */
73
+ export declare class IsolatedLanes {
74
+ private readonly options;
75
+ private readonly shutdown;
76
+ private readonly lifetime;
77
+ private readonly lanes;
78
+ private readonly waiting;
79
+ private readonly waitingControl;
80
+ private waitingCount;
81
+ private scheduled;
82
+ private sequence;
83
+ private draining?;
84
+ private control?;
85
+ private expected;
86
+ constructor(options: IsolatedLaneOptions);
87
+ register(): Promise<unknown>;
88
+ invoke(callback: string, args: readonly unknown[], scope: Invocation): Promise<unknown>;
89
+ private admit;
90
+ private remove;
91
+ private schedule;
92
+ private admitNext;
93
+ private tryAdmission;
94
+ private claim;
95
+ private makeRoomFor;
96
+ private openServing;
97
+ private idle;
98
+ private retire;
99
+ private evict;
100
+ private openControl;
101
+ private removeControl;
102
+ private admitControl;
103
+ private start;
104
+ /** Stop the admitted processes and PostgreSQL gates while their grant is revoked. */
105
+ revokeOrg(orgId?: string): void;
106
+ close(): Promise<void>;
107
+ }
108
+ export {};