vyomi-tunnel 1.3.0 → 1.3.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.
@@ -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.3.0" }) {
51
+ export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.3.1" }) {
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.3.0", log = () => {}, intervalMs = 300000, now = () => Date.now() } = {}) {
19
+ export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch, version = "1.3.1", 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
@@ -224,7 +224,7 @@ const HELP = `vyomi-tunnel - connect your machine to Vyomi
224
224
  show what you can reach, and how
225
225
  ssh <name>.vyomi connect to the Codespace, a Docker instance or k3s
226
226
  vyomi-tunnel forward <name> <local>:<remote>
227
- forward a port, e.g. forward k3s 6443:6443
227
+ forward a port, e.g. forward api 9100:9000 (the Mesh API), forward k3s 6443:6443
228
228
  vyomi-tunnel gateway-backend <https origin>=<local origin>
229
229
  let a Nano API Gateway reach your local backend (see: help gateway-backend)
230
230
  vyomi-tunnel reset <code>
@@ -316,8 +316,12 @@ If you set up SSH before this version, run 'vyomi-tunnel config' once to refresh
316
316
  forward: `vyomi-tunnel forward <name> <local>:<remote>
317
317
 
318
318
  Listen on 127.0.0.1:<local> and forward to <name>:<remote> in your Mesh Codespace.
319
+ vyomi-tunnel forward api 9100:9000 the Mesh API, for SDKs / CLIs / Terraform (http://127.0.0.1:9100)
320
+ vyomi-tunnel forward api 9543:9443 the Mesh API over TLS (Cosmos, Key Vault)
319
321
  vyomi-tunnel forward k3s 6443:6443
320
- vyomi-tunnel forward host 2222:22`,
322
+ vyomi-tunnel forward host 2222:22
323
+ Targets are your own VMs and k3s clusters, plus 'api' (the simulator's API ports 9000 and 9443 only). Vyomi's own containers
324
+ (simulator, llm*) are not forwarded or listed. A local port that is already in use is refused, with a free one suggested.`,
321
325
  mcp: `vyomi-tunnel mcp
322
326
 
323
327
  Runs the Vyomi MCP server (vyomi-mcp, bundled with this package) on stdin/stdout, for Claude Code and other agents:
@@ -352,7 +356,7 @@ export async function main(argv) {
352
356
  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];
353
357
  if (topic && !t) { console.error(`vyomi-tunnel: no help for "${topic}".`); process.stdout.write(HELP); return 2; }
354
358
  process.stdout.write((t || HELP) + (t ? "\n" : "")); return cmd ? 0 : 2; }
355
- if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.3.0"); return 0; }
359
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.3.1"); return 0; }
356
360
  const WS = createRequire(import.meta.url)(process.env.WS_PKG || "ws");
357
361
  // Mesh over the user's own ssh session (`--codespace <name>` or VYOMI_MESH_CODESPACE): no relay, no token (mesh-ssh.mjs).
358
362
  const ci = rest.indexOf("--codespace");
@@ -409,7 +413,7 @@ export async function main(argv) {
409
413
  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; }
410
414
  const { createCredsSync } = await import("./creds-sync.mjs");
411
415
  try {
412
- const cs = createCredsSync({ version: process.env.VYOMI_TUNNEL_VERSION_NUM || "1.3.0" });
416
+ const cs = createCredsSync({ version: process.env.VYOMI_TUNNEL_VERSION_NUM || "1.3.1" });
413
417
  const st = await cs.reset(code, os.hostname());
414
418
  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}.`);
415
419
  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."); }
