Files
magpie/internal/cli/web_cli.go
T
RainierandClaude Opus 5.5 4d9b798d50 web: a LazyCat box's administrators open the page with the box's sign-in (MAGPIE_WEB_SIGN_IN=lazycat) (#5987)
magpie in a LazyCat app (懒猫微服) is opened from the box's app list by
someone signed in to the box already, and asks for a key they never
saw: it is in the container's log. A package can only hand the key to
every browser that reaches the app, or put a proxy in front that adds
the key's cookie to what the box signed in.

The box's ingress, lzc-ingress, sends a browser that isn't signed in to
the box's login page, and puts on every request it passes the app the
box account (X-HC-User-ID), its role (X-HC-User-Role, ADMIN or NORMAL)
and what sent it (X-HC-Source, client for a browser), in place of what
the caller sent. With MAGPIE_WEB_SIGN_IN=lazycat webGuard takes that
sign-in besides the key: lazyCatSignIn lets in an ADMIN account sent by
a browser, each of the three named once, and tells anyone else the box's
reason.

The box's sign-in is a cookie of the box's, and the box's apps are one
site, so a browser sends it with another app's page's requests too: an
earlier build of this change let another app's page on the box include
/boot.js and read window.bootPrefs. So it is taken only for what the
page itself or the user asked for (boxFetched, the Fetch Metadata:
Sec-Fetch-Site same-origin or none, or a GET or HEAD navigation to a
document from another page), never for another page's script, frame,
fetch or form POST, nor from a browser that sends no Fetch Metadata.

It sets no cookie of the page's own, so signing out of the box signs out
of the page. The key's link and cookie work as before, /api still
answers the page alone (webOwnPage), and the gateway's client routes on
the page's port go to the gateway first (onePort), which asks for a
gateway key. StartWeb refuses another value, and lazycat where
LAZYCAT_APP_DOMAIN, which LazyCat sets in an app's containers, isn't
set: all magpie can check, so the setting is the package's word that the
box's ingress is the only way to the page's port. magpie web prints the
box's address beside the link.

Docs: reference.md's new LazyCat section, with a manifest and what must
never reach the page's port, and gui-shell.md's Browser mode row.

On a box (lzcos 1.6.2+fix.4), a probe app that echoes its request
headers: a signed-in browser's request carries X-HC-User-ID,
X-HC-User-Role ADMIN and X-HC-Source client, forged ones replaced; not
signed in, / goes to the login page and a public path gets none of the
three (forged ones taken off, repeated or in lower case too), while
X-HC-User-Groups passes on as the caller wrote it, so it is never read;
a TCP ingress passes every header as sent. Another app's container
reaches the app through the ingress alone (straight to the app's
container it times out); the box itself, and a container in its network
(network_mode: host, which a manifest may set), reach the port.

A test app made from the docs' manifest, running a build of this change
on 68cb92e8e in the image's place as its user (uid 65532): the box's
administrator opens the console with no key, and no cookie is set;
/v1/models still asks for a gateway key; from another app's page a
navigation opens the console, while a script include of /boot.js and a
frame are turned away; in the container, past the ingress, a request
with no Fetch Metadata, no X-HC-Source, NORMAL or a header twice gets a
401. Bound to /lzcapp/var/config, which the box makes as root's, magpie
couldn't write /config; bound to /lzcapp/var it can, and a gateway key
outlived the container.

Tests, through webServed with the headers the probe saw:
TestLazyCatSignInOpensThePage, TurnsAway, AsksWhereFrom, IsAskedEachTime
and IsNoGatewayKey (the client routes, with each sign-in that opens the
page), and TestWebBoxSignInChecksItsValue.
TestRemoteOpensTheOtherMagpie, new on main, gives webHandler no box
sign-in.

Run, at this tree, on 6c3f113ce: Docker golang:1.26.8 (linux/arm64):
gofmt clean; go vet -tags gtk3 ./... (with the GTK and WebKitGTK
headers, as CI), -tags nogui and GOOS=windows clean; both builds ok.
macOS 27.2 (go1.26.8, not root, a temporary HOME): go vet ./... and the
two cross vets clean, the three builds ok; go test -tags nogui ./...,
TestScriptFindsClaudeMoved skipped (it runs the real
/Applications/Claude.app, #5989): 92 packages ok; red outside
this change, each red the same at 6c3f113ce:
TestBunProxyLoginWithReservedCharacters (#3397),
TestGitUpdateInstallsTheBranchsCommitNow and
TestGitUpdateKeepsACommitPin (#5988), on this Mac's bun 1.3.11,
older than MinBun; TestEveryRouteHasACommandOrIsNamed: POST
/api/settings/join, new with e053c337a, has no command. /join, new
with it too, is a client route, so the docs' manifest lists it.

Broken by hand, each red, all green again put back; a break that lets in
what must be turned away was seen to reach the page: TurnsAway with the
once-each check out, no sender taken, the role in any case, the role or
the sender check out (IsAskedEachTime too), app:… and system alone
turned away, or the key's "open the link" kept in the box's 401;
AsksWhereFrom with boxFetched out, no Fetch Metadata taken, another
page's navigation taken of any method or into a frame, an object or an
embed (or anything but an iframe), its request for a document that isn't
a navigation, or another app's page's script (same-site, no-cors);
OpensThePage with another page's navigation taken by GET alone, or none
taken (IsNoGatewayKey too), a cookie set, or webOwnPage out;
IsAskedEachTime with the first sign-in kept; ChecksItsValue with lazycat
taken outside LazyCat or StartWeb not asking webBoxSignIn's error;
IsNoGatewayKey with the client routes behind the box's sign-in, or one
the box signs in on, or a HEAD to one, given to the page;
TestLazyCatManifestListsTheClientRoutes with /me out of the docs.

Not tried: a NORMAL account in a real browser (the box has one
account); signing out of the box in a browser; the box's own client
apps opening the page; a browser without Fetch Metadata; a header named
twice on a signed-in request through the ingress (a browser can't send
one); a multi-instance app; another lzcos version; a community plugin's
page on the box; a real vendor call through the box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:15:40 +08:00

254 lines
8.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
import (
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/yetone/magpie/internal/daemon"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/gui"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/stats"
)
// 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] [--gateway]
// [--tls-cert <file> --tls-key <file>] —
// the app's window in a browser, for a computer that can't show the app;
// --gateway shows it in gateway mode (gui.WebGateway) unless Settings says
// otherwise; with a certificate the page and the gateway are HTTPS to
// other computers.
func webCmd(args []string) error {
args, err := tlsFlags(args)
if err != nil {
return err
}
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
case a == "--gateway":
gui.WebGateway.Store(true)
default:
return fmt.Errorf("magpie web: unknown %q · magpie web [--addr host:port] [--lan] [--no-open] [--gateway] [--tls-cert <file> --tls-key <file>], MAGPIE_WEB_KEY to keep one key", a)
}
}
if lan && addr == webAddr {
_, port, _ := net.SplitHostPort(webAddr)
addr = "0.0.0.0:" + port
}
// the service serves the page already: its own, beside the gateway
// it serves, is the one to open
if a, k := daemon.Web(); a != "" && gateway.ServedBy().Running {
link := webLink(a, k)
fmt.Println(green.Render("●"), "the magpie service serves this page:", bold.Render(link))
fmt.Println(muted.Render(" magpie daemon web off turns it off"))
if open {
openInBrowser(link)
}
return nil
}
// the app serves this page on this port already (Settings › Network
// and sharing › Browser access): its own is the one to open
if a, k := gui.AppPage(); a != "" && samePort(a, addr) && answers(a) {
link := webLink(a, k)
fmt.Println(green.Render("●"), "the magpie app serves this page:", bold.Render(link))
fmt.Println(muted.Render(" Settings › Network and sharing › Browser access turns it off"))
if open {
openInBrowser(link)
}
return nil
}
// what this page's gateway starts (agents, MCP servers) gets the node a
// version manager put on PATH only in the shell's profile, as the app's
// does: a service or autostart has none of it (#3803)
proc.UserPath()
w, err := gui.StartWeb(addr, version)
if err != nil {
return err
}
if !w.ServesGateway() {
// another magpie has the gateway (the service, magpie serve, the
// app): this page shows its settings and accounts, read from the
// same files, and takes the gateway up when that one stops
o := gateway.ServedBy()
who := "another magpie"
if o.Version != "" {
who += " (" + o.Version + ")"
}
fmt.Println(muted.Render(" the gateway on " + gateway.URL() + " is served by " + who + "; this page shows the same settings and accounts, and serves the gateway once that one stops"))
if st, err := daemon.Get(); err == nil && st.Running {
fmt.Println(muted.Render(" to have the service serve this page itself: magpie daemon web on"))
}
}
printWeb(w)
if open {
openInBrowser(w.Link)
}
return w.Wait()
}
// samePort: a and b (host:port) name one port.
func samePort(a, b string) bool {
_, pa, ea := net.SplitHostPort(a)
_, pb, eb := net.SplitHostPort(b)
return ea == nil && eb == nil && pa == pb
}
// answers: something listens on addr's port on this computer.
func answers(addr string) bool {
_, port, err := net.SplitHostPort(addr)
if err != nil {
return false
}
c, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", port), 500*time.Millisecond)
if err != nil {
return false
}
c.Close()
return true
}
// printWeb prints where a started page is, and what its link carries.
func printWeb(w *gui.Web) {
fmt.Println(green.Render("●"), "magpie web on", bold.Render(w.Link))
if w.BoxLink != "" {
fmt.Println(muted.Render(" the LazyCat box's administrators, signed in to the box, open"), w.BoxLink, muted.Render("without the key"))
}
if l := tlsLine(); l != "" {
fmt.Println(l)
}
host, port, _ := net.SplitHostPort(w.Addr)
key := w.Link[strings.Index(w.Link, "/?k="):]
if ip := net.ParseIP(host); ip != nil && !ip.IsLoopback() {
for _, l := range gui.NetworkLinks(port, key) {
fmt.Println(muted.Render(" on the network"), l)
}
if gateway.ContainerAddrs() {
fmt.Println(muted.Render(" " + containerNote))
}
if l := containerLine(); l != "" {
fmt.Println(l)
}
fmt.Println(amber.Render("!"), lanWarning())
} else if l := proxyLink(key); l != "" {
fmt.Println(muted.Render(" through your proxy"), l)
}
carries := "this run's key (MAGPIE_WEB_KEY keeps one across runs)"
if os.Getenv("MAGPIE_WEB_KEY") != "" {
carries = "MAGPIE_WEB_KEY"
}
fmt.Println(muted.Render(" the link carries " + carries + " · gateway " + advertisedURL() + " · Ctrl-C to stop"))
}
// lanWarning is said wherever the page is served on the network.
func lanWarning() string {
if gateway.TLSOn() {
return "anyone with the link can change magpie and see its keys"
}
return "anyone with the link can change magpie and see its keys, and the network carries it unencrypted (--tls-cert and --tls-key serve it over https)"
}
// webLink is the link to a page served on addr with key, from this
// computer.
func webLink(addr, key string) string {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "http://" + addr + "/?k=" + url.QueryEscape(key)
}
if ip := net.ParseIP(host); host == "" || ip != nil && ip.IsUnspecified() {
host = "127.0.0.1"
}
// this computer may call its loopback page over plain http; any other
// address it has is https with TLS on, as other computers see it
scheme := "http"
if ip := net.ParseIP(host); host != "localhost" && (ip == nil || !ip.IsLoopback()) {
scheme = gateway.Scheme()
}
return scheme + "://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)
}
// proxyLink is the page's link through a reverse proxy in front of a page
// served on loopback (#1479), with the key: MAGPIE_WEB_URL, the page's own
// address there (https://magpie.example.com), or else MAGPIE_PUBLIC_URL
// with no port of its own, as NetworkLinks takes it (#372). One with a
// port names a host whose ports are published, not a proxy. "" with
// neither, or a MAGPIE_WEB_URL that isn't a plain http(s) address.
func proxyLink(key string) string {
if v := strings.TrimSpace(os.Getenv("MAGPIE_WEB_URL")); v != "" {
if !strings.Contains(v, "://") {
v = "https://" + v
}
u, err := url.Parse(v)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
return ""
}
return strings.TrimRight(u.String(), "/") + key
}
u, err := url.Parse(gateway.PublicURL())
if err != nil || u.Host == "" || u.Port() != "" {
return ""
}
return strings.TrimRight(u.String(), "/") + key
}
// serveCmd: magpie serve [--web[=host:port]] — the gateway, and with
// --web magpie web's page from the same process: what the service runs
// (`magpie daemon install --web`), so the page shows the gateway that
// serves the agents, its routing included (HuanCheng on Discord).
func serveCmd(args []string) error {
args, err := tlsFlags(args)
if err != nil {
return err
}
web := ""
for _, a := range args {
switch {
case a == "--web":
web = webAddr
case strings.HasPrefix(a, "--web="):
web = strings.TrimPrefix(a, "--web=")
if _, _, err := net.SplitHostPort(web); err != nil {
return fmt.Errorf("magpie serve: --web=%s isn't host:port", web)
}
default:
return fmt.Errorf("magpie serve: unknown %q · magpie serve [--web[=host:port]] [--tls-cert <file> --tls-key <file>]", a)
}
}
proc.UserPath() // as magpie web's (#3803)
if web == "" {
return serve()
}
go stats.Run(version, "serve")
w, err := gui.StartWeb(web, version)
if err != nil {
return err
}
public := advertisedURL()
fmt.Println(green.Render("●"), "magpie gateway on", bold.Render(gateway.URL()))
fmt.Println(muted.Render(" OpenAI "), public+"/v1/chat/completions", muted.Render("·"), public+"/v1/responses")
fmt.Println(muted.Render(" Anthropic"), public+"/v1/messages")
if l := tlsLine(); l != "" {
fmt.Println(l)
}
if !w.ServesGateway() {
fmt.Println(amber.Render("!"), "another magpie serves the gateway there: this one serves it once that one stops")
}
printWeb(w)
return w.Wait()
}