cmux-ssh-here 0.2.0 → 0.3.0

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.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/bin.js +202 -23
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -23,6 +23,7 @@ Open the link — cmux connects on its own. `Ctrl-C` in the terminal stops the s
23
23
  - The token is passed in the deep link's `user=`; the server only accepts the correct token.
24
24
  - cmux deep links deliberately carry no passwords or keys, so the secret is the token itself.
25
25
  - Full PTY shell via `node-pty`, with window-resize support.
26
+ - Real exec channel (raw pipes) and a filesystem-backed SFTP server, so `scp`/`sftp` work — this is what lets `cmux ssh` upload and run its remote helper. A shell-only server is not enough for cmux.
26
27
  - When `tmux` is available, the interactive shell runs inside it: sessions persist and are shared across connections, and the session list (`choose-tree`) is shown on connect. Without `tmux`, it falls back to a plain login shell.
27
28
 
28
29
  ## Requirements
@@ -39,3 +40,4 @@ Open the link — cmux connects on its own. `Ctrl-C` in the terminal stops the s
39
40
  ## Options
40
41
 
41
42
  - `PORT=2222 npx cmux-ssh-here` — fixed port (random free port by default).
43
+ - `CMUX_SSH_DEBUG=1 npx cmux-ssh-here` — log incoming auth/env/exec/shell requests to stderr (troubleshooting).
package/bin.js CHANGED
@@ -3,13 +3,21 @@
3
3
  // Spins up an ephemeral token-auth SSH server and prints a cmux deep link.
4
4
  // Anyone on the LAN who opens the link lands in a shell as the current user.
5
5
  // ponytail: the token is a bearer secret. Trusted LAN only, not the internet.
6
+ //
7
+ // This is a near-full SSH server (auth + pty/shell + exec + SFTP) on purpose:
8
+ // cmux's `cmux ssh` flow scp-uploads a helper daemon (cmuxd-remote) and then
9
+ // talks a binary protocol to it over an exec channel. A shell-only server is
10
+ // not enough; SFTP (for scp) and raw-pipe exec (binary-clean) are required.
6
11
  import ssh2 from "ssh2"; // ponytail: ssh2 is CJS, no named exports
7
12
  const { Server } = ssh2;
13
+ const { OPEN_MODE, STATUS_CODE } = ssh2.utils.sftp;
8
14
  import { generateKeyPairSync, randomBytes } from "node:crypto";
9
15
  import os from "node:os";
16
+ import fs from "node:fs";
17
+ import { spawn } from "node:child_process";
10
18
  import { chmodSync } from "node:fs";
11
19
  import { createRequire } from "node:module";
12
- import { dirname, join } from "node:path";
20
+ import { dirname, join, resolve } from "node:path";
13
21
 
14
22
  // ponytail: node-pty's prebuilt spawn-helper sometimes unpacks without +x
15
23
  // (packaging bug) -> "posix_spawnp failed". Fix it before importing.
@@ -21,7 +29,9 @@ if (process.platform !== "win32") {
21
29
  }
22
30
  const { default: pty } = await import("node-pty");
23
31
 
