vyomi-tunnel 1.2.1 → 1.2.2
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/bin/credentials.mjs +1 -1
- package/bin/creds-sync.mjs +70 -0
- package/bin/mesh-lazy-hub.mjs +22 -6
- package/bin/mesh-ssh.mjs +1 -1
- package/bin/vyomi-tunnel.mjs +25 -6
- package/package.json +1 -1
package/bin/credentials.mjs
CHANGED
|
@@ -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.
|
|
51
|
+
export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.2.2" }) {
|
|
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;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Keeps the running tunnel honest about its credentials. It never exits on a bad key (a service manager would crash-loop it); instead it
|
|
2
|
+
// reports the key's state on /health, re-checks on a timer, when the credentials file changes, and on POST /reload, and it can be
|
|
3
|
+
// re-paired from the Vyomi page with POST /reset {code} (a single-use pairing code made by the signed-in portal user).
|
|
4
|
+
//
|
|
5
|
+
// Security: the relay answers CORS "*", so /reset must not be usable by an arbitrary website. It accepts only Vyomi origins (or none, i.e. a
|
|
6
|
+
// local program), a loopback Host header (DNS-rebinding guard), and it redeems the code ONLY at the portal named in the existing credentials
|
|
7
|
+
// file (or https://vyomi.cloud when there is none) -- never at a URL supplied by the caller.
|
|
8
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, copyFileSync } from "node:fs";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { loadCredentials, fetchSession, DEFAULT_PORTAL } from "./credentials.mjs";
|
|
12
|
+
|
|
13
|
+
const BAD = { InvalidAccessKey: "invalid", SignatureMismatch: "invalid", KeyRevoked: "revoked" };
|
|
14
|
+
const CODE_RE = /^[A-Za-z0-9_-]{20,64}$/;
|
|
15
|
+
export const ALLOWED_ORIGINS = [/^https:\/\/(www\.)?vyomi\.cloud$/, /^https?:\/\/localhost(:\d+)?$/, /^https?:\/\/127\.0\.0\.1(:\d+)?$/];
|
|
16
|
+
export const originAllowed = (origin) => !origin || ALLOWED_ORIGINS.some((re) => re.test(origin));
|
|
17
|
+
export const hostIsLoopback = (host) => /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(String(host || ""));
|
|
18
|
+
|
|
19
|
+
export function createCredsSync({ env = process.env, fetchFn = globalThis.fetch, version = "1.2.2", log = () => {}, intervalMs = 300000, now = () => Date.now() } = {}) {
|
|
20
|
+
const home = env.VYOMI_HOME || join(homedir(), ".vyomi");
|
|
21
|
+
const file = env.VYOMI_CREDENTIALS_FILE || join(home, "credentials");
|
|
22
|
+
let st = { state: "unknown", key_id: "", portal: "", checked_at: 0, error: "" };
|
|
23
|
+
let mtime = 0, timer = null, busy = null;
|
|
24
|
+
|
|
25
|
+
async function check() {
|
|
26
|
+
if (busy) return busy;
|
|
27
|
+
busy = (async () => {
|
|
28
|
+
const c = loadCredentials({ env });
|
|
29
|
+
if (!c) st = { state: "none", key_id: "", portal: DEFAULT_PORTAL, checked_at: now(), error: "NoCredentials" };
|
|
30
|
+
else {
|
|
31
|
+
try { await fetchSession({ creds: c, fetchFn, version }); st = { state: "ok", key_id: c.accessKeyId, portal: c.portal, checked_at: now(), error: "" }; }
|
|
32
|
+
catch (e) {
|
|
33
|
+
const state = BAD[e.code] || (e.code === "PlanNotAllowed" || e.code === "NoMeshSession" ? "ok" : "unreachable"); // plan/mesh state is not a key problem
|
|
34
|
+
st = { state, key_id: c.accessKeyId, portal: c.portal, checked_at: now(), error: e.code || "Error" };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
try { mtime = statSync(file).mtimeMs; } catch { mtime = 0; }
|
|
38
|
+
log(`credentials: ${st.state}${st.key_id ? " (" + st.key_id + ")" : ""}${st.error ? " " + st.error : ""}`);
|
|
39
|
+
return st;
|
|
40
|
+
})().finally(() => { busy = null; });
|
|
41
|
+
return busy;
|
|
42
|
+
}
|
|
43
|
+
|
|
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") {
|
|
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(/\/$/, "");
|
|
48
|
+
let r;
|
|
49
|
+
try { r = await fetchFn(portal + "/api/tunnel/pair/redeem", { method: "POST", headers: { "content-type": "application/json" }, signal: AbortSignal.timeout(20000),
|
|
50
|
+
body: JSON.stringify({ code, host: String(host).replace(/[^A-Za-z0-9._ -]/g, "").slice(0, 40) }) }); }
|
|
51
|
+
catch { const e = new Error("cannot reach the portal"); e.status = 502; throw e; }
|
|
52
|
+
const j = await r.json().catch(() => null);
|
|
53
|
+
if (!r.ok || !j?.credentials_file) { const e = new Error(j?.message || j?.error || `the portal refused the code (HTTP ${r.status})`); e.status = r.status === 410 ? 410 : 502; throw e; }
|
|
54
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
55
|
+
if (existsSync(file)) { try { copyFileSync(file, `${file}.bak.${Math.floor(now() / 1000)}`); } catch { /* */ } }
|
|
56
|
+
const tmp = file + ".tmp"; writeFileSync(tmp, j.credentials_file, { mode: 0o600 }); try { chmodSync(tmp, 0o600); } catch { /* */ } renameSync(tmp, file);
|
|
57
|
+
log("credentials replaced by a reset from the Vyomi page");
|
|
58
|
+
return check();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function start() {
|
|
62
|
+
check();
|
|
63
|
+
timer = setInterval(() => { // file change => re-check now; otherwise on the slow timer
|
|
64
|
+
let m = 0; try { m = statSync(file).mtimeMs; } catch { /* */ }
|
|
65
|
+
if (m !== mtime || now() - st.checked_at >= intervalMs) check();
|
|
66
|
+
}, 5000);
|
|
67
|
+
timer.unref?.();
|
|
68
|
+
}
|
|
69
|
+
return { check, reset, start, stop: () => clearInterval(timer), state: () => ({ ...st, version }) };
|
|
70
|
+
}
|
package/bin/mesh-lazy-hub.mjs
CHANGED
|
@@ -8,8 +8,8 @@ import { createSshHub } from "./mesh-ssh.mjs";
|
|
|
8
8
|
|
|
9
9
|
export function createLazySshHub({ WebSocketServer, WebSocket, openMesh, currentCodespace = null, recheckMs = 30000, log = () => {}, retryMs = 15000, now = Date.now } = {}) {
|
|
10
10
|
let hub = null, pending = null, failed = null; // failed: {at, err}
|
|
11
|
-
let hubCs = null, checkedAt = 0; // the Codespace this link was opened for; when we last re-checked it
|
|
12
|
-
const drop = () => { const h = hub; hub = null; hubCs = null; try { h && h.close(); } catch { /* */ } };
|
|
11
|
+
let hubCs = null, hubTr = null, checkedAt = 0; // the Codespace this link was opened for; when we last re-checked it
|
|
12
|
+
const drop = (why) => { const h = hub; if (h && why) log(`Mesh link dropped: ${why}`); hub = null; hubCs = null; hubTr = null; try { h && h.close(); } catch { /* */ } };
|
|
13
13
|
// A Mesh restart creates a NEW Codespace. A relay that keeps running must not keep talking to the dead one: while there is Mesh traffic,
|
|
14
14
|
// re-read the account's current Codespace (at most every recheckMs, from a fresh signed session) and drop the link when it changed or the
|
|
15
15
|
// Mesh session is over. The next request then opens a fresh link.
|
|
@@ -21,8 +21,9 @@ export function createLazySshHub({ WebSocketServer, WebSocket, openMesh, current
|
|
|
21
21
|
log(r.error ? "your Mesh session has ended." : `Mesh moved to a new Codespace (${r.codespace}); reconnecting.`); drop(); failed = null;
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
|
-
const stale = () => { checkedAt = 0; setTimeout(drop, 0); }; // the simulator stream failed: don't keep a possibly dead link
|
|
24
|
+
const stale = () => { checkedAt = 0; setTimeout(() => drop("simulator stream failed"), 0); }; // the simulator stream failed: don't keep a possibly dead link
|
|
25
25
|
function ensure() {
|
|
26
|
+
if (hub && hubTr && hubTr.closed === true) { drop("the ssh link to the Codespace closed"); failed = null; } // a dead link is never reused
|
|
26
27
|
return fresh().then(() => hub ? hub : open());
|
|
27
28
|
}
|
|
28
29
|
function open() {
|
|
@@ -33,7 +34,7 @@ export function createLazySshHub({ WebSocketServer, WebSocket, openMesh, current
|
|
|
33
34
|
if (o.error) { const e = new Error(o.error); e.code = o.code || "MeshUnavailable"; throw e; }
|
|
34
35
|
o.transport.onStop(() => { log("your Mesh session has ended."); drop(); });
|
|
35
36
|
hub = createSshHub({ WebSocketServer, WebSocket, transport: o.transport, log });
|
|
36
|
-
hubCs = (o.sess && o.sess.codespace) || o.transport.codespace || null; checkedAt = now();
|
|
37
|
+
hubTr = o.transport; hubCs = (o.sess && o.sess.codespace) || o.transport.codespace || null; checkedAt = now();
|
|
37
38
|
failed = null;
|
|
38
39
|
return hub;
|
|
39
40
|
})().catch((e) => { failed = { at: now(), err: e }; throw e; }).finally(() => { pending = null; });
|
|
@@ -49,12 +50,27 @@ export function createLazySshHub({ WebSocketServer, WebSocket, openMesh, current
|
|
|
49
50
|
/** Mesh plane = HTTP carrying X-Vyomi-Session-Token (the Nano console's compute/AI calls). Anything else is the relay's own business. */
|
|
50
51
|
http(req, res, body) {
|
|
51
52
|
if (req.headers["x-vyomi-session-token"] === undefined) return false;
|
|
52
|
-
const
|
|
53
|
-
ensure().then((h) => h.http(req, res, body)).catch((e) => {
|
|
53
|
+
const fail = (e) => {
|
|
54
54
|
if (res.headersSent) return;
|
|
55
55
|
res.writeHead(e.code === "PlanNotAllowed" ? 403 : 503, { "content-type": "application/json" });
|
|
56
56
|
res.end(JSON.stringify({ error: { ok: false, code: e.code || "MeshUnavailable", reason: String(e.message).slice(0, 200) } }));
|
|
57
|
+
};
|
|
58
|
+
// A 502 means the link to the simulator died. Drop it, open a fresh link and replay the request ONCE (the body is buffered), so a dead
|
|
59
|
+
// link heals without the caller seeing an error. A second 502 is passed through and the link is dropped again for the next request.
|
|
60
|
+
const attempt = (retried) => ensure().then((h) => {
|
|
61
|
+
const wh = res.writeHead, en = res.end; let held = false;
|
|
62
|
+
res.writeHead = (st, ...a) => {
|
|
63
|
+
if (st === 502) { if (!retried && !res.headersSent) { held = true; return res; } stale(); }
|
|
64
|
+
return wh.call(res, st, ...a);
|
|
65
|
+
};
|
|
66
|
+
res.end = (...a) => {
|
|
67
|
+
res.writeHead = wh; res.end = en;
|
|
68
|
+
if (held) { held = false; drop("simulator stream failed; reopening"); failed = null; return void attempt(true).catch(fail); }
|
|
69
|
+
return en.apply(res, a);
|
|
70
|
+
};
|
|
71
|
+
h.http(req, res, body);
|
|
57
72
|
});
|
|
73
|
+
attempt(false).catch(fail);
|
|
58
74
|
return true;
|
|
59
75
|
},
|
|
60
76
|
upgrade: (_q, socket) => { refuse(socket, 410, "MeshLinkNotUsed"); return true; },
|
package/bin/mesh-ssh.mjs
CHANGED
|
@@ -212,7 +212,7 @@ export function createSshTransport({ codespace, spawn = nodeSpawn, ghBin = null,
|
|
|
212
212
|
|
|
213
213
|
function close() { closed = true; clearTimeout(stopTimer); clearInterval(ka.timer); for (const c of live) { try { c.kill(); } catch { /* */ } } live.clear(); if (cfg && dir) sp("ssh", [...sshArgs(cfg), "-O", "exit", cfg.host], { stdio: "ignore" }).on("error", () => {}); }
|
|
214
214
|
|
|
215
|
-
return { resolve, open, exec, list, stopAt, onStop: (h) => stopHandlers.push(h), simulatorTarget, httpToSimulator, close, get codespace() { return codespace; }, keepalive: () => ({ ...ka, timer: undefined }) };
|
|
215
|
+
return { resolve, open, exec, list, stopAt, onStop: (h) => stopHandlers.push(h), simulatorTarget, httpToSimulator, close, get codespace() { return codespace; }, get closed() { return closed; }, keepalive: () => ({ ...ka, timer: undefined }) };
|
|
216
216
|
}
|
|
217
217
|
|
|
218
218
|
/** A drop-in for mesh-hub's createHub() when the link runs over ssh: same surface local-relay.mjs already calls.
|
package/bin/vyomi-tunnel.mjs
CHANGED
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
import { egress } from "./egress.mjs";
|
|
36
36
|
import { createLazySshHub } from "./mesh-lazy-hub.mjs";
|
|
37
37
|
import { createLocalGw } from "./gw-egress-node.mjs";
|
|
38
|
+
import { createCredsSync, originAllowed, hostIsLoopback } from "./creds-sync.mjs";
|
|
38
39
|
import { Readable } from "node:stream";
|
|
39
40
|
import http from "node:http";
|
|
40
41
|
import net from "node:net";
|
|
@@ -52,11 +53,10 @@ if (["login", "config", "connect", "status", "forward", "keep", "gh-login", "gat
|
|
|
52
53
|
|
|
53
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); }
|
|
54
55
|
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const VERSION = "1.2.1";
|
|
56
|
+
// 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
|
+
// 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";
|
|
59
|
+
const credsSync = createCredsSync({ version: VERSION, log: (m) => console.log("[creds] " + m) });
|
|
60
60
|
const PORT = Number(process.env.RELAY_PORT || 8090);
|
|
61
61
|
// Mesh plane: the Nano console reaches the user's Mesh Codespace THROUGH this relay (the link runs on the laptop, over their own
|
|
62
62
|
// `gh codespace ssh`; opened on first use). No hosted relay, no MESH_RELAY_URL. Needs a Pro/Max key + a running Mesh Codespace.
|
|
@@ -110,13 +110,31 @@ const server = http.createServer((req, res) => {
|
|
|
110
110
|
ok: true, relay: "vyomi-local", version: VERSION,
|
|
111
111
|
tab: open > 0, tabs: open,
|
|
112
112
|
// vm-tcp: this tunnel bridges host TCP ports to in-browser VMs (ssh to Nano EC2/GCE/Azure VMs).
|
|
113
|
-
features: ["http", "vm-tcp", "vm-egress", "db-tcp", ...(gw.enabled ? ["gw-egress"] : []), "mesh-link", "mesh-shell"],
|
|
113
|
+
features: ["http", "vm-tcp", "vm-egress", "db-tcp", ...(gw.enabled ? ["gw-egress"] : []), "mesh-link", "mesh-shell", "creds-sync"],
|
|
114
|
+
credentials: (({ state, key_id, portal, checked_at, error }) => ({ state, key_id, portal, checked_at, error }))(credsSync.state()),
|
|
114
115
|
mesh_sessions: hub.enabled() ? hub.linked().length : 0,
|
|
115
116
|
mesh_streams: hub.streams(),
|
|
116
117
|
vms: [...vmHosts.values()].filter((v) => !v.db).map((v) => ({ vm: v.vm, port: v.port, host_port: v.hostPort })),
|
|
117
118
|
dbs: [...vmHosts.values()].filter((v) => v.db).map((v) => ({ db: v.vm, engine: v.engine, host_port: v.hostPort })),
|
|
118
119
|
}));
|
|
119
120
|
}
|
|
121
|
+
// Credentials: POST /reload re-reads and re-validates the key now; POST /reset {code} re-pairs this tunnel with the signed-in Vyomi account.
|
|
122
|
+
// Vyomi origins and loopback Host only (see creds-sync.mjs): the relay is CORS "*" and must not let an arbitrary page swap the key.
|
|
123
|
+
if ((url.pathname === "/reload" || url.pathname === "/reset") && req.method === "POST") {
|
|
124
|
+
const origin = req.headers.origin;
|
|
125
|
+
if (!originAllowed(origin) || !hostIsLoopback(req.headers.host)) { cors(res, 403, { "content-type": "application/json" }); return res.end(JSON.stringify({ ok: false, error: "forbidden_origin" })); }
|
|
126
|
+
const chunks = []; req.on("data", (c) => chunks.length < 64 && chunks.push(c));
|
|
127
|
+
req.on("end", async () => {
|
|
128
|
+
const send = (st, o) => { cors(res, st, { "content-type": "application/json", ...(origin ? { "access-control-allow-origin": origin, vary: "origin" } : {}) }); res.end(JSON.stringify(o)); };
|
|
129
|
+
try {
|
|
130
|
+
let c;
|
|
131
|
+
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"); }
|
|
133
|
+
const { state, key_id, portal, checked_at, error } = c; send(200, { ok: true, credentials: { state, key_id, portal, checked_at, error } });
|
|
134
|
+
} catch (e) { send(e.status || 500, { ok: false, error: String(e.message).slice(0, 160) }); }
|
|
135
|
+
});
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
120
138
|
// Nano VM egress: allow-listed package-manager / toolchain fetches for the in-browser VMs (wasm/relay/egress.mjs).
|
|
121
139
|
if (url.pathname === "/egress") {
|
|
122
140
|
const body = [];
|
|
@@ -325,6 +343,7 @@ const liveness = setInterval(() => {
|
|
|
325
343
|
}, PING_MS);
|
|
326
344
|
wss.on("close", () => { clearInterval(liveness); clearInterval(vmLiveness); });
|
|
327
345
|
|
|
346
|
+
credsSync.start();
|
|
328
347
|
server.listen(PORT, HOST, () => {
|
|
329
348
|
const shown = HOST === "0.0.0.0" ? "<this-machine-ip>" : HOST;
|
|
330
349
|
console.log(`Vyomi-Nano local tunnel v${VERSION}`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vyomi-tunnel",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
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": {
|