@infosupport/huddle-cli 0.0.0-experiment-66.39.1 → 0.0.0-experiment-97.41.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/config.js CHANGED
@@ -3,7 +3,6 @@ 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;
7
6
  exports.configPath = configPath;
8
7
  exports.readConfig = readConfig;
9
8
  exports.writeConfig = writeConfig;
@@ -13,8 +12,8 @@ exports.imageTag = imageTag;
13
12
  const fs_1 = __importDefault(require("fs"));
14
13
  const os_1 = __importDefault(require("os"));
15
14
  const path_1 = __importDefault(require("path"));
16
- exports.CONFIG_DIR = path_1.default.join(os_1.default.homedir(), '.huddle');
17
- const CONFIG_PATH = path_1.default.join(exports.CONFIG_DIR, 'config.json');
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');
18
17
  function configPath() {
19
18
  return CONFIG_PATH;
20
19
  }
@@ -27,7 +26,7 @@ function readConfig() {
27
26
  }
28
27
  }
29
28
  function writeConfig(config) {
30
- fs_1.default.mkdirSync(exports.CONFIG_DIR, { recursive: true });
29
+ fs_1.default.mkdirSync(CONFIG_DIR, { recursive: true });
31
30
  fs_1.default.writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
32
31
  }
33
32
  /** Operator-token voor API-auth: env wint, anders uit de config. */
package/dist/firewall.js CHANGED
@@ -1,18 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.runFirewallList = runFirewallList;
7
4
  exports.runFirewallAdd = runFirewallAdd;
8
5
  exports.runFirewallDelete = runFirewallDelete;
9
- exports.runFirewallExport = runFirewallExport;
10
- exports.runFirewallImport = runFirewallImport;
11
- exports.runFirewallGroup = runFirewallGroup;
12
- exports.runFirewallFolder = runFirewallFolder;
13
- const fs_1 = __importDefault(require("fs"));
14
6
  const api_1 = require("./api");
15
- const config_1 = require("./config");
16
7
  const utils_1 = require("./utils");
