Files
magpie/internal/gui/assets/autobackup.js
T
yetone 900ae0fa51 backup, sync: sign-ins go too when picked, sealed, never over a later renewal
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/main bc10a6198):
- 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/main
  bc10a6198 give 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/main 5ee5274bd (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.
2026-11-03 17:24:19 +08:00

182 lines
9.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Settings › Sync's Back up by itself (jwaitq on Discord: 定期自动备份,
// 支持回退选择版本): the setup backed up into a folder on this computer on a
// schedule, the last few kept, and any of them put back, what is here being
// backed up first so that can be undone. app.js imports this when Settings
// draws Sync, so it weighs nothing on the core.
// the server's view, kept over Settings' redraws and read again when it is
// half a minute old; the read under way, which a redraw while it is out
// draws with too; what the last restore came to, said once under the
// versions
let autoBackupView = null;
let autoBackupAt = 0;
let autoBackupLoad = null;
let autoBackupSaid = null;
// the passphrase asked for as the sign-ins are turned on, when none is set
let autoBackupPhrase = false;
// autoBackupFill puts the rows in place of at, the empty element renderSync
// leaves at the end of Sync's list: rows, so the list's lines run between
// them as between Sync's own.
window.autoBackupFill = function (at) {
let drawn = [at];
const draw = () => {
if (!drawn[0].isConnected) return;
const rows = autoBackupRows(autoBackupView);
drawn[0].before(...rows);
for (const r of drawn) r.remove();
drawn = rows;
};
if (autoBackupView) draw();
if (Date.now() - autoBackupAt >= 30000) {
autoBackupAt = Date.now();
const load = api("autobackup").then((v) => { autoBackupView = v; }, (e) => { autoBackupView = { error: e.message, backups: [] }; });
autoBackupLoad = load;
load.then(() => { if (autoBackupLoad === load) autoBackupLoad = null; });
}
autoBackupLoad?.then(draw);
};
// autoBackupDo posts one action and draws Sync again with what it says
async function autoBackupDo(action, body, b) {
b?.classList.add("busy");
try {
autoBackupView = await api("autobackup/" + action, body || {});
autoBackupAt = Date.now();
} catch (e) {
statusErr(e);
}
renderSync();
}
function autoBackupRows(v) {
const rows = [];
const row = (name, sub, ...tools) => {
const r = el("div", "row pref auto-backup");
const who = el("div", "who");
const s = el("div", "sub", sub);
who.append(el("div", "name", name), s);
const val = el("div", "val");
val.append(...tools);
r.append(who, val);
rows.push(r);
return r;
};
const btn = (label, fn) => { const b = el("button", "text", label); b.type = "button"; b.onclick = (e) => fn(b, e); return b; };
const on = !!v.on;
const head = row(t("Back up by itself"), v.error ? t("Couldn't back up: {error}", { error: v.error })
: on ? (v.signIns ? t("Your providers, settings and profiles, without API keys, and the sign-ins sealed with a passphrase, into a folder on this computer")
: t("Your providers, settings and profiles, without API keys or sign-ins, into a folder on this computer")) : t("Off: no backups are made by themselves"),
segs([[0, t("Off")], [1, t("1 hour")], [6, t("6 hours")], [24, t("1 day")], [168, t("1 week")]], on ? v.hours : 0,
(h) => autoBackupDo("set", h ? { on: true, hours: h } : { on: false })));
if (v.error) head.querySelector(".sub").classList.add("bad", "wraps");
if (on) {
row(t("Versions kept"), t("The oldest is removed when a new one is made; one is made only when something changed"),
segs([3, 7, 14, 30].map((n) => [n, String(n)]), v.keep, (n) => autoBackupDo("set", { keep: n })));
// the sign-ins (qianxunji, curtinp118 on Discord): off unless picked,
// and sealed with a passphrase asked for the first time
const asking = autoBackupPhrase && !v.signIns;
row(t("Sign-ins in backups"), v.signIns ? t("Subscription accounts and plugin sign-ins, sealed with the passphrase set here")
: t("Off: after a restore on another computer, sign in again"),
segs([["off", t("Off")], ["on", t("On")]], v.signIns || asking ? "on" : "off", (x) => {
if (x === "on" && !v.passphrase) { autoBackupPhrase = true; renderSync(); return; }
autoBackupPhrase = false;
autoBackupDo("set", { signIns: x === "on" });
}));
if (asking) rows.push(autoBackupPhraseForm());
}
if (on || v.backups?.length) {
const tools = [btn(t("Change…"), (b) => autoBackupDo("choose", {}, b)), btn(t("Show"), () => api("autobackup/reveal", {}).catch(statusErr))];
if (v.custom) tools.push(btn(t("Default"), (b) => autoBackupDo("set", { dir: "" }, b)));
row(t("Backup folder"), v.dir || "", ...tools).querySelector(".sub").classList.add("wraps", "auto-backup-dir");
}
const list = v.backups || [];
const sub = row(t("Versions"), list.length ? t("{n} backups · newest {when}", { n: list.length, when: syncWhen(list[0].made) }) : t("None yet"),
btn(t("Back up now"), (b) => autoBackupDo("now", {}, b))).querySelector(".sub");
if (autoBackupSaid) {
sub.after(...autoBackupSaid.map((l) => el("div", "sub wraps auto-backup-said", l)));
autoBackupSaid = null;
}
for (const b of list) {
const when = autoBackupWhen(b.made);
const what = [t(b.providers === 1 ? "1 provider" : "{n} providers", { n: b.providers })];
if (b.reason === "restore") what.unshift(t("What was here before a restore"));
if (b.signIns) what.push(t("sign-ins"));
row(when, what.join(" · "), btn(t("Restore…"), () => autoBackupAsk(b, when))).classList.add("auto-backup-version");
}
return rows;
}
// autoBackupWhen names a version by when it was made, as its row does
const autoBackupWhen = (made) => new Date(made).toLocaleString(intlLang(), { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
// autoBackupAsk asks before a version is put back, in the app's own
// dialog, saying what changes and that what is here is backed up first.
function autoBackupAsk(b, when) {
const ed = el("div", "editor restore-ask auto-backup-ask");
const head = el("div", "ehead");
head.append(el("b", "", t("Restore the backup of {when}?", { when })));
ed.append(head);
ed.append(el("p", "lib-confirm", t("Your providers, settings, profiles and agents' models become this backup's. Providers added since are kept, and each keeps its API keys here.")));
if (b.signIns) ed.append(el("p", "lib-confirm", t("Its sign-ins are put in where they were renewed later than the ones here; none here is removed.")));
ed.append(el("p", "lib-confirm", t("What is here now is backed up first: restore that one to undo this.")));
const err = el("p", "editor-error", "");
ed.append(err);
const bar = el("div", "bar");
const go = el("button", "text primary danger-fill", t("Restore"));
go.onclick = async (e) => {
e.stopPropagation();
go.disabled = true;
go.classList.add("busy");
try {
const r = await api("autobackup/restore", { name: b.name });
closeConfirmAsk();
autoBackupView = r.view;
autoBackupAt = Date.now();
const x = r.result || {};
const lines = [t("Restored the backup of {when}", { when }) + " · " + t("Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed", { added: x.Added, replaced: x.Replaced, profiles: x.Profiles, agents: x.Agents })];
if (x.NeedKey?.length) lines.push(t("Needs a key: {names}", { names: x.NeedKey.join(", ") }));
if (x.SignIns) { await import("./syncfiles.js"); lines.push(...signInsSaid(x.SignIns)); }
if (x.SignInsLocked) lines.push(t("This backup's sign-ins are sealed with another passphrase, so they were left out."));
const before = r.view?.backups?.find((k) => k.name === r.before);
if (before) lines.push(t("What was here before is the version of {when}: restore it to undo.", { when: autoBackupWhen(before.made) }));
autoBackupSaid = lines;
renderSync();
refreshAfterSync();
} catch (x) {
go.disabled = false;
go.classList.remove("busy");
err.textContent = x.message;
}
};
const cancel = el("button", "text", t("Cancel"));
cancel.onclick = cancelAsk;
bar.append(el("span", "grow"), cancel, go);
ed.append(bar);
confirmAsk = ed;
openModal(ed);
$("#modal").classList.add("lib");
cancel.focus(NO_SCROLL);
}
// autoBackupPhraseForm asks for the passphrase the backups' sign-ins are
// sealed with, as they are turned on
function autoBackupPhraseForm() {
const ed = el("div", "editor sync-form auto-backup-phrase");
const p1 = input("", t("passphrase"), "password");
const p2 = input("", t("again"), "password");
ed.append(...field(t("Passphrase"), p1, t("The sign-ins in each backup are sealed with it. Anyone with a backup and the passphrase can use those accounts. Keep it: without it a backup's sign-ins can't be opened.")),
...field("", p2));
const go = el("button", "text primary", t("Turn on"));
const cancel = el("button", "text", t("Cancel"));
const say = syncBar(ed, "", el("span", "grow"), cancel, go);
cancel.onclick = () => { autoBackupPhrase = false; renderSync(); };
go.onclick = async () => {
if (!p1.value) return say(t("Pick a passphrase: the file is sealed with it"));
if (p1.value !== p2.value) return say(t("The two passphrases differ"));
autoBackupPhrase = false;
await autoBackupDo("set", { signIns: true, passphrase: p1.value }, go);
};
return ed;
}