@pmndre/pine 0.0.0-stage → 0.22.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.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/bin/pine.js +27 -0
  4. package/docs/SKILL.md +234 -0
  5. package/docs/references/agents.md +454 -0
  6. package/docs/references/coding.md +311 -0
  7. package/docs/references/computer.md +212 -0
  8. package/docs/references/configuration.md +310 -0
  9. package/docs/references/events.md +267 -0
  10. package/docs/references/mcp.md +420 -0
  11. package/docs/references/operations.md +394 -0
  12. package/docs/references/overview.md +195 -0
  13. package/docs/references/security.md +896 -0
  14. package/docs/references/setup.md +385 -0
  15. package/docs/references/sources.md +772 -0
  16. package/docs/references/stack.md +121 -0
  17. package/docs/references/tui.md +575 -0
  18. package/examples/home/.env.example +7 -0
  19. package/examples/home/USER.md +4 -0
  20. package/examples/home/agents/main/agent.json +4 -0
  21. package/examples/home/agents/main/workspace/AGENTS.md +14 -0
  22. package/examples/home/agents/main/workspace/MEMORY.md +4 -0
  23. package/examples/home/agents/main/workspace/SOUL.md +4 -0
  24. package/examples/home/models.json +62 -0
  25. package/examples/home/pine.json +34 -0
  26. package/examples/home/skills/README.txt +7 -0
  27. package/examples/launchd/com.pine.daemon.plist +32 -0
  28. package/examples/systemd/pine.service +22 -0
  29. package/mcp/browser.d.ts +99 -0
  30. package/mcp/browser.js +496 -0
  31. package/mcp/commands.d.ts +20 -0
  32. package/mcp/commands.js +88 -0
  33. package/mcp/computer.d.ts +139 -0
  34. package/mcp/computer.js +698 -0
  35. package/mcp/computer.swift +989 -0
  36. package/mcp/lib.d.ts +23 -0
  37. package/mcp/lib.js +52 -0
  38. package/mcp/web.d.ts +6 -0
  39. package/mcp/web.js +140 -0
  40. package/package.json +32 -4
  41. package/src/access.d.ts +112 -0
  42. package/src/access.js +438 -0
  43. package/src/actions.d.ts +75 -0
  44. package/src/actions.js +167 -0
  45. package/src/admin.d.ts +167 -0
  46. package/src/admin.js +625 -0
  47. package/src/agent-admin.d.ts +24 -0
  48. package/src/agent-admin.js +55 -0
  49. package/src/agents.d.ts +540 -0
  50. package/src/agents.js +2776 -0
  51. package/src/background.d.ts +29 -0
  52. package/src/background.js +100 -0
  53. package/src/cli.d.ts +2 -0
  54. package/src/cli.js +777 -0
  55. package/src/computer.d.ts +30 -0
  56. package/src/computer.js +32 -0
  57. package/src/config.d.ts +396 -0
  58. package/src/config.js +549 -0
  59. package/src/dev/claude-model.d.ts +37 -0
  60. package/src/dev/claude-model.js +204 -0
  61. package/src/env-file.d.ts +4 -0
  62. package/src/env-file.js +40 -0
  63. package/src/goals.d.ts +133 -0
  64. package/src/goals.js +316 -0
  65. package/src/http.d.ts +46 -0
  66. package/src/http.js +509 -0
  67. package/src/limiter.d.ts +32 -0
  68. package/src/limiter.js +84 -0
  69. package/src/login.d.ts +23 -0
  70. package/src/login.js +130 -0
  71. package/src/manual.d.ts +61 -0
  72. package/src/manual.js +443 -0
  73. package/src/mcp-config.d.ts +49 -0
  74. package/src/mcp-config.js +182 -0
  75. package/src/models.d.ts +90 -0
  76. package/src/models.js +274 -0
  77. package/src/net.d.ts +50 -0
  78. package/src/net.js +150 -0
  79. package/src/pine.d.ts +32 -0
  80. package/src/pine.js +134 -0
  81. package/src/programs.d.ts +123 -0
  82. package/src/programs.js +412 -0
  83. package/src/router.d.ts +56 -0
  84. package/src/router.js +164 -0
  85. package/src/sandbox-fs.d.ts +34 -0
  86. package/src/sandbox-fs.js +186 -0
  87. package/src/sandbox-linux.d.ts +96 -0
  88. package/src/sandbox-linux.js +297 -0
  89. package/src/sandbox-setup.d.ts +70 -0
  90. package/src/sandbox-setup.js +216 -0
  91. package/src/security.d.ts +238 -0
  92. package/src/security.js +660 -0
  93. package/src/skills.d.ts +67 -0
  94. package/src/skills.js +163 -0
  95. package/src/snapshots.d.ts +68 -0
  96. package/src/snapshots.js +306 -0
  97. package/src/source-types.d.ts +61 -0
  98. package/src/source-types.js +1 -0
  99. package/src/sources/command.d.ts +4 -0
  100. package/src/sources/command.js +77 -0
  101. package/src/sources/folder.d.ts +6 -0
  102. package/src/sources/folder.js +116 -0
  103. package/src/sources/ftp.d.ts +4 -0
  104. package/src/sources/ftp.js +307 -0
  105. package/src/sources/http.d.ts +4 -0
  106. package/src/sources/http.js +201 -0
  107. package/src/sources/mqtt.d.ts +18 -0
  108. package/src/sources/mqtt.js +97 -0
  109. package/src/sources/telegram.d.ts +22 -0
  110. package/src/sources/telegram.js +283 -0
  111. package/src/sources/webhook.d.ts +4 -0
  112. package/src/sources/webhook.js +52 -0
  113. package/src/sources.d.ts +344 -0
  114. package/src/sources.js +966 -0
  115. package/src/store.d.ts +99 -0
  116. package/src/store.js +277 -0
  117. package/src/timers.d.ts +83 -0
  118. package/src/timers.js +318 -0
  119. package/src/tools.d.ts +11 -0
  120. package/src/tools.js +1297 -0
  121. package/src/tui/app.d.ts +305 -0
  122. package/src/tui/app.js +3195 -0
  123. package/src/tui/client.d.ts +236 -0
  124. package/src/tui/client.js +131 -0
  125. package/src/tui/code-pane.d.ts +68 -0
  126. package/src/tui/code-pane.js +535 -0
  127. package/src/tui/highlight.d.ts +8 -0
  128. package/src/tui/highlight.js +86 -0
  129. package/src/tui/picture.d.ts +206 -0
  130. package/src/tui/picture.js +801 -0
  131. package/src/tui/run.d.ts +8 -0
  132. package/src/tui/run.js +97 -0
  133. package/src/tui/theme.d.ts +32 -0
  134. package/src/tui/theme.js +128 -0
  135. package/src/tui/undo.d.ts +5 -0
  136. package/src/tui/undo.js +50 -0
  137. package/src/tui/voice.d.ts +49 -0
  138. package/src/tui/voice.js +155 -0
  139. package/src/tui/voice.swift +223 -0
  140. package/src/types.d.ts +139 -0
  141. package/src/types.js +1 -0
  142. package/src/undo.d.ts +224 -0
  143. package/src/undo.js +465 -0
  144. package/src/update.d.ts +35 -0
  145. package/src/update.js +130 -0
  146. package/src/util.d.ts +65 -0
  147. package/src/util.js +171 -0
  148. package/src/watching.d.ts +20 -0
  149. package/src/watching.js +68 -0
  150. package/src/workspace-view.d.ts +72 -0
  151. package/src/workspace-view.js +221 -0
