@nathanstephenson/flow 0.1.3 → 0.1.4

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 (67) hide show
  1. package/README.md +46 -2
  2. package/build/workflow-runtime.cjs +1 -46
  3. package/dist/backend/claude/index.js +108 -34
  4. package/dist/backend/claude/permissions.js +26 -15
  5. package/dist/backend/claude/subagents.js +4 -0
  6. package/dist/backend/mcp-stdio-supervisor.js +196 -0
  7. package/dist/backend/mcp.js +146 -51
  8. package/dist/backend/permission-errors.js +3 -0
  9. package/dist/backend/pi/agent-permissions.js +74 -0
  10. package/dist/backend/pi/index.js +29 -9
  11. package/dist/backend/registry.js +5 -30
  12. package/dist/backend/worker/assets.js +16 -0
  13. package/dist/backend/worker/claude-state.js +61 -0
  14. package/dist/backend/worker/entry.js +186 -0
  15. package/dist/backend/worker/index.js +255 -0
  16. package/dist/backend/worker/launcher.js +67 -0
  17. package/dist/backend/worker/protocol.js +11 -0
  18. package/dist/backend/worker/rpc.js +108 -0
  19. package/dist/build-id +1 -1
  20. package/dist/cli/bootstrap.js +1 -1
  21. package/dist/cli/main.js +9 -1
  22. package/dist/client/connection.js +107 -2
  23. package/dist/client/diff.js +43 -0
  24. package/dist/client/reduce.js +3 -0
  25. package/dist/daemon/config-store.js +36 -1
  26. package/dist/daemon/config.js +54 -18
  27. package/dist/daemon/host.js +279 -29
  28. package/dist/daemon/log.js +98 -0
  29. package/dist/daemon/runtime.js +10 -1
  30. package/dist/daemon/server.js +67 -1
  31. package/dist/daemon/workflow-execution-routes.js +1 -1
  32. package/dist/daemon/workflow-executions.js +63 -25
  33. package/dist/daemon/workflow-mcp.js +2 -4
  34. package/dist/daemon/workflow-routes.js +4 -3
  35. package/dist/isolation/filesystem.js +382 -0
  36. package/dist/isolation/launcher.js +40 -0
  37. package/dist/isolation/node-assets.js +84 -0
  38. package/dist/isolation/support.js +40 -0
  39. package/dist/isolation/toolchain-assets.js +62 -0
  40. package/dist/protocol/presentation.js +230 -0
  41. package/dist/protocol/settings.js +1 -4
  42. package/dist/workflows/executors.js +118 -62
  43. package/dist/workflows/graph.js +3 -6
  44. package/dist/workflows/json-schema.js +8 -3
  45. package/dist/workflows/mcp.js +15 -1
  46. package/dist/workflows/runtime-settings.js +7 -7
  47. package/dist/workflows/runtime.js +1 -34
  48. package/package.json +1 -1
  49. package/web/dist/assets/index-Bn-ECZ7w.js +174 -0
  50. package/web/dist/assets/index-DL0CGVaN.css +2 -0
  51. package/web/dist/assets/input-NIrLDFaS.js +6 -0
  52. package/web/dist/assets/settings-mcp-B60T2XUv.js +1 -0
  53. package/web/dist/assets/settings-secrets-BtQwc-w4.js +1 -0
  54. package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +23 -0
  55. package/web/dist/assets/switch-DyYU6B5T.js +1 -0
  56. package/web/dist/assets/workflows-BAdf2yKH.js +7 -0
  57. package/web/dist/assets/workflows-pane-MSSNIrgu.js +1 -0
  58. package/web/dist/index.html +4 -4
  59. package/web/dist/assets/index-BmX_AxCZ.js +0 -170
  60. package/web/dist/assets/index-DWF4-3Fh.css +0 -2
  61. package/web/dist/assets/select-6i3wxovH.js +0 -1
  62. package/web/dist/assets/settings-mcp-CSLXJftV.js +0 -1
  63. package/web/dist/assets/settings-secrets-DpEwZLL4.js +0 -1
  64. package/web/dist/assets/settings-workflows-Dt-GaRtX.js +0 -23
  65. package/web/dist/assets/switch-ftZleVB8.js +0 -6
  66. package/web/dist/assets/workflows-DDRfFnAE.js +0 -7
  67. package/web/dist/assets/workflows-pane-g5njqean.js +0 -1
