From 758a4084ee9b2e8a08dcebf8110942029b094e49 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 12:11:11 +0800 Subject: [PATCH] sync: LAN sharing stays as each computer has it, so turning it on at home no longer turns it on at work (Lullaby on Discord) Settings.KeepOwn now keeps LAN (sharing on the local network), AllowIPs (the addresses let in to it) and SessionTerminal (the Mac app a session resumes in) from this computer whenever a sync, a join, a Restore, an Undo or a backup file brings settings in. davsync's hashes blanks the same fields, so flipping sharing is no change to push. A backup restored onto a new computer leaves sharing off there: it opens the gateway to the network, so it is turned on by hand, like the port and proxy. The default sharing key is not per computer. It lives in the gateway-key store, which rides the settings part with LANKey and LANKeyID, so every computer holds the same key, and a second computer turning sharing on takes up that key instead of making another one (configureLAN finds it by LANKeyID or k.LAN). Audit of Settings, what stays synced and why: - already own: Window/WindowMaximised, UIFont/CodeFont, Proxy, Port, Dock/DockWindow, Lightweight, KeepAwake/KeepAwakeDisplay, Tray*, GatewayMode, NoWSLAgents, QuotaReads, NoAccountDiscovery, GatewayConversations. - made own now: LAN, AllowIPs (the address list belongs to the network this computer is on), SessionTerminal (another Mac may not have the app). - not in Settings: launch at login (internal/autostart, the OS's own setting) and the listen address (MAGPIE_ADDR, plus Port). Remote access through Tailscale etc. goes through those. - still synced: CORSOrigins (pages and extensions the user uses, and each still needs a gateway key), OTel, Redact*, update settings (NoAutoUpdate, AutoRestart, UpdateMirror, ChinaMirror), alerts, model and agent choices, Theme/Lang/TextSize. These are the user's preferences, not facts about one machine. Older magpie versions still take LAN from the bundle. Only new clients ignore it. Docs: sync-backup.md gets a "What stays on each computer" section, and gateway-routing.md says AllowIPs is per computer. README and site docs don't list what sync carries, and no GUI string does either, so they are unchanged. Run, on origin/main 95e7c6bcc + this change: - gofmt -l internal/settings internal/davsync: nothing printed - GOOS=darwin/linux/windows go vet -tags nogui on settings, davsync, backup, access, gui: exit 0 each - go test -tags nogui settings, davsync, backup, access, gui: all ok - before the rebase, on 226222118: go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: all ok Full suite: SUITE_LINE Broken by hand: with the three KeepOwn lines removed, TestLANSharingStaysOnItsComputer fails ("work after joining: sharing on the local network is true, want false", the same after a restore, "turning sharing off at home pushed 1 times", "home after work turned sharing on: ... true, want false", plus the AllowIPs and SessionTerminal ones), and TestLANSharingIsNoChange fails ("sharing on the local network changes the settings part's hash"). With LAN alone dropped from KeepOwn, the LAN checks and the hash test fail and the others pass. Restoring the change turns both green. Not tried: two real computers syncing through a real WebDAV, S3 or GitHub folder. The test uses two sandbox homes and a fake WebDAV server. --- docs/subsystems/gateway-routing.md | 2 +- docs/subsystems/sync-backup.md | 24 +++++ internal/davsync/lan_own_test.go | 168 +++++++++++++++++++++++++++++ internal/settings/settings.go | 23 +++- 4 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 internal/davsync/lan_own_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index bd707494d..12d1a5bbd 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -28,7 +28,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 token, then by User-Agent. 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) | | 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) | -| 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), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/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`, 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 GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. 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. 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; `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`; 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`). 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), [`internal/settings/origins.go`](../../internal/settings/origins.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), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/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`, 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 GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. 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. 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; `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`). 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), [`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, 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), 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 several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: 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, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. 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) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight`. `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 10b1a5804..53d2f8394 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -28,6 +28,30 @@ clone a working tree or synchronize arbitrary files. [`app.js`](../../internal/gui/assets/app.js) and [`webdav_cli.go`](../../webdav_cli.go) reach the same sync operations. +## What stays on each computer + +The settings part carries the user's preferences, but not what is only about +one computer. [`Settings.KeepOwn`](../../internal/settings/settings.go) puts +those back from this computer's settings whenever a sync, a join, a Restore, +an Undo or a backup file brings settings in, and `hashes` blanks them, so +changing one is no change to push. They are: the window's size and whether it +was maximised, the fonts, the proxy, the gateway's port, sharing on the local +network (`LAN`) and the addresses let in to it (`AllowIPs`), the Dock, gateway +mode, keeping awake, lightweight windows, WSL lookups, account discovery, when +allowances are read, recording gateway conversations, the Mac terminal a +session resumes in (`SessionTerminal`) and what the menu bar shows. Launch at +login is the system's own setting (`internal/autostart`) and the listen +address is `MAGPIE_ADDR`, so neither is in a bundle. + +Sharing turned on at one computer never turns it on or off at another +(Lullaby on Discord). A backup restored onto a new computer leaves sharing as +that computer has it, off on a fresh one: sharing opens the gateway to the +network, and the user turns it on there by hand, as the port and proxy are +set there. The default sharing key is different: it is in the gateway-key +store, which rides the settings part with `LANKey` and `LANKeyID`, so every +computer holds the same one, and sharing turned on at a second computer takes +it up rather than making another (`TestLANSharingStaysOnItsComputer`). + ## Runtime and state The gateway runs sync every three minutes by default. `SetAuto` can select a diff --git a/internal/davsync/lan_own_test.go b/internal/davsync/lan_own_test.go new file mode 100644 index 000000000..516de60c2 --- /dev/null +++ b/internal/davsync/lan_own_test.go @@ -0,0 +1,168 @@ +package davsync + +import ( + "context" + "net/http/httptest" + "slices" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// Sharing the gateway on the local network is this computer's own (Lullaby +// on Discord: turned on at home, it came on at work too). Two computers in +// one folder, sharing on at one and off at the other, each keep their own +// through syncs both ways, a join and a Restore; flipping it is no change +// to push; the default key still follows the folder, so the other computer +// turning sharing on takes up the same key. The addresses let in and the +// terminal a session resumes in are this computer's too. +func TestLANSharingStaysOnItsComputer(t *testing.T) { + fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}, cond: true, putETag: true} + srv := httptest.NewServer(fake) + defer srv.Close() + cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "lan sharing fixture passphrase", Keys: true} + home, work := newComputer(t), newComputer(t) + use := func(c computer) { + t.Helper() + c.use(t) + appdir.UseExecutable("") + provider.ForgetAccounts() + } + t.Cleanup(provider.ForgetAccounts) + now := func() { + t.Helper() + if err := Now(context.Background()); err != nil { + t.Fatal(err) + } + } + puts := func() int { + fake.mu.Lock() + defer fake.mu.Unlock() + return fake.puts + } + edit := func(f func(*settings.Settings)) { + t.Helper() + s := settings.Load() + f(&s) + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + } + want := func(where string, lan bool, allow []string, term string) { + t.Helper() + s := settings.Load() + if s.LAN != lan { + t.Errorf("%s: sharing on the local network is %v, want %v (this computer's own)", where, s.LAN, lan) + } + if !slices.Equal(s.AllowIPs, allow) { + t.Errorf("%s: addresses let in are %v, want %v (this computer's own)", where, s.AllowIPs, allow) + } + if s.SessionTerminal != term { + t.Errorf("%s: session terminal is %q, want %q (this computer's own)", where, s.SessionTerminal, term) + } + } + + // Home shares the gateway, on its own network, and syncs first. + use(home) + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + homeKey := access.LANSecret() + if homeKey == "" { + t.Fatal("fixture: sharing on made no default key") + } + edit(func(s *settings.Settings) { + s.Theme = "dark" + s.AllowIPs = []string{"192.168.1.0/24"} + s.SessionTerminal = "com.googlecode.iterm2" + }) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + now() + + // Work, sharing off, joins: home's theme comes in, home's sharing + // doesn't. + use(work) + edit(func(s *settings.Settings) { s.AllowIPs = []string{"10.0.0.0/8"} }) + if err := Configure(cfg); err != nil { + t.Fatal(err) + } + now() + if s := settings.Load(); s.Theme != "dark" { + t.Fatalf("fixture: the join brought no settings in (theme %q)", s.Theme) + } + want("work after joining", false, []string{"10.0.0.0/8"}, "") + if access.LANSecret() != "" { + t.Error("work after joining: the gateway is shared with a key") + } + // a Restore of the folder's setup leaves it as it is too + edit(func(s *settings.Settings) { s.Theme = "light" }) + if _, err := Restore(context.Background()); err != nil { + t.Fatal(err) + } + if s := settings.Load(); s.Theme != "dark" { + t.Fatalf("fixture: the restore brought no settings in (theme %q)", s.Theme) + } + want("work after a restore", false, []string{"10.0.0.0/8"}, "") + + // Work changes a synced setting: it goes up, with work's sharing off, + // and home takes it in still sharing. + edit(func(s *settings.Settings) { s.Theme = "light" }) + now() + use(home) + now() + if s := settings.Load(); s.Theme != "light" { + t.Fatalf("fixture: home didn't take work's change in (theme %q)", s.Theme) + } + want("home after work's push", true, []string{"192.168.1.0/24"}, "com.googlecode.iterm2") + if got := access.LANSecret(); got != homeKey { + t.Errorf("home after work's push: shared with %q, want its key", got) + } + + // Home turning sharing off is no change to push. + before := puts() + if err := access.ConfigureLAN(false, false); err != nil { + t.Fatal(err) + } + now() + if n := puts() - before; n != 0 { + t.Errorf("turning sharing off at home pushed %d times", n) + } + + // Work turns sharing on: with the folder's default key, and home stays + // off through syncs both ways. + use(work) + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + if got := access.LANSecret(); got != homeKey { + t.Errorf("work shares with %q, want the folder's default key", got) + } + edit(func(s *settings.Settings) { s.Theme = "system" }) + now() + use(home) + now() + if s := settings.Load(); s.Theme != "system" { + t.Fatalf("fixture: home didn't take work's change in (theme %q)", s.Theme) + } + want("home after work turned sharing on", false, []string{"192.168.1.0/24"}, "com.googlecode.iterm2") + use(work) + now() + want("work after syncing again", true, []string{"10.0.0.0/8"}, "") +} + +// The settings part's hash, which tells a change to push, doesn't see +// sharing, the addresses let in or the terminal. +func TestLANSharingIsNoChange(t *testing.T) { + a := settings.Settings{Theme: "dark"} + b := a + b.LAN, b.AllowIPs, b.SessionTerminal = true, []string{"10.0.0.0/8"}, "com.googlecode.iterm2" + if hashes(backup.Bundle{Settings: &a})["settings"] != hashes(backup.Bundle{Settings: &b})["settings"] { + t.Error("sharing on the local network changes the settings part's hash") + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 6fb20bf02..9e08918b9 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -44,7 +44,8 @@ type Settings struct { Lang string `json:"lang,omitempty"` // system | en | zh Tray string `json:"tray,omitempty"` // what clicking the tray icon opens: panel | window // SessionTerminal is the Mac app that opens a resumed session, by bundle - // id. "" and "system" follow the .command file association. + // id. "" and "system" follow the .command file association. This + // computer's own (KeepOwn): another Mac may not have that app. SessionTerminal string `json:"sessionTerminal,omitempty"` // Currency is what a cost — the Usage page's, the tray panel's, the // TUI's and the CLI's — is shown converted to: usd (its native @@ -94,6 +95,11 @@ type Settings struct { RedactRules []redact.Rule `json:"redactRules,omitempty"` // LAN shares the gateway on the local network; remote callers must use // named caller keys. LANKey is retained for older Magpie versions. + // LAN is this computer's own (KeepOwn; Lullaby on Discord: sharing + // turned on at home came on at work too). LANKey and LANKeyID name the + // default key, which rides the synced gateway-key store, so they follow + // the folder: turned on on another computer, sharing there takes up the + // same key. LAN bool `json:"lan,omitempty"` LANKey string `json:"lanKey,omitempty"` // CORSOrigins are the web pages (scheme://host[:port]) and browser @@ -108,7 +114,8 @@ type Settings struct { // reach the gateway from at all (lc on Discord); any other is refused // 403 even with a gateway key. None: every address, as before. This // computer is always let in. MAGPIE_ALLOW_IPS, where set, is used in - // its place (gateway.AllowIPs). + // its place (gateway.AllowIPs). This computer's own (KeepOwn), as LAN + // is: the addresses are of the network this computer is on. AllowIPs []string `json:"allowIPs,omitempty"` // Port is the gateway's port on this computer, 0 for DefaultPort. // MAGPIE_ADDR, where it is set, comes first (GatewayAddr). @@ -900,9 +907,13 @@ func (s Settings) Compact() int { // KeepOwn puts back cur's settings that are this computer's own, which a // sync or a restored backup never brings from another: the window's size -// and whether it was maximised, the proxy, the gateway's port, the Dock, gateway mode, whether WSL is looked in, whether agents' sign-ins are read, when allowances are read, and what the menu bar or tray shows beside magpie's -// icon (yoooo on Discord: usage turned off on a Mac came back from a -// Windows box that shows it). +// and whether it was maximised, the proxy, the gateway's port, whether it +// is shared on the local network and the addresses let in to it, the +// Dock, gateway mode, whether WSL is looked in, whether agents' sign-ins +// are read, when allowances are read, the terminal app a session resumes +// in, and what the menu bar or tray shows beside magpie's icon (yoooo on +// Discord: usage turned off on a Mac came back from a Windows box that +// shows it; Lullaby: sharing turned on at home came on at work). func (s *Settings) KeepOwn(cur Settings) { s.GatewayConversations = cur.GatewayConversations s.UIFont, s.CodeFont = cur.UIFont, cur.CodeFont @@ -913,6 +924,8 @@ func (s *Settings) KeepOwn(cur Settings) { s.NoWSLAgents = cur.NoWSLAgents s.QuotaReads = cur.QuotaReads s.NoAccountDiscovery = cur.NoAccountDiscovery + s.LAN, s.AllowIPs = cur.LAN, cur.AllowIPs + s.SessionTerminal = cur.SessionTerminal } // RenamePerModel moves what the user said of a provider's models to the id