From 59e4f417b22ed604f4e9f98e2e17b7840333ebc1 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 27 Sep 2026 16:21:26 +0800 Subject: [PATCH] =?UTF-8?q?web:=20magpie=20web=20serves=20the=20app's=20wi?= =?UTF-8?q?ndow=20to=20a=20browser,=20with=20the=20gateway=20beside=20it?= =?UTF-8?q?=20=E2=80=94=20for=20a=20computer=20that=20can't=20show=20the?= =?UTF-8?q?=20app:=20no=20desktop,=20WSL,=20a=20server=20over=20SSH,=20or?= =?UTF-8?q?=20the=20CLI-only=20build,=20which=20now=20carries=20the=20page?= =?UTF-8?q?=20too=20(what=20of=20the=20app=20needs=20Wails=20is=20left=20o?= =?UTF-8?q?ut=20of=20nogui=20builds).=20Every=20request=20needs=20this=20r?= =?UTF-8?q?un's=20key,=20which=20the=20printed=20link=20carries=20and=20tr?= =?UTF-8?q?ades=20for=20a=20cookie=20other=20sites'=20pages=20can't=20send?= =?UTF-8?q?=20with=20a=20POST;=20--lan=20serves=20it=20on=20the=20network?= =?UTF-8?q?=20too,=20with=20a=20warning,=20--addr=20elsewhere,=20--no-open?= =?UTF-8?q?=20leaves=20the=20browser=20shut.=20In=20the=20browser=20the=20?= =?UTF-8?q?page=20opens=20links=20and=20sign-ins=20itself,=20names=20a=20f?= =?UTF-8?q?older=20instead=20of=20opening=20it,=20and=20leaves=20out=20the?= =?UTF-8?q?=20tray,=20the=20Dock=20and=20open=20at=20login.=20Tested=20fro?= =?UTF-8?q?m=20a=20nogui=20build=20in=20a=20sandbox:=20no=20key,=20a=20wro?= =?UTF-8?q?ng=20key=20and=20a=20cookieless=20POST=20are=20refused;=20with?= =?UTF-8?q?=20the=20link=20Agents,=20Providers=20and=20Settings=20load=20a?= =?UTF-8?q?nd=20a=20setting=20saves.=20Issue=20#102?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + internal/gui/api.go | 2 +- internal/gui/app.go | 81 +---------------------- internal/gui/assets/app.js | 13 +++- internal/gui/backend.go | 87 ++++++++++++++++++++++++ internal/gui/dev_off.go | 1 - internal/gui/devshell_off.go | 7 ++ internal/gui/folder_other.go | 2 +- internal/gui/folder_windows.go | 2 + internal/gui/glide_darwin.go | 2 + internal/gui/glide_other.go | 2 +- internal/gui/titlebar_gtk3.go | 2 +- internal/gui/titlebar_gtk4.go | 2 +- internal/gui/titlebar_other.go | 2 +- internal/gui/web.go | 117 +++++++++++++++++++++++++++++++++ internal/gui/web_test.go | 40 +++++++++++ main.go | 4 ++ web_cli.go | 58 ++++++++++++++++ 18 files changed, 336 insertions(+), 89 deletions(-) create mode 100644 internal/gui/backend.go create mode 100644 internal/gui/devshell_off.go create mode 100644 internal/gui/web.go create mode 100644 internal/gui/web_test.go create mode 100644 web_cli.go diff --git a/README.md b/README.md index 225c363fd..2dff81442 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ gateway translates. 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 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/api.go b/internal/gui/api.go index bff9dd728..97ffc1ee7 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -156,7 +156,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // they came only with the settings, so the tabs showed English first mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) { s := settings.Load() - b, _ := json.Marshal(map[string]string{"lang": s.Lang, "theme": s.Theme}) + b, _ := json.Marshal(map[string]any{"lang": s.Lang, "theme": s.Theme, "web": isWeb(w)}) rw.Header().Set("Content-Type", "text/javascript; charset=utf-8") rw.Header().Set("Cache-Control", "no-store") rw.Write(append(append([]byte("window.bootPrefs = "), b...), ";\n"...)) diff --git a/internal/gui/app.go b/internal/gui/app.go index a266a933e..840f80ec2 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -1,7 +1,8 @@ +//go:build !nogui + package gui import ( - "context" "crypto/sha256" _ "embed" "encoding/hex" @@ -16,11 +17,7 @@ import ( "github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/events" - "github.com/yetone/magpie/internal/agent" - "github.com/yetone/magpie/internal/catalog" - "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/library" - "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/update" ) @@ -324,80 +321,6 @@ func Run(version string, showMain bool, link string) error { return h.app.Run() } -// served is the gateway this process serves, nil while another magpie -// has it. -var served atomic.Pointer[gateway.Server] - -// startBackend starts what serves the page and the agents: the gateway, -// unless another magpie has it (then that one serves and this one only -// shows its status, and gw is nil — until that one is gone: a magpie left -// running from before an update, a magpie serve in a terminal), and the -// model lists kept warm. -func startBackend() (gw *gateway.Server) { - gw = serveGateway() - go watchGateway() - // Model lists are fetched, never compiled in: whatever the agents can see - // comes from the models.dev catalog plus each vendor's own /models answer. - // Keep both halves warm without making the user click anything. - go func() { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - if catalog.Stale() { - if err := catalog.Sync(ctx); err != nil { - log.Println("catalog:", err) - } - } - cancel() - // A signed-in agent's list exists only at the vendor; fill it in the - // first time so the picker never shows a stale snapshot. - for _, p := range provider.All() { - if p.Account == nil || !p.Ready() { - continue - } - if _, ok := p.Fetched(); ok { - continue - } - c, cancel := context.WithTimeout(context.Background(), 20*time.Second) - if _, err := p.Fetch(c); err != nil { - log.Println(p.ID + ": " + err.Error()) - } - cancel() - } - // lists an older magpie wrote into agents' files, without what - // it has learnt since (context windows, providers added) - agent.SyncCatalog() - }() - return gw -} - -var gatewayWatch = 15 * time.Second - -// watchGateway takes the gateway up once the magpie that had it is gone. -func watchGateway() { - for { - time.Sleep(gatewayWatch) - if served.Load() == nil && !gateway.Running() { - serveGateway() - } - } -} - -// serveGateway starts the gateway here when no magpie has it: the one -// started, or nil. -func serveGateway() *gateway.Server { - if gateway.Running() { - return nil - } - gw := gateway.New() - served.Store(gw) - go func() { - if err := gw.ListenAndServe(context.Background()); err != nil { - log.Println("gateway:", err) - served.CompareAndSwap(gw, nil) // another took the port first - } - }() - return gw -} - // singleInstance makes a second launch hand over to this one, off the Mac. // The id covers the executable and the config dir, so a build elsewhere or // a sandboxed HOME runs on its own. diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c44bb36e4..00e5f0e3e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -4,11 +4,15 @@ const $$ = (s) => document.querySelectorAll(s); const params = new URLSearchParams(location.search); const mode = params.get("mode") || "window"; document.body.classList.add(mode); +// `magpie web`: the page in a browser tab, with no window of the app's +// around it — it opens links itself, and what is the desktop's is left out +const web = !!window.bootPrefs?.web; +if (web) document.body.classList.add("web"); // The Mac window draws its title bar inside the page (the traffic lights); // on Linux the page's header is the whole title bar (plainTitlebar), so it // has the name, the close button and a double-click to maximise. -if (/^Mac/.test(navigator.platform)) document.body.classList.add("mac"); -if (/^Linux/.test(navigator.platform)) document.body.classList.add("linux"); +if (!web && /^Mac/.test(navigator.platform)) document.body.classList.add("mac"); +if (!web && /^Linux/.test(navigator.platform)) document.body.classList.add("linux"); // The window is dragged by its header, and only where the header says so // (--wails-draggable), so the tabs and buttons in it stay plain clicks. // Outside the app — a browser on the gateway's page — there is no runtime. @@ -50,6 +54,7 @@ const favoriteKey = (o) => o.ref || o.value; const isFavorite = (o) => modelFavorites.has(favoriteKey(o)) || modelFavorites.has(o.value); async function api(path, body) { + if (web && path === "open") { window.open(body.url, "_blank", "noopener"); return null; } const res = await fetch("/api/" + path, { method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json" }, @@ -3080,6 +3085,7 @@ async function startSignIn(agent, risky) { renderProviders(); try { signing = await api("signin", { agent }); + if (web && signing.url) api("open", { url: signing.url }); renderProviders(); followSignIn(signing.id); } catch (e) { @@ -3968,8 +3974,9 @@ function renderSettings() { $("#themeSegs").replaceChildren(segs(THEMES.map(([id, name]) => [id, t(name)]), s.theme, (theme) => savePrefs({ ...keep, theme }))); $("#langSegs").replaceChildren(segs(LOCALES.map(([id, name]) => [id, t(name)]), s.lang, (lang) => savePrefs({ ...keep, lang }))); $("#traySegs").replaceChildren(segs(TRAYS.map(([id, name]) => [id, t(name)]), s.tray || "panel", (tray) => savePrefs({ ...keep, tray }))); - // the Dock is the Mac's + // the Dock is the Mac's; the tray and the login item the app's $("#dockRow").hidden = !document.body.classList.contains("mac"); + $("#traySegs").parentElement.hidden = $("#loginSegs").parentElement.hidden = web; $("#dockSegs").replaceChildren(segs([["off", t("Hide")], ["window", t("With window")], ["on", t("Show")]], s.dock ? "on" : s.dockWindow ? "window" : "off", (v) => savePrefs({ ...keep, dock: v === "on", dockWindow: v === "window" }))); // the system's record, set on its own, not with the other choices diff --git a/internal/gui/backend.go b/internal/gui/backend.go new file mode 100644 index 000000000..54f1b42fd --- /dev/null +++ b/internal/gui/backend.go @@ -0,0 +1,87 @@ +package gui + +import ( + "context" + "log" + "sync/atomic" + "time" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" +) + +// served is the gateway this process serves, nil while another magpie +// has it. +var served atomic.Pointer[gateway.Server] + +// startBackend starts what serves the page and the agents: the gateway, +// unless another magpie has it (then that one serves and this one only +// shows its status, and gw is nil — until that one is gone: a magpie left +// running from before an update, a magpie serve in a terminal), and the +// model lists kept warm. +func startBackend() (gw *gateway.Server) { + gw = serveGateway() + go watchGateway() + // Model lists are fetched, never compiled in: whatever the agents can see + // comes from the models.dev catalog plus each vendor's own /models answer. + // Keep both halves warm without making the user click anything. + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + if catalog.Stale() { + if err := catalog.Sync(ctx); err != nil { + log.Println("catalog:", err) + } + } + cancel() + // A signed-in agent's list exists only at the vendor; fill it in the + // first time so the picker never shows a stale snapshot. + for _, p := range provider.All() { + if p.Account == nil || !p.Ready() { + continue + } + if _, ok := p.Fetched(); ok { + continue + } + c, cancel := context.WithTimeout(context.Background(), 20*time.Second) + if _, err := p.Fetch(c); err != nil { + log.Println(p.ID + ": " + err.Error()) + } + cancel() + } + // lists an older magpie wrote into agents' files, without what + // it has learnt since (context windows, providers added) + agent.SyncCatalog() + }() + return gw +} + +var gatewayWatch = 15 * time.Second + +// watchGateway takes the gateway up once the magpie that had it is gone. +func watchGateway() { + for { + time.Sleep(gatewayWatch) + if served.Load() == nil && !gateway.Running() { + serveGateway() + } + } +} + +// serveGateway starts the gateway here when no magpie has it: the one +// started, or nil. +func serveGateway() *gateway.Server { + if gateway.Running() { + return nil + } + gw := gateway.New() + served.Store(gw) + go func() { + if err := gw.ListenAndServe(context.Background()); err != nil { + log.Println("gateway:", err) + served.CompareAndSwap(gw, nil) // another took the port first + } + }() + return gw +} diff --git a/internal/gui/dev_off.go b/internal/gui/dev_off.go index f2e2ac468..3bd00a4e2 100644 --- a/internal/gui/dev_off.go +++ b/internal/gui/dev_off.go @@ -14,5 +14,4 @@ func devListen(http.Handler) {} func devPage(h http.Handler) http.Handler { return h } func devRole() string { return "" } func devBackend(func(Windows) http.Handler) error { return nil } -func devShell(*host) http.Handler { return nil } func stash(link string) string { return stashImport(link) } diff --git a/internal/gui/devshell_off.go b/internal/gui/devshell_off.go new file mode 100644 index 000000000..57a79644b --- /dev/null +++ b/internal/gui/devshell_off.go @@ -0,0 +1,7 @@ +//go:build !dev && !nogui + +package gui + +import "net/http" + +func devShell(*host) http.Handler { return nil } diff --git a/internal/gui/folder_other.go b/internal/gui/folder_other.go index 7b17d8fb2..1f0a2cbfe 100644 --- a/internal/gui/folder_other.go +++ b/internal/gui/folder_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !nogui package gui diff --git a/internal/gui/folder_windows.go b/internal/gui/folder_windows.go index 7a2060e63..8fbdf5fa6 100644 --- a/internal/gui/folder_windows.go +++ b/internal/gui/folder_windows.go @@ -1,3 +1,5 @@ +//go:build !nogui + package gui import ( diff --git a/internal/gui/glide_darwin.go b/internal/gui/glide_darwin.go index da9cf10c5..a808605aa 100644 --- a/internal/gui/glide_darwin.go +++ b/internal/gui/glide_darwin.go @@ -1,3 +1,5 @@ +//go:build !nogui + package gui /* diff --git a/internal/gui/glide_other.go b/internal/gui/glide_other.go index 110cb6e49..2967d765c 100644 --- a/internal/gui/glide_other.go +++ b/internal/gui/glide_other.go @@ -1,4 +1,4 @@ -//go:build !darwin +//go:build !darwin && !nogui package gui diff --git a/internal/gui/titlebar_gtk3.go b/internal/gui/titlebar_gtk3.go index 4329b35da..6a8c567f1 100644 --- a/internal/gui/titlebar_gtk3.go +++ b/internal/gui/titlebar_gtk3.go @@ -1,4 +1,4 @@ -//go:build linux && cgo && gtk3 +//go:build linux && cgo && gtk3 && !nogui package gui diff --git a/internal/gui/titlebar_gtk4.go b/internal/gui/titlebar_gtk4.go index 9c5226e65..25c6a1987 100644 --- a/internal/gui/titlebar_gtk4.go +++ b/internal/gui/titlebar_gtk4.go @@ -1,4 +1,4 @@ -//go:build linux && cgo && !gtk3 +//go:build linux && cgo && !gtk3 && !nogui package gui diff --git a/internal/gui/titlebar_other.go b/internal/gui/titlebar_other.go index 287ecbd5e..f12aaba3d 100644 --- a/internal/gui/titlebar_other.go +++ b/internal/gui/titlebar_other.go @@ -1,4 +1,4 @@ -//go:build !linux || !cgo +//go:build (!linux || !cgo) && !nogui package gui diff --git a/internal/gui/web.go b/internal/gui/web.go new file mode 100644 index 000000000..1f0fa7a89 --- /dev/null +++ b/internal/gui/web.go @@ -0,0 +1,117 @@ +package gui + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "errors" + "net" + "net/http" + "sync" + "time" +) + +// `magpie web` serves the window's page to a browser, for a computer that +// can't show the app — no desktop, WSL, a server reached over SSH — with +// the gateway beside it as the app has. What is the desktop's (the panel, +// the tray, the Dock) does nothing there; a folder is named, not opened. + +// webHost is the Windows a browser tab stands for. +type webHost struct{ quit func() } + +func (webHost) HidePanel() {} +func (webHost) ShowMain(string) {} +func (h webHost) Quit() { h.quit() } +func (webHost) OpenURL(string) {} // the page opens links itself +func (webHost) Copy(string) bool { return false } +func (webHost) FitPanel(int, Glide) {} +func (webHost) TintPanel([4]uint8, int) bool { return false } +func (webHost) OpenFolder(path string) error { + return errors.New("in the browser magpie can't open folders: it is " + tilde(path)) +} + +// Web is a started `magpie web`: its address and the link that signs a +// browser in. +type Web struct { + Addr, Link string + srv *http.Server + quit chan struct{} +} + +// StartWeb serves the page on addr (host:port). Every request needs the +// key the link carries, taken once into a cookie other sites' pages can't +// 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) { + 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() { + host = "127.0.0.1" + } + var once sync.Once + quit := func() { once.Do(func() { close(w.quit) }) } + w.Link = "http://" + net.JoinHostPort(host, port) + "/?k=" + key + w.srv = &http.Server{ + Handler: webGuard("magpie_web_"+port, key, Handler(webHost{quit}, startBackend())), + ReadHeaderTimeout: 30 * time.Second, + } + go w.srv.Serve(ln) + return w, nil +} + +// Wait returns once the page's Quit is used. +func (w *Web) Wait() { + <-w.quit + time.Sleep(200 * time.Millisecond) // the answer to the Quit gets out + w.srv.Close() +} + +// 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 { + 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") { + if !same(q.Get("k")) { + 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}) + q.Del("k") + u := *r.URL + u.RawQuery = q.Encode() + http.Redirect(rw, r, u.RequestURI(), http.StatusSeeOther) + return + } + if c, err := r.Cookie(cookie); err != nil || !same(c.Value) { + http.Error(rw, "open the link magpie web printed when it started: it carries the key", http.StatusUnauthorized) + return + } + next.ServeHTTP(rw, r) + }) +} + +// LANAddrs are this computer's addresses on the local network, for the +// links to print when the page is served there. +func LANAddrs() []string { + var out []string + as, _ := net.InterfaceAddrs() + for _, a := range as { + n, ok := a.(*net.IPNet) + if !ok || n.IP.IsLoopback() || n.IP.To4() == nil || !n.IP.IsPrivate() { + continue + } + out = append(out, n.IP.String()) + } + return out +} + +// isWeb: the page is served to a browser by `magpie web`. +func isWeb(w Windows) bool { _, ok := w.(webHost); return ok } diff --git a/internal/gui/web_test.go b/internal/gui/web_test.go new file mode 100644 index 000000000..d9a20561c --- /dev/null +++ b/internal/gui/web_test.go @@ -0,0 +1,40 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestWebGuard(t *testing.T) { + h := webGuard("c", "key", 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) + return rec + } + if c := do(httptest.NewRequest("GET", "/api/state", nil)).Code; c != http.StatusUnauthorized { + t.Fatalf("no key: %d", c) + } + if c := do(httptest.NewRequest("GET", "/?k=nope", nil)).Code; c != http.StatusUnauthorized { + t.Fatalf("wrong key: %d", c) + } + rec := do(httptest.NewRequest("GET", "/?k=key&view=settings", nil)) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/?view=settings" { + 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 { + t.Fatalf("cookie: %+v", ck) + } + r := httptest.NewRequest("POST", "/api/settings", nil) + r.AddCookie(ck[0]) + if c := do(r).Code; c != http.StatusTeapot { + t.Fatalf("with cookie: %d", c) + } + r = httptest.NewRequest("POST", "/api/settings", nil) + r.AddCookie(&http.Cookie{Name: "c", Value: "other"}) + if c := do(r).Code; c != http.StatusUnauthorized { + t.Fatalf("wrong cookie: %d", c) + } +} diff --git a/main.go b/main.go index 9f5ff0c4e..4165bfb33 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,8 @@ const usage = `magpie — one place to pick every agent's model magpie tray start in the menu bar only magpie autostart [on|off] open magpie (in the menu bar) when you log in, or say whether it does magpie tui the same thing, in the terminal + magpie web [--addr host:port] [--lan] [--no-open] + the app's window in a browser, with the gateway (no desktop needed: WSL, a server over SSH) magpie ls list detected agents and their settings magpie show one agent magpie set an agent's model e.g. magpie claude deepseek/deepseek-chat @@ -125,6 +127,8 @@ func run(args []string) error { switch args[0] { case "tui": return tui.Run() + case "web": + return webCmd(args[1:]) case "app", "gui": return runGUI(true, "") case "tray": diff --git a/web_cli.go b/web_cli.go new file mode 100644 index 000000000..95a0b2e61 --- /dev/null +++ b/web_cli.go @@ -0,0 +1,58 @@ +package main + +import ( + "fmt" + "net" + "strings" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/gui" +) + +// webAddr is where `magpie web` listens unless told: beside the gateway. +const webAddr = "127.0.0.1:3430" + +// webCmd: magpie web [--addr host:port] [--lan] [--no-open] — the app's +// window in a browser, for a computer that can't show the app. +func webCmd(args []string) error { + addr, lan, open := webAddr, false, true + for i := 0; i < len(args); i++ { + switch a := args[i]; { + case a == "--addr" && i+1 < len(args): + i++ + addr = args[i] + case strings.HasPrefix(a, "--addr="): + addr = strings.TrimPrefix(a, "--addr=") + case a == "--lan": + lan = true + case a == "--no-open": + open = false + default: + return fmt.Errorf("magpie web: unknown %q · magpie web [--addr host:port] [--lan] [--no-open]", a) + } + } + if lan && addr == webAddr { + _, port, _ := net.SplitHostPort(webAddr) + addr = "0.0.0.0:" + port + } + w, err := gui.StartWeb(addr) + if err != nil { + return err + } + fmt.Println(green.Render("●"), "magpie web on", bold.Render(w.Link)) + host, _, _ := net.SplitHostPort(w.Addr) + if ip := net.ParseIP(host); ip != nil && !ip.IsLoopback() { + _, port, _ := net.SplitHostPort(w.Addr) + key := w.Link[strings.Index(w.Link, "/?k="):] + for _, a := range gui.LANAddrs() { + fmt.Println(muted.Render(" on the network"), "http://"+net.JoinHostPort(a, port)+key) + } + 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")) + if open { + openInBrowser(w.Link) + } + w.Wait() + return nil +}