@infosupport/huddle-cli 0.0.0-experiment-98.52.1 → 0.0.0-experiment-109.54.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/control-address.js +160 -0
- package/dist/control-probe.js +174 -0
- package/dist/experiment.js +6 -0
- package/dist/firewall.js +10 -6
- package/dist/images.js +13 -9
- package/dist/index.js +139 -45
- package/dist/init.js +354 -89
- package/dist/logs.js +213 -0
- package/dist/migrate.js +53 -17
- package/dist/node.js +534 -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 +11 -3
- package/dist/indexfolder.js +0 -167
package/dist/node.js
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
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
|
+
// DELIVERY
|
|
16
|
+
// Published CLI packages declare one optional Huddle Node package per supported
|
|
17
|
+
// os/cpu. npm installs only its matching package; this file resolves its SEA
|
|
18
|
+
// executable without a postinstall download or a host Node runtime dependency.
|
|
19
|
+
// A checkout still wins, deliberately, so contributors run what they built.
|
|
20
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
21
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
22
|
+
};
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.NODE_CONTROL_HOST_FILE = exports.NODE_LOG_FILE = exports.NODE_PID_FILE = exports.MissingNodeEntryError = exports.DEFAULT_NODE_PORT = void 0;
|
|
25
|
+
exports.platformNodePackageName = platformNodePackageName;
|
|
26
|
+
exports.installedNodeEntry = installedNodeEntry;
|
|
27
|
+
exports.explicitNodeEntry = explicitNodeEntry;
|
|
28
|
+
exports.nodeEntryCandidates = nodeEntryCandidates;
|
|
29
|
+
exports.nodeLaunch = nodeLaunch;
|
|
30
|
+
exports.resolveNodeEntry = resolveNodeEntry;
|
|
31
|
+
exports.nodeEnv = nodeEnv;
|
|
32
|
+
exports.nodeDataDir = nodeDataDir;
|
|
33
|
+
exports.nodeCaDir = nodeCaDir;
|
|
34
|
+
exports.readOperatorToken = readOperatorToken;
|
|
35
|
+
exports.readGatewayToken = readGatewayToken;
|
|
36
|
+
exports.runNode = runNode;
|
|
37
|
+
exports.normalizeControlHost = normalizeControlHost;
|
|
38
|
+
exports.nodeUrl = nodeUrl;
|
|
39
|
+
exports.nodeProbeUrls = nodeProbeUrls;
|
|
40
|
+
exports.readNodePid = readNodePid;
|
|
41
|
+
exports.readNodeControlHost = readNodeControlHost;
|
|
42
|
+
exports.isNodePidAlive = isNodePidAlive;
|
|
43
|
+
exports.pingNode = pingNode;
|
|
44
|
+
exports.waitForNode = waitForNode;
|
|
45
|
+
exports.stopNode = stopNode;
|
|
46
|
+
exports.stopNodeAndWait = stopNodeAndWait;
|
|
47
|
+
exports.startNodeDetached = startNodeDetached;
|
|
48
|
+
const child_process_1 = require("child_process");
|
|
49
|
+
const fs_1 = __importDefault(require("fs"));
|
|
50
|
+
const os_1 = __importDefault(require("os"));
|
|
51
|
+
const path_1 = __importDefault(require("path"));
|
|
52
|
+
const utils_1 = require("./utils");
|
|
53
|
+
const config_1 = require("./config");
|
|
54
|
+
exports.DEFAULT_NODE_PORT = 24842;
|
|
55
|
+
/**
|
|
56
|
+
* The executable is an optional dependency rather than a postinstall download:
|
|
57
|
+
* npm selects the one package whose os/cpu fields match the host. Keep this
|
|
58
|
+
* mapping here, beside resolution, so adding an architecture is a deliberate
|
|
59
|
+
* CLI change with a test rather than an implicit package-name convention.
|
|
60
|
+
*/
|
|
61
|
+
function platformNodePackageName(platform = process.platform, arch = process.arch) {
|
|
62
|
+
const supported = new Set(['win32-x64', 'darwin-x64', 'darwin-arm64', 'linux-x64']);
|
|
63
|
+
const target = `${platform}-${arch}`;
|
|
64
|
+
return supported.has(target) ? `@infosupport/huddle-node-${target}` : null;
|
|
65
|
+
}
|
|
66
|
+
function installedNodeEntry(cliDir, platform = process.platform, arch = process.arch) {
|
|
67
|
+
const pkg = platformNodePackageName(platform, arch);
|
|
68
|
+
if (!pkg)
|
|
69
|
+
return null;
|
|
70
|
+
const executable = platform === 'win32' ? 'huddle-node.exe' : 'huddle-node';
|
|
71
|
+
try {
|
|
72
|
+
// `npm install -g` may hoist optional dependencies beside the CLI package,
|
|
73
|
+
// while a regular install commonly nests them below it. Node's resolver
|
|
74
|
+
// knows both layouts; a hard-coded `cli/node_modules` path does not.
|
|
75
|
+
const manifest = require.resolve(`${pkg}/package.json`, { paths: [path_1.default.resolve(cliDir, '..')] });
|
|
76
|
+
const entry = path_1.default.join(path_1.default.dirname(manifest), 'bin', executable);
|
|
77
|
+
return fs_1.default.existsSync(entry) ? entry : null;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// An explicitly named entry, if there is one. Resolved separately from the
|
|
84
|
+
// search path on purpose: naming a build is a claim about which one to run, so
|
|
85
|
+
// a missing file has to fail loudly rather than quietly starting a different
|
|
86
|
+
// build that happens to exist elsewhere.
|
|
87
|
+
function explicitNodeEntry(opts, env = process.env) {
|
|
88
|
+
const explicit = opts.entry ?? env.HUDDLE_NODE_ENTRY;
|
|
89
|
+
return explicit ? path_1.default.resolve(explicit) : null;
|
|
90
|
+
}
|
|
91
|
+
// Where to look when nothing was named. Pure, so the search order is testable
|
|
92
|
+
// without a filesystem full of fixtures.
|
|
93
|
+
function nodeEntryCandidates(cliDir) {
|
|
94
|
+
// A repo checkout: cli/dist/index.js → ../../gateway/dist/index.js, and the
|
|
95
|
+
// same one level up for layouts that nest the build one deeper.
|
|
96
|
+
const exe = process.platform === 'win32' ? '.exe' : '';
|
|
97
|
+
const candidates = [
|
|
98
|
+
path_1.default.resolve(cliDir, '..', '..', 'gateway', 'dist', 'index.js'),
|
|
99
|
+
path_1.default.resolve(cliDir, '..', '..', '..', 'gateway', 'dist', 'index.js'),
|
|
100
|
+
// A single executable, either beside the CLI or dropped in ~/.huddle by
|
|
101
|
+
// hand. Last, so a checkout keeps winning over a stale download when both
|
|
102
|
+
// exist — the layout of someone working ON Huddle, whose build is the one
|
|
103
|
+
// they mean.
|
|
104
|
+
path_1.default.resolve(cliDir, '..', '..', 'gateway', 'build', 'sea', `huddle-node${exe}`),
|
|
105
|
+
];
|
|
106
|
+
// A checkout takes precedence so contributors always run the code they just
|
|
107
|
+
// built. Installed CLI packages have no checkout sibling and take this path.
|
|
108
|
+
const installed = installedNodeEntry(cliDir);
|
|
109
|
+
if (installed)
|
|
110
|
+
candidates.push(installed);
|
|
111
|
+
candidates.push(path_1.default.join(os_1.default.homedir(), '.huddle', `huddle-node${exe}`));
|
|
112
|
+
return candidates;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* How to launch a resolved entry: `node build.js`, or the file on its own.
|
|
116
|
+
*
|
|
117
|
+
* Huddle Node ships two ways (gateway/scripts/build-sea.mjs). From a checkout
|
|
118
|
+
* it is gateway/dist/index.js, which needs a Node to run it. Downloaded, it IS
|
|
119
|
+
* a Node — a single executable with the whole app injected into the binary, and
|
|
120
|
+
* handing that to `node` makes it argv[1] and gets the REPL, or on Windows an
|
|
121
|
+
* ENOEXEC. The two are not distinguishable by asking the file politely, so the
|
|
122
|
+
* rule is the extension the build actually produces: .js means script, anything
|
|
123
|
+
* else means executable.
|
|
124
|
+
*
|
|
125
|
+
* Kept separate from resolveNodeEntry() because both spawn sites need it, and
|
|
126
|
+
* they are 150 lines apart — the foreground `huddle node` and the detached one
|
|
127
|
+
* `huddle init` uses.
|
|
128
|
+
*/
|
|
129
|
+
function nodeLaunch(entry) {
|
|
130
|
+
return entry.toLowerCase().endsWith('.js')
|
|
131
|
+
? { command: process.execPath, args: [entry] }
|
|
132
|
+
: { command: entry, args: [] };
|
|
133
|
+
}
|
|
134
|
+
class MissingNodeEntryError extends Error {
|
|
135
|
+
entry;
|
|
136
|
+
constructor(entry) {
|
|
137
|
+
super(`No Huddle Node build at ${entry}`);
|
|
138
|
+
this.entry = entry;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
exports.MissingNodeEntryError = MissingNodeEntryError;
|
|
142
|
+
// Returns the entry to run, or null when nothing was named and nothing was
|
|
143
|
+
// found. Throws MissingNodeEntryError when something WAS named but is absent.
|
|
144
|
+
function resolveNodeEntry(opts, cliDir, env = process.env) {
|
|
145
|
+
const explicit = explicitNodeEntry(opts, env);
|
|
146
|
+
if (explicit) {
|
|
147
|
+
if (!fs_1.default.existsSync(explicit))
|
|
148
|
+
throw new MissingNodeEntryError(explicit);
|
|
149
|
+
return explicit;
|
|
150
|
+
}
|
|
151
|
+
for (const c of nodeEntryCandidates(cliDir)) {
|
|
152
|
+
if (fs_1.default.existsSync(c))
|
|
153
|
+
return c;
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
// The environment that makes this process Huddle Node. The role IS the
|
|
158
|
+
// deployment (gateway/src/runtime-env.ts): `node` drops the proxies and moves
|
|
159
|
+
// every path off the container layout onto ~/.huddle. Anything the caller
|
|
160
|
+
// already set wins, so an operator can still point a run at a different data
|
|
161
|
+
// dir or port.
|
|
162
|
+
function nodeEnv(opts, env = process.env) {
|
|
163
|
+
const out = { ...env, HUDDLE_ROLE: 'node' };
|
|
164
|
+
if (opts.port)
|
|
165
|
+
out.HUDDLE_API_PORT = opts.port;
|
|
166
|
+
if (opts.dataDir)
|
|
167
|
+
out.HUDDLE_DATA_DIR = path_1.default.resolve(opts.dataDir);
|
|
168
|
+
// Where the GATEWAY container will reach the control channel. Loopback is the
|
|
169
|
+
// default and stays it on Docker Desktop; on native Linux `huddle init` passes
|
|
170
|
+
// the bridge address here, because a container cannot reach the host's
|
|
171
|
+
// loopback there. See cli/src/control-address.ts.
|
|
172
|
+
if (opts.controlHost)
|
|
173
|
+
out.HUDDLE_CONTROL_HOST = opts.controlHost;
|
|
174
|
+
if (opts.operatorToken)
|
|
175
|
+
out.HUDDLE_OPERATOR_TOKEN = opts.operatorToken;
|
|
176
|
+
for (const [k, v] of Object.entries(opts.extraEnv ?? {}))
|
|
177
|
+
out[k] = v;
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Where Huddle Node keeps its state. Mirrors `dataDir` in
|
|
182
|
+
* gateway/src/runtime-env.ts — the CLI has to be able to name the same
|
|
183
|
+
* directories the process it just spawned will use.
|
|
184
|
+
*/
|
|
185
|
+
function nodeDataDir(opts = {}, env = process.env) {
|
|
186
|
+
if (opts.dataDir)
|
|
187
|
+
return path_1.default.resolve(opts.dataDir);
|
|
188
|
+
return env.HUDDLE_DATA_DIR?.trim() || path_1.default.join(os_1.default.homedir(), '.huddle');
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The MITM CA directory — its own subdirectory of the data dir, and that is what
|
|
192
|
+
* makes it mountable: `huddle init` binds exactly this into the gateway
|
|
193
|
+
* read-only, while the database and the operator token stay behind.
|
|
194
|
+
*/
|
|
195
|
+
function nodeCaDir(opts = {}, env = process.env) {
|
|
196
|
+
return path_1.default.join(nodeDataDir(opts, env), 'ca');
|
|
197
|
+
}
|
|
198
|
+
/** The operator token Huddle Node persisted, or null if it has not written one. */
|
|
199
|
+
function readOperatorToken(dataDir = nodeDataDir()) {
|
|
200
|
+
try {
|
|
201
|
+
return fs_1.default.readFileSync(path_1.default.join(dataDir, 'operator-token'), 'utf8').trim() || null;
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The gateway token Huddle Node runs with — the narrow, machine-to-machine
|
|
209
|
+
* credential for the control channel (gateway/src/auth.ts). Node writes it into
|
|
210
|
+
* its data dir on first boot, so this is only readable AFTER Node is up.
|
|
211
|
+
*
|
|
212
|
+
* Deliberately not generated here. One writer for a secret means there is never
|
|
213
|
+
* a question of which copy is real.
|
|
214
|
+
*/
|
|
215
|
+
function readGatewayToken(dataDir) {
|
|
216
|
+
const fromEnv = process.env.HUDDLE_GATEWAY_TOKEN?.trim();
|
|
217
|
+
if (fromEnv)
|
|
218
|
+
return fromEnv;
|
|
219
|
+
const file = path_1.default.join(dataDir, 'gateway-token');
|
|
220
|
+
try {
|
|
221
|
+
return fs_1.default.readFileSync(file, 'utf8').trim();
|
|
222
|
+
}
|
|
223
|
+
catch (err) {
|
|
224
|
+
if (err.code !== 'ENOENT')
|
|
225
|
+
throw err;
|
|
226
|
+
// Node is up (we waited for it) but did not write its half of the pair, so
|
|
227
|
+
// it is older than the boot that mints it — say that, instead of leaking a
|
|
228
|
+
// bare ENOENT from the middle of gateway creation.
|
|
229
|
+
throw new Error(`Huddle Node has not written ${file}.\n` +
|
|
230
|
+
` It mints that token at boot, so this build of Node predates the fix.\n` +
|
|
231
|
+
` Stop it and re-run: the pid is in ${exports.NODE_PID_FILE}.`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function runNode(opts = {}) {
|
|
235
|
+
let entry;
|
|
236
|
+
try {
|
|
237
|
+
entry = resolveNodeEntry(opts, __dirname);
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
if (!(err instanceof MissingNodeEntryError))
|
|
241
|
+
throw err;
|
|
242
|
+
console.error((0, utils_1.red)(err.message));
|
|
243
|
+
console.error((0, utils_1.dim)(' Named explicitly, so no other build was tried.'));
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
if (!entry) {
|
|
247
|
+
console.error((0, utils_1.red)('No Huddle Node executable found.'));
|
|
248
|
+
console.error('');
|
|
249
|
+
console.error(' A normal npm installation includes a platform-specific Huddle Node package.');
|
|
250
|
+
console.error(' Reinstall the CLI to fetch its optional dependency:');
|
|
251
|
+
console.error((0, utils_1.cyan)(' npm install -g @infosupport/huddle-cli'));
|
|
252
|
+
console.error('');
|
|
253
|
+
console.error(' In a repo checkout, build Huddle Node first:');
|
|
254
|
+
console.error((0, utils_1.cyan)(' npm --prefix gateway install && npm --prefix gateway run build'));
|
|
255
|
+
console.error('');
|
|
256
|
+
console.error(' Or point at a build explicitly:');
|
|
257
|
+
console.error((0, utils_1.cyan)(' huddle node --entry /path/to/gateway/dist/index.js'));
|
|
258
|
+
console.error((0, utils_1.dim)(' (or set HUDDLE_NODE_ENTRY)'));
|
|
259
|
+
process.exit(1);
|
|
260
|
+
}
|
|
261
|
+
// The SEA opens SQLite during boot. A source checkout often has ~/.huddle
|
|
262
|
+
// already, but `huddle node --data-dir <new path>` must work on its own too.
|
|
263
|
+
fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
|
|
264
|
+
const env = nodeEnv(opts);
|
|
265
|
+
const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
|
|
266
|
+
console.log((0, utils_1.bold)('Huddle Node') + (0, utils_1.dim)(' — control plane, on this host'));
|
|
267
|
+
console.log(` entry ${(0, utils_1.dim)(entry)}`);
|
|
268
|
+
console.log(` portal ${(0, utils_1.cyan)(`http://localhost:${port}`)}`);
|
|
269
|
+
console.log(` data ${(0, utils_1.dim)(env.HUDDLE_DATA_DIR ?? path_1.default.join(os_1.default.homedir(), '.huddle'))}`);
|
|
270
|
+
console.log('');
|
|
271
|
+
console.log((0, utils_1.yellow)(' The firewall still lives in huddle-gateway; this process does not enforce it.'));
|
|
272
|
+
console.log((0, utils_1.dim)(' Ctrl-C to stop.'));
|
|
273
|
+
console.log('');
|
|
274
|
+
// Foreground on purpose: this is the shape you want while working ON Huddle.
|
|
275
|
+
// `huddle init` uses startNodeDetached() below. stdio inherit so Huddle Node's
|
|
276
|
+
// own logging is what the operator sees.
|
|
277
|
+
await new Promise((resolve) => {
|
|
278
|
+
const launch = nodeLaunch(entry);
|
|
279
|
+
const child = (0, child_process_1.spawn)(launch.command, launch.args, { env, stdio: 'inherit' });
|
|
280
|
+
// Forward the signals an operator actually sends, so Ctrl-C stops Huddle
|
|
281
|
+
// Node rather than orphaning it behind a dead CLI.
|
|
282
|
+
const forward = (sig) => () => { try {
|
|
283
|
+
child.kill(sig);
|
|
284
|
+
}
|
|
285
|
+
catch { /* already gone */ } };
|
|
286
|
+
const onInt = forward('SIGINT');
|
|
287
|
+
const onTerm = forward('SIGTERM');
|
|
288
|
+
process.on('SIGINT', onInt);
|
|
289
|
+
process.on('SIGTERM', onTerm);
|
|
290
|
+
child.on('error', (err) => {
|
|
291
|
+
console.error((0, utils_1.red)(`Failed to start Huddle Node: ${err.message}`));
|
|
292
|
+
process.exitCode = 1;
|
|
293
|
+
resolve();
|
|
294
|
+
});
|
|
295
|
+
child.on('exit', (code, signal) => {
|
|
296
|
+
process.off('SIGINT', onInt);
|
|
297
|
+
process.off('SIGTERM', onTerm);
|
|
298
|
+
if (signal)
|
|
299
|
+
console.log((0, utils_1.dim)(`\nHuddle Node stopped (${signal}).`));
|
|
300
|
+
else if (code)
|
|
301
|
+
process.exitCode = code;
|
|
302
|
+
resolve();
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
// ── Detached lifecycle (what `huddle init` uses) ─────────────────────────────
|
|
307
|
+
//
|
|
308
|
+
// Huddle Node has to outlive the shell `huddle init` was typed in, so init
|
|
309
|
+
// spawns it detached and remembers the pid. Two files in ~/.huddle: the pid, and
|
|
310
|
+
// a log, because a background process with nowhere to write its output is a
|
|
311
|
+
// process you cannot debug.
|
|
312
|
+
//
|
|
313
|
+
// The pid file is a hint, not a lock. A pid can be recycled, so isNodeRunning()
|
|
314
|
+
// treats it as "worth probing" and the HTTP health check is what actually
|
|
315
|
+
// decides whether Huddle Node is up — see waitForNode().
|
|
316
|
+
exports.NODE_PID_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.pid');
|
|
317
|
+
exports.NODE_LOG_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.log');
|
|
318
|
+
// The control host the running Node was actually started with — see
|
|
319
|
+
// startNodeDetached()'s mismatch check below. Written beside the pid file
|
|
320
|
+
// because the two describe the same process and go stale together.
|
|
321
|
+
exports.NODE_CONTROL_HOST_FILE = path_1.default.join(config_1.CONFIG_DIR, 'node.control-host');
|
|
322
|
+
/**
|
|
323
|
+
* Collapse "unset" to the address nodeEnv/resolveControlAddress default to, so
|
|
324
|
+
* an unset request compares equal to a previous unset run instead of the empty
|
|
325
|
+
* string never matching anything. 127.0.0.1 is that default on both sides:
|
|
326
|
+
* nodeEnv() only sets HUDDLE_CONTROL_HOST when opts.controlHost is given, and
|
|
327
|
+
* control-address.ts's derive() falls back to the same loopback literal.
|
|
328
|
+
*/
|
|
329
|
+
function normalizeControlHost(host) {
|
|
330
|
+
return host?.trim() || '127.0.0.1';
|
|
331
|
+
}
|
|
332
|
+
/** The URL a HUMAN talks to Huddle Node on: printed, opened in a browser. */
|
|
333
|
+
function nodeUrl(port = exports.DEFAULT_NODE_PORT) {
|
|
334
|
+
return `http://localhost:${port}`;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* The addresses the CLI itself talks to Huddle Node on — loopback literals, in
|
|
338
|
+
* order, not the name `localhost`.
|
|
339
|
+
*
|
|
340
|
+
* Node binds ONE address (runtime-env.ts's apiBindHost: 127.0.0.1 in host mode),
|
|
341
|
+
* while `localhost` is two — and on Windows it resolves to ::1 first, where
|
|
342
|
+
* nothing listens. A browser papers over that with Happy Eyeballs, and so does a
|
|
343
|
+
* recent enough Node; an older one just fails. That combination is nasty,
|
|
344
|
+
* because it makes Huddle look half-installed rather than broken: the portal
|
|
345
|
+
* opens fine, but `huddle init` sits out its 30s probe against a perfectly
|
|
346
|
+
* healthy process and exits BEFORE it ever creates the gateway container.
|
|
347
|
+
*
|
|
348
|
+
* So probe the literals and accept whichever answers. HUDDLE_API_HOST wins when
|
|
349
|
+
* set, since then Node is not on loopback at all.
|
|
350
|
+
*/
|
|
351
|
+
function nodeProbeUrls(port = exports.DEFAULT_NODE_PORT) {
|
|
352
|
+
const bound = process.env.HUDDLE_API_HOST?.trim();
|
|
353
|
+
if (bound && bound !== '0.0.0.0' && bound !== '::') {
|
|
354
|
+
const host = bound.includes(':') && !bound.startsWith('[') ? `[${bound}]` : bound;
|
|
355
|
+
return [`http://${host}:${port}`];
|
|
356
|
+
}
|
|
357
|
+
return [`http://127.0.0.1:${port}`, `http://[::1]:${port}`];
|
|
358
|
+
}
|
|
359
|
+
function readNodePid() {
|
|
360
|
+
try {
|
|
361
|
+
const pid = Number(fs_1.default.readFileSync(exports.NODE_PID_FILE, 'utf8').trim());
|
|
362
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** The control host the running Node was actually started with, or null if unknown. */
|
|
369
|
+
function readNodeControlHost() {
|
|
370
|
+
try {
|
|
371
|
+
return fs_1.default.readFileSync(exports.NODE_CONTROL_HOST_FILE, 'utf8').trim() || null;
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
/** Does the recorded pid still name a live process? Says nothing about whether it is Huddle Node. */
|
|
378
|
+
function isNodePidAlive() {
|
|
379
|
+
const pid = readNodePid();
|
|
380
|
+
if (pid === null)
|
|
381
|
+
return false;
|
|
382
|
+
try {
|
|
383
|
+
process.kill(pid, 0);
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Is Huddle Node answering? /api/auth/status is the probe: it needs no operator
|
|
392
|
+
* token (api.ts keeps it public so the portal can find out whether login is
|
|
393
|
+
* needed), so a 200 here means the API is up, not merely that a port is open.
|
|
394
|
+
*/
|
|
395
|
+
async function pingNode(port, timeoutMs = 1500) {
|
|
396
|
+
const ac = new AbortController();
|
|
397
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
398
|
+
try {
|
|
399
|
+
for (const base of nodeProbeUrls(port)) {
|
|
400
|
+
try {
|
|
401
|
+
const res = await fetch(`${base}/api/auth/status`, { signal: ac.signal });
|
|
402
|
+
if (res.ok)
|
|
403
|
+
return true;
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
// Wrong family, or not up yet. Try the next address, then the next tick.
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return false;
|
|
410
|
+
}
|
|
411
|
+
finally {
|
|
412
|
+
clearTimeout(timer);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
async function waitForNode(port, timeoutMs = 30_000) {
|
|
416
|
+
const deadline = Date.now() + timeoutMs;
|
|
417
|
+
for (;;) {
|
|
418
|
+
if (await pingNode(port))
|
|
419
|
+
return true;
|
|
420
|
+
if (Date.now() >= deadline)
|
|
421
|
+
return false;
|
|
422
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async function stopNode() {
|
|
426
|
+
const pid = readNodePid();
|
|
427
|
+
if (pid === null)
|
|
428
|
+
return false;
|
|
429
|
+
try {
|
|
430
|
+
process.kill(pid, 'SIGTERM');
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
// Already gone. Clearing the pid file below is still the right cleanup.
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
fs_1.default.unlinkSync(exports.NODE_PID_FILE);
|
|
437
|
+
}
|
|
438
|
+
catch { /* nothing to clean up */ }
|
|
439
|
+
try {
|
|
440
|
+
fs_1.default.unlinkSync(exports.NODE_CONTROL_HOST_FILE);
|
|
441
|
+
}
|
|
442
|
+
catch { /* nothing to clean up */ }
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* stopNode(), then wait until Huddle Node has actually gone quiet. SIGTERM is
|
|
447
|
+
* not instant, and a caller about to spawn a replacement on the same port needs
|
|
448
|
+
* to know the old process is truly down, not merely asked to leave — otherwise
|
|
449
|
+
* the new one can lose the race for the port, or the old one keeps answering
|
|
450
|
+
* and gets mistaken for the new one. Shared by startNodeDetached()'s own
|
|
451
|
+
* mismatch handling and init.ts's control-channel rebind.
|
|
452
|
+
*/
|
|
453
|
+
async function stopNodeAndWait(port, timeoutMs = 10_000) {
|
|
454
|
+
if (!(await stopNode()))
|
|
455
|
+
return true; // nothing was running
|
|
456
|
+
const deadline = Date.now() + timeoutMs;
|
|
457
|
+
while (await pingNode(port)) {
|
|
458
|
+
if (Date.now() >= deadline)
|
|
459
|
+
return false;
|
|
460
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
461
|
+
}
|
|
462
|
+
return true;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Start Huddle Node in the background and wait until it answers.
|
|
466
|
+
*
|
|
467
|
+
* Refuses to spawn a second one: two Huddle Nodes on one machine would both open
|
|
468
|
+
* the same SQLite file and both hand the gateway a policy feed, and only one of
|
|
469
|
+
* them would own the port. If one is already answering AND bound to the control
|
|
470
|
+
* host this call is asking for, that one is used.
|
|
471
|
+
*
|
|
472
|
+
* That second condition matters because the API (what pingNode checks) always
|
|
473
|
+
* listens on loopback regardless of HUDDLE_CONTROL_HOST — so a Node started with
|
|
474
|
+
* a different control host still answers the ping. Reusing it anyway would hand
|
|
475
|
+
* the gateway a control URL nothing is listening on: it fails closed, so every
|
|
476
|
+
* devcontainer is denied all egress while init reports success. So a running
|
|
477
|
+
* Node bound to a different host than requested is stopped and replaced here,
|
|
478
|
+
* rather than reused — see NODE_CONTROL_HOST_FILE.
|
|
479
|
+
*/
|
|
480
|
+
async function startNodeDetached(opts = {}) {
|
|
481
|
+
const env = nodeEnv(opts);
|
|
482
|
+
const port = env.HUDDLE_API_PORT ?? String(exports.DEFAULT_NODE_PORT);
|
|
483
|
+
const requestedControlHost = normalizeControlHost(opts.controlHost);
|
|
484
|
+
// Resolved before anything is stopped: if the replacement build can't be
|
|
485
|
+
// found, a mismatched-host Node below should be left running rather than
|
|
486
|
+
// killed and not replaced.
|
|
487
|
+
const entry = resolveNodeEntry(opts, __dirname);
|
|
488
|
+
if (!entry)
|
|
489
|
+
throw new MissingNodeEntryError(nodeEntryCandidates(__dirname)[0]);
|
|
490
|
+
if (await pingNode(port)) {
|
|
491
|
+
const runningControlHost = normalizeControlHost(readNodeControlHost() ?? undefined);
|
|
492
|
+
if (runningControlHost === requestedControlHost) {
|
|
493
|
+
return { pid: readNodePid() ?? 0, entry: '(already running)', port, reused: true };
|
|
494
|
+
}
|
|
495
|
+
// Bound to a different control host than asked for: stop it and fall
|
|
496
|
+
// through to spawn a fresh one on the requested host, rather than silently
|
|
497
|
+
// reusing a process the gateway would never actually be able to reach.
|
|
498
|
+
if (!(await stopNodeAndWait(port))) {
|
|
499
|
+
throw new Error(`Huddle Node is running on the old control host (${runningControlHost}) and did not stop in time ` +
|
|
500
|
+
`to rebind to ${requestedControlHost}.\n` +
|
|
501
|
+
` Stop it manually (pid in ${exports.NODE_PID_FILE}) and re-run.`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
fs_1.default.mkdirSync(config_1.CONFIG_DIR, { recursive: true });
|
|
505
|
+
fs_1.default.mkdirSync(nodeDataDir(opts), { recursive: true, mode: 0o700 });
|
|
506
|
+
// Append, not truncate: the log of the run that just failed is usually the
|
|
507
|
+
// thing you need after a restart.
|
|
508
|
+
const log = fs_1.default.openSync(exports.NODE_LOG_FILE, 'a');
|
|
509
|
+
const launch = nodeLaunch(entry);
|
|
510
|
+
const child = (0, child_process_1.spawn)(launch.command, launch.args, {
|
|
511
|
+
env,
|
|
512
|
+
detached: true,
|
|
513
|
+
stdio: ['ignore', log, log],
|
|
514
|
+
windowsHide: true,
|
|
515
|
+
});
|
|
516
|
+
child.unref();
|
|
517
|
+
fs_1.default.closeSync(log);
|
|
518
|
+
if (child.pid) {
|
|
519
|
+
fs_1.default.writeFileSync(exports.NODE_PID_FILE, String(child.pid));
|
|
520
|
+
fs_1.default.writeFileSync(exports.NODE_CONTROL_HOST_FILE, requestedControlHost);
|
|
521
|
+
}
|
|
522
|
+
if (!(await waitForNode(port))) {
|
|
523
|
+
// Alive-but-unreachable and dead are different bugs with the same symptom,
|
|
524
|
+
// and the difference is the first thing you want to know: init stops here,
|
|
525
|
+
// so the gateway container is never created and Huddle looks half-installed.
|
|
526
|
+
const stillRunning = child.pid ? isNodePidAlive() : false;
|
|
527
|
+
throw new Error(`Huddle Node did not come up on ${nodeProbeUrls(port).join(' or ')} within 30s.\n` +
|
|
528
|
+
(stillRunning
|
|
529
|
+
? ` The process (pid ${child.pid}) is still running, so it started but is not answering there.\n`
|
|
530
|
+
: ` The process is gone, so it failed during startup.\n`) +
|
|
531
|
+
` Check ${exports.NODE_LOG_FILE} — it holds everything the process printed.`);
|
|
532
|
+
}
|
|
533
|
+
return { pid: child.pid ?? 0, entry, port, reused: false };
|
|
534
|
+
}
|