From 84ef25805e58f7979293d9daa3cedb096ed1cae8 Mon Sep 17 00:00:00 2001 From: Arvak Date: Sun, 27 Sep 2026 17:26:32 +0800 Subject: [PATCH] =?UTF-8?q?web:=20MAGPIE=5FWEB=5FKEY=20keeps=20the=20page'?= =?UTF-8?q?s=20key=20across=20runs=20=E2=80=94=20for=20magpie=20web=20kept?= =?UTF-8?q?=20running=20as=20a=20service,=20where=20a=20new=20key=20each?= =?UTF-8?q?=20start=20signs=20every=20browser=20out;=20with=20it=20the=20c?= =?UTF-8?q?ookie=20outlives=20the=20browser=20session=20too=20(400=20days,?= =?UTF-8?q?=20Chrome's=20most).=20Unset,=20each=20run=20makes=20its=20own?= =?UTF-8?q?=20key=20in=20a=20session=20cookie,=20as=20before.=20A=20key=20?= =?UTF-8?q?under=2016=20characters=20is=20refused.=20(#109)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + internal/gui/web.go | 49 +++++++++++++++++++++++++++++++++------- internal/gui/web_test.go | 32 ++++++++++++++++++++++++-- web_cli.go | 7 +++++- 4 files changed, 78 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d7f0bca49..fa81c29cd 100644 --- a/README.md +++ b/README.md @@ -350,6 +350,7 @@ magpie # open the app: a window plus the menu bar icon magpie tray # menu bar icon only (use this in your login items) magpie tui # the same thing, in the terminal magpie web # the app's window in a browser (WSL, a server over SSH); --lan, --addr, --no-open + # (a new key each run; MAGPIE_WEB_KEY keeps one, for a page run as a service) magpie ls # list every agent and its current settings magpie claude opus # set a model (agent names accept prefixes: cc, oc, gem …) magpie codex gpt-5.6-sol diff --git a/internal/gui/web.go b/internal/gui/web.go index 1f0fa7a89..b3a0d1af0 100644 --- a/internal/gui/web.go +++ b/internal/gui/web.go @@ -5,8 +5,11 @@ import ( "crypto/subtle" "encoding/hex" "errors" + "fmt" "net" "net/http" + "net/url" + "os" "sync" "time" ) @@ -43,13 +46,18 @@ type Web struct { // send with a POST (every change is one), so neither a page elsewhere nor // anyone else on the network reaches the settings and keys behind it. func StartWeb(addr string) (*Web, error) { + key, fixed, err := webKey() + if err != nil { + return nil, err + } + var keep time.Duration + if fixed { + keep = webCookieAge + } ln, err := net.Listen("tcp", addr) if err != nil { return nil, err } - b := make([]byte, 16) - rand.Read(b) - key := hex.EncodeToString(b) w := &Web{Addr: ln.Addr().String(), quit: make(chan struct{})} host, port, _ := net.SplitHostPort(w.Addr) if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() { @@ -57,9 +65,9 @@ func StartWeb(addr string) (*Web, error) { } var once sync.Once quit := func() { once.Do(func() { close(w.quit) }) } - w.Link = "http://" + net.JoinHostPort(host, port) + "/?k=" + key + w.Link = "http://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key) w.srv = &http.Server{ - Handler: webGuard("magpie_web_"+port, key, Handler(webHost{quit}, startBackend())), + Handler: webGuard("magpie_web_"+port, key, keep, Handler(webHost{quit}, startBackend())), ReadHeaderTimeout: 30 * time.Second, } go w.srv.Serve(ln) @@ -73,9 +81,34 @@ func (w *Web) Wait() { w.srv.Close() } +// webKeyMin is the shortest MAGPIE_WEB_KEY taken: it is all that stands +// between the network and the keys behind the page. +const webKeyMin = 16 + +// webCookieAge is how long a browser keeps a fixed key's cookie (the most +// Chrome allows); a run's own key lives in a cookie that goes with the +// browser session, as the key goes with the run. +const webCookieAge = 400 * 24 * time.Hour + +// webKey is the key the link carries: a new one each run, unless +// MAGPIE_WEB_KEY names one — for a page kept running as a service, which +// browsers then stay signed in to across restarts. fixed says which. +func webKey() (key string, fixed bool, err error) { + if k := os.Getenv("MAGPIE_WEB_KEY"); k != "" { + if len(k) < webKeyMin { + return "", false, fmt.Errorf("MAGPIE_WEB_KEY is %d characters; it needs at least %d", len(k), webKeyMin) + } + return k, true, nil + } + b := make([]byte, 16) + rand.Read(b) + return hex.EncodeToString(b), false, nil +} + // webGuard lets through requests with the key: in the link's k, which it -// trades for a cookie and a clean address, or in that cookie. -func webGuard(cookie, key string, next http.Handler) http.Handler { +// trades for a cookie (kept for keep, or the browser session when 0) and +// a clean address, or in that cookie. +func webGuard(cookie, key string, keep time.Duration, next http.Handler) http.Handler { same := func(v string) bool { return subtle.ConstantTimeCompare([]byte(v), []byte(key)) == 1 } return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { if q := r.URL.Query(); q.Has("k") { @@ -83,7 +116,7 @@ func webGuard(cookie, key string, next http.Handler) http.Handler { http.Error(rw, "this link's key is not this magpie web's: use the link it printed when it started", http.StatusUnauthorized) return } - http.SetCookie(rw, &http.Cookie{Name: cookie, Value: key, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode}) + http.SetCookie(rw, &http.Cookie{Name: cookie, Value: key, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: int(keep / time.Second)}) q.Del("k") u := *r.URL u.RawQuery = q.Encode() diff --git a/internal/gui/web_test.go b/internal/gui/web_test.go index d9a20561c..0d449e75a 100644 --- a/internal/gui/web_test.go +++ b/internal/gui/web_test.go @@ -4,10 +4,11 @@ import ( "net/http" "net/http/httptest" "testing" + "time" ) func TestWebGuard(t *testing.T) { - h := webGuard("c", "key", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusTeapot) })) + h := webGuard("c", "key", 0, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusTeapot) })) do := func(r *http.Request) *httptest.ResponseRecorder { rec := httptest.NewRecorder() h.ServeHTTP(rec, r) @@ -24,7 +25,7 @@ func TestWebGuard(t *testing.T) { t.Fatalf("link: %d %q", rec.Code, rec.Header().Get("Location")) } ck := rec.Result().Cookies() - if len(ck) != 1 || ck[0].Value != "key" || !ck[0].HttpOnly || ck[0].SameSite != http.SameSiteLaxMode { + if len(ck) != 1 || ck[0].Value != "key" || !ck[0].HttpOnly || ck[0].SameSite != http.SameSiteLaxMode || ck[0].MaxAge != 0 { t.Fatalf("cookie: %+v", ck) } r := httptest.NewRequest("POST", "/api/settings", nil) @@ -38,3 +39,30 @@ func TestWebGuard(t *testing.T) { t.Fatalf("wrong cookie: %d", c) } } + +func TestWebKey(t *testing.T) { + t.Setenv("MAGPIE_WEB_KEY", "") + a, fixed, err := webKey() + if err != nil || fixed || len(a) != 32 { + t.Fatalf("a run's own key: %q %v %v", a, fixed, err) + } + if b, _, _ := webKey(); b == a { + t.Fatal("two runs got one key") + } + t.Setenv("MAGPIE_WEB_KEY", "short") + if _, _, err := webKey(); err == nil { + t.Fatal("a short MAGPIE_WEB_KEY was taken") + } + t.Setenv("MAGPIE_WEB_KEY", "0123456789abcdef-kept") + if k, fixed, err := webKey(); err != nil || !fixed || k != "0123456789abcdef-kept" { + t.Fatalf("MAGPIE_WEB_KEY: %q %v %v", k, fixed, err) + } + + // a fixed key's cookie outlives the browser + h := webGuard("c", "0123456789abcdef-kept", webCookieAge, http.NotFoundHandler()) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", "/?k=0123456789abcdef-kept", nil)) + if ck := rec.Result().Cookies(); len(ck) != 1 || time.Duration(ck[0].MaxAge)*time.Second != webCookieAge { + t.Fatalf("fixed key's cookie: %+v", ck) + } +} diff --git a/web_cli.go b/web_cli.go index 95a0b2e61..cb7da71c0 100644 --- a/web_cli.go +++ b/web_cli.go @@ -3,6 +3,7 @@ package main import ( "fmt" "net" + "os" "strings" "github.com/yetone/magpie/internal/gateway" @@ -49,7 +50,11 @@ func webCmd(args []string) error { } fmt.Println(amber.Render("!"), "anyone with the link can change magpie and see its keys, and the network carries it unencrypted") } - fmt.Println(muted.Render(" the link carries this run's key · gateway " + gateway.URL() + " · Ctrl-C to stop")) + carries := "this run's key" + if os.Getenv("MAGPIE_WEB_KEY") != "" { + carries = "MAGPIE_WEB_KEY" + } + fmt.Println(muted.Render(" the link carries " + carries + " · gateway " + gateway.URL() + " · Ctrl-C to stop")) if open { openInBrowser(w.Link) }