Files
magpie/internal/gui/tests/saved-ssh-proxy.test.cjs
T
yetone b2b3d488c1 settings: an SSH server as a saved proxy, and a failed proxy says why
@laiuuui on X (tweet 2122704105005314155) was told to put Gemini behind
a proxy in a supported region. Their VPSes give only SSH (address, port,
password or key), and every http:// proxy they added failed with Go's
words alone.

A saved proxy can now be an SSH server. Settings > Network > Add proxy
has Proxy | SSH; SSH asks for the server, the user and the password, and
Advanced (closed) holds a private key and the trusted host key. magpie
logs in itself with golang.org/x/crypto/ssh (no ssh command) and resolves
the @id to a SOCKS5 server of its own on loopback, which takes only its
own random login and carries each CONNECT as a direct-tcpip channel, as
ssh -D does: lazy login, keepalive@openssh.com every 20s, one re-login
when a channel finds the connection dead.
- Save logs in first: a refused login is said there and nothing is kept.
- The host key is trusted on first use, kept in authorized_keys form and
  shown as its SHA256 fingerprint; another key is refused
  (HostKeyChangedError, both fingerprints said) until Trust a new key.
- The key is a secret like the password: left out of backups and
  syncs without keys, kept on a sync that has none.
- ssh:// typed as a plain address is refused: its login goes with a
  saved proxy.