@@ -0,0 +1,382 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { access } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { pathToolchainAssets } from "./toolchain-assets.js";
7
+ const virtualRoot = "/tmp/flow-isolation";
8
+ const virtualState = `${virtualRoot}/state`;
9
+ const virtualHome = `${virtualRoot}/home`;
10
+ function within(path, parent) {
11
+ const tail = relative(parent, path);
12
+ return tail === "" || (tail !== ".." && !tail.startsWith(`..${sep}`) && !isAbsolute(tail));
13
+ }
14
+ /** Resolve existing ancestors too: an absent secret path may have a symlinked parent. */
15
+ function canonical(path) {
16
+ const absolute = resolve(path);
17
+ try {
18
+ return realpathSync(absolute);
19
+ }
20
+ catch (error) {
21
+ if (error.code !== "ENOENT")
22
+ throw error;
23
+ const parent = dirname(absolute);
24
+ if (parent === absolute)
25
+ throw error;
26
+ return join(canonical(parent), basename(absolute));
27
+ }
28
+ }
29
+ /** Mask an existing ancestor instead of dropping protection for a future credential path. */
30
+ function existingMask(path) {
31
+ while (!existsSync(path)) {
32
+ const parent = dirname(path);
33
+ if (parent === path)
34
+ throw new Error(`Cannot mask protected path: ${path}`);
35
+ path = parent;
36
+ }
37
+ if (path === "/")
38
+ throw new Error("Protected path has no safe existing ancestor");
39
+ return path;
40
+ }
41
+ function expandHome(path, home) {
42
+ return path === "~" ? home : path.startsWith("~/") ? join(home, path.slice(2)) : path;
43
+ }
44
+ async function probeBoundary(command, args, env, fds) {
45
+ await new Promise((resolveProbe, reject) => {
46
+ const child = spawn(command, args, { env, stdio: ["ignore", "ignore", "pipe", ...fds] });
47
+ let stderr = "";
48
+ const timer = setTimeout(() => child.kill("SIGKILL"), 10_000);
49
+ child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-8192); });
50
+ child.once("error", (error) => { clearTimeout(timer); reject(error); });
51
+ child.once("close", (code, signal) => {
52
+ clearTimeout(timer);
53
+ if (code === 0)
54
+ resolveProbe();
55
+ else
56
+ reject(Object.assign(new Error("Boundary probe failed"), { code, signal, stderr }));
57
+ });
58
+ });
59
+ }
60
+ async function executable(command, env) {
61
+ const candidates = command.includes("/") ? [resolve(command)]
62
+ : (env.PATH ?? "/usr/bin:/bin").split(":").map((dir) => resolve(dir, command));
63
+ for (const path of candidates) {
64
+ try {
65
+ await access(path, constants.X_OK);
66
+ if (statSync(path).isFile())
67
+ return realpathSync(path);
68
+ }
69
+ catch { /* Try the next PATH entry. No unrestricted fallback. */ }
70
+ }
71
+ throw new Error(`Executable not found: ${command}`);
72
+ }
73
+ function scrubEnvironment(inherited) {
74
+ const env = { ...inherited };
75
+ // Undefined entries also override launchers which merge process.env into this result.
76
+ for (const key of new Set([...Object.keys(process.env), ...Object.keys(env)])) {
77
+ if (/^(FLOW_|LD_|DYLD_|XDG_|PI_SESSION_)/.test(key) || /^(NODE_OPTIONS|NODE_PATH|BASH_ENV|ENV|ZDOTDIR|TMPDIR|TMP|TEMP|PI_CODING_AGENT_DIR|PI_CODING_AGENT_SESSION_DIR|CLAUDE_CONFIG_DIR|CLAUDE_SECURESTORAGE_CONFIG_DIR|SSH_AUTH_SOCK|SSH_AGENT_PID|DBUS_SESSION_BUS_ADDRESS|DOCKER_HOST|CONTAINER_HOST|NODE_CHANNEL_FD|NODE_CHANNEL_SERIALIZATION_MODE)$/.test(key)) {
78
+ env[key] = undefined;
79
+ }
80
+ }
81
+ Object.assign(env, {
82
+ HOME: virtualHome, TMPDIR: "/tmp", TMP: "/tmp", TEMP: "/tmp",
83
+ XDG_CONFIG_HOME: `${virtualHome}/.config`, XDG_CACHE_HOME: `${virtualHome}/.cache`,
84
+ XDG_DATA_HOME: `${virtualHome}/.local/share`, XDG_STATE_HOME: `${virtualHome}/.local/state`,
85
+ XDG_RUNTIME_DIR: `${virtualRoot}/run`,
86
+ PI_CODING_AGENT_DIR: `${virtualHome}/.pi/agent`,
87
+ PI_CODING_AGENT_SESSION_DIR: `${virtualState}/sessions`,
88
+ CLAUDE_CONFIG_DIR: `${virtualHome}/.claude`,
89
+ });
90
+ return env;
91
+ }
92
+ function scopeContext(options) {
93
+ const inherited = { ...process.env, ...options.env };
94
+ const home = canonical(homedir());
95
+ const credentialHome = canonical(inherited.HOME ?? home);
96
+ const piDir = canonical(expandHome(inherited.PI_CODING_AGENT_DIR ?? join(credentialHome, ".pi/agent"), credentialHome));
97
+ // Relative Claude roots resolve against the CLI's Scope, not this host's cwd;
98
+ // literal ~ is not expanded by Claude either. Refuse rather than mask/stage the
99
+ // wrong store. Empty roots retain the SDK's default-home semantics.
100
+ for (const key of ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"]) {
101
+ if (inherited[key] && !isAbsolute(inherited[key]))
102
+ throw new Error(`${key} must be absolute when filesystem isolation is enabled`);
103
+ }
104
+ const claudeDir = canonical(inherited.CLAUDE_CONFIG_DIR || join(credentialHome, ".claude"));
105
+ // Claude can use a separate auth/lock root. An explicit empty override means the
106
+ // default home store, not the config root. Mask the real source and stage only its
107
+ // credential file; never propagate this host-root override into a restricted worker.
108
+ const authRoot = inherited.CLAUDE_SECURESTORAGE_CONFIG_DIR;
109
+ const claudeAuthDir = canonical(authRoot === undefined ? claudeDir : authRoot || join(credentialHome, ".claude"));
110
+ const flowRoots = [...new Set([join(home, ".flow"), inherited.FLOW_STATE_DIR, process.env.FLOW_STATE_DIR, options.stateRoot]
111
+ .filter((path) => !!path).map(canonical))];
112
+ const runtimePaths = [process.env, inherited].flatMap((env) => {
113
+ const sockets = [env.SSH_AUTH_SOCK,
114
+ ...[env.DOCKER_HOST, env.CONTAINER_HOST].map((value) => value?.startsWith('unix://') ? value.slice(7) : undefined),
115
+ env.DBUS_SESSION_BUS_ADDRESS?.match(/(?:^|;)unix:path=([^,;]+)/)?.[1]];
116
+ const runtime = env.XDG_RUNTIME_DIR;
117
+ return [...sockets, ...(runtime && !['/tmp', '/var/tmp', '/run'].some((root) => within(canonical(runtime), canonical(root))) ? [runtime] : [])]
118
+ .filter((path) => !!path && isAbsolute(path));
119
+ });
120
+ const hostCredentials = [home, credentialHome].flatMap((root) => [".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".config/gcloud", ".local/share/keyrings",
121
+ ".netrc", ".npmrc", ".git-credentials", ".git-credential-cache", ".cache/git/credential"]
122
+ .map((name) => join(root, name)));
123
+ const protectedPaths = [...new Set([...flowRoots, ...hostCredentials, ...runtimePaths, join(home, ".pi/agent"), join(home, ".claude"), join(home, ".claude.json"),
124
+ piDir, claudeDir, claudeAuthDir, join(credentialHome, ".claude.json"), ...(options.protectedPaths ?? [])].map(canonical))];
125
+ const scope = realpathSync(options.scope);
126
+ if (options.expectedScope !== undefined && scope !== resolve(options.expectedScope)) {
127
+ throw new Error('Scope changed since selection; refusing redirected execution');
128
+ }
129
+ if (!statSync(scope).isDirectory())
130
+ throw new Error("Scope must be a directory");
131
+ const launcher = inherited.FLOW_BWRAP_PATH ?? "/usr/bin/bwrap";
132
+ if ((isAbsolute(launcher) && within(canonical(launcher), scope)) || within(canonical(process.execPath), scope)) {
133
+ throw new Error("Unsafe Scope: would expose a trusted launch executable");
134
+ }
135
+ const temporary = relative(canonical("/tmp"), scope).split(sep)[0];
136
+ if (/^flow-isolation-[A-Za-z0-9]{6}$/.test(temporary ?? ""))
137
+ throw new Error("Unsafe Scope: private isolation staging path");
138
+ if (within(home, scope) || within(credentialHome, scope) || within(canonical("/tmp"), scope)
139
+ || within(canonical(virtualRoot), scope) || within(scope, canonical(virtualRoot))
140
+ || ["/proc", "/sys", "/dev", "/run", "/var/run", "/var/tmp"].some((path) => within(scope, canonical(path)))) {
141
+ throw new Error("Unsafe Scope: root, home, or reserved isolation path");
142
+ }
143
+ for (const path of protectedPaths) {
144
+ if (within(path, scope))
145
+ throw new Error(`Scope would expose protected host state: ${path}`);
146
+ if (within(scope, path)) {
147
+ const worktree = join(path, "worktrees");
148
+ if (!flowRoots.includes(path) || !within(scope, worktree) || relative(worktree, scope).split(sep).length < 2) {
149
+ throw new Error(`Scope is inside protected host state: ${path}`);
150
+ }
151
+ }
152
+ }
153
+ return { inherited, home, credentialHome, piDir, claudeDir, claudeAuthDir, flowRoots, protectedPaths, scope };
154
+ }
155
+ /** Validate Scope against the shared policy before preparing or probing a restricted launch. */
156
+ export function validateFilesystemScope(options) {
157
+ return scopeContext(options).scope;
158
+ }
159
+ /**
160
+ * Linux-only, fail-closed filesystem boundary shared by workers, MCP stdio and Workflow code.
161
+ * The host filesystem is read-only, except the canonical Scope and one private backend directory.
162
+ * Host state/auth, common socket locations and the host process table are hidden. Network is
163
+ * intentionally shared for model access: external services (including loopback HTTP), credentials
164
+ * deliberately passed to the worker, and sockets elsewhere are NOT confined by this boundary.
165
+ * The caller owns process supervision; cleanup must follow termination, never precede it.
166
+ */
167
+ export async function prepareFilesystemIsolation(options) {
168
+ if (process.platform !== "linux")
169
+ throw new Error("Filesystem isolation unavailable; unrestricted launch refused: requires Linux and Bubblewrap");
170
+ let scratch;
171
+ const sources = [];
172
+ const cleanup = () => {
173
+ try {
174
+ if (scratch) {
175
+ rmSync(scratch, { recursive: true, force: true });
176
+ scratch = undefined;
177
+ }
178
+ }
179
+ finally {
180
+ for (const fd of sources.splice(0))
181
+ closeSync(fd);
182
+ }
183
+ };
184
+ // Pin validated mount sources in the host only, not inherited application descriptors. A
185
+ // concurrently writable ancestor must not swap Scope for a symlink between validation and bind.
186
+ const pinned = (path) => {
187
+ const before = statSync(path);
188
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | (before.isDirectory() ? constants.O_DIRECTORY : 0));
189
+ sources.push(fd);
190
+ const after = fstatSync(fd);
191
+ if (before.dev !== after.dev || before.ino !== after.ino || realpathSync(`/proc/self/fd/${fd}`) !== path) {
192
+ throw new Error(`Execution mount source changed during preparation: ${path}`);
193
+ }
194
+ return String((options.ipc ? 4 : 3) + sources.length - 1);
195
+ };
196
+ try {
197
+ const { inherited, home, credentialHome, piDir, claudeDir, claudeAuthDir, flowRoots, protectedPaths, scope } = scopeContext(options);
198
+ const env = scrubEnvironment(inherited);
199
+ if (options.credentials === "claude" && inherited.FLOW_CLAUDE_PATH)
200
+ env.FLOW_CLAUDE_PATH = inherited.FLOW_CLAUDE_PATH;
201
+ // npm extends PATH with project-controlled .bin directories. They must never select our
202
+ // enforcement program; an explicit operator override must also be outside writable Scope.
203
+ const launcher = inherited.FLOW_BWRAP_PATH ?? "/usr/bin/bwrap";
204
+ if (!isAbsolute(launcher))
205
+ throw new Error("FLOW_BWRAP_PATH must be an absolute trusted executable path");
206
+ const bwrap = await executable(launcher, env);
207
+ if (within(bwrap, scope))
208
+ throw new Error("Unsafe Scope: would expose the trusted isolation launcher");
209
+ if (flowRoots.some((root) => /^sessions\/[^/]+\/backend(?:\/|$)/.test(relative(root, bwrap))
210
+ || within(bwrap, join(root, 'worktrees')))
211
+ || /^flow-isolation-[A-Za-z0-9]{6}(?:\/|$)/.test(relative(canonical('/tmp'), bwrap))) {
212
+ throw new Error("Trusted launch executable must be outside writable backend state and scratch");
213
+ }
214
+ const command = await executable(options.command, env);
215
+ const maskRoots = [...protectedPaths.map(existingMask), canonical('/tmp'), canonical('/var/tmp'), canonical('/run')];
216
+ const tools = pathToolchainAssets(env.PATH ?? '/usr/bin:/bin', scope, path => maskRoots.some(root => within(path, root)), path => protectedPaths.some(root => within(path, root)) || ['/var/tmp', '/run'].some(root => within(path, canonical(root))));
217
+ env.PATH = tools.path;
218
+ const aliases = new Map();
219
+ const readable = [...new Set([command, ...tools.assets, ...(options.readablePaths ?? []),
220
+ ...(env.FLOW_CLAUDE_PATH ? [await executable(env.FLOW_CLAUDE_PATH, env)] : [])].map(asset => {
221
+ const source = realpathSync(asset);
222
+ // Preserve every lookup symlink, including $PREFIX/lib -> another library directory.
223
+ // Canonicalize each alias's parents to prevent an ancestor alias grafting into hidden
224
+ // state. Do not mount alias targets' parents: only the requested canonical leaf is data.
225
+ let logical = sep;
226
+ for (const name of resolve(asset).split(sep).filter(Boolean)) {
227
+ logical = join(logical, name);
228
+ if (lstatSync(logical).isSymbolicLink()) {
229
+ const destination = join(canonical(dirname(logical)), basename(logical));
230
+ aliases.set(destination, realpathSync(logical));
231
+ }
232
+ }
233
+ return source;
234
+ }))];
235
+ const validateAsset = (path) => {
236
+ if ([home, credentialHome, "/", ...["/tmp", "/var/tmp", "/run", "/var/run", "/proc", "/dev", "/sys"].map(canonical)].includes(path)
237
+ || protectedPaths.some((secret) => within(path, secret) || within(secret, path))
238
+ || within(path, virtualRoot) || ["/proc", "/dev", "/sys", "/run", "/var/tmp"].some((root) => within(path, canonical(root)))) {
239
+ throw new Error(`Readable execution asset would expose protected state: ${path}`);
240
+ }
241
+ };
242
+ readable.forEach(validateAsset);
243
+ // Never stage credentials under operator TMPDIR: it could be inside a writable Scope.
244
+ scratch = mkdtempSync(join(canonical("/tmp"), "flow-isolation-"));
245
+ const backend = options.stateDir ? realpathSync(options.stateDir) : join(scratch, "backend");
246
+ if (options.stateDir) {
247
+ if (basename(backend) !== "backend" || !statSync(backend).isDirectory() || within(home, backend) || within(credentialHome, backend)
248
+ || within(scope, backend) || within(backend, scope) || within(backend, virtualRoot) || within(virtualRoot, backend)) {
249
+ throw new Error("stateDir must be a dedicated backend directory, separate from Scope");
250
+ }
251
+ for (const path of protectedPaths) {
252
+ if (within(path, backend))
253
+ throw new Error("stateDir would widen access to protected host state");
254
+ if (within(backend, path) && (!flowRoots.includes(path) || !/^sessions\/[^/]+\/backend$/.test(relative(path, backend)))) {
255
+ throw new Error("Inside host state, stateDir must be sessions/<id>/backend, never sessions or secrets");
256
+ }
257
+ }
258
+ }
259
+ else
260
+ mkdirSync(backend, { mode: 0o700 });
261
+ // These programs run outside the boundary, including during the probe. Neither Scope nor
262
+ // private state may grant a model authority to replace them before a later launch/Revive.
263
+ for (const trusted of [bwrap, canonical(process.execPath)]) {
264
+ if ([backend, scratch].some((writable) => within(trusted, writable))) {
265
+ throw new Error("Trusted launch executable must be outside writable backend state and scratch");
266
+ }
267
+ }
268
+ const args = ["--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--die-with-parent", "--new-session", "--cap-drop", "ALL",
269
+ "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/var/tmp", "--tmpfs", canonical("/run")];
270
+ // Masks must precede the selected Worktree bind. Remount only the parent, not its children.
271
+ const masks = [...new Set([...protectedPaths, backend, scratch]
272
+ .filter((path) => !["/tmp", "/var/tmp", "/run"].some((root) => within(path, canonical(root))))
273
+ .map(existingMask))]
274
+ .sort((a, b) => a.length - b.length)
275
+ .filter((path, index, paths) => !paths.slice(0, index).some((parent) => within(path, parent)));
276
+ const directoryMasks = [];
277
+ for (const path of masks) {
278
+ if (statSync(path).isDirectory()) {
279
+ args.push("--tmpfs", path);
280
+ directoryMasks.push(path);
281
+ }
282
+ else
283
+ args.push("--ro-bind", "/dev/null", path);
284
+ }
285
+ // Ancestor masks may hide runtime assets too. Restore only explicitly validated assets,
286
+ // never the ancestor itself: new host credentials must stay hidden for this worker's life.
287
+ for (const path of readable) {
288
+ if ((within(path, canonical("/tmp")) || masks.some((mask) => within(path, mask)))
289
+ && !within(path, scope))
290
+ args.push("--ro-bind-fd", pinned(path), path);
291
+ }
292
+ for (const [destination, source] of aliases) {
293
+ if (!within(destination, scope)
294
+ && (within(destination, canonical('/tmp')) || masks.some(mask => within(destination, mask)))
295
+ && !readable.some(parent => within(destination, parent) && statSync(parent).isDirectory())) {
296
+ validateAsset(destination);
297
+ validateAsset(source);
298
+ // Keep a symlink, not a second directory bind: Node realpath must still resolve to
299
+ // the pinned canonical tree so the linked package's own ancestor dependencies work.
300
+ // Parents are empty mask directories; a restored asset parent already carries its alias.
301
+ args.push('--symlink', source, destination);
302
+ }
303
+ }
304
+ const privateHome = join(scratch, "home");
305
+ mkdirSync(join(privateHome, ".pi/agent"), { recursive: true, mode: 0o700 });
306
+ mkdirSync(join(privateHome, ".claude"), { mode: 0o700 });
307
+ args.push("--bind-fd", pinned(scope), scope, "--dir", virtualRoot, "--bind-fd", pinned(privateHome), virtualHome, "--dir", `${virtualRoot}/run`, "--bind-fd", pinned(backend), virtualState);
308
+ for (const path of directoryMasks)
309
+ args.push("--remount-ro", path);
310
+ const stage = (source, destination) => {
311
+ if (!existsSync(source))
312
+ return;
313
+ if (!statSync(source).isFile() || realpathSync(source) !== resolve(source)) {
314
+ throw new Error(`Credential must be a regular, non-symlink file: ${source}`);
315
+ }
316
+ // Mutable SDK-local copies permit OAuth refresh, file locks and atomic config rewrites.
317
+ // Only this private staging tree is writable: never write refreshed data back to the source.
318
+ writeFileSync(join(privateHome, relative(virtualHome, destination)), readFileSync(source), { mode: 0o600 });
319
+ };
320
+ const resources = (label, directory, destination, names) => {
321
+ for (const name of names) {
322
+ const source = join(directory, name);
323
+ if (!existsSync(source))
324
+ continue;
325
+ const asset = realpathSync(source);
326
+ if (asset !== source || protectedPaths.some((secret) => secret !== directory &&
327
+ (within(asset, secret) || within(secret, asset))))
328
+ throw new Error(`Unsafe ${label} resource: ${source}`);
329
+ args.push("--ro-bind-fd", pinned(asset), join(destination, name));
330
+ }
331
+ };
332
+ if (options.credentials === "pi") {
333
+ for (const name of ["auth.json", "models.json", "settings.json"])
334
+ stage(join(piDir, name), join(env.PI_CODING_AGENT_DIR, name));
335
+ resources("Pi", piDir, env.PI_CODING_AGENT_DIR, ["AGENTS.md", "skills", "prompts", "themes", "extensions", "packages", "bin", "tools"]);
336
+ }
337
+ else if (options.credentials === "claude") {
338
+ stage(join(claudeAuthDir, ".credentials.json"), join(env.CLAUDE_CONFIG_DIR, ".credentials.json"));
339
+ const config = existsSync(join(claudeDir, ".claude.json")) ? join(claudeDir, ".claude.json") : join(credentialHome, ".claude.json");
340
+ stage(config, join(virtualHome, ".claude.json"));
341
+ stage(config, join(env.CLAUDE_CONFIG_DIR, ".claude.json"));
342
+ resources("Claude", claudeDir, env.CLAUDE_CONFIG_DIR, ["CLAUDE.md", "commands", "skills", "agents", "rules", "plugins"]);
343
+ // The CLI owns its project transcripts. Persist only that subtree, not global credentials.
344
+ const projects = join(backend, "claude-projects");
345
+ if (!existsSync(projects))
346
+ mkdirSync(projects, { mode: 0o700 });
347
+ if (!statSync(projects).isDirectory() || realpathSync(projects) !== projects) {
348
+ throw new Error("Unsafe Claude backend transcript directory");
349
+ }
350
+ args.push("--bind-fd", pinned(projects), join(env.CLAUDE_CONFIG_DIR, "projects"));
351
+ }
352
+ // Mount descriptors are consumed before hiding the host process table.
353
+ args.push("--proc", "/proc", "--remount-ro", "/proc", "--dev", "/dev");
354
+ // Clear inside Bubblewrap as well: callers may merge env with their own inherited environment.
355
+ args.push("--clearenv");
356
+ for (const [key, value] of Object.entries(env))
357
+ if (value !== undefined)
358
+ args.push("--setenv", key, value);
359
+ args.push("--chdir", scope);
360
+ // Probe the actual mount policy and namespaces, not merely `bwrap --version`. Never run the
361
+ // requested program when unavailable; no cached probe can turn a later failure into fallback.
362
+ try {
363
+ // Reserve fd 3 in the probe exactly as in an IPC worker launch.
364
+ await probeBoundary(bwrap, [...args, "--", "/bin/true"], env, [...(options.ipc ? ["ignore"] : []), ...sources]);
365
+ }
366
+ catch (error) {
367
+ // execFile's default message includes every --setenv argument, including provider keys.
368
+ const failure = error;
369
+ throw new Error(`Bubblewrap namespace/mount probe failed (${failure.signal ?? failure.code ?? "unknown"}): ${(failure.stderr ?? "").trim().slice(-2048)}`);
370
+ }
371
+ // Bubblewrap (unlike some other sandbox launchers) retains inherited application fds;
372
+ // it has no --preserve-fds option. Restore Node's spawn-time IPC environment after clearenv.
373
+ if (options.ipc)
374
+ args.push("--setenv", "NODE_CHANNEL_FD", "3", "--setenv", "NODE_CHANNEL_SERIALIZATION_MODE", "advanced", "--setenv", "FLOW_BACKEND_WORKER", "1");
375
+ args.push("--", command, ...options.args);
376
+ return { command: bwrap, args, env, stdioFds: sources.slice(), scope, stateDir: virtualState, cleanup };
377
+ }
378
+ catch (error) {
379
+ cleanup();
380
+ throw new Error(`Filesystem isolation unavailable; unrestricted launch refused: ${error.message}`, { cause: error });
381
+ }
382
+ }
@@ -0,0 +1,40 @@
1
+ import { isSea } from "node:sea";
2
+ import { workerCommand } from "../backend/worker/launcher.js";
3
+ const flag = "--flow-isolation-launch";
4
+ /** The MCP SDK cannot pass mount descriptors. A trusted, non-interactive supervisor passes them
5
+ * to Bubblewrap, sharing stdio verbatim. It never executes server code outside the boundary. */
6
+ export function filesystemStdioLaunch(isolation) {
7
+ const payload = JSON.stringify({ command: isolation.command, args: isolation.args,
8
+ sources: isolation.stdioFds.map((fd) => `/proc/${process.pid}/fd/${fd}`) });
9
+ if (isSea()) {
10
+ const plan = workerCommand();
11
+ return { command: plan.command, args: [flag, payload] };
12
+ }
13
+ // Use already-loaded code, not a disk entry a writable Project could replace before launch.
14
+ const program = `(${runFilesystemLauncher.toString()})().catch(error=>{console.error(error.message);process.exitCode=1})`;
15
+ return { command: process.execPath, args: ["-e", program, payload] };
16
+ }
17
+ export function isFilesystemLauncher() { return process.argv.includes(flag); }
18
+ export async function runFilesystemLauncher() {
19
+ const { spawn } = await import("node:child_process");
20
+ const { closeSync, constants, openSync } = await import("node:fs");
21
+ const spec = JSON.parse(process.argv.at(-1));
22
+ if (typeof spec.command !== "string" || !Array.isArray(spec.args) || !spec.args.every((value) => typeof value === "string") ||
23
+ !Array.isArray(spec.sources) || !spec.sources.every((value) => typeof value === "string" && /^\/proc\/\d+\/fd\/\d+$/.test(value))) {
24
+ throw new Error("Invalid filesystem launch specification");
25
+ }
26
+ const fds = [];
27
+ try {
28
+ for (const source of spec.sources)
29
+ fds.push(openSync(source, constants.O_RDONLY));
30
+ await new Promise((resolve, reject) => {
31
+ const child = spawn(spec.command, spec.args, { env: process.env, stdio: [0, 1, 2, ...fds] });
32
+ child.once("error", reject);
33
+ child.once("close", (code) => { process.exitCode = code ?? 1; resolve(); });
34
+ });
35
+ }
36
+ finally {
37
+ for (const fd of fds)
38
+ closeSync(fd);
39
+ }
40
+ }
@@ -0,0 +1,84 @@
1
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ /** Existing Node search trees and linked package targets, never their home/workspace
4
+ * ancestors. These are execution-asset candidates, NOT grants: callers must pass every
5
+ * result through prepareFilesystemIsolation's protected-path validation.
6
+ * Uses Node's search algorithm for both npm installs and dependencies beside a SEA.
7
+ */
8
+ export function nodeExecutionAssets(entries) {
9
+ const assets = new Set();
10
+ const searched = new Set();
11
+ const trees = new Set();
12
+ const pending = [];
13
+ const addTree = (path) => {
14
+ if (!existsSync(path))
15
+ return;
16
+ const canonical = realpathSync(path);
17
+ if (!statSync(canonical).isDirectory())
18
+ return;
19
+ // Retain the lookup name too: an ancestor mask hides the original node_modules
20
+ // symlink even when its canonical target is restored. The policy rebuilds only
21
+ // this validated alias, never its containing home/workspace.
22
+ assets.add(path);
23
+ assets.add(canonical);
24
+ if (!trees.has(canonical)) {
25
+ trees.add(canonical);
26
+ pending.push(canonical);
27
+ // Packages in an aliased tree resolve from its real directory, which need not be
28
+ // named node_modules. Preserve that directory's own ancestor lookup trees too.
29
+ search(canonical);
30
+ }
31
+ };
32
+ const search = (entry) => {
33
+ const canonical = realpathSync(entry);
34
+ const directory = statSync(canonical).isDirectory() ? canonical : dirname(canonical);
35
+ if (searched.has(directory))
36
+ return;
37
+ searched.add(directory);
38
+ // Node skips node_modules/node_modules, but otherwise searches up to the root.
39
+ // NODE_PATH is scrubbed. Loaders needing Node's default global-prefix directories
40
+ // must supply those roots explicitly (as the SEA SDK loader does).
41
+ for (let ancestor = directory;; ancestor = dirname(ancestor)) {
42
+ if (basename(ancestor) !== "node_modules")
43
+ addTree(join(ancestor, "node_modules"));
44
+ if (ancestor === dirname(ancestor))
45
+ break;
46
+ }
47
+ };
48
+ for (const entry of entries)
49
+ search(entry);
50
+ const visitPackage = (path) => {
51
+ // Broken optional links are not existing assets. Other filesystem errors fail closed.
52
+ if (!existsSync(path))
53
+ return;
54
+ const canonical = realpathSync(path);
55
+ if (!statSync(canonical).isDirectory())
56
+ return;
57
+ if (canonical !== path) {
58
+ assets.add(canonical);
59
+ search(canonical);
60
+ }
61
+ // Nested installs may themselves contain external links, even in unlinked packages.
62
+ addTree(join(canonical, "node_modules"));
63
+ };
64
+ for (let index = 0; index < pending.length; index++) {
65
+ const tree = pending[index];
66
+ for (const entry of readdirSync(tree, { withFileTypes: true })) {
67
+ if (entry.name.startsWith("."))
68
+ continue; // .bin and package-manager metadata aren't packages.
69
+ const path = join(tree, entry.name);
70
+ if (!existsSync(path))
71
+ continue;
72
+ if (entry.name.startsWith("@") && statSync(path).isDirectory()) {
73
+ const canonical = realpathSync(path);
74
+ if (canonical !== path)
75
+ assets.add(canonical);
76
+ for (const name of readdirSync(path))
77
+ visitPackage(join(path, name));
78
+ }
79
+ else
80
+ visitPackage(path);
81
+ }
82
+ }
83
+ return [...assets];
84
+ }
@@ -0,0 +1,40 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { prepareFilesystemIsolation } from "./filesystem.js";
4
+ /**
5
+ * Capability means an actual successful namespace/descriptor-mount launch, not an installed binary.
6
+ * prepareFilesystemIsolation itself runs /bin/true through the complete policy before returning.
7
+ * No credentials are staged, and the temporary Scope is separate from the real protected state root.
8
+ * This is a startup decision only: each subsequent restricted launch still fails closed on error.
9
+ */
10
+ export const detectFilesystemIsolationSupport = async (options) => {
11
+ if ((options.platform ?? process.platform) !== "linux") {
12
+ return { supported: false, reason: "Filesystem isolation requires Linux and Bubblewrap" };
13
+ }
14
+ let scope;
15
+ let isolation;
16
+ try {
17
+ // Never use operator TMPDIR, which can point into protected host state or a writable Scope.
18
+ scope = mkdtempSync(join("/tmp", "flow-isolation-support-"));
19
+ isolation = await prepareFilesystemIsolation({
20
+ scope, stateRoot: options.stateRoot, command: "/bin/true", args: [], credentials: "none",
21
+ ...(options.env === undefined ? {} : { env: options.env }),
22
+ });
23
+ return { supported: true };
24
+ }
25
+ catch (error) {
26
+ // The launch policy adds “unrestricted launch refused”; that is true for enabled launches,
27
+ // not a capability explanation when automatic selection legitimately chooses unrestricted.
28
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;
29
+ return { supported: false, reason: cause instanceof Error ? cause.message : String(cause) };
30
+ }
31
+ finally {
32
+ try {
33
+ isolation?.cleanup();
34
+ }
35
+ finally {
36
+ if (scope !== undefined)
37
+ rmSync(scope, { recursive: true, force: true });
38
+ }
39
+ }
40
+ };
@@ -0,0 +1,62 @@
1
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { nodeExecutionAssets } from "./node-assets.js";
4
+ /** Discover assets only; the filesystem policy must validate and pin every returned path. */
5
+ export function pathToolchainAssets(path, scope, hidden, protectedPath) {
6
+ const assets = new Set();
7
+ const entries = path.split(':').map(entry => {
8
+ const logical = isAbsolute(entry) ? entry : resolve(scope, entry || '.');
9
+ if (!existsSync(logical) || !statSync(logical).isDirectory())
10
+ return entry;
11
+ const directory = realpathSync(logical);
12
+ // Intentionally masked stores (e.g. Pi's credential directory in an inherited PATH) stay
13
+ // hidden. Only collateral ancestor-mask damage is repaired; explicit protected commands
14
+ // are still refused by the launch policy, and SDK resources use their narrow staging path.
15
+ if (protectedPath(directory))
16
+ return entry;
17
+ const masked = hidden(logical) || hidden(directory);
18
+ if (masked)
19
+ assets.add(directory);
20
+ // Rewriting masked directory aliases preserves command selection without mounting a broad
21
+ // home ancestor merely to restore a symlink such as ~/.nvm/current/bin -> versions/.../bin.
22
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
23
+ if (!entry.isSymbolicLink())
24
+ continue;
25
+ const candidate = join(directory, entry.name);
26
+ if (!existsSync(candidate))
27
+ continue;
28
+ const target = realpathSync(candidate);
29
+ if (!hidden(target) || protectedPath(target))
30
+ continue;
31
+ if (statSync(target).isDirectory()) {
32
+ assets.add(target);
33
+ continue;
34
+ }
35
+ let root = dirname(target);
36
+ // npm/npx/corepack launch scripts need their package's relative modules, not just the
37
+ // target file. A manifest identifies a narrow package; never infer an arbitrary ancestor.
38
+ for (let parent = root; parent !== dirname(parent); parent = dirname(parent)) {
39
+ if (existsSync(join(parent, 'package.json'))) {
40
+ root = parent;
41
+ break;
42
+ }
43
+ }
44
+ assets.add(root);
45
+ }
46
+ if (masked && basename(directory) === 'bin') {
47
+ const root = dirname(directory);
48
+ // Python virtual environments resolve their interpreter's prefix through this file.
49
+ if (existsSync(join(root, 'pyvenv.cfg')))
50
+ assets.add(root);
51
+ else
52
+ for (const name of ['lib', 'lib64']) {
53
+ const library = join(root, name);
54
+ if (existsSync(library) && statSync(library).isDirectory() && hidden(library))
55
+ assets.add(realpathSync(library));
56
+ }
57
+ }
58
+ return masked ? directory : entry;
59
+ });
60
+ const paths = [...assets];
61
+ return { path: entries.join(':'), assets: [...paths, ...nodeExecutionAssets(paths)] };
62
+ }