@infosupport/huddle-cli 0.0.0-experiment-98.63.1 → 0.0.0-experiment-109.66.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/dist/init.js CHANGED
@@ -1,19 +1,210 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ // `huddle init` — bring up both halves of Huddle.
3
+ //
4
+ // Huddle is two processes now (docs/ADR-huddle-node-split.md):
5
+ //
6
+ // Huddle Node on the HOST — portal, API, database, CA, Docker
7
+ // orchestration, sbx. Started here, detached.
8
+ // huddle-gateway in a CONTAINER — the filtering proxies devcontainers are
9
+ // DNAT'ed to, and nothing else.
10
+ //
11
+ // Order matters: Node owns the database, the CA and the gateway token, so it has
12
+ // to exist before there is anything for the gateway to be handed. The container
13
+ // is started second and given exactly three things — where Node is, the token to
14
+ // talk to it with, and the CA directory read-only.
15
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || (function () {
32
+ var ownKeys = function(o) {
33
+ ownKeys = Object.getOwnPropertyNames || function (o) {
34
+ var ar = [];
35
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
36
+ return ar;
37
+ };
38
+ return ownKeys(o);
39
+ };
40
+ return function (mod) {
41
+ if (mod && mod.__esModule) return mod;
42
+ var result = {};
43
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
44
+ __setModuleDefault(result, mod);
45
+ return result;
46
+ };
47
+ })();
5
48
  Object.defineProperty(exports, "__esModule", { value: true });
6
49
  exports.HOST_SOCKET_DIR = exports.INTERNAL_NET = void 0;
7
50
  exports.runInit = runInit;
8
51
  const child_process_1 = require("child_process");
9
- const crypto_1 = __importDefault(require("crypto"));
10
52
  const utils_1 = require("./utils");
11
53
  const runtime_1 = require("./runtime");
12
54
  const images_1 = require("./images");
13
55
  const config_1 = require("./config");
14
- const fs_1 = __importDefault(require("fs"));
56
+ const control_address_1 = require("./control-address");
57
+ const control_probe_1 = require("./control-probe");
58
+ const node_1 = require("./node");
15
59
  const CONTAINER = 'huddle';
