@infosupport/huddle-cli 0.0.0-experiment-128.65.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/README.md CHANGED
@@ -25,11 +25,66 @@ huddle # start an IntelliJ devcontainer for the current director
25
25
  huddle ./project # start for a specific directory
26
26
  huddle --ide rider
27
27
  huddle --ide vscode --name devcontainer-demo
28
+ huddle --ide vscode --mount ../docker-corpa=/workspaces/backend --mount ../frontend-real-estate-info=/workspaces/frontend --name corpa-dev
28
29
  huddle fw list
29
30
  huddle firewall list -i
30
31
  ```
31
32
 
32
- Default API URL: `http://localhost:3000`. Override it with `--url` or `HUDDLE_URL`.
33
+ `--mount <host>=<container>` mounts an additional folder, worktree-isolated like the main workspace, at the container path you choose. The left side is a host path (relative paths are resolved against the current directory); the right side must be an **absolute** container path. Repeatable — pass one per folder — and cannot be combined with `--workspace`/`--empty`. Two mounts may not target the same container path.
34
+
35
+ `--workspace-root <path>` sets the absolute container path the IDE opens as its project root. It requires at least one `--mount`. Without it the root defaults to the deepest directory the mount targets share, so the example above opens `/workspaces` and shows `backend/` and `frontend/` inside it. Mount targets that share nothing fall back to `/workspaces`.
36
+
37
+ ```bash
38
+ huddle --ide vscode \
39
+ --mount ../ai-context-repo=/workspaces/ai \
40
+ --mount ../backend-repo=/workspaces/backend \
41
+ --mount ../frontend-repo=/workspaces/frontend \
42
+ --workspace-root /workspaces --name corpa-dev
43
+ ```
44
+
45
+ Default API URL: `http://localhost:24842` — Huddle Node, on the host. Override it with
46
+ `--url` or `HUDDLE_URL`.
47
+
48
+ ## Selecting host folders in the portal
49
+
50
+ A browser cannot hand a server a folder path, so every host-path field in the portal
51
+ grows a **Browse** button that opens Huddle's own folder dialog — starting a
52
+ devcontainer, the folder mappings, and the team-managed folders. Ctrl-click picks
53
+ several folders at once when starting a devcontainer, and each becomes its own
54
+ worktree.
55
+
56
+ It browses your host live: Huddle Node runs there and lists one folder per request as
57
+ you open them, so a project you cloned a minute ago is simply in the list. There is
58
+ nothing to index and no CLI command to run first. Hidden (dot) folders are listed too,
59
+ and every input keeps accepting a path you type or paste.
60
+
61
+ Windows paths may be typed either way (`T:\projects\app` or `T:/projects/app`) —
62
+ Huddle stores one canonical form, so the two spellings are the same folder.
63
+
64
+ ## Starting sandboxes (Docker Sandboxes / sbx)
65
+
66
+ ```bash
67
+ huddle sbx start # sandbox for the current directory
68
+ huddle sbx start my-box --workspace T:\projects\app # a specific folder
69
+ huddle sbx start my-box \
70
+ --workspace T:\projects\app \
71
+ --folder T:\projects\shared-lib \
72
+ --folder T:\docs:ro # extra folders, one read-only
73
+ ```
74
+
75
+ `--workspace <path>` is the folder the agent starts in. `--folder <host path>` adds
76
+ another folder and is **repeatable**; append `:ro` to mount that folder read-only.
77
+ Unlike `--mount` for devcontainers there is no container path to choose: sbx mounts
78
+ every folder inside the sandbox at the same path it has on the host (a Windows path
79
+ `T:\projects\app` becomes `/t/projects/app`).
80
+
81
+ The **folder mappings** from Settings (the settings folders devcontainers get, e.g.
82
+ `~/.claude`) are added to every sandbox automatically: each one rides along as an
83
+ extra folder and is then linked at the path the agent reads it from. An existing
84
+ folder in the sandbox is never overwritten — only its missing entries are linked in,
85
+ so the agent credentials sbx manages itself stay untouched. Mappings that cannot
86
+ travel (a Docker volume, or a `~`/relative host path) are reported per sandbox
87
+ instead of silently dropped.
33
88
 
34
89
  ## Experiments