17
8
  async function runFirewallList(opts) {
18
9
  const qs = new URLSearchParams({ status: opts.status ?? 'requested' });
@@ -65,9 +56,9 @@ async function resolveRule(rule, status, scope) {
65
56
  }
66
57
  // Creates a custom firewall rule. Supports wildcards: `*.` in the domain
67
58
  // (e.g. `*.pkgs.dev.azure.com`) and `*` in the path pattern (e.g.
68
- // `/_packaging/*/nuget/v3/*` for an Azure DevOps feed with a changing
69
- // GUID). Defaults to 'allow'; --deny creates a block rule. Without --container
70
- // the rule is global.
59
+ // `/_packaging/*/nuget/v3/*` for an Azure DevOps feed with a rotating
60
+ // GUID). Defaults to 'allow'; with --deny a block rule. Without --container the
61
+ // rule is global.
71
62
  async function runFirewallAdd(opts) {
72
63
  const domain = (opts.domain ?? '').trim();
73
64
  if (!domain) {
@@ -109,7 +100,11 @@ async function runFirewallDelete(opts) {
109
100
  qs.set('container', opts.container);
110
101
  const query = qs.toString();
111
102
  const rules = await (0, api_1.get)(`/api/rules${query ? `?${query}` : ''}`);
112
- const matches = rules.filter((r) => r.domain === target);
103
+ // Hostnames are case-insensitive everywhere else in the firewall stack, so
104
+ // match the domain case-insensitively — a rule stored as `GitHub.com` must be
105
+ // deletable by typing `github.com`.
106
+ const needle = target.toLowerCase();
107
+ const matches = rules.filter((r) => r.domain.toLowerCase() === needle);
113
108
  if (matches.length === 0) {
114
109
  const scope = opts.container ? ` for container ${opts.container}` : '';
115
110
  throw new Error(`No firewall rule found for "${target}"${scope}.`);
@@ -140,146 +135,3 @@ function printRulesTable(rules) {
140
135
  function formatTarget(rule) {
141
136
  return rule.path_pattern ? `${rule.domain}${rule.path_pattern}` : rule.domain;
142
137
  }
143
- async function runFirewallExport(opts) {
144
- const qs = new URLSearchParams();
145
- if (opts.container)
146
- qs.set('container', opts.container);
147
- const suffix = qs.toString() ? `?${qs}` : '';
148
- const doc = await (0, api_1.get)(`/api/rules/export${suffix}`);
149
- const json = JSON.stringify(doc, null, 2);
150
- if (opts.out) {
151
- fs_1.default.writeFileSync(opts.out, `${json}\n`);
152
- // Progress to stderr so a pure `--out` run leaks nothing to stdout.
153
- console.error((0, utils_1.green)(`[OK] Exported ${doc.rules.length} rule(s) to ${opts.out}`));
154
- }
155
- else {
156
- console.log(json);
157
- }
158
- }
159
- async function runFirewallImport(opts) {
160
- let raw;
161
- try {
162
- raw = fs_1.default.readFileSync(opts.file, 'utf8');
163
- }
164
- catch {
165
- throw new Error(`Cannot read ${opts.file}`);
166
- }
167
- let doc;
168
- try {
169
- doc = JSON.parse(raw);
170
- }
171
- catch {
172
- throw new Error(`${opts.file} is not valid JSON`);
173
- }
174
- const mode = opts.replace ? 'replace' : 'merge';
175
- const qs = new URLSearchParams();
176
- if (opts.container)
177
- qs.set('container', opts.container);
178
- const suffix = qs.toString() ? `?${qs}` : '';
179
- const res = await (0, api_1.post)(`/api/rules/import${suffix}`, { mode, rules: doc.rules });
180
- console.error((0, utils_1.green)(`[OK] Imported (${mode}): ${res.imported} added, ${res.updated} updated, ${res.skipped} skipped`));
181
- }
182
- async function resolveGroupByName(name) {
183
- const groups = await (0, api_1.get)('/api/groups');
184
- const match = groups.filter((g) => g.name.toLowerCase() === name.toLowerCase());
185
- if (match.length === 0)
186
- throw new Error(`No group named "${name}". Run \`huddle firewall group list\`.`);
187
- return match[0];
188
- }
189
- async function runFirewallGroup(opts) {
190
- const action = opts.action ?? 'list';
191
- if (action === 'list') {
192
- const groups = await (0, api_1.get)('/api/groups');
193
- if (groups.length === 0) {
194
- console.log((0, utils_1.dim)('No firewall groups yet.'));
195
- return;
196
- }
197
- const headers = ['ID', 'Name', 'Rules', 'Shared', 'Source'];
198
- const rows = groups.map((g) => [String(g.id), g.name, String(g.rule_count), g.shared ? 'yes' : 'no', g.source]);
199
- (0, utils_1.printTable)(headers, rows);
200
- return;
201
- }
202
- if (action === 'export') {
203
- const name = (opts.arg ?? '').trim();
204
- if (!name)
205
- throw new Error('Usage: huddle firewall group export <name> [--out <file>]');
206
- const g = await resolveGroupByName(name);
207
- const env = await (0, api_1.get)(`/api/groups/${g.id}/export`);
208
- const json = JSON.stringify(env, null, 2);
209
- if (opts.out) {
210
- fs_1.default.writeFileSync(opts.out, `${json}\n`);
211
- console.error((0, utils_1.green)(`[OK] Exported group "${g.name}" to ${opts.out}`));
212
- }
213
- else {
214
- console.log(json);
215
- }
216
- return;
217
- }
218
- if (action === 'import') {
219
- const file = (opts.arg ?? '').trim();
220
- if (!file)
221
- throw new Error('Usage: huddle firewall group import <file> [--replace]');
222
- let raw;
223
- try {
224
- raw = fs_1.default.readFileSync(file, 'utf8');
225
- }
226
- catch {
227
- throw new Error(`Cannot read ${file}`);
228
- }
229
- let envelope;
230
- try {
231
- envelope = JSON.parse(raw);
232
- }
233
- catch {
234
- throw new Error(`${file} is not valid JSON`);
235
- }
236
- const mode = opts.replace ? 'replace' : 'merge';
237
- const res = await (0, api_1.post)('/api/groups/import', { mode, envelope });
238
- console.error((0, utils_1.green)(`[OK] Imported group "${res.group.name}" (${mode}): ${res.imported} added, ${res.updated} updated, ${res.skipped} skipped`));
239
- return;
240
- }
241
- if (action === 'apply') {
242
- const name = (opts.arg ?? '').trim();
243
- if (!name)
244
- throw new Error('Usage: huddle firewall group apply <name> [--container <id>]');
245
- const g = await resolveGroupByName(name);
246
- const container = opts.container ?? null;
247
- const res = await (0, api_1.post)(`/api/groups/${g.id}/apply`, { container });
248
- const scope = container ? `container ${container}` : 'global';
249
- console.log((0, utils_1.green)(`[OK] Applied "${g.name}" to ${scope}: ${res.applied} added, ${res.updated} updated`));
250
- return;
251
- }
252
- throw new Error(`Unknown group action: ${action}. Use list | export | import | apply.`);
253
- }
254
- async function runFirewallFolder(opts) {
255
- const action = opts.action ?? 'show';
256
- if (action === 'show') {
257
- // The CLI config is the source of truth for the path.
258
- const folder = (0, config_1.readConfig)().firewallRulesFolder;
259
- console.log(folder ? folder : (0, utils_1.dim)('(no firewall rules folder configured)'));
260
- return;
261
- }
262
- if (action === 'set') {
263
- const path = (opts.path ?? '').trim();
264
- if (!path)
265
- throw new Error('Usage: huddle firewall folder set <path>');
266
- // Config-only: the gateway reads the folder at the fixed mount point the CLI
267
- // binds it to; there is no DB setting. Persist here and mount on restart.
268
- (0, config_1.writeConfig)({ ...(0, config_1.readConfig)(), firewallRulesFolder: path });
269
- console.log((0, utils_1.green)(`[OK] Firewall rules folder set to ${(0, utils_1.cyan)(path)}`));
270
- console.log((0, utils_1.dim)(' Run `huddle restart` to mount it into the gateway; it is then read on start & reload.'));
271
- return;
272
- }
273
- if (action === 'reload') {
274
- const res = await (0, api_1.post)('/api/firewall-rules-folder/reload', {});
275
- if (!res.mounted) {
276
- console.log((0, utils_1.dim)('No firewall rules folder mounted. Set one with `huddle firewall folder set <path>` and run `huddle restart`.'));
277
- return;
278
- }
279
- console.log((0, utils_1.green)(`[OK] Reloaded: ${res.groups} group(s), ${res.imported} rule(s), ${res.errors.length} error(s)`));
280
- for (const e of res.errors)
281
- console.error((0, utils_1.red)(` [!] ${e.file}: ${e.message}`));
282
- return;
283
- }
284
- throw new Error(`Unknown folder action: ${action}. Use show | set | reload.`);
285
- }
package/dist/index.js CHANGED
@@ -15,9 +15,9 @@ const images_1 = require("./images");
15
15
  const self_update_1 = require("./self-update");
16
16
  const utils_1 = require("./utils");
17
17
  const experiment_1 = require("./experiment");
18
- const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'out', 'ca-path', 'output']);
19
- const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'replace', 'docker-socket', 'force']);
20
- const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'restart', 'experiment', 'migrate', 'help', 'version']);
18
+ const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment', 'path', 'ca-path', 'output']);
19
+ const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v', 'deny', 'docker-socket', 'force']);
20
+ const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'experiment', 'migrate', 'help', 'version']);
21
21
  function parseArgs(argv) {
22
22
  const positional = [];
23
23
  const flags = {};
@@ -94,8 +94,6 @@ Usage:
94
94
  huddle start [options] [folder] Explicitly start a devcontainer
95
95
  huddle init [options] Pull the Huddle + devcontainer base images and
96
96
  start them via Docker or Podman
97
- huddle restart Recreate the gateway (e.g. to mount a changed
98
- team firewall-rules folder)
99
97
  huddle migrate [folder] Wire an existing docker-compose devcontainer
100
98
  behind Huddle by generating an override file
101
99
  huddle firewall list [options] Show firewall requests
@@ -104,14 +102,6 @@ Usage:
104
102
  supported: *.example.com and /path/*)
105
103
  huddle firewall delete <id> Delete a firewall rule by id (or domain;
106
104
  narrow with --container)
107
- huddle firewall export [options] Export firewall rules as JSON
108
- huddle firewall import <file> Import firewall rules from a JSON file
109
- huddle firewall group list List firewall groups (#69)
110
- huddle firewall group export <name> Export a group as JSON (--out <file>)
111
- huddle firewall group import <file> Import a group (--replace to mirror)
112
- huddle firewall group apply <name> Apply a group (--container <id> or global)
113
- huddle firewall folder set <path> Set the team-managed rules folder
114
- huddle firewall folder reload Re-read the team-managed rules folder
115
105
  huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
116
106
  and run init
117
107
  huddle experiment reset Back to the stable release
@@ -142,8 +132,6 @@ Migrate options:
142
132
  Firewall options:
143
133
  -i, --interactive Interactively approve/deny (list)
144
134
  --container <name> Filter by (list) / scope to (add) a container
145
- (or __global__). On import: remap all rules
146
- to this scope
147
135
  --status <requested|allow|deny> Filter by status (default: requested)
148
136
 
149
137
  Firewall add options:
@@ -152,11 +140,6 @@ Firewall add options:
152
140
  (e.g. /_packaging/*/nuget/v3/*)
153
141
  --deny Create a block rule (default: allow)
154
142
 
155
- Firewall export/import options:
156
- --out <file> Write export to a file (default: stdout)
157
- --replace Import in replace mode: wipe the target
158
- scope first (default: merge/upsert)
159
-
160
143
  Global options:
161
144
  --url <url> Huddle URL (default: http://localhost:3000)
162
145
  Or via the HUDDLE_URL env var
@@ -219,15 +202,6 @@ async function main() {
219
202
  await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
220
203
  return;
221
204
  }
222
- if (cmd === 'restart') {
223
- // Stop + recreate the gateway (runInit does `rm -f` first) so changed team
224
- // folders get mounted. The portal writes the paths straight into the mounted
225
- // ~/.huddle/config.json, so runInit already reads the latest values here.
226
- const initOpts = { runtime: flagString(flags, 'runtime') };
227
- (0, experiment_1.ensureCliForChannel)(process.argv.slice(2));
228
- await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
229
- return;
230
- }
231
205
  if (cmd === 'experiment') {
232
206
  const subCmd = sub ?? 'status';
233
207
  if (subCmd === 'use') {
@@ -269,36 +243,6 @@ async function main() {
269
243
  container: flagString(flags, 'container'),
270
244
  });
271
245
  }
272
- else if (subCmd === 'export') {
273
- await (0, firewall_1.runFirewallExport)({
274
- container: flagString(flags, 'container'),
275
- out: flagString(flags, 'out'),
276
- });
277
- }
278
- else if (subCmd === 'import') {
279
- const file = positional[2];
280
- if (!file) {
281
- console.error('Usage: huddle firewall import <file> [--replace] [--container <id>]');
282
- process.exit(1);
283
- }
284
- await (0, firewall_1.runFirewallImport)({
285
- file,
286
- replace: flagBool(flags, 'replace'),
287
- container: flagString(flags, 'container'),
288
- });
289
- }
290
- else if (subCmd === 'group' || subCmd === 'groups') {
291
- await (0, firewall_1.runFirewallGroup)({
292
- action: positional[2],
293
- arg: positional[3],
294
- out: flagString(flags, 'out'),
295
- replace: flagBool(flags, 'replace'),
296
- container: flagString(flags, 'container'),
297
- });
298
- }
299
- else if (subCmd === 'folder') {
300
- await (0, firewall_1.runFirewallFolder)({ action: positional[2], path: positional[3] });
301
- }
302
246
  else {
303
247
  console.error(`Unknown firewall subcommand: ${subCmd}`);
304
248
  process.exit(1);
package/dist/init.js CHANGED
@@ -145,19 +145,6 @@ async function runInit(opts, images) {
145
145
  // network (moby/moby#36174). Which source IP the gateway sees for forwarded
146
146
  // traffic no longer matters — the control plane authenticates with the
147
147
  // operator token instead of source-IP filtering.
148
- // Team-managed folders (#69). Bind the CLI config dir (~/.huddle) read-write so
149
- // the gateway/portal read and write the folder paths there (config.json is the
150
- // single source of truth), then bind each configured team folder to a FIXED
151
- // path so the gateway reads it without knowing the host path. Read-only.
152
- const fwFolder = cfg.firewallRulesFolder?.trim();
153
- const extFolder = cfg.extensionsFolder?.trim();
154
- const homeMountFlag = ` -v "${config_1.CONFIG_DIR}:/huddle-home:rw" -e HUDDLE_HOME_DIR=/huddle-home`;
155
- const fwMountFlag = fwFolder ? ` -v "${fwFolder}:/firewall-rules:ro"` : '';
156
- const extMountFlag = extFolder ? ` -v "${extFolder}:/extensions:ro"` : '';
157
- if (fwFolder)
158
- console.log((0, utils_1.dim)(` Mounting firewall-rules folder: ${fwFolder} -> /firewall-rules`));
159
- if (extFolder)
160
- console.log((0, utils_1.dim)(` Mounting extensions folder: ${extFolder} -> /extensions`));
161
148
  run(`${rt} run -d` +
162
149
  ` --name ${CONTAINER}` +
163
150
  ` --network ${runtime.defaultNetwork}` +
@@ -166,11 +153,8 @@ async function runInit(opts, images) {
166
153
  ` -e HUDDLE_OPERATOR_TOKEN=${operatorToken}` +
167
154
  ` -p ${HOST_PORT}:3000` +
168
155
  ` -v ${VOLUME}:/data` +
169
- ` -v ${runtime.socketPath}:/var/run/docker.sock` +
156
+ ` -v "${runtime.socketPath}:/var/run/docker.sock"` +
170
157
  ` -v "${hostTmpSockets}:/tmp/dc-sockets"` +
171
- homeMountFlag +
172
- fwMountFlag +
173
- extMountFlag +
174
158
  (0, images_1.gatewayEnvFlags)(images) +
175
159
  ` ${IMAGE}`);
176
160
  // Attaching devcontainer-net after the container has started pollutes
package/dist/migrate.js CHANGED
@@ -118,11 +118,9 @@ function findMarkedNetworks(compose) {
118
118
  * Throws on hard configuration errors (no/ambiguous marked network); collects
119
119
  * softer problems in `warnings`.
120
120
  */
121
- function buildOverride(compose, opts = {}) {
122
- const caPath = opts.caPath ?? exports.DEFAULT_CA_PATH;
123
- const internalNet = opts.internalNet ?? init_1.INTERNAL_NET;
124
- const socketDir = opts.socketDir ?? init_1.HOST_SOCKET_DIR;
125
- const warnings = [];
121
+ // Exactly one network must carry the huddle.network label. Zero or more than one
122
+ // is a hard error the operator must resolve before a safe override can be built.
123
+ function resolveMarkedNetwork(compose) {
126
124
  const marked = findMarkedNetworks(compose);
127
125
  if (marked.length === 0) {
128
126
  throw new Error(`No network marked with \`${exports.HUDDLE_NETWORK_LABEL}: "true"\` was found. ` +
@@ -131,18 +129,70 @@ function buildOverride(compose, opts = {}) {
131
129
  if (marked.length > 1) {
132
130
  throw new Error(`Multiple networks marked with \`${exports.HUDDLE_NETWORK_LABEL}\`: ${marked.join(', ')}. Mark exactly one.`);
133
131
  }
134
- const markedNetwork = marked[0];
135
- // Pick a collision-free key for the injected egress network.
136
- const existingNetKeys = new Set(Object.keys(compose.networks ?? {}));
137
- let huddleNetKey = opts.huddleNetKey ?? exports.HUDDLE_NET_KEY;
138
- if (existingNetKeys.has(huddleNetKey) && huddleNetKey !== markedNetwork) {
139
- huddleNetKey = `${exports.HUDDLE_NET_KEY}-egress`;
132
+ return marked[0];
133
+ }
134
+ // Pick a key for the injected egress network that collides with NOTHING: not an
135
+ // existing network, and not the marked network itself (otherwise the two keys in
136
+ // the service's `networks` map collapse into one and the egress net is silently
137
+ // never added). Keep suffixing until it is unique.
138
+ function pickHuddleNetKey(compose, markedNetwork, preferred) {
139
+ const taken = new Set(Object.keys(compose.networks ?? {}));
140
+ taken.add(markedNetwork);
141
+ let key = preferred;
142
+ if (taken.has(key)) {
143
+ let n = 0;
144
+ do {
145
+ key = n === 0 ? `${exports.HUDDLE_NET_KEY}-egress` : `${exports.HUDDLE_NET_KEY}-egress-${n}`;
146
+ n++;
147
+ } while (taken.has(key));
148
+ }
149
+ return key;
150
+ }
151
+ // Build the override entry for a single service: keep it on the marked network,
152
+ // add the Huddle egress network + proxy env, and (with --docker-socket) mount the
153
+ // filtered Docker socket. Any second, non-internal network is flagged as a
154
+ // blocker — it would be an unfiltered route out that bypasses Huddle.
155
+ function buildInjectedService(svc, name, compose, ctx, warnings, blockers) {
156
+ for (const netKey of serviceNetworkKeys(svc)) {
157
+ if (netKey === ctx.markedNetwork)
158
+ continue;
159
+ const def = (compose.networks?.[netKey] ?? {});
160
+ if (!isTruthy(def.internal)) {
161
+ blockers.push(`Service "${name}" is also on network "${netKey}", which is not internal. ` +
162
+ 'Remove it or make it internal — a second non-internal network bypasses Huddle.');
163
+ }
140
164
  }
165
+ const injected = {
166
+ // Keep the service on its own network AND add the Huddle egress network.
167
+ // Map form is robust regardless of Compose's list merge semantics.
168
+ networks: { [ctx.markedNetwork]: null, [ctx.huddleNetKey]: null },
169
+ environment: huddleProxyEnv(ctx.caPath, ctx.dockerSocket),
170
+ };
171
+ if (ctx.dockerSocket) {
172
+ const cn = svc.container_name;
173
+ if (!cn) {
174
+ warnings.push(`Service "${name}" has no \`container_name\`, so the filtered Docker socket cannot be mounted ` +
175
+ 'at a stable path. Set a fixed container_name or drop --docker-socket for this service.');
176
+ }
177
+ else {
178
+ injected.volumes = [`${ctx.socketDir}/${cn}:/var/run/huddle`];
179
+ }
180
+ }
181
+ return injected;
182
+ }
183
+ function buildOverride(compose, opts = {}) {
184
+ const caPath = opts.caPath ?? exports.DEFAULT_CA_PATH;
185
+ const internalNet = opts.internalNet ?? init_1.INTERNAL_NET;
186
+ const socketDir = opts.socketDir ?? init_1.HOST_SOCKET_DIR;
187
+ const warnings = [];
188
+ const blockers = [];
189
+ const markedNetwork = resolveMarkedNetwork(compose);
190
+ const huddleNetKey = pickHuddleNetKey(compose, markedNetwork, opts.huddleNetKey ?? exports.HUDDLE_NET_KEY);
141
191
  // Guardrail: the marked network must be internal, otherwise it already has a
142
192
  // route to the internet and would bypass the firewall/proxy.
143
193
  const markedDef = (compose.networks?.[markedNetwork] ?? {});
144
194
  if (!isTruthy(markedDef.internal)) {
145
- warnings.push(`Network "${markedNetwork}" is not marked \`internal: true\`. It must be internal, ` +
195
+ blockers.push(`Network "${markedNetwork}" is not marked \`internal: true\`. It must be internal, ` +
146
196
  'otherwise services can reach the internet directly and bypass Huddle.');
147
197
  }
148
198
  const services = Object.entries(compose.services ?? {})
@@ -151,37 +201,11 @@ function buildOverride(compose, opts = {}) {
151
201
  if (services.length === 0) {
152
202
  warnings.push(`No service is attached to the marked network "${markedNetwork}"; the override wires nothing.`);
153
203
  }
204
+ const ctx = { markedNetwork, huddleNetKey, caPath, socketDir, dockerSocket: !!opts.dockerSocket };
154
205
  const overrideServices = {};
155
206
  for (const name of services) {
156
207
  const svc = (compose.services?.[name] ?? {});
157
- // Guardrail: warn if the service also sits on another network that is not
158
- // internal — that would be a second, unfiltered route out.
159
- for (const netKey of serviceNetworkKeys(svc)) {
160
- if (netKey === markedNetwork)
161
- continue;
162
- const def = (compose.networks?.[netKey] ?? {});
163
- if (!isTruthy(def.internal)) {
164
- warnings.push(`Service "${name}" is also on network "${netKey}", which is not internal. ` +
165
- 'Remove it or make it internal — a second non-internal network bypasses Huddle.');
166
- }
167
- }
168
- const injected = {
169
- // Keep the service on its own network AND add the Huddle egress network.
170
- // Map form is robust regardless of Compose's list merge semantics.
171
- networks: { [markedNetwork]: null, [huddleNetKey]: null },
172
- environment: huddleProxyEnv(caPath, !!opts.dockerSocket),
173
- };
174
- if (opts.dockerSocket) {
175
- const cn = svc.container_name;
176
- if (!cn) {
177
- warnings.push(`Service "${name}" has no \`container_name\`, so the filtered Docker socket cannot be mounted ` +
178
- 'at a stable path. Set a fixed container_name or drop --docker-socket for this service.');
179
- }
180
- else {
181
- injected.volumes = [`${socketDir}/${cn}:/var/run/huddle`];
182
- }
183
- }
184
- overrideServices[name] = injected;
208
+ overrideServices[name] = buildInjectedService(svc, name, compose, ctx, warnings, blockers);
185
209
  }
186
210
  const override = {
187
211
  services: overrideServices,
@@ -191,7 +215,7 @@ function buildOverride(compose, opts = {}) {
191
215
  [huddleNetKey]: { external: true, name: internalNet },
192
216
  },
193
217
  };
194
- return { markedNetwork, services, override, warnings };
218
+ return { markedNetwork, services, override, warnings, blockers };
195
219
  }
196
220
  function tokenize(input) {
197
221
  const out = [];
@@ -220,6 +244,10 @@ function stripComment(line) {
220
244
  }
221
245
  return line;
222
246
  }
247
+ // Shared depth cap for both the reader (parseNode ↔ parseMapping/parseSequence)
248
+ // and the writer (dumpYaml ↔ dumpInlineOrBlock). Real compose trees are only a
249
+ // few levels deep; a much larger cap still forecloses stack-exhaustion (CWE-674).
250
+ const MAX_YAML_DEPTH = 64;
223
251
  function unsupportedYaml(feature) {
224
252
  return new Error(`the compose file uses ${feature}, which \`huddle migrate\`'s built-in YAML reader does ` +
225
253
  'not support and would mis-parse (risking a dropped, un-filtered service). Inline or ' +
@@ -253,9 +281,14 @@ function rejectUnsupportedYaml(lines) {
253
281
  const value = lineValue(text);
254
282
  if (BLOCK_SCALAR_HEADER.test(value))
255
283
  throw unsupportedYaml('a block scalar (`|` or `>`)');
256
- if (/^&[A-Za-z0-9_]/.test(value))
284
+ // Match an anchor/alias in any NODE position: at the value start OR right
285
+ // after a flow opener/separator (`[`, `{`, `,`) or a flow-map colon — so
286
+ // `networks: [*net]` and `{n: *net}` are caught too, not just `x: *net`.
287
+ // The trailing name char keeps this off scalar `&`/`*` (env URLs, globs like
288
+ // `*.log`), which never start an anchor/alias name.
289
+ if (/(^|[[{,:]\s*)&[A-Za-z0-9_]/.test(value))
257
290
  throw unsupportedYaml('a YAML anchor (`&`)');
258
- if (/^\*[A-Za-z0-9_]/.test(value))
291
+ if (/(^|[[{,:]\s*)\*[A-Za-z0-9_]/.test(value))
259
292
  throw unsupportedYaml('a YAML alias (`*`)');
260
293
  }
261
294
  }
@@ -263,12 +296,17 @@ function parseYaml(input) {
263
296
  const lines = tokenize(input);
264
297
  rejectUnsupportedYaml(lines);
265
298
  let pos = 0;
266
- function parseNode(indent) {
299
+ // Cap the mutual recursion (parseNode ↔ parseMapping/parseSequence) so a deeply
300
+ // nested (malformed or hostile) compose file cannot exhaust the stack (CWE-674).
301
+ function parseNode(indent, depth) {
302
+ if (depth > MAX_YAML_DEPTH) {
303
+ throw new Error(`YAML nesting exceeds ${MAX_YAML_DEPTH} levels; refusing to parse this compose file.`);
304
+ }
267
305
  if (pos >= lines.length || lines[pos].indent < indent)
268
306
  return null;
269
- return isSeqItem(lines[pos].text) ? parseSequence(indent) : parseMapping(indent);
307
+ return isSeqItem(lines[pos].text) ? parseSequence(indent, depth) : parseMapping(indent, depth);
270
308
  }
271
- function parseMapping(indent) {
309
+ function parseMapping(indent, depth) {
272
310
  const map = {};
273
311
  while (pos < lines.length && lines[pos].indent === indent && !isSeqItem(lines[pos].text)) {
274
312
  const { text } = lines[pos];
@@ -284,7 +322,7 @@ function parseYaml(input) {
284
322
  map[key] = parseScalar(rest);
285
323
  }
286
324
  else if (pos < lines.length && lines[pos].indent > indent) {
287
- map[key] = parseNode(lines[pos].indent);
325
+ map[key] = parseNode(lines[pos].indent, depth + 1);
288
326
  }
289
327
  else {
290
328
  map[key] = null;
@@ -292,20 +330,20 @@ function parseYaml(input) {
292
330
  }
293
331
  return map;
294
332
  }
295
- function parseSequence(indent) {
333
+ function parseSequence(indent, depth) {
296
334
  const arr = [];
297
335
  while (pos < lines.length && lines[pos].indent === indent && isSeqItem(lines[pos].text)) {
298
336
  const afterDash = lines[pos].text.replace(/^-\s*/, '');
299
337
  if (afterDash === '') {
300
338
  pos++;
301
- arr.push(pos < lines.length && lines[pos].indent > indent ? parseNode(lines[pos].indent) : null);
339
+ arr.push(pos < lines.length && lines[pos].indent > indent ? parseNode(lines[pos].indent, depth + 1) : null);
302
340
  }
303
341
  else if (findKeyColon(afterDash) >= 0) {
304
342
  // Inline map item: "- key: value". Re-interpret the remainder as a
305
343
  // mapping that starts at a virtual indent past the dash.
306
344
  const virtualIndent = indent + (lines[pos].text.length - afterDash.length);
307
345
  lines[pos] = { indent: virtualIndent, text: afterDash };
308
- arr.push(parseMapping(virtualIndent));
346
+ arr.push(parseMapping(virtualIndent, depth + 1));
309
347
  }
310
348
  else {
311
349
  arr.push(parseScalar(afterDash));
@@ -314,7 +352,7 @@ function parseYaml(input) {
314
352
  }
315
353
  return arr;
316
354
  }
317
- const root = parseNode(lines.length ? lines[0].indent : 0);
355
+ const root = parseNode(lines.length ? lines[0].indent : 0, 0);
318
356
  return (root && typeof root === 'object' ? root : {});
319
357
  }
320
358
  function isSeqItem(text) {
@@ -345,8 +383,12 @@ function parseScalar(raw) {
345
383
  const map = {};
346
384
  for (const part of splitFlow(value.slice(1, -1))) {
347
385
  const colon = findKeyColon(part);
386
+ // Fail closed: a flow-map entry we cannot split into `key: value` (e.g. the
387
+ // compact `{networks:[dev, public]}` form, where the colon has no following
388
+ // space) must NOT be silently dropped — that would omit the service from the
389
+ // generated override and leave it on its original, un-filtered network.
348
390
  if (colon < 0)
349
- continue;
391
+ throw unsupportedYaml('a compact flow-mapping entry (`{key:value}` without a space after the colon)');
350
392
  map[unquote(part.slice(0, colon).trim())] = parseScalar(part.slice(colon + 1).trim());
351
393
  }
352
394
  return map;
@@ -405,6 +447,13 @@ function unquote(value) {
405
447
  }
406
448
  /** Emits an object as YAML using the subset the reader understands. */
407
449
  function dumpYaml(obj, indent = 0) {
450
+ // `indent` doubles as the recursion depth (dumpYaml ↔ dumpInlineOrBlock each
451
+ // step it by one). Cap it so a pathologically nested object cannot exhaust the
452
+ // stack (CWE-674) — mirrors the MAX_DEPTH guard on the parse side. Legitimate
453
+ // compose trees are only a few levels deep.
454
+ if (indent > MAX_YAML_DEPTH) {
455
+ throw new Error(`YAML nesting exceeds ${MAX_YAML_DEPTH} levels; refusing to emit this override.`);
456
+ }
408
457
  const pad = ' '.repeat(indent);
409
458
  if (obj === null || obj === undefined)
410
459
  return '';
@@ -535,7 +584,17 @@ async function runMigrate(opts) {
535
584
  console.log(`Wired services: ${result.services.length ? result.services.map(utils_1.bold).join(', ') : (0, utils_1.dim)('(none)')}`);
536
585
  for (const w of result.warnings)
537
586
  console.log((0, utils_1.yellow)(`[!] ${w}`));
587
+ for (const b of result.blockers)
588
+ console.log((0, utils_1.red)(`[x] ${b}`));
538
589
  console.log();
590
+ // Fail closed: these blockers mean the migrated service would keep a direct
591
+ // route to the internet, so writing the override and reporting success would
592
+ // be misleading. Refuse unless the operator explicitly overrides with --force.
593
+ if (result.blockers.length > 0 && !opts.force) {
594
+ throw new Error(`Refusing to write the override: the migration would leave a direct internet path ` +
595
+ `(${result.blockers.length} blocker(s) above). Fix your compose file, or re-run with ` +
596
+ `--force to generate it anyway.`);
597
+ }
539
598
  const overrideText = '# Generated by `huddle migrate` — do NOT edit by hand; re-run the command instead.\n' +
540
599
  '# Merge this on top of your docker-compose.yml so the marked services reach the\n' +
541
600
  '# internet only through the Huddle proxy. Your own compose file stays untouched.\n' +
package/dist/runtime.js CHANGED
@@ -72,13 +72,14 @@ function parseDockerContextSocket(json) {
72
72
  const path = host.slice('unix://'.length);
73
73
  if (!path.startsWith('/'))
74
74
  return null;
75
- // The returned path is later interpolated UNquoted into a `docker run -v
76
- // <path>:...` shell command (init.ts). The `Host` from `docker context
75
+ // The returned path is interpolated into a `docker run -v "<path>:..."` shell
76
+ // command (init.ts), where it is DOUBLE-QUOTED. The `Host` from `docker context
77
77
  // inspect` is attacker-influenceable (whoever can create/activate a docker
78
- // context controls the value), so only allow characters that occur in a real
79
- // socket path. This way a manipulated context cannot smuggle in shell
80
- // metacharacters ($(), backticks, ;, |, spaces, ...) — command injection.
81
- if (!/^[A-Za-z0-9._/-]+$/.test(path))
78
+ // context controls the value), so restrict it to characters that occur in a real
79
+ // socket path: allow spaces (legal in e.g. macOS `/Users/First Last/.rd/...`)
80
+ // but never the metacharacters that stay dangerous inside double quotes
81
+ // ($, backtick, ", \) or the command separators (;, |, &, (), newline).
82
+ if (!/^[A-Za-z0-9._/ -]+$/.test(path))
82
83
  return null;
83
84
  return path;
84
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infosupport/huddle-cli",
3
- "version": "0.0.0-experiment-66.39.1",
3
+ "version": "0.0.0-experiment-97.41.1",
4
4
  "description": "Huddle CLI — start devcontainers and manage firewall rules",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Info Support B.V.",