gui: open a server's magpie in a window of the app (xuanwo on X)

xuanwo runs magpie on a server and wants the desktop app to show that
magpie's routing and usage. Browser access in Settings › Network and
sharing goes the other way: it serves this app's page to a browser.

Settings › Network and sharing has a new section, Another magpie. It takes
an address and a key. You can paste the whole link the server printed
(`magpie daemon install --web`, `magpie web`, or another app's Browser
access), and its k= becomes the key. The app then opens that magpie's own
web page in a window of its own. The window signs in through the server's
own webGuard with ?k=, the same way a browser does, and is traded for its
cookie. Nothing new is served here: the page in the window talks to the
server alone and gets no bound calls from this app.

- remoteAddr:
  - https:// is used when no scheme is typed.
  - Plain http is allowed only to an IP, localhost, a .local name or a
    one-word name, so the key never crosses the internet in the clear.
    This is also the rule a Mac's webview applies.
  - userinfo and other schemes are refused.
- remoteProbe: before the window opens, it asks for the link without
  following redirects. Only a 303 that sets a magpie_web_* cookie counts
  as success. A 401, a 403 (allowed addresses), an untrusted certificate,
  no answer, or any other reply is reported in Settings, translated.
- remote-magpie.json:
  - It sits beside settings.json, mode 0600, and the key is never in
    settings.json.
  - GET /api/remote returns the address and hasKey, never the key.
  - POST with no key reuses the key kept for the same address.
  - POST /api/remote/forget removes the file.
- The routes are on the app's own windows' API only (!isWeb). A host that
  can't open windows refuses.

Run (on mote, at this tree):
- go test -count=1 ./internal/gui/: ok.
- Go tests:
  - TestRemoteAddr
  - TestRemoteOpensTheOtherMagpie: real webHandler; wrong or missing key
    refused, nothing kept; the pasted link opens; 0600; the key is not
    returned; a cookie-jar client following the opened link reaches the
    page behind the key; the kept key is reused; forget.
  - TestRemoteNotMagpie
  - TestRemoteNotOnBrowserPages
- GUI test, new: another-magpie.test.cjs. Covers 5 languages, 360px,
  and a browser page with no section that never asks /api/remote.