@@ -446,7 +450,10 @@ export async function main(argv) {
446
450
  if (kinds.some((k) => ["host", "instance", "k3s", "llm", "service"].includes(k))) { // Mesh also needs a plan that allows it
447
451
  const o = meshDown ? { error: auth.error } : await openMesh({ cs, configure: false });
448
452
  if (o.error) meshP = Promise.resolve({ err: o.error });
449
- else { transport = o.transport; meshP = transport.list().then((ts) => ({ ts, cs: transport.codespace })).catch((e) => ({ err: e.message })); }
453
+ else {
454
+ transport = o.transport;
455
+ meshP = transport.list().then(async (ts) => ({ ts, cs: transport.codespace, api: !!(await transport.simulatorTarget().catch(() => null)) })).catch((e) => ({ err: e.message }));
456
+ }
450
457
  }
451
458
  const ssh = await import("./mesh-ssh.mjs");
452
459
  const port = process.env.RELAY_PORT || 8090;
@@ -457,20 +464,37 @@ export async function main(argv) {
457
464
  for (const d of h.dbs || []) rows.push({ where: "browser", name: d.db, type: "db", address: `127.0.0.1:${d.host_port}`, connect: `${d.engine || "db"} client -> 127.0.0.1:${d.host_port}` });
458
465
  } catch { notes.push(`local relay not running on :${port} (run: vyomi-tunnel)`); }
459
466
  const m = await meshP;
460
- if (m && m.err) notes.push("mesh: " + m.err);
461
- else if (m) for (const t of m.ts) {
462
- // a free local port, as the MCP does: the offline appliance or another stack often holds :9000 / :6443 here
463
- const fwd = async (r) => `vyomi-tunnel forward ${t.name} ${await ssh.freeLocalPort(r)}:${r}`;
464
- const how = t.kind === "k3s" ? await fwd(6443) : t.ssh ? `ssh ${t.name}${SUFFIX}` : t.ports.length ? await fwd(t.ports[0]) : "";
465
- rows.push({ where: "mesh", name: t.name, type: t.kind, address: t.ip ? t.ip + (t.ports[0] ? ":" + t.ports[0] : "") : "", connect: how });
466
- }
467
- transport?.close();
468
- try { for (const f of fs.readdirSync(path.join(HOME, "forwards"))) { // active forwards (one file per running `forward`)
467
+ const fwds = []; // running forwards (one file per `forward` process)
468
+ try { for (const f of fs.readdirSync(path.join(HOME, "forwards"))) {
469
469
  const fp = path.join(HOME, "forwards", f); let d; try { d = JSON.parse(fs.readFileSync(fp, "utf8")); } catch { continue; }
470
470
  let alive = true; try { process.kill(d.pid, 0); } catch { alive = false; }
471
471
  if (!alive) { try { fs.rmSync(fp); } catch { /* */ } continue; }
472
- rows.push({ where: "local", name: `${d.target}`, type: "forward", address: `127.0.0.1:${d.local}`, connect: `-> ${d.target}:${d.remote} (pid ${d.pid})` });
472
+ // A forward to another Codespace (deleted, or replaced by a new Mesh) is stale: it answers on its port but reaches nothing current.
473
+ d.stale = !!(m && m.cs && d.codespace && d.codespace !== m.cs);
474
+ fwds.push(d);
473
475
  } } catch { /* none */ }
476
+ const taken = new Set(fwds.map((d) => d.local)); // one free local port per suggestion
477
+ const fwd = async (name, r) => {
478
+ const live = fwds.find((d) => !d.stale && d.target === name && d.remote === r);
479
+ if (live) return `already forwarded: 127.0.0.1:${live.local}`;
480
+ const p = await ssh.freeLocalPort(r, undefined, taken); taken.add(p); // the offline appliance or another stack often holds :9000 / :6443
481
+ return `vyomi-tunnel forward ${name} ${p}:${r}`;
482
+ };
483
+ if (m && m.err) notes.push("mesh: " + m.err);
484
+ else if (m) {
485
+ // The Mesh API (simulator ports 9000 / 9443 only): the one way SDKs, CLIs and Terraform on this machine reach a Codespace Mesh.
486
+ if (m.api) rows.push({ where: "mesh", name: ssh.API_TARGET, type: "service", address: "", connect: await fwd(ssh.API_TARGET, 9000) });
487
+ for (const t of m.ts) {
488
+ const how = t.kind === "k3s" ? await fwd(t.name, 6443) : t.ssh ? `ssh ${t.name}${SUFFIX}` : t.ports.length ? await fwd(t.name, t.ports[0]) : "";
489
+ rows.push({ where: "mesh", name: t.name, type: t.kind, address: t.ip ? t.ip + (t.ports[0] ? ":" + t.ports[0] : "") : "", connect: how });
490
+ }
491
+ }
492
+ transport?.close();
493
+ for (const d of fwds) {
494
+ const r = { where: "local", name: `${d.target}`, type: "forward", address: `127.0.0.1:${d.local}`, connect: `-> ${d.target}:${d.remote} (pid ${d.pid})` };
495
+ if (d.stale) r.connect += ` STALE: for Codespace ${d.codespace}, not your current Mesh; stop it: kill ${d.pid}`; // rows keep the schema 1 keys
496
+ rows.push(r);
497
+ }
474
498
  const out = rows.filter((r) => kinds.includes(r.type));
475
499
  if (out.some((r) => r.connect.startsWith("ssh ") && r.connect.endsWith(SUFFIX)) && !sshConfigured()) notes.push(`'ssh <name>${SUFFIX}' needs a one-time setup: vyomi-tunnel config`);
476
500
  if (json) { console.log(JSON.stringify({ schema: 1, rows: out, notes }, null, 2)); return out.length ? 0 : 1; }
package/bin/mesh-ssh.mjs CHANGED
@@ -26,6 +26,15 @@ const HOP = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade",
26
26
  // Docs: docs/architecture/v4.0/MESH-SOFTWARE-PROTECTION.md. The same allow-list is enforced on the Codespace by `vyomi-gate`.
27
27
  export const USER_CONTAINER = /^(vyomi-i-[A-Za-z0-9][A-Za-z0-9._-]{0,60}|vyomi-k3s-[0-9a-f]{10})$/;
28
28
  const GATE = "/usr/local/sbin/vyomi-gate";
29
+ // The one exception for Vyomi's own stack: `api` reaches the simulator's API ports (9000 HTTP, 9443 TLS) and nothing else, through
30
+ // the same fixed lookup the console's API tunnel uses. That is the product a user pays for (SDKs, CLIs, Terraform on the laptop);
31
+ // the shell, the files, other ports and the llm* containers stay out of reach.
32
+ export const API_TARGET = "api";
33
+ export const API_TLS_PORT = 9443;
34
+ /** A name that means one of Vyomi's own Mesh containers (never a target): simulator, llm*, as typed or as compose names. */
35
+ export const isCoreName = (name) => /^(vyomi-mesh-)?(simulator|llm(-[a-z]+)?)(-\d+)?$/i.test(String(name || ""));
36
+ /** `gh` answered 404 for the Codespace: say which one and the likely cause. */
37
+ export const missingCodespace = (cs) => `Codespace ${cs} was not found on your GitHub account (deleted?). If VYOMI_MESH_CODESPACE or --codespace names it, unset it to use your current Mesh (gh codespace list).`;
29
38
  /** Run `verb` through the Codespace's root-owned gate when it is installed; older Codespaces fall back to the plain docker command. */
30
39
  const viaGate = (verb, legacy) => `if [ -x ${GATE} ]; then sudo -n ${GATE} ${verb}; else ${legacy}; fi`;
31
40
  const dockerIp = (rawName) => viaGate(`ip ${rawName}`, `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' ${rawName} 2>/dev/null`);
@@ -112,7 +121,10 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
112
121
  }
113
122
  if (!codespace) { codespace = await findCodespace(ghBin, sp); log("using Codespace " + codespace); }
114
123
  dir = mkdtempSync(join(process.platform === "win32" ? tmpdir() : "/tmp", "vm-")); // short: a unix ControlPath is limited to ~100 chars
115
- const text = await collect(sp(ghBin, ["codespace", "ssh", "-c", codespace, "--config"], { stdio: ["ignore", "pipe", "pipe"] }));
124
+ const text = await collect(sp(ghBin, ["codespace", "ssh", "-c", codespace, "--config"], { stdio: ["ignore", "pipe", "pipe"] })).catch((e) => {
125
+ if (/HTTP 404|not found/i.test(e.message)) throw new Error(missingCodespace(codespace));
126
+ throw e;
127
+ });
116
128
  const m = /^Host\s+(\S+)/m.exec(text);
117
129
  if (!m) throw new Error("gh did not return an ssh config for this Codespace");
118
130
  const file = join(dir, "ssh_config");
@@ -147,6 +159,13 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
147
159
  /** Where does <name> listen, from the Codespace host's point of view? Same names and fixed ports as mesh-dial's resolver. */
148
160
  async function resolve(name, port = 22) {
149
161
  const n = String(name || "").toLowerCase();
162
+ await ensureConfig(); // a gh / Codespace failure is reported as itself, not as "not found"
163
+ if (n === API_TARGET) { // the Mesh API only: the simulator's two API ports, never a shell or another port
164
+ const p = Number(port) || simulatorPort;
165
+ if (p !== simulatorPort && p !== API_TLS_PORT) return null;
166
+ const s = await simulatorTarget();
167
+ return s ? { host: s.host, port: p, reserved: "api" } : null;
168
+ }
150
169
  if (n === "host" || n === "codespace") return { host: "127.0.0.1", port: hostSshPort, reserved: "host" };
151
170
  if (K3S.test(n)) { const ip = await containerIp(n); return ip ? { host: ip, port: 6443, reserved: "k3s" } : null; }
152
171
  if (n === "k3s") {
@@ -339,6 +358,7 @@ export function createSshHub({ WebSocketServer, WebSocket: WSClient = null, tran
339
358
  // ── CLI side: `vyomi-tunnel connect|forward` straight over the ssh transport (no relay, no token) ─────────────────────────────
340
359
  /** `connect`: pipe stdin/stdout to <name>:<port> in the Codespace. Resolves with the exit code (0 clean, 1 failed, 3 not found). */
341
360
  export async function connectSsh(name, { port = 22, transport, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr } = {}) {
361
+ if (isCoreName(name)) { stderr.write(`vyomi-tunnel: ${name} is part of Vyomi's own Mesh software and cannot be reached. For the Mesh API: vyomi-tunnel forward api 9100:9000\n`); return 3; }
342
362
  let t; try { t = await transport.resolve(name, port); } catch (e) { stderr.write(`vyomi-tunnel: ${e.message}\n`); return 1; }
343
363
  if (!t) { stderr.write(`vyomi-tunnel: ${name}: not found in the Codespace. If it was just started or woken from idle, its mesh may still be starting: \`vyomi-tunnel list mesh\` lists it once it is up.\n`); return 3; }
344
364
  let up; try { up = await transport.open(t.host, t.port); } catch (e) { stderr.write(`vyomi-tunnel: ${e.message}\n`); return 1; }
@@ -364,21 +384,26 @@ export async function localPortBusy(port, net = nodeNet) {
364
384
 
365
385
  /** The local port to suggest for forwarding <remote>: <remote> itself when free here, else the first free one of <remote>+100..+199
366
386
  * (9000 -> 9100+, 9443 -> 9543+, the same rule as the vyomi MCP's forward hint). */
367
- export async function freeLocalPort(remote, net = nodeNet) {
368
- if (!(await localPortBusy(remote, net))) return remote;
369
- for (let p = remote + 100; p < remote + 200; p++) if (!(await localPortBusy(p, net))) return p;
387
+ export async function freeLocalPort(remote, net = nodeNet, taken = new Set()) {
388
+ const free = async (p) => !taken.has(p) && !(await localPortBusy(p, net));
389
+ if (await free(remote)) return remote;
390
+ for (let p = remote + 100; p < remote + 200; p++) if (await free(p)) return p;
370
391
  return remote;
371
392
  }
372
393
 
373
394
  /** `forward`: listen on 127.0.0.1:<local>; each accepted socket is one ssh stream to <target>:<remote> inside the Codespace. */
374
395
  export async function forwardSsh(target, { local, remote, transport, net, stderr = process.stderr } = {}) {
375
- const t = await transport.resolve(target, remote);
376
- if (!t) { stderr.write(`vyomi-tunnel: ${target}: not found in the Codespace. If it was just started or woken from idle, its mesh may still be starting: \`vyomi-tunnel list mesh\` lists it once it is up.\n`); return { close() {}, done: Promise.resolve(3), port: 0 }; }
377
- if (local > 0 && await localPortBusy(local, net)) {
378
- const alt = await freeLocalPort(remote, net);
379
- stderr.write(`vyomi-tunnel: 127.0.0.1:${local} is already in use on this machine (another Vyomi or Docker stack?). Use another local port: vyomi-tunnel forward ${target} ${alt}:${remote}\n`);
380
- return { close() {}, done: Promise.resolve(1), port: 0 };
396
+ const fail = (code, msg) => { stderr.write(`vyomi-tunnel: ${msg}\n`); return { close() {}, done: Promise.resolve(code), port: 0 }; };
397
+ if (isCoreName(target)) {
398
+ return fail(3, `${target} is part of Vyomi's own Mesh software and is not forwarded. For the Mesh API (SDKs, CLIs, Terraform): vyomi-tunnel forward api ${await freeLocalPort(9000, net)}:9000`);
399
+ }
400
+ if (target === API_TARGET && remote !== 9000 && remote !== API_TLS_PORT) return fail(2, "api forwards only the Mesh API ports: 9000 (HTTP) and 9443 (TLS), e.g. vyomi-tunnel forward api 9100:9000");
401
+ if (local > 0 && await localPortBusy(local, net)) { // a local check first: no Codespace round trip for a port that is taken here
402
+ return fail(1, `127.0.0.1:${local} is already in use on this machine (another Vyomi or Docker stack?). Use another local port: vyomi-tunnel forward ${target} ${await freeLocalPort(remote, net)}:${remote}`);
381
403
  }
404
+ let t; try { t = await transport.resolve(target, remote); } catch (e) { return fail(1, e.message); }
405
+ if (!t && target === API_TARGET) return fail(3, "the Mesh API is not reachable: the simulator is not running in the Codespace. If the Mesh was just started or woken from idle it may still be starting: `vyomi-tunnel list mesh` shows the api row once it is up.");
406
+ if (!t) return fail(3, `${target}: not found in the Codespace. If it was just started or woken from idle, its mesh may still be starting: \`vyomi-tunnel list mesh\` lists it once it is up.`);
382
407
  const socks = new Set(); let finish; const done = new Promise((r) => { finish = r; });
383
408
  const srv = net.createServer(async (sock) => {
384
409
  socks.add(sock); sock.setNoDelay(true);
@@ -86,7 +86,7 @@ if (process.argv[2]) {
86
86
 
87
87
  // The tunnel keeps running even when its key is missing, revoked or wrong (a service manager would crash-loop it otherwise): the state is
88
88
  // shown on /health, re-checked on a timer and when ~/.vyomi/credentials changes, and the Vyomi page can re-pair it (POST /reset).
89
- const VERSION = "1.3.0";
89
+ const VERSION = "1.3.1";
90
90
  const credsSync = createCredsSync({ version: VERSION, log: (m) => console.log("[creds] " + m) });
91
91
  const PORT = Number(process.env.RELAY_PORT || 8090);
92
92
  if (!Number.isInteger(PORT) || PORT < 1 || PORT > 65535) { console.error(`vyomi-tunnel: ${friendlyError({ code: "ERR_SOCKET_BAD_PORT" })}`); process.exit(2); }
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vyomi-tunnel",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
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": {