16
- const VOLUME = 'huddle-data';
60
+ /**
61
+ * Ask Huddle Node to wire the freshly created gateway into every devcontainer.
62
+ *
63
+ * The container above is brand new, so each existing devcontainer is attached to
64
+ * a `huddle` that no longer exists and DNATs port 80 to an IP that is gone —
65
+ * which is silent, not loud: the devcontainer just stops reaching anything.
66
+ *
67
+ * Node does this itself at boot, but that only covers a first install. Re-running
68
+ * init reuses the Node that is already up while replacing the container, so the
69
+ * request has to come from here. Node's job and not the CLI's, because rebuilding
70
+ * those rules means exec'ing into every devcontainer.
71
+ *
72
+ * Best-effort: a gateway that is up but not yet wired is worth reporting, not
73
+ * worth failing init over — the portal offers a per-container reconnect too.
74
+ */
75
+ async function rewireGateway(port, token) {
76
+ const url = `${(0, node_1.nodeProbeUrls)(port)[0]}/api/docker/rewire-gateway`;
77
+ try {
78
+ const res = await fetch(url, {
79
+ method: 'POST',
80
+ headers: token ? { authorization: `Bearer ${token}` } : {},
81
+ });
82
+ if (!res.ok)
83
+ throw new Error(`HTTP ${res.status}`);
84
+ const rep = (await res.json());
85
+ const attached = rep.attached?.length ?? 0;
86
+ const reissued = rep.reissued?.length ?? 0;
87
+ console.log((0, utils_1.dim)(` wired into ${attached} devcontainer network(s), ${rep.refreshed?.length ?? 0} refreshed`));
88
+ // Only when it happened: a container that already trusted this root is the
89
+ // normal case and says nothing. A container that did NOT is worth seeing,
90
+ // because until this ran its HTTPS was failing on the CA signature.
91
+ if (reissued)
92
+ console.log((0, utils_1.dim)(` root CA reinstalled in ${reissued} devcontainer(s)`));
93
+ }
94
+ catch (err) {
95
+ console.log((0, utils_1.yellow)(`[!] Could not wire the gateway into the devcontainer networks: ${err.message}`));
96
+ console.log((0, utils_1.dim)(' Existing devcontainers may not reach Huddle until you reconnect them in the portal.'));
97
+ }
98
+ }
99
+ /**
100
+ * Confirm the gateway can actually reach Huddle Node — and move the control
101
+ * channel if it cannot.
102
+ *
103
+ * resolveControlAddress() derives an address from what the engine reports about
104
+ * itself, and that derivation is right until it is not: on Rancher Desktop for
105
+ * Windows the engine is a WSL distro, so `host.docker.internal` resolves to that
106
+ * distro's own docker0 gateway while Huddle Node is a Windows process on the
107
+ * Windows loopback. Both halves are healthy and they cannot see each other.
108
+ *
109
+ * There is no way to tell that from a derivation, and getting it wrong is
110
+ * expensive: the gateway fails closed, so every devcontainer is denied all
111
+ * egress and nothing appears in the portal to approve — a firewall that looks
112
+ * installed and blocks everything. So open the connection for real, from the
113
+ * gateway's own image on the gateway's own network, and believe the result.
114
+ *
115
+ * `rebind` restarts Huddle Node on a different interface and reports whether it
116
+ * managed to. Passed in rather than done here because init owns the options
117
+ * Node was started with.
118
+ */
119
+ async function verifyControlChannel(rt, image, network, control, rebind) {
120
+ const first = (0, control_probe_1.probeControlUrl)(rt, image, control.url, network, control.runArgs);
121
+ if (first.reachable) {
122
+ console.log((0, utils_1.dim)(` reachable from a container at ${control.url} (${first.detail})`));
123
+ return { ...control, reachable: true };
124
+ }
125
+ const unreachable = (fixed, detail) => {
126
+ console.log((0, utils_1.yellow)(`[!] The gateway cannot reach Huddle Node at ${fixed.url} (${detail}).`));
127
+ console.log((0, utils_1.yellow)(' It fails closed, so every devcontainer will be denied all egress and'));
128
+ console.log((0, utils_1.yellow)(' nothing will show up in the portal to approve.'));
129
+ return { ...fixed, reachable: false };
130
+ };
131
+ // An address someone named by hand is not ours to overrule — they know their
132
+ // own topology, and silently moving the channel would hide the real problem.
133
+ if (process.env.HUDDLE_NODE_CONTROL_URL?.trim() || process.env.HUDDLE_CONTROL_HOST?.trim()) {
134
+ const out = unreachable(control, first.detail);
135
+ console.log((0, utils_1.dim)(' That address was set explicitly, so it is left as it is.'));
136
+ return out;
137
+ }
138
+ console.log((0, utils_1.dim)(` ${control.url} did not answer (${first.detail}) — looking for an address that does`));
139
+ const vmGateway = (0, control_probe_1.engineHostAddress)(rt, image);
140
+ // Cheapest first: another way for the container to reach the loopback Node is
141
+ // already bound to. Nothing restarts, and nothing about how Huddle is exposed
142
+ // changes — so this is the outcome to want, not merely the quickest one.
143
+ for (const url of (0, control_probe_1.hostCandidateUrls)(CONTROL_PORT, vmGateway)) {
144
+ const probe = (0, control_probe_1.probeControlUrl)(rt, image, url, network, []);
145
+ if (!probe.reachable)
146
+ continue;
147
+ console.log((0, utils_1.dim)(` reachable from a container at ${url} (${probe.detail})`));
148
+ return {
149
+ bindHost: control.bindHost,
150
+ url,
151
+ runArgs: [],
152
+ reason: `${control_address_1.HOST_ALIAS} does not reach this machine from ${rt}; ${new URL(url).hostname} does`,
153
+ reachable: true,
154
+ };
155
+ }
156
+ // Nothing reaches loopback, so Huddle Node has to move to an interface the
157
+ // engine can route to. Only an address this machine actually owns: the
158
+ // engine's own gateway is not one, and binding it kills Node outright.
159
+ const bindIp = (0, control_probe_1.pickBindAddress)((0, control_probe_1.localIpv4Addresses)(), vmGateway);
160
+ if (!bindIp) {
161
+ const out = unreachable(control, first.detail);
162
+ console.log((0, utils_1.dim)(` Tried every address ${rt} suggested${vmGateway ? ` (its gateway is ${vmGateway})` : ''}.`));
163
+ console.log((0, utils_1.dim)(' Name one yourself and re-run init:'));
164
+ console.log((0, utils_1.cyan)(' HUDDLE_CONTROL_HOST=<address the container reaches this machine on> huddle init'));
165
+ return out;
166
+ }
167
+ const moved = {
168
+ bindHost: bindIp,
169
+ url: `http://${bindIp}:${CONTROL_PORT}`,
170
+ runArgs: [],
171
+ reason: `${control_address_1.HOST_ALIAS} does not reach this machine; ${rt} routes to it at ${bindIp}`,
172
+ reachable: false,
173
+ };
174
+ console.log((0, utils_1.dim)(` moving the control channel to ${bindIp} and restarting Huddle Node`));
175
+ if (!(await rebind(bindIp))) {
176
+ // Put it back where it was. A control channel that does not work is a broken
177
+ // firewall; no Huddle Node at all is a broken machine — no portal, no API,
178
+ // and init about to hand the gateway a token it cannot read.
179
+ console.log((0, utils_1.yellow)(`[!] Huddle Node would not start on ${bindIp} — restoring ${control.bindHost}.`));
180
+ if (!(await rebind(control.bindHost))) {
181
+ console.log((0, utils_1.red)(' It would not start there either. Check the log:'));
182
+ console.log((0, utils_1.cyan)(` ${node_1.NODE_LOG_FILE}`));
183
+ }
184
+ const out = unreachable(control, first.detail);
185
+ console.log((0, utils_1.dim)(' Name an address yourself and re-run init:'));
186
+ console.log((0, utils_1.cyan)(' HUDDLE_CONTROL_HOST=<address the container reaches this machine on> huddle init'));
187
+ return out;
188
+ }
189
+ const second = (0, control_probe_1.probeControlUrl)(rt, image, moved.url, network, []);
190
+ if (second.reachable) {
191
+ console.log((0, utils_1.dim)(` reachable from a container at ${moved.url} (${second.detail})`));
192
+ return { ...moved, reachable: true };
193
+ }
194
+ const out = unreachable(moved, second.detail);
195
+ console.log((0, utils_1.dim)(` ${rt} routes to this machine at ${bindIp} and Huddle Node is bound there,`));
196
+ console.log((0, utils_1.dim)(' so something here is dropping the connection. On Windows that is Defender'));
197
+ console.log((0, utils_1.dim)(` Firewall: allow inbound TCP ${CONTROL_PORT} for node.exe on that adapter.`));
198
+ console.log((0, utils_1.dim)(' Nothing needs re-running afterwards — the gateway keeps retrying.'));
199
+ return out;
200
+ }
201
+ /**
202
+ * Huddle Node's control channel on the host. Its own port, never the portal's:
203
+ * the portal carries the operator token and stays on loopback, while this one
204
+ * may have to be reachable from the gateway container. Must match
205
+ * HUDDLE_CONTROL_PORT in gateway/src/runtime-env.ts.
206
+ */
207
+ const CONTROL_PORT = Number(process.env.HUDDLE_CONTROL_PORT ?? 24843);
17
208
  /**
18
209
  * The shared, internal network that `huddle init` creates (`--internal`, so it
19
210
  * has no route to the internet of its own). Devcontainers attach to it to reach
@@ -28,7 +219,7 @@ exports.INTERNAL_NET = 'devcontainer-net';
28
219
  * `huddle migrate` can generate the matching bind mount.
29
220
  */
