gui: a magpie folder the user can't write gets a one-click Repair (YouWhat)

YouWhat on Discord (macOS): adding a custom provider failed with
"mkdir ~/.config/magpie: permission denied". ~/.config wasn't the user's
(a command run under sudo makes it root's), so magpie couldn't make its
folder. The app still ran because reads of a missing file mean "none",
but every save failed. The GUI saves showed the raw error; the
background writes (usage, quotas, caches) dropped theirs.

Now:
- appdir.Blocked() names the folder that keeps magpie from writing its
  config or cache folder: the folder itself, or the first one above it
  when it doesn't exist yet. Only folders inside the home folder are
  named. Unix only; on Windows it is "".
- /api/state carries configBlocked. A failed save whose error is a
  permission refusal comes back with code config_blocked. The window asks
  once a load, and again over the editor whose save failed. "Not now"
  returns to that editor as it was left. The tray panel doesn't ask.
- Repair (POST /api/config/repair): a folder the user owns gets u+rwx with
  no prompt. Another user's folder is chowned to the user, through the
  system's password prompt (update.AsAdmin, the updater's: osascript on a
  Mac, pkexec on Linux). That chown is not recursive for ~/.config, so the
  other apps' folders inside it stay as they are; magpie's own folder is
  chowned -R, since everything in it is magpie's. magpie web shows no
  prompt; it names the sudo command instead. Data never moves: every
  reader keeps the one path, so nothing splits.
- Words in en, zh, zh-TW, ja and de.
- The core-script budget goes up by 1,112 bytes (app.js stays under its
  own), with no room added.