@@ -0,0 +1,186 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ import { createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition, defineTool } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { bin, tilde } from "./security.js";
6
+ const MAX_READ = 50 * 1024 * 1024;
7
+ const MAX_OUT = 40_000;
8
+ export function sandboxExec(fs, argv, opts = {}) {
9
+ return new Promise((resolve, reject) => {
10
+ // Empty where the call meets no sandbox ("auto" and "bypass" mode): the program runs as it is.
11
+ const jail = fs.prefix();
12
+ // The programs are named by where they lie on this system, never looked up on a PATH an agent could shape.
13
+ const argv0 = [...jail, bin(path.basename(argv[0])), ...argv.slice(1)];
14
+ const child = spawn(argv0[0], argv0.slice(1), { cwd: fs.cwd, env: fs.env(), stdio: ["pipe", "pipe", "pipe"] });
15
+ const max = opts.maxBytes ?? MAX_READ;
16
+ const chunks = [];
17
+ let size = 0;
18
+ let truncated = false;
19
+ let stderr = "";
20
+ child.stdout.on("data", (d) => {
21
+ if (size + d.length > max) {
22
+ truncated = true;
23
+ chunks.push(d.subarray(0, Math.max(0, max - size)));
24
+ size = max;
25
+ child.kill("SIGKILL");
26
+ }
27
+ else {
28
+ chunks.push(d);
29
+ size += d.length;
30
+ }
31
+ });
32
+ child.stderr.on("data", (d) => (stderr.length < 4000 ? (stderr += d.toString("utf8")) : undefined));
33
+ const timer = setTimeout(() => child.kill("SIGKILL"), opts.timeoutMs ?? 60_000);
34
+ const onAbort = () => child.kill("SIGKILL");
35
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
36
+ child.on("error", (e) => (clearTimeout(timer), reject(e)));
37
+ child.on("close", (code) => {
38
+ clearTimeout(timer);
39
+ opts.signal?.removeEventListener("abort", onAbort);
40
+ resolve({ code: code ?? (truncated ? 0 : 1), stdout: Buffer.concat(chunks), stderr, truncated });
41
+ });
42
+ child.stdin.on("error", () => { });
43
+ child.stdin.end(opts.stdin ?? "");
44
+ });
45
+ }
46
+ function explain(file, stderr) {
47
+ if (/Operation not permitted|Permission denied|Read-only file system|Device or resource busy/.test(stderr))
48
+ return new Error(`${file}: not permitted. Your file access is limited to your workspace.`);
49
+ if (/No such file or directory/.test(stderr))
50
+ return Object.assign(new Error(`ENOENT: no such file or directory, open '${file}'`), { code: "ENOENT" });
51
+ if (/Is a directory/.test(stderr))
52
+ return Object.assign(new Error(`EISDIR: ${file} is a directory`), { code: "EISDIR" });
53
+ return new Error(`${file}: ${stderr.trim().split("\n")[0] || "operation failed"}`);
54
+ }
55
+ export function sniffImage(head) {
56
+ if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
57
+ return "image/png";
58
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff)
59
+ return "image/jpeg";
60
+ if (head.length >= 6 && ["GIF87a", "GIF89a"].includes(head.subarray(0, 6).toString("latin1")))
61
+ return "image/gif";
62
+ if (head.length >= 12 && head.subarray(0, 4).toString("latin1") === "RIFF" && head.subarray(8, 12).toString("latin1") === "WEBP")
63
+ return "image/webp";
64
+ return null;
65
+ }
66
+ const text = (s) => ({ content: [{ type: "text", text: s }], details: undefined });
67
+ const clip = (s) => (s.length > MAX_OUT ? `${s.slice(0, MAX_OUT)}\n[output cut at ${MAX_OUT} characters; narrow the search]` : s);
68
+ /** read, write, edit, grep, find and ls, all executed inside the sandbox. */
69
+ export function sandboxedFileTools(fs, enabled) {
70
+ const readFile = async (file) => {
71
+ const r = await sandboxExec(fs, ["/bin/cat", "--", file]);
72
+ if (r.code !== 0 && !r.truncated)
73
+ throw explain(file, r.stderr);
74
+ return r.stdout;
75
+ };
76
+ /** A call that writes. What it made although the run may not make it is gone again afterwards, and the call fails. */
77
+ const writing = async (file, argv, stdin) => {
78
+ const guard = fs.guard?.();
79
+ let r;
80
+ let gone = [];
81
+ try {
82
+ r = await sandboxExec(fs, argv, { stdin });
83
+ }
84
+ finally {
85
+ gone = guard?.restore() ?? [];
86
+ }
87
+ if (gone.length)
88
+ throw explain(file, "Operation not permitted");
89
+ if (r.code !== 0)
90
+ throw explain(file, r.stderr);
91
+ };
92
+ const writeFile = (file, content) => writing(file, ["/bin/sh", "-c", 'cat > "$1"', "sh", file], content);
93
+ // Opening the file is the only check that tells "missing" from "not permitted".
94
+ const readable = async (file) => {
95
+ const r = await sandboxExec(fs, ["/usr/bin/head", "-c", "1", "--", file], { maxBytes: 16 });
96
+ if (r.code !== 0)
97
+ throw explain(file, r.stderr || "No such file or directory");
98
+ };
99
+ const writable = async (file) => {
100
+ await readable(file);
101
+ const r = await sandboxExec(fs, ["/bin/test", "-w", file]);
102
+ if (r.code !== 0)
103
+ throw explain(file, "Permission denied");
104
+ };
105
+ // "~" is the owner's home, as pi's read, write and edit take it.
106
+ const resolve = (p) => path.resolve(fs.cwd, tilde(p && p.length ? p : "."));
107
+ const tools = {
108
+ read: () => createReadToolDefinition(fs.cwd, {
109
+ operations: {
110
+ readFile,
111
+ access: readable,
112
+ detectImageMimeType: async (file) => sniffImage((await sandboxExec(fs, ["/usr/bin/head", "-c", "16", "--", file])).stdout),
113
+ },
114
+ }),
115
+ write: () => createWriteToolDefinition(fs.cwd, {
116
+ operations: {
117
+ writeFile,
118
+ mkdir: (dir) => writing(dir, ["/bin/mkdir", "-p", "--", dir]),
119
+ },
120
+ }),
121
+ edit: () => createEditToolDefinition(fs.cwd, { operations: { readFile, writeFile, access: writable } }),
122
+ ls: () => defineTool({
123
+ name: "ls",
124
+ label: "ls",
125
+ description: "List the entries of a directory. Directories end with /.",
126
+ parameters: Type.Object({ path: Type.Optional(Type.String({ description: "Directory, default: your workspace" })), limit: Type.Optional(Type.Number({ description: "Maximum entries, default 500" })) }),
127
+ execute: async (_id, p, signal) => {
128
+ const dir = resolve(p.path);
129
+ const r = await sandboxExec(fs, ["/bin/ls", "-1Ap", "--", dir], { signal, maxBytes: 2_000_000 });
130
+ if (r.code !== 0)
131
+ throw explain(p.path ?? ".", r.stderr);
132
+ const entries = r.stdout.toString("utf8").split("\n").filter(Boolean);
133
+ const limit = Math.max(1, Math.min(Number(p.limit) || 500, 5000));
134
+ return text(entries.length ? entries.slice(0, limit).join("\n") + (entries.length > limit ? `\n[${entries.length - limit} more entries]` : "") : "(empty directory)");
135
+ },
136
+ }),
137
+ find: () => defineTool({
138
+ name: "find",
139
+ label: "find",
140
+ description: "Find files by name. The pattern is a glob such as *.md or src/*.ts; .git and node_modules are skipped.",
141
+ parameters: Type.Object({ pattern: Type.String(), path: Type.Optional(Type.String({ description: "Directory to search, default: your workspace" })), limit: Type.Optional(Type.Number({ description: "Maximum results, default 200" })) }),
142
+ execute: async (_id, p, signal) => {
143
+ const dir = resolve(p.path);
144
+ const match = p.pattern.includes("/") ? ["-path", `*${p.pattern.replace(/^\.?\//, "")}`] : ["-name", p.pattern];
145
+ const r = await sandboxExec(fs, ["/usr/bin/find", dir, "(", "-name", ".git", "-o", "-name", "node_modules", ")", "-prune", "-o", ...match, "-print"], { signal, maxBytes: 4_000_000 });
146
+ const lines = r.stdout.toString("utf8").split("\n").filter(Boolean).map((f) => path.relative(dir, f) || ".");
147
+ if (!lines.length && r.code !== 0 && r.stderr)
148
+ throw explain(p.path ?? ".", r.stderr);
149
+ const limit = Math.max(1, Math.min(Number(p.limit) || 200, 2000));
150
+ return text(lines.length ? clip(lines.slice(0, limit).join("\n") + (lines.length > limit ? `\n[${lines.length - limit} more results]` : "")) : "no files found");
151
+ },
152
+ }),
153
+ grep: () => defineTool({
154
+ name: "grep",
155
+ label: "grep",
156
+ description: "Search file contents with a regular expression. Returns file:line:text. .git and node_modules are skipped.",
157
+ parameters: Type.Object({
158
+ pattern: Type.String({ description: "Regular expression (extended syntax)" }),
159
+ path: Type.Optional(Type.String({ description: "File or directory, default: your workspace" })),
160
+ glob: Type.Optional(Type.String({ description: "Only files whose name matches, for example *.md" })),
161
+ ignoreCase: Type.Optional(Type.Boolean()),
162
+ literal: Type.Optional(Type.Boolean({ description: "Treat the pattern as plain text" })),
163
+ context: Type.Optional(Type.Number({ description: "Lines of context around each match" })),
164
+ limit: Type.Optional(Type.Number({ description: "Maximum output lines, default 200" })),
165
+ }),
166
+ execute: async (_id, p, signal) => {
167
+ const target = resolve(p.path);
168
+ const args = ["-rnI", p.literal ? "-F" : "-E", "--exclude-dir=.git", "--exclude-dir=node_modules"];
169
+ if (p.ignoreCase)
170
+ args.push("-i");
171
+ if (p.glob)
172
+ args.push(`--include=${p.glob}`);
173
+ if (Number(p.context) > 0)
174
+ args.push("-C", String(Math.min(Number(p.context), 20)));
175
+ const r = await sandboxExec(fs, ["/usr/bin/grep", ...args, "-e", p.pattern, "--", target], { signal, maxBytes: 4_000_000 });
176
+ if (r.code > 1 && !r.stdout.length)
177
+ throw explain(p.path ?? ".", r.stderr);
178
+ const prefix = target.endsWith(path.sep) ? target : target + path.sep;
179
+ const lines = r.stdout.toString("utf8").split("\n").filter(Boolean).map((l) => (l.startsWith(prefix) ? l.slice(prefix.length) : l));
180
+ const limit = Math.max(1, Math.min(Number(p.limit) || 200, 2000));
181
+ return text(lines.length ? clip(lines.slice(0, limit).join("\n") + (lines.length > limit ? `\n[${lines.length - limit} more lines]` : "")) : "no matches");
182
+ },
183
+ }),
184
+ };
185
+ return enabled.filter((name) => tools[name]).map((name) => tools[name]());
186
+ }
@@ -0,0 +1,96 @@
1
+ export interface Jail {
2
+ /** The owner's home folder: closed, except for what is listed below. */
3
+ userHome: string;
4
+ /** pine's home folder: closed wherever it lies, except for the agent's own folders. */
5
+ pineHome: string;
6
+ /** pine's program files: never writable. */
7
+ pineCode: string;
8
+ read: string[];
9
+ write: string[];
10
+ ownedRead: string[];
11
+ ownedWrite: string[];
12
+ /** Closed even where a wider rule would open them. */
13
+ closed: string[];
14
+ /**
15
+ * Folders in which the services of the machine listen (/run). They stay readable, but the
16
+ * sockets in them are covered, for the case that the network (and with it sockets) is
17
+ * granted: behind them are the container daemon and the system bus. Default: `SHARED`.
18
+ */
19
+ shared?: string[];
20
+ network: boolean;
21
+ variant: "normal" | "restricted";
22
+ /** For a run that has read outside content: what exists and may not be changed, and repositories whose folder may not be moved aside. */
23
+ frozen?: {
24
+ paths: string[];
25
+ repositories: string[];
26
+ };
27
+ }
28
+ /**
29
+ * Where services of the machine and of the desktop session listen. `SESSIONS` are closed whole;
30
+ * in `SHARED` each socket is covered. Only folders whose content stays: covering something in a
31
+ * temp folder that is gone a moment later would make the command fail.
32
+ */
33
+ export declare const SHARED: string[];
34
+ export declare const SESSIONS: string[];
35
+ /**
36
+ * A system call filter (seccomp, as a compiled BPF program) that refuses to make a socket of
37
+ * the kind that connects programs on one machine (AF_UNIX), by name or by file. Pairs of
38
+ * connected sockets, which a program makes to talk to its own children, are another call and
39
+ * stay allowed. Programs built for another processor (32 bit on a 64 bit system) are refused
40
+ * whole, because they make sockets through calls this filter does not read.
41
+ * Undefined on a processor this was not written for.
42
+ */
43
+ export declare function noLocalSockets(arch?: string): Buffer | undefined;
44
+ /**
45
+ * The whole command line in front of a command: bwrap with its arguments, and with the filter
46
+ * when local sockets are to be refused. bwrap reads a filter from an open file; a shell opens
47
+ * one for it that holds the filter's bytes, so no file of pine's has to lie where it is found.
48
+ */
49
+ export declare function jailed(bwrap: string, args: string[], localSockets: boolean, arch?: string): string[];
50
+ /**
51
+ * The sockets in the shared folders, a few levels down. A read-only mount does not keep a
52
+ * program from connecting to a socket, so each is covered. Sockets made after this look are not
53
+ * covered; `--unshare-net` closes the ones that have no file at all.
54
+ */
55
+ export declare function sockets(dirs: string[], skip?: string[]): string[];
56
+ /** The arguments for bwrap, up to and including the "--" after which the command follows. */
57
+ export declare function bwrapArgs(jail: Jail): string[];
58
+ /** A helper that may read everything, write only in `write`, and has no network: git for a view, a picture converter. */
59
+ export declare function helperArgs(write: string[], shared?: string[], sessions?: string[]): string[];
60
+ export interface Protected {
61
+ /** The agent's folders in which these rules hold: its workspace, and a folder opened for the conversation. */
62
+ roots: string[];
63
+ /** Single files that may not change, wherever they lie (USER.md, the files at the top of the workspace). */
64
+ files: string[];
65
+ /** File names that may not change anywhere under a root (AGENTS.md, CLAUDE.md, ...). */
66
+ names: string[];
67
+ /** Folders at the top of a root that may not change (.pi, .agents). */
68
+ dirs: string[];
69
+ /** Single files that may change all the same: the agent's own files, once the owner has said so for the conversation. */
70
+ open?: string[];
71
+ }
72
+ /** How far down the look goes. Exported because it is a limit of the protection, and the manual states it. */
73
+ export declare const DEPTH = 6;
74
+ /**
75
+ * Every place under the roots that the rules protect and that exists right now: instruction
76
+ * files, the protected folders, and for each repository its hooks and its configuration (also of
77
+ * its submodules). Looked for `DEPTH` levels deep and not in folders of installed packages or
78
+ * build output: a tree is not searched to the bottom for every command.
79
+ */
80
+ export declare function protectedNow(p: Protected): {
81
+ paths: string[];
82
+ repositories: string[];
83
+ };
84
+ /**
85
+ * What mounts cannot forbid: making a protected file or folder that was not there. Taken before
86
+ * a command that outside content may steer; `restore` after it removes every protected path the
87
+ * command made, and says which. (What was there before is mounted read-only and cannot have changed.)
88
+ */
89
+ export declare class Guard {
90
+ private p;
91
+ private before;
92
+ constructor(p: Protected);
93
+ /** Protected paths and repositories as they are now, plus the names at the top of each root that would be protected if they existed. */
94
+ private all;
95
+ restore(): string[];
96
+ }
@@ -0,0 +1,297 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const isInside = (root, p) => p === root || p.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
4
+ const exists = (p) => {
5
+ try {
6
+ fs.lstatSync(p);
7
+ return true;
8
+ }
9
+ catch {
10
+ return false;
11
+ }
12
+ };
13
+ const isDir = (p) => {
14
+ try {
15
+ return fs.statSync(p).isDirectory();
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ /** Parents before what lies in them, so that a later mount never hides an earlier one by accident. */
22
+ const shallowFirst = (list) => [...new Set(list)].filter(exists).sort((a, b) => a.split(path.sep).length - b.split(path.sep).length || a.localeCompare(b));
23
+ /**
24
+ * Where services of the machine and of the desktop session listen. `SESSIONS` are closed whole;
25
+ * in `SHARED` each socket is covered. Only folders whose content stays: covering something in a
26
+ * temp folder that is gone a moment later would make the command fail.
27
+ */
28
+ export const SHARED = ["/run", "/var/run"];
29
+ export const SESSIONS = ["/run/user", "/tmp/.X11-unix", "/tmp/.ICE-unix"];
30
+ /**
31
+ * A system call filter (seccomp, as a compiled BPF program) that refuses to make a socket of
32
+ * the kind that connects programs on one machine (AF_UNIX), by name or by file. Pairs of
33
+ * connected sockets, which a program makes to talk to its own children, are another call and
34
+ * stay allowed. Programs built for another processor (32 bit on a 64 bit system) are refused
35
+ * whole, because they make sockets through calls this filter does not read.
36
+ * Undefined on a processor this was not written for.
37
+ */
38
+ export function noLocalSockets(arch = process.arch) {
39
+ // The processor's number in a system call's record, and the number of the socket call on it.
40
+ const known = { x64: [0xc000003e, 41], arm64: [0xc00000b7, 198] };
41
+ if (!known[arch])
42
+ return undefined;
43
+ const [processor, socket] = known[arch];
44
+ const LOAD = 0x20;
45
+ const EQUAL = 0x15;
46
+ const AT_LEAST = 0x35;
47
+ const RETURN = 0x06;
48
+ const ALLOW = 0x7fff0000;
49
+ const refuse = (errno) => 0x00050000 | errno;
50
+ // [code, jump if true, jump if false, value]; a jump counts the instructions it skips.
51
+ const program = [
52
+ [LOAD, 0, 0, 4], // which processor the call was made for
53
+ [EQUAL, 0, 7, processor], // another one: refuse (9)
54
+ [LOAD, 0, 0, 0], // which call
55
+ [AT_LEAST, 5, 0, 0x40000000], // the 32 bit calls of a 64 bit processor: refuse (9)
56
+ [EQUAL, 0, 2, socket], // not "socket": allow (7)
57
+ [LOAD, 0, 0, 16], // its first argument: the kind of socket
58
+ [EQUAL, 1, 0, 1], // AF_UNIX: refuse (8)
59
+ [RETURN, 0, 0, ALLOW],
60
+ [RETURN, 0, 0, refuse(1)], // "Operation not permitted"
61
+ [RETURN, 0, 0, refuse(38)], // "Function not implemented"
62
+ ];
63
+ const out = Buffer.alloc(program.length * 8);
64
+ program.forEach(([code, yes, no, value], i) => {
65
+ out.writeUInt16LE(code, i * 8);
66
+ out.writeUInt8(yes, i * 8 + 2);
67
+ out.writeUInt8(no, i * 8 + 3);
68
+ out.writeUInt32LE(value >>> 0, i * 8 + 4);
69
+ });
70
+ return out;
71
+ }
72
+ /**
73
+ * The whole command line in front of a command: bwrap with its arguments, and with the filter
74
+ * when local sockets are to be refused. bwrap reads a filter from an open file; a shell opens
75
+ * one for it that holds the filter's bytes, so no file of pine's has to lie where it is found.
76
+ */
77
+ export function jailed(bwrap, args, localSockets, arch = process.arch) {
78
+ const filter = localSockets ? undefined : noLocalSockets(arch);
79
+ if (!filter)
80
+ return [bwrap, ...args];
81
+ const bash = ["/bin/bash", "/usr/bin/bash"].find(exists) ?? "bash";
82
+ const bytes = [...filter].map((b) => `\\${b.toString(8).padStart(3, "0")}`).join("");
83
+ return [bash, "-c", 'exec 9< <(printf "$0") && exec "$@"', bytes, bwrap, "--seccomp", "9", ...args];
84
+ }
85
+ /**
86
+ * The sockets in the shared folders, a few levels down. A read-only mount does not keep a
87
+ * program from connecting to a socket, so each is covered. Sockets made after this look are not
88
+ * covered; `--unshare-net` closes the ones that have no file at all.
89
+ */
90
+ export function sockets(dirs, skip = []) {
91
+ const found = [];
92
+ let seen = 0;
93
+ const walk = (dir, depth) => {
94
+ for (const e of readDir(dir)) {
95
+ if (++seen > 4000)
96
+ return;
97
+ const full = path.join(dir, e.name);
98
+ if (e.isSocket())
99
+ found.push(full);
100
+ else if (e.isDirectory() && !e.isSymbolicLink() && depth < 3 && !skip.includes(full))
101
+ walk(full, depth + 1);
102
+ }
103
+ };
104
+ for (const dir of new Set(dirs))
105
+ if (isDir(dir) && !fs.lstatSync(dir).isSymbolicLink())
106
+ walk(dir, 0);
107
+ return found.sort();
108
+ }
109
+ /**
110
+ * Where pine runs as root (a container, usually), bubblewrap would hand the command root's
111
+ * powers, and with them it could take the mounts away again. In every variant it gets none.
112
+ */
113
+ const POWERLESS = ["--cap-drop", "ALL"];
114
+ /** The arguments for bwrap, up to and including the "--" after which the command follows. */
115
+ export function bwrapArgs(jail) {
116
+ const args = [];
117
+ const ro = (p) => args.push("--ro-bind", p, p);
118
+ const rw = (p) => args.push("--bind", p, p);
119
+ /** An empty folder in place of a folder. Made read-only at the end, once the folders put back into it have their places. */
120
+ const emptied = [];
121
+ const empty = (p) => (emptied.push(p), args.push("--tmpfs", p));
122
+ const seal = () => {
123
+ for (const p of emptied)
124
+ args.push("--remount-ro", p);
125
+ };
126
+ /** Close a path that a wider mount has opened: an empty folder in place of a folder, an empty file in place of a file. */
127
+ const close = (p) => {
128
+ if (isDir(p))
129
+ empty(p);
130
+ else if (exists(p))
131
+ args.push("--ro-bind", "/dev/null", p);
132
+ };
133
+ const owned = () => {
134
+ // pine's home is closed wherever it lies; only the agent's own folders in it are put back.
135
+ if (isDir(jail.pineHome))
136
+ empty(jail.pineHome);
137
+ for (const p of shallowFirst(jail.ownedRead.filter((r) => isInside(jail.pineHome, r))))
138
+ ro(p);
139
+ for (const p of shallowFirst(jail.ownedWrite.filter((r) => isInside(jail.pineHome, r))))
140
+ rw(p);
141
+ };
142
+ // Everything can be read and nothing written; devices and /proc are the sandbox's own.
143
+ args.push("--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc");
144
+ // The owner's home is closed. What the agent was given is put back, folder by folder.
145
+ if (isDir(jail.userHome) && jail.userHome !== path.parse(jail.userHome).root)
146
+ empty(jail.userHome);
147
+ for (const p of shallowFirst(jail.read))
148
+ ro(p);
149
+ for (const p of shallowFirst(jail.write))
150
+ rw(p);
151
+ owned();
152
+ // What must stay closed although it lies inside something that was just opened. Whatever lies
153
+ // in a closed folder (pine's home, the owner's home) and was not put back is closed already.
154
+ // pine's home was closed last, so in it only the agent's own folders count as opened.
155
+ const own = [...jail.ownedRead, ...jail.ownedWrite];
156
+ const opened = [...jail.read, ...jail.write, ...own];
157
+ const hidden = (p) => (isInside(jail.pineHome, p) ? !own.some((r) => isInside(r, p)) : isInside(jail.userHome, p) && !opened.some((r) => isInside(r, p)));
158
+ for (const p of shallowFirst(jail.closed))
159
+ if (!hidden(p))
160
+ close(p);
161
+ // The services of the machine and of the desktop: what the macOS profile denies by name
162
+ // (keychain, clipboard, other programs) is reached through sockets here.
163
+ for (const p of sockets(jail.shared ?? SHARED, jail.closed))
164
+ if (!jail.closed.some((c) => isInside(c, p)))
165
+ args.push("--ro-bind", "/dev/null", p);
166
+ if (jail.variant === "restricted" && jail.frozen) {
167
+ // A repository's folder becomes a mount of its own, so that it cannot be moved aside and
168
+ // another put in its place. Then what exists and must not change is mounted read-only.
169
+ // Only where the agent can write at all: a mount would otherwise open what is closed to it.
170
+ const writable = (p) => (isInside(jail.pineHome, p) ? jail.ownedWrite : [...jail.write, ...jail.ownedWrite]).some((r) => isInside(r, p));
171
+ for (const p of shallowFirst(jail.frozen.repositories.filter(writable)))
172
+ rw(p);
173
+ for (const p of shallowFirst(jail.frozen.paths.filter(writable)))
174
+ ro(p);
175
+ }
176
+ seal();
177
+ if (!jail.network)
178
+ args.push("--unshare-net");
179
+ // Its own process list, so it sees and signals nothing but itself; gone when pine is gone;
180
+ // and no way to type into the terminal pine runs in.
181
+ args.push(...POWERLESS, "--unshare-pid", "--unshare-ipc", "--die-with-parent", "--new-session", "--");
182
+ return args;
183
+ }
184
+ /** A helper that may read everything, write only in `write`, and has no network: git for a view, a picture converter. */
185
+ export function helperArgs(write, shared = SHARED, sessions = SESSIONS) {
186
+ const args = ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc"];
187
+ for (const p of shallowFirst(write))
188
+ args.push("--bind", p, p);
189
+ for (const p of sessions)
190
+ if (isDir(p))
191
+ args.push("--tmpfs", p);
192
+ for (const p of sockets(shared, sessions))
193
+ args.push("--ro-bind", "/dev/null", p);
194
+ for (const p of sessions)
195
+ if (isDir(p))
196
+ args.push("--remount-ro", p);
197
+ args.push("--unshare-net", ...POWERLESS, "--unshare-pid", "--unshare-ipc", "--die-with-parent", "--new-session", "--");
198
+ return args;
199
+ }
200
+ /** How far down the look goes. Exported because it is a limit of the protection, and the manual states it. */
201
+ export const DEPTH = 6;
202
+ const MAX_DIRS = 20_000;
203
+ const SKIP = new Set(["node_modules", ".venv", "venv", "__pycache__", ".cache", ".npm", ".pnpm-store", ".yarn", ".gradle", ".tox", ".next", "dist", "build", "target", "DerivedData"]);
204
+ /**
205
+ * Every place under the roots that the rules protect and that exists right now: instruction
206
+ * files, the protected folders, and for each repository its hooks and its configuration (also of
207
+ * its submodules). Looked for `DEPTH` levels deep and not in folders of installed packages or
208
+ * build output: a tree is not searched to the bottom for every command.
209
+ */
210
+ export function protectedNow(p) {
211
+ const paths = new Set(p.files.filter(exists));
212
+ const repositories = new Set();
213
+ let seen = 0;
214
+ const repository = (git) => {
215
+ if (!isDir(git))
216
+ return; // a submodule's or worktree's ".git" is a file that points elsewhere
217
+ repositories.add(git);
218
+ for (const name of ["hooks", "config"])
219
+ if (exists(path.join(git, name)))
220
+ paths.add(path.join(git, name));
221
+ // Submodules keep their own hooks and configuration under modules/.
222
+ const walk = (dir, depth) => {
223
+ if (depth > 4 || !isDir(dir))
224
+ return;
225
+ for (const name of ["hooks", "config"])
226
+ if (exists(path.join(dir, name)) && exists(path.join(dir, "HEAD")))
227
+ paths.add(path.join(dir, name));
228
+ for (const e of readDir(dir))
229
+ if (e.isDirectory() && !["hooks", "objects", "refs", "logs", "info"].includes(e.name))
230
+ walk(path.join(dir, e.name), depth + 1);
231
+ };
232
+ walk(path.join(git, "modules"), 0);
233
+ };
234
+ const visit = (dir, depth, top) => {
235
+ if (++seen > MAX_DIRS)
236
+ return;
237
+ for (const e of readDir(dir)) {
238
+ const full = path.join(dir, e.name);
239
+ if (e.name === ".git")
240
+ repository(full);
241
+ else if (top && p.dirs.includes(e.name))
242
+ paths.add(full);
243
+ else if (!e.isDirectory() && p.names.includes(e.name))
244
+ paths.add(full);
245
+ else if (e.isDirectory() && !e.isSymbolicLink() && depth < DEPTH && !SKIP.has(e.name))
246
+ visit(full, depth + 1, false);
247
+ }
248
+ };
249
+ for (const root of p.roots)
250
+ if (isDir(root))
251
+ visit(root, 0, true);
252
+ for (const file of p.open ?? [])
253
+ paths.delete(file);
254
+ return { paths: [...paths], repositories: [...repositories] };
255
+ }
256
+ function readDir(dir) {
257
+ try {
258
+ return fs.readdirSync(dir, { withFileTypes: true });
259
+ }
260
+ catch {
261
+ return [];
262
+ }
263
+ }
264
+ /**
265
+ * What mounts cannot forbid: making a protected file or folder that was not there. Taken before
266
+ * a command that outside content may steer; `restore` after it removes every protected path the
267
+ * command made, and says which. (What was there before is mounted read-only and cannot have changed.)
268
+ */
269
+ export class Guard {
270
+ p;
271
+ before;
272
+ constructor(p) {
273
+ this.p = p;
274
+ this.before = this.all();
275
+ }
276
+ /** Protected paths and repositories as they are now, plus the names at the top of each root that would be protected if they existed. */
277
+ all() {
278
+ const now = protectedNow(this.p);
279
+ return new Set([...now.paths, ...now.repositories]);
280
+ }
281
+ restore() {
282
+ const made = [...this.all()].filter((x) => !this.before.has(x)).sort((a, b) => a.length - b.length);
283
+ const gone = [];
284
+ for (const x of made) {
285
+ if (gone.some((g) => isInside(g, x)))
286
+ continue;
287
+ try {
288
+ fs.rmSync(x, { recursive: true, force: true });
289
+ gone.push(x);
290
+ }
291
+ catch {
292
+ // what cannot be removed is reported by whoever reads the list as still there
293
+ }
294
+ }
295
+ return gone;
296
+ }
297
+ }
@@ -0,0 +1,70 @@
1
+ /** What pine init looks at. A function of this alone decides what to do, so it can be tested without a machine. */
2
+ export interface Machine {
3
+ /** Where bwrap is, when it is installed. */
4
+ bwrap?: string;
5
+ /** Whether a sandbox could be made, and what bubblewrap said when not. */
6
+ works: boolean;
7
+ said?: string;
8
+ /** The kernel keeps ordinary programs from making user namespaces unless AppArmor allows it (Ubuntu). */
9
+ apparmor: boolean;
10
+ /** There is a file at PROFILE_FILE already. */
11
+ profile: boolean;
12
+ /** Whether a program is there: a package manager, sudo, apparmor_parser. */
13
+ has(program: string): boolean;
14
+ root: boolean;
15
+ container: boolean;
16
+ /** apt has no package lists yet, as in a container that was just made. */
17
+ aptEmpty: boolean;
18
+ /** System libraries the downloaded browser needs and does not find. */
19
+ browserLacks: string[];
20
+ }
21
+ export interface Step {
22
+ /** What it does, in words. */
23
+ says: string;
24
+ /** The command, without sudo. "{file}" stands for a file holding `content`. */
25
+ argv: string[];
26
+ content?: string;
27
+ /** It asks for administrator rights itself, so pine does not put sudo in front. */
28
+ elevates?: boolean;
29
+ }
30
+ export interface Plan {
31
+ /** Nothing to do. */
32
+ ok: boolean;
33
+ /** What is missing, in words. */
34
+ why: string;
35
+ steps: Step[];
36
+ /** Why pine cannot do it here, and what would. */
37
+ cannot?: string;
38
+ }
39
+ export declare const PROFILE_FILE = "/etc/apparmor.d/bwrap";
40
+ /** The rule that lets bubblewrap make the user namespaces its sandboxes consist of. */
41
+ export declare const profileFor: (bwrap: string) => string;
42
+ /** What has to be done on this machine for the sandbox to work. */
43
+ export declare function sandboxPlan(m: Machine): Plan;
44
+ /**
45
+ * What the browser needs, when it lacks system libraries. Playwright, whose browser it is, knows
46
+ * the packages; it installs them with apt, so only where apt is.
47
+ */
48
+ export declare function browserPlan(m: Machine, cli?: string): {
49
+ step?: Step;
50
+ cannot?: string;
51
+ } | undefined;
52
+ /** A step as the owner reads it. */
53
+ export declare const shown: (step: Step, root?: boolean) => string;
54
+ /** This machine, looked at. */
55
+ export declare function lookAtMachine(): Machine;
56
+ export interface SetupIo {
57
+ out(line: string): void;
58
+ /** Ask a yes-or-no question; undefined when nobody is there to answer. */
59
+ confirm(question: string): Promise<boolean | undefined>;
60
+ /** Do it without asking. */
61
+ yes?: boolean;
62
+ machine?: () => Machine;
63
+ run?: (step: Step, root: boolean) => number;
64
+ }
65
+ /**
66
+ * Make the sandbox work on this Linux machine and give the browser its libraries, or say
67
+ * plainly why not. Returns whether the sandbox works afterwards. pine runs either way; without
68
+ * a sandbox agents get no shell.
69
+ */
70
+ export declare function setUpSandbox(io: SetupIo): Promise<boolean>;