vyomi-tunnel 1.2.3 → 1.2.5

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.
@@ -48,7 +48,7 @@ const friendly = (portal) => ({
48
48
  Throttled: "too many requests; wait a moment and retry.",
49
49
  });
50
50
 
51
- export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.2.3" }) {
51
+ export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.2.5" }) {
52
52
  const path = "/api/tunnel/session", body = JSON.stringify({ client: "vyomi-tunnel/" + version });
53
53
  const date = now().toISOString().replace(/\.\d+Z$/, "Z");
54
54
  let r;
@@ -16,7 +16,7 @@ export const ALLOWED_ORIGINS = [/^https:\/\/(www\.)?vyomi\.cloud$/, /^https?:\/\
16
16
  export const originAllowed = (origin) => !origin || ALLOWED_ORIGINS.some((re) => re.test(origin));
17
17
  export const hostIsLoopback = (host) => /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(String(host || ""));
18
18
 
19
- export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch, version = "1.2.3", log = () => {}, intervalMs = 300000, now = () => Date.now() } = {}) {
19
+ export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch, version = "1.2.5", log = () => {}, intervalMs = 300000, now = () => Date.now() } = {}) {
20
20
  const home = env.VYOMI_HOME || join(homedir(), ".vyomi");
21
21
  const file = env.VYOMI_CREDENTIALS_FILE || join(home, "credentials");
22
22
  let st = { state: "unknown", key_id: "", portal: "", checked_at: 0, error: "" };
package/bin/mesh-cli.mjs CHANGED
@@ -113,6 +113,27 @@ export function forward(target, { local, remote, relay, token, WS, allowPrivileg
113
113
  });
114
114
  }
115
115
 
