vyomi-tunnel 1.2.2 → 1.2.4

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 CHANGED
@@ -78,3 +78,10 @@ Port range: `VM_PORT_MIN` / `VM_PORT_MAX`.
78
78
  Durable Object; this local build holds one registered tab.
79
79
 
80
80
  Canonical source: `wasm/relay/local-relay.mjs` in the appliance repo.
81
+
82
+ ## Re-pair the tunnel (`reset`)
83
+
84
+ If the tunnel's access key was revoked, belongs to another account, or is missing, the Vyomi console shows a strip with **Reset tunnel**.
85
+ From a terminal: `vyomi-tunnel reset <code>` (or paste the install link `https://vyomi.cloud/i/<code>`). Get the one-time code from the
86
+ console: Setup Tunnel > Get install command. It writes a new key to `~/.vyomi/credentials` (mode 600, old file kept as `credentials.bak.<time>`)
87
+ and a running tunnel reloads it by itself.
@@ -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.2" }) {
51
+ export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.2.4" }) {
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.2", log = () => {}, intervalMs = 300000, now = () => Date.now() } = {}) {
19
+ export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch, version = "1.2.4", 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: "" };
@@ -42,9 +42,12 @@ export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch,
42
42
  }
43
43
 
44
44
  /** Redeem a pairing code at the PINNED portal and replace the credentials file (mode 600, previous file kept as .bak). */
