@justjoshn/pi-pstack-v2 0.1.7 → 0.2.0
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.
- package/README.md +13 -7
- package/docs/guide/01-setup.md +3 -3
- package/docs/guide/02-poteto-mode.md +1 -1
- package/docs/guide/07-overnight.md +3 -3
- package/docs/pi-mechanisms.md +20 -38
- package/package.json +5 -3
- package/skills/benchmark-checklist/SKILL.md +1 -1
- package/skills/control-cli/SKILL.md +1 -1
- package/skills/make-bot-ui/SKILL.md +2 -2
- package/skills/poteto-mode/SKILL.md +2 -2
- package/skills/poteto-mode/playbooks/autopilot-full.md +2 -2
- package/skills/poteto-mode/playbooks/babysit.md +1 -1
- package/skills/poteto-mode/playbooks/shipping.md +2 -2
- package/skills/statechart/SKILL.md +1 -1
- package/skills/statechart/references/render.md +1 -1
- package/src/gondolin/bash.ts +51 -0
- package/src/gondolin/fs-operations.ts +56 -0
- package/src/gondolin/grep.ts +96 -0
- package/src/gondolin/index.ts +51 -0
- package/src/gondolin/paths.ts +34 -0
- package/src/gondolin/search.ts +67 -0
- package/src/gondolin/tools.ts +40 -0
- package/src/gondolin/vm.ts +62 -0
- package/src/index.ts +31 -130
- package/src/jobs.ts +58 -315
- package/src/credentials.ts +0 -171
- package/src/git.ts +0 -94
- package/src/paths.ts +0 -16
- package/src/requests.ts +0 -182
- package/src/sandbox.ts +0 -284
- package/src/sweep.ts +0 -187
- package/src/transcript.ts +0 -79
package/src/git.ts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
-
import { basename, dirname, join, resolve } from 'node:path';
|
|
4
|
-
|
|
5
|
-
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
6
|
-
import { landing, within } from './paths.ts';
|
|
7
|
-
import { codePaths, PI_CODE } from './sweep.ts';
|
|
8
|
-
|
|
9
|
-
export function git(cwd: string, args: string[]): string {
|
|
10
|
-
return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** Like `git`, but undefined when git exits non-zero, is killed, or does not start. */
|
|
14
|
-
function tryGit(cwd: string, args: string[]): string | undefined {
|
|
15
|
-
const result = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
16
|
-
return result.status === 0 ? result.stdout.trim() : undefined;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function gitPath(cwd: string, flag: '--git-common-dir' | '--show-toplevel' | '--absolute-git-dir'): string | undefined {
|
|
20
|
-
const found = tryGit(cwd, ['rev-parse', flag]);
|
|
21
|
-
return found === undefined ? undefined : resolve(cwd, found);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** A job may only work inside the session's project, so the model cannot widen its own sandbox by naming another directory. */
|
|
25
|
-
export function projectPath(ctx: ExtensionContext, path: string | undefined): string {
|
|
26
|
-
const root = realpathSync(gitPath(ctx.cwd, '--show-toplevel') ?? ctx.cwd);
|
|
27
|
-
const target = realpathSync(path === undefined ? ctx.cwd : resolve(ctx.cwd, path));
|
|
28
|
-
// A linked worktree of the same repository, such as a worker's checkout, is the same project on another branch.
|
|
29
|
-
const common = gitPath(ctx.cwd, '--git-common-dir');
|
|
30
|
-
const targetCommon = gitPath(target, '--git-common-dir');
|
|
31
|
-
const sameRepository = common !== undefined && targetCommon !== undefined && landing(targetCommon) === landing(common);
|
|
32
|
-
const worktree = sameRepository ? gitPath(target, '--show-toplevel') : undefined;
|
|
33
|
-
if (!within(target, [root, ...(worktree ? [worktree] : [])])) throw new Error(`cwd must be inside this project (${root}), got ${target}. To work on another branch, pass worktree and the job gets its own checkout.`);
|
|
34
|
-
// A checkout of another repository can sit inside the project, and a job there would be handed that repository's git directory.
|
|
35
|
-
if (targetCommon !== undefined && !sameRepository && !within(targetCommon, [root])) throw new Error(`cwd ${target} is a checkout of another repository (${targetCommon}). A job works only in this session's repository.`);
|
|
36
|
-
return target;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Each existing directory above `path` up to, and excluding, the checkout. */
|
|
40
|
-
function existingAncestors(path: string, cwd: string): string[] {
|
|
41
|
-
const dir = dirname(path);
|
|
42
|
-
if (!within(dir, [cwd]) || dir === cwd) return [];
|
|
43
|
-
return [...(existsSync(dir) ? [dir] : []), ...existingAncestors(dir, cwd)];
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Paths an unsandboxed process later executes from: git hooks and config, Pi's project extensions and settings, and
|
|
48
|
-
* editor and agent-harness configuration. Git finds hooks through `.git`, and in a linked worktree through its `commondir`
|
|
49
|
-
* and `gitdir` files, so each of those is protected too. A job that could repoint any of them would make the next
|
|
50
|
-
* `git commit` run its own hooks unsandboxed.
|
|
51
|
-
*/
|
|
52
|
-
export function protectedPaths(cwd: string, common: string | undefined): { protect: string[]; lock: string[]; gitDirs: string[] } {
|
|
53
|
-
// Every code entry already in the checkout, at any depth, since Pi, git, editors, and harnesses find them anywhere.
|
|
54
|
-
const found = codePaths([cwd]);
|
|
55
|
-
const piDirs = [...new Set([join(cwd, '.pi'), ...found.filter((path) => basename(dirname(path)) === '.pi').map(dirname)])];
|
|
56
|
-
const pi = piDirs.flatMap((dir) => PI_CODE.map((name) => join(dir, name)));
|
|
57
|
-
// The checkout's own .git is its git directory, which the job may write. Any other is a repository git would run hooks
|
|
58
|
-
// from, and an editor or harness entry runs as it stands. `pi` already covers each .pi directory, and a .pi link stays as it is.
|
|
59
|
-
const others = found.filter((path) => basename(path) !== '.pi' && basename(dirname(path)) !== '.pi' && path !== join(cwd, '.git'));
|
|
60
|
-
let protect = [...pi, ...others];
|
|
61
|
-
let lock: string[] = [];
|
|
62
|
-
if (common) {
|
|
63
|
-
const own = gitPath(cwd, '--absolute-git-dir') ?? common;
|
|
64
|
-
const worktree = own === common ? [] : [join(cwd, '.git'), ...['commondir', 'gitdir', 'config.worktree'].map((name) => join(own, name))];
|
|
65
|
-
const configured = tryGit(cwd, ['config', '--get', 'core.hooksPath']);
|
|
66
|
-
const hooksPath = configured ? [resolve(gitPath(cwd, '--show-toplevel') ?? cwd, configured)] : [];
|
|
67
|
-
protect = [...protect, join(common, 'hooks'), join(common, 'config'), join(common, 'config.worktree'), join(common, 'info'), ...worktree, ...hooksPath];
|
|
68
|
-
lock = [join(cwd, '.git'), own, common];
|
|
69
|
-
}
|
|
70
|
-
// A directory above a protected path could be renamed away and replaced, so each existing one up to the checkout is locked.
|
|
71
|
-
const ancestors = protect.flatMap((path) => existingAncestors(path, cwd));
|
|
72
|
-
return { protect, lock: [...new Set([...lock, ...ancestors])], gitDirs: common ? [common] : [] };
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Adds the worktree and returns whether it created the branch, so a failed start can remove it. */
|
|
76
|
-
export function addWorktree(cwd: string, path: string, branch: string, base: string | undefined): boolean {
|
|
77
|
-
if (branch.startsWith('-') || base?.startsWith('-')) throw new Error('worktree and base cannot start with "-".');
|
|
78
|
-
const exists = tryGit(cwd, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]) !== undefined;
|
|
79
|
-
git(cwd, exists ? ['worktree', 'add', path, branch] : ['worktree', 'add', '-b', branch, path, base === undefined ? 'HEAD' : baseOrSoleRemoteBranch(cwd, base)]);
|
|
80
|
-
return !exists;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function dropWorktree(repo: string, createdBranch: string | undefined): void {
|
|
84
|
-
git(repo, ['worktree', 'prune']);
|
|
85
|
-
if (createdBranch !== undefined) git(repo, ['branch', '-D', createdBranch]);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function baseOrSoleRemoteBranch(cwd: string, base: string): string {
|
|
89
|
-
if (tryGit(cwd, ['rev-parse', '--verify', '--quiet', `${base}^{commit}`]) !== undefined) return base;
|
|
90
|
-
const remote = git(cwd, ['for-each-ref', '--format=%(refname:short)', `refs/remotes/*/${base}`])
|
|
91
|
-
.split('\n')
|
|
92
|
-
.filter(Boolean);
|
|
93
|
-
return remote.length === 1 ? (remote[0] ?? base) : base;
|
|
94
|
-
}
|
package/src/paths.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { existsSync, realpathSync } from 'node:fs';
|
|
2
|
-
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
3
|
-
|
|
4
|
-
/** Resolves symlinks in the longest existing prefix, so a path that does not exist yet still compares by where it would land. */
|
|
5
|
-
export function landing(path: string): string {
|
|
6
|
-
const absolute = resolve(path);
|
|
7
|
-
if (existsSync(absolute)) return realpathSync(absolute);
|
|
8
|
-
const parent = dirname(absolute);
|
|
9
|
-
return parent === absolute ? absolute : join(landing(parent), relative(parent, absolute));
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export const within = (path: string, roots: string[]): boolean =>
|
|
13
|
-
roots.some((root) => {
|
|
14
|
-
const inside = relative(landing(root), landing(path));
|
|
15
|
-
return inside !== '..' && !inside.startsWith(`..${sep}`) && !isAbsolute(inside);
|
|
16
|
-
});
|
package/src/requests.ts
DELETED
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import { basename, join } from 'node:path';
|
|
4
|
-
|
|
5
|
-
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
6
|
-
import { z } from 'zod';
|
|
7
|
-
import { jobAgentDir } from './credentials.ts';
|
|
8
|
-
import { addWorktree, dropWorktree, gitPath, protectedPaths } from './git.ts';
|
|
9
|
-
import { brokeredSession, exitPath, type Job, type JobSpec, launchBrokered, readSpec, resultsDir, settleBrokered } from './jobs.ts';
|
|
10
|
-
import { landing, within } from './paths.ts';
|
|
11
|
-
import { type SandboxPolicy, sandboxed } from './sandbox.ts';
|
|
12
|
-
|
|
13
|
-
const MAX_REQUEST_DEPTH = 8;
|
|
14
|
-
const EXIT_REFUSED = 126;
|
|
15
|
-
const EXIT_LOST = 137;
|
|
16
|
-
const EXIT_LAUNCH_FAILED = 127;
|
|
17
|
-
const strings = z.array(z.string());
|
|
18
|
-
|
|
19
|
-
type CreatedWorktree = { path: string; repo: string; createdBranch: string | undefined };
|
|
20
|
-
|
|
21
|
-
const requestedWorktreePath = (out: string): string => landing(join(out, 'worktree'));
|
|
22
|
-
|
|
23
|
-
function createRequestedWorktree(top: Job, spec: JobSpec, out: string, grant: string[]): CreatedWorktree | { refused: string } {
|
|
24
|
-
const asked: unknown = spec.createWorktree;
|
|
25
|
-
if (spec.kind !== 'pi' || typeof asked !== 'object' || asked === null) return { refused: 'Only a Pi worker request can ask for a worktree.' };
|
|
26
|
-
const { branch, base } = asked as Record<string, unknown>;
|
|
27
|
-
if (typeof branch !== 'string' || (base !== undefined && typeof base !== 'string')) return { refused: 'Its worktree request is malformed.' };
|
|
28
|
-
const repo = top.spec.cwd;
|
|
29
|
-
const common = gitPath(repo, '--git-common-dir');
|
|
30
|
-
if (common === undefined || !within(common, grant)) return { refused: `The worker that asked may not write the repository at ${repo}, so it cannot get a worktree of it.` };
|
|
31
|
-
const path = requestedWorktreePath(out);
|
|
32
|
-
try {
|
|
33
|
-
return { path, repo, createdBranch: addWorktree(repo, path, branch, base) ? branch : undefined };
|
|
34
|
-
} catch (error) {
|
|
35
|
-
return { refused: `pstack could not create the worktree: ${error instanceof Error ? error.message : String(error)}` };
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** The checkouts a job may write, and the protected paths in them, which its wrapper sweeps after it for code that appeared. */
|
|
40
|
-
export const sweepFor = (policy: SandboxPolicy): JobSpec['sweep'] => ({
|
|
41
|
-
// A job's own session, nested, temp, and agent directories live under Pi's agent directory. A worktree does too, and is a checkout.
|
|
42
|
-
roots: policy.writable.filter((path) => (basename(path) === 'worktree' || !within(path, [policy.agentDir])) && !within(path, policy.gitDirs)),
|
|
43
|
-
protect: policy.protect.filter((path) => within(path, policy.writable)),
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
const readGrant = (out: string): string[] => {
|
|
47
|
-
try {
|
|
48
|
-
const grant = strings.safeParse(JSON.parse(readFileSync(join(out, 'granted.json'), 'utf8')));
|
|
49
|
-
return grant.success ? grant.data : [];
|
|
50
|
-
} catch {
|
|
51
|
-
return [];
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
const isStrings = (value: unknown): value is string[] => strings.safeParse(value).success;
|
|
56
|
-
|
|
57
|
-
// A session that is already gone makes this fail, which is expected.
|
|
58
|
-
const tmuxKill = (socket: string, session: string): void => {
|
|
59
|
-
spawnSync('tmux', ['-S', socket, 'kill-session', '-t', `=${session}`], { stdio: 'ignore' });
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
const hasSession = (socket: string, session: string): boolean => spawnSync('tmux', ['-S', socket, 'has-session', '-t', `=${session}`], { stdio: 'ignore' }).status === 0;
|
|
63
|
-
|
|
64
|
-
/** A worker writes these files, so anything malformed is skipped instead of stopping every other request. */
|
|
65
|
-
const wellFormed = (spec: JobSpec): boolean => {
|
|
66
|
-
const policy = spec.policy;
|
|
67
|
-
if (!policy || (spec.kind !== 'pi' && spec.kind !== 'command') || typeof spec.cwd !== 'string' || !isStrings(spec.command) || spec.command.length === 0) return false;
|
|
68
|
-
return [policy.writable, policy.protect, policy.lock, policy.gitDirs].every(isStrings);
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
/** What a request asked to write or run in that its requester may not, or undefined when it is allowed. */
|
|
72
|
-
function refusalFor(top: Job, spec: JobSpec, worktree: string | undefined, grant: string[]): string | undefined {
|
|
73
|
-
const checked = spec.policy.writable.map(landing).filter((path) => path !== worktree);
|
|
74
|
-
const cwdAllowed = worktree === undefined ? within(spec.cwd, [top.spec.cwd, ...grant]) : landing(spec.cwd) === worktree;
|
|
75
|
-
const refused = [...checked.filter((path) => !within(path, grant)), ...(cwdAllowed ? [] : [`cwd ${spec.cwd}`])];
|
|
76
|
-
return refused.length ? `pstack refused to launch this job. It asked to write outside what the job that requested it may write: ${refused.join(', ')}` : undefined;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Ends the tmux session of a launched request whose requester is done, and settles one that vanished. */
|
|
80
|
-
function superviseLaunched(socket: string, session: string, out: string, ending: boolean): void {
|
|
81
|
-
if (ending) tmuxKill(socket, session);
|
|
82
|
-
else if (!hasSession(socket, session)) settleBrokered(out, EXIT_LOST, 'pstack lost this job: its tmux session ended without an exit code.');
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
type Launch = { top: Job; socket: string; spec: JobSpec; dir: string; out: string; grant: string[] };
|
|
86
|
-
|
|
87
|
-
/** Builds the policy a request runs under from the paths just validated, so swapping a link afterwards changes nothing. */
|
|
88
|
-
function grantedPolicy({ top, dir }: Launch, writable: string[], guarded: { protect: string[]; lock: string[]; gitDirs: string[] }): SandboxPolicy {
|
|
89
|
-
const base: SandboxPolicy = {
|
|
90
|
-
writable,
|
|
91
|
-
protect: [...guarded.protect, ...top.spec.policy.protect],
|
|
92
|
-
lock: [...guarded.lock, ...top.spec.policy.lock],
|
|
93
|
-
gitDirs: [...guarded.gitDirs, ...top.spec.policy.gitDirs],
|
|
94
|
-
checkouts: [],
|
|
95
|
-
credentials: jobAgentDir(top.dir),
|
|
96
|
-
agentDir: getAgentDir(),
|
|
97
|
-
jobDir: dir,
|
|
98
|
-
};
|
|
99
|
-
return { ...base, checkouts: sweepFor(base).roots };
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function startRequest(request: Launch, made: CreatedWorktree | undefined, checked: string[], writesWorktree: boolean): boolean {
|
|
103
|
-
const { top, socket, spec, dir, out } = request;
|
|
104
|
-
const common = made === undefined ? undefined : gitPath(made.path, '--git-common-dir');
|
|
105
|
-
const guarded = made === undefined ? spec.policy : protectedPaths(made.path, common);
|
|
106
|
-
const writable = made !== undefined && writesWorktree ? [...checked, made.path, ...(common ? [landing(common)] : [])] : checked;
|
|
107
|
-
const granted = grantedPolicy(request, writable, guarded);
|
|
108
|
-
mkdirSync(out, { recursive: true });
|
|
109
|
-
writeFileSync(join(out, 'granted.json'), JSON.stringify(writable));
|
|
110
|
-
// The worker supplies tmp, so it is trusted only if it is one of the writable paths validated above.
|
|
111
|
-
const { tmp: asked, ...rest } = spec;
|
|
112
|
-
const tmp = typeof asked === 'string' && writable.includes(landing(asked)) ? landing(asked) : undefined;
|
|
113
|
-
return launchBrokered(top.dir, dir, { ...rest, ...(made ? { cwd: made.path } : {}), ...(tmp ? { tmp } : {}) }, sweepFor(granted), sandboxed(spec.command, granted), socket);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Validates a not yet launched request against its requester's grant, then launches it or settles it as refused. */
|
|
117
|
-
function launchRequest(request: Launch): void {
|
|
118
|
-
const { top, spec, out, grant } = request;
|
|
119
|
-
const worktree = spec.createWorktree === undefined ? undefined : requestedWorktreePath(out);
|
|
120
|
-
const asked = spec.policy.writable.map(landing);
|
|
121
|
-
const refusal = refusalFor(top, spec, worktree, grant);
|
|
122
|
-
if (refusal) {
|
|
123
|
-
settleBrokered(out, EXIT_REFUSED, refusal);
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
const made = worktree === undefined ? undefined : createRequestedWorktree(top, spec, out, grant);
|
|
127
|
-
if (made !== undefined && 'refused' in made) {
|
|
128
|
-
settleBrokered(out, EXIT_REFUSED, `pstack refused to launch this job. ${made.refused}`);
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
const checked = asked.filter((path) => path !== worktree);
|
|
132
|
-
let launched = false;
|
|
133
|
-
try {
|
|
134
|
-
launched = startRequest(request, made, checked, worktree !== undefined && asked.includes(worktree));
|
|
135
|
-
} catch (error) {
|
|
136
|
-
settleBrokered(out, EXIT_LAUNCH_FAILED, `pstack could not launch this job: ${error instanceof Error ? error.message : String(error)}`);
|
|
137
|
-
}
|
|
138
|
-
if (made !== undefined && !launched) {
|
|
139
|
-
rmSync(made.path, { recursive: true, force: true });
|
|
140
|
-
dropWorktree(made.repo, made.createdBranch);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function serveRequest(top: Job, socket: string, dir: string, requesterDone: boolean, depth: number, grant: string[]): void {
|
|
145
|
-
// A worker could link an entry back up its own tree, so only real directories are followed.
|
|
146
|
-
if (!lstatSync(dir).isDirectory()) return;
|
|
147
|
-
const spec = readSpec(dir);
|
|
148
|
-
if (!spec || !wellFormed(spec)) return;
|
|
149
|
-
const out = resultsDir(top.dir, dir);
|
|
150
|
-
const stopped = existsSync(join(dir, 'stop'));
|
|
151
|
-
const done = existsSync(exitPath(out)) || stopped;
|
|
152
|
-
// A request's own requests may write only what the root granted it, recorded where no worker can write.
|
|
153
|
-
serveRequests(top, socket, join(dir, 'nested'), requesterDone || done, depth + 1, readGrant(out));
|
|
154
|
-
if (!spec.brokered || existsSync(exitPath(out))) return;
|
|
155
|
-
if (existsSync(join(out, 'launched'))) {
|
|
156
|
-
superviseLaunched(socket, brokeredSession(dir), out, requesterDone || stopped);
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
if (requesterDone || stopped) return;
|
|
160
|
-
if (spec.kind === 'pi' && depth > 0) {
|
|
161
|
-
settleBrokered(out, EXIT_REFUSED, 'pstack refused to start this Pi worker. A worker started by another worker cannot start workers of its own.');
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
launchRequest({ top, socket, spec, dir, out, grant });
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Launches the requests that sandboxed workers under one of this session's jobs wrote. A request may write only inside
|
|
169
|
-
* what the root granted the top-level job, so no worker can hand a descendant more than it was given. The root only
|
|
170
|
-
* reads from the request directory, which a worker controls, and writes results under the top-level job.
|
|
171
|
-
*/
|
|
172
|
-
export function serveRequests(top: Job, socket: string, nested: string, requesterDone: boolean, depth = 0, grant: string[] = top.spec.policy.writable): void {
|
|
173
|
-
// A worker could link its nested directory back up its own tree, so only real directories are followed, and not far.
|
|
174
|
-
if (depth > MAX_REQUEST_DEPTH || !existsSync(nested) || !lstatSync(nested).isDirectory()) return;
|
|
175
|
-
for (const name of readdirSync(nested)) {
|
|
176
|
-
try {
|
|
177
|
-
serveRequest(top, socket, join(nested, name), requesterDone, depth, grant);
|
|
178
|
-
} catch {
|
|
179
|
-
// One request failing must not stop the others.
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
package/src/sandbox.ts
DELETED
|
@@ -1,284 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import { basename, dirname, join } from 'node:path';
|
|
4
|
-
|
|
5
|
-
import { hostEnv } from './host-env.ts';
|
|
6
|
-
import { passthroughObject } from './object-schema.ts';
|
|
7
|
-
import { EDITOR_CODE, HARNESS_DIRS, HARNESS_INSTRUCTIONS, WORKSPACE_SUFFIX } from './sweep.ts';
|
|
8
|
-
|
|
9
|
-
type Env = NodeJS.ProcessEnv;
|
|
10
|
-
type Arch = NodeJS.Architecture;
|
|
11
|
-
type Platform = NodeJS.Platform;
|
|
12
|
-
|
|
13
|
-
export const SANDBOX_ENV = 'PSTACK_V2_SANDBOXED';
|
|
14
|
-
/** The job directory of the sandboxed process. Jobs it asks the root to start are requested under its writable `nested/` directory. */
|
|
15
|
-
export const JOB_DIR_ENV = 'PSTACK_V2_JOB_DIR';
|
|
16
|
-
/** The directory of the top-level job a process descends from. Its `brokered/` directory holds what the root launched for descendants. */
|
|
17
|
-
export const TOP_DIR_ENV = 'PSTACK_V2_TOP_DIR';
|
|
18
|
-
|
|
19
|
-
export interface SandboxPolicy {
|
|
20
|
-
/** Paths the job may write. */
|
|
21
|
-
writable: string[];
|
|
22
|
-
/** Paths inside `writable` that stay read-only because an unsandboxed process would execute what they hold, such as git hooks. */
|
|
23
|
-
protect: string[];
|
|
24
|
-
/** Paths whose own entry may not be renamed, removed, or replaced, while writes inside them stay allowed, such as `.git`. */
|
|
25
|
-
lock: string[];
|
|
26
|
-
/** Git common directories the job may write. Every worktree and submodule redirection file under them stays read-only. */
|
|
27
|
-
gitDirs: string[];
|
|
28
|
-
/** Checkouts the job may write. No `.pi` code entry or `.git` entry anywhere in them may be written, even one that does not exist yet. */
|
|
29
|
-
checkouts: string[];
|
|
30
|
-
agentDir: string;
|
|
31
|
-
/**
|
|
32
|
-
* The job's own Pi agent directory, shared with every job its top-level job starts. Only the contents of its credentials
|
|
33
|
-
* copy and Pi's lock directories are writable, so no job can change what another job's Pi loads.
|
|
34
|
-
*/
|
|
35
|
-
credentials: string;
|
|
36
|
-
/** The job's own directory. Jobs it asks the root to start are requested under its `nested/` directory. */
|
|
37
|
-
jobDir: string;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** A policy read back from a job's spec file, as written: its keys are not checked here, and requests.ts checks the lists it relies on. */
|
|
41
|
-
export const SandboxPolicySchema = passthroughObject<SandboxPolicy>();
|
|
42
|
-
|
|
43
|
-
const real = (path: string): string => (existsSync(path) ? realpathSync(path) : path);
|
|
44
|
-
/** A path as the kernel sees it when the entry itself is the target: the real parent plus the entry's own name, links unresolved. */
|
|
45
|
-
const entry = (path: string): string => join(real(dirname(path)), basename(path));
|
|
46
|
-
const escapeRegex = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
47
|
-
const quote = (text: string): string => JSON.stringify(text);
|
|
48
|
-
|
|
49
|
-
// tmux servers outside the sandbox run commands unsandboxed, so a job may not connect to their sockets or replace them.
|
|
50
|
-
const TMUX_SOCKETS = '^/private/(tmp|var/folders/[^/]+/[^/]+/T)/(tmux|pstack-v2)-';
|
|
51
|
-
// Files through which git finds a worktree's or submodule's hooks and config.
|
|
52
|
-
const gitRedirects = (common: string): string => `^${escapeRegex(real(common))}/(config\\.worktree|worktrees/[^/]+/(commondir|gitdir|config\\.worktree)|modules/.+/(hooks|config|info|commondir|gitdir|config\\.worktree))(/|$)`;
|
|
53
|
-
|
|
54
|
-
/** The git directories of the linked worktrees the job works in, which it may write apart from their redirection files. */
|
|
55
|
-
const ownWorktrees = (policy: SandboxPolicy): string[] => policy.lock.filter((path) => policy.gitDirs.some((common) => dirname(path) === join(common, 'worktrees')));
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* bubblewrap can only make read-only what exists, so the git paths a job may not create are created first, empty. Git
|
|
59
|
-
* reads an empty `config.worktree` as no settings, and empty `hooks`, `info`, `worktrees`, and `modules` directories as none.
|
|
60
|
-
*/
|
|
61
|
-
function placeholders(policy: SandboxPolicy): void {
|
|
62
|
-
for (const common of policy.gitDirs) {
|
|
63
|
-
if (!existsSync(common)) continue;
|
|
64
|
-
for (const name of ['hooks', 'info', 'worktrees', 'modules']) mkdirSync(join(common, name), { recursive: true });
|
|
65
|
-
for (const dir of [common, ...ownWorktrees(policy)]) if (existsSync(dir) && !existsSync(join(dir, 'config.worktree'))) writeFileSync(join(dir, 'config.worktree'), '');
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** Rules refusing a checkout's git entries, Pi code, and editor and harness configuration. */
|
|
70
|
-
function checkoutRules(policy: SandboxPolicy): string[] {
|
|
71
|
-
return [
|
|
72
|
-
// Any .git a checkout gains is a repository git would run hooks from, apart from the checkout's own git directory.
|
|
73
|
-
...policy.checkouts.map((root) => {
|
|
74
|
-
const git = existsSync(join(root, '.git')) && statSync(join(root, '.git')).isDirectory() ? '.+/\\.git' : '(.*/)?\\.git';
|
|
75
|
-
return `(deny file-write* (regex #"^${escapeRegex(real(root))}/(${git}|(.*/)?\\.pi/(extensions|settings\\.json|mcp\\.json|npm|git))(/|$)"))`;
|
|
76
|
-
}),
|
|
77
|
-
// Editor and agent-harness configuration runs unsandboxed when the checkout is opened, so it is refused at any depth,
|
|
78
|
-
// apart from the harnesses' instruction directories.
|
|
79
|
-
...policy.checkouts.map((root) => {
|
|
80
|
-
const under = `^${escapeRegex(real(root))}/(.*/)?`;
|
|
81
|
-
const alt = (names: readonly string[]): string => names.map(escapeRegex).join('|');
|
|
82
|
-
const harness = `${under}(${alt(HARNESS_DIRS)})`;
|
|
83
|
-
return `(deny file-write* (regex #"${under}(${alt(EDITOR_CODE)}|[^/]*${escapeRegex(WORKSPACE_SUFFIX)})(/|$)") (require-all (regex #"${harness}(/|$)") (require-not (regex #"${harness}/(${alt(HARNESS_INSTRUCTIONS)})(/|$)"))))`;
|
|
84
|
-
}),
|
|
85
|
-
];
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Rules that hold for every job: local sockets, launch services, signals, and preference writes. */
|
|
89
|
-
const SEATBELT_TAIL: string[] = [
|
|
90
|
-
// Any local service socket could start a process outside the sandbox, such as Docker's, so only DNS is reachable.
|
|
91
|
-
'(deny network-outbound (remote unix-socket))',
|
|
92
|
-
// biome-ignore lint/security/noSecrets: macOS DNS uses this fixed mDNSResponder Unix socket path.
|
|
93
|
-
'(allow network-outbound (remote unix-socket (path-literal "/private/var/run/mDNSResponder")))',
|
|
94
|
-
// Nor may it serve one, such as a tmux server of its own. Linux refuses the same through seccomp.
|
|
95
|
-
'(deny network-bind (local unix-socket))',
|
|
96
|
-
// Services that start processes on a caller's behalf would run them outside the sandbox: LaunchServices (`open`) and Apple Events.
|
|
97
|
-
// `open -a` on an app the job wrote launches it through launchd, so the lookup rules below cannot stop it, and lsopen does.
|
|
98
|
-
'(deny appleevent-send)',
|
|
99
|
-
'(deny lsopen)',
|
|
100
|
-
// A job may signal only processes in its own sandbox, never the wrapper that cleans up after it or the root Pi.
|
|
101
|
-
'(deny signal)',
|
|
102
|
-
'(allow signal (target same-sandbox))',
|
|
103
|
-
// launchservicesd stays reachable because Firefox checks in with it at startup and aborts without it. Opening goes through lsopen.
|
|
104
|
-
'(deny mach-lookup (global-name-regex #"^com\\.apple\\.lsd\\.") (global-name "com.apple.coreservices.appleevents"))',
|
|
105
|
-
// launchd would run a job it is handed outside the sandbox, and preference writes go through a daemon outside it.
|
|
106
|
-
'(deny mach-lookup (global-name-regex #"^com\\.apple\\.xpc\\.launchd\\."))',
|
|
107
|
-
'(deny user-preference-write)',
|
|
108
|
-
];
|
|
109
|
-
|
|
110
|
-
export function seatbeltProfile(policy: SandboxPolicy): string {
|
|
111
|
-
const subpaths = (paths: string[]): string => paths.map((path) => `(subpath ${quote(real(path))})`).join(' ');
|
|
112
|
-
// A protected path that is itself a symlink is guarded at the link as well as at its target, so it cannot be swapped.
|
|
113
|
-
const guarded = [...policy.protect.map((path) => `(subpath ${quote(real(path))}) (literal ${quote(entry(path))})`), ...policy.lock.map((path) => `(literal ${quote(real(path))}) (literal ${quote(entry(path))})`)];
|
|
114
|
-
const inAgentDir = policy.writable.filter((path) => real(path) === real(policy.agentDir) || real(path).startsWith(`${real(policy.agentDir)}/`));
|
|
115
|
-
const lines = [
|
|
116
|
-
'(version 1)',
|
|
117
|
-
'(allow default)',
|
|
118
|
-
// Later rules win, so the order is the job's own paths, then Pi's agent directory closed even when a job path holds
|
|
119
|
-
// it, then the job's own paths inside it, then the paths an unsandboxed process would execute from. Shared temp
|
|
120
|
-
// directories are not writable: unsandboxed programs load code cached there, so each job gets its own.
|
|
121
|
-
'(deny file-write*)',
|
|
122
|
-
`(allow file-write* (literal "/dev/null") (literal "/dev/ptmx") (regex #"^/dev/tty") (regex #"^/dev/fd/") ${subpaths(policy.writable)})`,
|
|
123
|
-
`(deny file-write* (subpath ${quote(real(policy.agentDir))}))`,
|
|
124
|
-
// Inside Pi's agent directory only the job's own paths are writable, its session, nested jobs, temp, and its own agent
|
|
125
|
-
// directory with its credentials copy. Your real auth.json and settings are never writable.
|
|
126
|
-
...(inAgentDir.length ? [`(allow file-write* ${subpaths(inAgentDir)})`] : []),
|
|
127
|
-
...(policy.credentials ? [`(allow file-write-data (literal ${quote(join(real(policy.credentials), 'auth.json'))}))`, `(allow file-write* (regex #"^${escapeRegex(real(policy.credentials))}/[^/]+\\.lock(/|$)"))`] : []),
|
|
128
|
-
// A job may not add or change a worktree or submodule, apart from the metadata of the worktree it works in.
|
|
129
|
-
...policy.gitDirs.map((common) => `(deny file-write* (subpath ${quote(real(join(common, 'worktrees')))}) (subpath ${quote(real(join(common, 'modules')))}))`),
|
|
130
|
-
...(ownWorktrees(policy).length ? [`(allow file-write* ${subpaths(ownWorktrees(policy))})`] : []),
|
|
131
|
-
`(deny file-write* (regex #"${TMUX_SOCKETS}") ${guarded.join(' ')} ${policy.gitDirs.map((common) => `(regex #"${gitRedirects(common)}")`).join(' ')})`,
|
|
132
|
-
...checkoutRules(policy),
|
|
133
|
-
...SEATBELT_TAIL,
|
|
134
|
-
];
|
|
135
|
-
return lines.join('\n');
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const REDIRECT_FILES = ['commondir', 'gitdir', 'config.worktree'];
|
|
139
|
-
const MODULE_REDIRECTS = ['hooks', 'config', 'info', ...REDIRECT_FILES];
|
|
140
|
-
const MAX_MODULE_DEPTH = 6;
|
|
141
|
-
|
|
142
|
-
/** Existing worktree and submodule redirection files under a git common directory, for bubblewrap, which can only bind what exists. */
|
|
143
|
-
function existingRedirects(common: string): string[] {
|
|
144
|
-
const worktrees = join(common, 'worktrees');
|
|
145
|
-
const linked = existsSync(worktrees) ? readdirSync(worktrees).flatMap((name) => REDIRECT_FILES.map((file) => join(worktrees, name, file))) : [];
|
|
146
|
-
const walk = (dir: string, depth: number): string[] => {
|
|
147
|
-
if (depth > MAX_MODULE_DEPTH || !existsSync(dir)) return [];
|
|
148
|
-
return readdirSync(dir).flatMap((name) => {
|
|
149
|
-
const path = join(dir, name);
|
|
150
|
-
if (MODULE_REDIRECTS.includes(name)) return [path];
|
|
151
|
-
return statSync(path).isDirectory() ? walk(path, depth + 1) : [];
|
|
152
|
-
});
|
|
153
|
-
};
|
|
154
|
-
return [join(common, 'config.worktree'), ...linked, ...walk(join(common, 'modules'), 0)].filter(existsSync);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const ROOT_DIR = '/';
|
|
158
|
-
const DEV_DIR = '/dev';
|
|
159
|
-
const PROC_DIR = '/proc';
|
|
160
|
-
const PRIVATE_TMP_DIR = '/tmp';
|
|
161
|
-
const RUN_DIR = '/run';
|
|
162
|
-
const VAR_RUN_DIR = '/var/run';
|
|
163
|
-
const SYSTEMD_RESOLVE_DIR = '/run/systemd/resolve';
|
|
164
|
-
const RESOLVCONF_DIR = '/run/resolvconf';
|
|
165
|
-
const RESOLVER_DIRS = [SYSTEMD_RESOLVE_DIR, RESOLVCONF_DIR];
|
|
166
|
-
const SHELL = '/bin/sh';
|
|
167
|
-
|
|
168
|
-
const bind = (flag: string, path: string): string[] => [flag, path, path];
|
|
169
|
-
|
|
170
|
-
/** The job's agent directory becomes a throwaway tmpfs holding its entries read-only, and only its credentials copy is bound writable. */
|
|
171
|
-
const credentialMounts = (credentials: string): string[] =>
|
|
172
|
-
credentials && existsSync(credentials) ? ['--tmpfs', credentials, ...readdirSync(credentials).flatMap((name) => bind(name === 'auth.json' ? '--bind' : '--ro-bind', join(credentials, name)))] : [];
|
|
173
|
-
|
|
174
|
-
export function bwrapArgs(policy: SandboxPolicy, env: Env = hostEnv(), uid: number = process.getuid?.() ?? 0): string[] {
|
|
175
|
-
// Service sockets live under /run, such as Docker's and the system bus, so it is hidden, except the DNS resolver's files.
|
|
176
|
-
const hidden = [...new Set([RUN_DIR, VAR_RUN_DIR, `/run/user/${uid}`, env['XDG_RUNTIME_DIR']])].filter((path): path is string => Boolean(path) && existsSync(path as string) && !lstatSync(path as string).isSymbolicLink());
|
|
177
|
-
const worktreeGitDirs = policy.gitDirs.flatMap((common) => ['worktrees', 'modules'].map((name) => join(common, name)).filter(existsSync));
|
|
178
|
-
return [
|
|
179
|
-
// Its own PID namespace means every process a job starts dies with it, and none can signal the wrapper outside.
|
|
180
|
-
// A private /tmp, since unsandboxed programs load code they cached in the shared one. It also hides outside tmux sockets.
|
|
181
|
-
...['--ro-bind', ROOT_DIR, ROOT_DIR, '--dev', DEV_DIR, '--proc', PROC_DIR, '--unshare-pid', '--tmpfs', PRIVATE_TMP_DIR],
|
|
182
|
-
// Pi's agent directory stays visible, read-only, even when it sits under the private /tmp.
|
|
183
|
-
...(existsSync(policy.agentDir) ? bind('--ro-bind', policy.agentDir) : []),
|
|
184
|
-
...policy.writable.filter(existsSync).flatMap((path) => bind('--bind', path)),
|
|
185
|
-
// Later mounts win, so everything below lands on top of the writable paths, even one that contains these.
|
|
186
|
-
...hidden.flatMap((path) => ['--tmpfs', path]),
|
|
187
|
-
...RESOLVER_DIRS.filter(existsSync).flatMap((path) => bind('--ro-bind', path)),
|
|
188
|
-
...credentialMounts(policy.credentials),
|
|
189
|
-
// A mount point cannot be renamed, so a locked directory is bound onto itself, still writable inside, and a locked file read-only.
|
|
190
|
-
...policy.lock.filter(existsSync).flatMap((path) => bind(statSync(path).isDirectory() ? '--bind' : '--ro-bind', path)),
|
|
191
|
-
...worktreeGitDirs.flatMap((path) => bind('--ro-bind', path)),
|
|
192
|
-
...ownWorktrees(policy).flatMap((path) => bind('--bind', path)),
|
|
193
|
-
...[...policy.protect, ...policy.gitDirs.flatMap(existingRedirects)].filter(existsSync).flatMap((path) => bind('--ro-bind', path)),
|
|
194
|
-
// Shared /tmp is read-only, as on macOS, once everything under it is mounted.
|
|
195
|
-
...['--remount-ro', PRIVATE_TMP_DIR, '--die-with-parent', '--'],
|
|
196
|
-
];
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Linux syscall numbers and audit architecture for the seccomp filter, per Node architecture. */
|
|
200
|
-
const SYSCALLS: Partial<Record<Arch, { audit: number; socket: number; ioUringSetup: number }>> = {
|
|
201
|
-
x64: { audit: 0xc000003e, socket: 41, ioUringSetup: 425 },
|
|
202
|
-
arm64: { audit: 0xc00000b7, socket: 198, ioUringSetup: 425 },
|
|
203
|
-
};
|
|
204
|
-
|
|
205
|
-
const ALLOW = 0x7fff0000;
|
|
206
|
-
const DENY = 0x00050001;
|
|
207
|
-
const SECCOMP_ARCH_OFFSET = 4;
|
|
208
|
-
const SECCOMP_FIRST_ARG_OFFSET = 16;
|
|
209
|
-
const SKIP_TO_DENY_FROM_ARCH = 7;
|
|
210
|
-
const SKIP_TO_DENY_FROM_X32 = 5;
|
|
211
|
-
const SKIP_TO_DENY_FROM_IO_URING = 4;
|
|
212
|
-
const SKIP_SOCKET_CHECK = 2;
|
|
213
|
-
const X32_SYSCALL_BIT = 0x40000000;
|
|
214
|
-
const AF_UNIX = 1;
|
|
215
|
-
const BPF_INSTRUCTION_BYTES = 8;
|
|
216
|
-
const BPF_JT_OFFSET = 2;
|
|
217
|
-
const BPF_JF_OFFSET = 3;
|
|
218
|
-
const BPF_K_OFFSET = 4;
|
|
219
|
-
|
|
220
|
-
/**
|
|
221
|
-
* A classic BPF program for bubblewrap's `--seccomp`: a job may not open a Unix socket, the way macOS denies binding or
|
|
222
|
-
* connecting one, so it reaches no local service, abstract socket, or tmux server. Socket pairs, which child processes
|
|
223
|
-
* use for pipes, stay allowed. io_uring could open a socket around the filter, and another architecture's syscall
|
|
224
|
-
* numbers around its checks, so both are refused.
|
|
225
|
-
*/
|
|
226
|
-
export function seccompFilter(arch: Arch = process.arch): Buffer {
|
|
227
|
-
const nr = SYSCALLS[arch];
|
|
228
|
-
if (!nr) throw new Error(`pstack's Linux sandbox supports x64 and arm64, not ${arch}.`);
|
|
229
|
-
const LD = 0x20;
|
|
230
|
-
const JEQ = 0x15;
|
|
231
|
-
const JGE = 0x35;
|
|
232
|
-
const RET = 0x06;
|
|
233
|
-
const program: [number, number, number, number][] = [
|
|
234
|
-
[LD, 0, 0, SECCOMP_ARCH_OFFSET],
|
|
235
|
-
[JEQ, 0, SKIP_TO_DENY_FROM_ARCH, nr.audit],
|
|
236
|
-
[LD, 0, 0, 0],
|
|
237
|
-
[JGE, SKIP_TO_DENY_FROM_X32, 0, X32_SYSCALL_BIT],
|
|
238
|
-
[JEQ, SKIP_TO_DENY_FROM_IO_URING, 0, nr.ioUringSetup],
|
|
239
|
-
[JEQ, 0, SKIP_SOCKET_CHECK, nr.socket],
|
|
240
|
-
[LD, 0, 0, SECCOMP_FIRST_ARG_OFFSET],
|
|
241
|
-
[JEQ, 1, 0, AF_UNIX],
|
|
242
|
-
[RET, 0, 0, ALLOW],
|
|
243
|
-
[RET, 0, 0, DENY],
|
|
244
|
-
];
|
|
245
|
-
const bytes = Buffer.alloc(program.length * BPF_INSTRUCTION_BYTES);
|
|
246
|
-
program.forEach(([code, jt, jf, k], index) => {
|
|
247
|
-
const at = index * BPF_INSTRUCTION_BYTES;
|
|
248
|
-
bytes.writeUInt16LE(code, at);
|
|
249
|
-
bytes.writeUInt8(jt, at + BPF_JT_OFFSET);
|
|
250
|
-
bytes.writeUInt8(jf, at + BPF_JF_OFFSET);
|
|
251
|
-
bytes.writeUInt32LE(k, at + BPF_K_OFFSET);
|
|
252
|
-
});
|
|
253
|
-
return bytes;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** The filter's file in Pi's agent directory, which no job may write, so none can loosen the filter before a launch. */
|
|
257
|
-
function seccompFile(agentDir: string): string {
|
|
258
|
-
const path = join(agentDir, 'pstack-v2', `seccomp-${process.arch}.bpf`);
|
|
259
|
-
const filter = seccompFilter();
|
|
260
|
-
if (!existsSync(path) || !readFileSync(path).equals(filter)) {
|
|
261
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
262
|
-
writeFileSync(path, filter);
|
|
263
|
-
}
|
|
264
|
-
return path;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const available = (command: string): boolean => spawnSync(SHELL, ['-c', command], { stdio: 'ignore' }).status === 0;
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* Wraps argv so it runs with writes limited to the policy. bubblewrap nests, so a Linux job inside a sandbox gets its own
|
|
271
|
-
* narrower one. macOS refuses a second Seatbelt profile, so a sandboxed macOS worker asks the root Pi to launch instead.
|
|
272
|
-
*/
|
|
273
|
-
export function sandboxed(argv: string[], policy: SandboxPolicy, platform: Platform = process.platform, env: Env = hostEnv()): string[] {
|
|
274
|
-
if (platform === 'darwin' && available('command -v sandbox-exec')) {
|
|
275
|
-
placeholders(policy);
|
|
276
|
-
return ['sandbox-exec', '-p', seatbeltProfile(policy), ...argv];
|
|
277
|
-
}
|
|
278
|
-
if (platform === 'linux' && available('command -v bwrap')) {
|
|
279
|
-
placeholders(policy);
|
|
280
|
-
// bubblewrap reads the filter from a file descriptor, which the shell opens just before it becomes bwrap.
|
|
281
|
-
return [SHELL, '-c', 'exec 9<"$1"; shift; exec bwrap --seccomp 9 "$@"', 'sh', seccompFile(policy.agentDir), ...bwrapArgs(policy, env), ...argv];
|
|
282
|
-
}
|
|
283
|
-
throw new Error(`pstack runs every job in a sandbox and found none on ${platform}. Install bubblewrap (bwrap) on Linux or WSL2, or use macOS, where Seatbelt (sandbox-exec) is built in.`);
|
|
284
|
-
}
|