qianxunji (#feedback) and curtinp118 on Discord: a VPS restored from a backup, or a new computer joining sync, had to sign in to every subscription again. Sign-ins (subscription accounts in logins.json, Codex's auth.json, plugins' sign-ins in plugin-auth.json) can now go too, in each place only when picked; all are off by default, so an upgrade carries nothing new. - Sync (WebDAV, S3, GitHub): a "Sign-ins" tick in the form, with a line saying anyone with the passphrase and the server's file can use the accounts, and that an account on two computers can be signed out on one when the other renews it. CLI: `magpie webdav|s3|github set sign-ins=yes`. - Export: "With the sign-ins", off; ticked, the passphrase hint says the file holds them. CLI: `magpie backup --sign-ins`. - Import: "Bring in the sign-ins too, when the file has them", on. CLI: `magpie restore --no-sign-ins` leaves them out. - Back up by itself: "Sign-ins in backups", Off/On. On asks for a passphrase (twice) that seals the sign-ins alone (the rest of an automatic backup stays unsealed, as before); it is kept in autobackup.json (0600), never sent in the view. A backup whose sign-ins another passphrase sealed restores without them and says so. What goes (provider.CollectSignIns, plugin.CarriedAuth): magpie's own copies only, not an agent's own account, an agent-home row, a hidden or plugin: row, or a retired built-in. Each record is keyed by agent + email + org (or the account key); ids two rows share go on neither side. Restore/import (RestoreSignIns) adds what is missing and updates only when the incoming copy was renewed later; nothing here is removed. Before writing over a row it counts every row that could be the same account (same login, same refresh token, same id): none adds, several keeps all, one is kept when it isn't magpie's own copy, is held, or is the agent's live account. Codex's auth.json is written temp-and-rename, 0600, only where Codex is signed out. Sync merges per record against the last sync's hashes (MergeSignIns): the later renewal wins; a removal crosses only when the other side still had it as of the last sync; ApplySignIns re-checks each row's hash before writing so a renewal in between is kept. A computer with the tick off sends none, so others remove nothing for it; turning it off, a Restore, or a replaced server file clears the last-sync record. Export's and Import's forms moved out of app.js into syncfiles.js, imported when one opens (as autobackup.js is), so the core is 3.2KB under its budget with no raise (app.js 3.2KB smaller than before). docs/subsystems/sync-backup.md has a "Sign-ins, when picked" section; subscription_signin_test.go's header now says it pins the default. Run at the pushed head (678d28cba on origin/mainbc10a6198): - wsl-run go test -tags nogui -timeout 45m: backup, davsync, plugin, gui ok (TestCoreScriptBudget in it). provider: one red, TestCancelledPluginSignInSavesNothing, the late sign-in saved after Cancel. It is green 20 of 20 alone, at this head and at origin/main alike, and this change adds only new files there whose tests run after it; filed as #5047. cli there hung in proc.lookStamp's os.Stat on WSL at load 100, so it ran again on mote: one red, TestEveryRouteHasACommandOrIsNamed (GET /api/context/reply, #5026), the same at origin/main. gateway -run TestCompactionOverByteCapEveryTime ok (#4862 on mote's full run). TestMainWindowCorners on mote: red the same at origin/main (#3949). - GUI, on mote: the 16 files that open Sync, plus i18n-keys and old-webkit, Chromium and WebKit, every language: 255 of 294 pass. The 39 reds are segs-press-redraw's searchAllRow (#4566), s3-sync in WebKit (#2448) and usage-agents-hide (#3414). The same files at origin/mainbc10a6198give the same 39 pass and 39 fail. sync-signins, auto-backup, sync-sign-in, i18n-keys and old-webkit alone on WSL: 92/92. - The whole GUI suite on WSL, stopped at 737 of its tests (1162 files, load ~100 there): 9 reds, all WebKit, none in a Sync file: account-eye (#4244, #5052), add-button (#4792), account-plugin-user and agent-expand-steady. The last two pass at this head and at origin/main on mote. The rest of the suite was not run. - gofmt -l: clean. go vet: darwin (internal/gui, internal/cli), GOOS=linux and GOOS=windows -tags nogui for backup, davsync, provider, plugin, cli, gui: ok. - win-run and wsl-run: go test -tags nogui -run 'SignIns|Carries|AutoBackupSignIns' ./internal/provider ./internal/backup ./internal/davsync: ok on Windows 11 and Ubuntu 24.04. - sync-signins.test.cjs: 20/20, Chromium and WebKit, 1100 and 420px, en/zh/zh-TW/ja/de, no horizontal overflow, no page errors. Then rebased on origin/main5ee5274bd(12 commits; davsync.go, app.js and i18n.js merged with no conflict) and run again at the pushed head on mote: gofmt clean; go test -run 'TestCoreScriptBudget|SignIns|Carries| AutoBackup|Sync' for gui, davsync, backup and provider: ok; sync-signins, auto-backup, sync-sign-in, i18n-keys, old-webkit: 92/92. Broken by hand, each red, then restored: - RestoreSignIns writing an older token over a newer one: TestRestoreSignInsNeverWritesAnOlderTokenOver red. - The ambiguous-account guard has two layers (more than one match, and a single match with another record id); with only the first removed the test stayed green, with both removed TestRestoreSignInsLeavesAnAmbiguousAccount went red. - MergeSignIns removing a row renewed here: TestMergeSignInsRemovedOnlyWhenTheOtherSideRemovedIt red. - Codex auth.json written over a signed-in Codex: TestRestoreSignInsSignsCodexInOnlyWhereSignedOut red. - ApplySignIns not re-checking the hash: TestApplySignInsKeepsWhatChangedSinceTheMerge red. - davsync forgetting the last-sync record (st.SignIns = nil): TestSyncSignIns red. - GUI: Export's tick on by default, and auto backup's On posting with no passphrase: sync-signins.test.cjs red for each. Not tried: real accounts carried to a real VPS or second computer (all Go tests use testenv homes, fake DAV and fake tokens; the Keychain is never reached); a real vendor's refresh after a carried sign-in, and how each vendor treats one refresh token used from two machines; the CLI flags against a sandbox HOME (covered by the cli package's tests only); auto backup's sign-ins have no CLI switch.
300 lines
8.9 KiB
Go
300 lines
8.9 KiB
Go
package davsync
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// ErrOff is a Restore, Undo or SetAuto asked for with sync off.
|
|
var ErrOff = errors.New("sync is off")
|
|
|
|
// SetAuto sets how many minutes apart the gateway's magpie syncs by
|
|
// itself, one of AutoChoices; Manual: never, only when asked (#847).
|
|
func SetAuto(minutes int) error {
|
|
if !slices.Contains(AutoChoices, minutes) {
|
|
return fmt.Errorf("sync by itself every 3, 15, 30 or 60 minutes, or never, not %d", minutes)
|
|
}
|
|
return locked(func() error {
|
|
c, ok := Load()
|
|
if !ok {
|
|
return ErrOff
|
|
}
|
|
c.AutoEvery = minutes
|
|
if minutes == int(Every/time.Minute) {
|
|
c.AutoEvery = 0
|
|
}
|
|
b, err := json.MarshalIndent(c, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := edit.WriteAtomic(path("sync.json"), b); err != nil {
|
|
return err
|
|
}
|
|
return os.Chmod(path("sync.json"), 0o600)
|
|
})
|
|
}
|
|
|
|
// Restore makes this computer's setup the server's, whatever changed here:
|
|
// each part synced that differs is brought in, as a sync brings in a part
|
|
// changed only there. What was here first is sealed into the sync folder,
|
|
// with the API keys, and Undo brings it back. It is the parts brought in.
|
|
func Restore(ctx context.Context) ([]string, error) {
|
|
var brought []string
|
|
err := locked(func() error {
|
|
c, ok := Load()
|
|
if !ok {
|
|
return ErrOff
|
|
}
|
|
d, err := newRemote(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data, ver, err := d.get(ctx, version{}) // the file as it is now, never the cached copy
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if data == nil {
|
|
return errors.New("there is no magpie setup on the server yet: nothing to restore")
|
|
}
|
|
remote, err := backup.Open(data, c.Passphrase)
|
|
if errors.Is(err, backup.ErrPassphrase) {
|
|
return errors.New("the passphrase doesn't open the file on the server: it was sealed with another one; use the passphrase set on your other computers")
|
|
}
|
|
if err != nil {
|
|
return described(c, data, err)
|
|
}
|
|
local, err := collect(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
here := withHere(nil, hereOf(c, local)) // an agent's picks kept here are no change
|
|
L, R := hashesOwn(local, here), hashesOwn(remote, here)
|
|
for _, p := range Parts {
|
|
if L[p] == R[p] || !c.syncs(p) || (p == "library" && remote.Library == nil) {
|
|
continue
|
|
}
|
|
brought = append(brought, p)
|
|
}
|
|
st := loadState()
|
|
if st.Key != stateKey(c) {
|
|
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Here: st.Here}
|
|
}
|
|
if len(brought) > 0 {
|
|
kept, err := keepHere(c)
|
|
if err != nil {
|
|
return fmt.Errorf("keeping this computer's setup before restoring: %w", err)
|
|
}
|
|
for _, p := range brought {
|
|
if p == "agents" {
|
|
// the server's whole, the fields kept here too: they
|
|
// follow the others again, as Follow leaves them
|
|
got, err := bringAgents(remote.Agents, here)
|
|
broughtIn(&st, got)
|
|
st.Own, st.Follow = nil, false
|
|
if err != nil {
|
|
return fmt.Errorf("bringing in the %s: %w", p, err)
|
|
}
|
|
continue
|
|
}
|
|
if err := bring(remote, p); err != nil {
|
|
return fmt.Errorf("bringing in the %s: %w", p, err)
|
|
}
|
|
}
|
|
if local, err = collect(c); err != nil {
|
|
return err
|
|
}
|
|
st.Undo = kept
|
|
st.Notice = &Notice{At: time.Now(), Here: brought, Saved: filepath.Dir(kept), Restored: true}
|
|
}
|
|
// the server's sign-ins, when they go: put in as a backup's are,
|
|
// nothing renewed later here written over
|
|
if c.SignIns && remote.SignIns != nil {
|
|
if _, err := provider.RestoreSignIns(remote.SignIns); err != nil {
|
|
return fmt.Errorf("bringing in the sign-ins: %w", err)
|
|
}
|
|
if local, err = collect(c); err != nil {
|
|
return err
|
|
}
|
|
st.SignIns = nil
|
|
}
|
|
// as a sync that brought them in leaves it: the next one has
|
|
// nothing to push back
|
|
st.Here = hereOf(c, local)
|
|
own := withHere(st.Own, st.Here)
|
|
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, own), hashesOwn(remote, own), sum(data), ver
|
|
st.Blind = nil // what is here now is what the server has
|
|
remember(data)
|
|
st.Last, st.Error = time.Now(), ""
|
|
saveState(st)
|
|
return nil
|
|
})
|
|
return brought, err
|
|
}
|
|
|
|
// Upload writes this computer's setup over the server's file when that
|
|
// file isn't a backup a sync can read — empty, cut short, another app's —
|
|
// so a sync stopped on it has a way on that the user chooses. A file that
|
|
// opens as a backup, one sealed with another passphrase, a newer magpie's,
|
|
// and a page the server answered with instead of a file are never written
|
|
// over. What the server held is kept in the sync folder first, and nothing
|
|
// is written when it can't be. The write is made over the version read, so
|
|
// a file another computer wrote meanwhile isn't.
|
|
func Upload(ctx context.Context) error {
|
|
return locked(func() error {
|
|
c, ok := Load()
|
|
if !ok {
|
|
return ErrOff
|
|
}
|
|
d, err := newRemote(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data, ver, err := d.get(ctx, version{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if data != nil {
|
|
_, err := backup.Open(data, c.Passphrase)
|
|
switch {
|
|
case err == nil:
|
|
return errors.New("the file on the server is a magpie backup this computer can open: Sync now merges with it instead, and nothing was written over it")
|
|
case errors.Is(err, backup.ErrPassphrase):
|
|
return errors.New("the file on the server is a magpie backup sealed with another passphrase, so it wasn't written over: use the passphrase set on your other computers")
|
|
}
|
|
err = described(c, data, err)
|
|
var nb *notBackup
|
|
if !errors.As(err, &nb) || !nb.f.Replace {
|
|
return err
|
|
}
|
|
if len(data) > 0 {
|
|
if err := keepAside(data, "server-replaced", 5); err != nil {
|
|
return fmt.Errorf("keeping the server's file before writing over it, so nothing was written: %w", err)
|
|
}
|
|
}
|
|
}
|
|
local, err := collect(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b := local
|
|
b.Created, b.App = time.Now().UTC(), "magpie"
|
|
sealed, err := backup.Seal(b, c.Passphrase)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
v, err := d.put(ctx, sealed, ver.ETag)
|
|
if errors.Is(err, errChanged) {
|
|
return errors.New("the file on the server changed while it was being replaced, so it wasn't: sync now to see what it is")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
st := loadState()
|
|
if st.Key != stateKey(c) {
|
|
st = state{Key: stateKey(c), Brought: st.Brought, Replaced: st.Replaced, Own: st.Own, Here: st.Here}
|
|
}
|
|
// as the first sync to an empty server leaves it
|
|
st.Here = hereOf(c, local)
|
|
own := withHere(st.Own, st.Here)
|
|
st.Local, st.Remote, st.Sum, st.Server = hashesOwn(local, own), hashesOwn(b, own), sum(sealed), v
|
|
st.Blind = nil // it replaced what wasn't a backup: nothing to merge again
|
|
remember(sealed)
|
|
st.Last, st.Error, st.File = time.Now(), "", nil
|
|
saveState(st)
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// Undo puts back the setup the last Restore replaced. The next sync takes
|
|
// it to the server, as any change made here.
|
|
func Undo() ([]string, error) {
|
|
var back []string
|
|
err := locked(func() error {
|
|
c, ok := Load()
|
|
if !ok {
|
|
return ErrOff
|
|
}
|
|
st := loadState()
|
|
if st.Key != stateKey(c) || st.Undo == "" {
|
|
return errors.New("there is no restore to undo")
|
|
}
|
|
data, err := os.ReadFile(st.Undo)
|
|
if err != nil {
|
|
return fmt.Errorf("the copy kept before the restore is gone: %w", err)
|
|
}
|
|
kept, err := backup.Open(data, c.Passphrase)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
local, err := collect(withKeys(c))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
L, K := hashes(local), hashes(kept)
|
|
for _, p := range Parts {
|
|
if L[p] == K[p] || !c.syncs(p) || (p == "library" && kept.Library == nil) {
|
|
continue
|
|
}
|
|
if err := bring(kept, p); err != nil {
|
|
return fmt.Errorf("bringing back the %s: %w", p, err)
|
|
}
|
|
back = append(back, p)
|
|
}
|
|
st.Undo, st.Notice = "", nil
|
|
saveState(st)
|
|
return nil
|
|
})
|
|
return back, err
|
|
}
|
|
|
|
// syncs is whether part goes to the server with c.
|
|
func (c Config) syncs(part string) bool {
|
|
return (part != "agents" || c.Agents) && (part != "library" || c.library())
|
|
}
|
|
|
|
func withKeys(c Config) Config { c.Keys = true; return c }
|
|
|
|
// keepHere seals this computer's setup, keys and all, into the sync
|
|
// folder before a restore replaces it; the path. The newest few are kept.
|
|
func keepHere(c Config) (string, error) {
|
|
b, err := collect(withKeys(c))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
sealed, err := backup.Seal(b, c.Passphrase)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
dir := path("sync")
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
name := filepath.Join(dir, time.Now().Format("2006-01-02-150405")+"-before-restore"+backup.Ext)
|
|
if err := edit.WriteAtomic(name, sealed); err != nil {
|
|
return "", err
|
|
}
|
|
os.Chmod(name, 0o600)
|
|
old, _ := filepath.Glob(filepath.Join(dir, "*-before-restore"+backup.Ext))
|
|
slices.Sort(old)
|
|
for len(old) > 5 {
|
|
os.Remove(old[0])
|
|
old = old[1:]
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
func isFile(p string) bool {
|
|
fi, err := os.Stat(p)
|
|
return err == nil && fi.Mode().IsRegular()
|
|
}
|