settings, gateway, gui: a browser extension is listed among the web pages that may call magpie by its origin, chrome-extension://<id> and the like (#1051, SkyAerope on Discord)

What: Settings › Network and sharing › Web pages now takes a browser
extension's origin besides http(s) ones: chrome-extension://<id>
(Chromium, the id 32 letters a-p), moz-extension://<uuid> (Firefox's
Internal UUID) and safari-web-extension://<uuid> (Safari). cleanOrigin
takes only those three schemes, only with an id of that browser's shape,
lower-cased and with a trailing "/" let go; a bare scheme, a wildcard, a
path, a port, user info, a query or another browser's id shape is
refused. The GUI maps the new refusal to the same message, which now
names the extension form, in en/zh/zh-TW/ja/de, and a listed origin
wraps instead of being cut (an extension's runs to 50-60 characters and
was ellipsized at a 440px panel). The 401 a listed caller gets without a
key names extensions too. Docs: gateway-routing.md, the settings field.

Why: an extension without host_permissions (Sider and the like) is held
to CORS; the gateway never answered its preflight, since its origin
couldn't be listed. Nothing else in the access rules changes: corsGuard
treats a listed extension exactly as a listed page (preflight answered,
every call needs an enabled gateway key or gets 401, even on loopback),
an unlisted extension passes with no CORS headers as before (foreignPage
still only judges http/https), and lanGuard's rebound/Host checks, the
allow list and every other route guard are untouched.

The Origin each browser sends was checked, not guessed: real Chromium
(below) sent Origin: chrome-extension://<32 a-p>; Firefox's is
moz-extension://<Internal UUID> (Gotify's and others' CORS docs list
it); Safari's is safari-web-extension://<lowercase uuid>, per Apple's
developer forums (thread 654839), where an Apple engineer notes the uuid
changes on each Safari launch, so a Safari listing lasts until it
restarts (said in the doc). A content script's fetch carries the page's
origin (MDN), so only extension pages, popups and workers are covered.

Run, at 28aac86bc:
- TestCleanExtensionOrigins (good ids, upper case, trailing slash;
  malformed, wildcard, bare scheme, path, port, userinfo, query, swapped
  id shapes) and TestCORSExtensionOrigin (through lanGuard: unlisted
  preflight/request get no CORS headers and the request runs as before;
  listed chrome and moz preflight 204 with the headers; keyed call 200
  with Access-Control-Allow-Origin; keyless or wrong key 401 without
  reaching the vendor; another id still unlisted). Both fail on the old
  origins.go (the extension origin "is not an origin").
- go test ./internal/settings ./internal/gateway ./internal/gui: green.
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui,
  GOOS=windows: clean.
