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.
307 lines
8.3 KiB
Go
307 lines
8.3 KiB
Go
package gui
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/davsync"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// backupRoutes are the Settings page's Export and Import, and the WebDAV
|
|
// sync set up there.
|
|
func backupRoutes(mux *http.ServeMux, w Windows) {
|
|
mux.HandleFunc("POST /api/backup/export", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Pass string
|
|
Keys bool
|
|
Library *bool // nil is yes
|
|
SignIns bool // the subscriptions' and plugins' sign-ins too
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
b, err := backup.Collect(in.Keys, Version)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if in.Library != nil && !*in.Library {
|
|
b.Library = nil
|
|
}
|
|
if in.SignIns {
|
|
if err := backup.WithSignIns(&b); err != nil {
|
|
fail(rw, fmt.Errorf("the sign-ins couldn't be read, so no backup was made: %w", err))
|
|
return
|
|
}
|
|
}
|
|
data, err := backup.Seal(b, in.Pass)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
dir := downloads()
|
|
name := filepath.Join(dir, "magpie-"+time.Now().Format("2006-01-02")+backup.Ext)
|
|
for i := 2; ; i++ { // never over an earlier one
|
|
if _, err := os.Stat(name); err != nil {
|
|
break
|
|
}
|
|
name = filepath.Join(dir, fmt.Sprintf("magpie-%s-%d%s", time.Now().Format("2006-01-02"), i, backup.Ext))
|
|
}
|
|
if err := edit.WriteAtomic(name, data); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
os.Chmod(name, 0o600)
|
|
_ = w.OpenFolder(dir) // saved either way; the path is in the answer
|
|
writeJSON(rw, map[string]any{"path": tilde(name), "providers": len(b.Providers), "profiles": len(b.Profiles), "agents": len(b.Agents), "library": b.Library != nil, "signIns": signInCount(b.SignIns)})
|
|
})
|
|
mux.HandleFunc("POST /api/backup/import", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Data string
|
|
Pass string
|
|
Agents bool
|
|
Library *bool // nil is yes
|
|
SignIns *bool // nil is yes: the backup's sign-ins, when it has them
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
data, err := base64.StdEncoding.DecodeString(in.Data)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
b, err := backup.Open(data, in.Pass)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
parts := backup.All
|
|
parts.Agents = in.Agents
|
|
parts.Library = in.Library == nil || *in.Library
|
|
parts.SignIns = in.SignIns == nil || *in.SignIns
|
|
res, err := backup.Restore(b, parts)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, res)
|
|
})
|
|
|
|
// backups made by themselves into a folder here, and putting one back
|
|
// (jwaitq on Discord)
|
|
mux.HandleFunc("GET /api/autobackup", func(rw http.ResponseWriter, r *http.Request) {
|
|
writeJSON(rw, autoView())
|
|
})
|
|
mux.HandleFunc("POST /api/autobackup/{action}", func(rw http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
On *bool
|
|
Hours *int
|
|
Keep *int
|
|
Dir *string // "" is the default folder
|
|
Name string
|
|
// SignIns puts the sign-ins in the backups, sealed with
|
|
// Passphrase ("" keeps the one set)
|
|
SignIns *bool
|
|
Passphrase string
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil && !errors.Is(err, io.EOF) {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
set := func(f func(*backup.AutoConfig)) error {
|
|
c, err := backup.LoadAuto()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
f(&c)
|
|
return backup.SaveAuto(c)
|
|
}
|
|
var err error
|
|
switch r.PathValue("action") {
|
|
case "set": // only what was sent: the rest stays as the user set it
|
|
err = set(func(c *backup.AutoConfig) {
|
|
if in.On != nil {
|
|
c.Off = !*in.On
|
|
}
|
|
if in.Hours != nil {
|
|
c.Hours = *in.Hours
|
|
}
|
|
if in.Keep != nil {
|
|
c.Keep = *in.Keep
|
|
}
|
|
if in.Dir != nil && *in.Dir == "" {
|
|
c.Dir = ""
|
|
}
|
|
if in.Passphrase != "" {
|
|
c.Passphrase = in.Passphrase
|
|
}
|
|
if in.SignIns != nil {
|
|
c.SignIns = *in.SignIns
|
|
}
|
|
})
|
|
case "choose": // a folder from the system's picker, checked writable
|
|
var dir string
|
|
if dir, err = w.ChooseFolder("Choose a folder for backups"); err == nil && dir != "" {
|
|
if err = writable(dir); err == nil {
|
|
err = set(func(c *backup.AutoConfig) { c.Dir = dir })
|
|
}
|
|
}
|
|
case "now":
|
|
_, err = backup.AutoNow(Version)
|
|
case "reveal":
|
|
dir := backup.AutoStatus().Dir
|
|
if err = os.MkdirAll(dir, 0o700); err == nil {
|
|
err = w.OpenFolder(dir)
|
|
}
|
|
case "restore": // what is here is backed up first, to undo it
|
|
res, before, err := backup.AutoRestore(in.Name, Version)
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, map[string]any{"view": autoView(), "result": res, "before": before.Name})
|
|
return
|
|
default:
|
|
http.NotFound(rw, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
writeJSON(rw, autoView())
|
|
})
|
|
|
|
mux.HandleFunc("GET /api/davsync", func(rw http.ResponseWriter, r *http.Request) {
|
|
writeJSON(rw, davsync.Status())
|
|
})
|
|
mux.HandleFunc("POST /api/davsync/{action}", func(rw http.ResponseWriter, r *http.Request) {
|
|
// no time limit: a large backup on a slow line takes minutes (#657),
|
|
// and davsync ends a request that stops moving
|
|
ctx := r.Context()
|
|
var err error
|
|
var brought []string
|
|
switch r.PathValue("action") {
|
|
case "save": // and sync at once, so a wrong address or password shows now
|
|
var c davsync.Config
|
|
if err = json.NewDecoder(r.Body).Decode(&c); err == nil {
|
|
err = davsync.Configure(c)
|
|
}
|
|
if err != nil { // said in the form, what was typed in it kept
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
err = busy(davsync.SyncNow(ctx)) // how it went is in the status
|
|
case "now":
|
|
err = busy(davsync.SyncNow(ctx))
|
|
case "off":
|
|
err = davsync.Off()
|
|
case "dismiss":
|
|
err = davsync.Dismiss()
|
|
case "auto": // how often it syncs by itself, or never (#847)
|
|
var in struct{ Minutes int }
|
|
if err = json.NewDecoder(r.Body).Decode(&in); err == nil {
|
|
err = davsync.SetAuto(in.Minutes)
|
|
}
|
|
case "restore": // the server's setup over this computer's, which is kept
|
|
brought, err = davsync.Restore(ctx)
|
|
case "undo":
|
|
_, err = davsync.Undo()
|
|
case "upload": // this computer's setup over a server file that isn't a backup, kept first
|
|
err = davsync.Upload(ctx)
|
|
case "follow": // the agent fields kept on this computer follow the others again
|
|
err = busy(davsync.Follow(ctx))
|
|
case "reveal":
|
|
err = w.OpenFolder(filepath.Join(settings.Dir(), "sync"))
|
|
default:
|
|
http.NotFound(rw, r)
|
|
return
|
|
}
|
|
v := davsync.Status()
|
|
switch {
|
|
case errors.Is(err, davsync.ErrBusy):
|
|
// nothing ran to put it in the status: it is said there all the same
|
|
v.Error = err.Error()
|
|
case err != nil:
|
|
fail(rw, err)
|
|
return
|
|
}
|
|
if r.PathValue("action") == "restore" { // and what it brought in: nothing when it was the same
|
|
writeJSON(rw, struct {
|
|
davsync.View
|
|
Brought []string `json:"brought"`
|
|
}{v, brought})
|
|
return
|
|
}
|
|
writeJSON(rw, v)
|
|
})
|
|
}
|
|
|
|
// autoView is backup.AutoStatus with the folder as the page shows it.
|
|
func autoView() backup.AutoView {
|
|
v := backup.AutoStatus()
|
|
v.Dir = tilde(v.Dir)
|
|
return v
|
|
}
|
|
|
|
// writable says whether a file can be made in dir.
|
|
func writable(dir string) error {
|
|
f, err := os.CreateTemp(dir, ".magpie-backup-*.tmp")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
f.Close()
|
|
return os.Remove(f.Name())
|
|
}
|
|
|
|
// busy is what of a sync's failure the status doesn't hold: that it waited
|
|
// its time out for another magpie's. The rest is in the status.
|
|
func busy(err error) error {
|
|
if errors.Is(err, davsync.ErrBusy) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// downloads is where an export is saved: the Downloads folder the system
|
|
// keeps (appdir.Downloads: Windows' known folder, the XDG one on Linux,
|
|
// which 1Shin on Discord had moved off home\Downloads), else
|
|
// home\Downloads, else home when there is none.
|
|
func downloads() string {
|
|
home, _ := os.UserHomeDir()
|
|
for _, d := range []string{appdir.Downloads(), filepath.Join(home, "Downloads")} {
|
|
if d != "" && isDir(d) {
|
|
return d
|
|
}
|
|
}
|
|
return home
|
|
}
|
|
|
|
func isDir(p string) bool {
|
|
fi, err := os.Stat(p)
|
|
return err == nil && fi.IsDir()
|
|
}
|
|
|
|
// signInCount is how many sign-ins a backup carries.
|
|
func signInCount(s *provider.SignIns) int {
|
|
if s == nil {
|
|
return 0
|
|
}
|
|
return len(s.Logins) + len(s.Plugins)
|
|
}
|