diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 0953a4094..7444f908f 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -17,6 +17,7 @@ three. | Settings from the terminal | `POST /api/settings` saves through `settingsapi.Apply` (`internal/settingsapi`, outside the GUI so the `nogui` build has it): the carry of keys a page leaves out (`Merge`), the vision, image and searcher checks, `settings.Save`'s own checks, and `catalog.Touched`. `magpie settings list\|get\|set\|reset` (#4745) builds the same body with `settingsapi.Body` (the whole file with one key changed, so a key the save keeps when it isn't sent is set even to off) and calls the same `Apply`; a refused value writes nothing. `settingsapi.Keys` names what the save writes; `TestKeysAreWhatTheSaveWrites` fails when a field of `settings.Settings` is saved without it, `TestSettingsCLISetsWhatTheWindowSaves` when a key the page's `savePrefs` sends isn't one, and `TestEveryRouteHasACommandOrIsNamed` when an `/api` route has neither a command nor a reason in `notYet` (`internal/cli/settings_parity_test.go`). The running app's in-process follow-ups (fonts, Dock, tray menu, alerts, language, update check) run only from the window's save; a change from the terminal is read from the file. | [`internal/settingsapi/settingsapi.go`](../../internal/settingsapi/settingsapi.go), [`settings_cli.go`](../../internal/cli/settings_cli.go) | | Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Added to a phone's home screen the page opens as an app of its own, with no browser bars (ninja_s6114 on Discord): `index.html` names `manifest.json` (display standalone), an apple-touch-icon and the iOS meta tags, the status bar keeps its own ground (`default`), and its theme colours match only `(display-mode: standalone)`, so a browser's tab and the app's windows take none. `webGuard` serves those three files (`webAppFiles`: the manifest, `icons/apple-touch-icon.png`, `icons/icon-512.png`) without the key, to GET and HEAD at those exact paths alone, as a home screen may ask without the cookie; see `TestWebAppAddsToHomeScreen` and `web-app-standalone.test.cjs`. The cookie is SameSite=Lax, which a browser sends with any request from the same site, other ports and sibling subdomains included, so `webOwnPage` answers `/api` for the page's own origin only: a write goes through net/http's `CrossOriginProtection` (Sec-Fetch-Site same-origin or none; from a browser without it, an Origin that is absent or names the Host or `MAGPIE_PUBLIC_URL`), and any request whose Sec-Fetch-Site says another origin sent it is refused, a GET too; see `TestWebAPIAnswersItsOwnPageOnly`. The desktop window's `/api` is in-process with no cookie and isn't held to it. Gateway mode shows every page but Agents on a machine that is only a gateway (`GATEWAY_HIDES`); the Library has its MCP servers and the MCP router alone, for other computers' apps to reach with a gateway key (treeman_26897 on Discord, `gateway-mode.test.cjs`, `library-mcp-agentless.test.cjs`). `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304; never an event stream, which gzip would hold back until its buffer fills); the app's own windows read the page in-process and get it uncompressed. The page's port answers the gateway's client routes too (`onePort`, `gateway.ClientPath`: `/v1/…`, `/v1beta/…`, `/mcp/…`, the Codex backend path and the routes without `/v1`; never `/api/*` or `/_magpie/*`, never a path that isn't clean), so one reverse-proxy location serves the page and the agents (zgcwkj on Discord). They skip the page's key and gzip and go to the gateway's own guards, always as a request from another machine (`gateway.FromPagePort`, the `X-Magpie-Page-Port` mark: `local` is false for it, from loopback too and under `MAGPIE_TRUST_PROXY`, so magpie must be shared and the request carry an enabled gateway key), since a raw TCP forward or a proxy that adds no forwarding header reaches this port from loopback looking like an agent here (reported privately by Coffemon); agents here use the gateway's own port. `Server.Front` (lanGuard over Handler) serves them in process when this process serves the gateway, or `toGateway`, a reverse proxy to `gateway.URL()`, when another magpie does; it keeps the Host, the forwarding headers and the mark, adds X-Forwarded-For for a peer that isn't loopback, and the peer's loopback address as X-Forwarded-For when none came, so a gateway of an older magpie that doesn't know the mark still asks for a key. `lanGuard` moves the mark into the request's context and takes the header off, so it never goes upstream. The page itself calls no client route. See `TestWebOnePortServedHere`, `TestWebOnePortServedElsewhere`, `TestWebOnePortAgentsHereUseTheGatewayPort`, `TestPagePortMarkIsNeverLocal` and `TestClientPathCoversHandler`. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go), [`oneport.go`](../../internal/gateway/oneport.go) | | The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) | +| Another magpie in a window | Settings › Network and sharing › Another magpie (`renderRemote` in `plugins/gateway/settings.js`) opens a magpie elsewhere, a server's (`magpie daemon install --web`, `magpie web`, another app's Browser access), in a window of the app's own, so its routing and usage are read from the desktop (xuanwo on X). The window (`OpenRemote`, `remote_app.go`) loads that magpie's own web page with `?k=` and signs in through its `webGuard` as a browser does: nothing is served here, and the page in it reaches that magpie alone (a remote page gets no bound calls). The address is the link that magpie printed (its `k=` taken out as the key) or a bare address, https:// when no scheme is typed; plain http only to an IP, localhost, a `.local` or a one-word name (`remoteAddr`), as a Mac's webview allows, so the key never crosses the internet in the clear. Before the window opens, `remoteProbe` asks for the link without following it: only a 303 setting a `magpie_web_*` cookie is that magpie taking the key; a 401, a 403 (allowed addresses), an untrusted certificate, no answer or anything else is said in Settings. Address and key live in `remote-magpie.json` beside settings.json (0600, never in settings.json); `GET /api/remote` says the address and whether a key is kept, never the key, and `POST /api/remote` with no key uses the one kept for the same address. The routes are on the app's own windows' API only (`!isWeb`), and a host that can't open windows refuses. See `TestRemoteAddr`, `TestRemoteOpensTheOtherMagpie`, `TestRemoteNotMagpie`, `TestRemoteNotOnBrowserPages` and `another-magpie.test.cjs`. | [`remote.go`](../../internal/gui/remote.go), [`remote_app.go`](../../internal/gui/remote_app.go) | | The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins//` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; a client whose User-Agent names only an HTTP library, a runtime or an API SDK (`usage.IsLibrary`: curl, Bun, python-httpx, Go-http-client, OpenAI/Python), or nothing (`other`), is no agent and goes on one card, `scripts`, named Scripts with its libraries listed, read from each route's kept agent so older history folds too, while the Usage page's Agents list keeps each by its own name (theforeveriris on X, `context_scripts_test.go`, `context-scripts.test.cjs`); clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory, else the request archive's copy masked the same way, with a 404 saying why there is none (`archive`: off, missing, cut, unread; `context_archive.go`), and its Reply the reply from `/api/context/reply` (`openCtxText`, in `ctxtext.js`, `context-text.test.cjs`), rendered 100 items and 20000 characters at a time; a session's details on the Sessions page and Usage's Sessions list draw a Context line of its requests from `/api/context/session`, which reads only the days from its first to its last (30 at most) and keeps that one session, so the tab's 80-session cap never leaves it out (`sessCtxLine` in `plugins/usage/page.js`, liang_yongxiang on Discord, `context_session_test.go`, `sessions-context-line.test.cjs`); its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) | | Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; Settings' are listed above its button at the foot, which is laid from its end (`.side-foot`'s `column-reverse`, its rows kept whole and scrolled from the end when the window is too short), so the list grows up from the button and the button and the gateway's line stay where they were clicked (jen_celeus on X, `sidebar-settings-steady.test.cjs`); a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) | | Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`, with *Never mask* and *Masked words* drawn a value a row by `wordList` in `plugins/redact/settings.js`, saved as the same list of strings the one comma-separated box saved, `redact-words-list.test.cjs`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). While anything is masked, *Instead of masking, send to* (`redactRouteRow` in `plugins/redact/settings.js`, the redact plugin's part of Settings, which wraps `renderRedact` so app.js carries none of it) picks, in the app menu, a model a request masking would change goes to as written: Off by default, and only the models `/api/settings` lists as `maskRouteModels` (every route of theirs unmasked, `gateway.MaskRoute`), saved with `POST /api/settings/redact-route` (`redact-route.test.cjs`). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) | diff --git a/internal/gui/api.go b/internal/gui/api.go index e5dd95d7c..4fff41754 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -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) diff --git a/internal/gui/app.go b/internal/gui/app.go index 87f2f6613..9cbe9acef 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -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 diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 866ce4aff..887338b49 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -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 */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 38f37c53f..2f1abffb7 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index fed49d9ad..79a7cc00c 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -362,6 +362,8 @@
Browser access
+
Another magpie
+
Images
diff --git a/internal/gui/assets/plugins/gateway/settings.js b/internal/gui/assets/plugins/gateway/settings.js index 231de8439..e7a28000b 100644 --- a/internal/gui/assets/plugins/gateway/settings.js +++ b/internal/gui/assets/plugins/gateway/settings.js @@ -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)); +} diff --git a/internal/gui/remote.go b/internal/gui/remote.go new file mode 100644 index 000000000..c5ae5eb60 --- /dev/null +++ b/internal/gui/remote.go @@ -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{}) + }) +} diff --git a/internal/gui/remote_app.go b/internal/gui/remote_app.go new file mode 100644 index 000000000..1ea2c30a8 --- /dev/null +++ b/internal/gui/remote_app.go @@ -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) + }) +} diff --git a/internal/gui/remote_test.go b/internal/gui/remote_test.go new file mode 100644 index 000000000..e1ce20607 --- /dev/null +++ b/internal/gui/remote_test.go @@ -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) + } +} diff --git a/internal/gui/tests/another-magpie.test.cjs b/internal/gui/tests/another-magpie.test.cjs new file mode 100644 index 000000000..79221fa39 --- /dev/null +++ b/internal/gui/tests/another-magpie.test.cjs @@ -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, []); + }); + }); +}