Files
magpie/internal/gui/tests/browser-access.test.cjs
T
yetone e056779a67 gui: the app serves its page to a browser, behind its key (Settings › Browser access)
jiakun_zhao on X ran `magpie web` in a terminal beside the desktop app,
to manage it through a Cloudflare tunnel. Settings › Network and sharing ›
Browser access now has the app serve the same page itself: Off, This
computer (127.0.0.1, for a tunnel or SSH forward) or Local network.

Access is magpie web's, unchanged: the key in the link is traded for the
cookie (webGuard), the allow list holds, and the gateway's client routes
on the page's port need a gateway key (onePort). A rebound Host and
Origin: null get no cookie. There is no way to serve it without the key.
The key and choice live in web-page.json (0600) beside settings.json, so
a sync never carries them. GET/POST /api/web-page are the app windows'
alone: a browser on the page can't read the key or turn the page off. A
busy port (magpie web, the magpie before an update) is tried every 4s;
`magpie web` on the same port opens the app's link instead.

Run at d43b7c40d (this change on ef155a5ca), then rebased onto the four
newer main commits, which touch gateway, usage, proc and library only:
- gofmt -l internal/gui internal/cli: nothing. go vet, GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of internal/gui and internal/cli:
  clean. go build: ok.
- go test -timeout 45m ./internal/gui/ ./internal/cli/: ok (180s, 70s).
- GUI, alone: browser-access.test.cjs and model-test-one.test.cjs pass in
  both engines; i18n-keys 23 of 24, its red is #3897 ("Runs as" from
  7f827b3b0), not this change. agent-stale-copies.test.cjs 80 of 80 at
  8d343a811 (this change before the rebase).
- Full GUI suite at 8d343a811: cut short. The disk filled (708MB free):
  browsers failed to launch with ENOSPC in agent-stale-copies, which then
  passed 80 of 80 alone, and node ended with exit 7 before the rest of
  the files ran. There is no full GUI record for this change.

Not tried: a real Cloudflare tunnel to the page, and Local network from
another machine.
2026-10-27 18:58:16 +08:00