30
221
  exports.HOST_SOCKET_DIR = '/tmp/dc-sockets';
31
- const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
222
+ const HOST_PORT = process.env.HUDDLE_PORT ?? String(node_1.DEFAULT_NODE_PORT);
32
223
  // Run a binary with an argv array — NO shell. Values that originate from config
33
224
  // (team-folder paths, which are writable via `huddle firewall folder set` and the
34
225
  // authenticated settings API) must never be interpolated into a shell string, or
@@ -45,6 +236,23 @@ function runArgsSilent(file, args) {
45
236
  return false;
46
237
  }
47
238
  }
239
+ /**
240
+ * Report where each devcontainer's filtered Docker socket will be served.
241
+ *
242
+ * On the ENGINE host, and by the GATEWAY — which is the only process guaranteed
243
+ * to be there. Huddle Node is on the operator's machine, and that is the engine
244
+ * host only when the engine is native: on Docker Desktop, Rancher and `podman
245
+ * machine` the engine lives in a VM, so a socket Node created would sit on
246
+ * macOS/Windows while the devcontainer mounts one out of the VM. Node keeps the
247
+ * filter — the security boundary — and the gateway tunnels each connection to
248
+ * it over the control channel (gateway/src/control/socket-relay-protocol.ts).
249
+ *
250
+ * Nothing to create here, therefore: the directory is the gateway's bind mount,
251
+ * and the engine makes it on the engine side when it does not exist.
252
+ */
253
+ function reportSocketDir() {
254
+ console.log((0, utils_1.dim)(`Socket directory: ${exports.HOST_SOCKET_DIR} (on the engine host, served by the gateway)`));
255
+ }
48
256
  /**
49
257
  * Pulls the devcontainer base images ahead of time. Best-effort: if an image is
50
258
  * not (yet) available in the registry, we only warn — the gateway then builds it
@@ -89,112 +297,169 @@ async function runInit(opts, images) {
89
297
  runArgs(rt, ['pull', IMAGE]);
90
298
  pullBaseImages(rt, images.baseImages.map((b) => b.image));
91
299
  }
92
- console.log((0, utils_1.dim)(`Volume: ${VOLUME}`));
93
- runArgsSilent(rt, ['volume', 'inspect', VOLUME]) || runArgs(rt, ['volume', 'create', VOLUME]);
94
300
  console.log((0, utils_1.dim)(`Network: ${exports.INTERNAL_NET}`));
95
301
  runArgsSilent(rt, ['network', 'inspect', exports.INTERNAL_NET]) || runArgs(rt, ['network', 'create', '--internal', exports.INTERNAL_NET]);
96
302
  console.log((0, utils_1.dim)(`Removing old container if it exists`));
97
303
  runArgsSilent(rt, ['rm', '-f', CONTAINER]);
98
- console.log((0, utils_1.dim)(`Socket directory: /tmp/dc-sockets`));
99
- // The mount SOURCE must be the path on the Docker ENGINE host (on Windows:
100
- // the WSL2/Linux VM), even when the CLI itself runs on Windows. The gateway
101
- // (SOCKET_DIR in docker.ts) and every devcontainer socket mount rely on
102
- // /tmp/dc-sockets on the engine host; mounting a Windows temp dir splits
103
- // gateway and devcontainers across two filesystems, and Unix sockets are
104
- // unreliable on such a drvfs/9p mount anyway.
105
- const hostTmpSockets = exports.HOST_SOCKET_DIR;
106
- if (runtime.isRemote) {
107
- if (runtime.name === 'podman') {
108
- // Podman does NOT create a missing bind source itself (unlike Docker
109
- // Desktop) and fails with "statfs: no such file or directory". So create
110
- // the directory explicitly in the machine VM; the socket lives there too.
111
- console.log((0, utils_1.dim)(` (Podman: creating ${hostTmpSockets} in the machine VM)`));
112
- if (!runArgsSilent('podman', ['machine', 'ssh', `mkdir -p ${hostTmpSockets}`])) {
113
- console.log((0, utils_1.yellow)(`[!] Could not create ${hostTmpSockets} in the Podman VM.`));
114
- }
115
- }
116
- else {
117
- // Docker Desktop creates a missing bind source itself in the VM on `run`.
118
- console.log((0, utils_1.dim)(` (${runtime.name}: the engine creates ${hostTmpSockets} in the VM)`));
119
- }
120
- }
121
- else {
122
- try {
123
- fs_1.default.mkdirSync(hostTmpSockets, { recursive: true });
124
- }
125
- catch (err) {
126
- console.log((0, utils_1.yellow)(`[!] Could not create ${hostTmpSockets}: ${err}`));
127
- }
128
- }
129
- console.log((0, utils_1.dim)(`Starting container`));
130
- // The gateway is engine-agnostic (talks the Docker-compatible API on the
131
- // mounted socket), but does need to know it's Podman: it then sets
132
- // `--security-opt label=disable` on every devcontainer so it can reach the
133
- // SELinux-labeled proxy socket. (Applied as argv below via runtime.securityOpts.)
134
- // Operator token for control-plane auth. Reuse the token from the config (so an
135
- // existing browser session/CLI keeps working across re-inits), otherwise
136
- // generate one. We pass it to the gateway via env AND store it locally so that
137
- // subsequent `huddle` commands can authenticate.
304
+ reportSocketDir();
305
+ // ── Huddle Node, on this host ──────────────────────────────────────────────
306
+ //
307
+ // First, because it owns everything the gateway is about to be handed: the
308
+ // database, the CA, and the gateway token.
309
+ // Operator token for the portal and the CLI. Reuse the one in the config (so an
310
+ // existing browser session keeps working across re-inits), otherwise let Huddle
311
+ // Node mint one on first boot and read it back.
138
312
  const cfg = (0, config_1.readConfig)();
139
- const operatorToken = process.env.HUDDLE_OPERATOR_TOKEN?.trim() ||
140
- (cfg.operatorToken && cfg.operatorToken.trim()) ||
141
- crypto_1.default.randomBytes(32).toString('base64url');
142
- if (cfg.operatorToken !== operatorToken) {
143
- (0, config_1.updateConfig)({ operatorToken });
144
- }
145
- // The container is created on the engine's default network first (with -p),
146
- // then joins devcontainer-net (--internal) afterwards: Docker skips the host
147
- // port-forward entirely when a container is created directly on an --internal
148
- // network (moby/moby#36174). Which source IP the gateway sees for forwarded
149
- // traffic no longer matters — the control plane authenticates with the
150
- // operator token instead of source-IP filtering.
151
- // Team-managed folders (#69). Bind the CLI config dir (~/.huddle) read-write so
152
- // the gateway/portal read and write the folder paths there (config.json is the
153
- // single source of truth), then bind each configured team folder to a FIXED
154
- // path so the gateway reads it without knowing the host path. The firewall-rules
155
- // folder is bound read-write so the portal's "Sync to folder" can write the
156
- // groups back out; extensions stay read-only (loaded, never written).
313
+ const operatorToken = process.env.HUDDLE_OPERATOR_TOKEN?.trim() || cfg.operatorToken?.trim();
314
+ // Team-managed folders (#69). These used to be bind mounts into the container
315
+ // at fixed paths, because the gateway could not see the host filesystem. Huddle
316
+ // Node runs ON the host, so it just reads the paths where they are.
157
317
  const fwFolder = cfg.firewallRulesFolder?.trim();
158
318
  const extFolder = cfg.extensionsFolder?.trim();
159
319
  if (fwFolder)
160
- console.log((0, utils_1.dim)(` Mounting firewall-rules folder: ${fwFolder} -> /firewall-rules`));
320
+ console.log((0, utils_1.dim)(` Firewall-rules folder: ${fwFolder}`));
161
321
  if (extFolder)
162
- console.log((0, utils_1.dim)(` Mounting extensions folder: ${extFolder} -> /extensions`));
163
- // Build the container command as an argv array (runArgs → execFileSync, no
164
- // shell). The folder paths below come from config and are operator-writable via
165
- // the settings API, so they must never reach a shell as a string.
322
+ console.log((0, utils_1.dim)(` Extensions folder: ${extFolder}`));
323
+ // Where the gateway will look for the control channel, and therefore which
324
+ // interface Node has to bind it on. The two are one decision, so they are
325
+ // resolved together (control-address.ts).
326
+ let control = (0, control_address_1.resolveControlAddress)({
327
+ isRemote: runtime.isRemote,
328
+ port: CONTROL_PORT,
329
+ gatewayIp: (0, control_address_1.bridgeGateway)(rt, runtime.defaultNetwork),
330
+ override: process.env.HUDDLE_NODE_CONTROL_URL,
331
+ bindOverride: process.env.HUDDLE_CONTROL_HOST,
332
+ });
333
+ console.log((0, utils_1.dim)('Starting Huddle Node (host)'));
334
+ // Deliberately NOT passed as environment: Huddle Node reads both folders from
335
+ // this same config file, per call. Handing them over at startup would freeze
336
+ // them for the lifetime of the process — and since startNodeDetached() reuses
337
+ // an already-running Node, even `huddle restart` would not always refresh it.
338
+ const extraEnv = { ...(0, images_1.baseImageEnv)(images), HUDDLE_RUNTIME: runtime.name };
339
+ let node;
340
+ try {
341
+ node = await (0, node_1.startNodeDetached)({
342
+ port: HOST_PORT,
343
+ controlHost: control.bindHost,
344
+ operatorToken,
345
+ extraEnv,
346
+ });
347
+ }
348
+ catch (err) {
349
+ if (err instanceof node_1.MissingNodeEntryError) {
350
+ console.error((0, utils_1.red)('No Huddle Node build found — Huddle cannot start without one.'));
351
+ console.error('');
352
+ console.error(' In a repo checkout, build it first:');
353
+ console.error((0, utils_1.cyan)(' npm --prefix gateway install && npm --prefix gateway run build'));
354
+ console.error((0, utils_1.dim)(' Or point at an existing build with HUDDLE_NODE_ENTRY.'));
355
+ process.exit(1);
356
+ }
357
+ throw err;
358
+ }
359
+ console.log((0, utils_1.dim)(node.reused
360
+ ? ` already running on ${(0, node_1.nodeUrl)(node.port)}`
361
+ : ` pid ${node.pid}, log ${node_1.NODE_LOG_FILE}`));
362
+ console.log((0, utils_1.dim)(` control channel: ${control.bindHost}:${CONTROL_PORT} — ${control.reason}`));
363
+ // Both halves are up; now prove they can see each other, before the gateway is
364
+ // handed an address it may never reach.
365
+ control = await verifyControlChannel(rt, IMAGE, runtime.defaultNetwork, control, async (bindHost) => {
366
+ // startNodeDetached() now recognizes a running Node bound to a different
367
+ // control host than requested and stops-and-restarts it on its own
368
+ // (cli/src/node.ts) — so naming the new host here is enough.
369
+ try {
370
+ node = await (0, node_1.startNodeDetached)({ port: HOST_PORT, controlHost: bindHost, operatorToken, extraEnv });
371
+ return true;
372
+ }
373
+ catch {
374
+ // Reported by the caller, which knows whether this was the move or the
375
+ // rollback. Throwing here would abort init with Huddle Node already down.
376
+ return false;
377
+ }
378
+ });
379
+ // Huddle Node persists the token it generated on first boot; from here on the
380
+ // CLI reads it rather than inventing one.
381
+ const token = operatorToken ?? (0, node_1.readOperatorToken)();
382
+ if (token && cfg.operatorToken !== token)
383
+ (0, config_1.updateConfig)({ operatorToken: token });
384
+ // ── huddle-gateway, in a container ─────────────────────────────────────────
385
+ //
386
+ // What it gets is the whole list: where Node is, the token to talk to Node
387
+ // with, and the CA directory read-only. No Docker socket, no database volume,
388
+ // no config, no published portal — none of which it can use any more, and each
389
+ // of which was reachable from a devcontainer.
390
+ console.log((0, utils_1.dim)('Starting huddle-gateway (container)'));
391
+ const gatewayToken = (0, node_1.readGatewayToken)((0, node_1.nodeDataDir)());
166
392
  const dockerArgs = ['run', '-d', '--name', CONTAINER, '--network', runtime.defaultNetwork];
167
393
  for (const opt of runtime.securityOpts)
168
394
  dockerArgs.push('--security-opt', opt);
169
- dockerArgs.push('-e', `HUDDLE_RUNTIME=${runtime.name}`);
170
- dockerArgs.push('-e', `HUDDLE_OPERATOR_TOKEN=${operatorToken}`);
171
- dockerArgs.push('-p', `${HOST_PORT}:3000`);
172
- dockerArgs.push('-v', `${VOLUME}:/data`);
173
- dockerArgs.push('-v', `${runtime.socketPath}:/var/run/docker.sock`);
174
- dockerArgs.push('-v', `${hostTmpSockets}:/tmp/dc-sockets`);
175
- dockerArgs.push('-v', `${config_1.CONFIG_DIR}:/huddle-home:rw`, '-e', 'HUDDLE_HOME_DIR=/huddle-home');
176
- if (fwFolder)
177
- dockerArgs.push('-v', `${fwFolder}:/firewall-rules:rw`);
178
- if (extFolder)
179
- dockerArgs.push('-v', `${extFolder}:/extensions:ro`);
180
- dockerArgs.push(...(0, images_1.gatewayEnvArgs)(images));
395
+ dockerArgs.push(...control.runArgs);
396
+ dockerArgs.push('-e', 'HUDDLE_ROLE=gateway');
397
+ dockerArgs.push('-e', `HUDDLE_NODE_CONTROL_URL=${control.url}`);
398
+ dockerArgs.push('-e', `HUDDLE_GATEWAY_TOKEN=${gatewayToken}`);
399
+ // Docker Sandboxes (sbx, experimental): publish the gateway's dedicated sbx
400
+ // proxy port to host loopback so the host sbx daemon can forward sandbox egress
401
+ // to Huddle at http://localhost:<port>. Kept on 127.0.0.1 (local only).
402
+ const sbxProxyPort = process.env.HUDDLE_SBX_PROXY_PORT?.trim() || '32768';
403
+ dockerArgs.push('-p', `127.0.0.1:${sbxProxyPort}:${sbxProxyPort}`);
404
+ dockerArgs.push('-e', `HUDDLE_SBX_PROXY_PORT=${sbxProxyPort}`);
405
+ // The MITM CA, read-only. Its own directory precisely so this mount can exist:
406
+ // the rest of ~/.huddle is the database and the operator token.
407
+ dockerArgs.push('-v', `${(0, node_1.nodeCaDir)()}:/ca:ro`);
408
+ // Where the per-devcontainer Docker sockets live. Both sides of this bind are
409
+ // the ENGINE host's path, which is the point: the gateway creates the socket
410
+ // here and the devcontainer mounts the same path, so the two meet whether or
411
+ // not the engine runs in a VM. Read-write, and it has to be: creating those
412
+ // sockets is the job. It grants nothing — the filter behind them is Huddle
413
+ // Node's, and reaching it costs the gateway token.
414
+ dockerArgs.push('-v', `${exports.HOST_SOCKET_DIR}:${exports.HOST_SOCKET_DIR}`);
181
415
  dockerArgs.push(IMAGE);
182
416
  runArgs(rt, dockerArgs);
183
417
  // Attaching devcontainer-net after the container has started pollutes
184
418
  // resolv.conf on Podman with that network's internal aardvark-DNS; the
185
- // gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
186
- // index.ts).
419
+ // gateway cleans that up itself (see dns-egress.ts / boot-gateway.ts).
187
420
  runArgsSilent(rt, ['network', 'connect', exports.INTERNAL_NET, CONTAINER]);
421
+ await rewireGateway(HOST_PORT, token);
188
422
  console.log();
189
- console.log((0, utils_1.green)(`[OK] Huddle is running at http://localhost:${HOST_PORT}`));
423
+ console.log((0, utils_1.green)(`[OK] Huddle is running at ${(0, node_1.nodeUrl)(HOST_PORT)}`));
424
+ console.log();
425
+ // Docker Sandboxes (sbx): sbx is a host binary, driven by Huddle Node on the
426
+ // host — there is nothing to start here. What still has to happen at init time
427
+ // is the host trust store, and only when sbx is actually installed. Best-effort;
428
+ // never fails the init.
429
+ try {
430
+ const { resolveSbxBin } = await Promise.resolve().then(() => __importStar(require('./sbx-host')));
431
+ const bin = resolveSbxBin();
432
+ const sbxPresent = (() => { try {
433
+ (0, child_process_1.execFileSync)(bin, ['version'], { stdio: 'ignore', timeout: 15000 });
434
+ return true;
435
+ }
436
+ catch {
437
+ return false;
438
+ } })();
439
+ if (sbxPresent) {
440
+ // Huddle's CA has to be trusted on the HOST too, not just inside each
441
+ // sandbox: sbx terminates TLS itself for some hosts (measured on
442
+ // platform.claude.com) and then validates Huddle's leaf against the host
443
+ // trust store. Without this the sandbox gets "Empty reply from server"
444
+ // and `claude` fails with ECONNRESET. See cli/src/sbx-host-ca.ts.
445
+ const { installHostCa, printHostCaResult } = await Promise.resolve().then(() => __importStar(require('./sbx-host-ca')));
446
+ printHostCaResult(installHostCa());
447
+ }
448
+ else {
449
+ console.log((0, utils_1.dim)(' (sbx not found on PATH — install Docker Sandboxes to use sbx boxes)'));
450
+ }
451
+ }
452
+ catch (err) {
453
+ console.log((0, utils_1.dim)(` (could not prepare sbx on the host: ${err.message})`));
454
+ }
190
455
  console.log();
191
456
  // Full auto-login link: open it and the portal logs you in automatically with
192
457
  // the operator token (the frontend reads ?token=..., logs in and then removes it
193
458
  // from the address bar). This way you don't have to paste anything.
194
- const loginUrl = `http://localhost:${HOST_PORT}/?token=${encodeURIComponent(operatorToken)}`;
459
+ const loginUrl = `${(0, node_1.nodeUrl)(HOST_PORT)}/?token=${encodeURIComponent(token ?? '')}`;
195
460
  console.log((0, utils_1.bold)('Open the portal (auto-login link):'));
196
461
  console.log((0, utils_1.green)(` ${loginUrl}`));
197
462
  console.log((0, utils_1.dim)(' Opens the portal and logs you in automatically.'));
198
- console.log((0, utils_1.dim)(` Manual token (if you prefer to paste it): ${operatorToken}`));
463
+ console.log((0, utils_1.dim)(` Manual token (if you prefer to paste it): ${token}`));
199
464
  console.log((0, utils_1.dim)(' The token is also saved to ~/.huddle/config.json for the CLI.'));
200
465
  }