Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(sandbox,plugins): add WSL sandbox and remove MXC sandbox, and bundle sandbox binaries (#771)

Myriad-Dreamin57c6a1820038
diff --git a/.gitignore b/.gitignore
index d135232d..12de4503 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,3 +47,4 @@ packages/server/src/ifaces.json
plugins/*/ifaces.json
# rendered by scripts/iface-page.mjs (pnpm ifaces:page); CI publishes it
dist-ifaces/
+plugins/sandbox-bwrap/vendor/
diff --git a/changelog/unreleased/2026-09-17-sandbox-backends.md b/changelog/unreleased/2026-09-17-sandbox-backends.md
new file mode 100644
index 00000000..b3dce55d
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-sandbox-backends.md
@@ -0,0 +1,38 @@
+# Sandbox backends: WSL on Windows, a bundled bubblewrap, load-time checks, and no MXC
+
+- **Date:** 2026-09-17
+- **Type:** feat
+- **Scope:** `core`, `server`, `plugins`, `build`, `tooling`
+- **PR:** [#771](https://github.com/Prism-Shadow/penguin-harness/pull/771)
+
+[中文版](2026-09-17-sandbox-backends.zh.md)
+
+Windows gets a sandbox backend that runs commands in a WSL2 distro under bubblewrap. On Linux the bwrap backend brings its own bubblewrap. Every native backend checks at load that it can serve, confining modes keep a writable temp directory, full access can still cut the network, and the MXC backend is removed.
+
+## Windows: the WSL backend
+
+`sandbox-wsl` confines each agent command inside a dedicated WSL2 distro, as an unprivileged account, under bubblewrap. The distro is Ubuntu 24.04 by default; Alpine is the small option, at a tenth of the download and the musl limits that come with it. It implements fs-write, network and mask-paths.
+
+- **The distro is read-only and the Windows drives are hidden.** The Workspace is bound back in at its `/mnt/<drive>/…` path, read-write or read-only by mode. `network: "none"` leaves the command in an empty network namespace. A masked directory gets a tmpfs, a masked file `/dev/null`.
+- **A refused write says so.** The mount that hides the Windows drives is remounted read-only once the Workspace is bound, so `echo x > /mnt/c/Users/anything` fails instead of succeeding into a tmpfs that vanishes with the command.
+- **Names resolve.** WSL keeps the generated `resolv.conf` outside the distro's root and `/etc/resolv.conf` points at it. Both candidate paths are bound back read-only, so hiding `/mnt` and `/run` does not break name resolution.
+- **Windows interop is switched off inside the distro.** With it on, a Windows program started inside bwrap is an ordinary host process: it wrote to the Windows disk and reached the internet with the network cut. The profile also hides `/run`, where WSL keeps its interop sockets.
+- **Setup is a few tasks, each reporting the step it is on.** Install WSL raises one Windows consent prompt and follows `wsl --install`'s output as it runs. Initialize downloads the base rootfs (checked against its sha256), imports it, installs bubblewrap and the package list through apt or apk, and needs no administrator. Check confinement runs real commands through the sandbox and lists each result. Remove distro unregisters it. Until the distro exists, the backend declines to load and says so.
+- **Commands run in Linux.** Windows toolchains cannot run confined; the distro's package list supplies Linux ones.
+- **The confinement seam can carry environment.** A backend's `ConfinedArgv` (and the platform's `SpawnConfiner`) may name entries laid over the command's environment at spawn. The WSL launcher is a script run by the server's own interpreter, which in the desktop app is the app binary and runs a script only under `ELECTRON_RUN_AS_NODE`.
+
+## Linux and macOS: no dependency on the host
+
+- **The bwrap plugin ships `bwrap` itself**, one binary per architecture (`linux-x64`, `linux-arm64`), with the libcap it loads and both licenses beside it. `scripts/vendor-bwrap.mjs` vendors them at build time from conda-forge, pinned by exact URL and sha256; a hash that does not match fails the build. The binary finds its library through an `$ORIGIN/../lib` rpath.
+- **Precedence at each spawn:** the one the plugin ships, else a `bwrap` on PATH. A host with neither still fails closed, now saying to check `kernel.unprivileged_userns_clone`.
+- **Seatbelt names `/usr/bin/sandbox-exec` by its absolute path**, so a PATH without `/usr/bin`, or with another program of that name first, no longer decides what confines a command.
+- The bwrap backend's live enforcement tests run against the shipped binary on a host with no bubblewrap of its own.
+
+## Every backend
+
+- **A backend checks at load that it can serve.** bwrap and Seatbelt load through `loadPenguinBwrapProvider` / `loadSeatbeltProvider`. Off their own platform they decline; on it they run their base-profile probe without blocking and reject, with the reason, when the runner is missing or refuses the profile. Before, a Windows host counted bwrap as a mounted backend covering every dimension and routed every confining policy to it. The confine-time probe stays.
+- **Nothing is silently absent.** `SandboxService` settles every backend source at once, in routing order, and records a rejection as a failure and a null as a decline. When a command fails closed, the message names both: `backends not in use: <name> (<reason>); <name> (not for this host)`.
+- **The temp directory is writable in either confining mode.** `SandboxPolicy` gained `writableTemp`, and the service sets it on every confining policy: bwrap mounts a private, writable `/tmp` (binding `$TMPDIR` too when it lives elsewhere) and Seatbelt allows the temp areas. Before, `read-only` left them read-only, and shells failed before running anything.
+- **The network has a local level.** Beside no network and an open one, `network: "local"` lets a command reach the host's localhost and nothing else. It is its own dimension, `network-local`, so the service routes it only to a backend that declares it and fails closed elsewhere. Seatbelt implements it (every socket denied, then localhost let back in); bwrap and WSL cannot, because an empty network namespace loses the host's loopback too, and they refuse it rather than read it as an open network.
+- **Full access can cut the network.** `danger-full-access` used to short-circuit to unconfined before the network setting was read. Full access with the network open and no masked paths is still unconfined; full access that cuts the network or masks a path now reaches a backend that enforces that while leaving files alone. bwrap, on Linux and inside the WSL distro, binds the root read-write and still `--unshare-net`s; Seatbelt denies no writes and still `(deny network*)`s.
+- **The MXC backend is removed.** `plugins/sandbox-mxc` is gone and `@microsoft/mxc-sdk` left the workspace. The builtin plugin registry lists four sandbox backends: bwrap, Seatbelt, WSL and the DSH adaptor.
diff --git a/changelog/unreleased/2026-09-17-sandbox-backends.zh.md b/changelog/unreleased/2026-09-17-sandbox-backends.zh.md
new file mode 100644
index 00000000..c1cd746e
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-sandbox-backends.zh.md
@@ -0,0 +1,38 @@
+# 沙盒后端:Windows 用 WSL、自带 bubblewrap、加载时自检,并移除 MXC
+
+- **Date:** 2026-09-17
+- **Type:** feat
+- **Scope:** `core`, `server`, `plugins`, `build`, `tooling`
+- **PR:** [#771](https://github.com/Prism-Shadow/penguin-harness/pull/771)
+
+[English](2026-09-17-sandbox-backends.md)
+
+Windows 有了沙盒后端:命令在 WSL2 发行版里、在 bubblewrap 下执行。Linux 上 bwrap 后端自带 bubblewrap。每个原生后端在加载时检查自己能否工作,封禁模式下临时目录可写,完全访问也能断网,MXC 后端被移除。
+
+## Windows:WSL 后端
+
+`sandbox-wsl` 让每条 Agent 命令在一个专用的 WSL2 发行版中、以非特权账户、在 bubblewrap 下执行。发行版缺省为 Ubuntu 24.04;Alpine 作为小体积选项保留,下载量约为前者的十分之一,代价是 musl 带来的兼容性限制。它实现 fs-write、network 与 mask-paths 三个维度。
+
+- **发行版只读,Windows 磁盘不可见。** 工作区按模式以读写或只读方式挂回其 `/mnt/<盘符>/…` 路径。`network: "none"` 让命令处于空的网络命名空间。被屏蔽的目录挂 tmpfs,被屏蔽的文件挂 `/dev/null`。
+- **被拒绝的写入会如实报错。** 遮盖 Windows 磁盘的挂载在工作区绑定完成后重新挂为只读,因此 `echo x > /mnt/c/Users/anything` 会失败,而不是「成功」写进一个随命令消失的 tmpfs。
+- **域名可以解析。** WSL 把生成的 `resolv.conf` 放在发行版根目录之外,`/etc/resolv.conf` 只是指向它的符号链接。两个候选路径都以只读方式挂回,隐藏 `/mnt` 与 `/run` 不再破坏域名解析。
+- **发行版内关闭 Windows interop。** 开着它时,在 bwrap 内启动的 Windows 程序就是普通的宿主进程:实测它在断网状态下仍写入了 Windows 磁盘并访问了外网。沙盒配置还隐藏了 WSL 存放 interop 套接字的 `/run`。
+- **安装由几项任务完成,每项都报告当前步骤。** 安装 WSL 只弹出一次 Windows 授权,并实时跟随 `wsl --install` 的输出。初始化下载基础 rootfs(校验 sha256)、导入、用 apt 或 apk 安装 bubblewrap 与软件包列表,无需管理员权限。检查隔离效果通过沙盒执行真实命令并逐项列出结果。移除发行版会将其注销。发行版建好之前,后端拒绝加载并说明原因。
+- **命令在 Linux 中执行。** Windows 工具链无法在沙盒内运行;由发行版的软件包列表提供 Linux 版本。
+- **封禁接口可以携带环境变量。** 后端的 `ConfinedArgv`(以及平台的 `SpawnConfiner`)可以指定在启动时叠加到命令环境上的变量。WSL 启动器是由服务器自己的解释器运行的脚本,而桌面端的解释器是应用本身的二进制,只有在 `ELECTRON_RUN_AS_NODE` 下才会运行脚本。
+
+## Linux 与 macOS:不再依赖主机
+
+- **bwrap 插件自带 `bwrap`**,按架构各一份(`linux-x64`、`linux-arm64`),连同它加载的 libcap 与两份许可证。`scripts/vendor-bwrap.mjs` 在构建时从 conda-forge 取回,按确切 URL 与 sha256 钉死;哈希对不上即构建失败。该二进制通过 `$ORIGIN/../lib` 的 rpath 找到自己的库。
+- **每次启动命令时的取用顺序:** 插件自带的,其次才是 PATH 上的 `bwrap`。两者皆无的主机仍然 fail closed,并提示去看 `kernel.unprivileged_userns_clone`。
+- **Seatbelt 以绝对路径 `/usr/bin/sandbox-exec` 指名运行器**,PATH 里没有 `/usr/bin`、或有同名程序排在前面,都不再决定谁来封禁命令。
+- bwrap 后端的实机封禁测试,在一台自身没有 bubblewrap 的主机上针对自带二进制跑通。
+
+## 所有后端
+
+- **后端在加载时检查自己能否工作。** bwrap 与 Seatbelt 经 `loadPenguinBwrapProvider` / `loadSeatbeltProvider` 加载。不在自己的平台上时让出;在自己的平台上则以不阻塞的方式运行基础配置探测,运行器缺失或拒绝该配置时带着原因拒绝加载。此前 Windows 主机会把 bwrap 算作覆盖全部维度的已挂载后端,把每条封禁策略都派给它。命令执行时的探测保留。
+- **没有后端会悄无声息地缺席。** `SandboxService` 同时等待所有后端来源,按路由顺序记录:拒绝记为失败,null 记为让出。命令因此被拒绝时,消息把两者都点名:`backends not in use: <name> (<reason>); <name> (not for this host)`。
+- **两种封禁模式下临时目录都可写。** `SandboxPolicy` 新增 `writableTemp`,沙盒服务在每条封禁策略上都设置它:bwrap 挂载私有、可写的 `/tmp`(`$TMPDIR` 在别处时一并绑定),Seatbelt 放行临时目录。此前 `read-only` 模式下临时目录只读,Shell 在执行任何指令之前就会失败。
+- **网络多了本地一档。** 除无网络与完全访问外,`network: "local"` 只允许命令访问本机 localhost。它是单独的维度 `network-local`,沙盒服务只把它路由给声明了该维度的后端,其他情况 fail closed。Seatbelt 实现了它(先拒绝所有套接字,再放行 localhost);bwrap 与 WSL 做不到——空的网络命名空间连主机的回环也一并失去——它们拒绝这一档,而不是当作开放网络处理。
+- **完全访问也能断网。** `danger-full-access` 过去在读取网络设置之前就短路为「不封禁」。完全访问、网络放行且无屏蔽路径时仍不封禁;完全访问且断网或屏蔽路径时,会走到一个后端去执行这一维度,同时不限制文件。bwrap(在 Linux 上与在 WSL 发行版里)把根目录以读写方式绑定并仍 `--unshare-net`;Seatbelt 不拒绝任何写入但仍 `(deny network*)`。
+- **移除了 MXC 后端。** `plugins/sandbox-mxc` 被删除,`@microsoft/mxc-sdk` 离开了工作区。内置插件注册表列出四个沙盒后端:bwrap、Seatbelt、WSL 与 DSH 适配器。
diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.ts
index a94289d9..da135ba3 100644
--- a/packages/core/src/environment/tools/command/session.ts
+++ b/packages/core/src/environment/tools/command/session.ts
@@ -27,6 +27,7 @@
*/
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import type { ToolResult } from "../types.js";
+import type { ConfinedSpawn } from "../../../interfaces/index.js";
import { CappedTextBuffer, WakeSignal } from "../background/index.js";
import { sessionShell } from "./shell.js";
import { pathPrependPrefix } from "./path-prepend.js";
@@ -87,7 +88,7 @@ export interface SpawnOptions {
* Workspace root) before handing the confiner down, so this narrower shape only
* carries what the spawn itself knows (see `SpawnConfiner` in interfaces.ts).
*/
- confine?: (argv: readonly string[], opts: { cwd: string }) => readonly string[];
+ confine?: (argv: readonly string[], opts: { cwd: string }) => ConfinedSpawn;
}
export class ManagedSession {
@@ -122,16 +123,17 @@ export class ManagedSession {
// The confinement seam runs BEFORE spawn on the exact argv (shell included), so a
// confiner that cannot enforce its policy aborts the spawn by throwing (fail-closed)
// rather than letting the command run unconfined. The rewritten argv is spawned in
- // place of the original; env assembly is unaffected (the runner inherits it).
+ // place of the original; env assembly is unaffected (the runner inherits it), except
+ // for the entries the runner itself asked for, which go on top.
const argv = [shell.command, ...shell.args, prefix + opts.cmd];
- const confined = opts.confine ? [...opts.confine(argv, { cwd: opts.cwd })] : argv;
- const program = confined[0];
+ const confined = opts.confine ? opts.confine(argv, { cwd: opts.cwd }) : { argv };
+ const program = confined.argv[0];
if (program === undefined) {
throw new Error("spawn confiner returned an empty argv");
}
- this.child = spawn(program, confined.slice(1), {
+ this.child = spawn(program, confined.argv.slice(1), {
cwd: opts.cwd,
- env: opts.env,
+ env: confined.env === undefined ? opts.env : { ...opts.env, ...confined.env },
detached: SUPPORTS_PROCESS_GROUP, // Become the process-group leader, so the whole group can be signaled
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true, // No flashing console window on Windows (ignored elsewhere)
diff --git a/packages/core/src/interfaces/environment.ts b/packages/core/src/interfaces/environment.ts
index 1eb6b5bd..5f500f1c 100644
--- a/packages/core/src/interfaces/environment.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -367,12 +367,24 @@ export type ProxyEnvPolicy = { mode: "strip" } | { mode: "inject"; url: string;
* may differ from the workspace); `workspaceDir` is the Session's Workspace root — the
* directory a workspace-scoped confinement policy should treat as writable, never
* inferred from `cwd` (a command may run in a workdir outside the Workspace).
- * @returns the argv to spawn instead.
+ * @returns what to spawn instead: the argv, and any environment entries the runner
+ * itself needs (see {@link ConfinedSpawn}).
*/
export type SpawnConfiner = (
argv: readonly string[],
opts: { cwd: string; workspaceDir: string },
-) => readonly string[];
+) => ConfinedSpawn;
+
+/**
+ * A confiner's answer. `argv` replaces the spawn's argv wholesale; `env` is laid over
+ * the environment the manager assembled for the command — entries the runner needs to
+ * be a runner at all (an interpreter switch, say), never the command's own settings,
+ * which stay the manager's to decide.
+ */
+export interface ConfinedSpawn {
+ argv: readonly string[];
+ env?: Readonly<Record<string, string>>;
+}
/**
* An approved tool-call execution request.
diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.ts
index b9227030..54c451d7 100644
--- a/packages/core/src/plugin/sandbox.ts
+++ b/packages/core/src/plugin/sandbox.ts
@@ -31,8 +31,17 @@ export type ConfinedSandboxMode = Exclude<SandboxMode, "danger-full-access">;
* The isolation dimensions of this interface. A provider declares the subset it
* implements; `fs-write` is the floor every confining backend covers, while `network`
* and `mask-paths` are optional implementations (see {@link SandboxProvider.dimensions}).
+ * `network-local` is the local network level: only the host's localhost is reachable. It is
+ * its own dimension because a backend that can cut the network cannot necessarily keep the
+ * host's loopback while cutting the rest.
*/
-export type SandboxDimension = "fs-write" | "network" | "mask-paths";
+export type SandboxDimension = "fs-write" | "network" | "network-local" | "mask-paths";
+
+/**
+ * The network levels, narrowest first: `none` = no network at all, `local` = only the host's
+ * localhost, absent = unrestricted.
+ */
+export type SandboxNetwork = "none" | "local";
/**
* What one confined execution is allowed to touch — carried PER CALL, not fixed on the
@@ -41,14 +50,28 @@ export type SandboxDimension = "fs-write" | "network" | "mask-paths";
* implements it (never silently dropped).
*/
export interface SandboxPolicy {
- /** The file-effect mode this execution runs under (`fs-write`). */
- mode: ConfinedSandboxMode;
+ /**
+ * The file-effect mode this execution runs under (`fs-write`). A provider is normally
+ * consulted only for a confining mode; it is handed `danger-full-access` ONLY when the
+ * policy still requires another dimension (a network cut, a masked path). Then it must
+ * leave the filesystem unrestricted while enforcing that other dimension — "everything
+ * writable, but no network" is a real, expressible policy.
+ */
+ mode: SandboxMode;
/** Absolute root directory `workspace-write` may write under. */
workspaceRoot: string;
- /** `network`: "none" = the confined process gets no network at all. */
- network?: "none";
+ /**
+ * `network`: "none" = the confined process gets no network at all (dimension `network`);
+ * "local" = it reaches the host's localhost and nothing else (dimension `network-local`).
+ */
+ network?: SandboxNetwork;
/** `mask-paths`: absolute paths hidden from the confined process, reads included. */
maskPaths?: readonly string[];
+ /**
+ * The system temporary directory is writable, in either confining mode: shells and most
+ * tools need somewhere to write before they run anything. Absent = not granted.
+ */
+ writableTemp?: boolean;
}
/**
@@ -84,6 +107,14 @@ export interface ConfinedArgv {
denialSignatures: readonly string[];
/** Structured runner-failure evidence (see {@link RunnerFailureRule}). */
runnerFailureRules: readonly RunnerFailureRule[];
+ /**
+ * Environment entries the RUNNER needs, laid over the command's own environment at
+ * spawn. A runner that is a script has to tell its interpreter how to behave — the
+ * desktop app's own binary runs a script only under `ELECTRON_RUN_AS_NODE`, and
+ * nothing in an argv can say so. These describe the runner, not the command: a runner
+ * that hands the environment on keeps them from the command it confines.
+ */
+ env?: Readonly<Record<string, string>>;
}
/**
@@ -112,6 +143,6 @@ export type SandboxProviderSource = SandboxProvider | PromiseLike<SandboxProvide
export type SandboxSettings = {
/** `danger-full-access` = confinement off; commands spawn exactly as before. */
mode: SandboxMode;
- network?: "none";
+ network?: SandboxNetwork;
maskPaths?: string[];
};
diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.ts
index 840c7d91..149493c1 100644
--- a/packages/core/test/exec-session.test.ts
+++ b/packages/core/test/exec-session.test.ts
@@ -521,7 +521,9 @@ describe("confineSpawn seam rewrites the exact argv a command spawns", () => {
seen = { argv, cwd: opts.cwd, workspaceDir: opts.workspaceDir };
// Stand-in runner: replaces the invocation wholesale and prints a marker, proving
// the child that actually ran is the rewritten argv, not the original shell.
- return [process.execPath, "-e", "console.log('CONFINED wrapped=' + process.argv.length)"];
+ return {
+ argv: [process.execPath, "-e", "console.log('CONFINED wrapped=' + process.argv.length)"],
+ };
};
const res = await runTool(confinedEnv, "exec_command", { cmd: "echo original" });
expect(res.output).toContain("CONFINED wrapped=");
@@ -550,11 +552,28 @@ describe("confineSpawn seam rewrites the exact argv a command spawns", () => {
it("the getter is re-read at every spawn, so a hot-swapped confiner needs no new Environment", async () => {
const first = await runTool(confinedEnv, "exec_command", { cmd: "echo unconfined-run" });
expect(first.output).toContain("unconfined-run");
- confiner = () => [process.execPath, "-e", "console.log('CONFINED')"];
+ confiner = () => ({ argv: [process.execPath, "-e", "console.log('CONFINED')"] });
const second = await runTool(confinedEnv, "exec_command", { cmd: "echo unconfined-run" });
expect(second.output).toContain("CONFINED");
expect(second.output).not.toContain("unconfined-run");
});
+
+ it("the entries a confiner asks for reach the runner, on top of the assembled environment", async () => {
+ // A runner that is a script must be able to tell its interpreter how to behave (the
+ // desktop app's binary runs a script only under ELECTRON_RUN_AS_NODE); the argv alone
+ // cannot say so. The rest of the environment is still the manager's.
+ confiner = () => ({
+ argv: [
+ process.execPath,
+ "-e",
+ "console.log('RUNNER=' + process.env.PENGUIN_RUNNER_MARK + ' PATH=' + (process.env.PATH ?? '').length)",
+ ],
+ env: { PENGUIN_RUNNER_MARK: "set-by-confiner" },
+ });
+ const res = await runTool(confinedEnv, "exec_command", { cmd: "echo original" });
+ expect(res.output).toContain("RUNNER=set-by-confiner");
+ expect(res.output).not.toMatch(/PATH=0\b/);
+ });
});
describe("proxyEnv policy governs the proxy variables commands inherit", () => {
diff --git a/packages/core/test/kernel-modules.test.ts b/packages/core/test/kernel-modules.test.ts
index 4d97b6c4..642c70cd 100644
--- a/packages/core/test/kernel-modules.test.ts
+++ b/packages/core/test/kernel-modules.test.ts
@@ -265,11 +265,11 @@ describe("parseManifest", () => {
it("reads an empty requires, provides, contributes or children left out as empty", () => {
expect(
parseManifest({
- name: "SandboxMxc",
+ name: "SandboxBwrap",
contributes: { "SandboxModule.providers": [{ id: "p" }] },
}),
).toEqual({
- name: "SandboxMxc",
+ name: "SandboxBwrap",
requires: {},
provides: {},
contributes: { "SandboxModule.providers": [{ id: "p" }] },
diff --git a/packages/server/src/plugin/builtin-index.json b/packages/server/src/plugin/builtin-index.json
index 6e92fc0e..56fc9869 100644
--- a/packages/server/src/plugin/builtin-index.json
+++ b/packages/server/src/plugin/builtin-index.json
@@ -20,13 +20,13 @@
"categories": ["sandbox"]
},
{
- "name": "@prismshadow/penguin-plugin-sandbox-mxc",
+ "name": "@prismshadow/penguin-plugin-sandbox-wsl",
"version": "0.2.2",
- "description": "Windows sandbox backend for PenguinHarness over Microsoft MXC (Microsoft eXecution Containers): filesystem confinement, network isolation and path masking via the processcontainer backend.",
+ "description": "WSL sandbox backend for PenguinHarness on Windows: commands run in a dedicated WSL2 distro under bubblewrap, with Windows interop switched off.",
"authors": ["Prism Shadow"],
"license": "Apache-2.0",
"repository": "https://github.com/Prism-Shadow/penguin-harness",
- "keywords": ["windows", "mxc", "network-isolation", "path-masking"],
+ "keywords": ["windows", "wsl", "bubblewrap", "network-isolation", "path-masking"],
"categories": ["sandbox"]
},
{
diff --git a/packages/server/src/sandbox/dimensions.ts b/packages/server/src/sandbox/dimensions.ts
index 0f04901e..9d899212 100644
--- a/packages/server/src/sandbox/dimensions.ts
+++ b/packages/server/src/sandbox/dimensions.ts
@@ -18,6 +18,7 @@ import type {
export const SANDBOX_DIMENSIONS: readonly SandboxDimension[] = [
"fs-write",
"network",
+ "network-local",
"mask-paths",
];
@@ -29,7 +30,8 @@ export function providerDimensions(provider: SandboxProvider): readonly SandboxD
/** The dimensions a settings object actually requires. */
export function requestedDimensions(settings: SandboxSettings): SandboxDimension[] {
const dims: SandboxDimension[] = ["fs-write"];
- if (settings.network !== undefined) dims.push("network");
+ if (settings.network === "none") dims.push("network");
+ if (settings.network === "local") dims.push("network-local");
if (settings.maskPaths !== undefined && settings.maskPaths.length > 0) dims.push("mask-paths");
return dims;
}
diff --git a/packages/server/src/sandbox/index.ts b/packages/server/src/sandbox/index.ts
index 5df56c4e..b58ab0c0 100644
--- a/packages/server/src/sandbox/index.ts
+++ b/packages/server/src/sandbox/index.ts
@@ -21,14 +21,15 @@
* plugin platform fs-write network mask-paths
* penguin-plugin-sandbox-bwrap Linux yes yes yes
* penguin-plugin-sandbox-seatbelt macOS yes yes yes
- * penguin-plugin-sandbox-mxc Windows yes yes yes
+ * penguin-plugin-sandbox-wsl Windows yes yes yes
* penguin-plugin-sandbox-dsh all three yes — —
*
* The DSH adaptor is the portable floor covering file effects only (its own chain picks
* bwrap/Landlock, Seatbelt or the Windows ACL runner per host); the three native
- * backends add the other two dimensions, one per platform. Where none implements a
- * requested dimension, service.ts fails closed naming what each covers rather than
- * quietly confining less than was asked.
+ * backends add the other two dimensions, one per platform. Windows is served by bubblewrap
+ * inside a dedicated WSL2 distro, so commands there run in Linux (see sandbox-wsl's README).
+ * Where none implements a requested dimension, service.ts fails closed naming what each
+ * covers rather than quietly confining less than was asked.
*/
export { SandboxService } from "./service.js";
export { SANDBOX_DIMENSIONS, providerDimensions, requestedDimensions } from "./dimensions.js";
diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.ts
index 9c757e05..e7b41896 100644
--- a/packages/server/src/sandbox/service.ts
+++ b/packages/server/src/sandbox/service.ts
@@ -30,8 +30,17 @@ interface MountedProvider {
export class SandboxService {
private readonly mounted: MountedProvider[] = [];
- /** name → why it failed to load; surfaced in the fail-closed message. */
+ /**
+ * name → why it FAILED: it could not load, or failed its check on a host it is meant for —
+ * never silently absent. Surfaced in the fail-closed message.
+ */
private readonly loadErrors = new Map<string, string>();
+ /**
+ * The backends that declined: this host is not theirs (a Linux backend on Windows). Nothing
+ * is wrong with a deployment that installs one backend per platform, so a decline is not a
+ * failure — it is listed only when NO backend serves, where it is the explanation.
+ */
+ private readonly declinedNames: string[] = [];
/**
* Ships with confinement OFF (`danger-full-access`): the default flips to
* workspace-write together with the deployment-facing config surface, so a
@@ -49,14 +58,23 @@ export class SandboxService {
* exists for deployments flipping the mode in the first milliseconds after boot.
*/
constructor(registrations: Iterable<[string, SandboxProviderSource]> = []) {
+ // Every source is settled at once (a backend's check runs while the others load, and a
+ // rejection is handled the moment it happens); the results are recorded in registration
+ // order, which is routing order.
+ const settled = [...registrations].map(([name, source]) => ({
+ name,
+ result: Promise.resolve(source).then(
+ (provider) => ({ provider }),
+ (err: unknown) => ({ error: err instanceof Error ? err.message : String(err) }),
+ ),
+ }));
this.ready = (async () => {
- for (const [name, source] of registrations) {
- try {
- const provider = await source;
- if (provider !== null && provider !== undefined) this.mounted.push({ name, provider });
- } catch (err) {
- this.loadErrors.set(name, err instanceof Error ? err.message : String(err));
- }
+ for (const { name, result } of settled) {
+ const outcome = await result;
+ if ("error" in outcome) this.loadErrors.set(name, outcome.error);
+ else if (outcome.provider === null || outcome.provider === undefined) {
+ this.declinedNames.push(name);
+ } else this.mounted.push({ name, provider: outcome.provider });
}
})();
}
@@ -108,8 +126,12 @@ export class SandboxService {
confiner(): SpawnConfiner {
return (argv, opts) => {
const settings = this.settings;
- if (settings.mode === "danger-full-access") return argv;
const required = requestedDimensions(settings);
+ // Full access with nothing else asked (no network cut, no masked paths) is genuinely
+ // unconfined — spawn as-is. But full access that STILL cuts the network or masks a path
+ // needs a backend: returning here would silently drop that half of the policy. So the
+ // short-circuit is "no confinement dimension beyond fs-write", not "mode is full".
+ if (settings.mode === "danger-full-access" && required.length === 1) return { argv };
const provider = this.pick(required, settings.mode);
// workspaceRoot is the Session's Workspace, never the per-command cwd: a command
// running in a workdir outside the Workspace must not widen the writable roots.
@@ -120,10 +142,15 @@ export class SandboxService {
...(settings.maskPaths !== undefined && settings.maskPaths.length > 0
? { maskPaths: settings.maskPaths }
: {}),
+ // Always: without a writable temp directory a shell cannot start.
+ writableTemp: true,
};
// ConfinedArgv also carries enforcement / denialSignatures / runnerFailureRules;
// the classification consumer (denial vs runner failure) lands with escalation.
- return provider.confine(argv, policy).argv;
+ const confined = provider.confine(argv, policy);
+ return confined.env === undefined
+ ? { argv: confined.argv }
+ : { argv: confined.argv, env: confined.env };
};
}
@@ -146,11 +173,11 @@ export class SandboxService {
}
private failedSuffix(): string {
- if (this.loadErrors.size === 0) return "";
- const failures = [...this.loadErrors]
- .map(([name, message]) => `${name} (${message})`)
- .join("; ");
- return `; backends that failed to load: ${failures}`;
+ const parts = [...this.loadErrors].map(([name, message]) => `${name} (${message})`);
+ if (this.declinedNames.length > 0) {
+ parts.push(`${this.declinedNames.join(", ")} (not for this host)`);
+ }
+ return parts.length === 0 ? "" : `; backends not in use: ${parts.join("; ")}`;
}
}
@@ -184,7 +211,7 @@ export interface SandboxSlots {
schema: {
"settings?": {
mode: "'read-only'|'workspace-write'|'danger-full-access'",
- "network?": "'none'",
+ "network?": "'none'|'local'",
"maskPaths?": "string[]",
},
},
diff --git a/packages/server/test/plugin-registry.test.ts b/packages/server/test/plugin-registry.test.ts
index bef5c931..e4122803 100644
--- a/packages/server/test/plugin-registry.test.ts
+++ b/packages/server/test/plugin-registry.test.ts
@@ -70,7 +70,7 @@ describe("builtinPluginRegistry", () => {
expect(entries.map((e) => e.name)).toEqual([
"@prismshadow/penguin-plugin-sandbox-bwrap",
"@prismshadow/penguin-plugin-sandbox-seatbelt",
- "@prismshadow/penguin-plugin-sandbox-mxc",
+ "@prismshadow/penguin-plugin-sandbox-wsl",
"@prismshadow/penguin-plugin-sandbox-dsh",
]);
for (const entry of entries) {
diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.ts
index 6c5afb3f..c0e37380 100644
--- a/packages/server/test/sandbox.test.ts
+++ b/packages/server/test/sandbox.test.ts
@@ -50,7 +50,7 @@ describe("sandbox service — the built-in interface and its optional dimensions
it("default settings are danger-full-access: argv passes through, no backend is consulted", async () => {
const dsh = fake("dsh");
const svc = await service([["dsh-local", dsh.provider]]);
- expect(svc.confiner()([...ARGV], OPTS)).toEqual([...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual([...ARGV]);
expect(dsh.calls).toHaveLength(0);
});
@@ -66,7 +66,19 @@ describe("sandbox service — the built-in interface and its optional dimensions
]);
svc.configure({ mode: "read-only" });
expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(
- /failed to load: dsh-local \(Cannot find module 'landlock-run'\)/,
+ /not in use: dsh-local \(Cannot find module 'landlock-run'\)/,
+ );
+ });
+
+ it("separates a backend that declines this host from one that failed on it", async () => {
+ const svc = await service([
+ ["quiet", Promise.resolve(null)],
+ ["loud", Promise.reject(new Error("'bwrap' is missing"))],
+ ]);
+ expect(svc.backends()).toEqual([]);
+ svc.configure({ mode: "read-only" });
+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(
+ /loud \('bwrap' is missing\); quiet \(not for this host\)/,
);
});
@@ -74,7 +86,7 @@ describe("sandbox service — the built-in interface and its optional dimensions
// The deployed-machine shape (see scripts/deploy.mjs): the load fails, the default
// settings keep working, and only a confining mode fails.
const svc = await service([["dsh-local", Promise.reject(new Error("MODULE_NOT_FOUND"))]]);
- expect(svc.confiner()([...ARGV], OPTS)).toEqual([...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual([...ARGV]);
svc.configure({ mode: "workspace-write" });
expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(/MODULE_NOT_FOUND/);
});
@@ -83,7 +95,7 @@ describe("sandbox service — the built-in interface and its optional dimensions
const dsh = fake("dsh");
const svc = await service([["dsh-local", dsh.provider]]);
svc.configure({ mode: "workspace-write" });
- expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["dsh", "--", ...ARGV]);
// workspaceRoot is the Workspace, never the per-command cwd.
expect(dsh.calls[0]).toMatchObject({ mode: "workspace-write", workspaceRoot: "/work/project" });
expect(svc.backends()).toEqual([{ name: "dsh-local", dimensions: ["fs-write"] }]);
@@ -115,7 +127,7 @@ describe("sandbox service — capability routing across backends", () => {
["penguin-bwrap", bwrap.provider],
]);
svc.configure({ mode: "workspace-write" });
- expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["dsh", "--", ...ARGV]);
expect(bwrap.calls).toHaveLength(0);
});
@@ -126,11 +138,57 @@ describe("sandbox service — capability routing across backends", () => {
["penguin-bwrap", bwrap.provider],
]);
svc.configure({ mode: "workspace-write", network: "none", maskPaths: ["/home/u/.ssh"] });
- expect(svc.confiner()([...ARGV], OPTS)).toEqual(["bwrap", "--", ...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["bwrap", "--", ...ARGV]);
expect(dsh.calls).toHaveLength(0);
expect(bwrap.calls[0]).toMatchObject({ network: "none", maskPaths: ["/home/u/.ssh"] });
});
+ it("full access still routes to a backend when it cuts the network (never dropped)", async () => {
+ const { dsh, bwrap } = entries();
+ const svc = await service([
+ ["dsh-local", dsh.provider],
+ ["penguin-bwrap", bwrap.provider],
+ ]);
+ // Full access + no network is genuinely unconfined: it passes through.
+ svc.configure({ mode: "danger-full-access" });
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual([...ARGV]);
+ expect(bwrap.calls).toHaveLength(0);
+ // But full access that ALSO cuts the network must reach a backend that can cut it — the
+ // filesystem stays unrestricted, the network does not.
+ svc.configure({ mode: "danger-full-access", network: "none" });
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["bwrap", "--", ...ARGV]);
+ expect(bwrap.calls[0]).toMatchObject({ mode: "danger-full-access", network: "none" });
+ });
+
+ it("the local network level routes only to a backend declaring network-local", async () => {
+ const { dsh, bwrap } = entries();
+ const seatbelt = fake("seatbelt", ["fs-write", "network", "network-local", "mask-paths"]);
+ const svc = await service([
+ ["dsh-local", dsh.provider],
+ ["penguin-bwrap", bwrap.provider],
+ ["penguin-seatbelt", seatbelt.provider],
+ ]);
+ svc.configure({ mode: "workspace-write", network: "local" });
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["seatbelt", "--", ...ARGV]);
+ expect(bwrap.calls).toHaveLength(0);
+ expect(seatbelt.calls[0]).toMatchObject({ network: "local" });
+ // Full access with the local level still needs that backend: nothing is dropped.
+ svc.configure({ mode: "danger-full-access", network: "local" });
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["seatbelt", "--", ...ARGV]);
+ });
+
+ it("the local network level fails closed where no backend declares it", async () => {
+ const { dsh, bwrap } = entries();
+ const svc = await service([
+ ["dsh-local", dsh.provider],
+ ["penguin-bwrap", bwrap.provider],
+ ]);
+ svc.configure({ mode: "workspace-write", network: "local" });
+ expect(() => svc.confiner()([...ARGV], OPTS)).toThrow(/requires fs-write \+ network-local/);
+ // Never read as "no network" or "open network" by a backend that cannot do it.
+ expect(bwrap.calls).toHaveLength(0);
+ });
+
it("an empty maskPaths list does not require the dimension", async () => {
const { dsh, bwrap } = entries();
const svc = await service([
@@ -138,7 +196,7 @@ describe("sandbox service — capability routing across backends", () => {
["penguin-bwrap", bwrap.provider],
]);
svc.configure({ mode: "read-only", maskPaths: [] });
- expect(svc.confiner()([...ARGV], OPTS)).toEqual(["dsh", "--", ...ARGV]);
+ expect(svc.confiner()([...ARGV], OPTS).argv).toEqual(["dsh", "--", ...ARGV]);
});
it("a backend throw (unusable runner, etc.) propagates — fail-closed end to end", async () => {
diff --git a/plugins/sandbox-bwrap/README.md b/plugins/sandbox-bwrap/README.md
index 86e3c4dc..7b3adbe9 100644
--- a/plugins/sandbox-bwrap/README.md
+++ b/plugins/sandbox-bwrap/README.md
@@ -6,10 +6,21 @@ interface — filesystem writes, network isolation and path masking.
## Requirements
-- Linux, with `bwrap` on PATH.
+- Linux. On any other platform the backend declines to mount, so a policy is routed to a backend
+ that host has.
- Unprivileged user namespaces enabled. The backend probes functionally at load and
declines when the kernel will not grant them, rather than confining less than asked.
+**It brings its own bubblewrap.** The package ships a binary per architecture
+(`vendor/linux-x64`, `vendor/linux-arm64`), pinned by URL and sha256 from conda-forge and
+vendored at build time by `scripts/vendor-bwrap.mjs`, together with the libcap it loads and both
+licenses. A deployment therefore needs nothing installed: no `apt install bubblewrap`, no version
+skew between hosts, and no sandbox that is quietly off because a machine lacked the program. The
+binary finds its library through an `$ORIGIN/../lib` rpath, which is what makes it usable from a
+backend that only rewrites an argv and never sets an environment.
+
+Precedence, when a command is confined: the one shipped here, else a `bwrap` on PATH.
+
## How the profile is built
bwrap applies mounts **in order**, and a later mount shadows an earlier one, so the
@@ -18,8 +29,10 @@ profile is assembled in this sequence:
| Stage | Flags |
| --- | --- |
| The read-only world | `--ro-bind / /`, `--dev /dev`, `--proc /proc`, `--die-with-parent` |
-| `workspace-write` | `--tmpfs /tmp`, `--bind <workspaceRoot> <same>` |
+| writable temp (either mode) | `--tmpfs /tmp`, `--bind <tmpdir> <same>` when `$TMPDIR` is elsewhere |
+| `workspace-write` | `--bind <workspaceRoot> <same>` |
| `network: none` | `--unshare-net` |
+| `network: local` | not supported: an empty network namespace loses the host's loopback too |
| `mask-paths` | `--tmpfs <dir>` or `--ro-bind /dev/null <file>` |
Masking comes last on purpose: the entries have to shadow the read-only bind of `/` that
diff --git a/plugins/sandbox-bwrap/package.json b/plugins/sandbox-bwrap/package.json
index 53e4a03d..47ff314a 100644
--- a/plugins/sandbox-bwrap/package.json
+++ b/plugins/sandbox-bwrap/package.json
@@ -15,13 +15,14 @@
"license": "Apache-2.0",
"files": [
"dist",
+ "vendor",
"README.md",
"ifaces.json"
],
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run --passWithNoTests",
- "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
+ "build": "node ../../scripts/vendor-bwrap.mjs && node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
"devDependencies": {
"@prismshadow/penguin-core": "workspace:*",
diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.ts
index 29192e88..fe54a0eb 100644
--- a/plugins/sandbox-bwrap/src/index.ts
+++ b/plugins/sandbox-bwrap/src/index.ts
@@ -13,7 +13,8 @@
* later mount shadows an earlier one:
*
* --ro-bind / / --dev /dev --proc /proc --die-with-parent the read-only world
- * [workspace-write] --tmpfs /tmp --bind <workspaceRoot> <same>
+ * [writable temp] --tmpfs /tmp --bind <tmpdir> <same> a private, writable /tmp
+ * [workspace-write] --bind <workspaceRoot> <same>
* [network: none] --unshare-net no network namespace
* [mask-paths] --tmpfs <dir> | --ro-bind /dev/null <file> shadowing the above
* -- <the caller's argv>
@@ -30,9 +31,10 @@
* remains readable as stale metadata. Mask it explicitly with `maskPaths` if that
* matters for a deployment.
*/
-import { spawnSync } from "node:child_process";
-import { statSync } from "node:fs";
+import { execFile, spawnSync } from "node:child_process";
+import { accessSync, constants, statSync } from "node:fs";
import path from "node:path";
+import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import { Bind, Component } from "@prismshadow/penguin-core/plugin";
import type {
@@ -40,33 +42,79 @@ import type {
Plugin,
SandboxPolicy,
SandboxProvider,
+ SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
/** Default probe budget; a probe that hangs must not hang the first spawn forever. */
const PROBE_TIMEOUT_MS = 5_000;
-/** Test seams: inject the probe verdict and capture the runner name. */
+/**
+ * The bwrap this plugin SHIPS for the host it is running on, or "" when it carries none.
+ *
+ * A deployment must not depend on the distribution having bubblewrap — most do not install it,
+ * and an operator who has to run `apt install bubblewrap` before the sandbox works is an
+ * operator whose sandbox is off. The binary lives beside the built module
+ * (`vendor/<platform>-<arch>/bin/bwrap`, see scripts/vendor-bwrap.mjs) and finds its own
+ * libcap through an `$ORIGIN/../lib` rpath, which is what lets a backend that only rewrites an
+ * argv use it: there is no environment to set.
+ */
+export function vendoredRunner(
+ platform: NodeJS.Platform = process.platform,
+ arch: string = process.arch,
+ runnable: (p: string) => boolean = executable,
+): string {
+ const candidate = fileURLToPath(
+ new URL(`../vendor/${platform}-${arch}/bin/bwrap`, import.meta.url),
+ );
+ return runnable(candidate) ? candidate : "";
+}
+
+/** Present AND executable: a package installer may drop the exec bit, and then it is not ours to run. */
+function executable(target: string): boolean {
+ try {
+ accessSync(target, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Test seams: inject the probe verdict and the runner name. */
export interface PenguinBwrapInternals {
- probe?: (timeoutMs: number) => boolean;
+ probe?: (timeoutMs: number, runner: string) => boolean;
runner?: string;
}
-/** The writable roots `workspace-write` grants: the workspace plus the temp areas, canonical and deduplicated. */
+/**
+ * The writable roots a policy grants, canonical and deduplicated: the workspace under
+ * `workspace-write`, and the temp areas whenever the policy makes temp writable (either mode).
+ */
export function writableRoots(policy: SandboxPolicy): string[] {
- if (policy.mode !== "workspace-write") return [];
- const roots = [policy.workspaceRoot, "/tmp", tmpdir()].map((root) => path.resolve(root));
+ const roots = [
+ ...(policy.mode === "workspace-write" ? [policy.workspaceRoot] : []),
+ ...(policy.writableTemp === true ? ["/tmp", tmpdir()] : []),
+ ].map((root) => path.resolve(root));
return [...new Set(roots)];
}
/** The bwrap profile arguments for one policy (everything before `--` and the caller's argv). */
export function bwrapProfileArgs(policy: SandboxPolicy): string[] {
- const args = ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent"];
- if (policy.mode === "workspace-write") {
- args.push("--tmpfs", "/tmp");
- for (const root of writableRoots(policy)) {
- if (root === "/tmp") continue; // already a writable tmpfs above
- args.push("--bind", root, root);
- }
+ // Full access binds the root read-WRITE: the filesystem is unrestricted, and only the other
+ // dimensions below (a network cut, a masked path) still apply — which is the whole reason a
+ // full-access policy reached a backend at all.
+ const rootBind = policy.mode === "danger-full-access" ? "--bind" : "--ro-bind";
+ const args = [rootBind, "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent"];
+ const roots = writableRoots(policy);
+ if (policy.writableTemp === true) args.push("--tmpfs", "/tmp");
+ for (const root of roots) {
+ if (root === "/tmp") continue; // already a writable tmpfs above
+ args.push("--bind", root, root);
+ }
+ if (policy.network === "local") {
+ // An empty network namespace also loses the host's loopback, so "localhost only" has no
+ // spelling here. The service never routes it here (no network-local dimension); refuse
+ // rather than read it as an open network.
+ throw new Error("penguin-bwrap cannot confine to the local network (localhost only)");
}
if (policy.network === "none") args.push("--unshare-net");
for (const target of policy.maskPaths ?? []) {
@@ -84,28 +132,71 @@ export function bwrapProfileArgs(policy: SandboxPolicy): string[] {
}
/** Functional probe: can bwrap actually create the base profile on this host? */
+/** The argv that checks bwrap can build the base profile at all. */
+const BASE_PROFILE_PROBE = [
+ "--ro-bind",
+ "/",
+ "/",
+ "--dev",
+ "/dev",
+ "--proc",
+ "/proc",
+ "--die-with-parent",
+ "--",
+ "true",
+];
+
function defaultProbe(timeoutMs: number, runner: string): boolean {
- const probe = spawnSync(
- runner,
- ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent", "--", "true"],
- { timeout: timeoutMs, stdio: "ignore" },
- );
+ const probe = spawnSync(runner, BASE_PROFILE_PROBE, { timeout: timeoutMs, stdio: "ignore" });
return probe.status === 0;
}
+/** The base-profile probe, without blocking the process: what the load-time check runs. */
+function probeAsync(timeoutMs: number, runner: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile(runner, BASE_PROFILE_PROBE, { timeout: timeoutMs }, (err) => resolve(err === null));
+ });
+}
+
+/**
+ * Loads the backend, checking first that it can serve on this host — and rejecting, with the
+ * reason, when it cannot: it runs on Linux only, and needs a bwrap that accepts the base profile.
+ * A backend mounted without being able to serve would be routed policies and fail every command;
+ * one that declined without a reason would leave nobody able to tell why. The sandbox service
+ * records the rejection and names it when a command fails closed.
+ */
+export async function loadPenguinBwrapProvider(
+ internals: PenguinBwrapInternals & { platform?: NodeJS.Platform } = {},
+): Promise<SandboxProvider | null> {
+ const platform = internals.platform ?? process.platform;
+ // Not this host's backend: a decline, not a failure — the deployment installed it for
+ // its Linux machines, and saying so on every Windows card would be noise.
+ if (platform !== "linux") return null;
+ const runner = internals.runner ?? (vendoredRunner() || "bwrap");
+ const usable = internals.probe
+ ? internals.probe(PROBE_TIMEOUT_MS, runner)
+ : await probeAsync(PROBE_TIMEOUT_MS, runner);
+ if (!usable) {
+ throw new Error(
+ `'${runner}' is missing or refuses the base profile (are unprivileged user namespaces enabled on this host? \`sysctl kernel.unprivileged_userns_clone\`)`,
+ );
+ }
+ return createPenguinBwrapProvider(internals);
+}
+
/**
* The backend. The probe runs once, lazily (first confine), and is cached: an
* unavailable bwrap throws — fail-closed — rather than degrading to a weaker profile,
* because the dimensions routed here (network, mask-paths) have no weaker form.
*/
export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}): SandboxProvider {
- const runner = internals.runner ?? "bwrap";
- const probe = internals.probe ?? ((timeoutMs: number) => defaultProbe(timeoutMs, runner));
+ const runner = internals.runner ?? (vendoredRunner() || "bwrap");
+ const probe = internals.probe ?? defaultProbe;
let usable: boolean | undefined;
return {
dimensions: ["fs-write", "network", "mask-paths"],
confine(argv, policy): ConfinedArgv {
- usable ??= probe(PROBE_TIMEOUT_MS);
+ usable ??= probe(PROBE_TIMEOUT_MS, runner);
if (!usable) {
throw new Error(
`penguin-bwrap cannot confine on this host: '${runner}' is missing or refuses the ` +
@@ -145,10 +236,10 @@ export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}
},
})
export class SandboxBwrap {
- @Bind("sandbox-bwrap.provider") provider!: SandboxProvider;
+ @Bind("sandbox-bwrap.provider") provider!: SandboxProviderSource;
setup() {
- this.provider = createPenguinBwrapProvider();
+ this.provider = loadPenguinBwrapProvider();
}
}
diff --git a/plugins/sandbox-bwrap/test/live.test.ts b/plugins/sandbox-bwrap/test/live.test.ts
index e81b99ca..064e07c2 100644
--- a/plugins/sandbox-bwrap/test/live.test.ts
+++ b/plugins/sandbox-bwrap/test/live.test.ts
@@ -35,8 +35,8 @@ const usable = (() => {
const mgr = new CommandSessionManager({
confineSpawn: () => (argv, opts) =>
policy === null
- ? argv
- : provider.confine(argv, { ...policy, workspaceRoot: opts.workspaceDir }).argv,
+ ? { argv }
+ : provider.confine(argv, { writableTemp: true, ...policy, workspaceRoot: opts.workspaceDir }),
workspaceDir: ws,
});
diff --git a/plugins/sandbox-bwrap/test/profile.test.ts b/plugins/sandbox-bwrap/test/profile.test.ts
index b99fb9d3..a292d87a 100644
--- a/plugins/sandbox-bwrap/test/profile.test.ts
+++ b/plugins/sandbox-bwrap/test/profile.test.ts
@@ -4,10 +4,15 @@
* paths are deterministic on any host (a real-bwrap host also runs sandbox-live).
*/
import { describe, expect, it } from "vitest";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
-import { bwrapProfileArgs, createPenguinBwrapProvider } from "../src/index.js";
+import {
+ bwrapProfileArgs,
+ createPenguinBwrapProvider,
+ loadPenguinBwrapProvider,
+ vendoredRunner,
+} from "../src/index.js";
const ARGV = ["bash", "-lc", "echo hi"] as const;
const WS = "/work/project";
@@ -35,16 +40,49 @@ describe("penguin-bwrap profile", () => {
// skipIf(win32): the profile echoes host path resolution, which turns the POSIX
// workspace literal into a drive path — and bwrap never runs there anyway.
it.skipIf(process.platform === "win32")(
- "workspace-write: the workspace and a tmpfs /tmp become writable",
+ "workspace-write: the workspace becomes writable, and /tmp only when temp is",
() => {
const args = bwrapProfileArgs({ mode: "workspace-write", workspaceRoot: WS });
- expect(args).toContain("--tmpfs");
expect(args.join(" ")).toContain(`--bind ${WS} ${WS}`);
+ expect(args).not.toContain("--tmpfs");
+
+ const withTemp = bwrapProfileArgs({
+ mode: "workspace-write",
+ workspaceRoot: WS,
+ writableTemp: true,
+ });
+ expect(withTemp.join(" ")).toContain("--tmpfs /tmp");
+ expect(withTemp.join(" ")).toContain(`--bind ${WS} ${WS}`);
// /tmp is the tmpfs, never also a bind of the host's /tmp.
- expect(args.join(" ")).not.toContain("--bind /tmp /tmp");
+ expect(withTemp.join(" ")).not.toContain("--bind /tmp /tmp");
},
);
+ it("read-only with writable temp: a tmpfs /tmp is the only writable place", () => {
+ const args = bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, writableTemp: true });
+ expect(args.join(" ")).toContain("--tmpfs /tmp");
+ expect(args.join(" ")).not.toContain(`--bind ${WS}`);
+ });
+
+ it("refuses the local network level rather than reading it as an open network", () => {
+ expect(() =>
+ bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, network: "local" }),
+ ).toThrow(/local network/);
+ });
+
+ it("full access binds the root read-WRITE, but still cuts the network when asked", () => {
+ const args = bwrapProfileArgs({
+ mode: "danger-full-access",
+ workspaceRoot: WS,
+ network: "none",
+ });
+ // The whole filesystem is writable: --bind / /, never --ro-bind / /.
+ expect(args.slice(0, 3)).toEqual(["--bind", "/", "/"]);
+ expect(args.join(" ")).not.toContain("--ro-bind / /");
+ // The network cut still applies — that is why the policy reached a backend at all.
+ expect(args).toContain("--unshare-net");
+ });
+
it("network: none adds --unshare-net; absent leaves the network alone", () => {
expect(bwrapProfileArgs({ mode: "read-only", workspaceRoot: WS, network: "none" })).toContain(
"--unshare-net",
@@ -132,3 +170,36 @@ describe("penguin-bwrap provider", () => {
expect(probes).toBe(1);
});
});
+
+describe("bwrap on another platform", () => {
+ it("declines off Linux (not a failure), and fails with a reason on Linux it cannot serve", async () => {
+ const other = "win32" as const;
+ await expect(
+ loadPenguinBwrapProvider({ platform: other, probe: () => true }),
+ ).resolves.toBeNull();
+ await expect(
+ loadPenguinBwrapProvider({ platform: "linux", probe: () => false }),
+ ).rejects.toThrow(/is missing or refuses/);
+ await expect(
+ loadPenguinBwrapProvider({ platform: "linux", probe: () => true }),
+ ).resolves.toBeDefined();
+ });
+});
+
+describe("the bwrap it runs", () => {
+ it("ships its own, so a host without bubblewrap still confines", () => {
+ // The real thing: the package carries a binary for THIS host (scripts/vendor-bwrap.mjs) —
+ // on Linux only, the one platform bubblewrap runs on. Elsewhere there is none to carry.
+ const shipped = vendoredRunner();
+ if (process.platform !== "linux") {
+ expect(shipped).toBe("");
+ return;
+ }
+ expect(shipped).toMatch(/vendor[\\/]linux-(x64|arm64)[\\/]bin[\\/]bwrap$/);
+ expect(existsSync(shipped)).toBe(true);
+ });
+
+ it("carries none for a host it has no binary for, and says so with an empty path", () => {
+ expect(vendoredRunner("win32", "x64", () => false)).toBe("");
+ });
+});
diff --git a/plugins/sandbox-dsh/README.md b/plugins/sandbox-dsh/README.md
index d5542d64..de5c496d 100644
--- a/plugins/sandbox-dsh/README.md
+++ b/plugins/sandbox-dsh/README.md
@@ -18,7 +18,7 @@ functionally:
DSH's policy vocabulary governs **file-write effects only**, so this adaptor declares
exactly `fs-write`. The sandbox service therefore never routes a `network` or
`mask-paths` policy here, and the adaptor never has to silently drop a dimension it
-cannot honor — for those, use the bubblewrap, Seatbelt or MXC backend for your platform.
+cannot honor — for those, use the bubblewrap, Seatbelt or WSL backend for your platform.
## Requirements
diff --git a/plugins/sandbox-dsh/src/index.ts b/plugins/sandbox-dsh/src/index.ts
index 59008dee..c6ffb6bd 100644
--- a/plugins/sandbox-dsh/src/index.ts
+++ b/plugins/sandbox-dsh/src/index.ts
@@ -41,6 +41,11 @@ export async function loadDshAdaptor(): Promise<SandboxProvider | null> {
// DSH's own words: "Network and process visibility are outside this vocabulary."
dimensions: ["fs-write"],
confine(argv, policy): ConfinedArgv {
+ if (policy.mode === "danger-full-access") {
+ // Unreachable: this backend implements only fs-write, so the service never hands it a
+ // full-access policy (which only ever arrives with a network/mask dimension it lacks).
+ throw new Error("dsh-local does not implement full filesystem access with confinement");
+ }
const confined = dsh.confine(argv, {
mode: policy.mode,
workspaceRoot: policy.workspaceRoot,
diff --git a/plugins/sandbox-dsh/test/live.test.ts b/plugins/sandbox-dsh/test/live.test.ts
index db9c085b..de52b45c 100644
--- a/plugins/sandbox-dsh/test/live.test.ts
+++ b/plugins/sandbox-dsh/test/live.test.ts
@@ -38,8 +38,8 @@ const usable =
const mgr = new CommandSessionManager({
confineSpawn: () => (argv, opts) =>
mode === null || provider === null
- ? argv
- : provider.confine(argv, { mode, workspaceRoot: opts.workspaceDir }).argv,
+ ? { argv }
+ : provider.confine(argv, { mode, workspaceRoot: opts.workspaceDir }),
workspaceDir: ws,
});
diff --git a/plugins/sandbox-mxc/README.md b/plugins/sandbox-mxc/README.md
deleted file mode 100644
index 0b7b3300..00000000
--- a/plugins/sandbox-mxc/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Windows sandbox backend (Microsoft MXC)
-
-Confines command subprocesses on Windows through
-**MXC** (Microsoft eXecution Containers), using its `processcontainer` backend.
-Implements **all three** dimensions of the harness sandbox interface.
-
-## Why this exists
-
-Windows has neither bubblewrap nor `sandbox-exec`, and the DSH adaptor's Windows rung
-(restricted tokens plus ACLs) governs file writes only. MXC's `processcontainer` backend
-is the one Windows mechanism that expresses all three dimensions, and it maps onto them
-directly:
-
-| Harness dimension | MXC |
-| --- | --- |
-| `fs-write` | `filesystem.readwritePaths` / `readonlyPaths` |
-| `mask-paths` | `filesystem.deniedPaths` |
-| `network` | `network.allowOutbound: false` (MXC already defaults to deny) |
-
-## Requirements
-
-- Windows.
-- `@microsoft/mxc-sdk`, an **optional peer dependency**. It carries roughly 40MB of
- per-platform binaries plus a native pty module, so only a deployment that actually wants
- this backend pays for them. It is reached through a dynamic import, and a missing SDK
- fails this backend's load — reported fail-closed — rather than the platform bundle's.
-
-## Windows only, deliberately
-
-MXC also ships Linux (bubblewrap/LXC) and macOS (Seatbelt) backends, but this harness
-already has native, live-verified plugins for those. Declaring them here would add an
-untested second path to a solved problem, so on any non-Windows host this backend declines
-and routing moves on.
-
-## Install
-
-It ships with the harness build. On the Plugins page, install it to the Project that should
-run it: the App re-assembles itself, no restart. Written by hand, it is a row of the Project's
-`.project_config.toml`:
-
-```toml
-[plugins]
-"@prismshadow/penguin-plugin-sandbox-mxc" = "*"
-```
-
-Installing is an operator-side action: the harness resolves the package from the installation,
-never from this listing.
-
-## License
-
-Apache-2.0.
diff --git a/plugins/sandbox-mxc/src/index.ts b/plugins/sandbox-mxc/src/index.ts
deleted file mode 100644
index 33488c05..00000000
--- a/plugins/sandbox-mxc/src/index.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-/**
- * @prismshadow/penguin-plugin-sandbox-mxc — a Windows sandbox backend over Microsoft
- * MXC (Microsoft eXecution Containers).
- *
- * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page
- * and the harness resolves it from the installation. It compiles against the
- * `@prismshadow/penguin-core/plugin` surface (types, plus the decorators its bundle
- * carries) and has no runtime dependency on the
- * harness or on any other backend.
- *
- * WHY THIS EXISTS: Windows has no bubblewrap and no sandbox-exec, and the DSH adaptor's
- * Windows rung (restricted tokens + ACLs) governs file writes only. MXC's
- * `processcontainer` backend is the one mechanism that expresses all three dimensions
- * of this harness's sandbox interface on Windows, and it maps onto them directly:
- *
- * fs-write → filesystem.readwritePaths / readonlyPaths
- * mask-paths → filesystem.deniedPaths
- * network → network.allowOutbound: false (MXC's default is already deny)
- *
- * WINDOWS ONLY, deliberately. MXC also carries Linux (bubblewrap/LXC) and macOS
- * (Seatbelt) backends, but this harness already ships native, live-verified plugins for
- * those; declaring them here too would only add an untested second path to a solved
- * problem. On any non-Windows host this backend declines and the routing moves on.
- *
- * The SDK is an OPTIONAL PEER DEPENDENCY, loaded through a dynamic import for the same
- * reason the DSH adaptor loads its chain that way: it carries ~40MB of per-platform
- * binaries plus a native pty module, so only a deployment that actually wants it pays
- * for it, and an installation missing it surfaces as an unavailable capability (the
- * sandbox service then fails closed for a confining policy) rather than a broken boot.
- *
- * COUPLING SURFACE, stated because MXC is Public Preview and its schema may move before
- * 1.0. Beyond the published `buildSandboxPayload`/`getPlatformSupport` API this backend
- * relies on exactly two internals, both verified against 0.7.0 and both asserted in the
- * tests: the runner is `bin/<arch>/wxc-exec.exe` inside the SDK package, and it takes
- * the whole config as `--config-base64 <base64 JSON>` with the command inside the
- * config (which is what lets an argv-rewriting seam host it at all — there is no
- * trailing argv to append).
- */
-import { createRequire } from "node:module";
-import path from "node:path";
-import { spawnSync } from "node:child_process";
-import { Bind, Component } from "@prismshadow/penguin-core/plugin";
-import type {
- ConfinedArgv,
- Plugin,
- SandboxPolicy,
- SandboxProvider,
- SandboxProviderSource,
-} from "@prismshadow/penguin-core/plugin";
-
-/** Default probe budget; a probe that hangs must not hang the first spawn forever. */
-const PROBE_TIMEOUT_MS = 5_000;
-
-/** The MXC policy schema this backend writes. Pinned: a preview schema is a moving target. */
-const MXC_POLICY_VERSION = "0.7.0-alpha";
-
-/** The narrow slice of the MXC SDK this backend uses (see the coupling note above). */
-export interface MxcSdk {
- buildSandboxPayload(
- script: string,
- policy: Record<string, unknown>,
- workingDirectory?: string,
- containerName?: string,
- containment?: string,
- ): Record<string, unknown>;
-}
-
-/** Test seams: inject the SDK, the runner path, and the probe verdict. */
-export interface MxcInternals {
- sdk?: MxcSdk;
- runnerPath?: string;
- probe?: (runner: string, timeoutMs: number) => boolean;
- platform?: NodeJS.Platform;
-}
-
-/**
- * Quotes one argument the way `CommandLineToArgvW` parses it, so the argv the harness
- * handed us survives the round trip through MXC's single `commandLine` string. The
- * backslash rules are the fiddly part: a run of backslashes is only doubled when it
- * precedes a quote (a closing one included), which is why the two cases below differ.
- */
-export function quoteWindowsArg(arg: string): string {
- if (arg.length > 0 && !/[ \t\n\v"]/.test(arg)) return arg;
- let quoted = '"';
- let backslashes = 0;
- for (const char of arg) {
- if (char === "\\") {
- backslashes++;
- continue;
- }
- if (char === '"') {
- quoted += "\\".repeat(backslashes * 2 + 1) + '"';
- } else {
- quoted += "\\".repeat(backslashes) + char;
- }
- backslashes = 0;
- }
- quoted += "\\".repeat(backslashes * 2) + '"';
- return quoted;
-}
-
-/** The argv the harness is about to spawn, as one Windows command line. */
-export function toCommandLine(argv: readonly string[]): string {
- return argv.map(quoteWindowsArg).join(" ");
-}
-
-/** The MXC SandboxPolicy for one harness policy: the three dimensions, mapped. */
-export function mxcPolicyFor(policy: SandboxPolicy): Record<string, unknown> {
- const readwritePaths = policy.mode === "workspace-write" ? [policy.workspaceRoot] : [];
- return {
- version: MXC_POLICY_VERSION,
- filesystem: {
- // The whole volume readable, the workspace writable under workspace-write, and
- // the masked paths denied outright — MXC's deniedPaths outranks the grants above.
- readonlyPaths: [path.parse(path.resolve(policy.workspaceRoot)).root],
- readwritePaths,
- deniedPaths: [...(policy.maskPaths ?? [])],
- },
- // MXC defaults to deny; say it explicitly so the intent survives a schema default change.
- network: { allowOutbound: policy.network === "none" ? false : true },
- };
-}
-
-/** The runner shipped inside the installed SDK: bin/<arch>/wxc-exec.exe. */
-export function resolveRunner(requireFrom: NodeRequire = createRequire(import.meta.url)): string {
- const manifest = requireFrom.resolve("@microsoft/mxc-sdk/package.json");
- return path.join(path.dirname(manifest), "bin", process.arch, "wxc-exec.exe");
-}
-
-/** Functional probe: the runner answers `--probe` on a host where it can actually confine. */
-function defaultProbe(runner: string, timeoutMs: number): boolean {
- const probe = spawnSync(runner, ["--probe"], { timeout: timeoutMs, stdio: "ignore" });
- return probe.status === 0;
-}
-
-/**
- * Loads the backend. Resolves to null where it cannot serve — a non-Windows host, or an
- * installation without the optional SDK — so the harness reports an unavailable
- * capability instead of a failure.
- */
-export async function loadMxcProvider(
- internals: MxcInternals = {},
-): Promise<SandboxProvider | null> {
- const platform = internals.platform ?? process.platform;
- if (platform !== "win32") return null;
- const sdk = internals.sdk ?? ((await import("@microsoft/mxc-sdk")) as unknown as MxcSdk);
- const runner = internals.runnerPath ?? resolveRunner();
- const probe = internals.probe ?? defaultProbe;
- return createMxcProvider(sdk, runner, probe);
-}
-
-/** The backend itself, over an already-resolved SDK and runner (the unit-testable core). */
-export function createMxcProvider(
- sdk: MxcSdk,
- runner: string,
- probe: (runner: string, timeoutMs: number) => boolean = defaultProbe,
-): SandboxProvider {
- let usable: boolean | undefined;
- return {
- dimensions: ["fs-write", "network", "mask-paths"],
- confine(argv, policy): ConfinedArgv {
- usable ??= probe(runner, PROBE_TIMEOUT_MS);
- if (!usable) {
- throw new Error(
- "penguin-mxc cannot confine on this host: the MXC runner is missing or reports no " +
- "usable containment; refusing to run the command unconfined.",
- );
- }
- const config = sdk.buildSandboxPayload(
- // The command travels INSIDE the config — MXC takes no trailing argv, which is
- // exactly what lets this argv-rewriting seam host it.
- toCommandLine(argv),
- mxcPolicyFor(policy),
- policy.workspaceRoot,
- undefined,
- "process",
- );
- const encoded = Buffer.from(JSON.stringify(config), "utf8").toString("base64");
- return {
- argv: [runner, "--config-base64", encoded],
- // processcontainer enforces the policy it accepts; MXC reports its own inability
- // through the probe and through structured errors, not by confining less.
- enforcement: "full",
- // Win32 denial dialects: cmd, PowerShell/.NET, and Node's own EACCES text.
- denialSignatures: ["access is denied", "access to the path", "permission denied"],
- runnerFailureRules: [{ fatalSignatures: ["wxc-exec", "mxc error"] }],
- };
- },
- };
-}
-
-/**
- * The plugin's one module: a provider on the sandbox slot, the code half of the
- * contribution the decorator declares (its manifest is generated into ifaces.json from
- * here). Created per App, so a hot swap gets a fresh provider.
- */
-@Component({
- contributes: {
- "SandboxModule.providers": [
- {
- id: "sandbox-mxc.provider",
- name: "penguin-mxc",
- dimensions: ["fs-write", "network", "mask-paths"],
- },
- ],
- },
-})
-export class SandboxMxc {
- @Bind("sandbox-mxc.provider") provider!: SandboxProviderSource;
-
- setup() {
- this.provider = loadMxcProvider();
- }
-}
-
-const plugin: Plugin = { modules: [SandboxMxc] };
-export default plugin;
diff --git a/plugins/sandbox-mxc/test/backend.test.ts b/plugins/sandbox-mxc/test/backend.test.ts
deleted file mode 100644
index 06f250f7..00000000
--- a/plugins/sandbox-mxc/test/backend.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-/**
- * Unit tests for the MXC Windows backend: the dimension mapping, the Windows
- * command-line quoting the argv must survive, the runner invocation shape, and the
- * platform/probe gating. These run on any host — the SDK is injected where the test is
- * about our mapping, and exercised for real where the test is about the SDK contract.
- */
-import { describe, expect, it } from "vitest";
-import path from "node:path";
-import {
- createMxcProvider,
- loadMxcProvider,
- mxcPolicyFor,
- quoteWindowsArg,
- resolveRunner,
- toCommandLine,
- type MxcSdk,
-} from "../src/index.js";
-
-const RUNNER = "C:\\app\\node_modules\\@microsoft\\mxc-sdk\\bin\\x64\\wxc-exec.exe";
-const WS = "C:\\work\\project";
-const ARGV = ["cmd.exe", "/d", "/s", "/c", "echo hi"] as const;
-
-/** Records what the backend asks the SDK to build. */
-function recordingSdk(): { sdk: MxcSdk; calls: Array<Record<string, unknown>> } {
- const calls: Array<Record<string, unknown>> = [];
- const sdk: MxcSdk = {
- buildSandboxPayload(script, policy, workingDirectory, _name, containment) {
- calls.push({ script, policy, workingDirectory, containment });
- return { process: { commandLine: script }, containment };
- },
- };
- return { sdk, calls };
-}
-
-function decodeConfig(argv: readonly string[]): Record<string, unknown> {
- expect(argv[1]).toBe("--config-base64");
- return JSON.parse(Buffer.from(argv[2]!, "base64").toString("utf8")) as Record<string, unknown>;
-}
-
-describe("windows command-line quoting", () => {
- it("leaves simple arguments alone", () => {
- expect(quoteWindowsArg("cmd.exe")).toBe("cmd.exe");
- expect(quoteWindowsArg("/c")).toBe("/c");
- });
-
- it("quotes anything containing whitespace", () => {
- expect(quoteWindowsArg("echo hi")).toBe('"echo hi"');
- expect(quoteWindowsArg("")).toBe('""');
- });
-
- it("escapes embedded quotes and the backslashes that precede them", () => {
- // CommandLineToArgvW: a backslash run doubles only before a quote.
- expect(quoteWindowsArg('say "hi"')).toBe('"say \\"hi\\""');
- expect(quoteWindowsArg('a\\"b')).toBe('"a\\\\\\"b"');
- // Inside quotes a trailing backslash run doubles, because the closing quote follows it.
- expect(quoteWindowsArg("C:\\dir\\ x")).toBe('"C:\\dir\\ x"');
- expect(quoteWindowsArg("a b\\")).toBe('"a b\\\\"');
- });
-
- it("a path without whitespace or quotes passes through, trailing backslash included", () => {
- // CommandLineToArgvW only treats backslashes specially when a quote follows them,
- // and arguments are joined with spaces — so an unquoted trailing backslash round
- // trips exactly. Quoting it would be harmless but is not required, and the simpler
- // rule is the one with fewer ways to be wrong.
- expect(quoteWindowsArg("C:\\Windows\\System32")).toBe("C:\\Windows\\System32");
- expect(quoteWindowsArg("C:\\dir\\")).toBe("C:\\dir\\");
- });
-
- it("joins an argv into one command line", () => {
- expect(toCommandLine(ARGV)).toBe('cmd.exe /d /s /c "echo hi"');
- });
-});
-
-describe("dimension mapping", () => {
- it("workspace-write grants the workspace and nothing else", () => {
- const policy = mxcPolicyFor({ mode: "workspace-write", workspaceRoot: WS });
- expect(policy.filesystem).toMatchObject({
- readwritePaths: [WS],
- readonlyPaths: [path.parse(path.resolve(WS)).root],
- deniedPaths: [],
- });
- });
-
- it("read-only grants nothing writable", () => {
- expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS }).filesystem).toMatchObject({
- readwritePaths: [],
- });
- });
-
- it("network: none maps to allowOutbound false; absent leaves the network alone", () => {
- expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS, network: "none" })).toMatchObject({
- network: { allowOutbound: false },
- });
- expect(mxcPolicyFor({ mode: "read-only", workspaceRoot: WS })).toMatchObject({
- network: { allowOutbound: true },
- });
- });
-
- it("mask-paths map to deniedPaths", () => {
- expect(
- mxcPolicyFor({
- mode: "workspace-write",
- workspaceRoot: WS,
- maskPaths: ["C:\\Users\\me\\.ssh"],
- }).filesystem,
- ).toMatchObject({ deniedPaths: ["C:\\Users\\me\\.ssh"] });
- });
-});
-
-describe("runner invocation", () => {
- it("implements every dimension of the sandbox interface", () => {
- const { sdk } = recordingSdk();
- expect(createMxcProvider(sdk, RUNNER, () => true).dimensions).toEqual([
- "fs-write",
- "network",
- "mask-paths",
- ]);
- });
-
- it("wraps as [runner, --config-base64, <config>] with the command INSIDE the config", () => {
- const { sdk, calls } = recordingSdk();
- const confined = createMxcProvider(sdk, RUNNER, () => true).confine([...ARGV], {
- mode: "workspace-write",
- workspaceRoot: WS,
- network: "none",
- maskPaths: ["C:\\secrets"],
- });
- expect(confined.argv[0]).toBe(RUNNER);
- expect(confined.argv).toHaveLength(3);
- // No trailing argv: MXC takes the command through the config, which is what lets an
- // argv-rewriting seam host it at all.
- expect(decodeConfig(confined.argv)).toMatchObject({
- process: { commandLine: 'cmd.exe /d /s /c "echo hi"' },
- containment: "process",
- });
- expect(calls[0]).toMatchObject({ workingDirectory: WS, containment: "process" });
- expect(confined.enforcement).toBe("full");
- });
-
- it("an unusable runner fails closed, and the probe runs once", () => {
- const { sdk } = recordingSdk();
- let probes = 0;
- const provider = createMxcProvider(sdk, RUNNER, () => {
- probes++;
- return false;
- });
- const policy = { mode: "read-only", workspaceRoot: WS } as const;
- expect(() => provider.confine([...ARGV], policy)).toThrow(/cannot confine on this host/);
- expect(() => provider.confine([...ARGV], policy)).toThrow(/refusing to run/);
- expect(probes).toBe(1);
- });
-});
-
-describe("platform gating and SDK contract", () => {
- it("declines on every non-Windows host instead of pretending", async () => {
- expect(await loadMxcProvider({ platform: "linux" })).toBeNull();
- expect(await loadMxcProvider({ platform: "darwin" })).toBeNull();
- });
-
- it("the runner path is bin/<arch>/wxc-exec.exe inside the installed SDK", () => {
- // One of the two MXC internals this backend depends on (see its module doc).
- const runner = resolveRunner();
- expect(runner.endsWith(path.join("bin", process.arch, "wxc-exec.exe"))).toBe(true);
- expect(runner).toContain(path.join("@microsoft", "mxc-sdk"));
- });
-
- it("the REAL SDK still maps our policy onto the fields this backend relies on", async () => {
- // Drift guard: MXC is Public Preview, so this asserts against the installed SDK
- // rather than a fake — if the schema moves, this fails here instead of on Windows.
- const sdk = (await import("@microsoft/mxc-sdk")) as unknown as MxcSdk;
- const config = sdk.buildSandboxPayload(
- toCommandLine(ARGV),
- mxcPolicyFor({
- mode: "workspace-write",
- workspaceRoot: WS,
- network: "none",
- maskPaths: ["C:\\secrets"],
- }),
- WS,
- undefined,
- "process",
- );
- expect(config).toMatchObject({
- process: { commandLine: 'cmd.exe /d /s /c "echo hi"' },
- filesystem: {
- readwritePaths: [WS],
- deniedPaths: ["C:\\secrets"],
- },
- network: { defaultPolicy: "block" },
- // No containment assertion: the backend passes "process" in but never reads the
- // echo, and the SDK resolves that field per HOST (seatbelt on darwin) — on the
- // only host this backend runs, Windows, it is the process containment requested.
- });
- });
-});
diff --git a/plugins/sandbox-mxc/tsup.config.ts b/plugins/sandbox-mxc/tsup.config.ts
deleted file mode 100644
index 30688a7a..00000000
--- a/plugins/sandbox-mxc/tsup.config.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { defineConfig } from "tsup";
-
-export default defineConfig({
- entry: ["src/index.ts"],
- format: ["esm"],
- target: "node24",
- dts: true,
- clean: true,
- sourcemap: true,
-});
diff --git a/plugins/sandbox-seatbelt/README.md b/plugins/sandbox-seatbelt/README.md
index cc372489..aadc7428 100644
--- a/plugins/sandbox-seatbelt/README.md
+++ b/plugins/sandbox-seatbelt/README.md
@@ -4,9 +4,19 @@ The macOS counterpart to the bubblewrap backend, built on `sandbox-exec` (Seatbe
Implements **all three** dimensions of the harness sandbox interface — filesystem writes,
network isolation and path masking — as policy rules rather than mounts.
+## The program it runs
+
+`sandbox-exec` is part of macOS: it lives at `/usr/bin/sandbox-exec` on every install, and it is
+Apple's to distribute, not this project's — so unlike the Linux backend, which ships its own
+bubblewrap, there is nothing here to vendor. What that buys elsewhere, this buys by naming the
+absolute path rather than a bare command: a PATH without `/usr/bin`, or one that puts something
+else called `sandbox-exec` first, no longer decides what confines a command. A host where it does not work is caught by the
+load-time probe.
+
## Requirements
-- macOS, with `sandbox-exec` available (part of the base system).
+- macOS, with `sandbox-exec` available (part of the base system). On any other platform the
+ backend declines to mount, so a policy is routed to a backend that host has.
## How the profile is built
@@ -14,10 +24,15 @@ network isolation and path masking — as policy rules rather than mounts.
(allow default) ; start from the host's world
(deny file-write*) ; nothing is writable…
(allow file-write* (literal "/dev/null") …) ; …beyond the required sinks
-;; workspace-write
+;; workspace-write, and the temp areas when temp is writable
(allow file-write* (subpath "<workspaceRoot>") …)
;; network: none
(deny network*)
+;; network: local (only the host's localhost)
+(deny network*)
+(allow network-outbound (remote ip "localhost:*"))
+(allow network-bind (local ip "localhost:*"))
+(allow network-inbound (local ip "localhost:*"))
;; mask-paths
(deny file-read* file-write* (subpath "<p>"))
```
diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.ts
index 4139407e..f339593a 100644
--- a/plugins/sandbox-seatbelt/src/index.ts
+++ b/plugins/sandbox-seatbelt/src/index.ts
@@ -15,6 +15,7 @@
* (allow file-write* (literal "/dev/null") …) …beyond the required sinks
* [workspace-write] (allow file-write* (subpath <root>) …)
* [network: none] (deny network*)
+ * [network: local] (deny network*) then allow localhost: outbound to, bind and inbound on it
* [mask-paths] (deny file-read* file-write* (subpath <p>))
*
* Rule ORDER is the counterpart to bwrap's mount order: in SBPL the LAST matching rule
@@ -29,8 +30,8 @@
* working, the probe below is what turns that into a fail-closed refusal rather than an
* unconfined run.
*/
-import { spawnSync } from "node:child_process";
-import { realpathSync } from "node:fs";
+import { execFile, spawnSync } from "node:child_process";
+import { existsSync, realpathSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { Bind, Component } from "@prismshadow/penguin-core/plugin";
@@ -39,6 +40,7 @@ import type {
Plugin,
SandboxPolicy,
SandboxProvider,
+ SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
/** Default probe budget; a probe that hangs must not hang the first spawn forever. */
@@ -47,9 +49,26 @@ const PROBE_TIMEOUT_MS = 5_000;
/** The write sinks a confined process needs even under read-only. */
const REQUIRED_WRITE_SINKS = ["/dev/null", "/dev/stdout", "/dev/stderr", "/dev/dtracehelper"];
+/**
+ * Where macOS keeps the program this backend runs.
+ *
+ * Unlike the Linux backend, which ships its own bubblewrap, there is nothing to vendor here:
+ * `sandbox-exec` is part of macOS, lives at a fixed path on every install, and is Apple's to
+ * distribute, not ours. What the shipped binary bought there — never depending on the host's
+ * setup — this buys by naming the absolute path instead of a bare command: a PATH that lacks
+ * `/usr/bin`, or that puts something else called `sandbox-exec` earlier, no longer decides what
+ * confines a command. A host missing it is caught by the probe at load, with the reason.
+ */
+export const SYSTEM_RUNNER = "/usr/bin/sandbox-exec";
+
+/** The program to run when the settings name none: the OS's own, else a PATH lookup. */
+export function defaultRunner(exists: (p: string) => boolean = existsSync): string {
+ return exists(SYSTEM_RUNNER) ? SYSTEM_RUNNER : "sandbox-exec";
+}
+
/** Test seams: inject the probe verdict and the runner name. */
export interface SeatbeltInternals {
- probe?: (timeoutMs: number) => boolean;
+ probe?: (timeoutMs: number, runner: string) => boolean;
runner?: string;
}
@@ -62,10 +81,19 @@ export function canonicalPath(target: string): string {
}
}
-/** The writable roots `workspace-write` grants: the workspace plus the temp areas, canonical and deduplicated. */
+/**
+ * The writable roots a policy grants, canonical and deduplicated: the workspace under
+ * `workspace-write`, and the temp areas whenever the policy makes temp writable (either mode).
+ */
export function writableRoots(policy: SandboxPolicy): string[] {
- if (policy.mode !== "workspace-write") return [];
- return [...new Set([policy.workspaceRoot, "/tmp", tmpdir()].map(canonicalPath))];
+ return [
+ ...new Set(
+ [
+ ...(policy.mode === "workspace-write" ? [policy.workspaceRoot] : []),
+ ...(policy.writableTemp === true ? ["/tmp", tmpdir()] : []),
+ ].map(canonicalPath),
+ ),
+ ];
}
/** Quote one path as an SBPL string literal. */
@@ -75,13 +103,18 @@ function sbplString(value: string): string {
/** The SBPL profile for one policy: the exact text handed to `sandbox-exec -p`. */
export function seatbeltProfile(policy: SandboxPolicy): string {
- const forms = [
- "(version 1)",
- "(allow default)",
- "(deny file-write*)",
- `(allow file-write* ${REQUIRED_WRITE_SINKS.map((sink) => `(literal ${sbplString(sink)})`).join(" ")})`,
- ];
- const roots = writableRoots(policy);
+ // Full access denies no writes: "(allow default)" already permits them, and only the network
+ // and mask forms below still bite. A confining mode denies writes and re-allows the sinks.
+ const full = policy.mode === "danger-full-access";
+ const forms = full
+ ? ["(version 1)", "(allow default)"]
+ : [
+ "(version 1)",
+ "(allow default)",
+ "(deny file-write*)",
+ `(allow file-write* ${REQUIRED_WRITE_SINKS.map((sink) => `(literal ${sbplString(sink)})`).join(" ")})`,
+ ];
+ const roots = full ? [] : writableRoots(policy);
if (roots.length > 0) {
forms.push(
`(allow file-write* ${roots.map((root) => `(subpath ${sbplString(root)})`).join(" ")})`,
@@ -91,6 +124,16 @@ export function seatbeltProfile(policy: SandboxPolicy): string {
// Seatbelt filters network natively: no sockets at all, outbound or inbound.
forms.push("(deny network*)");
}
+ if (policy.network === "local") {
+ // Everything is denied, then the host's loopback is let back in: connecting to a local
+ // server, and binding and accepting on localhost for one's own. Later rules win in SBPL.
+ forms.push(
+ "(deny network*)",
+ '(allow network-outbound (remote ip "localhost:*"))',
+ '(allow network-bind (local ip "localhost:*"))',
+ '(allow network-inbound (local ip "localhost:*"))',
+ );
+ }
// LAST: a mask must outrank the write allowances above, including a masked path that
// happens to sit inside the workspace.
for (const target of policy.maskPaths ?? []) {
@@ -120,18 +163,45 @@ function defaultProbe(timeoutMs: number, runner: string): boolean {
return probe.status === 0;
}
+/**
+ * Loads the backend, checking first that it can serve on this host — and rejecting, with the
+ * reason, when it cannot: it runs on macOS only, and needs a sandbox-exec that accepts its
+ * profile. The sandbox service records the rejection and names it when a command fails closed,
+ * so the backend is never silently absent.
+ */
+export async function loadSeatbeltProvider(
+ internals: SeatbeltInternals & { platform?: NodeJS.Platform } = {},
+): Promise<SandboxProvider | null> {
+ const platform = internals.platform ?? process.platform;
+ // Not this host's backend: a decline, not a failure (see penguin-bwrap's loader).
+ if (platform !== "darwin") return null;
+ const runner = internals.runner ?? defaultRunner();
+ const usable = internals.probe
+ ? internals.probe(PROBE_TIMEOUT_MS, runner)
+ : await new Promise<boolean>((resolve) => {
+ execFile(
+ runner,
+ [...seatbeltArgs({ mode: "read-only", workspaceRoot: "/" }), "--", "true"],
+ { timeout: PROBE_TIMEOUT_MS },
+ (err) => resolve(err === null),
+ );
+ });
+ if (!usable) throw new Error(`'${runner}' is missing or refuses the Seatbelt profile`);
+ return createSeatbeltProvider(internals);
+}
+
/**
* The backend. The probe runs once, lazily (first confine), and is cached; an
* unusable Seatbelt throws — fail-closed — rather than degrading to a weaker profile.
*/
export function createSeatbeltProvider(internals: SeatbeltInternals = {}): SandboxProvider {
- const runner = internals.runner ?? "sandbox-exec";
- const probe = internals.probe ?? ((timeoutMs: number) => defaultProbe(timeoutMs, runner));
+ const runner = internals.runner ?? defaultRunner();
+ const probe = internals.probe ?? defaultProbe;
let usable: boolean | undefined;
return {
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "network-local", "mask-paths"],
confine(argv, policy): ConfinedArgv {
- usable ??= probe(PROBE_TIMEOUT_MS);
+ usable ??= probe(PROBE_TIMEOUT_MS, runner);
if (!usable) {
throw new Error(
`penguin-seatbelt cannot confine on this host: '${runner}' is missing or refuses the ` +
@@ -162,16 +232,16 @@ export function createSeatbeltProvider(internals: SeatbeltInternals = {}): Sandb
{
id: "sandbox-seatbelt.provider",
name: "penguin-seatbelt",
- dimensions: ["fs-write", "network", "mask-paths"],
+ dimensions: ["fs-write", "network", "network-local", "mask-paths"],
},
],
},
})
export class SandboxSeatbelt {
- @Bind("sandbox-seatbelt.provider") provider!: SandboxProvider;
+ @Bind("sandbox-seatbelt.provider") provider!: SandboxProviderSource;
setup() {
- this.provider = createSeatbeltProvider();
+ this.provider = loadSeatbeltProvider();
}
}
diff --git a/plugins/sandbox-seatbelt/test/live.test.ts b/plugins/sandbox-seatbelt/test/live.test.ts
index 739138b9..86b7a85a 100644
--- a/plugins/sandbox-seatbelt/test/live.test.ts
+++ b/plugins/sandbox-seatbelt/test/live.test.ts
@@ -34,8 +34,8 @@ const usable = (() => {
const mgr = new CommandSessionManager({
confineSpawn: () => (argv, opts) =>
policy === null
- ? argv
- : provider.confine(argv, { ...policy, workspaceRoot: canonicalPath(opts.workspaceDir) }).argv,
+ ? { argv }
+ : provider.confine(argv, { ...policy, workspaceRoot: canonicalPath(opts.workspaceDir) }),
workspaceDir: ws,
});
diff --git a/plugins/sandbox-seatbelt/test/profile.test.ts b/plugins/sandbox-seatbelt/test/profile.test.ts
index 60102760..77049d43 100644
--- a/plugins/sandbox-seatbelt/test/profile.test.ts
+++ b/plugins/sandbox-seatbelt/test/profile.test.ts
@@ -11,7 +11,10 @@ import path from "node:path";
import {
canonicalPath,
createSeatbeltProvider,
+ defaultRunner,
+ loadSeatbeltProvider,
seatbeltProfile,
+ SYSTEM_RUNNER,
writableRoots,
} from "../src/index.js";
@@ -31,10 +34,52 @@ describe.skipIf(process.platform === "win32")("seatbelt profile", () => {
expect(profile).not.toContain(`(subpath "${WS}")`);
});
- it("workspace-write: the workspace and the temp areas become writable", () => {
+ it("workspace-write: the workspace becomes writable, and the temp areas only when temp is", () => {
const profile = seatbeltProfile({ mode: "workspace-write", workspaceRoot: WS });
expect(profile).toContain(`(allow file-write* (subpath "${canonicalPath(WS)}")`);
- expect(profile).toContain(canonicalPath(tmpdir()));
+ expect(profile).not.toContain(`(subpath "${canonicalPath(tmpdir())}")`);
+ const withTemp = seatbeltProfile({
+ mode: "workspace-write",
+ workspaceRoot: WS,
+ writableTemp: true,
+ });
+ expect(withTemp).toContain(`(subpath "${canonicalPath(tmpdir())}")`);
+ });
+
+ it("read-only with writable temp: the temp areas are the only writable roots", () => {
+ expect(writableRoots({ mode: "read-only", workspaceRoot: WS, writableTemp: true })).toEqual([
+ ...new Set(["/tmp", tmpdir()].map(canonicalPath)),
+ ]);
+ });
+
+ it("full access denies no writes, yet still cuts the network when asked", () => {
+ const profile = seatbeltProfile({
+ mode: "danger-full-access",
+ workspaceRoot: WS,
+ network: "none",
+ });
+ // No write denial at all — "(allow default)" already permits every file write.
+ expect(profile).not.toContain("(deny file-write*)");
+ // The network cut still applies.
+ expect(profile).toContain("(deny network*)");
+ });
+
+ it("network: local denies every socket, then lets the host's localhost back in", () => {
+ const profile = seatbeltProfile({
+ mode: "workspace-write",
+ workspaceRoot: WS,
+ network: "local",
+ });
+ const deny = profile.indexOf("(deny network*)");
+ expect(deny).toBeGreaterThan(-1);
+ for (const form of [
+ '(allow network-outbound (remote ip "localhost:*"))',
+ '(allow network-bind (local ip "localhost:*"))',
+ '(allow network-inbound (local ip "localhost:*"))',
+ ]) {
+ // Later rules win in SBPL: each allowance comes after the blanket denial.
+ expect(profile.indexOf(form)).toBeGreaterThan(deny);
+ }
});
it("network: none denies every socket", () => {
@@ -93,6 +138,7 @@ describe("seatbelt provider", () => {
expect(createSeatbeltProvider({ probe: () => true }).dimensions).toEqual([
"fs-write",
"network",
+ "network-local",
"mask-paths",
]);
});
@@ -126,3 +172,26 @@ describe("seatbelt provider", () => {
expect(probes).toBe(1);
});
});
+
+describe("seatbelt on another platform", () => {
+ it("declines off macOS (not a failure), and fails with a reason on macOS it cannot serve", async () => {
+ const other = "linux" as const;
+ await expect(loadSeatbeltProvider({ platform: other, probe: () => true })).resolves.toBeNull();
+ await expect(loadSeatbeltProvider({ platform: "darwin", probe: () => false })).rejects.toThrow(
+ /is missing or refuses/,
+ );
+ await expect(
+ loadSeatbeltProvider({ platform: "darwin", probe: () => true }),
+ ).resolves.toBeDefined();
+ });
+});
+
+describe("the sandbox-exec it runs", () => {
+ it("names the macOS program by its absolute path, so PATH cannot decide what confines", () => {
+ expect(SYSTEM_RUNNER).toBe("/usr/bin/sandbox-exec");
+ expect(defaultRunner(() => true)).toBe(SYSTEM_RUNNER);
+ // A host without it (or any non-macOS machine running these tests) falls back to a lookup,
+ // and the load-time probe is what rejects a host where nothing answers.
+ expect(defaultRunner(() => false)).toBe("sandbox-exec");
+ });
+});
diff --git a/plugins/sandbox-wsl/README.md b/plugins/sandbox-wsl/README.md
new file mode 100644
index 00000000..54642dc3
--- /dev/null
+++ b/plugins/sandbox-wsl/README.md
@@ -0,0 +1,41 @@
+# @prismshadow/penguin-plugin-sandbox-wsl
+
+A Windows sandbox backend for PenguinHarness. Each agent command runs in a dedicated WSL2 distro (Ubuntu by default), as an unprivileged account, under [bubblewrap](https://github.com/containers/bubblewrap).
+
+| Dimension | How |
+| ---------- | ------------------------------------------------------------------------------------------ |
+| fs-write | The distro is read-only; the Workspace is bound read-write (or read-only) at its /mnt path |
+| network | `network: "none"` runs the command in an empty network namespace; `"local"` is not supported |
+| mask-paths | A tmpfs over a directory, `/dev/null` over a file |
+
+Other Windows drives are hidden from a confined command. The mount that hides them is remounted read-only after the Workspace is bound, so a write to a path outside the Workspace is refused rather than landing in a tmpfs that vanishes with the command.
+
+WSL keeps the generated `resolv.conf` outside the distro's root, at `/mnt/wsl/resolv.conf` or `/run/resolvconf/resolv.conf`, and `/etc/resolv.conf` is a symlink to it. Both are bound back read-only, or covering those directories would leave a reachable network where no host name resolves.
+
+## Setup
+
+Setup is a few tasks the plugin exports, each reporting the step it is on while it runs. Until the distro exists, the backend declines to load and says so.
+
+1. **Install WSL**: raises the Windows consent prompt for `setup/install-wsl.ps1`, which runs `wsl --install --no-distribution`. Some machines need a restart afterwards. This is the only step that needs an administrator.
+2. **Initialize sandbox distro**: downloads the base rootfs (checked against its published sha256), imports it as its own distro, installs bubblewrap and the package list (`git` and `curl`), creates the `penguin` account, and switches Windows interop off.
+3. **Check confinement**: runs real commands through the sandbox and lists what passed.
+
+State lives in `%LOCALAPPDATA%\penguin\sandbox-wsl` (`state.json`, the downloaded rootfs, the distro's disk).
+
+## Why interop is switched off
+
+With interop on, a Windows program started inside bwrap is an ordinary host process. It escapes every namespace: in a measured run it wrote to the Windows disk and reached the internet with the network cut. The distro's `/etc/wsl.conf` disables interop, the sandbox also hides `/run` where WSL keeps its interop sockets, and the check verifies both.
+
+## The base Linux
+
+| Base | Download | Unpacked | Note |
+| --- | --- | --- | --- |
+| Ubuntu 24.04 LTS (default) | 29 MB | 84 MB | glibc: what prebuilt binaries, native npm modules and pip wheels expect |
+| Alpine | 3.5 MB | 8.7 MB | musl: much smaller, and some prebuilt binaries and wheels do not run |
+
+## Limits
+
+- Commands run in Linux, not Git Bash. Windows toolchains cannot run confined; the distro carries Linux ones instead.
+- A Windows path in a command means nothing inside the distro. The Workspace is at `/mnt/<drive>/…`.
+- A Workspace on a network share has no path inside the distro and cannot be confined.
+- The Workspace is bound at its own path, so the empty directory chain above it (`/mnt/c/Users/…`) is visible even though every other drive is hidden.
diff --git a/plugins/sandbox-mxc/package.json b/plugins/sandbox-wsl/package.json
similarity index 59%
rename from plugins/sandbox-mxc/package.json
rename to plugins/sandbox-wsl/package.json
index b31fd14e..8b00939d 100644
--- a/plugins/sandbox-mxc/package.json
+++ b/plugins/sandbox-wsl/package.json
@@ -1,9 +1,9 @@
{
- "name": "@prismshadow/penguin-plugin-sandbox-mxc",
+ "name": "@prismshadow/penguin-plugin-sandbox-wsl",
"version": "0.2.2",
"private": true,
"type": "module",
- "description": "Windows sandbox backend for PenguinHarness over Microsoft MXC (Microsoft eXecution Containers): filesystem confinement, network isolation and path masking via the processcontainer backend.",
+ "description": "WSL sandbox backend for PenguinHarness on Windows: commands run in a dedicated WSL2 distro under bubblewrap, with Windows interop switched off.",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
@@ -15,6 +15,7 @@
"license": "Apache-2.0",
"files": [
"dist",
+ "setup",
"README.md",
"ifaces.json"
],
@@ -23,16 +24,7 @@
"test": "vitest run --passWithNoTests",
"build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
- "peerDependencies": {
- "@microsoft/mxc-sdk": ">=0.7.0 <1"
- },
- "peerDependenciesMeta": {
- "@microsoft/mxc-sdk": {
- "optional": true
- }
- },
"devDependencies": {
- "@microsoft/mxc-sdk": "0.7.0",
"@prismshadow/penguin-core": "workspace:*",
"tsup": "^8.3.0",
"vitest": "^3.2.6"
diff --git a/plugins/sandbox-wsl/setup/install-wsl.ps1 b/plugins/sandbox-wsl/setup/install-wsl.ps1
new file mode 100644
index 00000000..2a6d6c64
--- /dev/null
+++ b/plugins/sandbox-wsl/setup/install-wsl.ps1
@@ -0,0 +1,24 @@
+# Installs WSL for the PenguinHarness WSL sandbox. Runs ELEVATED, once: the harness raises the
+# Windows consent prompt for this script, or a person runs it from an administrator PowerShell.
+#
+# powershell -ExecutionPolicy Bypass -File install-wsl.ps1 -Log C:\path\install.log
+#
+# It installs the WSL package and the Windows features it needs, without a Linux distribution
+# (the harness imports its own). The output goes to <Log>.out as wsl.exe writes it, so the
+# harness can show its progress; the last line of <Log> is "PENGUIN-EXIT <code>".
+param([Parameter(Mandatory = $true)][string]$Log)
+$ErrorActionPreference = 'Continue'
+New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Log) | Out-Null
+Remove-Item -Force -ErrorAction SilentlyContinue "$Log.out", "$Log.err"
+"started $(Get-Date -Format o) as $([Security.Principal.WindowsIdentity]::GetCurrent().Name)" | Out-File -Encoding utf8 $Log
+$env:WSL_UTF8 = '1'
+$wsl = Join-Path $env:SystemRoot 'System32\wsl.exe'
+try {
+ $p = Start-Process -FilePath $wsl -ArgumentList '--install', '--no-distribution' -NoNewWindow -Wait -PassThru `
+ -RedirectStandardOutput "$Log.out" -RedirectStandardError "$Log.err"
+ $code = $p.ExitCode
+} catch {
+ "failed to start wsl.exe: $($_.Exception.Message)" | Out-File -Append -Encoding utf8 $Log
+ $code = -1
+}
+"PENGUIN-EXIT $code" | Out-File -Append -Encoding utf8 $Log
diff --git a/plugins/sandbox-wsl/src/host.ts b/plugins/sandbox-wsl/src/host.ts
new file mode 100644
index 00000000..781f45b5
--- /dev/null
+++ b/plugins/sandbox-wsl/src/host.ts
@@ -0,0 +1,188 @@
+/**
+ * The Windows side: running wsl.exe, what it says about this machine, and the file this backend
+ * keeps about the distro it set up.
+ *
+ * wsl.exe speaks UTF-16 by default; `WSL_UTF8=1` makes it write UTF-8, which is what every call
+ * here sets. Its notices (a localhost proxy it cannot mirror into NAT mode) arrive on stderr on
+ * every call and are dropped before anything reads the output.
+ */
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { isWslNotice } from "./profile.js";
+
+/** wsl.exe by its full path: a server started with a trimmed PATH still finds it. */
+export function wslExe(env: NodeJS.ProcessEnv = process.env): string {
+ return path.win32.join(env.SystemRoot ?? "C:\\Windows", "System32", "wsl.exe");
+}
+
+/** Where this backend keeps its state, its downloads and the distro's disk. */
+export function stateDir(env: NodeJS.ProcessEnv = process.env): string {
+ const local =
+ env.LOCALAPPDATA ??
+ path.win32.join(env.USERPROFILE ?? "C:\\Users\\Default", "AppData", "Local");
+ return path.win32.join(local, "penguin", "sandbox-wsl");
+}
+
+/** What a finished wsl.exe call said. */
+export interface WslResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+/** Drops WSL's own notices, and the NULs a UTF-16 answer leaves when read as UTF-8. */
+export function cleanOutput(text: string): string {
+ return text
+ .replace(/\0/g, "")
+ .split(/\r?\n/)
+ .filter((line) => !isWslNotice(line))
+ .join("\n")
+ .trim();
+}
+
+/** Runs wsl.exe to completion. `input` is written to its stdin; `onLine` sees stdout as it comes. */
+export function runWsl(
+ args: readonly string[],
+ opts: { timeoutMs?: number; input?: string; onLine?: (line: string) => void } = {},
+): Promise<WslResult> {
+ return new Promise((resolve) => {
+ const child = spawn(wslExe(), args, {
+ windowsHide: true,
+ env: { ...process.env, WSL_UTF8: "1" },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ let partial = "";
+ const timer =
+ opts.timeoutMs !== undefined ? setTimeout(() => child.kill(), opts.timeoutMs) : undefined;
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ if (opts.onLine === undefined) return;
+ partial += chunk;
+ const lines = partial.split(/\r?\n|\r/);
+ partial = lines.pop() ?? "";
+ for (const line of lines) if (line.trim() !== "") opts.onLine(line.replace(/\0/g, ""));
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ child.on("error", (err) => {
+ if (timer) clearTimeout(timer);
+ resolve({ code: -1, stdout: "", stderr: err.message });
+ });
+ child.on("close", (code) => {
+ if (timer) clearTimeout(timer);
+ resolve({ code: code ?? -1, stdout: cleanOutput(stdout), stderr: cleanOutput(stderr) });
+ });
+ child.stdin.end(opts.input ?? "");
+ });
+}
+
+/** What this machine has, as far as this backend is concerned. */
+export interface HostFacts {
+ /** `missing`: no working WSL (not installed, or installed and waiting for a restart). */
+ wsl: "missing" | "installed";
+ /** The version line wsl.exe reports, when it answers. */
+ version?: string;
+ /** What wsl.exe said when it did not work, for the card. */
+ problem?: string;
+ distros: string[];
+}
+
+/** The version number out of `wsl --version`'s first line, whatever language labels it. */
+export function versionOf(output: string): string {
+ const first = output.split("\n")[0]?.trim() ?? "";
+ return first.replace(/^[^::]*[::]\s*/, "");
+}
+
+/** Reads WSL's presence, its version and the distros it has. Never throws. */
+export async function readHost(): Promise<HostFacts> {
+ if (!fs.existsSync(wslExe())) {
+ return { wsl: "missing", problem: `${wslExe()} does not exist`, distros: [] };
+ }
+ const version = await runWsl(["--version"], { timeoutMs: 20_000 });
+ if (version.code !== 0) {
+ return {
+ wsl: "missing",
+ problem: (version.stdout || version.stderr).split("\n")[0] ?? "",
+ distros: [],
+ };
+ }
+ const list = await runWsl(["--list", "--quiet"], { timeoutMs: 20_000 });
+ const distros =
+ list.code === 0
+ ? list.stdout
+ .split("\n")
+ .map((l) => l.trim())
+ .filter((l) => l !== "")
+ : [];
+ return {
+ wsl: "installed",
+ version: versionOf(version.stdout),
+ distros,
+ };
+}
+
+/** What Initialize leaves behind: the distro it made and what it put in it. */
+export interface WslState {
+ distro: string;
+ user: string;
+ /** The Linux it was built from ("ubuntu" | "alpine"), and that image's version. */
+ base: string;
+ version: string;
+ packages: string[];
+ initializedAt: string;
+}
+
+export function stateFile(): string {
+ return path.win32.join(stateDir(), "state.json");
+}
+
+export function readState(): WslState | null {
+ try {
+ const doc = JSON.parse(fs.readFileSync(stateFile(), "utf8")) as Partial<WslState>;
+ if (typeof doc.distro !== "string" || typeof doc.user !== "string") return null;
+ return {
+ distro: doc.distro,
+ user: doc.user,
+ base: typeof doc.base === "string" ? doc.base : "alpine",
+ version: typeof doc.version === "string" ? doc.version : "",
+ packages: Array.isArray(doc.packages) ? doc.packages.map(String) : [],
+ initializedAt: typeof doc.initializedAt === "string" ? doc.initializedAt : "",
+ };
+ } catch {
+ return null;
+ }
+}
+
+export function writeState(state: WslState): void {
+ fs.mkdirSync(stateDir(), { recursive: true });
+ fs.writeFileSync(stateFile(), `${JSON.stringify(state, null, 2)}\n`);
+}
+
+export function removeState(): void {
+ fs.rmSync(stateFile(), { force: true });
+}
+
+/** The drive letters present on this machine, lowercase. */
+export function localDrives(exists: (p: string) => boolean = fs.existsSync): string[] {
+ const drives: string[] = [];
+ for (let c = 0x61; c <= 0x7a; c++) {
+ const letter = String.fromCharCode(c);
+ if (exists(`${letter}:\\`)) drives.push(letter);
+ }
+ return drives;
+}
+
+/** Whether a Windows path is a directory, a file, or nothing. */
+export function pathKind(p: string): "dir" | "file" | null {
+ try {
+ return fs.statSync(p).isDirectory() ? "dir" : "file";
+ } catch {
+ return null;
+ }
+}
diff --git a/plugins/sandbox-wsl/src/index.ts b/plugins/sandbox-wsl/src/index.ts
new file mode 100644
index 00000000..0fca1b13
--- /dev/null
+++ b/plugins/sandbox-wsl/src/index.ts
@@ -0,0 +1,148 @@
+/**
+ * @prismshadow/penguin-plugin-sandbox-wsl — a Windows sandbox backend that confines in a Linux
+ * distro: each agent command runs in a dedicated WSL2 distro, as an unprivileged account, under
+ * bubblewrap.
+ *
+ * A PLUGIN PACKAGE, not part of the platform: a Project asks for it on the Plugins page and the
+ * harness resolves it from the installation. It compiles against the
+ * `@prismshadow/penguin-core/plugin` surface and has no runtime dependency on the harness.
+ *
+ * fs-write → bwrap binds the Workspace (read-write or read-only) at its /mnt path; the
+ * distro is read-only and every other Windows drive is hidden
+ * network → `network: "none"` leaves the command in an empty network namespace
+ * mask-paths → a tmpfs over a directory, /dev/null over a file
+ *
+ * WHAT MAKES IT A SANDBOX. WSL's interop lets a Linux process start a Windows program, and that
+ * program is an ordinary host process: inside bwrap with the network cut, `cmd.exe` still wrote
+ * to the Windows disk and reached the internet (measured on Windows 11, WSL 2.7). The distro
+ * this backend sets up switches interop off in its /etc/wsl.conf, and `check` proves it stays
+ * off. It is also why the distro is its own and not the person's Ubuntu.
+ *
+ * WHAT IT COSTS. Commands run in Linux, not in Git Bash: Windows toolchains (node.exe, git.exe)
+ * cannot run confined, so the distro carries its own (the packages setting). A Windows path in
+ * a command means nothing there; the Workspace is at `/mnt/<drive>/…`.
+ *
+ * SETUP. Installing WSL needs an administrator once: `installWsl` raises Windows' own consent
+ * prompt for the script shipped in setup/. Everything after that runs as the harness's own
+ * user: `initialize` downloads the base rootfs (Ubuntu by default, Alpine as the small option),
+ * imports it, installs bubblewrap and the packages, and switches interop off, and `check` runs
+ * real commands through the sandbox. Each reports the step it is on while it runs. Until the
+ * distro exists, the backend declines to load and says so.
+ */
+import { fileURLToPath } from "node:url";
+import { Bind, Component } from "@prismshadow/penguin-core/plugin";
+import type {
+ ConfinedArgv,
+ Plugin,
+ SandboxPolicy,
+ SandboxProvider,
+ SandboxProviderSource,
+} from "@prismshadow/penguin-core/plugin";
+import { readHost, readState } from "./host.js";
+import { launchJob, wslSettingsOf } from "./tasks.js";
+import type { WslSettings } from "./tasks.js";
+
+export { bwrapArgs, chdirRoots, linuxProgram, toLinuxPath } from "./profile.js";
+export {
+ launchJob,
+ parseMinirootfs,
+ parseUbuntuSums,
+ provisionScript,
+ resolveRelease,
+ wslSettingsOf,
+} from "./tasks.js";
+export { Tasks, check, initialize, installWsl, remove } from "./tasks.js";
+export type { BaseImage, CheckLine, TaskKind, TaskOutcome } from "./tasks.js";
+export type { WslSettings } from "./tasks.js";
+
+/** Where the launcher lives, beside this module in the built package. */
+export function launcherPath(): string {
+ return fileURLToPath(new URL("./launch.js", import.meta.url));
+}
+
+/** Test seams. */
+export interface WslInternals {
+ platform?: NodeJS.Platform;
+ node?: string;
+ launcher?: string;
+}
+
+/** Why the backend cannot serve yet, or null when it can. */
+async function unavailable(settings: WslSettings): Promise<string | null> {
+ const state = readState();
+ if (state === null) {
+ return "the sandbox distro is not initialized";
+ }
+ if (state.distro !== settings.distro) {
+ return `the distro setting names ${settings.distro}, but ${state.distro} is the one initialized: initialize again`;
+ }
+ const host = await readHost();
+ if (host.wsl !== "installed")
+ return `WSL does not work on this machine: ${host.problem ?? "not installed"}`;
+ if (!host.distros.some((d) => d.toLowerCase() === state.distro.toLowerCase())) {
+ return `the distro ${state.distro} is gone from WSL: initialize again`;
+ }
+ return null;
+}
+
+/**
+ * Loads the backend: on Windows only (elsewhere it declines — another backend serves), and only
+ * once the distro exists. Until then it rejects with what is missing.
+ */
+export async function loadWslProvider(
+ settings: () => WslSettings,
+ internals: WslInternals = {},
+): Promise<SandboxProvider | null> {
+ if ((internals.platform ?? process.platform) !== "win32") return null;
+ const reason = await unavailable(settings());
+ if (reason !== null) throw new Error(reason);
+ return createWslProvider(settings, internals);
+}
+
+export function createWslProvider(
+ settings: () => WslSettings,
+ internals: WslInternals = {},
+): SandboxProvider {
+ const node = internals.node ?? process.execPath;
+ const launcher = internals.launcher ?? launcherPath();
+ return {
+ dimensions: ["fs-write", "network", "mask-paths"],
+ confine(argv, policy: SandboxPolicy): ConfinedArgv {
+ const state = readState();
+ if (state === null) {
+ throw new Error("penguin-wsl cannot confine: the sandbox distro is not initialized");
+ }
+ const job = launchJob(argv, policy, settings(), state);
+ return {
+ argv: [node, launcher, Buffer.from(JSON.stringify(job), "utf8").toString("base64")],
+ // In the desktop app `node` is the app's own binary, which runs a script only with this.
+ env: { ELECTRON_RUN_AS_NODE: "1" },
+ enforcement: "full",
+ denialSignatures: ["read-only file system", "permission denied", "operation not permitted"],
+ runnerFailureRules: [{ fatalSignatures: ["penguin-wsl:", "bwrap: ", "Wsl/"] }],
+ };
+ },
+ };
+}
+
+@Component({
+ contributes: {
+ "SandboxModule.providers": [
+ {
+ id: "sandbox-wsl.provider",
+ name: "penguin-wsl",
+ dimensions: ["fs-write", "network", "mask-paths"],
+ },
+ ],
+ },
+})
+export class SandboxWsl {
+ @Bind("sandbox-wsl.provider") provider!: SandboxProviderSource;
+
+ setup() {
+ this.provider = loadWslProvider(() => wslSettingsOf({}));
+ }
+}
+
+const plugin: Plugin = { modules: [SandboxWsl] };
+export default plugin;
diff --git a/plugins/sandbox-wsl/src/launch.ts b/plugins/sandbox-wsl/src/launch.ts
new file mode 100644
index 00000000..9732fc3b
--- /dev/null
+++ b/plugins/sandbox-wsl/src/launch.ts
@@ -0,0 +1,126 @@
+/**
+ * The launcher: one confined command, run inside the sandbox distro under bubblewrap.
+ *
+ * The provider could hand the harness a `wsl.exe …` argv directly, but two things need a
+ * process of their own. The command's working directory is only known at spawn, and it has to
+ * become a Linux path bwrap can `--chdir` into. And wsl.exe prints its own warnings on stderr
+ * before the command runs (a localhost proxy it cannot mirror, on every single call), which an
+ * agent would otherwise read as the command's output. So the harness runs
+ * `node launch.js <job>`, and this program runs wsl.exe with the same stdin and stdout, filters
+ * those lines out of the start of stderr, and exits with the command's code.
+ */
+import { spawn } from "node:child_process";
+import path from "node:path";
+import { isWslNotice, toLinuxPath, within } from "./profile.js";
+
+/** What the provider hands the launcher. */
+export interface LaunchJob {
+ wsl: string;
+ distro: string;
+ user: string;
+ /** The bwrap profile (see profile.ts). */
+ bwrap: string[];
+ /** Where a `--chdir` may point. */
+ chdirRoots: string[];
+ /** The command, already in its Linux spelling. */
+ command: string[];
+}
+
+/** The wsl.exe arguments for a job started in `cwd`. */
+export function wslArgs(job: LaunchJob, cwd: string): string[] {
+ const linuxCwd = toLinuxPath(cwd, job.distro);
+ const chdir =
+ linuxCwd !== null && within(linuxCwd, job.chdirRoots)
+ ? ["--chdir", linuxCwd]
+ : job.chdirRoots.length > 0 && job.chdirRoots[0] !== "/"
+ ? ["--chdir", job.chdirRoots[0]!]
+ : [];
+ return [
+ "-d",
+ job.distro,
+ "-u",
+ job.user,
+ // wsl.exe would otherwise translate this process's cwd itself, and warn when it cannot.
+ "--cd",
+ "/",
+ "--exec",
+ "/usr/bin/bwrap",
+ ...job.bwrap,
+ ...chdir,
+ "--",
+ ...job.command,
+ ];
+}
+
+/**
+ * Copies a stream to stderr, dropping WSL's own notices from its first lines. Only the start is
+ * inspected: wsl.exe prints them before the command runs, and holding back a command's partial
+ * line (a progress bar) for longer would delay what it writes.
+ */
+export function noticeFilter(write: (chunk: string) => void): {
+ push(chunk: string): void;
+ end(): void;
+} {
+ let pending = "";
+ let passthrough = false;
+ let lines = 0;
+ return {
+ push(chunk) {
+ if (passthrough) {
+ write(chunk);
+ return;
+ }
+ pending += chunk;
+ let newline = pending.indexOf("\n");
+ while (newline !== -1 && !passthrough) {
+ const line = pending.slice(0, newline + 1);
+ pending = pending.slice(newline + 1);
+ if (!isWslNotice(line.replace(/\r?\n$/, ""))) {
+ write(line);
+ lines++;
+ }
+ if (lines > 0 || pending.length > 4096) passthrough = true;
+ newline = pending.indexOf("\n");
+ }
+ if (passthrough && pending !== "") {
+ write(pending);
+ pending = "";
+ }
+ },
+ end() {
+ if (pending !== "" && !isWslNotice(pending)) write(pending);
+ pending = "";
+ },
+ };
+}
+
+function main(): void {
+ const encoded = process.argv[2];
+ if (encoded === undefined) {
+ process.stderr.write("penguin-wsl: the launcher was started without a job\n");
+ process.exit(126);
+ }
+ const job = JSON.parse(Buffer.from(encoded, "base64").toString("utf8")) as LaunchJob;
+ const child = spawn(job.wsl, wslArgs(job, process.cwd()), {
+ stdio: ["inherit", "inherit", "pipe"],
+ windowsHide: true,
+ env: { ...process.env, WSL_UTF8: "1" },
+ });
+ const filter = noticeFilter((chunk) => process.stderr.write(chunk));
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk: string) => filter.push(chunk));
+ child.stderr.on("end", () => filter.end());
+ child.on("error", (err) => {
+ process.stderr.write(`penguin-wsl: could not start ${job.wsl}: ${err.message}\n`);
+ process.exit(127);
+ });
+ child.on("exit", (code, signal) => {
+ process.exitCode = code ?? (signal !== null ? 128 : 1);
+ });
+ for (const signal of ["SIGINT", "SIGTERM", "SIGBREAK"] as const) {
+ process.on(signal, () => child.kill());
+ }
+}
+
+// Run only as the launcher, not when a test imports the helpers above.
+if (process.argv[1] !== undefined && path.basename(process.argv[1]).startsWith("launch")) main();
diff --git a/plugins/sandbox-wsl/src/profile.ts b/plugins/sandbox-wsl/src/profile.ts
new file mode 100644
index 00000000..6c782e21
--- /dev/null
+++ b/plugins/sandbox-wsl/src/profile.ts
@@ -0,0 +1,165 @@
+/**
+ * The pure half of the backend: how a Windows path is spelled inside the distro, which Linux
+ * program a Windows argv names, and the bubblewrap profile one policy becomes. No process is
+ * started here, so all of it is tested on any host.
+ *
+ * The profile, in order (bwrap applies mounts in order, and a later one shadows an earlier):
+ *
+ * --die-with-parent --unshare-all [--share-net] namespaces; the network only when allowed
+ * --ro-bind / / (--bind / / under full access) the distro itself
+ * --dev /dev --proc /proc
+ * --tmpfs /run WSL's interop sockets are not reachable
+ * --ro-bind-try /run/resolvconf/resolv.conf … … but name resolution still is (see below)
+ * [writable temp] --tmpfs /tmp
+ * [confining modes] --tmpfs /mnt every Windows drive hidden …
+ * [exposeWindowsDrives] --ro-bind /mnt/<d> … … or shown read-only
+ * [workspace] --bind | --ro-bind <ws> the Workspace, at its own /mnt path
+ * --ro-bind-try /mnt/wsl/resolv.conf … the file /etc/resolv.conf points at
+ * --remount-ro /mnt the covering tmpfs itself is read-only
+ * [mask-paths] --tmpfs <dir> | --ro-bind /dev/null <file>
+ *
+ * Why /mnt is hidden rather than left read-only: under WSL the whole Windows profile arrives at
+ * /mnt/c/Users/<name>, credentials and browser data included. A policy that says "write the
+ * Workspace" never meant "read the rest of the person's disk", and on Linux the equivalent
+ * files belong to the host, not to a mount the distro adds. The setting that shows them
+ * read-only exists for a toolchain that has to read something outside the Workspace.
+ *
+ * Why the tmpfs is remounted read-only: a tmpfs is writable, and bwrap creates the Workspace's
+ * parent directories inside it. A write to `/mnt/c/Users/anything` therefore SUCCEEDED, in a
+ * file that existed only for that one command and never reached Windows — a denial reported as
+ * success, which is worse than a denial. Remounting after the binds makes the covering mount
+ * refuse writes (EROFS) while the Workspace bound under it stays writable.
+ *
+ * Why resolv.conf is bound back: WSL keeps the generated one outside the distro's own root
+ * (/mnt/wsl/resolv.conf, or /run/resolvconf/resolv.conf), and /etc/resolv.conf is a symlink to
+ * it. Covering /mnt and /run therefore took DNS away — every name failed to resolve while the
+ * network itself was reachable. The two candidates are bound back read-only; `-try` because a
+ * distro uses one of them, not both.
+ */
+import path from "node:path";
+import type { SandboxPolicy } from "@prismshadow/penguin-core/plugin";
+
+/** Where WSL mounts the Windows drives inside a distro (its default automount root). */
+export const MOUNT_ROOT = "/mnt";
+
+/** The generated resolv.conf, bound back through the tmpfs that would otherwise hide it. */
+export const RESOLV_MNT = ["--ro-bind-try", "/mnt/wsl/resolv.conf", "/mnt/wsl/resolv.conf"];
+export const RESOLV_RUN = [
+ "--ro-bind-try",
+ "/run/resolvconf/resolv.conf",
+ "/run/resolvconf/resolv.conf",
+];
+
+/**
+ * A Windows path as the distro sees it: `C:\Users\k\ws` → `/mnt/c/Users/k/ws`, and a path into
+ * this distro's own filesystem (`\\wsl.localhost\<distro>\home\x`) → `/home/x`. Null for what
+ * has no spelling in the distro: a relative path, another distro's files, a network share.
+ */
+export function toLinuxPath(windowsPath: string, distro?: string): string | null {
+ const p = windowsPath.trim();
+ if (p.startsWith("/")) return path.posix.normalize(p);
+ const drive = /^([A-Za-z]):(?:[\\/](.*))?$/.exec(p);
+ if (drive) {
+ const rest = (drive[2] ?? "").split(/[\\/]+/).filter((s) => s !== "");
+ return [`${MOUNT_ROOT}/${drive[1]!.toLowerCase()}`, ...rest].join("/");
+ }
+ const unc =
+ /^[\\/]{2}(?:\?[\\/]UNC[\\/])?(wsl\.localhost|wsl\$)[\\/]([^\\/]+)(?:[\\/](.*))?$/i.exec(p);
+ if (unc && distro !== undefined && unc[2]!.toLowerCase() === distro.toLowerCase()) {
+ const rest = (unc[3] ?? "").split(/[\\/]+/).filter((s) => s !== "");
+ return `/${rest.join("/")}`;
+ }
+ return null;
+}
+
+/**
+ * The Linux program a Windows argv's first element means. The harness resolves its shell on
+ * Windows as `bash` (Git Bash on PATH) or a full path to `bash.exe`; inside the distro that is
+ * the distro's own bash. Anything else is looked up by its bare name on the distro's PATH —
+ * a Windows program cannot run there at all, since interop is off.
+ */
+export function linuxProgram(command: string): string {
+ const base = path.win32.basename(command).replace(/\.exe$/i, "");
+ const lower = base.toLowerCase();
+ if (lower === "bash") return "/bin/bash";
+ if (lower === "sh") return "/bin/sh";
+ return base;
+}
+
+/** What the profile needs to know about the host besides the policy. */
+export interface ProfileHost {
+ /** The distro's name, for a Workspace inside its own filesystem. */
+ distro: string;
+ /** Show every Windows drive read-only instead of hiding them. */
+ exposeWindowsDrives: boolean;
+ /** The drive letters that exist on this machine (lowercase), for exposing them. */
+ drives: readonly string[];
+ /** Whether a Windows path is a directory, a file, or nothing (a mask on nothing is skipped). */
+ kind: (windowsPath: string) => "dir" | "file" | null;
+}
+
+/** The bubblewrap arguments for one policy: everything before `--` and the command. */
+export function bwrapArgs(policy: SandboxPolicy, host: ProfileHost): string[] {
+ const full = policy.mode === "danger-full-access";
+ if (policy.network === "local") {
+ // bwrap's empty network namespace also loses the host's loopback, so "localhost only" has
+ // no spelling here. The service never routes it here (no network-local dimension); refuse
+ // rather than read it as an open network.
+ throw new Error("penguin-wsl cannot confine to the local network (localhost only)");
+ }
+ const args = ["--die-with-parent", "--unshare-all"];
+ if (policy.network !== "none") args.push("--share-net");
+ args.push(full ? "--bind" : "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc");
+ args.push("--tmpfs", "/run", ...RESOLV_RUN);
+ if (policy.writableTemp === true) args.push("--tmpfs", "/tmp");
+ if (!full) {
+ const workspace = toLinuxPath(policy.workspaceRoot, host.distro);
+ if (workspace === null) {
+ throw new Error(
+ `penguin-wsl: the Workspace ${policy.workspaceRoot} has no path inside the WSL distro ` +
+ "(it must be on a local drive), so it cannot be confined there.",
+ );
+ }
+ args.push("--tmpfs", MOUNT_ROOT);
+ if (host.exposeWindowsDrives) {
+ for (const d of host.drives)
+ args.push("--ro-bind", `${MOUNT_ROOT}/${d}`, `${MOUNT_ROOT}/${d}`);
+ }
+ args.push(policy.mode === "workspace-write" ? "--bind" : "--ro-bind", workspace, workspace);
+ // Last over /mnt, and only now: the bind above needs a writable tmpfs to create its
+ // mountpoint in, and the remount is what stops a write outside the Workspace from
+ // "succeeding" into a tmpfs nobody ever reads.
+ args.push(...RESOLV_MNT, "--remount-ro", MOUNT_ROOT);
+ }
+ for (const target of policy.maskPaths ?? []) {
+ const kind = host.kind(target);
+ const linux = toLinuxPath(target, host.distro);
+ if (kind === null || linux === null) continue;
+ if (kind === "dir") args.push("--tmpfs", linux);
+ else args.push("--ro-bind", "/dev/null", linux);
+ }
+ return args;
+}
+
+/**
+ * The directories a confined command may start in: a cwd outside every one of them does not
+ * exist inside the sandbox, and bwrap refuses a `--chdir` there.
+ */
+export function chdirRoots(policy: SandboxPolicy, host: ProfileHost): string[] {
+ if (policy.mode === "danger-full-access") return ["/"];
+ if (host.exposeWindowsDrives) return host.drives.map((d) => `${MOUNT_ROOT}/${d}`);
+ const workspace = toLinuxPath(policy.workspaceRoot, host.distro);
+ return workspace === null ? [] : [workspace];
+}
+
+/** Whether a Linux path is one of the roots or inside one. */
+export function within(linuxPath: string, roots: readonly string[]): boolean {
+ return roots.some(
+ (root) => root === "/" || linuxPath === root || linuxPath.startsWith(`${root}/`),
+ );
+}
+
+/** A line WSL itself writes to stderr before the command runs, which is not the command's. */
+export function isWslNotice(line: string): boolean {
+ return /^wsl: /i.test(line) && /(proxy|localhost|代理)/i.test(line);
+}
diff --git a/plugins/sandbox-wsl/src/tasks.ts b/plugins/sandbox-wsl/src/tasks.ts
new file mode 100644
index 00000000..025933a2
--- /dev/null
+++ b/plugins/sandbox-wsl/src/tasks.ts
@@ -0,0 +1,854 @@
+/**
+ * What the card's buttons do: install WSL (elevated, once), initialize the sandbox distro, check
+ * that it confines, and remove it. Each runs in the background and reports the step it is on;
+ * the card shows that as a progress notice and reads it again until the task ends.
+ */
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { SandboxPolicy } from "@prismshadow/penguin-core/plugin";
+import {
+ localDrives,
+ pathKind,
+ readHost,
+ readState,
+ removeState,
+ runWsl,
+ stateDir,
+ wslExe,
+ writeState,
+} from "./host.js";
+import type { HostFacts, WslState } from "./host.js";
+import { wslArgs } from "./launch.js";
+import type { LaunchJob } from "./launch.js";
+import { bwrapArgs, chdirRoots, linuxProgram, toLinuxPath } from "./profile.js";
+
+/** The Linux the distro is built from. */
+export type BaseImage = "ubuntu" | "alpine";
+
+/** This backend's settings, as it reads them from its group. */
+export interface WslSettings {
+ distro: string;
+ base: BaseImage;
+ exposeWindowsDrives: boolean;
+ /** A package mirror for the chosen base, or "" for its official one. */
+ mirror: string;
+ packages: string[];
+}
+
+export const DEFAULT_DISTRO = "penguin-sandbox";
+/**
+ * Ubuntu by default, not Alpine. Alpine's rootfs is a tenth of the size, but it is musl: a
+ * prebuilt native npm module, a pip wheel or a downloaded binary that works everywhere else
+ * does not run on it, and what a person finds when they search for the error is glibc advice.
+ * The sandbox is where an agent's commands live, so it has to be the ordinary Linux.
+ */
+export const DEFAULT_BASE: BaseImage = "ubuntu";
+/** The Ubuntu LTS series the base rootfs comes from. */
+export const UBUNTU_SERIES = "24.04";
+/** Where each base's official images and packages come from. */
+export const UBUNTU_IMAGES = "https://cdimage.ubuntu.com/ubuntu-base/releases";
+export const UBUNTU_ARCHIVE = "http://archive.ubuntu.com/ubuntu";
+export const UBUNTU_SECURITY = "http://security.ubuntu.com/ubuntu";
+export const ALPINE_MIRROR = "https://dl-cdn.alpinelinux.org/alpine";
+export const DEFAULT_PACKAGES = ["git", "curl"];
+/** The account commands run as inside the distro: not root, so bwrap is the only way up. */
+export const SANDBOX_USER = "penguin";
+
+/** Its group's stored document as settings; anything unusable falls back to the default. */
+export function wslSettingsOf(doc: Record<string, unknown>): WslSettings {
+ const distro = typeof doc.distro === "string" ? doc.distro.trim() : "";
+ const mirror = typeof doc.mirror === "string" ? doc.mirror.trim() : "";
+ const packages = Array.isArray(doc.packages)
+ ? doc.packages.map((p) => String(p).trim()).filter((p) => /^[a-z0-9][a-z0-9._+-]*$/.test(p))
+ : DEFAULT_PACKAGES;
+ return {
+ distro: /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(distro) ? distro : DEFAULT_DISTRO,
+ base: doc.base === "alpine" ? "alpine" : DEFAULT_BASE,
+ exposeWindowsDrives: doc.exposeWindowsDrives === true,
+ mirror: /^https?:\/\//.test(mirror) ? mirror.replace(/\/+$/, "") : "",
+ packages,
+ };
+}
+
+/** The launcher job for one command under one policy — what the provider and the check share. */
+export function launchJob(
+ argv: readonly string[],
+ policy: SandboxPolicy,
+ settings: WslSettings,
+ state: WslState,
+): LaunchJob {
+ const host = {
+ distro: state.distro,
+ exposeWindowsDrives: settings.exposeWindowsDrives,
+ drives: localDrives(),
+ kind: pathKind,
+ };
+ return {
+ wsl: wslExe(),
+ distro: state.distro,
+ user: state.user,
+ bwrap: bwrapArgs(policy, host),
+ chdirRoots: chdirRoots(policy, host),
+ command: [linuxProgram(argv[0] ?? "bash"), ...argv.slice(1)],
+ };
+}
+
+/** Two languages for everything the card says. */
+export interface Text {
+ en: string;
+ zh: string;
+}
+
+export type TaskKind = "install" | "initialize" | "check" | "remove";
+
+export const TASK_TITLES: Record<TaskKind, Text> = {
+ install: { en: "Installing WSL", zh: "正在安装 WSL" },
+ initialize: { en: "Initializing the sandbox distro", zh: "正在初始化沙盒发行版" },
+ check: { en: "Checking confinement", zh: "正在检查隔离效果" },
+ remove: { en: "Removing the sandbox distro", zh: "正在移除沙盒发行版" },
+};
+
+/** One line of the confinement check. `ok: null` is information, not a verdict. */
+export interface CheckLine {
+ name: Text;
+ ok: boolean | null;
+ detail: string;
+}
+
+export interface TaskOutcome {
+ kind: TaskKind;
+ ok: boolean;
+ message: Text;
+ at: number;
+ /** Set by an install whose features only take effect after a restart. */
+ restart?: boolean;
+}
+
+/** Everything the card reads, kept for the life of the plugin's module. */
+export class Tasks {
+ running: { kind: TaskKind; step: Text; startedAt: number } | null = null;
+ last: TaskOutcome | null = null;
+ lastCheck: { at: number; lines: CheckLine[] } | null = null;
+ host: HostFacts | null = null;
+ private hostRead: Promise<void> | null = null;
+ private hostReadAt = 0;
+
+ /** Reads the machine again; concurrent callers share one read. */
+ refreshHost(): Promise<void> {
+ if (this.hostRead !== null) return this.hostRead;
+ this.hostRead = readHost()
+ .then((facts) => {
+ this.host = facts;
+ })
+ .finally(() => {
+ this.hostRead = null;
+ this.hostReadAt = Date.now();
+ });
+ return this.hostRead;
+ }
+
+ /** A stale reading is refreshed in the background; the card shows what it has meanwhile. */
+ touchHost(maxAgeMs = 15_000): void {
+ if (this.running === null && Date.now() - this.hostReadAt > maxAgeMs) void this.refreshHost();
+ }
+
+ /** Starts a task unless one runs; resolves when it ends, having recorded its outcome. */
+ start(
+ kind: TaskKind,
+ body: (report: (step: Text) => void) => Promise<Omit<TaskOutcome, "kind" | "at">>,
+ ): Promise<void> | null {
+ if (this.running !== null) return null;
+ const task = { kind, step: { en: "starting…", zh: "开始…" }, startedAt: Date.now() };
+ this.running = task;
+ const report = (step: Text) => {
+ task.step = step;
+ };
+ return body(report)
+ .catch((err: unknown) => {
+ const text = err instanceof Error ? err.message : String(err);
+ return { ok: false, message: { en: text, zh: text } };
+ })
+ .then(async (outcome) => {
+ this.last = { kind, at: Date.now(), ...outcome };
+ await this.refreshHost();
+ this.running = null;
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Install WSL — the one step that needs an administrator.
+// ---------------------------------------------------------------------------------------------
+
+function installScript(): string {
+ return fileURLToPath(new URL("../setup/install-wsl.ps1", import.meta.url));
+}
+
+function powershell(env: NodeJS.ProcessEnv = process.env): string {
+ return path.win32.join(
+ env.SystemRoot ?? "C:\\Windows",
+ "System32",
+ "WindowsPowerShell",
+ "v1.0",
+ "powershell.exe",
+ );
+}
+
+/** The command that raises the consent prompt for the install script (each argument quoted once). */
+export function elevationCommand(script: string, log: string): string {
+ const args = ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, "-Log", log]
+ .map((arg) => `'${arg.replace(/'/g, "''")}'`)
+ .join(",");
+ return (
+ `$ErrorActionPreference='Stop'; ` +
+ `Start-Process -FilePath 'powershell.exe' -Verb RunAs -WindowStyle Hidden -ArgumentList @(${args})`
+ );
+}
+
+function readText(file: string): string {
+ try {
+ return fs
+ .readFileSync(file, "utf8")
+ .replace(/^\uFEFF/, "")
+ .replace(/\0/g, "");
+ } catch {
+ return "";
+ }
+}
+
+/** The last thing a progress-writing program printed: its last non-empty line or `\r` segment. */
+export function lastSegment(text: string): string {
+ const parts = text.split(/[\r\n]+/).map((s) => s.trim());
+ for (let i = parts.length - 1; i >= 0; i--) if (parts[i] !== "") return parts[i]!;
+ return "";
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export async function installWsl(
+ report: (step: Text) => void,
+): Promise<Omit<TaskOutcome, "kind" | "at">> {
+ const script = installScript();
+ if (!fs.existsSync(script)) {
+ const text = `the install script is missing from this installation (${script})`;
+ return { ok: false, message: { en: text, zh: `本次安装缺少脚本(${script})` } };
+ }
+ const log = path.win32.join(stateDir(), "install.log");
+ fs.mkdirSync(stateDir(), { recursive: true });
+ for (const f of [log, `${log}.out`, `${log}.err`]) fs.rmSync(f, { force: true });
+ // Not detached: ShellExecute's RunAs verb raises no prompt from a process without a console
+ // (measured on Windows 11 by the account backend). `unref` keeps the server free of it.
+ let failure = "";
+ const child = spawn(powershell(), ["-NoProfile", "-Command", elevationCommand(script, log)], {
+ stdio: "ignore",
+ windowsHide: true,
+ });
+ child.on("error", (err) => {
+ failure = err.message;
+ });
+ child.on("exit", (code) => {
+ if (code !== 0 && code !== null) failure = `the permission request exited ${code}`;
+ });
+ child.unref();
+ report({
+ en: "waiting for you to accept the Windows permission prompt on this machine's screen",
+ zh: "等待你在这台机器的屏幕上确认 Windows 授权弹窗",
+ });
+ const started = Date.now();
+ let exit: number | null = null;
+ while (exit === null) {
+ await sleep(1000);
+ if (failure !== "") {
+ return {
+ ok: false,
+ message: {
+ en: `No prompt was shown: ${failure}. Run ${script} -Log <file> from an administrator PowerShell instead.`,
+ zh: `没有弹出授权窗口:${failure}。请改为在管理员 PowerShell 中运行 ${script} -Log <文件>。`,
+ },
+ };
+ }
+ const text = readText(log);
+ if (text === "") {
+ if (Date.now() - started > 5 * 60_000) {
+ return {
+ ok: false,
+ message: {
+ en: "Nobody accepted the Windows permission prompt within five minutes, so WSL was not installed.",
+ zh: "五分钟内没有人确认 Windows 授权弹窗,WSL 未安装。",
+ },
+ };
+ }
+ continue;
+ }
+ const done = /PENGUIN-EXIT (-?\d+)/.exec(text);
+ if (done) {
+ exit = Number(done[1]);
+ break;
+ }
+ const tail = lastSegment(readText(`${log}.out`)) || lastSegment(readText(`${log}.err`));
+ report({
+ en: tail === "" ? "wsl --install is running" : `wsl --install: ${tail}`,
+ zh: tail === "" ? "wsl --install 正在运行" : `wsl --install:${tail}`,
+ });
+ if (Date.now() - started > 60 * 60_000) {
+ return {
+ ok: false,
+ message: {
+ en: "wsl --install ran for an hour without finishing.",
+ zh: "wsl --install 运行一小时仍未结束。",
+ },
+ };
+ }
+ }
+ const output = `${readText(`${log}.out`)}\n${readText(`${log}.err`)}`;
+ report({ en: "reading what the install left", zh: "读取安装结果" });
+ const host = await readHost();
+ const restart = exit === 3010 || /restart|reboot|重新启动|重启/i.test(output);
+ if (exit === 0 || exit === 3010) {
+ if (host.wsl === "installed" && !restart) {
+ return {
+ ok: true,
+ message: {
+ en: `WSL is installed (${host.version ?? ""}). Initialize the sandbox distro next.`,
+ zh: `WSL 已安装(${host.version ?? ""})。下一步初始化沙盒发行版。`,
+ },
+ };
+ }
+ return {
+ ok: true,
+ restart: true,
+ message: {
+ en: "WSL is installed. Restart Windows to finish, then come back and initialize the sandbox distro.",
+ zh: "WSL 已安装。重启 Windows 完成安装后,回到这里初始化沙盒发行版。",
+ },
+ };
+ }
+ const reason = lastSegment(output) || `exit code ${exit}`;
+ return {
+ ok: false,
+ message: { en: `wsl --install failed: ${reason}`, zh: `wsl --install 失败:${reason}` },
+ };
+}
+
+// ---------------------------------------------------------------------------------------------
+// Initialize — unelevated: download Alpine, import it, provision it.
+// ---------------------------------------------------------------------------------------------
+
+/** The rootfs one base offers: where to get it, what it should hash to, and its version. */
+export interface BaseRelease {
+ version: string;
+ file: string;
+ url: string;
+ sha256: string;
+ size: number;
+}
+
+/** The minirootfs entry of an Alpine latest-releases.yaml (a list of flat maps). */
+export function parseMinirootfs(yaml: string): Omit<BaseRelease, "url"> | null {
+ for (const block of yaml.split(/^-\s*$/m)) {
+ const field = (key: string) => new RegExp(`^\\s*${key}:\\s*(.+?)\\s*$`, "m").exec(block)?.[1];
+ if (field("flavor") !== "alpine-minirootfs") continue;
+ const file = field("file");
+ const sha256 = field("sha256");
+ if (file === undefined || sha256 === undefined) continue;
+ return {
+ version: field("version") ?? "",
+ file,
+ sha256: sha256.toLowerCase(),
+ size: Number(field("size") ?? 0),
+ };
+ }
+ return null;
+}
+
+/**
+ * The newest ubuntu-base tarball for one architecture, out of the release directory's
+ * SHA256SUMS — which is both the listing and the checksum, so one fetch answers both.
+ */
+export function parseUbuntuSums(
+ sums: string,
+ arch: string,
+): Omit<BaseRelease, "url" | "size"> | null {
+ const pattern = new RegExp(
+ `^([0-9a-f]{64}) \\*?(ubuntu-base-([0-9.]+)-base-${arch}\\.tar\\.gz)$`,
+ );
+ let best: Omit<BaseRelease, "url" | "size"> | null = null;
+ const order = (v: string) => v.split(".").map(Number);
+ for (const line of sums.split(/\r?\n/)) {
+ const m = pattern.exec(line.trim());
+ if (m === null) continue;
+ const candidate = { sha256: m[1]!.toLowerCase(), file: m[2]!, version: m[3]! };
+ if (best === null) best = candidate;
+ else {
+ const [a, b] = [order(candidate.version), order(best.version)];
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ if ((a[i] ?? 0) === (b[i] ?? 0)) continue;
+ if ((a[i] ?? 0) > (b[i] ?? 0)) best = candidate;
+ break;
+ }
+ }
+ }
+ return best;
+}
+
+/** Asks the chosen base where its rootfs is. Rejects with what to tell the person. */
+export async function resolveRelease(
+ base: BaseImage,
+ fetchImpl: typeof fetch,
+ arch: string = process.arch,
+): Promise<BaseRelease> {
+ if (base === "ubuntu") {
+ const dir = `${UBUNTU_IMAGES}/${UBUNTU_SERIES}/release`;
+ const res = await fetchImpl(`${dir}/SHA256SUMS`);
+ if (!res.ok)
+ throw new Error(`could not read Ubuntu's checksums (HTTP ${res.status} from ${dir})`);
+ const release = parseUbuntuSums(await res.text(), arch === "arm64" ? "arm64" : "amd64");
+ if (release === null)
+ throw new Error(`Ubuntu ${UBUNTU_SERIES} publishes no base rootfs for this architecture`);
+ return { ...release, url: `${dir}/${release.file}`, size: 0 };
+ }
+ const dir = `${ALPINE_MIRROR}/latest-stable/releases/${arch === "arm64" ? "aarch64" : "x86_64"}`;
+ const res = await fetchImpl(`${dir}/latest-releases.yaml`);
+ if (!res.ok)
+ throw new Error(`could not read Alpine's release list (HTTP ${res.status} from ${dir})`);
+ const release = parseMinirootfs(await res.text());
+ if (release === null) throw new Error("Alpine's release list names no minirootfs");
+ return { ...release, url: `${dir}/${release.file}` };
+}
+
+/** How a base is named on the card. */
+export const BASE_TITLES: Record<BaseImage, string> = { ubuntu: "Ubuntu", alpine: "Alpine" };
+
+/** The provisioning script, run as root inside the distro with sh reading it from stdin. */
+export function provisionScript(
+ base: BaseImage,
+ mirror: string,
+ packages: readonly string[],
+): string {
+ const wslConf = [
+ // Interop off is what makes the sandbox a sandbox: with it on, any Windows program started
+ // inside bwrap runs as an ordinary host process, outside every namespace (measured).
+ "cat > /etc/wsl.conf <<'EOF'",
+ "[interop]",
+ "enabled=false",
+ "appendWindowsPath=false",
+ "[user]",
+ `default=${SANDBOX_USER}`,
+ "EOF",
+ ];
+ if (base === "ubuntu") {
+ const pkgs = ["bubblewrap", "ca-certificates", ...packages].filter(
+ (p, i, all) => all.indexOf(p) === i,
+ );
+ return [
+ "set -e",
+ ...wslConf,
+ "export DEBIAN_FRONTEND=noninteractive",
+ ...(mirror === ""
+ ? []
+ : [
+ // Both archives, since a mirror that carries one carries the other.
+ `sed -i 's|${UBUNTU_ARCHIVE}/*|${mirror}/|; s|${UBUNTU_SECURITY}/*|${mirror}/|' /etc/apt/sources.list.d/ubuntu.sources`,
+ ]),
+ 'echo "apt-get update"',
+ "apt-get update",
+ `echo "apt-get install ${pkgs.join(" ")}"`,
+ `apt-get install -y --no-install-recommends ${pkgs.join(" ")}`,
+ // Recommends are off, so the account tools are named rather than assumed.
+ `id ${SANDBOX_USER} >/dev/null 2>&1 || useradd -m -s /bin/bash ${SANDBOX_USER}`,
+ "bwrap --version",
+ "echo PENGUIN-PROVISIONED",
+ "",
+ ].join("\n");
+ }
+ const pkgs = ["bubblewrap", "bash", ...packages].filter((p, i, all) => all.indexOf(p) === i);
+ const repo = mirror === "" ? ALPINE_MIRROR : mirror;
+ return [
+ "set -e",
+ ...wslConf,
+ "ver=$(cut -d. -f1,2 /etc/alpine-release)",
+ `printf '%s/v%s/main\\n%s/v%s/community\\n' '${repo}' "$ver" '${repo}' "$ver" > /etc/apk/repositories`,
+ 'echo "apk update"',
+ "apk update",
+ `echo "apk add ${pkgs.join(" ")}"`,
+ `apk add --no-progress ${pkgs.join(" ")}`,
+ `id ${SANDBOX_USER} >/dev/null 2>&1 || adduser -D -s /bin/bash ${SANDBOX_USER}`,
+ "bwrap --version",
+ "echo PENGUIN-PROVISIONED",
+ "",
+ ].join("\n");
+}
+
+export async function initialize(
+ settings: WslSettings,
+ report: (step: Text) => void,
+ fetchImpl: typeof fetch = fetch,
+): Promise<Omit<TaskOutcome, "kind" | "at">> {
+ const fail = (en: string, zh: string) => ({ ok: false, message: { en, zh } });
+ const baseName = BASE_TITLES[settings.base];
+ report({ en: "checking WSL", zh: "检查 WSL" });
+ const host = await readHost();
+ if (host.wsl !== "installed") {
+ return fail(
+ `WSL does not work on this machine yet (${host.problem ?? "not installed"}): install it first.`,
+ `这台机器上的 WSL 还不可用(${host.problem ?? "未安装"}):请先安装。`,
+ );
+ }
+ const distro = settings.distro;
+ const previous = readState();
+ let version =
+ previous?.distro === distro && previous.base === settings.base ? previous.version : "";
+ const exists = host.distros.some((d) => d.toLowerCase() === distro.toLowerCase());
+ if (exists) {
+ // A distro already there is provisioned in place — with the package manager IT has, which
+ // is not necessarily the one the setting now names. Asking it beats running apt in an
+ // Alpine and reporting "apt-get: not found".
+ report({ en: "reading what the existing distro is", zh: "读取现有发行版的类型" });
+ const os = await runWsl(
+ [
+ "-d",
+ distro,
+ "-u",
+ "root",
+ "--cd",
+ "/",
+ "--exec",
+ "/bin/sh",
+ "-c",
+ ". /etc/os-release; echo id=$ID",
+ ],
+ { timeoutMs: 60_000 },
+ );
+ const id = /id=(\w+)/.exec(os.stdout)?.[1] ?? "";
+ if (id !== "" && id !== settings.base) {
+ return fail(
+ `${distro} already exists and is ${BASE_TITLES[id === "alpine" ? "alpine" : "ubuntu"]}, not ${baseName}. Remove it first, or set the base Linux back to what it is.`,
+ `${distro} 已存在,且是 ${BASE_TITLES[id === "alpine" ? "alpine" : "ubuntu"]} 而非 ${baseName}。请先移除它,或把「基础 Linux」改回它本来的类型。`,
+ );
+ }
+ }
+ if (!exists) {
+ report({ en: `asking ${baseName} for its base image`, zh: `查询 ${baseName} 的基础镜像` });
+ let release;
+ try {
+ release = await resolveRelease(settings.base, fetchImpl);
+ } catch (err) {
+ const why = err instanceof Error ? err.message : String(err);
+ return fail(`${why}.`, `${why}。`);
+ }
+ version = release.version;
+ const rootfsDir = path.win32.join(stateDir(), "rootfs");
+ fs.mkdirSync(rootfsDir, { recursive: true });
+ const tarball = path.win32.join(rootfsDir, release.file);
+ const sha = (file: string) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
+ if (!fs.existsSync(tarball) || sha(tarball) !== release.sha256) {
+ const res = await fetchImpl(release.url);
+ if (!res.ok || res.body === null) {
+ return fail(
+ `downloading ${release.file} failed: HTTP ${res.status}`,
+ `下载 ${release.file} 失败:HTTP ${res.status}`,
+ );
+ }
+ const total = release.size || Number(res.headers.get("content-length") ?? 0);
+ const chunks: Buffer[] = [];
+ let got = 0;
+ for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
+ chunks.push(Buffer.from(chunk));
+ got += chunk.byteLength;
+ const pct = total > 0 ? ` ${Math.floor((got / total) * 100)}%` : "";
+ report({
+ en: `downloading ${baseName} ${release.version} (${(got / 1048576).toFixed(1)} MB${pct})`,
+ zh: `下载 ${baseName} ${release.version}(${(got / 1048576).toFixed(1)} MB${pct})`,
+ });
+ }
+ fs.writeFileSync(`${tarball}.part`, Buffer.concat(chunks));
+ fs.renameSync(`${tarball}.part`, tarball);
+ if (sha(tarball) !== release.sha256) {
+ fs.rmSync(tarball, { force: true });
+ return fail(
+ `${release.file} does not match its published sha256`,
+ `${release.file} 与发布的 sha256 不符`,
+ );
+ }
+ }
+ report({ en: `importing ${distro} into WSL`, zh: `导入 ${distro} 到 WSL` });
+ const disk = path.win32.join(stateDir(), "distros", distro);
+ fs.mkdirSync(disk, { recursive: true });
+ const imported = await runWsl(["--import", distro, disk, tarball, "--version", "2"], {
+ timeoutMs: 10 * 60_000,
+ });
+ if (imported.code !== 0) {
+ const why = imported.stdout || imported.stderr || `exit ${imported.code}`;
+ return fail(`wsl --import failed: ${why}`, `wsl --import 失败:${why}`);
+ }
+ }
+ report({
+ en: "installing bubblewrap and tools inside the distro",
+ zh: "在发行版内安装 bubblewrap 与工具",
+ });
+ let lastLine = "";
+ const provisioned = await runWsl(
+ ["-d", distro, "-u", "root", "--cd", "/", "--exec", "/bin/sh", "-s"],
+ {
+ timeoutMs: 20 * 60_000,
+ input: provisionScript(settings.base, settings.mirror, settings.packages),
+ onLine: (line) => {
+ lastLine = line.trim();
+ report({ en: `inside the distro: ${lastLine}`, zh: `发行版内:${lastLine}` });
+ },
+ },
+ );
+ if (provisioned.code !== 0 || !provisioned.stdout.includes("PENGUIN-PROVISIONED")) {
+ const why = provisioned.stderr || lastLine || `exit ${provisioned.code}`;
+ return fail(
+ `provisioning ${distro} failed: ${why}. If packages could not be downloaded, set a reachable mirror.`,
+ `配置 ${distro} 失败:${why}。如果是软件包下载失败,请设置一个可访问的镜像。`,
+ );
+ }
+ report({
+ en: "restarting the distro so interop stays off",
+ zh: "重启发行版,使 interop 关闭生效",
+ });
+ await runWsl(["--terminate", distro], { timeoutMs: 60_000 });
+ const state: WslState = {
+ distro,
+ user: SANDBOX_USER,
+ base: settings.base,
+ version,
+ packages: settings.packages,
+ initializedAt: new Date().toISOString(),
+ };
+ writeState(state);
+ return {
+ ok: true,
+ message: {
+ en: `The sandbox distro ${distro} (${baseName} ${version}) is ready: agent commands now run inside it under bubblewrap. Run the check to see what it confines.`,
+ zh: `沙盒发行版 ${distro}(${baseName} ${version})已就绪:Agent 的命令现在在其中通过 bubblewrap 执行。运行检查可查看隔离效果。`,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------------------------
+// Check — runs real commands through the same profile the provider builds.
+// ---------------------------------------------------------------------------------------------
+
+export async function check(
+ settings: WslSettings,
+ report: (step: Text) => void,
+): Promise<{ result: Omit<TaskOutcome, "kind" | "at">; lines: CheckLine[] }> {
+ const state = readState();
+ if (state === null) {
+ const text = { en: "The sandbox distro is not initialized yet.", zh: "沙盒发行版尚未初始化。" };
+ return { result: { ok: false, message: text }, lines: [] };
+ }
+ const root = path.win32.join(stateDir(), "check");
+ const ws = path.win32.join(root, "workspace");
+ const outside = path.win32.join(root, "outside");
+ const masked = path.win32.join(ws, "masked");
+ fs.rmSync(root, { recursive: true, force: true });
+ fs.mkdirSync(masked, { recursive: true });
+ fs.mkdirSync(outside, { recursive: true });
+ fs.writeFileSync(path.win32.join(masked, "token.txt"), "secret\n");
+ const lx = (p: string) => toLinuxPath(p, state.distro) ?? p;
+ const lines: CheckLine[] = [];
+ const confined = async (policy: SandboxPolicy, script: string) => {
+ const job = launchJob(["bash", "-c", script], policy, settings, state);
+ return runWsl(wslArgs(job, ws), { timeoutMs: 60_000 });
+ };
+ const base: SandboxPolicy = { mode: "workspace-write", workspaceRoot: ws, writableTemp: true };
+ const add = (en: string, zh: string, ok: boolean | null, detail: string) => {
+ lines.push({ name: { en, zh }, ok, detail });
+ };
+
+ report({ en: "Windows interop is off", zh: "Windows interop 已关闭" });
+ const interop = await runWsl(
+ [
+ "-d",
+ state.distro,
+ "-u",
+ "root",
+ "--cd",
+ "/",
+ "--exec",
+ "/bin/sh",
+ "-c",
+ "/mnt/c/Windows/System32/cmd.exe /c exit 0 >/dev/null 2>&1; echo rc=$?",
+ ],
+ { timeoutMs: 60_000 },
+ );
+ add(
+ "A Windows program cannot start from the distro",
+ "发行版内无法启动 Windows 程序",
+ !/rc=0\b/.test(interop.stdout),
+ interop.stdout || interop.stderr,
+ );
+
+ report({ en: "the sandbox runs", zh: "沙盒可以运行" });
+ const alive = await confined(base, "uname -sr; id -un");
+ add(
+ "bubblewrap starts a confined command",
+ "bubblewrap 能启动被隔离的命令",
+ alive.code === 0,
+ alive.stdout || alive.stderr,
+ );
+
+ report({ en: "writing the Workspace", zh: "写工作区" });
+ await confined(base, "echo ok > probe.txt");
+ const wrote = fs.existsSync(path.win32.join(ws, "probe.txt"));
+ add(
+ "workspace-write: the Workspace is writable",
+ "workspace-write:工作区可写",
+ wrote,
+ wrote ? "probe.txt written" : "no file appeared on Windows",
+ );
+
+ report({ en: "writing outside the Workspace", zh: "写工作区外" });
+ // The command must FAIL, not merely leave Windows untouched: a write that lands in the
+ // covering tmpfs reports success and disappears with the command, which reads to an agent
+ // as permission it does not have.
+ const out = await confined(base, `echo x > '${lx(outside)}/probe.txt' && echo WROTE`);
+ const escaped = fs.existsSync(path.win32.join(outside, "probe.txt"));
+ add(
+ "workspace-write: a write outside the Workspace is refused, not silently lost",
+ "workspace-write:工作区外的写入被拒绝,而不是悄悄丢失",
+ !escaped && !out.stdout.includes("WROTE"),
+ out.stderr || out.stdout || "the write reported success",
+ );
+
+ report({ en: "writing where the drives are covered", zh: "写被遮盖的磁盘路径" });
+ const covered = await confined(base, "echo x > /mnt/c/Users/penguin-probe.txt && echo WROTE");
+ add(
+ "the mount that hides the drives refuses writes too",
+ "遮盖磁盘的挂载同样拒绝写入",
+ !covered.stdout.includes("WROTE"),
+ covered.stderr || covered.stdout || "the write reported success",
+ );
+
+ report({ en: "read-only mode", zh: "只读模式" });
+ const ro = await confined({ ...base, mode: "read-only" }, "echo x > ro.txt");
+ const roWrote = fs.existsSync(path.win32.join(ws, "ro.txt"));
+ add(
+ "read-only: the Workspace is not writable",
+ "read-only:工作区不可写",
+ !roWrote,
+ ro.stderr || ro.stdout,
+ );
+
+ report({ en: "the Windows drives", zh: "Windows 磁盘" });
+ const drive = await confined(base, "test -e /mnt/c/Windows && echo visible || echo hidden");
+ const visible = drive.stdout.includes("visible");
+ add(
+ settings.exposeWindowsDrives
+ ? "Windows drives are visible read-only (setting on)"
+ : "Windows drives outside the Workspace are hidden (setting off)",
+ settings.exposeWindowsDrives
+ ? "Windows 磁盘以只读方式可见(设置已开)"
+ : "工作区以外的 Windows 磁盘不可见(设置已关)",
+ visible === settings.exposeWindowsDrives,
+ drive.stdout || drive.stderr,
+ );
+
+ report({ en: "the network", zh: "网络" });
+ // A name rather than a literal address: a machine behind a proxy that rewrites addresses
+ // refuses a connection to 1.1.1.1 while the network it actually uses works.
+ const netProbe =
+ "timeout 8 bash -c 'exec 3<>/dev/tcp/example.com/443' && echo connected || echo blocked";
+ // Resolution is its own question: covering /mnt and /run took away the file
+ // /etc/resolv.conf points at, so names failed while addresses still worked.
+ const dnsProbe = "getent hosts example.com >/dev/null && echo resolved || echo unresolved";
+ const none = await confined({ ...base, network: "none" }, netProbe);
+ add(
+ "network none: no connection",
+ "network none:无法连接",
+ none.stdout.includes("blocked"),
+ none.stdout || none.stderr,
+ );
+ const open = await confined(base, netProbe);
+ add(
+ "network allowed: connects (information)",
+ "允许网络:可以连接(仅供参考)",
+ open.stdout.includes("connected") ? true : null,
+ open.stdout || open.stderr,
+ );
+ const dns = await confined(base, dnsProbe);
+ add(
+ "network allowed: a host name resolves",
+ "允许网络:域名可以解析",
+ dns.stdout.includes("resolved") ? true : open.stdout.includes("connected") ? false : null,
+ dns.stdout || dns.stderr,
+ );
+
+ report({ en: "a masked path", zh: "屏蔽路径" });
+ const mask = await confined(
+ { ...base, maskPaths: [masked] },
+ `cat '${lx(masked)}/token.txt' 2>&1 || true`,
+ );
+ add(
+ "mask-paths: a masked file cannot be read",
+ "mask-paths:被屏蔽的文件不可读",
+ !mask.stdout.includes("secret"),
+ mask.stdout || mask.stderr,
+ );
+
+ report({ en: "writable temp", zh: "可写临时目录" });
+ const tmp = await confined(base, "echo x > /tmp/probe && echo ok");
+ add(
+ "the temp directory is writable",
+ "临时目录可写",
+ tmp.stdout.includes("ok"),
+ tmp.stdout || tmp.stderr,
+ );
+
+ fs.rmSync(root, { recursive: true, force: true });
+ const failed = lines.filter((l) => l.ok === false);
+ return {
+ lines,
+ result:
+ failed.length === 0
+ ? {
+ ok: true,
+ message: {
+ en: `All ${lines.length} checks passed.`,
+ zh: `全部 ${lines.length} 项检查通过。`,
+ },
+ }
+ : {
+ ok: false,
+ message: {
+ en: `${failed.length} of ${lines.length} checks failed: ${failed.map((l) => l.name.en).join("; ")}`,
+ zh: `${lines.length} 项检查中有 ${failed.length} 项失败:${failed.map((l) => l.name.zh).join(";")}`,
+ },
+ },
+ };
+}
+
+export async function remove(
+ settings: WslSettings,
+ report: (step: Text) => void,
+): Promise<Omit<TaskOutcome, "kind" | "at">> {
+ const distro = readState()?.distro ?? settings.distro;
+ report({ en: `wsl --unregister ${distro}`, zh: `wsl --unregister ${distro}` });
+ const res = await runWsl(["--unregister", distro], { timeoutMs: 5 * 60_000 });
+ removeState();
+ fs.rmSync(path.win32.join(stateDir(), "distros", distro), { recursive: true, force: true });
+ if (
+ res.code !== 0 &&
+ !/WSL_E_DISTRO_NOT_FOUND|no distribution/i.test(`${res.stdout}${res.stderr}`)
+ ) {
+ const why = res.stdout || res.stderr;
+ return {
+ ok: false,
+ message: { en: `wsl --unregister failed: ${why}`, zh: `wsl --unregister 失败:${why}` },
+ };
+ }
+ return {
+ ok: true,
+ message: {
+ en: `${distro} is removed with everything inside it. The sandbox backend stays off until you initialize again.`,
+ zh: `${distro} 及其中所有内容已移除。在重新初始化之前,沙盒后端保持停用。`,
+ },
+ };
+}
diff --git a/plugins/sandbox-wsl/test/profile.test.ts b/plugins/sandbox-wsl/test/profile.test.ts
new file mode 100644
index 00000000..499a14cd
--- /dev/null
+++ b/plugins/sandbox-wsl/test/profile.test.ts
@@ -0,0 +1,297 @@
+/**
+ * Unit tests for the WSL backend's pure half: path mapping, the program a Windows argv names,
+ * the bubblewrap profile per policy, the launcher's argv and notice filter, and the parsing of
+ * Alpine's release list. No wsl.exe is started, so these run on any host.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ bwrapArgs,
+ chdirRoots,
+ linuxProgram,
+ parseMinirootfs,
+ parseUbuntuSums,
+ provisionScript,
+ toLinuxPath,
+ wslSettingsOf,
+} from "../src/index.js";
+import { noticeFilter, wslArgs } from "../src/launch.js";
+import { cleanOutput, versionOf } from "../src/host.js";
+import { lastSegment } from "../src/tasks.js";
+
+const HOST = {
+ distro: "penguin-sandbox",
+ exposeWindowsDrives: false,
+ drives: ["c", "d"],
+ kind: (p: string) =>
+ p.endsWith("secret") ? ("dir" as const) : p.endsWith(".env") ? ("file" as const) : null,
+};
+const WS = "C:\\Users\\k\\ws";
+
+describe("toLinuxPath", () => {
+ it("maps a drive path under /mnt, lowercasing the drive", () => {
+ expect(toLinuxPath("C:\\Users\\k\\ws")).toBe("/mnt/c/Users/k/ws");
+ expect(toLinuxPath("d:/data/")).toBe("/mnt/d/data");
+ expect(toLinuxPath("E:\\")).toBe("/mnt/e");
+ });
+
+ it("maps this distro's own UNC path, and nothing else's", () => {
+ expect(toLinuxPath("\\\\wsl.localhost\\penguin-sandbox\\home\\x", "penguin-sandbox")).toBe(
+ "/home/x",
+ );
+ expect(toLinuxPath("\\\\wsl$\\Ubuntu\\home\\x", "penguin-sandbox")).toBeNull();
+ expect(toLinuxPath("\\\\server\\share\\x", "penguin-sandbox")).toBeNull();
+ expect(toLinuxPath("relative\\x")).toBeNull();
+ });
+});
+
+describe("linuxProgram", () => {
+ it("turns the Windows shell into the distro's", () => {
+ expect(linuxProgram("bash")).toBe("/bin/bash");
+ expect(linuxProgram("C:\\Program Files\\Git\\bin\\bash.exe")).toBe("/bin/bash");
+ expect(linuxProgram("sh.exe")).toBe("/bin/sh");
+ expect(linuxProgram("git.exe")).toBe("git");
+ });
+});
+
+describe("bwrapArgs", () => {
+ it("workspace-write: read-only distro, /run and /mnt hidden, the Workspace bound writable", () => {
+ const args = bwrapArgs({ mode: "workspace-write", workspaceRoot: WS }, HOST);
+ expect(args.slice(0, 3)).toEqual(["--die-with-parent", "--unshare-all", "--share-net"]);
+ expect(args.join(" ")).toContain("--ro-bind / /");
+ expect(args.join(" ")).toContain("--tmpfs /run");
+ const mnt = args.indexOf("/mnt");
+ const bind = args.indexOf("/mnt/c/Users/k/ws");
+ expect(args[mnt - 1]).toBe("--tmpfs");
+ expect(args[bind - 1]).toBe("--bind");
+ expect(bind).toBeGreaterThan(mnt);
+ });
+
+ it("read-only binds the Workspace read-only; network none drops --share-net", () => {
+ const args = bwrapArgs({ mode: "read-only", workspaceRoot: WS, network: "none" }, HOST);
+ expect(args).not.toContain("--share-net");
+ expect(args[args.indexOf("/mnt/c/Users/k/ws") - 1]).toBe("--ro-bind");
+ });
+
+ it("writable temp adds a tmpfs /tmp; exposing drives binds each read-only before the Workspace", () => {
+ const args = bwrapArgs(
+ { mode: "workspace-write", workspaceRoot: WS, writableTemp: true },
+ { ...HOST, exposeWindowsDrives: true },
+ );
+ expect(args.join(" ")).toContain("--tmpfs /tmp");
+ expect(args.join(" ")).toContain(
+ "--ro-bind /mnt/c /mnt/c --ro-bind /mnt/d /mnt/d --bind /mnt/c/Users/k/ws",
+ );
+ });
+
+ it("refuses the local network level rather than reading it as an open network", () => {
+ expect(() =>
+ bwrapArgs({ mode: "read-only", workspaceRoot: WS, network: "local" }, HOST),
+ ).toThrow(/local network/);
+ });
+
+ it("full access binds the distro writable and leaves /mnt alone, still cutting the network", () => {
+ const args = bwrapArgs(
+ { mode: "danger-full-access", workspaceRoot: WS, network: "none" },
+ HOST,
+ );
+ expect(args.join(" ")).toContain("--bind / /");
+ expect(args).not.toContain("/mnt");
+ expect(args).not.toContain("--share-net");
+ });
+
+ it("masks come last: a tmpfs over a directory, /dev/null over a file, nothing for a missing path", () => {
+ const args = bwrapArgs(
+ {
+ mode: "workspace-write",
+ workspaceRoot: WS,
+ maskPaths: [`${WS}\\secret`, `${WS}\\.env`, `${WS}\\gone`],
+ },
+ HOST,
+ );
+ const tail = args.slice(args.indexOf("--remount-ro") + 2);
+ expect(tail).toEqual([
+ "--tmpfs",
+ "/mnt/c/Users/k/ws/secret",
+ "--ro-bind",
+ "/dev/null",
+ "/mnt/c/Users/k/ws/.env",
+ ]);
+ });
+
+ it("seals the covering mount after the Workspace bind, so a write outside it fails", () => {
+ // A writable tmpfs over /mnt reported success for a write that reached nothing, which is a
+ // denial disguised as permission. The remount has to come AFTER the bind, which needs a
+ // writable tmpfs to create its mountpoint in.
+ const args = bwrapArgs({ mode: "workspace-write", workspaceRoot: WS }, HOST);
+ const remount = args.indexOf("--remount-ro");
+ expect(args[remount + 1]).toBe("/mnt");
+ expect(remount).toBeGreaterThan(args.lastIndexOf("/mnt/c/Users/k/ws"));
+ // Full access does not cover /mnt at all, so there is nothing to seal.
+ expect(bwrapArgs({ mode: "danger-full-access", workspaceRoot: WS }, HOST)).not.toContain(
+ "--remount-ro",
+ );
+ });
+
+ it("binds the generated resolv.conf back through both tmpfs, so names still resolve", () => {
+ const args = bwrapArgs({ mode: "workspace-write", workspaceRoot: WS }, HOST).join(" ");
+ expect(args).toContain(
+ "--tmpfs /run --ro-bind-try /run/resolvconf/resolv.conf /run/resolvconf/resolv.conf",
+ );
+ expect(args).toContain("--ro-bind-try /mnt/wsl/resolv.conf /mnt/wsl/resolv.conf --remount-ro");
+ });
+
+ it("refuses a Workspace with no path in the distro rather than confining nothing", () => {
+ expect(() =>
+ bwrapArgs({ mode: "workspace-write", workspaceRoot: "\\\\server\\share\\ws" }, HOST),
+ ).toThrow(/penguin-wsl: .*no path inside the WSL distro/);
+ });
+});
+
+describe("the launcher", () => {
+ const job = {
+ wsl: "C:\\Windows\\System32\\wsl.exe",
+ distro: "penguin-sandbox",
+ user: "penguin",
+ bwrap: ["--ro-bind", "/", "/"],
+ chdirRoots: chdirRoots({ mode: "workspace-write", workspaceRoot: WS }, HOST),
+ command: ["/bin/bash", "-lc", "pwd"],
+ };
+
+ it("runs bwrap as the sandbox user and changes into the cwd when it is inside the Workspace", () => {
+ expect(wslArgs(job, `${WS}\\sub`)).toEqual([
+ "-d",
+ "penguin-sandbox",
+ "-u",
+ "penguin",
+ "--cd",
+ "/",
+ "--exec",
+ "/usr/bin/bwrap",
+ "--ro-bind",
+ "/",
+ "/",
+ "--chdir",
+ "/mnt/c/Users/k/ws/sub",
+ "--",
+ "/bin/bash",
+ "-lc",
+ "pwd",
+ ]);
+ });
+
+ it("starts in the Workspace when the cwd is outside it", () => {
+ expect(wslArgs(job, "C:\\Windows")).toContain("/mnt/c/Users/k/ws");
+ });
+
+ it("drops WSL's own proxy notice from the start of stderr, and nothing else", () => {
+ const seen: string[] = [];
+ const f = noticeFilter((c) => seen.push(c));
+ f.push("wsl: A localhost proxy configuration was detected but not mirrored into WSL.\n");
+ f.push("bash: line 1: x: Read-only file system\n");
+ f.push("wsl: localhost again, but now it is the command's\n");
+ f.end();
+ expect(seen.join("")).toBe(
+ "bash: line 1: x: Read-only file system\nwsl: localhost again, but now it is the command's\n",
+ );
+ });
+});
+
+describe("host output and releases", () => {
+ it("cleans NULs and WSL notices out of wsl.exe output", () => {
+ expect(
+ cleanOutput("wsl: A localhost proxy configuration was detected\r\nU\0b\0u\0n\0t\0u\0\r\n"),
+ ).toBe("Ubuntu");
+ });
+
+ it("reads the version number whatever the label's language", () => {
+ expect(versionOf("WSL version: 2.7.14.0\nKernel version: 6.18")).toBe("2.7.14.0");
+ expect(versionOf("WSL 版本: 2.7.14.0")).toBe("2.7.14.0");
+ });
+
+ it("reads the last progress segment written with carriage returns", () => {
+ expect(lastSegment("Downloading: 10%\rDownloading: 55%\r\n\r\n")).toBe("Downloading: 55%");
+ });
+
+ it("finds the minirootfs in latest-releases.yaml", () => {
+ const yaml = [
+ "---",
+ "-",
+ ' title: "Netboot"',
+ " flavor: alpine-netboot",
+ " file: alpine-netboot-3.24.1-x86_64.tar.gz",
+ " sha256: aaaa",
+ "-",
+ ' title: "Mini root filesystem"',
+ " flavor: alpine-minirootfs",
+ " version: 3.24.1",
+ " file: alpine-minirootfs-3.24.1-x86_64.tar.gz",
+ " size: 3712345",
+ " sha256: ABCDEF",
+ ].join("\n");
+ expect(parseMinirootfs(yaml)).toEqual({
+ version: "3.24.1",
+ file: "alpine-minirootfs-3.24.1-x86_64.tar.gz",
+ sha256: "abcdef",
+ size: 3712345,
+ });
+ });
+
+ it("provisions Ubuntu with apt, interop off, and the packages once each", () => {
+ const script = provisionScript("ubuntu", "", ["git", "bubblewrap"]);
+ expect(script).toContain("[interop]\nenabled=false");
+ expect(script).toContain(
+ "apt-get install -y --no-install-recommends bubblewrap ca-certificates git\n",
+ );
+ expect(script).toContain("useradd -m -s /bin/bash penguin");
+ expect(script).not.toContain("sed -i");
+ });
+
+ it("points both Ubuntu archives at a mirror when one is set", () => {
+ const script = provisionScript("ubuntu", "https://mirror.example/ubuntu", []);
+ expect(script).toContain(
+ "sed -i 's|http://archive.ubuntu.com/ubuntu/*|https://mirror.example/ubuntu/|; " +
+ "s|http://security.ubuntu.com/ubuntu/*|https://mirror.example/ubuntu/|' " +
+ "/etc/apt/sources.list.d/ubuntu.sources",
+ );
+ });
+
+ it("provisions Alpine with apk, its own mirror, and bash", () => {
+ const script = provisionScript("alpine", "https://mirror.example/alpine", ["git", "bash"]);
+ expect(script).toContain("'https://mirror.example/alpine'");
+ expect(script).toContain("apk add --no-progress bubblewrap bash git\n");
+ expect(provisionScript("alpine", "", [])).toContain("'https://dl-cdn.alpinelinux.org/alpine'");
+ });
+
+ it("takes the newest ubuntu-base tarball for this architecture out of SHA256SUMS", () => {
+ const sums = [
+ "aaa *ubuntu-base-24.04.3-base-amd64.tar.gz",
+ `${"1".repeat(64)} *ubuntu-base-24.04.10-base-amd64.tar.gz`,
+ `${"2".repeat(64)} *ubuntu-base-24.04.9-base-amd64.tar.gz`,
+ `${"3".repeat(64)} *ubuntu-base-24.04.20-base-arm64.tar.gz`,
+ ].join("\n");
+ expect(parseUbuntuSums(sums, "amd64")).toEqual({
+ sha256: "1".repeat(64),
+ file: "ubuntu-base-24.04.10-base-amd64.tar.gz",
+ version: "24.04.10",
+ });
+ expect(parseUbuntuSums(sums, "riscv64")).toBeNull();
+ });
+
+ it("settings fall back to defaults for anything unusable, and Ubuntu is the default base", () => {
+ expect(
+ wslSettingsOf({
+ distro: "bad name",
+ base: "gentoo",
+ mirror: "ftp://x",
+ packages: ["ok", "Bad!"],
+ }),
+ ).toEqual({
+ distro: "penguin-sandbox",
+ base: "ubuntu",
+ exposeWindowsDrives: false,
+ mirror: "",
+ packages: ["ok"],
+ });
+ expect(wslSettingsOf({ base: "alpine" }).base).toBe("alpine");
+ });
+});
diff --git a/plugins/sandbox-mxc/tsconfig.json b/plugins/sandbox-wsl/tsconfig.json
similarity index 100%
rename from plugins/sandbox-mxc/tsconfig.json
rename to plugins/sandbox-wsl/tsconfig.json
diff --git a/plugins/sandbox-wsl/tsup.config.ts b/plugins/sandbox-wsl/tsup.config.ts
new file mode 100644
index 00000000..5eee3bdf
--- /dev/null
+++ b/plugins/sandbox-wsl/tsup.config.ts
@@ -0,0 +1,13 @@
+import { defineConfig } from "tsup";
+
+export default defineConfig({
+ // Two entries: the plugin the harness loads, and the launcher each confined command becomes —
+ // a small Node process that runs wsl.exe and keeps WSL's own console warnings out of the
+ // command's stderr.
+ entry: ["src/index.ts", "src/launch.ts"],
+ format: ["esm"],
+ target: "node24",
+ dts: true,
+ clean: true,
+ sourcemap: true,
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e4439954..936170b0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -620,11 +620,8 @@ importers:
specifier: ^3.2.6
- plugins/sandbox-mxc:
+ plugins/sandbox-seatbelt:
devDependencies:
- '@microsoft/mxc-sdk':
- specifier: 0.7.0
- version: 0.7.0
'@prismshadow/penguin-core':
specifier: workspace:*
version: file:packages/core([email protected])([email protected])
@@ -635,7 +632,7 @@ importers:
specifier: ^3.2.6
- plugins/sandbox-seatbelt:
+ plugins/sandbox-wsl:
devDependencies:
'@prismshadow/penguin-core':
specifier: workspace:*
@@ -1325,10 +1322,6 @@ packages:
resolution: {integrity: sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==}
engines: {node: '>= 10.0.0'}
- '@microsoft/[email protected]':
- resolution: {integrity: sha512-EWhz2pKkcPluZHAOI1yneV+JK0NO/3hdh7nABBb0x4PjyUWMeSWPTBAjtIu+BhtMYOqlaijSPZMZ0Hs/J4ZL4A==}
- engines: {node: '>=18.0.0'}
-
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==}
engines: {node: '>=20'}
@@ -3536,9 +3529,6 @@ packages:
resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}
- resolution: {integrity: sha512-vORSzHXi4Ofl7HemVWpuudLqCPdaQb4LfpRCUpE5HPxhp4JYscl8zZwxh11p26v2wvW24WMwnMfLjhRLixrfxA==}
-
resolution: {integrity: sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==}
engines: {node: '>=18'}
@@ -5303,11 +5293,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@microsoft/[email protected]':
- dependencies:
- node-pty: 1.2.0-beta.15
- semver: 7.8.5
-
'@modelcontextprotocol/[email protected]':
dependencies:
'@modelcontextprotocol/core': 2.0.0
@@ -8025,10 +8010,6 @@ snapshots:
dependencies:
node-addon-api: 7.1.1
- dependencies:
- node-addon-api: 7.1.1
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 012e2776..53404e36 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -38,10 +38,7 @@ allowBuilds:
# electron-winstaller.
koffi: false
# node-pty compiles its native pty binding (node-gyp) on install; without this the
- # terminal server has no pty and every session fails to spawn. The allow entry is
- # per-package-name, so it also builds the second, beta copy @microsoft/mxc-sdk pulls
- # in — harmless, and that copy is never loaded (the MXC plugin only asks the SDK to
- # BUILD a config; it spawns the runner through the harness, never through a pty).
+ # terminal server has no pty and every session fails to spawn.
node-pty: true
# pnpm 11 withholds freshly published versions by default (supply-chain gate), which
# would resolve agenthub back to the previous release and lose the fix the bump is for.
@@ -60,5 +57,4 @@ minimumReleaseAgeExclude:
- "@deepseek-ai/[email protected]"
- "@deepseek-ai/[email protected]"
- "@deepseek-ai/[email protected]"
- - "@microsoft/[email protected]"
- "@prismshadow/[email protected]"
diff --git a/scripts/build-plugins.mjs b/scripts/build-plugins.mjs
index f1ea3185..01680f61 100644
--- a/scripts/build-plugins.mjs
+++ b/scripts/build-plugins.mjs
@@ -40,7 +40,7 @@ const PLUGINS_SRC = path.join(ROOT, "plugins");
const CACHE = path.join(ROOT, "node_modules", ".cache", "penguin-plugins");
const COMPLETE = ".complete";
/** Folded into the cache key: bump when what this script WRITES changes, not only what it reads. */
-const PACK_FORMAT = 7;
+const PACK_FORMAT = 13;
/** The prefix's own manifest: npm needs one above `node_modules`, and it is ours, never a package's. */
const PREFIX_MANIFEST = { name: "penguin-builtin-plugins", private: true, version: "0.0.0" };
/**
@@ -140,7 +140,15 @@ function run(name, args, cwd) {
}
}
-/** What a plugin's pack depends on: its sources, its manifest, its README and its build config. */
+/**
+ * What a plugin's pack depends on: its sources, its manifest, its README, its build config —
+ * and every other directory the package SHIPS.
+ *
+ * That last part is not decoration. A plugin may carry files its code never imports (the Windows
+ * backend ships the PowerShell script its setup runs), and hashing only `src/` meant editing one
+ * of them changed nothing the cache could see: the build happily served a stale pack, and the
+ * fix nobody could find on the host was a file that had never left this machine.
+ */
async function sourceHash(dir, into) {
for (const rel of ["package.json", "README.md", "tsup.config.ts"]) {
const file = path.join(dir, rel);
@@ -151,13 +159,17 @@ async function sourceHash(dir, into) {
.update(await fsp.readFile(file))
.update("\0");
}
- const src = path.join(dir, "src");
- if (fs.existsSync(src)) {
- for (const rel of await walk(src)) {
+ const manifest = JSON.parse(await fsp.readFile(path.join(dir, "package.json"), "utf8"));
+ // `dist` and `vendor` are built or fetched from what is hashed here, never edited by hand.
+ const shipped = (manifest.files ?? []).filter((f) => !["dist", "vendor"].includes(f));
+ for (const name of ["src", ...shipped]) {
+ const sub = path.join(dir, name);
+ if (!fs.existsSync(sub) || !fs.statSync(sub).isDirectory()) continue;
+ for (const rel of await walk(sub)) {
into
- .update(`src/${rel}`)
+ .update(`${name}/${rel}`)
.update("\0")
- .update(await fsp.readFile(path.join(src, rel)))
+ .update(await fsp.readFile(path.join(sub, rel)))
.update("\0");
}
}
@@ -276,6 +288,13 @@ export async function buildBuiltinPlugins({ log = () => {} } = {}) {
log(`${platformPackages.length} per-platform native binaries: installed`);
}
}
+ // npm installs a package's files with the mode it pleases, and a vendored program
+ // arrives without its exec bit — which no consumer of the prefix can guess back.
+ for (const rel of await walk(out)) {
+ if (/(^|\/)vendor\/[^/]+\/bin\/[^/]+$/.test(rel)) {
+ await fsp.chmod(path.join(out, rel), 0o755);
+ }
+ }
await fsp.writeFile(path.join(out, COMPLETE), hash);
log(`${plugins.length} builtin plugins: installed (${hash})`);
} catch (err) {
diff --git a/scripts/vendor-bwrap.mjs b/scripts/vendor-bwrap.mjs
new file mode 100644
index 00000000..c6375ece
--- /dev/null
+++ b/scripts/vendor-bwrap.mjs
@@ -0,0 +1,274 @@
+/**
+ * The bubblewrap the sandbox backend runs, vendored into the plugin.
+ *
+ * A deployment must not depend on the host having `bwrap`: most distributions do not install
+ * one, several ship a version too old for the profile this backend builds, and asking an
+ * operator to `apt install bubblewrap` before the sandbox works is the kind of setup step that
+ * silently never happens. The plugin therefore carries its own binary, one per architecture,
+ * and falls back to a `bwrap` on PATH only when it has none for this host.
+ *
+ * WHERE IT COMES FROM: conda-forge, pinned by exact URL and sha256 below. Those builds target
+ * an old glibc and carry `$ORIGIN/../lib` as their rpath, so `vendor/<arch>/bin/bwrap` finds
+ * `vendor/<arch>/lib/libcap.so.2` beside it with no environment variable — which matters,
+ * because a sandbox backend rewrites an argv and never gets to set one.
+ *
+ * Bubblewrap is LGPL-2.1-or-later and libcap is BSD-3-Clause or GPL-2.0: their license files
+ * travel with the binaries (`vendor/<arch>/licenses/`), which is what shipping them requires.
+ *
+ * Usage (a library for build-plugins.mjs, and a CLI):
+ * node scripts/vendor-bwrap.mjs vendor into plugins/sandbox-bwrap/vendor/
+ */
+import { createHash } from "node:crypto";
+import { createRequire } from "node:module";
+import fs from "node:fs";
+import fsp from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { zstdDecompress } from "node:zlib";
+import { promisify } from "node:util";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const OUT = path.join(ROOT, "plugins", "sandbox-bwrap", "vendor");
+const CACHE = path.join(ROOT, "node_modules", ".cache", "penguin-bwrap-vendor");
+const tar = createRequire(path.join(ROOT, "packages", "server", "package.json"))("tar");
+const decompress = promisify(zstdDecompress);
+
+/** Bump when what this script WRITES changes, so a stale vendor directory is rebuilt. */
+const VENDOR_FORMAT = 1;
+
+/**
+ * What each architecture gets, pinned. A version moves only by editing this table: the sandbox
+ * runs what it says, and a build that cannot verify a hash fails rather than shipping a binary
+ * nobody pinned.
+ */
+const TARGETS = [
+ {
+ arch: "linux-x64",
+ packages: [
+ {
+ url: "https://conda.anaconda.org/conda-forge/linux-64/bubblewrap-0.11.2-h424e585_1.conda",
+ sha256: "94458118b18b0c25afc720d012c0ef1bd36fa4d31c2bb92c4d14662857457825",
+ },
+ {
+ url: "https://conda.anaconda.org/conda-forge/linux-64/libcap-2.78-h084b8d7_1.conda",
+ sha256: "8cb25174d6b6fac95d31e86cfe41faffc8ee9dacbf2bfd22e6c23377e8f338c1",
+ },
+ ],
+ },
+ {
+ arch: "linux-arm64",
+ packages: [
+ {
+ url: "https://conda.anaconda.org/conda-forge/linux-aarch64/bubblewrap-0.11.2-h9367005_1.conda",
+ sha256: "20022874a86589f68b508a6c34768fdcb418439a780a39d69b94f72403d05e68",
+ },
+ {
+ url: "https://conda.anaconda.org/conda-forge/linux-aarch64/libcap-2.78-hfcc8634_1.conda",
+ sha256: "6487e7644d062e18d389c11a9a3183e5a71c2652d05fdd88dbd063ad09f7ad4b",
+ },
+ ],
+ },
+];
+
+/** What is taken out of a package: the program, the library it loads, and their licenses. */
+const WANTED = [
+ { from: "bin/bwrap", to: "bin/bwrap", exec: true },
+ { from: /^lib\/libcap\.so(\.\d+)*$/, to: "lib", exec: false },
+ { from: /^(info\/)?licenses?\/.+/i, to: "licenses", exec: false },
+];
+
+function log(message) {
+ process.stdout.write(`[vendor-bwrap] ${message}\n`);
+}
+
+/** Downloads once into the cache, keyed by the hash the table pins, and verifies it. */
+async function fetchPackage(pkg) {
+ await fsp.mkdir(CACHE, { recursive: true });
+ const file = path.join(CACHE, `${pkg.sha256}-${path.basename(pkg.url)}`);
+ if (fs.existsSync(file)) return file;
+ const response = await fetch(pkg.url);
+ if (!response.ok) throw new Error(`${pkg.url}: HTTP ${response.status}`);
+ const bytes = Buffer.from(await response.arrayBuffer());
+ const digest = createHash("sha256").update(bytes).digest("hex");
+ if (digest !== pkg.sha256) {
+ throw new Error(`${pkg.url}: sha256 is ${digest}, and the pin says ${pkg.sha256}`);
+ }
+ await fsp.writeFile(file, bytes);
+ log(`${path.basename(pkg.url)}: downloaded (${(bytes.length / 1024).toFixed(0)}KB)`);
+ return file;
+}
+
+/**
+ * A `.conda` package is a ZIP holding `pkg-<name>.tar.zst`; this reads that member out of it
+ * without a ZIP library. It goes through the CENTRAL DIRECTORY rather than walking local
+ * headers, because these archives are ZIP64: a local header there carries 0xFFFFFFFF for the
+ * sizes and leaves the real ones to the central entry's extra field.
+ */
+export function readZipMember(zip, predicate) {
+ const end = findSignature(zip, 0x0605_4b50, 22);
+ if (end === -1) throw new Error("not a ZIP: no end-of-central-directory record");
+ let entries = zip.readUInt16LE(end + 10);
+ let directory = zip.readUInt32LE(end + 16);
+ const zip64 = findSignature(zip, 0x0606_4b50, 56);
+ if (zip64 !== -1) {
+ entries = Number(zip.readBigUInt64LE(zip64 + 32));
+ directory = Number(zip.readBigUInt64LE(zip64 + 48));
+ }
+ let at = directory;
+ for (let i = 0; i < entries; i++) {
+ if (zip.readUInt32LE(at) !== 0x0201_4b50) throw new Error("malformed central directory");
+ const method = zip.readUInt16LE(at + 10);
+ const nameLength = zip.readUInt16LE(at + 28);
+ const extraLength = zip.readUInt16LE(at + 30);
+ const commentLength = zip.readUInt16LE(at + 32);
+ const name = zip.toString("utf8", at + 46, at + 46 + nameLength);
+ let compressed = zip.readUInt32LE(at + 20);
+ let localHeader = zip.readUInt32LE(at + 42);
+ if (compressed === 0xffff_ffff || localHeader === 0xffff_ffff) {
+ ({ compressed, localHeader } = zip64Sizes(
+ zip.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength),
+ zip.readUInt32LE(at + 24) === 0xffff_ffff,
+ compressed === 0xffff_ffff,
+ localHeader === 0xffff_ffff,
+ { compressed, localHeader },
+ ));
+ }
+ if (predicate(name)) {
+ if (method !== 0) {
+ throw new Error(`${name}: compressed with method ${method}, expected stored`);
+ }
+ const start =
+ localHeader + 30 + zip.readUInt16LE(localHeader + 26) + zip.readUInt16LE(localHeader + 28);
+ return zip.subarray(start, start + compressed);
+ }
+ at += 46 + nameLength + extraLength + commentLength;
+ }
+ return null;
+}
+
+/** The first record with this signature, searched from the end (where ZIP keeps its trailers). */
+function findSignature(zip, signature, minimumTail) {
+ for (let at = zip.length - minimumTail; at >= 0; at--) {
+ if (zip.readUInt32LE(at) === signature) return at;
+ }
+ return -1;
+}
+
+/**
+ * The ZIP64 extra field (header id 0x0001) holds whichever of uncompressed size, compressed
+ * size and local-header offset the central entry could not, in that order — so which values it
+ * carries depends on which ones were 0xFFFFFFFF.
+ */
+function zip64Sizes(extra, uncompressedIsBig, compressedIsBig, offsetIsBig, fallback) {
+ let at = 0;
+ while (at + 4 <= extra.length) {
+ const id = extra.readUInt16LE(at);
+ const size = extra.readUInt16LE(at + 2);
+ if (id === 0x0001) {
+ let field = at + 4;
+ if (uncompressedIsBig) field += 8;
+ const compressed = compressedIsBig
+ ? Number(extra.readBigUInt64LE(field))
+ : fallback.compressed;
+ if (compressedIsBig) field += 8;
+ const localHeader = offsetIsBig ? Number(extra.readBigUInt64LE(field)) : fallback.localHeader;
+ return { compressed, localHeader };
+ }
+ at += 4 + size;
+ }
+ return fallback;
+}
+
+/** Unpacks one package into `stage`, keeping only WANTED files. */
+async function extract(file, stage) {
+ const zip = await fsp.readFile(file);
+ const scratch = await fsp.mkdtemp(path.join(os.tmpdir(), "penguin-bwrap-"));
+ try {
+ // Two members carry what is wanted: `pkg-*` the files themselves, `info-*` the licenses
+ // conda-forge keeps under `info/licenses/` — and shipping a binary means shipping those.
+ for (const prefix of ["pkg-", "info-"]) {
+ const member = readZipMember(
+ zip,
+ (name) => name.startsWith(prefix) && name.endsWith(".tar.zst"),
+ );
+ if (member === null) {
+ if (prefix === "pkg-") throw new Error(`${file}: no pkg-*.tar.zst inside`);
+ continue;
+ }
+ const tarFile = path.join(scratch, `${prefix}archive.tar`);
+ await fsp.writeFile(tarFile, await decompress(member));
+ await tar.x({ file: tarFile, cwd: scratch });
+ }
+ for (const want of WANTED) {
+ const matches = (await walk(scratch)).filter((rel) =>
+ typeof want.from === "string" ? rel === want.from : want.from.test(rel),
+ );
+ for (const rel of matches) {
+ const target =
+ typeof want.from === "string"
+ ? path.join(stage, want.to)
+ : path.join(stage, want.to, path.basename(rel));
+ await fsp.mkdir(path.dirname(target), { recursive: true });
+ const source = path.join(scratch, rel);
+ const link = await fsp.lstat(source);
+ if (link.isSymbolicLink()) {
+ // libcap.so.2 → libcap.so.2.78: kept as a link, the way the loader expects it.
+ const to = await fsp.readlink(source);
+ await fsp.rm(target, { force: true });
+ await fsp.symlink(to, target);
+ } else {
+ await fsp.copyFile(source, target);
+ await fsp.chmod(target, want.exec ? 0o755 : 0o644);
+ }
+ }
+ }
+ } finally {
+ await fsp.rm(scratch, { recursive: true, force: true });
+ }
+}
+
+/** Files under `dir`, as relative posix paths (symlinks included, since libcap ships one). */
+async function walk(dir, prefix = "") {
+ const out = [];
+ for (const entry of await fsp.readdir(dir, { withFileTypes: true })) {
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
+ if (entry.isDirectory()) out.push(...(await walk(path.join(dir, entry.name), rel)));
+ else out.push(rel);
+ }
+ return out.sort();
+}
+
+/**
+ * Vendors every target into `plugins/sandbox-bwrap/vendor/<arch>/`, skipping the work when the
+ * directory already holds this pinning (a `.complete` marker naming it).
+ */
+export async function vendorBwrap() {
+ const pinning = createHash("sha256")
+ .update(`${VENDOR_FORMAT}\0${JSON.stringify(TARGETS)}`)
+ .digest("hex");
+ const marker = path.join(OUT, ".complete");
+ if (fs.existsSync(marker) && (await fsp.readFile(marker, "utf8")) === pinning) return OUT;
+ await fsp.rm(OUT, { recursive: true, force: true });
+ for (const target of TARGETS) {
+ const stage = path.join(OUT, target.arch);
+ await fsp.mkdir(stage, { recursive: true });
+ for (const pkg of target.packages) await extract(await fetchPackage(pkg), stage);
+ if (!fs.existsSync(path.join(stage, "bin", "bwrap"))) {
+ throw new Error(`${target.arch}: the packages carried no bin/bwrap`);
+ }
+ log(`${target.arch}: vendored`);
+ }
+ await fsp.writeFile(marker, pinning);
+ return OUT;
+}
+
+if (process.argv[1] !== undefined && import.meta.url.endsWith(path.basename(process.argv[1]))) {
+ vendorBwrap().then(
+ (dir) => log(`ready: ${dir}`),
+ (err) => {
+ process.stderr.write(`[vendor-bwrap] ${err instanceof Error ? err.message : String(err)}\n`);
+ process.exit(1);
+ },
+ );
+}