@infosupport/huddle-cli 0.0.0-experiment-137.150.1 → 0.0.0-experiment-160.152.1

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.
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ // ── `huddle pipe serve|start|stop|status` ─────────────────────────────────────
3
+ // Runs and manages the host agent for the host pipe (docs/host-pipe.md).
4
+ // `huddle init` calls startPipeAgent() so the agent always runs the CLI version
5
+ // that was just installed; the commands here are for checking on it and for
6
+ // debugging (`serve` runs it in the foreground with the log on the terminal).
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.startPipeAgent = startPipeAgent;
12
+ exports.runPipe = runPipe;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const child_process_1 = require("child_process");
16
+ const utils_1 = require("../utils");
17
+ const protocol_1 = require("./protocol");
18
+ const serve_1 = require("./serve");
19
+ const LOG_PATH = path_1.default.join(protocol_1.PIPE_DIR, protocol_1.LOG_FILE);
20
+ const MAX_LOG_BYTES = 5 * 1024 * 1024;
21
+ const STOP_WAIT_MS = 3000;
22
+ const START_WAIT_MS = 3000;
23
+ function alive(pid) {
24
+ try {
25
+ process.kill(pid, 0);
26
+ return true;
27
+ }
28
+ catch (err) {
29
+ // EPERM: it exists but belongs to someone else.
30
+ return err.code === 'EPERM';
31
+ }
32
+ }
33
+ async function waitFor(check, ms) {
34
+ const deadline = Date.now() + ms;
35
+ while (Date.now() < deadline) {
36
+ if (check())
37
+ return true;
38
+ await new Promise((r) => setTimeout(r, 100));
39
+ }
40
+ return check();
41
+ }
42
+ /**
43
+ * Stops the agent named in the heartbeat. Only a FRESH heartbeat is trusted:
44
+ * pids get reused, and killing whatever now holds the pid of an agent that died
45
+ * last week would be a nasty surprise. A stale heartbeat is just removed.
46
+ */
47
+ async function stopRunning() {
48
+ const hb = (0, protocol_1.readHeartbeat)();
49
+ if (!hb || !(0, protocol_1.heartbeatFresh)(hb) || hb.pid === process.pid || !alive(hb.pid)) {
50
+ try {
51
+ fs_1.default.unlinkSync(path_1.default.join(protocol_1.PIPE_DIR, protocol_1.HEARTBEAT_FILE));
52
+ }
53
+ catch { /* none */ }
54
+ return null;
55
+ }
56
+ try {
57
+ process.kill(hb.pid, 'SIGTERM');
58
+ }
59
+ catch { /* exited meanwhile */ }
60
+ if (!(await waitFor(() => !alive(hb.pid), STOP_WAIT_MS))) {
61
+ try {
62
+ process.kill(hb.pid, 'SIGKILL');
63
+ }
64
+ catch { /* exited meanwhile */ }
65
+ await waitFor(() => !alive(hb.pid), 1000);
66
+ }
67
+ // On Windows kill() is TerminateProcess, so the agent had no chance to clean up.
68
+ const left = (0, protocol_1.readHeartbeat)();
69
+ if (left?.pid === hb.pid) {
70
+ try {
71
+ fs_1.default.unlinkSync(path_1.default.join(protocol_1.PIPE_DIR, protocol_1.HEARTBEAT_FILE));
72
+ }
73
+ catch { /* none */ }
74
+ }
75
+ return hb;
76
+ }
77
+ /** Keeps one previous log; the agent appends for as long as it runs. */
78
+ function rotateLog() {
79
+ try {
80
+ if (fs_1.default.statSync(LOG_PATH).size > MAX_LOG_BYTES)
81
+ fs_1.default.renameSync(LOG_PATH, `${LOG_PATH}.1`);
82
+ }
83
+ catch { /* no log yet */ }
84
+ }
85
+ /**
86
+ * Starts the agent in the background, replacing a running one so the agent
87
+ * always runs this CLI's code. Never throws: `huddle init` must not fail on it.
88
+ */
89
+ async function startPipeAgent() {
90
+ try {
91
+ (0, protocol_1.ensurePrivateDir)(protocol_1.PIPE_DIR);
92
+ const old = await stopRunning();
93
+ rotateLog();
94
+ // dist/pipe/command.js -> dist/index.js: the entry of THIS install, not
95
+ // whatever `huddle` resolves to on PATH.
96
+ const entry = path_1.default.join(__dirname, '..', 'index.js');
97
+ const logFd = fs_1.default.openSync(LOG_PATH, 'a', 0o600);
98
+ let pid;
99
+ try {
100
+ const child = (0, child_process_1.spawn)(process.execPath, [entry, 'pipe', 'serve'], {
101
+ detached: true,
102
+ stdio: ['ignore', logFd, logFd],
103
+ windowsHide: true,
104
+ });
105
+ child.on('error', () => { });
106
+ child.unref();
107
+ pid = child.pid;
108
+ }
109
+ finally {
110
+ fs_1.default.closeSync(logFd);
111
+ }
112
+ if (!pid)
113
+ return { ok: false, error: `could not start the host agent (see ${LOG_PATH})` };
114
+ const up = await waitFor(() => {
115
+ const hb = (0, protocol_1.readHeartbeat)();
116
+ return hb !== null && (0, protocol_1.heartbeatFresh)(hb) && hb.pid === pid;
117
+ }, START_WAIT_MS);
118
+ if (!up)
119
+ return { ok: false, pid, error: `the host agent did not report in (see ${LOG_PATH})` };
120
+ return { ok: true, pid, replaced: old?.pid };
121
+ }
122
+ catch (err) {
123
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
124
+ }
125
+ }
126
+ function runServe() {
127
+ const stamp = () => new Date().toISOString();
128
+ const log = (msg) => console.log(`${stamp()} ${msg}`);
129
+ log(`host pipe agent (pid ${process.pid}) serving ${protocol_1.PIPE_DIR}`);
130
+ const handle = (0, serve_1.servePipe)({ dir: protocol_1.PIPE_DIR, log, onReplaced: () => process.exit(0) });
131
+ const shutdown = (signal) => {
132
+ log(`${signal}: stopping`);
133
+ // Removes host.json right away; in-flight requests are abandoned (the
134
+ // gateway times them out) rather than holding up a stop.
135
+ void handle.stop();
136
+ process.exit(0);
137
+ };
138
+ process.on('SIGINT', () => shutdown('SIGINT'));
139
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
140
+ }
141
+ function ago(iso) {
142
+ const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));
143
+ return s < 60 ? `${s}s ago` : s < 3600 ? `${Math.floor(s / 60)}m ago` : `${Math.floor(s / 3600)}h ago`;
144
+ }
145
+ function runStatus() {
146
+ const hb = (0, protocol_1.readHeartbeat)();
147
+ if (hb && (0, protocol_1.heartbeatFresh)(hb)) {
148
+ console.log(`${(0, utils_1.green)('Host pipe: online')} ${(0, utils_1.dim)(`(pid ${hb.pid}, CLI ${hb.version}, ${hb.platform})`)}`);
149
+ console.log((0, utils_1.dim)(` tools: ${hb.tools.length ? hb.tools.join(', ') : 'none installed'}`));
150
+ console.log((0, utils_1.dim)(` started: ${hb.startedAt} · heartbeat ${ago(hb.updatedAt)}`));
151
+ }
152
+ else {
153
+ const last = hb ? ` (last heartbeat ${ago(hb.updatedAt)}, pid ${hb.pid})` : '';
154
+ console.log(`${(0, utils_1.yellow)('Host pipe: offline')}${(0, utils_1.dim)(last)}`);
155
+ console.log((0, utils_1.dim)(' Start it with: huddle pipe start'));
156
+ }
157
+ console.log((0, utils_1.dim)(` folder: ${protocol_1.PIPE_DIR}`));
158
+ console.log((0, utils_1.dim)(` log: ${LOG_PATH}`));
159
+ }
160
+ async function runPipe(opts) {
161
+ const action = opts.action ?? 'status';
162
+ if (action === 'serve') {
163
+ runServe();
164
+ }
165
+ else if (action === 'start') {
166
+ const r = await startPipeAgent();
167
+ if (!r.ok) {
168
+ console.error((0, utils_1.yellow)(`[!] ${r.error}`));
169
+ process.exit(1);
170
+ }
171
+ const replaced = r.replaced ? `, replaced pid ${r.replaced}` : '';
172
+ console.log((0, utils_1.green)('[OK] Host pipe started') + (0, utils_1.dim)(` (pid ${r.pid}${replaced}) · log ${LOG_PATH}`));
173
+ }
174
+ else if (action === 'stop') {
175
+ const stopped = await stopRunning();
176
+ console.log(stopped ? `Host pipe stopped ${(0, utils_1.dim)(`(pid ${stopped.pid})`)}` : (0, utils_1.dim)('Host pipe was not running'));
177
+ }
178
+ else if (action === 'status') {
179
+ runStatus();
180
+ }
181
+ else {
182
+ console.error(`Unknown pipe subcommand: ${action}`);
183
+ console.error('Usage: huddle pipe <status|start|stop|serve>');
184
+ process.exit(1);
185
+ }
186
+ }
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ // ── Host pipe op `fs.list`: browsing the host, one folder at a time ───────────
3
+ // Replaces the old folder *index* (`huddle indexfolder`), which existed only
4
+ // because the portal runs in a container and cannot see the host: an operator
5
+ // had to walk the host from a shell and push a snapshot of folder names into the
6
+ // database. Through the host pipe the portal can just look, and a live look is
7
+ // strictly better than a snapshot that went stale the moment a folder was made.
8
+ //
9
+ // Nothing is stored and nothing walks: each call reads exactly one directory,
10
+ // which keeps a drive root cheap and a folder created five seconds ago visible.
11
+ // Port of host-browse.ts from feat/sbx-sandboxes-rebased.
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.toHuddlePath = toHuddlePath;
17
+ exports.isAbsoluteHostPath = isAbsoluteHostPath;
18
+ exports.hostRoots = hostRoots;
19
+ exports.listHostFolders = listHostFolders;
20
+ exports.fsList = fsList;
21
+ exports.fsResolve = fsResolve;
22
+ const fs_1 = __importDefault(require("fs"));
23
+ const os_1 = __importDefault(require("os"));
24
+ const path_1 = __importDefault(require("path"));
25
+ const protocol_1 = require("./protocol");
26
+ /**
27
+ * A host path in Huddle notation: forward slashes, upper-case drive letter, no
28
+ * trailing slash except on a root. One spelling for the whole system, so the
29
+ * gateway can compare and store paths without knowing the host's platform.
30
+ * Duplicated (on purpose) from the gateway's host-path.ts: the CLI must not
31
+ * depend on gateway code.
32
+ */
33
+ function toHuddlePath(p, platform = process.platform) {
34
+ // A bare drive ('c:') is that drive's root here, not its current directory.
35
+ if (platform === 'win32' && /^[A-Za-z]:$/.test(p))
36
+ return `${p.toUpperCase()}/`;
37
+ const normalized = platform === 'win32' ? path_1.default.win32.normalize(p) : path_1.default.posix.normalize(p);
38
+ let s = normalized.replace(/\\/g, '/');
39
+ s = s.replace(/^([a-z]):/, (_m, d) => `${d.toUpperCase()}:`);
40
+ while (s.length > 1 && s.endsWith('/') && !/^[A-Z]:\/$/.test(s))
41
+ s = s.slice(0, -1);
42
+ return s;
43
+ }
44
+ /** Absolute in the host's own sense: '/x' on POSIX, 'C:/x' or a UNC '//server/share' on Windows. */
45
+ function isAbsoluteHostPath(p, platform = process.platform) {
46
+ if (platform === 'win32')
47
+ return /^[A-Za-z]:[\\/]/.test(p) || /^[\\/]{2}[^\\/]/.test(p);
48
+ return p.startsWith('/');
49
+ }
50
+ function leaf(p) {
51
+ if (p === '/')
52
+ return '/';
53
+ if (/^[A-Z]:\/$/.test(p))
54
+ return p.slice(0, 2);
55
+ return p.slice(p.lastIndexOf('/') + 1);
56
+ }
57
+ // Joins in Huddle notation rather than the platform's, so Windows hands back
58
+ // 'C:/projects/app' and not 'C:\projects\app'.
59
+ function joinHost(parent, segment) {
60
+ return parent.endsWith('/') ? `${parent}${segment}` : `${parent}/${segment}`;
61
+ }
62
+ /**
63
+ * Where browsing starts: the drives (Windows) or `/` (elsewhere), plus the home
64
+ * folder because that is where projects usually live and nobody wants to click
65
+ * through /home/<user> every time.
66
+ */
67
+ function hostRoots() {
68
+ const out = [];
69
+ const seen = new Set();
70
+ const add = (p, name) => {
71
+ const key = p.toLowerCase();
72
+ if (seen.has(key))
73
+ return;
74
+ seen.add(key);
75
+ out.push({ path: p, name: name ?? leaf(p) });
76
+ };
77
+ if (process.platform === 'win32') {
78
+ // Probing 26 letters is a stat per letter and no slower than the WMI query
79
+ // that answers the same question, without a dependency. A CD drive with no
80
+ // disc exists but throws on read; it is no place for a workspace, so
81
+ // anything unreadable is left out.
82
+ for (let i = 0; i < 26; i++) {
83
+ const letter = String.fromCharCode(65 + i);
84
+ try {
85
+ fs_1.default.readdirSync(`${letter}:/`);
86
+ }
87
+ catch {
88
+ continue;
89
+ }
90
+ add(`${letter}:/`, `${letter}:`);
91
+ }
92
+ }
93
+ else {
94
+ add('/', '/');
95
+ }
96
+ const home = os_1.default.homedir();
97
+ if (home) {
98
+ try {
99
+ if (fs_1.default.statSync(home).isDirectory())
100
+ add(toHuddlePath(home));
101
+ }
102
+ catch { /* no readable home: the drives/root above are enough */ }
103
+ }
104
+ return out;
105
+ }
106
+ /**
107
+ * The immediate subfolders of `dir`, sorted case-insensitively like a file
108
+ * dialog. Only one level: the portal asks again when it opens a folder.
109
+ *
110
+ * Hidden (dot) folders are included: `.config`, `.local` or a dotted worktree
111
+ * are real places, and a picker that omits a folder the operator sees in their
112
+ * own file manager reads as broken. Symlinked folders are included too; nothing
113
+ * walks, so a link loop is at worst someone clicking in circles.
114
+ *
115
+ * Sorting happens before truncation, so a huge folder shows its first `max`
116
+ * names alphabetically rather than an arbitrary readdir-order slice.
117
+ */
118
+ async function listHostFolders(dir, max = protocol_1.MAX_FOLDER_ENTRIES) {
119
+ let entries;
120
+ try {
121
+ entries = await fs_1.default.promises.readdir(dir, { withFileTypes: true });
122
+ }
123
+ catch (err) {
124
+ throw new protocol_1.PipeError('not_found', `cannot read folder ${dir}: ${err.code ?? err}`);
125
+ }
126
+ const names = [];
127
+ for (const e of entries) {
128
+ let isDir = e.isDirectory();
129
+ if (!isDir && e.isSymbolicLink()) {
130
+ try {
131
+ isDir = (await fs_1.default.promises.stat(path_1.default.join(dir, e.name))).isDirectory();
132
+ }
133
+ catch {
134
+ continue; // dangling link
135
+ }
136
+ }
137
+ if (isDir)
138
+ names.push(e.name);
139
+ }
140
+ names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
141
+ const truncated = names.length > max;
142
+ const folders = names.slice(0, max).map((name) => ({ path: joinHost(dir, name), name }));
143
+ return { path: dir, folders, truncated, max };
144
+ }
145
+ /** The `fs.list` op: no path → the roots, otherwise one folder. */
146
+ async function fsList(args, max = protocol_1.MAX_FOLDER_ENTRIES) {
147
+ const raw = args.path;
148
+ if (raw === undefined || raw === null || raw === '') {
149
+ return { path: '', folders: hostRoots(), truncated: false, max };
150
+ }
151
+ if (typeof raw !== 'string')
152
+ throw new protocol_1.PipeError('bad_request', 'path must be a string');
153
+ if (raw.includes('\0'))
154
+ throw new protocol_1.PipeError('bad_request', 'path contains a NUL byte');
155
+ if (!isAbsoluteHostPath(raw))
156
+ throw new protocol_1.PipeError('bad_request', `not an absolute host path: ${raw}`);
157
+ return listHostFolders(toHuddlePath(raw), max);
158
+ }
159
+ const MAX_RESOLVE_PATHS = 64;
160
+ /**
161
+ * The `fs.resolve` op: where each path really is (links followed), or null when
162
+ * it does not exist. The portal cannot see host links, and a workspace that is a
163
+ * link into ~/.huddle would otherwise pass its lexical mount check.
164
+ */
165
+ async function fsResolve(args) {
166
+ const raw = args.paths;
167
+ if (!Array.isArray(raw) || raw.length > MAX_RESOLVE_PATHS)
168
+ throw new protocol_1.PipeError('bad_request', `paths must be an array of at most ${MAX_RESOLVE_PATHS}`);
169
+ const paths = [];
170
+ for (const p of raw) {
171
+ if (typeof p !== 'string' || p.includes('\0') || !isAbsoluteHostPath(p))
172
+ throw new protocol_1.PipeError('bad_request', 'paths must be absolute host paths');
173
+ try {
174
+ paths.push(toHuddlePath(await fs_1.default.promises.realpath(p)));
175
+ }
176
+ catch {
177
+ paths.push(null);
178
+ }
179
+ }
180
+ return { paths };
181
+ }
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ // ── Host pipe: shared protocol bits ───────────────────────────────────────────
3
+ // The host pipe is a folder (~/.huddle/pipe on the host, /huddle-home/pipe in the
4
+ // gateway) through which the gateway asks the host for things it cannot do from
5
+ // inside its container. See docs/host-pipe.md — that file is the contract; the
6
+ // names and numbers below mirror it and must not drift.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.PipeError = exports.MAX_TOOL_TIMEOUT_MS = exports.DEFAULT_TOOL_TIMEOUT_MS = exports.MAX_OUTPUT_BYTES = exports.MAX_FOLDER_ENTRIES = exports.STALE_FILE_MS = exports.HEARTBEAT_STALE_MS = exports.HEARTBEAT_MS = exports.POLL_MS = exports.LOG_FILE = exports.HEARTBEAT_FILE = exports.PIPE_DIR = exports.PROTOCOL_VERSION = void 0;
12
+ exports.ensurePrivateDir = ensurePrivateDir;
13
+ exports.writeJsonAtomic = writeJsonAtomic;
14
+ exports.readHeartbeat = readHeartbeat;
15
+ exports.heartbeatFresh = heartbeatFresh;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ const config_1 = require("../config");
19
+ exports.PROTOCOL_VERSION = 1;
20
+ /** Where the agent serves by default: inside the ~/.huddle mount the gateway already has. */
21
+ exports.PIPE_DIR = path_1.default.join(config_1.CONFIG_DIR, 'pipe');
22
+ exports.HEARTBEAT_FILE = 'host.json';
23
+ exports.LOG_FILE = 'host.log';
24
+ exports.POLL_MS = 100;
25
+ exports.HEARTBEAT_MS = 2000;
26
+ /** The gateway calls the agent offline when the heartbeat is older than this. */
27
+ exports.HEARTBEAT_STALE_MS = 10_000;
28
+ /** Leftover request/reply files older than this are deleted on start. */
29
+ exports.STALE_FILE_MS = 60 * 60 * 1000;
30
+ exports.MAX_FOLDER_ENTRIES = 2000;
31
+ exports.MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
32
+ exports.DEFAULT_TOOL_TIMEOUT_MS = 30_000;
33
+ exports.MAX_TOOL_TIMEOUT_MS = 15 * 60 * 1000;
34
+ /** Thrown by an op handler to answer with `ok:false` and a specific code. */
35
+ class PipeError extends Error {
36
+ code;
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.code = code;
40
+ }
41
+ }
42
+ exports.PipeError = PipeError;
43
+ /**
44
+ * Writes JSON to `<file>.tmp` and renames it over `<file>`, so the other side
45
+ * never reads a half-written file. Rename within one folder is atomic on every
46
+ * platform, including across the Docker bind mount.
47
+ */
48
+ /**
49
+ * Creates the pipe folder owner-only, or makes an existing one so. Whoever can
50
+ * write a request into it can run the allowlisted host tools, so on POSIX it
51
+ * must be ours (not a symlink) and closed to everyone else, and its parent must
52
+ * not let anyone else swap it out. Throws when that cannot be made true. On
53
+ * Windows a folder under the user profile is private already.
54
+ */
55
+ function ensurePrivateDir(dir) {
56
+ fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
57
+ if (process.platform === 'win32' || typeof process.getuid !== 'function')
58
+ return;
59
+ const uid = process.getuid();
60
+ const st = fs_1.default.lstatSync(dir);
61
+ if (!st.isDirectory())
62
+ throw new Error(`${dir} is not a directory (a symlink is not accepted)`);
63
+ if (st.uid !== uid)
64
+ throw new Error(`${dir} belongs to uid ${st.uid}, not to you: refusing to use it as the host pipe`);
65
+ // The parent: ours (then closed to writes by others), or root's and either not
66
+ // writable by others or sticky (like /tmp), where nobody else can rename ours.
67
+ const parent = path_1.default.dirname(dir);
68
+ const ps = fs_1.default.statSync(parent);
69
+ const pmode = ps.mode & 0o7777;
70
+ if (ps.uid === uid) {
71
+ if (pmode & 0o022)
72
+ fs_1.default.chmodSync(parent, pmode & ~0o022);
73
+ }
74
+ else if (ps.uid !== 0 || ((pmode & 0o022) && !(pmode & 0o1000))) {
75
+ throw new Error(`${parent} can be changed by other users: refusing to serve the host pipe below it`);
76
+ }
77
+ if ((fs_1.default.statSync(dir).mode & 0o777) !== 0o700)
78
+ fs_1.default.chmodSync(dir, 0o700);
79
+ }
80
+ function writeJsonAtomic(file, data) {
81
+ const tmp = `${file}.tmp`;
82
+ fs_1.default.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
83
+ fs_1.default.renameSync(tmp, file);
84
+ }
85
+ /** The heartbeat in `dir`, or null when there is none (or it is unreadable). */
86
+ function readHeartbeat(dir = exports.PIPE_DIR) {
87
+ try {
88
+ const hb = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, exports.HEARTBEAT_FILE), 'utf8'));
89
+ return typeof hb === 'object' && hb !== null && typeof hb.pid === 'number' ? hb : null;
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ /** Same rule as the gateway: online only while the heartbeat is younger than 10 s. */
96
+ function heartbeatFresh(hb, now = Date.now()) {
97
+ const updated = Date.parse(hb.updatedAt);
98
+ return Number.isFinite(updated) && now - updated < exports.HEARTBEAT_STALE_MS;
99
+ }
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ // ── Host pipe op `sbx.kit`: the Huddle CA for a Docker Sandbox ──
3
+ // Huddle inspects TLS (it terminates it with its own CA) for a devcontainer, and
4
+ // the devcontainer is set up to trust that CA. A Docker Sandbox gets the same
5
+ // through an sbx kit (a "mixin": `sbx create --kit <dir>`), which sbx applies to
6
+ // the sandbox at create:
7
+ // - the CA in the system trust store (install, as root);
8
+ // - NODE_EXTRA_CA_CERTS / SSL_CERT_FILE / REQUESTS_CA_BUNDLE, like a devcontainer,
9
+ // but all on the system bundle: that keeps sbx's own proxy CA, which sbx's
10
+ // credential proxy needs (a tool trusting only the Huddle CA breaks there);
11
+ // - the CA in the keystore of a JetBrains backend (the JBR does not read the
12
+ // system store), also for a backend Toolbox installs later.
13
+ // sbx only combines kits of one format, so the kit comes in the agent's: v2
14
+ // (spec.yaml plus files/) for sbx before 0.51, v3 (a descriptor sbx builds into
15
+ // an image) from 0.51 on, where the built-in agents are v3 kits.
16
+ // The op writes the kit to ~/.huddle/sbx/kits/huddle-ca and returns its host path.
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.KIT_NAME = exports.SBX_KITS_DIR = void 0;
22
+ exports.sbxKit = sbxKit;
23
+ const fs_1 = __importDefault(require("fs"));
24
+ const path_1 = __importDefault(require("path"));
25
+ const config_1 = require("../config");
26
+ const protocol_1 = require("./protocol");
27
+ const fs_list_1 = require("./fs-list");
28
+ exports.SBX_KITS_DIR = path_1.default.join(config_1.CONFIG_DIR, 'sbx', 'kits');
29
+ exports.KIT_NAME = 'huddle-ca';
30
+ const PEM_RE = /^-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----\r?\n?$/;
31
+ const MAX_PEM = 16 * 1024;
32
+ const BUNDLE = '/etc/ssl/certs/ca-certificates.crt';
33
+ // v2: in the sandbox, files/home/ is /home/agent/.
34
+ const V2_IN_BOX = '/home/agent/.huddle-ca';
35
+ const V2_SPEC = `schemaVersion: "2"
36
+ kind: mixin
37
+ name: ${exports.KIT_NAME}
38
+ description: Trust the Huddle CA, so Huddle can inspect this sandbox's TLS
39
+ environment:
40
+ variables:
41
+ NODE_EXTRA_CA_CERTS: ${BUNDLE}
42
+ SSL_CERT_FILE: ${BUNDLE}
43
+ REQUESTS_CA_BUNDLE: ${BUNDLE}
44
+ setup:
45
+ install:
46
+ - command: "sh ${V2_IN_BOX}/install.sh"
47
+ user: "0"
48
+ # startup takes the command as argv, install as one string (sbx's schema).
49
+ startup:
50
+ - command: ["sh", "${V2_IN_BOX}/jbr-watch.sh"]
51
+ `;
52
+ // v3: the kit is an image layer over the agent's filesystem, so it stays out of
53
+ // /home/agent (a layer that has that folder would take over its owner).
54
+ const V3_IN_BOX = '/usr/local/share/huddle-ca';
55
+ // Install hooks only see the variables they name.
56
+ const V3_SPEC = `# syntax=docker/sandbox-kit:3
57
+ schemaVersion: "3"
58
+ kind: mixin
59
+ displayName: Huddle CA
60
+ description: Trust the Huddle CA, so Huddle can inspect this sandbox's TLS
61
+ build: |
62
+ FROM scratch
63
+ COPY share/ ${V3_IN_BOX}/
64
+ ENV NODE_EXTRA_CA_CERTS=${BUNDLE} SSL_CERT_FILE=${BUNDLE} REQUESTS_CA_BUNDLE=${BUNDLE}
65
+ capabilities:
66
+ - type: com.docker.sandbox/lifecycle@1
67
+ config:
68
+ install:
69
+ - command: "sh ${V3_IN_BOX}/install.sh"
70
+ user: "0"
71
+ env: [PROXY_CA_CERT_B64]
72
+ startup:
73
+ - command: ["sh", "${V3_IN_BOX}/jbr-watch.sh"]
74
+ `;
75
+ const install = (inBox) => `#!/bin/sh
76
+ # Generated by Huddle. Runs as root when the sandbox is created.
77
+ set -e
78
+ mkdir -p /usr/local/share/ca-certificates
79
+ install -m 0644 ${inBox}/huddle-ca.crt /usr/local/share/ca-certificates/huddle-ca.crt
80
+ # sbx's own proxy CA into the same store, so the bundle the variables point at
81
+ # trusts both (sbx's credential proxy signs with that one).
82
+ if [ -n "\${PROXY_CA_CERT_B64:-}" ]; then
83
+ echo "$PROXY_CA_CERT_B64" | base64 -d > /usr/local/share/ca-certificates/sbx-proxy-ca.crt 2>/dev/null \\
84
+ && chmod 644 /usr/local/share/ca-certificates/sbx-proxy-ca.crt \\
85
+ || rm -f /usr/local/share/ca-certificates/sbx-proxy-ca.crt
86
+ fi
87
+ update-ca-certificates >/dev/null 2>&1 || true
88
+ echo "[huddle] CA installed"
89
+ `;
90
+ // A JetBrains backend runs on its own JVM (the JBR), which only trusts its own
91
+ // keystore. Toolbox installs it under ~/.cache/JetBrains/RemoteDev/dist on the
92
+ // first connect, so this keeps watching (in the background) and imports the CA
93
+ // into every backend it finds, once.
94
+ const jbrWatch = (inBox) => `#!/bin/sh
95
+ # Generated by Huddle. Runs as the agent user on every sandbox start.
96
+ CA=/usr/local/share/ca-certificates/huddle-ca.crt
97
+ [ -f "$CA" ] || CA=${inBox}/huddle-ca.crt
98
+ import_all() {
99
+ for d in "$HOME"/.cache/JetBrains/RemoteDev/dist/*/; do
100
+ kt="$d/jbr/bin/keytool"; ks="$d/jbr/lib/security/cacerts"
101
+ [ -x "$kt" ] && [ -f "$ks" ] && [ ! -f "$d/.huddle-ca" ] || continue
102
+ "$kt" -delete -alias huddle-ca -keystore "$ks" -storepass changeit >/dev/null 2>&1 || true
103
+ "$kt" -importcert -noprompt -trustcacerts -alias huddle-ca -file "$CA" -keystore "$ks" -storepass changeit >/dev/null 2>&1 \\
104
+ && touch "$d/.huddle-ca"
105
+ done
106
+ }
107
+ import_all
108
+ ( while sleep 30; do import_all; done ) >/dev/null 2>&1 </dev/null &
109
+ exit 0
110
+ `;
111
+ /** The `sbx.kit` op: `{ caPem, format? }` → `{ dir, format }`, the kit's folder as a host path. */
112
+ function sbxKit(args, root = exports.SBX_KITS_DIR, platform = process.platform) {
113
+ const { caPem, format = 2 } = args;
114
+ if (typeof caPem !== 'string' || caPem.length > MAX_PEM || !PEM_RE.test(caPem)) {
115
+ throw new protocol_1.PipeError('bad_request', 'caPem must be one PEM certificate');
116
+ }
117
+ if (format !== 2 && format !== 3)
118
+ throw new protocol_1.PipeError('bad_request', 'format must be 2 or 3');
119
+ const dir = path_1.default.join(root, exports.KIT_NAME);
120
+ try {
121
+ (0, protocol_1.ensurePrivateDir)(root);
122
+ // Rewritten whole: a kit left in the other format would confuse sbx.
123
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
124
+ (0, protocol_1.ensurePrivateDir)(dir);
125
+ const inBox = format === 3 ? V3_IN_BOX : V2_IN_BOX;
126
+ const files = format === 3 ? path_1.default.join(dir, 'share') : path_1.default.join(dir, 'files', 'home', '.huddle-ca');
127
+ fs_1.default.mkdirSync(files, { recursive: true, mode: 0o700 });
128
+ // \n only: these are read inside the Linux sandbox, also when written on Windows.
129
+ const write = (file, text) => fs_1.default.writeFileSync(file, text.replace(/\r\n/g, '\n'), { mode: 0o644 });
130
+ if (format === 3)
131
+ write(path_1.default.join(dir, `${exports.KIT_NAME}.yaml`), V3_SPEC);
132
+ else
133
+ write(path_1.default.join(dir, 'spec.yaml'), V2_SPEC);
134
+ write(path_1.default.join(files, 'huddle-ca.crt'), caPem.endsWith('\n') ? caPem : `${caPem}\n`);
135
+ write(path_1.default.join(files, 'install.sh'), install(inBox));
136
+ write(path_1.default.join(files, 'jbr-watch.sh'), jbrWatch(inBox));
137
+ }
138
+ catch (err) {
139
+ throw new protocol_1.PipeError('internal', `could not write the sbx kit: ${err.message ?? err}`);
140
+ }
141
+ return { dir: (0, fs_list_1.toHuddlePath)(dir, platform), format };
142
+ }