116
+ export const INSTANCE_KEY = path.join(HOME, "mesh-instance-key");
117
+ // Through the Codespace's root-owned gate when it has one (the user needs no docker access); older Codespaces fall back to docker.
118
+ const KEY_CMD = "if [ -x /usr/local/sbin/vyomi-gate ]; then sudo -n /usr/local/sbin/vyomi-gate instance-key; else docker exec vyomi-mesh-simulator-1 cat /root/.vyomi/instance-keys/id_ed25519; fi";
119
+
120
+ /** Each Mesh makes its own VM login key. Fetch it from the Mesh on the first `connect` of a Codespace (and after a new Mesh), so
121
+ * `ssh <instance>.vyomi` needs no manual step. Best effort: a failure leaves ssh to report its usual error. Returns true when it wrote the key. */
122
+ export async function ensureInstanceKey(transport, codespace, { home = HOME, keyFile = path.join(home, "mesh-instance-key") } = {}) {
123
+ const mark = path.join(home, "instance_key_codespace");
124
+ let have = ""; try { have = fs.readFileSync(mark, "utf8").trim(); } catch { /* none yet */ }
125
+ if (codespace && have === codespace && fs.existsSync(keyFile)) return false;
126
+ try {
127
+ const pem = String(await transport.exec(KEY_CMD) || "").trim();
128
+ if (!/^-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(pem) || !/-----END [A-Z ]*PRIVATE KEY-----$/.test(pem)) return false;
129
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
130
+ fs.writeFileSync(keyFile, pem + "\n", { mode: 0o600 });
131
+ fs.chmodSync(keyFile, 0o600);
132
+ if (codespace) fs.writeFileSync(mark, codespace + "\n", { mode: 0o600 });
133
+ return true;
134
+ } catch { return false; }
135
+ }
136
+
116
137
  /** Every Mesh start creates a NEW Codespace, so the ssh host key behind `host.vyomi` changes each time and the key pinned in ~/.vyomi/known_hosts
117
138
  * from the last one makes ssh refuse with "REMOTE HOST IDENTIFICATION HAS CHANGED". Host-key checking stays ON: when the Codespace differs from
118
139
  * the last one seen, forget the old pins (this file is ours and only holds *.vyomi keys); a new Codespace is then trusted on first use and pinned
@@ -140,6 +161,10 @@ export async function configureSsh({ yes = false, cmd = "vyomi-tunnel", sshDir =
140
161
  " IdentitiesOnly yes",
141
162
  "",
142
163
  `Host *${SUFFIX}`,
164
+ // Mesh VMs: the login user and the per-Mesh VM key (fetched by `connect`, see ensureInstanceKey), so plain `ssh <instance>.vyomi` works.
165
+ " User ubuntu",
166
+ ` IdentityFile ${INSTANCE_KEY}`,
167
+ " IdentitiesOnly yes",
143
168
  ` ProxyCommand ${cmd} connect %h`,
144
169
  " ServerAliveInterval 30",
145
170
  " ServerAliveCountMax 4",
@@ -260,14 +285,11 @@ A type alone works too: vyomi-tunnel list vm`,
260
285
  vyomi-tunnel list mesh
261
286
  2. Once, add the *.vyomi names to your SSH config:
262
287
  vyomi-tunnel config
263
- 3. Each Mesh makes its own VM login key. Fetch it once per Mesh:
264
- ssh host.vyomi 'docker exec vyomi-mesh-simulator-1 cat /root/.vyomi/instance-keys/id_ed25519' > ~/.vyomi/mesh-instance-key
265
- chmod 600 ~/.vyomi/mesh-instance-key
266
- 4. Log in as 'ubuntu' with that key (use the instance id from step 1):
267
- ssh -i ~/.vyomi/mesh-instance-key -o IdentitiesOnly=yes ubuntu@i-0123456789ab.vyomi
288
+ 3. Log in (use the instance id from step 1). The tunnel fetches this Mesh's VM key by itself the first time:
289
+ ssh i-0123456789ab.vyomi
268
290
 
269
- A bare 'ssh i-0123456789ab.vyomi' offers neither the key nor the user, so it ends in 'Permission denied (publickey)'.
270
- A new Mesh is a new machine with a new key: repeat step 3. Problems: 'vyomi-tunnel help troubleshoot'.`,
291
+ Each Mesh makes its own VM key; the tunnel renews it when you start a new Mesh (saved as ~/.vyomi/mesh-instance-key).
292
+ If you set up SSH before this version, run 'vyomi-tunnel config' once to refresh the SSH settings. Problems: 'vyomi-tunnel help troubleshoot'.`,
271
293
  troubleshoot: `Common problems
272
294
 
273
295
  the portal refused the request (HTTP 405)
@@ -315,7 +337,7 @@ export async function main(argv) {
315
337
  if (!cmd || ["help", "-h", "--help", "-help", "-?"].includes(cmd) || rest.some((a) => ["-h", "--help", "-help"].includes(a))) { const topic = cmd === "help" ? rest[0] : (["-h", "--help", "-help", "-?"].includes(cmd) ? undefined : cmd); const t = topic && DETAILS[topic];
316
338
  if (topic && !t) { console.error(`vyomi-tunnel: no help for "${topic}".`); process.stdout.write(HELP); return 2; }
317
339
  process.stdout.write((t || HELP) + (t ? "\n" : "")); return cmd ? 0 : 2; }
318
- if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.2.3"); return 0; }
340
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.2.5"); return 0; }
319
341
  const WS = createRequire(import.meta.url)(process.env.WS_PKG || "ws");
320
342
  // Mesh over the user's own ssh session (`--codespace <name>` or VYOMI_MESH_CODESPACE): no relay, no token (mesh-ssh.mjs).
321
343
  const ci = rest.indexOf("--codespace");
@@ -329,6 +351,7 @@ export async function main(argv) {
329
351
  const transport = o.transport;
330
352
  resetKnownHostsOnNewCodespace(o.transport.codespace || (o.sess && o.sess.codespace));
331
353
  transport.onStop(() => console.error("vyomi-tunnel: your Mesh session has ended."));
354
+ if (cmd === "connect" && vmName(rest[0]) && vmName(rest[0]).toLowerCase() !== "host") await ensureInstanceKey(transport, transport.codespace || (o.sess && o.sess.codespace));
332
355
  try {
333
356
  if (cmd === "connect") { const vm = vmName(rest[0]); if (!vm) { console.error("usage: vyomi-tunnel connect <vm>[.vyomi] [port]"); return 2; } return await ssh.connectSsh(vm, { port: Number(rest[1] || 22), transport }); }
334
357
  const pos = rest.filter((x) => !x.startsWith("--")); const m = /^(\d{1,5}):(\d{1,5})$/.exec(pos[1] || "");
@@ -371,7 +394,7 @@ export async function main(argv) {
371
394
  if (!/^[A-Za-z0-9_-]{20,64}$/.test(code)) { console.error("usage: vyomi-tunnel reset <code> (get a code in the Vyomi console: Setup Tunnel > Get install command; see `vyomi-tunnel help reset`)"); return 2; }
372
395
  const { createCredsSync } = await import("./creds-sync.mjs");
373
396
  try {
374
- const cs = createCredsSync({ version: process.env.VYOMI_TUNNEL_VERSION_NUM || "1.2.3" });
397
+ const cs = createCredsSync({ version: process.env.VYOMI_TUNNEL_VERSION_NUM || "1.2.5" });
375
398
  const st = await cs.reset(code, os.hostname());
376
399
  console.log(st.state === "ok" ? `Done. The tunnel now uses access key ${st.key_id}.` : `The new key was saved (${st.key_id}) but the portal answered: ${st.error || st.state}.`);
377
400
  try { await fetch(`http://127.0.0.1:${process.env.RELAY_PORT || 8090}/reload`, { method: "POST", signal: AbortSignal.timeout(3000) }); console.log("The running tunnel reloaded it."); }
package/bin/mesh-ssh.mjs CHANGED
@@ -21,19 +21,25 @@ const CODESPACE = /^[A-Za-z0-9._-]{1,120}$/;
21
21
  const K3S = /^vyomi-k3s-[0-9a-f]{10}$/;
22
22
  const HOP = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade", "proxy-connection", "content-length", "x-vyomi-session-token"]);
23
23
 
24
- const dockerIp = (rawName) => `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' ${rawName} 2>/dev/null`;
24
+ // What a user may reach: their own VMs and k3s clusters. Vyomi's own containers (simulator, llm*, ...) are never a target.
25
+ // Docs: docs/architecture/v4.0/MESH-SOFTWARE-PROTECTION.md. The same allow-list is enforced on the Codespace by `vyomi-gate`.
26
+ export const USER_CONTAINER = /^(vyomi-i-[A-Za-z0-9][A-Za-z0-9._-]{0,60}|vyomi-k3s-[0-9a-f]{10})$/;
27
+ const GATE = "/usr/local/sbin/vyomi-gate";
28
+ /** Run `verb` through the Codespace's root-owned gate when it is installed; older Codespaces fall back to the plain docker command. */
29
+ const viaGate = (verb, legacy) => `if [ -x ${GATE} ]; then sudo -n ${GATE} ${verb}; else ${legacy}; fi`;
30
+ const dockerIp = (rawName) => viaGate(`ip ${rawName}`, `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' ${rawName} 2>/dev/null`);
25
31
 