45
- async function reset(code, host = "tunnel reset") {
45
+ async function reset(code, host = "tunnel reset", origin = "") {
46
46
  if (!CODE_RE.test(String(code || ""))) { const e = new Error("bad code"); e.status = 400; throw e; }
47
- const portal = (loadCredentials({ env })?.portal || env.VYOMI_PORTAL_URL || DEFAULT_PORTAL).replace(/\/$/, "");
47
+ // The portal is pinned to the one in the credentials file, EXCEPT that a request coming from the real https://vyomi.cloud page may re-point
48
+ // a tunnel that was paired elsewhere (e.g. a dev portal) at vyomi.cloud: that origin is the genuine portal and cannot be spoofed by a page.
49
+ const home = /^https:\/\/(www\.)?vyomi\.cloud$/.test(origin || "") ? DEFAULT_PORTAL : "";
50
+ const portal = (home || loadCredentials({ env })?.portal || env.VYOMI_PORTAL_URL || DEFAULT_PORTAL).replace(/\/$/, "");
48
51
  let r;
49
52
  try { r = await fetchFn(portal + "/api/tunnel/pair/redeem", { method: "POST", headers: { "content-type": "application/json" }, signal: AbortSignal.timeout(20000),
50
53
  body: JSON.stringify({ code, host: String(host).replace(/[^A-Za-z0-9._ -]/g, "").slice(0, 40) }) }); }
package/bin/mesh-cli.mjs CHANGED
@@ -113,6 +113,26 @@ 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
+ const KEY_CMD = "docker exec vyomi-mesh-simulator-1 cat /root/.vyomi/instance-keys/id_ed25519";
118
+
119
+ /** 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
120
+ * `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. */
121
+ export async function ensureInstanceKey(transport, codespace, { home = HOME, keyFile = path.join(home, "mesh-instance-key") } = {}) {
122
+ const mark = path.join(home, "instance_key_codespace");
123
+ let have = ""; try { have = fs.readFileSync(mark, "utf8").trim(); } catch { /* none yet */ }
124
+ if (codespace && have === codespace && fs.existsSync(keyFile)) return false;
125
+ try {
126
+ const pem = String(await transport.exec(KEY_CMD) || "").trim();
127
+ if (!/^-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(pem) || !/-----END [A-Z ]*PRIVATE KEY-----$/.test(pem)) return false;
128
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
129
+ fs.writeFileSync(keyFile, pem + "\n", { mode: 0o600 });
130
+ fs.chmodSync(keyFile, 0o600);
131
+ if (codespace) fs.writeFileSync(mark, codespace + "\n", { mode: 0o600 });
132
+ return true;
133
+ } catch { return false; }
134
+ }
135
+
116
136
  /** 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
137
  * from the last one makes ssh refuse with "REMOTE HOST IDENTIFICATION HAS CHANGED". Host-key checking stays ON: when the Codespace differs from
118
138
  * 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 +160,10 @@ export async function configureSsh({ yes = false, cmd = "vyomi-tunnel", sshDir =
140
160
  " IdentitiesOnly yes",
141
161
  "",
142
162
  `Host *${SUFFIX}`,
163
+ // Mesh VMs: the login user and the per-Mesh VM key (fetched by `connect`, see ensureInstanceKey), so plain `ssh <instance>.vyomi` works.
164
+ " User ubuntu",
165
+ ` IdentityFile ${INSTANCE_KEY}`,
166
+ " IdentitiesOnly yes",
143
167
  ` ProxyCommand ${cmd} connect %h`,
144
168
  " ServerAliveInterval 30",
145
169
  " ServerAliveCountMax 4",
@@ -198,6 +222,8 @@ const HELP = `vyomi-tunnel - connect your machine to Vyomi
198
222
  forward a port, e.g. forward k3s 6443:6443
199
223
  vyomi-tunnel gateway-backend <https origin>=<local origin>
200
224
  let a Nano API Gateway reach your local backend (see: help gateway-backend)
225
+ vyomi-tunnel reset <code>
226
+ re-pair this tunnel with your Vyomi account (see: help reset)
201
227
  vyomi-tunnel start the local relay for the Nano console
202
228
 
203
229
  Everything needs a key (Free works for Nano; Mesh needs Pro or Max).
@@ -205,6 +231,15 @@ Get one: 'vyomi-tunnel help credentials'.
205
231
  Log in to a Mesh VM over SSH: 'vyomi-tunnel help ssh'. Something failing? 'vyomi-tunnel help troubleshoot'.
206
232
  `;
207
233
  const DETAILS = {
234
+ reset: `Re-pair this tunnel with your Vyomi account (new access key, same machine)
235
+
236
+ vyomi-tunnel reset <code>
237
+ vyomi-tunnel reset https://vyomi.cloud/i/<code>
238
+
239
+ Use it when the tunnel's access key was revoked, belongs to another account, or is missing. Get a one-time code by opening the Vyomi
240
+ console, choosing Setup Tunnel > Get install command, and copying the part after /i/ (or the whole link). The code is single use and
241
+ valid for 15 minutes. It is redeemed only at the portal named in ~/.vyomi/credentials (https://vyomi.cloud when there is none), the old
242
+ file is kept as credentials.bak.<time>, the new one is written with mode 600, and a running tunnel reloads it by itself.`,
208
243
  "gateway-backend": `Let a Nano API Gateway call a backend that runs on your machine
209
244
 
210
245
  vyomi-tunnel gateway-backend https://hello-abc123-uc.a.run.app=http://127.0.0.1:3000
@@ -249,14 +284,11 @@ A type alone works too: vyomi-tunnel list vm`,
249
284
  vyomi-tunnel list mesh
250
285
  2. Once, add the *.vyomi names to your SSH config:
251
286
  vyomi-tunnel config
252
- 3. Each Mesh makes its own VM login key. Fetch it once per Mesh:
253
- ssh host.vyomi 'docker exec vyomi-mesh-simulator-1 cat /root/.vyomi/instance-keys/id_ed25519' > ~/.vyomi/mesh-instance-key
254
- chmod 600 ~/.vyomi/mesh-instance-key
255
- 4. Log in as 'ubuntu' with that key (use the instance id from step 1):
256
- ssh -i ~/.vyomi/mesh-instance-key -o IdentitiesOnly=yes ubuntu@i-0123456789ab.vyomi
287
+ 3. Log in (use the instance id from step 1). The tunnel fetches this Mesh's VM key by itself the first time:
288
+ ssh i-0123456789ab.vyomi
257
289
 
258
- A bare 'ssh i-0123456789ab.vyomi' offers neither the key nor the user, so it ends in 'Permission denied (publickey)'.
259
- A new Mesh is a new machine with a new key: repeat step 3. Problems: 'vyomi-tunnel help troubleshoot'.`,
290
+ Each Mesh makes its own VM key; the tunnel renews it when you start a new Mesh (saved as ~/.vyomi/mesh-instance-key).
291
+ If you set up SSH before this version, run 'vyomi-tunnel config' once to refresh the SSH settings. Problems: 'vyomi-tunnel help troubleshoot'.`,
260
292
  troubleshoot: `Common problems
261
293
 
262
294
  the portal refused the request (HTTP 405)
@@ -304,7 +336,7 @@ export async function main(argv) {
304
336
  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];
305
337
  if (topic && !t) { console.error(`vyomi-tunnel: no help for "${topic}".`); process.stdout.write(HELP); return 2; }
306
338
  process.stdout.write((t || HELP) + (t ? "\n" : "")); return cmd ? 0 : 2; }
307
- if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.2.1"); return 0; }
339
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(process.env.VYOMI_TUNNEL_VERSION || "vyomi-tunnel 1.2.4"); return 0; }
308
340
  const WS = createRequire(import.meta.url)(process.env.WS_PKG || "ws");
309
341
  // Mesh over the user's own ssh session (`--codespace <name>` or VYOMI_MESH_CODESPACE): no relay, no token (mesh-ssh.mjs).
310
342
  const ci = rest.indexOf("--codespace");
@@ -318,6 +350,7 @@ export async function main(argv) {
318
350
  const transport = o.transport;
319
351
  resetKnownHostsOnNewCodespace(o.transport.codespace || (o.sess && o.sess.codespace));
320
352
  transport.onStop(() => console.error("vyomi-tunnel: your Mesh session has ended."));
353
+ if (cmd === "connect" && vmName(rest[0]) && vmName(rest[0]).toLowerCase() !== "host") await ensureInstanceKey(transport, transport.codespace || (o.sess && o.sess.codespace));
321
354
  try {
322
355
  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 }); }
323
356
  const pos = rest.filter((x) => !x.startsWith("--")); const m = /^(\d{1,5}):(\d{1,5})$/.exec(pos[1] || "");
@@ -354,6 +387,20 @@ export async function main(argv) {
354
387
  console.log(`mapped ${m.from} -> ${m.to}\n(${g.mapFile()}; a running relay uses it immediately)`);
355
388
  return 0;
356
389
  }
390
+ if (cmd === "reset") { // re-pair with the account: same code flow as the console's Reset tunnel button
391
+ const arg = String(rest.find((x) => !x.startsWith("-")) || "");
392
+ const code = arg.replace(/[?#].*$/, "").replace(/\/+$/, "").split("/").pop();
393
+ 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; }
394
+ const { createCredsSync } = await import("./creds-sync.mjs");
395
+ try {
396
+ const cs = createCredsSync({ version: process.env.VYOMI_TUNNEL_VERSION_NUM || "1.2.4" });
397
+ const st = await cs.reset(code, os.hostname());
398
+ 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}.`);
399
+ 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."); }
400
+ catch { console.log("No tunnel is running here; it will use the new key when it starts."); }
401
+ return st.state === "ok" ? 0 : 1;
402
+ } catch (e) { console.error("vyomi-tunnel: " + (e.message || "reset failed")); return e.status === 410 ? 1 : 2; }
403
+ }
357
404
  if (cmd === "login" || cmd === "gh-login") { // there is no login: credentials live in a file, like ~/.aws/credentials
358
405
  console.error("vyomi-tunnel has no login. Save your access key as ~/.vyomi/credentials (console: avatar menu > Access Key). Run `vyomi-tunnel help credentials`.");
359
406
  return 2;
@@ -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
- if (["login", "config", "connect", "status", "forward", "keep", "gh-login", "gateway-backend", "list", "ls", "help", "-h", "--help", "-help", "--version", "-v", "version"].includes(process.argv[2])) {
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.2";
78
+ const VERSION = "1.2.4";
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) });
@@ -129,7 +150,7 @@ const server = http.createServer((req, res) => {
129
150
  try {
130
151
  let c;
131
152
  if (url.pathname === "/reload") c = await credsSync.check();
132
- else { let b = {}; try { b = JSON.parse(Buffer.concat(chunks).toString() || "{}"); } catch { /* */ } c = await credsSync.reset(b.code, "tunnel reset"); }
153
+ else { let b = {}; try { b = JSON.parse(Buffer.concat(chunks).toString() || "{}"); } catch { /* */ } c = await credsSync.reset(b.code, "tunnel reset", origin); }
133
154
  const { state, key_id, portal, checked_at, error } = c; send(200, { ok: true, credentials: { state, key_id, portal, checked_at, error } });
134
155
  } catch (e) { send(e.status || 500, { ok: false, error: String(e.message).slice(0, 160) }); }
135
156
  });
@@ -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.2",
3
+ "version": "1.2.4",
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": {