- GUI suite: every GUI file that draws Settings › Network (18, the new one included), plus
  i18n-keys, i18n-en-no-cjk and gui-de/ja/zh-tw. Chromium and WebKit:
  307/307 pass. Also remote-magpie.test.cjs (the Remote magpie
  provider's add sheet), run with the new file at the rebased head.
- gofmt -l: clean.
- go vet: darwin, GOOS=linux -tags nogui, and GOOS=windows on
  internal/gui; ok.

Broken by hand:
- A 303 without the magpie cookie taken as signed in:
  TestRemoteNotMagpie red.
- remoteRoutes outside !isWeb: TestRemoteNotOnBrowserPages red (200).
- renderRemote drawn on a browser's page, and errors not translated:
  another-magpie.test.cjs red in zh/zh-TW/ja/de and the browser case,
  in both engines.

Not tried:
- The real Wails window on macOS, Windows or Linux.
- A real server over https.
- Links on the remote page that open a new window (target=_blank,
  window.open) inside the remote window.
- Settings › Text size does not rezoom a remote window that is already
  open.
This commit is contained in:
yetone
2026-11-10 18:39:20 +08:00
parent f03ec97b8f
commit b358677305
11 changed files with 762 additions and 0 deletions
File diff suppressed because one or more lines are too long
+1
View File
@@ -1538,6 +1538,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
gatewayModeRoutes(mux)
if !isWeb(w) {
appPageRoutes(mux)
remoteRoutes(mux, w)
}
privacyModelRoutes(mux)
maskingRoutes(mux)
+2
View File
@@ -77,6 +77,8 @@ type host struct {
panel *application.WebviewWindow
main *application.WebviewWindow
tray *application.SystemTray
// remote shows another magpie's page (remote_app.go); main thread only
remote *application.WebviewWindow
// flapping is set while the tray bird plays its flap, so a second
// click in it doesn't start another over it
flapping atomic.Bool
+2
View File
@@ -4031,6 +4031,8 @@ input.words.compact-num { flex: none; width: 76px; font-variant-numeric: tabular
input.words.rule-kind { flex: none; width: 110px; }
input.words.gateway-port { flex: none; width: 110px; font-variant-numeric: tabular-nums; }input.words.rule-match { flex: 1 1 auto; width: auto; min-width: 0; }
input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; min-width: 0; }
input.words.remote-url { width: 280px; }
input.words.remote-key { width: 160px; }
/* a search API that signs in as a plugin's provider, in the key's place */
.search-signs { flex: 1 1 120px; min-width: 0; font-size: 12px; color: var(--fg-2); overflow-wrap: anywhere; }
/* a search API's base URL (#1580): on a line of its own under the key */
+48
View File
@@ -126,6 +126,18 @@ const I18N = {
"in {agents}": "用于 {agents}",
"Browser access": "浏览器访问",
"Open magpie in a browser": "在浏览器中打开 magpie",
"Another magpie": "另一个 magpie",
"Type the other magpie’s address": "请输入另一个 magpie 的地址",
"Type that magpie’s key: the k= in the link it printed, or its MAGPIE_WEB_KEY": "请输入那个 magpie 的密钥:它打印的链接里的 k=,或它的 MAGPIE_WEB_KEY",
"That magpie turned the key away: use the key in the link it printed": "那个 magpie 拒绝了这个密钥:请用它打印的链接里的密钥",
"That magpie doesn’t let this computer in: add this computer’s address to its allowed addresses": "那个 magpie 不允许这台电脑访问:请把这台电脑的地址加入它的允许地址",
"{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted": "{host} 是互联网上的域名:请用 https:// 打开,否则密钥会以明文经过网络",
"{host}’s certificate isn’t trusted by this computer": "这台电脑不信任 {host} 的证书",
"{host} doesn’t answer": "{host} 没有响应",
"{host} doesn’t answer as a magpie page: check the address and port (magpie web’s is 3430)": "{host} 的响应不是 magpie 页面:请检查地址和端口(magpie web 默认 3430)",
"The key is too short": "密钥太短",
"The key takes letters, digits and - . _ ~ only": "密钥只能包含字母、数字和 - . _ ~",
"The k= in its link": "链接里的 k=",
"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}": "App 运行时会把本窗口的页面提供给浏览器,链接里带着 Key,和 magpie web 一样。用 Cloudflare Tunnel 这类隧道时,把它指向 http://127.0.0.1:{port}",
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "端口 {p} 被其他程序占用(可能是 magpie web):magpie 每隔几秒会再试一次",
"Served; anyone with this link can change every setting": "已提供;拿到这个链接的人可以更改所有设置",
@@ -5038,6 +5050,18 @@ const I18N = {
"in {agents}": "用於 {agents}",
"Browser access": "瀏覽器存取",
"Open magpie in a browser": "在瀏覽器中開啟 magpie",
"Another magpie": "另一個 magpie",
"Type the other magpie’s address": "請輸入另一個 magpie 的位址",
"Type that magpie’s key: the k= in the link it printed, or its MAGPIE_WEB_KEY": "請輸入那個 magpie 的金鑰:它印出的連結中的 k=,或它的 MAGPIE_WEB_KEY",
"That magpie turned the key away: use the key in the link it printed": "那個 magpie 拒絕了這個金鑰:請用它印出的連結中的金鑰",
"That magpie doesn’t let this computer in: add this computer’s address to its allowed addresses": "那個 magpie 不允許這台電腦連線:請把這台電腦的位址加入它的允許位址",
"{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted": "{host} 是網際網路上的網域:請用 https:// 開啟,否則金鑰會以明文經過網路",
"{host}’s certificate isn’t trusted by this computer": "這台電腦不信任 {host} 的憑證",
"{host} doesn’t answer": "{host} 沒有回應",
"{host} doesn’t answer as a magpie page: check the address and port (magpie web’s is 3430)": "{host} 的回應不是 magpie 頁面:請檢查位址和連接埠(magpie web 預設 3430)",
"The key is too short": "金鑰太短",
"The key takes letters, digits and - . _ ~ only": "金鑰只能包含字母、數字和 - . _ ~",
"The k= in its link": "連結中的 k=",
"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}": "App 執行時會把本視窗的頁面提供給瀏覽器,連結裡帶著 Key,和 magpie web 一樣。用 Cloudflare Tunnel 這類通道時,把它指向 http://127.0.0.1:{port}",
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "連接埠 {p} 被其他程式佔用(可能是 magpie web):magpie 每隔幾秒會再試一次",
"Served; anyone with this link can change every setting": "已提供;拿到這個連結的人可以變更所有設定",
@@ -9935,6 +9959,18 @@ const I18N = {
"in {agents}": "{agents} で使用",
"Browser access": "ブラウザからのアクセス",
"Open magpie in a browser": "ブラウザで magpie を開く",
"Another magpie": "別の magpie",
"Type the other magpie’s address": "別の magpie のアドレスを入力してください",
"Type that magpie’s key: the k= in the link it printed, or its MAGPIE_WEB_KEY": "その magpie のキーを入力してください:表示されたリンクの k=、または MAGPIE_WEB_KEY",
"That magpie turned the key away: use the key in the link it printed": "その magpie はキーを拒否しました:表示されたリンクのキーを使ってください",
"That magpie doesn’t let this computer in: add this computer’s address to its allowed addresses": "その magpie はこのコンピューターを許可していません:このコンピューターのアドレスを許可リストに追加してください",
"{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted": "{host} はインターネット上の名前です:https:// で開いてください。そうしないとキーが暗号化されずにネットワークを通ります",
"{host}’s certificate isn’t trusted by this computer": "{host} の証明書はこのコンピューターで信頼されていません",
"{host} doesn’t answer": "{host} が応答しません",
"{host} doesn’t answer as a magpie page: check the address and port (magpie web’s is 3430)": "{host} は magpie のページとして応答しません:アドレスとポートを確認してください(magpie web は 3430)",
"The key is too short": "キーが短すぎます",
"The key takes letters, digits and - . _ ~ only": "キーに使えるのは英字、数字、- . _ ~ だけです",
"The k= in its link": "リンクの k=",
"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}": "アプリの実行中、このウィンドウのページをブラウザにも提供します。magpie web と同じく、リンクにキーが含まれます。Cloudflare Tunnel などのトンネルは http://127.0.0.1:{port} に向けてください",
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "ポート {p} は別のプログラム(magpie web かもしれません)が使用中です:magpie が数秒ごとに再試行します",
"Served; anyone with this link can change every setting": "提供中。このリンクを持つ人は、すべての設定を変更できます",
@@ -14834,6 +14870,18 @@ const I18N = {
"in {agents}": "in {agents}",
"Browser access": "Browserzugriff",
"Open magpie in a browser": "magpie im Browser öffnen",
"Another magpie": "Ein anderes magpie",
"Type the other magpie’s address": "Gib die Adresse des anderen magpie ein",
"Type that magpie’s key: the k= in the link it printed, or its MAGPIE_WEB_KEY": "Gib den Schlüssel dieses magpie ein: das k= im ausgegebenen Link oder sein MAGPIE_WEB_KEY",
"That magpie turned the key away: use the key in the link it printed": "Dieses magpie hat den Schlüssel abgelehnt: nimm den Schlüssel aus dem ausgegebenen Link",
"That magpie doesn’t let this computer in: add this computer’s address to its allowed addresses": "Dieses magpie lässt diesen Computer nicht herein: füge seine Adresse zu den erlaubten Adressen hinzu",
"{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted": "{host} ist ein Name im Internet: öffne ihn über https://, sonst geht der Schlüssel unverschlüsselt durchs Netz",
"{host}’s certificate isn’t trusted by this computer": "Das Zertifikat von {host} ist diesem Computer nicht vertraut",
"{host} doesn’t answer": "{host} antwortet nicht",
"{host} doesn’t answer as a magpie page: check the address and port (magpie web’s is 3430)": "{host} antwortet nicht als magpie-Seite: prüfe Adresse und Port (magpie web nutzt 3430)",
"The key is too short": "Der Schlüssel ist zu kurz",
"The key takes letters, digits and - . _ ~ only": "Der Schlüssel darf nur Buchstaben, Ziffern und - . _ ~ enthalten",
"The k= in its link": "Das k= im Link",
"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}": "Solange die App läuft, liefert sie die Seite dieses Fensters auch an Browser aus, mit einem Schlüssel im Link, wie magpie web. Einen Tunnel wie Cloudflare Tunnel richtest du auf http://127.0.0.1:{port}",
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "Port {p} ist von einem anderen Programm belegt, vielleicht magpie web: magpie versucht es alle paar Sekunden erneut",
"Served; anyone with this link can change every setting": "Wird ausgeliefert; wer diesen Link hat, kann jede Einstellung ändern",
+2
View File
@@ -362,6 +362,8 @@
<div class="list prefs" id="corsList"></div>
<div class="row-head" id="webPageHead"><span class="label" data-t>Browser access</span></div>
<div class="list prefs" id="webPageList"></div>
<div class="row-head" id="remoteHead"><span class="label" data-t>Another magpie</span></div>
<div class="list prefs" id="remoteList"></div>
</section>
<section class="set-page" id="setPage-models" role="tabpanel" aria-labelledby="setTab-models">
<div class="row-head"><span class="label" data-t>Images</span></div>
@@ -145,6 +145,7 @@ function corsSays(m) {
}
function renderCORS(s) {
renderWebPage(); // Browser access, the section under this one
renderRemote(); // Another magpie, under that
const box = $("#corsList");
box.replaceChildren();
const origins = s.corsOrigins || [];
@@ -579,3 +580,69 @@ function renderWebPage(asked) {
}
box.replaceChildren(...rows);
}
// renderRemote: Another magpie, a magpie on a server (magpie daemon install
// --web, magpie web, or an app's Browser access) opened in a window of the
// app's own (xuanwo on X: its routing and usage, read from the desktop).
// The window is that magpie's web page, signed in with the key in its link
// as a browser is; the app checks the key before opening it and keeps the
// address and key on this computer alone (remote.go). The key is never
// read back into the page. The app's windows alone draw it.
let remoteState = null, remoteDraft = { url: null, key: "" };
function remoteSays(m) {
let x;
if (/^type the other magpie's address/.test(m)) return t("Type the other magpie’s address");
if (/^type that magpie's key/.test(m)) return t("Type that magpie’s key: the k= in the link it printed, or its MAGPIE_WEB_KEY");
if (/turned the key away/.test(m)) return t("That magpie turned the key away: use the key in the link it printed");
if (/doesn't let this computer in/.test(m)) return t("That magpie doesn’t let this computer in: add this computer’s address to its allowed addresses");
if ((x = /^(\S+) is a name on the internet/.exec(m))) return t("{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted", { host: x[1] });
if ((x = /^(\S+)'s certificate isn't trusted/.exec(m))) return t("{host}’s certificate isn’t trusted by this computer", { host: x[1] });
if ((x = /^(\S+) doesn't answer/.exec(m))) return t("{host} doesn’t answer", { host: x[1] });
if ((x = /^(\S+) answered .*not as a magpie page/.exec(m))) return t("{host} doesn’t answer as a magpie page: check the address and port (magpie web’s is 3430)", { host: x[1] });
if (/^the key is \d+ characters/.test(m)) return t("The key is too short");
if (/^the key takes letters/.test(m)) return t("The key takes letters, digits and - . _ ~ only");
return t(m);
}
function renderRemote(asked) {
const head = $("#remoteHead"), box = $("#remoteList");
if (!box) return;
head.hidden = box.hidden = web;
if (web) return;
if (!asked) api("remote").then((r) => { remoteState = r; renderRemote(true); }).catch(() => {});
const s = remoteState;
if (!s) return;
const row = (name, ...tools) => {
const r = el("div", "row pref");
const who = el("div", "who");
who.append(el("div", "name", name));
const val = el("div", "val");
val.append(...tools);
r.append(who, val);
return r;
};
const addr = input(remoteDraft.url ?? s.url, "https://magpie.example.com");
addr.className = "words remote-url";
addr.setAttribute("aria-label", t("Address"));
addr.oninput = () => { remoteDraft.url = addr.value; };
const key = input(remoteDraft.key, s.hasKey ? t("Kept") : t("The k= in its link"), "password");
key.className = "words remote-key";
key.setAttribute("aria-label", t("Key"));
key.oninput = () => { remoteDraft.key = key.value; };
const open = el("button", "text", t("Open"));
open.onclick = () => {
open.disabled = true;
api("remote", { url: addr.value, key: key.value })
.then((r) => { remoteState = r; remoteDraft = { url: null, key: "" }; renderRemote(true); })
.catch((e) => { open.disabled = false; status(remoteSays(e.message), "err"); });
};
for (const f of [addr, key]) f.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") open.onclick(); };
const tools = [key, open];
if (s.url) {
const forget = el("button", "text", t("Forget"));
forget.onclick = () => api("remote/forget", {})
.then((r) => { remoteState = r; remoteDraft = { url: null, key: "" }; renderRemote(true); })
.catch(statusTErr);
tools.push(forget);
}
box.replaceChildren(row(t("Address"), addr), row(t("Key"), ...tools));
}
+263
View File
@@ -0,0 +1,263 @@
package gui
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/settings"
)
// The app opens another magpie's page in a window of its own: a magpie on
// a server (`magpie daemon install --web`, `magpie web`, or an app with
// Settings › Network and sharing › Browser access on), whose routing and
// usage the user reads from the desktop (xuanwo on X). The window is that
// magpie's own web page, signed in with its own key as a browser is
// (webGuard there): nothing is served here, and the page in the window
// talks to that magpie alone. The address and key live in
// remote-magpie.json beside settings.json, this computer's alone, never
// in settings.json: a sync or a backup never carries the key elsewhere.
// remoteFile is where the other magpie's address and key are kept, 0600.
func remoteFile() string { return filepath.Join(settings.Dir(), "remote-magpie.json") }
// remoteConf is remote-magpie.json: URL is the page's address without the
// key, Key the key its link carries.
type remoteConf struct {
URL string `json:"url,omitempty"`
Key string `json:"key,omitempty"`
}
// loadRemote reads remote-magpie.json; none is an empty conf.
func loadRemote() (remoteConf, error) {
var c remoteConf
b, err := os.ReadFile(remoteFile())
if errors.Is(err, os.ErrNotExist) {
return c, nil
}
if err != nil {
return remoteConf{}, err
}
if err := json.Unmarshal(b, &c); err != nil {
return remoteConf{}, fmt.Errorf("%s: %w", remoteFile(), err)
}
return c, nil
}
// saveRemote writes remote-magpie.json readable by its owner alone: the
// key opens every setting and key the other magpie has.
func saveRemote(c remoteConf) error {
p := remoteFile()
if c == (remoteConf{}) {
if err := os.Remove(p); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return err
}
if f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err == nil {
f.Close()
}
b, _ := json.MarshalIndent(c, "", " ")
if err := edit.WriteAtomic(p, append(b, '\n')); err != nil {
return err
}
return os.Chmod(p, 0o600)
}
// remoteAddr reads what was typed as the other magpie's address: the link
// it printed (with ?k=, which is taken out as the key) or the bare
// address, https:// when no scheme is named. Plain http is taken only
// where the key doesn't cross the internet in the clear: an IP address
// (this computer, the LAN, a Tailscale address), localhost, a .local name
// or a one-word name; a name on the internet needs https, which is also
// what a Mac's webview asks of one.
func remoteAddr(raw string) (addr, key string, err error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", errors.New("type the other magpie's address")
}
if !strings.Contains(raw, "://") {
raw = "https://" + raw
}
u, err := url.Parse(raw)
if err != nil || u.Host == "" || u.Hostname() == "" {
return "", "", fmt.Errorf("%q isn't an address such as https://magpie.example.com", raw)
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", "", fmt.Errorf("the address is http:// or https://, not %s://", u.Scheme)
}
if u.User != nil {
return "", "", errors.New("the address can't carry a user name or password: the key signs in")
}
if u.Scheme == "http" && !plainHTTPOK(u.Hostname()) {
return "", "", fmt.Errorf("%s is a name on the internet: open it over https://, or the key crosses the network unencrypted", u.Hostname())
}
q := u.Query()
key = q.Get("k")
q.Del("k")
u.RawQuery = q.Encode()
u.Fragment, u.RawFragment = "", ""
if u.Path == "" {
u.Path = "/"
}
return u.String(), key, nil
}
// plainHTTPOK: a page on host may be reached over plain http.
func plainHTTPOK(host string) bool {
h := strings.ToLower(strings.TrimSuffix(host, "."))
return net.ParseIP(h) != nil || h == "localhost" || strings.HasSuffix(h, ".local") || !strings.Contains(h, ".")
}
// remoteLink is the address with the key, which the page trades for its
// cookie and takes out of the address bar (webGuard).
func remoteLink(c remoteConf) string {
u, err := url.Parse(c.URL)
if err != nil {
return ""
}
q := u.Query()
q.Set("k", c.Key)
u.RawQuery = q.Encode()
return u.String()
}
// remoteProbe asks the other magpie whether it takes the key, as the
// window's first load would, so a wrong address or key is said in Settings
// rather than as a window with an error page. It reads nothing behind the
// key: webGuard answers a link with the key with a redirect and a cookie,
// and one without it with 401.
var remoteProbe = func(c remoteConf) error {
cl := &http.Client{
Timeout: 8 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
req, err := http.NewRequest(http.MethodGet, remoteLink(c), nil)
if err != nil {
return err
}
req.Header.Set("Accept", "text/html")
resp, err := cl.Do(req)
if err != nil {
var cert *tls.CertificateVerificationError
if errors.As(err, &cert) {
return fmt.Errorf("%s's certificate isn't trusted by this computer: %v", req.URL.Host, cert.Err)
}
return fmt.Errorf("%s doesn't answer: %v", req.URL.Host, errors.Unwrap(err))
}
resp.Body.Close()
switch {
case resp.StatusCode == http.StatusSeeOther && remoteSignedIn(resp):
return nil
case resp.StatusCode == http.StatusUnauthorized:
return errors.New("that magpie turned the key away: use the key in the link it printed (MAGPIE_WEB_KEY, or the k= in it)")
case resp.StatusCode == http.StatusForbidden:
return errors.New("that magpie doesn't let this computer in: add this computer's address to its allowed addresses")
}
return fmt.Errorf("%s answered %s, not as a magpie page: check the address and port (magpie web's is 3430)", req.URL.Host, resp.Status)
}
// remoteSignedIn: the answer sets magpie web's cookie.
func remoteSignedIn(resp *http.Response) bool {
for _, c := range resp.Cookies() {
if strings.HasPrefix(c.Name, "magpie_web_") {
return true
}
}
return false
}
// remoteOpener is a host that can open the other magpie's window: the
// app's, not a browser's.
type remoteOpener interface {
OpenRemote(link, title string)
}
// remoteJSON is GET /api/remote: the address kept, and whether a key is.
// The key itself never goes back to the page.
type remoteJSON struct {
URL string `json:"url"`
HasKey bool `json:"hasKey"`
}
// remoteRoutes: GET /api/remote says what is kept; POST takes {"url",
// "key"}, checks that magpie takes the key, keeps both and opens its
// window (a key left out keeps the one kept for the same address);
// POST /api/remote/forget forgets them. The app's own windows' alone.
func remoteRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/remote", func(rw http.ResponseWriter, r *http.Request) {
c, err := loadRemote()
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, remoteJSON{URL: c.URL, HasKey: c.Key != ""})
})
mux.HandleFunc("POST /api/remote", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
URL string `json:"url"`
Key string `json:"key"`
}
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 8192)).Decode(&in); err != nil {
fail(rw, err)
return
}
addr, key, err := remoteAddr(in.URL)
if err != nil {
fail(rw, err)
return
}
if k := strings.TrimSpace(in.Key); k != "" {
key = k
}
if key == "" {
if old, err := loadRemote(); err == nil && old.URL == addr {
key = old.Key
}
}
if key == "" {
fail(rw, errors.New("type that magpie's key: the k= in the link it printed, or its MAGPIE_WEB_KEY"))
return
}
if err := CheckWebKey(key); err != nil {
fail(rw, errors.New(strings.Replace(err.Error(), "MAGPIE_WEB_KEY", "the key", 1)))
return
}
o, ok := w.(remoteOpener)
if !ok {
fail(rw, errors.New("only the app opens another magpie in a window"))
return
}
c := remoteConf{URL: addr, Key: key}
if err := remoteProbe(c); err != nil {
fail(rw, err)
return
}
if err := saveRemote(c); err != nil {
fail(rw, err)
return
}
u, _ := url.Parse(addr)
o.OpenRemote(remoteLink(c), "magpie · "+u.Host)
writeJSON(rw, remoteJSON{URL: c.URL, HasKey: true})
})
mux.HandleFunc("POST /api/remote/forget", func(rw http.ResponseWriter, r *http.Request) {
if err := saveRemote(remoteConf{}); err != nil {
fail(rw, err)
return
}
writeJSON(rw, remoteJSON{})
})
}
+49
View File
@@ -0,0 +1,49 @@
//go:build !nogui
package gui
import (
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
"github.com/yetone/magpie/internal/settings"
)
// OpenRemote shows another magpie's page (remote.go) in a window of its
// own, link carrying its key; the window open already is pointed at link
// and brought up. It is an ordinary titled window: the page is that
// magpie's web page, which draws no title bar of its own.
func (h *host) OpenRemote(link, title string) {
application.InvokeSync(func() {
h.dockFront(settings.Load(), true, true)
if w := h.remote; w != nil {
w.SetTitle(title)
w.SetURL(link)
showHere(w, true)
return
}
minW, minH := windowMin(h.zoom(), 0, 0)
w := h.app.Window.NewWithOptions(application.WebviewWindowOptions{
Name: "remote",
Title: title,
URL: link,
Width: max(minW, 1100),
Height: max(minH, 760),
MinWidth: minW,
MinHeight: minH,
Zoom: h.zoom(),
})
h.remote = w
// closed, it is gone; the next Open makes it again
w.OnWindowEvent(events.Common.WindowClosing, func(*application.WindowEvent) {
application.InvokeAsync(func() {
if h.remote == w {
h.remote = nil
}
h.dock(settings.Load(), h.mainShown())
})
})
w.Center()
showHere(w, true)
})
}
+181
View File
@@ -0,0 +1,181 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"os"
"runtime"
"strings"
"testing"
"time"
)
// remoteWin is the app's windows, as far as another magpie's window goes:
// the links it was asked to open.
type remoteWin struct {
Windows
opened []string
}
func (w *remoteWin) OpenRemote(link, title string) { w.opened = append(w.opened, link) }
func remotePost(t *testing.T, w Windows, path, body string) (int, string) {
t.Helper()
mux := http.NewServeMux()
remoteRoutes(mux, w)
r := httptest.NewRequest("POST", path, strings.NewReader(body))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, r)
return rec.Code, rec.Body.String()
}
func jsonStr(s string) string { b, _ := json.Marshal(s); return string(b) }
// What is typed as the other magpie's address: the link it printed, with
// its key taken out, or a bare address; plain http only where the key
// doesn't cross the internet.
func TestRemoteAddr(t *testing.T) {
for _, c := range []struct{ in, addr, key, err string }{
{"https://magpie.example.com/?k=0123456789abcdef-key", "https://magpie.example.com/", "0123456789abcdef-key", ""},
{"magpie.example.com:3430", "https://magpie.example.com:3430/", "", ""},
{"http://192.168.1.20:3430/?k=abc&view=usage#x", "http://192.168.1.20:3430/?view=usage", "abc", ""},
{"http://100.101.1.2:3430", "http://100.101.1.2:3430/", "", ""},
{"http://nas.local:3430", "http://nas.local:3430/", "", ""},
{"http://server:3430", "http://server:3430/", "", ""},
{"https://example.com/magpie/", "https://example.com/magpie/", "", ""},
{"http://magpie.example.com:3430", "", "", "name on the internet"},
{"https://u:p@magpie.example.com", "", "", "user name"},
{"ftp://example.com", "", "", "http:// or https://"},
{"file:///etc/passwd", "", "", "isn't an address"},
{" ", "", "", "type the other"},
} {
addr, key, err := remoteAddr(c.in)
if c.err != "" {
if err == nil || !strings.Contains(err.Error(), c.err) {
t.Errorf("%q: err %v, want %q", c.in, err, c.err)
}
continue
}
if err != nil || addr != c.addr || key != c.key {
t.Errorf("%q: %q %q %v, want %q %q", c.in, addr, key, err, c.addr, c.key)
}
}
}
// xuanwo on X: the app opens a server's magpie, its routing and usage, in
// a window. The key is checked against that magpie's own page before the
// window opens, kept 0600 on this computer, never read back into the page,
// and the link the window opens signs in to the other magpie's page as a
// browser does.
func TestRemoteOpensTheOtherMagpie(t *testing.T) {
onePortHome(t)
const key = "0123456789abcdef-remote"
reached := 0
other := httptest.NewServer(webHandler("3430", key, webCookieAge, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
reached++
rw.WriteHeader(http.StatusTeapot)
})))
defer other.Close()
w := &remoteWin{}
// a wrong key: said, nothing opened, nothing kept
code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`,"key":"0123456789abcdef-wrong"}`)
if code != http.StatusBadRequest || !strings.Contains(body, "turned the key away") || len(w.opened) != 0 || reached != 0 {
t.Fatalf("wrong key: %d %s %v", code, body, w.opened)
}
if _, err := os.Stat(remoteFile()); !os.IsNotExist(err) {
t.Fatalf("a refused key was kept: %v", err)
}
// no key at all
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`}`); code != http.StatusBadRequest || !strings.Contains(body, "type that magpie's key") {
t.Fatalf("no key: %d %s", code, body)
}
// the link it printed, pasted whole
code, body = remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL+"/?k="+key)+`}`)
if code != http.StatusOK || len(w.opened) != 1 || w.opened[0] != other.URL+"/?k="+key {
t.Fatalf("open: %d %s %v", code, body, w.opened)
}
if strings.Contains(body, key) {
t.Fatalf("the key went back to the page: %s", body)
}
if reached != 0 {
t.Fatal("the check read the page behind the key")
}
fi, err := os.Stat(remoteFile())
if err != nil {
t.Fatal(err)
}
if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 {
t.Fatalf("remote-magpie.json is %v", fi.Mode().Perm())
}
mux := http.NewServeMux()
remoteRoutes(mux, w)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/remote", nil))
if s := rec.Body.String(); strings.Contains(s, key) || !strings.Contains(s, `"hasKey":true`) || !strings.Contains(s, other.URL) {
t.Fatalf("GET /api/remote: %s", s)
}
// the window's link signs in to the other magpie's page, as a browser
jar, _ := cookiejar.New(nil)
res, err := (&http.Client{Jar: jar, Timeout: 5 * time.Second}).Get(w.opened[0])
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusTeapot || reached != 1 || strings.Contains(res.Request.URL.String(), key) {
t.Fatalf("the window's link: %d at %s, reached %d", res.StatusCode, res.Request.URL, reached)
}
// opened again without the key: the one kept for the address
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`}`); code != http.StatusOK || len(w.opened) != 2 || w.opened[1] != other.URL+"/?k="+key {
t.Fatalf("again: %d %s %v", code, body, w.opened)
}
// forgotten
if code, _ := remotePost(t, w, "/api/remote/forget", `{}`); code != http.StatusOK {
t.Fatalf("forget: %d", code)
}
if _, err := os.Stat(remoteFile()); !os.IsNotExist(err) {
t.Fatalf("forgotten, still there: %v", err)
}
}
// Something at the address that isn't a magpie page, or none: said, and
// no window opened.
func TestRemoteNotMagpie(t *testing.T) {
onePortHome(t)
plain := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
http.Redirect(rw, r, "/login", http.StatusSeeOther) // a redirect with no magpie cookie
}))
defer plain.Close()
w := &remoteWin{}
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(plain.URL)+`,"key":"0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "not as a magpie page") || len(w.opened) != 0 {
t.Fatalf("not magpie: %d %s", code, body)
}
plain.Close()
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(plain.URL)+`,"key":"0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "doesn't answer") || len(w.opened) != 0 {
t.Fatalf("gone: %d %s", code, body)
}
}
// A page served to a browser (magpie web, the app's Browser access) has no
// /api/remote: only the app's own windows open another magpie, and a
// browser can't read or change the key kept for it.
func TestRemoteNotOnBrowserPages(t *testing.T) {
onePortHome(t)
h := webPageHandler(t, webHost{}, nil)
for _, m := range []string{"GET", "POST"} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(m, "/api/remote", strings.NewReader(`{"url":"http://127.0.0.1:1"}`)))
if rec.Code == http.StatusOK || strings.Contains(rec.Body.String(), "hasKey") {
t.Fatalf("%s /api/remote on a browser's page: %d %s", m, rec.Code, rec.Body.String())
}
}
// and a host that can't open windows refuses rather than keeping it
if code, body := remotePost(t, webHost{}, "/api/remote", `{"url":"http://127.0.0.1:1/?k=0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "only the app") {
t.Fatalf("browser host: %d %s", code, body)
}
}
+146
View File
@@ -0,0 +1,146 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Settings › Network and sharing › Another magpie (xuanwo on X: a magpie on a
// server, its routing and usage, opened from the desktop app). The address
// and the key are posted to /api/remote, which opens the window; an error
// from it is said in the page's language; once kept, the key field shows it
// is kept (never the key) and Forget posts /api/remote/forget. A browser on
// the page (web) has no such section and never asks for it. 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 kept = { url: "", hasKey: false };
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/remote") {
if (req.method() === "GET") { gets.n++; return json(kept); }
const body = JSON.parse(req.postData());
posts.push(body);
if (body.key === "wrong-wrong-wrong-wrong") return json({ error: "that magpie turned the key away: use the key in the link it printed (MAGPIE_WEB_KEY, or the k= in it)" }, 400);
if (/^http:\/\/magpie\.example\.com/.test(body.url)) return json({ error: "magpie.example.com is a name on the internet: open it over https://, or the key crosses the network unencrypted" }, 400);
kept = { url: body.url.replace(/\?k=.*/, ""), hasKey: true };
return json(kept);
}
if (url.pathname === "/api/remote/forget") { posts.push("forget"); kept = { url: "", hasKey: false }; return json(kept); }
if (url.pathname === "/api/web-page") return json({ mode: "", port: 3430, serving: false });
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 + ": Another magpie opens a server's magpie 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}-another-magpie-${i}.png`), fullPage: true });
}
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);
page.setDefaultNavigationTimeout(60000);
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);
const tr = (s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]);
return { page, errors, posts, gets, tr };
};
// posts are counted, not a time waited
const until = async (page, f) => { for (let i = 0; i < 250 && !f(); i++) await page.waitForTimeout(20); assert(f()); };
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("#remoteHead");
const list = page.locator("#remoteList");
await list.locator(".row.pref").first().waitFor();
assert.equal((await head.textContent()).trim(), await tr("Another magpie"));
if (lang !== "en") assert.notEqual(await tr("Another magpie"), "Another magpie", "translated");
assert.equal(await list.locator(".row.pref").count(), 2);
const addr = list.locator("input.remote-url"), key = list.locator("input.remote-key");
assert.equal(await key.getAttribute("type"), "password");
assert.equal(await list.getByRole("button", { name: await tr("Forget") }).count(), 0, "nothing kept: no Forget");
// a name on the internet over http: said in the page's language
await reach(page, addr);
await addr.fill("http://magpie.example.com:3430");
await key.fill(KEY);
const openBtn = list.getByRole("button", { name: await tr("Open"), exact: true });
await openBtn.click();
await page.locator("#status").filter({ hasText: await tr("{host} is a name on the internet: open it over https://, or the key crosses the network unencrypted", { host: "magpie.example.com" }) }).waitFor();
// a wrong key
await addr.fill("https://magpie.example.com");
await key.fill("wrong-wrong-wrong-wrong");
await openBtn.click();
await page.locator("#status").filter({ hasText: await tr("That magpie turned the key away: use the key in the link it printed") }).waitFor();
// the link it printed, with Enter
await key.fill("");
await addr.fill("https://magpie.example.com/?k=" + KEY);
await addr.press("Enter");
await until(page, () => posts.some((p) => p.url === "https://magpie.example.com/?k=" + KEY));
assert.deepEqual(posts.at(-1), { url: "https://magpie.example.com/?k=" + KEY, key: "" });
const forget = list.getByRole("button", { name: await tr("Forget") });
await forget.waitFor();
assert.equal(await addr.inputValue(), "https://magpie.example.com/", "kept without its key");
assert.equal(await key.inputValue(), "", "the key is never put back");
assert.equal(await key.getAttribute("placeholder"), await tr("Kept"));
assert.equal(await page.locator("#setPage-network select").count(), 0, "no native select");
await forget.click();
await until(page, () => posts.includes("forget"));
await page.waitForFunction(() => !document.querySelector("#remoteList input.remote-url").value);
assert.deepEqual(errors, []);
});
}
await t.test("360px wide, German", async () => {
const { page, errors, tr } = await open("de", false, 360);
const list = page.locator("#remoteList");
await list.locator("input.remote-url").waitFor();
await list.locator("input.remote-url").fill("https://magpie.example.com/?k=" + KEY);
await list.getByRole("button", { name: await tr("Open"), exact: true }).click();
await list.getByRole("button", { name: await tr("Forget") }).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");
assert.deepEqual(errors, []);
});
await t.test("a browser on the page has no Another magpie", async () => {
const { page, errors, gets } = await open("en", true);
await page.locator("#portList .row").first().waitFor();
assert.equal(await page.locator("#remoteHead").isVisible(), false);
assert.equal(await page.locator("#remoteList .row").count(), 0);
assert.equal(gets.n, 0, "never asks /api/remote");
assert.deepEqual(errors, []);
});
});
}