Files
magpie/docs/subsystems/sync-backup.md
T
yetone ea3dee96a8 gateway: a URL magpie didn't choose is downloaded from public addresses only, wherever the request came from
5241de909 held an image URL a caller names to public addresses. This
carries the same guarantee to every URL magpie downloads that isn't its
own fixed vendor endpoint, and drops where the request came from as a
reason to reach a private address.

What is downloaded through the one restricted client now (every resolved
address checked and pinned, the dialled address checked again, each of up
to 5 redirects checked the same; loopback, RFC 1918, fc00::/7, link-local
with metadata, CGNAT, multicast, unspecified, documentation/reserved,
IPv4-mapped, NAT64/6to4/Teredo forms all refused):
- a caller's reference image (fetchPicture, draw.go), as before;
- web_fetch's page (search_fetch.go), as before;
- an image a vendor answers by URL, downloaded for a b64_json caller
  (draw.go) - was the gateway's unrestricted client;
- /v1/videos/{id}/content's video URL from the vendor's status
  (video.go) - was the gateway's unrestricted client;
- generate_image's own download of the gateway's image URL
  (internal/imagemcp) - was http.DefaultClient.
A vendor's answer can be steered by what the model is asked to do, so
its URLs are treated as a caller's.

Policy: a request from this computer gets nothing more. The exemption for
a loopback request that wasn't from a web page or through a forwarding
header (withPrivateFetch/privateFetchAllowed) is gone: a reverse proxy or
relay on the same host makes every request it carries arrive that way.
Two explicit allowances remain:
- settings.json "fetchPrivate" (settings.FetchPrivate): names, name:port,
  IPs and CIDR ranges the user lets magpie download from. None by
  default, no Settings page, per-machine (KeepOwn, kept across a GUI
  save). A settings.json that can't be read lets nothing extra in.
- for a vendor's URL only, the host:port of that provider's own
  configured endpoints (a LAN or local provider serving its own images).
The refusal says to send the image itself or name the host in
fetchPrivate. A vendor image that can't be downloaded is still answered
by its URL; a video is a 502.

Audited and left alone: kiro, codex_search, codex_backend and the
catalog/provider http.DefaultClient uses (fixed vendor endpoints);
remoteVideoURL (p.Do to the provider); the MCP proxy and mcpauth (URLs
the user configured); community plugins (only fixed vendor endpoints,
nothing a request names).

Docs: docs/subsystems/gateway-routing.md (the guard paragraph, web_fetch,
test command), docs/subsystems/sync-backup.md (FetchPrivate stays on
each computer).

Tests (new or rewritten): TestEditImageURLFromThisComputer (loopback,
[::1], and loopback with X-Forwarded-For as a same-host reverse proxy:
400 naming fetchPrivate, the private server never asked; with
fetchPrivate ["127.0.0.1"] it is fetched, a non-image still refused),
TestFetchPrivateEntries, TestVendorImageURLAtPrivateAddressNotFetched
(127.0.0.1, a name resolving to it, ::ffff:127.0.0.1; the vendor's own
host:port still fetched), TestVideoContentAtPrivateAddressNotFetched,
imagemcp TestVendorImageAtPrivateAddressNotFetched. gui's
TestSettingsSaveKeepsWhatItDoesNotSend sets FetchPrivate. The two imagemcp
download tests and TestImageByURLIsFetchedForB64Caller now name their
local file server in fetchPrivate / resolve files.test to a public
address.

Broken by hand, each red, restored:
- draw.go inline fetch on s.client -> TestVendorImageURLAtPrivateAddressNotFetched red
- video.go on s.client -> TestVideoContentAtPrivateAddressNotFetched red
- imagemcp on http.DefaultClient -> its TestVendorImageAtPrivateAddressNotFetched red
- fetchPicture unrestricted (the old local bypass) -> TestEditImageURLFromThisComputer red
- fetchPrivate ignored -> TestEditImageURLFromThisComputer, TestFetchPrivateEntries red
Not distinguished: settings.Load in place of LoadChecked passes too (an
unparsable file with no last good generation gives no list either way).
Not tried: a real reverse proxy (nginx/caddy) in front of a running
magpie; the X-Forwarded-For loopback request stands in for it. Not tried
against a real vendor's image or video URL.

gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows clean.
Full suite: go test -tags nogui -timeout 45m ./... at 8b84dc902 plus this
change: every package ok except agent and gateway (timed out at 45m at
load average ~370, no test failed before the timeout) and gui
(TestSettingsSaveKeepsWhatItDoesNotSend, fixed here by adding
FetchPrivate; TestSetAnswersWhileDevinAndProvidersHang 12.4s under load,
(4726s) with -timeout 150m at load ~220.

Rebased onto ba132d68b (17 commits; only the doc test line conflicted).
At the rebased head: gofmt clean, vet darwin/linux/windows clean, and
the Image/Draw/Video/Fetch/Edit/Private/Public tests in gateway, imagemcp,
gui and settings ok.
2026-10-16 20:12:05 +08:00

8.1 KiB

Sync and backup

internal/backup collects magpie's portable setup into a passphrase-sealed bundle. internal/davsync keeps that bundle in a WebDAV folder, an S3 bucket or a GitHub repository. It merges changes between computers; it does not clone a working tree or synchronize arbitrary files.

Sources of truth

  • Config, Configure, Status and syncOnce keep the active server in sync.json, and the last local/remote hashes, versions, notices and undo file in sync-state.json. These files live beside magpie's settings. Secrets are local, never in the status response.
  • The remote interface reads a version and conditionally replaces it. WebDAV and S3 use ETags; GitHub uses the blob SHA required by its Contents API. github.go interprets github://owner/repo[/prefix], with Config.Branch selecting a branch or using the repository's default.
  • backup.go owns bundle contents and sealing. Sync divides the setup into providers, settings, profiles, agents and library. Provider keys, agent models, library and usage have their own inclusion switches.
  • usage.go shares separately sealed usage and quota files through a remote's files interface.
  • restore.go replaces local parts from the remote bundle, first keeping the local setup for Undo.
  • backup.go, the Settings form in app.js and 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 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 private hosts magpie may download from (FetchPrivate), 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 longer interval or manual sync only. Saving in Settings syncs immediately. Each operation holds the sync lock, so configuration changes cannot race a sync's state write.

A first computer creates a remote backup. Another computer joining takes the remote setup and keeps displaced local parts in its sync folder. Subsequent syncs compare each part with the hashes from the previous sync: local-only changes go up, remote-only changes come down, and a part changed on both sides keeps the newer version while retaining the replaced copy. A conditional write refused because another computer committed in between is retried through this same merge.

When a remote file is empty, damaged or another app's format, sync stops and describes it through ServerFile. Settings and the backend's upload command can replace it with this computer's setup, keeping the old file first. HTML and XML are not offered for replacement. GitHub diagnostics name the repository and magpie github upload, rather than WebDAV's recovery path.

A local file that is there but can't be read is unknown, never empty or the defaults. backup.Collect stops on an unreadable providers.json (with its groups and order), settings.json (settings.LoadChecked: unreadable, or not parsing with no good .bak) or library.json, and on a gateway key store that fails to export. A backup, an export and a sync all end with that error, nothing sealed or pushed; the sync's status shows it. A missing or empty settings.json is still none (TestCollectStopsOnUnreadableSettings, TestSyncStopsOnUnreadableProviders, TestSyncStopsOnUnreadableSettings, #2269).

Switching services keeps all inactive kinds in Config.Servers. Other remains the most recently left server for compatibility with older saved configurations and clients. Only the active server is used. Empty credential fields reuse a saved credential only for its matching account; GitHub restricts reuse to the same owner/repo. Branch or prefix changes within that repository can keep the token. The branch is part of the sync state key.

GitHub constraints and errors

  • The repository must exist and be private: prepare refuses one whose repository read doesn't say "private": true, since a public history hands every sealed version to anyone to guess the passphrase against (TestGitHubPublicRepositoryRefused). In an empty repository, the first encrypted backup initializes its default branch through the Contents API. A selected branch other than the default must already exist. The token needs repository Contents read and write.
  • Backups are <prefix>/magpie/magpie.magpie-backup; optional usage files live beside them under usage/. Changes create commits, and unchanged setup does not create another backup commit.
  • Tokens are separate from the library's GitHub token, sent only to https://api.github.com, and must differ from the encryption passphrase. Repository history retains older encrypted versions.
  • Repository and branch access is checked before a file's 404 can mean "no backup yet." Failed reads and malformed metadata fail sync.
  • Only the ref endpoint's explicit 409: Git Repository is empty. allows initialization, after repository access and the default branch are checked. The initial write omits branch so GitHub creates its default branch; other conflicts and missing branches are not treated as an empty repository.
  • Large files are downloaded by blob SHA, preserving the version that was read. Sync files are limited to 64 MiB. Usage listing fails at the Contents API's 1,000-file limit rather than treating a truncated list as complete.
  • A stale SHA or a racing initial creation returns errChanged. Other 422 responses stay actionable errors. Authentication, permission and branch failures remain distinct from missing files. Rate limits use sync backoff.
  • Request archival remains an S3-only feature; its objects are separate from the encrypted setup and usage files.

Verification

go test -tags nogui ./internal/davsync
go test -tags nogui ./internal/cli -run 'TestGitHubCmd|TestWebdavCmd|TestS3Cmd'
node --test internal/gui/tests/github-sync.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/sync-other-kind.test.cjs

TestGitHubEmptyRepository covers the first encrypted backup initializing an empty repository and an unchanged second sync. TestGitHubEmptyRepositoryFailures covers missing branches, unrelated ref conflicts and another computer winning the initial write. TestGitHubNotBackup covers backend-specific recovery advice when the repository holds an empty or foreign file.

Go tests use testenv homes and HTTP fixtures. Browser tests use isolated API fixtures in Chromium and WebKit. A live GitHub write requires a test repository and token; fixture tests do not establish that a particular account's permissions or repository rules allow commits.