@infosupport/huddle-cli 0.0.0-experiment-137.151.1 → 0.0.0-experiment-160.152.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -32
- package/dist/api.js +11 -5
- package/dist/config.js +5 -2
- package/dist/extension.js +170 -0
- package/dist/host-logs.js +60 -0
- package/dist/index.js +53 -28
- package/dist/init.js +50 -5
- package/dist/pipe/command.js +186 -0
- package/dist/pipe/fs-list.js +181 -0
- package/dist/pipe/protocol.js +99 -0
- package/dist/pipe/sbx-kit.js +142 -0
- package/dist/pipe/sbx-links.js +147 -0
- package/dist/pipe/serve.js +223 -0
- package/dist/pipe/ssh-hosts.js +155 -0
- package/dist/pipe/tools.js +246 -0
- package/dist/runtime.js +38 -19
- package/dist/start.js +10 -8
- package/dist/zip.js +74 -0
- package/images/base-devimage/Dockerfile +16 -2
- package/package.json +6 -3
- package/dist/indexfolder.js +0 -167
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe op `sbx.links`: Settings → Folder mappings for a Docker Sandbox ──
|
|
3
|
+
// sbx mounts only the folders it is given at create, at their host path. So each
|
|
4
|
+
// sandbox gets two extra folders, ~/.huddle/sbx/links/<name>/rw and /ro, with one
|
|
5
|
+
// link per folder mapping in them (a junction on Windows, which needs no admin
|
|
6
|
+
// rights or developer mode; a symlink elsewhere). The gateway passes them to
|
|
7
|
+
// `sbx create`, ro with `:ro`, and links each one to its container path inside.
|
|
8
|
+
//
|
|
9
|
+
// Tested against sbx v0.39.0 on Windows (sbx-folder-links-poc.mjs): sbx's file
|
|
10
|
+
// share follows these links on the host side, `:ro` on the ro folder holds for
|
|
11
|
+
// what is behind them too, and a link the sandbox makes in rw itself stays inside
|
|
12
|
+
// the sandbox (it never appears on the host, so it cannot reach other folders).
|
|
13
|
+
//
|
|
14
|
+
// The op only (re)builds those folders. An empty list removes the sandbox's
|
|
15
|
+
// folder. Links in it are removed, never followed.
|
|
16
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
+
};
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.SBX_LINKS_DIR = void 0;
|
|
21
|
+
exports.removeNoFollow = removeNoFollow;
|
|
22
|
+
exports.sbxLinks = sbxLinks;
|
|
23
|
+
const fs_1 = __importDefault(require("fs"));
|
|
24
|
+
const path_1 = __importDefault(require("path"));
|
|
25
|
+
const config_1 = require("../config");
|
|
26
|
+
const protocol_1 = require("./protocol");
|
|
27
|
+
const fs_list_1 = require("./fs-list");
|
|
28
|
+
exports.SBX_LINKS_DIR = path_1.default.join(config_1.CONFIG_DIR, 'sbx', 'links');
|
|
29
|
+
// Same rules as the gateway (environments/sbx.ts): the name is a folder name here.
|
|
30
|
+
const SANDBOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
31
|
+
const LINK_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
32
|
+
const MAX_LINKS = 64;
|
|
33
|
+
/** Removes `p` without following any link in it: a link is removed itself. */
|
|
34
|
+
function removeNoFollow(p) {
|
|
35
|
+
let st;
|
|
36
|
+
try {
|
|
37
|
+
st = fs_1.default.lstatSync(p);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (st.isSymbolicLink()) {
|
|
43
|
+
// A junction is a directory to unlink() on some Node versions.
|
|
44
|
+
try {
|
|
45
|
+
fs_1.default.unlinkSync(p);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
fs_1.default.rmdirSync(p);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
else if (st.isDirectory()) {
|
|
52
|
+
for (const e of fs_1.default.readdirSync(p))
|
|
53
|
+
removeNoFollow(path_1.default.join(p, e));
|
|
54
|
+
fs_1.default.rmdirSync(p);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
fs_1.default.unlinkSync(p);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function inside(child, parent, platform) {
|
|
61
|
+
const norm = (s) => {
|
|
62
|
+
const h = (0, fs_list_1.toHuddlePath)(s, platform);
|
|
63
|
+
return platform === 'win32' ? h.toLowerCase() : h;
|
|
64
|
+
};
|
|
65
|
+
const c = norm(child);
|
|
66
|
+
const p = norm(parent);
|
|
67
|
+
return c === p || c.startsWith(p.endsWith('/') ? p : `${p}/`);
|
|
68
|
+
}
|
|
69
|
+
function parseLinks(raw, platform) {
|
|
70
|
+
if (!Array.isArray(raw))
|
|
71
|
+
throw new protocol_1.PipeError('bad_request', 'links must be an array');
|
|
72
|
+
if (raw.length > MAX_LINKS)
|
|
73
|
+
throw new protocol_1.PipeError('bad_request', `at most ${MAX_LINKS} links`);
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
return raw.map((l) => {
|
|
76
|
+
const { id, hostPath, readOnly } = (l ?? {});
|
|
77
|
+
if (typeof id !== 'string' || !LINK_ID_RE.test(id))
|
|
78
|
+
throw new protocol_1.PipeError('bad_request', 'link id must be 1-64 letters, digits, _ or -');
|
|
79
|
+
if (seen.has(id))
|
|
80
|
+
throw new protocol_1.PipeError('bad_request', `duplicate link id ${id}`);
|
|
81
|
+
seen.add(id);
|
|
82
|
+
if (typeof hostPath !== 'string' || hostPath.includes('\0') || !(0, fs_list_1.isAbsoluteHostPath)(hostPath, platform)) {
|
|
83
|
+
throw new protocol_1.PipeError('bad_request', `link ${id}: hostPath must be an absolute path`);
|
|
84
|
+
}
|
|
85
|
+
return { id, hostPath, readOnly: readOnly === true };
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** The `sbx.links` op. `root` and `huddleHome` are only moved in tests. */
|
|
89
|
+
function sbxLinks(args, root = exports.SBX_LINKS_DIR, huddleHome = config_1.CONFIG_DIR, platform = process.platform) {
|
|
90
|
+
const { name } = args;
|
|
91
|
+
if (typeof name !== 'string' || !SANDBOX_NAME_RE.test(name))
|
|
92
|
+
throw new protocol_1.PipeError('bad_request', 'invalid sandbox name');
|
|
93
|
+
const links = parseLinks(args.links, platform);
|
|
94
|
+
// Resolved first: a mapping that is itself a link counts as where it points.
|
|
95
|
+
const usable = [];
|
|
96
|
+
const skipped = [];
|
|
97
|
+
for (const l of links) {
|
|
98
|
+
let target;
|
|
99
|
+
try {
|
|
100
|
+
target = fs_1.default.realpathSync(l.hostPath);
|
|
101
|
+
if (!fs_1.default.statSync(target).isDirectory()) {
|
|
102
|
+
skipped.push({ id: l.id, reason: 'not a folder' });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
skipped.push({ id: l.id, reason: 'does not exist' });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
// Same rule as every mount Huddle makes (gateway host-path.ts): never
|
|
111
|
+
// ~/.huddle or inside it, and a folder around it only read-only.
|
|
112
|
+
if (inside(target, huddleHome, platform)) {
|
|
113
|
+
skipped.push({ id: l.id, reason: "is Huddle's own folder or inside it" });
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!l.readOnly && inside(huddleHome, target, platform)) {
|
|
117
|
+
skipped.push({ id: l.id, reason: "contains Huddle's own folder, so only read-only" });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
usable.push({ ...l, target });
|
|
121
|
+
}
|
|
122
|
+
const boxDir = path_1.default.join(root, name);
|
|
123
|
+
try {
|
|
124
|
+
removeNoFollow(boxDir);
|
|
125
|
+
if (usable.length === 0)
|
|
126
|
+
return { rw: null, ro: null, skipped };
|
|
127
|
+
(0, protocol_1.ensurePrivateDir)(path_1.default.dirname(root));
|
|
128
|
+
(0, protocol_1.ensurePrivateDir)(root);
|
|
129
|
+
(0, protocol_1.ensurePrivateDir)(boxDir);
|
|
130
|
+
const made = { rw: null, ro: null };
|
|
131
|
+
for (const l of usable) {
|
|
132
|
+
const kind = l.readOnly ? 'ro' : 'rw';
|
|
133
|
+
const dir = path_1.default.join(boxDir, kind);
|
|
134
|
+
if (!made[kind]) {
|
|
135
|
+
fs_1.default.mkdirSync(dir, { mode: 0o700 });
|
|
136
|
+
made[kind] = (0, fs_list_1.toHuddlePath)(dir, platform);
|
|
137
|
+
}
|
|
138
|
+
fs_1.default.symlinkSync(l.target, path_1.default.join(dir, l.id), platform === 'win32' ? 'junction' : 'dir');
|
|
139
|
+
}
|
|
140
|
+
return { ...made, skipped };
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
if (err instanceof protocol_1.PipeError)
|
|
144
|
+
throw err;
|
|
145
|
+
throw new protocol_1.PipeError('internal', `could not prepare the folder links: ${err.message ?? err}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe: the agent's serve loop ─────────────────────────────────────────
|
|
3
|
+
// Polls the pipe folder for `<id>.in`, claims each by renaming it to
|
|
4
|
+
// `<id>.busy` (so it is handled exactly once, even if two agents race), runs it
|
|
5
|
+
// without blocking the loop (a 10-minute `sbx create` must not hold up a folder
|
|
6
|
+
// listing), writes `<id>.out` atomically and deletes the `.busy`. Every request
|
|
7
|
+
// gets a reply, a malformed one included; nothing a request contains can crash
|
|
8
|
+
// the loop. See docs/host-pipe.md for the protocol.
|
|
9
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
10
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
11
|
+
};
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.cleanStale = cleanStale;
|
|
14
|
+
exports.servePipe = servePipe;
|
|
15
|
+
const fs_1 = __importDefault(require("fs"));
|
|
16
|
+
const os_1 = __importDefault(require("os"));
|
|
17
|
+
const path_1 = __importDefault(require("path"));
|
|
18
|
+
const self_update_1 = require("../self-update");
|
|
19
|
+
const protocol_1 = require("./protocol");
|
|
20
|
+
const fs_list_1 = require("./fs-list");
|
|
21
|
+
const tools_1 = require("./tools");
|
|
22
|
+
const sbx_kit_1 = require("./sbx-kit");
|
|
23
|
+
const sbx_links_1 = require("./sbx-links");
|
|
24
|
+
const ssh_hosts_1 = require("./ssh-hosts");
|
|
25
|
+
// Ids are generated by the gateway (32 hex); anything that does not look like
|
|
26
|
+
// an id is not ours and is left alone rather than turned into a reply path.
|
|
27
|
+
const REQUEST_RE = /^([A-Za-z0-9_-]{1,128})\.in$/;
|
|
28
|
+
const LEFTOVER_RE = /\.(in|busy|out|tmp)$/;
|
|
29
|
+
async function dispatch(req, maxEntries) {
|
|
30
|
+
const args = req.args ?? {};
|
|
31
|
+
switch (req.op) {
|
|
32
|
+
case 'host.info':
|
|
33
|
+
return {
|
|
34
|
+
platform: process.platform,
|
|
35
|
+
version: (0, self_update_1.cliVersion)(),
|
|
36
|
+
home: (0, fs_list_1.toHuddlePath)(os_1.default.homedir()),
|
|
37
|
+
tools: await (0, tools_1.toolsInfo)(),
|
|
38
|
+
};
|
|
39
|
+
case 'fs.list':
|
|
40
|
+
return (0, fs_list_1.fsList)(args, maxEntries);
|
|
41
|
+
case 'fs.resolve':
|
|
42
|
+
return (0, fs_list_1.fsResolve)(args);
|
|
43
|
+
case 'tool.run':
|
|
44
|
+
return (0, tools_1.toolRun)(args);
|
|
45
|
+
case 'sbx.links':
|
|
46
|
+
return (0, sbx_links_1.sbxLinks)(args);
|
|
47
|
+
case 'sbx.kit':
|
|
48
|
+
return (0, sbx_kit_1.sbxKit)(args);
|
|
49
|
+
case 'ssh.key':
|
|
50
|
+
return (0, ssh_hosts_1.sshKey)(args);
|
|
51
|
+
case 'ssh.host':
|
|
52
|
+
return (0, ssh_hosts_1.sshHost)(args);
|
|
53
|
+
default:
|
|
54
|
+
throw new protocol_1.PipeError('unknown_op', `unknown op '${req.op}'`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function parseRequest(text) {
|
|
58
|
+
let req;
|
|
59
|
+
try {
|
|
60
|
+
req = JSON.parse(text);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new protocol_1.PipeError('bad_request', 'request is not valid JSON');
|
|
64
|
+
}
|
|
65
|
+
if (typeof req !== 'object' || req === null || Array.isArray(req))
|
|
66
|
+
throw new protocol_1.PipeError('bad_request', 'request must be a JSON object');
|
|
67
|
+
const r = req;
|
|
68
|
+
if (r.v !== protocol_1.PROTOCOL_VERSION)
|
|
69
|
+
throw new protocol_1.PipeError('bad_request', `unsupported protocol version ${JSON.stringify(r.v)} (agent speaks ${protocol_1.PROTOCOL_VERSION})`);
|
|
70
|
+
if (typeof r.op !== 'string' || !r.op)
|
|
71
|
+
throw new protocol_1.PipeError('bad_request', 'op must be a non-empty string');
|
|
72
|
+
if (r.args !== undefined && (typeof r.args !== 'object' || r.args === null || Array.isArray(r.args))) {
|
|
73
|
+
throw new protocol_1.PipeError('bad_request', 'args must be an object');
|
|
74
|
+
}
|
|
75
|
+
return r;
|
|
76
|
+
}
|
|
77
|
+
/** Deletes request/reply leftovers older than STALE_FILE_MS, skipping ids still in flight. */
|
|
78
|
+
function cleanStale(dir, inFlight = new Set(), now = Date.now()) {
|
|
79
|
+
const removed = [];
|
|
80
|
+
let names;
|
|
81
|
+
try {
|
|
82
|
+
names = fs_1.default.readdirSync(dir);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return removed;
|
|
86
|
+
}
|
|
87
|
+
for (const name of names) {
|
|
88
|
+
if (!LEFTOVER_RE.test(name) || inFlight.has(name.split('.')[0]))
|
|
89
|
+
continue;
|
|
90
|
+
const file = path_1.default.join(dir, name);
|
|
91
|
+
try {
|
|
92
|
+
if (now - fs_1.default.statSync(file).mtimeMs > protocol_1.STALE_FILE_MS) {
|
|
93
|
+
fs_1.default.unlinkSync(file);
|
|
94
|
+
removed.push(name);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch { /* gone already, or not ours to delete */ }
|
|
98
|
+
}
|
|
99
|
+
return removed;
|
|
100
|
+
}
|
|
101
|
+
function servePipe(opts) {
|
|
102
|
+
const { dir } = opts;
|
|
103
|
+
const maxEntries = opts.maxEntries ?? protocol_1.MAX_FOLDER_ENTRIES;
|
|
104
|
+
const log = opts.log ?? (() => { });
|
|
105
|
+
(0, protocol_1.ensurePrivateDir)(dir);
|
|
106
|
+
const startedAt = new Date().toISOString();
|
|
107
|
+
const version = (0, self_update_1.cliVersion)();
|
|
108
|
+
const inFlight = new Map();
|
|
109
|
+
let stopped = false;
|
|
110
|
+
let pollTimer;
|
|
111
|
+
let heartbeatTimer;
|
|
112
|
+
let cleanupTimer;
|
|
113
|
+
const removed = cleanStale(dir);
|
|
114
|
+
if (removed.length)
|
|
115
|
+
log(`removed ${removed.length} stale file(s)`);
|
|
116
|
+
const handle = async (id) => {
|
|
117
|
+
const busy = path_1.default.join(dir, `${id}.busy`);
|
|
118
|
+
let reply;
|
|
119
|
+
let op = '?';
|
|
120
|
+
try {
|
|
121
|
+
const req = parseRequest(await fs_1.default.promises.readFile(busy, 'utf8'));
|
|
122
|
+
op = req.op;
|
|
123
|
+
reply = { ok: true, result: await dispatch(req, maxEntries) };
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
reply = err instanceof protocol_1.PipeError
|
|
127
|
+
? { ok: false, error: { code: err.code, message: err.message } }
|
|
128
|
+
: { ok: false, error: { code: 'internal', message: err instanceof Error ? err.message : String(err) } };
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
(0, protocol_1.writeJsonAtomic)(path_1.default.join(dir, `${id}.out`), reply);
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
log(`${id} ${op}: could not write reply: ${err instanceof Error ? err.message : err}`);
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
fs_1.default.unlinkSync(busy);
|
|
138
|
+
}
|
|
139
|
+
catch { /* already gone */ }
|
|
140
|
+
log(`${id} ${op} -> ${reply.ok ? 'ok' : reply.error.code}`);
|
|
141
|
+
};
|
|
142
|
+
const poll = async () => {
|
|
143
|
+
let names = [];
|
|
144
|
+
try {
|
|
145
|
+
names = await fs_1.default.promises.readdir(dir);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// The folder went away (e.g. ~/.huddle was removed); recreate and carry on.
|
|
149
|
+
try {
|
|
150
|
+
(0, protocol_1.ensurePrivateDir)(dir);
|
|
151
|
+
}
|
|
152
|
+
catch { /* retry next tick */ }
|
|
153
|
+
}
|
|
154
|
+
for (const name of names) {
|
|
155
|
+
const m = REQUEST_RE.exec(name);
|
|
156
|
+
if (!m || stopped)
|
|
157
|
+
continue;
|
|
158
|
+
const id = m[1];
|
|
159
|
+
// Claiming is the rename: whoever renames first owns the request. A
|
|
160
|
+
// failure means someone else got it (or the gateway gave up on it).
|
|
161
|
+
try {
|
|
162
|
+
fs_1.default.renameSync(path_1.default.join(dir, name), path_1.default.join(dir, `${id}.busy`));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const p = handle(id).finally(() => inFlight.delete(id));
|
|
168
|
+
inFlight.set(id, p);
|
|
169
|
+
}
|
|
170
|
+
if (!stopped)
|
|
171
|
+
pollTimer = setTimeout(() => void poll(), opts.pollMs ?? protocol_1.POLL_MS);
|
|
172
|
+
};
|
|
173
|
+
const heartbeat = () => {
|
|
174
|
+
const file = path_1.default.join(dir, protocol_1.HEARTBEAT_FILE);
|
|
175
|
+
// Another agent (a newer CLI started by `huddle init`) took over: step aside
|
|
176
|
+
// rather than fight over host.json every two seconds.
|
|
177
|
+
const current = (0, protocol_1.readHeartbeat)(dir);
|
|
178
|
+
if (current && current.pid !== process.pid && current.startedAt > startedAt) {
|
|
179
|
+
log(`replaced by pid ${current.pid}; stopping`);
|
|
180
|
+
void stop().then(() => opts.onReplaced?.());
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const hb = {
|
|
184
|
+
v: protocol_1.PROTOCOL_VERSION,
|
|
185
|
+
pid: process.pid,
|
|
186
|
+
version,
|
|
187
|
+
platform: process.platform,
|
|
188
|
+
tools: (0, tools_1.availableTools)(),
|
|
189
|
+
startedAt,
|
|
190
|
+
updatedAt: new Date().toISOString(),
|
|
191
|
+
};
|
|
192
|
+
try {
|
|
193
|
+
(0, protocol_1.writeJsonAtomic)(file, hb);
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
log(`could not write heartbeat: ${err instanceof Error ? err.message : err}`);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
heartbeatTimer = setInterval(heartbeat, opts.heartbeatMs ?? protocol_1.HEARTBEAT_MS);
|
|
200
|
+
heartbeat();
|
|
201
|
+
// Orphaned replies (the gateway timed out and never collected them) would
|
|
202
|
+
// otherwise pile up for as long as the agent runs.
|
|
203
|
+
cleanupTimer = setInterval(() => cleanStale(dir, new Set(inFlight.keys())), protocol_1.STALE_FILE_MS);
|
|
204
|
+
cleanupTimer.unref();
|
|
205
|
+
void poll();
|
|
206
|
+
async function stop() {
|
|
207
|
+
if (!stopped) {
|
|
208
|
+
stopped = true;
|
|
209
|
+
clearTimeout(pollTimer);
|
|
210
|
+
clearInterval(heartbeatTimer);
|
|
211
|
+
clearInterval(cleanupTimer);
|
|
212
|
+
const current = (0, protocol_1.readHeartbeat)(dir);
|
|
213
|
+
if (current && current.pid === process.pid && current.startedAt === startedAt) {
|
|
214
|
+
try {
|
|
215
|
+
fs_1.default.unlinkSync(path_1.default.join(dir, protocol_1.HEARTBEAT_FILE));
|
|
216
|
+
}
|
|
217
|
+
catch { /* already gone */ }
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
await Promise.allSettled([...inFlight.values()]);
|
|
221
|
+
}
|
|
222
|
+
return { stop };
|
|
223
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ── Host pipe ops `ssh.key` and `ssh.host`: SSH into a devcontainer, no key setup ──
|
|
3
|
+
// Like `sbx setup ssh` does for Docker Sandboxes: Huddle keeps its own key pair in
|
|
4
|
+
// ~/.huddle/ssh (made here, on the host, so the private key never leaves it) and
|
|
5
|
+
// one ssh config entry per devcontainer, `<name>.huddle`, in ~/.huddle/ssh/hosts.
|
|
6
|
+
// ~/.ssh/config includes those at its top, so the IDE (JetBrains Toolbox), and
|
|
7
|
+
// `ssh <name>.huddle` in a terminal, connect without asking for a key.
|
|
8
|
+
//
|
|
9
|
+
// The gateway only ever gets the public key (`ssh.key`), which it puts in the
|
|
10
|
+
// container's authorized_keys. `ssh.host` writes the entry with the container's
|
|
11
|
+
// host key pinned, so the connection is verified without a fingerprint prompt.
|
|
12
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
13
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
14
|
+
};
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.INCLUDE_LINE = exports.SSH_DIR = void 0;
|
|
17
|
+
exports.generateEd25519 = generateEd25519;
|
|
18
|
+
exports.ensureInclude = ensureInclude;
|
|
19
|
+
exports.sshKey = sshKey;
|
|
20
|
+
exports.sshHost = sshHost;
|
|
21
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
22
|
+
const fs_1 = __importDefault(require("fs"));
|
|
23
|
+
const os_1 = __importDefault(require("os"));
|
|
24
|
+
const path_1 = __importDefault(require("path"));
|
|
25
|
+
const config_1 = require("../config");
|
|
26
|
+
const protocol_1 = require("./protocol");
|
|
27
|
+
exports.SSH_DIR = path_1.default.join(config_1.CONFIG_DIR, 'ssh');
|
|
28
|
+
const KEY_FILE = 'id_ed25519';
|
|
29
|
+
/** The line Huddle puts at the top of ~/.ssh/config. Hosts in an included file stay in it. */
|
|
30
|
+
exports.INCLUDE_LINE = 'Include ~/.huddle/ssh/hosts/*.conf';
|
|
31
|
+
// Docker container names ([a-zA-Z0-9][a-zA-Z0-9_.-]*) plus `.huddle`; also a file name here.
|
|
32
|
+
const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}\.huddle$/;
|
|
33
|
+
const USER_RE = /^[a-z_][a-z0-9_-]{0,31}$/;
|
|
34
|
+
const HOST_KEY_RE = /^ssh-ed25519 [A-Za-z0-9+/]+={0,3}$/;
|
|
35
|
+
const DEFAULT_DIRS = { huddle: exports.SSH_DIR, user: path_1.default.join(os_1.default.homedir(), '.ssh') };
|
|
36
|
+
function sshString(b) {
|
|
37
|
+
const buf = typeof b === 'string' ? Buffer.from(b) : b;
|
|
38
|
+
const len = Buffer.alloc(4);
|
|
39
|
+
len.writeUInt32BE(buf.length);
|
|
40
|
+
return Buffer.concat([len, buf]);
|
|
41
|
+
}
|
|
42
|
+
/** A new ed25519 key pair in OpenSSH's formats (unencrypted private key, `ssh-ed25519 …` public key). */
|
|
43
|
+
function generateEd25519(comment) {
|
|
44
|
+
const { privateKey } = crypto_1.default.generateKeyPairSync('ed25519');
|
|
45
|
+
const jwk = privateKey.export({ format: 'jwk' });
|
|
46
|
+
const seed = Buffer.from(jwk.d, 'base64url');
|
|
47
|
+
const pub = Buffer.from(jwk.x, 'base64url');
|
|
48
|
+
const pubBlob = Buffer.concat([sshString('ssh-ed25519'), sshString(pub)]);
|
|
49
|
+
const check = crypto_1.default.randomBytes(4);
|
|
50
|
+
let priv = Buffer.concat([check, check, sshString('ssh-ed25519'), sshString(pub), sshString(Buffer.concat([seed, pub])), sshString(comment)]);
|
|
51
|
+
const pad = (8 - (priv.length % 8)) % 8;
|
|
52
|
+
priv = Buffer.concat([priv, Buffer.from(Array.from({ length: pad }, (_, i) => i + 1))]);
|
|
53
|
+
const body = Buffer.concat([
|
|
54
|
+
Buffer.from('openssh-key-v1\0'),
|
|
55
|
+
sshString('none'), sshString('none'), sshString(''),
|
|
56
|
+
Buffer.from([0, 0, 0, 1]),
|
|
57
|
+
sshString(pubBlob),
|
|
58
|
+
sshString(priv),
|
|
59
|
+
]).toString('base64');
|
|
60
|
+
return {
|
|
61
|
+
privateKey: `-----BEGIN OPENSSH PRIVATE KEY-----\n${body.match(/.{1,70}/g).join('\n')}\n-----END OPENSSH PRIVATE KEY-----\n`,
|
|
62
|
+
publicKey: `ssh-ed25519 ${pubBlob.toString('base64')} ${comment}`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Huddle's public key, after making the key pair if there is none. */
|
|
66
|
+
function ensureKey(dir) {
|
|
67
|
+
(0, protocol_1.ensurePrivateDir)(dir);
|
|
68
|
+
const keyPath = path_1.default.join(dir, KEY_FILE);
|
|
69
|
+
const pubPath = `${keyPath}.pub`;
|
|
70
|
+
if (fs_1.default.existsSync(keyPath) && fs_1.default.existsSync(pubPath))
|
|
71
|
+
return fs_1.default.readFileSync(pubPath, 'utf8').trim();
|
|
72
|
+
const { privateKey, publicKey } = generateEd25519(`huddle@${os_1.default.hostname()}`);
|
|
73
|
+
fs_1.default.rmSync(keyPath, { force: true });
|
|
74
|
+
fs_1.default.writeFileSync(keyPath, privateKey, { mode: 0o600 });
|
|
75
|
+
fs_1.default.writeFileSync(pubPath, `${publicKey}\n`, { mode: 0o644 });
|
|
76
|
+
return publicKey;
|
|
77
|
+
}
|
|
78
|
+
/** Puts INCLUDE_LINE at the top of ~/.ssh/config (making it when there is none). */
|
|
79
|
+
function ensureInclude(userDir) {
|
|
80
|
+
const file = path_1.default.join(userDir, 'config');
|
|
81
|
+
let text = '';
|
|
82
|
+
try {
|
|
83
|
+
text = fs_1.default.readFileSync(file, 'utf8');
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
fs_1.default.mkdirSync(userDir, { recursive: true, mode: 0o700 });
|
|
87
|
+
}
|
|
88
|
+
if (text.split(/\r?\n/).some((l) => l.trim() === exports.INCLUDE_LINE))
|
|
89
|
+
return;
|
|
90
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
91
|
+
// At the top: an Include after a Host block would only apply inside that block.
|
|
92
|
+
const head = `# Added by Huddle: SSH into devcontainers as <name>.huddle${eol}${exports.INCLUDE_LINE}${eol}`;
|
|
93
|
+
fs_1.default.writeFileSync(file, text ? `${head}${eol}${text}` : head, { mode: 0o600 });
|
|
94
|
+
}
|
|
95
|
+
function prepare(dirs) {
|
|
96
|
+
try {
|
|
97
|
+
const publicKey = ensureKey(dirs.huddle);
|
|
98
|
+
(0, protocol_1.ensurePrivateDir)(path_1.default.join(dirs.huddle, 'hosts'));
|
|
99
|
+
ensureInclude(dirs.user);
|
|
100
|
+
return publicKey;
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
throw new protocol_1.PipeError('internal', `could not prepare SSH: ${err.message ?? err}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** The `ssh.key` op: Huddle's public key. */
|
|
107
|
+
function sshKey(_args, dirs = DEFAULT_DIRS) {
|
|
108
|
+
return { publicKey: prepare(dirs) };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The `ssh.host` op: (re)writes the entry for one devcontainer,
|
|
112
|
+
* `{ alias, port, user, hostKey }`, or removes it with `{ alias, remove: true }`.
|
|
113
|
+
*/
|
|
114
|
+
function sshHost(args, dirs = DEFAULT_DIRS) {
|
|
115
|
+
const { alias, port, user, hostKey, remove } = args;
|
|
116
|
+
if (typeof alias !== 'string' || !ALIAS_RE.test(alias))
|
|
117
|
+
throw new protocol_1.PipeError('bad_request', 'alias must be <container name>.huddle');
|
|
118
|
+
const hosts = path_1.default.join(dirs.huddle, 'hosts');
|
|
119
|
+
const conf = path_1.default.join(hosts, `${alias}.conf`);
|
|
120
|
+
const known = path_1.default.join(hosts, `${alias}.known_hosts`);
|
|
121
|
+
if (remove === true) {
|
|
122
|
+
fs_1.default.rmSync(conf, { force: true });
|
|
123
|
+
fs_1.default.rmSync(known, { force: true });
|
|
124
|
+
return { publicKey: null };
|
|
125
|
+
}
|
|
126
|
+
if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535)
|
|
127
|
+
throw new protocol_1.PipeError('bad_request', 'port must be 1-65535');
|
|
128
|
+
if (typeof user !== 'string' || !USER_RE.test(user))
|
|
129
|
+
throw new protocol_1.PipeError('bad_request', 'invalid user');
|
|
130
|
+
if (typeof hostKey !== 'string' || !HOST_KEY_RE.test(hostKey.trim()))
|
|
131
|
+
throw new protocol_1.PipeError('bad_request', 'hostKey must be an ssh-ed25519 public key');
|
|
132
|
+
const publicKey = prepare(dirs);
|
|
133
|
+
try {
|
|
134
|
+
fs_1.default.writeFileSync(known, `${alias} ${hostKey.trim()}\n`, { mode: 0o600 });
|
|
135
|
+
fs_1.default.writeFileSync(conf, [
|
|
136
|
+
'# Generated by Huddle; rewritten on every Connect IDE.',
|
|
137
|
+
`Host ${alias}`,
|
|
138
|
+
// 127.0.0.1, not localhost: the relay port is published on IPv4 loopback only,
|
|
139
|
+
// and a client that tries ::1 first (Toolbox's) gets "connection refused".
|
|
140
|
+
' HostName 127.0.0.1',
|
|
141
|
+
` Port ${port}`,
|
|
142
|
+
` User ${user}`,
|
|
143
|
+
` IdentityFile ~/.huddle/ssh/${KEY_FILE}`,
|
|
144
|
+
' IdentitiesOnly yes',
|
|
145
|
+
` HostKeyAlias ${alias}`,
|
|
146
|
+
` UserKnownHostsFile ~/.huddle/ssh/hosts/${alias}.known_hosts`,
|
|
147
|
+
' StrictHostKeyChecking yes',
|
|
148
|
+
'',
|
|
149
|
+
].join('\n'), { mode: 0o600 });
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
throw new protocol_1.PipeError('internal', `could not write the SSH entry: ${err.message ?? err}`);
|
|
153
|
+
}
|
|
154
|
+
return { publicKey };
|
|
155
|
+
}
|