177 lines
10 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.
// Settings › Network and sharing › Browser access (jiakun_zhao on X: the
// page managed through a Cloudflare tunnel took `magpie web` kept running in
// a terminal beside the app). Off, This computer or Local network, posted to
// /api/web-page; once on, the link (its key shown as "…", copied whole), a
// New key, the port with Apply, and why it isn't served when a port is
// taken, in the page's language. Local network without TLS says the page is
// not encrypted. A browser on the page (web) has no such section and never
// asks for it. No native <select>, no coloured left border, nothing wider
// than a 360px window. Every language, Chromium and WebKit; no backend, the
// API is faked here.
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 { reach, watchSettingsReads, settingsDrawn } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const KEY = "0123456789abcdef0123456789abcdef";
function server(lang, web, posts, gets) {
let wp = { mode: "", port: 3430, serving: false };
const say = () => {
if (!wp.mode) return { mode: "", port: wp.port, serving: false };
const s = { ...wp, link: `http://127.0.0.1:${wp.port}/?k=${wp.key}` };
if (wp.port === 3500) Object.assign(s, { serving: false, error: "port 3500 can't be taken (address already in use): magpie tries again every few seconds" });
else s.serving = true;
if (wp.mode === "lan") s.network = [`http://192.168.1.20:${wp.port}/?k=${wp.key}`];
return s;
};
return async (route) => {
const req = route.request();
const url = new URL(req.url());
const json = (data, status = 200) => route.fulfill({ status, json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web},sideGateway:{url:"http://127.0.0.1:3425",running:true,boot: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" }, web });
if (url.pathname === "/api/web-page") {
if (req.method() === "GET") { gets.n++; return json(say()); }
const body = JSON.parse(req.postData());
posts.push(body);
if (body.mode !== undefined) wp.mode = body.mode;
if (body.port !== undefined) wp.port = body.port;
if (body.newKey || !wp.key) wp.key = body.newKey && wp.key ? "fedcba9876543210fedcba9876543210" : KEY;
return json(say());
}
if (url.pathname === "/api/settings") return json({ lang, theme: "light", gateway: "http://127.0.0.1:3425", lan: false, lanURLs: [], version: "0.1.900", dir: "/config/magpie", fx: { rate: 7.2, at: new Date().toISOString(), stale: false } });
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Browser access turns the app's page on for a browser, with its key", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const pages = [];
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-browser-access-${i}.png`) });
}
await browser.close();
});
const open = async (lang, web, width = 900) => {
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
pages.push(page);
page.setDefaultTimeout(5000);
const errors = [], posts = [], gets = { n: 0 };
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, web, posts, gets));
await watchSettingsReads(page);
await page.goto("http://localhost:3430/?view=settings&tab=network");
await settingsDrawn(page);
// the page's own word for an English string
const tr = (s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]);
return { page, errors, posts, gets, tr };
};
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang, async () => {
const { page, errors, posts, tr } = await open(lang, false);
const head = page.locator("#webPageHead");
const list = page.locator("#webPageList");
await list.locator(".row.pref").first().waitFor();
assert.equal((await head.textContent()).trim(), await tr("Browser access"));
if (lang !== "en") assert.notEqual(await tr("Browser access"), "Browser access", "translated");
const first = list.locator(".row.pref").first();
assert.equal((await first.locator(".name").textContent()).trim(), await tr("Open magpie in a browser"));
assert.equal((await first.locator(".sub").textContent()).trim(), await tr("The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}", { port: 3430 }));
assert.equal(await list.locator(".row.pref").count(), 1, "off: one row");
const local = first.getByRole("button", { name: await tr("This computer") });
await reach(page, local);
await local.click();
await list.locator(".web-page-link-row").waitFor();
assert.deepEqual(posts.at(-1), { mode: "local" });
const linkRow = list.locator(".web-page-link-row");
const code = linkRow.locator("code");
assert.equal(await code.count(), 1);
assert.equal((await code.textContent()).trim(), "http://127.0.0.1:3430/?k=…", "the key isn't shown");
assert.equal(await linkRow.locator("button.copy").count(), 1);
assert.equal((await linkRow.locator(".sub").textContent()).trim(), await tr("Served; anyone with this link can change every setting"));
assert.equal(await list.locator(".web-page-warn").count(), 0, "this computer alone: no warning");
const rekey = linkRow.getByRole("button", { name: await tr("New key") });
await reach(page, rekey);
await rekey.click();
// the posts are counted here, not a time waited
for (let i = 0; i < 250 && !posts.some((p) => p.newKey); i++) await page.waitForTimeout(20);
assert(posts.some((p) => p.newKey), "New key posts newKey");
// a port another program has: said in the page's language
const field = list.locator("input.gateway-port");
await reach(page, field);
await field.fill("3500");
await list.getByRole("button", { name: await tr("Apply") }).click();
const why = await tr("Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds", { p: 3500 });
await list.locator(".web-page-link-row .sub.err").filter({ hasText: why }).waitFor();
assert.deepEqual(posts.at(-1), { port: 3500 });
// local network, no TLS: not encrypted, and every address's link
const lan = list.getByRole("button", { name: await tr("Local network") });
await reach(page, lan);
await lan.click();
await list.locator(".web-page-warn").waitFor();
assert.deepEqual(posts.at(-1), { mode: "lan" });
assert.equal(await list.locator(".web-page-link-row code").count(), 2);
assert.equal((await list.locator(".web-page-warn .name").textContent()).trim(), await tr("Not encrypted"));
assert.equal(await page.locator("#setPage-network select").count(), 0, "no native select");
for (const r of await list.locator(".row.pref").all()) {
const border = await r.evaluate((e) => getComputedStyle(e).borderLeftWidth);
assert(border === "0px" || border === "", "no left border accent: " + border);
}
const off = list.getByRole("button", { name: await tr("Off") }).first();
await reach(page, off);
await off.click();
await page.waitForFunction(() => document.querySelectorAll("#webPageList .row.pref").length === 1);
assert.deepEqual(posts.at(-1), { mode: "" });
assert.deepEqual(errors, []);
});
}
await t.test("360px wide, Chinese", async () => {
const { page, errors, tr } = await open("zh", false, 360);
const list = page.locator("#webPageList");
await list.locator(".row.pref").first().waitFor();
const lan = list.getByRole("button", { name: await tr("Local network") });
await reach(page, lan);
await lan.click();
await list.locator(".web-page-warn").waitFor();
const over = await list.evaluate((l) => [...l.querySelectorAll(".row.pref")].filter((r) => r.scrollWidth > r.clientWidth + 1 || r.getBoundingClientRect().right > innerWidth + 1).map((r) => r.textContent.slice(0, 40)));
assert.deepEqual(over, [], "rows wider than the window");
const cut = await list.evaluate((l) => [...l.querySelectorAll(".row.pref .name")].filter((n) => n.scrollWidth > n.clientWidth).map((n) => n.textContent));
assert.deepEqual(cut, [], "names cut off");
assert.deepEqual(errors, []);
});
await t.test("a browser on the page has no Browser access", async () => {
const { page, errors, gets } = await open("en", true);
await page.locator("#portList .row").first().waitFor();
assert.equal(await page.locator("#webPageHead").isVisible(), false);
assert.equal(await page.locator("#webPageList .row").count(), 0);
assert.equal(gets.n, 0, "never asks /api/web-page");
assert.deepEqual(errors, []);
});
});
}