@niwa-labs/sandbox 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/nono.ts ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * nono: the process class, a capability sandbox.
3
+ *
4
+ * nono is deny-by-default: nothing is readable or writable until it is granted. The manifest is
5
+ * the flag list nono is run with. Writing, the network and sockets map one to one; a path that is a
6
+ * file is granted as a file, since nono takes a directory flag only for a directory. Reading is an
7
+ * allow-list in nono, so a `closed` entry needs no flag: what was never granted is already closed,
8
+ * and a place granted inside a closed one stays granted. Carving a hole out of a granted directory
9
+ * cannot be said, so a `closed` place inside a place the box may read or write is refused rather
10
+ * than weakened, and that includes the system places the profile grants: a read it would allow is
11
+ * not left to look closed.
12
+ * nono runs with a `HOME` and PATH of its own, the host's; the spec's environment is set on the command inside.
13
+ *
14
+ * Writing is held to `write` exactly and reading to the cwd, `read` and the places a process needs to
15
+ * run. nono's default profile also lets a process write the shared temp areas and read all of
16
+ * `/private` (on macOS the user's own temp directory is there), so every run is given a profile of the
17
+ * host's that is the default one without those groups, the system places named one by one. nono is
18
+ * asked before the first launch how it resolves that profile: one that grants more than is named here
19
+ * is not available.
20
+ */
21
+
22
+ import { realpathSync, statSync } from "node:fs";
23
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
24
+ import { homedir, tmpdir } from "node:os";
25
+ import { basename, dirname, join, resolve, sep } from "node:path";
26
+
27
+ import type { BoxPolicy, Sandbox, SandboxManifest } from "./sandbox.ts";
28
+ import { BoxRefused, SandboxUnavailable } from "./sandbox.ts";
29
+ import type { BoxSpec } from "./spec.ts";
30
+ import { boxSpec } from "./spec.ts";
31
+ import { anchoredSpec } from "./paths.ts";
32
+ import { SYSTEM_PATH, probe, spawnBox } from "./spawn.ts";
33
+
34
+ /** A path with a leading `~` made the home directory, and otherwise as it is spelled. */
35
+ function homeExpanded(path: string): string {
36
+ return resolve(path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path);
37
+ }
38
+
39
+ /** A path as the sandbox sees it: `~` expanded, and the links of its longest existing part resolved. */
40
+ function expanded(path: string): string {
41
+ return resolved(homeExpanded(path));
42
+ }
43
+
44
+ const distinct = (paths: readonly string[]): string[] => [...new Set(paths)];
45
+
46
+ function resolved(absolute: string): string {
47
+ try {
48
+ return realpathSync(absolute);
49
+ } catch {
50
+ const parent = dirname(absolute);
51
+ return parent === absolute ? absolute : join(resolved(parent), basename(absolute));
52
+ }
53
+ }
54
+
55
+ /** Is `path` the place `root` names, or under it? */
56
+ function covers(root: string, path: string): boolean {
57
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
58
+ }
59
+
60
+ /** Is the place at this path a file? A path that is not there is taken for a directory to be made. */
61
+ function isFile(path: string): boolean {
62
+ try {
63
+ return statSync(homeExpanded(path)).isFile();
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /** The flag that grants a path for reading, or for reading and writing: a file's flag for a file. */
70
+ function grant(path: string, mode: "read" | "write"): string[] {
71
+ const file = isFile(path);
72
+ if (mode === "read") return [file ? "--read-file" : "--read", path];
73
+ return [file ? "--allow-file" : "--allow", path];
74
+ }
75
+
76
+ /**
77
+ * nono supplies proxy variables to the confined child, including a bypass list for loopback.
78
+ * A domain grant opens the proxy only. Send requests for the granted loopback names through
79
+ * that proxy too, keeping every other bypass entry and the parent's environment intact.
80
+ */
81
+ function proxyCommand(hosts: readonly string[], argv: readonly string[]): readonly string[] {
82
+ const local = hosts.filter((host) => ["127.0.0.1", "localhost", "::1", "[::1]"].includes(host));
83
+ if (local.length === 0 || !argv.length || argv[0]?.includes("=")) return argv;
84
+ const script = `
85
+ granted=$1
86
+ shift
87
+ filter() {
88
+ /usr/bin/awk -v granted="$granted" -F, '
89
+ BEGIN {
90
+ count = split(granted, hosts, ",")
91
+ for (i = 1; i <= count; i++) skip[hosts[i]] = 1
92
+ }
93
+ {
94
+ for (i = 1; i <= NF; i++) {
95
+ if ($i in skip) continue
96
+ printf "%s%s", separator, $i
97
+ separator = ","
98
+ }
99
+ }'
100
+ }
101
+ if [ "\${NO_PROXY+x}" ]; then NO_PROXY=$(printf "%s" "$NO_PROXY" | filter); export NO_PROXY; fi
102
+ if [ "\${no_proxy+x}" ]; then no_proxy=$(printf "%s" "$no_proxy" | filter); export no_proxy; fi
103
+ exec /usr/bin/env -- "$@"
104
+ `;
105
+ return ["/bin/sh", "-c", script, "niwa-proxy", local.join(","), ...argv];
106
+ }
107
+
108
+ /**
109
+ * What the nono process runs with: the host's, fixed. nono reads its own configuration from `HOME`
110
+ * and finds its tools through PATH before it confines anything, so the spec's environment is not
111
+ * given to it.
112
+ */
113
+ function launcherEnv(): Readonly<Record<string, string>> {
114
+ return { PATH: SYSTEM_PATH, HOME: homedir() };
115
+ }
116
+
117
+ /**
118
+ * Where nono is started from: a place the command has no way to put files in. nono wants the
119
+ * directory it runs in to be granted, and this is one of the system directories its default profile
120
+ * already lets it read, so no grant is added for it.
121
+ */
122
+ const TRUSTED_DIRECTORY = "/usr/share";
123
+
124
+ /**
125
+ * The profile nono runs with: its default, less every group that lets a process read or write a place
126
+ * the spec did not name. Those groups grant the shared temp areas (on macOS all of `/private`, which
127
+ * holds the user's own temp directory) and the user's tools; the places a process needs to run are
128
+ * granted again by name, and nothing else is. The groups that deny the user's credentials stay.
129
+ */
130
+ export interface NonoProfile {
131
+ readonly meta: { readonly name: string };
132
+ readonly extends: "default";
133
+ readonly groups: { readonly exclude: readonly string[] };
134
+ readonly filesystem: { readonly read: readonly string[]; readonly write: readonly string[]; readonly write_file: readonly string[] };
135
+ }
136
+
137
+ /**
138
+ * What a process on macOS reads to run: the system's programs, libraries and data, the link cache,
139
+ * the time zones and the developer tools `xcode-select` points at. Not `/private` or `/var` as a whole,
140
+ * not `/tmp`, and not `/var/folders`, where every user's temp directory is.
141
+ */
142
+ const MACOS_READS = [
143
+ "/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/libexec", "/usr/lib", "/usr/share", "/usr/local/bin", "/usr/local/lib",
144
+ "/usr/local/Cellar", "/usr/local/opt", "/opt", "/nix",
145
+ "/System/Library", "/System/Cryptexes", "/System/Volumes/Preboot/Cryptexes", "/Library", "/Applications",
146
+ "/private/etc", "/private/var/db/dyld", "/private/var/db/timezone", "/private/var/select", "/private/var/db/xcode_select_link",
147
+ // A path through the links at `/etc` and `/var` is matched as it is spelled, so each is named that way too.
148
+ "/etc", "/var/db/dyld", "/var/db/timezone", "/var/select", "/var/db/xcode_select_link",
149
+ "/dev",
150
+ ] as const;
151
+
152
+ /** What nono's own Linux read group grants, kept as it is: it names no temp area. */
153
+ const LINUX_READS = [
154
+ "/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin", "/lib", "/lib64", "/lib/x86_64-linux-gnu", "/lib/aarch64-linux-gnu",
155
+ "/usr/lib", "/usr/lib64", "/usr/lib/x86_64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/usr/local/lib", "/usr/local/lib64",
156
+ "/etc/resolv.conf", "/run/systemd/resolve", "/etc/hosts", "/etc/nsswitch.conf", "/etc/gai.conf", "/etc/group", "/etc/ssl",
157
+ "/etc/pki", "/etc/ca-certificates", "/var/lib/ca-certificates", "/etc/crypto-policies", "/etc/fonts", "/etc/ld.so.cache",
158
+ "/etc/ld.so.conf", "/etc/ld.so.conf.d", "/etc/localtime", "/etc/timezone", "/etc/locale.conf", "/etc/locale.gen",
159
+ "/etc/alternatives", "/etc/os-release", "/etc/passwd", "/etc/services", "/etc/mime.types", "/etc/manpath.config",
160
+ "/etc/man_db.conf", "/var/cache/man", "/run/systemd/userdb", "/usr/share", "/usr/share/locale", "/usr/share/locale-langpack",
161
+ "/usr/share/zoneinfo", "/usr/share/terminfo", "/usr/share/ca-certificates", "/lib/terminfo", "/etc/terminfo", "/dev/null",
162
+ "/dev/zero", "/dev/random", "/dev/urandom", "/dev/full", "/dev/tty", "/dev/console", "/dev/stdin", "/dev/stdout",
163
+ "/dev/stderr", "/dev/fd", "/dev/pts", "/proc/self", "/proc/cpuinfo", "/proc/meminfo", "/proc/stat", "/proc/loadavg",
164
+ "/proc/version", "/proc/filesystems",
165
+ ] as const;
166
+
167
+ /** The profile of each platform. On Linux nono's own read group is kept, so the profile names no read of its own. */
168
+ function profileFor(platform: NodeJS.Platform): NonoProfile {
169
+ const meta = { name: "niwa-box" } as const;
170
+ if (platform === "darwin") {
171
+ return {
172
+ meta,
173
+ extends: "default",
174
+ groups: { exclude: ["system_read_macos", "system_write_macos", "user_tools", "homebrew_macos"] },
175
+ filesystem: { read: [...MACOS_READS], write: ["/dev"], write_file: [] },
176
+ };
177
+ }
178
+ return {
179
+ meta,
180
+ extends: "default",
181
+ groups: { exclude: ["system_write_linux", "user_tools", "homebrew_linux"] },
182
+ filesystem: {
183
+ read: [],
184
+ write: ["/dev/fd", "/dev/pts", "/proc/self/fd"],
185
+ write_file: ["/dev/null", "/dev/zero", "/dev/full", "/dev/tty", "/dev/stdout", "/dev/stderr"],
186
+ },
187
+ };
188
+ }
189
+
190
+ /** Every place the profile of a platform lets a process write. */
191
+ function systemWrites(platform: NodeJS.Platform): readonly string[] {
192
+ const profile = profileFor(platform);
193
+ return [...profile.filesystem.write, ...profile.filesystem.write_file];
194
+ }
195
+
196
+ /** Every place the profile of a platform lets a process read, whoever grants it: the profile or a group it keeps. */
197
+ function systemReads(platform: NodeJS.Platform): readonly string[] {
198
+ return [...(platform === "darwin" ? MACOS_READS : LINUX_READS), ...systemWrites(platform)];
199
+ }
200
+
201
+ /**
202
+ * Does nono, resolving the profile at `path`, grant no more than the adapter says it does? A group a
203
+ * later nono adds to its default would otherwise open places nothing here knows of, and a nono whose
204
+ * answer cannot be read is not taken at its word either.
205
+ */
206
+ function resolvesAsSaid(binary: string, path: string, platform: NodeJS.Platform): boolean {
207
+ let grants: unknown;
208
+ try {
209
+ const shown = Bun.spawnSync([binary, "profile", "show", path, "--format", "manifest"], {
210
+ cwd: TRUSTED_DIRECTORY,
211
+ env: { ...launcherEnv() },
212
+ stdin: "ignore",
213
+ stdout: "pipe",
214
+ stderr: "ignore",
215
+ timeout: 10_000,
216
+ });
217
+ grants = (JSON.parse(shown.stdout.toString()) as { filesystem?: { grants?: unknown } }).filesystem?.grants;
218
+ } catch {
219
+ return false;
220
+ }
221
+ if (!Array.isArray(grants)) return false;
222
+ const reads = systemReads(platform).map(expanded);
223
+ const writes = systemWrites(platform).map(expanded);
224
+ const within = (roots: readonly string[], place: string) => roots.some((root) => covers(root, place));
225
+ return grants.every((grant: { access?: unknown; path?: unknown }) => {
226
+ if (typeof grant.path !== "string") return false;
227
+ const place = expanded(grant.path);
228
+ if (grant.access === "read") return within(reads, place);
229
+ if (grant.access === "write" || grant.access === "readwrite") return within(writes, place);
230
+ return false;
231
+ });
232
+ }
233
+
234
+ export interface NonoManifest extends SandboxManifest {
235
+ readonly sandbox: "nono";
236
+ readonly policy: BoxPolicy;
237
+ /** The profile file nono is run with, put before these flags at launch. */
238
+ readonly profile: NonoProfile;
239
+ /** The flags between `nono run` and the program. */
240
+ readonly flags: readonly string[];
241
+ }
242
+
243
+ export interface NonoOptions {
244
+ /** The nono binary. Default: `nono` found on PATH. */
245
+ readonly binary?: string;
246
+ /** The platform nono runs on. Default: this one. */
247
+ readonly platform?: NodeJS.Platform;
248
+ }
249
+
250
+ export function nono(options: NonoOptions = {}): Sandbox<NonoManifest> {
251
+ const binary = options.binary ?? Bun.which("nono") ?? undefined;
252
+ const platform = options.platform ?? process.platform;
253
+ let probed: Promise<boolean> | undefined;
254
+ const system = systemReads(platform).map(expanded);
255
+
256
+ const manifest = (given: BoxSpec): NonoManifest => {
257
+ // Relative paths are read from the box's working directory, which is where nono is run: the same
258
+ // place for the flags and for the check below.
259
+ const spec = anchoredSpec(given);
260
+ // A socket is granted for reading as well, so it is a place the box may read; so is every place
261
+ // the profile grants on its own.
262
+ const granted = [
263
+ ...[spec.cwd, ...spec.read, ...spec.write, ...spec.sockets].map((place) => ({ place: expanded(place), by: place })),
264
+ ...[...system, ...systemWrites(platform).map(expanded)].map((place) => ({ place, by: `${place} (a system place every box uses)` })),
265
+ ];
266
+ const carved = spec.closed.flatMap((closed) => {
267
+ const boundary = expanded(closed);
268
+ const inside = granted.find(({ place }) => covers(place, boundary) || covers(boundary, place));
269
+ if (inside === undefined) return [];
270
+ const message = covers(inside.place, boundary)
271
+ ? `nono cannot keep ${closed} closed inside ${inside.by}, which the box may use: its reads are an allow-list`
272
+ : `nono cannot open ${inside.by} inside ${closed}, which is closed`;
273
+ return [{ code: "adapter" as const, message }];
274
+ });
275
+ if (carved.length > 0) throw new BoxRefused(carved, "nono");
276
+ const net = spec.net.length === 0 ? ["--block-net"] : spec.net.flatMap((host) => ["--allow-domain", host]);
277
+ return {
278
+ sandbox: "nono",
279
+ cwd: spec.cwd,
280
+ env: spec.env,
281
+ policy: {
282
+ write: distinct(spec.write.map(homeExpanded)),
283
+ devices: systemWrites(platform),
284
+ read: { only: distinct([...[spec.cwd, ...spec.read, ...spec.write, ...spec.sockets].map(homeExpanded), ...systemReads(platform)]) },
285
+ net: spec.net,
286
+ },
287
+ profile: profileFor(platform),
288
+ flags: [
289
+ "--silent",
290
+ "--read", spec.cwd,
291
+ ...spec.read.flatMap((path) => grant(path, "read")),
292
+ ...spec.write.flatMap((path) => grant(path, "write")),
293
+ ...spec.sockets.flatMap((path) => ["--allow-unix-socket", path]),
294
+ ...net,
295
+ ],
296
+ };
297
+ };
298
+
299
+ /**
300
+ * The wrapper's own command, up to the one it runs, and the clean-up of the profile file it names.
301
+ * The file is the host's: written to a directory made for it, readable by this user only.
302
+ */
303
+ const wrapped = async (config: NonoManifest) => {
304
+ if (!binary) throw new SandboxUnavailable("nono", "the nono binary is not on PATH");
305
+ const dir = await mkdtemp(join(tmpdir(), "niwa-nono-"));
306
+ const cleanup = () => rm(dir, { recursive: true, force: true });
307
+ try {
308
+ const path = join(dir, "profile.json");
309
+ await writeFile(path, JSON.stringify(config.profile), { mode: 0o600 });
310
+ return { command: [binary, "run", "--profile", path, ...config.flags, "--"], profile: path, cleanup };
311
+ } catch (error) {
312
+ await cleanup();
313
+ throw error;
314
+ }
315
+ };
316
+
317
+ return {
318
+ name: "nono",
319
+ class: "process",
320
+ manifest,
321
+ available() {
322
+ probed ??= (async () => {
323
+ if (!binary) return false;
324
+ const dir = await mkdtemp(join(tmpdir(), "niwa-nono-probe-"));
325
+ let cleanup: (() => Promise<void>) | undefined;
326
+ try {
327
+ const wrapper = await wrapped(manifest(boxSpec({ cwd: dir })));
328
+ cleanup = wrapper.cleanup;
329
+ if (!resolvesAsSaid(binary, wrapper.profile, platform)) return false;
330
+ return await probe("nono", wrapper.command, dir, launcherEnv(), TRUSTED_DIRECTORY);
331
+ } finally {
332
+ await cleanup?.();
333
+ await rm(dir, { recursive: true, force: true });
334
+ }
335
+ })();
336
+ return probed;
337
+ },
338
+ async launch(spec, argv, options) {
339
+ const config = manifest(spec);
340
+ const wrapper = await wrapped(config);
341
+ try {
342
+ return spawnBox("nono", wrapper.command, { cwd: config.cwd, env: config.env, argv: proxyCommand(spec.net, argv) }, launcherEnv(), TRUSTED_DIRECTORY, wrapper.cleanup, options);
343
+ } catch (error) {
344
+ await wrapper.cleanup();
345
+ throw error;
346
+ }
347
+ },
348
+ };
349
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,31 @@
1
+ /** Where a relative path of a spec is read from, said once: the sandboxes and their checks all use it. */
2
+
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join, resolve } from "node:path";
5
+
6
+ import { boxSpec } from "./spec.ts";
7
+ import type { BoxSpec } from "./spec.ts";
8
+
9
+ /**
10
+ * The path a spec entry names, absolute. A relative one is taken from `base`, never from whatever
11
+ * directory the host happens to be in; `~` is left for the sandbox to expand.
12
+ */
13
+ export function anchored(path: string, base: string): string {
14
+ return path === "~" || path.startsWith("~/") || isAbsolute(path) ? path : resolve(base, path);
15
+ }
16
+
17
+ /**
18
+ * The working directory of a spec, absolute: the one place the host's own directory is consulted,
19
+ * and the one place a leading `~` is expanded here, since every relative path is read from the result.
20
+ */
21
+ export function workingDirectory(cwd: string): string {
22
+ if (cwd === "~" || cwd.startsWith("~/")) return join(homedir(), cwd.slice(2));
23
+ return anchored(cwd, process.cwd());
24
+ }
25
+
26
+ /** The spec with every relative path made absolute against its working directory. */
27
+ export function anchoredSpec(spec: BoxSpec): BoxSpec {
28
+ const cwd = workingDirectory(spec.cwd);
29
+ const within = (paths: readonly string[]) => paths.map((path) => anchored(path, cwd));
30
+ return boxSpec({ ...spec, cwd, read: within(spec.read), write: within(spec.write), closed: within(spec.closed), sockets: within(spec.sockets) });
31
+ }
package/src/profile.ts ADDED
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Profiles: the paths a tool or a harness needs, and nothing about why.
3
+ *
4
+ * A profile is the places a program reads, writes and reaches. It is a plain object, or a
5
+ * function of the machine it is resolved on (`home`, the environment, and `bin` to find a
6
+ * program). It says nothing of what its paths hold: a profile is taken whole or not at all.
7
+ */
8
+
9
+ import { realpathSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
12
+
13
+ /** What a profile names: the places read, the places written (and read), the hosts reached. */
14
+ export interface ProfilePaths {
15
+ readonly read?: readonly string[];
16
+ readonly write?: readonly string[];
17
+ readonly net?: readonly string[];
18
+ }
19
+
20
+ /** What a profile is resolved against: the machine it runs on. */
21
+ export interface ProfileContext {
22
+ /** The real home directory of the user. */
23
+ readonly home: string;
24
+ readonly env: Readonly<Record<string, string | undefined>>;
25
+ /**
26
+ * A program found through the PATH of `env`, or given by its absolute path (a runtime, an
27
+ * installed package): the path, its real path, and the root of the package it belongs to when it
28
+ * lies in a `node_modules`. Empty when it is not there. What it gives is never closed to another
29
+ * box: a profile names programs through it, and its own data without it.
30
+ */
31
+ bin(name: string): readonly string[];
32
+ }
33
+
34
+ /** A profile: its paths, or how to find them on a machine. Paths are absolute or start with `~`. */
35
+ export type BoxProfile = ProfilePaths | ((context: ProfileContext) => ProfilePaths);
36
+
37
+ /** A profile resolved on a machine: every path absolute, and the paths that are programs told apart. */
38
+ export interface ResolvedProfile {
39
+ readonly read: readonly string[];
40
+ readonly write: readonly string[];
41
+ readonly net: readonly string[];
42
+ /** The paths `bin` gave: programs and their packages, which are never closed to other boxes. */
43
+ readonly programs: readonly string[];
44
+ }
45
+
46
+ /** A path with `~` made the home directory. */
47
+ export function homeExpanded(path: string, home: string = homedir()): string {
48
+ if (path === "~") return home;
49
+ if (path.startsWith("~/")) return join(home, path.slice(2));
50
+ return path;
51
+ }
52
+
53
+ /**
54
+ * A path as a sandbox sees it: absolute, `~` expanded, and the links of its longest existing part
55
+ * resolved, so a link cannot name a place under a name that hides it.
56
+ */
57
+ export function realPlace(path: string, home: string = homedir()): string {
58
+ return resolvedLinks(resolve(homeExpanded(path, home)));
59
+ }
60
+
61
+ function resolvedLinks(absolute: string): string {
62
+ try {
63
+ return realpathSync(absolute);
64
+ } catch {
65
+ const parent = dirname(absolute);
66
+ return parent === absolute ? absolute : join(resolvedLinks(parent), basename(absolute));
67
+ }
68
+ }
69
+
70
+ /**
71
+ * A path with the links of the directories above it resolved but not its own: a program found
72
+ * through a link is run by the link's name, so the name has to stay reachable beside its target.
73
+ */
74
+ export function linkPlace(path: string, home: string = homedir()): string {
75
+ const absolute = resolve(homeExpanded(path, home));
76
+ const parent = dirname(absolute);
77
+ return parent === absolute ? absolute : join(resolvedLinks(parent), basename(absolute));
78
+ }
79
+
80
+ /** Is `path` the place `root` names, or under it? */
81
+ export function covers(root: string, path: string): boolean {
82
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
83
+ }
84
+
85
+ /** The root of the package a real path lies in, when it lies in a `node_modules`. */
86
+ function packageRoot(real: string): string | undefined {
87
+ const parts = real.split(sep);
88
+ const at = parts.lastIndexOf("node_modules");
89
+ if (at < 0 || at + 1 >= parts.length) return undefined;
90
+ const scoped = parts[at + 1]?.startsWith("@") === true;
91
+ const end = at + (scoped ? 3 : 2);
92
+ return end > parts.length ? undefined : parts.slice(0, end).join(sep);
93
+ }
94
+
95
+ /**
96
+ * A program on the PATH of `env`, or a program, runtime or installed package given by its absolute
97
+ * path: where it is, its real path, and its package. Nothing when it is not there.
98
+ */
99
+ export function programPaths(name: string, env: Readonly<Record<string, string | undefined>>): string[] {
100
+ const found = isAbsolute(name) ? name : Bun.which(name, { PATH: env["PATH"] ?? "" });
101
+ if (found === null) return [];
102
+ let real: string;
103
+ try {
104
+ real = realpathSync(found);
105
+ } catch {
106
+ return [];
107
+ }
108
+ const root = packageRoot(real);
109
+ return [...new Set([found, real, ...(root === undefined ? [] : [root])])];
110
+ }
111
+
112
+ /** The paths of a profile, checked: absolute or under `~`, never relative to wherever the host happens to be. */
113
+ function checked(paths: readonly string[] | undefined, home: string, of: string): string[] {
114
+ return (paths ?? []).map((path) => {
115
+ const expanded = homeExpanded(path, home);
116
+ if (!isAbsolute(expanded)) throw new TypeError(`profile ${of}: ${JSON.stringify(path)} is neither absolute nor under ~`);
117
+ return resolve(expanded);
118
+ });
119
+ }
120
+
121
+ /** Resolves a profile on this machine. `of` names it in errors. */
122
+ export function resolveProfile(profile: BoxProfile, of: string, machine: { home: string; env: Readonly<Record<string, string | undefined>> }): ResolvedProfile {
123
+ const programs: string[] = [];
124
+ const context: ProfileContext = {
125
+ home: machine.home,
126
+ env: machine.env,
127
+ bin(name) {
128
+ const paths = programPaths(name, machine.env);
129
+ programs.push(...paths);
130
+ return paths;
131
+ },
132
+ };
133
+ const paths = typeof profile === "function" ? profile(context) : profile;
134
+ return {
135
+ read: checked(paths.read, machine.home, of),
136
+ write: checked(paths.write, machine.home, of),
137
+ net: [...(paths.net ?? [])],
138
+ programs: [...new Set(programs)],
139
+ };
140
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The catalog: profiles of the common tools, as data.
3
+ *
4
+ * Each names the program and the places the tool keeps its configuration and its caches under the
5
+ * user's home. A box that takes a profile gets those places; a box that does not take it finds them
6
+ * closed, but for what the profile reads (its program, its configuration) when the box takes the
7
+ * toolchains: a tool runs there, and what it writes stays closed. The catalog is small on purpose:
8
+ * a host or a plugin adds the tools it needs with `sandbox({ profiles })`.
9
+ */
10
+
11
+ import type { BoxProfile } from "./profile.ts";
12
+
13
+ export type { BoxProfile, ProfileContext, ProfilePaths } from "./profile.ts";
14
+
15
+ /**
16
+ * git: the program and the user's configuration, its ignores and attributes. The credentials git's
17
+ * store keeps are written by it, so they stay git's: a box that does not take git does not read them.
18
+ */
19
+ export const git: BoxProfile = ({ home, env, bin }) => {
20
+ const config = `${env["XDG_CONFIG_HOME"] ?? `${home}/.config`}/git`;
21
+ return {
22
+ read: [...bin("git"), `${home}/.gitconfig`, `${config}/config`, `${config}/ignore`, `${config}/attributes`],
23
+ write: [`${home}/.git-credentials`, `${config}/credentials`],
24
+ };
25
+ };
26
+
27
+ /** node: the runtime. */
28
+ export const node: BoxProfile = ({ bin }) => ({ read: bin("node") });
29
+
30
+ /** bun: the runtime, its configuration and its install cache. */
31
+ export const bun: BoxProfile = ({ home, env, bin }) => ({
32
+ read: [...bin("bun"), `${home}/.bunfig.toml`],
33
+ write: [env["BUN_INSTALL_CACHE_DIR"] ?? `${env["BUN_INSTALL"] ?? `${home}/.bun`}/install/cache`],
34
+ });
35
+
36
+ /**
37
+ * npm: the program, the runtime it runs on, the cache, and the user's configuration, which npm
38
+ * writes (`npm login`, `npm config set`) and which may hold a registry's token: a box that does not
39
+ * take npm does not read it, toolchains or not.
40
+ */
41
+ export const npm: BoxProfile = ({ home, env, bin }) => ({
42
+ read: [...bin("npm"), ...bin("node")],
43
+ write: [env["npm_config_cache"] ?? env["NPM_CONFIG_CACHE"] ?? `${home}/.npm`, env["NPM_CONFIG_USERCONFIG"] ?? `${home}/.npmrc`],
44
+ });
45
+
46
+ /** cargo: the programs, the toolchains rustup installed, and the registry and git caches. */
47
+ export const cargo: BoxProfile = ({ home, env, bin }) => {
48
+ const cargoHome = env["CARGO_HOME"] ?? `${home}/.cargo`;
49
+ return {
50
+ read: [...bin("cargo"), ...bin("rustc"), `${cargoHome}/config.toml`, env["RUSTUP_HOME"] ?? `${home}/.rustup`],
51
+ write: [`${cargoHome}/registry`, `${cargoHome}/git`],
52
+ };
53
+ };
54
+
55
+ /** uv: the program, its configuration, the Pythons it installs and its cache. */
56
+ export const uv: BoxProfile = ({ home, env, bin }) => ({
57
+ read: [...bin("uv"), `${env["XDG_CONFIG_HOME"] ?? `${home}/.config`}/uv`],
58
+ write: [env["UV_CACHE_DIR"] ?? `${env["XDG_CACHE_HOME"] ?? `${home}/.cache`}/uv`, env["UV_PYTHON_INSTALL_DIR"] ?? `${env["XDG_DATA_HOME"] ?? `${home}/.local/share`}/uv`],
59
+ });
60
+
61
+ /** Every profile of the catalog, by its name. */
62
+ export const catalog = { git, node, bun, npm, cargo, uv } as const satisfies Readonly<Record<string, BoxProfile>>;