gui: the app serves its page to a browser, behind its key (Settings › Browser access)
jiakun_zhao on X ran `magpie web` in a terminal beside the desktop app, to manage it through a Cloudflare tunnel. Settings › Network and sharing › Browser access now has the app serve the same page itself: Off, This computer (127.0.0.1, for a tunnel or SSH forward) or Local network. Access is magpie web's, unchanged: the key in the link is traded for the cookie (webGuard), the allow list holds, and the gateway's client routes on the page's port need a gateway key (onePort). A rebound Host and Origin: null get no cookie. There is no way to serve it without the key. The key and choice live in web-page.json (0600) beside settings.json, so a sync never carries them. GET/POST /api/web-page are the app windows' alone: a browser on the page can't read the key or turn the page off. A busy port (magpie web, the magpie before an update) is tried every 4s; `magpie web` on the same port opens the app's link instead. Run at d43b7c40d (this change onef155a5ca), then rebased onto the four newer main commits, which touch gateway, usage, proc and library only: - gofmt -l internal/gui internal/cli: nothing. go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/gui and internal/cli: clean. go build: ok. - go test -timeout 45m ./internal/gui/ ./internal/cli/: ok (180s, 70s). - GUI, alone: browser-access.test.cjs and model-test-one.test.cjs pass in both engines; i18n-keys 23 of 24, its red is #3897 ("Runs as" from7f827b3b0), not this change. agent-stale-copies.test.cjs 80 of 80 at 8d343a811 (this change before the rebase). - Full GUI suite at 8d343a811: cut short. The disk filled (708MB free): browsers failed to launch with ENOSPC in agent-stale-copies, which then passed 80 of 80 alone, and node ended with exit 7 before the rest of the files ran. There is no full GUI record for this change. Not tried: a real Cloudflare tunnel to the page, and Local network from another machine.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -6,6 +6,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/daemon"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
@@ -61,6 +62,17 @@ func webCmd(args []string) error {
|
||||
}
|
||||
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)
|
||||
@@ -90,6 +102,27 @@ func webCmd(args []string) error {
|
||||
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))
|
||||
|
||||
@@ -35,3 +35,22 @@ func TestWebProxyLink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `magpie web` opens the app's page when the app serves it on the port it
|
||||
// would take, and starts its own on any other.
|
||||
func TestWebSamePort(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
a, b string
|
||||
want bool
|
||||
}{
|
||||
{"127.0.0.1:3430", "127.0.0.1:3430", true},
|
||||
{"0.0.0.0:3430", "127.0.0.1:3430", true},
|
||||
{"127.0.0.1:3430", "0.0.0.0:3431", false},
|
||||
{"", "127.0.0.1:3430", false},
|
||||
{"127.0.0.1:3430", "3430", false},
|
||||
} {
|
||||
if got := samePort(c.a, c.b); got != c.want {
|
||||
t.Errorf("samePort(%q, %q) = %v", c.a, c.b, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-2
@@ -823,7 +823,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
if gw != nil {
|
||||
served.Store(gw)
|
||||
}
|
||||
if isWeb(w) {
|
||||
// magpie web's own page, not the app's served to a browser, which the
|
||||
// app's windows share their settings state with
|
||||
if ownWeb(w) {
|
||||
webPage.Store(true)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
@@ -845,7 +847,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
// and whether it is a gateway's page alone (gatewaymode.go), so the
|
||||
// pages left out never show
|
||||
if on, _ := gatewayMode(isWeb(w)); on {
|
||||
if on, _ := gatewayMode(ownWeb(w)); on {
|
||||
boot["gateway"] = true
|
||||
}
|
||||
// and the built-in plugins it leaves out (builtins.go), gone
|
||||
@@ -1190,6 +1192,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
cliBehindRoutes(mux)
|
||||
gatewayFixRoutes(mux)
|
||||
gatewayModeRoutes(mux)
|
||||
if !isWeb(w) {
|
||||
appPageRoutes(mux)
|
||||
}
|
||||
privacyModelRoutes(mux)
|
||||
maskingRoutes(mux)
|
||||
builtinRoutes(mux)
|
||||
|
||||
+10
-2
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/autostart"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/library"
|
||||
"github.com/yetone/magpie/internal/omarchy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
@@ -353,8 +354,11 @@ func Run(version string, showMain bool, link string) error {
|
||||
zoom := h.zoom()
|
||||
go stats.Run(version, "app")
|
||||
handler := devShell(h)
|
||||
if handler == nil {
|
||||
handler = Handler(h, startBackend())
|
||||
ownPage := handler == nil
|
||||
var gw *gateway.Server
|
||||
if ownPage {
|
||||
gw = startBackend()
|
||||
handler = Handler(h, gw)
|
||||
}
|
||||
// Linux: the magpie before holds the app's D-Bus name until it quits,
|
||||
// once it has finished its requests; this one serves the gateway
|
||||
@@ -626,6 +630,10 @@ func Run(version string, showMain bool, link string) error {
|
||||
// GTK 3 with no font DPI set would lay every page out at a negative
|
||||
// width (#1371); give it one before the first webview is made.
|
||||
fontDPI()
|
||||
// the page to a browser too, where Settings says (apppage.go)
|
||||
if ownPage {
|
||||
startAppPage(h, gw)
|
||||
}
|
||||
return h.app.Run()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
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, 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
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// appPageTest is a fresh home and a fresh appPage in appPageServer's place,
|
||||
// its page a teapot that says it was reached. Whatever it serves is closed
|
||||
// when the test ends.
|
||||
func appPageTest(t *testing.T, reached *bool) *appPage {
|
||||
t.Helper()
|
||||
onePortHome(t)
|
||||
g := gateway.New()
|
||||
prevGW := served.Swap(g)
|
||||
p := &appPage{wake: make(chan struct{}, 1)}
|
||||
p.mk = func() http.Handler {
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
*reached = true
|
||||
rw.WriteHeader(http.StatusTeapot)
|
||||
})
|
||||
}
|
||||
prev := appPageServer
|
||||
appPageServer = p
|
||||
t.Cleanup(func() {
|
||||
p.mu.Lock()
|
||||
if p.srv != nil {
|
||||
p.srv.Close()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
appPageServer = prev
|
||||
served.Store(prevGW)
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
// appPagePost is POST /api/web-page on the app's windows' API.
|
||||
func appPagePost(t *testing.T, body string) (int, appPageJSON) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
appPageRoutes(mux)
|
||||
r := httptest.NewRequest("POST", "/api/web-page", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, r)
|
||||
var s appPageJSON
|
||||
json.Unmarshal(w.Body.Bytes(), &s)
|
||||
return w.Code, s
|
||||
}
|
||||
|
||||
// noRedirect is a client that shows a redirect rather than following it.
|
||||
var noRedirect = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
|
||||
func appPageGet(t *testing.T, port int, path, cookie string, hdr ...string) *http.Response {
|
||||
t.Helper()
|
||||
r, _ := http.NewRequest("GET", "http://127.0.0.1:"+strconv.Itoa(port)+path, nil)
|
||||
if cookie != "" {
|
||||
r.AddCookie(&http.Cookie{Name: "magpie_web_" + strconv.Itoa(port), Value: cookie})
|
||||
}
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
res, err := noRedirect.Do(r)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
res.Body.Close()
|
||||
return res
|
||||
}
|
||||
|
||||
// jiakun_zhao on X: the page the app's window shows, served to a browser
|
||||
// (through a Cloudflare tunnel) by the app itself rather than `magpie web`
|
||||
// kept running beside it. It is off until Settings turns it on, and never
|
||||
// answers without its key: not the page, not its API, not the gateway's
|
||||
// client routes without a gateway key; a new key turns every browser
|
||||
// signed in with the old one away.
|
||||
func TestAppPageServesOnlyWithItsKey(t *testing.T) {
|
||||
var reached bool
|
||||
p := appPageTest(t, &reached)
|
||||
if a, k := AppPage(); a != "" || k != "" {
|
||||
t.Fatalf("a new home serves the page at %q", a)
|
||||
}
|
||||
port := freePort(t)
|
||||
|
||||
code, s := appPagePost(t, `{"mode":"local","port":`+strconv.Itoa(port)+`}`)
|
||||
if code != 200 || !s.Serving || s.Mode != "local" || s.Port != port {
|
||||
t.Fatalf("turned on: %d %+v", code, s)
|
||||
}
|
||||
key := strings.TrimPrefix(s.Link, "http://127.0.0.1:"+strconv.Itoa(port)+"/?k=")
|
||||
if CheckWebKey(key) != nil || key == s.Link {
|
||||
t.Fatalf("the link carries no key: %q", s.Link)
|
||||
}
|
||||
if a, k := AppPage(); a != "127.0.0.1:"+strconv.Itoa(port) || k != key {
|
||||
t.Errorf("AppPage() = %q, %q", a, k)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
if fi, err := os.Stat(appPageFile()); err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("web-page.json: %v %v, want 0600", fi.Mode(), err)
|
||||
}
|
||||
}
|
||||
if b, _ := os.ReadFile(appPageFile()); !strings.Contains(string(b), key) {
|
||||
t.Errorf("the key is not in web-page.json: %s", b)
|
||||
}
|
||||
// only on this computer
|
||||
if _, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(port), time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.addr != "127.0.0.1:"+strconv.Itoa(port) {
|
||||
t.Errorf("local listens on %q", p.addr)
|
||||
}
|
||||
|
||||
for _, c := range []struct {
|
||||
name, path, cookie string
|
||||
hdr []string
|
||||
}{
|
||||
{"the page", "/", "", nil},
|
||||
{"the page, as a browser", "/", "", []string{"Accept", "text/html"}},
|
||||
{"the API", "/api/state", "", nil},
|
||||
{"the API, from another host", "/api/state", "", []string{"Host", "rebind.attacker.example:" + strconv.Itoa(port)}},
|
||||
{"the API, Origin null", "/api/state", "", []string{"Origin", "null"}},
|
||||
{"the API, a wrong cookie", "/api/state", "0123456789abcdef-wrong", nil},
|
||||
{"the page, a wrong key in the link", "/?k=0123456789abcdef-wrong", "", nil},
|
||||
} {
|
||||
res := appPageGet(t, port, c.path, c.cookie, c.hdr...)
|
||||
if res.StatusCode == http.StatusTeapot || res.StatusCode == 200 || res.StatusCode == http.StatusSeeOther {
|
||||
t.Errorf("%s without the key: %d", c.name, res.StatusCode)
|
||||
}
|
||||
}
|
||||
if reached {
|
||||
t.Fatal("the page was reached without its key")
|
||||
}
|
||||
// the gateway's client routes on the page's port need a gateway key,
|
||||
// from this computer too (a tunnel's requests come from loopback)
|
||||
if res := appPageGet(t, port, "/v1/models", ""); res.StatusCode == 200 {
|
||||
t.Errorf("/v1/models without a gateway key: %d", res.StatusCode)
|
||||
}
|
||||
// shared: a gateway key, and nothing less, lets an agent through
|
||||
gwKey := onePortKey(t)
|
||||
if res := appPageGet(t, port, "/v1/models", ""); res.StatusCode == 200 {
|
||||
t.Errorf("/v1/models shared, without a gateway key: %d", res.StatusCode)
|
||||
}
|
||||
if res := appPageGet(t, port, "/v1/models", key); res.StatusCode == 200 {
|
||||
t.Errorf("/v1/models with the page's cookie alone: %d", res.StatusCode)
|
||||
}
|
||||
if res := appPageGet(t, port, "/v1/models", "", "Authorization", "Bearer "+gwKey); res.StatusCode != 200 {
|
||||
t.Errorf("/v1/models with a gateway key: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
res := appPageGet(t, port, "/?k="+key, "")
|
||||
var cookie string
|
||||
for _, c := range res.Cookies() {
|
||||
if c.Name == "magpie_web_"+strconv.Itoa(port) {
|
||||
cookie = c.Value
|
||||
}
|
||||
}
|
||||
if res.StatusCode != http.StatusSeeOther || cookie != key {
|
||||
t.Fatalf("the link: %d, cookie %q", res.StatusCode, cookie)
|
||||
}
|
||||
if res := appPageGet(t, port, "/api/state", cookie); res.StatusCode != http.StatusTeapot {
|
||||
t.Fatalf("signed in: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// a new key: the old cookie is turned away, the new link signs in
|
||||
code, s = appPagePost(t, `{"newKey":true}`)
|
||||
if code != 200 || !s.Serving || strings.Contains(s.Link, key) {
|
||||
t.Fatalf("new key: %d %+v", code, s)
|
||||
}
|
||||
reached = false
|
||||
if res := appPageGet(t, port, "/api/state", cookie); res.StatusCode != http.StatusUnauthorized || reached {
|
||||
t.Errorf("the old key's cookie after a new key: %d", res.StatusCode)
|
||||
}
|
||||
if res := appPageGet(t, port, strings.TrimPrefix(s.Link, "http://127.0.0.1:"+strconv.Itoa(port)), ""); res.StatusCode != http.StatusSeeOther {
|
||||
t.Errorf("the new link: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// off: nothing listens
|
||||
if code, s = appPagePost(t, `{"mode":""}`); code != 200 || s.Serving || s.Link != "" {
|
||||
t.Fatalf("turned off: %d %+v", code, s)
|
||||
}
|
||||
if c, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(port), time.Second); err == nil {
|
||||
c.Close()
|
||||
t.Error("the page still listens once turned off")
|
||||
}
|
||||
if a, _ := AppPage(); a != "" {
|
||||
t.Errorf("AppPage() once off = %q", a)
|
||||
}
|
||||
}
|
||||
|
||||
// A port another program holds (`magpie web`, or the magpie before a
|
||||
// restart to update) is said, and taken once it is let go.
|
||||
func TestAppPageWaitsForABusyPort(t *testing.T) {
|
||||
var reached bool
|
||||
p := appPageTest(t, &reached)
|
||||
held, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := held.Addr().(*net.TCPAddr).Port
|
||||
code, s := appPagePost(t, `{"mode":"local","port":`+strconv.Itoa(port)+`}`)
|
||||
if code != 200 || s.Serving || !strings.Contains(s.Error, "port "+strconv.Itoa(port)) {
|
||||
t.Fatalf("on a held port: %d %+v", code, s)
|
||||
}
|
||||
if !p.waiting() {
|
||||
t.Error("a held port isn't tried again")
|
||||
}
|
||||
held.Close()
|
||||
p.apply()
|
||||
if s := p.state(); !s.Serving || s.Error != "" {
|
||||
t.Fatalf("once let go: %+v", s)
|
||||
}
|
||||
if p.waiting() {
|
||||
t.Error("still trying once served")
|
||||
}
|
||||
}
|
||||
|
||||
// A web-page.json that can't be read as a choice serves nothing, and says
|
||||
// why; Settings writes it anew only with the whole choice.
|
||||
func TestAppPageUnreadFileServesNothing(t *testing.T) {
|
||||
for _, body := range []string{"{not json", `{"mode":"everywhere","key":"0123456789abcdef-key"}`} {
|
||||
var reached bool
|
||||
p := appPageTest(t, &reached)
|
||||
if err := os.MkdirAll(strings.TrimSuffix(appPageFile(), "web-page.json"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(appPageFile(), []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.apply()
|
||||
if s := p.state(); s.Serving || s.Error == "" || s.Link != "" {
|
||||
t.Errorf("%s: %+v", body, s)
|
||||
}
|
||||
if a, _ := AppPage(); a != "" {
|
||||
t.Errorf("%s: AppPage() = %q", body, a)
|
||||
}
|
||||
if code, _ := appPagePost(t, `{"newKey":true}`); code == 200 {
|
||||
t.Errorf("%s: a new key alone wrote the file", body)
|
||||
}
|
||||
if code, s := appPagePost(t, `{"mode":""}`); code != 200 || s.Error != "" {
|
||||
t.Errorf("%s: turned off: %d %+v", body, code, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Settings turns down what isn't a choice: a mode not known, a port below
|
||||
// 1024 or the gateway's own.
|
||||
func TestAppPageTurnsDownBadChoices(t *testing.T) {
|
||||
var reached bool
|
||||
appPageTest(t, &reached)
|
||||
gwPort := freePort(t)
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:"+strconv.Itoa(gwPort))
|
||||
for _, body := range []string{`{"mode":"everywhere"}`, `{"port":80}`, `{"port":70000}`, `{"port":` + strconv.Itoa(gwPort) + `}`} {
|
||||
if code, _ := appPagePost(t, body); code == 200 {
|
||||
t.Errorf("%s was taken", body)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(appPageFile()); err == nil {
|
||||
t.Error("a choice turned down was written")
|
||||
}
|
||||
}
|
||||
|
||||
// A browser on the app's page is a browser tab: its page says web, the
|
||||
// app's Browser access isn't on its API (it can't turn the page off under
|
||||
// itself, nor read the key), and it doesn't make the app's own windows
|
||||
// `magpie web`'s (webPage).
|
||||
func TestAppPageBrowserIsATab(t *testing.T) {
|
||||
onePortHome(t)
|
||||
webPage.Store(false)
|
||||
t.Cleanup(func() { webPage.Store(false) })
|
||||
b := appWebHost{webHost{}, nil}
|
||||
if !isWeb(b) || ownWeb(b) {
|
||||
t.Fatalf("isWeb %v, ownWeb %v", isWeb(b), ownWeb(b))
|
||||
}
|
||||
h := Handler(b, nil)
|
||||
if webPage.Load() {
|
||||
t.Error("the app's page set webPage, as magpie web's does")
|
||||
}
|
||||
for _, m := range []string{"GET", "POST"} {
|
||||
r := httptest.NewRequest(m, "/api/web-page", strings.NewReader(`{"mode":"lan"}`))
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code == 200 {
|
||||
t.Errorf("%s /api/web-page from the browser: %d %s", m, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(appPageFile()); err == nil {
|
||||
t.Error("the browser wrote web-page.json")
|
||||
}
|
||||
r := httptest.NewRequest("GET", "/boot.js", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if !strings.Contains(w.Body.String(), `"web":true`) {
|
||||
t.Errorf("boot.js doesn't say web: %.200s", w.Body)
|
||||
}
|
||||
// the app's own windows have it
|
||||
r = httptest.NewRequest("GET", "/api/web-page", nil)
|
||||
w = httptest.NewRecorder()
|
||||
Handler(nil, nil).ServeHTTP(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Errorf("GET /api/web-page from the app: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -3530,6 +3530,17 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
|
||||
.row.pref.lan-address-row { position: relative; height: 50px; transition: height .28s var(--ease); }
|
||||
.row.pref.lan-address-row .who { position: absolute; top: 16px; left: 14px; }
|
||||
.prefs .lan-address-row .val { max-width: 64%; }
|
||||
/* Browser access: a link per address, each with its copy button */
|
||||
.prefs .web-page-link-row .val { max-width: 64%; gap: 6px; }
|
||||
.web-page-links { display: flex; flex-direction: column; align-items: flex-end; min-width: 0; }
|
||||
.web-page-link { display: inline-flex; align-items: center; min-width: 0; max-width: 100%; }
|
||||
.row.pref.web-page-warn .name { color: var(--amber); }
|
||||
/* three choices leave the words no room in a narrow window: they go under */
|
||||
@media (max-width: 600px) {
|
||||
.row.pref.web-page-mode { flex-wrap: wrap; row-gap: 8px; }
|
||||
.row.pref.web-page-mode .who { flex: 1 1 100%; }
|
||||
.prefs .web-page-mode .val { max-width: 100%; }
|
||||
}
|
||||
.lan-address-controls { position: absolute; inset: 0; pointer-events: none; }
|
||||
.lan-address-controls > * { position: absolute; pointer-events: auto; }
|
||||
.row.pref .proto.pick.lan-interface { top: 13px; right: 40px; width: 240px; max-width: calc(100% - 40px); margin-left: 0; font: var(--code-style, normal) var(--code-weight, 400) 12px var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); transition: top .28s var(--ease), background .12s, color .12s; }
|
||||
|
||||
@@ -4,6 +4,16 @@
|
||||
// works. {name} slots are filled by t(str, vars).
|
||||
const I18N = {
|
||||
zh: {
|
||||
"Browser access": "浏览器访问",
|
||||
"Open magpie in a browser": "在浏览器中打开 magpie",
|
||||
"The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}": "App 运行时会把本窗口的页面提供给浏览器,链接里带着 Key,和 magpie web 一样。用 Cloudflare Tunnel 这类隧道时,把它指向 http://127.0.0.1:{port}",
|
||||
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "端口 {p} 被其他程序占用(可能是 magpie web):magpie 每隔几秒会再试一次",
|
||||
"Served; anyone with this link can change every setting": "已提供;拿到这个链接的人可以更改所有设置",
|
||||
"Starting…": "正在启动…",
|
||||
"Link": "链接",
|
||||
"Port": "端口",
|
||||
"Not encrypted": "未加密",
|
||||
"Other computers reach the page over plain HTTP, so anyone on this network can read its key: on a network you don’t trust, keep it on This computer and reach it through a tunnel": "其他电脑通过明文 HTTP 访问这个页面,同一网络里的任何人都能读到它的 Key:在不信任的网络上,请选“本机”并通过隧道访问",
|
||||
"None": "无",
|
||||
"Prompt": "提示词",
|
||||
"Request hook": "请求 Hook",
|
||||
@@ -4023,6 +4033,16 @@ const I18N = {
|
||||
"Where": "位置",
|
||||
},
|
||||
"zh-TW": {
|
||||
"Browser access": "瀏覽器存取",
|
||||
"Open magpie in a browser": "在瀏覽器中開啟 magpie",
|
||||
"The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}": "App 執行時會把本視窗的頁面提供給瀏覽器,連結裡帶著 Key,和 magpie web 一樣。用 Cloudflare Tunnel 這類通道時,把它指向 http://127.0.0.1:{port}",
|
||||
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "連接埠 {p} 被其他程式佔用(可能是 magpie web):magpie 每隔幾秒會再試一次",
|
||||
"Served; anyone with this link can change every setting": "已提供;拿到這個連結的人可以變更所有設定",
|
||||
"Starting…": "正在啟動…",
|
||||
"Link": "連結",
|
||||
"Port": "連接埠",
|
||||
"Not encrypted": "未加密",
|
||||
"Other computers reach the page over plain HTTP, so anyone on this network can read its key: on a network you don’t trust, keep it on This computer and reach it through a tunnel": "其他電腦透過明文 HTTP 存取這個頁面,同一網路裡的任何人都能讀到它的 Key:在不信任的網路上,請選「本機」並透過通道存取",
|
||||
"None": "無",
|
||||
"Prompt": "提示詞",
|
||||
"Request hook": "請求 Hook",
|
||||
@@ -8027,6 +8047,16 @@ const I18N = {
|
||||
"Where": "位置",
|
||||
},
|
||||
ja: {
|
||||
"Browser access": "ブラウザからのアクセス",
|
||||
"Open magpie in a browser": "ブラウザで magpie を開く",
|
||||
"The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}": "アプリの実行中、このウィンドウのページをブラウザにも提供します。magpie web と同じく、リンクにキーが含まれます。Cloudflare Tunnel などのトンネルは http://127.0.0.1:{port} に向けてください",
|
||||
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "ポート {p} は別のプログラム(magpie web かもしれません)が使用中です:magpie が数秒ごとに再試行します",
|
||||
"Served; anyone with this link can change every setting": "提供中。このリンクを持つ人は、すべての設定を変更できます",
|
||||
"Starting…": "起動中…",
|
||||
"Link": "リンク",
|
||||
"Port": "ポート",
|
||||
"Not encrypted": "暗号化されていません",
|
||||
"Other computers reach the page over plain HTTP, so anyone on this network can read its key: on a network you don’t trust, keep it on This computer and reach it through a tunnel": "ほかのコンピュータは平文の HTTP でこのページにアクセスするため、同じネットワークの誰でもキーを読み取れます。信頼できないネットワークでは「このコンピュータ」のままにし、トンネル経由でアクセスしてください",
|
||||
"None": "なし",
|
||||
"Prompt": "プロンプト",
|
||||
"Request hook": "リクエストフック",
|
||||
@@ -12033,6 +12063,16 @@ const I18N = {
|
||||
"Where": "場所",
|
||||
},
|
||||
de: {
|
||||
"Browser access": "Browserzugriff",
|
||||
"Open magpie in a browser": "magpie im Browser öffnen",
|
||||
"The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}": "Solange die App läuft, liefert sie die Seite dieses Fensters auch an Browser aus, mit einem Schlüssel im Link, wie magpie web. Einen Tunnel wie Cloudflare Tunnel richtest du auf http://127.0.0.1:{port}",
|
||||
"Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds": "Port {p} ist von einem anderen Programm belegt, vielleicht magpie web: magpie versucht es alle paar Sekunden erneut",
|
||||
"Served; anyone with this link can change every setting": "Wird ausgeliefert; wer diesen Link hat, kann jede Einstellung ändern",
|
||||
"Starting…": "Wird gestartet…",
|
||||
"Link": "Link",
|
||||
"Port": "Port",
|
||||
"Not encrypted": "Nicht verschlüsselt",
|
||||
"Other computers reach the page over plain HTTP, so anyone on this network can read its key: on a network you don’t trust, keep it on This computer and reach it through a tunnel": "Andere Computer erreichen die Seite über unverschlüsseltes HTTP, also kann jeder in diesem Netzwerk ihren Schlüssel mitlesen: In einem Netzwerk, dem du nicht vertraust, bleib bei „Dieser Computer“ und nutze einen Tunnel",
|
||||
"None": "Keine",
|
||||
"Prompt": "Prompt",
|
||||
"Request hook": "Anfrage-Hook",
|
||||
|
||||
@@ -378,6 +378,8 @@
|
||||
<div class="list prefs" id="allowList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Web pages</span></div>
|
||||
<div class="list prefs" id="corsList"></div>
|
||||
<div class="row-head" id="webPageHead"><span class="label" data-t>Browser access</span></div>
|
||||
<div class="list prefs" id="webPageList"></div>
|
||||
</section>
|
||||
<section class="set-page" id="setPage-models" role="tabpanel" aria-labelledby="setTab-models">
|
||||
<div class="row-head"><span class="label" data-t>Images</span></div>
|
||||
|
||||
@@ -96,6 +96,7 @@ function corsSays(m) {
|
||||
return t(m);
|
||||
}
|
||||
function renderCORS(s) {
|
||||
renderWebPage(); // Browser access, the section under this one
|
||||
const box = $("#corsList");
|
||||
box.replaceChildren();
|
||||
const origins = s.corsOrigins || [];
|
||||
@@ -295,3 +296,73 @@ function renderLAN(s) {
|
||||
}
|
||||
if (sub) row(t("In a container"), sub, "").classList.add("lan-container");
|
||||
}
|
||||
|
||||
// renderWebPage: Browser access, the app's own page served to a browser
|
||||
// (apppage.go; jiakun_zhao on X managed magpie through a Cloudflare tunnel
|
||||
// with `magpie web` kept running in a terminal beside the app). Off, this
|
||||
// computer alone (for a tunnel or an SSH forward to reach), or the local
|
||||
// network. The page always asks for its key: the link carries it, and a
|
||||
// browser without it gets nothing. The app's windows alone draw it; a
|
||||
// browser on the page can't turn it off under itself.
|
||||
let webPageState = null, webPagePort = null;
|
||||
// Each draw asks again, as a port another program held can come free; the
|
||||
// answer draws without asking.
|
||||
function renderWebPage(asked) {
|
||||
const head = $("#webPageHead"), box = $("#webPageList");
|
||||
if (!box) return;
|
||||
head.hidden = box.hidden = web;
|
||||
if (web) return;
|
||||
if (!asked) api("web-page").then((r) => { webPageState = r; renderWebPage(true); }).catch(() => {});
|
||||
const s = webPageState;
|
||||
if (!s) return;
|
||||
const set = (body) => writingPrefs(api("web-page", body))
|
||||
.then((r) => { webPageState = r; webPagePort = null; renderWebPage(true); })
|
||||
.catch((e) => { status(t(e.message), "err"); webPageState = null; renderWebPage(); });
|
||||
const rows = [];
|
||||
const row = (name, sub, ...tools) => {
|
||||
const r = el("div", "row pref");
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name", name));
|
||||
if (sub) who.append(sub instanceof Node ? sub : el("div", "sub", sub));
|
||||
const val = el("div", "val");
|
||||
val.append(...tools);
|
||||
r.append(who, val);
|
||||
rows.push(r);
|
||||
return r;
|
||||
};
|
||||
row(t("Open magpie in a browser"),
|
||||
t("The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}", { port: s.port }),
|
||||
segs([["", t("Off")], ["local", t("This computer")], ["lan", t("Local network")]], s.mode || "", (mode) => set({ mode }))).classList.add("web-page-mode");
|
||||
if (s.mode) {
|
||||
const why = s.error ? el("div", "sub err", s.error.startsWith("port ") ? t("Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds", { p: s.port }) : t(s.error))
|
||||
: el("div", "sub", s.serving ? t("Served; anyone with this link can change every setting") : t("Starting…"));
|
||||
const links = [s.link, ...(s.mode === "lan" ? s.network || [] : [])].filter(Boolean);
|
||||
const box2 = el("div", "web-page-links");
|
||||
for (const l of links) {
|
||||
const line = el("span", "web-page-link");
|
||||
line.append(el("code", "", l.replace(/\?k=.*/, "?k=…")), copyBtn(l, t("Link"), t("Copied")));
|
||||
box2.append(line);
|
||||
}
|
||||
const rekey = el("button", "text", t("New key"));
|
||||
rekey.onclick = () => set({ newKey: true });
|
||||
row(t("Link"), why, box2, rekey).classList.add("web-page-link-row");
|
||||
const field = input(webPagePort ?? String(s.port), "3430");
|
||||
field.className = "words gateway-port";
|
||||
field.inputMode = "numeric";
|
||||
field.setAttribute("aria-label", t("Port"));
|
||||
const save = el("button", "text", t("Apply"));
|
||||
save.onclick = () => {
|
||||
const p = Number(field.value.trim());
|
||||
if (!Number.isInteger(p) || p < 1024 || p > 65535) return status(t("A port is a number from 1024 to 65535"), "err");
|
||||
set({ port: p });
|
||||
};
|
||||
field.oninput = () => { webPagePort = field.value; };
|
||||
field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save.onclick(); };
|
||||
row(t("Port"), "", field, save);
|
||||
if (s.mode === "lan" && !s.tls) {
|
||||
const r = row(t("Not encrypted"), t("Other computers reach the page over plain HTTP, so anyone on this network can read its key: on a network you don’t trust, keep it on This computer and reach it through a tunnel"));
|
||||
r.classList.add("web-page-warn");
|
||||
}
|
||||
}
|
||||
box.replaceChildren(...rows);
|
||||
}
|
||||
|
||||
@@ -535,10 +535,18 @@ func combinedSessionStats(days int) sessions.Stats {
|
||||
// page opens on the kept index and not on a first read of them all. Usage ›
|
||||
// Requests' whole history is read after it, not beside it on the disk: a
|
||||
// first All parsing 12k sessions kept that page a skeleton for 40 s.
|
||||
// Once a process: the app's page served to a browser (apppage.go) is a
|
||||
// second Handler beside the window's.
|
||||
func warmSessions() {
|
||||
if testing.Testing() {
|
||||
return
|
||||
}
|
||||
warmOnce.Do(warmStart)
|
||||
}
|
||||
|
||||
var warmOnce sync.Once
|
||||
|
||||
func warmStart() {
|
||||
go func() {
|
||||
time.Sleep(3 * time.Second)
|
||||
// with few readers, as nobody waits on it yet: after an update
|
||||
|
||||
@@ -2522,3 +2522,14 @@ does. Both engines, at 440px. The reckoning itself is covered by
|
||||
`TestHistoricalWindowHoldsUsesEachWindowsOwnReading`,
|
||||
`TestWindowHoldsResetBeforeRefillReading` and
|
||||
`TestWindowHoldsDryAgainAfterReset`.
|
||||
|
||||
## Browser access
|
||||
|
||||
`browser-access.test.cjs` checks Settings › Network and sharing › Browser
|
||||
access, the app's own page served to a browser: Off, This computer and
|
||||
Local network posted to `/api/web-page`, the link shown with its key as
|
||||
"…" and copied whole, New key, the port with Apply and a taken port's
|
||||
reason, the "Not encrypted" row on the local network, no native select or
|
||||
left border, nothing wider or cut off at 360px, and no such section (nor a
|
||||
read of it) in a browser on the page. Every language, Chromium and WebKit,
|
||||
with the API faked.
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings › Network and sharing › Browser access (jiakun_zhao on X: the
|
||||
// page managed through a Cloudflare tunnel took `magpie web` kept running in
|
||||
// a terminal beside the app). Off, This computer or Local network, posted to
|
||||
// /api/web-page; once on, the link (its key shown as "…", copied whole), a
|
||||
// New key, the port with Apply, and why it isn't served when a port is
|
||||
// taken, in the page's language. Local network without TLS says the page is
|
||||
// not encrypted. A browser on the page (web) has no such section and never
|
||||
// asks for it. No native <select>, no coloured left border, nothing wider
|
||||
// than a 360px window. Every language, Chromium and WebKit; no backend, the
|
||||
// API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { reach, watchSettingsReads, settingsDrawn } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const KEY = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
function server(lang, web, posts, gets) {
|
||||
let wp = { mode: "", port: 3430, serving: false };
|
||||
const say = () => {
|
||||
if (!wp.mode) return { mode: "", port: wp.port, serving: false };
|
||||
const s = { ...wp, link: `http://127.0.0.1:${wp.port}/?k=${wp.key}` };
|
||||
if (wp.port === 3500) Object.assign(s, { serving: false, error: "port 3500 can't be taken (address already in use): magpie tries again every few seconds" });
|
||||
else s.serving = true;
|
||||
if (wp.mode === "lan") s.network = [`http://192.168.1.20:${wp.port}/?k=${wp.key}`];
|
||||
return s;
|
||||
};
|
||||
return async (route) => {
|
||||
const req = route.request();
|
||||
const url = new URL(req.url());
|
||||
const json = (data, status = 200) => route.fulfill({ status, json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web},sideGateway:{url:"http://127.0.0.1:3425",running:true,boot:true}};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, web });
|
||||
if (url.pathname === "/api/web-page") {
|
||||
if (req.method() === "GET") { gets.n++; return json(say()); }
|
||||
const body = JSON.parse(req.postData());
|
||||
posts.push(body);
|
||||
if (body.mode !== undefined) wp.mode = body.mode;
|
||||
if (body.port !== undefined) wp.port = body.port;
|
||||
if (body.newKey || !wp.key) wp.key = body.newKey && wp.key ? "fedcba9876543210fedcba9876543210" : KEY;
|
||||
return json(say());
|
||||
}
|
||||
if (url.pathname === "/api/settings") return json({ lang, theme: "light", gateway: "http://127.0.0.1:3425", lan: false, lanURLs: [], version: "0.1.900", dir: "/config/magpie", fx: { rate: 7.2, at: new Date().toISOString(), stale: false } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": Browser access turns the app's page on for a browser, with its key", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const pages = [];
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-browser-access-${i}.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
|
||||
const open = async (lang, web, width = 900) => {
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
pages.push(page);
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posts = [], gets = { n: 0 };
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, web, posts, gets));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://localhost:3430/?view=settings&tab=network");
|
||||
await settingsDrawn(page);
|
||||
// the page's own word for an English string
|
||||
const tr = (s, vars) => page.evaluate(([s, vars]) => t(s, vars), [s, vars]);
|
||||
return { page, errors, posts, gets, tr };
|
||||
};
|
||||
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
await t.test(lang, async () => {
|
||||
const { page, errors, posts, tr } = await open(lang, false);
|
||||
const head = page.locator("#webPageHead");
|
||||
const list = page.locator("#webPageList");
|
||||
await list.locator(".row.pref").first().waitFor();
|
||||
assert.equal((await head.textContent()).trim(), await tr("Browser access"));
|
||||
if (lang !== "en") assert.notEqual(await tr("Browser access"), "Browser access", "translated");
|
||||
const first = list.locator(".row.pref").first();
|
||||
assert.equal((await first.locator(".name").textContent()).trim(), await tr("Open magpie in a browser"));
|
||||
assert.equal((await first.locator(".sub").textContent()).trim(), await tr("The app serves this window’s page with a key in its link, as magpie web does, while it runs. For a tunnel such as Cloudflare Tunnel, point it at http://127.0.0.1:{port}", { port: 3430 }));
|
||||
assert.equal(await list.locator(".row.pref").count(), 1, "off: one row");
|
||||
|
||||
const local = first.getByRole("button", { name: await tr("This computer") });
|
||||
await reach(page, local);
|
||||
await local.click();
|
||||
await list.locator(".web-page-link-row").waitFor();
|
||||
assert.deepEqual(posts.at(-1), { mode: "local" });
|
||||
const linkRow = list.locator(".web-page-link-row");
|
||||
const code = linkRow.locator("code");
|
||||
assert.equal(await code.count(), 1);
|
||||
assert.equal((await code.textContent()).trim(), "http://127.0.0.1:3430/?k=…", "the key isn't shown");
|
||||
assert.equal(await linkRow.locator("button.copy").count(), 1);
|
||||
assert.equal((await linkRow.locator(".sub").textContent()).trim(), await tr("Served; anyone with this link can change every setting"));
|
||||
assert.equal(await list.locator(".web-page-warn").count(), 0, "this computer alone: no warning");
|
||||
|
||||
const rekey = linkRow.getByRole("button", { name: await tr("New key") });
|
||||
await reach(page, rekey);
|
||||
await rekey.click();
|
||||
// the posts are counted here, not a time waited
|
||||
for (let i = 0; i < 250 && !posts.some((p) => p.newKey); i++) await page.waitForTimeout(20);
|
||||
assert(posts.some((p) => p.newKey), "New key posts newKey");
|
||||
|
||||
// a port another program has: said in the page's language
|
||||
const field = list.locator("input.gateway-port");
|
||||
await reach(page, field);
|
||||
await field.fill("3500");
|
||||
await list.getByRole("button", { name: await tr("Apply") }).click();
|
||||
const why = await tr("Port {p} is taken by another program, magpie web perhaps: magpie tries again every few seconds", { p: 3500 });
|
||||
await list.locator(".web-page-link-row .sub.err").filter({ hasText: why }).waitFor();
|
||||
assert.deepEqual(posts.at(-1), { port: 3500 });
|
||||
|
||||
// local network, no TLS: not encrypted, and every address's link
|
||||
const lan = list.getByRole("button", { name: await tr("Local network") });
|
||||
await reach(page, lan);
|
||||
await lan.click();
|
||||
await list.locator(".web-page-warn").waitFor();
|
||||
assert.deepEqual(posts.at(-1), { mode: "lan" });
|
||||
assert.equal(await list.locator(".web-page-link-row code").count(), 2);
|
||||
assert.equal((await list.locator(".web-page-warn .name").textContent()).trim(), await tr("Not encrypted"));
|
||||
|
||||
assert.equal(await page.locator("#setPage-network select").count(), 0, "no native select");
|
||||
for (const r of await list.locator(".row.pref").all()) {
|
||||
const border = await r.evaluate((e) => getComputedStyle(e).borderLeftWidth);
|
||||
assert(border === "0px" || border === "", "no left border accent: " + border);
|
||||
}
|
||||
const off = list.getByRole("button", { name: await tr("Off") }).first();
|
||||
await reach(page, off);
|
||||
await off.click();
|
||||
await page.waitForFunction(() => document.querySelectorAll("#webPageList .row.pref").length === 1);
|
||||
assert.deepEqual(posts.at(-1), { mode: "" });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
|
||||
await t.test("360px wide, Chinese", async () => {
|
||||
const { page, errors, tr } = await open("zh", false, 360);
|
||||
const list = page.locator("#webPageList");
|
||||
await list.locator(".row.pref").first().waitFor();
|
||||
const lan = list.getByRole("button", { name: await tr("Local network") });
|
||||
await reach(page, lan);
|
||||
await lan.click();
|
||||
await list.locator(".web-page-warn").waitFor();
|
||||
const over = await list.evaluate((l) => [...l.querySelectorAll(".row.pref")].filter((r) => r.scrollWidth > r.clientWidth + 1 || r.getBoundingClientRect().right > innerWidth + 1).map((r) => r.textContent.slice(0, 40)));
|
||||
assert.deepEqual(over, [], "rows wider than the window");
|
||||
const cut = await list.evaluate((l) => [...l.querySelectorAll(".row.pref .name")].filter((n) => n.scrollWidth > n.clientWidth).map((n) => n.textContent));
|
||||
assert.deepEqual(cut, [], "names cut off");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
await t.test("a browser on the page has no Browser access", async () => {
|
||||
const { page, errors, gets } = await open("en", true);
|
||||
await page.locator("#portList .row").first().waitFor();
|
||||
assert.equal(await page.locator("#webPageHead").isVisible(), false);
|
||||
assert.equal(await page.locator("#webPageList .row").count(), 0);
|
||||
assert.equal(gets.n, 0, "never asks /api/web-page");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
});
|
||||
}
|
||||
+12
-2
@@ -636,7 +636,7 @@ func updateRoutes(mux *http.ServeMux, w Windows) {
|
||||
if updates.json().State == "ready" {
|
||||
if in.When != "now" && !updates.idle() {
|
||||
updates.waitIdle(func() bool {
|
||||
if restartToUpdate(isWeb(w), in.View != "" || mainShown(w), in.View) {
|
||||
if restartFrom(w, in.View) {
|
||||
go leave(w.Quit)
|
||||
return true
|
||||
}
|
||||
@@ -650,7 +650,7 @@ func updateRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
switch j := updates.json(); {
|
||||
case j.State == "ready":
|
||||
if restartToUpdate(isWeb(w), in.View != "" || mainShown(w), in.View) {
|
||||
if restartFrom(w, in.View) {
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
go leave(w.Quit)
|
||||
return
|
||||
@@ -669,6 +669,16 @@ func updateRoutes(mux *http.ServeMux, w Windows) {
|
||||
// relaunchBinary is update.RelaunchBinary; tests stand in for it.
|
||||
var relaunchBinary = update.RelaunchBinary
|
||||
|
||||
// restartFrom is restartToUpdate asked from w's page, on view: a browser
|
||||
// on the app's page restarts the app, with its window up as it was, not
|
||||
// opened on the tab the browser was on.
|
||||
func restartFrom(w Windows, view string) bool {
|
||||
if a, ok := w.(appWebHost); ok {
|
||||
return restartToUpdate(false, mainShown(a.app), "")
|
||||
}
|
||||
return restartToUpdate(ownWeb(w), view != "" || mainShown(w), view)
|
||||
}
|
||||
|
||||
// restartToUpdate installs the staged version and arranges for it to open
|
||||
// once this process is gone; the caller then quits. magpie web runs on as
|
||||
// the new version in its own place (Web.Wait) instead of opening the app.
|
||||
|
||||
+12
-2
@@ -400,8 +400,18 @@ func compressible(ct string) bool {
|
||||
strings.HasSuffix(ct, "json") || ct == "image/svg+xml"
|
||||
}
|
||||
|
||||
// isWeb: the page is served to a browser by `magpie web`.
|
||||
func isWeb(w Windows) bool { _, ok := w.(webHost); return ok }
|
||||
// browserTab is a Windows that stands for a browser tab: magpie web's
|
||||
// (webHost) or one on the page the app serves (appWebHost).
|
||||
type browserTab interface{ browserTab() }
|
||||
|
||||
func (webHost) browserTab() {}
|
||||
|
||||
// isWeb: the page is served to a browser, by `magpie web` or by the app.
|
||||
func isWeb(w Windows) bool { _, ok := w.(browserTab); return ok }
|
||||
|
||||
// ownWeb: the page is `magpie web`'s own (its gateway mode, its restart
|
||||
// to update), not the app's served to a browser.
|
||||
func ownWeb(w Windows) bool { _, ok := w.(webHost); return ok }
|
||||
|
||||
// onePort hands the gateway's client routes (gateway.ClientPath: /v1/…,
|
||||
// /v1beta/…, /mcp/…) on the page's port to the gateway, so the page and the
|
||||
|
||||
Reference in New Issue
Block a user