gateway: join a shared magpie with a password (EV_John_Liu on X)

EV_John_Liu asked for quick setup on a LAN: the central magpie serves a
page behind a password where other PCs and Macs get their config and a
new key of their own.

Settings -> Network and sharing -> Join with a password sets the
password (at least 8 characters; only a salted PBKDF2-SHA256 hash is
kept, in join.json, 0600, written through temp-and-rename; a file that
can't be read or parsed means joining is closed). The row then shows the
address to give out, <shared address>/join, and Turn off joining.

/join is the key page (/me) opened to join: the visitor types a name for
the computer and the password. POST /v1/magpie/join makes a gateway key
named after that computer (or "Joined from <ip>"). The key is listed in
Gateway keys like any other, where it can be limited or removed. The
page shows the key once and then the setup for that key: Claude Code,
Codex, a new magpie tab (`magpie provider add remote-magpie '<key>'
url='<address>'`), OpenAI-compatible and curl.

Every route judged:
- lanGuard lets another machine reach GET /join and the join route
  without a key, only while magpie is shared. The route checks the
  password itself.
- A browser's POST must come from the page itself. Host must be one of
  this computer's own names (IP, localhost, MAGPIE_PUBLIC_URL's, its
  hostname), so a DNS-rebound name is refused. Origin must equal Host.
  Missing Origin and Origin "null" are refused, and so is any
  Sec-Fetch-Site but same-origin. corsGuard still refuses null, foreign
  and *.localhost Origins before this. curl and scripts, which send no
  browser marks, are judged on the password alone.
- Throttle: each try from another machine costs a token, a right
  password too. The bucket holds 10 and refills one every 10s, so a
  guesser gets about 360 tries an hour, and a flood of tries makes no
  flood of keys. Over the limit the route answers 429 with Retry-After.
- The password and key never go in a URL or a log line. The key comes
  back only in a no-store 201 body. Logs name the key's id and the
  caller's address.
- The routes are classed in the key-slot and read-only route lists.
  They carry no key.

Run on mote at this head (rebased on 065ca02c2):
- gofmt clean
- go vet: darwin, linux -tags nogui and windows, for access, gateway
  and gui
- go test: access, gui, and gateway's join, route-list, key page and
  LAN tests
- The whole gateway package ran before the rebase, and its only reds
  were the two route-list guards fixed here.
- GUI (node --test), chromium and webkit: lan-join (new), key-page,
  mtls-settings, allow-ips, i18n-keys, lan-docker, lan-lazycat,
  lan-address-height, side-gateway-lan: all ok before the rebase, and
  lan-join, key-page and i18n-keys ok again at this head.
- That GUI run caught a TDZ error: JOINING was read before its const,
  which broke /me too. It is fixed in this commit, and key-page went
  from red to green.

Broken by hand (each red, then put back):
- no throttle: TestJoinHoldsAGuesser red
- no lanGuard bypass: TestJoinMakesARevocableKey, TestJoinHoldsAGuesser
  and TestJoinClosed red
- no ownHost check: TestJoinRefusesOtherPages red
- joinRefusal returning "": rebound remote, cross-site and no-Origin
  browser POSTs each got a 201, red
- Dropping only the Origin comparison stayed green, because corsGuard
  refuses the same Origins first.

