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.
232 lines
6.8 KiB
Go
232 lines
6.8 KiB
Go
package cli
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
|
|
"golang.org/x/term"
|
|
|
|
"github.com/yetone/magpie/internal/backup"
|
|
"github.com/yetone/magpie/internal/edit"
|
|
)
|
|
|
|
// backupCmd writes every provider, setting, profile and agent model, and
|
|
// the library, to one file sealed with a passphrase:
|
|
// magpie backup [--no-keys] [--no-library] [--sign-ins] [file].
|
|
func backupCmd(args []string) error {
|
|
keys, lib, signIns, file := true, true, false, ""
|
|
for _, a := range args {
|
|
switch {
|
|
case a == "--no-keys":
|
|
keys = false
|
|
case a == "--no-library":
|
|
lib = false
|
|
case a == "--sign-ins":
|
|
signIns = true
|
|
case strings.HasPrefix(a, "-"):
|
|
return fmt.Errorf("unknown flag %s (magpie backup [--no-keys] [--no-library] [--sign-ins] [file])", a)
|
|
case file == "":
|
|
file = a
|
|
default:
|
|
return errors.New("usage: magpie backup [--no-keys] [--no-library] [--sign-ins] [file]")
|
|
}
|
|
}
|
|
if file == "" {
|
|
file = "magpie" + backup.Ext
|
|
}
|
|
b, err := backup.Collect(keys, version)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !lib {
|
|
b.Library = nil
|
|
}
|
|
if signIns {
|
|
if err := backup.WithSignIns(&b); err != nil {
|
|
return fmt.Errorf("the sign-ins couldn't be read, so no backup was made: %w", err)
|
|
}
|
|
}
|
|
pass, err := passphrase("Passphrase for the backup: ", true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
data, err := backup.Seal(b, pass)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := edit.WriteAtomic(file, data); err != nil {
|
|
return err
|
|
}
|
|
os.Chmod(file, 0o600)
|
|
what := "with their keys"
|
|
if !keys {
|
|
what = "without keys"
|
|
}
|
|
fmt.Printf("%s %s: %d providers %s, %d profiles, %d agent settings",
|
|
green.Render("saved"), file, len(b.Providers), what, len(b.Profiles), len(b.Agents))
|
|
if l := b.Library; l != nil {
|
|
fmt.Printf("; library: %d MCP servers, %d skills", len(l.MCP), len(l.Skills))
|
|
if l.Subagents != nil && len(*l.Subagents) > 0 {
|
|
fmt.Printf(", %d subagents", len(*l.Subagents))
|
|
}
|
|
}
|
|
if s := b.SignIns; s != nil {
|
|
fmt.Printf("; %d sign-ins", len(s.Logins)+len(s.Plugins))
|
|
}
|
|
fmt.Println()
|
|
if b.SignIns != nil {
|
|
fmt.Println(muted.Render("The subscriptions' and plugins' sign-ins are in it, sealed with the passphrase: anyone with the file and the passphrase can use those accounts. Keep the passphrase: without it the file can't be opened."))
|
|
} else {
|
|
fmt.Println(muted.Render("Subscriptions are not in it: sign in to them on the other machine (or back up with --sign-ins). Keep the passphrase: without it the file can't be opened."))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// restoreCmd puts a backup in: magpie restore [--no-agents] [--no-library] [--no-sign-ins] <file>.
|
|
func restoreCmd(args []string) error {
|
|
parts, file := backup.All, ""
|
|
for _, a := range args {
|
|
switch {
|
|
case a == "--no-agents":
|
|
parts.Agents = false
|
|
case a == "--no-library":
|
|
parts.Library = false
|
|
case a == "--no-sign-ins":
|
|
parts.SignIns = false
|
|
case strings.HasPrefix(a, "-"):
|
|
return fmt.Errorf("unknown flag %s (magpie restore [--no-agents] [--no-library] [--no-sign-ins] <file>)", a)
|
|
case file == "":
|
|
file = a
|
|
default:
|
|
return errors.New("usage: magpie restore [--no-agents] [--no-library] [--no-sign-ins] <file>")
|
|
}
|
|
}
|
|
if file == "" {
|
|
return errors.New("usage: magpie restore [--no-agents] [--no-library] [--no-sign-ins] <file>")
|
|
}
|
|
data, err := os.ReadFile(file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pass, err := passphrase("Passphrase: ", false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b, err := backup.Open(data, pass)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r, err := backup.Restore(b, parts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("%s providers: %d added, %d replaced", green.Render("restored"), r.Added, r.Replaced)
|
|
if r.Settings {
|
|
fmt.Print("; settings")
|
|
}
|
|
fmt.Printf("; %d profiles; %d agent settings changed", r.Profiles, r.Agents)
|
|
if r.Library {
|
|
fmt.Print("; library")
|
|
}
|
|
if s := r.SignIns; s != nil {
|
|
fmt.Printf("; sign-ins: %d added, %d updated, %d kept as they are here", s.Added, s.Updated, s.Kept)
|
|
if s.Codex {
|
|
fmt.Print(" (Codex signed in)")
|
|
}
|
|
}
|
|
fmt.Println()
|
|
if len(r.NeedKey) > 0 {
|
|
fmt.Println(muted.Render("Needs a key (magpie provider key <id>): " + strings.Join(r.NeedKey, ", ")))
|
|
}
|
|
if len(r.SignIn) > 0 {
|
|
fmt.Println(muted.Render("The backup's settings use these, not signed in on this computer (a backup carries settings, not sign-ins; to use one here: magpie accounts add <id>): " + strings.Join(r.SignIn, ", ")))
|
|
}
|
|
if len(r.Plugins) > 0 {
|
|
fmt.Println(muted.Render("Plugins added: " + strings.Join(r.Plugins, ", ")))
|
|
}
|
|
for _, spec := range slices.Sorted(maps.Keys(r.PluginErrors)) {
|
|
fmt.Println(muted.Render(fmt.Sprintf("Couldn't add the plugin %s: %s", spec, r.PluginErrors[spec])))
|
|
}
|
|
for _, p := range r.LibraryProblems {
|
|
fmt.Println(muted.Render(fmt.Sprintf("Library: %s couldn't get %s: %s", p.Agent, p.What, p.Error)))
|
|
}
|
|
if len(r.Skipped) > 0 {
|
|
fmt.Println(muted.Render("Left as they are (agent not here, or its model can't be reached yet): " + strings.Join(r.Skipped, ", ")))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// passphrase reads one from the terminal without echo, asked twice when
|
|
// it is being set; piped in, it is the next line of stdin.
|
|
func passphrase(prompt string, confirm bool) (string, error) {
|
|
return secret("passphrase", prompt, confirm)
|
|
}
|
|
|
|
// stdin is read through one reader, so a second secret piped in is the
|
|
// second line and not lost to the first one's buffer. The reader is made
|
|
// over os.Stdin as it is when first read, never at package init: package
|
|
// variables are set before any init runs, and on Windows the desktop
|
|
// build's init (console_windows.go) only then swaps in the terminal's
|
|
// CONIN$. A reader made earlier keeps the invalid handle, and every
|
|
// prompt fails with "read /dev/stdin: The handle is invalid".
|
|
var (
|
|
stdinMu sync.Mutex
|
|
stdinFile *os.File
|
|
stdinBuf *bufio.Reader
|
|
)
|
|
|
|
func stdin() *bufio.Reader {
|
|
stdinMu.Lock()
|
|
defer stdinMu.Unlock()
|
|
if stdinBuf == nil || stdinFile != os.Stdin {
|
|
stdinFile, stdinBuf = os.Stdin, bufio.NewReader(os.Stdin)
|
|
}
|
|
return stdinBuf
|
|
}
|
|
|
|
// secret reads what (a passphrase, a password) as passphrase does; piped
|
|
// in, it is the next line of stdin.
|
|
func secret(what, prompt string, confirm bool) (string, error) {
|
|
fd := int(os.Stdin.Fd())
|
|
if !term.IsTerminal(fd) {
|
|
line, err := stdin().ReadString('\n')
|
|
line = strings.TrimRight(line, "\r\n")
|
|
if line == "" {
|
|
if err != nil {
|
|
return "", fmt.Errorf("no %s on stdin: %w", what, err)
|
|
}
|
|
return "", fmt.Errorf("the %s is empty", what)
|
|
}
|
|
return line, nil
|
|
}
|
|
read := func(p string) (string, error) {
|
|
fmt.Fprint(os.Stderr, p)
|
|
b, err := term.ReadPassword(fd)
|
|
fmt.Fprintln(os.Stderr)
|
|
return string(b), err
|
|
}
|
|
pass, err := read(prompt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if pass == "" {
|
|
return "", fmt.Errorf("the %s is empty", what)
|
|
}
|
|
if confirm {
|
|
again, err := read("Again: ")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if again != pass {
|
|
return "", fmt.Errorf("the %ss differ", what)
|
|
}
|
|
}
|
|
return pass, nil
|
|
}
|