35
90
 
@@ -59,6 +114,9 @@ Main flags:
59
114
  ```text
60
115
  --ide <intellij|rider|vscode>
61
116
  --workspace <path>
117
+ --mount <host>=<container> (repeatable, container path must be absolute)
118
+ --workspace-root <path> (container path the IDE opens; requires --mount)
119
+ --folder <host path>[:ro] (repeatable; extra sandbox folder for `huddle sbx start`)
62
120
  --name <name>
63
121
  --image <image>
64
122
  --empty
package/dist/api.js CHANGED
@@ -4,7 +4,29 @@ exports.del = exports.put = exports.post = exports.get = exports.ApiError = void
4
4
  exports.setBaseUrl = setBaseUrl;
5
5
  exports.apiCall = apiCall;
6
6
  const config_1 = require("./config");
7
- let baseUrl = normalizeBaseUrl(process.env.HUDDLE_URL ?? 'http://localhost:3000');
7
+ const node_1 = require("./node");
8
+ // Huddle Node, on the host, on loopback. Not 3000 and not a container address:
9
+ // after the Node/Gateway split the API this talks to is the host process, and
10
+ // the gateway container has no API at all (docs/ADR-huddle-node-split.md).
11
+ //
12
+ // The loopback LITERALS, not `localhost` — nodeProbeUrls() is where that reason
13
+ // is written down. Both are kept, not just the first: Node binds one address and
14
+ // which one depends on the host, so the only honest default is to try each and
15
+ // keep whichever answers.
16
+ //
17
+ // An explicit --url or HUDDLE_URL replaces the list entirely — the operator named
18
+ // an address, and silently talking to a different one would be worse than failing.
19
+ //
20
+ // HUDDLE_PORT, when set, still has to flow through here: it is the same env var
21
+ // `huddle init`/`huddle node` read for a custom port (init.ts's HOST_PORT), so a
22
+ // custom port that stuck for the command that started Huddle Node must also
23
+ // stick for every command that talks to it afterwards — otherwise every command
24
+ // after `HUDDLE_PORT=<n> huddle init` probes the default port and never finds it.
25
+ const port = process.env.HUDDLE_PORT?.trim() || node_1.DEFAULT_NODE_PORT;
26
+ let candidates = (process.env.HUDDLE_URL
27
+ ? [process.env.HUDDLE_URL]
28
+ : (0, node_1.nodeProbeUrls)(port)).map(normalizeBaseUrl);
29
+ let baseUrl = candidates[0];
8
30
  class ApiError extends Error {
9
31
  status;
10
32
  constructor(message, status) {
@@ -15,7 +37,30 @@ class ApiError extends Error {
15
37
  }
16
38
  exports.ApiError = ApiError;
17
39
  function setBaseUrl(url) {
18
- baseUrl = normalizeBaseUrl(url);
40
+ candidates = [normalizeBaseUrl(url)];
41
+ baseUrl = candidates[0];
42
+ }
43
+ /**
44
+ * The first candidate that answers, remembered for the rest of the process.
45
+ *
46
+ * A refused connection is not a failure here — it is how we find out which
47
+ * loopback address Node bound. Anything the server actually answers, including a
48
+ * 500, ends the search: it proves we found Huddle.
49
+ */
50
+ async function reachHuddle(path, init) {
51
+ const order = [baseUrl, ...candidates.filter((c) => c !== baseUrl)];
52
+ let detail = '';
53
+ for (const candidate of order) {
54
+ try {
55
+ const res = await fetch(`${candidate}${path}`, init);
56
+ baseUrl = candidate;
57
+ return res;
58
+ }
59
+ catch (err) {
60
+ detail = err instanceof Error ? err.message : String(err);
61
+ }
62
+ }
63
+ throw new ApiError(`Cannot reach Huddle API at ${order.join(' or ')}: ${detail}`);
19
64
  }
20
65
  async function apiCall(method, path, body) {
21
66
  const headers = {};
@@ -26,18 +71,11 @@ async function apiCall(method, path, body) {
26
71
  const token = (0, config_1.operatorToken)();
27
72
  if (token)
28
73
  headers['authorization'] = `Bearer ${token}`;
29
- let res;
30
- try {
31
- res = await fetch(`${baseUrl}${path}`, {
32
- method,
33
- headers,
34
- body: body !== undefined ? JSON.stringify(body) : undefined,
35
- });
36
- }
37
- catch (err) {
38
- const detail = err instanceof Error ? err.message : String(err);
39
- throw new ApiError(`Cannot reach Huddle API at ${baseUrl}: ${detail}`);
40
- }
74
+ const res = await reachHuddle(path, {
75
+ method,
76
+ headers,
77
+ body: body !== undefined ? JSON.stringify(body) : undefined,
78
+ });
41
79
  const raw = await res.text();
42
80
  const payload = parsePayload(raw);
43
81
  if (!res.ok) {
package/dist/config.js CHANGED
@@ -3,17 +3,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CONFIG_DIR = void 0;
6
7
  exports.configPath = configPath;
7
8
  exports.readConfig = readConfig;
8
- exports.writeConfig = writeConfig;
9
+ exports.updateConfig = updateConfig;
9
10
  exports.operatorToken = operatorToken;
10
11
  exports.activeExperiment = activeExperiment;
11
12
  exports.imageTag = imageTag;
12
13
  const fs_1 = __importDefault(require("fs"));
14
+ const crypto_1 = require("crypto");
13
15
  const os_1 = __importDefault(require("os"));
14
16
  const path_1 = __importDefault(require("path"));
15
- const CONFIG_DIR = path_1.default.join(os_1.default.homedir(), '.huddle');
16
- const CONFIG_PATH = path_1.default.join(CONFIG_DIR, 'config.json');
17
+ exports.CONFIG_DIR = path_1.default.join(os_1.default.homedir(), '.huddle');
18
+ const CONFIG_PATH = path_1.default.join(exports.CONFIG_DIR, 'config.json');
17
19
  function configPath() {
18
20
  return CONFIG_PATH;
19
21
  }
@@ -25,9 +27,146 @@ function readConfig() {
25
27
  return {};
26
28
  }
27
29
  }
28
- function writeConfig(config) {
29
- fs_1.default.mkdirSync(CONFIG_DIR, { recursive: true });
30
- fs_1.default.writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
30
+ // ── Cross-process locking ─────────────────────────────────────────────────────
31
+ //
32
+ // The gateway edits this same file from inside its container (the portal writes
33
+ // the folder mappings and resource defaults there, see gateway/src/host-config.ts)
34
+ // while the CLI edits it from the host. Both do a read-modify-write of the whole
35
+ // document, so without a lock whoever writes last silently reverts the other's
36
+ // change. Same protocol on both sides: exclusive create of a sibling lock file,
37
+ // which works across the bind mount that joins the two.
38
+ const LOCK_PATH = `${CONFIG_PATH}.lock`;
39
+ const LOCK_WAIT_MS = 5000; // the gateway holds it for microseconds; this is pure headroom
40
+ const LOCK_STALE_MS = 10_000; // older than this means the holder died mid-write
41
+ function sleepSync(ms) {
42
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
43
+ }
44
+ // The lock file carries the identity of its holder, not just its existence. Age
45
+ // alone is not enough to decide it may be removed: a writer that pauses past
46
+ // LOCK_STALE_MS gets its lock broken and taken over, and would then delete the
47
+ // *new* holder's lock on the way out — letting a third writer in alongside the
48
+ // second, which is exactly the clobber the lock exists to prevent. A pid would
49
+ // not do as identity: the gateway runs in a container and this CLI on the host,
50
+ // sharing the file over a bind mount, so their pid spaces are unrelated.
51
+ function lockToken() {
52
+ return `${process.pid}:${(0, crypto_1.randomUUID)()}`;
53
+ }
54
+ function readLockToken() {
55
+ try {
56
+ return fs_1.default.readFileSync(LOCK_PATH, 'utf8');
57
+ }
58
+ catch {
59
+ return null; // gone between the stat and the read
60
+ }
61
+ }
62
+ // Remove a lock left behind by a writer that was killed mid-update, but only that
63
+ // exact lock: the token and mtime are re-read right before the unlink, so a lock
64
+ // another contender has meanwhile broken and taken over is left in place.
65
+ function breakStaleLock() {
66
+ let mtimeMs;
67
+ try {
68
+ mtimeMs = fs_1.default.statSync(LOCK_PATH).mtimeMs;
69
+ }
70
+ catch {
71
+ return; // already gone
72
+ }
73
+ if (Date.now() - mtimeMs <= LOCK_STALE_MS)
74
+ return;
75
+ const token = readLockToken();
76
+ if (token === null)
77
+ return;
78
+ try {
79
+ if (readLockToken() !== token)
80
+ return;
81
+ if (fs_1.default.statSync(LOCK_PATH).mtimeMs !== mtimeMs)
82
+ return;
83
+ fs_1.default.unlinkSync(LOCK_PATH);
84
+ }
85
+ catch { /* another process got there first — just retry */ }
86
+ }
87
+ // Returns the token identifying this holder, to be handed back to releaseLock.
88
+ function acquireLock() {
89
+ const deadline = Date.now() + LOCK_WAIT_MS;
90
+ for (;;) {
91
+ const token = lockToken();
92
+ try {
93
+ const fd = fs_1.default.openSync(LOCK_PATH, 'wx');
94
+ try {
95
+ fs_1.default.writeSync(fd, token);
96
+ }
97
+ finally {
98
+ fs_1.default.closeSync(fd);
99
+ }
100
+ return token;
101
+ }
102
+ catch (err) {
103
+ if (err.code !== 'EEXIST')
104
+ return null;
105
+ breakStaleLock();
106
+ if (Date.now() >= deadline)
107
+ return null;
108
+ sleepSync(25);
109
+ }
110
+ }
111
+ }
112
+ function releaseLock(token) {
113
+ // Never unlink a lock this writer no longer owns: if it was broken as stale and
114
+ // taken over, the file belongs to the writer that is running right now.
115
+ if (readLockToken() !== token)
116
+ return;
117
+ try {
118
+ fs_1.default.unlinkSync(LOCK_PATH);
119
+ }
120
+ catch { /* already gone */ }
121
+ }
122
+ let tmpSeq = 0;
123
+ /**
124
+ * The only writer. Merges a patch into the config file, re-reading it inside the
125
+ * lock so a concurrent gateway write is preserved instead of reverted; a key set
126
+ * to `undefined` is removed from the file. There is deliberately no
127
+ * write-the-whole-document variant: every such write was a read-modify-write of
128
+ * a snapshot that could already be stale.
129
+ *
130
+ * Throws when the lock cannot be taken. Writing anyway would reintroduce exactly
131
+ * the clobber the lock exists to prevent — the gateway would have the config open
132
+ * for a read-modify-write of its own, and one of the two edits would vanish. A
133
+ * failed command the operator can retry is the better outcome; the callers below
134
+ * (`huddle init`, `huddle firewall …`, `huddle experiment …`) all abort cleanly
135
+ * because nothing has been written yet at that point.
136
+ *
137
+ * The temp file name is unique per write — a shared `.tmp` lets two writers
138
+ * truncate each other's half-written file and rename the wreckage over the real
139
+ * config.
140
+ */
141
+ function updateConfig(patch) {
142
+ fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true });
143
+ const token = acquireLock();
144
+ if (token === null) {
145
+ throw new Error(`Could not lock ${CONFIG_PATH} within ${LOCK_WAIT_MS}ms — another Huddle process ` +
146
+ `is writing it. Nothing was changed; retry the command. If no other process is ` +
147
+ `running, remove the stale lock: rm ${LOCK_PATH}`);
148
+ }
149
+ const tmp = `${CONFIG_PATH}.${process.pid}.${tmpSeq++}.tmp`;
150
+ try {
151
+ const next = { ...readConfig(), ...patch };
152
+ for (const [k, v] of Object.entries(next)) {
153
+ if (v === undefined)
154
+ delete next[k];
155
+ }
156
+ fs_1.default.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
157
+ fs_1.default.renameSync(tmp, CONFIG_PATH);
158
+ return next;
159
+ }
160
+ catch (err) {
161
+ try {
162
+ fs_1.default.unlinkSync(tmp);
163
+ }
164
+ catch { /* never created, or already renamed */ }
165
+ throw err;
166
+ }
167
+ finally {
168
+ releaseLock(token);
169
+ }
31
170
  }
32
171
  /** Operator-token voor API-auth: env wint, anders uit de config. */
33
172
  function operatorToken() {
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ // Where huddle-gateway finds Huddle Node.
3
+ //
4
+ // The gateway follows Huddle Node's control channel (policy in, decisions out).
5
+ // Node runs on the host now, so this is a container→host call, and how a
6
+ // container reaches its host is the one thing that genuinely differs per engine:
7
+ //
8
+ // Engine in a VM (Docker Desktop, Rancher, `podman machine`)
9
+ // `host.docker.internal` is routed to the real host, and a process bound
10
+ // to the host's LOOPBACK is reachable through it. Node keeps 127.0.0.1.
11
+ //
12
+ // Engine native on Linux (docker/podman on the same kernel)
13
+ // There is no such routing: the container sees the host only as the bridge
14
+ // gateway address (172.17.0.1 for Docker's `bridge`, 10.88.0.1 for
15
+ // Podman's `podman`). A loopback-bound listener is simply not reachable,
16
+ // so the control channel has to bind that address.
17
+ //
18
+ // Only the CONTROL channel moves. The portal and the REST API stay on loopback
19
+ // in both cases — they carry the operator token, which opens container
20
+ // terminals, execs and policy writes. The control channel carries a second,
21
+ // narrower token (gateway/src/auth.ts) and is the only thing worth exposing to
22
+ // the bridge. Devcontainers cannot reach even that: their network is `--internal`
23
+ // and has no route off itself.
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.HOST_ALIAS = void 0;
26
+ exports.parseBridgeGateway = parseBridgeGateway;
27
+ exports.bridgeGateway = bridgeGateway;
28
+ exports.resolveControlAddress = resolveControlAddress;
29
+ const child_process_1 = require("child_process");
30
+ exports.HOST_ALIAS = 'host.docker.internal';
31
+ /**
32
+ * Pull the bridge gateway address out of `network inspect` JSON.
33
+ *
34
+ * Two shapes, because the engines disagree: Docker nests it under
35
+ * `IPAM.Config[].Gateway`, Podman under `subnets[].gateway`. Parsing the JSON
36
+ * rather than passing a Go template is what makes one code path serve both.
37
+ *
38
+ * Pure, so the shapes can be tested without an engine.
39
+ */
40
+ function parseBridgeGateway(json) {
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(json);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ const entry = Array.isArray(parsed) ? parsed[0] : parsed;
49
+ if (!entry || typeof entry !== 'object')
50
+ return null;
51
+ const docker = entry.IPAM?.Config;
52
+ const podman = entry.subnets;
53
+ const rows = Array.isArray(docker) ? docker : Array.isArray(podman) ? podman : [];
54
+ for (const row of rows) {
55
+ if (!row || typeof row !== 'object')
56
+ continue;
57
+ const value = row.Gateway
58
+ ?? row.gateway;
59
+ if (typeof value === 'string' && isIpLiteral(value))
60
+ return value;
61
+ }
62
+ return null;
63
+ }
64
+ /**
65
+ * An IP literal and nothing else. This value ends up as a bind address and
66
+ * inside a `-e HUDDLE_NODE_CONTROL_URL=...` argument, and it comes from whatever
67
+ * the engine reports — so a hostname, a CIDR suffix or anything with a shell
68
+ * metacharacter in it is rejected rather than passed on.
69
+ */
70
+ function isIpLiteral(value) {
71
+ const v = value.trim();
72
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(v)) {
73
+ return v.split('.').every((o) => Number(o) <= 255);
74
+ }
75
+ return /^[0-9a-fA-F:]+$/.test(v) && v.includes(':');
76
+ }
77
+ /** Ask the engine for the default network's gateway address. Best-effort. */
78
+ function bridgeGateway(rt, network) {
79
+ try {
80
+ const out = (0, child_process_1.execFileSync)(rt, ['network', 'inspect', network], {
81
+ encoding: 'utf8',
82
+ stdio: ['ignore', 'pipe', 'ignore'],
83
+ timeout: 15_000,
84
+ });
85
+ return parseBridgeGateway(out);
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ /** Bracket a literal IPv6 host for use in a URL, the way every other http://host:port here does. */
92
+ function formatHost(host) {
93
+ return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
94
+ }
95
+ /**
96
+ * Decide the pair (bind host, URL) from what we know about the engine. Pure —
97
+ * the engine probing happens in bridgeGateway() above.
98
+ */
99
+ function resolveControlAddress(input) {
100
+ const override = input.override?.trim();
101
+ const bindOverride = input.bindOverride?.trim();
102
+ const derived = derive(input);
103
+ // HUDDLE_CONTROL_HOST moves where Node binds; unless HUDDLE_NODE_CONTROL_URL
104
+ // says otherwise too, the URL handed to the gateway has to move with it. Left
105
+ // pinned to the auto-derived URL, Node ends up listening on the overridden
106
+ // host while the gateway keeps probing the stale one — and being fail-closed,
107
+ // denies every request. HUDDLE_NODE_CONTROL_URL, when given, still wins: it is
108
+ // the more specific override and may legitimately name something other than
109
+ // the bind host (a different port, a tunnel, host.docker.internal itself).
110
+ const url = override || (bindOverride ? `http://${formatHost(bindOverride)}:${input.port}` : derived.url);
111
+ return {
112
+ ...derived,
113
+ bindHost: bindOverride || derived.bindHost,
114
+ url,
115
+ reason: override || bindOverride
116
+ ? 'set explicitly via HUDDLE_NODE_CONTROL_URL / HUDDLE_CONTROL_HOST'
117
+ : derived.reason,
118
+ // Whoever set it explicitly knows their own topology better than we do.
119
+ reachable: derived.reachable || !!override || !!bindOverride,
120
+ // Either override may name something other than the alias; adding a host
121
+ // entry for a name nobody asked about would be noise at best.
122
+ runArgs: (override || bindOverride) ? [] : derived.runArgs,
123
+ };
124
+ }
125
+ function derive(input) {
126
+ const { port } = input;
127
+ if (input.isRemote) {
128
+ return {
129
+ bindHost: '127.0.0.1',
130
+ url: `http://${exports.HOST_ALIAS}:${port}`,
131
+ // Docker Desktop provides the alias already; Podman machine and Rancher
132
+ // are less consistent about it, and asking for it twice costs nothing.
133
+ runArgs: ['--add-host', `${exports.HOST_ALIAS}:host-gateway`],
134
+ reason: 'the engine runs in a VM, so the host is reachable on its loopback',
135
+ reachable: true,
136
+ };
137
+ }
138
+ if (input.gatewayIp) {
139
+ return {
140
+ bindHost: input.gatewayIp,
141
+ url: `http://${formatHost(input.gatewayIp)}:${port}`,
142
+ runArgs: [],
143
+ reason: `native engine — the container reaches this host at ${input.gatewayIp}`,
144
+ reachable: true,
145
+ };
146
+ }
147
+ // Native engine, and we could not read the bridge address — so there is no
148
+ // address we can honestly name. Loopback is deliberate: 0.0.0.0 would put the
149
+ // control channel on the LAN and any VPN to fix a problem we have not even
150
+ // confirmed. The gateway then reaches nothing and, being fail-closed, denies
151
+ // every request until an operator sets HUDDLE_CONTROL_HOST. A visibly dead
152
+ // firewall beats a quietly widened one.
153
+ return {
154
+ bindHost: '127.0.0.1',
155
+ url: `http://${exports.HOST_ALIAS}:${port}`,
156
+ runArgs: ['--add-host', `${exports.HOST_ALIAS}:host-gateway`],
157
+ reason: 'the bridge gateway address could not be read from the engine',
158
+ reachable: false,
159
+ };
160
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ // Does the gateway container ACTUALLY reach Huddle Node?
3
+ //
4
+ // control-address.ts derives an answer from what the engine says it is. That
5
+ // derivation has one assumption in it — "engine in a VM ⇒ the host is reachable
6
+ // on its loopback via host.docker.internal" — and it is false on Rancher
7
+ // Desktop for Windows: the engine runs in a WSL distro, `host.docker.internal`
8
+ // resolves to that distro's docker0 gateway (172.17.0.1), and Huddle Node is a
9
+ // Windows process bound to the Windows loopback. The name resolves, nothing
10
+ // listens, and the gateway fails closed: every devcontainer is denied all egress
11
+ // and nothing is filed as `requested`, because a gateway with no policy is not
12
+ // allowed to invent one.
13
+ //
14
+ // A derivation cannot tell that apart from a working setup. A connection can.
15
+ // So init stops guessing: it starts Node, then opens the real connection from a
16
+ // throwaway container, and only trusts an address that answered.
17
+ //
18
+ // Split from control-address.ts because everything here SPAWNS — the pure
19
+ // decision stays testable without an engine, and the parsers below are exported
20
+ // for the same reason.
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.parseProbeOutput = parseProbeOutput;
26
+ exports.probeControlUrl = probeControlUrl;
27
+ exports.parseDefaultGateway = parseDefaultGateway;
28
+ exports.engineHostAddress = engineHostAddress;
29
+ exports.hostCandidateUrls = hostCandidateUrls;
30
+ exports.localIpv4Addresses = localIpv4Addresses;
31
+ exports.pickBindAddress = pickBindAddress;
32
+ const child_process_1 = require("child_process");
33
+ const os_1 = __importDefault(require("os"));
34
+ /** How long any single engine call may take before we call it a failure. */
35
+ const PROBE_TIMEOUT_MS = 25_000;
36
+ /**
37
+ * Run the probe inside the gateway image itself.
38
+ *
39
+ * That image, not a stock one: it is already present (init just pulled or built
40
+ * it), so this costs no download, and it is the exact runtime the real gateway
41
+ * uses — same Node, same DNS resolution, same TLS stack.
42
+ */
43
+ function runInImage(rt, image, runArgs, entrypoint, cmdArgs = []) {
44
+ try {
45
+ return (0, child_process_1.execFileSync)(rt, ['run', '--rm', '--entrypoint', entrypoint, ...runArgs, image, ...cmdArgs], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS });
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ // The script the probe container runs. One line, because it travels as an argv
52
+ // entry through a shell on Windows. A 4s timeout of its own: an address that is
53
+ // silently dropped (a host firewall) must come back as a result, not as a hang.
54
+ const PROBE_SCRIPT = "fetch(process.env.PROBE_URL + '/control/health', { signal: AbortSignal.timeout(4000) })" +
55
+ ".then(r => console.log('PROBE_HTTP ' + r.status))" +
56
+ ".catch(e => console.log('PROBE_ERR ' + ((e.cause && e.cause.code) || e.name || e.message)))";
57
+ /**
58
+ * Read the probe container's single line of output.
59
+ *
60
+ * ANY HTTP status means reachable, and 401 is the expected one: /control/health
61
+ * is behind the gateway token and the probe deliberately sends none. What is
62
+ * being tested is whether the packets arrive, not whether we are authorised —
63
+ * the token is checked separately, and conflating the two is how "unreachable"
64
+ * ends up hiding a token mismatch.
65
+ */
66
+ function parseProbeOutput(out) {
67
+ if (out === null)
68
+ return { reachable: false, detail: 'the probe container could not be started' };
69
+ const line = out.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? '';
70
+ const http = /^PROBE_HTTP (\d+)$/.exec(line);
71
+ if (http)
72
+ return { reachable: true, detail: `HTTP ${http[1]}` };
73
+ const err = /^PROBE_ERR (.+)$/.exec(line);
74
+ if (err)
75
+ return { reachable: false, detail: err[1] };
76
+ return { reachable: false, detail: line || 'no output' };
77
+ }
78
+ /**
79
+ * Open the control channel from where the gateway will open it: same image,
80
+ * same network, same --add-host arguments. Anything less tests a different path
81
+ * than the one that has to work.
82
+ */
83
+ function probeControlUrl(rt, image, url, network, runArgs) {
84
+ const out = runInImage(rt, image, ['--network', network, ...runArgs, '-e', `PROBE_URL=${url}`], 'node', ['-e', PROBE_SCRIPT]);
85
+ return parseProbeOutput(out);
86
+ }
87
+ /**
88
+ * Pull the gateway out of `ip route show default`.
89
+ *
90
+ * Two shapes, since busybox and iproute2 order the fields differently:
91
+ * default via 172.20.144.1 dev eth0 proto kernel
92
+ * default dev eth0 scope link src 10.0.0.5 via 10.0.0.1
93
+ * so match on `via <ip>` wherever it sits rather than on a field position.
94
+ */
95
+ function parseDefaultGateway(routeOutput) {
96
+ if (!routeOutput)
97
+ return null;
98
+ for (const line of routeOutput.split('\n')) {
99
+ if (!line.trim().startsWith('default'))
100
+ continue;
101
+ const via = /\bvia\s+(\d{1,3}(?:\.\d{1,3}){3})\b/.exec(line);
102
+ if (via && via[1].split('.').every((o) => Number(o) <= 255))
103
+ return via[1];
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * The address of the machine the ENGINE runs on, seen from inside the engine.
109
+ *
110
+ * `--network host` puts the probe in the engine host's own network namespace —
111
+ * the WSL distro on Rancher Desktop, the Linux VM elsewhere — so its default
112
+ * route names the next hop out of that namespace. On WSL that next hop is the
113
+ * Windows host, on the vEthernet adapter the two share, which is exactly the
114
+ * address a container can reach and `host.docker.internal` failed to name.
115
+ *
116
+ * Only worth asking when the derived address did not answer: on Docker Desktop
117
+ * this returns the VM's own internal gateway, which is not what anyone wants.
118
+ */
119
+ function engineHostAddress(rt, image) {
120
+ return parseDefaultGateway(runInImage(rt, image, ['--network', 'host'], 'ip', ['-4', 'route', 'show', 'default']));
121
+ }
122
+ /**
123
+ * The other names and addresses a container might reach this machine on, tried
124
+ * only when the derived one did not answer.
125
+ *
126
+ * `host.docker.internal` is not a promise. Rancher Desktop points it at the
127
+ * WSL distro's own docker0 gateway, which is the distro, not this machine —
128
+ * measured, and it is what sent us here. So try the aliases other engines
129
+ * publish, and then the one address that is not a guess at all:
130
+ *
131
+ * Rancher Desktop and `podman machine` both route the VM through
132
+ * gvisor-tap-vsock, which serves 192.168.127.0/24 with the gateway on .1 and
133
+ * THIS MACHINE on .254 — a userspace forwarder running here, so it reaches the
134
+ * host loopback exactly like Docker Desktop's alias does. Derived from whatever
135
+ * gateway the engine reported rather than hardcoded, because the subnet is
136
+ * configurable.
137
+ *
138
+ * Every one of these is a candidate, not an answer: each is probed, and only an
139
+ * address that replies is used.
140
+ */
141
+ function hostCandidateUrls(port, vmGateway) {
142
+ const hosts = ['host.rancher-desktop.internal', 'host.containers.internal'];
143
+ const octets = vmGateway ? /^(\d{1,3}\.\d{1,3}\.\d{1,3})\.\d{1,3}$/.exec(vmGateway) : null;
144
+ if (octets)
145
+ hosts.push(`${octets[1]}.254`);
146
+ return hosts.map((h) => `http://${h}:${port}`);
147
+ }
148
+ /** Every IPv4 address this machine actually has, loopback excluded. */
149
+ function localIpv4Addresses() {
150
+ const out = [];
151
+ for (const addrs of Object.values(os_1.default.networkInterfaces())) {
152
+ for (const a of addrs ?? []) {
153
+ if (a.family === 'IPv4' && !a.internal)
154
+ out.push(a.address);
155
+ }
156
+ }
157
+ return out;
158
+ }
159
+ /**
160
+ * An address Huddle Node can BIND that the engine can also reach.
161
+ *
162
+ * Both halves matter, and the second one is the trap: the engine's default
163
+ * gateway is not this machine. On Rancher Desktop it is 192.168.127.1, served by
164
+ * a forwarder — binding it fails with EADDRNOTAVAIL and takes Huddle Node down
165
+ * with it, which is exactly how a control-channel fix turned into no Huddle at
166
+ * all. So only ever offer an address this machine really owns, on the same
167
+ * subnet the engine routes through.
168
+ */
169
+ function pickBindAddress(local, vmGateway) {
170
+ if (!vmGateway)
171
+ return null;
172
+ const prefix = vmGateway.replace(/\.\d+$/, '.');
173
+ return local.find((a) => a.startsWith(prefix)) ?? null;
174
+ }