@infosupport/huddle-cli 1.2.11 → 1.2.13
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/experiment.js +10 -3
- package/dist/firewall.js +68 -0
- package/dist/index.js +59 -10
- package/dist/init.js +27 -13
- package/dist/migrate.js +641 -0
- package/dist/runtime.js +76 -15
- package/package.json +1 -1
package/dist/experiment.js
CHANGED
|
@@ -33,9 +33,14 @@ function parseIssueNumber(raw) {
|
|
|
33
33
|
* itself (install + restart) is done by self-update.ts. On a switch this
|
|
34
34
|
* function does not return (process.exit with the exit code of the new process).
|
|
35
35
|
*/
|
|
36
|
-
function ensureCliForChannel(relaunchArgs) {
|
|
36
|
+
function ensureCliForChannel(relaunchArgs, opts = {}) {
|
|
37
37
|
const wanted = (0, config_1.activeExperiment)();
|
|
38
|
-
|
|
38
|
+
// Normally we only switch when the experiment NUMBER differs — otherwise every
|
|
39
|
+
// command would reinstall. But `huddle experiment use <n>` must pick up a newer
|
|
40
|
+
// build of the SAME experiment (the CLI version is baked in, so the number
|
|
41
|
+
// alone can't tell 66.34 from 66.35): force a reinstall of the channel tag,
|
|
42
|
+
// which npm resolves to the latest build for that experiment.
|
|
43
|
+
if (!opts.force && wanted === cliExperiment())
|
|
39
44
|
return;
|
|
40
45
|
const spec = wanted !== undefined ? `${self_update_1.CLI_PACKAGE}@experiment-${wanted}` : `${self_update_1.CLI_PACKAGE}@latest`;
|
|
41
46
|
try {
|
|
@@ -56,7 +61,9 @@ async function runExperimentUse(issue, initOpts = {}) {
|
|
|
56
61
|
console.log((0, utils_1.green)(`Experiment ${issue} activated`) + (0, utils_1.dim)(` (${(0, config_1.configPath)()})`));
|
|
57
62
|
const relaunchArgs = ['init', ...(initOpts.runtime ? ['--runtime', initOpts.runtime] : [])];
|
|
58
63
|
try {
|
|
59
|
-
|
|
64
|
+
// Force: `use` always (re)installs the latest build of the target experiment,
|
|
65
|
+
// even when already on that experiment number, so a republished build lands.
|
|
66
|
+
ensureCliForChannel(relaunchArgs, { force: true });
|
|
60
67
|
}
|
|
61
68
|
catch (err) {
|
|
62
69
|
// Activation failed → roll back the config so a subsequent `huddle init`
|
package/dist/firewall.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.runFirewallList = runFirewallList;
|
|
4
|
+
exports.runFirewallAdd = runFirewallAdd;
|
|
5
|
+
exports.runFirewallDelete = runFirewallDelete;
|
|
4
6
|
const api_1 = require("./api");
|
|
5
7
|
const utils_1 = require("./utils");
|
|
6
8
|
async function runFirewallList(opts) {
|
|
@@ -52,6 +54,72 @@ async function reviewRule(rule, idx, total) {
|
|
|
52
54
|
async function resolveRule(rule, status, scope) {
|
|
53
55
|
await (0, api_1.post)(`/api/rules/${rule.id}/resolve`, { status, scope });
|
|
54
56
|
}
|
|
57
|
+
// Creates a custom firewall rule. Supports wildcards: `*.` in the domain
|
|
58
|
+
// (e.g. `*.pkgs.dev.azure.com`) and `*` in the path pattern (e.g.
|
|
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.
|
|
62
|
+
async function runFirewallAdd(opts) {
|
|
63
|
+
const domain = (opts.domain ?? '').trim();
|
|
64
|
+
if (!domain) {
|
|
65
|
+
throw new Error('Usage: huddle firewall add <domain> [--path <pattern>] [--deny] [--container <id>]');
|
|
66
|
+
}
|
|
67
|
+
const status = opts.deny ? 'deny' : 'allow';
|
|
68
|
+
const path = opts.path?.trim();
|
|
69
|
+
const body = {
|
|
70
|
+
domain,
|
|
71
|
+
container_id: opts.container ?? null,
|
|
72
|
+
status,
|
|
73
|
+
};
|
|
74
|
+
if (path)
|
|
75
|
+
body.path_pattern = path;
|
|
76
|
+
const rule = await (0, api_1.post)('/api/rules', body);
|
|
77
|
+
const target = formatTarget(rule);
|
|
78
|
+
const scope = rule.container_id ? `container: ${rule.container_id}` : 'global';
|
|
79
|
+
const verb = status === 'deny' ? (0, utils_1.red)('Denied') : (0, utils_1.green)('Allowed');
|
|
80
|
+
console.log(`${verb} ${(0, utils_1.bold)((0, utils_1.cyan)(target))} ${(0, utils_1.dim)(`(${scope})`)}`);
|
|
81
|
+
}
|
|
82
|
+
// Deletes a firewall rule. Accepts the numeric id shown by `firewall list`
|
|
83
|
+
// (deleted directly) or a domain, which is resolved to a single rule id via a
|
|
84
|
+
// lookup. `--container` narrows a domain match to one scope; an ambiguous
|
|
85
|
+
// domain (multiple matching rules) is refused with the candidate ids so the
|
|
86
|
+
// caller can re-run with an exact id.
|
|
87
|
+
async function runFirewallDelete(opts) {
|
|
88
|
+
const target = (opts.target ?? '').trim();
|
|
89
|
+
if (!target) {
|
|
90
|
+
throw new Error('Usage: huddle firewall delete <id-or-domain> [--container <id>]');
|
|
91
|
+
}
|
|
92
|
+
let id;
|
|
93
|
+
if (/^\d+$/.test(target)) {
|
|
94
|
+
id = Number(target);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
// Domain form: list all rules (optionally scoped) and resolve to one id.
|
|
98
|
+
const qs = new URLSearchParams();
|
|
99
|
+
if (opts.container)
|
|
100
|
+
qs.set('container', opts.container);
|
|
101
|
+
const query = qs.toString();
|
|
102
|
+
const rules = await (0, api_1.get)(`/api/rules${query ? `?${query}` : ''}`);
|
|
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);
|
|
108
|
+
if (matches.length === 0) {
|
|
109
|
+
const scope = opts.container ? ` for container ${opts.container}` : '';
|
|
110
|
+
throw new Error(`No firewall rule found for "${target}"${scope}.`);
|
|
111
|
+
}
|
|
112
|
+
if (matches.length > 1) {
|
|
113
|
+
const ids = matches
|
|
114
|
+
.map((r) => ` ${r.id} ${r.status.padEnd(9)} ${formatTarget(r)} ${r.container_id ?? '(global)'}`)
|
|
115
|
+
.join('\n');
|
|
116
|
+
throw new Error(`"${target}" matches ${matches.length} rules — delete by id (or narrow with --container):\n${ids}`);
|
|
117
|
+
}
|
|
118
|
+
id = matches[0].id;
|
|
119
|
+
}
|
|
120
|
+
await (0, api_1.del)(`/api/rules/${id}`);
|
|
121
|
+
console.log(`${(0, utils_1.green)('Deleted')} rule ${(0, utils_1.bold)((0, utils_1.cyan)(String(id)))}`);
|
|
122
|
+
}
|
|
55
123
|
function printRulesTable(rules) {
|
|
56
124
|
const headers = ['ID', 'Status', 'Domain/path', 'Container', 'Requests', 'Seen'];
|
|
57
125
|
const rows = rules.map((r) => [
|
package/dist/index.js
CHANGED
|
@@ -10,13 +10,14 @@ const api_1 = require("./api");
|
|
|
10
10
|
const start_1 = require("./start");
|
|
11
11
|
const firewall_1 = require("./firewall");
|
|
12
12
|
const init_1 = require("./init");
|
|
13
|
+
const migrate_1 = require("./migrate");
|
|
13
14
|
const images_1 = require("./images");
|
|
14
15
|
const self_update_1 = require("./self-update");
|
|
15
16
|
const utils_1 = require("./utils");
|
|
16
17
|
const experiment_1 = require("./experiment");
|
|
17
|
-
const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment']);
|
|
18
|
-
const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v']);
|
|
19
|
-
const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'experiment', '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']);
|
|
20
21
|
function parseArgs(argv) {
|
|
21
22
|
const positional = [];
|
|
22
23
|
const flags = {};
|
|
@@ -93,8 +94,14 @@ Usage:
|
|
|
93
94
|
huddle start [options] [folder] Explicitly start a devcontainer
|
|
94
95
|
huddle init [options] Pull the Huddle + devcontainer base images and
|
|
95
96
|
start them via Docker or Podman
|
|
97
|
+
huddle migrate [folder] Wire an existing docker-compose devcontainer
|
|
98
|
+
behind Huddle by generating an override file
|
|
96
99
|
huddle firewall list [options] Show firewall requests
|
|
97
100
|
huddle fw list [options] Alias for firewall list
|
|
101
|
+
huddle firewall add <domain> Add a custom firewall rule (wildcards
|
|
102
|
+
supported: *.example.com and /path/*)
|
|
103
|
+
huddle firewall delete <id> Delete a firewall rule by id (or domain;
|
|
104
|
+
narrow with --container)
|
|
98
105
|
huddle experiment use <nr> Activate the experimental build of issue/PR <nr>
|
|
99
106
|
and run init
|
|
100
107
|
huddle experiment reset Back to the stable release
|
|
@@ -113,11 +120,26 @@ Start options:
|
|
|
113
120
|
--image <image> Use a specific image
|
|
114
121
|
--empty Empty container without a workspace
|
|
115
122
|
|
|
123
|
+
Migrate options:
|
|
124
|
+
--ca-path <path> Where the Huddle CA lands in the container
|
|
125
|
+
(NODE_EXTRA_CA_CERTS; default /home/vscode/.huddle-ca.crt)
|
|
126
|
+
--docker-socket Also wire the filtered Docker socket + DOCKER_HOST
|
|
127
|
+
(requires gateway socket pre-provisioning; see docs)
|
|
128
|
+
--output <path> Override file to write
|
|
129
|
+
(default: docker-compose.huddle.yml next to the source)
|
|
130
|
+
--force Overwrite an existing override file
|
|
131
|
+
|
|
116
132
|
Firewall options:
|
|
117
|
-
-i, --interactive Interactively approve/deny
|
|
118
|
-
--container <name> Filter by container
|
|
133
|
+
-i, --interactive Interactively approve/deny (list)
|
|
134
|
+
--container <name> Filter by (list) / scope to (add) a container
|
|
119
135
|
--status <requested|allow|deny> Filter by status (default: requested)
|
|
120
136
|
|
|
137
|
+
Firewall add options:
|
|
138
|
+
--path <pattern> Path pattern; * matches within a segment,
|
|
139
|
+
a trailing * spans deeper segments
|
|
140
|
+
(e.g. /_packaging/*/nuget/v3/*)
|
|
141
|
+
--deny Create a block rule (default: allow)
|
|
142
|
+
|
|
121
143
|
Global options:
|
|
122
144
|
--url <url> Huddle URL (default: http://localhost:3000)
|
|
123
145
|
Or via the HUDDLE_URL env var
|
|
@@ -200,14 +222,41 @@ async function main() {
|
|
|
200
222
|
}
|
|
201
223
|
if (cmd === 'firewall' || cmd === 'fw') {
|
|
202
224
|
const subCmd = sub ?? 'list';
|
|
203
|
-
if (subCmd
|
|
225
|
+
if (subCmd === 'list') {
|
|
226
|
+
await (0, firewall_1.runFirewallList)({
|
|
227
|
+
interactive: flagBool(flags, 'i', 'interactive'),
|
|
228
|
+
container: flagString(flags, 'container'),
|
|
229
|
+
status: flagString(flags, 'status'),
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
else if (subCmd === 'add') {
|
|
233
|
+
await (0, firewall_1.runFirewallAdd)({
|
|
234
|
+
domain: positional[2],
|
|
235
|
+
path: flagString(flags, 'path'),
|
|
236
|
+
deny: flagBool(flags, 'deny'),
|
|
237
|
+
container: flagString(flags, 'container'),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
else if (subCmd === 'delete' || subCmd === 'remove' || subCmd === 'rm') {
|
|
241
|
+
await (0, firewall_1.runFirewallDelete)({
|
|
242
|
+
target: positional[2],
|
|
243
|
+
container: flagString(flags, 'container'),
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
204
247
|
console.error(`Unknown firewall subcommand: ${subCmd}`);
|
|
205
248
|
process.exit(1);
|
|
206
249
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (cmd === 'migrate') {
|
|
253
|
+
await (0, migrate_1.runMigrate)({
|
|
254
|
+
path: positional[1],
|
|
255
|
+
caPath: flagString(flags, 'ca-path'),
|
|
256
|
+
dockerSocket: flagBool(flags, 'docker-socket'),
|
|
257
|
+
output: flagString(flags, 'output'),
|
|
258
|
+
force: flagBool(flags, 'force'),
|
|
259
|
+
runtime: flagString(flags, 'runtime'),
|
|
211
260
|
});
|
|
212
261
|
return;
|
|
213
262
|
}
|
package/dist/init.js
CHANGED
|
@@ -3,6 +3,7 @@ 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.HOST_SOCKET_DIR = exports.INTERNAL_NET = void 0;
|
|
6
7
|
exports.runInit = runInit;
|
|
7
8
|
const child_process_1 = require("child_process");
|
|
8
9
|
const crypto_1 = __importDefault(require("crypto"));
|
|
@@ -13,7 +14,20 @@ const config_1 = require("./config");
|
|
|
13
14
|
const fs_1 = __importDefault(require("fs"));
|
|
14
15
|
const CONTAINER = 'huddle';
|
|
15
16
|
const VOLUME = 'huddle-data';
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The shared, internal network that `huddle init` creates (`--internal`, so it
|
|
19
|
+
* has no route to the internet of its own). Devcontainers attach to it to reach
|
|
20
|
+
* the Huddle proxy — it is the only way out. Exported so `huddle migrate` can
|
|
21
|
+
* point an existing Compose project at the exact same network.
|
|
22
|
+
*/
|
|
23
|
+
exports.INTERNAL_NET = 'devcontainer-net';
|
|
24
|
+
/**
|
|
25
|
+
* Directory on the Docker ENGINE host where the gateway serves each
|
|
26
|
+
* devcontainer's filtered Docker socket (`<HOST_SOCKET_DIR>/<container_name>`).
|
|
27
|
+
* Kept in sync with SOCKET_DIR in gateway/src/docker.ts. Exported so
|
|
28
|
+
* `huddle migrate` can generate the matching bind mount.
|
|
29
|
+
*/
|
|
30
|
+
exports.HOST_SOCKET_DIR = '/tmp/dc-sockets';
|
|
17
31
|
const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
|
|
18
32
|
function run(cmd) {
|
|
19
33
|
(0, child_process_1.execSync)(cmd, { stdio: 'inherit' });
|
|
@@ -73,8 +87,8 @@ async function runInit(opts, images) {
|
|
|
73
87
|
}
|
|
74
88
|
console.log((0, utils_1.dim)(`Volume: ${VOLUME}`));
|
|
75
89
|
runSilent(`${rt} volume inspect ${VOLUME}`) || run(`${rt} volume create ${VOLUME}`);
|
|
76
|
-
console.log((0, utils_1.dim)(`Network: ${INTERNAL_NET}`));
|
|
77
|
-
runSilent(`${rt} network inspect ${INTERNAL_NET}`) || run(`${rt} network create --internal ${INTERNAL_NET}`);
|
|
90
|
+
console.log((0, utils_1.dim)(`Network: ${exports.INTERNAL_NET}`));
|
|
91
|
+
runSilent(`${rt} network inspect ${exports.INTERNAL_NET}`) || run(`${rt} network create --internal ${exports.INTERNAL_NET}`);
|
|
78
92
|
console.log((0, utils_1.dim)(`Removing old container if it exists`));
|
|
79
93
|
runSilent(`${rt} rm -f ${CONTAINER}`);
|
|
80
94
|
console.log((0, utils_1.dim)(`Socket directory: /tmp/dc-sockets`));
|
|
@@ -84,7 +98,7 @@ async function runInit(opts, images) {
|
|
|
84
98
|
// /tmp/dc-sockets on the engine host; mounting a Windows temp dir splits
|
|
85
99
|
// gateway and devcontainers across two filesystems, and Unix sockets are
|
|
86
100
|
// unreliable on such a drvfs/9p mount anyway.
|
|
87
|
-
const hostTmpSockets =
|
|
101
|
+
const hostTmpSockets = exports.HOST_SOCKET_DIR;
|
|
88
102
|
if (runtime.isRemote) {
|
|
89
103
|
if (runtime.name === 'podman') {
|
|
90
104
|
// Podman does NOT create a missing bind source itself (unlike Docker
|
|
@@ -114,10 +128,10 @@ async function runInit(opts, images) {
|
|
|
114
128
|
// `--security-opt label=disable` on every devcontainer so it can reach the
|
|
115
129
|
// SELinux-labeled proxy socket.
|
|
116
130
|
const securityOptFlags = runtime.securityOpts.map((opt) => ` --security-opt ${opt}`).join('');
|
|
117
|
-
// Operator
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
131
|
+
// Operator token for control-plane auth. Reuse the token from the config (so an
|
|
132
|
+
// existing browser session/CLI keeps working across re-inits), otherwise
|
|
133
|
+
// generate one. We pass it to the gateway via env AND store it locally so that
|
|
134
|
+
// subsequent `huddle` commands can authenticate.
|
|
121
135
|
const cfg = (0, config_1.readConfig)();
|
|
122
136
|
const operatorToken = process.env.HUDDLE_OPERATOR_TOKEN?.trim() ||
|
|
123
137
|
(cfg.operatorToken && cfg.operatorToken.trim()) ||
|
|
@@ -139,7 +153,7 @@ async function runInit(opts, images) {
|
|
|
139
153
|
` -e HUDDLE_OPERATOR_TOKEN=${operatorToken}` +
|
|
140
154
|
` -p ${HOST_PORT}:3000` +
|
|
141
155
|
` -v ${VOLUME}:/data` +
|
|
142
|
-
` -v ${runtime.socketPath}:/var/run/docker.sock` +
|
|
156
|
+
` -v "${runtime.socketPath}:/var/run/docker.sock"` +
|
|
143
157
|
` -v "${hostTmpSockets}:/tmp/dc-sockets"` +
|
|
144
158
|
(0, images_1.gatewayEnvFlags)(images) +
|
|
145
159
|
` ${IMAGE}`);
|
|
@@ -147,13 +161,13 @@ async function runInit(opts, images) {
|
|
|
147
161
|
// resolv.conf on Podman with that network's internal aardvark-DNS; the
|
|
148
162
|
// gateway cleans that up itself (see dns-egress.ts / the startup sanitize in
|
|
149
163
|
// index.ts).
|
|
150
|
-
runSilent(`${rt} network connect ${INTERNAL_NET} ${CONTAINER}`);
|
|
164
|
+
runSilent(`${rt} network connect ${exports.INTERNAL_NET} ${CONTAINER}`);
|
|
151
165
|
console.log();
|
|
152
166
|
console.log((0, utils_1.green)(`[OK] Huddle is running at http://localhost:${HOST_PORT}`));
|
|
153
167
|
console.log();
|
|
154
|
-
//
|
|
155
|
-
//
|
|
156
|
-
//
|
|
168
|
+
// Full auto-login link: open it and the portal logs you in automatically with
|
|
169
|
+
// the operator token (the frontend reads ?token=..., logs in and then removes it
|
|
170
|
+
// from the address bar). This way you don't have to paste anything.
|
|
157
171
|
const loginUrl = `http://localhost:${HOST_PORT}/?token=${encodeURIComponent(operatorToken)}`;
|
|
158
172
|
console.log((0, utils_1.bold)('Open the portal (auto-login link):'));
|
|
159
173
|
console.log((0, utils_1.green)(` ${loginUrl}`));
|
package/dist/migrate.js
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.OVERRIDE_FILENAME = exports.DEFAULT_CA_PATH = exports.HUDDLE_NET_KEY = exports.HUDDLE_NETWORK_LABEL = void 0;
|
|
7
|
+
exports.huddleProxyEnv = huddleProxyEnv;
|
|
8
|
+
exports.normalizeLabels = normalizeLabels;
|
|
9
|
+
exports.serviceNetworkKeys = serviceNetworkKeys;
|
|
10
|
+
exports.findMarkedNetworks = findMarkedNetworks;
|
|
11
|
+
exports.buildOverride = buildOverride;
|
|
12
|
+
exports.parseYaml = parseYaml;
|
|
13
|
+
exports.dumpYaml = dumpYaml;
|
|
14
|
+
exports.resolveComposeFile = resolveComposeFile;
|
|
15
|
+
exports.runMigrate = runMigrate;
|
|
16
|
+
const child_process_1 = require("child_process");
|
|
17
|
+
const fs_1 = __importDefault(require("fs"));
|
|
18
|
+
const path_1 = __importDefault(require("path"));
|
|
19
|
+
const utils_1 = require("./utils");
|
|
20
|
+
const runtime_1 = require("./runtime");
|
|
21
|
+
const init_1 = require("./init");
|
|
22
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
// Conventions
|
|
24
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
25
|
+
/**
|
|
26
|
+
* Label a developer puts on ONE network in their existing docker-compose.yml to
|
|
27
|
+
* mark it as "the network whose services should run behind Huddle". Every
|
|
28
|
+
* service attached to that network gets the proxy env, the CA path and (opt-in)
|
|
29
|
+
* the filtered Docker socket injected via the generated override — the
|
|
30
|
+
* developer never hand-writes any of that.
|
|
31
|
+
*/
|
|
32
|
+
exports.HUDDLE_NETWORK_LABEL = 'huddle.network';
|
|
33
|
+
/**
|
|
34
|
+
* Network key added by the override that points at Huddle's shared internal
|
|
35
|
+
* network. Marked services are additionally attached to it so they reach the
|
|
36
|
+
* Huddle proxy; their own (internal) network is left untouched. Renamed if the
|
|
37
|
+
* project already uses this key.
|
|
38
|
+
*/
|
|
39
|
+
exports.HUDDLE_NET_KEY = 'huddle';
|
|
40
|
+
/** Default absolute path the CA is fetched to (see the printed postCreateCommand). */
|
|
41
|
+
exports.DEFAULT_CA_PATH = '/home/vscode/.huddle-ca.crt';
|
|
42
|
+
/** Default filename for the generated Compose override. */
|
|
43
|
+
exports.OVERRIDE_FILENAME = 'docker-compose.huddle.yml';
|
|
44
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
45
|
+
// Egress wiring that gets injected (mirrors the working .devcontainer example,
|
|
46
|
+
// which issue-66-reply.md calls the source of truth). `huddle` stays in NO_PROXY
|
|
47
|
+
// so the direct CA fetch to huddle:3000 does not loop through the proxy on :80.
|
|
48
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
49
|
+
function huddleProxyEnv(caPath, dockerSocket) {
|
|
50
|
+
const env = {
|
|
51
|
+
HTTP_PROXY: 'http://huddle:80',
|
|
52
|
+
HTTPS_PROXY: 'http://huddle:80',
|
|
53
|
+
http_proxy: 'http://huddle:80',
|
|
54
|
+
https_proxy: 'http://huddle:80',
|
|
55
|
+
NO_PROXY: 'localhost,127.0.0.1,::1,[::1],huddle',
|
|
56
|
+
no_proxy: 'localhost,127.0.0.1,::1,[::1],huddle',
|
|
57
|
+
NODE_EXTRA_CA_CERTS: caPath,
|
|
58
|
+
};
|
|
59
|
+
if (dockerSocket) {
|
|
60
|
+
// The container talks to Huddle's filtered socket, never the raw engine.
|
|
61
|
+
env.DOCKER_HOST = 'unix:///var/run/huddle/docker.sock';
|
|
62
|
+
}
|
|
63
|
+
return env;
|
|
64
|
+
}
|
|
65
|
+
/** YAML/Compose truthiness: accepts booleans and the usual string spellings. */
|
|
66
|
+
function isTruthy(value) {
|
|
67
|
+
if (value === true)
|
|
68
|
+
return true;
|
|
69
|
+
if (typeof value === 'string')
|
|
70
|
+
return ['true', '1', 'yes', 'on'].includes(value.trim().toLowerCase());
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
/** Reads a `labels:` block (map form or `- key=value` list form) into a plain map. */
|
|
74
|
+
function normalizeLabels(labels) {
|
|
75
|
+
const out = {};
|
|
76
|
+
if (!labels)
|
|
77
|
+
return out;
|
|
78
|
+
if (Array.isArray(labels)) {
|
|
79
|
+
for (const entry of labels) {
|
|
80
|
+
if (typeof entry !== 'string')
|
|
81
|
+
continue;
|
|
82
|
+
const eq = entry.indexOf('=');
|
|
83
|
+
if (eq >= 0)
|
|
84
|
+
out[entry.slice(0, eq).trim()] = entry.slice(eq + 1).trim();
|
|
85
|
+
else
|
|
86
|
+
out[entry.trim()] = '';
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
for (const [k, v] of Object.entries(labels))
|
|
91
|
+
out[k] = v == null ? '' : String(v);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
/** Network keys of a service (map form or list form) as a plain array. */
|
|
96
|
+
function serviceNetworkKeys(service) {
|
|
97
|
+
const nets = service.networks;
|
|
98
|
+
if (!nets)
|
|
99
|
+
return [];
|
|
100
|
+
if (Array.isArray(nets))
|
|
101
|
+
return nets.filter((n) => typeof n === 'string');
|
|
102
|
+
return Object.keys(nets);
|
|
103
|
+
}
|
|
104
|
+
/** All network keys carrying the `huddle.network` label. */
|
|
105
|
+
function findMarkedNetworks(compose) {
|
|
106
|
+
const networks = compose.networks ?? {};
|
|
107
|
+
return Object.entries(networks)
|
|
108
|
+
.filter(([, def]) => def && isTruthy(normalizeLabels(def.labels)[exports.HUDDLE_NETWORK_LABEL]))
|
|
109
|
+
.map(([key]) => key);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Core generator: given a parsed compose object, produce the Compose OVERRIDE
|
|
113
|
+
* that wires every service on the marked network behind Huddle. Purely additive
|
|
114
|
+
* — it never rewrites the user's own network (which would clash with a base
|
|
115
|
+
* `internal: true` when Compose merges the two files), it only ADDS a second
|
|
116
|
+
* `huddle` network (external → Huddle's internal net) plus env/CA/socket.
|
|
117
|
+
*
|
|
118
|
+
* Throws on hard configuration errors (no/ambiguous marked network); collects
|
|
119
|
+
* softer problems in `warnings`.
|
|
120
|
+
*/
|
|
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) {
|
|
124
|
+
const marked = findMarkedNetworks(compose);
|
|
125
|
+
if (marked.length === 0) {
|
|
126
|
+
throw new Error(`No network marked with \`${exports.HUDDLE_NETWORK_LABEL}: "true"\` was found. ` +
|
|
127
|
+
'Add that label to the (internal) network your services use.');
|
|
128
|
+
}
|
|
129
|
+
if (marked.length > 1) {
|
|
130
|
+
throw new Error(`Multiple networks marked with \`${exports.HUDDLE_NETWORK_LABEL}\`: ${marked.join(', ')}. Mark exactly one.`);
|
|
131
|
+
}
|
|
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
|
+
}
|
|
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);
|
|
191
|
+
// Guardrail: the marked network must be internal, otherwise it already has a
|
|
192
|
+
// route to the internet and would bypass the firewall/proxy.
|
|
193
|
+
const markedDef = (compose.networks?.[markedNetwork] ?? {});
|
|
194
|
+
if (!isTruthy(markedDef.internal)) {
|
|
195
|
+
blockers.push(`Network "${markedNetwork}" is not marked \`internal: true\`. It must be internal, ` +
|
|
196
|
+
'otherwise services can reach the internet directly and bypass Huddle.');
|
|
197
|
+
}
|
|
198
|
+
const services = Object.entries(compose.services ?? {})
|
|
199
|
+
.filter(([, svc]) => serviceNetworkKeys(svc).includes(markedNetwork))
|
|
200
|
+
.map(([key]) => key);
|
|
201
|
+
if (services.length === 0) {
|
|
202
|
+
warnings.push(`No service is attached to the marked network "${markedNetwork}"; the override wires nothing.`);
|
|
203
|
+
}
|
|
204
|
+
const ctx = { markedNetwork, huddleNetKey, caPath, socketDir, dockerSocket: !!opts.dockerSocket };
|
|
205
|
+
const overrideServices = {};
|
|
206
|
+
for (const name of services) {
|
|
207
|
+
const svc = (compose.services?.[name] ?? {});
|
|
208
|
+
overrideServices[name] = buildInjectedService(svc, name, compose, ctx, warnings, blockers);
|
|
209
|
+
}
|
|
210
|
+
const override = {
|
|
211
|
+
services: overrideServices,
|
|
212
|
+
networks: {
|
|
213
|
+
// external: true → reuse the network `huddle init` already created; do not
|
|
214
|
+
// create or take ownership of it here.
|
|
215
|
+
[huddleNetKey]: { external: true, name: internalNet },
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
return { markedNetwork, services, override, warnings, blockers };
|
|
219
|
+
}
|
|
220
|
+
function tokenize(input) {
|
|
221
|
+
const out = [];
|
|
222
|
+
for (const rawLine of input.split(/\r?\n/)) {
|
|
223
|
+
const stripped = stripComment(rawLine);
|
|
224
|
+
if (stripped.trim() === '')
|
|
225
|
+
continue;
|
|
226
|
+
const indent = stripped.length - stripped.trimStart().length;
|
|
227
|
+
out.push({ indent, text: stripped.trim() });
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
/** Removes a `# comment`, but never one that sits inside quotes or a `://` URL. */
|
|
232
|
+
function stripComment(line) {
|
|
233
|
+
let inSingle = false;
|
|
234
|
+
let inDouble = false;
|
|
235
|
+
for (let i = 0; i < line.length; i++) {
|
|
236
|
+
const c = line[i];
|
|
237
|
+
if (c === "'" && !inDouble)
|
|
238
|
+
inSingle = !inSingle;
|
|
239
|
+
else if (c === '"' && !inSingle)
|
|
240
|
+
inDouble = !inDouble;
|
|
241
|
+
else if (c === '#' && !inSingle && !inDouble && (i === 0 || /\s/.test(line[i - 1]))) {
|
|
242
|
+
return line.slice(0, i);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return line;
|
|
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;
|
|
251
|
+
function unsupportedYaml(feature) {
|
|
252
|
+
return new Error(`the compose file uses ${feature}, which \`huddle migrate\`'s built-in YAML reader does ` +
|
|
253
|
+
'not support and would mis-parse (risking a dropped, un-filtered service). Inline or ' +
|
|
254
|
+
'quote it, or flatten the file first with `docker compose config`, then re-run `huddle migrate`.');
|
|
255
|
+
}
|
|
256
|
+
// A YAML block-scalar header: `|` or `>` followed by an optional indentation
|
|
257
|
+
// indicator (1-9) and/or chomping indicator (+/-), each at most once, in either
|
|
258
|
+
// order. Anchored so plain scalars that merely start with `>`/`|` (e.g. `>=1.0`)
|
|
259
|
+
// do not match.
|
|
260
|
+
const BLOCK_SCALAR_HEADER = /^[|>]([1-9][+-]?|[+-][1-9]?)?$/;
|
|
261
|
+
// The value carried by a tokenized line: a mapping value (after `key:`), a
|
|
262
|
+
// sequence-item value (after `- `), or the bare line.
|
|
263
|
+
function lineValue(text) {
|
|
264
|
+
const colon = findKeyColon(text);
|
|
265
|
+
if (colon >= 0)
|
|
266
|
+
return text.slice(colon + 1).trim();
|
|
267
|
+
if (isSeqItem(text))
|
|
268
|
+
return text.replace(/^-\s*/, '').trim();
|
|
269
|
+
return text;
|
|
270
|
+
}
|
|
271
|
+
// Fail-closed on YAML features the indentation reader below cannot represent
|
|
272
|
+
// (finding #9). Block scalars (`|`/`>`), anchors/aliases (`&`/`*`) and merge keys
|
|
273
|
+
// (`<<`) are silently mis-parsed — a block scalar's indented body is read as real
|
|
274
|
+
// structure, which can swallow the next service and drop it from the generated
|
|
275
|
+
// override (leaving it with an unfiltered route out). Detect them up front and
|
|
276
|
+
// refuse with a clear, actionable error instead of guessing.
|
|
277
|
+
function rejectUnsupportedYaml(lines) {
|
|
278
|
+
for (const { text } of lines) {
|
|
279
|
+
if (/^<<\s*:/.test(text))
|
|
280
|
+
throw unsupportedYaml('a merge key (`<<`)');
|
|
281
|
+
const value = lineValue(text);
|
|
282
|
+
if (BLOCK_SCALAR_HEADER.test(value))
|
|
283
|
+
throw unsupportedYaml('a block scalar (`|` or `>`)');
|
|
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))
|
|
290
|
+
throw unsupportedYaml('a YAML anchor (`&`)');
|
|
291
|
+
if (/(^|[[{,:]\s*)\*[A-Za-z0-9_]/.test(value))
|
|
292
|
+
throw unsupportedYaml('a YAML alias (`*`)');
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function parseYaml(input) {
|
|
296
|
+
const lines = tokenize(input);
|
|
297
|
+
rejectUnsupportedYaml(lines);
|
|
298
|
+
let pos = 0;
|
|
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
|
+
}
|
|
305
|
+
if (pos >= lines.length || lines[pos].indent < indent)
|
|
306
|
+
return null;
|
|
307
|
+
return isSeqItem(lines[pos].text) ? parseSequence(indent, depth) : parseMapping(indent, depth);
|
|
308
|
+
}
|
|
309
|
+
function parseMapping(indent, depth) {
|
|
310
|
+
const map = {};
|
|
311
|
+
while (pos < lines.length && lines[pos].indent === indent && !isSeqItem(lines[pos].text)) {
|
|
312
|
+
const { text } = lines[pos];
|
|
313
|
+
const colon = findKeyColon(text);
|
|
314
|
+
if (colon < 0) {
|
|
315
|
+
// Not a mapping line where we expected one — stop and let the caller cope.
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
const key = unquote(text.slice(0, colon).trim());
|
|
319
|
+
const rest = text.slice(colon + 1).trim();
|
|
320
|
+
pos++;
|
|
321
|
+
if (rest !== '') {
|
|
322
|
+
map[key] = parseScalar(rest);
|
|
323
|
+
}
|
|
324
|
+
else if (pos < lines.length && lines[pos].indent > indent) {
|
|
325
|
+
map[key] = parseNode(lines[pos].indent, depth + 1);
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
map[key] = null;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return map;
|
|
332
|
+
}
|
|
333
|
+
function parseSequence(indent, depth) {
|
|
334
|
+
const arr = [];
|
|
335
|
+
while (pos < lines.length && lines[pos].indent === indent && isSeqItem(lines[pos].text)) {
|
|
336
|
+
const afterDash = lines[pos].text.replace(/^-\s*/, '');
|
|
337
|
+
if (afterDash === '') {
|
|
338
|
+
pos++;
|
|
339
|
+
arr.push(pos < lines.length && lines[pos].indent > indent ? parseNode(lines[pos].indent, depth + 1) : null);
|
|
340
|
+
}
|
|
341
|
+
else if (findKeyColon(afterDash) >= 0) {
|
|
342
|
+
// Inline map item: "- key: value". Re-interpret the remainder as a
|
|
343
|
+
// mapping that starts at a virtual indent past the dash.
|
|
344
|
+
const virtualIndent = indent + (lines[pos].text.length - afterDash.length);
|
|
345
|
+
lines[pos] = { indent: virtualIndent, text: afterDash };
|
|
346
|
+
arr.push(parseMapping(virtualIndent, depth + 1));
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
arr.push(parseScalar(afterDash));
|
|
350
|
+
pos++;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return arr;
|
|
354
|
+
}
|
|
355
|
+
const root = parseNode(lines.length ? lines[0].indent : 0, 0);
|
|
356
|
+
return (root && typeof root === 'object' ? root : {});
|
|
357
|
+
}
|
|
358
|
+
function isSeqItem(text) {
|
|
359
|
+
return text === '-' || text.startsWith('- ');
|
|
360
|
+
}
|
|
361
|
+
/** Index of the `key:` colon (the first colon followed by space or end-of-line). */
|
|
362
|
+
function findKeyColon(text) {
|
|
363
|
+
let inSingle = false;
|
|
364
|
+
let inDouble = false;
|
|
365
|
+
for (let i = 0; i < text.length; i++) {
|
|
366
|
+
const c = text[i];
|
|
367
|
+
if (c === "'" && !inDouble)
|
|
368
|
+
inSingle = !inSingle;
|
|
369
|
+
else if (c === '"' && !inSingle)
|
|
370
|
+
inDouble = !inDouble;
|
|
371
|
+
else if (c === ':' && !inSingle && !inDouble && (i + 1 === text.length || text[i + 1] === ' ')) {
|
|
372
|
+
return i;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return -1;
|
|
376
|
+
}
|
|
377
|
+
function parseScalar(raw) {
|
|
378
|
+
const value = raw.trim();
|
|
379
|
+
if (value.startsWith('[') && value.endsWith(']')) {
|
|
380
|
+
return splitFlow(value.slice(1, -1)).map((v) => parseScalar(v));
|
|
381
|
+
}
|
|
382
|
+
if (value.startsWith('{') && value.endsWith('}')) {
|
|
383
|
+
const map = {};
|
|
384
|
+
for (const part of splitFlow(value.slice(1, -1))) {
|
|
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.
|
|
390
|
+
if (colon < 0)
|
|
391
|
+
throw unsupportedYaml('a compact flow-mapping entry (`{key:value}` without a space after the colon)');
|
|
392
|
+
map[unquote(part.slice(0, colon).trim())] = parseScalar(part.slice(colon + 1).trim());
|
|
393
|
+
}
|
|
394
|
+
return map;
|
|
395
|
+
}
|
|
396
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
397
|
+
return unquote(value);
|
|
398
|
+
}
|
|
399
|
+
if (value === 'true')
|
|
400
|
+
return true;
|
|
401
|
+
if (value === 'false')
|
|
402
|
+
return false;
|
|
403
|
+
if (value === 'null' || value === '~' || value === '')
|
|
404
|
+
return null;
|
|
405
|
+
if (/^-?\d+(\.\d+)?$/.test(value))
|
|
406
|
+
return Number(value);
|
|
407
|
+
return value;
|
|
408
|
+
}
|
|
409
|
+
/** Splits a flow collection body on top-level commas (ignores commas in quotes/brackets). */
|
|
410
|
+
function splitFlow(body) {
|
|
411
|
+
const parts = [];
|
|
412
|
+
let depth = 0;
|
|
413
|
+
let inSingle = false;
|
|
414
|
+
let inDouble = false;
|
|
415
|
+
let current = '';
|
|
416
|
+
for (const c of body) {
|
|
417
|
+
if (c === "'" && !inDouble)
|
|
418
|
+
inSingle = !inSingle;
|
|
419
|
+
else if (c === '"' && !inSingle)
|
|
420
|
+
inDouble = !inDouble;
|
|
421
|
+
if (!inSingle && !inDouble) {
|
|
422
|
+
if (c === '[' || c === '{')
|
|
423
|
+
depth++;
|
|
424
|
+
else if (c === ']' || c === '}')
|
|
425
|
+
depth--;
|
|
426
|
+
else if (c === ',' && depth === 0) {
|
|
427
|
+
if (current.trim() !== '')
|
|
428
|
+
parts.push(current.trim());
|
|
429
|
+
current = '';
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
current += c;
|
|
434
|
+
}
|
|
435
|
+
if (current.trim() !== '')
|
|
436
|
+
parts.push(current.trim());
|
|
437
|
+
return parts;
|
|
438
|
+
}
|
|
439
|
+
function unquote(value) {
|
|
440
|
+
if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
|
|
441
|
+
return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
442
|
+
}
|
|
443
|
+
if (value.startsWith("'") && value.endsWith("'") && value.length >= 2) {
|
|
444
|
+
return value.slice(1, -1).replace(/''/g, "'");
|
|
445
|
+
}
|
|
446
|
+
return value;
|
|
447
|
+
}
|
|
448
|
+
/** Emits an object as YAML using the subset the reader understands. */
|
|
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
|
+
}
|
|
457
|
+
const pad = ' '.repeat(indent);
|
|
458
|
+
if (obj === null || obj === undefined)
|
|
459
|
+
return '';
|
|
460
|
+
if (Array.isArray(obj)) {
|
|
461
|
+
if (obj.length === 0)
|
|
462
|
+
return `${pad}[]\n`;
|
|
463
|
+
return obj.map((item) => `${pad}- ${dumpInlineOrBlock(item, indent)}`).join('');
|
|
464
|
+
}
|
|
465
|
+
if (typeof obj === 'object') {
|
|
466
|
+
const entries = Object.entries(obj);
|
|
467
|
+
if (entries.length === 0)
|
|
468
|
+
return `${pad}{}\n`;
|
|
469
|
+
let out = '';
|
|
470
|
+
for (const [key, value] of entries) {
|
|
471
|
+
// Keys can come straight from an untrusted compose file (service/network
|
|
472
|
+
// names). Emit them through the same quote/escape path as scalar values so
|
|
473
|
+
// a crafted key (`a: b`, `evil #comment`, or one containing a newline)
|
|
474
|
+
// cannot break out of its line and inject sibling compose directives.
|
|
475
|
+
const k = formatScalar(key);
|
|
476
|
+
if (value === null || value === undefined) {
|
|
477
|
+
out += `${pad}${k}:\n`;
|
|
478
|
+
}
|
|
479
|
+
else if (typeof value === 'object') {
|
|
480
|
+
const isEmpty = Array.isArray(value) ? value.length === 0 : Object.keys(value).length === 0;
|
|
481
|
+
if (isEmpty) {
|
|
482
|
+
out += `${pad}${k}: ${Array.isArray(value) ? '[]' : '{}'}\n`;
|
|
483
|
+
}
|
|
484
|
+
else {
|
|
485
|
+
out += `${pad}${k}:\n${dumpYaml(value, indent + 1)}`;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
else {
|
|
489
|
+
out += `${pad}${k}: ${formatScalar(value)}\n`;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return out;
|
|
493
|
+
}
|
|
494
|
+
return `${pad}${formatScalar(obj)}\n`;
|
|
495
|
+
}
|
|
496
|
+
function dumpInlineOrBlock(item, indent) {
|
|
497
|
+
if (item !== null && typeof item === 'object') {
|
|
498
|
+
// Render the nested structure, then splice its first line onto the dash.
|
|
499
|
+
const block = dumpYaml(item, indent + 1);
|
|
500
|
+
return block.trimStart();
|
|
501
|
+
}
|
|
502
|
+
return `${formatScalar(item)}\n`;
|
|
503
|
+
}
|
|
504
|
+
function formatScalar(value) {
|
|
505
|
+
if (typeof value === 'boolean' || typeof value === 'number')
|
|
506
|
+
return String(value);
|
|
507
|
+
const str = String(value);
|
|
508
|
+
if (needsQuote(str)) {
|
|
509
|
+
// Escape backslash first, then quotes, then control chars — otherwise a raw
|
|
510
|
+
// newline/CR/tab would terminate the current line and let attacker-supplied
|
|
511
|
+
// text be reparsed as fresh YAML structure.
|
|
512
|
+
const escaped = str
|
|
513
|
+
.replace(/\\/g, '\\\\')
|
|
514
|
+
.replace(/"/g, '\\"')
|
|
515
|
+
.replace(/\n/g, '\\n')
|
|
516
|
+
.replace(/\r/g, '\\r')
|
|
517
|
+
.replace(/\t/g, '\\t');
|
|
518
|
+
return `"${escaped}"`;
|
|
519
|
+
}
|
|
520
|
+
return str;
|
|
521
|
+
}
|
|
522
|
+
function needsQuote(str) {
|
|
523
|
+
if (str === '')
|
|
524
|
+
return true;
|
|
525
|
+
if (/^(true|false|null|~|yes|no|on|off)$/i.test(str))
|
|
526
|
+
return true;
|
|
527
|
+
if (/^-?\d+(\.\d+)?$/.test(str))
|
|
528
|
+
return true;
|
|
529
|
+
if (/[:#[\]{}&*!|>%@`,"']/.test(str))
|
|
530
|
+
return true;
|
|
531
|
+
if (/[\n\r\t]/.test(str))
|
|
532
|
+
return true;
|
|
533
|
+
if (/^\s|\s$/.test(str))
|
|
534
|
+
return true;
|
|
535
|
+
return false;
|
|
536
|
+
}
|
|
537
|
+
/** Resolves the docker-compose file for a project directory (or an explicit file). */
|
|
538
|
+
function resolveComposeFile(target) {
|
|
539
|
+
const resolved = path_1.default.resolve(target ?? process.cwd());
|
|
540
|
+
let stat;
|
|
541
|
+
try {
|
|
542
|
+
stat = fs_1.default.statSync(resolved);
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
throw new Error(`Path does not exist: ${resolved}`);
|
|
546
|
+
}
|
|
547
|
+
if (stat.isFile())
|
|
548
|
+
return resolved;
|
|
549
|
+
for (const name of ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml']) {
|
|
550
|
+
const candidate = path_1.default.join(resolved, name);
|
|
551
|
+
if (fs_1.default.existsSync(candidate))
|
|
552
|
+
return candidate;
|
|
553
|
+
}
|
|
554
|
+
throw new Error(`No docker-compose file found in ${resolved}`);
|
|
555
|
+
}
|
|
556
|
+
/** Best-effort check that Huddle's internal network already exists. */
|
|
557
|
+
function huddleNetworkExists(internalNet, runtime) {
|
|
558
|
+
try {
|
|
559
|
+
const rt = (0, runtime_1.resolveRuntime)(runtime);
|
|
560
|
+
// execFileSync (arg array, no shell) instead of execSync: no shell is
|
|
561
|
+
// involved, so there is no command-injection surface via the runtime/network name.
|
|
562
|
+
(0, child_process_1.execFileSync)(rt.name, ['network', 'inspect', internalNet], { stdio: 'ignore' });
|
|
563
|
+
return true;
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
return undefined; // runtime unavailable or network missing — don't block.
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async function runMigrate(opts) {
|
|
570
|
+
const composeFile = resolveComposeFile(opts.path);
|
|
571
|
+
const projectDir = path_1.default.dirname(composeFile);
|
|
572
|
+
const caPath = opts.caPath ?? exports.DEFAULT_CA_PATH;
|
|
573
|
+
console.log(`${(0, utils_1.bold)('Migrating')} ${(0, utils_1.cyan)(composeFile)} to run behind Huddle...\n`);
|
|
574
|
+
const raw = fs_1.default.readFileSync(composeFile, 'utf8');
|
|
575
|
+
let compose;
|
|
576
|
+
try {
|
|
577
|
+
compose = parseYaml(raw);
|
|
578
|
+
}
|
|
579
|
+
catch (err) {
|
|
580
|
+
throw new Error(`Could not parse ${composeFile}: ${err instanceof Error ? err.message : String(err)}`);
|
|
581
|
+
}
|
|
582
|
+
const result = buildOverride(compose, { caPath, dockerSocket: opts.dockerSocket });
|
|
583
|
+
console.log(`Marked network: ${(0, utils_1.bold)(result.markedNetwork)}`);
|
|
584
|
+
console.log(`Wired services: ${result.services.length ? result.services.map(utils_1.bold).join(', ') : (0, utils_1.dim)('(none)')}`);
|
|
585
|
+
for (const w of result.warnings)
|
|
586
|
+
console.log((0, utils_1.yellow)(`[!] ${w}`));
|
|
587
|
+
for (const b of result.blockers)
|
|
588
|
+
console.log((0, utils_1.red)(`[x] ${b}`));
|
|
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
|
+
}
|
|
598
|
+
const overrideText = '# Generated by `huddle migrate` — do NOT edit by hand; re-run the command instead.\n' +
|
|
599
|
+
'# Merge this on top of your docker-compose.yml so the marked services reach the\n' +
|
|
600
|
+
'# internet only through the Huddle proxy. Your own compose file stays untouched.\n' +
|
|
601
|
+
dumpYaml(result.override);
|
|
602
|
+
const outPath = opts.output ? path_1.default.resolve(opts.output) : path_1.default.join(projectDir, exports.OVERRIDE_FILENAME);
|
|
603
|
+
if (fs_1.default.existsSync(outPath) && !opts.force) {
|
|
604
|
+
throw new Error(`${outPath} already exists. Re-run with --force to overwrite.`);
|
|
605
|
+
}
|
|
606
|
+
fs_1.default.writeFileSync(outPath, overrideText);
|
|
607
|
+
console.log((0, utils_1.green)(`[OK] Wrote override: ${outPath}`));
|
|
608
|
+
console.log();
|
|
609
|
+
// Best-effort readiness hint.
|
|
610
|
+
if (huddleNetworkExists(init_1.INTERNAL_NET, opts.runtime) === undefined) {
|
|
611
|
+
console.log((0, utils_1.yellow)(`[!] Could not confirm the "${init_1.INTERNAL_NET}" network exists. Run \`huddle init\` first.`));
|
|
612
|
+
console.log();
|
|
613
|
+
}
|
|
614
|
+
printNextSteps(composeFile, outPath, caPath, !!opts.dockerSocket);
|
|
615
|
+
}
|
|
616
|
+
function printNextSteps(composeFile, outPath, caPath, dockerSocket) {
|
|
617
|
+
const composeBase = path_1.default.basename(composeFile);
|
|
618
|
+
const overrideBase = path_1.default.basename(outPath);
|
|
619
|
+
console.log((0, utils_1.bold)('Next steps (this command only GENERATED the override — it did not start anything):'));
|
|
620
|
+
console.log();
|
|
621
|
+
console.log(' 1. Make sure Huddle is running:');
|
|
622
|
+
console.log((0, utils_1.cyan)(' huddle init'));
|
|
623
|
+
console.log();
|
|
624
|
+
console.log(' 2. Fetch the Huddle CA inside the container. Add to your devcontainer.json:');
|
|
625
|
+
console.log((0, utils_1.cyan)(` "postCreateCommand": "curl -fsS http://huddle:3000/api/tls/ca.crt -o ${caPath} || echo 'CA not fetched (HTTPS tunnelled, no MITM)'"`));
|
|
626
|
+
console.log((0, utils_1.dim)(` (Adjust ${caPath} to your remoteUser's home if it differs; pass --ca-path to change it.)`));
|
|
627
|
+
console.log();
|
|
628
|
+
console.log(' 3. Reference the override so the IDE merges it. In devcontainer.json:');
|
|
629
|
+
console.log((0, utils_1.cyan)(` "dockerComposeFile": ["${composeBase}", "${overrideBase}"]`));
|
|
630
|
+
console.log((0, utils_1.dim)(' Or start it yourself:'));
|
|
631
|
+
console.log((0, utils_1.cyan)(` docker compose -f ${composeBase} -f ${overrideBase} up -d`));
|
|
632
|
+
console.log();
|
|
633
|
+
if (dockerSocket) {
|
|
634
|
+
console.log((0, utils_1.yellow)(' Note (--docker-socket): the socket mount is GENERATED but NOT yet served.'));
|
|
635
|
+
console.log((0, utils_1.dim)(' Huddle does not yet pre-provision the per-container filtered socket for IDE-started\n' +
|
|
636
|
+
' containers (issue #66 follow-up). Until it does, the mount source will not exist and\n' +
|
|
637
|
+
' DOCKER_HOST will point at a missing socket. Only enable this once that lands.'));
|
|
638
|
+
console.log();
|
|
639
|
+
}
|
|
640
|
+
console.log((0, utils_1.dim)('See docs/migrate-devcontainers.md for the full guide and the marked-network convention.'));
|
|
641
|
+
}
|
package/dist/runtime.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseDockerContextSocket = parseDockerContextSocket;
|
|
4
|
+
exports.isRancherDesktopSocket = isRancherDesktopSocket;
|
|
3
5
|
exports.parseRuntimeName = parseRuntimeName;
|
|
4
6
|
exports.resolveRuntime = resolveRuntime;
|
|
5
7
|
const child_process_1 = require("child_process");
|
|
@@ -16,12 +18,12 @@ function isAvailable(runtime) {
|
|
|
16
18
|
return commandOutput(`${runtime} info`) !== undefined;
|
|
17
19
|
}
|
|
18
20
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* symlink/shim
|
|
22
|
-
* `docker --version`. Podman's `info
|
|
23
|
-
* Host.ServiceIsRemote; Docker's info
|
|
24
|
-
*
|
|
21
|
+
* Determines the REAL engine behind a command, or undefined if the engine is
|
|
22
|
+
* not reachable. Do not trust the command name: `docker` is often a
|
|
23
|
+
* symlink/shim to Podman (podman-docker), and Podman then even emulates
|
|
24
|
+
* `docker --version`. Podman's `info`, on the other hand, has the field
|
|
25
|
+
* Host.ServiceIsRemote; Docker's info schema does not. That is a reliable
|
|
26
|
+
* distinction that also works through the shim.
|
|
25
27
|
*/
|
|
26
28
|
function detectEngine(command) {
|
|
27
29
|
if (commandOutput(`${command} info --format "{{.Host.ServiceIsRemote}}"`) !== undefined) {
|
|
@@ -42,10 +44,60 @@ function podmanSocketPath() {
|
|
|
42
44
|
function dockerSocketPath() {
|
|
43
45
|
return process.platform === 'win32' ? '//var/run/docker.sock' : '/var/run/docker.sock';
|
|
44
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Extracts the unix socket path from the JSON of `docker context inspect`. The
|
|
49
|
+
* active context determines which engine the `docker` command talks to; Rancher
|
|
50
|
+
* Desktop (dockerd/moby mode) sets a `rancher-desktop` context whose
|
|
51
|
+
* `Endpoints.docker.Host` points to `unix:///<home>/.rd/docker.sock` instead of
|
|
52
|
+
* the default `/var/run/docker.sock`.
|
|
53
|
+
*
|
|
54
|
+
* Pure function so we can test the parsing in isolation. Returns `null` for
|
|
55
|
+
* non-parsable input or a non-unix endpoint (npipe:// on Windows,
|
|
56
|
+
* tcp:// / ssh:// remote), because those cannot be bind-mounted as a file path.
|
|
57
|
+
*/
|
|
58
|
+
function parseDockerContextSocket(json) {
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(json);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
// `docker context inspect` returns an array; one context is one element.
|
|
67
|
+
const entry = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
68
|
+
const host = entry
|
|
69
|
+
?.Endpoints?.docker?.Host;
|
|
70
|
+
if (typeof host !== 'string' || !host.startsWith('unix://'))
|
|
71
|
+
return null;
|
|
72
|
+
const path = host.slice('unix://'.length);
|
|
73
|
+
if (!path.startsWith('/'))
|
|
74
|
+
return null;
|
|
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
|
+
// inspect` is attacker-influenceable (whoever can create/activate a docker
|
|
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))
|
|
83
|
+
return null;
|
|
84
|
+
return path;
|
|
85
|
+
}
|
|
86
|
+
/** Recognizes the Rancher Desktop socket path (dockerd/moby mode): `~/.rd/docker.sock`. */
|
|
87
|
+
function isRancherDesktopSocket(socketPath) {
|
|
88
|
+
return typeof socketPath === 'string' && /(^|\/)\.rd\/docker\.sock$/.test(socketPath);
|
|
89
|
+
}
|
|
90
|
+
/** Socket path of the active docker context, or undefined if it cannot be queried. */
|
|
91
|
+
function dockerContextSocket() {
|
|
92
|
+
const json = commandOutput('docker context inspect');
|
|
93
|
+
if (!json)
|
|
94
|
+
return undefined;
|
|
95
|
+
return parseDockerContextSocket(json) ?? undefined;
|
|
96
|
+
}
|
|
45
97
|
function podmanIsRemote() {
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
98
|
+
// On macOS/Windows Podman always runs in a `podman machine` VM; on Linux too
|
|
99
|
+
// the client can point at a remote socket. `ServiceIsRemote` is the
|
|
100
|
+
// authoritative source.
|
|
49
101
|
return commandOutput(`podman info --format "{{.Host.ServiceIsRemote}}"`) === 'true';
|
|
50
102
|
}
|
|
51
103
|
function buildRuntime(name) {
|
|
@@ -58,12 +110,21 @@ function buildRuntime(name) {
|
|
|
58
110
|
securityOpts: ['label=disable'],
|
|
59
111
|
};
|
|
60
112
|
}
|
|
113
|
+
// Rancher Desktop (dockerd/moby mode) looks like an ordinary Docker engine,
|
|
114
|
+
// but the socket is not at /var/run/docker.sock: the active docker context
|
|
115
|
+
// points to `~/.rd/docker.sock`. Follow that context so we bind-mount the
|
|
116
|
+
// correct socket; otherwise we fall back to the default location (real native
|
|
117
|
+
// Docker, Docker Desktop). Rancher Desktop runs the engine in a VM (Lima/WSL)
|
|
118
|
+
// on EVERY platform, so it is always 'remote'.
|
|
119
|
+
const contextSocket = dockerContextSocket();
|
|
120
|
+
const isRancher = isRancherDesktopSocket(contextSocket);
|
|
61
121
|
return {
|
|
62
122
|
name,
|
|
63
|
-
socketPath: dockerSocketPath(),
|
|
123
|
+
socketPath: isRancher ? contextSocket : dockerSocketPath(),
|
|
64
124
|
defaultNetwork: 'bridge',
|
|
65
|
-
// Docker Desktop (macOS/Windows)
|
|
66
|
-
|
|
125
|
+
// Docker Desktop (macOS/Windows) and Rancher Desktop run in a VM; native
|
|
126
|
+
// Docker on Linux does not.
|
|
127
|
+
isRemote: isRancher || process.platform !== 'linux',
|
|
67
128
|
securityOpts: [],
|
|
68
129
|
};
|
|
69
130
|
}
|
|
@@ -87,9 +148,9 @@ function resolveRuntime(explicit) {
|
|
|
87
148
|
}
|
|
88
149
|
return buildRuntime(name);
|
|
89
150
|
}
|
|
90
|
-
// Auto-
|
|
91
|
-
//
|
|
92
|
-
// is,
|
|
151
|
+
// Auto-detection: first look behind the `docker` command (which may be a
|
|
152
|
+
// Podman shim), then at `podman`. This way a real Docker engine wins if there
|
|
153
|
+
// is one, but we also recognize Podman when it poses as `docker`.
|
|
93
154
|
const detected = detectEngine('docker') ?? detectEngine('podman');
|
|
94
155
|
if (detected)
|
|
95
156
|
return buildRuntime(detected);
|