diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 15f40600d..95aab8c0d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20421,21 +20421,23 @@ const UPDATE_EVERY = [30, 60, 360, 1440]; // that names a proxy of its own (or Direct) keeps it whatever this says (netproxy.With), so the // line says it holds for those without one (#1832). let proxyCustom = false; // Custom picked, not saved yet -// Keep SOCKS credentials in their own fields; URL userinfo is the existing -// saved format, with reserved characters escaped before it reaches Go/Bun. +// The login has fields of its own; the setting stays one address with it as +// userinfo, split as Go's url.Parse does (last @, then first :). function proxyFields(value) { - try { - const u = new URL(value); - if (/^socks5h?:$/.test(u.protocol)) { - const encodedUsername = u.username, encodedPassword = u.password; - // A saved proxy can contain non-UTF-8 credential bytes. Keep their - // escapes, still masked, and preserve those bytes until edited. - const decode = (v) => { try { return decodeURIComponent(v); } catch { return v; } }; - u.username = ""; u.password = ""; - return { address: u.href, username: decode(encodedUsername), password: decode(encodedPassword), encodedUsername, encodedPassword, socks: true }; - } - } catch {} - return { address: value, username: "", password: "", socks: /^socks5h?:\/\//i.test(value) }; + const [, scheme = "", auth, rest] = /^([a-z][\w+.-]*:\/\/)?([^/?#]*)(.*)$/is.exec((value || "").trim()); + const at = auth.lastIndexOf("@"), info = at < 0 ? "" : auth.slice(0, at), c = info.indexOf(":"); + const eu = c < 0 ? info : info.slice(0, c), ep = c < 0 ? "" : info.slice(c + 1); + // non-UTF-8 escapes are kept as saved until edited + const dec = (v) => { try { return decodeURIComponent(v); } catch { return v; } }; + return { address: scheme + auth.slice(at + 1) + rest, username: dec(eu), password: dec(ep), eu, ep }; +} +// each typed part percent-encoded; one left as loaded keeps its escapes +function proxyAddress(a, f, user, pass) { + a = (a || "").trim(); + if (!a || !(user || pass)) return a; + const enc = (t, l, e) => t === l && e !== undefined ? e : encodeURIComponent(t); + const [, scheme = "", rest] = /^([a-z][\w+.-]*:\/\/)?(.*)$/is.exec(a); + return scheme + enc(user, f.username, f.eu) + (pass ? ":" + enc(pass, f.password, f.ep) : "") + "@" + rest; } function proxyDisplay(value) { // Also mask an older backend's proxyNow, and environment/system proxies. @@ -20478,29 +20480,20 @@ function renderProxy(s, keep) { field.className = "proxy-credential"; field.setAttribute("aria-label", field.placeholder); } - const updateAuth = () => { - const parsed = proxyFields(i.value.trim()); - auth.hidden = !parsed.socks; + // a pasted login moves into the fields + i.oninput = () => { + const parsed = proxyFields(i.value); if (parsed.username || parsed.password) { fields = parsed; i.value = parsed.address; username.value = parsed.username; password.value = parsed.password; } }; - i.oninput = updateAuth; - updateAuth(); let saving = false; const save = () => { - let v = i.value.trim(); - if (!v || saving) return; - if (!auth.hidden) { - try { - const u = new URL(v); - u.username = username.value === fields.username && fields.encodedUsername !== undefined ? fields.encodedUsername : encodeURIComponent(username.value); - u.password = password.value === fields.password && fields.encodedPassword !== undefined ? fields.encodedPassword : encodeURIComponent(password.value); - v = u.href; - } catch {} // the settings API explains an invalid address - } + if (!i.value.trim() || saving) return; + let v; + try { v = proxyAddress(i.value, fields, username.value, password.value); } catch { return; } if (v === s.proxy) return; saving = true; proxyCustom = false; diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index be2933f20..64f46e96f 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -7,12 +7,14 @@ checks that request hooks have no provider badge. `MAGPIE_GATEWAY_ASSETS` select an older asset directory for a failing regression comparison; user settings and live gateways are never accessed. -`settings-proxy-auth.test.cjs` checks optional SOCKS5/SOCKS5h usernames and -passwords in Settings, using the real page with isolated API fixtures. It -covers saving and reloading, escaped and non-UTF-8 credentials, masked -addresses/status, clearing authentication, Tab and Escape, mode switches, -HTTP compatibility, and narrow windows in English and Chinese on Chromium -and WebKit. +`settings-proxy-auth.test.cjs` checks a proxy's optional username and +password in Settings, in fields of their own for SOCKS5/SOCKS5h, HTTP, +HTTPS and bare host:port proxies alike, using the real page with isolated +API fixtures. It covers saving and reloading, @ : / % # and spaces in a +password, escaped and non-UTF-8 credentials, a login saved in the address +before loading into the fields, masked addresses/status, clearing +authentication, Tab and Escape, mode switches, and narrow windows in all +five languages on Chromium and WebKit. ## Installed desktop fonts `fonts.test.cjs` exercises the interface/code font controls with installed diff --git a/internal/gui/tests/settings-proxy-auth.test.cjs b/internal/gui/tests/settings-proxy-auth.test.cjs index 629b7f937..4b6b748e8 100644 --- a/internal/gui/tests/settings-proxy-auth.test.cjs +++ b/internal/gui/tests/settings-proxy-auth.test.cjs @@ -1,6 +1,9 @@ // Run with Node's test runner and Playwright on the module path; see README.md. -// Optional SOCKS credentials survive saving/reloading, never appear in the -// address or status, and typing between fields cannot save a partial login. +// A proxy's optional username and password, in fields of their own for +// every kind of proxy (SOCKS, and HTTP for 微雨南山 on Discord), survive +// saving/reloading, never appear in the address or status, and typing +// between fields cannot save a partial login. A login saved in the address +// before loads into the fields. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -51,7 +54,7 @@ const labels = { for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of Object.keys(labels)) { const l = labels[lang]; - test(`${engine} ${lang}: optional SOCKS credentials in settings`, async (t) => { + test(`${engine} ${lang}: optional proxy credentials in settings`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); t.after(() => browser.close()); const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" }); @@ -133,12 +136,47 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await pass.inputValue(), "p%FFss"); await saved(() => box.getByRole("button", { name: l.save, exact: true }).click(), "socks5://name:p%FFss@127.0.0.1:1080"); - // HTTP and bare addresses still work; a hidden SOCKS login isn't attached. + // An HTTP proxy has the same fields (微雨南山 on Discord): its login + // is typed as it is, @ : / % # and spaces included, and each part is + // encoded into the address, which keeps no slash or port of URL's. await address.fill("http://127.0.0.1:7890"); - assert.equal(await user.isVisible(), false); + assert.equal(await user.isVisible(), true, "an HTTP proxy has a username field"); + assert.equal(await pass.isVisible(), true, "an HTTP proxy has a password field"); + await user.fill(""); + await pass.fill(""); await saved(() => address.press("Enter"), "http://127.0.0.1:7890"); + await user.fill("me@corp:x"); + await pass.fill("p@ss:w/rd% #1 x"); + // the bytes internal/netproxy's TestProxyLoginWithReservedCharacters signs in with + const httpLogin = "http://me%40corp%3Ax:p%40ss%3Aw%2Frd%25%20%231%20x@127.0.0.1:7890"; + await saved(() => pass.press("Enter"), httpLogin); + await page.reload(); + assert.equal(await address.inputValue(), "http://127.0.0.1:7890"); + assert.equal(await user.inputValue(), "me@corp:x"); + assert.equal(await pass.inputValue(), "p@ss:w/rd% #1 x"); + assert.equal(await pass.getAttribute("type"), "password"); + for (const secret of ["p@ss", "p%40ss", "corp"]) assert(!(await page.locator("#proxySub").innerText()).includes(secret), `status shows ${secret}`); + for (const width of [560, 375]) { + await page.setViewportSize({ width, height: 760 }); + for (const field of [address, user, pass]) { + const rect = await field.boundingBox(); + assert(rect && rect.x >= 0 && rect.x + rect.width <= width, `HTTP proxy field outside ${width}px window`); + } + if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-http-proxy-${width}.png`) }); + } + await page.setViewportSize({ width: 1100, height: 760 }); + + // A bare host:port stays as typed, with or without a login. + await user.fill(""); + await pass.fill(""); await address.fill("127.0.0.1:7891"); await saved(() => page.locator("#proxySub").click(), "127.0.0.1:7891"); + await user.fill("u"); + await pass.fill("p w"); + await saved(() => pass.press("Enter"), "u:p%20w@127.0.0.1:7891"); + await page.reload(); + assert.equal(await address.inputValue(), "127.0.0.1:7891"); + assert.equal(await pass.inputValue(), "p w"); await address.fill("socks5://127.0.0.1:1080"); await user.fill("unsaved-user"); @@ -147,5 +185,30 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await saved(() => box.getByRole("button", { name: l.auto, exact: true }).click(), ""); assert.deepEqual(errors, []); }); + + test(`${engine} ${lang}: an HTTP proxy saved with its login in the address loads into the fields`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 375, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(4000); + const posts = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + // as one typed whole before: a raw @ in the password, as Go reads it + await page.route("**/*", server(lang, posts, "https://al%20ice:se@cr%23et@proxy.example:8443")); + await page.goto("http://magpie.test/?view=settings&tab=network"); + const box = page.locator("#proxySegs"); + assert.equal(await box.locator("input.proxy").inputValue(), "https://proxy.example:8443"); + assert.equal(await box.getByRole("textbox", { name: l.user, exact: true }).inputValue(), "al ice"); + const pass = box.getByLabel(l.pass, { exact: true }); + assert.equal(await pass.inputValue(), "se@cr#et"); + assert.equal(await pass.getAttribute("type"), "password"); + const sub = await page.locator("#proxySub").innerText(); + assert(!sub.includes("se@cr") && !sub.includes("al%20ice"), `status shows the login: ${sub}`); + // left as it was, it is saved as it was + await pass.press("Enter"); + assert.equal(posts.length, 0, "an unchanged login is not saved again"); + assert.deepEqual(errors, []); + }); } } diff --git a/internal/netproxy/login_test.go b/internal/netproxy/login_test.go new file mode 100644 index 000000000..8022c27e7 --- /dev/null +++ b/internal/netproxy/login_test.go @@ -0,0 +1,201 @@ +package netproxy + +import ( + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// The login Settings › Proxy saves (微雨南山 on Discord): a username and +// a password typed in fields of their own, each percent-encoded into the +// address's userinfo as the page's proxyAddress does +// (encodeURIComponent). These are the page's own bytes for them. +const ( + loginUser = "me@corp:x" + loginPass = "p@ss:w/rd% #1 x" + loginUserEnc = "me%40corp%3Ax" + loginPassEnc = "p%40ss%3Aw%2Frd%25%20%231%20x" +) + +func clearProxyEnv(t *testing.T) { + t.Helper() + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + sysCache.at, sysCache.p = farFuture, Proxy{} + t.Cleanup(func() { sysCache.at = zero }) +} + +// fakeHTTPProxy is an HTTP proxy that carries a request only with the +// user and password given, answering 407 otherwise. +func fakeHTTPProxy(t *testing.T, user, pass string) *httptest.Server { + t.Helper() + want := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass)) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Proxy-Authorization") != want { + w.Header().Set("Proxy-Authenticate", `Basic realm="fake"`) + http.Error(w, "proxy login refused", http.StatusProxyAuthRequired) + return + } + io.WriteString(w, "carried "+r.URL.String()) + })) + t.Cleanup(srv.Close) + return srv +} + +// throughSaved gets target through the proxy settings name, as a vendor +// request takes it (For; Func skips the test servers' loopback). +func throughSaved(t *testing.T, target string) (string, int) { + t.Helper() + tr := &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) { return For(r.URL) }} + defer tr.CloseIdleConnections() + res, err := (&http.Client{Transport: tr}).Get(target) + if err != nil { + t.Fatalf("GET %s through the saved proxy: %v", target, err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return string(b), res.StatusCode +} + +// A password holding @ : / % # and spaces, saved as the Settings page +// saves it, reads back as typed and signs in to an HTTP proxy and a +// SOCKS5 one; one off by a character is refused, so the fakes check it. +// Nothing shown of the address carries either part of the login. +func TestProxyLoginWithReservedCharacters(t *testing.T) { + vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "vendor "+r.URL.Path) })) + defer vendor.Close() + + t.Run("http", func(t *testing.T) { + clearProxyEnv(t) + p := fakeHTTPProxy(t, loginUser, loginPass) + saved := "http://" + loginUserEnc + ":" + loginPassEnc + "@" + strings.TrimPrefix(p.URL, "http://") + if err := settings.Save(settings.Settings{Proxy: saved}); err != nil { + t.Fatal(err) + } + if got := settings.Load().Proxy; got != saved { + t.Fatalf("saved %q, read back %q", saved, got) + } + u, _ := url.Parse("http://vendor.example/v1/models") + pu, err := For(u) + if err != nil || pu == nil { + t.Fatalf("For = %v, %v", pu, err) + } + if pw, _ := pu.User.Password(); pu.User.Username() != loginUser || pw != loginPass { + t.Fatalf("login read back as %q / %q", pu.User.Username(), pw) + } + if body, code := throughSaved(t, "http://vendor.example/v1/models"); code != 200 || body != "carried http://vendor.example/v1/models" { + t.Fatalf("through the HTTP proxy: %d %q", code, body) + } + // a CLI magpie starts gets the same login in its *_PROXY + for _, e := range EnvWith("", []string{}) { + if k, v, _ := strings.Cut(e, "="); k == "HTTPS_PROXY" { + eu, err := url.Parse(v) + if err != nil { + t.Fatal(err) + } + if pw, _ := eu.User.Password(); eu.User.Username() != loginUser || pw != loginPass { + t.Fatalf("HTTPS_PROXY's login is %q / %q", eu.User.Username(), pw) + } + } + } + // one character off is refused + wrong := "http://" + loginUserEnc + ":" + strings.Replace(loginPassEnc, "%23", "%2523", 1) + "@" + strings.TrimPrefix(p.URL, "http://") + if err := settings.Save(settings.Settings{Proxy: wrong}); err != nil { + t.Fatal(err) + } + if _, code := throughSaved(t, "http://vendor.example/"); code != http.StatusProxyAuthRequired { + t.Fatalf("a wrong password was carried: %d", code) + } + assertHidden(t) + }) + + t.Run("socks5", func(t *testing.T) { + clearProxyEnv(t) + socks, n := fakeSOCKS(t, loginUser, loginPass) + saved := "socks5://" + loginUserEnc + ":" + loginPassEnc + "@" + socks.Host + if err := settings.Save(settings.Settings{Proxy: saved}); err != nil { + t.Fatal(err) + } + // Go's transport speaks SOCKS5 itself + if body, code := throughSaved(t, vendor.URL+"/go"); code != 200 || body != "vendor /go" { + t.Fatalf("through the SOCKS5 proxy: %d %q", code, body) + } + // and the plugin host's Bun goes through the bridge, whose own + // handshake (socksHandshake) sends the login + pu, err := Parse(saved) + if err != nil { + t.Fatal(err) + } + b, err := Bridge(pu) + if err != nil { + t.Fatal(err) + } + bu, _ := url.Parse(b) + res, err := (&http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(bu)}}).Get(vendor.URL + "/bridge") + if err != nil { + t.Fatal(err) + } + got, _ := io.ReadAll(res.Body) + res.Body.Close() + if string(got) != "vendor /bridge" { + t.Fatalf("through the bridge: %d %q", res.StatusCode, got) + } + if n.Load() != 2 { + t.Fatalf("the SOCKS proxy carried %d connections, want 2", n.Load()) + } + wrong := "socks5://" + loginUserEnc + ":" + strings.TrimSuffix(loginPassEnc, "x") + "@" + socks.Host + if err := settings.Save(settings.Settings{Proxy: wrong}); err != nil { + t.Fatal(err) + } + tr := &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) { return For(r.URL) }} + defer tr.CloseIdleConnections() + if _, err := (&http.Client{Transport: tr}).Get(vendor.URL + "/no"); err == nil { + t.Fatal("a wrong SOCKS password was carried") + } + assertHidden(t) + }) +} + +// assertHidden: what Settings shows of the saved proxy names neither +// part of the login, decoded or not. +func assertHidden(t *testing.T) { + t.Helper() + shown, source := Describe() + for _, secret := range []string{loginUser, loginPass, loginUserEnc, loginPassEnc, "p@ss", "p%40ss", "corp"} { + if strings.Contains(shown, secret) || strings.Contains(Redact(settings.Load().Proxy), secret) { + t.Fatalf("Describe (%s) shows %q: %q", source, secret, shown) + } + } +} + +// Bun, which the plugin host's fetches and Claude Code run on, signs in +// to an HTTP proxy with the same login: it decodes the userinfo as Go +// does. Run when a bun is at hand ($MAGPIE_BUN or on PATH). +func TestBunProxyLoginWithReservedCharacters(t *testing.T) { + bun := os.Getenv("MAGPIE_BUN") + if bun == "" { + bun, _ = exec.LookPath("bun") + } + if bun == "" { + t.Skip("no bun") + } + p := fakeHTTPProxy(t, loginUser, loginPass) + proxy := "http://" + loginUserEnc + ":" + loginPassEnc + "@" + strings.TrimPrefix(p.URL, "http://") + js := `console.log(await (await fetch("http://vendor.example/x", { proxy: process.env.P })).text())` + cmd := exec.Command(bun, "-e", js) + cmd.Env = append(os.Environ(), "P="+proxy) + out, err := cmd.CombinedOutput() + if err != nil || strings.TrimSpace(string(out)) != "carried http://vendor.example/x" { + t.Fatalf("bun through the HTTP proxy: %v %s", err, out) + } +}