- GUI: cors-origins (extended: an extension added upper-cased with a
  trailing slash is saved lower-cased and fits the panel, a malformed id
  and chrome-extension://* refused in the page's language), i18n-keys,
  gui-de, gui-ja, gui-zh-tw, allow-ips, lan-docker, chromium and webkit:
  green. cors-origins fails on the old app.js/app.css (the name was cut,
  the extension refusal untranslated).
- Real use: an unpacked MV3 extension with no host_permissions, loaded in
  headless Chromium 1234 (playwright launchPersistentContext,
  --load-extension), fetched a sandbox gateway (lanGuard(New().Handler())
  on 127.0.0.1:3591 under a temp HOME, fake vendor) from its service
  worker and its own page. Not listed: "Failed to fetch" in all four
  cases. Listed (typed upper-case with "/"): with the key, read 200 and
  the vendor's reply; without it, read the 401.

Not tried: Firefox and Safari extensions for real (their origins are from
the sources above), Edge/Brave, and the full magpie serve binary (the
harness ran the gateway's own handler stack, not its background loops).
This commit is contained in:
yetone
2026-10-13 01:57:37 +08:00
parent fe4295e1db
commit 91e7ef56af
10 changed files with 228 additions and 23 deletions
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -13,8 +13,9 @@ import (
"github.com/yetone/magpie/internal/settings"
)
// corsGuard lets the web pages the user listed in Settings › Gateway
// (settings.CORSOrigins, #1051) call the gateway from a browser: their
// corsGuard lets the web pages and browser extensions the user listed
// in Settings › Network (settings.CORSOrigins, #1051) call the gateway
// from a browser: their
// preflight is answered, and their calls get the headers that let the page
// read the reply. Such a call carries an enabled gateway key — a page is
// not an agent the user started, and on loopback a call needs no key, so
@@ -62,7 +63,7 @@ func corsGuard(next http.Handler) http.Handler {
keyed := access.Caller(r.Context()).KeyID != "" ||
slices.ContainsFunc(callerKeys(r), func(k string) bool { _, ok := access.Authenticate(k); return ok })
if !keyed {
writeError(w, provider.Chat, http.StatusUnauthorized, "a web page calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer <key> (or x-api-key)")
writeError(w, provider.Chat, http.StatusUnauthorized, "a web page or browser extension calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer <key> (or x-api-key)")
return
}
next.ServeHTTP(w, r)
+102
View File
@@ -289,3 +289,105 @@ func TestForeignPagesRefused(t *testing.T) {
t.Errorf("usemagpie.ai's Omarchy theme: %d %s", w.Code, w.Body)
}
}
// A browser extension the user listed by its origin (#1051, SkyAerope on
// Discord: an extension such as Sider, without host permissions, is held
// to CORS like a page) is treated as a listed web page is, no more: its
// preflight is answered, its keyed call reads the reply, and a call
// without a gateway key is refused 401. An extension not listed is
// answered as before — no CORS headers, so only one that holds host
// permissions (and doesn't enforce CORS) reads anything.
func TestCORSExtensionOrigin(t *testing.T) {
fresh(t)
var hits atomic.Int64
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
t.Fatal(err)
}
secret, err := access.Update("add-key", access.Change{Name: "Extension"})
if err != nil {
t.Fatal(err)
}
const ext = "chrome-extension://abcdefghijklmnopabcdefghijklmnop"
const other = "chrome-extension://ponmlkjihgfedcbaponmlkjihgfedcba"
const fox = "moz-extension://e0b5d7c7-c079-484b-8825-44d261383cb6"
srv := lanGuard(New().Handler())
do := func(method, origin, key string) *httptest.ResponseRecorder {
t.Helper()
var body io.Reader
if method == "POST" {
body = strings.NewReader(chatReq)
}
r := httptest.NewRequest(method, "/v1/chat/completions", body)
r.RemoteAddr = "127.0.0.1:50123"
r.Host = "127.0.0.1:3425"
r.Header.Set("Origin", origin)
r.Header.Set("Sec-Fetch-Mode", "cors")
r.Header.Set("User-Agent", "Mozilla/5.0 Chrome/140.0")
if method == "OPTIONS" {
r.Header.Set("Access-Control-Request-Method", "POST")
r.Header.Set("Access-Control-Request-Headers", "authorization, content-type")
} else {
r.Header.Set("Content-Type", "application/json")
}
if key != "" {
r.Header.Set("Authorization", "Bearer "+key)
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, r)
return w
}
// not listed: no CORS headers, as before; a web page listed doesn't list it
s := settings.Load()
s.CORSOrigins = []string{"http://localhost:3000"}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if w := do("OPTIONS", ext, ""); w.Code == http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Fatalf("unlisted extension's preflight: %d %v", w.Code, w.Header())
}
if w := do("POST", ext, ""); w.Code != http.StatusOK || w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Fatalf("unlisted extension, as before: %d %v %s", w.Code, w.Header(), w.Body)
}
// listed, written as the user might copy it
if s.CORSOrigins, err = settings.CleanOrigins([]string{"http://localhost:3000", "CHROME-EXTENSION://ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP/", fox}); err != nil {
t.Fatal(err)
}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
for _, o := range []string{ext, fox} {
w := do("OPTIONS", o, "")
if w.Code != http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != o ||
w.Header().Get("Access-Control-Allow-Headers") != "authorization, content-type" || !strings.Contains(w.Header().Get("Access-Control-Allow-Methods"), "POST") {
t.Errorf("%s preflight: %d %v", o, w.Code, w.Header())
}
if w := do("POST", o, secret); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "ok") || w.Header().Get("Access-Control-Allow-Origin") != o {
t.Errorf("%s with its key: %d %v %s", o, w.Code, w.Header(), w.Body)
}
}
n := hits.Load()
// a listed extension needs a gateway key, as a listed page does
if w := do("POST", ext, ""); w.Code != http.StatusUnauthorized || w.Header().Get("Access-Control-Allow-Origin") != ext || !strings.Contains(w.Body.String(), "gateway key") {
t.Errorf("listed extension without a key: %d %v %s", w.Code, w.Header(), w.Body)
}
if w := do("POST", ext, "not-a-key"); w.Code != http.StatusUnauthorized {
t.Errorf("listed extension with a wrong key: %d %s", w.Code, w.Body)
}
if hits.Load() != n {
t.Fatal("a keyless call from a listed extension reached the vendor")
}
// another extension is still not listed
if w := do("OPTIONS", other, ""); w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Errorf("another extension's preflight: %d %v", w.Code, w.Header())
}
if w := do("POST", other, secret); w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Errorf("another extension: %d %v", w.Code, w.Header())
}
}
+1
View File
@@ -2996,6 +2996,7 @@ input.words.compact-num { flex: none; width: 76px; font-variant-numeric: tabular
.row.pref.rule-row { flex-wrap: wrap; row-gap: 8px; }
.row.pref.rule-row .who { flex: 1 1 100%; }
.row.pref.rule-row .sub { white-space: normal; }
.row.pref.cors-origin .name { white-space: normal; overflow-wrap: anywhere; }
/* a kind of personal data, under Mask personal data */
.row.pref.redact-kind .who { padding-left: 14px; min-width: 0; }
.row.pref.redact-kind .sub { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
+2 -2
View File
@@ -22434,7 +22434,7 @@ let corsDraft = { value: "", err: "" };
// page's language
function corsSays(m) {
if (/wildcard/.test(m)) return t("Name each origin: a wildcard would let every web page use magpie");
if (/is not an origin/.test(m)) return t("Write an origin as http://localhost:3000 or https://app.example.com");
if (/is not an (extension's )?origin/.test(m)) return t("Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID");
return t(m);
}
function renderCORS(s) {
@@ -22467,7 +22467,7 @@ function renderCORS(s) {
r.append(who, val);
box.append(r);
for (const o of origins) {
const row = el("div", "row pref");
const row = el("div", "row pref cors-origin"); // an extension's id runs long: wrapped, never cut
const w = el("div", "who");
w.append(el("div", "name", o));
const x = el("button", "text", t("Remove"));
+4 -4
View File
@@ -1898,7 +1898,7 @@ const I18N = {
"MAGPIE_ALLOW_IPS sets this list; change it there": "此列表由 MAGPIE_ALLOW_IPS 设置,请在那里修改",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "这些来源的网页脚本可以在浏览器中调用网关,每个请求需带上「网关」页的网关密钥。其他网站的网页会被拒绝,本机的网页不受影响",
"Name each origin: a wildcard would let every web page use magpie": "请逐个填写来源:通配符会让任何网页都能使用 magpie",
"Write an origin as http://localhost:3000 or https://app.example.com": "来源格式如 http://localhost:3000 或 https://app.example.com",
"Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "来源格式如 http://localhost:3000 或 https://app.example.com;浏览器插件写作 chrome-extension://、moz-extension:// 或 safari-web-extension:// 加上它的 ID",
"{name} removed": "已移除 {name}",
"Add": "添加",
"{name} added": "已添加 {name}",
@@ -6356,7 +6356,7 @@ const I18N = {
"MAGPIE_ALLOW_IPS sets this list; change it there": "此清單由 MAGPIE_ALLOW_IPS 設定,請在那裡修改",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "這些來源的網頁尾本可以在瀏覽器中呼叫閘道,每個請求需帶上「閘道」頁的閘道金鑰。其他網站的網頁會被拒絕,本機的網頁不受影響",
"Name each origin: a wildcard would let every web page use magpie": "請逐個填寫來源:萬用字元會讓任何網頁都能使用 magpie",
"Write an origin as http://localhost:3000 or https://app.example.com": "來源格式如 http://localhost:3000 或 https://app.example.com",
"Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "來源格式如 http://localhost:3000 或 https://app.example.com;瀏覽器擴充功能寫作 chrome-extension://、moz-extension:// 或 safari-web-extension:// 加上它的 ID",
"{name} removed": "已移除 {name}",
"Add": "新增",
"{name} added": "已新增 {name}",
@@ -10792,7 +10792,7 @@ const I18N = {
"MAGPIE_ALLOW_IPS sets this list; change it there": "このリストは MAGPIE_ALLOW_IPS で設定されています。そちらで変更してください",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "これらのオリジンのスクリプトはブラウザからゲートウェイを呼び出せます。各リクエストには「ゲートウェイ」ページのゲートウェイキーが必要です。ほかのサイトのページは拒否されます(このコンピューター上のページは除く)",
"Name each origin: a wildcard would let every web page use magpie": "オリジンは一つずつ指定してください。ワイルドカードではどの Web ページでも magpie を使えてしまいます",
"Write an origin as http://localhost:3000 or https://app.example.com": "オリジンは http://localhost:3000 や https://app.example.com の形式で入力してください",
"Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "オリジンは http://localhost:3000 や https://app.example.com の形式で、ブラウザー拡張機能は chrome-extension://、moz-extension://、safari-web-extension:// のあとに ID を続けて入力してください",
"{name} removed": "{name} を削除しました",
"Add": "追加",
"{name} added": "{name} を追加しました",
@@ -15247,7 +15247,7 @@ const I18N = {
"MAGPIE_ALLOW_IPS sets this list; change it there": "MAGPIE_ALLOW_IPS legt diese Liste fest; ändere sie dort",
"Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not": "Skripte dieser Herkünfte können das Gateway aus dem Browser aufrufen, jede Anfrage mit einem Gateway-Schlüssel aus „Gateway“. Seiten anderer Websites werden abgewiesen, Seiten auf diesem Computer nicht",
"Name each origin: a wildcard would let every web page use magpie": "Jede Herkunft einzeln angeben: Ein Platzhalter ließe jede Webseite magpie nutzen",
"Write an origin as http://localhost:3000 or https://app.example.com": "Eine Herkunft wird wie http://localhost:3000 oder https://app.example.com geschrieben",
"Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID": "Eine Herkunft wird wie http://localhost:3000 oder https://app.example.com geschrieben, die einer Browsererweiterung als chrome-extension://, moz-extension:// oder safari-web-extension:// mit ihrer ID",
"{name} removed": "{name} entfernt",
"Add": "Hinzufügen",
"{name} added": "{name} hinzugefügt",
+26 -7
View File
@@ -3,7 +3,9 @@
// http://localhost:3000 couldn't read the gateway's answers): Settings ›
// Network lists them by origin. One is added from a field and its Add
// button (or Enter), saved as the gateway cleaned it, and taken away with
// its Remove; a wildcard or a URL that isn't an origin is refused, said in
// its Remove; a browser extension is added by its origin
// (chrome-extension://<id>, SkyAerope on Discord); a wildcard, a URL that
// isn't an origin or an extension id no browser gives is refused, said in
// the page's language, and nothing is saved. At a 440px panel every row
// fits, and no click moves the page. English and Chinese, Chromium and
// WebKit; no backend, the API is faked here.
@@ -37,9 +39,17 @@ function clean(list) {
const out = [];
for (const raw of list) {
if (raw.includes("*")) return { error: `"${raw}": name each origin; a wildcard would let every web page use magpie` };
const ext = /^(chrome-extension|moz-extension|safari-web-extension):\/\/(.*?)\/?$/.exec(raw.trim().toLowerCase());
if (ext) {
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
if (!(ext[1] === "chrome-extension" ? /^[a-p]{32}$/ : uuid).test(ext[2])) return { error: `"${raw}" is not an extension's origin: write it as ${ext[1]}://<its ID>, the ID as the browser's extensions page shows it` };
const o = ext[1] + "://" + ext[2];
if (!out.includes(o)) out.push(o);
continue;
}
let u;
try { u = new URL(raw); } catch { u = null; }
if (!u || !/^https?:$/.test(u.protocol) || (u.pathname !== "/" && u.pathname !== "")) return { error: `"${raw}" is not an origin: write it as http://localhost:3000 or https://app.example.com` };
if (!u || !/^https?:$/.test(u.protocol) || (u.pathname !== "/" && u.pathname !== "")) return { error: `"${raw}" is not an origin: write it as http://localhost:3000 or https://app.example.com, or an extension's as chrome-extension://<its ID>` };
if (!out.includes(u.origin)) out.push(u.origin);
}
return { origins: out };
@@ -77,7 +87,7 @@ const words = {
head: "Web pages", name: "Web pages that may call magpie", add: "Add", remove: "Remove",
sub: "Scripts on these origins can call the gateway from a browser, each request with a gateway key from Gateway. A page from any other site is refused; pages on this computer are not",
wildcard: "Name each origin: a wildcard would let every web page use magpie",
notOrigin: "Write an origin as http://localhost:3000 or https://app.example.com",
notOrigin: "Write an origin as http://localhost:3000 or https://app.example.com, or a browser extension's as chrome-extension://, moz-extension:// or safari-web-extension:// followed by its ID",
},
zh: {
head: "网页", name: "允许调用 magpie 的网页", add: "添加", remove: "移除",
@@ -165,15 +175,24 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await box.locator(".row:not(.rule-row) .name", { hasText: "https://app.example.com" }).waitFor();
assert.deepEqual(posts.at(-1), ["http://localhost:3000", "https://app.example.com"]);
await fits();
// a browser extension, by its origin as copied from its page
const ext = "chrome-extension://abcdefghijklmnopabcdefghijklmnop";
await row.locator("input").fill(ext.toUpperCase() + "/");
before = await scroll();
await row.locator("button", { hasText: w.add }).click();
await box.locator(".row:not(.rule-row) .name", { hasText: ext }).waitFor();
assert.deepEqual(posts.at(-1), ["http://localhost:3000", "https://app.example.com", ext.toUpperCase() + "/"]);
assert.equal(await scroll(), before, "adding an extension moved the page");
await fits();
// refused, in the page's language, and nothing saved
for (const [bad, says] of [["*", w.wildcard], ["localhost:4000/v1", w.notOrigin]]) {
for (const [bad, says] of [["*", w.wildcard], ["localhost:4000/v1", w.notOrigin], ["chrome-extension://abc", w.notOrigin], ["chrome-extension://*", w.wildcard]]) {
await row.locator("input").fill(bad);
before = await scroll();
await row.locator("button", { hasText: w.add }).click();
await page.waitForFunction((s) => document.querySelector("#corsList .rule-row .sub.err")?.textContent.trim() === s, says);
assert.equal(await row.locator("input").inputValue(), bad, "what the user wrote stays, to be corrected");
assert.equal(await box.locator(".row:not(.rule-row)").count(), 2);
assert.equal(await box.locator(".row:not(.rule-row)").count(), 3);
assert.equal(await scroll(), before, "a refusal moved the page");
await fits();
}
@@ -182,8 +201,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const gone = box.locator(".row:not(.rule-row)").filter({ hasText: "http://localhost:3000" });
before = await scroll();
await gone.locator("button", { hasText: w.remove }).click();
await page.waitForFunction(() => document.querySelectorAll("#corsList .row:not(.rule-row)").length === 1);
assert.deepEqual(posts.at(-1), ["https://app.example.com"]);
await page.waitForFunction(() => document.querySelectorAll("#corsList .row:not(.rule-row)").length === 2);
assert.deepEqual(posts.at(-1), ["https://app.example.com", "chrome-extension://abcdefghijklmnopabcdefghijklmnop"]);
assert.equal(await scroll(), before, "Remove moved the page");
assert.equal((await row.locator(".sub").textContent()).trim(), w.sub, "a save clears the refusal");
+38 -4
View File
@@ -4,15 +4,18 @@ import (
"fmt"
"net"
"net/url"
"regexp"
"slices"
"strings"
)
// CleanOrigins is the web origins a user typed for CORSOrigins, as a
// browser's Origin header spells them: scheme://host[:port], lower-cased,
// with no path and the scheme's default port left out. Only http and
// https are origins; "*" is refused, since it would let every web page the
// user opens spend their subscriptions.
// with no path and the scheme's default port left out. http and https are
// origins, and so is a browser extension's page by its id (#1051,
// SkyAerope: an extension without host permissions is held to CORS like a
// page), as extensionIDs spells them; "*" is refused, since it would let
// every web page or extension the user has spend their subscriptions.
func CleanOrigins(in []string) ([]string, error) {
var out []string
for _, raw := range in {
@@ -35,10 +38,13 @@ func cleanOrigin(raw string) (string, error) {
if strings.Contains(raw, "*") {
return "", fmt.Errorf("%q: name each origin; a wildcard would let every web page use magpie", raw)
}
if o, ok, err := extensionOrigin(raw); ok {
return o, err
}
u, err := url.Parse(strings.TrimSuffix(raw, "/"))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil ||
(u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
return "", fmt.Errorf("%q is not an origin: write it as http://localhost:3000 or https://app.example.com", raw)
return "", fmt.Errorf("%q is not an origin: write it as http://localhost:3000 or https://app.example.com, or an extension's as chrome-extension://<its ID>", raw)
}
host, port := strings.ToLower(u.Hostname()), u.Port()
if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") {
@@ -52,3 +58,31 @@ func cleanOrigin(raw string) (string, error) {
}
return u.Scheme + "://" + host, nil
}
// extensionIDs is the host each browser's extension origin has, as it
// sends it in Origin for a fetch from the extension's own pages, popup or
// service worker (a content script's fetch carries the page's origin):
// Chromium's chrome-extension://<id>, the id 32 letters a–p; Firefox's
// moz-extension://<uuid>, its per-install Internal UUID; Safari's
// safari-web-extension://<uuid>, which Safari picks anew on each launch.
var extensionIDs = map[string]*regexp.Regexp{
"chrome-extension": regexp.MustCompile(`^[a-p]{32}$`),
"moz-extension": regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`),
"safari-web-extension": regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`),
}
// extensionOrigin is raw as an extension's origin, lower-cased, with a
// trailing "/" let go; ok says raw names an extension scheme at all, and
// then err says when its id isn't one that browser gives.
func extensionOrigin(raw string) (o string, ok bool, err error) {
scheme, rest, found := strings.Cut(strings.ToLower(raw), "://")
id := extensionIDs[scheme]
if !found || id == nil {
return "", false, nil
}
rest = strings.TrimSuffix(rest, "/")
if !id.MatchString(rest) {
return "", true, fmt.Errorf("%q is not an extension's origin: write it as %s://<its ID>, the ID as the browser's extensions page shows it", raw, scheme)
}
return scheme + "://" + rest, true, nil
}
+46
View File
@@ -22,3 +22,49 @@ func TestCleanOrigins(t *testing.T) {
}
}
}
// A browser extension's page is listed by its origin, as the browser
// sends it (#1051, SkyAerope on Discord: chrome-extension://<id> couldn't
// be added): Chromium's id of 32 letters a–p, Firefox's and Safari's
// UUID, however the user cased it or with a trailing "/". A bare scheme,
// a wildcard, an id that browser never gives, a path or a port is refused.
func TestCleanExtensionOrigins(t *testing.T) {
const chrome = "abcdefghijklmnopabcdefghijklmnop"
const uuid = "e0b5d7c7-c079-484b-8825-44d261383cb6"
got, err := CleanOrigins([]string{
"chrome-extension://" + chrome,
" Chrome-Extension://" + strings.ToUpper(chrome) + "/ ",
"moz-extension://" + strings.ToUpper(uuid) + "/",
"safari-web-extension://" + uuid,
})
if err != nil {
t.Fatal(err)
}
want := []string{"chrome-extension://" + chrome, "moz-extension://" + uuid, "safari-web-extension://" + uuid}
if strings.Join(got, " ") != strings.Join(want, " ") {
t.Fatalf("%v, want %v", got, want)
}
for _, bad := range []string{
"chrome-extension://", "chrome-extension:///", "chrome-extension://*", "chrome-extension://" + chrome[:31] + "*",
"chrome-extension://" + chrome[:31], // too short
"chrome-extension://" + chrome + "a", // too long
"chrome-extension://" + chrome[:31] + "q", // not a–p
"chrome-extension://" + chrome + "/popup.html", // a page, not an origin
"chrome-extension://" + chrome + ":80",
"chrome-extension://u@" + chrome,
"chrome-extension://" + chrome + "?x=1",
"chrome-extension://" + uuid, // Firefox's id under Chrome's scheme
"moz-extension://" + chrome, // and Chrome's under Firefox's
"moz-extension://{" + uuid + "}", // braces are not in the origin
"moz-extension://" + strings.ReplaceAll(uuid, "-", ""),
"moz-extension://" + uuid[:35] + "g",
"safari-web-extension://" + uuid + "/x",
"moz-extension://*",
"safari-web-extension://",
"ms-browser-extension://" + chrome,
} {
if o, err := CleanOrigins([]string{bad}); err == nil {
t.Errorf("%q taken as %v", bad, o)
}
}
}
+4 -2
View File
@@ -91,8 +91,10 @@ type Settings struct {
// named caller keys. LANKey is retained for older Magpie versions.
LAN bool `json:"lan,omitempty"`
LANKey string `json:"lanKey,omitempty"`
// CORSOrigins are the web pages (scheme://host[:port]) whose scripts
// may call the gateway from a browser (#1051): a preflight from one is
// CORSOrigins are the web pages (scheme://host[:port]) and browser
// extensions (chrome-extension://<id>, moz-extension://<uuid>,
// safari-web-extension://<uuid>) whose scripts may call the gateway
// from a browser (#1051): a preflight from one is
// answered, and its calls carry the CORS headers that let it read the
// reply, each with an enabled gateway key. None by default: a page
// gets no CORS headers, as before.