Run (on mote via mote-run, at this tree, based on 17114b505):
- gofmt -l: empty. go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -timeout 45m ./internal/appdir ./internal/update
  ./internal/gui ./internal/proc: appdir, update and proc ok. gui fails
  only TestMainWindowCorners/macOS_26_SDK, which fails the same on
  origin/main 17114b505 on mote (open: #3949). TestCoreScriptBudget's
  first red led to the raise above, and it passes after.
- Red on old code: TestBlockedConfigIsRepairedInOneClick at 17114b505
  fails with "failed save = 400 {"error":"mkdir …/.config/magpie:
  permission denied"}; want code config_blocked". Its sandbox HOME has
  .config at chmod 555, which is the reporter's error. With the change it
  passes: the save names ~/.config, Repair returns 204, the same save goes
  through into ~/.config/magpie/providers.json, and state clears.
  TestRepairOfAnotherUsersFolderAsksAnAdmin fakes another owner and checks
  that the script is "chown <uid>:<gid> '<~/.config>' && chmod u+rwx",
  with no -R, that magpie's own folder gets -R, and that web shows no
  prompt.
- GUI: config-blocked.test.cjs, cli-behind.test.cjs and i18n-keys.test.cjs
  in Chromium and WebKit (en, zh), 12/12 ok. The new file checks the keys
  in zh, zh-TW, ja and de. It is red on the old assets (2/2 not ok in
  Chromium).

Not tried: a real root-owned ~/.config and the real osascript or pkexec
prompt (no sudo on the test boxes). The script runs through the updater's
AsAdmin, which already runs a privileged script. The TUI and CLI don't
offer the repair yet: #4287.
This commit is contained in:
yetone
2026-10-29 22:10:21 +08:00
parent 17114b505d
commit 5be581a1c3
11 changed files with 583 additions and 5 deletions
+92
View File
@@ -0,0 +1,92 @@
//go:build !windows
package appdir
import (
"errors"
"io/fs"
"os"
"path/filepath"
"syscall"
)
// Blocked is the folder that keeps magpie from writing its own files, or ""
// when it can: magpie's config or cache folder that this user can't write,
// or, while one of them isn't there yet, the folder it would be made in. A
// ~/.config that a command run under sudo made belongs to root, so magpie
// couldn't make ~/.config/magpie and every save failed with "permission
// denied" (YouWhat on Discord). Only a folder inside the home folder is
// named: one outside it (an XDG_CONFIG_HOME on a shared disk) isn't the
// user's to take back.
func Blocked() string {
h, err := Home()
if err != nil {
return ""
}
for _, dir := range []string{Config(), Cache()} {
if b := blockedAt(dir); b != "" && inside(b, h) {
return b
}
}
return ""
}
// blockedAt is the folder on the way to dir this user can't write, "" when
// dir is writable or can be made.
func blockedAt(dir string) string {
for p := filepath.Clean(dir); ; {
fi, err := os.Stat(p)
switch {
case err == nil:
if !fi.IsDir() || writable(p) {
return "" // a file in the way isn't a matter of owners
}
return p
case !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission):
return ""
}
up := filepath.Dir(p)
if up == p {
return ""
}
p = up
}
}
// writable says whether this user can make and change files in dir.
func writable(dir string) bool {
return syscall.Access(dir, 0x2|0x1) == nil // W_OK|X_OK
}
// inside says whether p is strictly inside dir.
func inside(p, dir string) bool {
rel, err := filepath.Rel(filepath.Clean(dir), filepath.Clean(p))
return err == nil && rel != "." && rel != ".." && !filepath.IsAbs(rel) && !startsUp(rel)
}
func startsUp(rel string) bool {
return len(rel) >= 3 && rel[:3] == ".."+string(filepath.Separator)
}
// Own says whether p is magpie's own folder or inside it: its config or
// cache folder. A repair may take back everything in it; anything above
// it is changed only by itself.
func Own(p string) bool {
for _, dir := range []string{Config(), Cache()} {
if c := filepath.Clean(p); c == filepath.Clean(dir) || inside(c, dir) {
return true
}
}
return false
}
// Mine says whether this user owns p, so its mode can be put right without
// an administrator.
func Mine(p string) bool {
fi, err := os.Stat(p)
if err != nil {
return false
}
st, ok := fi.Sys().(*syscall.Stat_t)
return ok && int(st.Uid) == os.Getuid()
}
+49
View File
@@ -0,0 +1,49 @@
//go:build !windows
package appdir
import (
"os"
"path/filepath"
"testing"
)
// A ~/.config the user can't write (sudo made it root's) is named as what
// blocks magpie; a writable one, or one not there yet under a writable
// home, isn't; and a folder outside the home folder is never named.
func TestBlockedNamesTheFolderInTheWay(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("root writes any folder")
}
UseExecutable("")
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", "")
t.Setenv("XDG_CACHE_HOME", "")
if b := Blocked(); b != "" {
t.Fatalf("Blocked = %q with nothing made yet, want empty", b)
}
cfg := filepath.Join(home, ".config")
os.Mkdir(cfg, 0o555)
t.Cleanup(func() { os.Chmod(cfg, 0o755) })
if b := Blocked(); b != cfg {
t.Fatalf("Blocked = %q, want %s", b, cfg)
}
if !Mine(cfg) {
t.Fatal("Mine = false for the user's own folder")
}
if Own(cfg) || !Own(filepath.Join(cfg, "magpie")) || !Own(filepath.Join(cfg, "magpie", "x")) {
t.Fatal("Own: only magpie's own folder and what is in it")
}
os.Chmod(cfg, 0o755)
if b := Blocked(); b != "" {
t.Fatalf("Blocked = %q once writable, want empty", b)
}
outside := t.TempDir()
os.Chmod(outside, 0o555)
t.Cleanup(func() { os.Chmod(outside, 0o755) })
t.Setenv("XDG_CONFIG_HOME", filepath.Join(outside, "cfg"))
if b := Blocked(); b != "" {
t.Fatalf("Blocked = %q outside the home folder, want empty: not the user's to take back", b)
}
}
+11
View File
@@ -0,0 +1,11 @@
package appdir
// Blocked is "" on Windows: a profile folder there isn't taken over by a
// command run as Administrator the way sudo leaves ~/.config root's.
func Blocked() string { return "" }
// Own says whether p is magpie's own folder or inside it.
func Own(p string) bool { return false }
// Mine says whether this user owns p.
func Mine(p string) bool { return false }
+15 -2
View File
@@ -287,8 +287,12 @@ type stateJSON struct {
// it's a copied file rather than the installer's link: a copy can't
// follow updates (#531's lesson). "" when it's the link or absent, or
// the advice was dismissed for this version.
CLIBehind string `json:"cliBehind,omitempty"`
Settings settings.Settings `json:"settings"`
CLIBehind string `json:"cliBehind,omitempty"`
// ConfigBlocked is the folder this user can't write that keeps magpie
// from saving its files (a ~/.config sudo left root's), which the
// window offers to make theirs again; "" when magpie can save
ConfigBlocked string `json:"configBlocked,omitempty"`
Settings settings.Settings `json:"settings"`
// FX is the dollar-to-yuan rate the cny currency choice shows costs at,
// here too (not only in settingsJSON) so a cost drawn before the reader
// ever opens Settings already converts, if cny was chosen last time.
@@ -1249,6 +1253,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
updateRoutes(mux, w)
whatsNewRoutes(mux)
cliBehindRoutes(mux)
configRepairRoutes(mux, !isWeb(w))
gatewayFixRoutes(mux)
gatewayModeRoutes(mux)
if !isWeb(w) {
@@ -2557,6 +2562,7 @@ func state() stateJSON {
}
s.Unlisted = unlistedModels()
s.CLIBehind = cliBehind()
s.ConfigBlocked = configBlocked()
for _, e := range provider.Served() {
if e.Group == "" {
s.Served++
@@ -2841,6 +2847,13 @@ func fail(rw http.ResponseWriter, err error) {
if errors.As(err, &noHandler) {
out["code"], out["app"], out["exe"], out["said"] = "no_link_handler", noHandler.App, noHandler.Exe, linkSaid[noHandler.Exe != ""]
}
// a save refused because a folder on the way to magpie's own isn't the
// user's: the window offers to make it theirs again
if permissionDenied(err) {
if b := configBlocked(); b != "" {
out["code"], out["blocked"] = "config_blocked", b
}
}
var noModels *agent.NoModelsError
if errors.As(err, &noModels) {
out["code"] = "no_models"
+37
View File
@@ -150,6 +150,11 @@ async function api(path, body, heads, signal) {
err.code = data.code;
err.message = t("None of magpie's models is left in {agent}'s model list: pick one under Model list → Pick, then connect {agent}", { agent: data.agent });
}
if (data?.code === "config_blocked") { // a folder magpie can't write: Repair offered
err.code = data.code;
err.message = t("magpie can't save into {path}: it belongs to another user", { path: data.blocked });
setTimeout(() => configBlockedAsk(data.blocked), 0);
}
if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language
if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go)
// an account the agent is signed in to, refused removal while it has
@@ -4251,6 +4256,7 @@ async function load(again) {
}
renderUpdateBadge();
cliBehindOnce();
if (state?.configBlocked && !configBlockedAsked && $("#modal").hidden) configBlockedAsk(state.configBlocked);
whatsNewOnce();
recoveredOnce();
}
@@ -4482,6 +4488,37 @@ function cliBehindOnce() {
$("#modal").classList.add("lib");
ok.focus({ preventScroll: true });
}
// configBlockedAsk: a folder on the way to magpie's own isn't the user's (a
// ~/.config sudo made root's, YouWhat): Repair makes it theirs, once a load
// and over the save it failed, which it goes back to
let configBlockedAsked = false;
function configBlockedAsk(path) {
if (mode === "panel" || !path || confirmAsk?.classList.contains("cfg-blocked")) return;
configBlockedAsked = true;
const m = $("#modal"), under = !m.hidden && !m.classList.contains("out") && !confirmAsk && m.firstElementChild.firstElementChild;
const ed = el("div", "editor cfg-blocked"), head = el("div", "ehead"), bar = el("div", "bar");
head.append(el("b", "", t("magpie can't save its settings")));
ed.append(head, el("p", "lib-confirm", t("{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.", { path })));
const later = el("button", "text", t("Not now")), go = el("button", "text primary", t("Repair"));
later.onclick = cancelAsk;
go.onclick = async (e) => {
e.stopPropagation();
go.disabled = true;
try {
if ((await api("config/repair", {}))?.canceled) return;
if (state) state.configBlocked = "";
closeConfirmAsk();
status(t("Repaired: magpie can save again"), "ok");
} catch (err) { status(err.message, "err", 12000); } finally { go.disabled = false; }
};
bar.append(el("span", "grow"), later, go);
ed.append(bar);
if (under) ed.back = () => openModal(under);
confirmAsk = ed;
openModal(ed);
m.classList.add("lib");
go.focus({ preventScroll: true });
}
async function whatsNewOnce() {
if (whatsNewAsked || mode === "panel" || document.hidden || !$("#modal").hidden) return;
whatsNewAsked = true;
+20
View File
@@ -1612,6 +1612,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "隐藏,直到又有已弃用的订阅登录",
"{names} can run on it again, with the same accounts.": "{names} 可以再次由它运行,账号不变。",
"Not now": "暂不",
"magpie can't save into {path}: it belongs to another user": "magpie 无法保存到 {path}:它属于另一个用户",
"magpie can't save its settings": "magpie 无法保存设置",
"{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} 属于另一个用户(常见于以前用 sudo 运行过某个命令),magpie 无法在那里保存供应商和设置。点「修复」把它改回归你所有;系统可能会要求输入密码。",
"Repair": "修复",
"Repaired: magpie can save again": "已修复:magpie 可以保存了",
"{user} is signed out": "{user} 已退出登录",
"Signed out": "已退出登录",
"Move {name} here": "把 {name} 迁到这里",
@@ -5712,6 +5717,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "隱藏,直到又有已棄用的訂閱登入",
"{names} can run on it again, with the same accounts.": "{names} 可以再次由它執行,帳號不變。",
"Not now": "暫不",
"magpie can't save into {path}: it belongs to another user": "magpie 無法儲存到 {path}:它屬於另一個使用者",
"magpie can't save its settings": "magpie 無法儲存設定",
"{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} 屬於另一個使用者(常見於以前用 sudo 執行過某個指令),magpie 無法在那裡儲存供應商和設定。按「修復」把它改回歸你所有;系統可能會要求輸入密碼。",
"Repair": "修復",
"Repaired: magpie can save again": "已修復:magpie 可以儲存了",
"{user} is signed out": "{user} 已退出登入",
"Signed out": "已退出登入",
"Move {name} here": "把 {name} 遷到這裡",
@@ -9789,6 +9799,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "別の非推奨サブスクリプションにサインインするまで非表示にする",
"{names} can run on it again, with the same accounts.": "{names} は同じアカウントのまま、再びこれで動作できます。",
"Not now": "後で",
"magpie can't save into {path}: it belongs to another user": "magpie は {path} に保存できません:別のユーザーのものです",
"magpie can't save its settings": "magpie が設定を保存できません",
"{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} は別のユーザーのものです(sudo でコマンドを実行した後によくあります)。そのため magpie はプロバイダーや設定をそこに保存できません。「修復」であなたのものに戻します。システムがパスワードを求めることがあります。",
"Repair": "修復",
"Repaired: magpie can save again": "修復しました:magpie は保存できます",
"{user} is signed out": "{user} はサインアウトしました",
"Signed out": "サインアウトしました",
"Move {name} here": "{name} をここへ移行",
@@ -13896,6 +13911,11 @@ const I18N = {
"Hide this until another deprecated subscription is signed in": "Ausblenden, bis ein weiteres veraltetes Abo angemeldet wird",
"{names} can run on it again, with the same accounts.": "{names} kann wieder darüber laufen, mit denselben Konten.",
"Not now": "Nicht jetzt",
"magpie can't save into {path}: it belongs to another user": "magpie kann nicht in {path} speichern: Der Ordner gehört einem anderen Benutzer",
"magpie can't save its settings": "magpie kann seine Einstellungen nicht speichern",
"{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.": "{path} gehört einem anderen Benutzer, oft nachdem ein Befehl mit sudo ausgeführt wurde, daher kann magpie dort keine Anbieter oder Einstellungen speichern. „Reparieren“ macht ihn wieder zu Ihrem; das System fragt eventuell nach Ihrem Passwort.",
"Repair": "Reparieren",
"Repaired: magpie can save again": "Repariert: magpie kann wieder speichern",
"{user} is signed out": "{user} ist abgemeldet",
"Signed out": "Abgemeldet",
"Move {name} here": "{name} hierher umziehen",
+108
View File
@@ -0,0 +1,108 @@
package gui
import (
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"strings"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/update"
)
// A folder on the way to magpie's own that this user can't write — most
// often a ~/.config a command run under sudo once made, so it belongs to
// root — fails every save with "permission denied" (YouWhat on Discord:
// adding a custom provider said "mkdir ~/.config/magpie: permission
// denied"). magpie's files stay where every reader looks for them; the
// window offers to make that folder the user's again, with one click and
// the system's password prompt. Only that folder changes: ~/.config gets
// its owner back and nothing in it does, since the other apps' folders
// there are theirs, and magpie's own folder, when it is the one taken, is
// taken back whole.
// configBlocked is the folder that keeps magpie from saving, as the window
// names it, or "".
func configBlocked() string {
if b := appdir.Blocked(); b != "" {
return tilde(b)
}
return ""
}
// permissionDenied says whether err is the system refusing a write.
func permissionDenied(err error) bool {
if errors.Is(err, fs.ErrPermission) {
return true
}
msg := err.Error()
return strings.Contains(msg, "permission denied") || strings.Contains(msg, "operation not permitted")
}
// asAdmin runs a script as root after the system's password prompt; tests
// stand in for it.
var asAdmin = update.AsAdmin
// mine says whether this user owns a folder; tests stand in for it.
var mine = appdir.Mine
// errRepairCanceled is the password prompt dismissed.
var errRepairCanceled = update.ErrCanceled
// repairConfig makes the folder that keeps magpie from saving this user's
// again, then makes magpie's folders. prompt is whether the system's
// password prompt can be shown: not to magpie web's page on another
// device, where no one sits at this computer's screen to answer it.
func repairConfig(prompt bool) error {
if b := appdir.Blocked(); b != "" {
if mine(b) {
// the user's own, only its mode is wrong: no password needed
fi, err := os.Stat(b)
if err != nil {
return err
}
if err := os.Chmod(b, fi.Mode().Perm()|0o700); err != nil {
return err
}
} else {
recurse := ""
if appdir.Own(b) {
recurse = "-R " // magpie's own folder: everything in it is magpie's
}
q := update.ShellQuote(b)
script := fmt.Sprintf("chown %s%d:%d %s && chmod u+rwx %s", recurse, os.Getuid(), os.Getgid(), q, q)
if !prompt || !canElevate() {
return fmt.Errorf("%s belongs to another user, and no administrator prompt can be shown here: run `sudo %s` in a terminal", b, script)
}
if err := asAdmin("magpie needs "+b+" to be yours again to save its settings.", script); err != nil {
return err
}
}
}
for _, dir := range []string{appdir.Config(), appdir.Cache()} {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
if b := appdir.Blocked(); b != "" {
return fmt.Errorf("%s still can't be written", b)
}
return nil
}
// configRepairRoutes serves the window's Repair.
func configRepairRoutes(mux *http.ServeMux, prompt bool) {
mux.HandleFunc("POST /api/config/repair", func(rw http.ResponseWriter, r *http.Request) {
if err := repairConfig(prompt); err != nil {
if errors.Is(err, errRepairCanceled) {
writeJSON(rw, map[string]bool{"canceled": true})
return
}
fail(rw, err)
return
}
rw.WriteHeader(http.StatusNoContent)
})
}
+133
View File
@@ -0,0 +1,133 @@
//go:build !windows
package gui
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// YouWhat on Discord: ~/.config wasn't the user's (sudo had made it), so
// adding a custom provider failed with "mkdir ~/.config/magpie: permission
// denied" and nothing said what to do. The failed save now names the
// folder (config_blocked), /api/state names it for the window's Repair,
// and Repair makes it writable again, after which the same save goes
// through, into the folder every reader looks in.
func TestBlockedConfigIsRepairedInOneClick(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("root writes any folder")
}
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
dotConfig := filepath.Join(home, ".config")
if err := os.Mkdir(dotConfig, 0o555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chmod(dotConfig, 0o755) })
h := Handler(nil, nil)
call := func(method, path, body string) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body)))
return rec.Code, rec.Body.String()
}
const add = `{"id":"mine","name":"Mine","chat":"http://127.0.0.1:1/v1","key":"sk-a","models":["m1"],"new":true}`
code, body := call("POST", "/api/provider/save", add)
var failed struct{ Error, Code, Blocked string }
json.Unmarshal([]byte(body), &failed)
if code == 200 {
t.Fatalf("save into a folder the user can't write went through: %s", body)
}
if failed.Code != "config_blocked" || failed.Blocked != "~/.config" {
t.Fatalf("failed save = %d %s; want code config_blocked naming ~/.config, so the window can offer Repair", code, body)
}
_, body = call("GET", "/api/state", "")
var s struct {
ConfigBlocked string `json:"configBlocked"`
}
json.Unmarshal([]byte(body), &s)
if s.ConfigBlocked != "~/.config" {
t.Fatalf("state configBlocked = %q, want ~/.config", s.ConfigBlocked)
}
if code, body := call("POST", "/api/config/repair", "{}"); code != 204 {
t.Fatalf("repair: %d %s", code, body)
}
if code, body := call("POST", "/api/provider/save", add); code != 200 {
t.Fatalf("save after repair: %d %s", code, body)
}
if _, err := os.Stat(filepath.Join(dotConfig, "magpie", "providers.json")); err != nil {
t.Fatalf("the provider isn't in ~/.config/magpie, where every reader looks: %v", err)
}
_, body = call("GET", "/api/state", "")
s.ConfigBlocked = ""
json.Unmarshal([]byte(body), &s)
if s.ConfigBlocked != "" {
t.Fatalf("state configBlocked = %q after repair, want empty", s.ConfigBlocked)
}
}
// A folder another user owns (root, after sudo) can't be chmodded by the
// user: Repair asks the system's password prompt to give that folder alone
// back, not everything under it, while magpie's own folder is given back
// whole. Magpie web's page, on another device, never shows the prompt.
func TestRepairOfAnotherUsersFolderAsksAnAdmin(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("root writes any folder")
}
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
dotConfig := filepath.Join(home, ".config")
if err := os.Mkdir(dotConfig, 0o555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chmod(dotConfig, 0o755) })
wasAdmin, wasElevate, wasMine := asAdmin, canElevate, mine
t.Cleanup(func() { asAdmin, canElevate, mine = wasAdmin, wasElevate, wasMine })
mine = func(string) bool { return false } // as if root's
canElevate = func() bool { return true }
var scripts []string
asAdmin = func(why, script string) error {
scripts = append(scripts, script)
return os.Chmod(dotConfig, 0o755) // what chown + chmod u+rwx would leave
}
if err := repairConfig(true); err != nil {
t.Fatal(err)
}
if len(scripts) != 1 || strings.Contains(scripts[0], "-R") || !strings.Contains(scripts[0], "'"+dotConfig+"'") {
t.Fatalf("scripts = %q; want one chown of %s alone, not -R over other apps' folders", scripts, dotConfig)
}
if _, err := os.Stat(filepath.Join(dotConfig, "magpie")); err != nil {
t.Fatalf("magpie's folder not made after repair: %v", err)
}
// magpie's own folder taken: given back whole
own := filepath.Join(dotConfig, "magpie")
os.Chmod(own, 0o555)
t.Cleanup(func() { os.Chmod(own, 0o755) })
scripts = nil
asAdmin = func(why, script string) error { scripts = append(scripts, script); return os.Chmod(own, 0o755) }
if err := repairConfig(true); err != nil {
t.Fatal(err)
}
if len(scripts) != 1 || !strings.Contains(scripts[0], "chown -R ") {
t.Fatalf("scripts = %q; want magpie's own folder given back whole", scripts)
}
// magpie web: no prompt, the command to run instead
os.Chmod(own, 0o555)
scripts = nil
err := repairConfig(false)
if err == nil || len(scripts) != 0 || !strings.Contains(err.Error(), "sudo chown") {
t.Fatalf("web repair = %v, scripts %q; want no prompt and the command named", err, scripts)
}
}
File diff suppressed because one or more lines are too long
+108
View File
@@ -0,0 +1,108 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// YouWhat on Discord: ~/.config wasn't the user's (a command run with sudo
// had made it root's), so adding a custom provider failed with "mkdir
// ~/.config/magpie: permission denied". /api/state names the folder that
// blocks magpie (configBlocked), and the window asks once a load to Repair
// it, which POSTs /api/config/repair. A save refused for it (code
// config_blocked) says so in the reader's language and asks again, over
// the editor whose save failed; Not now goes back to that editor as it was
// left. The panel is too small for a dialog. No backend, the API is faked.
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 assets = path.resolve(__dirname, "../assets");
const KEYS = [
"magpie can't save into {path}: it belongs to another user",
"magpie can't save its settings",
"{path} belongs to another user, often after a command was run with sudo, so magpie can't save providers or settings there. Repair makes it yours again; the system may ask for your password.",
"Repair",
"Repaired: magpie can save again",
];
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
function server(lang, calls) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ status, json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") {
const s = { agents: [], profiles: [], settings: { lang, theme: "light" } };
if (calls.blocked) s.configBlocked = "~/.config";
return json(s);
}
if (url.pathname === "/api/config/repair") { calls.repair++; calls.blocked = false; return route.fulfill({ status: 204 }); }
if (url.pathname === "/api/test-save") return json({ error: "mkdir /Users/u/.config/magpie: permission denied", code: "config_blocked", blocked: "~/.config" }, 400);
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/update" || url.pathname === "/api/drift") return json({});
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a folder magpie can't write is repaired in one click`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(async () => { await browser.close(); });
const errors = [];
const open = async (calls, url = "http://magpie.test/", width = 900) => {
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, calls));
await page.goto(url);
return page;
};
const tr = (page, k) => page.evaluate(([k, lang]) => (lang === "en" ? k : I18N[lang][k]), [k, lang]);
// blocked at load: asked, and Repair repairs
const calls = { blocked: true, repair: 0 };
const page = await open(calls);
const dialog = page.locator("#modal:not([hidden])");
await dialog.waitFor();
assert.match(await dialog.textContent(), /~\/\.config/, "the dialog names the folder");
assert.ok((await dialog.textContent()).includes(await tr(page, "magpie can't save its settings")));
await dialog.getByRole("button", { name: await tr(page, "Repair"), exact: true }).click();
await page.waitForFunction(() => document.querySelector("#modal").hidden);
assert.equal(calls.repair, 1, "Repair reached the API");
assert.equal(await page.locator("#status").textContent(), await tr(page, "Repaired: magpie can save again"));
// a save refused for it: said in the reader's language, asked over
// the editor, and Not now goes back to that editor as it was
const p2 = await open({ blocked: false, repair: 0 });
await p2.waitForTimeout(300);
assert.ok(await p2.locator("#modal").evaluate((m) => m.hidden), "nothing asked while magpie can save");
const said = await p2.evaluate(async () => {
const ed = el("div", "editor");
const head = el("div", "ehead"); head.append(el("b", "", "Add provider"));
const input = el("input"); input.id = "typed"; input.value = "my provider";
ed.append(head, input);
openModal(ed);
try { await api("test-save", {}); } catch (e) { return e.message; }
return "";
});
assert.equal(said, (await tr(p2, "magpie can't save into {path}: it belongs to another user")).replace("{path}", "~/.config"));
const ask = p2.locator("#modal .cfg-blocked");
await ask.waitFor();
await ask.getByRole("button", { name: await tr(p2, "Not now"), exact: true }).click();
await p2.locator("#modal #typed").waitFor();
assert.equal(await p2.locator("#modal #typed").inputValue(), "my provider", "back to the editor as it was left");
// the panel stays quiet
const panel = await open({ blocked: true, repair: 0 }, "http://magpie.test/?mode=panel", 380);
await panel.waitForTimeout(500);
assert.ok(await panel.locator("#modal").evaluate((m) => m.hidden), "the panel stays quiet");
const missing = await page.evaluate(([ks, langs]) => langs.filter((l) => l !== "en").flatMap((l) => ks.filter((k) => !I18N[l][k]).map((k) => l + ": " + k)), [KEYS, LANGS]);
assert.deepEqual(missing, [], "every language has the dialog's words");
assert.deepEqual(errors, []);
});
}
}
+9 -2
View File
@@ -56,12 +56,16 @@ var run = func(name string, args ...string) ([]byte, error) {
}
// asAdmin runs a shell script as root, after the system's password prompt.
func asAdmin(script string) error {
func asAdmin(script string) error { return AsAdmin("magpie is updating itself.", script) }
// AsAdmin runs a shell script as root, after the system's password prompt,
// which says why (on a Mac). ErrCanceled is the prompt dismissed.
func AsAdmin(why, script string) error {
var out []byte
var err error
switch runtime.GOOS {
case "darwin":
out, err = run("osascript", "-e", `do shell script "`+appleString(script)+`" with prompt "magpie is updating itself." with administrator privileges`)
out, err = run("osascript", "-e", `do shell script "`+appleString(script)+`" with prompt "`+appleString(why)+`" with administrator privileges`)
if err != nil && strings.Contains(string(out), "(-128)") {
return ErrCanceled
}
@@ -88,6 +92,9 @@ func swapScript(staged, bundle, old string) string {
return "rm -rf " + o + " && mv " + b + " " + o + " && if mv " + s + " " + b + "; then rm -rf " + o + "; else mv " + o + " " + b + "; exit 1; fi"
}
// ShellQuote quotes s for /bin/sh.
func ShellQuote(s string) string { return shellQuote(s) }
// shellQuote quotes s for /bin/sh.
func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }