@infosupport/huddle-cli 0.0.0-experiment-98.51.1 → 0.0.0-experiment-109.53.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.
- package/README.md +37 -32
- package/dist/api.js +45 -14
- package/dist/config.js +141 -3
- package/dist/control-address.js +148 -0
- package/dist/control-probe.js +174 -0
- package/dist/experiment.js +18 -7
- package/dist/firewall.js +11 -7
- package/dist/images.js +13 -9
- package/dist/index.js +136 -43
- package/dist/init.js +359 -89
- package/dist/logs.js +213 -0
- package/dist/migrate.js +95 -65
- package/dist/node.js +390 -0
- package/dist/sbx-host-ca.js +237 -0
- package/dist/sbx-host.js +36 -0
- package/dist/sbx.js +211 -0
- package/package.json +5 -3
- package/dist/indexfolder.js +0 -143
package/dist/node.js
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Huddle Node — the control plane, running directly on the host.
|
|
3
|
+
//
|
|
4
|
+
// Huddle Node is the half of Huddle that has no business being behind the
|
|
5
|
+
// firewall it configures: the portal, the REST/WS API, project + devcontainer
|
|
6
|
+
// orchestration, extensions and sbx. huddle-gateway keeps the other half — the
|
|
7
|
+
// filtering proxies devcontainers are DNAT'ed to (docs/ADR-huddle-node-split.md).
|
|
8
|
+
//
|
|
9
|
+
// Two entry points live here. `huddle node` runs it in the FOREGROUND, which is
|
|
10
|
+
// what you want when you are working on Huddle itself: logs on your terminal,
|
|
11
|
+
// Ctrl-C stops it. `huddle init` calls startNodeDetached() instead, because an
|
|
12
|
+
// init that only survives as long as the terminal it was typed in is not an
|
|
13
|
+
// init at all.
|
|
14
|
+
//
|
|
15
|
+
// PACKAGING GAP (deliberately not solved here)
|
|
16
|
+
// This command runs an EXISTING Huddle Node build; it cannot produce one. The
|
|
17
|
+
// published CLI ships only its own dist and has zero dependencies, while
|
|
18
|
+
// Huddle Node needs fastify, dockerode and better-sqlite3 — the last a native
|
|
19
|
+
// module needing prebuilds per platform. Deciding how a released Huddle Node
|
|
20
|
+
// reaches the host (bundled in the CLI package, a separate npm package, or
|
|
21
|
+
// extracted from the gateway image) is its own step. Until then this resolves
|
|
22
|
+
// a local build, which is what a repo checkout and `huddle init` in dev mode
|
|
23
|
+
// both already have.
|
|
24
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
25
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
26
|
+
};
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.NODE_LOG_FILE = exports.NODE_PID_FILE = exports.MissingNodeEntryError = exports.DEFAULT_NODE_PORT = void 0;
|
|
29
|
+
exports.explicitNodeEntry = explicitNodeEntry;
|
|
30
|
+
exports.nodeEntryCandidates = nodeEntryCandidates;
|
|
31
|
+
exports.resolveNodeEntry = resolveNodeEntry;
|
|
32
|
+
exports.nodeEnv = nodeEnv;
|
|
33
|
+
exports.nodeDataDir = nodeDataDir;
|
|
34
|
+
exports.nodeCaDir = nodeCaDir;
|
|
35
|
+
exports.readOperatorToken = readOperatorToken;
|
|
36
|
+
exports.readGatewayToken = readGatewayToken;
|
|
37
|
+
exports.runNode = runNode;
|
|
38
|
+
exports.nodeUrl = nodeUrl;
|
|
39
|
+
exports.nodeProbeUrls = nodeProbeUrls;
|
|
40
|
+
exports.readNodePid = readNodePid;
|
|
41
|
+
exports.isNodePidAlive = isNodePidAlive;
|
|
42
|
+
exports.pingNode = pingNode;
|
|
43
|
+
exports.waitForNode = waitForNode;
|
|
44
|
+
exports.stopNode = stopNode;
|
|
45
|
+
exports.startNodeDetached = startNodeDetached;
|
|
46
|
+
const child_process_1 = require("child_process");
|
|
47
|
+
const fs_1 = __importDefault(require("fs"));
|
|
48
|
+
const os_1 = __importDefault(require("os"));
|
|
49
|
+
const path_1 = __importDefault(require("path"));
|
|
50
|
+
const utils_1 = require("./utils");
|
|
51
|
+
const config_1 = require("./config");
|
|
52
|
+
exports.DEFAULT_NODE_PORT = 24842;
|
|
53
|
+
// An explicitly named entry, if there is one. Resolved separately from the
|
|
54
|
+
// search path on purpose: naming a build is a claim about which one to run, so
|
|
55
|
+
// a missing file has to fail loudly rather than quietly starting a different
|
|
56
|
+
// build that happens to exist elsewhere.
|
|
57
|
+
function explicitNodeEntry(opts, env = process.env) {
|
|
58
|
+
const explicit = opts.entry ?? env.HUDDLE_NODE_ENTRY;
|
|
59
|
+
return explicit ? path_1.default.resolve(explicit) : null;
|
|
60
|
+
}
|
|
61
|
+
// Where to look when nothing was named. Pure, so the search order is testable
|
|
62
|
+
// without a filesystem full of fixtures.
|
|
63
|
+
function nodeEntryCandidates(cliDir) {
|
|
64
|
+
// A repo checkout: cli/dist/index.js → ../../gateway/dist/index.js, and the
|
|
65
|
+
// same one level up for layouts that nest the build one deeper.
|
|
66
|
+
return [
|
|
67
|
+
path_1.default.resolve(cliDir, '..', '..', 'gateway', 'dist', 'index.js'),
|
|
68
|
+
path_1.default.resolve(cliDir, '..', '..', '..', 'gateway', 'dist', 'index.js'),
|
|
69
|
+
];
|
|
70
|
+
}
|
|
71
|
+
class MissingNodeEntryError extends Error {
|
|
72
|
+
entry;
|
|
73
|
+
constructor(entry) {
|
|
74
|
+
super(`No Huddle Node build at ${entry}`);
|
|
75
|
+
this.entry = entry;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
exports.MissingNodeEntryError = MissingNodeEntryError;
|
|
79
|
+
// Returns the entry to run, or null when nothing was named and nothing was
|
|
80
|
+
// found. Throws MissingNodeEntryError when something WAS named but is absent.
|
|
81
|
+
function resolveNodeEntry(opts, cliDir, env = process.env) {
|
|
82
|
+
const explicit = explicitNodeEntry(opts, env);
|
|
83
|
+
if (explicit) {
|
|
84
|
+
if (!fs_1.default.existsSync(explicit))
|
|
85
|
+
throw new MissingNodeEntryError(explicit);
|
|
86
|
+
return explicit;
|
|
87
|
+
}
|
|
88
|
+
for (const c of nodeEntryCandidates(cliDir)) {
|
|
89
|
+
if (fs_1.default.existsSync(c))
|
|
90
|
+
return c;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
// The environment that makes this process Huddle Node. The role IS the
|
|
95
|
+
// deployment (gateway/src/runtime-env.ts): `node` drops the proxies and moves
|
|
96
|
+
// every path off the container layout onto ~/.huddle. Anything the caller
|
|
97
|
+
// already set wins, so an operator can still point a run at a different data
|
|
98
|
+
// dir or port.
|
|
99
|
+
function nodeEnv(opts, env = process.env) {
|
|
100
|
+
const out = { ...env, HUDDLE_ROLE: 'node' };
|
|
101
|
+
if (opts.port)
|
|
102
|
+
out.HUDDLE_API_PORT = opts.port;
|
|
103
|
+
if (opts.dataDir)
|
|
104
|
+
out.HUDDLE_DATA_DIR = path_1.default.resolve(opts.dataDir);
|
|
105
|
+
// Where the GATEWAY container will reach the control channel. Loopback is the
|
|
106
|
+
// default and stays it on Docker Desktop; on native Linux `huddle init` passes
|
|
107
|
+
// the bridge address here, because a container cannot reach the host's
|
|
108
|
+
// loopback there. See cli/src/control-address.ts.
|
|
109
|
+
if (opts.controlHost)
|
|
110
|
+
out.HUDDLE_CONTROL_HOST = opts.controlHost;
|
|
111
|
+
if (opts.operatorToken)
|
|
112
|
+
out.HUDDLE_OPERATOR_TOKEN = opts.operatorToken;
|
|
113
|
+
for (const [k, v] of Object.entries(opts.extraEnv ?? {}))
|
|
114
|
+
out[k] = v;
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Where Huddle Node keeps its state. Mirrors `dataDir` in
|
|
119
|
+
* gateway/src/runtime-env.ts — the CLI has to be able to name the same
|
|
120
|
+
* directories the process it just spawned will use.
|
|
121
|
+
*/
|
|
122
|
+
function nodeDataDir(opts = {}, env = process.env) {
|
|
123
|
+
if (opts.dataDir)
|
|
124
|
+
return path_1.default.resolve(opts.dataDir);
|
|
125
|
+
return env.HUDDLE_DATA_DIR?.trim() || path_1.default.join(os_1.default.homedir(), '.huddle');
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The MITM CA directory — its own subdirectory of the data dir, and that is what
|
|
129
|
+
* makes it mountable: `huddle init` binds exactly this into the gateway
|
|
130
|
+
* read-only, while the database and the operator token stay behind.
|
|
131
|
+
*/
|
|
132
|
+
function nodeCaDir(opts = {}, env = process.env) {
|
|
133
|
+
return path_1.default.join(nodeDataDir(opts, env), 'ca');
|
|
134
|
+
}
|
|
135
|
+
/** The operator token Huddle Node persisted, or null if it has not written one. */
|
|
136
|
+
function readOperatorToken(dataDir = nodeDataDir()) {
|
|
137
|
+
try {
|
|
138
|
+
return fs_1.default.readFileSync(path_1.default.join(dataDir, 'operator-token'), 'utf8').trim() || null;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The gateway token Huddle Node runs with — the narrow, machine-to-machine
|
|
146
|
+
* credential for the control channel (gateway/src/auth.ts). Node writes it into
|
|
147
|
+
* its data dir on first boot, so this is only readable AFTER Node is up.
|
|
148
|
+
*
|
|
149
|
+
* Deliberately not generated here. One writer for a secret means there is never
|
|
150
|
+
* a question of which copy is real.
|
|
151
|
+
*/
|
|
152
|
+
function readGatewayToken(dataDir) {
|
|
153
|
+
const fromEnv = process.env.HUDDLE_GATEWAY_TOKEN?.trim();
|
|
154
|
+
if (fromEnv)
|
|
155
|
+
return fromEnv;
|
|
156
|
+
const file = path_1.default.join(dataDir, 'gateway-token');
|
|
157
|
+
try {
|
|
158
|
+
return fs_1.default.readFileSync(file, 'utf8').trim();
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
if (err.code !== 'ENOENT')
|
|
162
|
+
throw err;
|
|
163
|
+
// Node is up (we waited for it) but did not write its half of the pair, so
|
|
164
|
+
// it is older than the boot that mints it — say that, instead of leaking a
|
|
165
|
+
// bare ENOENT from the middle of gateway creation.
|
|
166
|
+
throw new Error(`Huddle Node has not written ${file}.\n` +
|
|
167
|
+
` It mints that token at boot, so this build of Node predates the fix.\n` +
|
|
168
|
+
` Stop it and re-run: the pid is in ${exports.NODE_PID_FILE}.`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
async function runNode(opts = {}) {
|
|
172
|
+
let entry;
|
|
173
|
+
try {
|
|
174
|
+
entry = resolveNodeEntry(opts, __dirname);
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
if (!(err instanceof MissingNodeEntryError))
|
|
178
|
+
throw err;
|
|
179
|
+
console.error((0, utils_1.red)(err.message));
|
|
180
|
+
console.error((0, utils_1.dim)(' Named explicitly, so no other build was tried.'));
|
|
181
|
+
process.exit(1);
|
|
182
|
+
}
|
|
183
|
+
if (!entry) {
|
|
184
|
+
console.error((0, utils_1.red)('No Huddle Node build found.'));
|
|
185
|
+
console.error('');
|
|
186
|
+
console.error(' `huddle node` runs an existing build; it does not create one.');
|
|
187
|
+
console.error(' In a repo checkout, build it first:');
|
|
188
|
+
console.error((0, utils_1.cyan)(' npm --prefix gateway install && npm --prefix gateway run build'));
|
|
189
|
+
console.error('');
|
|
190
|
+
console.error(' Or point at a build explicitly:');
|
|
191
|
+
console.error((0, utils_1.cyan)(' huddle node --entry /path/to/gateway/dist/index.js'));
|
|
192
|
+
console.error((0, utils_1.dim)(' (or set HUDDLE_NODE_ENTRY)'));
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
const env = nodeEnv(opts);
|
|
196
|
+
const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
|
|
197
|
+
console.log((0, utils_1.bold)('Huddle Node') + (0, utils_1.dim)(' — control plane, on this host'));
|
|
198
|
+
console.log(` entry ${(0, utils_1.dim)(entry)}`);
|
|
199
|
+
console.log(` portal ${(0, utils_1.cyan)(`http://localhost:${port}`)}`);
|
|
200
|
+
console.log(` data ${(0, utils_1.dim)(env.HUDDLE_DATA_DIR ?? path_1.default.join(os_1.default.homedir(), '.huddle'))}`);
|
|
201
|
+
console.log('');
|
|
202
|
+
console.log((0, utils_1.yellow)(' The firewall still lives in huddle-gateway; this process does not enforce it.'));
|
|
203
|
+
console.log((0, utils_1.dim)(' Ctrl-C to stop.'));
|
|
204
|
+
console.log('');
|
|
205
|
+
// Foreground on purpose: this is the shape you want while working ON Huddle.
|
|
206
|
+
// `huddle init` uses startNodeDetached() below. stdio inherit so Huddle Node's
|
|
207
|
+
// own logging is what the operator sees.
|
|
208
|
+
await new Promise((resolve) => {
|
|
209
|
+
const child = (0, child_process_1.spawn)(process.execPath, [entry], { env, stdio: 'inherit' });
|
|
210
|
+
// Forward the signals an operator actually sends, so Ctrl-C stops Huddle
|
|
211
|
+
// Node rather than orphaning it behind a dead CLI.
|
|
212
|
+
const forward = (sig) => () => { try {
|
|
213
|
+
child.kill(sig);
|
|
214
|
+
}
|
|
215
|
+
catch { /* already gone */ } };
|
|
216
|
+
const onInt = forward('SIGINT');
|
|
217
|
+
const onTerm = forward('SIGTERM');
|
|
218
|
+
process.on('SIGINT', onInt);
|
|
219
|
+
process.on('SIGTERM', onTerm);
|
|
220
|
+
child.on('error', (err) => {
|
|
221
|
+
console.error((0, utils_1.red)(`Failed to start Huddle Node: ${err.message}`));
|
|
222
|
+
process.exitCode = 1;
|
|
223
|
+
resolve();
|
|
224
|
+
});
|
|
225
|
+
child.on('exit', (code, signal) => {
|
|
226
|
+
process.off('SIGINT', onInt);
|
|
227
|
+
process.off('SIGTERM', onTerm);
|
|
228
|
+
if (signal)
|
|
229
|
+
console.log((0, utils_1.dim)(`\nHuddle Node stopped (${signal}).`));
|
|
230
|
+
else if (code)
|
|
231
|
+
process.exitCode = code;
|
|
232
|
+
resolve();
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
// ── Detached lifecycle (what `huddle init` uses) ─────────────────────────────
|
|
237
|
+
//
|
|
238
|
+
// Huddle Node has to outlive the shell `huddle init` was typed in, so init
|
|
239
|
+
// spawns it detached and remembers the pid. Two files in ~/.huddle: the pid, and
|
|
240
|
+
// a log, because a background process with nowhere to write its output is a
|
|
241
|
+
// process you cannot debug.
|
|
242
|
+
//
|
|
243
|
+
// The pid file is a hint, not a lock. A pid can be recycled, so isNodeRunning()
|
|
244
|
+
// treats it as "worth probing" and the HTTP health check is what actually
|
|
245
|
+
// decides whether Huddle Node is up — see waitForNode().
|
|
246
|
+
exports.NODE_PID_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.pid');
|
|
247
|
+
exports.NODE_LOG_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.log');
|
|
248
|
+
/** The URL a HUMAN talks to Huddle Node on: printed, opened in a browser. */
|
|
249
|
+
function nodeUrl(port = exports.DEFAULT_NODE_PORT) {
|
|
250
|
+
return `http://localhost:${port}`;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The addresses the CLI itself talks to Huddle Node on — loopback literals, in
|
|
254
|
+
* order, not the name `localhost`.
|
|
255
|
+
*
|
|
256
|
+
* Node binds ONE address (runtime-env.ts's apiBindHost: 127.0.0.1 in host mode),
|
|
257
|
+
* while `localhost` is two — and on Windows it resolves to ::1 first, where
|
|
258
|
+
* nothing listens. A browser papers over that with Happy Eyeballs, and so does a
|
|
259
|
+
* recent enough Node; an older one just fails. That combination is nasty,
|
|
260
|
+
* because it makes Huddle look half-installed rather than broken: the portal
|
|
261
|
+
* opens fine, but `huddle init` sits out its 30s probe against a perfectly
|
|
262
|
+
* healthy process and exits BEFORE it ever creates the gateway container.
|
|
263
|
+
*
|
|
264
|
+
* So probe the literals and accept whichever answers. HUDDLE_API_HOST wins when
|
|
265
|
+
* set, since then Node is not on loopback at all.
|
|
266
|
+
*/
|
|
267
|
+
function nodeProbeUrls(port = exports.DEFAULT_NODE_PORT) {
|
|
268
|
+
const bound = process.env.HUDDLE_API_HOST?.trim();
|
|
269
|
+
if (bound && bound !== '0.0.0.0' && bound !== '::') {
|
|
270
|
+
const host = bound.includes(':') && !bound.startsWith('[') ? `[${bound}]` : bound;
|
|
271
|
+
return [`http://${host}:${port}`];
|
|
272
|
+
}
|
|
273
|
+
return [`http://127.0.0.1:${port}`, `http://[::1]:${port}`];
|
|
274
|
+
}
|
|
275
|
+
function readNodePid() {
|
|
276
|
+
try {
|
|
277
|
+
const pid = Number(fs_1.default.readFileSync(exports.NODE_PID_FILE, 'utf8').trim());
|
|
278
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Does the recorded pid still name a live process? Says nothing about whether it is Huddle Node. */
|
|
285
|
+
function isNodePidAlive() {
|
|
286
|
+
const pid = readNodePid();
|
|
287
|
+
if (pid === null)
|
|
288
|
+
return false;
|
|
289
|
+
try {
|
|
290
|
+
process.kill(pid, 0);
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Is Huddle Node answering? /api/auth/status is the probe: it needs no operator
|
|
299
|
+
* token (api.ts keeps it public so the portal can find out whether login is
|
|
300
|
+
* needed), so a 200 here means the API is up, not merely that a port is open.
|
|
301
|
+
*/
|
|
302
|
+
async function pingNode(port, timeoutMs = 1500) {
|
|
303
|
+
const ac = new AbortController();
|
|
304
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
305
|
+
try {
|
|
306
|
+
for (const base of nodeProbeUrls(port)) {
|
|
307
|
+
try {
|
|
308
|
+
const res = await fetch(`${base}/api/auth/status`, { signal: ac.signal });
|
|
309
|
+
if (res.ok)
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
// Wrong family, or not up yet. Try the next address, then the next tick.
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
clearTimeout(timer);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async function waitForNode(port, timeoutMs = 30_000) {
|
|
323
|
+
const deadline = Date.now() + timeoutMs;
|
|
324
|
+
for (;;) {
|
|
325
|
+
if (await pingNode(port))
|
|
326
|
+
return true;
|
|
327
|
+
if (Date.now() >= deadline)
|
|
328
|
+
return false;
|
|
329
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async function stopNode() {
|
|
333
|
+
const pid = readNodePid();
|
|
334
|
+
if (pid === null)
|
|
335
|
+
return false;
|
|
336
|
+
try {
|
|
337
|
+
process.kill(pid, 'SIGTERM');
|
|
338
|
+
}
|
|
339
|
+
catch {
|
|
340
|
+
// Already gone. Clearing the pid file below is still the right cleanup.
|
|
341
|
+
}
|
|
342
|
+
try {
|
|
343
|
+
fs_1.default.unlinkSync(exports.NODE_PID_FILE);
|
|
344
|
+
}
|
|
345
|
+
catch { /* nothing to clean up */ }
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Start Huddle Node in the background and wait until it answers.
|
|
350
|
+
*
|
|
351
|
+
* Refuses to spawn a second one: two Huddle Nodes on one machine would both open
|
|
352
|
+
* the same SQLite file and both hand the gateway a policy feed, and only one of
|
|
353
|
+
* them would own the port. If one is already answering, that one is used.
|
|
354
|
+
*/
|
|
355
|
+
async function startNodeDetached(opts = {}) {
|
|
356
|
+
const env = nodeEnv(opts);
|
|
357
|
+
const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
|
|
358
|
+
if (await pingNode(port)) {
|
|
359
|
+
return { pid: readNodePid() ?? 0, entry: '(already running)', port, reused: true };
|
|
360
|
+
}
|
|
361
|
+
const entry = resolveNodeEntry(opts, __dirname);
|
|
362
|
+
if (!entry)
|
|
363
|
+
throw new MissingNodeEntryError(nodeEntryCandidates(__dirname)[0]);
|
|
364
|
+
fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true });
|
|
365
|
+
// Append, not truncate: the log of the run that just failed is usually the
|
|
366
|
+
// thing you need after a restart.
|
|
367
|
+
const log = fs_1.default.openSync(exports.NODE_LOG_FILE, 'a');
|
|
368
|
+
const child = (0, child_process_1.spawn)(process.execPath, [entry], {
|
|
369
|
+
env,
|
|
370
|
+
detached: true,
|
|
371
|
+
stdio: ['ignore', log, log],
|
|
372
|
+
windowsHide: true,
|
|
373
|
+
});
|
|
374
|
+
child.unref();
|
|
375
|
+
fs_1.default.closeSync(log);
|
|
376
|
+
if (child.pid)
|
|
377
|
+
fs_1.default.writeFileSync(exports.NODE_PID_FILE, String(child.pid));
|
|
378
|
+
if (!(await waitForNode(port))) {
|
|
379
|
+
// Alive-but-unreachable and dead are different bugs with the same symptom,
|
|
380
|
+
// and the difference is the first thing you want to know: init stops here,
|
|
381
|
+
// so the gateway container is never created and Huddle looks half-installed.
|
|
382
|
+
const stillRunning = child.pid ? isNodePidAlive() : false;
|
|
383
|
+
throw new Error(`Huddle Node did not come up on ${nodeProbeUrls(port).join(' or ')} within 30s.\n` +
|
|
384
|
+
(stillRunning
|
|
385
|
+
? ` The process (pid ${child.pid}) is still running, so it started but is not answering there.\n`
|
|
386
|
+
: ` The process is gone, so it failed during startup.\n`) +
|
|
387
|
+
` Check ${exports.NODE_LOG_FILE} — it holds everything the process printed.`);
|
|
388
|
+
}
|
|
389
|
+
return { pid: child.pid ?? 0, entry, port, reused: false };
|
|
390
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Huddle CA → HOST trust store (sbx mode) ───────────────────────────────────
|
|
3
|
+
// WHY THIS EXISTS (measured, not assumed):
|
|
4
|
+
//
|
|
5
|
+
// In sbx mode there are TWO TLS terminators, not one. For most hosts the sbx
|
|
6
|
+
// proxy just tunnels CONNECT to Huddle, so the client *inside* the sandbox sees
|
|
7
|
+
// Huddle's leaf and `sbx.ts:trustCa()` (CA installed in the sandbox) is enough:
|
|
8
|
+
//
|
|
9
|
+
// sandbox curl https://github.com → issuer: CN=Huddle DMZ Proxy Root CA
|
|
10
|
+
//
|
|
11
|
+
// But for at least the Claude/Anthropic hosts sbx terminates TLS ITSELF:
|
|
12
|
+
//
|
|
13
|
+
// sandbox curl https://platform.claude.com → issuer: CN=Docker Sandboxes Proxy CA
|
|
14
|
+
//
|
|
15
|
+
// There the upstream leg to Huddle is dialed by the sbx daemon — a HOST process
|
|
16
|
+
// that validates against the HOST trust store, which does not know Huddle's CA.
|
|
17
|
+
// The handshake with the client succeeds (sbx signs its own leaf immediately),
|
|
18
|
+
// the upstream validation then fails, and the connection is closed without a
|
|
19
|
+
// response: `curl: (52) Empty reply from server`, and `claude` reports
|
|
20
|
+
// "Failed to connect to platform.claude.com: ECONNRESET".
|
|
21
|
+
//
|
|
22
|
+
// So the CA has to be trusted in TWO places: inside the sandbox (trustCa) and on
|
|
23
|
+
// the host (here). Idempotent — safe to call on every `huddle init`.
|
|
24
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
25
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
26
|
+
};
|
|
27
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
+
exports.HOST_CA_PATH = void 0;
|
|
29
|
+
exports.certFingerprint = certFingerprint;
|
|
30
|
+
exports.installHostCa = installHostCa;
|
|
31
|
+
exports.printHostCaResult = printHostCaResult;
|
|
32
|
+
const fs_1 = __importDefault(require("fs"));
|
|
33
|
+
const os_1 = __importDefault(require("os"));
|
|
34
|
+
const path_1 = __importDefault(require("path"));
|
|
35
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
36
|
+
const child_process_1 = require("child_process");
|
|
37
|
+
const config_1 = require("./config");
|
|
38
|
+
const sbx_host_1 = require("./sbx-host");
|
|
39
|
+
const node_1 = require("./node");
|
|
40
|
+
const utils_1 = require("./utils");
|
|
41
|
+
/** Stable host path, so re-running init points at the same file. */
|
|
42
|
+
exports.HOST_CA_PATH = path_1.default.join(config_1.CONFIG_DIR, 'huddle-ca.crt');
|
|
43
|
+
const LINUX_CA_PATH = '/usr/local/share/ca-certificates/huddle-ca.crt';
|
|
44
|
+
/** No console window per child process on Windows (same reason as sbx-host.ts). */
|
|
45
|
+
const NO_WINDOW = { windowsHide: true };
|
|
46
|
+
function run(file, args, timeout = 30_000) {
|
|
47
|
+
try {
|
|
48
|
+
const out = (0, child_process_1.execFileSync)(file, args, { encoding: 'utf8', timeout, stdio: ['ignore', 'pipe', 'pipe'], ...NO_WINDOW });
|
|
49
|
+
return { code: 0, out: out ?? '' };
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
const e = err;
|
|
53
|
+
const out = `${e.stdout ?? ''}${e.stderr ?? ''}` || e.message || '';
|
|
54
|
+
return { code: typeof e.status === 'number' ? e.status : 1, out: String(out) };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** Blocking sleep — this runs in the CLI's synchronous init path, not in a loop. */
|
|
58
|
+
function sleepSync(ms) {
|
|
59
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Read the CA off this machine. It used to take a `docker exec` into the gateway
|
|
63
|
+
* container, because that is where the CA lived; Huddle Node owns it now and
|
|
64
|
+
* writes it to ~/.huddle/ca (gateway/src/runtime-env.ts), so this is a file read.
|
|
65
|
+
*
|
|
66
|
+
* Still retried: initCa() runs during Node's boot, and `huddle init` calls this
|
|
67
|
+
* moments after the process reported healthy.
|
|
68
|
+
*/
|
|
69
|
+
function readHostCa(tries = 12) {
|
|
70
|
+
const caPath = path_1.default.join((0, node_1.nodeCaDir)(), 'ca.crt');
|
|
71
|
+
for (let i = 0; i < tries; i++) {
|
|
72
|
+
try {
|
|
73
|
+
const pem = fs_1.default.readFileSync(caPath, 'utf8');
|
|
74
|
+
if (pem.includes('-----BEGIN CERTIFICATE-----'))
|
|
75
|
+
return pem;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// Not written yet — that is the race this loop exists for.
|
|
79
|
+
}
|
|
80
|
+
if (i === tries - 1)
|
|
81
|
+
return null;
|
|
82
|
+
sleepSync(500);
|
|
83
|
+
}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
/** SHA-1 over the DER body of the first PEM block — the thumbprint certutil uses. */
|
|
87
|
+
function certFingerprint(pem) {
|
|
88
|
+
const b64 = pem
|
|
89
|
+
.split('-----BEGIN CERTIFICATE-----')[1]
|
|
90
|
+
?.split('-----END CERTIFICATE-----')[0]
|
|
91
|
+
?.replace(/\s+/g, '');
|
|
92
|
+
if (!b64)
|
|
93
|
+
throw new Error('not a PEM certificate');
|
|
94
|
+
return crypto_1.default.createHash('sha1').update(Buffer.from(b64, 'base64')).digest('hex').toUpperCase();
|
|
95
|
+
}
|
|
96
|
+
// ── per-platform install ─────────────────────────────────────────────────────
|
|
97
|
+
/**
|
|
98
|
+
* Is the cert in this Windows root store? Asks the STORE, never the exit code:
|
|
99
|
+
* certutil's status codes are unreliable here (`-addstore` can print its success
|
|
100
|
+
* banner "Signature matches Public Key" and still exit non-zero, and
|
|
101
|
+
* `-verifystore` fails a chain check on a root it does happily hold). The
|
|
102
|
+
* thumbprint appearing in the listing is the only honest answer.
|
|
103
|
+
*/
|
|
104
|
+
function inWindowsStore(scope, fp) {
|
|
105
|
+
const scoped = scope === 'user' ? ['-user'] : [];
|
|
106
|
+
const has = (out) => out.replace(/[\s:]/g, '').toUpperCase().includes(fp);
|
|
107
|
+
// Targeted lookup first; fall back to a full dump for certutil builds that
|
|
108
|
+
// don't take a thumbprint as the cert-id argument.
|
|
109
|
+
if (has(run('certutil', [...scoped, '-store', 'Root', fp]).out))
|
|
110
|
+
return true;
|
|
111
|
+
return has(run('certutil', [...scoped, '-store', 'Root'], 60_000).out);
|
|
112
|
+
}
|
|
113
|
+
/** Pick the line that actually says what went wrong, not just the last one. */
|
|
114
|
+
function certutilError(out) {
|
|
115
|
+
const lines = out.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
116
|
+
const blame = [...lines].reverse().find((l) => /CertUtil:|FAILED|denied|0x[0-9A-Fa-f]{8}/.test(l));
|
|
117
|
+
return blame ?? lines.pop() ?? 'certutil failed';
|
|
118
|
+
}
|
|
119
|
+
function installWindows(certPath, fp) {
|
|
120
|
+
const manualHint = `certutil -addstore -f Root "${certPath}" (elevated prompt)`;
|
|
121
|
+
const found = (store, alreadyTrusted) => ({ ok: true, alreadyTrusted, store, certPath, fingerprint: fp, daemonRestarted: false });
|
|
122
|
+
// Go (which sbx is built with) reads the CURRENT_USER "ROOT" store, which the
|
|
123
|
+
// machine store is merged into — so the user store works WITHOUT elevation.
|
|
124
|
+
if (inWindowsStore('user', fp))
|
|
125
|
+
return found('windows-user', true);
|
|
126
|
+
if (inWindowsStore('machine', fp))
|
|
127
|
+
return found('windows-machine', true);
|
|
128
|
+
const user = run('certutil', ['-user', '-addstore', '-f', 'Root', certPath]);
|
|
129
|
+
if (inWindowsStore('user', fp))
|
|
130
|
+
return found('windows-user', false);
|
|
131
|
+
// Fall back to the machine store (needs an elevated prompt; usually fails here).
|
|
132
|
+
run('certutil', ['-addstore', '-f', 'Root', certPath]);
|
|
133
|
+
if (inWindowsStore('machine', fp))
|
|
134
|
+
return found('windows-machine', false);
|
|
135
|
+
return {
|
|
136
|
+
ok: false, alreadyTrusted: false, certPath, fingerprint: fp, daemonRestarted: false,
|
|
137
|
+
error: certutilError(user.out),
|
|
138
|
+
manualHint,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function installMacos(certPath, fp) {
|
|
142
|
+
const keychain = path_1.default.join(os_1.default.homedir(), 'Library/Keychains/login.keychain-db');
|
|
143
|
+
const manualHint = `security add-trusted-cert -r trustRoot -k "${keychain}" "${certPath}"`;
|
|
144
|
+
const found = run('security', ['find-certificate', '-a', '-Z', keychain]);
|
|
145
|
+
if (found.code === 0 && found.out.toUpperCase().includes(fp)) {
|
|
146
|
+
return { ok: true, alreadyTrusted: true, store: 'macos-login', certPath, fingerprint: fp, daemonRestarted: false };
|
|
147
|
+
}
|
|
148
|
+
// No -d: the login keychain needs no sudo (it may raise a GUI confirmation).
|
|
149
|
+
const add = run('security', ['add-trusted-cert', '-r', 'trustRoot', '-k', keychain, certPath], 60_000);
|
|
150
|
+
if (add.code === 0) {
|
|
151
|
+
return { ok: true, alreadyTrusted: false, store: 'macos-login', certPath, fingerprint: fp, daemonRestarted: false };
|
|
152
|
+
}
|
|
153
|
+
return { ok: false, alreadyTrusted: false, certPath, fingerprint: fp, daemonRestarted: false, error: add.out.trim(), manualHint };
|
|
154
|
+
}
|
|
155
|
+
function installLinux(certPath, pem, fp) {
|
|
156
|
+
const manualHint = `sudo cp "${certPath}" ${LINUX_CA_PATH} && sudo update-ca-certificates`;
|
|
157
|
+
try {
|
|
158
|
+
if (fs_1.default.readFileSync(LINUX_CA_PATH, 'utf8').trim() === pem.trim()) {
|
|
159
|
+
return { ok: true, alreadyTrusted: true, store: 'linux-system', certPath, fingerprint: fp, daemonRestarted: false };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch { /* not installed yet */ }
|
|
163
|
+
const copy = run('sh', ['-c', `cp ${JSON.stringify(certPath)} ${LINUX_CA_PATH} 2>/dev/null || (command -v sudo >/dev/null 2>&1 && sudo -n cp ${JSON.stringify(certPath)} ${LINUX_CA_PATH})`]);
|
|
164
|
+
if (copy.code !== 0) {
|
|
165
|
+
return { ok: false, alreadyTrusted: false, certPath, fingerprint: fp, daemonRestarted: false, error: 'need root to write ' + LINUX_CA_PATH, manualHint };
|
|
166
|
+
}
|
|
167
|
+
run('sh', ['-c', 'command -v update-ca-certificates >/dev/null 2>&1 && (update-ca-certificates >/dev/null 2>&1 || sudo -n update-ca-certificates >/dev/null 2>&1) || true'], 60_000);
|
|
168
|
+
return { ok: true, alreadyTrusted: false, store: 'linux-system', certPath, fingerprint: fp, daemonRestarted: false };
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Trust Huddle's CA on the HOST, then restart the sbx daemon so it reloads its
|
|
172
|
+
* root set. Never throws — sandbox mode is optional
|
|
173
|
+
* and this must never fail `huddle init`.
|
|
174
|
+
*/
|
|
175
|
+
function installHostCa(opts = {}) {
|
|
176
|
+
const pem = readHostCa();
|
|
177
|
+
if (!pem) {
|
|
178
|
+
const caPath = path_1.default.join((0, node_1.nodeCaDir)(), 'ca.crt');
|
|
179
|
+
return {
|
|
180
|
+
ok: false, alreadyTrusted: false, daemonRestarted: false,
|
|
181
|
+
error: `could not read ${caPath} — is Huddle Node running?`,
|
|
182
|
+
manualHint: `huddle init (Huddle Node writes the CA on boot)`,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
let fp;
|
|
186
|
+
try {
|
|
187
|
+
fp = certFingerprint(pem);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
return { ok: false, alreadyTrusted: false, daemonRestarted: false, error: err.message };
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true });
|
|
194
|
+
fs_1.default.writeFileSync(exports.HOST_CA_PATH, pem, { mode: 0o644 });
|
|
195
|
+
}
|
|
196
|
+
catch (err) {
|
|
197
|
+
return { ok: false, alreadyTrusted: false, fingerprint: fp, daemonRestarted: false, error: err.message };
|
|
198
|
+
}
|
|
199
|
+
let result;
|
|
200
|
+
if (process.platform === 'win32')
|
|
201
|
+
result = installWindows(exports.HOST_CA_PATH, fp);
|
|
202
|
+
else if (process.platform === 'darwin')
|
|
203
|
+
result = installMacos(exports.HOST_CA_PATH, fp);
|
|
204
|
+
else
|
|
205
|
+
result = installLinux(exports.HOST_CA_PATH, pem, fp);
|
|
206
|
+
// A freshly added root is only picked up by a running daemon after a restart.
|
|
207
|
+
// 'always' is for the explicit `huddle sbx trust-host`: you only type that when
|
|
208
|
+
// something is broken, and a store that was filled by an earlier run (before
|
|
209
|
+
// any restart) must not be silently skipped as "already trusted".
|
|
210
|
+
const mode = opts.restartDaemon ?? 'auto';
|
|
211
|
+
if (result.ok && mode !== 'never' && (mode === 'always' || !result.alreadyTrusted)) {
|
|
212
|
+
result.daemonRestarted = run((0, sbx_host_1.resolveSbxBin)(), ['daemon', 'restart'], 120_000).code === 0;
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
/** Human-readable one-liner + guidance. Shared by `huddle init` and `huddle sbx trust-host`. */
|
|
217
|
+
function printHostCaResult(r, indent = ' ') {
|
|
218
|
+
if (r.ok && r.alreadyTrusted) {
|
|
219
|
+
console.log((0, utils_1.dim)(`${indent}Huddle CA already trusted on the host (${r.store}) — sbx can reach Huddle over TLS.`));
|
|
220
|
+
if (r.daemonRestarted)
|
|
221
|
+
console.log((0, utils_1.dim)(`${indent} sbx daemon restarted so it re-reads the root store.`));
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (r.ok) {
|
|
225
|
+
console.log((0, utils_1.green)(`${indent}[OK] Huddle CA trusted on the host (${r.store})`));
|
|
226
|
+
console.log((0, utils_1.dim)(`${indent} ${r.certPath} · SHA-1 ${r.fingerprint}`));
|
|
227
|
+
console.log((0, utils_1.dim)(`${indent} ${r.daemonRestarted ? 'sbx daemon restarted' : 'restart the sbx daemon to pick it up: sbx daemon restart'}`));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
console.log((0, utils_1.yellow)(`${indent}Could not trust Huddle's CA on the host: ${r.error}`));
|
|
231
|
+
console.log((0, utils_1.dim)(`${indent} Without it, sbx cannot validate Huddle for the hosts it MITMs itself`));
|
|
232
|
+
console.log((0, utils_1.dim)(`${indent} (e.g. platform.claude.com) — those requests die as "Empty reply from server".`));
|
|
233
|
+
if (r.manualHint)
|
|
234
|
+
console.log((0, utils_1.dim)(`${indent} Do it manually: ${r.manualHint}`));
|
|
235
|
+
if (r.certPath)
|
|
236
|
+
console.log((0, utils_1.dim)(`${indent} Then: sbx daemon restart`));
|
|
237
|
+
}
|
package/dist/sbx-host.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Finding sbx on the host ───────────────────────────────────────────────────
|
|
3
|
+
// Docker Sandboxes (`sbx`) is a HOST binary. It manages VMs/containers through
|
|
4
|
+
// the user's own Docker installation and it is the thing Huddle points at its
|
|
5
|
+
// egress proxy — it was never something the gateway container could run.
|
|
6
|
+
//
|
|
7
|
+
// This module is what remains of the sbx bridge after the split (step 5 of
|
|
8
|
+
// docs/ADR-huddle-node-split.md): the bridge existed only to carry argv from a
|
|
9
|
+
// containerized Huddle to the host and back, and Huddle Node runs on the host,
|
|
10
|
+
// so it exec's sbx directly. Resolving WHICH binary and keeping Windows from
|
|
11
|
+
// flashing a console window are still real problems, so they live on here.
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.NO_WINDOW = void 0;
|
|
14
|
+
exports.resolveSbxBin = resolveSbxBin;
|
|
15
|
+
const child_process_1 = require("child_process");
|
|
16
|
+
/**
|
|
17
|
+
* No console window per child process on Windows.
|
|
18
|
+
*
|
|
19
|
+
* Huddle spawns sbx often and sometimes from a detached, console-less process;
|
|
20
|
+
* without this, Windows opens a terminal window for every single call.
|
|
21
|
+
*/
|
|
22
|
+
exports.NO_WINDOW = { windowsHide: true };
|
|
23
|
+
/** Resolve the host sbx binary: HUDDLE_SBX_BIN, else `sbx`, else `sbx.exe`. */
|
|
24
|
+
function resolveSbxBin() {
|
|
25
|
+
const env = process.env.HUDDLE_SBX_BIN?.trim();
|
|
26
|
+
if (env)
|
|
27
|
+
return env;
|
|
28
|
+
for (const c of ['sbx', 'sbx.exe']) {
|
|
29
|
+
try {
|
|
30
|
+
(0, child_process_1.execFileSync)(c, ['version'], { stdio: 'ignore', timeout: 15000, ...exports.NO_WINDOW });
|
|
31
|
+
return c;
|
|
32
|
+
}
|
|
33
|
+
catch { /* try next */ }
|
|
34
|
+
}
|
|
35
|
+
return 'sbx';
|
|
36
|
+
}
|