Discover LAN servers and relay authenticated browser peer connections

This commit is contained in:
2026-11-08 21:57:05 +00:00
parent 89814d9fbe
commit 349428f11d
13 changed files with 1265 additions and 8 deletions
+113
View File
@@ -0,0 +1,113 @@
package discovery
import (
"context"
"io"
"log"
"net"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/hashicorp/mdns"
)
// FoundServer is a validated service advertised on the serving host's LAN.
type FoundServer struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Auth string `json:"auth"`
Version string `json:"version"`
}
// Browse sends one bounded DNS-SD query, never a network port scan.
func Browse(ctx context.Context) ([]FoundServer, error) {
return browse(ctx, mdns.QueryContext)
}
func browse(ctx context.Context, query func(context.Context, *mdns.QueryParam) error) ([]FoundServer, error) {
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
entries := make(chan *mdns.ServiceEntry, 128)
result := make(chan error, 1)
go func() {
result <- query(ctx, &mdns.QueryParam{Service: ServiceType, Domain: "local", Timeout: 3 * time.Second,
Entries: entries, WantUnicastResponse: true, Logger: log.New(io.Discard, "", 0)})
}()
found := map[string]FoundServer{}
consume := func(entry *mdns.ServiceEntry) {
if item, ok := discovered(entry); ok && len(found) < 128 {
found[item.Endpoint] = item
}
}
for {
select {
case entry := <-entries:
consume(entry)
case err := <-result:
for {
select {
case entry := <-entries:
consume(entry)
default:
values := make([]FoundServer, 0, len(found))
for _, item := range found {
values = append(values, item)
}
sort.Slice(values, func(i, j int) bool { return values[i].Endpoint < values[j].Endpoint })
return values, err
}
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func discovered(entry *mdns.ServiceEntry) (FoundServer, bool) {
if entry == nil || entry.Port < 1 || entry.Port > 65535 {
return FoundServer{}, false
}
fields := map[string]string{}
for _, value := range entry.InfoFields {
if key, text, ok := strings.Cut(value, "="); ok {
fields[key] = text
}
}
path := fields["path"]
if path != "/connect" {
return FoundServer{}, false
}
ip := entry.AddrV4
if ip == nil {
ip = entry.AddrV6
}
if ip == nil && entry.AddrV6IPAddr != nil {
ip = entry.AddrV6IPAddr.IP
}
if ip == nil || ip.IsUnspecified() || ip.IsMulticast() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return FoundServer{}, false
}
if fields["tls"] != "0" && fields["tls"] != "1" {
return FoundServer{}, false
}
scheme := "ws"
if fields["tls"] == "1" {
scheme = "wss"
}
auth := fields["auth"]
if auth != "password" && auth != "none" {
return FoundServer{}, false
}
name := strings.TrimSpace(fields["name"])
if name == "" {
name = strings.TrimSuffix(entry.Host, ".")
}
if name == "" || len(name) > 200 {
return FoundServer{}, false
}
endpoint := (&url.URL{Scheme: scheme, Host: net.JoinHostPort(ip.String(), strconv.Itoa(entry.Port)), Path: path}).String()
return FoundServer{Name: name, Endpoint: endpoint, Auth: auth, Version: fields["v"]}, true
}
+61
View File
@@ -0,0 +1,61 @@
package discovery
import (
"context"
"net"
"testing"
"github.com/hashicorp/mdns"
)
func service(ip string) *mdns.ServiceEntry {
return &mdns.ServiceEntry{AddrV4: net.ParseIP(ip), Host: "server.local.", Port: 8083,
InfoFields: []string{"name=Linux desktop", "path=/connect", "tls=0", "auth=password", "v=release"}}
}
func TestBrowseCollectsDeduplicatedValidAdvertisements(t *testing.T) {
values, err := browse(context.Background(), func(ctx context.Context, p *mdns.QueryParam) error {
if p.Service != ServiceType || p.Timeout.Seconds() > 4 {
t.Fatal("unbounded or wrong service query")
}
for _, entry := range []*mdns.ServiceEntry{service("192.168.1.3"), service("192.168.1.2"), service("192.168.1.3"), service("127.0.0.1"), nil} {
p.Entries <- entry
}
return nil
})
if err != nil || len(values) != 2 {
t.Fatalf("values=%+v err=%v", values, err)
}
if values[0].Endpoint != "ws://192.168.1.2:8083/connect" || values[0].Name != "Linux desktop" || values[0].Auth != "password" {
t.Fatalf("wrong record: %+v", values[0])
}
}
func TestBrowseHonorsCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := browse(ctx, func(ctx context.Context, p *mdns.QueryParam) error { <-ctx.Done(); return ctx.Err() })
if err == nil {
t.Fatal("canceled browse must fail")
}
}
func TestDiscoveryRejectsMalformedAndUnsafeAdvertisements(t *testing.T) {
for _, ip := range []string{"0.0.0.0", "127.0.0.1", "224.0.0.1", "169.254.3.1", "::", "::1", "fe80::1"} {
if _, ok := discovered(service(ip)); ok {
t.Fatalf("accepted address %s", ip)
}
}
for _, fields := range [][]string{{"path=//evil/connect", "auth=password", "tls=0"}, {"path=/connect", "auth=unknown", "tls=0"}, {"path=/connect", "auth=password", "tls=garbage"}} {
item := service("192.168.1.2")
item.InfoFields = fields
if _, ok := discovered(item); ok {
t.Fatalf("accepted invalid TXT %+v", fields)
}
}
item := service("192.168.1.2")
item.Port = 65536
if _, ok := discovered(item); ok {
t.Fatal("accepted invalid port")
}
}
+3 -2
View File
@@ -287,8 +287,9 @@ type Message struct {
// AttentionAcks is the ack_attention body, the attention_acks reply (the
// whole set) and the attention_acks_changed push (the delta). See
// attention_acks.go.
AttentionAcks *AttentionAcks `json:"attention_acks,omitempty"`
ServerStats *ServerStats `json:"server_stats,omitempty"`
AttentionAcks *AttentionAcks `json:"attention_acks,omitempty"`
DiscoveredServers []DiscoveredServer `json:"discovered_servers,omitzero"`
ServerStats *ServerStats `json:"server_stats,omitempty"`
// App notification stream (see notifications.go): After is the
// subscribe_notifications cursor, Notifications the subscribe reply,
// Notification one push, and IDs the clear_notifications request, the
+14
View File
@@ -0,0 +1,14 @@
package protocol
const (
DiscoverServersRequest = "discover_servers"
DiscoverServersResult = "discovered_servers"
)
// DiscoveredServer is one Pipelines DNS-SD advertisement on the serving LAN.
type DiscoveredServer struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Auth string `json:"auth"`
Version string `json:"version"`
}
+51
View File
@@ -0,0 +1,51 @@
package server
import (
"context"
"encoding/json"
"net/http"
"time"
"git.a-wan.net/alan/pipelines/internal/discovery"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
var discoverySlots = make(chan struct{}, 4)
func discoverServers(ctx context.Context) ([]discovery.FoundServer, error) {
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
select {
case discoverySlots <- struct{}{}:
defer func() { <-discoverySlots }()
return discovery.Browse(ctx)
case <-ctx.Done():
return nil, ctx.Err()
}
}
func handleServerDiscovery(ctx context.Context, request protocol.Message, write func(protocol.Message) error) {
servers, err := discoverServers(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "LAN discovery unavailable: " + err.Error()})
return
}
items := make([]protocol.DiscoveredServer, 0, len(servers))
for _, server := range servers {
items = append(items, protocol.DiscoveredServer(server))
}
_ = write(protocol.Message{Type: protocol.DiscoverServersResult, ID: request.ID, DiscoveredServers: items})
}
func serveServerDiscovery(w http.ResponseWriter, r *http.Request) {
servers, err := discoverServers(r.Context())
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json")
if err != nil {
http.Error(w, "LAN discovery unavailable", http.StatusServiceUnavailable)
return
}
_ = json.NewEncoder(w).Encode(struct {
Servers []discovery.FoundServer `json:"discovered_servers"`
}{servers})
}
+5
View File
@@ -153,6 +153,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
runs.serveArtifact(w, r)
})
mux.HandleFunc("GET /discovery", serveServerDiscovery)
mux.HandleFunc("GET /files", serveHomeFile)
mux.HandleFunc("POST /chat-uploads", serveChatUpload)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
@@ -276,6 +277,10 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
if handleDirectoryListing(request, write) {
continue
}
if request.Type == protocol.DiscoverServersRequest {
go handleServerDiscovery(connCtx, request, write)
continue
}
if request.Type == protocol.ServerStatsRequest {
go handleServerStats(connCtx, request, runs, options.ServerStatsSampler, started, build, write)
continue