plugin pages: name the scheme in a browser's policy, and the service's 'self' (#4198)

In `magpie web`, iOS Safari (18.7) loaded none of a plugin page's
scripts: pagePolicy named the page's folder as a scheme-less host-source
(host/_magpie/plugin/<tok>/), a sandboxed frame's origin is opaque, and
that WebKit took the missing scheme from it, so the bridge never said
hello and the page was broken at 10s (orinsid; YangHonghang on v0.1.2681,
young02036 on Discord).

- pagePolicy: a browser's policy now names the folder under both
  https:// and http:// (ownSources). Behind nginx or Cloudflare TLS ends
  before magpie and nothing magpie trusts says which scheme the page came
  over, so X-Forwarded-Proto is not read; both name the same host, port
  and folder, and an https page can't load http:// files anyway. The
  desktop window keeps its own transport alone (wails://, http:// on
  Windows, #2501).
- The second layer (YangHonghang): a page's local service sends its own
  policy, `connect-src 'self'`, and what it sends runs under magpie's
  `sandbox allow-scripts`. In WebKit, 'self' there didn't match the
  service page's own fetch of api/x. servePageService now names the
  service's root (/_magpie/plugin/<tok>/_magpie/service/) under both
  schemes after each 'self' in a CSP header the service sends, plus ws://
  and wss:// in connect-src and default-src (serviceSelf). 'self' stays,
  so nothing allowed before is taken away. A <meta> policy isn't
  rewritten; the plugin docs (en, zh, ja) say to write whole sources.

Run at f0a723d4c's tree (rebased on c74b932c8), on mote:
- go test ./internal/gui/: every test ok but TestMainWindowCorners, red
  the same at an origin/main e7185daeb copy (#3949, macOS 27). The real
  WKWebView test TestPluginPageLoadsItsFilesInTheWindow (desktop
  wails:// path) passes.
- gofmt -l, go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet:
  clean.
- node --test plugin-page, plugin-panels, plugin-page-idle (chromium and
  webkit): 14/14.
- win-run: TestPluginPage*, TestServiceSelf, TestPluginPanel* ok on
  Windows 11 (the window's http:// scheme).
- A scratch test (not committed) served the real pluginPageRoutes(web)
  and a fake service with "default-src 'self'; connect-src 'self'" over
  http and https (httptest TLS), framed sandbox=allow-scripts, in
  Playwright Chromium 151 and WebKit 26.5. At origin/main WebKit refused
  the service's fetch ("Refused to connect to .../_magpie/service/api/x
  because it does not appear in the connect-src directive", the
  reporter's words); with this change it fetched, and Chromium did both
  times. The page's bridge said hello in both engines both times.

Broken by hand: ownSources back to the scheme-less source and
serviceSelf skipped: TestPluginPageWebPolicyNamesItsScheme,
TestPluginPageServedShutIn, TestPluginPanelsServedShutIn,
TestPluginPageWindowPolicy and TestPluginPageServiceProxied go red.

Not tried: a real iPhone. Playwright's WebKit is not iOS Safari, and it
loads the scheme-less source fine, so the first layer is fixed on the
reporters' evidence and the CSP rule, not seen fail and pass here. Not
tried behind a real nginx or Cloudflare, nor a service WebSocket.
This commit is contained in:
yetone
2026-11-02 15:27:15 +08:00
parent c74b932c82
commit 1747559d02
11 changed files with 187 additions and 16 deletions
+13 -2
View File
@@ -316,8 +316,19 @@ starts a Bun host.
(macOS, Linux), and a sandboxed frame has an opaque origin, so a CSP
source without a scheme matches only http(s) there. `ownWindow` puts the
native scheme on the request's context and `pagePolicy` names the folder
under it (#2501); the web keeps a scheme-less source.
`TestPluginPageWindowPolicy` checks the policy, and
under it (#2501). iOS Safari (18.7) takes a missing scheme from that
opaque origin on http(s) too, and loaded none of a page's scripts from
`magpie web` (#4198): a browser's policy names the folder
under both `https://` and `http://` (`ownSources`), since a proxy that
ends TLS (nginx, Cloudflare) leaves magpie nothing it trusts to say
which. A page's service sends its own policy, where `'self'` meant its
whole 127.0.0.1 origin; sandboxed, WebKit refused the service page's
fetches under `connect-src 'self'`. `serviceSelf` names the service's
root under both schemes after each `'self'` in a policy header it sends
(and `ws://`, `wss://` in `connect-src` and `default-src`); a `<meta>`
policy is the plugin's to write with whole sources.
`TestPluginPageWindowPolicy`, `TestPluginPageWebPolicyNamesItsScheme`,
`TestServiceSelf` and `TestPluginPageServiceProxied` check the policies, and
`TestPluginPageLoadsItsFilesInTheWindow` loads a page through
`ownWindow` in a real WKWebView; Playwright, on http, can't see it.
- **Slots.** A page names a slot with `<div class="plugin-slot"
+56
View File
@@ -39,6 +39,52 @@ const pageServicePath = "_magpie/service/"
// plugin's scripts would have the window's cookie and its /api.
const pageServicePolicy = "sandbox allow-scripts; frame-ancestors 'self'"
// serviceSelf is policy, a Content-Security-Policy the page's service
// sent, with every 'self' followed by self, the service's root under this
// server named with its scheme (ownSources). To the service, 'self' is
// all of 127.0.0.1:<port>, which is that root here. But what it sends runs
// sandboxed (pageServicePolicy), in an opaque origin, and WebKit doesn't
// match a fetch to 'self' there: the service's own page refused its every
// fetch of api/… (YangHonghang on #4198, `connect-src 'self'`), while
// Chromium let it through. connect-src gets ws:// and wss:// too, for a WebSocket,
// which 'self' covers and an http(s) source doesn't. 'self' stays, so
// nothing a browser allowed before is taken away. A policy in a <meta>
// tag of the service's page isn't seen here, and is the plugin's to write
// with whole sources.
func serviceSelf(policy string, self []string) string {
ds := strings.Split(policy, ";")
for i, d := range ds {
f := strings.Fields(d)
if len(f) < 2 {
continue
}
add := append([]string(nil), self...)
if strings.EqualFold(f[0], "connect-src") || strings.EqualFold(f[0], "default-src") {
for _, s := range self {
if rest, ok := strings.CutPrefix(s, "http"); ok {
add = append(add, "ws"+rest)
}
}
}
out := []string{f[0]}
named := false
for _, src := range f[1:] {
out = append(out, src)
if strings.EqualFold(src, "'self'") && !named {
out = append(out, add...)
named = true
}
}
if named {
ds[i] = " " + strings.Join(out, " ")
if i == 0 {
ds[i] = ds[i][1:]
}
}
}
return strings.Join(ds, ";")
}
// pageServiceTransport dials the service on loopback, never through a
// proxy.
var pageServiceTransport = &http.Transport{
@@ -115,6 +161,16 @@ func servePageService(rw http.ResponseWriter, r *http.Request, p *pluginPage, to
ModifyResponse: func(res *http.Response) error {
h := res.Header
h.Del("Set-Cookie")
// the service's own policy, its 'self' named for WebKit
// (serviceSelf); then magpie's sandbox
if v := h.Values("Content-Security-Policy"); len(v) > 0 {
self := ownSources(r, root)
out := make([]string, len(v))
for i, policy := range v {
out[i] = serviceSelf(policy, self)
}
h["Content-Security-Policy"] = out
}
h.Add("Content-Security-Policy", pageServicePolicy)
h.Set("Referrer-Policy", "no-referrer")
h.Set("X-Content-Type-Options", "nosniff")
+29
View File
@@ -45,6 +45,8 @@ func newFakeService(t *testing.T) *fakeService {
switch r.URL.Path {
case "/":
http.SetCookie(rw, &http.Cookie{Name: "svc", Value: "1"})
// YangHonghang's chat service on #4198
rw.Header().Set("Content-Security-Policy", "default-src 'self'; connect-src 'self'; img-src 'self' data:")
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(rw, `<!doctype html><title>chat</title><script src="app.js"></script>`)
case "/api/chat":
@@ -255,6 +257,15 @@ func TestPluginPageServiceProxied(t *testing.T) {
if res.Header.Get("Referrer-Policy") != "no-referrer" {
t.Errorf("Referrer-Policy %q", res.Header.Get("Referrer-Policy"))
}
// the service's own 'self' named with its scheme, for WebKit's
// sandboxed frame (#4198); magpie's sandbox still after it
root := strings.TrimPrefix(srv.URL, "http://") + strings.TrimSuffix(p.URL, "index.html") + pageServicePath
if v := res.Header.Values("Content-Security-Policy"); len(v) != 2 || v[1] != pageServicePolicy ||
v[0] != "default-src 'self' https://"+root+" http://"+root+" wss://"+root+" ws://"+root+
"; connect-src 'self' https://"+root+" http://"+root+" wss://"+root+" ws://"+root+
"; img-src 'self' https://"+root+" http://"+root+" data:" {
t.Errorf("the service's policy: %q", v)
}
// a path and query of the service's own
res = get(base + "api/icon/a%2Fb.png?size=2")
@@ -375,3 +386,21 @@ func TestServiceLocation(t *testing.T) {
}
}
}
// serviceSelf names the service's root beside each 'self', in any case,
// once a directive, and leaves a policy with none as it came.
func TestServiceSelf(t *testing.T) {
self := []string{"https://h/r/", "http://h/r/"}
for _, c := range []struct{ in, want string }{
{"connect-src 'self'", "connect-src 'self' https://h/r/ http://h/r/ wss://h/r/ ws://h/r/"},
{"script-src 'SELF' 'unsafe-inline'; frame-ancestors 'none'", "script-src 'SELF' https://h/r/ http://h/r/ 'unsafe-inline'; frame-ancestors 'none'"},
{"img-src 'self' 'self'", "img-src 'self' https://h/r/ http://h/r/ 'self'"},
{"default-src 'none'; style-src https://cdn.example", "default-src 'none'; style-src https://cdn.example"},
{"", ""},
{"upgrade-insecure-requests; script-src 'self'", "upgrade-insecure-requests; script-src 'self' https://h/r/ http://h/r/"},
} {
if got := serviceSelf(c.in, self); got != c.want {
t.Errorf("serviceSelf(%q) = %q, want %q", c.in, got, c.want)
}
}
}
+22 -7
View File
@@ -228,13 +228,7 @@ func pagePolicy(r *http.Request, tok string) string {
own := "'self'"
if r.Host != "" {
// the page's own folder: not the window's files, nor /api
own = r.Host + pluginPagePrefix + tok + "/"
// WebKit does not match a scheme-less host source under wails://.
// Only the native handler supplies this scheme; web keeps its
// relative source so HTTP, HTTPS and reverse proxies still work.
if scheme, _ := r.Context().Value(windowSchemeKey{}).(string); scheme != "" {
own = scheme + "://" + own
}
own = strings.Join(ownSources(r, pluginPagePrefix+tok+"/"), " ")
}
return strings.Join([]string{
"sandbox allow-scripts",
@@ -254,6 +248,27 @@ func pagePolicy(r *http.Request, tok string) string {
}, "; ")
}
// ownSources are the sources, with their scheme, that name path on the
// address r came to. A sandboxed frame's origin is opaque, and a source
// with no scheme takes its scheme from that origin: iOS Safari (iOS 18.7)
// matched the scheme-less host/path to nothing and never asked for a
// page's scripts, so the page was broken at 10s (#4198, orinsid and
// YangHonghang). Chromium, and the newer WebKit Playwright runs, take
// the scheme from the URL loaded, which is why only the iPhone failed.
//
// The desktop window names its own transport (ownWindow): wails://, or
// http:// on Windows (#2501). A browser's page (magpie web) can come over
// http or https, directly or through a proxy that ends TLS before magpie
// (nginx, Cloudflare), and nothing magpie trusts says which, so both are
// named: the same host, port and folder either way, and an https page
// can't load http:// files anyway (mixed content).
func ownSources(r *http.Request, path string) []string {
if scheme, _ := r.Context().Value(windowSchemeKey{}).(string); scheme != "" {
return []string{scheme + "://" + r.Host + path}
}
return []string{"https://" + r.Host + path, "http://" + r.Host + path}
}
// pageHostWait is how long a page's HTML waits for its plugin's host,
// short of the window's 10 seconds for the page to say hello
// (pluginpages.js's HELLO_MS).
+1 -1
View File
@@ -109,7 +109,7 @@ func TestPluginPageServedShutIn(t *testing.T) {
t.Fatalf("the page: %d %s", w.Code, w.Body)
}
csp := w.Header().Get("Content-Security-Policy")
for _, want := range []string{"sandbox allow-scripts", "default-src 'none'", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;", "form-action 'none'", "frame-src 'none'"} {
for _, want := range []string{"sandbox allow-scripts", "default-src 'none'", "connect-src 'none'", "script-src https://127.0.0.1:3437" + pluginPagePrefix + tok + "/ http://127.0.0.1:3437" + pluginPagePrefix + tok + "/;", "form-action 'none'", "frame-src 'none'"} {
if !strings.Contains(csp, want) {
t.Errorf("policy %q has no %q", csp, want)
}
+59 -2
View File
@@ -28,8 +28,8 @@ func TestPluginPageWindowPolicy(t *testing.T) {
source string
}{
{"desktop", desktopHost, true, desktop},
{"web", "127.0.0.1:3437", false, "127.0.0.1:3437"},
{"web localhost", "localhost", false, "localhost"},
{"web", "127.0.0.1:3437", false, "https://127.0.0.1:3437"},
{"web localhost", "localhost", false, "https://localhost"},
} {
t.Run(c.name, func(t *testing.T) {
var handler http.Handler = pageMux()
@@ -63,3 +63,60 @@ func TestPluginPageWindowPolicy(t *testing.T) {
})
}
}
// A browser's page (magpie web) names its folder with a scheme: WebKit
// takes a scheme-less source's scheme from the sandboxed frame's opaque
// origin and matched nothing, so iOS Safari loaded no script (#4198).
// Served over http, or https with TLS ended by a proxy in front, both
// schemes are named, on the Host the browser asked for; what the proxy
// says in its forwarding headers changes nothing.
func TestPluginPageWebPolicyNamesItsScheme(t *testing.T) {
pagePlugins(t)
page := pluginPages()[0]
for _, c := range []struct {
name, host string
hdr map[string]string
}{
{"http", "192.168.1.5:3430", nil},
{"https behind nginx", "magpie.test.xyz", map[string]string{"X-Forwarded-Proto": "https", "X-Forwarded-For": "1.2.3.4"}},
{"https behind Cloudflare", "magpie.test.xyz", map[string]string{"X-Forwarded-Proto": "https", "Cf-Visitor": `{"scheme":"https"}`, "X-Forwarded-Host": "evil.example"}},
} {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest("GET", pluginPagePrefix+page.token+"/index.html", nil)
r.Host = c.host
for k, v := range c.hdr {
r.Header.Set(k, v)
}
w := do(pageMux(), r)
if w.Code != http.StatusOK {
t.Fatalf("HTTP %d", w.Code)
}
policy := w.Header().Get("Content-Security-Policy")
folder := c.host + pluginPagePrefix + page.token + "/"
want := "https://" + folder + " http://" + folder
for _, d := range []string{"script-src " + want + ";", "style-src " + want + " 'unsafe-inline';", "img-src " + want + " data:;", "font-src " + want + ";", "media-src " + want + ";"} {
if !strings.Contains(policy, d) {
t.Errorf("policy has no %q: %s", d, policy)
}
}
// no source without its scheme is left
for _, d := range strings.Split(policy, ";") {
for _, src := range strings.Fields(d)[1:] {
if strings.Contains(src, "/_magpie/") && !strings.HasPrefix(src, "https://") && !strings.HasPrefix(src, "http://") {
t.Errorf("scheme-less source %q in %s", src, policy)
}
}
}
if strings.Contains(policy, "evil.example") {
t.Errorf("a forwarding header named a host: %s", policy)
}
})
}
// the desktop window names its own transport alone
r := httptest.NewRequest("GET", pluginPagePrefix+page.token+"/index.html", nil)
r.Host = "localhost"
w := do(ownWindow(pageMux()), r)
if policy := w.Header().Get("Content-Security-Policy"); strings.Contains(policy, "https://") {
t.Errorf("the window's policy names https: %s", policy)
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ func TestPluginPanelsServedShutIn(t *testing.T) {
t.Fatalf("panel %d: %d %s", i, w.Code, w.Body)
}
csp := w.Header().Get("Content-Security-Policy")
for _, want := range []string{"sandbox allow-scripts", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;"} {
for _, want := range []string{"sandbox allow-scripts", "connect-src 'none'", "script-src https://127.0.0.1:3437" + pluginPagePrefix + tok + "/ http://127.0.0.1:3437" + pluginPagePrefix + tok + "/;"} {
if !strings.Contains(csp, want) {
t.Errorf("panel %d: policy %q has no %q", i, csp, want)
}
+3 -3
View File
@@ -38,11 +38,11 @@ const pages = [
entry(BROKEN, "broken", "Broken", []),
];
// what pluginpage.go's pagePolicy sends, for this host: the page's folder
// under each scheme the window is served on
// what pluginpage.go's pagePolicy sends a browser, for this host: the
// page's folder under https and http (ownSources, #4198)
const policy = (tok) => {
const dir = `magpie.test/_magpie/plugin/${tok}/`;
const own = `wails://${dir} http://${dir} https://${dir}`;
const own = `https://${dir} http://${dir}`;
return [
"sandbox allow-scripts", "default-src 'none'", `script-src ${own}`, `style-src ${own} 'unsafe-inline'`,
`img-src ${own} data:`, `font-src ${own}`, `media-src ${own}`, "connect-src 'none'", "frame-src 'none'",
+1
View File
@@ -912,6 +912,7 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls
<ul>
<li>ページはスクリプトだけを許したサンドボックスのフレーム(<code>sandbox="allow-scripts"</code>、<code>Content-Security-Policy</code> でも同じ)で、独自のオリジンで動きます。ウィンドウにも、magpie の cookie にも、ウィンドウのストレージにも届きません。</li>
<li>ポリシーで読み込めるのは自分のファイルだけです。<code>connect-src 'none'</code> なので <code>fetch</code>、WebSocket、beacon は使えず、フォームやフレームもありません。スクリプトはファイル(<code>&lt;script src&gt;</code>)にする必要があり、インラインは使えません。インラインのスタイルと <code>data:</code> の画像は使えます。</li>
<li>sandbox のフレームでは、WebKit(iPhone と Mac の Safari、Mac と Linux のウィンドウ)は <code>'self'</code> やスキームのないソースを何にも一致させないことがあります。<code>connect-src 'self'</code> の <code>fetch</code> は拒否されます。プラグインのサービスが返すページも sandbox で動くので、自分のポリシーには完全なソース(<code>https://…</code>)を書いてください。サービスが <code>magpie web</code> 経由で送る <code>Content-Security-Policy</code> ヘッダーでは、magpie が各 <code>'self'</code> の後にサービスのアドレスを足します。<code>&lt;meta&gt;</code> タグのものには足しません。</li>
<li>このようなフレームが送れるリクエスト(<code>Origin: null</code>、フレームからのリクエスト、ほかのサイトのリクエスト)は magpie の API がすべて拒否するので、ポリシーがなくてもページは API に入れません。ファイルは <code>/_magpie/plugin/&lt;token&gt;/</code> から配信され、token は magpie を起動するたびに変わります。</li>
<li>それでもページは自分をほかのサイトへ移動できます。そのサイトがフレームを持つことになるので、読み取りは秘密でないものだけを返します。ページが読めるものは公開されたものとして扱ってください。</li>
<li>ページが捕まえなかったエラーは、その場所に<span class="ui">このページは動作を停止しました</span>と<span class="ui">再試行</span>を表示します。ページ自身のスクリプトのエラーはページには「Script error.」としか届かないので、詳しくはウィンドウのコンソールを見てください。</li>
+1
View File
@@ -912,6 +912,7 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls
<ul>
<li>The page runs in a frame sandboxed to scripts alone (<code>sandbox="allow-scripts"</code>, and the same in its <code>Content-Security-Policy</code>), in an origin of its own. It can’t reach the window, magpie’s cookie or the window’s storage.</li>
<li>Its policy allows its own files and nothing else: <code>connect-src 'none'</code>, so no <code>fetch</code>, WebSocket or beacon, and no forms or frames. Scripts must be files (<code>&lt;script src&gt;</code>), not inline. Inline styles and <code>data:</code> pictures are fine.</li>
<li>In a sandboxed frame, WebKit (Safari on iPhone and Mac, the Mac and Linux window) may match <code>'self'</code>, or a source without a scheme, to nothing: a <code>fetch</code> under <code>connect-src 'self'</code> is refused. A page your plugin’s service serves, which runs sandboxed too, should name whole sources (<code>https://…</code>) in its own policy. magpie adds the service’s address next to each <code>'self'</code> in a <code>Content-Security-Policy</code> header the service sends through <code>magpie web</code>, but not in a <code>&lt;meta&gt;</code> tag.</li>
<li>magpie’s API refuses any request a frame like this one can make (<code>Origin: null</code>, a frame or another site’s request), so it is closed to the page even without the policy. Its files are served at <code>/_magpie/plugin/&lt;token&gt;/</code>, a token that changes each time magpie starts.</li>
<li>A page can still send itself to another site, which then holds its frame. That is why reads give nothing secret. Treat what a page can read as public.</li>
<li>An error the page doesn’t catch shows <span class="ui">This page stopped working</span> in its place, with <span class="ui">Try again</span>. Its own scripts’ errors reach it as “Script error.”, so look in the window’s console for the rest.</li>
+1
View File
@@ -912,6 +912,7 @@ document.getElementById(<span class="s">"calls"</span>).textContent = `${s.calls
<ul>
<li>页面运行在只允许脚本的沙盒框架里(<code>sandbox="allow-scripts"</code>,它的 <code>Content-Security-Policy</code> 里也一样),有自己独立的 origin。它碰不到窗口、magpie 的 cookie 和窗口的存储。</li>
<li>它的策略只允许加载自己的文件:<code>connect-src 'none'</code>,所以没有 <code>fetch</code>、WebSocket 或 beacon,也没有表单和框架。脚本必须是文件(<code>&lt;script src&gt;</code>),不能内联;内联样式和 <code>data:</code> 图片可以。</li>
<li>在 sandbox 框架里,WebKit(iPhone 和 Mac 上的 Safari、Mac 和 Linux 的窗口)的 <code>'self'</code> 和不带 scheme 的源可能什么都匹配不上:<code>connect-src 'self'</code> 下的 <code>fetch</code> 会被拦下。插件服务提供的页面同样在 sandbox 里运行,它自己的策略应写完整的源(<code>https://…</code>)。服务经 <code>magpie web</code> 发出的 <code>Content-Security-Policy</code> 响应头里,magpie 会在每个 <code>'self'</code> 后面补上服务的地址,<code>&lt;meta&gt;</code> 标签里的不会。</li>
<li>这种框架能发出的请求(<code>Origin: null</code>、框架请求、别的网站的请求),magpie 的 API 都会拒绝,所以就算没有策略,页面也进不了 API。它的文件从 <code>/_magpie/plugin/&lt;token&gt;/</code> 提供,token 每次 magpie 启动都会变。</li>
<li>页面仍然可以把自己跳转到别的网站,那个网站就接管了它的框架。所以读取只给不机密的东西:把页面能读到的都当作公开的。</li>
<li>页面没接住的错误会在它的位置显示<span class="ui">此页面已停止工作</span>和<span class="ui">重试</span>。它自己脚本的错误在页面里只显示为“Script error.”,详细内容看窗口的控制台。</li>