vyomi-tunnel 1.1.0 → 1.2.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.
@@ -0,0 +1,85 @@
1
+ // vyomi-tunnel credentials: the AWS-CLI model. ~/.vyomi/credentials (INI) holds an access key; the tunnel signs a request to the portal
2
+ // and gets a short-lived session (plan, Mesh session end, Codespace, GitHub token). Contract: docs/architecture/v4.0/TUNNEL-CREDENTIALS-CONTRACT.md
3
+ import { createHmac, createHash } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ export class TunnelAuthError extends Error { constructor(code, message) { super(message); this.code = code; } }
9
+ export const DEFAULT_PORTAL = "https://vyomi.cloud";
10
+ export const keysUrl = (portal) => (portal || DEFAULT_PORTAL).replace(/\/$/, "") + "/account/tunnel-credentials";
11
+ export const KEYS_URL = keysUrl();
12
+ export const noCredentials = (portal) => `No Vyomi credentials. Download your access key and secret from ${keysUrl(portal)} (console: avatar menu > Access Key) and save the file as ~/.vyomi/credentials`;
13
+ export const NO_CREDENTIALS = noCredentials();
14
+
15
+ export function parseIni(text) {
16
+ const out = {}; let cur = null;
17
+ for (const raw of String(text || "").split(/\r?\n/)) {
18
+ const line = raw.replace(/\s[;#].*$/, "").trim(); // inline comments need a space before ; or #
19
+ if (!line || line.startsWith(";") || line.startsWith("#")) continue;
20
+ const sec = /^\[([^\]]+)\]$/.exec(line); if (sec) { cur = out[sec[1].trim()] = out[sec[1].trim()] || {}; continue; }
21
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/.exec(line); if (kv && cur) cur[kv[1].toLowerCase()] = kv[2].trim();
22
+ }
23
+ return out;
24
+ }
25
+
26
+ /** @returns {accessKeyId, secretAccessKey, githubToken, portal, profile, source} or null */
27
+ export function loadCredentials({ env = process.env, read = (f) => readFileSync(f, "utf8"), home = env.VYOMI_HOME || join(homedir(), ".vyomi") } = {}) {
28
+ const profile = env.VYOMI_PROFILE || "default";
29
+ const file = env.VYOMI_CREDENTIALS_FILE || join(home, "credentials");
30
+ let sec = {}; let source = "env";
31
+ try { sec = parseIni(read(file))[profile] || {}; source = file; } catch { /* no file: env only */ }
32
+ const accessKeyId = env.VYOMI_ACCESS_KEY_ID || sec.vyomi_access_key_id || "";
33
+ const secretAccessKey = env.VYOMI_SECRET_ACCESS_KEY || sec.vyomi_secret_access_key || "";
34
+ if (!accessKeyId || !secretAccessKey) return null;
35
+ return { accessKeyId, secretAccessKey, githubToken: sec.github_token || "", portal: (env.VYOMI_PORTAL_URL || sec.portal || DEFAULT_PORTAL).replace(/\/$/, ""), profile, source };
36
+ }
37
+
38
+ export const sha256hex = (s) => createHash("sha256").update(s).digest("hex");
39
+ export const sign = ({ secret, method, path, date, body }) => createHmac("sha256", secret).update(`${method}\n${path}\n${date}\n${sha256hex(body)}`).digest("hex");
40
+
41
+ const friendly = (portal) => ({
42
+ InvalidAccessKey: `your Vyomi access key is not valid. Create a new one at ${keysUrl(portal)}.`,
43
+ SignatureMismatch: `your Vyomi secret key does not match. Create a new access key at ${keysUrl(portal)}.`,
44
+ RequestTimeSkew: "your computer's clock is off by more than 5 minutes. Fix the clock and retry.",
45
+ KeyRevoked: `this access key was revoked. Create a new one at ${keysUrl(portal)}.`,
46
+ PlanNotAllowed: "Mesh needs a Pro or Max plan.",
47
+ NoMeshSession: "Mesh is not running. Start it in the Vyomi console, then retry.",
48
+ Throttled: "too many requests; wait a moment and retry.",
49
+ });
50
+
51
+ export async function fetchSession({ creds, fetchFn = globalThis.fetch, now = () => new Date(), version = "1.2.0" }) {
52
+ const path = "/api/tunnel/session", body = JSON.stringify({ client: "vyomi-tunnel/" + version });
53
+ const date = now().toISOString().replace(/\.\d+Z$/, "Z");
54
+ let r;
55
+ try {
56
+ r = await fetchFn(creds.portal + path, { method: "POST", body, signal: AbortSignal.timeout(15000), headers: { "content-type": "application/json",
57
+ "x-vyomi-key": creds.accessKeyId, "x-vyomi-date": date, "x-vyomi-signature": sign({ secret: creds.secretAccessKey, method: "POST", path, date, body }) } });
58
+ } catch (e) { throw new TunnelAuthError("Unreachable", `cannot reach ${creds.portal} (${String(e.message).slice(0, 80)})`); }
59
+ let j = null; try { j = await r.json(); } catch { /* not json */ }
60
+ if (!r.ok) { const code = j?.error?.code || "Error"; throw new TunnelAuthError(code, friendly(creds.portal)[code] || j?.error?.message || `the portal refused the request (HTTP ${r.status})`); }
61
+ const s = j?.session; if (!s || typeof s.expires_at !== "number") throw new TunnelAuthError("BadResponse", "unexpected response from the portal");
62
+ return { tier: s.tier || "", meshAllowed: s.allowed !== false, expiresAt: s.expires_at, sessionEnd: s.session_end ?? null, codespace: s.mesh?.codespace || "", meshState: s.mesh?.state || "",
63
+ githubToken: s.github?.token || "" };
64
+ }
65
+
66
+ /** A cached, auto-refreshing session. get() throws TunnelAuthError (NoCredentials, ...). */
67
+ export function createSessionManager({ env = process.env, loader = () => loadCredentials({ env }), fetchFn, now = () => new Date(), log = () => {}, refreshMarginS = 120 } = {}) {
68
+ let cur = null, creds = null;
69
+ async function get() {
70
+ creds = creds || loader(); if (!creds) throw new TunnelAuthError("NoCredentials", noCredentials(env.VYOMI_PORTAL_URL));
71
+ const t = now().getTime() / 1000;
72
+ if (cur && cur.expiresAt - t > refreshMarginS) return withGithub(cur);
73
+ cur = await fetchSession({ creds, fetchFn, now });
74
+ if (cur.sessionEnd && cur.sessionEnd <= t) { cur = null; throw new TunnelAuthError("SessionEnded", "your Mesh session has ended. Start Mesh again in the console."); }
75
+ log(`session ok (${cur.tier || "?"}${cur.sessionEnd ? ", ends " + new Date(cur.sessionEnd * 1000).toISOString() : ""})`);
76
+ return withGithub(cur);
77
+ }
78
+ const withGithub = (s) => ({ ...s, githubToken: s.githubToken || creds?.githubToken || "" });
79
+ return { get, creds: () => creds };
80
+ }
81
+
82
+ /** Every command needs a valid key (Nano included: a Free key is fine). Returns the session, or {error, code}. */
83
+ export async function requireSession({ log = () => {}, ...opts } = {}) {
84
+ try { return { sess: await createSessionManager({ log, ...opts }).get() }; } catch (e) { return { error: e.message, code: e.code || "Error" }; }
85
+ }
package/bin/egress.mjs ADDED
@@ -0,0 +1,73 @@
1
+ /* Allow-listed egress proxy for Nano's in-browser VMs.
2
+ *
3
+ * The VM's network is the browser's own fetch (v86 "fetch" adapter), which can't read cross-origin responses (no CORS on
4
+ * Alpine/PyPI/npm mirrors) and can't do TLS from inside the guest. The VM host points v86's cors_proxy at
5
+ * `<relay>/egress?u=<url-encoded>`; this module fetches the URL (http or https, redirects followed hop by hop) and
6
+ * streams it back with CORS headers. ONLY package-manager / toolchain hosts are reachable; everything else is refused,
7
+ * so the relay is never an open proxy and can't be pointed at localhost / private addresses.
8
+ *
9
+ * in the VM: sudo apk add openjdk8-jre (repositories use http://dl-cdn.alpinelinux.org/...)
10
+ * pip install --index-url http://pypi.org/simple <pkg>
11
+ */
12
+ export const ALLOWED_HOSTS = [
13
+ // Alpine
14
+ "alpinelinux.org",
15
+ // Python
16
+ "pypi.org", "pythonhosted.org",
17
+ // Node
18
+ "npmjs.org", "npmjs.com", "nodejs.org",
19
+ // Java
20
+ "maven.org", "maven.apache.org", "gradle.org", "adoptium.net", "azul.com",
21
+ // Go / PHP / Rust / Ruby
22
+ "golang.org", "go.dev", "packagist.org", "getcomposer.org", "crates.io", "rust-lang.org", "rubygems.org",
23
+ // Source hosting + artifacts
24
+ "github.com", "githubusercontent.com", "gitlab.com", "storage.googleapis.com", "dl.google.com",
25
+ ];
26
+ export const MAX_HOPS = 6;
27
+ export const hostAllowed = (host) => {
28
+ host = String(host || "").toLowerCase().replace(/\.$/, "");
29
+ if (!host || /^[\d.]+$/.test(host) || host.includes(":") || host === "localhost") return false; // no IPs, no localhost
30
+ return ALLOWED_HOSTS.some((d) => host === d || host.endsWith("." + d));
31
+ };
32
+
33
+ const CORS = { "access-control-allow-origin": "*", "access-control-allow-private-network": "true", "access-control-expose-headers": "*" };
34
+
35
+ /** Handle GET/HEAD/POST /egress?u=<url>; returns a web Response. */
36
+ export async function egress(request) {
37
+ const reqUrl = new URL(request.url);
38
+ let target;
39
+ try { target = new URL(reqUrl.searchParams.get("u") || ""); } catch (_) { return new Response("bad url", { status: 400, headers: CORS }); }
40
+ const method = request.method.toUpperCase();
41
+ if (!["GET", "HEAD", "POST"].includes(method)) return new Response("method not allowed", { status: 405, headers: CORS });
42
+ const body = method === "POST" ? await request.arrayBuffer() : undefined;
43
+ const headers = {};
44
+ for (const h of ["accept", "accept-encoding", "content-type", "range", "user-agent"]) { const v = request.headers.get(h); if (v) headers[h] = v; }
45
+ for (let hop = 0; hop <= MAX_HOPS; hop++) {
46
+ if (!/^https?:$/.test(target.protocol) || !hostAllowed(target.hostname))
47
+ return new Response(`egress blocked: ${target.hostname} is not on the Nano VM allow-list`, { status: 403, headers: CORS });
48
+ if (target.protocol === "http:") target = new URL(target.href.replace(/^http:/, "https:")); // the guest speaks plain HTTP (no TLS inside); upstream is always HTTPS (PyPI's CDN 403s plain HTTP)
49
+ let res;
50
+ try { res = await fetch(target, { method, headers, body, redirect: "manual" }); }
51
+ catch (e) { return new Response("egress fetch failed: " + (e && e.message), { status: 502, headers: CORS }); }
52
+ if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
53
+ target = new URL(res.headers.get("location"), target); // re-checked against the allow-list on the next hop
54
+ continue;
55
+ }
56
+ // The guest cannot do TLS, so package indexes must point it at plain-HTTP URLs on allow-listed hosts (this proxy upgrades them upstream):
57
+ // PyPI's simple index links to https://files.pythonhosted.org/... which pip would otherwise try to fetch itself.
58
+ const ct = String(res.headers.get("content-type") || "");
59
+ if (/text\/html|application\/vnd\.pypi\.simple|application\/json/i.test(ct) && /(^|\.)(pypi\.org|pythonhosted\.org)$/.test(target.hostname) && method === "GET") {
60
+ const txt = (await res.text()).replace(/https:\/\/((?:[a-z0-9-]+\.)*(?:pypi\.org|pythonhosted\.org))/gi, "http://$1");
61
+ const oh = new Headers(res.headers);
62
+ for (const k of ["content-encoding", "content-length", "transfer-encoding", "connection", "set-cookie"]) oh.delete(k);
63
+ for (const [k, v] of Object.entries(CORS)) oh.set(k, v);
64
+ return new Response(txt, { status: res.status, headers: oh });
65
+ }
66
+ const out = new Headers(res.headers);
67
+ for (const k of ["content-encoding", "content-length", "transfer-encoding", "connection", "set-cookie"]) out.delete(k);
68
+ for (const [k, v] of Object.entries(CORS)) out.set(k, v);
69
+ const len = res.headers.get("content-length"); if (len && !res.headers.get("content-encoding")) out.set("content-length", len);
70
+ return new Response(method === "HEAD" ? null : res.body, { status: res.status, headers: out });
71
+ }
72
+ return new Response("too many redirects", { status: 508, headers: CORS });
73
+ }
@@ -0,0 +1,89 @@
1
+ // Find the GitHub CLI, or install a private pinned copy. vyomi-tunnel authenticates to a Codespace through `gh codespace ssh`
2
+ // (the user's own GitHub login), so users must never have to install gh themselves.
3
+ // 1. a system `gh` on PATH that is recent enough -> use it
4
+ // 2. a managed copy in ~/.vyomi/bin -> use it
5
+ // 3. otherwise download the pinned official release, verify its SHA-256 (hashes below come from the release's checksums file),
6
+ // unpack into ~/.vyomi/bin. Never touches PATH, Homebrew or system directories.
7
+ import { spawn as nodeSpawn } from "node:child_process";
8
+ import { createHash } from "node:crypto";
9
+ import { mkdirSync, mkdtempSync, existsSync, writeFileSync, copyFileSync, chmodSync, rmSync, readdirSync, statSync } from "node:fs";
10
+ import { homedir, tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ export const GH_VERSION = "2.103.3";
14
+ export const GH_MIN = [2, 40, 0]; // codespace ssh --config / --stdio need a reasonably recent gh
15
+ const SHA256 = {
16
+ "linux_amd64.tar.gz": "4c806978ffce1cec70853302a56d70ac6da4f19bae7adca4e1a8ab00633dd91d",
17
+ "linux_arm64.tar.gz": "ee32df2323c8847f5fac6cb6b4b69ca75828e9329a8f22f677021f7b3306ce63",
18
+ "macOS_amd64.zip": "a2f86418f4350ae6e9ec60d5000bdf7665728436946a97fc27fe50e6ae752682",
19
+ "macOS_arm64.zip": "d700207eae9ae98fe2b89535c2c087c07823d4628c56364695a5a07ef311c062",
20
+ "windows_amd64.zip": "98d0cfa794721665d7973dd728c78aff7bd836d58f10f6d7a03568eccb0a22e0",
21
+ "windows_arm64.zip": "197211c98687d7770ac331fe8a3b6c198c389108c1536cdbedf659fe4703e484",
22
+ };
23
+
24
+ export const assetFor = (platform = process.platform, arch = process.arch) => {
25
+ const a = arch === "arm64" ? "arm64" : arch === "x64" ? "amd64" : null;
26
+ const os = { darwin: ["macOS", "zip"], linux: ["linux", "tar.gz"], win32: ["windows", "zip"] }[platform];
27
+ if (!a || !os) return null;
28
+ const key = `${os[0]}_${a}.${os[1]}`;
29
+ return SHA256[key] ? { key, name: `gh_${GH_VERSION}_${key}`, sha256: SHA256[key] } : null;
30
+ };
31
+
32
+ const parseVersion = (text) => { const m = /gh version (\d+)\.(\d+)\.(\d+)/.exec(String(text)); return m ? [+m[1], +m[2], +m[3]] : null; };
33
+ const atLeast = (v, min) => { for (let i = 0; i < 3; i++) { if (v[i] !== min[i]) return v[i] > min[i]; } return true; };
34
+
35
+ function run(spawn, bin, args) {
36
+ return new Promise((resolve) => {
37
+ let out = "", c;
38
+ try { c = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] }); } catch { return resolve({ ok: false, out: "" }); }
39
+ c.stdout?.on("data", (d) => { out += d; }); c.stderr?.on("data", (d) => { out += d; });
40
+ c.on("error", () => resolve({ ok: false, out })); c.on("close", (code) => resolve({ ok: code === 0, out }));
41
+ });
42
+ }
43
+ async function usable(spawn, bin) { const r = await run(spawn, bin, ["--version"]); const v = r.ok ? parseVersion(r.out) : null; return v && atLeast(v, GH_MIN) ? v.join(".") : null; }
44
+
45
+ /** @returns {Promise<{path:string, source:"system"|"managed"|"installed", version:string}>} */
46
+ export async function ensureGh({ env = process.env, spawn = nodeSpawn, fetchFn = globalThis.fetch, home = env.VYOMI_HOME || join(homedir(), ".vyomi"),
47
+ platform = process.platform, arch = process.arch, log = () => {}, extract = null } = {}) {
48
+ const exe = platform === "win32" ? "gh.exe" : "gh";
49
+ if (env.VYOMI_GH) { const v = await usable(spawn, env.VYOMI_GH); if (v) return { path: env.VYOMI_GH, source: "system", version: v }; }
50
+ const sys = await usable(spawn, "gh");
51
+ if (sys) return { path: "gh", source: "system", version: sys };
52
+ const dir = join(home, "bin"), managed = join(dir, exe);
53
+ if (existsSync(managed)) { const v = await usable(spawn, managed); if (v) return { path: managed, source: "managed", version: v }; }
54
+
55
+ const asset = assetFor(platform, arch);
56
+ if (!asset) throw new Error(`GitHub CLI is required and there is no download for ${platform}/${arch}. Install it from https://cli.github.com and retry.`);
57
+ const url = `https://github.com/cli/cli/releases/download/v${GH_VERSION}/${asset.name}`;
58
+ log(`GitHub CLI not found; installing gh ${GH_VERSION} into ${dir}`);
59
+ let buf;
60
+ try { const r = await fetchFn(url); if (!r.ok) throw new Error("HTTP " + r.status); buf = Buffer.from(await r.arrayBuffer()); }
61
+ catch (e) { throw new Error(`could not download the GitHub CLI (${e.message}). Install it from https://cli.github.com and retry.`); }
62
+ const got = createHash("sha256").update(buf).digest("hex");
63
+ if (got !== asset.sha256) throw new Error("the downloaded GitHub CLI failed its SHA-256 check; refusing to run it");
64
+ const tmp = mkdtempSync(join(tmpdir(), "vyomi-gh-"));
65
+ try {
66
+ const file = join(tmp, asset.key.endsWith("zip") ? "gh.zip" : "gh.tgz");
67
+ writeFileSync(file, buf);
68
+ if (extract) await extract(file, tmp);
69
+ else { const r = await run(spawn, "tar", ["-xf", file, "-C", tmp]); if (!r.ok) throw new Error("could not unpack the GitHub CLI: " + r.out.trim().slice(0, 200)); }
70
+ const found = findExe(tmp, exe);
71
+ if (!found) throw new Error("the GitHub CLI archive did not contain " + exe);
72
+ mkdirSync(dir, { recursive: true });
73
+ copyFileSync(found, managed); if (platform !== "win32") chmodSync(managed, 0o755);
74
+ } finally { try { rmSync(tmp, { recursive: true, force: true }); } catch { /* */ } }
75
+ const v = await usable(spawn, managed);
76
+ if (!v) throw new Error("the installed GitHub CLI does not run on this machine");
77
+ return { path: managed, source: "installed", version: v };
78
+ }
79
+ function findExe(dir, name) {
80
+ for (const f of readdirSync(dir)) { const p = join(dir, f), s = statSync(p); if (s.isDirectory()) { const r = findExe(p, name); if (r) return r; } else if (f === name && p.includes(join("bin", name))) return p; }
81
+ return null;
82
+ }
83
+
84
+ /** Is the user signed in to GitHub with the codespace scope? Returns {ok, reason}. */
85
+ export async function ghAuthOk(ghPath, { spawn = nodeSpawn, env = process.env } = {}) {
86
+ if (env.GH_TOKEN || env.GITHUB_TOKEN) return { ok: true };
87
+ const r = await run(spawn, ghPath, ["auth", "status"]);
88
+ return r.ok ? { ok: true } : { ok: false, reason: "not signed in to GitHub. Run `vyomi-tunnel login`." };
89
+ }
@@ -0,0 +1,99 @@
1
+ /* Node half of the gateway egress (see gw-egress.mjs): the backend map file, DNS, a size/time-capped transport that connects to the
2
+ * address the policy validated (no second DNS answer), the local route handler, and the origin + token gate for browsers.
3
+ *
4
+ * Map file: ~/.vyomi/gateway-backends.json {"version":1,"backends":{"https://hello-abc-uc.a.run.app":"http://127.0.0.1:3000"}}
5
+ * written by `vyomi-tunnel gateway-backend`; re-read on every request (mtime-cached), so no relay restart is needed.
6
+ */
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import http from "node:http";
11
+ import https from "node:https";
12
+ import dns from "node:dns";
13
+ import crypto from "node:crypto";
14
+ import { serveGwEgress, createRateLimiter, LIMITS, isMetadataAddress, originOf } from "./gw-egress.mjs";
15
+
16
+ export const mapFile = (env = process.env) => env.VYOMI_GATEWAY_BACKENDS_FILE || path.join(env.VYOMI_HOME || path.join(os.homedir(), ".vyomi"), "gateway-backends.json");
17
+
18
+ export function loadMap(env = process.env) {
19
+ let m = {};
20
+ try { m = (JSON.parse(fs.readFileSync(mapFile(env), "utf8")).backends) || {}; } catch (_) { /* none */ }
21
+ for (const pair of String(env.VYOMI_GATEWAY_BACKENDS || "").split(",").map((s) => s.trim()).filter(Boolean)) {
22
+ const i = pair.indexOf("="); if (i > 0) m[pair.slice(0, i)] = pair.slice(i + 1);
23
+ }
24
+ return m;
25
+ }
26
+ export function saveMap(backends, env = process.env) {
27
+ const f = mapFile(env);
28
+ fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
29
+ fs.writeFileSync(f, JSON.stringify({ version: 1, backends }, null, 2), { mode: 0o600 });
30
+ }
31
+ /** Validate one `<https origin>=<local origin>` pair. -> {from, to} or {error}. */
32
+ export function parseMapping(arg) {
33
+ const i = String(arg || "").indexOf("=");
34
+ if (i < 1) return { error: "expected <https origin>=<local origin>, e.g. https://hello-abc-uc.a.run.app=http://127.0.0.1:3000" };
35
+ let a, b;
36
+ try { a = new URL(arg.slice(0, i)); b = new URL(arg.slice(i + 1)); } catch (_) { return { error: "both sides must be URLs" }; }
37
+ if (a.protocol !== "https:") return { error: "the backend (left side) must be an https origin, as written in the API config" };
38
+ if (!/^https?:$/.test(b.protocol)) return { error: "the local target (right side) must be http or https" };
39
+ if ((a.pathname !== "/" && a.pathname !== "") || a.search || a.username || b.username || (b.pathname !== "/" && b.pathname !== "") || b.search) return { error: "give origins only (scheme://host[:port], no path, query or credentials)" };
40
+ if (isMetadataAddress(b.hostname.replace(/^\[|\]$/g, "")) || /(^|\.)metadata\.google\.internal$/.test(b.hostname)) return { error: "link-local / metadata addresses cannot be mapped" };
41
+ return { from: a.origin, to: b.origin };
42
+ }
43
+
44
+ export const resolveAll = async (host) => (await dns.promises.lookup(host, { all: true })).map((a) => a.address);
45
+
46
+ /** Capped, pinned, no-redirect transport over node http(s). */
47
+ export function nodeTransport({ method, url, headers, body, timeoutMs, maxBytes, pin }) {
48
+ return new Promise((resolve, reject) => {
49
+ const mod = url.protocol === "https:" ? https : http;
50
+ const opts = { method, headers: { ...headers, host: url.host }, timeout: timeoutMs, agent: false };
51
+ if (pin) opts.lookup = (_h, _o, cb) => (_o && _o.all ? cb(null, [{ address: pin, family: pin.includes(":") ? 6 : 4 }]) : cb(null, pin, pin.includes(":") ? 6 : 4));
52
+ if (url.protocol === "https:") opts.servername = url.hostname;
53
+ const req = mod.request(url, opts, (res) => {
54
+ const parts = []; let n = 0;
55
+ res.on("data", (c) => { n += c.length; if (n > maxBytes) { reject(Object.assign(new Error("response too large"), { code: "too-large" })); req.destroy(); res.destroy(); } else parts.push(c); });
56
+ res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: new Uint8Array(Buffer.concat(parts)) }));
57
+ res.on("error", (e) => reject(Object.assign(e, { code: "failed" })));
58
+ });
59
+ const timer = setTimeout(() => { reject(Object.assign(new Error("timeout"), { code: "timeout" })); req.destroy(); }, timeoutMs);
60
+ req.on("timeout", () => { reject(Object.assign(new Error("timeout"), { code: "timeout" })); req.destroy(); });
61
+ req.on("error", (e) => { clearTimeout(timer); reject(Object.assign(e, { code: e.code === "timeout" ? "timeout" : "failed" })); });
62
+ req.on("close", () => clearTimeout(timer));
63
+ req.end(body ? Buffer.from(body) : undefined);
64
+ });
65
+ }
66
+
67
+ const BASE_ORIGINS = [/^https:\/\/(www\.)?vyomi\.cloud$/, /^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/];
68
+ /** The local gateway-egress surface: a per-process token handed (via CORS-gated GET /gw-token) only to the Nano page's origin. */
69
+ export function createLocalGw({ env = process.env, resolve = resolveAll, transport = nodeTransport, log = (m) => console.log("[relay] " + m), token = crypto.randomBytes(24).toString("hex") } = {}) {
70
+ const extra = String(env.VYOMI_GW_ORIGINS || "").split(",").map((s) => s.trim()).filter(Boolean);
71
+ const originOk = (o) => !!o && (BASE_ORIGINS.some((r) => r.test(o)) || extra.includes(o));
72
+ const limiter = createRateLimiter(LIMITS.local.perMinute);
73
+ const packaged = /^vyomi-tunnel/.test(path.basename(process.argv[1] || "")); // the published CLI always runs signed in (packaging/tunnel/bin/vyomi-tunnel.mjs)
74
+ const enabled = env.VYOMI_RELAY_AUTH === "1" || env.VYOMI_GW_EGRESS === "1" || packaged; // the user's own CLI (signed in), or an explicit opt-in; never the appliance-bundled copy
75
+ const send = (res, o, origin) => {
76
+ res.writeHead(o.status, { ...o.headers, "access-control-allow-origin": origin || "*", "vary": "Origin", "access-control-allow-private-network": "true", "cache-control": "no-store" });
77
+ res.end(o.body);
78
+ };
79
+ /** returns true when the request was handled */
80
+ function http_(req, res, bodyBuf) {
81
+ const p = new URL(req.url, "http://x").pathname;
82
+ if (p !== "/gw-token" && p !== "/gw-egress") return false;
83
+ const origin = req.headers.origin || "";
84
+ const fail = (st, code, msg) => send(res, { status: st, headers: { "content-type": "application/json" }, body: JSON.stringify({ error: msg, code }) }, originOk(origin) ? origin : null);
85
+ if (!enabled) { fail(501, "disabled", "gateway egress is off in this relay (start the signed-in `vyomi-tunnel`)"); return true; }
86
+ if (!originOk(origin)) { fail(403, "forbidden-origin", "this page's origin may not use the gateway egress"); return true; }
87
+ if (p === "/gw-token") { if (req.method !== "GET") fail(405, "method-not-allowed", "GET only"); else send(res, { status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ token }) }, origin); return true; }
88
+ if (req.method !== "POST") { fail(405, "method-not-allowed", "POST only"); return true; }
89
+ const given = String(req.headers["x-vyomi-gw-token"] || "");
90
+ const ok = given.length === token.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(token));
91
+ if (!ok) { fail(401, "unauthorized", "missing or wrong gateway token (GET /gw-token first)"); return true; }
92
+ if (bodyBuf.length > Math.ceil(LIMITS.local.reqBody * 4 / 3) + 4096) { fail(413, "too-large", "request body too large"); return true; }
93
+ let payload; try { payload = JSON.parse(bodyBuf.toString("utf8")); } catch (_) { fail(400, "bad-request", "body must be JSON"); return true; }
94
+ serveGwEgress({ mode: "local", payload, map: loadMap(env), transport, resolve, limiter, who: token.slice(0, 8), log: (e) => log("gw-egress " + JSON.stringify(e)) })
95
+ .then((o) => send(res, o, origin), (e) => fail(500, "error", String(e && e.message || e)));
96
+ return true;
97
+ }
98
+ return { http: http_, token, enabled };
99
+ }
@@ -0,0 +1,173 @@
1
+ /* Gateway-backend egress for Nano (docs/architecture/v4.0/GATEWAY-NANO-FORWARDING.md).
2
+ *
3
+ * The Nano tab runs the API Gateway engine in Pyodide, which has no sockets. When a request matches a route, the engine hands the
4
+ * backend call (method, url, headers, body) to the browser bridge (wasm/gw-bridge.js), which POSTs it HERE:
5
+ *
6
+ * mode "local" (wasm/relay/local-relay.mjs, `vyomi-tunnel`): ONLY origins the user mapped with
7
+ * `vyomi-tunnel gateway-backend <https origin>=<local origin>`; anything else -> 502 not-mapped. Never an open proxy.
8
+ * mode "hosted" (wasm/relay/worker.js, relay.vyomi.cloud): PUBLIC https backends on an allow-list, 443 only, no IP literals,
9
+ * no redirects, tight limits, and a registered Nano session is required.
10
+ *
11
+ * This module is runtime-neutral (no node imports): the policy lives here, the socket work is a pluggable `transport`
12
+ * (wasm/relay/gw-egress-node.mjs for node, fetch for the Worker).
13
+ *
14
+ * Wire: POST {method,url,headers,body(base64),timeout} -> 200 {status,headers,body(base64)} (the BACKEND's answer, whatever its status)
15
+ * or a refusal {error, code} with 400/401/403/405/413/429/502/504.
16
+ * Redirects are NEVER followed: a 3xx from the backend is returned to the gateway verbatim (ESPv2 does the same), so a backend cannot
17
+ * bounce the relay onto a private address.
18
+ */
19
+
20
+ export const METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]; // no CONNECT, no TRACE
21
+ export const LIMITS = {
22
+ local: { reqBody: 6 * 1024 * 1024, respBody: 16 * 1024 * 1024, timeoutMs: 30000, perMinute: 240 },
23
+ hosted: { reqBody: 1 * 1024 * 1024, respBody: 4 * 1024 * 1024, timeoutMs: 15000, perMinute: 60 },
24
+ };
25
+ const HOP_REQ = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "trailers",
26
+ "transfer-encoding", "upgrade", "host", "content-length", "cookie", "expect", "x-vyomi-gw-token", "x-vyomi-session"]);
27
+ const HOP_RESP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "trailers",
28
+ "transfer-encoding", "upgrade", "content-length", "set-cookie", "set-cookie2"]);
29
+ export const stripRequestHeaders = (h) => {
30
+ const out = {};
31
+ for (const [k, v] of Object.entries(h || {})) { const lk = k.toLowerCase(); if (!HOP_REQ.has(lk) && !lk.startsWith("x-vyomi-") && typeof v === "string") out[lk] = v; }
32
+ return out;
33
+ };
34
+ export const stripResponseHeaders = (h) => {
35
+ const out = {};
36
+ for (const [k, v] of Object.entries(h || {})) { const lk = k.toLowerCase(); if (!HOP_RESP.has(lk)) out[lk] = Array.isArray(v) ? v.join(", ") : String(v); }
37
+ return out;
38
+ };
39
+
40
+ // ── address classification ───────────────────────────────────────────────────
41
+ const v4 = (ip) => { const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip); return m ? m.slice(1).map(Number) : null; };
42
+ /** true when `ip` (v4 or v6 literal) is loopback / private / link-local / metadata / unspecified / CGNAT / multicast / reserved. */
43
+ export function isPrivateAddress(ip) {
44
+ ip = String(ip || "").toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
45
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip); if (mapped) ip = mapped[1];
46
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
47
+ if (mappedHex) { const a = parseInt(mappedHex[1], 16), b = parseInt(mappedHex[2], 16); ip = `${a >> 8}.${a & 255}.${b >> 8}.${b & 255}`; }
48
+ const q = v4(ip);
49
+ if (q) {
50
+ const [a, b, c] = q;
51
+ return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
52
+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19));
53
+ }
54
+ if (ip.includes(":")) {
55
+ if (ip === "::" || ip === "::1") return true;
56
+ const first = ip.split(":")[0] || "0";
57
+ const w = parseInt(first || "0", 16);
58
+ return (w & 0xfe00) === 0xfc00 || (w & 0xffc0) === 0xfe80 || (w & 0xff00) === 0xff00 || ip.startsWith("64:ff9b:") || ip.startsWith("2001:db8");
59
+ }
60
+ return false;
61
+ }
62
+ /** link-local + cloud-metadata: refused even for a MAPPED (user-approved) local target. */
63
+ export function isMetadataAddress(ip) {
64
+ ip = String(ip || "").toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
65
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip); if (mapped) ip = mapped[1];
66
+ const q = v4(ip);
67
+ if (q) return (q[0] === 169 && q[1] === 254) || q[0] === 0;
68
+ return ip === "::" || /^fe[89ab][0-9a-f]:/.test(ip) || ip === "fd00:ec2::254";
69
+ }
70
+ const isIpLiteral = (h) => /^[\d.]+$/.test(h) || h.includes(":") || /^0x[0-9a-f]+$/i.test(h);
71
+ const INTERNAL_NAME = /(^|\.)(localhost|local|internal|localdomain|lan|home|corp|intranet|metadata\.google\.internal)$/;
72
+
73
+ // Public serverless / PaaS hosts a Nano user's backend is likely to live on. The hosted relay reaches ONLY these (+ env GW_EGRESS_ALLOW).
74
+ export const DEFAULT_HOSTED_ALLOW = [
75
+ ".run.app", ".cloudfunctions.net", ".appspot.com", // GCP: Cloud Run, Functions, App Engine
76
+ ".azurewebsites.net", ".azurecontainerapps.io", ".azure-api.net", // Azure: App Service / Functions, Container Apps, APIM
77
+ ".execute-api.amazonaws.com", ".lambda-url.on.aws", ".elasticbeanstalk.com", // AWS (regional hosts end in .amazonaws.com; checked as suffix below)
78
+ ".vercel.app", ".netlify.app", ".onrender.com", ".fly.dev", ".railway.app", ".herokuapp.com", ".workers.dev", ".pages.dev", ".deno.dev", ".glitch.me",
79
+ ];
80
+ export const hostAllowed = (host, allow) => {
81
+ host = String(host || "").toLowerCase().replace(/\.$/, "");
82
+ return (allow || DEFAULT_HOSTED_ALLOW).some((d) => { d = d.toLowerCase(); return d.startsWith(".") ? host.endsWith(d) && host.length > d.length : host === d; })
83
+ || /\.execute-api\.[a-z0-9-]+\.amazonaws\.com$/.test(host) || /\.lambda-url\.[a-z0-9-]+\.on\.aws$/.test(host);
84
+ };
85
+ /** Hosted-relay target rule. -> null if allowed, else the refusal reason. */
86
+ export function hostedTargetProblem(u, allow) {
87
+ if (u.protocol !== "https:") return "https only";
88
+ if (u.username || u.password) return "credentials in the URL are not allowed";
89
+ if (u.port && u.port !== "443") return "port 443 only";
90
+ const h = u.hostname.toLowerCase().replace(/\.$/, "");
91
+ if (isIpLiteral(h) || INTERNAL_NAME.test(h) || isPrivateAddress(h)) return "private, loopback and IP-literal targets are blocked";
92
+ if (!hostAllowed(h, allow)) return `${h} is not on the hosted relay's backend allow-list`;
93
+ return null;
94
+ }
95
+ export const originOf = (u) => `${u.protocol}//${u.host}`;
96
+
97
+ // ── rate limit ───────────────────────────────────────────────────────────────
98
+ export function createRateLimiter(perMinute, now = () => Date.now()) {
99
+ const hits = new Map();
100
+ return { take(key) {
101
+ const t = now(), arr = (hits.get(key) || []).filter((x) => t - x < 60000);
102
+ if (arr.length >= perMinute) { hits.set(key, arr); return false; }
103
+ arr.push(t); hits.set(key, arr);
104
+ if (hits.size > 5000) for (const [k, v] of hits) if (!v.length || t - v[v.length - 1] > 60000) hits.delete(k);
105
+ return true;
106
+ } };
107
+ }
108
+
109
+ const json = (status, obj, extra) => ({ status, headers: { "content-type": "application/json", ...(extra || {}) }, body: JSON.stringify(obj) });
110
+ const refuse = (status, code, error, extra) => json(status, { error, code }, extra);
111
+ const b64 = {
112
+ dec: (s) => { const bin = atob(String(s || "")); const a = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) a[i] = bin.charCodeAt(i); return a; },
113
+ enc: (bytes) => { let s = ""; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); return btoa(s); },
114
+ };
115
+
116
+ /**
117
+ * The policy core. `authorized` has already been decided by the caller (token + Origin / session); `who` is the rate-limit + log key.
118
+ * @param {object} o
119
+ * mode "local" | "hosted"
120
+ * payload parsed JSON {method,url,headers,body,timeout}
121
+ * map (local) {httpsOrigin: targetOrigin}
122
+ * allow (hosted) host allow-list override
123
+ * transport async ({method, url:URL, headers, body:Uint8Array|undefined, timeoutMs, maxBytes, pin}) -> {status, headers, body:Uint8Array}
124
+ * throws {code:"timeout"|"too-large"|"blocked"|"failed", message}
125
+ * resolve (local) async (hostname) -> [ip...] (DNS), used to re-check a mapped target against metadata/link-local
126
+ * limiter, who, log
127
+ * @returns {status, headers, body(string)} an HTTP-ish answer for the relay to send
128
+ */
129
+ export async function serveGwEgress(o) {
130
+ const { mode, payload, map, allow, transport, resolve, limiter, who = "?", log = () => {} } = o;
131
+ const lim = LIMITS[mode], t0 = Date.now();
132
+ const note = (st, why, u) => { try { log({ mode, who, method: payload && payload.method, origin: u ? originOf(u) : "", path: u ? u.pathname : "", status: st, why: why || "", ms: Date.now() - t0 }); } catch (_) {} };
133
+ if (limiter && !limiter.take(who)) { note(429, "rate"); return refuse(429, "rate-limited", "gateway egress rate limit reached; retry in a minute", { "retry-after": "30" }); }
134
+ const method = String((payload && payload.method) || "GET").toUpperCase();
135
+ if (!METHODS.includes(method)) { note(405, "method"); return refuse(405, "method-not-allowed", `${method} is not allowed`); }
136
+ let u;
137
+ try { u = new URL(String(payload.url || "")); } catch (_) { note(400, "bad-url"); return refuse(400, "bad-url", "invalid backend url"); }
138
+ if (u.username || u.password) { note(400, "userinfo", u); return refuse(400, "bad-url", "credentials in the backend URL are not allowed"); }
139
+ let body;
140
+ if (payload.body) {
141
+ if (String(payload.body).length > Math.ceil(lim.reqBody * 4 / 3) + 4) { note(413, "req-size", u); return refuse(413, "too-large", "request body too large"); }
142
+ try { body = b64.dec(payload.body); } catch (_) { return refuse(400, "bad-body", "body is not base64"); }
143
+ if (body.length > lim.reqBody) { note(413, "req-size", u); return refuse(413, "too-large", "request body too large"); }
144
+ if (!body.length) body = undefined;
145
+ }
146
+ let target = u, pin = null;
147
+ if (mode === "local") {
148
+ const dst = map && Object.prototype.hasOwnProperty.call(map, originOf(u)) ? map[originOf(u)] : null;
149
+ if (!dst) { note(502, "not-mapped", u); return refuse(502, "not-mapped", `backend ${originOf(u)} is not mapped. Run: vyomi-tunnel gateway-backend ${originOf(u)}=<local origin, e.g. http://127.0.0.1:3000>`); }
150
+ let d; try { d = new URL(dst); } catch (_) { return refuse(502, "bad-map", "the mapping target is invalid"); }
151
+ target = new URL(d.origin + u.pathname + u.search);
152
+ const host = target.hostname.replace(/^\[|\]$/g, "");
153
+ let ips = isIpLiteral(host) ? [host] : [];
154
+ if (!ips.length && resolve) { try { ips = await resolve(host); } catch (_) { note(502, "dns", u); return refuse(502, "dns", `cannot resolve ${host}`); } }
155
+ if (ips.some(isMetadataAddress)) { note(403, "metadata", u); return refuse(403, "blocked", "the mapped target resolves to a link-local / metadata address"); }
156
+ pin = ips[0] || null; // connect to the address we validated, not a second DNS answer (rebinding)
157
+ } else {
158
+ const why = hostedTargetProblem(u, allow);
159
+ if (why) { note(403, why, u); return refuse(403, "blocked", why); }
160
+ }
161
+ const headers = stripRequestHeaders(payload.headers);
162
+ const timeoutMs = Math.min(lim.timeoutMs, Math.max(1000, Math.round(Number(payload.timeout || 15) * 1000)));
163
+ let r;
164
+ try { r = await transport({ method, url: target, headers, body, timeoutMs, maxBytes: lim.respBody, pin, redirect: "manual" }); }
165
+ catch (e) {
166
+ const code = (e && e.code) || "failed";
167
+ const st = code === "timeout" ? 504 : code === "too-large" ? 413 : code === "blocked" ? 403 : 502;
168
+ note(st, code, u);
169
+ return refuse(st, code === "failed" ? "unreachable" : code, code === "timeout" ? "backend timed out" : code === "too-large" ? "backend response too large" : `backend unreachable: ${String((e && e.message) || e).slice(0, 120)}`);
170
+ }
171
+ note(r.status, "ok", u);
172
+ return json(200, { status: r.status, headers: stripResponseHeaders(r.headers), body: b64.enc(r.body || new Uint8Array(0)) });
173
+ }
package/bin/keeper.mjs ADDED
@@ -0,0 +1,87 @@
1
+ /* Codespace TTL keeper: vyomi-tunnel keep [--user vscode] [--key <file>] [--interval 240]
2
+ *
3
+ * Holds ONE real ssh session to the Codespace host's sshd (reserved `codespace` target, tunnel architecture 9b) and writes a small
4
+ * line to it every ~interval seconds, because GitHub's idle timer is reset by SSH traffic the client sends, not by our relay's
5
+ * WebSocket traffic. `ssh` runs the handshake and key auth end to end; the keeper only supplies the schedule, reconnects and stop.
6
+ *
7
+ * Nothing here talks to GitHub or needs `gh`. It never logs the session token (the ProxyCommand reads it from the environment).
8
+ * It stops at the token's session_end, on abort, or after `maxFailures` consecutive failed connects.
9
+ *
10
+ * Status (for the portal's `keepalive` field): { state: "connecting"|"alive"|"reconnecting"|"stopped", reason?, lastWriteAt, writes, failures }.
11
+ */
12
+ import { spawn } from "node:child_process";
13
+
14
+ const sleep = (ms, signal) => new Promise((res) => {
15
+ const t = setTimeout(res, ms);
16
+ signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true });
17
+ });
18
+
19
+ /** ssh argv for the host target. `proxy` is the ProxyCommand string, e.g. "vyomi-tunnel connect codespace". */
20
+ export function sshArgs({ user = "vscode", key, proxy, target = "codespace" } = {}) {
21
+ const a = ["-T", "-o", "BatchMode=yes", "-o", `ProxyCommand=${proxy}`, "-o", "StrictHostKeyChecking=accept-new",
22
+ "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=3", "-o", "ConnectTimeout=30"];
23
+ if (key) a.push("-i", key, "-o", "IdentitiesOnly=yes");
24
+ a.push(`${user}@${target}.vyomi`, "cat > /dev/null"); // the remote side just swallows what we send
25
+ return a;
26
+ }
27
+
28
+ /**
29
+ * Run the keeper until stopped. `spawnFn(cmd, args, opts)` defaults to child_process.spawn (tests inject a fake ssh).
30
+ * Returns { stop(), done: Promise<status>, status() }.
31
+ */
32
+ export function keep({
33
+ ssh = "ssh", user, key, proxy, target, intervalMs = 240000, jitter = 0.1, sessionEndMs = Infinity,
34
+ maxFailures = 10, settleMs = 500, backoffMs = [2000, 5000, 15000, 30000, 60000], spawnFn = spawn, now = Date.now, onStatus = () => {}, log = () => {},
35
+ env = process.env,
36
+ } = {}) {
37
+ const ac = new AbortController();
38
+ const st = { state: "connecting", lastWriteAt: 0, writes: 0, failures: 0 };
39
+ const set = (patch) => { Object.assign(st, patch); try { onStatus({ ...st }); } catch { /* observer errors never stop the keeper */ } };
40
+ const ended = () => now() >= sessionEndMs;
41
+
42
+ const done = (async () => {
43
+ let consecutive = 0;
44
+ while (!ac.signal.aborted && !ended()) {
45
+ set({ state: consecutive ? "reconnecting" : "connecting" });
46
+ const child = spawnFn(ssh, sshArgs({ user, key, proxy, target }), { stdio: ["pipe", "ignore", "pipe"], env });
47
+ let exited = false, errTail = "";
48
+ const exit = new Promise((res) => {
49
+ child.on("exit", (code, sig) => { exited = true; res({ code, sig }); });
50
+ child.on("error", (e) => { exited = true; errTail = e.message; res({ code: -1 }); });
51
+ });
52
+ child.stderr?.on("data", (d) => { errTail = (errTail + d).slice(-300); });
53
+ child.stdin?.on("error", () => { /* the exit handler reports it */ });
54
+
55
+ // First write immediately: proves the channel works and counts as activity at once.
56
+ const write = () => {
57
+ if (exited || !child.stdin?.writable) return false;
58
+ child.stdin.write(`vyomi-keepalive ${new Date(now()).toISOString()}\n`);
59
+ set({ state: "alive", lastWriteAt: now(), writes: st.writes + 1 });
60
+ return true;
61
+ };
62
+ let wrote = false;
63
+ const startedAt = now();
64
+ await Promise.race([sleep(settleMs, ac.signal), exit]); // let ssh authenticate before the first write
65
+ if (!exited && !ac.signal.aborted) wrote = write();
66
+ while (!exited && !ac.signal.aborted && !ended()) {
67
+ const wait = intervalMs * (1 + (Math.random() * 2 - 1) * jitter);
68
+ const cap = Number.isFinite(sessionEndMs) ? Math.max(0, sessionEndMs - now()) : wait;
69
+ await Promise.race([sleep(Math.min(wait, cap), ac.signal), exit]);
70
+ if (!exited && !ac.signal.aborted && !ended()) write();
71
+ }
72
+ if (!exited) { try { child.stdin?.end(); child.kill(); } catch { /* already gone */ } await exit; }
73
+ if (ac.signal.aborted || ended()) break;
74
+
75
+ // ssh ended on its own: count a failure only if it never carried a write (a connect/auth failure), then back off.
76
+ consecutive = wrote && now() - startedAt > 5000 ? 0 : consecutive + 1;
77
+ set({ failures: st.failures + 1 });
78
+ log(`keeper: ssh ended (${errTail.trim().split("\n").pop() || "no output"}); failure ${consecutive}`);
79
+ if (consecutive >= maxFailures) { set({ state: "stopped", reason: "too many failed connects" }); return { ...st }; }
80
+ await sleep(backoffMs[Math.min(consecutive - 1, backoffMs.length - 1)], ac.signal);
81
+ }
82
+ set({ state: "stopped", reason: ac.signal.aborted ? "stopped" : "session ended" });
83
+ return { ...st };
84
+ })();
85
+
86
+ return { stop: () => ac.abort(), done, status: () => ({ ...st }) };
87
+ }