gui: plugin pages load behind a proxy that signs in by cookie (xuanwo on X)

A plugin page's frame is sandboxed (opaque origin), so its stylesheet and
scripts are cross-site requests that carry no SameSite=Lax cookie. Behind
Cloudflare Access they were redirected to the sign-in page and the page
said it "didn't answer" (Day card). index.html's manifest link also
fetched without credentials.

In magpie web the page's HTML now comes as one document (pageinline.go):
classic scripts (bridge included) and url()-free stylesheets are written
in, scripts allowed by sha256 in the policy, deferred ones moved to the end
of body. A script the page adds later is fetched by the window (asset call,
folder-checked, window carries the cookie) and loaded from a data: address
(WebKit finds no blob made in a sandboxed frame). The manifest link has
crossorigin="use-credentials". Modules, url() stylesheets, images and
fonts loaded by the page itself still ask the proxy.

Run on mote at this tree: go test -run PluginPage ./internal/gui; node
--test plugin-page, plugin-page-idle, plugin-page-cookie-proxy in
chromium and webkit; gofmt; vet. Broken by hand: inlining off turns
TestPluginPageWebComesAsOneDocument red, the bridge shim off turns the
cookie-proxy test red in both engines.
Not tried: a real Cloudflare Access tunnel; images/fonts behind a proxy.
This commit is contained in:
yetone
2026-11-11 19:11:55 +08:00
parent c4a9856dfb
commit 55dff77b4d
8 changed files with 341 additions and 3 deletions
+12
View File
@@ -339,6 +339,18 @@ starts a Bun host.
`TestServiceSelf` and `TestPluginPageServiceProxied` check the policies, and
`TestPluginPageLoadsItsFilesInTheWindow` loads a page through
`ownWindow` in a real WKWebView; Playwright, on http, can't see it.
Behind a proxy that signs readers in by a SameSite=Lax cookie (Cloudflare
Access) the sandboxed frame's files carried none and were redirected to
the sign-in (xuanwo on X, Day card). In `magpie web` the page's HTML comes
as one document (`inlinePage`, pageinline.go): its classic scripts (the
bridge included) and url()-free stylesheets are written in, the scripts
allowed by hash, and a script the page adds later is fetched by the window
(`asset` in pluginpages.js, under the page's folder only) and loaded from
a `data:` address (`data:` in script-src; WebKit finds no blob made in a
sandboxed frame). Left as they were: modules, stylesheets with url(),
images and fonts the page loads itself. index.html's manifest link asks
with `crossorigin="use-credentials"`. `TestPluginPageWebComesAsOneDocument`,
`plugin-page-cookie-proxy.test.cjs`.
- **Slots.** A page names a slot with `<div class="plugin-slot"
data-slot="…" hidden>` in its markup, or app.js draws one with
`magpie.slot(name, context)` ([`pluginpages.js`](../../internal/gui/assets/pluginpages.js)).
+1 -1
View File
@@ -11,7 +11,7 @@
the page's cookie.
The theme colours are the window's in standalone alone, so a browser's
tab and the app's own windows look as they did -->
<link rel="manifest" href="manifest.json">
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="apple-touch-icon" href="icons/apple-touch-icon.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
+11
View File
@@ -141,6 +141,17 @@
if (!e.reads.includes(name)) throw new Error(t("{name} doesn't ask to read {what}", { name: titled(e), what: name }));
return api("plugin-pages/read", { spec: e.spec, read: name, params: m.params?.params || {} });
}
case "asset": {
// a file of the page's own folder, for a page that cannot ask for
// it itself (pageinline.go): this request carries the window's
// cookie
const dir = new URL(e.url.replace(/[^/]*$/, ""), location.href).href;
const u = new URL(String(m.params?.url || ""), location.href);
if (!u.href.startsWith(dir) || u.hash) throw new Error(t("No such call: {what}", { what: "asset" }));
const res = await fetch(u.href, { credentials: "same-origin" });
if (!res.ok) throw new Error(String(res.status));
return { type: res.headers.get("content-type") || "", data: await res.arrayBuffer() };
}
case "image.copy":
case "image.save":
return import("./pageshare.js").then(() => pageShare(e.spec, m.method === "image.save", m.params));
+30
View File
@@ -65,6 +65,36 @@
parent.postMessage({ magpie: 1, id, method, params }, "*");
});
}
// A page that came as one document (pageinline.go) can't ask for its
// other files itself: a proxy that signs readers in by cookie turns away
// a sandboxed frame's requests. A script it adds is fetched by the
// window, which has the cookie, and loaded from a data: address.
if (globalThis.__magpieInlined) {
const put = (node, ref) => {
let abs;
try { abs = new URL(ref, location.href).href; } catch { return false; }
call("asset", { url: abs }).then(({ type, data }) => {
// a data: address, not a blob's: WebKit finds no blob made in a
// sandboxed frame
let bin = "";
const bytes = new Uint8Array(data);
for (let i = 0; i < bytes.length; i += 8192) bin += String.fromCharCode(...bytes.subarray(i, i + 8192));
node.setAttribute("src", "data:text/javascript;base64," + btoa(bin));
node.__magpiePut(node);
}, () => node.__magpiePut(node));
return true;
};
const add = (orig) => function (node, ...rest) {
if (node instanceof HTMLScriptElement && node.hasAttribute("src") && !node.__magpieDone && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(node.getAttribute("src"))) {
const ref = node.getAttribute("src");
node.__magpiePut = (n) => { n.__magpieDone = true; orig.call(this, n, ...rest); };
if (put(node, ref)) return node;
}
return orig.call(this, node, ...rest);
};
Node.prototype.appendChild = add(Node.prototype.appendChild);
Node.prototype.insertBefore = add(Node.prototype.insertBefore);
}
function paint(theme) {
const root = document.documentElement;
root.dataset.theme = theme.dark ? "dark" : "light";
+134
View File
@@ -0,0 +1,134 @@
package gui
import (
"crypto/sha256"
"encoding/base64"
"net/url"
"os"
"regexp"
"strings"
"github.com/yetone/magpie/internal/plugin"
)
// A plugin's page is framed with sandbox="allow-scripts", so its origin is
// opaque and every file it loads is a cross-site request that carries no
// cookie of SameSite=Lax (Cloudflare Access's CF_Authorization is one).
// Behind a proxy that signs readers in by cookie, the page's HTML came
// (the frame's own navigation is same-site) but its stylesheet and
// scripts were redirected to the sign-in page, and the page said it
// "didn't answer" (xuanwo on X, Day card).
//
// A page served to a browser therefore comes as one document: its own
// classic scripts and stylesheets are written into the HTML, the scripts
// allowed by their hashes in the page's policy. Loads the page makes
// later (a script it adds) ask the window for the file (pagebridge.js's
// asset call), which carries the cookie.
var (
inlineScript = regexp.MustCompile(`(?is)<script\b([^>]*?)\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')([^>]*)>\s*</script\s*>`)
inlineLink = regexp.MustCompile(`(?is)<link\b[^>]*>`)
attrRel = regexp.MustCompile(`(?is)\brel\s*=\s*["']?\s*stylesheet\b`)
attrHref = regexp.MustCompile(`(?is)\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')`)
attrType = regexp.MustCompile(`(?is)\btype\s*=\s*["']?\s*([^"'\s>]*)`)
attrDefer = regexp.MustCompile(`(?is)\bdefer\b`)
bodyClose = regexp.MustCompile(`(?i)</body\s*>`)
)
// maxInlinePage bounds a page written as one document.
const maxInlinePage = 8 << 20
// localRef is a reference to a file in the page's folder: relative, no
// scheme, query or fragment.
func localRef(ref string) (string, bool) {
ref = strings.TrimSpace(ref)
if ref == "" || strings.HasPrefix(ref, "/") || strings.HasPrefix(ref, "#") || strings.ContainsAny(ref, "?#\\") {
return "", false
}
if u, err := url.Parse(ref); err != nil || u.Scheme != "" || u.Host != "" {
return "", false
}
return ref, true
}
// inlinePage writes a page's own classic scripts and stylesheets into its
// HTML. It answers the document and the hashes of the scripts it wrote;
// what it can't write in (a module, a stylesheet naming url()s, a file
// not found) stays a reference. The bridge is marked inlined so it knows
// to fetch later loads through the window.
func inlinePage(html []byte, dir string) (out []byte, hashes []string) {
var deferred []string
size := len(html)
hash := func(body string) string {
sum := sha256.Sum256([]byte(body))
h := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
hashes = append(hashes, h)
return h
}
read := func(ref string) (string, bool) {
if ref == pluginBridgePath {
return "globalThis.__magpieInlined=1;\n" + string(pageBridgeJS), true
}
file, ok := plugin.FileIn(dir, ref)
if !ok {
return "", false
}
b, err := os.ReadFile(file)
if err != nil || size+len(b) > maxInlinePage {
return "", false
}
size += len(b)
return string(b), true
}
res := inlineScript.ReplaceAllStringFunc(string(html), func(tag string) string {
m := inlineScript.FindStringSubmatch(tag)
attrs := m[1] + " " + m[4]
if t := attrType.FindStringSubmatch(attrs); t != nil && t[1] != "" && !strings.EqualFold(t[1], "text/javascript") && !strings.EqualFold(t[1], "application/javascript") {
return tag
}
ref, ok := localRef(m[2] + m[3])
if !ok {
return tag
}
body, ok := read(ref)
if !ok {
return tag
}
body = strings.ReplaceAll(body, "</script", `<\/script`)
hash(body)
s := "<script>" + body + "\n</script>"
if attrDefer.MatchString(attrs) {
deferred = append(deferred, s)
return ""
}
return s
})
res = inlineLink.ReplaceAllStringFunc(res, func(tag string) string {
if !attrRel.MatchString(tag) {
return tag
}
m := attrHref.FindStringSubmatch(tag)
if m == nil {
return tag
}
ref, ok := localRef(m[1] + m[2])
if !ok {
return tag
}
body, ok := read(ref)
if !ok || strings.Contains(strings.ToLower(body), "url(") || strings.Contains(strings.ToLower(body), "@import") {
return tag
}
return "<style>" + strings.ReplaceAll(body, "</style", `<\/style`) + "</style>"
})
if len(deferred) > 0 {
tail := strings.Join(deferred, "\n")
if loc := bodyClose.FindAllStringIndex(res, -1); len(loc) > 0 {
i := loc[len(loc)-1][0]
res = res[:i] + tail + "\n" + res[i:]
} else {
res += "\n" + tail
}
}
return []byte(res), hashes
}
+27 -2
View File
@@ -225,7 +225,7 @@ func windowOf(spec string) (name string, reads []string, ok bool) {
// inline styles, data: pictures, and nothing over the network. sandbox
// keeps a page opened by itself (not in the window's frame) as shut in as
// the frame keeps it.
func pagePolicy(r *http.Request, tok string) string {
func pagePolicy(r *http.Request, tok string, hashes ...string) string {
own := "'self'"
if r.Host != "" {
// the page's own folder: not the window's files, nor /api
@@ -234,7 +234,7 @@ func pagePolicy(r *http.Request, tok string) string {
return strings.Join([]string{
"sandbox allow-scripts",
"default-src 'none'",
"script-src " + own,
"script-src " + strings.Join(append([]string{own}, hashes...), " "),
"style-src " + own + " 'unsafe-inline'",
"img-src " + own + " data:",
"font-src " + own,
@@ -388,6 +388,26 @@ func servePluginPage(rw http.ResponseWriter, r *http.Request, web bool) {
pageHost(r.Context())
}
h := rw.Header()
// A page in a browser comes as one document (pageinline.go): its
// sandboxed frame sends no cookie for its files, which a proxy that
// signs readers in by cookie turns away.
if web && rel == entry && isHTML(rel) {
if file, ok := plugin.FileIn(dir, rel); ok {
b, err := os.ReadFile(file)
if err != nil {
http.NotFound(rw, r)
return
}
doc, hashes := inlinePage(b, dir)
h.Set("Content-Security-Policy", pagePolicy(r, tok, append(hashes, "data:")...))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Cache-Control", "no-cache")
h.Set("Content-Type", "text/html; charset=utf-8")
http.ServeContent(rw, r, "index.html", time.Time{}, strings.NewReader(string(doc)))
return
}
}
h.Set("Content-Security-Policy", pagePolicy(r, tok))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
@@ -620,3 +640,8 @@ func pageRead(read string, params map[string]any) (any, error) {
}
return nil, fmt.Errorf("no read %q", read)
}
func isHTML(rel string) bool {
ext := strings.ToLower(filepath.Ext(rel))
return ext == ".html" || ext == ".htm"
}
+52
View File
@@ -411,3 +411,55 @@ func TestPluginPagePolicyBehindProxyHost(t *testing.T) {
t.Fatalf("the Host's address twice: %s", p)
}
}
// Behind a proxy that signs readers in by cookie (Cloudflare Access), a
// page's sandboxed frame sends no cookie for its stylesheet and scripts,
// and the proxy turns them away. In magpie web the page comes as one
// document, its scripts allowed by hash (xuanwo on X, Day card).
func TestPluginPageWebComesAsOneDocument(t *testing.T) {
on, _ := pagePlugins(t)
dir := filepath.Join(on, "page")
html := `<!doctype html><link rel="stylesheet" href="s.css"><script src="_magpie/bridge.js"></script><script src="a.js"></script><script src="b.js" defer></script><script src="https://x.example/c.js"></script><body><p id=p></p></body>`
for name, body := range map[string]string{"index.html": html, "s.css": "p{color:red}", "a.js": "window.A=1", "b.js": "window.B=document.getElementById('p')"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
// the proxy: no cookie, no file
proxy := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
c, _ := r.Cookie("CF_Authorization")
sub := r.URL.Path != "" && !strings.HasSuffix(r.URL.Path, "/index.html")
if sub && c == nil {
http.Redirect(rw, r, "https://team.cloudflareaccess.com/cdn-cgi/access/login", http.StatusFound)
return
}
next.ServeHTTP(rw, r)
})
}
mux := http.NewServeMux()
pluginPageRoutes(mux, true)
var pages []pluginPage
_ = json.Unmarshal(do(mux, httptest.NewRequest("GET", "/api/plugin-pages", nil)).Body.Bytes(), &pages)
w := do(proxy(mux), httptest.NewRequest("GET", pages[0].URL, nil))
body := w.Body.String()
if w.Code != 200 || strings.Contains(body, `src="a.js"`) || strings.Contains(body, `href="s.css"`) {
t.Fatalf("the files aren't in the page: %d %s", w.Code, body)
}
if !strings.Contains(body, "window.A=1") || !strings.Contains(body, "p{color:red}") || !strings.Contains(body, "__magpieInlined") || !strings.Contains(body, `src="https://x.example/c.js"`) {
t.Errorf("the page: %s", body)
}
if strings.Index(body, "window.B=") < strings.Index(body, "<p id=p>") {
t.Errorf("a deferred script runs before the page is read: %s", body)
}
csp := w.Header().Get("Content-Security-Policy")
if n := strings.Count(csp, "'sha256-"); n != 3 || !strings.Contains(csp, "data:") {
t.Errorf("hashes of the three scripts: %s", csp)
}
// not in a browser (the desktop window): files as they are
mux = http.NewServeMux()
pluginPageRoutes(mux, false)
if b := do(mux, httptest.NewRequest("GET", pages[0].URL, nil)).Body.String(); !strings.Contains(b, `src="a.js"`) {
t.Errorf("the window's page was rewritten: %s", b)
}
}
@@ -0,0 +1,74 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Behind a proxy that signs readers in by a SameSite=Lax cookie (Cloudflare
// Access), a plugin page's sandboxed frame is a cross-site origin and sends
// none: its files are redirected to the sign-in page (xuanwo on X, Day card).
// The server writes the page's own files into its HTML (pageinline.go, tested
// in Go); a script the page adds later is fetched by the window, which has
// the cookie (pagebridge.js), and loaded from a data: address.
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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));
const bridge = path.resolve(process.env.MAGPIE_BRIDGE || path.join(__dirname, "../pagebridge.js"));
const tok = "c".repeat(32);
const page = { spec: "/x/cookie", name: "cookie", key: "plugin-cookie", title: "cookie", reads: [], url: `/_magpie/plugin/${tok}/index.html` };
let webkitEngine = false;
async function server(route) {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"en",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: "en", theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/plugin-pages") return json([page]);
if (url.pathname === "/api/plugin-panels") return json([]);
if (url.pathname.startsWith("/api/")) return json({});
if (url.pathname.startsWith("/_magpie/plugin/")) {
const name = url.pathname.slice(`/_magpie/plugin/${tok}/`.length);
const headers = { "Cache-Control": "no-cache" };
if (name === "index.html") {
const body = `<!doctype html><meta charset="utf-8"><script>globalThis.__magpieInlined=1;\n${(await fs.readFile(bridge, "utf8")).replaceAll("</script", "<\\/script")}</script>
<script>window.dyn = new Promise((ok, no) => { const s = document.createElement("script"); s.src = "dyn.js"; s.onload = () => ok(window.DYN); s.onerror = () => no(new Error("dyn.js")); document.head.appendChild(s); });</script><p>page</p>`;
return route.fulfill({ headers: { ...headers, "Content-Type": "text/html", "Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline' data:; style-src 'unsafe-inline'" }, body });
}
// the proxy: no cookie, no file
const h = await route.request().allHeaders();
// Playwright's WebKit shows no cookie on an intercepted request; the
// window's fetch has a Referer, and the frame (no-referrer) has none
const signedIn = h.cookie?.includes("CF_Authorization") || (webkitEngine && h.referer);
if (!signedIn) return route.abort("failed"); // the proxy redirects to its sign-in, which the frame's CORS/CSP turn into an error
if (name === "dyn.js") return route.fulfill({ headers: { ...headers, "Content-Type": "text/javascript" }, body: "window.DYN = 42;" });
return route.fulfill({ status: 404, body: "" });
}
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: a script a page adds loads behind a proxy that wants a cookie`, async (t) => {
webkitEngine = engine === "webkit";
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const ctx = await browser.newContext({ viewport: { width: 1100, height: 700 }, reducedMotion: "reduce" });
await ctx.addCookies([{ name: "CF_Authorization", value: "x", url: "http://magpie.test/", sameSite: "Lax" }]);
const p = await ctx.newPage();
p.setDefaultTimeout(8000);
p.setDefaultNavigationTimeout(60000);
await p.route("**/*", server);
await p.goto("http://magpie.test/");
await p.locator("#nav button[data-plugin-page]").first().waitFor({ state: "attached" });
await p.evaluate(() => show("plugin-cookie"));
const frame = () => p.frames().find((x) => x.url().includes(tok));
for (let i = 0; i < 100 && !frame(); i++) await p.waitForTimeout(50);
assert.ok(frame(), "the frame opened");
assert.equal(await frame().evaluate(() => window.dyn), 42);
assert.equal(await p.locator("#view-plugin-cookie .slot-error").count(), 0);
});
}