@bakers-build/addon-runtime-bwrap 0.0.0-stage → 0.9.1-next.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 keytec GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @bakers-build/addon-runtime-bwrap
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Isolate complete agent runs with an external Bubblewrap sandbox.
4
+
5
+ Part of the bakers.build CLI. Install the meta package `@bakers-build/bakers` to get the `bakers` CLI with all addons. Source: https://github.com/bakers-build/bakers-build (bakers-cli/).
@@ -0,0 +1,11 @@
1
+ import type { BbRuntime } from '@bakers-build/conductor/contract';
2
+ export interface BwrapOptions {
3
+ readPaths?: string[];
4
+ }
5
+ export interface BwrapDeps {
6
+ cachePath: string;
7
+ bwrapPath?: string;
8
+ cliRoot: string;
9
+ env: Readonly<Record<string, string | undefined>>;
10
+ }
11
+ export declare function bwrapRuntime(options: BwrapOptions, deps: BwrapDeps): BbRuntime;
@@ -0,0 +1,215 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { gitSandboxPaths, quarantinePlanted, shellQuote, } from '@bakers-build/core';
6
+ const SYSTEM = [
7
+ '/usr',
8
+ '/bin',
9
+ '/sbin',
10
+ '/lib',
11
+ '/lib64',
12
+ '/etc/ssl/certs',
13
+ '/etc/ssl/openssl.cnf',
14
+ '/etc/resolv.conf',
15
+ '/etc/hosts',
16
+ '/etc/passwd',
17
+ '/etc/group',
18
+ '/etc/nsswitch.conf',
19
+ '/etc/localtime',
20
+ ];
21
+ const launcher = fileURLToPath(new URL(import.meta.url.includes('/dist/') ? '../../launch.mjs' : '../launch.mjs', import.meta.url));
22
+ const within = (path, root) => path === root || path.startsWith(root + sep);
23
+ function softwarePaths(env) {
24
+ const paths = [dirname(process.execPath)];
25
+ for (const path of (env.PATH ?? '').split(':')) {
26
+ if (!isAbsolute(path) || !existsSync(path) || !statSync(path).isDirectory())
27
+ continue;
28
+ paths.push(path);
29
+ for (const name of readdirSync(path)) {
30
+ const entry = join(path, name);
31
+ try {
32
+ if (lstatSync(entry).isSymbolicLink()) {
33
+ const target = realpathSync(entry);
34
+ if (lstatSync(target).isFile()) {
35
+ accessSync(target, constants.X_OK);
36
+ paths.push(target);
37
+ }
38
+ }
39
+ }
40
+ catch {
41
+ /* An unavailable optional program is not a mount. */
42
+ }
43
+ }
44
+ }
45
+ return paths;
46
+ }
47
+ /** Build an explicit filesystem view; no blanket bind of the host root or home. */
48
+ function argv(input, options, deps) {
49
+ const ws = resolve(input.workspacePath);
50
+ const git = (flag) => execFileSync('git', ['-C', ws, 'rev-parse', '--path-format=absolute', flag], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
51
+ const common = git('--git-common-dir');
52
+ const gitDir = git('--git-dir');
53
+ if (common === gitDir)
54
+ throw new Error('runtime-bwrap requires a linked Git worktree; the main checkout stays outside the run');
55
+ const worktreeConfig = join(gitDir, 'config.worktree');
56
+ if (!existsSync(worktreeConfig))
57
+ writeFileSync(worktreeConfig, '');
58
+ const gitPaths = gitSandboxPaths(ws);
59
+ const protectedPaths = [...gitPaths.protect, join(ws, '.git'), deps.cliRoot];
60
+ for (const path of input.writePaths ?? []) {
61
+ if (!isAbsolute(path) ||
62
+ protectedPaths.some((root) => within(realpathSync(path), existsSync(root) ? realpathSync(root) : resolve(root)) ||
63
+ within(existsSync(root) ? realpathSync(root) : resolve(root), realpathSync(path))))
64
+ throw new Error(`runtime-bwrap: protected write path ${path}`);
65
+ }
66
+ const mounts = new Map();
67
+ const mount = (path, write) => {
68
+ if (!isAbsolute(path) ||
69
+ path === '/' ||
70
+ (deps.env.HOME && within(deps.env.HOME, path)))
71
+ throw new Error(`runtime-bwrap: refusing broad or relative path ${path}`);
72
+ if (!existsSync(path))
73
+ throw new Error(`runtime-bwrap: required path is missing: ${path}`);
74
+ const actual = realpathSync(path);
75
+ if (actual === '/' ||
76
+ (deps.env.HOME && within(realpathSync(deps.env.HOME), actual)))
77
+ throw new Error(`runtime-bwrap: refusing broad path ${path}`);
78
+ mounts.set(path, write);
79
+ };
80
+ for (const path of [
81
+ ...SYSTEM.filter(existsSync),
82
+ ...softwarePaths(deps.env),
83
+ deps.cliRoot,
84
+ common,
85
+ ...(options.readPaths ?? []),
86
+ ...(input.readPaths ?? []),
87
+ ])
88
+ mount(path, false);
89
+ for (const path of [
90
+ ws,
91
+ input.homePath,
92
+ ...gitPaths.write,
93
+ ...(input.writePaths ?? []),
94
+ ])
95
+ mount(path, true);
96
+ for (const path of protectedPaths.filter(existsSync))
97
+ mount(path, false);
98
+ const bindings = [...mounts].sort(([a], [b]) => a.split(sep).length - b.split(sep).length || a.localeCompare(b));
99
+ return [
100
+ '--unshare-user',
101
+ '--unshare-pid',
102
+ '--unshare-ipc',
103
+ '--unshare-uts',
104
+ '--new-session',
105
+ '--die-with-parent',
106
+ '--cap-drop',
107
+ 'ALL',
108
+ '--proc',
109
+ '/proc',
110
+ '--dev',
111
+ '/dev',
112
+ '--tmpfs',
113
+ '/tmp',
114
+ '--dir',
115
+ '/tmp/run',
116
+ ...bindings.flatMap(([path, write]) => [
117
+ write ? '--bind' : '--ro-bind',
118
+ path,
119
+ path,
120
+ ]),
121
+ '--chdir',
122
+ ws,
123
+ '--',
124
+ '/bin/sh',
125
+ '-c',
126
+ input.command,
127
+ ];
128
+ }
129
+ export function bwrapRuntime(options, deps) {
130
+ const pathOf = (run) => {
131
+ if (!/^[A-Za-z0-9-]+$/.test(run.uuid))
132
+ throw new Error('runtime-bwrap: invalid run uuid');
133
+ return join(deps.cachePath, run.uuid);
134
+ };
135
+ return {
136
+ id: 'bwrap',
137
+ async prepareRun(run) {
138
+ const homePath = pathOf(run);
139
+ mkdirSync(homePath, { recursive: true, mode: 0o700 });
140
+ return { homePath };
141
+ },
142
+ async wrap(input) {
143
+ const homePath = pathOf(input.run);
144
+ if (input.homePath !== homePath)
145
+ throw new Error('runtime-bwrap: private run home was not prepared');
146
+ const env = {
147
+ ...input.env,
148
+ HOME: homePath,
149
+ PATH: deps.env.PATH ?? '/usr/local/bin:/usr/bin:/bin',
150
+ TMPDIR: '/tmp',
151
+ XDG_RUNTIME_DIR: '/tmp/run',
152
+ XDG_CACHE_HOME: join(homePath, '.cache'),
153
+ XDG_CONFIG_HOME: join(homePath, '.config'),
154
+ XDG_DATA_HOME: join(homePath, '.local/share'),
155
+ };
156
+ const planPath = `${homePath}.launch.json`;
157
+ writeFileSync(planPath, JSON.stringify({
158
+ bwrap: deps.bwrapPath ?? '/usr/bin/bwrap',
159
+ argv: argv(input, options, deps),
160
+ envKeys: Object.keys(env),
161
+ workspacePath: input.workspacePath,
162
+ }), { mode: 0o600 });
163
+ return {
164
+ command: [process.execPath, launcher, planPath]
165
+ .map(shellQuote)
166
+ .join(' '),
167
+ env,
168
+ };
169
+ },
170
+ async cleanup(run) {
171
+ const homePath = pathOf(run);
172
+ const planPath = `${homePath}.launch.json`;
173
+ const pidPath = `${planPath}.pid`;
174
+ if (existsSync(pidPath)) {
175
+ const pid = Number(readFileSync(pidPath, 'utf8'));
176
+ if (!Number.isSafeInteger(pid) || pid < 2)
177
+ throw new Error('runtime-bwrap: invalid launcher pid');
178
+ let owned = false;
179
+ try {
180
+ const command = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0');
181
+ owned = command[1] === launcher && command[2] === planPath;
182
+ }
183
+ catch (err) {
184
+ if (err.code !== 'ENOENT')
185
+ throw err;
186
+ }
187
+ if (owned) {
188
+ process.kill(pid, 'SIGTERM');
189
+ for (let i = 0; i < 20 && existsSync(`/proc/${pid}`); i++)
190
+ await new Promise((done) => setTimeout(done, 50));
191
+ if (existsSync(`/proc/${pid}`))
192
+ process.kill(pid, 'SIGKILL');
193
+ for (let i = 0; i < 20 && existsSync(`/proc/${pid}`); i++)
194
+ await new Promise((done) => setTimeout(done, 50));
195
+ if (existsSync(`/proc/${pid}`))
196
+ throw new Error('runtime-bwrap: launcher did not stop; retaining the home');
197
+ }
198
+ }
199
+ if (existsSync(planPath)) {
200
+ const plan = JSON.parse(readFileSync(planPath, 'utf8'));
201
+ const common = execFileSync('git', [
202
+ '-C',
203
+ plan.workspacePath,
204
+ 'rev-parse',
205
+ '--path-format=absolute',
206
+ '--git-common-dir',
207
+ ], { encoding: 'utf8' }).trim();
208
+ await quarantinePlanted(plan.workspacePath, common);
209
+ rmSync(planPath);
210
+ }
211
+ rmSync(homePath, { recursive: true, force: true });
212
+ rmSync(pidPath, { force: true });
213
+ },
214
+ };
215
+ }
@@ -0,0 +1,4 @@
1
+ import type { RuntimePlugin } from '@bakers-build/conductor/contract';
2
+ import { type BwrapOptions } from './backend.js';
3
+ export { type BwrapDeps, type BwrapOptions, bwrapRuntime } from './backend.js';
4
+ export declare function runtimeBwrap(options?: BwrapOptions): RuntimePlugin;
@@ -0,0 +1,64 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { accessSync, constants, existsSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { delimiter, dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { cliRootOf } from '@bakers-build/core';
7
+ import { bwrapRuntime } from './backend.js';
8
+ export { bwrapRuntime } from './backend.js';
9
+ function packageOf(file) {
10
+ let dir = dirname(realpathSync(file));
11
+ while (!existsSync(join(dir, 'package.json')) && dirname(dir) !== dir)
12
+ dir = dirname(dir);
13
+ return dir;
14
+ }
15
+ export function runtimeBwrap(options = {}) {
16
+ return {
17
+ kind: 'runtime',
18
+ id: 'bwrap',
19
+ isolates: true,
20
+ requiredModules: [],
21
+ createRuntime: async () => {
22
+ if (process.platform !== 'linux')
23
+ throw new Error('runtime-bwrap requires Linux');
24
+ const bwrap = (process.env.PATH ?? '')
25
+ .split(delimiter)
26
+ .map((dir) => join(dir, 'bwrap'))
27
+ .find((path) => {
28
+ try {
29
+ accessSync(path, constants.X_OK);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ });
36
+ if (!bwrap)
37
+ throw new Error('runtime-bwrap: install bubblewrap on the conductor host');
38
+ try {
39
+ execFileSync(bwrap, [
40
+ '--unshare-user',
41
+ '--unshare-pid',
42
+ '--ro-bind',
43
+ '/',
44
+ '/',
45
+ '--proc',
46
+ '/proc',
47
+ '--',
48
+ '/bin/true',
49
+ ], { timeout: 15000, stdio: 'pipe' });
50
+ }
51
+ catch (err) {
52
+ throw new Error(`runtime-bwrap: cannot create Linux namespaces; check user namespace/AppArmor policy (${String(err)})`);
53
+ }
54
+ const home = realpathSync(homedir());
55
+ const cliRoot = cliRootOf(packageOf(fileURLToPath(import.meta.url)), packageOf(fileURLToPath(import.meta.resolve('@bakers-build/conductor/contract'))), home);
56
+ return bwrapRuntime(options, {
57
+ cachePath: join(process.env.XDG_CACHE_HOME || join(home, '.cache'), 'bakers/runtime-bwrap'),
58
+ cliRoot,
59
+ env: process.env,
60
+ bwrapPath: realpathSync(bwrap),
61
+ });
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,3 @@
1
+ import type { Preset } from '@bakers-build/conductor/contract';
2
+ export declare const scopes: Preset['scopes'];
3
+ export declare const runtimes: Preset['runtimes'];
@@ -0,0 +1,6 @@
1
+ import { runtimeBwrap } from './index.js';
2
+ export const scopes = ['machine'];
3
+ export const runtimes = (acc, options) => [
4
+ ...acc,
5
+ runtimeBwrap(options),
6
+ ];
package/launch.mjs ADDED
@@ -0,0 +1,24 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+
4
+ const planPath = process.argv[2];
5
+ const plan = JSON.parse(readFileSync(planPath, 'utf8'));
6
+ // The executor's shell can carry unrelated secrets; only declared run keys enter bwrap.
7
+ const env = Object.fromEntries(
8
+ plan.envKeys
9
+ .filter((key) => process.env[key] !== undefined)
10
+ .map((key) => [key, process.env[key]]),
11
+ );
12
+ writeFileSync(`${planPath}.pid`, String(process.pid), { mode: 0o600 });
13
+ const child = spawn(plan.bwrap, plan.argv, { env, stdio: 'inherit' });
14
+ for (const signal of ['SIGTERM', 'SIGHUP', 'SIGINT'])
15
+ process.on(signal, () => child.kill(signal));
16
+ child.on('error', (err) => {
17
+ console.error(`runtime-bwrap: ${err.message}`);
18
+ process.exitCode = 1;
19
+ rmSync(`${planPath}.pid`, { force: true });
20
+ });
21
+ child.on('exit', (code, signal) => {
22
+ process.exitCode = code ?? (signal ? 1 : 0);
23
+ rmSync(`${planPath}.pid`, { force: true });
24
+ });
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "@bakers-build/addon-runtime-bwrap options",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "properties": {
7
+ "readPaths": {
8
+ "type": "array",
9
+ "items": { "type": "string", "pattern": "^/" },
10
+ "default": [],
11
+ "description": "Additional absolute host paths exposed read-only for coding tools. Never grant the host root or the operator home."
12
+ }
13
+ }
14
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-runtime-bwrap",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.9.1-next.5",
4
+ "description": "Isolate complete agent runs with an external Bubblewrap sandbox.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./dist/src/index.js",
9
+ "./preset": "./dist/src/preset.js",
10
+ "./options.schema.json": "./options.schema.json"
11
+ },
12
+ "files": [
13
+ "dist/src",
14
+ "launch.mjs",
15
+ "options.schema.json"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/bakers-build/bakers-build.git",
23
+ "directory": "bakers-cli/addons/runtime-bwrap"
24
+ },
25
+ "peerDependencies": {
26
+ "@bakers-build/conductor": "^0.9.1-next.5",
27
+ "@bakers-build/core": "^0.9.1-next.5"
28
+ },
29
+ "bakersBuild": {
30
+ "commit": "d9242cad6cabee1faf010b5d46ac1bac33f6e0a1",
31
+ "channel": "next"
32
+ }
33
+ }