Repository navigation
feat(turn): embedded TURN relay with ephemeral credentials (#102) - #116
Merged
Merged
Conversation
Players behind symmetric NAT or UDP-blocking firewalls can't establish WebRTC, so the SDK falls back to relaying through the WebSocket. The issue framed this as a bandwidth problem, but it isn't — TURN relays through the same server. The real problem is that the WS relay is capped at 30 msg/s with 8 KiB frames and rides TCP, so it is always reliable+ordered. Turn-based games are fine on it; anything ticking above 30 Hz is not, and the unreliable data channel (#94) silently degrades to reliable+ordered exactly when a game needs it most. Embedded pion/turn rather than a coturn installer: the setup wizard has never touched anything outside .env, and having it apt-install a daemon, write a unit file, and manage its lifecycle would be the most invasive thing in the codebase — with the operator owning the cleanup. pion is pure Go and links straight in, so the feature is just a flag. Operators already running coturn lose nothing: the credential scheme is coturn's use-auth-secret, so --turn-servers still works unchanged. Credentials are ephemeral (10-min TTL), derived per user via HMAC-SHA1 over "<expiry>:<user-id>" and minted at /rtc-config, which is already AuthRequired. No TURN passwords are stored anywhere. HMAC -SHA1 is the scheme's mandated construction, not an oversight — it is what keeps these interchangeable with coturn, and SHA-1's collision weaknesses don't carry into HMAC. Opt-in, and deliberately so: TURN needs inbound UDP that HTTP-only ingress (Cloudflare Tunnel, most PaaS) cannot carry at all. Failing to bind is fatal rather than a warning — the operator asked for TURN explicitly, and silently continuing would leave NAT-restricted players on the WS relay while the logs claim success. Notes: - ICEServersFor advertises the *bound* port, not the requested one, so --turn-listen with :0 doesn't hand clients a dead ":0" candidate. - iceServersFor copies RTCIceServers instead of appending to it. A bare append would write into that package-level slice's spare capacity, letting concurrent requests hand one user another user's credential. TestICEServersFor_DoesNotMutateStaticList pins this. - A private --turn-public-ip warns rather than fails; it's legal, and it fails in a way (candidates gather, nothing connects) that is otherwise miserable to debug. - Relay-port range defaults to 100 ports = 100 concurrent relayed peers. Tests: credential round-trip, expiry boundary, malformed usernames, colon-injection in user IDs, wrong-secret rejection, config validation, and an end-to-end pass driving pion's TURN client against the running relay — valid credentials get an allocation, forged and expired ones are refused. Verified against a real binary: UDP port bound, live STUN Binding Request answered 0x0101, /rtc-config 401s unauthenticated. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two gaps found reviewing the previous commit. /rtc-config had no rate limit. That was fine when it returned a static list, but it now mints TURN credentials, and each response grants ~10 minutes of relay access to whoever holds it. An authenticated account could mint an endless supply and hand them out. Now 30/min per IP — the SPA fetches this once per game launch, so legitimate use is far below that. Nothing capped allocations per account. The relay port range is finite (100 ports by default) and allocations live until they time out, so a single account could take the entire range and deny the relay to everyone else. pion exposes QuotaHandler for exactly this; paired with the allocation lifecycle events it gives an accurate live count. The quota is keyed on the account, not the TURN username. Usernames embed an expiry, so a client gets a fresh one from every /rtc-config call and username-keyed counting would let a caller reset its own quota just by re-minting. userIDFrom deliberately skips the expiry check that CheckUsername does: an allocation is torn down after its credential expires, and the counter has to decrement then or the quota leaks until restart. Limit is 8 — the worst legitimate case is a full 8-player mesh where every peer needs relay. Tests: re-minting does not reset the quota, and one account hitting its cap does not affect another's ability to allocate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Keeps CLAUDE.md accurate as of this branch — #115 refreshed it against main, and this branch adds a package it doesn't know about. Records the reasoning that isn't recoverable from the code: why the relay exists (the WS fallback's 30 msg/s cap, not bandwidth), why it's opt-in (inbound UDP), and why the quota is keyed on user ID rather than the TURN username. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
yusufkaraaslan
force-pushed
the
feat/embedded-turn
branch
from
August 4, 2026 04:44
9bddb52 to
def9d18
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #102.
Correcting the premise first
The issue says players fall back to the relay, "which works but uses server bandwidth." That framing is off — TURN also relays through your server, at comparable or slightly higher bandwidth since there's no app-level throttle. Swapping one relay for another saves nothing.
The actual problem is worse than bandwidth. The WebSocket relay is capped at 30 msg/s with 8 KiB frames (
ws.go:21,25) and rides TCP, so it is always reliable+ordered:So this is worth more than the issue claims, just for different reasons. Priority was marked Low on a bandwidth argument that doesn't hold; the correctness argument is stronger.
Why embedded, not a coturn installer
./playmore setuphas never touched anything outside.env. Having it apt-install a daemon, write a unit file, and manage its lifecycle would be the most invasive thing in the codebase — and the operator, not us, owns the cleanup. pion/turn is pure Go (no CGO, consistent with the SQLite driver choice) and links straight in, so the whole feature is a flag.Operators already running coturn lose nothing: the credential scheme is coturn's
use-auth-secret, so--turn-serverspointed at an external coturn keeps working unchanged.Credentials
Ephemeral, 10-minute TTL, derived per user as
base64(HMAC-SHA1(secret, "<expiry>:<user-id>"))and minted atGET /rtc-config(alreadyAuthRequired). No TURN passwords stored anywhere.HMAC-SHA1 is the scheme's mandated construction, not an oversight — it's what keeps these interchangeable with coturn, and SHA-1's collision weaknesses don't carry into HMAC, which has no practical forgery attack. Flagged in a comment so it doesn't get cargo-culted elsewhere.
Opt-in, and failure is loud
TURN needs inbound UDP (control port + one port per concurrent relayed peer). HTTP-only ingress — Cloudflare Tunnel, ngrok, most PaaS — cannot carry that traffic at all, which is why this ships off by default and
docs/SETUP.mdleads with the requirement.Failing to bind is fatal rather than a warning: the operator asked for TURN explicitly, and continuing silently would leave NAT-restricted players on the WS relay while the logs claim success.
Two bugs caught while building
ICEServersForadvertised the requested port, not the bound one. With--turn-listen 0.0.0.0:0that hands clients a dead:0candidate. Now readsconn.LocalAddr().append(RTCIceServers, minted...)would have been a credential leak. Appending onto the package-level slice writes into its spare capacity, so two concurrent/rtc-configrequests could stomp each other and hand one user another user's TURN credential. Now copies.TestICEServersFor_DoesNotMutateStaticListconstructs a slice withcap > len— the only condition under which the bug is observable — and pins it.Testing
24 new tests. Unit coverage for credential round-trip, expiry boundary (at-expiry valid, one second past not), malformed usernames, colon-injection in user IDs, wrong-secret rejection, and config validation.
The one that matters is
TestAllocate_EndToEnd: it drives pion's TURN client against the running relay and asserts a valid credential gets a real allocation while forged and expired ones are refused. Valid succeeding and both invalid cases failing is what makes it discriminating rather than trivially green.Also verified against a real built binary, not just tests:
ssconfirms)0x0101with the transaction ID echoed/rtc-config401s unauthenticatedgo test ./...,go build ./...,go vet ./...all clean.Not included
internal/lobby/is unformatted on main (gofmt -lflagshub.go,hub_test.go,lobby.go). Pre-existing and unrelated — left alone rather than adding churn here.🤖 Generated with Claude Code