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 on68cb92e8ein 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, on6c3f113ce: 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 at6c3f113ce: TestBunProxyLoginWithReservedCharacters (#3397), TestGitUpdateInstallsTheBranchsCommitNow and TestGitUpdateKeepsACommitPin (#5988), on this Mac's bun 1.3.11, older than MinBun; TestEveryRouteHasACommandOrIsNamed: POST /api/settings/join, new withe053c337a, 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>
355 lines
10 KiB
Go
355 lines
10 KiB
Go
package gui
|
||
|
||
import (
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
"net/http"
|
||
"net/url"
|
||
"os"
|
||
"path/filepath"
|
||
"strconv"
|
||
"sync"
|
||
"sync/atomic"
|
||
"time"
|
||
|
||
"github.com/yetone/magpie/internal/edit"
|
||
"github.com/yetone/magpie/internal/gateway"
|
||
"github.com/yetone/magpie/internal/settings"
|
||
)
|
||
|
||
// The app serves its window's page to a browser too, when Settings ›
|
||
// Network and sharing › Browser access says so (jiakun_zhao on X: the page
|
||
// managed through a Cloudflare tunnel took `magpie web` kept running in a
|
||
// terminal beside the app). It is magpie web's page, served from the app's
|
||
// own process, beside the gateway the app serves: the same key in the
|
||
// link, traded for the same cookie (webGuard), the same allow list, and
|
||
// the gateway's client routes on its port judged as from another machine
|
||
// (onePort). There is no way to serve it without the key.
|
||
//
|
||
// "local" listens on 127.0.0.1 alone, for a tunnel or an SSH forward to
|
||
// reach (cloudflared's service is http://127.0.0.1:<port>); "lan" on every
|
||
// address, for other computers on the network. Its port and key live in
|
||
// web-page.json beside settings.json, this computer's alone, never in
|
||
// settings.json: a sync or a backup never carries the key to another
|
||
// computer, nor turns the page on there.
|
||
|
||
// appPageFile is where the app's page's choice and key are kept, 0600.
|
||
func appPageFile() string { return filepath.Join(settings.Dir(), "web-page.json") }
|
||
|
||
// appPageDefaultPort is magpie web's own port: a browser signed in to one
|
||
// is signed in to the other where they share the key.
|
||
const appPageDefaultPort = 3430
|
||
|
||
// appPageConf is web-page.json: Mode "" (off), "local" or "lan"; Port 0
|
||
// for appPageDefaultPort; Key the link's.
|
||
type appPageConf struct {
|
||
Mode string `json:"mode,omitempty"`
|
||
Port int `json:"port,omitempty"`
|
||
Key string `json:"key,omitempty"`
|
||
}
|
||
|
||
func (c appPageConf) port() int {
|
||
if c.Port == 0 {
|
||
return appPageDefaultPort
|
||
}
|
||
return c.Port
|
||
}
|
||
|
||
// addr is where the page listens, "" when it is off.
|
||
func (c appPageConf) addr() string {
|
||
switch c.Mode {
|
||
case "local":
|
||
return net.JoinHostPort("127.0.0.1", strconv.Itoa(c.port()))
|
||
case "lan":
|
||
return net.JoinHostPort("0.0.0.0", strconv.Itoa(c.port()))
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// loadAppPage reads web-page.json. A file that can't be read or parsed is
|
||
// off, and says why: nothing is served on a choice not known.
|
||
func loadAppPage() (appPageConf, error) {
|
||
var c appPageConf
|
||
b, err := os.ReadFile(appPageFile())
|
||
if errors.Is(err, os.ErrNotExist) {
|
||
return c, nil
|
||
}
|
||
if err != nil {
|
||
return appPageConf{}, err
|
||
}
|
||
if err := json.Unmarshal(b, &c); err != nil {
|
||
return appPageConf{}, fmt.Errorf("%s: %w", appPageFile(), err)
|
||
}
|
||
if c.Mode != "" && c.Mode != "local" && c.Mode != "lan" {
|
||
return appPageConf{}, fmt.Errorf("%s: mode is local, lan or off, not %q", appPageFile(), c.Mode)
|
||
}
|
||
return c, nil
|
||
}
|
||
|
||
// saveAppPage writes web-page.json readable by its owner alone: it holds
|
||
// the key that opens every setting and key magpie has.
|
||
func saveAppPage(c appPageConf) error {
|
||
p := appPageFile()
|
||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||
return err
|
||
}
|
||
// made 0600 before anything is in it, so WriteAtomic keeps that mode
|
||
if f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err == nil {
|
||
f.Close()
|
||
}
|
||
b, _ := json.MarshalIndent(c, "", " ")
|
||
if err := edit.WriteAtomic(p, append(b, '\n')); err != nil {
|
||
return err
|
||
}
|
||
return os.Chmod(p, 0o600)
|
||
}
|
||
|
||
// AppPage is where the app serves its page and its key, "" when it doesn't
|
||
// say it does: `magpie web` points to it rather than starting a second.
|
||
func AppPage() (addr, key string) {
|
||
c, err := loadAppPage()
|
||
if err != nil || c.addr() == "" || CheckWebKey(c.Key) != nil {
|
||
return "", ""
|
||
}
|
||
return c.addr(), c.Key
|
||
}
|
||
|
||
// appWebHost is the Windows a browser on the app's page stands for: a
|
||
// browser's (webHost's) in all but quitting, which quits the app, and the
|
||
// window the app has up, which a restart to update brings back.
|
||
type appWebHost struct {
|
||
webHost
|
||
app Windows
|
||
}
|
||
|
||
func (a appWebHost) MainShown() bool { return mainShown(a.app) }
|
||
|
||
// appPage is the app's page served to a browser: listening where
|
||
// web-page.json says, or trying again every appPageRetry while another
|
||
// program (magpie web, the magpie before a restart to update) has the port.
|
||
type appPage struct {
|
||
mu sync.Mutex
|
||
mk func() http.Handler // the page behind the key; nil until the app starts
|
||
page http.Handler
|
||
srv *http.Server
|
||
addr string // where it listens, "" when it doesn't
|
||
cur atomic.Pointer[http.Handler] // webServed with the key now
|
||
key string
|
||
err string // why it isn't served where asked
|
||
wake chan struct{}
|
||
}
|
||
|
||
var appPageServer = &appPage{wake: make(chan struct{}, 1)}
|
||
|
||
// appPageRetry is how often a busy port is tried again.
|
||
var appPageRetry = 4 * time.Second
|
||
|
||
// startAppPage has the app serve its page as web-page.json says, now and
|
||
// whenever Settings changes it. app is the app's own windows; gw the
|
||
// gateway it serves (nil while another magpie has it).
|
||
func startAppPage(app Windows, gw *gateway.Server) {
|
||
p := appPageServer
|
||
p.mu.Lock()
|
||
p.mk = func() http.Handler { return Handler(appWebHost{webHost{quit: app.Quit}, app}, gw) }
|
||
p.mu.Unlock()
|
||
go p.run()
|
||
}
|
||
|
||
func (p *appPage) run() {
|
||
for {
|
||
p.apply()
|
||
var retry <-chan time.Time
|
||
if p.waiting() {
|
||
retry = time.After(appPageRetry)
|
||
}
|
||
select {
|
||
case <-p.wake:
|
||
case <-retry:
|
||
}
|
||
}
|
||
}
|
||
|
||
// nudge has the loop look again, so a port found busy now is tried again.
|
||
func (p *appPage) nudge() {
|
||
select {
|
||
case p.wake <- struct{}{}:
|
||
default:
|
||
}
|
||
}
|
||
|
||
// waiting: the page is asked for and not served.
|
||
func (p *appPage) waiting() bool {
|
||
p.mu.Lock()
|
||
defer p.mu.Unlock()
|
||
return p.err != "" && p.mk != nil
|
||
}
|
||
|
||
// apply brings what is served to what web-page.json says.
|
||
func (p *appPage) apply() {
|
||
c, err := loadAppPage()
|
||
p.mu.Lock()
|
||
defer p.mu.Unlock()
|
||
if p.mk == nil {
|
||
return
|
||
}
|
||
want := c.addr()
|
||
if err != nil {
|
||
want, p.err = "", err.Error()
|
||
}
|
||
if p.srv != nil && p.addr != want {
|
||
p.srv.Close()
|
||
p.srv, p.addr = nil, ""
|
||
}
|
||
if want == "" {
|
||
if err == nil {
|
||
p.err = ""
|
||
}
|
||
return
|
||
}
|
||
if CheckWebKey(c.Key) != nil {
|
||
p.err = "the page has no key yet"
|
||
return
|
||
}
|
||
if p.page == nil {
|
||
p.page = p.mk()
|
||
}
|
||
if p.key != c.Key || p.cur.Load() == nil {
|
||
h := webServed(strconv.Itoa(c.port()), c.Key, webCookieAge, nil, p.page)
|
||
p.cur.Store(&h)
|
||
p.key = c.Key
|
||
}
|
||
if p.srv != nil {
|
||
return
|
||
}
|
||
ln, err := net.Listen("tcp", want)
|
||
if err != nil {
|
||
p.err = busySays(c.port(), err)
|
||
return
|
||
}
|
||
// with --tls-cert the page is HTTPS to other computers, as magpie web's
|
||
if ln, err = gateway.ServeTLS(ln); err != nil {
|
||
p.err = err.Error()
|
||
return
|
||
}
|
||
p.srv = &http.Server{
|
||
Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { (*p.cur.Load()).ServeHTTP(rw, r) }),
|
||
ReadHeaderTimeout: 30 * time.Second,
|
||
}
|
||
p.addr, p.err = want, ""
|
||
go p.srv.Serve(ln)
|
||
log.Printf("magpie: the page is served to browsers on %s", ln.Addr())
|
||
}
|
||
|
||
// busySays is why the page couldn't listen on port: most often another
|
||
// program has it (magpie web, or the magpie before a restart to update).
|
||
func busySays(port int, err error) string {
|
||
return fmt.Sprintf("port %d can't be taken (%v): magpie tries again every few seconds", port, err)
|
||
}
|
||
|
||
// appPageJSON is GET /api/web-page: the choice, and what came of it.
|
||
type appPageJSON struct {
|
||
Mode string `json:"mode"`
|
||
Port int `json:"port"`
|
||
Serving bool `json:"serving"`
|
||
Link string `json:"link,omitempty"` // this computer's, with the key
|
||
Network []string `json:"network,omitempty"` // other computers', with the key ("lan")
|
||
Error string `json:"error,omitempty"`
|
||
// TLS: other computers get it over HTTPS (--tls-cert)
|
||
TLS bool `json:"tls,omitempty"`
|
||
}
|
||
|
||
func (p *appPage) state() appPageJSON {
|
||
c, err := loadAppPage()
|
||
p.mu.Lock()
|
||
defer p.mu.Unlock()
|
||
s := appPageJSON{Mode: c.Mode, Port: c.port(), Serving: p.srv != nil && p.addr == c.addr(), Error: p.err, TLS: gateway.TLSOn()}
|
||
if err != nil {
|
||
s.Error = err.Error()
|
||
}
|
||
if c.Mode == "" || CheckWebKey(c.Key) != nil {
|
||
return s
|
||
}
|
||
k := "/?k=" + url.QueryEscape(c.Key)
|
||
s.Link = "http://" + net.JoinHostPort("127.0.0.1", strconv.Itoa(c.port())) + k
|
||
if c.Mode == "lan" {
|
||
s.Network = NetworkLinks(strconv.Itoa(c.port()), k)
|
||
}
|
||
return s
|
||
}
|
||
|
||
// appPageRoutes: GET /api/web-page says what is served; POST takes
|
||
// {"mode": "" | "local" | "lan", "port": n, "newKey": true}, each part
|
||
// optional, and answers the same. The app's own windows' alone: a browser
|
||
// on the page can't turn it off under itself, nor read the key it came in
|
||
// without.
|
||
func appPageRoutes(mux *http.ServeMux) {
|
||
mux.HandleFunc("GET /api/web-page", func(rw http.ResponseWriter, r *http.Request) {
|
||
writeJSON(rw, appPageServer.state())
|
||
})
|
||
mux.HandleFunc("POST /api/web-page", func(rw http.ResponseWriter, r *http.Request) {
|
||
var in struct {
|
||
Mode *string `json:"mode"`
|
||
Port *int `json:"port"`
|
||
NewKey bool `json:"newKey"`
|
||
}
|
||
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 4096)).Decode(&in); err != nil {
|
||
fail(rw, err)
|
||
return
|
||
}
|
||
c, err := loadAppPage()
|
||
if err != nil {
|
||
// a file that can't be read is written anew only when the
|
||
// whole choice is given
|
||
if in.Mode == nil {
|
||
fail(rw, err)
|
||
return
|
||
}
|
||
c = appPageConf{}
|
||
}
|
||
if in.Mode != nil {
|
||
switch *in.Mode {
|
||
case "", "local", "lan":
|
||
c.Mode = *in.Mode
|
||
default:
|
||
fail(rw, fmt.Errorf("browser access is off, local or lan, not %q", *in.Mode))
|
||
return
|
||
}
|
||
}
|
||
if in.Port != nil {
|
||
if err := appPagePortOK(*in.Port); err != nil {
|
||
fail(rw, err)
|
||
return
|
||
}
|
||
c.Port = *in.Port
|
||
if c.Port == appPageDefaultPort {
|
||
c.Port = 0
|
||
}
|
||
}
|
||
if in.NewKey || CheckWebKey(c.Key) != nil {
|
||
c.Key = NewWebKey()
|
||
}
|
||
if err := saveAppPage(c); err != nil {
|
||
fail(rw, err)
|
||
return
|
||
}
|
||
appPageServer.apply()
|
||
appPageServer.nudge()
|
||
writeJSON(rw, appPageServer.state())
|
||
})
|
||
}
|
||
|
||
// appPagePortOK says what is wrong with port for the page: it is a port of
|
||
// its own, 1024 up, not the gateway's.
|
||
func appPagePortOK(port int) error {
|
||
if port < 1024 || port > 65535 {
|
||
return errors.New("a port is a number from 1024 to 65535")
|
||
}
|
||
if u, err := url.Parse(gateway.URL()); err == nil && u.Port() == strconv.Itoa(port) {
|
||
return fmt.Errorf("port %d is the gateway's: pick another one", port)
|
||
}
|
||
return nil
|
||
}
|