Files
magpie/internal/cli/web_cli.go
T
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +08:00

209 lines
7.0 KiB
Go

package cli
import (
"fmt"
"net"
"net/url"
"os"
"strings"
"github.com/yetone/magpie/internal/daemon"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/gui"
"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
}
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()
}
// 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 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))
}
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)
}
}
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()
}