A failed proxy says why (netproxy.Why: an English template the page
translates in all five languages, Go's words after it): an SSH server
typed as http:// or socks5:// ("is an SSH server, not a proxy: add it as
SSH"), a refused login, keyboard-interactive refused (OpenSSH without
PAM, "unexpected message type 51"), nothing listening, not SSH, TLS on a
plain proxy, 407, timeouts, hangups, and a server that logs in but won't
forward (AllowTcpForwarding no, or macOS 27's sshd, which hangs up on
every forward, OpenSSH's own ssh -W too). A check the user asks for
reads the server's first bytes when Go's text can't tell: Go reads a
real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an
HTTP status line with a malformed code, and an SSH server's banner can
reach Go's transport before its request goes out
("readLoopPeekFailLocked", found red 1 of 20 on mica, then 40 of 40
green). Each save is tested at once.

app.js keeps one line (api() hands a proxy_why reply to proxies.js,
where proxyWhy now lives); both script budgets are raised by that line's
52/54 bytes, with the reason in core_budget_test.go.

Run (mica, at this head on origin/main 81c666e1c):
- go test -tags nogui ./internal/netproxy/... ./internal/settings/
  ./internal/davsync/ ./internal/gui/ ./internal/provider/
  ./internal/backup/...: ok
- GOOS=linux and GOOS=windows go vet of netproxy, settings, gui; gofmt -l
  internal: clean
- GUI, chromium and webkit, en/zh/zh-TW/ja/de, 1100 and 420px:
  saved-ssh-proxy, saved-proxies, i18n-keys, provider-proxy-missing:
  64/64
- Tests use netproxy/sshtest, an SSH server on loopback that answers
  channels itself; nothing reaches the network.

Broken by hand, each red: accepting any host key
(TestSSHProxyRefusesAChangedHostKey); no login check on the SOCKS end
(TestSSHProxyLocalEndNeedsItsLogin); no SSH banner case and no banner
probe (TestProxyFailureNamesAnSSHServer, its OpenSSH-banner case); no
type-51 case (TestSSHProxySaysWhyItFailed, keyboard-interactive); no
code 2 for a hangup (TestSavedSSHProxyThatWontForward, both cases);
api() not handing proxy_why to proxies.js (saved-ssh-proxy, 20 of 20
cases red: err.why is already a failed move's reason).

Real use: Ubuntu 24.04 OpenSSH_9.6p1 (WSL magpie-desktop, a user sshd
on loopback, key login): the host key was learned, a Cloudflare trace
through the tunnel came back ip=104.194.93.45 loc=US, a wrong password
said "turned the login away", a changed host key said both
fingerprints, and http:// and socks5:// pointed at the sshd both said
"is an SSH server". mote's and mica's sshd (macOS 27, OpenSSH 10.5 and
10.3) log in and refuse every forward, now said as "won't forward
connections".

Not tried: a password login against a real sshd (the user sshd had no
shadow access), a real VPS, and the full go test ./... and full GUI
suite: both mote and mica were running other sessions' GUI suites the
whole time.
2026-11-18 01:01:30 +08:00

130 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Run with Node's test runner and Playwright on the module path; see README.md.
// An SSH server as a saved proxy (@laiuuui on X: a VPS gives only SSH, an
// IP, port, user and password). Add proxy › SSH takes its host, user and
// password; a refused login says why in the reader's language and keeps
// what was typed; a kept one is tested at once. The private key and the
// trusted host key wait under a closed Advanced.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const FP = "SHA256:Zx9bR4uE0oKp2m3Yd5qVw7nLs8tGh1jC6aF0eI2xQ4k";
function server(lang, posts) {
let cur = {
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100,
proxy: "", proxyNow: "", proxySource: "off", pluginProxy: "",
trayUsageEvery: 3, version: "test", dir: "/test", lanURLs: [],
visionModels: [], imageGenModels: [], workbuddyCheckins: [],
proxies: [{ id: "px2", name: "Home", url: "socks5://192.168.1.2:1080" }],
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
};
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data, status = 200, headers = {}) => route.fulfill({ status, headers, json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx });
if (url.pathname === "/api/settings") return json(cur);
if (url.pathname === "/api/proxies/test") {
const b = req.postDataJSON();
posts.push({ test: b.id });
return json({ ok: true, ms: 42, ip: "203.0.113.5", loc: "JP", at: 1 });
}
if (url.pathname === "/api/proxies/save") {
const b = req.postDataJSON();
posts.push({ save: b });
// the server's words for a refused login (netproxy.sshWhy)
if (b.pass === "wrong") return json({ error: "refused", code: "proxy_why", why: "the SSH server at {addr} turned the login away: check the user and the password or key", addr: "203.0.113.5:22", detail: "ssh: unable to authenticate" }, 400);
const row = { id: "px3", name: b.name, url: b.url, user: b.user, hasPass: true, hostKey: FP };
cur = { ...cur, proxies: [...cur.proxies.filter((p) => p.id !== "px3"), row] };
return json(cur, 200, { "X-Magpie-Proxy": "px3" });
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const labels = {
en: { add: "Add proxy", name: "Name", save: "Save", edit: "Edit", host: "SSH server", user: "User", pass: "Password", refused: "turned the login away", ok: "Reachable, 42 ms", adv: "Advanced", key: "Private key", trust: "Trust a new key", trusted: "The key the server shows next is trusted" },
zh: { add: "添加代理", name: "名称", save: "保存", edit: "编辑", host: "SSH 服务器", user: "用户", pass: "密码", refused: "拒绝登录", ok: "可连接,42 毫秒", adv: "高级", key: "私钥", trust: "信任新密钥", trusted: "将信任服务器下次出示的密钥" },
"zh-TW": { add: "新增代理", name: "名稱", save: "儲存", edit: "編輯", host: "SSH 伺服器", user: "使用者", pass: "密碼", refused: "拒絕登入", ok: "可連線,42 毫秒", adv: "進階", key: "私鑰", trust: "信任新金鑰", trusted: "將信任伺服器下次出示的金鑰" },
ja: { add: "プロキシを追加", name: "名前", save: "保存", edit: "編集", host: "SSH サーバー", user: "ユーザー", pass: "パスワード", refused: "ログインを拒否しました", ok: "接続できます、42 ms", adv: "詳細設定", key: "秘密鍵", trust: "新しい鍵を信頼", trusted: "サーバーが次に示す鍵を信頼します" },
de: { add: "Proxy hinzufügen", name: "Name", save: "Speichern", edit: "Bearbeiten", host: "SSH-Server", user: "Benutzer", pass: "Passwort", refused: "hat die Anmeldung abgelehnt", ok: "Erreichbar, 42 ms", adv: "Erweitert", key: "Privater Schlüssel", trust: "Neuem Schlüssel vertrauen", trusted: "Der Schlüssel, den der Server als Nächstes zeigt, wird vertraut" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(labels)) {
const l = labels[lang];
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}px: an SSH server is added as a saved proxy`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(4000);
page.setDefaultNavigationTimeout(60000);
const posts = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/?view=settings&tab=network");
const list = page.locator("#proxiesList");
await list.getByText("Home", { exact: true }).waitFor();
await list.getByRole("button", { name: l.add, exact: true }).click();
await list.getByRole("button", { name: "SSH", exact: true }).click();
// the key waits under a closed Advanced
const adv = list.locator("details.proxy-advanced");
assert.equal(await adv.evaluate((d) => d.open), false);
assert.equal(await list.getByLabel(l.key, { exact: true }).isVisible(), false);
await list.getByLabel(l.name, { exact: true }).fill("VPS");
await list.getByLabel(l.host, { exact: true }).fill("203.0.113.5:22");
await list.getByLabel(l.user, { exact: true }).fill("root");
await list.getByLabel(l.pass, { exact: true }).fill("wrong");
await list.getByRole("button", { name: l.save, exact: true }).click();
// a refused login says why, translated, and keeps what was typed
await list.locator(".proxy-form .sub.err").getByText(l.refused, { exact: false }).waitFor();
const said = await list.locator(".proxy-form .sub.err").textContent();
assert(said.includes("203.0.113.5:22") && said.includes("ssh: unable to authenticate"), said);
assert.equal(await list.getByLabel(l.user, { exact: true }).inputValue(), "root");
assert.equal(await list.getByLabel(l.host, { exact: true }).inputValue(), "203.0.113.5:22");
await list.getByLabel(l.pass, { exact: true }).fill("s3cret");
await list.getByRole("button", { name: l.save, exact: true }).click();
const row = list.locator(".saved-proxy").filter({ hasText: "VPS" });
await row.getByText("SSH root@203.0.113.5:22", { exact: false }).waitFor();
// tested at once
await row.getByText(l.ok, { exact: false }).waitFor();
const saves = posts.filter((p) => p.save).map((p) => p.save);
assert.deepEqual([saves.at(-1).url, saves.at(-1).user, saves.at(-1).pass], ["ssh://203.0.113.5:22", "root", "s3cret"]);
assert.equal(posts.filter((p) => p.test).at(-1).test, "px3");
assert.equal(await page.evaluate(() => document.body.textContent.includes("s3cret")), false, "the password is never shown");
// the trusted host key, and trusting a new one
await row.getByRole("button", { name: l.edit, exact: true }).click();
await list.locator("details.proxy-advanced summary").click();
await list.getByText(FP, { exact: false }).waitFor();
await list.getByRole("button", { name: l.trust, exact: true }).click();
await list.getByText(l.trusted, { exact: true }).waitFor();
await list.getByRole("button", { name: l.save, exact: true }).click();
await list.locator(".proxy-form").waitFor({ state: "detached" });
const last = posts.filter((p) => p.save).at(-1).save;
assert.equal(last.trustNewKey, true);
assert.equal("pass" in last, false, "a blank password keeps the saved one");
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
assert(over <= 0, `the page scrolls sideways by ${over}px`);
assert.deepEqual(errors, []);
});
}
}
}