sync: Copy setup gives the sync setup as text, sealed with the passphrase (WJaunita45604 on X)

Setting sync up on a second computer meant typing the server, user,
password (or S3 keys, or GitHub token) and every tick again. Settings ›
Sync's form, with sync on, now has Copy setup. It copies one line,
`magpie-sync:…`, to paste into the same form on the other computer.

- The line is not base64 of the settings. It is the setup (server,
  password or token, endpoint, region, path style, branch, the ticks)
  sealed with the sync passphrase by backup.SealData, the AES-GCM and
  PBKDF2 envelope the server's file already uses. The passphrase is never
  in it. Whoever has the line and not the passphrase has nothing. The
  copied note says what it holds and that the same passphrase opens it.
- Pasted into any field of the form, the line is not typed in; the form
  asks for the passphrase, opens it (POST /api/davsync/setup-open), picks
  WebDAV, S3 or GitHub from its address and fills every field and tick.
  Nothing is saved until Turn on, and Turn on opens a pasted line first. A
  wrong passphrase, or text that isn't a setup, is said in the reader's
  language. A line a chat wrapped, or text around it, still opens.
- Not built: GitLab or MySQL sync backends.

Run (mica):
- At the pushed tree (run as 8fadc2ef8, the same tree before these bodies): go test ./internal/gui ./internal/davsync
  ok; sync-setup-text, i18n-keys and i18n-en-no-cjk in the 110 of 110 the
  commit before names. At the base 5b25d7e9e: ./internal/backup ok too.
  New TestSetupTextOpensWithItsPassphrase (WebDAV, S3, GitHub; no secret
  readable in the text or its decoded bytes; wrapped line; wrong
  passphrase), TestSetupTextNeedsSyncAndItsOwnText and
  TestDavsyncSetupTextRoutes (through the page's routes: off, copy, open on
  a computer with sync off, wrong passphrase, nothing saved).