Not tried:
- a real two-machine LAN join with the built app
- a Windows or Linux run of the tests (vet only)
- the full suite, which starts after the tag
This commit is contained in:
yetone
2026-11-10 22:42:11 +08:00
parent 87b3af7653
commit e053c337aa
16 changed files with 1141 additions and 9 deletions
+28
View File
@@ -886,6 +886,34 @@ shared and with a key (`gatewayKeyPage` in `keys.js`). `key_page.go`, and
[`key_page_test.go`](../../internal/gateway/key_page_test.go);
`internal/gui/tests/key-page.test.cjs` drives the page itself.
`GET /join` is the same page as the join page (EV_John_Liu on X): with a
password set in Settings → Local network → Join with a password
(`POST /api/settings/join`, `internal/gui/join.go`), another computer
opens it, types the password and a name for itself, and gets a gateway
key of its own (`access.Update("add-key")`, named for it or "Joined from
<address>"), shown once and then filled into the page's setup, which adds
a magpie tab (`magpie provider add remote-magpie`). The key is listed in
Gateway keys and is limited, turned off or removed there like any other.
Only a salted PBKDF2-SHA256 hash of the password is kept, in `join.json`
(`internal/access/join.go`, 0600, temp and rename); a file that can't be
read or parsed means joining is closed. `lanGuard` lets `GET /join` and
`GET`/`POST /v1/magpie/join` (`joinPageOpen`, `joinAsked`) through
without a key, after the allow list, the rebinding check, mTLS and the
not-shared refusal. `joinKey` then refuses a browser's request
(`fromBrowser`) unless the Host is this computer's own (`ownHost`: no
rebound name, no `*.localhost`) and the Origin is that same address, not
missing and not `null`, with `Sec-Fetch-Site` same-origin where sent;
curl and scripts are judged on the password alone. Every try from another
machine takes a token from the join's own bucket (10, then one each 10s),
the right password too, so a guesser and a flood of keys are both held
with 429 and `Retry-After`. Neither the password nor the key is logged,
and the key goes back in a `no-store` body only. `join.go`, and
`TestJoinMakesARevocableKey`, `TestJoinHoldsAGuesser`,
`TestJoinRefusesOtherPages` and `TestJoinClosed` in
[`join_test.go`](../../internal/gateway/join_test.go), `TestJoinPassword`
in `internal/access`; `internal/gui/tests/lan-join.test.cjs` drives the
page and the Settings rows.
System One uses `RouteDecider` and `postDecide` in
[`decide.go`](../../internal/gateway/decide.go), taking one provider prefix
off at each hop and preserving the state, questions and vendor errors.
+148
View File
@@ -0,0 +1,148 @@
package access
import (
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/settings"
)
// The join password (EV_John_Liu on X): while magpie is shared, another
// computer on the network opens the gateway's /join page, types this
// password and gets a gateway key of its own, with the setup for its
// agents. Only a salted PBKDF2-SHA256 hash of it is kept, in join.json
// beside caller-keys.json: this computer's own, never synced or backed up
// with the settings, and never shown again once set. A file that can't be
// read or parsed means join is closed: a failed read is unknown, never an
// open door.
// JoinMinLen is the fewest characters a join password may have.
const JoinMinLen = 8
// joinIter is PBKDF2's rounds; a variable so the tests run quickly.
var joinIter = 210_000
type joinFile struct {
Salt []byte `json:"salt"`
Hash []byte `json:"hash"`
Iter int `json:"iter"`
Set time.Time `json:"set"`
}
var joinMu sync.Mutex
// JoinPath is the file the join password's hash is kept in.
func JoinPath() string { return filepath.Join(settings.Dir(), "join.json") }
func readJoin() (joinFile, bool) {
b, err := os.ReadFile(JoinPath())
if err != nil {
return joinFile{}, false
}
var f joinFile
if json.Unmarshal(b, &f) != nil || len(f.Salt) < 16 || len(f.Hash) != sha256.Size || f.Iter < 1 {
return joinFile{}, false
}
return f, true
}
// JoinOn: a join password is set, and readable.
func JoinOn() bool {
joinMu.Lock()
defer joinMu.Unlock()
_, ok := readJoin()
return ok
}
// JoinSince is when the join password was set; zero when none is.
func JoinSince() time.Time {
joinMu.Lock()
defer joinMu.Unlock()
f, _ := readJoin()
return f.Set
}
// SetJoinPassword sets the join password, or with "" clears it, which
// closes the join page. Keys already given out stay until each is removed
// in Gateway keys.
func SetJoinPassword(pw string) error {
joinMu.Lock()
defer joinMu.Unlock()
if pw == "" {
if err := os.Remove(JoinPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
if utf8.RuneCountInString(pw) < JoinMinLen {
return errors.New("Use a password of at least 8 characters")
}
if len(pw) > 1024 {
return errors.New("Use a password of at most 1024 bytes")
}
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return err
}
h, err := pbkdf2.Key(sha256.New, pw, salt, joinIter, sha256.Size)
if err != nil {
return err
}
b, err := json.Marshal(joinFile{Salt: salt, Hash: h, Iter: joinIter, Set: time.Now().UTC()})
if err != nil {
return err
}
return writePrivate(JoinPath(), b)
}
// JoinPasswordOK: pw is the join password. None set, or a file that can't
// be read, lets no password in.
func JoinPasswordOK(pw string) bool {
joinMu.Lock()
f, ok := readJoin()
joinMu.Unlock()
if !ok || pw == "" || len(pw) > 1024 {
return false
}
h, err := pbkdf2.Key(sha256.New, pw, f.Salt, f.Iter, sha256.Size)
return err == nil && subtle.ConstantTimeCompare(h, f.Hash) == 1
}
// writePrivate writes b to path through a temp file renamed over it,
// readable by this user alone.
func writePrivate(path string, b []byte) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp-*")
if err != nil {
return err
}
name := tmp.Name()
defer os.Remove(name)
if err := tmp.Chmod(0o600); err != nil {
tmp.Close()
return err
}
if _, err := tmp.Write(append(b, '\n')); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(name, path)
}
+51
View File
@@ -0,0 +1,51 @@
package access
import (
"os"
"strings"
"testing"
)
func init() { joinIter = 1000 }
func TestJoinPassword(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if JoinOn() || JoinPasswordOK("") || JoinPasswordOK("anything") {
t.Fatal("open with no password")
}
if err := SetJoinPassword("short"); err == nil {
t.Fatal("a 5-character password was taken")
}
if err := SetJoinPassword("long enough pw"); err != nil {
t.Fatal(err)
}
if !JoinOn() || !JoinPasswordOK("long enough pw") || JoinPasswordOK("long enough pW") || JoinPasswordOK("") {
t.Fatal("password check")
}
b, err := os.ReadFile(JoinPath())
if err != nil {
t.Fatal(err)
}
if string(b) == "" || strings.Contains(string(b), "long enough") {
t.Fatalf("join.json holds the password: %s", b)
}
if fi, _ := os.Stat(JoinPath()); fi.Mode().Perm() != 0o600 && os.PathSeparator == '/' {
t.Errorf("mode %v", fi.Mode())
}
// a file that can't be parsed shuts the door
if err := os.WriteFile(JoinPath(), []byte(`{"salt":"","hash":"","iter":0}`), 0o600); err != nil {
t.Fatal(err)
}
if JoinOn() || JoinPasswordOK("long enough pw") || JoinPasswordOK("") {
t.Fatal("a broken join.json let a password in")
}
if err := SetJoinPassword("long enough pw"); err != nil {
t.Fatal(err)
}
if err := SetJoinPassword(""); err != nil {
t.Fatal(err)
}
if JoinOn() || JoinPasswordOK("long enough pw") {
t.Fatal("still open after clearing")
}
}
+5
View File
@@ -1046,6 +1046,11 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove)
mux.HandleFunc("GET "+KeyPagePath, s.keyPage)
mux.HandleFunc("GET "+keyPageData, s.keyInfo)
// the join page, where another computer that knows the join password
// gets a gateway key of its own (join.go)
mux.HandleFunc("GET "+JoinPagePath, s.joinPage)
mux.HandleFunc("GET "+joinData, s.joinOpen)
mux.HandleFunc("POST "+joinData, s.joinKey)
// the Claude Code processes the Claude subscription runs, for magpie
// claude-code runs (loopback only)
mux.HandleFunc("GET "+ClaudeRunsPath, s.claudeRuns)
+195
View File
@@ -0,0 +1,195 @@
package gateway
import (
"encoding/json"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// JoinPagePath is the join page (EV_John_Liu on X): on a magpie shared on
// the network with a join password set (Settings → Network and sharing →
// Join with a password), another computer opens <address>/join, types the
// password and a name for itself, and gets a gateway key of its own, made
// then and listed in Gateway keys under that name, where it is limited or
// removed as any other key. The page then shows that key's setup for
// Claude Code, Codex, another magpie or any OpenAI-compatible app, as the
// key page (/me) does: it is the same page.
const JoinPagePath = "/join"
// joinData is the join's own route: GET says whether joining is open,
// POST {password, name} makes the key.
const joinData = "/v1/magpie/join"
// joinPageOpen: r asks for the join page itself, the key page's bytes,
// which lanGuard serves to another machine without a key while magpie is
// shared.
func joinPageOpen(r *http.Request) bool {
return r.URL.Path == JoinPagePath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead)
}
// joinAsked: r is the join's route, which carries a password, not a key:
// the handler judges it (joinKey).
func joinAsked(r *http.Request) bool {
return r.URL.Path == joinData && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodPost)
}
// The join's own bucket, apart from tooManyAuthFails': each try from
// another machine takes a token, a right password too (each makes a key),
// so a guesser gets joinBurst tries and then one each joinRefill — 360 an
// hour against a password of 8 characters or more — and a flood of tries
// makes no flood of keys. A right key elsewhere is never held by it.
const (
joinBurst = 10
joinRefill = 10 * time.Second
)
var joinThrottle = struct {
sync.Mutex
tokens float64
last time.Time
now func() time.Time
}{tokens: joinBurst, now: time.Now}
// tooManyJoins takes one try's token; over when there is none, with the
// wait until one refills.
func tooManyJoins() (over bool, retry time.Duration) {
t := &joinThrottle
t.Lock()
defer t.Unlock()
now := t.now()
if t.last.IsZero() {
t.last = now
}
t.tokens = min(joinBurst, t.tokens+now.Sub(t.last).Seconds()/joinRefill.Seconds())
t.last = now
if t.tokens >= 1 {
t.tokens--
return false, 0
}
return true, time.Duration((1 - t.tokens) * float64(joinRefill))
}
func resetJoinThrottle() {
t := &joinThrottle
t.Lock()
t.tokens, t.last, t.now = joinBurst, time.Time{}, time.Now
t.Unlock()
}
// joinPage serves the key page, which reads from its address that it is
// the join page.
func (s *Server) joinPage(w http.ResponseWriter, r *http.Request) { s.keyPage(w, r) }
// joinOpen tells the page whether a password is set to join with.
func (s *Server) joinOpen(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, map[string]bool{"open": access.JoinOn()})
}
// joinRefusal: why a browser's join isn't one its own page sent, or "".
// A browser's POST carries an Origin, which must be the page's own address
// (the Host it called), at a name of this computer's (ownHost): an IP,
// localhost, MAGPIE_PUBLIC_URL's or its own host name. So a page elsewhere
// can't make keys through a visitor's browser, neither by its own Origin,
// by Origin "null" from a sandboxed frame, at a localhost subdomain WebKit
// asks the DNS for, nor by a name of its own rebound to this computer. A
// request no browser sent (curl, a script) carries none of a browser's
// marks and is judged on the password alone.
func joinRefusal(r *http.Request) string {
if !fromBrowser(r) {
return ""
}
if !ownHost(r.Host) {
return "open the join page at this computer's address (an IP, or MAGPIE_PUBLIC_URL's name), not " + r.Host
}
origin := r.Header.Get("Origin")
if origin == "" || origin == "null" {
return "a browser joins from the join page itself"
}
u, err := url.Parse(origin)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Path != "" ||
hostPort(u.Host, u.Scheme) != hostPort(r.Host, u.Scheme) {
return "a browser joins from the join page itself, not " + origin
}
if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" {
return "a browser joins from the join page itself"
}
return ""
}
// joinKey makes a gateway key for a computer that knows the join password.
// Neither the password nor the key is logged; the key goes back in the
// body alone, never cached.
func (s *Server) joinKey(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if why := joinRefusal(r); why != "" {
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why)
writeError(w, provider.Chat, http.StatusForbidden, why)
return
}
if !access.JoinOn() {
writeError(w, provider.Chat, http.StatusNotFound, "joining with a password is off on this magpie")
return
}
if !local(r) {
if over, retry := tooManyJoins(); over {
w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1))
writeError(w, provider.Chat, http.StatusTooManyRequests, "too many tries to join; slow down")
return
}
}
var in struct {
Password string `json:"password"`
Name string `json:"name"`
}
b, _ := io.ReadAll(io.LimitReader(r.Body, 8<<10))
if json.Unmarshal(b, &in) != nil {
writeError(w, provider.Chat, http.StatusBadRequest, `send {"password": "…", "name": "this computer's name"}`)
return
}
if !access.JoinPasswordOK(in.Password) {
log.Printf("refused %s %s from %s: wrong join password", r.Method, r.URL.Path, r.RemoteAddr)
writeError(w, provider.Chat, http.StatusUnauthorized, "wrong password")
return
}
name := joinKeyName(in.Name, clientIP(r))
secret, err := access.Update("add-key", access.Change{Name: name})
if err != nil {
writeError(w, provider.Chat, http.StatusInternalServerError, err.Error())
return
}
who, _ := access.Authenticate(secret)
log.Printf("made gateway key %s (%s) for a computer that joined from %s", who.KeyID, name, r.RemoteAddr)
writeJSON(w, http.StatusCreated, map[string]string{"key": secret, "id": who.KeyID, "name": name})
}
// joinKeyName is the name typed, one line of at most 120 characters, or
// "Joined from <address>".
func joinKeyName(typed, ip string) string {
name := strings.Join(strings.Fields(strings.Map(func(r rune) rune {
if r < 32 || r == 127 {
return ' '
}
return r
}, typed)), " ")
if utf8.RuneCountInString(name) > 120 {
name = string([]rune(name)[:119]) + "…"
}
if name == "" {
name = "Joined from " + ip
if ip == "" {
name = "Joined"
}
}
return name
}
+261
View File
@@ -0,0 +1,261 @@
package gateway
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/settings"
)
const joinPw = "correct horse battery"
// joinGateway is a shared gateway with a join password set, its join
// bucket full and on a clock the test moves.
func joinGateway(t *testing.T) (http.Handler, *time.Time) {
t.Helper()
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
newCaller(t)
if err := access.SetJoinPassword(joinPw); err != nil {
t.Fatal(err)
}
resetJoinThrottle()
now := time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC)
joinThrottle.Lock()
joinThrottle.now = func() time.Time { return now }
joinThrottle.Unlock()
t.Cleanup(resetJoinThrottle)
return lanGuard(New().Handler()), &now
}
type joinReq struct {
from, host, body string
header map[string]string
}
func (q joinReq) do(h http.Handler) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", joinData, strings.NewReader(q.body))
r.RemoteAddr = q.from
if q.from == "" {
r.RemoteAddr = "192.168.1.9:5000"
}
r.Host = q.host
if q.host == "" {
r.Host = "192.168.1.5:3425"
}
r.Header.Set("Content-Type", "application/json")
for k, v := range q.header {
r.Header.Set(k, v)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func joinBody(pw, name string) string {
b, _ := json.Marshal(map[string]string{"password": pw, "name": name})
return string(b)
}
// the join page's own POST, as a browser sends it
var joinPageHeaders = map[string]string{
"Origin": "http://192.168.1.5:3425",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"User-Agent": "Mozilla/5.0",
}
// EV_John_Liu on X: another computer on the network opens /join without a
// key, types the password, and gets a gateway key of its own, named for
// it, which works at once and stops when removed in Gateway keys.
func TestJoinMakesARevocableKey(t *testing.T) {
h, _ := joinGateway(t)
var logs bytes.Buffer
was := log.Writer()
log.SetOutput(&logs)
t.Cleanup(func() { log.SetOutput(was) })
page := keyPageReq{method: "GET", path: JoinPagePath, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h)
if page.Code != 200 || !strings.Contains(page.Body.String(), `id="join"`) {
t.Fatal("join page", page.Code)
}
open := keyPageReq{method: "GET", path: joinData, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h)
if open.Code != 200 || strings.TrimSpace(open.Body.String()) != `{"open":true}` {
t.Fatal("open", open.Code, open.Body.String())
}
w := joinReq{body: joinBody(joinPw, "Studio\nMac mini"), header: joinPageHeaders}.do(h)
if w.Code != http.StatusCreated {
t.Fatal(w.Code, w.Body.String())
}
if cc := w.Header().Get("Cache-Control"); cc != "no-store" {
t.Error("Cache-Control", cc)
}
var got struct{ Key, ID, Name string }
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || got.Key == "" {
t.Fatal(err, w.Body.String())
}
if got.Name != "Studio Mac mini" {
t.Errorf("name %q", got.Name)
}
keys, _ := access.List()
found := false
for _, k := range keys {
found = found || (k.ID == got.ID && k.Name == "Studio Mac mini")
}
if !found {
t.Fatalf("no key %s in %+v", got.ID, keys)
}
me := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", host: "192.168.1.5:3425", header: map[string]string{"Authorization": "Bearer " + got.Key}}.do(h)
if me.Code != 200 {
t.Fatal("the new key", me.Code, me.Body.String())
}
if _, err := access.Update("remove-key", access.Change{Key: got.ID}); err != nil {
t.Fatal(err)
}
me = keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", host: "192.168.1.5:3425", header: map[string]string{"Authorization": "Bearer " + got.Key}}.do(h)
if me.Code != 401 {
t.Fatal("a removed key", me.Code)
}
// a name left empty is the address it joined from; curl (no browser)
// joins on the password alone
w = joinReq{body: joinBody(joinPw, "")}.do(h)
if w.Code != http.StatusCreated || !strings.Contains(w.Body.String(), `"name":"Joined from 192.168.1.9"`) {
t.Fatal(w.Code, w.Body.String())
}
if strings.Contains(logs.String(), got.Key) || strings.Contains(logs.String(), joinPw) {
t.Errorf("a secret in the log: %s", logs.String())
}
}
// A wrong password is 401, and every try from another machine takes from
// the join's bucket: past the burst it is 429 with Retry-After, the right
// password too, until the bucket refills.
func TestJoinHoldsAGuesser(t *testing.T) {
h, now := joinGateway(t)
var logs bytes.Buffer
was := log.Writer()
log.SetOutput(&logs)
t.Cleanup(func() { log.SetOutput(was) })
for i := range joinBurst {
if w := (joinReq{body: joinBody("guess-"+string(rune('a'+i))+"-wrong", "")}).do(h); w.Code != 401 {
t.Fatal(i, w.Code, w.Body.String())
}
}
w := joinReq{body: joinBody(joinPw, "")}.do(h)
if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") == "" {
t.Fatal("past the burst", w.Code, w.Header())
}
if strings.Contains(w.Body.String(), `"key"`) {
t.Fatal("a key past the burst", w.Body.String())
}
if strings.Contains(logs.String(), "guess-") {
t.Errorf("a password in the log: %s", logs.String())
}
*now = now.Add(joinRefill)
if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != http.StatusCreated {
t.Fatal("after a refill", w.Code, w.Body.String())
}
if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != http.StatusTooManyRequests {
t.Fatal("one token a refill", w.Code)
}
}
// A page elsewhere can't make keys through a visitor's browser: Origin
// null, another site, a *.localhost name, a name of its own rebound to
// this computer, a cross-site fetch and a browser's POST with no Origin
// are refused, before the password is judged; none makes a key.
func TestJoinRefusesOtherPages(t *testing.T) {
h, _ := joinGateway(t)
browser := func(extra map[string]string) map[string]string {
m := map[string]string{"User-Agent": "Mozilla/5.0", "Sec-Fetch-Mode": "cors"}
for k, v := range extra {
m[k] = v
}
return m
}
for name, q := range map[string]joinReq{
"null": {header: browser(map[string]string{"Origin": "null"})},
"another site": {header: browser(map[string]string{"Origin": "https://evil.example"})},
"localhost sub": {header: browser(map[string]string{"Origin": "http://evil.localhost:3425"})},
"localhost host": {host: "evil.localhost:3425", from: "127.0.0.1:5000",
header: browser(map[string]string{"Origin": "http://evil.localhost:3425"})},
"rebound": {host: "evil.example:3425", from: "127.0.0.1:5000",
header: browser(map[string]string{"Origin": "http://evil.example:3425"})},
"rebound remote": {host: "evil.example:3425",
header: browser(map[string]string{"Origin": "http://evil.example:3425"})},
"cross-site": {header: browser(map[string]string{"Origin": "http://192.168.1.5:3425", "Sec-Fetch-Site": "cross-site"})},
"no Origin": {header: browser(nil)},
"other port": {header: browser(map[string]string{"Origin": "http://192.168.1.5:8080"})},
} {
q.body = joinBody(joinPw, "x")
w := q.do(h)
if w.Code < 400 || strings.Contains(w.Body.String(), `"key"`) {
t.Errorf("%s: %d %s", name, w.Code, w.Body.String())
}
}
if keys, _ := access.List(); len(keys) != 0 {
t.Errorf("keys made: %+v", keys)
}
// and the page's own POST from this computer goes through
q := joinReq{from: "127.0.0.1:5000", host: "127.0.0.1:3425", body: joinBody(joinPw, "here"),
header: browser(map[string]string{"Origin": "http://127.0.0.1:3425", "Sec-Fetch-Site": "same-origin"})}
if w := q.do(h); w.Code != http.StatusCreated {
t.Fatal("own page", w.Code, w.Body.String())
}
}
// With no password set, or magpie not shared, nothing joins.
func TestJoinClosed(t *testing.T) {
h, _ := joinGateway(t)
if err := access.SetJoinPassword(""); err != nil {
t.Fatal(err)
}
if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != 404 {
t.Error("no password", w.Code, w.Body.String())
}
open := keyPageReq{method: "GET", path: joinData, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h)
if strings.TrimSpace(open.Body.String()) != `{"open":false}` {
t.Error("open", open.Body.String())
}
if err := access.SetJoinPassword(joinPw); err != nil {
t.Fatal(err)
}
s := settings.Load()
s.LAN = false
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code == http.StatusCreated {
t.Error("not shared", w.Code, w.Body.String())
}
if keys, _ := access.List(); len(keys) != 0 {
t.Errorf("keys made: %+v", keys)
}
}
func TestJoinKeyName(t *testing.T) {
long := strings.Repeat("é", 200)
for in, want := range map[string]string{
" Studio\tMac\x00 ": "Studio Mac",
"": "Joined from 10.0.0.2",
long: strings.Repeat("é", 119) + "…",
} {
if got := joinKeyName(in, "10.0.0.2"); got != want {
t.Errorf("%q: %q", in, got)
}
}
if got := joinKeyName("", ""); got != "Joined" {
t.Error(got)
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ var keySlotFree = []string{
"POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens",
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath,
ImageMCPPath, BrowserMCPPath, MemoryMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
HubMCPPath + "{agent}", HubMCPAll, "/",
HubMCPPath + "{agent}", HubMCPAll, "/", "POST " + joinData,
}
// Every route is judged for a key's MaxConcurrency: held (keySlotRoutes)
+110 -8
View File
@@ -79,6 +79,10 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px
.models button .mono { overflow-wrap: anywhere; }
.models button[aria-checked=true] { background: color-mix(in srgb, var(--accent) 12%, transparent); }
.empty { color: var(--sub); padding: 6px 2px; }
#join .field + input { margin-bottom: 2px; }
#once { margin-bottom: 4px; }
.once-row { margin-top: 6px; }
.once-row code { background: var(--code); border-radius: 6px; padding: 6px 8px; overflow-wrap: anywhere; }
[hidden] { display: none !important; }
@media (max-width: 480px) {
main { padding-top: 24px; }
@@ -105,6 +109,21 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px
</form>
</section>
<section id="join" hidden>
<h1 data-t="joinTitle">Join this magpie</h1>
<p class="sub" data-t="joinIntro">Get a gateway key of your own for this computer, and the setup for its agents.</p>
<form id="joinForm" autocomplete="off">
<label class="field" for="device" data-t="device">This computer’s name</label>
<input id="device" type="text" spellcheck="false" autocapitalize="off" autocomplete="off" maxlength="120">
<label class="field" for="pw" data-t="password">Password</label>
<div class="form-row">
<input id="pw" type="password" spellcheck="false" autocapitalize="off" autocomplete="off">
<button class="primary" id="joinGo" type="submit" data-t="joinGo">Join</button>
</div>
<p class="error" id="joinErr" role="alert" hidden></p>
</form>
</section>
<section id="info" hidden>
<div class="head">
<div class="grow">
@@ -115,6 +134,11 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px
<button class="link" id="forget" type="button" data-t="forget">Forget key</button>
</div>
<p class="error" id="err2" role="alert" hidden></p>
<div class="card" id="once" hidden>
<p class="sub" data-t="yourKey">Your gateway key</p>
<div class="row once-row"><code class="mono grow" id="onceKey"></code><span id="onceCopy"></span></div>
<p class="note" data-t="keepKey">Keep it somewhere safe: this page won’t show it again.</p>
</div>
<h2 data-t="limits">Limits</h2>
<div class="card" id="limits"></div>
@@ -150,6 +174,11 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px
"use strict";
const STR = {
en: {
joinTitle: "Join this magpie", joinIntro: "Get a gateway key of your own for this computer, and the setup for its agents.",
device: "This computer’s name", password: "Password", joinGo: "Join", wrongPw: "Wrong password.",
joinOff: "Joining with a password is off on this magpie. Ask whoever runs it for a gateway key.",
yourKey: "Your gateway key", keepKey: "Keep it somewhere safe: this page won’t show it again.",
magpieNote: "On a computer with magpie, run this in a terminal, or add Remote magpie in Providers with this address and key.",
title: "Your gateway key", intro: "Enter the gateway key you were given to see what it has used, what it may use and how to set up your agents.",
keyLabel: "Gateway key", go: "Continue", kept: "The key stays in this tab and is sent to this gateway alone.",
bad: "This isn't an enabled gateway key here. Check it with whoever gave it to you.", net: "The gateway didn't answer. Check the address and try again.",
@@ -170,6 +199,11 @@ const STR = {
pick: "The model is the one picked below.",
},
zh: {
joinTitle: "加入这个 magpie", joinIntro: "为这台电脑领取一个专属的网关密钥,并拿到它上面智能体的配置。",
device: "这台电脑的名字", password: "密码", joinGo: "加入", wrongPw: "密码不对。",
joinOff: "这个 magpie 没有开启密码加入。请向它的管理者要一个网关密钥。",
yourKey: "你的网关密钥", keepKey: "请妥善保存:这个页面不会再显示它。",
magpieNote: "装了 magpie 的电脑:在终端里运行这行,或在服务商里添加「远程 magpie」,填入这个地址和密钥。",
title: "你的网关密钥", intro: "输入你拿到的网关密钥,查看它的用量、可用的模型,以及怎样配置你的智能体。",
keyLabel: "网关密钥", go: "继续", kept: "密钥只保存在这个标签页里,只会发给这个网关。",
bad: "这不是此处可用的网关密钥。请向给你密钥的人确认。", net: "网关没有响应。请检查地址后重试。",
@@ -190,6 +224,11 @@ const STR = {
pick: "模型为下方选中的那个。",
},
"zh-TW": {
joinTitle: "加入這個 magpie", joinIntro: "為這台電腦領取一個專屬的閘道金鑰,並取得其上代理程式的設定。",
device: "這台電腦的名稱", password: "密碼", joinGo: "加入", wrongPw: "密碼不正確。",
joinOff: "這個 magpie 沒有開啟密碼加入。請向它的管理者索取閘道金鑰。",
yourKey: "你的閘道金鑰", keepKey: "請妥善保存:這個頁面不會再顯示它。",
magpieNote: "裝了 magpie 的電腦:在終端機執行這行,或在服務商中新增「遠端 magpie」,填入這個位址和金鑰。",
title: "你的閘道金鑰", intro: "輸入你拿到的閘道金鑰,查看它的用量、可用的模型,以及如何設定你的代理程式。",
keyLabel: "閘道金鑰", go: "繼續", kept: "金鑰只保存在這個分頁中,只會傳給這個閘道。",
bad: "這不是此處可用的閘道金鑰。請向提供金鑰的人確認。", net: "閘道沒有回應。請檢查位址後再試。",
@@ -210,6 +249,11 @@ const STR = {
pick: "模型為下方選取的那個。",
},
ja: {
joinTitle: "この magpie に参加", joinIntro: "このコンピュータ専用のゲートウェイキーと、エージェントの設定を受け取ります。",
device: "このコンピュータの名前", password: "パスワード", joinGo: "参加", wrongPw: "パスワードが違います。",
joinOff: "この magpie ではパスワードでの参加がオフです。管理者にゲートウェイキーを頼んでください。",
yourKey: "あなたのゲートウェイキー", keepKey: "安全な場所に保管してください。このページでは再表示されません。",
magpieNote: "magpie のあるコンピュータでは、ターミナルでこれを実行するか、プロバイダでこのアドレスとキーのリモート magpie を追加します。",
title: "あなたのゲートウェイキー", intro: "受け取ったゲートウェイキーを入力すると、使用量、使えるモデル、エージェントの設定方法が表示されます。",
keyLabel: "ゲートウェイキー", go: "続ける", kept: "キーはこのタブにだけ保存され、このゲートウェイにだけ送られます。",
bad: "ここで有効なゲートウェイキーではありません。キーをくれた人に確認してください。", net: "ゲートウェイから応答がありません。アドレスを確認して、もう一度お試しください。",
@@ -230,6 +274,11 @@ const STR = {
pick: "モデルは下で選んだものです。",
},
de: {
joinTitle: "Diesem magpie beitreten", joinIntro: "Holen Sie sich einen eigenen Zugangsschlüssel für diesen Computer und die Einrichtung seiner Agenten.",
device: "Name dieses Computers", password: "Passwort", joinGo: "Beitreten", wrongPw: "Falsches Passwort.",
joinOff: "Beitreten mit Passwort ist bei diesem magpie aus. Bitten Sie den Betreiber um einen Zugangsschlüssel.",
yourKey: "Ihr Zugangsschlüssel", keepKey: "Bewahren Sie ihn sicher auf: Diese Seite zeigt ihn nicht noch einmal.",
magpieNote: "Auf einem Computer mit magpie im Terminal ausführen, oder unter Anbieter ein Remote-magpie mit dieser Adresse und diesem Schlüssel hinzufügen.",
title: "Ihr Zugangsschlüssel", intro: "Geben Sie den Zugangsschlüssel ein, den Sie bekommen haben, um seine Nutzung, die erlaubten Modelle und die Einrichtung Ihrer Agenten zu sehen.",
keyLabel: "Zugangsschlüssel", go: "Weiter", kept: "Der Schlüssel bleibt in diesem Tab und wird nur an dieses Gateway gesendet.",
bad: "Das ist hier kein aktiver Zugangsschlüssel. Fragen Sie, wer ihn Ihnen gegeben hat.", net: "Das Gateway antwortet nicht. Prüfen Sie die Adresse und versuchen Sie es erneut.",
@@ -263,14 +312,16 @@ const LANG = (() => {
const t = (k, v) => String(STR[LANG][k] ?? STR.en[k] ?? k).replace(/\{(\w+)\}/g, (_, n) => (v && n in v ? v[n] : ""));
document.documentElement.lang = LANG;
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t(e.dataset.t); });
document.title = t("title") + " · magpie";
// /join is the same page, opened to join with a password
const JOINING = /\/join\/?$/.test(location.pathname);
document.title = t(JOINING ? "joinTitle" : "title") + " · magpie";
const $ = (id) => document.getElementById(id);
$("filter").placeholder = t("filter");
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
// the gateway's address is where this page was opened, less "/me": a
// the gateway's address is where this page was opened, less "/me" or "/join": a
// reverse proxy that serves magpie under a path keeps it
const BASE = location.origin + location.pathname.replace(/\/me\/?$/, "");
const BASE = location.origin + location.pathname.replace(/\/(me|join)\/?$/, "");
const PLACEHOLDER = "YOUR_GATEWAY_KEY";
const STORE = "magpie-key";
let key = "", data = null, model = "", tab = "claude";
@@ -312,8 +363,42 @@ $("form").addEventListener("submit", async (e) => {
});
$("forget").onclick = () => {
key = ""; data = null; store.set("");
$("info").hidden = true; $("signin").hidden = false; $("key").focus();
$("once").hidden = true;
signedOut();
};
// signedOut: the form to sign in with a key, or on /join the one to join with
function signedOut() {
$("info").hidden = true;
$("signin").hidden = JOINING; $("join").hidden = !JOINING;
$(JOINING ? "device" : "key").focus();
}
// joining: the password makes a gateway key of this computer's own, shown
// once, then the page is that key's, its setup filled in with it
$("joinForm").addEventListener("submit", async (e) => {
e.preventDefault();
const pw = $("pw").value;
if (!pw) return $("pw").focus();
$("joinGo").disabled = true;
$("joinErr").hidden = true;
const fail = (m) => { $("joinErr").textContent = m; $("joinErr").hidden = false; };
try {
const res = await fetch(BASE + "/v1/magpie/join", { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: pw, name: $("device").value.trim() }), cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer" });
if (!res.ok) return fail(res.status === 401 ? t("wrongPw") : res.status === 404 ? t("joinOff") : why(res.status));
const j = await res.json();
$("pw").value = "";
key = j.key; store.set(key);
$("onceKey").textContent = key;
$("onceCopy").replaceChildren(copyBtn(key));
$("once").hidden = false;
$("withKey").checked = true;
const r = await load(key);
if (r.ok) return show(r.body);
fail(why(r.status));
} catch { fail(t("net")); }
finally { $("joinGo").disabled = false; }
});
$("refresh").onclick = async () => {
$("err2").hidden = true;
try {
@@ -328,7 +413,7 @@ $("filter").oninput = () => drawModels();
function show(d) {
data = d;
$("signin").hidden = true; $("info").hidden = false;
$("signin").hidden = true; $("join").hidden = true; $("info").hidden = false;
$("name").textContent = d.name || "—";
drawLimits(); drawUsage();
const ids = (d.models || []).map((m) => m.id);
@@ -389,7 +474,7 @@ function drawUsage() {
if (!top.children.length) top.append(el("li", "empty", t("none")));
}
const TABS = [["claude", "Claude Code"], ["codex", "Codex"], ["openai", null], ["curl", null]];
const TABS = [["claude", "Claude Code"], ["codex", "Codex"], ["magpie", "magpie"], ["openai", null], ["curl", null]];
function drawTabs() {
const box = $("tabs");
box.replaceChildren();
@@ -449,6 +534,11 @@ function drawSetup() {
"model = " + q(m), 'model_provider = "magpie"', "",
"[model_providers.magpie]", 'name = "magpie"', "base_url = " + q(v1), 'wire_api = "responses"', "experimental_bearer_token = " + q(k),
].join("\n"));
} else if (tab === "magpie") {
// another computer's magpie takes this one as a provider, Remote
// magpie, and wires its own agents to it
$("tabNote").textContent = t("magpieNote");
block("", "magpie provider add remote-magpie " + sh(k) + " url=" + sh(BASE));
} else if (tab === "openai") {
$("tabNote").textContent = t("oaiNote");
const kv = el("div", "kv");
@@ -485,14 +575,26 @@ function drawModels() {
}
(async () => {
if (JOINING) {
signedOut();
// whether a password is set to join with; a key this tab already
// holds is shown below as on /me
fetch(BASE + "/v1/magpie/join", { cache: "no-store", credentials: "omit" })
.then((r) => r.ok ? r.json() : { open: r.status !== 403 && r.status !== 404, status: r.status })
.then((j) => {
if (j.open) return;
$("joinErr").textContent = j.status === 403 ? t("notShared") : t("joinOff"); $("joinErr").hidden = false;
$("joinGo").disabled = true;
}, () => {});
}
const k = store.get();
if (!k) return $("key").focus();
if (!k) return signedOut();
try {
const r = await load(k);
if (r.ok) { key = k; return show(r.body); }
if (r.status === 401) store.set("");
} catch {}
$("key").focus();
signedOut();
})();
</script>
</body>
+7
View File
@@ -620,6 +620,13 @@ func lanGuard(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
return
}
// so is the join page, and its route carries a password, not a
// key: the handler judges the password, the browser that sent it
// and how often it is tried (join.go)
if remote && (joinPageOpen(r) || joinAsked(r)) {
next.ServeHTTP(w, r)
return
}
// a link the image server handed out opens with its own token
// and no key (imageTokenAsked); the handler judges the token, and
// refuses one that opens nothing as a request without a key
+2
View File
@@ -31,6 +31,8 @@ var clientPrefixes = []string{
// the key page (KeyPagePath): a key's holder opens it at the address
// they give their agents
KeyPagePath,
// and the join page (JoinPagePath), at the same address
JoinPagePath,
}
// ClientPath: p is one of the gateway's client routes, which `magpie web`
+4
View File
@@ -43,6 +43,10 @@ var readOnlyRoutes = map[string]bool{
"GET " + OwnMCPPath: true,
"GET " + KeyPagePath: true,
"GET " + keyPageData: true,
// the join carries a password, not a key (join.go)
"GET " + JoinPagePath: true,
"GET " + joinData: true,
"POST " + joinData: true,
// a proof carries no key, and answers none (remote_prove.go)
"POST " + provider.RemoteProvePath: true,
}
+5
View File
@@ -427,6 +427,9 @@ type settingsJSON struct {
MTLSCerts []mtlsCert `json:"mtlsCerts,omitempty"`
MTLSErr string `json:"mtlsError,omitempty"`
MTLSSaved string `json:"mtlsSaved,omitempty"`
// JoinOn: a password is set to join with (join.go); the password
// itself is never sent
JoinOn bool `json:"joinOn,omitempty"`
// Dir is the data folder beside a portable magpie (#508)
Portable bool `json:"portable,omitempty"`
// Log is the log the desktop app writes (applog), as shown; "" for a
@@ -829,6 +832,7 @@ func settingsState() settingsJSON {
if s.LAN || s.OnNetwork || s.MTLS {
s.MTLSCerts, s.MTLSErr = mtlsCerts()
}
s.JoinOn = access.JoinOn()
if s.LAN || gateway.OnNetwork() {
s.PublicURL = gateway.PublicURL()
s.PublicKind = gateway.URLKind(s.PublicURL)
@@ -1536,6 +1540,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
backupRoutes(mux, w)
dataFolderRoutes(mux, w)
mtlsRoutes(mux, w)
joinRoutes(mux)
uninstallRoutes(mux, w)
archiveRoutes(mux)
libraryRoutes(mux, w)
+32
View File
@@ -2741,6 +2741,14 @@ const I18N = {
"Web pages that may call magpie": "允许调用 magpie 的网页",
"Allowed addresses": "允许的地址",
"Require a client certificate": "要求客户端证书",
"Join with a password": "加入密码",
"Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents": "其他电脑打开加入链接并输入这个密码,即可领取自己的网关密钥和智能体配置",
"New password": "新密码",
"Set": "设置",
"Turn off joining": "关闭加入",
"Join link": "加入链接",
"Use a password of at least 8 characters": "请使用至少 8 个字符的密码",
"Use a password of at most 1024 bytes": "请使用不超过 1024 字节的密码",
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他电脑只能经 HTTPS、凭这里签发的证书连到 magpie,有网关密钥也不行;本机始终可以",
"Client certificates": "客户端证书",
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "为设备保存到「下载」:证书、私钥和 magpie 的 CA",
@@ -7672,6 +7680,14 @@ const I18N = {
"Web pages that may call magpie": "允許呼叫 magpie 的網頁",
"Allowed addresses": "允許的位址",
"Require a client certificate": "要求用戶端憑證",
"Join with a password": "加入密碼",
"Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents": "其他電腦開啟加入連結並輸入這個密碼,即可領取自己的閘道金鑰和代理程式設定",
"New password": "新密碼",
"Set": "設定",
"Turn off joining": "關閉加入",
"Join link": "加入連結",
"Use a password of at least 8 characters": "請使用至少 8 個字元的密碼",
"Use a password of at most 1024 bytes": "請使用不超過 1024 位元組的密碼",
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他電腦只能經 HTTPS、憑這裡簽發的憑證連到 magpie,有閘道金鑰也不行;本機始終可以",
"Client certificates": "用戶端憑證",
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "為裝置儲存到「下載」:憑證、私鑰和 magpie 的 CA",
@@ -12581,6 +12597,14 @@ const I18N = {
"Web pages that may call magpie": "magpie を呼び出せる Web ページ",
"Allowed addresses": "許可するアドレス",
"Require a client certificate": "クライアント証明書を必須にする",
"Join with a password": "パスワードで参加",
"Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents": "ほかのコンピュータが参加リンクを開いてこのパスワードを入力すると、専用のゲートウェイキーとエージェントの設定を受け取れます",
"New password": "新しいパスワード",
"Set": "設定",
"Turn off joining": "参加をオフにする",
"Join link": "参加リンク",
"Use a password of at least 8 characters": "8 文字以上のパスワードにしてください",
"Use a password of at most 1024 bytes": "1024 バイト以下のパスワードにしてください",
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "他のコンピューターは、ここで発行した証明書を持って HTTPS でのみ magpie に接続できます。ゲートウェイキーがあっても同じです。このコンピューターは常に接続できます",
"Client certificates": "クライアント証明書",
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "デバイス用に「ダウンロード」へ保存:証明書、その鍵、magpie の CA",
@@ -17521,6 +17545,14 @@ const I18N = {
"Web pages that may call magpie": "Webseiten, die magpie aufrufen dürfen",
"Allowed addresses": "Erlaubte Adressen",
"Require a client certificate": "Client-Zertifikat verlangen",
"Join with a password": "Beitritt mit Passwort",
"Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents": "Andere Computer öffnen den Beitrittslink und geben dieses Passwort ein, um einen eigenen Zugangsschlüssel und die Einrichtung ihrer Agenten zu erhalten",
"New password": "Neues Passwort",
"Set": "Festlegen",
"Turn off joining": "Beitritt ausschalten",
"Join link": "Beitrittslink",
"Use a password of at least 8 characters": "Verwenden Sie ein Passwort mit mindestens 8 Zeichen",
"Use a password of at most 1024 bytes": "Verwenden Sie ein Passwort mit höchstens 1024 Bytes",
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "Andere Computer erreichen magpie nur über HTTPS mit einem hier ausgestellten Zertifikat, auch mit Gateway-Schlüssel; dieser Computer immer",
"Client certificates": "Client-Zertifikate",
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "Für das Gerät in „Downloads“ gespeichert: das Zertifikat, sein Schlüssel und magpies CA",
@@ -509,6 +509,58 @@ function renderLAN(s) {
update();
}
if (sub) row(head || t("In a container"), sub, "").classList.add("lan-container");
renderJoin(s, box);
}
// renderJoin: Join with a password (EV_John_Liu on X), under the shared
// address. With a password set, another computer opens <address>/join,
// types it, and gets a gateway key of its own, named for it in Gateway
// keys, and the setup for its agents. Only a hash is kept: the field is
// always empty, and a password typed in it replaces the one set.
let joinDraft = { value: "", err: "" };
function renderJoin(s, box) {
const d = joinDraft;
const set = (password) => writingPrefs(api("settings/join", { password }))
.then((ns) => { prefs = ns; joinDraft = { value: "", err: "" }; renderSettings(); status(t("Saved"), "ok", 1500); })
.catch((e) => { d.err = t(e.message); status(d.err, "err"); renderSettings(); });
const r = el("div", "row pref rule-row join-row");
const who = el("div", "who");
who.append(el("div", "name", t("Join with a password")),
el("div", "sub" + (d.err ? " err" : ""), d.err || t("Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents")));
const field = input(d.value, s.joinOn ? t("New password") : t("Password"));
field.type = "password";
field.className = "words rule-match join-pw";
field.setAttribute("aria-label", t("Password"));
field.autocomplete = "new-password";
field.spellcheck = false;
const go = el("button", "text", t("Set"));
go.type = "button";
go.onclick = () => {
d.value = field.value;
if (!d.value) return field.focus();
set(d.value);
};
field.oninput = () => { d.value = field.value; };
field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go.onclick(); };
const val = el("div", "val rule-add");
val.append(field, go);
if (s.joinOn) {
const off = el("button", "text join-off", t("Turn off joining"));
off.type = "button";
off.onclick = () => set("");
val.append(off);
}
r.append(who, val);
box.append(r);
if (!s.joinOn || !lanSelectedURL) return;
const link = lanSelectedURL + "/join";
const lr = el("div", "row pref join-link-row");
const lw = el("div", "who");
lw.append(el("div", "name", t("Join link")));
const lv = el("div", "val");
lv.append(el("code", "", link), copyBtn(link, t("Join link")));
lr.append(lw, lv);
box.append(lr);
}
// renderWebPage: Browser access, the app's own page served to a browser
+31
View File
@@ -0,0 +1,31 @@
package gui
import (
"encoding/json"
"net/http"
"github.com/yetone/magpie/internal/access"
)
// joinRoutes: Settings → Local network → Join with a password (EV_John_Liu
// on X). A password set here opens the gateway's /join page to other
// computers while magpie is shared: each that types it gets a gateway key
// of its own, removed in Gateway keys like any other. "" turns it off.
// The password is kept as a hash only (access.SetJoinPassword) and never
// sent back.
func joinRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/settings/join", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
Password string `json:"password"`
}
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 8<<10)).Decode(&in); err != nil {
fail(rw, err)
return
}
if err := access.SetJoinPassword(in.Password); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
}
+209
View File
@@ -0,0 +1,209 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Join with a password (EV_John_Liu on X): on a magpie shared on the
// network, Settings › Local network sets a password, and another computer
// opens <address>/join, types it and a name for itself, and gets a gateway
// key of its own, shown once, with its setup (Claude Code, Codex, another
// magpie, OpenAI-compatible) filled in. The join page is the gateway's own
// keypage.html, served under its Content-Security-Policy; the key never
// rides in an address. Chromium and WebKit, 390px, every language; no
// backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
const html = fs.readFileSync(path.resolve(__dirname, "../../gateway/keypage.html"), "utf8");
const CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
const BASE = "http://192.168.1.20:3425";
const PW = "correct horse";
const KEY = "sk-magpie-joined-0123456789";
const ME = {
name: "Studio Mac", readOnly: false, version: "dev", limits: [],
usage: { today: { calls: 0 }, "7d": { calls: 0 }, "30d": { calls: 0 } }, topModels: [],
models: [{ id: "plan/m1", label: "m1 · Plan" }],
};
const LOCALE = { en: "en-US", zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" };
const TITLE = { en: "Join this magpie", zh: "加入这个 magpie", "zh-TW": "加入這個 magpie", ja: "この magpie に参加", de: "Diesem magpie beitreten" };
async function openJoin(browser, lang, { open = true } = {}) {
const page = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: LOCALE[lang], reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const seen = { urls: [], errors: [], posts: [] };
page.on("pageerror", (e) => seen.errors.push(e.message));
page.on("request", (r) => seen.urls.push(r.url()));
await page.route("**/*", (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/join") return route.fulfill({ contentType: "text/html; charset=utf-8", headers: { "Content-Security-Policy": CSP }, body: html });
if (url.pathname === "/v1/magpie/join" && req.method() === "GET") return route.fulfill({ json: { open } });
if (url.pathname === "/v1/magpie/join") {
const body = req.postDataJSON();
seen.posts.push(body);
if (!open) return route.fulfill({ status: 404, json: { error: { message: "off" } } });
if (body.password !== PW) return route.fulfill({ status: 401, json: { error: { message: "wrong password" } } });
return route.fulfill({ status: 201, json: { key: KEY, id: "k9", name: body.name } });
}
if (url.pathname === "/v1/magpie/me") {
if (req.headers().authorization !== "Bearer " + KEY) return route.fulfill({ status: 401, json: {} });
return route.fulfill({ json: ME });
}
return route.fulfill({ status: 404, body: "" });
});
await page.goto(BASE + "/join");
return { page, seen };
}
const assets = path.resolve(__dirname, "../assets");
const file = async (route, url) => {
const f = 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(f)];
await route.fulfill({ body: await fsp.readFile(f), contentType });
};
function settingsServer(lang, posts, over) {
const s = {
theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.400", dir: "/config/magpie",
gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", login: false,
visionModels: [], imageGenModels: [], allowIPs: [], mtlsCerts: [],
lan: true, lanURLs: [BASE], fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, ...over,
};
return async (route) => {
const url = new URL(route.request().url());
const json = (data, status = 200) => route.fulfill({ json: data, status });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web: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" }, fx: s.fx });
if (url.pathname === "/api/settings") return json(s);
if (url.pathname === "/api/settings/join") {
const body = route.request().postDataJSON();
posts.push(body);
if (body.password && body.password.length < 8) return json({ error: "Use a password of at least 8 characters" }, 400);
s.joinOn = !!body.password;
return json(s);
}
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({});
await file(route, url);
};
}
const STRINGS = ["Join with a password", "Other computers open the join link and type this password to get a gateway key of their own and the setup for their agents",
"New password", "Set", "Turn off joining", "Join link", "Use a password of at least 8 characters", "Use a password of at most 1024 bytes"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": join with a password (EV_John_Liu on X)", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang + ": a computer joins and gets its key and setup", async () => {
const { page, seen } = await openJoin(browser, lang);
assert.equal(await page.locator("#join h1").textContent(), TITLE[lang]);
assert.equal(await page.locator("#signin").isHidden(), true);
// a wrong password is told so, and makes nothing
await page.fill("#device", "Studio Mac");
await page.fill("#pw", "guess-guess");
await page.click("#joinGo");
await page.locator("#joinErr").waitFor();
const err = await page.locator("#joinErr").textContent();
if (lang !== "en") assert.doesNotMatch(err, /Wrong password/);
assert.equal(await page.locator("#info").isHidden(), true);
await page.fill("#pw", PW);
await page.click("#joinGo");
await page.locator("#info").waitFor();
assert.deepEqual(seen.posts.at(-1), { password: PW, name: "Studio Mac" });
assert.equal(await page.locator("#name").textContent(), "Studio Mac");
assert.equal(await page.locator("#onceKey").textContent(), KEY);
assert.equal(await page.locator("#pw").inputValue(), "", "the password is taken out of the field");
// another magpie's setup, with this address and the key
await page.click(`#tabs [data-tab="magpie"]`);
const snip = await page.locator("#snip pre").first().textContent();
assert.equal(snip, `magpie provider add remote-magpie '${KEY}' url='${BASE}'`);
await page.click(`#tabs [data-tab="claude"]`);
assert.match(await page.locator("#snip pre").first().textContent(), new RegExp(`"ANTHROPIC_BASE_URL": "${BASE}"[\\s\\S]*"${KEY}"`));
// no key or password in an address, nothing thrown, nothing wider than the phone
for (const u of seen.urls) assert.ok(!u.includes(KEY) && !u.includes(encodeURIComponent(PW)) && !u.includes("guess"), u);
assert.deepEqual(seen.errors, []);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
// forgetting the key comes back to the join form, the key gone
await page.click("#forget");
await page.locator("#join").waitFor();
assert.equal(await page.locator("#once").isHidden(), true);
await page.context().close();
});
}
await t.test("joining off: the form says so and sends nothing", async () => {
const { page, seen } = await openJoin(browser, "zh", { open: false });
await page.locator("#joinErr").waitFor();
assert.match(await page.locator("#joinErr").textContent(), /没有开启密码加入/);
assert.equal(await page.locator("#joinGo").isDisabled(), true);
assert.deepEqual(seen.posts, []);
await page.context().close();
});
await t.test("every language has the Settings strings", async () => {
const page = await (await browser.newContext({ viewport: { width: 390, height: 640 } })).newPage();
await page.route("**/*", settingsServer("en", [], {}));
await watchSettingsReads(page);
await page.goto("http://127.0.0.1:4999/?view=settings&tab=network");
await settingsDrawn(page);
for (const lang of ["zh", "zh-TW", "ja", "de"]) {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k] || I18N[lang][k] === k), [lang, STRINGS]);
assert.deepEqual(missing, [], lang);
}
await page.context().close();
});
for (const lang of ["en", "zh"]) {
await t.test(lang + ": Settings sets the password, shows the link, turns it off", async () => {
const posts = [];
const page = await (await browser.newContext({ viewport: { width: 390, height: 640 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", settingsServer(lang, posts, {}));
await watchSettingsReads(page);
await page.goto("http://127.0.0.1:4999/?view=settings&tab=network");
await settingsDrawn(page);
const w = {};
for (const s of STRINGS) w[s] = await page.evaluate((s) => t(s), s);
const row = page.locator("#lanList .join-row");
await row.waitFor();
assert.equal((await row.locator(".name").textContent()).trim(), w["Join with a password"]);
assert.equal(await page.locator("#lanList .join-link-row").count(), 0);
const field = row.locator("input.join-pw");
assert.equal(await field.getAttribute("type"), "password");
await reach(page, field);
// too short: the gateway's word, in the page's language
await field.fill("short");
await row.locator("button", { hasText: w["Set"] }).click();
await page.waitForFunction((m) => document.querySelector("#lanList .join-row .sub.err")?.textContent === m, w["Use a password of at least 8 characters"]);
await page.locator("#lanList .join-row input.join-pw").fill(PW);
await page.locator("#lanList .join-row button", { hasText: w["Set"] }).click();
const link = page.locator("#lanList .join-link-row code");
await link.waitFor();
assert.equal(await link.textContent(), BASE + "/join");
assert.deepEqual(posts.at(-1), { password: PW });
assert.equal(await page.locator("#lanList .join-row input.join-pw").inputValue(), "", "the password isn't kept in the field");
const bad = await page.evaluate(() => {
const right = document.querySelector("#lanList").getBoundingClientRect().right + 0.5;
return [...document.querySelectorAll("#lanList .join-row *, #lanList .join-link-row *")]
.filter((e) => e.getBoundingClientRect().right > right && !e.closest("code")).map((e) => e.className)
.concat(document.documentElement.scrollWidth > innerWidth ? ["page scrolls sideways"] : []);
});
assert.deepEqual(bad, []);
await page.locator("#lanList .join-row button.join-off").click();
await page.waitForFunction(() => !document.querySelector("#lanList .join-link-row"));
assert.deepEqual(posts.at(-1), { password: "" });
assert.deepEqual(errors, []);
await page.context().close();
});
}
});
}