26
32
  /** Turn `docker inspect` rows (name|image|ips|exposed ports) into the targets a user can reach, with the name to type for each. */
27
33
  export function classifyTargets(text) {
28
34
  const out = [{ name: "host", kind: "host", what: "the Codespace's own sshd", ssh: true, ports: [22] }];
29
35
  for (const line of String(text || "").split("\n")) {
30
- const [raw, image = "", ips = "", ports = ""] = line.split("|"); const n = (raw || "").replace(/^\//, "").trim();
36
+ const [raw, , ips = "", ports = ""] = line.split("|"); const n = (raw || "").replace(/^\//, "").trim();
31
37
  if (!NAME.test(n)) continue;
32
38
  const ps = ports.split(/\s+/).map((x) => Number(x.split("/")[0])).filter(Boolean);
33
39
  const ip = ips.trim().split(/\s+/)[0] || "";
34
- if (/^vyomi-k3s-[0-9a-f]{10}$/.test(n)) out.push({ name: n, kind: "k3s", what: "Kubernetes API (port 6443)", ip, ports: [6443], image });
35
- else if (n.startsWith("vyomi-i-")) out.push({ name: n.slice(8), kind: "instance", what: "Docker instance", ssh: true, ip, ports: ps.length ? ps : [22], image });
36
- else out.push({ name: n, kind: /(^|[-_])(llm|embed)/.test(n) ? "llm" : "service", what: "service container", ip, ports: ps, image });
40
+ if (!USER_CONTAINER.test(n)) continue; // Vyomi's own containers are never listed (and no image names are shown)
41
+ if (n.startsWith("vyomi-k3s-")) out.push({ name: n, kind: "k3s", what: "Kubernetes API (port 6443)", ip, ports: [6443] });
42
+ else out.push({ name: n.slice(8), kind: "instance", what: "Docker instance", ssh: true, ip, ports: ps.length ? ps : [22] });
37
43
  }
38
44
  return out;
39
45
  }
@@ -114,7 +120,8 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
114
120
  return collect(sp("ssh", [...sshArgs(c), c.host, cmd], { stdio: ["ignore", "pipe", "pipe"] }));
115
121
  }
116
122
 
117
- async function containerIp(rawName) {
123
+ async function containerIp(rawName, internal = false) {
124
+ if (!internal && !USER_CONTAINER.test(rawName)) return null; // user-facing lookups reach only allow-listed containers
118
125
  const hit = ips.get(rawName);
119
126
  if (hit && Date.now() - hit.at < ipTtlMs) return hit.ip;
120
127
  const out = (await exec(dockerIp(rawName)).catch(() => "")).trim().split(/\s+/)[0];
@@ -123,7 +130,7 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
123
130
  return out;
124
131
  }
125
132
  async function composeContainer(service) {
126
- const out = (await exec(`docker ps --filter label=com.docker.compose.service=${service} --format '{{.Names}}' | head -1`).catch(() => "")).trim();
133
+ const out = (await exec(viaGate(`compose ${service}`, `docker ps --filter label=com.docker.compose.service=${service} --format '{{.Names}}' | head -1`)).catch(() => "")).trim();
127
134
  return NAME.test(out) ? out : null;
128
135
  }
129
136
 
@@ -133,12 +140,12 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
133
140
  if (n === "host" || n === "codespace") return { host: "127.0.0.1", port: hostSshPort, reserved: "host" };
134
141
  if (K3S.test(n)) { const ip = await containerIp(n); return ip ? { host: ip, port: 6443, reserved: "k3s" } : null; }
135
142
  if (n === "k3s") {
136
- const out = (await exec(`docker ps --filter name=vyomi-k3s- --format '{{.Names}}' | head -1`).catch(() => "")).trim();
143
+ const out = (await exec(viaGate("k3s", `docker ps --filter name=vyomi-k3s- --format '{{.Names}}' | head -1`)).catch(() => "")).trim();
137
144
  const ip = K3S.test(out) ? await containerIp(out) : null;
138
145
  return ip ? { host: ip, port: 6443, reserved: "k3s" } : null;
139
146
  }
140
147
  if (!NAME.test(String(name || ""))) return null;
141
- for (const c of [`vyomi-i-${name}`, `vyomi-${name}`, name]) {
148
+ for (const c of [`vyomi-i-${name}`, name]) { // the bare name only works when it is itself a user container (vyomi-i-...)
142
149
  const ip = await containerIp(c);
143
150
  if (ip) return { host: ip, port: Number(port) || 22 };
144
151
  }
@@ -147,7 +154,7 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
147
154
 
148
155
  async function simulatorTarget() {
149
156
  const c = await composeContainer("simulator");
150
- const ip = c ? await containerIp(c) : null;
157
+ const ip = c ? await containerIp(c, true) : null; // internal: the console's own API calls, never a user-typed target
151
158
  return ip ? { host: ip, port: simulatorPort } : null;
152
159
  }
153
160
 
@@ -203,7 +210,7 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
203
210
 
204
211
  /** Everything reachable in the Mesh Codespace right now. */
205
212
  async function list() {
206
- const text = await exec(`docker ps -q | xargs -r docker inspect -f '{{.Name}}|{{.Config.Image}}|{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}|{{range $p, $_ := .Config.ExposedPorts}}{{$p}} {{end}}'`);
213
+ const text = await exec(viaGate("list", `docker ps -q | xargs -r docker inspect -f '{{.Name}}|{{.Config.Image}}|{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}|{{range $p, $_ := .Config.ExposedPorts}}{{$p}} {{end}}'`));
207
214
  return classifyTargets(text);
208
215
  }
209
216
 
@@ -45,19 +45,40 @@ import { createRequire } from "node:module";
45
45
  // resolves wherever it's installed (e.g. NODE_PATH=/tmp/node_modules for tests).
46
46
  const { WebSocketServer, WebSocket } = createRequire(import.meta.url)(process.env.WS_PKG || "ws");
47
47
 
48
+ function friendlyError(e) {
49
+ const code = e && e.code;
50
+ if (code === "EADDRINUSE") return `port ${process.env.RELAY_PORT || 8090} is already in use. A Vyomi tunnel is probably already running (check http://127.0.0.1:${process.env.RELAY_PORT || 8090}/health); stop it first, or set RELAY_PORT to another port.`;
51
+ if (code === "EACCES") return "permission denied for that port. Use a port above 1024 (RELAY_PORT).";
52
+ if (code === "ERR_SOCKET_BAD_PORT") return "RELAY_PORT must be a number from 1 to 65535.";
53
+ return (e && e.message) || String(e);
54
+ }
55
+ process.on("unhandledRejection", (e) => { console.error(`vyomi-tunnel: ${friendlyError(e)}`); if (process.env.VYOMI_DEBUG) console.error(e && e.stack); process.exit(1); });
56
+
48
57
  // Mesh / SSH client subcommands (no relay is started for these): login | config | connect <vm> | status | forward <target> <local>:<remote> | keep
49
58
  if (["login", "config", "connect", "status", "forward", "keep", "reset", "gh-login", "gateway-backend", "list", "ls", "help", "-h", "--help", "-help", "--version", "-v", "version"].includes(process.argv[2])) {
50
59
  const { main } = await import("./mesh-cli.mjs");
51
- process.exit(await main(process.argv.slice(2)));
60
+ try {
61
+ process.exit(await main(process.argv.slice(2)));
62
+ } catch (e) { // a user-facing tool never prints a stack trace (set VYOMI_DEBUG=1 to see it)
63
+ console.error(`vyomi-tunnel: ${friendlyError(e)}`);
64
+ if (process.env.VYOMI_DEBUG) console.error(e && e.stack);
65
+ process.exit(1);
66
+ }
52
67
  }
53
68
 
54
- if (process.argv[2] && !process.argv[2].startsWith("-")) { console.error(`vyomi-tunnel: unknown command "${process.argv[2]}". Run \`vyomi-tunnel help\`.`); process.exit(2); }
69
+ // Anything else on the command line is a mistake: running the relay with a stray flag would silently ignore it (or crash if one is already running).
70
+ if (process.argv[2]) {
71
+ const what = process.argv[2].startsWith("-") ? "option" : "command";
72
+ console.error(`vyomi-tunnel: unknown ${what} "${process.argv[2]}". Run \`vyomi-tunnel help\`.`);
73
+ process.exit(2);
74
+ }
55
75
 
56
76
  // The tunnel keeps running even when its key is missing, revoked or wrong (a service manager would crash-loop it otherwise): the state is
57
77
  // shown on /health, re-checked on a timer and when ~/.vyomi/credentials changes, and the Vyomi page can re-pair it (POST /reset).
58
- const VERSION = "1.2.3";
78
+ const VERSION = "1.2.5";
59
79
  const credsSync = createCredsSync({ version: VERSION, log: (m) => console.log("[creds] " + m) });
60
80
  const PORT = Number(process.env.RELAY_PORT || 8090);
81
+ if (!Number.isInteger(PORT) || PORT < 1 || PORT > 65535) { console.error(`vyomi-tunnel: ${friendlyError({ code: "ERR_SOCKET_BAD_PORT" })}`); process.exit(2); }
61
82
  // Mesh plane: the Nano console reaches the user's Mesh Codespace THROUGH this relay (the link runs on the laptop, over their own
62
83
  // `gh codespace ssh`; opened on first use). No hosted relay, no MESH_RELAY_URL. Needs a Pro/Max key + a running Mesh Codespace.
63
84
  const hub = createLazySshHub({ WebSocketServer, WebSocket, openMesh: async (o) => (await import("./mesh-cli.mjs")).openMesh(o), currentCodespace: async (o) => (await import("./mesh-cli.mjs")).currentMeshCodespace(o), log: (m) => console.log("[relay] " + m) });
@@ -343,6 +364,7 @@ const liveness = setInterval(() => {
343
364
  }, PING_MS);
344
365
  wss.on("close", () => { clearInterval(liveness); clearInterval(vmLiveness); });
345
366
 
367
+ server.on("error", (e) => { console.error(`vyomi-tunnel: ${friendlyError(e)}`); if (process.env.VYOMI_DEBUG) console.error(e && e.stack); process.exit(1); });
346
368
  credsSync.start();
347
369
  server.listen(PORT, HOST, () => {
348
370
  const shown = HOST === "0.0.0.0" ? "<this-machine-ip>" : HOST;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vyomi-tunnel",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "description": "Vyomi-Nano local reverse-tunnel — reach the in-browser cloud simulator from any local SDK/CLI. The install-once, zero-cloud counterpart to the hosted Cloudflare relay; the Nano tab auto-detects it and prefers it.",
5
5
  "type": "module",
6
6
  "bin": {