v0.3: WebRTC P2P via Pion (Go) + RTCPeerConnection (browser)

Server: unchanged shape, just added a "signal" message type to the
existing /api/send + /api/stream bus. Now carries both "clipboard"
(payload) and "signal" (offer/answer/ICE) over the same envelope.

Client: -rtc flag turns the Go listener into a Pion peer. Posts an SDP
offer at startup, accepts the browser's answer through the signaling
bus, exchanges ICE, then receives clipboard text over a DataChannel
named "tether". On message: writes to OS clipboard same as SSE path.

Web UI: acts as the answerer. Listens for "signal" SSE events, replies
to offers, exchanges ICE. When DataChannel opens, the send button uses
RTCDataChannel.send() instead of POST /api/send — data no longer
traverses the server after pairing. Pill in the header flips
sse → negotiating → rtc to make this visible.

Toolchain: bumped go.mod to go 1.26, switched to pion/webrtc v4 and
prometheus/client_golang v1.23.x.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Claude Opus 4.7
2026-05-21 00:37:31 -05:00
parent 80539ae60c
commit 98dc2ca2a6
5 changed files with 421 additions and 301 deletions

View File

@@ -1,7 +1,10 @@
// tether-server: HTTP+SSE relay for phone↔client clipboard sync.
// tether-server v0.3: HTTP+SSE relay with extensible message envelope.
//
// v0.1: SSE-only relay with broadcast bus.
// v0.2 (this): /metrics endpoint + signaling stubs (mailbox for WebRTC SDP/ICE).
// The same /api/send + /api/stream pipeline carries TWO message kinds:
// - "clipboard" — the user-facing payload (text)
// - "signal" — WebRTC SDP/ICE for peer negotiation
//
// Peers filter by .Type on the client side. Server is neutral relay.
package main
import (
@@ -23,10 +26,14 @@ import (
//go:embed web/index.html
var webFS embed.FS
// Message envelope. Type defaults to "clipboard" for backward compat.
type Message struct {
Text string `json:"text"`
Source string `json:"source,omitempty"`
TS int64 `json:"ts"`
Type string `json:"type,omitempty"` // "clipboard" | "signal"
Text string `json:"text,omitempty"` // clipboard text
Signal json.RawMessage `json:"signal,omitempty"` // {kind:offer|answer|ice, ...}
From string `json:"from,omitempty"` // sender peer id (for signal filtering)
Source string `json:"source,omitempty"` // human-readable label
TS int64 `json:"ts"`
}
type bus struct {
@@ -38,13 +45,16 @@ type bus struct {
func newBus() *bus { return &bus{clients: map[chan Message]string{}} }
func (b *bus) subscribe(label string) chan Message {
ch := make(chan Message, 16)
ch := make(chan Message, 32)
b.mu.Lock()
b.clients[ch] = label
// only replay clipboard messages — signals are time-sensitive
for _, m := range b.history {
select {
case ch <- m:
default:
if m.Type == "" || m.Type == "clipboard" {
select {
case ch <- m:
default:
}
}
}
b.mu.Unlock()
@@ -63,9 +73,11 @@ func (b *bus) unsubscribe(ch chan Message) {
func (b *bus) publish(m Message) {
b.mu.Lock()
defer b.mu.Unlock()
b.history = append(b.history, m)
if len(b.history) > 10 {
b.history = b.history[len(b.history)-10:]
if m.Type == "" || m.Type == "clipboard" {
b.history = append(b.history, m)
if len(b.history) > 10 {
b.history = b.history[len(b.history)-10:]
}
}
for ch := range b.clients {
select {
@@ -75,16 +87,15 @@ func (b *bus) publish(m Message) {
}
}
// Prometheus metrics --------------------------------------------------------
// Prometheus metrics
var (
messages = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tether_messages_total",
Help: "Total messages published to the broadcast bus, by source label.",
}, []string{"source"})
Help: "Total messages published to the broadcast bus, by source and type.",
}, []string{"source", "type"})
bytesIn = promauto.NewCounter(prometheus.CounterOpts{
Name: "tether_message_bytes_total",
Help: "Total bytes of message text published.",
Help: "Total bytes of clipboard text published.",
})
subscribers = promauto.NewGauge(prometheus.GaugeOpts{
Name: "tether_active_subscribers",
@@ -93,46 +104,15 @@ var (
publishLatency = promauto.NewHistogram(prometheus.HistogramOpts{
Name: "tether_publish_duration_seconds",
Help: "Latency of the publish() fan-out, including channel sends.",
Buckets: prometheus.ExponentialBuckets(0.0001, 4, 8), // 0.1ms..1.6s
Buckets: prometheus.ExponentialBuckets(0.0001, 4, 8),
})
)
// Signaling mailbox (v0.3 WebRTC scaffolding) --------------------------------
// Peers POST offers/answers/ICE candidates into a per-room mailbox, peers GET
// to drain. Pure relay — no SDP parsing, no peer state on server.
type signalBox struct {
mu sync.Mutex
rooms map[string][]json.RawMessage
}
func newSignalBox() *signalBox { return &signalBox{rooms: map[string][]json.RawMessage{}} }
func (s *signalBox) post(room string, msg json.RawMessage) {
s.mu.Lock()
defer s.mu.Unlock()
s.rooms[room] = append(s.rooms[room], msg)
if len(s.rooms[room]) > 64 {
s.rooms[room] = s.rooms[room][len(s.rooms[room])-64:]
}
}
func (s *signalBox) drain(room string) []json.RawMessage {
s.mu.Lock()
defer s.mu.Unlock()
out := s.rooms[room]
delete(s.rooms, room)
return out
}
// ---------------------------------------------------------------------------
func main() {
addr := flag.String("addr", ":8765", "listen address")
flag.Parse()
b := newBus()
sig := newSignalBox()
sub, _ := fs.Sub(webFS, "web")
mux := http.NewServeMux()
@@ -149,6 +129,9 @@ func main() {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
if m.Type == "" {
m.Type = "clipboard"
}
if m.Source == "" {
m.Source = r.Header.Get("X-Tether-Source")
if m.Source == "" {
@@ -160,9 +143,13 @@ func main() {
t0 := time.Now()
b.publish(m)
publishLatency.Observe(time.Since(t0).Seconds())
messages.WithLabelValues(m.Source).Inc()
bytesIn.Add(float64(len(m.Text)))
log.Printf("publish: %s len=%d", m.Source, len(m.Text))
messages.WithLabelValues(m.Source, m.Type).Inc()
if m.Type == "clipboard" {
bytesIn.Add(float64(len(m.Text)))
log.Printf("publish clipboard: %s len=%d", m.Source, len(m.Text))
} else {
log.Printf("publish %s: from=%s", m.Type, m.From)
}
w.WriteHeader(http.StatusNoContent)
})
@@ -195,7 +182,11 @@ func main() {
return
case m := <-ch:
bs, _ := json.Marshal(m)
fmt.Fprintf(w, "event: clipboard\ndata: %s\n\n", bs)
eventName := m.Type
if eventName == "" {
eventName = "clipboard"
}
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", eventName, bs)
fl.Flush()
case <-ka.C:
fmt.Fprintf(w, ": keepalive\n\n")
@@ -204,35 +195,6 @@ func main() {
}
})
// WebRTC signaling: POST to add a message, GET to drain.
// /api/signal/<room> is a dumb relay — peers exchange SDP + ICE via this.
mux.HandleFunc("/api/signal/", func(w http.ResponseWriter, r *http.Request) {
room := r.URL.Path[len("/api/signal/"):]
if room == "" {
http.Error(w, "missing room", http.StatusBadRequest)
return
}
switch r.Method {
case http.MethodPost:
body, _ := func() (json.RawMessage, error) {
var raw json.RawMessage
err := json.NewDecoder(r.Body).Decode(&raw)
return raw, err
}()
sig.post(room, body)
w.WriteHeader(http.StatusNoContent)
case http.MethodGet:
out := sig.drain(room)
if out == nil {
out = []json.RawMessage{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
default:
http.Error(w, "POST or GET", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})

View File

@@ -19,6 +19,12 @@
header { display: flex; align-items: baseline; gap: 8px; }
h1 { margin: 0; font-size: 22px; font-weight: 600; letter-spacing: -0.5px; }
.tag { font-size: 11px; color: #888; letter-spacing: 0.5px; text-transform: uppercase; }
.pill {
font-size: 10px; padding: 2px 8px; border-radius: 999px;
background: #1f1f1f; color: #888; letter-spacing: 0.4px;
}
.pill.live { background: #052e16; color: #4ade80; }
.pill.connecting { background: #1f2937; color: #fbbf24; }
.row { display: flex; flex-direction: column; gap: 6px; }
label { font-size: 11px; color: #888; letter-spacing: 0.4px; text-transform: uppercase; }
textarea {
@@ -56,6 +62,7 @@
max-height: 200px; overflow: auto;
}
.meta { font-size: 11px; color: #666; margin-top: 4px; }
.meta .rtc-badge { color: #4ade80; }
footer {
margin-top: auto; padding-top: 8px;
font-size: 11px; color: #555; text-align: center;
@@ -67,6 +74,7 @@
<header>
<h1>tether</h1>
<span class="tag">phone ↔ laptop</span>
<span class="pill" id="rtcPill">sse</span>
</header>
<div class="row">
@@ -86,21 +94,41 @@
</div>
<footer>
<a href="https://gitea.pecord.io/pecord/tether">tether on gitea</a> · v0.1
<a href="https://gitea.pecord.io/pecord/tether">tether on gitea</a> · v0.3
</footer>
<script>
const $ = (id) => document.getElementById(id);
const peerID = "tether-browser-" + Math.random().toString(36).slice(2, 8);
let rtcChannel = null; // open RTCDataChannel, when we have one
const status = (msg, cls) => {
const s = $("status");
s.textContent = msg;
s.className = "status" + (cls ? " " + cls : "");
};
const setPill = (mode) => {
const p = $("rtcPill");
p.textContent = mode;
p.className = "pill " + (mode === "rtc" ? "live" : mode === "negotiating" ? "connecting" : "");
};
function addIncoming(text, source, ts, viaRTC) {
const el = document.createElement("div");
el.className = "msg";
el.textContent = text;
const meta = document.createElement("div");
meta.className = "meta";
const badge = viaRTC ? '<span class="rtc-badge">via rtc</span> · ' : '';
meta.innerHTML = badge + (source || "client") + " @ " + new Date(ts || Date.now()).toLocaleTimeString();
el.appendChild(meta);
const feed = $("incoming");
feed.insertBefore(el, feed.firstChild);
}
$("pasteBtn").addEventListener("click", async () => {
try {
const text = await navigator.clipboard.readText();
$("out").value = text;
$("out").value = await navigator.clipboard.readText();
status("pasted from clipboard", "ok");
} catch (e) {
status("clipboard read denied — paste manually", "err");
@@ -110,38 +138,91 @@
$("sendBtn").addEventListener("click", async () => {
const text = $("out").value;
if (!text) { status("empty", "err"); return; }
status("sending…");
try {
const r = await fetch("/api/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text }),
});
if (r.ok) {
status("delivered ✓", "ok");
} else {
status("server returned " + r.status, "err");
}
} catch (e) {
status("network error", "err");
if (rtcChannel && rtcChannel.readyState === "open") {
rtcChannel.send(text);
status("sent via rtc ✓", "ok");
} else {
status("sending via http…");
try {
const r = await fetch("/api/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "clipboard", text, source: "phone" }),
});
status(r.ok ? "delivered ✓" : "server returned " + r.status, r.ok ? "ok" : "err");
} catch (e) { status("network error", "err"); }
}
});
// SSE: receive incoming messages from clients
// ── WebRTC peer ────────────────────────────────────────────────────────
// Browser acts as ANSWERER. Listens for offers via SSE, replies via /api/send.
async function postSignal(payload) {
await fetch("/api/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "signal",
from: peerID,
source: "phone",
signal: JSON.stringify(payload),
}),
});
}
let pc = null;
async function handleOffer(sdp) {
if (pc) try { pc.close(); } catch (_) {}
pc = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
});
setPill("negotiating");
pc.onicecandidate = (ev) => {
if (ev.candidate) postSignal({ kind: "ice", candidate: ev.candidate.toJSON() });
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === "connected") setPill("rtc");
else if (pc.connectionState === "failed" || pc.connectionState === "disconnected") setPill("sse");
};
pc.ondatachannel = (ev) => {
const ch = ev.channel;
ch.onopen = () => { rtcChannel = ch; setPill("rtc"); };
ch.onclose = () => { rtcChannel = null; setPill("sse"); };
ch.onmessage = (m) => addIncoming(m.data, "laptop", Date.now(), true);
};
await pc.setRemoteDescription({ type: "offer", sdp });
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
await postSignal({ kind: "answer", sdp: answer });
}
async function handleIceCandidate(candidate) {
if (pc) {
try { await pc.addIceCandidate(candidate); } catch (e) {}
}
}
// ── SSE main feed ──────────────────────────────────────────────────────
function connectFeed() {
const es = new EventSource("/api/stream");
es.addEventListener("clipboard", (ev) => {
try {
const m = JSON.parse(ev.data);
const el = document.createElement("div");
el.className = "msg";
el.textContent = m.text;
const meta = document.createElement("div");
meta.className = "meta";
meta.textContent = (m.source || "client") + " @ " + new Date(m.ts).toLocaleTimeString();
el.appendChild(meta);
const feed = $("incoming");
feed.insertBefore(el, feed.firstChild);
if (m.source !== "phone") {
addIncoming(m.text, m.source, m.ts, false);
}
} catch (e) {}
});
es.addEventListener("signal", (ev) => {
try {
const m = JSON.parse(ev.data);
if (m.from === peerID) return; // ignore our own
let payload = m.signal;
if (typeof payload === "string") payload = JSON.parse(payload);
if (payload.kind === "offer" && payload.sdp) {
handleOffer(payload.sdp.sdp);
} else if (payload.kind === "ice" && payload.candidate) {
handleIceCandidate(payload.candidate);
}
} catch (e) {}
});
es.onerror = () => setTimeout(connectFeed, 2000);