From 4623f54190d8547dc4191f91e4ec23011c87fd4e Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 22:44:04 +0800 Subject: [PATCH] gateway: HTTPS for other computers, from magpie's CA or an imported certificate (zhangly1 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit zhangly1 on X: Claude on another computer on the LAN needed magpie at https://. Settings → Network and sharing → HTTPS (magpie https on) serves other computers TLS on the gateway's own port, with a certificate magpie's CA (the mTLS one, in ~/.config/magpie/mtls) signs for this computer's names and addresses; this computer keeps plain http://. The switch is read per connection, so no restart. - Certificate row: Import… takes the user's own PEM certificate (with chain) and unencrypted key, in any files and order; a pair that can't be served (no key, no cert, a stranger key, a passphrase, run out, nothing PEM) is refused with the reason in the page's language and leaves nothing behind. Remove goes back to magpie's CA. --tls-cert still comes first. - magpie's CA row: SHA-256 shown, Save puts magpie-ca.crt in Downloads; the gateway serves it without a key at /magpie-ca.crt to any address the share lets in. Rows under it give curl -kO, macOS, Windows, Linux and NODE_EXTRA_CA_CERTS steps with Copy. - A page open from another computer can't turn HTTPS on or off under itself (it would lose its own address). - magpie https status|on|off|import|remove|ca --out; the serve banner names magpie's CA or the imported file instead of "(mTLS)". - docs/reference.md and gateway-routing.md say all of it, and that Windows' curl.exe needs --ssl-no-revoke for any private CA. Run: - gofmt -l clean; go vet linux -tags nogui ./internal/..., GOOS=windows and GOOS=darwin -tags nogui vet of the touched packages (WSL, mote refused ssh all evening). - WSL: go test -tags nogui gateway -run HTTPS|MTLS|ClientCert|CAFile|TLS|LAN ok; gui -run HTTPS|MTLS|Keep ok; settings, settingsapi, mtls ok; cli -run Help|HTTPS|TLS|Serve|Banner|Flag|Unknown ok. The whole cli package hit its 40m timeout in TestEveryAgentFieldNameWritesNothing (#5234, #4247, not this change). - GUI (WSL Playwright, chromium + webkit): https-settings (en, zh, 390px, strings in all four languages) ok, plus mtls-settings, allow-ips, browser-access, cors-origins, gui-de/ja/zh-tw, i18n-keys, i18n-en-no-cjk, lan-*, public-url*, api-key-theme, connect-address-kept, gateway-connect-keys, gateway-caller-keys, side-gateway-lan, menu-scroll. Reds at load ~130: api-key-theme (#5044), connect-address-kept (#5972), gateway-caller-keys (#2572), gui-ja (#5943), lan-docker (#4692), all red the same at base 10bef5fe0 run beside it; allow-ips and gateway-connect-keys went red once under that load and pass 18/18 at concurrency 1, base and this change side by side. - Real: a sandbox HOME gateway built from this tree on WSL (MAGPIE_ADDR=0.0.0.0:3593, a gateway key, magpie https on, magpie serve). From the Windows host: curl -k /magpie-ca.crt 200 without a key; Node fetch with NODE_EXTRA_CA_CERTS=magpie-ca.crt 200 on /v1/models, 401 without the key, SELF_SIGNED_CERT_IN_CHAIN without the CA; plain http:// 400; curl.exe --cacert needs --ssl-no-revoke (schannel), then 200. Cert SANs: localhost, the hostname, .local, 127.0.0.1, ::1 and every address. magpie https import of an openssl CA's leaf on the running gateway: Node trusting that CA 200, magpie's CA alone refused. remove + off on the running gateway: plain http:// from Windows 200. This computer's plain http:// 200 throughout. - At the pushed tree (on origin/main ee818e8bc), WSL: gofmt -l clean; go vet -tags nogui linux, GOOS=windows, GOOS=darwin nogui of gateway, gui, cli ok; go test -run 'HTTPS|CAFile|MTLS|LAN' gateway, gui ok. GUI https-settings, mtls-settings, i18n-keys, gui-de/ja/zh-tw, allow-ips, lan-* (both engines): 147/155; reds are gui-ja (#5943), lan-docker (#4692), allow-ips webkit under load, and gui-zh-tw chromium under load (2 of 3 green alone, filed #5983). Broken by hand: - TLSOn without HTTPSOn: TestHTTPSOtherComputer red. - lanGuard without the caFileOpen exemption: TestHTTPSCAFile red. - mtls config without GetCertificate = settingsCert: all three serving tests red. - app.js without renderHTTPS(s): https-settings red in both engines. Not tried: the macOS, Windows and Linux system trust commands on a real store (they change the box's trust); Claude Desktop itself; a darwin GUI run (mote unreachable); the full suite before the tag (started after it). --- docs/reference.md | 35 +++ docs/subsystems/gateway-routing.md | 1 + internal/cli/help_cli.go | 2 + internal/cli/help_cli_test.go | 2 +- internal/cli/https_cli.go | 137 +++++++++ internal/cli/main.go | 7 + internal/cli/tls_cli.go | 5 +- internal/gateway/gateway.go | 1 + internal/gateway/https.go | 280 ++++++++++++++++++ internal/gateway/https_test.go | 240 +++++++++++++++ internal/gateway/lan.go | 4 +- internal/gateway/mtls.go | 8 +- internal/gateway/tls.go | 8 +- internal/gui/api.go | 1 + internal/gui/assets/app.css | 1 + internal/gui/assets/app.js | 1 + internal/gui/assets/i18n.js | 52 ++++ internal/gui/assets/index.html | 1 + .../gui/assets/plugins/gateway/settings.js | 100 +++++++ internal/gui/https.go | 132 +++++++++ internal/gui/https_test.go | 107 +++++++ internal/gui/settings_keep_test.go | 1 + internal/gui/tests/https-settings.test.cjs | 244 +++++++++++++++ internal/mtls/mtls.go | 3 + internal/settings/settings.go | 21 +- internal/settingsapi/settingsapi.go | 1 + 26 files changed, 1383 insertions(+), 12 deletions(-) create mode 100644 internal/cli/https_cli.go create mode 100644 internal/gateway/https.go create mode 100644 internal/gateway/https_test.go create mode 100644 internal/gui/https.go create mode 100644 internal/gui/https_test.go create mode 100644 internal/gui/tests/https-settings.test.cjs diff --git a/docs/reference.md b/docs/reference.md index aca8ecead..cf63cee57 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -962,6 +962,40 @@ since no certificate for the server's name covers loopback. A container or a WSL distro calling through its NAT address is another computer, and uses `https://`. Gateway keys, sharing and allowed addresses work as over HTTP. +**HTTPS on the local network.** Without a certificate of your own, turn +on Settings → Network and sharing → HTTPS (or `magpie https on`; zhangly1 +on X: Claude on another computer needed magpie at `https://`). magpie +serves other computers `https://` with a certificate its own CA (the mTLS +one, in `~/.config/magpie/mtls`) signs for this computer's names, its +addresses and the name the client dialled; this computer keeps plain +`http://`. Each computer that calls magpie trusts the CA once: Save under +magpie's CA puts `magpie-ca.crt` in Downloads, and the gateway serves it +to any address the share lets in, without a key, at +`https://:/magpie-ca.crt` (`curl -kO`, then check its +SHA-256 against the one Settings and `magpie https` show). Then: + +```sh +# macOS +sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt +# Windows, as administrator +certutil -addstore -f Root magpie-ca.crt +# Debian, Ubuntu +sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates +# Claude Code and other Node apps, which keep their own list +export NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt +``` + +Windows' own `curl.exe` checks revocation, which a private CA has none +of, so it needs `--ssl-no-revoke`; Node, browsers and Claude Code don't. + +To serve a certificate of your own instead (one your network's CA, or a +public one, signed), Import… under Certificate (or `magpie https import +cert.pem key.pem`): PEM, the certificate with its chain and an +unencrypted key, in one file or several. It is kept in +`~/.config/magpie/https` and read again when it changes; Remove goes back +to magpie's CA. `--tls-cert` comes before both. A page open from another +computer can't turn HTTPS on or off under itself. + **Client certificates (mTLS).** A magpie open to the internet can also ask every other computer for a client certificate it issued itself (hhdaxia on X, #5596), so a stolen gateway key alone gets nowhere. Turn on @@ -3531,6 +3565,7 @@ magpie web # the app's window in a browser (WSL, a server o # (behind a reverse proxy, MAGPIE_WEB_URL=https:// prints the link through it) magpie serve # the gateway alone, no window; --web[=host:port] serves the page too, from the same process # --tls-cert --tls-key : https:// for other computers (see HTTPS under sharing) +magpie https # https:// for other computers: on, off, import , remove, ca [--out] magpie mtls # other computers need a client certificate magpie issued: on, off, issue , revoke , list magpie daemon install # run magpie serve as a service (systemd, launchd); --web, --lan, --addr serve the page too; --tls-cert/--tls-key, --no-tls magpie ls # list every agent and its current settings diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 00b5a3cad..2e4b5f1fb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -29,6 +29,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked: first by an agent named in the path, then by token, then by User-Agent. An agent that can be given neither a key nor a User-Agent of its own is given an address with its id in it, `/agent//v1` (`AgentPath`, `AgentURL` in [`agentpath.go`](../../internal/gateway/agentpath.go)): `lanGuard` takes `/agent/` off the path when `` is an agent magpie knows (`takeAgentPath`), and the request is served at the rest as that agent's; `startedByAgent` never takes it for a script. OpenBot is one: it seals an endpoint's key and headers where magpie can't write, and hands the endpoint to the OpenCode it runs, whose User-Agent is OpenCode's, so its requests were counted as OpenCode's (SSNQT on X; `TestAgentInPath`). A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs `codex app-server` with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (`x-codex-window-id`, `x-codex-turn-metadata`) tell it apart from Claude Code's own requests (`codexForClaudeCode`); an app that runs Codex as its own engine under its own name (Lody) stays that app. VS Code's Agents window runs `codex app-server` as `vscode_agent_host`, its originator and User-Agent: its calls are counted under VS Code (`vscodeAgentHostUA` in [`vscode.go`](../../internal/agent/vscode.go)), and its turns are Codex's for every Codex rule (`fromCodex`, `hostedCodex`), so one of Codex's own models asked there goes on Codex's sign-in (`codexOwnOffMagpie`) rather than 404; only Codex's own names (`codexNamed`) are kept as Codex's shape for a test asked as Codex (`TestVSCodeAgentHostIsCodex`, `TestVSCodeAgentHostOwnModelGoesOnSignIn`, `TestVSCodeAgentHostNotCodexTestShape`). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) | | WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-`. It becomes a loopback request carrying `magpie` or `magpie-` (`asFromLoopback`). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, `//v1/…`: `takeWSLPathKey` takes it off before `fromWSL` judges the request, and the request goes on without it. Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | +| HTTPS | With Settings → Network and sharing → HTTPS on (settings `HTTPS`, `magpie https on`; zhangly1 on X) `TLSOn` is true, so the listener serves other computers TLS as with mTLS, without a client certificate asked. Without `--tls-cert`, `settingsCert` serves the pair imported to `/https` (`ImportCert`: PEM in any split, the leaf the key matches first; refuses an encrypted key, a mismatch, an expired leaf; read again through `certFiles`), else `ownServerCert` from magpie's CA (made when HTTPS is turned on). A WSL distro's connection is sniffed, so its plain HTTP still works. `GET /magpie-ca.crt` (`caFile`) serves the CA to any address `lanGuard` lets in without a key (`caFileOpen`), 404 before one exists. The Settings routes (`internal/gui/https.go`) refuse a page from another computer that would flip the switch under itself (`errFarPage`). `TestHTTPSOtherComputer`, `TestHTTPSThisComputerPlain`, `TestHTTPSImportedCert`, `TestHTTPSCAFile`, `TestSettingsHTTPSFarPage`, `https-settings.test.cjs`. | [`https.go`](../../internal/gateway/https.go), [`tls.go`](../../internal/gateway/tls.go) | | mTLS | With Settings → Network and sharing → Require a client certificate on (settings `MTLS`, `magpie mtls on`; hhdaxia on X, #5596), other computers reach the gateway and `magpie web`'s page only over TLS with a client certificate magpie's own CA (`internal/mtls`, `MTLSStore`: `ca.pem`, `ca-key.pem`, `clients.json` under the settings folder) issued and hasn't revoked. `tlsServer.config(strict)` is asked per connection, so the switch needs no relisten: without `--tls-cert` it serves a certificate the CA signs in memory for this computer's names, addresses and the SNI name (`ownServerCert`, made again when they or the CA change, or after a day), and with mTLS on even without `--tls-cert` the listener serves TLS. A peer that isn't this computer or a WSL distro (`fromWSLNet`) is asked `RequireAndVerifyClientCert` and its handshake ended when `VerifyConnection`'s `Admits` fails. The guards (`lanGuard`, and `ClientCertGuard` on the page) then refuse 403 every request `NeedsClientCert` names: plain HTTP, a proxy's or tunnel's on loopback (`proxied`, unless `MAGPIE_TRUST_PROXY=1` says the proxy checks certificates itself), the page port (`viaPagePort`), a connection made before the switch, a certificate revoked since its handshake. This computer (`local`, `ownAddress`) and a WSL agent with the WSL key (`fromWSL`) are answered as before. The Settings routes (`internal/gui/mtls.go`) never let a page from another computer shut itself out: without a certificate it can't turn mTLS on, and it can't revoke or issue again the certificate it came with (`pageCert`, `errOwnCert`). Not handled: a `.p12` for browsers, and a proxy that can't check certificates itself. `TestMTLSOtherComputerHandshake`, `TestMTLSGuardEveryRoute`, `TestMTLSThisComputerAndProxies`, `TestMTLSToggleWithoutRelisten`, `TestMTLSRevokeMidConnection`, `TestClientCertGuardPage`, `TestSettingsMTLSPageLockout`. | [`mtls.go`](../../internal/gateway/mtls.go), [`tls.go`](../../internal/gateway/tls.go), [`internal/mtls`](../../internal/mtls/mtls.go) | | HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before. Obsidian's `app://obsidian.md` (`appOrigin`) is also answered with CORS headers, keyless: Copilot for Obsidian streams through its window's fetch, which reads no reply without them, and the origin is one only Obsidian's own window sends, so it gets no more than its calls without an Origin get, and from the network it still needs a key (`TestCORSObsidian`, shirotokiren on X); `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id the asking agent's own subscription in magpie serves (a provider whose `Account.Agent` is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (`ownFirst`, `provider.OwnRoute`; freefcw on X: Codex's bare `gpt-6-astra` went to Devin through `auto-gpt-6-astra`, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (`SetToGroup`, `agent.SetToGroup` over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and `agent.Reseat` prefer the agent's own subscription the same way (`AutoStandInFor`, `sameModel`). Otherwise a bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api): with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and `magpie group auto on` (`provider.OffSpread`, `offSpreadRefused`): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (`Resolve`), with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | diff --git a/internal/cli/help_cli.go b/internal/cli/help_cli.go index 8bbe33064..d8d84cb50 100644 --- a/internal/cli/help_cli.go +++ b/internal/cli/help_cli.go @@ -56,6 +56,8 @@ func helpFor(args []string) string { return statuslineUsage case "mtls": return mtlsUsage + case "https": + return httpsUsage case "heap": return heapUsage case "cpu": diff --git a/internal/cli/help_cli_test.go b/internal/cli/help_cli_test.go index 5e70fb58a..5dbbfd319 100644 --- a/internal/cli/help_cli_test.go +++ b/internal/cli/help_cli_test.go @@ -129,7 +129,7 @@ func runCommands(t *testing.T) []string { if len(cmds) < 40 { t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds) } - return append(cmds, "healthcheck", "heap", "cpu", "goroutines", "mtls") + return append(cmds, "healthcheck", "heap", "cpu", "goroutines", "mtls", "https") } func types(ix *ast.IndexExpr) string { diff --git a/internal/cli/https_cli.go b/internal/cli/https_cli.go new file mode 100644 index 000000000..1e441e7ce --- /dev/null +++ b/internal/cli/https_cli.go @@ -0,0 +1,137 @@ +package cli + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +const httpsUsage = `usage: magpie https [on|off|import […]|remove|ca [--out ]] + other computers reach this magpie's gateway, and magpie web's page, at https:// + (zhangly1 on X: Claude on another computer on the LAN). This computer, and a WSL + distro's agent, may still call plain http://. + magpie https whether it is on, the certificate served and magpie's CA + magpie https on|off serve other computers over https://, or plain http:// again + magpie https import serve your own certificate (its chain after it) and key, + PEM, in one file or several; kept in magpie's folder + magpie https remove back to a certificate magpie's own CA signs for this + computer's names and addresses + magpie https ca save magpie's CA as magpie-ca.crt in Downloads (or --out) + Without a certificate of your own, each computer that calls magpie trusts its CA once. + Get it from Settings, or on that computer from https://:/magpie-ca.crt + (check its SHA-256 against the one magpie https prints), then: + macOS sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt + Windows certutil -addstore -f Root magpie-ca.crt (as administrator) + Linux sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates + Node apps such as Claude Code: NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt` + +func httpsCmd(args []string) error { + if len(args) == 0 || args[0] == "status" { + return httpsStatus() + } + switch args[0] { + case "on", "off": + on := args[0] == "on" + if on { + if c, _ := gateway.ImportedFiles(); c == "" { + if _, _, err := gateway.CA(); err != nil { + return err + } + } + } + if err := settings.SetHTTPS(on); err != nil { + return err + } + if !on { + fmt.Println("HTTPS off: other computers call magpie at http:// again") + if gateway.TLSOn() { + fmt.Println("(still served over https://: --tls-cert or mTLS is on)") + } + return nil + } + fmt.Println("HTTPS on: other computers call magpie at https://; this computer may still call http://") + return httpsStatus() + case "import": + if len(args) < 2 { + return errors.New("usage: magpie https import […]") + } + var files [][]byte + for _, f := range args[1:] { + b, err := os.ReadFile(f) + if err != nil { + return err + } + files = append(files, b) + } + if err := gateway.ImportCert(files...); err != nil { + return err + } + fmt.Println("imported: other computers are served this certificate over https://") + if !gateway.HTTPSOn() && !gateway.TLSOn() { + fmt.Println("HTTPS is off: magpie https on to serve it") + } + return httpsStatus() + case "remove": + if err := gateway.RemoveImportedCert(); err != nil { + return err + } + fmt.Println("removed: magpie's CA signs the certificate served") + return nil + case "ca": + rest, out, err := outFlag(args[1:]) + if err != nil { + return err + } + if len(rest) != 0 { + return errors.New("usage: magpie https ca [--out ]") + } + b, fp, err := gateway.CA() + if err != nil { + return err + } + if out == "" { + out = downloadsDir() + } + p := filepath.Join(out, "magpie-ca.crt") + if err := mtls.WriteFile(p, b, 0o644); err != nil { + return err + } + fmt.Println(p) + fmt.Println(" SHA-256 " + fp) + return nil + } + return fmt.Errorf("magpie https: unknown %q\n%s", args[0], httpsUsage) +} + +func httpsStatus() error { + state := "off" + if gateway.HTTPSOn() { + state = "on" + } + fmt.Println("HTTPS " + state) + if !gateway.TLSOn() { + return nil + } + c, err := gateway.ServedCert() + if err != nil { + return err + } + from := map[string]string{"files": "--tls-cert " + c.File, "imported": "imported", "magpie": "magpie's CA"}[c.From] + fmt.Printf(" certificate %s · %s · until %s\n", from, strings.Join(c.Names, ", "), c.Until.Format("2006-01-02")) + if c.From == "magpie" { + _, fp, err := gateway.CA() + if err != nil { + return err + } + fmt.Println(" CA " + gateway.MTLSStore().CAFile()) + fmt.Println(" SHA-256 " + fp) + fmt.Println(" trust it on each computer that calls magpie: magpie https --help") + } + return nil +} diff --git a/internal/cli/main.go b/internal/cli/main.go index a0f382b03..b31a8739c 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -133,6 +133,8 @@ const usage = `magpie — one place to pick every agent's model magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK) magpie mtls [on|off|issue |list|revoke ] require a client certificate magpie issued from other computers (mTLS) + magpie https [on|off|import |remove|ca] + other computers call magpie at https://, with your certificate or one magpie's own CA signs magpie heap [] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory magpie cpu [] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU magpie goroutines [] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something @@ -356,6 +358,11 @@ func run(args []string) error { // else is read or moved return mtlsCmd(args[1:]) } + if len(args) > 0 && args[0] == "https" { + // HTTPS for other computers: the setting, the certificate and + // magpie's CA, nothing else + return httpsCmd(args[1:]) + } if len(args) > 0 && args[0] == "cpu" { // the running magpie's CPU profile: asks it, and moves nothing here return cpuCmd(args[1:]) diff --git a/internal/cli/tls_cli.go b/internal/cli/tls_cli.go index 4959a57a5..89a92e3c5 100644 --- a/internal/cli/tls_cli.go +++ b/internal/cli/tls_cli.go @@ -44,7 +44,10 @@ func tlsLine() string { } cert, _ := gateway.TLSFiles() if cert == "" { - cert = "magpie's own CA (mTLS)" + cert = "magpie's own CA" + if c, _ := gateway.ImportedFiles(); c != "" { + cert = c + } } s := muted.Render(" TLS ") + " " + cert if sum := gateway.TLSSummary(); sum != "" { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 72064eddd..fdc16f5d0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1045,6 +1045,7 @@ func (s *Server) routes() *routeMux { // another magpie looking for it at a new address (remote_prove.go) mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove) mux.HandleFunc("GET "+KeyPagePath, s.keyPage) + mux.HandleFunc("GET "+CAPath, s.caFile) mux.HandleFunc("GET "+keyPageData, s.keyInfo) // the join page, where another computer that knows the join password // gets a gateway key of its own (join.go) diff --git a/internal/gateway/https.go b/internal/gateway/https.go new file mode 100644 index 000000000..1d9af305a --- /dev/null +++ b/internal/gateway/https.go @@ -0,0 +1,280 @@ +package gateway + +import ( + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "log" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +// HTTPS for other computers without a certificate of a server's own +// (zhangly1 on X: Claude on another computer on the LAN needed magpie at +// https://). With Settings → Network and sharing → HTTPS on (settings +// HTTPS, `magpie https on`) the listener serves other computers TLS as it +// does with --tls-cert or mTLS (tlsListener), with: +// +// - the certificate and key imported in Settings or by `magpie https +// import` (kept in /https, read again when they change), else +// - one magpie's own CA (the mTLS one, made on first use) signs in +// memory for this computer's names, its addresses and the name the +// client dialled (ownServerCert). +// +// --tls-cert comes before both. Another computer trusts magpie's CA once: +// Settings saves it to Downloads, and the gateway serves it at CAPath to +// any address it lets in, without a key (a CA's certificate is public; +// its fingerprint is shown beside it to check the copy by). This computer, +// and a WSL distro's agent, may still call plain http://. + +// HTTPSOn: other computers reach magpie over https:// (the setting). +func HTTPSOn() bool { return settings.Shared().HTTPS } + +// CAPath is where the gateway serves magpie's CA, for another computer to +// trust: .crt, which Windows opens to install and Debian's +// update-ca-certificates reads, as PEM, which every system takes. +const CAPath = "/magpie-ca.crt" + +// FromThisComputer: r came from this computer, over loopback or to one of +// its own addresses, not through a proxy. +func FromThisComputer(r *http.Request) bool { return local(r) || ownAddress(r) } + +func httpsDir() string { return filepath.Join(settings.Dir(), "https") } + +// ImportedFiles are the certificate and key Settings imported, "" for +// none (both must be there). +func ImportedFiles() (cert, key string) { + cert, key = filepath.Join(httpsDir(), "cert.pem"), filepath.Join(httpsDir(), "key.pem") + if _, err := os.Stat(cert); err != nil { + return "", "" + } + if _, err := os.Stat(key); err != nil { + return "", "" + } + return cert, key +} + +var imported struct { + sync.Mutex + files *certFiles +} + +// importedCert serves the imported pair, read again when it changes; nil +// with none imported. +func importedCert() *certFiles { + c, k := ImportedFiles() + if c == "" { + return nil + } + imported.Lock() + defer imported.Unlock() + if imported.files == nil || imported.files.cert != c || imported.files.key != k { + imported.files = &certFiles{cert: c, key: k} + } + return imported.files +} + +// settingsCert is the server certificate without --tls-cert: the one +// imported, else one magpie's CA signs. An imported pair that doesn't +// load (its files removed by hand, say) gives way to magpie's own rather +// than ending every handshake. +func settingsCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { + if f := importedCert(); f != nil { + c, err := f.get(hello) + if err == nil { + return c, nil + } + log.Printf("TLS: the imported certificate in %s doesn't load (%v): serving one magpie's CA signs", httpsDir(), err) + } + return ownServerCert(hello) +} + +// ImportCert keeps a certificate (its chain after it) and its key for +// HTTPS, from PEM files given in any order and split any way: one file +// holding both, or a certificate, a chain and a key apart. The +// certificate the key belongs to goes first. Refused: no certificate, no +// key, an encrypted key, a key that belongs to none of them, or a +// certificate that has run out. +func ImportCert(files ...[]byte) error { + var certs [][]byte + var key *pem.Block + for _, b := range files { + for { + var blk *pem.Block + blk, b = pem.Decode(b) + if blk == nil { + break + } + switch { + case blk.Type == "CERTIFICATE": + certs = append(certs, blk.Bytes) + case blk.Type == "ENCRYPTED PRIVATE KEY" || blk.Headers["Proc-Type"] != "": + return errors.New("the private key has a passphrase: give it without one (openssl pkey -in key.pem -out key-open.pem)") + case strings.HasSuffix(blk.Type, "PRIVATE KEY"): + if key == nil { + key = blk + } + } + } + } + switch { + case len(certs) == 0 && key == nil: + return errors.New("no PEM certificate or key in the files given") + case len(certs) == 0: + return errors.New("a private key but no certificate: give the certificate's file too") + case key == nil: + return errors.New("a certificate but no private key: give the key's file too") + } + keyPEM := pem.EncodeToMemory(key) + leaf := -1 + for i, der := range certs { + if _, err := tls.X509KeyPair(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), keyPEM); err == nil { + leaf = i + break + } + } + if leaf < 0 { + return errors.New("the private key belongs to none of the certificates given") + } + certs[0], certs[leaf] = certs[leaf], certs[0] + var chain []byte + for _, der := range certs { + chain = append(chain, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...) + } + pair, err := tls.X509KeyPair(chain, keyPEM) + if err != nil { + return fmt.Errorf("the certificate and key can't be served: %w", err) + } + if pair.Leaf == nil { + if pair.Leaf, err = x509.ParseCertificate(pair.Certificate[0]); err != nil { + return err + } + } + if time.Now().After(pair.Leaf.NotAfter) { + return fmt.Errorf("the certificate ran out on %s", pair.Leaf.NotAfter.Format("2006-01-02")) + } + if err := os.MkdirAll(httpsDir(), 0o700); err != nil { + return err + } + if err := mtls.WriteFile(filepath.Join(httpsDir(), "key.pem"), keyPEM, 0o600); err != nil { + return err + } + return mtls.WriteFile(filepath.Join(httpsDir(), "cert.pem"), chain, 0o644) +} + +// RemoveImportedCert goes back to the certificate magpie's CA signs. +func RemoveImportedCert() error { + for _, f := range []string{"cert.pem", "key.pem"} { + if err := os.Remove(filepath.Join(httpsDir(), f)); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil +} + +// CertInfo is what the certificate other computers are served says. +type CertInfo struct { + // From: "files" (--tls-cert, File naming it), "imported" or "magpie" + // (its CA's) + From string `json:"from"` + File string `json:"file,omitempty"` + Names []string `json:"names,omitempty"` + Issuer string `json:"issuer,omitempty"` + Until time.Time `json:"until"` +} + +// ServedCert says which certificate other computers get over https://. +func ServedCert() (CertInfo, error) { + var c *tls.Certificate + var info CertInfo + var err error + if cf, kf := TLSFiles(); cf != "" && kf != "" { + info.From, info.File = "files", cf + var pair tls.Certificate + pair, err = tls.LoadX509KeyPair(cf, kf) + c = &pair + } else if f := importedCert(); f != nil { + info.From = "imported" + c, err = f.get(nil) + } else { + info.From = "magpie" + c, err = ownServerCert(nil) + } + if err != nil { + return info, err + } + if c == nil || len(c.Certificate) == 0 { + return info, errors.New("no certificate") + } + leaf, err := x509.ParseCertificate(c.Certificate[0]) + if err != nil { + return info, err + } + info.Names = append(info.Names, leaf.DNSNames...) + for _, ip := range leaf.IPAddresses { + info.Names = append(info.Names, ip.String()) + } + if len(info.Names) == 0 && leaf.Subject.CommonName != "" { + info.Names = []string{leaf.Subject.CommonName} + } + info.Issuer, info.Until = leaf.Issuer.CommonName, leaf.NotAfter + return info, nil +} + +// CA is magpie's CA certificate as PEM, made on first use, and its +// SHA-256 fingerprint (AB:CD:…), which a copy fetched over the network +// is checked by. +func CA() (pemBytes []byte, fingerprint string, err error) { + ca, _, err := MTLSStore().CA() + if err != nil { + return nil, "", err + } + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.Raw}), Fingerprint(ca.Raw), nil +} + +// Fingerprint is der's SHA-256 as colon-separated hex pairs, as Keychain +// Access, certmgr and openssl x509 -fingerprint show it. +func Fingerprint(der []byte) string { + sum := sha256.Sum256(der) + parts := make([]string, len(sum)) + for i, b := range sum { + parts[i] = fmt.Sprintf("%02X", b) + } + return strings.Join(parts, ":") +} + +// caFileOpen: r asks for magpie's CA, which is answered without a key. +func caFileOpen(r *http.Request) bool { + return r.URL.Path == CAPath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead) +} + +// caFile serves magpie's CA. One isn't made for a request: until HTTPS or +// mTLS made it, there is none to trust. +func (s *Server) caFile(w http.ResponseWriter, r *http.Request) { + st := MTLSStore() + if !st.HasCA() { + http.Error(w, "this magpie has no CA yet: turn on HTTPS in Settings → Network and sharing (magpie https on)", http.StatusNotFound) + return + } + b, err := os.ReadFile(st.CAFile()) + if err != nil { + http.Error(w, "magpie's CA can't be read: "+err.Error(), http.StatusInternalServerError) + return + } + h := w.Header() + h.Set("Content-Type", "application/x-x509-ca-cert") + h.Set("Content-Disposition", `attachment; filename="magpie-ca.crt"`) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Cache-Control", "no-cache") + w.Write(b) +} diff --git a/internal/gateway/https_test.go b/internal/gateway/https_test.go new file mode 100644 index 000000000..792d45ebc --- /dev/null +++ b/internal/gateway/https_test.go @@ -0,0 +1,240 @@ +package gateway + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "io" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/settings" +) + +func setHTTPS(t *testing.T, on bool) { + t.Helper() + if err := settings.SetHTTPS(on); err != nil { + t.Fatal(err) + } + if HTTPSOn() != on { + t.Fatalf("HTTPSOn() = %v after SetHTTPS(%v)", !on, on) + } +} + +// trusting is an HTTPS client that trusts only roots' certificates. +func trusting(t *testing.T, roots ...*x509.Certificate) *http.Client { + t.Helper() + pool := x509.NewCertPool() + for _, c := range roots { + pool.AddCert(c) + } + tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DisableKeepAlives: true} + t.Cleanup(tr.CloseIdleConnections) + return &http.Client{Timeout: 5 * time.Second, Transport: tr} +} + +func magpieCA(t *testing.T) *x509.Certificate { + t.Helper() + b, fp, err := CA() + if err != nil { + t.Fatal(err) + } + blk, _ := pem.Decode(b) + if blk == nil { + t.Fatalf("CA() isn't PEM: %q", b) + } + c, err := x509.ParseCertificate(blk.Bytes) + if err != nil { + t.Fatal(err) + } + if fp != Fingerprint(c.Raw) || len(fp) != 32*3-1 { + t.Fatalf("fingerprint %q", fp) + } + return c +} + +// zhangly1 on X: Claude on another computer on the LAN needed magpie at +// https://. With HTTPS on, another computer is served TLS with a +// certificate magpie's CA signs, which a client trusting that CA alone +// verifies, plain http:// from it is refused, and the switch takes +// effect at the next connection; off, it is plain http:// again. +func TestHTTPSOtherComputer(t *testing.T) { + key := mtlsHome(t, false) + addr := serveMTLSGateway(t, true, "") + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("off: %d %q %v", code, body, err) + } + setHTTPS(t, true) + if !TLSOn() || Scheme() != "https" { + t.Fatalf("TLSOn %v, Scheme %q with HTTPS on", TLSOn(), Scheme()) + } + c := trusting(t, magpieCA(t)) + for _, rt := range mtlsRoutes { + code, body, err := mcall(t, c, rt[0], "https://"+addr+rt[1], key) + if err != nil || code != 200 || body != "served "+rt[1] { + t.Errorf("on, %s %s: %d %q %v", rt[0], rt[1], code, body, err) + } + } + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err == nil && code < 400 { + t.Errorf("on, plain from another computer: %d %q, want it refused", code, body) + } + if _, _, err := mcall(t, trusting(t), "GET", "https://"+addr+"/v1/models", key); err == nil { + t.Error("a client that doesn't trust magpie's CA verified its certificate") + } + info, err := ServedCert() + if err != nil || info.From != "magpie" || info.Issuer == "" || !info.Until.After(time.Now()) { + t.Errorf("ServedCert: %+v %v", info, err) + } + setHTTPS(t, false) + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("off again: %d %q %v", code, body, err) + } +} + +// This computer's own agents keep plain http:// with HTTPS on. +func TestHTTPSThisComputerPlain(t *testing.T) { + key := mtlsHome(t, false) + setHTTPS(t, true) + addr := serveMTLSGateway(t, false, "") + if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("this computer, plain: %d %q %v", code, body, err) + } + if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("this computer, https: %d %q %v", code, body, err) + } +} + +// testPKI is a CA of the test's own and a server certificate it signs +// for 127.0.0.1, valid until notAfter. +type testPKI struct { + ca *x509.Certificate + caPEM, cert, key []byte + otherKey, encKey []byte + expiredC, expiredK []byte +} + +func newTestPKI(t *testing.T) testPKI { + t.Helper() + var p testPKI + caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + caTpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Test Root"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + der, err := x509.CreateCertificate(rand.Reader, caTpl, caTpl, &caKey.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + p.ca, _ = x509.ParseCertificate(der) + p.caPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + leaf := func(serial int64, until time.Time) ([]byte, []byte) { + k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + tpl := &x509.Certificate{SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "nas.home"}, DNSNames: []string{"nas.home"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, NotBefore: until.Add(-48 * time.Hour), NotAfter: until, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + d, err := x509.CreateCertificate(rand.Reader, tpl, p.ca, &k.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + kd, _ := x509.MarshalPKCS8PrivateKey(k) + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: d}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: kd}) + } + p.cert, p.key = leaf(2, time.Now().Add(12*time.Hour)) + _, p.otherKey = leaf(3, time.Now().Add(12*time.Hour)) + p.expiredC, p.expiredK = leaf(4, time.Now().Add(-time.Hour)) + p.encKey = pem.EncodeToMemory(&pem.Block{Type: "ENCRYPTED PRIVATE KEY", Bytes: []byte{1, 2, 3}}) + return p +} + +// The user's own certificate and key, imported (a chain and a key apart, +// in any order), are served instead of one magpie's CA signs; a pair +// that can't be served is refused and leaves nothing behind; removed, +// magpie's CA signs again. +func TestHTTPSImportedCert(t *testing.T) { + key := mtlsHome(t, false) + setHTTPS(t, true) + p := newTestPKI(t) + for name, files := range map[string][][]byte{ + "no key": {p.cert}, + "no certificate": {p.key}, + "a stranger key": {p.cert, p.otherKey}, + "a passphrase": {p.cert, p.encKey}, + "run out": {p.expiredC, p.expiredK}, + "nothing in them": {[]byte("hello")}, + } { + if err := ImportCert(files...); err == nil { + t.Errorf("%s: imported", name) + } + if c, _ := ImportedFiles(); c != "" { + t.Fatalf("%s: left %s behind", name, c) + } + } + // the key first, the CA's certificate before the leaf: the leaf the + // key belongs to goes first + if err := ImportCert(p.key, append(append([]byte{}, p.caPEM...), p.cert...)); err != nil { + t.Fatal(err) + } + if c, k := ImportedFiles(); c == "" || k == "" { + t.Fatal("nothing kept") + } else if fi, err := os.Stat(k); err == nil && fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' { + t.Errorf("key.pem mode %v", fi.Mode().Perm()) + } + addr := serveMTLSGateway(t, true, "") + if code, body, err := mcall(t, trusting(t, p.ca), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("imported: %d %q %v", code, body, err) + } + if _, _, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err == nil { + t.Error("magpie's CA's certificate was served over the imported one") + } + if info, err := ServedCert(); err != nil || info.From != "imported" || info.Issuer != "Test Root" || !strings.Contains(strings.Join(info.Names, ","), "nas.home") { + t.Errorf("ServedCert: %+v %v", info, err) + } + if err := RemoveImportedCert(); err != nil { + t.Fatal(err) + } + if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 { + t.Fatalf("removed: %d %q %v", code, body, err) + } +} + +// Another computer fetches magpie's CA without a key, from an address +// the share lets in, before it trusts magpie's https://; every other +// route still asks for the key. With no CA made yet there is none. +func TestHTTPSCAFile(t *testing.T) { + mtlsHome(t, false) + var s Server + mux := http.NewServeMux() + mux.HandleFunc("GET "+CAPath, s.caFile) + mux.HandleFunc("GET /v1/models", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "models") }) + h := lanGuard(mux) + get := func(path string) *httptest.ResponseRecorder { + r := httptest.NewRequest("GET", path, nil) + r.RemoteAddr = "192.168.1.9:5000" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + w := get(CAPath) + want, _, _ := CA() + if w.Code != 200 || w.Body.String() != string(want) || w.Header().Get("Content-Type") != "application/x-x509-ca-cert" { + t.Fatalf("CA: %d %q %q", w.Code, w.Header().Get("Content-Type"), w.Body.String()) + } + if w := get("/v1/models"); w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden { + t.Errorf("/v1/models without a key: %d", w.Code) + } + if w := get(CAPath + "x"); w.Code < 400 { + t.Errorf("%sx without a key: %d", CAPath, w.Code) + } + if err := os.RemoveAll(filepath.Dir(MTLSStore().CAFile())); err != nil { + t.Fatal(err) + } + if w := get(CAPath); w.Code != http.StatusNotFound { + t.Errorf("no CA: %d", w.Code) + } +} diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 1ed1a702a..88ada726a 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -616,7 +616,9 @@ func lanGuard(next http.Handler) http.Handler { } // the key page itself is the same bytes for everyone, so it is // opened before the key it asks for is typed; its data isn't - if remote && keyPageOpen(r) { + // magpie's CA, too: public, and fetched before the computer + // asking trusts magpie's https:// (https.go) + if remote && (keyPageOpen(r) || caFileOpen(r)) { next.ServeHTTP(w, r) return } diff --git a/internal/gateway/mtls.go b/internal/gateway/mtls.go index a71c9ae05..71f302da9 100644 --- a/internal/gateway/mtls.go +++ b/internal/gateway/mtls.go @@ -135,12 +135,12 @@ type tlsServer struct { } // config is the TLS config for a connection, nil to serve it plain HTTP -// (no --tls-cert and mTLS off). strict asks for a client certificate and +// (no --tls-cert, mTLS off and HTTPS off). strict asks for a client certificate and // ends a handshake without one, for a peer that isn't this computer or a // WSL distro. func (t *tlsServer) config(strict bool) *tls.Config { on := MTLSOn() - if t == nil || (t.files == nil && !on) { + if t == nil || (t.files == nil && !on && !HTTPSOn()) { return nil } cfg := &tls.Config{ @@ -152,7 +152,7 @@ func (t *tlsServer) config(strict bool) *tls.Config { if t.files != nil { cfg.GetCertificate = t.files.get } else { - cfg.GetCertificate = ownServerCert + cfg.GetCertificate = settingsCert } if !on { return cfg @@ -249,7 +249,7 @@ func ownServerCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { } c, err := st.ServerCert(names, ips) if err != nil { - return nil, errors.New("mTLS: magpie's CA can't sign a server certificate: " + err.Error()) + return nil, errors.New("TLS: magpie's CA can't sign a server certificate: " + err.Error()) } ownCerts.key, ownCerts.stamp, ownCerts.made, ownCerts.cert = key.String(), stampOf(st.CAFile()), time.Now(), &c return &c, nil diff --git a/internal/gateway/tls.go b/internal/gateway/tls.go index e118f777a..38b8e5dee 100644 --- a/internal/gateway/tls.go +++ b/internal/gateway/tls.go @@ -40,10 +40,10 @@ func TLSFiles() (cert, key string) { } // TLSOn: the gateway serves other computers over HTTPS: with the files -// set, or with mTLS on (mtls.go). +// set, with mTLS on (mtls.go), or with HTTPS on (https.go). func TLSOn() bool { c, k := TLSFiles() - return c != "" && k != "" || MTLSOn() + return c != "" && k != "" || MTLSOn() || HTTPSOn() } // Scheme is the gateway's scheme for other computers: https with TLS on. @@ -109,7 +109,7 @@ func TLSSummary() string { c, err = tls.LoadX509KeyPair(cf, kf) } else { var own *tls.Certificate - if own, err = ownServerCert(nil); own != nil { + if own, err = settingsCert(nil); own != nil { c = *own } } @@ -288,7 +288,7 @@ func (l *tlsListener) accept() { switch { case cfg == nil: l.taken(c) - case wsl && MTLSOn(): + case wsl && (MTLSOn() || HTTPSOn()): go l.sniff(c, cfg) default: l.taken(tls.Server(c, cfg)) diff --git a/internal/gui/api.go b/internal/gui/api.go index b7ef0d645..e8c2dcd7e 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1541,6 +1541,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { dataFolderRoutes(mux, w) mtlsRoutes(mux, w) joinRoutes(mux) + httpsRoutes(mux, w) uninstallRoutes(mux, w) archiveRoutes(mux) libraryRoutes(mux, w) diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 9458edfbc..ddeb1e3c6 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -4134,6 +4134,7 @@ input.words.remote-key { width: 160px; } .warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; } .row.pref .sub .warn { color: var(--amber); } .row.pref .sub.wraps { white-space: normal; } +.row.pref code.sub.https-cmd { display: block; font-size: 11px; user-select: text; -webkit-user-select: text; overflow-wrap: anywhere; } .row.pref .login-allow-open { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; } .row.pref .login-allow-open:hover { text-decoration: underline; } /* the field's clock and picker in the page's own palette */ diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 02de8642f..924ab5122 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20043,6 +20043,7 @@ function renderSettings() { renderLAN(s); renderAllow(s); renderMTLS(s); + renderHTTPS(s); renderCORS(s); renderSync(); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c5ee1d87c..695945687 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2749,6 +2749,19 @@ const I18N = { "Join link": "加入链接", "Use a password of at least 8 characters": "请使用至少 8 个字符的密码", "Use a password of at most 1024 bytes": "请使用不超过 1024 字节的密码", + "Other computers call magpie at https://; this computer can still use http://": "其他电脑通过 https:// 访问 magpie;本机仍可用 http://", + "Already served over https:// by Require a client certificate or --tls-cert": "已通过“要求客户端证书”或 --tls-cert 以 https:// 提供", + "Your certificate": "你的证书", + "Signed by magpie’s CA": "由 magpie 的 CA 签发", + "magpie’s CA": "magpie 的 CA", + "Trust it once on each computer that calls magpie · SHA-256 {fp}": "在每台访问 magpie 的电脑上信任一次 · SHA-256 {fp}", + "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "此页面是从其他电脑打开的:请在运行 magpie 的电脑上开关 HTTPS", + "Claude Code and other Node apps": "Claude Code 等 Node 应用", + "A certificate but no private key: choose the key’s file too": "有证书但没有私钥:请同时选择私钥文件", + "A private key but no certificate: choose the certificate’s file too": "有私钥但没有证书:请同时选择证书文件", + "The private key belongs to none of the certificates": "私钥与所选证书都不匹配", + "The private key has a passphrase: choose one without": "私钥设有密码:请选择无密码的私钥", + "No PEM certificate or key in the files chosen": "所选文件中没有 PEM 证书或私钥", "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他电脑只能经 HTTPS、凭这里签发的证书连到 magpie,有网关密钥也不行;本机始终可以", "Client certificates": "客户端证书", "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "为设备保存到「下载」:证书、私钥和 magpie 的 CA", @@ -7691,6 +7704,19 @@ const I18N = { "Join link": "加入連結", "Use a password of at least 8 characters": "請使用至少 8 個字元的密碼", "Use a password of at most 1024 bytes": "請使用不超過 1024 位元組的密碼", + "Other computers call magpie at https://; this computer can still use http://": "其他電腦透過 https:// 存取 magpie;本機仍可用 http://", + "Already served over https:// by Require a client certificate or --tls-cert": "已透過「要求用戶端憑證」或 --tls-cert 以 https:// 提供", + "Your certificate": "你的憑證", + "Signed by magpie’s CA": "由 magpie 的 CA 簽發", + "magpie’s CA": "magpie 的 CA", + "Trust it once on each computer that calls magpie · SHA-256 {fp}": "在每台存取 magpie 的電腦上信任一次 · SHA-256 {fp}", + "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "此頁面是從其他電腦開啟的:請在執行 magpie 的電腦上開關 HTTPS", + "Claude Code and other Node apps": "Claude Code 等 Node 應用程式", + "A certificate but no private key: choose the key’s file too": "有憑證但沒有私鑰:請同時選擇私鑰檔案", + "A private key but no certificate: choose the certificate’s file too": "有私鑰但沒有憑證:請同時選擇憑證檔案", + "The private key belongs to none of the certificates": "私鑰與所選憑證都不相符", + "The private key has a passphrase: choose one without": "私鑰設有密碼:請選擇無密碼的私鑰", + "No PEM certificate or key in the files chosen": "所選檔案中沒有 PEM 憑證或私鑰", "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他電腦只能經 HTTPS、憑這裡簽發的憑證連到 magpie,有閘道金鑰也不行;本機始終可以", "Client certificates": "用戶端憑證", "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "為裝置儲存到「下載」:憑證、私鑰和 magpie 的 CA", @@ -12611,6 +12637,19 @@ const I18N = { "Join link": "参加リンク", "Use a password of at least 8 characters": "8 文字以上のパスワードにしてください", "Use a password of at most 1024 bytes": "1024 バイト以下のパスワードにしてください", + "Other computers call magpie at https://; this computer can still use http://": "他のコンピューターは https:// で magpie に接続します。このコンピューターは http:// も使えます", + "Already served over https:// by Require a client certificate or --tls-cert": "「クライアント証明書を必須にする」または --tls-cert により https:// で提供中", + "Your certificate": "独自の証明書", + "Signed by magpie’s CA": "magpie の CA が署名", + "magpie’s CA": "magpie の CA", + "Trust it once on each computer that calls magpie · SHA-256 {fp}": "magpie に接続する各コンピューターで一度信頼してください · SHA-256 {fp}", + "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "このページは別のコンピューターから開かれています。HTTPS のオン・オフは magpie を実行しているコンピューターで行ってください", + "Claude Code and other Node apps": "Claude Code などの Node アプリ", + "A certificate but no private key: choose the key’s file too": "証明書はありますが秘密鍵がありません。秘密鍵のファイルも選んでください", + "A private key but no certificate: choose the certificate’s file too": "秘密鍵はありますが証明書がありません。証明書のファイルも選んでください", + "The private key belongs to none of the certificates": "秘密鍵がどの証明書とも一致しません", + "The private key has a passphrase: choose one without": "秘密鍵にパスフレーズがあります。パスフレーズのないものを選んでください", + "No PEM certificate or key in the files chosen": "選んだファイルに PEM の証明書も秘密鍵もありません", "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "他のコンピューターは、ここで発行した証明書を持って HTTPS でのみ magpie に接続できます。ゲートウェイキーがあっても同じです。このコンピューターは常に接続できます", "Client certificates": "クライアント証明書", "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "デバイス用に「ダウンロード」へ保存:証明書、その鍵、magpie の CA", @@ -17562,6 +17601,19 @@ const I18N = { "Join link": "Beitrittslink", "Use a password of at least 8 characters": "Verwenden Sie ein Passwort mit mindestens 8 Zeichen", "Use a password of at most 1024 bytes": "Verwenden Sie ein Passwort mit höchstens 1024 Bytes", + "Other computers call magpie at https://; this computer can still use http://": "Andere Computer rufen magpie über https:// auf; dieser Computer kann weiter http:// nutzen", + "Already served over https:// by Require a client certificate or --tls-cert": "Wird bereits über https:// bereitgestellt (Client-Zertifikat verlangen oder --tls-cert)", + "Your certificate": "Eigenes Zertifikat", + "Signed by magpie’s CA": "Von magpies CA signiert", + "magpie’s CA": "magpies CA", + "Trust it once on each computer that calls magpie · SHA-256 {fp}": "Einmal auf jedem Computer vertrauen, der magpie aufruft · SHA-256 {fp}", + "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "Diese Seite ist von einem anderen Computer geöffnet: HTTPS auf dem Computer ein- oder ausschalten, auf dem magpie läuft", + "Claude Code and other Node apps": "Claude Code und andere Node-Apps", + "A certificate but no private key: choose the key’s file too": "Ein Zertifikat, aber kein privater Schlüssel: auch die Schlüsseldatei wählen", + "A private key but no certificate: choose the certificate’s file too": "Ein privater Schlüssel, aber kein Zertifikat: auch die Zertifikatsdatei wählen", + "The private key belongs to none of the certificates": "Der private Schlüssel gehört zu keinem der Zertifikate", + "The private key has a passphrase: choose one without": "Der private Schlüssel hat eine Passphrase: einen ohne wählen", + "No PEM certificate or key in the files chosen": "Keine PEM-Zertifikate oder -Schlüssel in den gewählten Dateien", "Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "Andere Computer erreichen magpie nur über HTTPS mit einem hier ausgestellten Zertifikat, auch mit Gateway-Schlüssel; dieser Computer immer", "Client certificates": "Client-Zertifikate", "Saved to Downloads for the device: the certificate, its key and magpie’s CA": "Für das Gerät in „Downloads“ gespeichert: das Zertifikat, sein Schlüssel und magpies CA", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index dbc356345..28c3ce5ea 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -362,6 +362,7 @@
+
Web pages
Browser access
diff --git a/internal/gui/assets/plugins/gateway/settings.js b/internal/gui/assets/plugins/gateway/settings.js index 41364086f..fd894301a 100644 --- a/internal/gui/assets/plugins/gateway/settings.js +++ b/internal/gui/assets/plugins/gateway/settings.js @@ -346,6 +346,106 @@ function renderMTLS(s) { } } +// renderHTTPS: HTTPS for other computers (zhangly1 on X: Claude on another +// computer on the LAN needed magpie at https://), under Share on local +// network. On, other computers get the certificate imported here, or one +// magpie's own CA signs; then the CA's row saves it to Downloads, and the +// rows under it say how another computer fetches and trusts it. Asked of +// its own route (https.go), as Browser access is; drawn while magpie +// answers other computers or the switch is on. +let httpsState = null; +function httpsSays(m) { + if (/^this page is open from another computer/.test(m)) return t("This page is open from another computer: turn HTTPS on or off from the computer magpie runs on"); + if (/^a certificate but no private key/.test(m)) return t("A certificate but no private key: choose the key’s file too"); + if (/^a private key but no certificate/.test(m)) return t("A private key but no certificate: choose the certificate’s file too"); + if (/^the private key belongs to none/.test(m)) return t("The private key belongs to none of the certificates"); + if (/^the private key has a passphrase/.test(m)) return t("The private key has a passphrase: choose one without"); + if (/^no PEM certificate or key/.test(m)) return t("No PEM certificate or key in the files chosen"); + return t(m); +} +function renderHTTPS(s, asked) { + const box = $("#httpsList"); + if (!box) return; + if (!asked) api("settings/https").then((h) => { httpsState = h; renderHTTPS(prefs, true); }).catch(() => {}); + const h = httpsState; + if (!s || !h || (!s.lan && !s.onNetwork && !h.on)) return void box.replaceChildren(); + const post = (what, body) => writingPrefs(api("settings/https" + what, body)) + .then((nh) => { + httpsState = nh; renderHTTPS(prefs, true); + if (nh.saved) status(t("Saved to {path}", { path: nh.saved }), "ok", 4000); + }) + .catch((e) => { status(httpsSays(e.message), "err"); renderHTTPS(prefs, true); }); + const rows = []; + const row = (cls, name, sub, ...tools) => { + const r = el("div", "row pref " + cls); + const who = el("div", "who"); + who.append(el("div", "name", name)); + if (sub) who.append(sub instanceof Node ? sub : el("div", "sub", sub)); + const val = el("div", "val"); + val.append(...tools); + r.append(who, val); + rows.push(r); + return r; + }; + row("https-row", "HTTPS", + h.served && !h.on ? t("Already served over https:// by Require a client certificate or --tls-cert") : t("Other computers call magpie at https://; this computer can still use http://"), + segs([["off", t("Off")], ["on", t("On")]], h.on ? "on" : "off", (v) => post("", { on: v === "on" }))); + if (h.served) { + const c = h.cert; + const until = c && new Date(c.until).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" }); + const from = !c ? "" : c.from === "files" ? "--tls-cert " + c.file : c.from === "imported" ? t("Your certificate") : t("Signed by magpie’s CA"); + const sub = h.certError ? el("div", "sub err", t(h.certError)) + : el("div", "sub", [from, (c.names || []).join(", "), t("Until {date}", { date: until })].filter(Boolean).join(" · ")); + sub.title = sub.textContent; + const tools = []; + if (!h.files) { + const file = el("input"); + file.type = "file"; + file.multiple = true; + file.accept = ".pem,.crt,.cer,.key,application/x-pem-file,application/x-x509-ca-cert"; + file.hidden = true; + file.onchange = async () => { + const files = await Promise.all([...file.files].map((f) => f.text())); + file.value = ""; + if (files.length) post("/import", { files }); + }; + const pick = el("button", "text", t("Import…")); + pick.type = "button"; + pick.onclick = () => file.click(); + tools.push(file, pick); + if (c?.from === "imported") { + const x = el("button", "text", t("Remove")); + x.type = "button"; + x.onclick = () => post("/remove", {}); + tools.push(x); + } + } + row("https-cert", t("Certificate"), sub, ...tools); + } + if (h.ca) { + const save = el("button", "text", t("Save")); + save.type = "button"; + save.onclick = () => post("/ca", {}); + const sub = el("div", "sub wraps", t("Trust it once on each computer that calls magpie · SHA-256 {fp}", { fp: h.ca })); + row("https-ca", t("magpie’s CA"), sub, save); + // the address picked under Share on local network, else the first + const at = (h.caURLs || []).find((u) => u.startsWith(lanSelectedURL + "/")) || h.caURLs?.[0]; + const steps = [ + at && [t("Download"), "curl -kO " + at], + ["macOS", "sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt"], + ["Windows", "certutil -addstore -f Root magpie-ca.crt"], + ["Linux", "sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates"], + [t("Claude Code and other Node apps"), "NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt"], + ]; + for (const [name, cmd] of steps.filter(Boolean)) { + const code = el("code", "sub https-cmd", cmd); + code.title = cmd; + row("https-step", name, code, copyBtn(cmd, name, t("Copied"))); + } + } + box.replaceChildren(...rows); +} + // renderLAN: the gateway shared on the local network, for agents on other // machines. Gateway keys and connection examples live together in Gateway. let lanSelectedURL = "", lanProtocol = "openai"; diff --git a/internal/gui/https.go b/internal/gui/https.go new file mode 100644 index 000000000..d80de6f43 --- /dev/null +++ b/internal/gui/https.go @@ -0,0 +1,132 @@ +package gui + +import ( + "encoding/json" + "errors" + "net/http" + "path/filepath" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/mtls" + "github.com/yetone/magpie/internal/settings" +) + +// httpsState is Settings → Network and sharing's HTTPS rows (zhangly1 on +// X: Claude on another computer on the LAN needed magpie at https://). +type httpsState struct { + On bool `json:"on"` + // Served: other computers are served https:// now, by this switch, + // --tls-cert (Files) or mTLS + Served bool `json:"served"` + Files bool `json:"files,omitempty"` + MTLS bool `json:"mtls,omitempty"` + // Cert: the certificate served, while Served + Cert *gateway.CertInfo `json:"cert,omitempty"` + CertErr string `json:"certError,omitempty"` + // CA: magpie's CA's SHA-256 while it signs the certificate served, + // and CAURLs where other computers download it + CA string `json:"ca,omitempty"` + CAURLs []string `json:"caURLs,omitempty"` + // Saved: where the CA was just saved + Saved string `json:"saved,omitempty"` +} + +func httpsNow() httpsState { + s := httpsState{On: gateway.HTTPSOn(), Served: gateway.TLSOn(), MTLS: gateway.MTLSOn()} + c, k := gateway.TLSFiles() + s.Files = c != "" && k != "" + if !s.Served { + return s + } + info, err := gateway.ServedCert() + if err != nil { + s.CertErr = err.Error() + return s + } + s.Cert = &info + if info.From == "magpie" { + if _, fp, err := gateway.CA(); err == nil { + s.CA = fp + } + for _, u := range gateway.LANURLs() { + s.CAURLs = append(s.CAURLs, u+gateway.CAPath) + } + } + return s +} + +var errFarPage = errors.New("this page is open from another computer, and HTTPS changes how it is reached: turn it on or off from the computer magpie runs on") + +func httpsRoutes(mux *http.ServeMux, w Windows) { + mux.HandleFunc("GET /api/settings/https", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, httpsNow()) + }) + // on or off: on makes magpie's CA first, unless a certificate was + // imported. A page open from another computer can't flip it under + // itself: its next request would come in the other scheme. + mux.HandleFunc("POST /api/settings/https", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ On bool } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if isWeb(w) && !gateway.FromThisComputer(r) && in.On != gateway.HTTPSOn() { + fail(rw, errFarPage) + return + } + if in.On { + if c, _ := gateway.ImportedFiles(); c == "" { + if _, _, err := gateway.CA(); err != nil { + fail(rw, err) + return + } + } + } + if err := settings.SetHTTPS(in.On); err != nil { + fail(rw, err) + return + } + writeJSON(rw, httpsNow()) + }) + // the user's own certificate and key: the PEM files' text, any split + mux.HandleFunc("POST /api/settings/https/import", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Files []string } + if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 1<<20)).Decode(&in); err != nil { + fail(rw, err) + return + } + files := make([][]byte, len(in.Files)) + for i, f := range in.Files { + files[i] = []byte(f) + } + if err := gateway.ImportCert(files...); err != nil { + fail(rw, err) + return + } + writeJSON(rw, httpsNow()) + }) + mux.HandleFunc("POST /api/settings/https/remove", func(rw http.ResponseWriter, r *http.Request) { + if err := gateway.RemoveImportedCert(); err != nil { + fail(rw, err) + return + } + writeJSON(rw, httpsNow()) + }) + // magpie's CA, saved to Downloads as magpie-ca.crt for another computer + mux.HandleFunc("POST /api/settings/https/ca", func(rw http.ResponseWriter, r *http.Request) { + b, _, err := gateway.CA() + if err != nil { + fail(rw, err) + return + } + p := filepath.Join(downloads(), "magpie-ca.crt") + if err := mtls.WriteFile(p, b, 0o644); err != nil { + fail(rw, err) + return + } + _ = w.OpenFolder(filepath.Dir(p)) + s := httpsNow() + s.Saved = tilde(p) + writeJSON(rw, s) + }) +} diff --git a/internal/gui/https_test.go b/internal/gui/https_test.go new file mode 100644 index 000000000..0e84de459 --- /dev/null +++ b/internal/gui/https_test.go @@ -0,0 +1,107 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/settings" +) + +// webTab is the page served to a browser (magpie web). +type webTab struct{ folderOnly } + +func (webTab) browserTab() {} + +func httpsMux(t *testing.T, w Windows) func(method, path, body, from string) (int, httpsState, string) { + t.Helper() + mux := http.NewServeMux() + httpsRoutes(mux, w) + return func(method, path, body, from string) (int, httpsState, string) { + t.Helper() + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if from != "" { + r.RemoteAddr = from + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, r) + var s httpsState + json.Unmarshal(rec.Body.Bytes(), &s) + return rec.Code, s, rec.Body.String() + } +} + +// Settings → Network and sharing → HTTPS (zhangly1 on X): on makes +// magpie's CA and serves a certificate it signs, its fingerprint shown; +// Save puts magpie-ca.crt in Downloads; off goes back to plain http://. +func TestSettingsHTTPSOnSaveOff(t *testing.T) { + h := sandboxHome(t) + t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499") + t.Setenv(gateway.TLSCertEnv, "") + t.Setenv(gateway.TLSKeyEnv, "") + os.MkdirAll(filepath.Join(h, "Downloads"), 0o755) + call := httpsMux(t, folderOnly{}) + + if code, s, out := call("GET", "/api/settings/https", "", ""); code != 200 || s.On || s.Served { + t.Fatalf("at first: %d %s", code, out) + } + code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "") + if code != 200 || !s.On || !s.Served || !settings.Shared().HTTPS || s.Cert == nil || s.Cert.From != "magpie" || s.CA == "" { + t.Fatalf("on: %d %s", code, out) + } + for _, u := range s.CAURLs { + if !strings.HasPrefix(u, "https://") || !strings.HasSuffix(u, gateway.CAPath) { + t.Errorf("CA's address %q", u) + } + } + code, s, out = call("POST", "/api/settings/https/ca", `{}`, "") + if code != 200 || s.Saved == "" { + t.Fatalf("save: %d %s", code, out) + } + b, err := os.ReadFile(filepath.Join(h, "Downloads", "magpie-ca.crt")) + want, fp, _ := gateway.CA() + if err != nil || string(b) != string(want) || fp != s.CA { + t.Fatalf("saved CA: %v %q", err, b) + } + code, s, out = call("POST", "/api/settings/https", `{"on":false}`, "") + if code != 200 || s.On || s.Served || settings.Shared().HTTPS { + t.Fatalf("off: %d %s", code, out) + } +} + +// A page open in a browser on another computer can't turn HTTPS on or +// off under itself; one on this computer can, and the app's window can. +func TestSettingsHTTPSFarPage(t *testing.T) { + sandboxHome(t) + t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499") + call := httpsMux(t, webTab{}) + if code, _, out := call("POST", "/api/settings/https", `{"on":true}`, "192.168.1.9:5000"); code < 400 || settings.Shared().HTTPS { + t.Fatalf("far page turned it on: %d %s", code, out) + } + if code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "127.0.0.1:5000"); code != 200 || !s.On { + t.Fatalf("this computer's page: %d %s", code, out) + } + // the same value again changes nothing, and is answered + if code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "192.168.1.9:5000"); code != 200 || !s.On { + t.Fatalf("far page, unchanged: %d %s", code, out) + } +} + +// An import that doesn't parse is refused with the reason, and nothing is +// kept. +func TestSettingsHTTPSImportRefused(t *testing.T) { + sandboxHome(t) + call := httpsMux(t, folderOnly{}) + code, _, out := call("POST", "/api/settings/https/import", `{"files":["not a certificate"]}`, "") + if code < 400 || !strings.Contains(out, "no PEM certificate or key") { + t.Fatalf("import: %d %s", code, out) + } + if c, _ := gateway.ImportedFiles(); c != "" { + t.Fatalf("kept %s", c) + } +} diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index eff75cedb..ea3d9c4b0 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -217,6 +217,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { was.RouterAllTools = true // the Library's servers/hub-tools was.BusyLoad = 150 // the Routing page's busy-load was.MTLS = true // Network and sharing's settings/mtls + was.HTTPS = true // Network and sharing's settings/https // the Routing groups page's defaults for every group (groups/defaults) was.GroupSink, was.GroupFirstToken, was.GroupPatience = true, 30, 120 if err := settings.Save(was); err != nil { diff --git a/internal/gui/tests/https-settings.test.cjs b/internal/gui/tests/https-settings.test.cjs new file mode 100644 index 000000000..e0dbc79b4 --- /dev/null +++ b/internal/gui/tests/https-settings.test.cjs @@ -0,0 +1,244 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// HTTPS for other computers (zhangly1 on X: Claude on another computer on +// the LAN needed magpie at https://): Settings › Network, under Require a +// client certificate, turns HTTPS on; the Certificate row says which is +// served and imports the user's own PEM files (or removes them); magpie's +// CA row shows its SHA-256 and saves it to Downloads, the path said; the +// rows under it give the download and each system's trust command with a +// Copy button. A refused import or a far page's switch is told in the +// page's language. Hidden while magpie answers only this computer. +// English and Chinese, Chromium and WebKit, 390px; the strings in all +// four languages; 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 { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const file = async (route, url) => { + const f = 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(f)]; + await route.fulfill({ body: await fs.readFile(f), contentType }); +}; +const boot = (route, lang) => route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + +const FP = Array.from({ length: 32 }, (_, i) => (i * 7 + 16).toString(16).toUpperCase().padStart(2, "0")).join(":"); +const FAR = "this page is open from another computer, and HTTPS changes how it is reached: turn it on or off from the computer magpie runs on"; +const NOKEY = "a certificate but no private key: give the key's file too"; + +function server(lang, posts, over = {}) { + const s = { + theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.400", dir: "/config/magpie", + gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", login: false, + visionModels: [], imageGenModels: [], allowIPs: [], + lan: true, lanURLs: ["http://192.168.1.20:3425"], mtls: false, mtlsCerts: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, ...over.settings, + }; + let h = { on: false, served: false }; + const served = (from) => ({ + on: true, served: true, + cert: { from, names: from === "magpie" ? ["mac.local", "192.168.1.20"] : ["nas.home"], issuer: from === "magpie" ? "magpie CA" : "Test Root", until: "2027-11-10T00:00:00Z" }, + ...(from === "magpie" ? { ca: FP, caURLs: ["https://192.168.1.20:3425/magpie-ca.crt"] } : {}), + }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data, status = 200) => route.fulfill({ json: data, status }); + if (url.pathname === "/boot.js") return boot(route, lang); + 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" }, fx: s.fx }); + if (url.pathname === "/api/settings") return json(s); + if (url.pathname === "/api/settings/https" && route.request().method() === "GET") return json(h); + if (url.pathname.startsWith("/api/settings/https")) { + const body = route.request().postDataJSON(); + posts.push({ path: url.pathname, body }); + if (url.pathname === "/api/settings/https") { + if (over.farPage) return json({ error: FAR }, 400); + h = body.on ? served("magpie") : { on: false, served: false }; + } else if (url.pathname.endsWith("/import")) { + if (body.files.length < 2) return json({ error: NOKEY }, 400); + h = served("imported"); + } else if (url.pathname.endsWith("/remove")) { + h = served("magpie"); + } else if (url.pathname.endsWith("/ca")) { + return json({ ...h, saved: "~/Downloads/magpie-ca.crt" }); + } + return json(h); + } + if (url.pathname === "/api/copy") { posts.push({ path: url.pathname, body: route.request().postDataJSON() }); return json({}); } + 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({}); + await file(route, url); + }; +} + +const en = { + sub: "Other computers call magpie at https://; this computer can still use http://", + mine: "Your certificate", + signed: "Signed by magpie’s CA", + ca: "magpie’s CA", + node: "Claude Code and other Node apps", + far: "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on", + nokey: "A certificate but no private key: choose the key’s file too", +}; +const zh = { sub: "其他电脑通过 https:// 访问 magpie;本机仍可用 http://", ca: "magpie 的 CA" }; +const others = [ + "Already served over https:// by Require a client certificate or --tls-cert", + "Trust it once on each computer that calls magpie · SHA-256 {fp}", + "A private key but no certificate: choose the certificate’s file too", + "The private key belongs to none of the certificates", + "The private key has a passphrase: choose one without", + "No PEM certificate or key in the files chosen", +]; + +async function open(browser, lang, posts, over) { + const page = await (await browser.newContext({ viewport: { width: 390, height: 640 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts, over)); + await watchSettingsReads(page); + await page.goto("http://127.0.0.1:4999/?view=settings&tab=network"); + await settingsDrawn(page); + return { page, errors }; +} + +async function fits(box) { + const bad = await box.evaluate((b) => { + const out = []; + const right = b.getBoundingClientRect().right + 0.5; + for (const e of b.querySelectorAll(".row, button, .name, code")) { + const r = e.getBoundingClientRect(); + if (r.right > right || r.width === 0) out.push(e.className + " " + r.right + ">" + right); + if (e.matches("button, .name") && e.scrollWidth > e.clientWidth + 1) out.push("cut: " + e.textContent); + } + if (document.documentElement.scrollWidth > innerWidth) out.push("page scrolls sideways"); + return out; + }); + assert.deepEqual(bad, []); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": HTTPS in Settings (zhangly1 on X)", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + + await t.test("every language has the strings", async () => { + const { page } = await open(browser, "en", []); + for (const lang of ["zh", "zh-TW", "ja", "de"]) { + const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k] || I18N[lang][k] === k), + [lang, [...Object.values(en), ...others]]); + assert.deepEqual(missing, [], lang); + } + await page.context().close(); + }); + + await t.test("hidden while magpie answers only this computer", async () => { + const { page, errors } = await open(browser, "en", [], { settings: { lan: false, lanURLs: [] } }); + await page.locator("#lanList .row").first().waitFor(); + await page.waitForTimeout(200); + assert.equal(await page.locator("#httpsList .row").count(), 0); + assert.deepEqual(errors, []); + await page.context().close(); + }); + + for (const lang of ["en", "zh"]) { + await t.test(lang + ": on, the CA and its steps, import, remove, off", async () => { + const posts = []; + const { page, errors } = await open(browser, lang, posts); + const w = {}; + for (const [k, s] of Object.entries(en)) { + w[k] = await page.evaluate((s) => t(s), s); + if (lang !== "en") assert.notEqual(w[k], s, `"${s}" has no ${lang} translation`); + if (lang === "zh" && zh[k]) assert.equal(w[k], zh[k]); + } + const box = page.locator("#httpsList"); + const toggle = box.locator(".https-row"); + await toggle.waitFor(); + assert.equal((await toggle.locator(".name").textContent()).trim(), "HTTPS"); + assert.equal((await toggle.locator(".sub").textContent()).trim(), w.sub); + assert.equal(await box.locator(".https-cert").count(), 0, "no certificate row while off"); + await fits(box); + + const on = toggle.locator("button.opt").last(); + await reach(page, on); + await on.click(); + await box.locator(".https-ca").waitFor(); + assert.deepEqual(posts.at(-1), { path: "/api/settings/https", body: { on: true } }); + const certSub = (await box.locator(".https-cert .sub").textContent()).trim(); + assert.ok(certSub.startsWith(w.signed + " · mac.local, 192.168.1.20 · "), certSub); + assert.ok((await box.locator(".https-ca .sub").textContent()).includes("SHA-256 " + FP)); + const steps = await box.locator(".https-step").evaluateAll((rs) => rs.map((r) => [r.querySelector(".name").textContent, r.querySelector("code").textContent])); + assert.deepEqual(steps.map((s) => s[0]).slice(1), ["macOS", "Windows", "Linux", w.node]); + assert.equal(steps[0][1], "curl -kO https://192.168.1.20:3425/magpie-ca.crt"); + assert.match(steps[1][1], /add-trusted-cert .* magpie-ca\.crt$/); + assert.equal(steps[2][1], "certutil -addstore -f Root magpie-ca.crt"); + await fits(box); + + // Copy sends the command itself + const copy = box.locator(".https-step").nth(2).locator("button.copy"); + await reach(page, copy); + await copy.click(); + await page.waitForFunction(() => document.querySelector("#status")?.textContent); + assert.deepEqual(posts.at(-1), { path: "/api/copy", body: { text: "certutil -addstore -f Root magpie-ca.crt" } }); + + const save = box.locator(".https-ca button"); + await reach(page, save); + await save.click(); + const savedSays = await page.evaluate(() => t("Saved to {path}", { path: "~/Downloads/magpie-ca.crt" })); + await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), savedSays); + assert.deepEqual(posts.at(-1), { path: "/api/settings/https/ca", body: {} }); + + // a certificate without its key is refused, in the page's language + const input = box.locator(".https-cert input[type=file]"); + await input.setInputFiles([{ name: "cert.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("-----BEGIN CERTIFICATE-----\nAA==\n-----END CERTIFICATE-----\n") }]); + await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), w.nokey); + assert.equal(posts.at(-1).path, "/api/settings/https/import"); + await input.setInputFiles([ + { name: "cert.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("CERT") }, + { name: "key.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("KEY") }, + ]); + await box.locator(".https-cert .sub", { hasText: w.mine }).waitFor(); + assert.deepEqual(posts.at(-1), { path: "/api/settings/https/import", body: { files: ["CERT", "KEY"] } }); + assert.equal(await box.locator(".https-ca").count(), 0, "no CA row with the user's own certificate"); + const remove = box.locator(".https-cert button").last(); + await reach(page, remove); + await remove.click(); + await box.locator(".https-ca").waitFor(); + assert.deepEqual(posts.at(-1), { path: "/api/settings/https/remove", body: {} }); + + const off = box.locator(".https-row button.opt").first(); + await reach(page, off); + await off.click(); + await page.waitForFunction(() => !document.querySelector("#httpsList .https-cert")); + assert.deepEqual(posts.at(-1), { path: "/api/settings/https", body: { on: false } }); + const border = await box.locator(".row").first().evaluate((r) => getComputedStyle(r).borderLeftWidth); + assert(border === "0px" || border === "", "no left border accent: " + border); + assert.equal(await box.locator("select").count(), 0); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + + await t.test("a page on another computer is told why it can't, in its language", async () => { + const posts = []; + const { page, errors } = await open(browser, "zh", posts, { farPage: true }); + const toggle = page.locator("#httpsList .https-row"); + await toggle.waitFor(); + const on = toggle.locator("button.opt").last(); + await reach(page, on); + await on.click(); + const says = await page.evaluate((s) => t(s), en.far); + assert.notEqual(says, en.far); + await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), says); + await page.waitForFunction(() => document.querySelector("#httpsList .https-row .opt")?.classList.contains("on")); + assert.deepEqual(errors, []); + await page.context().close(); + }); + }); +} diff --git a/internal/mtls/mtls.go b/internal/mtls/mtls.go index 1084510ce..bfcce79b2 100644 --- a/internal/mtls/mtls.go +++ b/internal/mtls/mtls.go @@ -431,6 +431,9 @@ func pemOf(typ string, der []byte) []byte { return pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}) } +// WriteFile is writeFile, for the certificate Settings imports. +func WriteFile(path string, b []byte, mode os.FileMode) error { return writeFile(path, b, mode) } + // writeFile writes b to path through a temp file renamed over it, so a // reader never sees half of one. func writeFile(path string, b []byte, mode os.FileMode) error { diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 1b1110149..4094ba128 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -236,6 +236,13 @@ type Settings struct { // without a good certificate is refused. This computer's own // (KeepOwn), as LAN is. MTLS bool `json:"mtls,omitempty"` + // HTTPS serves the gateway and magpie web's page to other computers + // over https:// (zhangly1 on X: Claude on another computer on the LAN + // needed https), with the certificate imported in Settings (kept in + // /https) or else one magpie's own CA signs for this computer's + // names and addresses (gateway.ServedCert). This computer may still + // call plain http://. This computer's own (KeepOwn), as LAN is. + HTTPS bool `json:"https,omitempty"` // FetchPrivate are the private hosts and ranges (a name, name:port, an // IP or a CIDR range) magpie may download a URL from that it didn't // choose itself: an image or video a request names or a vendor answers @@ -1529,7 +1536,7 @@ func (s *Settings) KeepOwn(cur Settings) { s.NoWSLAgents = cur.NoWSLAgents s.QuotaReads = cur.QuotaReads s.NoAccountDiscovery = cur.NoAccountDiscovery - s.LAN, s.AllowIPs, s.MTLS = cur.LAN, cur.AllowIPs, cur.MTLS + s.LAN, s.AllowIPs, s.MTLS, s.HTTPS = cur.LAN, cur.AllowIPs, cur.MTLS, cur.HTTPS s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools s.FetchPrivate = cur.FetchPrivate s.SessionTerminal = cur.SessionTerminal @@ -2032,6 +2039,18 @@ func SetMTLS(on bool) error { return save(s, false) } +// SetHTTPS sets HTTPS alone, from what the file holds now. A settings +// file that can't be read is left as it is, with the error. +func SetHTTPS(on bool) error { + defer lockFile()() + s, err := loadChecked() + if err != nil { + return err + } + s.HTTPS = on + return save(s, false) +} + // SetQuitNoAsk sets QuitNoAsk alone, from what the file holds now (the // Quit question's "Don't ask again"). A settings file that can't be read // is left as it is, with the error. diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index cf374352d..4115b03c4 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -287,6 +287,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err in.CORSOrigins = cur.CORSOrigins // set on its own (cors) in.AllowIPs = cur.AllowIPs // set on its own (allowips) in.MTLS = cur.MTLS // set on its own (mtls) + in.HTTPS = cur.HTTPS // set on its own (https) in.FetchPrivate = cur.FetchPrivate // in settings.json only in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note) in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools)