Files
waste-go/cmd/anchor/main.go

246 lines
5.9 KiB
Go
Raw Normal View History

Migrate to YAW/2 protocol: WebRTC transport, anchor signaling, nacl/box crypto Replace the original raw-TCP peer connections and Blowfish/RSA-era design with the YAW/2 protocol stack: Transport - internal/mesh/peer.go: raw TCP + manual ECDH replaced with pion/webrtc DataChannels (ICE, DTLS, SCTP). Peers negotiate via sealed offer/answer/ candidate exchange rather than direct dialling. - internal/nat: deleted — ICE subsumes everything this package was going to do. Signaling - cmd/anchor: new WebSocket signaling server (replaces cmd/relay). Verifies Ed25519 challenge/join signatures, routes opaque nacl/box blobs, broadcasts peer-join/peer-leave events. Never sees plaintext signaling content. - internal/anchor: new anchor client. Manages PeerConnection lifecycle, decides offerer by peer-id comparison, seals/opens signaling payloads with nacl/box, implements mesh.Anchor. Crypto (internal/crypto) - PeerID encoding: base64url → lowercase hex (64 chars, YAW/2 §2). - Sign/Verify: hex signatures throughout. - Added CurvePublicKey/CurvePrivateKey: X25519 keys derived from Ed25519 identity via Montgomery conversion (filippo.io/edwards25519), matching libsodium's crypto_sign_ed25519_*_to_curve25519. - Added SignalingBox/SignalingOpen: nacl/box (XSalsa20-Poly1305) seal/open for signaling payloads. Wire types (internal/proto) - ChatMessage gains Mid (random 16-byte hex) for mesh deduplication (§8). - FileChunk removed from PeerMessage — chunks go on a separate binary DataChannel labelled "f:<xid>"; FileDone added. - New types: SignalingPayload, AnchorMessage, HelloMessage, HelloBindString. - PeerID.Short() now returns first 16 hex chars grouped in 4s. - IPC: CmdConnect removed; CmdJoinNetwork/CmdLeaveNetwork added; EvtSessionReady added (fires when DataChannel opens and hello is received). IPC (internal/ipc) - join_network/leave_network replace connect (direct TCP dial). - Network joins are context-scoped: leave_network or client disconnect cancels the anchor connection cleanly. README updated to reflect new project layout, getting-started commands, IPC protocol, and roadmap state. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 17:48:14 +02:00
// waste-anchor: WebSocket signaling server for YAW/2.
// Deploy on your Hetzner VPS alongside a STUN server (coturn in STUN-only mode).
// The anchor never reads the content of "box" fields — it only routes sealed blobs.
package main
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"flag"
"log"
"net/http"
"sync"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
"github.com/waste-go/internal/proto"
)
func main() {
bind := flag.String("bind", "0.0.0.0:17339", "address to listen on")
flag.Parse()
a := newAnchor()
http.HandleFunc("/ws", a.handleWS)
log.Printf("anchor: listening on %s", *bind)
if err := http.ListenAndServe(*bind, nil); err != nil {
log.Fatalf("anchor: %v", err)
}
}
// ── Anchor ────────────────────────────────────────────────────────────────────
type client struct {
id string // hex peer id, set after join
net string // hashed network name, set after join
send chan proto.AnchorMessage
conn *websocket.Conn
}
type anchor struct {
mu sync.RWMutex
clients map[string]*client // keyed by hex peer id
}
func newAnchor() *anchor {
return &anchor{clients: make(map[string]*client)}
}
func (a *anchor) register(c *client) {
a.mu.Lock()
a.clients[c.id] = c
a.mu.Unlock()
}
func (a *anchor) unregister(c *client) {
if c.id == "" {
return
}
a.mu.Lock()
delete(a.clients, c.id)
a.mu.Unlock()
// Notify everyone in the same network.
leave := proto.AnchorMessage{Type: proto.AnchorPeerLeave, ID: c.id}
a.mu.RLock()
for _, peer := range a.clients {
if peer.net == c.net {
select {
case peer.send <- leave:
default:
}
}
}
a.mu.RUnlock()
log.Printf("anchor: peer left: %s", c.id[:min(8, len(c.id))])
}
// networkPeerIDs returns the hex ids of all peers in the same network as netHash.
func (a *anchor) networkPeerIDs(netHash, excludeID string) []string {
a.mu.RLock()
defer a.mu.RUnlock()
var ids []string
for id, c := range a.clients {
if c.net == netHash && id != excludeID {
ids = append(ids, id)
}
}
return ids
}
func (a *anchor) forwardTo(toID string, msg proto.AnchorMessage) bool {
a.mu.RLock()
c, ok := a.clients[toID]
a.mu.RUnlock()
if !ok {
return false
}
select {
case c.send <- msg:
return true
default:
return false
}
}
// ── WebSocket handler ─────────────────────────────────────────────────────────
func (a *anchor) handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true})
if err != nil {
log.Printf("anchor: ws accept: %v", err)
return
}
defer conn.Close(websocket.StatusNormalClosure, "bye")
c := &client{
send: make(chan proto.AnchorMessage, 64),
conn: conn,
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
// Send a challenge nonce immediately.
nonce := make([]byte, 16)
rand.Read(nonce)
nonceHex := hex.EncodeToString(nonce)
if err := wsjson.Write(ctx, conn, proto.AnchorMessage{
Type: proto.AnchorChallenge,
Nonce: nonceHex,
}); err != nil {
return
}
// Writer goroutine.
go func() {
for msg := range c.send {
if err := wsjson.Write(ctx, conn, msg); err != nil {
cancel()
return
}
}
}()
// Read loop.
for {
var msg proto.AnchorMessage
if err := wsjson.Read(ctx, conn, &msg); err != nil {
break
}
switch msg.Type {
case proto.AnchorJoin:
if msg.ID == "" || msg.Net == "" || msg.Sig == "" {
log.Printf("anchor: join missing fields from %s", r.RemoteAddr)
continue
}
pubBytes, err := hex.DecodeString(msg.ID)
if err != nil || len(pubBytes) != ed25519.PublicKeySize {
log.Printf("anchor: join: bad peer id from %s", r.RemoteAddr)
continue
}
sigBytes, err := hex.DecodeString(msg.Sig)
if err != nil {
log.Printf("anchor: join: bad sig from %s", r.RemoteAddr)
continue
}
Bring wire protocol into full YAW/2 spec compliance Five interop issues fixed against PROTOCOL.md: - Join signature now covers nonce_raw || net_ascii (64-char UTF-8 hex string) as specified in §5.1, not net_raw_bytes. Both anchor server and client updated to match. - Chat wire fields renamed to spec names: text/ts (Unix ms int64) replacing body/sent_at (ISO timestamp). Flat layout on PeerMessage matches §8 exactly; store and TUI updated accordingly. - Direct messages now use the spec "pm" type (flat {type,mid,text,ts}) instead of chat+to. Receiver reconstructs a ChatMessage with dm:<short-id> room for IPC/storage. §8 compliant. - File transfer message types changed to spec hyphenated names: file-offer, file-accept, file-cancel, file-done with spec field names (name/size not filename/size_bytes). §9 compliant. - DataChannel open-race (§14 gotcha #3) fixed with sync.Once: doOpen fires on OnOpen callback or immediately if the channel is already open when WireDataChannel is called (answerer race). Also fixes two bugs found during testing: - mid was missing from outgoing wire messages, causing all received messages to arrive with mid="" and collide on the UNIQUE DB constraint. mid is now included on all sent chat/pm messages; a random mid is generated for any received message that omits it. - Test scripts hardened: kill -9 + active lsof polling replaces blind sleep for port cleanup; join_network sent before peer_field queries (local_peer is now network-scoped and nil until joined). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-22 11:38:01 +02:00
// §5.1: sig covers nonce_raw || net_ascii (net as 64-char hex UTF-8 string)
signed := append(nonce, []byte(msg.Net)...)
Migrate to YAW/2 protocol: WebRTC transport, anchor signaling, nacl/box crypto Replace the original raw-TCP peer connections and Blowfish/RSA-era design with the YAW/2 protocol stack: Transport - internal/mesh/peer.go: raw TCP + manual ECDH replaced with pion/webrtc DataChannels (ICE, DTLS, SCTP). Peers negotiate via sealed offer/answer/ candidate exchange rather than direct dialling. - internal/nat: deleted — ICE subsumes everything this package was going to do. Signaling - cmd/anchor: new WebSocket signaling server (replaces cmd/relay). Verifies Ed25519 challenge/join signatures, routes opaque nacl/box blobs, broadcasts peer-join/peer-leave events. Never sees plaintext signaling content. - internal/anchor: new anchor client. Manages PeerConnection lifecycle, decides offerer by peer-id comparison, seals/opens signaling payloads with nacl/box, implements mesh.Anchor. Crypto (internal/crypto) - PeerID encoding: base64url → lowercase hex (64 chars, YAW/2 §2). - Sign/Verify: hex signatures throughout. - Added CurvePublicKey/CurvePrivateKey: X25519 keys derived from Ed25519 identity via Montgomery conversion (filippo.io/edwards25519), matching libsodium's crypto_sign_ed25519_*_to_curve25519. - Added SignalingBox/SignalingOpen: nacl/box (XSalsa20-Poly1305) seal/open for signaling payloads. Wire types (internal/proto) - ChatMessage gains Mid (random 16-byte hex) for mesh deduplication (§8). - FileChunk removed from PeerMessage — chunks go on a separate binary DataChannel labelled "f:<xid>"; FileDone added. - New types: SignalingPayload, AnchorMessage, HelloMessage, HelloBindString. - PeerID.Short() now returns first 16 hex chars grouped in 4s. - IPC: CmdConnect removed; CmdJoinNetwork/CmdLeaveNetwork added; EvtSessionReady added (fires when DataChannel opens and hello is received). IPC (internal/ipc) - join_network/leave_network replace connect (direct TCP dial). - Network joins are context-scoped: leave_network or client disconnect cancels the anchor connection cleanly. README updated to reflect new project layout, getting-started commands, IPC protocol, and roadmap state. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 17:48:14 +02:00
if !ed25519.Verify(ed25519.PublicKey(pubBytes), signed, sigBytes) {
log.Printf("anchor: join: sig verification failed for %s", msg.ID[:min(8, len(msg.ID))])
continue
}
c.id = msg.ID
c.net = msg.Net
a.register(c)
peers := a.networkPeerIDs(msg.Net, c.id)
if err := wsjson.Write(ctx, conn, proto.AnchorMessage{
Type: proto.AnchorJoined,
Peers: peers,
}); err != nil {
break
}
// Notify existing peers that someone new joined.
join := proto.AnchorMessage{Type: proto.AnchorPeerJoin, ID: c.id}
for _, pid := range peers {
a.forwardTo(pid, join)
}
log.Printf("anchor: peer joined: %s net=%s peers=%d", c.id[:min(8, len(c.id))], msg.Net[:8], len(peers))
case proto.AnchorTo:
if c.id == "" {
continue // not joined yet
}
if msg.To == "" || msg.Box == "" {
continue
}
fwd := proto.AnchorMessage{
Type: proto.AnchorFrom,
From: c.id,
Box: msg.Box,
}
if !a.forwardTo(msg.To, fwd) {
select {
case c.send <- proto.AnchorMessage{Type: proto.AnchorNoPeer, ID: msg.To}:
default:
}
}
default:
log.Printf("anchor: unknown message type %q from %s", msg.Type, r.RemoteAddr)
}
}
a.unregister(c)
close(c.send)
}
// hashNetName returns the SHA-256 hash of a plaintext network name.
// The anchor stores only hashed names — it never sees the plaintext.
func hashNetName(name string) string {
h := sha256.Sum256([]byte("yaw2-net:" + name))
return hex.EncodeToString(h[:])
}
// Compile-time check: hashNetName is used by daemons, kept here for reference.
var _ = hashNetName
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Ensure wsjson import is used (avoids accidental drop).
var _ = time.Now