diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md
index b70a68b9c..461ce0d6c 100644
--- a/docs/subsystems/plugin-runtime.md
+++ b/docs/subsystems/plugin-runtime.md
@@ -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 ``
+ 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 `
, 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
+// 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")
diff --git a/internal/gui/pageservice_test.go b/internal/gui/pageservice_test.go
index 42e9e7fff..3fa4dbef1 100644
--- a/internal/gui/pageservice_test.go
+++ b/internal/gui/pageservice_test.go
@@ -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, `
chat`)
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)
+ }
+ }
+}
diff --git a/internal/gui/pluginpage.go b/internal/gui/pluginpage.go
index e2d1fd67e..bced6a399 100644
--- a/internal/gui/pluginpage.go
+++ b/internal/gui/pluginpage.go
@@ -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).
diff --git a/internal/gui/pluginpage_test.go b/internal/gui/pluginpage_test.go
index c1941cf89..12396df70 100644
--- a/internal/gui/pluginpage_test.go
+++ b/internal/gui/pluginpage_test.go
@@ -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)
}
diff --git a/internal/gui/pluginpage_window_test.go b/internal/gui/pluginpage_window_test.go
index 41412b43a..d2587696d 100644
--- a/internal/gui/pluginpage_window_test.go
+++ b/internal/gui/pluginpage_window_test.go
@@ -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)
+ }
+}
diff --git a/internal/gui/pluginpanel_test.go b/internal/gui/pluginpanel_test.go
index b5a9209c1..0b2f64a2f 100644
--- a/internal/gui/pluginpanel_test.go
+++ b/internal/gui/pluginpanel_test.go
@@ -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)
}
diff --git a/internal/gui/tests/plugin-page.test.cjs b/internal/gui/tests/plugin-page.test.cjs
index a93c079e6..9300e5d70 100644
--- a/internal/gui/tests/plugin-page.test.cjs
+++ b/internal/gui/tests/plugin-page.test.cjs
@@ -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'",
diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.html
index e47d28ebf..0056bd1bd 100644
--- a/site/public/docs/ja/plugins.html
+++ b/site/public/docs/ja/plugins.html
@@ -912,6 +912,7 @@ document.getElementById(
"calls").textContent = `${s.calls
- ページはスクリプトだけを許したサンドボックスのフレーム(
sandbox="allow-scripts"、Content-Security-Policy でも同じ)で、独自のオリジンで動きます。ウィンドウにも、magpie の cookie にも、ウィンドウのストレージにも届きません。
- ポリシーで読み込めるのは自分のファイルだけです。
connect-src 'none' なので fetch、WebSocket、beacon は使えず、フォームやフレームもありません。スクリプトはファイル(<script src>)にする必要があり、インラインは使えません。インラインのスタイルと data: の画像は使えます。
+ - sandbox のフレームでは、WebKit(iPhone と Mac の Safari、Mac と Linux のウィンドウ)は
'self' やスキームのないソースを何にも一致させないことがあります。connect-src 'self' の fetch は拒否されます。プラグインのサービスが返すページも sandbox で動くので、自分のポリシーには完全なソース(https://…)を書いてください。サービスが magpie web 経由で送る Content-Security-Policy ヘッダーでは、magpie が各 'self' の後にサービスのアドレスを足します。<meta> タグのものには足しません。
- このようなフレームが送れるリクエスト(
Origin: null、フレームからのリクエスト、ほかのサイトのリクエスト)は magpie の API がすべて拒否するので、ポリシーがなくてもページは API に入れません。ファイルは /_magpie/plugin/<token>/ から配信され、token は magpie を起動するたびに変わります。
- それでもページは自分をほかのサイトへ移動できます。そのサイトがフレームを持つことになるので、読み取りは秘密でないものだけを返します。ページが読めるものは公開されたものとして扱ってください。
- ページが捕まえなかったエラーは、その場所にこのページは動作を停止しましたと再試行を表示します。ページ自身のスクリプトのエラーはページには「Script error.」としか届かないので、詳しくはウィンドウのコンソールを見てください。
diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.html
index 4b70bf716..44d24dfda 100644
--- a/site/public/docs/plugins.html
+++ b/site/public/docs/plugins.html
@@ -912,6 +912,7 @@ document.getElementById("calls").textContent = `${s.calls
- The page runs in a frame sandboxed to scripts alone (
sandbox="allow-scripts", and the same in its Content-Security-Policy), in an origin of its own. It can’t reach the window, magpie’s cookie or the window’s storage.
- Its policy allows its own files and nothing else:
connect-src 'none', so no fetch, WebSocket or beacon, and no forms or frames. Scripts must be files (<script src>), not inline. Inline styles and data: pictures are fine.
+ - In a sandboxed frame, WebKit (Safari on iPhone and Mac, the Mac and Linux window) may match
'self', or a source without a scheme, to nothing: a fetch under connect-src 'self' is refused. A page your plugin’s service serves, which runs sandboxed too, should name whole sources (https://…) in its own policy. magpie adds the service’s address next to each 'self' in a Content-Security-Policy header the service sends through magpie web, but not in a <meta> tag.
- magpie’s API refuses any request a frame like this one can make (
Origin: null, a frame or another site’s request), so it is closed to the page even without the policy. Its files are served at /_magpie/plugin/<token>/, a token that changes each time magpie starts.
- 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.
- An error the page doesn’t catch shows This page stopped working in its place, with Try again. Its own scripts’ errors reach it as “Script error.”, so look in the window’s console for the rest.
diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.html
index 336e94332..27ca3b659 100644
--- a/site/public/docs/zh/plugins.html
+++ b/site/public/docs/zh/plugins.html
@@ -912,6 +912,7 @@ document.getElementById("calls").textContent = `${s.calls
- 页面运行在只允许脚本的沙盒框架里(
sandbox="allow-scripts",它的 Content-Security-Policy 里也一样),有自己独立的 origin。它碰不到窗口、magpie 的 cookie 和窗口的存储。
- 它的策略只允许加载自己的文件:
connect-src 'none',所以没有 fetch、WebSocket 或 beacon,也没有表单和框架。脚本必须是文件(<script src>),不能内联;内联样式和 data: 图片可以。
+ - 在 sandbox 框架里,WebKit(iPhone 和 Mac 上的 Safari、Mac 和 Linux 的窗口)的
'self' 和不带 scheme 的源可能什么都匹配不上:connect-src 'self' 下的 fetch 会被拦下。插件服务提供的页面同样在 sandbox 里运行,它自己的策略应写完整的源(https://…)。服务经 magpie web 发出的 Content-Security-Policy 响应头里,magpie 会在每个 'self' 后面补上服务的地址,<meta> 标签里的不会。
- 这种框架能发出的请求(
Origin: null、框架请求、别的网站的请求),magpie 的 API 都会拒绝,所以就算没有策略,页面也进不了 API。它的文件从 /_magpie/plugin/<token>/ 提供,token 每次 magpie 启动都会变。
- 页面仍然可以把自己跳转到别的网站,那个网站就接管了它的框架。所以读取只给不机密的东西:把页面能读到的都当作公开的。
- 页面没接住的错误会在它的位置显示此页面已停止工作和重试。它自己脚本的错误在页面里只显示为“Script error.”,详细内容看窗口的控制台。