Files
magpie/internal/access/join.go
T
yetone e053c337aa 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
2026-11-10 22:42:11 +08:00

149 lines
3.8 KiB
Go

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)
}