@infosupport/huddle-cli 0.0.0-experiment-76.23.1 → 0.0.0-experiment-66.27.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/firewall.js +71 -0
- package/dist/index.js +78 -10
- package/dist/init.js +19 -5
- package/dist/migrate.js +542 -0
- package/dist/runtime.js +63 -3
- package/package.json +1 -1
package/dist/firewall.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
exports.runFirewallList = runFirewallList;
|
|
7
|
+
exports.runFirewallAdd = runFirewallAdd;
|
|
8
|
+
exports.runFirewallExport = runFirewallExport;
|
|
9
|
+
exports.runFirewallImport = runFirewallImport;
|
|
10
|
+
const fs_1 = __importDefault(require("fs"));
|
|
4
11
|
const api_1 = require("./api");
|
|
5
12
|
const utils_1 = require("./utils");
|
|
6
13
|
async function runFirewallList(opts) {
|
|
@@ -52,6 +59,31 @@ async function reviewRule(rule, idx, total) {
|
|
|
52
59
|
async function resolveRule(rule, status, scope) {
|
|
53
60
|
await (0, api_1.post)(`/api/rules/${rule.id}/resolve`, { status, scope });
|
|
54
61
|
}
|
|
62
|
+
// Maakt een eigen firewall-regel aan. Ondersteunt wildcards: `*.` in het domein
|
|
63
|
+
// (bv. `*.pkgs.dev.azure.com`) en `*` in het padpatroon (bv.
|
|
64
|
+
// `/_packaging/*/nuget/v3/*` voor een Azure-DevOps-feed met een wisselende
|
|
65
|
+
// GUID). Standaard 'allow'; met --deny een block-regel. Zonder --container is
|
|
66
|
+
// de regel globaal.
|
|
67
|
+
async function runFirewallAdd(opts) {
|
|
68
|
+
const domain = (opts.domain ?? '').trim();
|
|
69
|
+
if (!domain) {
|
|
70
|
+
throw new Error('Usage: huddle firewall add <domain> [--path <pattern>] [--deny] [--container <id>]');
|
|
71
|
+
}
|
|
72
|
+
const status = opts.deny ? 'deny' : 'allow';
|
|
73
|
+
const path = opts.path?.trim();
|
|
74
|
+
const body = {
|
|
75
|
+
domain,
|
|
76
|
+
container_id: opts.container ?? null,
|
|
77
|
+
status,
|
|
78
|
+
};
|
|
79
|
+
if (path)
|
|
80
|
+
body.path_pattern = path;
|
|
81
|
+
const rule = await (0, api_1.post)('/api/rules', body);
|
|
82
|
+
const target = formatTarget(rule);
|
|
83
|
+
const scope = rule.container_id ? `container: ${rule.container_id}` : 'global';
|
|
84
|
+
const verb = status === 'deny' ? (0, utils_1.red)('Denied') : (0, utils_1.green)('Allowed');
|
|
85
|
+
console.log(`${verb} ${(0, utils_1.bold)((0, utils_1.cyan)(target))} ${(0, utils_1.dim)(`(${scope})`)}`);
|
|
86
|
+
}
|
|
55
87
|
function printRulesTable(rules) {
|
|
56
88
|
const headers = ['ID', 'Status', 'Domain/path', 'Container', 'Requests', 'Seen'];
|
|
57
89
|
const rows = rules.map((r) => [
|
|
@@ -67,3 +99,42 @@ function printRulesTable(rules) {
|
|
|
67
99
|
function formatTarget(rule) {
|
|
68
100
|
return rule.path_pattern ? `${rule.domain}${rule.path_pattern}` : rule.domain;
|
|
69
101
|
}
|
|
102
|
+
async function runFirewallExport(opts) {
|
|
103
|
+
const qs = new URLSearchParams();
|
|
104
|
+
if (opts.container)
|
|
105
|
+
qs.set('container', opts.container);
|
|
106
|
+
const suffix = qs.toString() ? `?${qs}` : '';
|
|
107
|
+
const doc = await (0, api_1.get)(`/api/rules/export${suffix}`);
|
|
108
|
+
const json = JSON.stringify(doc, null, 2);
|
|
109
|
+
if (opts.out) {
|
|
110
|
+
fs_1.default.writeFileSync(opts.out, `${json}\n`);
|
|
111
|
+
// Voortgang naar stderr zodat een pure `--out` run niets naar stdout lekt.
|
|
112
|
+
console.error((0, utils_1.green)(`[OK] Exported ${doc.rules.length} rule(s) to ${opts.out}`));
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
console.log(json);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function runFirewallImport(opts) {
|
|
119
|
+
let raw;
|
|
120
|
+
try {
|
|
121
|
+
raw = fs_1.default.readFileSync(opts.file, 'utf8');
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw new Error(`Cannot read ${opts.file}`);
|
|
125
|
+
}
|
|
126
|
+
let doc;
|
|
127
|
+
try {
|
|
128
|
+
doc = JSON.parse(raw);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
throw new Error(`${opts.file} is not valid JSON`);
|
|
132
|
+
}
|
|
133
|
+
const mode = opts.replace ? 'replace' : 'merge';
|
|
134
|
+
const qs = new URLSearchParams();
|
|
135
|
+
if (opts.container)
|
|
136
|
+
qs.set('container', opts.container);
|
|
137
|
+
const suffix = qs.toString() ? `?${qs}` : '';
|
|
138
|
+
const res = await (0, api_1.post)(`/api/rules/import${suffix}`, { mode, rules: doc.rules });
|
|
139
|
+
console.error((0, utils_1.green)(`[OK] Imported (${mode}): ${res.imported} added, ${res.updated} updated, ${res.skipped} skipped`));
|
|
140
|
+
}
|
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', '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', '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 export [options] Export firewall rules as JSON
|
|
104
|
+
huddle firewall import <file> Import firewall rules from a JSON file
|
|
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,33 @@ 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
|
|
135
|
+
(or __global__). On import: remap all rules
|
|
136
|
+
to this scope
|
|
119
137
|
--status <requested|allow|deny> Filter by status (default: requested)
|
|
120
138
|
|
|
139
|
+
Firewall add options:
|
|
140
|
+
--path <pattern> Path pattern; * matches within a segment,
|
|
141
|
+
a trailing * spans deeper segments
|
|
142
|
+
(e.g. /_packaging/*/nuget/v3/*)
|
|
143
|
+
--deny Create a block rule (default: allow)
|
|
144
|
+
|
|
145
|
+
Firewall export/import options:
|
|
146
|
+
--out <file> Write export to a file (default: stdout)
|
|
147
|
+
--replace Import in replace mode: wipe the target
|
|
148
|
+
scope first (default: merge/upsert)
|
|
149
|
+
|
|
121
150
|
Global options:
|
|
122
151
|
--url <url> Huddle URL (default: http://localhost:3000)
|
|
123
152
|
Or via the HUDDLE_URL env var
|
|
@@ -200,14 +229,53 @@ async function main() {
|
|
|
200
229
|
}
|
|
201
230
|
if (cmd === 'firewall' || cmd === 'fw') {
|
|
202
231
|
const subCmd = sub ?? 'list';
|
|
203
|
-
if (subCmd
|
|
232
|
+
if (subCmd === 'list') {
|
|
233
|
+
await (0, firewall_1.runFirewallList)({
|
|
234
|
+
interactive: flagBool(flags, 'i', 'interactive'),
|
|
235
|
+
container: flagString(flags, 'container'),
|
|
236
|
+
status: flagString(flags, 'status'),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
else if (subCmd === 'add') {
|
|
240
|
+
await (0, firewall_1.runFirewallAdd)({
|
|
241
|
+
domain: positional[2],
|
|
242
|
+
path: flagString(flags, 'path'),
|
|
243
|
+
deny: flagBool(flags, 'deny'),
|
|
244
|
+
container: flagString(flags, 'container'),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
else if (subCmd === 'export') {
|
|
248
|
+
await (0, firewall_1.runFirewallExport)({
|
|
249
|
+
container: flagString(flags, 'container'),
|
|
250
|
+
out: flagString(flags, 'out'),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
else if (subCmd === 'import') {
|
|
254
|
+
const file = positional[2];
|
|
255
|
+
if (!file) {
|
|
256
|
+
console.error('Usage: huddle firewall import <file> [--replace] [--container <id>]');
|
|
257
|
+
process.exit(1);
|
|
258
|
+
}
|
|
259
|
+
await (0, firewall_1.runFirewallImport)({
|
|
260
|
+
file,
|
|
261
|
+
replace: flagBool(flags, 'replace'),
|
|
262
|
+
container: flagString(flags, 'container'),
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
204
266
|
console.error(`Unknown firewall subcommand: ${subCmd}`);
|
|
205
267
|
process.exit(1);
|
|
206
268
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (cmd === 'migrate') {
|
|
272
|
+
await (0, migrate_1.runMigrate)({
|
|
273
|
+
path: positional[1],
|
|
274
|
+
caPath: flagString(flags, 'ca-path'),
|
|
275
|
+
dockerSocket: flagBool(flags, 'docker-socket'),
|
|
276
|
+
output: flagString(flags, 'output'),
|
|
277
|
+
force: flagBool(flags, 'force'),
|
|
278
|
+
runtime: flagString(flags, 'runtime'),
|
|
211
279
|
});
|
|
212
280
|
return;
|
|
213
281
|
}
|
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
|
|
@@ -147,7 +161,7 @@ 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();
|
package/dist/migrate.js
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
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
|
+
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 = [];
|
|
126
|
+
const marked = findMarkedNetworks(compose);
|
|
127
|
+
if (marked.length === 0) {
|
|
128
|
+
throw new Error(`No network marked with \`${exports.HUDDLE_NETWORK_LABEL}: "true"\` was found. ` +
|
|
129
|
+
'Add that label to the (internal) network your services use.');
|
|
130
|
+
}
|
|
131
|
+
if (marked.length > 1) {
|
|
132
|
+
throw new Error(`Multiple networks marked with \`${exports.HUDDLE_NETWORK_LABEL}\`: ${marked.join(', ')}. Mark exactly one.`);
|
|
133
|
+
}
|
|
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`;
|
|
140
|
+
}
|
|
141
|
+
// Guardrail: the marked network must be internal, otherwise it already has a
|
|
142
|
+
// route to the internet and would bypass the firewall/proxy.
|
|
143
|
+
const markedDef = (compose.networks?.[markedNetwork] ?? {});
|
|
144
|
+
if (!isTruthy(markedDef.internal)) {
|
|
145
|
+
warnings.push(`Network "${markedNetwork}" is not marked \`internal: true\`. It must be internal, ` +
|
|
146
|
+
'otherwise services can reach the internet directly and bypass Huddle.');
|
|
147
|
+
}
|
|
148
|
+
const services = Object.entries(compose.services ?? {})
|
|
149
|
+
.filter(([, svc]) => serviceNetworkKeys(svc).includes(markedNetwork))
|
|
150
|
+
.map(([key]) => key);
|
|
151
|
+
if (services.length === 0) {
|
|
152
|
+
warnings.push(`No service is attached to the marked network "${markedNetwork}"; the override wires nothing.`);
|
|
153
|
+
}
|
|
154
|
+
const overrideServices = {};
|
|
155
|
+
for (const name of services) {
|
|
156
|
+
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;
|
|
185
|
+
}
|
|
186
|
+
const override = {
|
|
187
|
+
services: overrideServices,
|
|
188
|
+
networks: {
|
|
189
|
+
// external: true → reuse the network `huddle init` already created; do not
|
|
190
|
+
// create or take ownership of it here.
|
|
191
|
+
[huddleNetKey]: { external: true, name: internalNet },
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
return { markedNetwork, services, override, warnings };
|
|
195
|
+
}
|
|
196
|
+
function tokenize(input) {
|
|
197
|
+
const out = [];
|
|
198
|
+
for (const rawLine of input.split(/\r?\n/)) {
|
|
199
|
+
const stripped = stripComment(rawLine);
|
|
200
|
+
if (stripped.trim() === '')
|
|
201
|
+
continue;
|
|
202
|
+
const indent = stripped.length - stripped.trimStart().length;
|
|
203
|
+
out.push({ indent, text: stripped.trim() });
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
/** Removes a `# comment`, but never one that sits inside quotes or a `://` URL. */
|
|
208
|
+
function stripComment(line) {
|
|
209
|
+
let inSingle = false;
|
|
210
|
+
let inDouble = false;
|
|
211
|
+
for (let i = 0; i < line.length; i++) {
|
|
212
|
+
const c = line[i];
|
|
213
|
+
if (c === "'" && !inDouble)
|
|
214
|
+
inSingle = !inSingle;
|
|
215
|
+
else if (c === '"' && !inSingle)
|
|
216
|
+
inDouble = !inDouble;
|
|
217
|
+
else if (c === '#' && !inSingle && !inDouble && (i === 0 || /\s/.test(line[i - 1]))) {
|
|
218
|
+
return line.slice(0, i);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return line;
|
|
222
|
+
}
|
|
223
|
+
function parseYaml(input) {
|
|
224
|
+
const lines = tokenize(input);
|
|
225
|
+
let pos = 0;
|
|
226
|
+
function parseNode(indent) {
|
|
227
|
+
if (pos >= lines.length || lines[pos].indent < indent)
|
|
228
|
+
return null;
|
|
229
|
+
return isSeqItem(lines[pos].text) ? parseSequence(indent) : parseMapping(indent);
|
|
230
|
+
}
|
|
231
|
+
function parseMapping(indent) {
|
|
232
|
+
const map = {};
|
|
233
|
+
while (pos < lines.length && lines[pos].indent === indent && !isSeqItem(lines[pos].text)) {
|
|
234
|
+
const { text } = lines[pos];
|
|
235
|
+
const colon = findKeyColon(text);
|
|
236
|
+
if (colon < 0) {
|
|
237
|
+
// Not a mapping line where we expected one — stop and let the caller cope.
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
const key = unquote(text.slice(0, colon).trim());
|
|
241
|
+
const rest = text.slice(colon + 1).trim();
|
|
242
|
+
pos++;
|
|
243
|
+
if (rest !== '') {
|
|
244
|
+
map[key] = parseScalar(rest);
|
|
245
|
+
}
|
|
246
|
+
else if (pos < lines.length && lines[pos].indent > indent) {
|
|
247
|
+
map[key] = parseNode(lines[pos].indent);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
map[key] = null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return map;
|
|
254
|
+
}
|
|
255
|
+
function parseSequence(indent) {
|
|
256
|
+
const arr = [];
|
|
257
|
+
while (pos < lines.length && lines[pos].indent === indent && isSeqItem(lines[pos].text)) {
|
|
258
|
+
const afterDash = lines[pos].text.replace(/^-\s*/, '');
|
|
259
|
+
if (afterDash === '') {
|
|
260
|
+
pos++;
|
|
261
|
+
arr.push(pos < lines.length && lines[pos].indent > indent ? parseNode(lines[pos].indent) : null);
|
|
262
|
+
}
|
|
263
|
+
else if (findKeyColon(afterDash) >= 0) {
|
|
264
|
+
// Inline map item: "- key: value". Re-interpret the remainder as a
|
|
265
|
+
// mapping that starts at a virtual indent past the dash.
|
|
266
|
+
const virtualIndent = indent + (lines[pos].text.length - afterDash.length);
|
|
267
|
+
lines[pos] = { indent: virtualIndent, text: afterDash };
|
|
268
|
+
arr.push(parseMapping(virtualIndent));
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
arr.push(parseScalar(afterDash));
|
|
272
|
+
pos++;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return arr;
|
|
276
|
+
}
|
|
277
|
+
const root = parseNode(lines.length ? lines[0].indent : 0);
|
|
278
|
+
return (root && typeof root === 'object' ? root : {});
|
|
279
|
+
}
|
|
280
|
+
function isSeqItem(text) {
|
|
281
|
+
return text === '-' || text.startsWith('- ');
|
|
282
|
+
}
|
|
283
|
+
/** Index of the `key:` colon (the first colon followed by space or end-of-line). */
|
|
284
|
+
function findKeyColon(text) {
|
|
285
|
+
let inSingle = false;
|
|
286
|
+
let inDouble = false;
|
|
287
|
+
for (let i = 0; i < text.length; i++) {
|
|
288
|
+
const c = text[i];
|
|
289
|
+
if (c === "'" && !inDouble)
|
|
290
|
+
inSingle = !inSingle;
|
|
291
|
+
else if (c === '"' && !inSingle)
|
|
292
|
+
inDouble = !inDouble;
|
|
293
|
+
else if (c === ':' && !inSingle && !inDouble && (i + 1 === text.length || text[i + 1] === ' ')) {
|
|
294
|
+
return i;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return -1;
|
|
298
|
+
}
|
|
299
|
+
function parseScalar(raw) {
|
|
300
|
+
const value = raw.trim();
|
|
301
|
+
if (value.startsWith('[') && value.endsWith(']')) {
|
|
302
|
+
return splitFlow(value.slice(1, -1)).map((v) => parseScalar(v));
|
|
303
|
+
}
|
|
304
|
+
if (value.startsWith('{') && value.endsWith('}')) {
|
|
305
|
+
const map = {};
|
|
306
|
+
for (const part of splitFlow(value.slice(1, -1))) {
|
|
307
|
+
const colon = findKeyColon(part);
|
|
308
|
+
if (colon < 0)
|
|
309
|
+
continue;
|
|
310
|
+
map[unquote(part.slice(0, colon).trim())] = parseScalar(part.slice(colon + 1).trim());
|
|
311
|
+
}
|
|
312
|
+
return map;
|
|
313
|
+
}
|
|
314
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
315
|
+
return unquote(value);
|
|
316
|
+
}
|
|
317
|
+
if (value === 'true')
|
|
318
|
+
return true;
|
|
319
|
+
if (value === 'false')
|
|
320
|
+
return false;
|
|
321
|
+
if (value === 'null' || value === '~' || value === '')
|
|
322
|
+
return null;
|
|
323
|
+
if (/^-?\d+(\.\d+)?$/.test(value))
|
|
324
|
+
return Number(value);
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
/** Splits a flow collection body on top-level commas (ignores commas in quotes/brackets). */
|
|
328
|
+
function splitFlow(body) {
|
|
329
|
+
const parts = [];
|
|
330
|
+
let depth = 0;
|
|
331
|
+
let inSingle = false;
|
|
332
|
+
let inDouble = false;
|
|
333
|
+
let current = '';
|
|
334
|
+
for (const c of body) {
|
|
335
|
+
if (c === "'" && !inDouble)
|
|
336
|
+
inSingle = !inSingle;
|
|
337
|
+
else if (c === '"' && !inSingle)
|
|
338
|
+
inDouble = !inDouble;
|
|
339
|
+
if (!inSingle && !inDouble) {
|
|
340
|
+
if (c === '[' || c === '{')
|
|
341
|
+
depth++;
|
|
342
|
+
else if (c === ']' || c === '}')
|
|
343
|
+
depth--;
|
|
344
|
+
else if (c === ',' && depth === 0) {
|
|
345
|
+
if (current.trim() !== '')
|
|
346
|
+
parts.push(current.trim());
|
|
347
|
+
current = '';
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
current += c;
|
|
352
|
+
}
|
|
353
|
+
if (current.trim() !== '')
|
|
354
|
+
parts.push(current.trim());
|
|
355
|
+
return parts;
|
|
356
|
+
}
|
|
357
|
+
function unquote(value) {
|
|
358
|
+
if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
|
|
359
|
+
return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
360
|
+
}
|
|
361
|
+
if (value.startsWith("'") && value.endsWith("'") && value.length >= 2) {
|
|
362
|
+
return value.slice(1, -1).replace(/''/g, "'");
|
|
363
|
+
}
|
|
364
|
+
return value;
|
|
365
|
+
}
|
|
366
|
+
/** Emits an object as YAML using the subset the reader understands. */
|
|
367
|
+
function dumpYaml(obj, indent = 0) {
|
|
368
|
+
const pad = ' '.repeat(indent);
|
|
369
|
+
if (obj === null || obj === undefined)
|
|
370
|
+
return '';
|
|
371
|
+
if (Array.isArray(obj)) {
|
|
372
|
+
if (obj.length === 0)
|
|
373
|
+
return `${pad}[]\n`;
|
|
374
|
+
return obj.map((item) => `${pad}- ${dumpInlineOrBlock(item, indent)}`).join('');
|
|
375
|
+
}
|
|
376
|
+
if (typeof obj === 'object') {
|
|
377
|
+
const entries = Object.entries(obj);
|
|
378
|
+
if (entries.length === 0)
|
|
379
|
+
return `${pad}{}\n`;
|
|
380
|
+
let out = '';
|
|
381
|
+
for (const [key, value] of entries) {
|
|
382
|
+
// Keys can come straight from an untrusted compose file (service/network
|
|
383
|
+
// names). Emit them through the same quote/escape path as scalar values so
|
|
384
|
+
// a crafted key (`a: b`, `evil #comment`, or one containing a newline)
|
|
385
|
+
// cannot break out of its line and inject sibling compose directives.
|
|
386
|
+
const k = formatScalar(key);
|
|
387
|
+
if (value === null || value === undefined) {
|
|
388
|
+
out += `${pad}${k}:\n`;
|
|
389
|
+
}
|
|
390
|
+
else if (typeof value === 'object') {
|
|
391
|
+
const isEmpty = Array.isArray(value) ? value.length === 0 : Object.keys(value).length === 0;
|
|
392
|
+
if (isEmpty) {
|
|
393
|
+
out += `${pad}${k}: ${Array.isArray(value) ? '[]' : '{}'}\n`;
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
out += `${pad}${k}:\n${dumpYaml(value, indent + 1)}`;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
out += `${pad}${k}: ${formatScalar(value)}\n`;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
405
|
+
return `${pad}${formatScalar(obj)}\n`;
|
|
406
|
+
}
|
|
407
|
+
function dumpInlineOrBlock(item, indent) {
|
|
408
|
+
if (item !== null && typeof item === 'object') {
|
|
409
|
+
// Render the nested structure, then splice its first line onto the dash.
|
|
410
|
+
const block = dumpYaml(item, indent + 1);
|
|
411
|
+
return block.trimStart();
|
|
412
|
+
}
|
|
413
|
+
return `${formatScalar(item)}\n`;
|
|
414
|
+
}
|
|
415
|
+
function formatScalar(value) {
|
|
416
|
+
if (typeof value === 'boolean' || typeof value === 'number')
|
|
417
|
+
return String(value);
|
|
418
|
+
const str = String(value);
|
|
419
|
+
if (needsQuote(str)) {
|
|
420
|
+
// Escape backslash first, then quotes, then control chars — otherwise a raw
|
|
421
|
+
// newline/CR/tab would terminate the current line and let attacker-supplied
|
|
422
|
+
// text be reparsed as fresh YAML structure.
|
|
423
|
+
const escaped = str
|
|
424
|
+
.replace(/\\/g, '\\\\')
|
|
425
|
+
.replace(/"/g, '\\"')
|
|
426
|
+
.replace(/\n/g, '\\n')
|
|
427
|
+
.replace(/\r/g, '\\r')
|
|
428
|
+
.replace(/\t/g, '\\t');
|
|
429
|
+
return `"${escaped}"`;
|
|
430
|
+
}
|
|
431
|
+
return str;
|
|
432
|
+
}
|
|
433
|
+
function needsQuote(str) {
|
|
434
|
+
if (str === '')
|
|
435
|
+
return true;
|
|
436
|
+
if (/^(true|false|null|~|yes|no|on|off)$/i.test(str))
|
|
437
|
+
return true;
|
|
438
|
+
if (/^-?\d+(\.\d+)?$/.test(str))
|
|
439
|
+
return true;
|
|
440
|
+
if (/[:#[\]{}&*!|>%@`,"']/.test(str))
|
|
441
|
+
return true;
|
|
442
|
+
if (/[\n\r\t]/.test(str))
|
|
443
|
+
return true;
|
|
444
|
+
if (/^\s|\s$/.test(str))
|
|
445
|
+
return true;
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
/** Resolves the docker-compose file for a project directory (or an explicit file). */
|
|
449
|
+
function resolveComposeFile(target) {
|
|
450
|
+
const resolved = path_1.default.resolve(target ?? process.cwd());
|
|
451
|
+
let stat;
|
|
452
|
+
try {
|
|
453
|
+
stat = fs_1.default.statSync(resolved);
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
throw new Error(`Path does not exist: ${resolved}`);
|
|
457
|
+
}
|
|
458
|
+
if (stat.isFile())
|
|
459
|
+
return resolved;
|
|
460
|
+
for (const name of ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml']) {
|
|
461
|
+
const candidate = path_1.default.join(resolved, name);
|
|
462
|
+
if (fs_1.default.existsSync(candidate))
|
|
463
|
+
return candidate;
|
|
464
|
+
}
|
|
465
|
+
throw new Error(`No docker-compose file found in ${resolved}`);
|
|
466
|
+
}
|
|
467
|
+
/** Best-effort check that Huddle's internal network already exists. */
|
|
468
|
+
function huddleNetworkExists(internalNet, runtime) {
|
|
469
|
+
try {
|
|
470
|
+
const rt = (0, runtime_1.resolveRuntime)(runtime);
|
|
471
|
+
// execFileSync (arg-array, geen shell) i.p.v. execSync: er komt geen shell aan
|
|
472
|
+
// te pas, dus geen command-injection-oppervlak via de runtime-/netwerknaam.
|
|
473
|
+
(0, child_process_1.execFileSync)(rt.name, ['network', 'inspect', internalNet], { stdio: 'ignore' });
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return undefined; // runtime unavailable or network missing — don't block.
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async function runMigrate(opts) {
|
|
481
|
+
const composeFile = resolveComposeFile(opts.path);
|
|
482
|
+
const projectDir = path_1.default.dirname(composeFile);
|
|
483
|
+
const caPath = opts.caPath ?? exports.DEFAULT_CA_PATH;
|
|
484
|
+
console.log(`${(0, utils_1.bold)('Migrating')} ${(0, utils_1.cyan)(composeFile)} to run behind Huddle...\n`);
|
|
485
|
+
const raw = fs_1.default.readFileSync(composeFile, 'utf8');
|
|
486
|
+
let compose;
|
|
487
|
+
try {
|
|
488
|
+
compose = parseYaml(raw);
|
|
489
|
+
}
|
|
490
|
+
catch (err) {
|
|
491
|
+
throw new Error(`Could not parse ${composeFile}: ${err instanceof Error ? err.message : String(err)}`);
|
|
492
|
+
}
|
|
493
|
+
const result = buildOverride(compose, { caPath, dockerSocket: opts.dockerSocket });
|
|
494
|
+
console.log(`Marked network: ${(0, utils_1.bold)(result.markedNetwork)}`);
|
|
495
|
+
console.log(`Wired services: ${result.services.length ? result.services.map(utils_1.bold).join(', ') : (0, utils_1.dim)('(none)')}`);
|
|
496
|
+
for (const w of result.warnings)
|
|
497
|
+
console.log((0, utils_1.yellow)(`[!] ${w}`));
|
|
498
|
+
console.log();
|
|
499
|
+
const overrideText = '# Generated by `huddle migrate` — do NOT edit by hand; re-run the command instead.\n' +
|
|
500
|
+
'# Merge this on top of your docker-compose.yml so the marked services reach the\n' +
|
|
501
|
+
'# internet only through the Huddle proxy. Your own compose file stays untouched.\n' +
|
|
502
|
+
dumpYaml(result.override);
|
|
503
|
+
const outPath = opts.output ? path_1.default.resolve(opts.output) : path_1.default.join(projectDir, exports.OVERRIDE_FILENAME);
|
|
504
|
+
if (fs_1.default.existsSync(outPath) && !opts.force) {
|
|
505
|
+
throw new Error(`${outPath} already exists. Re-run with --force to overwrite.`);
|
|
506
|
+
}
|
|
507
|
+
fs_1.default.writeFileSync(outPath, overrideText);
|
|
508
|
+
console.log((0, utils_1.green)(`[OK] Wrote override: ${outPath}`));
|
|
509
|
+
console.log();
|
|
510
|
+
// Best-effort readiness hint.
|
|
511
|
+
if (huddleNetworkExists(init_1.INTERNAL_NET, opts.runtime) === undefined) {
|
|
512
|
+
console.log((0, utils_1.yellow)(`[!] Could not confirm the "${init_1.INTERNAL_NET}" network exists. Run \`huddle init\` first.`));
|
|
513
|
+
console.log();
|
|
514
|
+
}
|
|
515
|
+
printNextSteps(composeFile, outPath, caPath, !!opts.dockerSocket);
|
|
516
|
+
}
|
|
517
|
+
function printNextSteps(composeFile, outPath, caPath, dockerSocket) {
|
|
518
|
+
const composeBase = path_1.default.basename(composeFile);
|
|
519
|
+
const overrideBase = path_1.default.basename(outPath);
|
|
520
|
+
console.log((0, utils_1.bold)('Next steps (this command only GENERATED the override — it did not start anything):'));
|
|
521
|
+
console.log();
|
|
522
|
+
console.log(' 1. Make sure Huddle is running:');
|
|
523
|
+
console.log((0, utils_1.cyan)(' huddle init'));
|
|
524
|
+
console.log();
|
|
525
|
+
console.log(' 2. Fetch the Huddle CA inside the container. Add to your devcontainer.json:');
|
|
526
|
+
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)'"`));
|
|
527
|
+
console.log((0, utils_1.dim)(` (Adjust ${caPath} to your remoteUser's home if it differs; pass --ca-path to change it.)`));
|
|
528
|
+
console.log();
|
|
529
|
+
console.log(' 3. Reference the override so the IDE merges it. In devcontainer.json:');
|
|
530
|
+
console.log((0, utils_1.cyan)(` "dockerComposeFile": ["${composeBase}", "${overrideBase}"]`));
|
|
531
|
+
console.log((0, utils_1.dim)(' Or start it yourself:'));
|
|
532
|
+
console.log((0, utils_1.cyan)(` docker compose -f ${composeBase} -f ${overrideBase} up -d`));
|
|
533
|
+
console.log();
|
|
534
|
+
if (dockerSocket) {
|
|
535
|
+
console.log((0, utils_1.yellow)(' Note (--docker-socket): the socket mount is GENERATED but NOT yet served.'));
|
|
536
|
+
console.log((0, utils_1.dim)(' Huddle does not yet pre-provision the per-container filtered socket for IDE-started\n' +
|
|
537
|
+
' containers (issue #66 follow-up). Until it does, the mount source will not exist and\n' +
|
|
538
|
+
' DOCKER_HOST will point at a missing socket. Only enable this once that lands.'));
|
|
539
|
+
console.log();
|
|
540
|
+
}
|
|
541
|
+
console.log((0, utils_1.dim)('See docs/migrate-devcontainers.md for the full guide and the marked-network convention.'));
|
|
542
|
+
}
|
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");
|
|
@@ -42,6 +44,55 @@ function podmanSocketPath() {
|
|
|
42
44
|
function dockerSocketPath() {
|
|
43
45
|
return process.platform === 'win32' ? '//var/run/docker.sock' : '/var/run/docker.sock';
|
|
44
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Haalt het unix-socketpad uit de JSON van `docker context inspect`. De actieve
|
|
49
|
+
* context bepaalt naar welke engine het `docker`-commando praat; Rancher Desktop
|
|
50
|
+
* (dockerd/moby-modus) zet een `rancher-desktop`-context waarvan
|
|
51
|
+
* `Endpoints.docker.Host` naar `unix:///<home>/.rd/docker.sock` wijst i.p.v. de
|
|
52
|
+
* standaard `/var/run/docker.sock`.
|
|
53
|
+
*
|
|
54
|
+
* Pure functie zodat we het parsen los kunnen testen. Geeft `null` terug bij
|
|
55
|
+
* niet-parsebare invoer of een niet-unix endpoint (npipe:// op Windows,
|
|
56
|
+
* tcp:// / ssh:// remote), want die zijn niet als bestandspad te bind-mounten.
|
|
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` levert een array; één context is één 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
|
+
// Het teruggegeven pad wordt later ONgequote in een `docker run -v <pad>:...`
|
|
76
|
+
// shell-commando geïnterpoleerd (init.ts). De `Host` uit `docker context
|
|
77
|
+
// inspect` is beïnvloedbaar (wie een docker-context kan aanmaken/activeren
|
|
78
|
+
// bepaalt de waarde), dus laat alleen tekens toe die in een echt socketpad
|
|
79
|
+
// voorkomen. Zo kan een gemanipuleerde context geen shell-metatekens
|
|
80
|
+
// ($(), backticks, ;, |, spaties, ...) binnensmokkelen — command injection.
|
|
81
|
+
if (!/^[A-Za-z0-9._/-]+$/.test(path))
|
|
82
|
+
return null;
|
|
83
|
+
return path;
|
|
84
|
+
}
|
|
85
|
+
/** Herkent het socketpad van Rancher Desktop (dockerd/moby-modus): `~/.rd/docker.sock`. */
|
|
86
|
+
function isRancherDesktopSocket(socketPath) {
|
|
87
|
+
return typeof socketPath === 'string' && /(^|\/)\.rd\/docker\.sock$/.test(socketPath);
|
|
88
|
+
}
|
|
89
|
+
/** Socketpad van de actieve docker-context, of undefined als het niet op te vragen is. */
|
|
90
|
+
function dockerContextSocket() {
|
|
91
|
+
const json = commandOutput('docker context inspect');
|
|
92
|
+
if (!json)
|
|
93
|
+
return undefined;
|
|
94
|
+
return parseDockerContextSocket(json) ?? undefined;
|
|
95
|
+
}
|
|
45
96
|
function podmanIsRemote() {
|
|
46
97
|
// Op macOS/Windows draait Podman altijd in een `podman machine`-VM; ook op
|
|
47
98
|
// Linux kan de client op een remote socket wijzen. `ServiceIsRemote` is de
|
|
@@ -58,12 +109,21 @@ function buildRuntime(name) {
|
|
|
58
109
|
securityOpts: ['label=disable'],
|
|
59
110
|
};
|
|
60
111
|
}
|
|
112
|
+
// Rancher Desktop (dockerd/moby-modus) ziet er als een gewone Docker-engine
|
|
113
|
+
// uit, maar de socket zit niet op /var/run/docker.sock: de actieve
|
|
114
|
+
// docker-context wijst naar `~/.rd/docker.sock`. Volg die context zodat we de
|
|
115
|
+
// juiste socket bind-mounten; anders vallen we terug op de standaardlocatie
|
|
116
|
+
// (echte native Docker, Docker Desktop). Rancher Desktop draait de engine op
|
|
117
|
+
// ELK platform in een VM (Lima/WSL), dus is hij altijd 'remote'.
|
|
118
|
+
const contextSocket = dockerContextSocket();
|
|
119
|
+
const isRancher = isRancherDesktopSocket(contextSocket);
|
|
61
120
|
return {
|
|
62
121
|
name,
|
|
63
|
-
socketPath: dockerSocketPath(),
|
|
122
|
+
socketPath: isRancher ? contextSocket : dockerSocketPath(),
|
|
64
123
|
defaultNetwork: 'bridge',
|
|
65
|
-
// Docker Desktop (macOS/Windows)
|
|
66
|
-
|
|
124
|
+
// Docker Desktop (macOS/Windows) en Rancher Desktop draaien in een VM;
|
|
125
|
+
// native Docker op Linux niet.
|
|
126
|
+
isRemote: isRancher || process.platform !== 'linux',
|
|
67
127
|
securityOpts: [],
|
|
68
128
|
};
|
|
69
129
|
}
|
package/package.json
CHANGED