24
- const token = randomBytes(9).toString("base64url"); // secret carried in user=<token>
32
+ // ponytail: hex (not base64url) cmux rejects a user that starts with "-",
33
+ // and an ssh client treats a leading-dash username as a flag. Hex is URL/ssh-safe.
34
+ const token = randomBytes(12).toString("hex"); // secret carried in user=<token>
25
35
  const { privateKey } = generateKeyPairSync("rsa", {
26
36
  // ponytail: rsa PEM parses cleanly in ssh2 (ed25519 PKCS8 is hit-or-miss)
27
37
  modulusLength: 2048,
@@ -30,15 +40,24 @@ const { privateKey } = generateKeyPairSync("rsa", {
30
40
  });
31
41
 
32
42
  const shellPath = process.env.SHELL || "/bin/zsh";
43
+ const debug = process.env.CMUX_SSH_DEBUG ? (...a) => console.error("[debug]", ...a) : () => {};
33
44
 
34
45
  const lanIP = () =>
35
46
  Object.values(os.networkInterfaces())
36
47
  .flat()
37
48
  .find((i) => i?.family === "IPv4" && !i.internal && !i.address.startsWith("169.254"))?.address;
38
49
 
39
- // Run a command in a PTY and bridge it to an ssh2 channel.
40
- function bridge(stream, args, term) {
41
- const child = pty.spawn(shellPath, args, {
50
+ // Interactive shell over a PTY (plain `ssh user@host` with no remote command).
51
+ function startShell(stream, term) {
52
+ // ponytail: route the interactive shell through tmux so sessions persist and
53
+ // are shared across LAN connections; show the session list on connect.
54
+ // Falls back to a plain login shell when tmux is absent.
55
+ const start =
56
+ 'if command -v tmux >/dev/null 2>&1; then ' +
57
+ 'exec tmux new-session -A -s main \\; choose-tree -Zs; ' +
58
+ 'else printf "[cmux-ssh-here] tmux not found; opening a plain shell\\n"; ' +
59
+ 'exec "$SHELL" -l; fi';
60
+ const child = pty.spawn(shellPath, ["-lc", start], {
42
61
  name: term.term,
43
62
  cols: term.cols,
44
63
  rows: term.rows,
@@ -48,52 +67,212 @@ function bridge(stream, args, term) {
48
67
  child.onData((d) => stream.write(d));
49
68
  stream.on("data", (d) => child.write(d.toString()));
50
69
  child.onExit(({ exitCode }) => {
51
- try {
52
- stream.exit(exitCode ?? 0);
53
- } catch {}
70
+ try { stream.exit(exitCode ?? 0); } catch {}
71
+ stream.end();
72
+ });
73
+ return child;
74
+ }
75
+
76
+ // exec channel: run a command with RAW pipes (no PTY) so binary protocols
77
+ // (cmux's daemon stdio) stay byte-exact. Faithful to how sshd runs exec.
78
+ function startExec(stream, command, env) {
79
+ const child = spawn(shellPath, ["-c", command], { cwd: os.homedir(), env: { ...process.env, ...env } });
80
+ child.stdout.on("data", (d) => stream.write(d));
81
+ child.stderr.on("data", (d) => stream.stderr.write(d));
82
+ stream.on("data", (d) => child.stdin.write(d));
83
+ stream.on("end", () => child.stdin.end());
84
+ child.on("close", (code) => {
85
+ try { stream.exit(code ?? 0); } catch {}
86
+ stream.end();
87
+ });
88
+ child.on("error", () => {
89
+ try { stream.exit(127); } catch {}
54
90
  stream.end();
55
91
  });
56
92
  return child;
57
93
  }
58
94
 
59
- const server = new Server({ hostKeys: [privateKey] }, (client) => {
60
- client.on("authentication", (ctx) =>
61
- ctx.username === token ? ctx.accept() : ctx.reject()
95
+ // Minimal real-filesystem SFTP server so `scp`/`sftp` work (cmux uploads its
96
+ // daemon via scp, which uses the SFTP subsystem on modern OpenSSH).
97
+ function attachSFTP(accept) {
98
+ const sftp = accept();
99
+ // ponytail: client half-closes (EOF) after its last request. A real sshd sends
100
+ // exit-status 0 then EOF/close for the sftp subsystem; without it scp/sftp
101
+ // report failure ("Exit status -1") even though the transfer succeeded.
102
+ // These are ssh2 internals (no public exit() on the SFTP wrapper), but stable.
103
+ sftp.on("end", () => {
104
+ try {
105
+ sftp._protocol.exitStatus(sftp.outgoing.id, 0);
106
+ sftp._protocol.channelEOF(sftp.outgoing.id);
107
+ } catch {}
108
+ sftp.end();
109
+ });
110
+ const handles = new Map();
111
+ let next = 0;
112
+ const open = (obj) => {
113
+ const id = next++;
114
+ handles.set(id, obj);
115
+ const b = Buffer.alloc(4);
116
+ b.writeUInt32BE(id, 0);
117
+ return b;
118
+ };
119
+ const get = (h) => (h.length === 4 ? handles.get(h.readUInt32BE(0)) : undefined);
120
+ const fail = (reqid, err) =>
121
+ sftp.status(
122
+ reqid,
123
+ err?.code === "ENOENT"
124
+ ? STATUS_CODE.NO_SUCH_FILE
125
+ : err?.code === "EACCES" || err?.code === "EPERM"
126
+ ? STATUS_CODE.PERMISSION_DENIED
127
+ : STATUS_CODE.FAILURE
128
+ );
129
+ const toAttrs = (st) => ({
130
+ mode: st.mode,
131
+ uid: st.uid,
132
+ gid: st.gid,
133
+ size: st.size,
134
+ atime: Math.floor(st.atimeMs / 1000),
135
+ mtime: Math.floor(st.mtimeMs / 1000),
136
+ });
137
+ const fsFlags = (flags) => {
138
+ const C = fs.constants;
139
+ let f = flags & OPEN_MODE.READ && flags & OPEN_MODE.WRITE ? C.O_RDWR : flags & OPEN_MODE.WRITE ? C.O_WRONLY : C.O_RDONLY;
140
+ if (flags & OPEN_MODE.APPEND) f |= C.O_APPEND;
141
+ if (flags & OPEN_MODE.CREAT) f |= C.O_CREAT;
142
+ if (flags & OPEN_MODE.TRUNC) f |= C.O_TRUNC;
143
+ if (flags & OPEN_MODE.EXCL) f |= C.O_EXCL;
144
+ return f;
145
+ };
146
+
147
+ sftp.on("REALPATH", (reqid, p) => {
148
+ let r;
149
+ try {
150
+ r = fs.realpathSync(p === "" ? "." : p);
151
+ } catch {
152
+ r = p.startsWith("/") ? resolve(p) : join(os.homedir(), p === "." ? "" : p);
153
+ }
154
+ sftp.name(reqid, [{ filename: r, longname: r, attrs: {} }]);
155
+ });
156
+ sftp.on("OPEN", (reqid, filename, flags, attrs) => {
157
+ fs.open(filename, fsFlags(flags), attrs?.mode ?? 0o644, (err, fd) => {
158
+ if (err) return fail(reqid, err);
159
+ sftp.handle(reqid, open({ fd, path: filename }));
160
+ });
161
+ });
162
+ sftp.on("WRITE", (reqid, handle, offset, data) => {
163
+ const h = get(handle);
164
+ if (!h || h.fd == null) return sftp.status(reqid, STATUS_CODE.FAILURE);
165
+ fs.write(h.fd, data, 0, data.length, offset, (err) => (err ? fail(reqid, err) : sftp.status(reqid, STATUS_CODE.OK)));
166
+ });
167
+ sftp.on("READ", (reqid, handle, offset, length) => {
168
+ const h = get(handle);
169
+ if (!h || h.fd == null) return sftp.status(reqid, STATUS_CODE.FAILURE);
170
+ const buf = Buffer.alloc(length);
171
+ fs.read(h.fd, buf, 0, length, offset, (err, bytes) => {
172
+ if (err) return fail(reqid, err);
173
+ if (!bytes) return sftp.status(reqid, STATUS_CODE.EOF);
174
+ sftp.data(reqid, buf.subarray(0, bytes));
175
+ });
176
+ });
177
+ sftp.on("FSTAT", (reqid, handle) => {
178
+ const h = get(handle);
179
+ if (!h || h.fd == null) return sftp.status(reqid, STATUS_CODE.FAILURE);
180
+ fs.fstat(h.fd, (err, st) => (err ? fail(reqid, err) : sftp.attrs(reqid, toAttrs(st))));
181
+ });
182
+ sftp.on("FSETSTAT", (reqid, handle, attrs) => {
183
+ const h = get(handle);
184
+ if (!h || h.fd == null) return sftp.status(reqid, STATUS_CODE.FAILURE);
185
+ if (attrs?.mode != null) {
186
+ try { fs.fchmodSync(h.fd, attrs.mode); } catch (e) { return fail(reqid, e); }
187
+ }
188
+ sftp.status(reqid, STATUS_CODE.OK);
189
+ });
190
+ sftp.on("CLOSE", (reqid, handle) => {
191
+ const h = get(handle);
192
+ if (h?.fd != null) try { fs.closeSync(h.fd); } catch {}
193
+ if (h) handles.delete(handle.readUInt32BE(0));
194
+ sftp.status(reqid, STATUS_CODE.OK);
195
+ });
196
+ const onStat = (reqid, p) => fs.stat(p, (err, st) => (err ? fail(reqid, err) : sftp.attrs(reqid, toAttrs(st))));
197
+ sftp.on("STAT", onStat);
198
+ sftp.on("LSTAT", (reqid, p) => fs.lstat(p, (err, st) => (err ? fail(reqid, err) : sftp.attrs(reqid, toAttrs(st)))));
199
+ sftp.on("SETSTAT", (reqid, p, attrs) => {
200
+ if (attrs?.mode != null) {
201
+ try { fs.chmodSync(p, attrs.mode); } catch (e) { return fail(reqid, e); }
202
+ }
203
+ sftp.status(reqid, STATUS_CODE.OK);
204
+ });
205
+ sftp.on("MKDIR", (reqid, p, attrs) =>
206
+ fs.mkdir(p, { mode: attrs?.mode ?? 0o755 }, (err) => (err ? fail(reqid, err) : sftp.status(reqid, STATUS_CODE.OK)))
207
+ );
208
+ sftp.on("RMDIR", (reqid, p) => fs.rmdir(p, (err) => (err ? fail(reqid, err) : sftp.status(reqid, STATUS_CODE.OK))));
209
+ sftp.on("REMOVE", (reqid, p) => fs.unlink(p, (err) => (err ? fail(reqid, err) : sftp.status(reqid, STATUS_CODE.OK))));
210
+ sftp.on("RENAME", (reqid, from, to) =>
211
+ fs.rename(from, to, (err) => (err ? fail(reqid, err) : sftp.status(reqid, STATUS_CODE.OK)))
62
212
  );
213
+ sftp.on("OPENDIR", (reqid, p) => {
214
+ try {
215
+ sftp.handle(reqid, open({ dir: p, entries: fs.readdirSync(p), idx: 0 }));
216
+ } catch (e) {
217
+ fail(reqid, e);
218
+ }
219
+ });
220
+ sftp.on("READDIR", (reqid, handle) => {
221
+ const h = get(handle);
222
+ if (!h || !h.entries) return sftp.status(reqid, STATUS_CODE.FAILURE);
223
+ if (h.idx >= h.entries.length) return sftp.status(reqid, STATUS_CODE.EOF);
224
+ const names = h.entries.slice(h.idx).map((name) => {
225
+ let st;
226
+ try { st = fs.lstatSync(join(h.dir, name)); } catch {}
227
+ return { filename: name, longname: name, attrs: st ? toAttrs(st) : {} };
228
+ });
229
+ h.idx = h.entries.length;
230
+ sftp.name(reqid, names);
231
+ });
232
+ }
233
+
234
+ const serverCfg = { hostKeys: [privateKey] };
235
+ if (process.env.CMUX_SSH2_DEBUG) serverCfg.debug = (m) => { if (/SFTP|CHANNEL|EOF|CLOSE/.test(m)) console.error("[ssh2]", m); };
236
+ const server = new Server(serverCfg, (client) => {
237
+ client.on("authentication", (ctx) => {
238
+ debug("auth", ctx.method, ctx.username);
239
+ return ctx.username === token ? ctx.accept() : ctx.reject();
240
+ });
63
241
  client.on("session", (accept) => {
64
242
  const session = accept();
65
- // Defaults; overwritten by pty/env requests before shell/exec.
66
243
  const term = { term: "xterm-256color", cols: 80, rows: 24, env: {} };
67
244
  let child;
68
245
 
69
246
  session.on("pty", (a, _r, info) => {
247
+ debug("pty", info.term, info.cols, info.rows);
70
248
  term.term = info.term || term.term;
71
249
  term.cols = info.cols || term.cols;
72
250
  term.rows = info.rows || term.rows;
73
251
  a?.();
74
252
  });
75
253
  session.on("env", (a, _r, info) => {
254
+ debug("env", info.key, "=", info.val);
76
255
  term.env[info.key] = info.val;
77
256
  a?.();
78
257
  });
79
258
  session.on("window-change", (a, _r, info) => {
80
- child?.resize(info.cols, info.rows);
259
+ child?.resize?.(info.cols, info.rows);
81
260
  a?.();
82
261
  });
83
262
  session.on("shell", (acc) => {
84
- // ponytail: route the interactive shell through tmux so sessions persist
85
- // and are shared across LAN connections; show the session list on connect.
86
- // Falls back to a plain login shell when tmux is absent.
87
- const start =
88
- 'if command -v tmux >/dev/null 2>&1; then ' +
89
- 'exec tmux new-session -A -s main \\; choose-tree -Zs; ' +
90
- 'else printf "[cmux-ssh-here] tmux not found; opening a plain shell (no server-side sessions)\\n"; ' +
91
- 'exec "$SHELL" -l; fi';
92
- child = bridge(acc(), ["-lc", start], term);
263
+ debug("shell");
264
+ child = startShell(acc(), term);
93
265
  });
94
266
  session.on("exec", (acc, _r, info) => {
95
- child = bridge(acc(), ["-c", info.command], term);
267
+ debug("exec", info.command);
268
+ child = startExec(acc(), info.command, term.env);
269
+ });
270
+ session.on("sftp", (acc) => {
271
+ debug("sftp");
272
+ attachSFTP(acc);
96
273
  });
274
+ // ponytail: no 'subsystem' handler — ssh2 auto-rejects non-sftp subsystems,
275
+ // and a handler here also intercepts the sftp request and kills the channel.
97
276
  });
98
277
  });
99
278
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cmux-ssh-here",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Spin up a token-auth SSH server and print a cmux deep link to connect over LAN",
5
5
  "type": "module",
6
6
  "bin": {