- New sync-setup-text.test.cjs, Chromium and WebKit, en, zh, zh-TW, ja, de
  at 900px and en, zh at 440px: 42 of 42. The sync GUI files and
  i18n-keys / i18n-en-no-cjk: green but s3-sync webkit en, red the same
  alone on origin/main e4ea31321 (#3413).
- GOOS=linux go vet -tags nogui, GOOS=windows go vet: clean. gofmt clean.
- Broken by hand: SetupText unsealed (base64 of the JSON) made
  TestSetupTextOpensWithItsPassphrase red ("dav-app-password-9z is
  readable"); Turn on without opening the pasted line made all seven
  "pasted setup fills" GUI tests red. Both restored green.

Not tried: a real WebDAV, S3 or GitHub server between two computers, a
paste in the real app, WebKitGTK.
This commit is contained in:
yetone
2026-11-13 18:39:28 +08:00
parent a44da380b9
commit d21cb563e9
7 changed files with 502 additions and 1 deletions
+101
View File
@@ -0,0 +1,101 @@
package davsync
import (
"encoding/base64"
"encoding/json"
"errors"
"regexp"
"strings"
"github.com/yetone/magpie/internal/backup"
)
// SetupPrefix begins a sync setup copied as text (WJaunita45604 on X: one
// copy, pasted on another computer, sets sync up there the same).
const SetupPrefix = "magpie-sync:"
// Setup is what a setup copied as text holds: the server, its password or
// token, and what is synced. Never the passphrase: the text is sealed with
// it, so it is typed on the other computer to open the text, as it is
// typed there to open the server's file.
type Setup struct {
URL string `json:"url"`
User string `json:"user,omitempty"`
Password string `json:"password,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Region string `json:"region,omitempty"`
PathStyle bool `json:"pathStyle,omitempty"`
Branch string `json:"branch,omitempty"`
Keys bool `json:"keys"`
Agents bool `json:"agents"`
Library bool `json:"library"`
Memory bool `json:"memory"`
Usage bool `json:"usage,omitempty"`
SignIns bool `json:"signIns,omitempty"`
}
// ErrSetupOff is SetupText with sync off: there is nothing to copy.
var ErrSetupOff = errors.New("sync isn't set up on this computer")
// ErrNotSetup is OpenSetupText given text that isn't a copied setup.
var ErrNotSetup = errors.New("this isn't a sync setup copied from magpie")
// ErrSetupPassphrase is OpenSetupText with a passphrase that doesn't open it.
var ErrSetupPassphrase = errors.New("the passphrase doesn't open this setup: type the one sync uses on the other computer")
// SetupText is this computer's sync setup as one line of text, sealed with
// its passphrase (AES-GCM under a PBKDF2 key, as the server's file is), so
// the text alone gives no one the server's password.
func SetupText() (string, error) {
c, ok := Load()
if !ok {
return "", ErrSetupOff
}
if c.Passphrase == "" {
return "", ErrSetupOff
}
b, err := json.Marshal(Setup{URL: c.URL, User: c.User, Password: c.Password, Endpoint: c.Endpoint, Region: c.Region,
PathStyle: c.PathStyle, Branch: c.Branch, Keys: c.Keys, Agents: c.Agents, Library: c.library(), Memory: c.memoryOn(),
Usage: c.Usage, SignIns: c.SignIns})
if err != nil {
return "", err
}
sealed, err := backup.SealData(b, c.Passphrase)
if err != nil {
return "", err
}
return SetupPrefix + base64.RawURLEncoding.EncodeToString(sealed), nil
}
// setupBody is the setup's text after its prefix, to the first character
// that can't be in it: line breaks and spaces a chat or a mail wrapped it
// with are in it, and taken out after.
var setupBody = regexp.MustCompile(`^[A-Za-z0-9_\-+/=\s]*`)
// OpenSetupText opens what SetupText gave, with the passphrase it was sealed
// with. Text before the setup, and line breaks a chat put in it, are skipped.
func OpenSetupText(text, pass string) (Setup, error) {
i := strings.Index(text, SetupPrefix)
if i < 0 {
return Setup{}, ErrNotSetup
}
body := text[i+len(SetupPrefix):]
body = strings.Join(strings.Fields(setupBody.FindString(body)), "")
body = strings.NewReplacer("+", "-", "/", "_", "=", "").Replace(body)
sealed, err := base64.RawURLEncoding.DecodeString(body)
if err != nil {
return Setup{}, ErrNotSetup
}
plain, err := backup.OpenData(sealed, pass)
if errors.Is(err, backup.ErrPassphrase) {
return Setup{}, ErrSetupPassphrase
}
if err != nil {
return Setup{}, ErrNotSetup
}
var s Setup
if json.Unmarshal(plain, &s) != nil || s.URL == "" {
return Setup{}, ErrNotSetup
}
return s, nil
}
+84
View File
@@ -0,0 +1,84 @@
package davsync
import (
"encoding/base64"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
// A sync setup copied as text (WJaunita45604 on X) opens on another computer
// with the same passphrase, into the same server, password and choices. The
// text holds neither the password nor the passphrase readable: base64 alone
// would hand the server to anyone who saw it.
func TestSetupTextOpensWithItsPassphrase(t *testing.T) {
for _, c := range []Config{
{URL: "https://dav.jianguoyun.com/dav/", User: "me@example.com", Password: "dav-app-password-9z", Passphrase: "correct horse", Keys: true, Agents: true, Usage: true},
{URL: "s3://bucket/team", User: "AKIAEXAMPLE", Password: "s3-secret-Qx7", Passphrase: "correct horse", Endpoint: "https://acc.r2.cloudflarestorage.com", Region: "auto", PathStyle: true, Library: new(bool), SignIns: true},
{URL: "github://me/backup/magpie", Password: "github_pat_11ABCDEF", Passphrase: "correct horse", Branch: "sync", Memory: new(bool)},
} {
newComputer(t).use(t)
writeSetup(t, c)
text, err := SetupText()
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(text, SetupPrefix) || strings.ContainsAny(text, " \n") {
t.Fatalf("not one line with its prefix: %q", text)
}
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(text, SetupPrefix))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{c.Password, c.Passphrase, c.User, "jianguoyun", "bucket", "github"} {
if secret != "" && (strings.Contains(text, secret) || strings.Contains(string(raw), secret)) {
t.Fatalf("%q is readable in the text", secret)
}
}
// another computer: a chat wrapped the line, and text came before it
newComputer(t).use(t)
wrapped := "here it is: " + text[:40] + "\n" + text[40:90] + " \r\n" + text[90:] + "\n"
if _, err := OpenSetupText(wrapped, "wrong horse"); !errors.Is(err, ErrSetupPassphrase) {
t.Fatalf("a wrong passphrase: %v", err)
}
s, err := OpenSetupText(wrapped, c.Passphrase)
if err != nil {
t.Fatal(err)
}
want := Setup{URL: c.URL, User: c.User, Password: c.Password, Endpoint: c.Endpoint, Region: c.Region, PathStyle: c.PathStyle,
Branch: c.Branch, Keys: c.Keys, Agents: c.Agents, Library: c.library(), Memory: c.memoryOn(), Usage: c.Usage, SignIns: c.SignIns}
if s != want {
t.Fatalf("opened %+v, want %+v", s, want)
}
}
}
func TestSetupTextNeedsSyncAndItsOwnText(t *testing.T) {
newComputer(t).use(t)
if _, err := SetupText(); !errors.Is(err, ErrSetupOff) {
t.Fatalf("sync off: %v", err)
}
for _, s := range []string{"", "magpie-sync:", "magpie-sync:!!!", "magpie-sync:aGVsbG8", "https://dav.example.com"} {
if _, err := OpenSetupText(s, "x"); !errors.Is(err, ErrNotSetup) {
t.Fatalf("%q: %v", s, err)
}
}
}
func writeSetup(t *testing.T, c Config) {
t.Helper()
b, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(path("sync.json")), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path("sync.json"), b, 0o600); err != nil {
t.Fatal(err)
}
}
+32
View File
@@ -1975,6 +1975,14 @@ const I18N = {
"Add a provider": "添加供应商",
"Add your first provider": "添加第一个供应商",
"Find a vendor, or paste a URL and key…": "查找供应商,或粘贴地址和密钥…",
"Copy setup": "复制配置",
"Sync setup": "同步配置",
"Sync setup copied: the server and its password, sealed with your passphrase. On the other computer, paste it into this form and type the same passphrase.": "同步配置已复制:服务器和它的密码,已用你的口令加密。在另一台电脑上,把它粘贴到这个表单里,再输入同一个口令。",
"Type the passphrase sync uses on the other computer: the pasted setup is sealed with it": "输入另一台电脑上同步用的口令:粘贴的配置是用它加密的",
"Filled in from the pasted setup.": "已从粘贴的配置填入。",
"sync isn't set up on this computer": "这台电脑还没有设置同步",
"this isn't a sync setup copied from magpie": "这不是从 magpie 复制的同步配置",
"the passphrase doesn't open this setup: type the one sync uses on the other computer": "这个口令打不开这份配置:请输入另一台电脑上同步用的口令",
"Find a model…": "查找模型…",
"Words match a model's id, name, provider or a group's models": "按模型 ID、名称、供应商或模型组里的模型查找",
"Reasoning: {levels}": "推理强度:{levels}",
@@ -7169,6 +7177,14 @@ const I18N = {
"Add a provider": "新增供應商",
"Add your first provider": "新增第一個供應商",
"Find a vendor, or paste a URL and key…": "查詢供應商,或貼上位址和金鑰…",
"Copy setup": "複製設定",
"Sync setup": "同步設定",
"Sync setup copied: the server and its password, sealed with your passphrase. On the other computer, paste it into this form and type the same passphrase.": "同步設定已複製:伺服器和它的密碼,已用你的口令加密。在另一台電腦上,把它貼到這個表單裡,再輸入同一個口令。",
"Type the passphrase sync uses on the other computer: the pasted setup is sealed with it": "輸入另一台電腦上同步用的口令:貼上的設定是用它加密的",
"Filled in from the pasted setup.": "已從貼上的設定填入。",
"sync isn't set up on this computer": "這台電腦還沒有設定同步",
"this isn't a sync setup copied from magpie": "這不是從 magpie 複製的同步設定",
"the passphrase doesn't open this setup: type the one sync uses on the other computer": "這個口令打不開這份設定:請輸入另一台電腦上同步用的口令",
"Find a model…": "查詢模型…",
"Words match a model's id, name, provider or a group's models": "按模型 ID、名稱、供應商或模型組裡的模型查詢",
"Reasoning: {levels}": "推理強度:{levels}",
@@ -12337,6 +12353,14 @@ const I18N = {
"Add a provider": "プロバイダを追加",
"Add your first provider": "最初のプロバイダを追加",
"Find a vendor, or paste a URL and key…": "ベンダーを検索、または URL とキーを貼り付け…",
"Copy setup": "設定をコピー",
"Sync setup": "同期の設定",
"Sync setup copied: the server and its password, sealed with your passphrase. On the other computer, paste it into this form and type the same passphrase.": "同期の設定をコピーしました:サーバーとそのパスワードを、パスフレーズで暗号化しています。もう一台のコンピュータでこのフォームに貼り付け、同じパスフレーズを入力してください。",
"Type the passphrase sync uses on the other computer: the pasted setup is sealed with it": "もう一台のコンピュータで同期に使っているパスフレーズを入力してください:貼り付けた設定はそれで暗号化されています",
"Filled in from the pasted setup.": "貼り付けた設定から入力しました。",
"sync isn't set up on this computer": "このコンピュータでは同期が設定されていません",
"this isn't a sync setup copied from magpie": "これは magpie からコピーした同期の設定ではありません",
"the passphrase doesn't open this setup: type the one sync uses on the other computer": "このパスフレーズではこの設定を開けません:もう一台のコンピュータで同期に使っているものを入力してください",
"Find a model…": "モデルを検索…",
"Words match a model's id, name, provider or a group's models": "モデルの ID、名前、プロバイダ、またはグループのモデルに一致する語で検索します",
"Reasoning: {levels}": "推論:{levels}",
@@ -17536,6 +17560,14 @@ const I18N = {
"Add a provider": "Anbieter hinzufügen",
"Add your first provider": "Ersten Anbieter hinzufügen",
"Find a vendor, or paste a URL and key…": "Anbieter suchen oder URL und Schlüssel einfügen…",
"Copy setup": "Einrichtung kopieren",
"Sync setup": "Sync-Einrichtung",
"Sync setup copied: the server and its password, sealed with your passphrase. On the other computer, paste it into this form and type the same passphrase.": "Sync-Einrichtung kopiert: der Server und sein Passwort, mit deiner Passphrase verschlüsselt. Füge sie auf dem anderen Computer in dieses Formular ein und gib dieselbe Passphrase ein.",
"Type the passphrase sync uses on the other computer: the pasted setup is sealed with it": "Gib die Passphrase ein, die Sync auf dem anderen Computer nutzt: die eingefügte Einrichtung ist damit verschlüsselt",
"Filled in from the pasted setup.": "Aus der eingefügten Einrichtung übernommen.",
"sync isn't set up on this computer": "Sync ist auf diesem Computer nicht eingerichtet",
"this isn't a sync setup copied from magpie": "Das ist keine aus magpie kopierte Sync-Einrichtung",
"the passphrase doesn't open this setup: type the one sync uses on the other computer": "Diese Passphrase öffnet die Einrichtung nicht: gib die ein, die Sync auf dem anderen Computer nutzt",
"Find a model…": "Modell suchen…",
"Words match a model's id, name, provider or a group's models": "Suchbegriffe passen auf ID, Name oder Anbieter eines Modells oder auf die Modelle einer Gruppe",
"Reasoning: {levels}": "Reasoning: {levels}",
+54 -1
View File
@@ -82,10 +82,63 @@ window.davForm = function (v) {
show();
const off = v.on ? el("button", "text danger", t("Turn off")) : el("span");
const cancel = el("button", "text", t("Cancel"));
const say = syncBar(ed, "", off, el("span", "grow"), cancel, save);
// this setup as text, for another computer (WJaunita45604 on X): sealed
// with the passphrase, which the text never holds
const copySetup = v.on ? el("button", "text sync-copy", t("Copy setup")) : el("span");
const said = syncBar(ed, "", off, copySetup, el("span", "grow"), cancel, save);
const say = (msg, note) => { said(msg); ed.querySelector(".editor-error").classList.toggle("note", !!note); };
copySetup.onclick = async () => {
try {
const r = await api("davsync/setup-text", {});
await copy(r.text, t("Sync setup"), copySetup, t("Sync setup copied: the server and its password, sealed with your passphrase. On the other computer, paste it into this form and type the same passphrase."));
} catch (e) { say(t(e.message)); }
};
// a setup copied on another computer, pasted in any field here, fills
// the form once the passphrase it was sealed with is typed
let pasted = "";
const fill = (s) => {
kind = /^s3:\/\//i.test(s.url) ? "s3" : /^github:\/\//i.test(s.url) ? "github" : "webdav";
if (kind === "s3") {
const m = /^s3:\/\/([^/]*)\/?(.*)$/i.exec(s.url);
bucket.value = m[1]; prefix.value = m[2];
endpoint.value = s.endpoint || ""; region.value = s.region || ""; keyID.value = s.user || ""; secret.value = s.password || ""; pathStyle.checked = !!s.pathStyle;
} else if (kind === "github") {
const m = /^github:\/\/([^/]+\/[^/]+)\/?(.*)$/i.exec(s.url);
repo.value = m?.[1] || ""; ghPrefix.value = m?.[2] || ""; branch.value = s.branch || ""; token.value = s.password || "";
} else { url.value = s.url; user.value = s.user || ""; pass.value = s.password || ""; }
keys.checked = !!s.keys; agents.checked = !!s.agents; lib.checked = !!s.library; mem.checked = !!s.memory; use.checked = !!s.usage; si.checked = !!s.signIns;
siSay.hidden = !si.checked;
// the kind picked as a click on it would, its thumb moved too
to[1].querySelector(`.segs [data-seg="${kind}"]`)?.click();
show();
};
const openPasted = async () => {
if (!pasted) return true;
if (!phrase.value) {
say(t("Type the passphrase sync uses on the other computer: the pasted setup is sealed with it"), true);
phrase.focus();
return false;
}
try {
fill(await api("davsync/setup-open", { text: pasted, passphrase: phrase.value }));
pasted = "";
say(t("Filled in from the pasted setup."), true);
return true;
} catch (e) { say(t(e.message)); return false; }
};
ed.addEventListener("paste", (e) => {
const text = e.clipboardData?.getData("text") || "";
if (!text.includes("magpie-sync:")) return;
e.preventDefault();
pasted = text;
openPasted();
});
phrase.addEventListener("keydown", (e) => { if (e.key === "Enter" && pasted) openPasted(); });
phrase.addEventListener("change", () => { if (pasted) openPasted(); });
cancel.onclick = () => { syncOpen = ""; renderSync(); };
off.onclick = async () => { syncOpen = ""; renderSync(await api("davsync/off", {}).catch(() => null) || undefined); };
save.onclick = async () => {
if (!(await openPasted())) return;
const b = bucket.value.trim(), p = prefix.value.trim().replace(/^\/+|\/+$/g, "");
if (kind === "s3" && !b) return say(t("Name the bucket"));
const repository = repo.value.trim().replace(/^https:\/\/github\.com\//i, "").replace(/\/+$/, "").replace(/\.git$/i, "");
+21
View File
@@ -241,6 +241,27 @@ func backupRoutes(mux *http.ServeMux, w Windows) {
err = busy(davsync.Follow(ctx))
case "reveal":
err = w.OpenFolder(filepath.Join(settings.Dir(), "sync"))
case "setup-text": // this setup as text sealed with its passphrase, to paste on another computer
text, err := davsync.SetupText()
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]string{"text": text})
return
case "setup-open": // a setup pasted from another computer, for the form: nothing is saved
var in struct{ Text, Passphrase string }
if err = json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
s, err := davsync.OpenSetupText(in.Text, in.Passphrase)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, s)
return
default:
http.NotFound(rw, r)
return
+55
View File
@@ -0,0 +1,55 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/davsync"
)
// Settings › Sync's Copy setup and its paste on another computer
// (WJaunita45604 on X), through the routes the page calls: the text comes
// sealed, opens with the passphrase into the setup the form fills, says a
// wrong passphrase as such, and saves nothing on the computer it opens on.
func TestDavsyncSetupTextRoutes(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
backupRoutes(mux, folderOnly{})
post := func(action, body string) (int, map[string]any) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/davsync/"+action, strings.NewReader(body)))
var v map[string]any
json.Unmarshal(w.Body.Bytes(), &v)
return w.Code, v
}
if code, v := post("setup-text", "{}"); code != 400 || v["error"] != davsync.ErrSetupOff.Error() {
t.Fatalf("sync off: %d %v", code, v)
}
if err := davsync.Configure(davsync.Config{URL: "https://dav.jianguoyun.com/dav/", User: "me@example.com", Password: "app-password-9z", Passphrase: "correct horse", Keys: true}); err != nil {
t.Fatal(err)
}
code, v := post("setup-text", "{}")
text, _ := v["text"].(string)
if code != 200 || !strings.HasPrefix(text, davsync.SetupPrefix) || strings.Contains(text, "app-password") {
t.Fatalf("copy: %d %v", code, v)
}
if err := davsync.Off(); err != nil { // the other computer: sync off there
t.Fatal(err)
}
in, _ := json.Marshal(map[string]string{"text": text, "passphrase": "wrong horse"})
if code, v := post("setup-open", string(in)); code != 400 || v["error"] != davsync.ErrSetupPassphrase.Error() {
t.Fatalf("wrong passphrase: %d %v", code, v)
}
in, _ = json.Marshal(map[string]string{"text": text, "passphrase": "correct horse"})
code, v = post("setup-open", string(in))
if code != 200 || v["url"] != "https://dav.jianguoyun.com/dav/" || v["user"] != "me@example.com" || v["password"] != "app-password-9z" || v["keys"] != true {
t.Fatalf("open: %d %v", code, v)
}
if _, on := davsync.Load(); on {
t.Fatal("opening a pasted setup turned sync on")
}
}
+155
View File
@@ -0,0 +1,155 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A sync setup copied as text (WJaunita45604 on X): Copy setup in the open
// sync form copies the text magpie seals with the passphrase; on another
// computer, the text pasted into the form asks for that passphrase, says a
// wrong one in the reader's language, and with the right one fills the
// form, the kind picked from the server's address. Nothing is saved until
// Turn on. The API is faked; nothing is synced or sealed here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { openPart } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const TEXT = "magpie-sync:eyJmb3JtYXQiOiJtYWdwaWUtZGF0YSJ9AbCdEf0123456789";
const opened = { url: "s3://bucket/team", user: "AKIAEXAMPLE", password: "s3-secret-Qx7", endpoint: "https://acct.r2.cloudflarestorage.com", region: "auto", pathStyle: true, keys: true, agents: true, library: false, memory: true, signIns: true };
function serve(lang, on, posts) {
const settings = { theme: "light", lang, tray: "panel", version: "test", dir: "/tmp/magpie", gateway: "http://127.0.0.1:3425", visionModels: [], imageGenModels: [], fx: { rate: 7.2, stale: false } };
const sync = on ? { on: true, kind: "webdav", url: "https://dav.example.com/dav/", user: "me", passwordSet: true, passphraseSet: true, keys: true, agents: true, library: true, memory: true, last: "2026-11-13T08:00:00Z" }
: { on: false, keys: true, agents: true, library: true, memory: true };
return async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
const json = (data, status = 200) => route.fulfill({ status, json: data });
if (pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:false};` });
if (pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (pathname === "/api/settings") return json(settings);
if (pathname === "/api/usage/quotas") return json([]);
if (pathname === "/api/groups") return json({ groups: [], models: [] });
if (pathname === "/api/plugins") return json({ plugins: [] });
if (pathname === "/api/davsync") return json(sync);
if (pathname.startsWith("/api/davsync/") || pathname === "/api/copy") {
const body = request.postDataJSON();
posts.push({ path: pathname, body });
if (pathname === "/api/davsync/setup-text") return json({ text: TEXT });
if (pathname === "/api/copy") return json({});
if (pathname === "/api/davsync/setup-open") {
if (body.passphrase !== "correct horse") return json({ error: "the passphrase doesn't open this setup: type the one sync uses on the other computer" }, 400);
return json(opened);
}
if (pathname === "/api/davsync/save") return json({ ...sync, on: true, kind: "s3", url: body.url });
return json(sync);
}
if (pathname.startsWith("/api/")) return json({});
const file = path.join(assets, pathname === "/" ? "index.html" : pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
return route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const launch = (engine) => engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" });
const press = (loc) => loc.evaluate((b) => b.click());
async function open(engine, lang, width, on, t) {
const browser = await launch(engine);
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, on, posts));
await page.goto("http://magpie.test/");
await page.locator("#prefs").click();
await openPart(page, "sync");
const first = page.locator("#syncList .row.pref").first();
await first.waitFor({ state: "visible" });
await press(first.locator(".val button").last());
const form = page.locator("#syncList .sync-form");
await form.waitFor({ state: "visible" });
return { page, form, errors, posts };
}
const said = (page, s) => page.evaluate((x) => t(x), s);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const [lang, width] of [["en", 900], ["zh", 900], ["zh-TW", 900], ["ja", 900], ["de", 900], ["en", 440], ["zh", 440]]) {
test(`${engine} ${lang} ${width}px: Copy setup copies the sealed text`, async (t) => {
const { page, form, errors, posts } = await open(engine, lang, width, true, t);
const copy = form.locator(".bar .sync-copy");
assert.equal((await copy.textContent()).trim(), await said(page, "Copy setup"));
if (lang !== "en") assert.notEqual((await copy.textContent()).trim(), "Copy setup");
await press(copy);
for (let i = 0; i < 40 && !posts.some((p) => p.path === "/api/copy"); i++) await page.waitForTimeout(50);
assert.deepEqual(posts.find((p) => p.path === "/api/copy")?.body, { text: TEXT });
assert.ok(await form.evaluate((f) => f.scrollWidth <= f.clientWidth + 1), "the form's bar fits");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: a pasted setup fills the form with its passphrase`, async (t) => {
const { page, form, errors, posts } = await open(engine, lang, width, false, t);
// no Copy setup while sync is off: there is nothing to copy
assert.equal(await form.locator(".bar .sync-copy").count(), 0);
const address = form.locator("input").first();
const phrase = form.locator("input[type=password]").last();
const note = form.locator(".editor-error");
const pasted = await address.evaluate((i, s) => {
i.focus();
const dt = new DataTransfer();
dt.setData("text/plain", s);
const e = new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true });
i.dispatchEvent(e);
return e.defaultPrevented;
}, "on the other computer:\n" + TEXT.slice(0, 30) + "\n" + TEXT.slice(30));
assert.equal(pasted, true);
assert.equal(await address.inputValue(), "", "the text isn't typed into the address");
const ask = await said(page, "Type the passphrase sync uses on the other computer: the pasted setup is sealed with it");
if (lang !== "en") assert.notEqual(ask, "Type the passphrase sync uses on the other computer: the pasted setup is sealed with it");
assert.equal(await note.textContent(), ask);
assert.ok(await note.evaluate((n) => n.classList.contains("note")));
assert.ok(!posts.some((p) => p.path === "/api/davsync/setup-open"), "nothing asked without a passphrase");
await phrase.fill("wrong horse");
await phrase.press("Enter");
const wrong = await said(page, "the passphrase doesn't open this setup: type the one sync uses on the other computer");
if (lang !== "en") assert.notEqual(wrong, "the passphrase doesn't open this setup: type the one sync uses on the other computer");
for (let i = 0; i < 40 && (await note.textContent()) !== wrong; i++) await page.waitForTimeout(50);
assert.equal(await note.textContent(), wrong);
assert.ok(await note.evaluate((n) => !n.classList.contains("note")));
// the right one, then straight to Turn on: the setup is opened first
await phrase.fill("correct horse");
await press(form.locator(".bar .primary"));
for (let i = 0; i < 60 && !posts.some((p) => p.path === "/api/davsync/save"); i++) await page.waitForTimeout(50);
const save = posts.find((p) => p.path === "/api/davsync/save")?.body;
assert.ok(save, "saved");
assert.deepEqual([save.url, save.user, save.password, save.endpoint, save.region, save.pathStyle, save.passphrase, save.library, save.signIns],
["s3://bucket/team", "AKIAEXAMPLE", "s3-secret-Qx7", "https://acct.r2.cloudflarestorage.com", "auto", true, "correct horse", false, true]);
const asks = posts.filter((p) => p.path === "/api/davsync/setup-open");
assert.ok(asks.length >= 2 && asks.every((p) => p.body.text.includes(TEXT.slice(30))));
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}px: the pasted setup shows S3 picked before Turn on`, async (t) => {
const { page, form, errors } = await open(engine, lang, width, false, t);
const phrase = form.locator("input[type=password]").last();
await phrase.fill("correct horse");
await phrase.evaluate((i, s) => {
const dt = new DataTransfer();
dt.setData("text/plain", s);
i.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true }));
}, TEXT);
const filled = await said(page, "Filled in from the pasted setup.");
for (let i = 0; i < 40 && (await form.locator(".editor-error").textContent()) !== filled; i++) await page.waitForTimeout(50);
assert.equal(await form.locator(".editor-error").textContent(), filled);
assert.equal(await form.locator(".segs .opt.on").getAttribute("data-seg"), "s3");
const values = await form.locator("input:visible").evaluateAll((is) => is.map((i) => i.type === "checkbox" ? i.checked : i.value));
for (const v of ["https://acct.r2.cloudflarestorage.com", "bucket", "team", "auto", "AKIAEXAMPLE", "s3-secret-Qx7", "correct horse"]) assert.ok(values.includes(v), v);
assert.deepEqual(errors, []);
});
}
}