package tunnel // Relay claims: the persistence behind relay mode (docs/relay-mode.md, // issue #738 Phase 1). A relay is a tunnel with a stable identity: the client // holds an Ed25519 keypair, and the hostname it is assigned on first claim // belongs to that keypair from then on. Reconnects prove the key and get the // same hostname back; nobody else can take it. // // Claims live in the gateway's own small SQLite database — deliberately not // the router registry, which stays a routing table. The gateway remains the // only writer. import ( "crypto/ed25519" "database/sql" "encoding/base64" "fmt" "time" _ "modernc.org/sqlite" ) type Claims struct{ sql *sql.DB } func OpenClaims(path string) (*Claims, error) { d, err := sql.Open("sqlite", path) if err != nil { return nil, err } d.SetMaxOpenConns(1) for _, p := range []string{ "PRAGMA journal_mode=WAL", "PRAGMA busy_timeout=5000", } { if _, err := d.Exec(p); err != nil { return nil, err } } if _, err := d.Exec(` CREATE TABLE IF NOT EXISTS relay_claims ( host TEXT PRIMARY KEY, pubkey TEXT NOT NULL UNIQUE, -- base64url raw ed25519 public key created_at INTEGER NOT NULL, last_seen INTEGER NOT NULL );`); err != nil { return nil, err } return &Claims{sql: d}, nil } // HostFor returns the hostname already claimed by pubkey ("" if none). func (c *Claims) HostFor(pubkey string) (string, error) { var host string err := c.sql.QueryRow(`SELECT host FROM relay_claims WHERE pubkey = ?`, pubkey).Scan(&host) if err == sql.ErrNoRows { return "", nil } return host, err } // Owner returns the pubkey that owns host ("" if unclaimed). func (c *Claims) Owner(host string) (string, error) { var pk string err := c.sql.QueryRow(`SELECT pubkey FROM relay_claims WHERE host = ?`, host).Scan(&pk) if err == sql.ErrNoRows { return "", nil } return pk, err } // Claim records host as owned by pubkey (first come, first kept). func (c *Claims) Claim(host, pubkey string) error { now := time.Now().Unix() _, err := c.sql.Exec( `INSERT INTO relay_claims(host, pubkey, created_at, last_seen) VALUES(?,?,?,?)`, host, pubkey, now, now) return err } // Touch updates last_seen for pubkey's claim. func (c *Claims) Touch(pubkey string) { _, _ = c.sql.Exec(`UPDATE relay_claims SET last_seen = ? WHERE pubkey = ?`, time.Now().Unix(), pubkey) } // DeleteByHost frees a claim: the hostname returns to the pool and whoever // held it can no longer reclaim it. func (c *Claims) DeleteByHost(host string) error { _, err := c.sql.Exec(`DELETE FROM relay_claims WHERE host = ?`, host) return err } // SweepIdle frees claims not seen for longer than idle, skipping any host in // keep (the currently-connected tunnels — a relay that has been online for // months without reconnecting is the opposite of abandoned). Returns the // freed hostnames. func (c *Claims) SweepIdle(idle time.Duration, keep map[string]bool) ([]string, error) { cutoff := time.Now().Add(-idle).Unix() rows, err := c.sql.Query(`SELECT host FROM relay_claims WHERE last_seen < ?`, cutoff) if err != nil { return nil, err } var stale []string for rows.Next() { var h string if err := rows.Scan(&h); err != nil { rows.Close() return nil, err } if !keep[h] { stale = append(stale, h) } } rows.Close() for _, h := range stale { if err := c.DeleteByHost(h); err != nil { return stale, err } } return stale, nil } // VerifyClaimSig checks that sig (base64url) signs nonce with pubkey // (base64url raw ed25519). func VerifyClaimSig(pubkey, nonce, sig string) error { pk, err := base64.RawURLEncoding.DecodeString(pubkey) if err != nil || len(pk) != ed25519.PublicKeySize { return fmt.Errorf("bad public key") } sg, err := base64.RawURLEncoding.DecodeString(sig) if err != nil { return fmt.Errorf("bad signature encoding") } if !ed25519.Verify(ed25519.PublicKey(pk), []byte(nonce), sg) { return fmt.Errorf("signature doesn't verify") } return nil }