3 Commits
v0.1.4 ... main

Author SHA1 Message Date
Fredrik Johansson
697a7e614d fix: challenge nonce must be 32 bytes per YAW/2 §5.1
All checks were successful
Build / Build & release (push) Successful in 13m46s
The anchor was sending a 16-byte nonce. The spec (yaw2.0-protocol.md §5.1
and yaw2-implementation.md §7.1) requires 32 bytes. Any spec-conformant
peer would fail join signature verification against this anchor, breaking
interop. Signature verification was already using the raw nonce bytes
(not hex), so only the allocation size needed changing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 18:35:57 +02:00
Fredrik Johansson
d07342e97e docs: fix placeholder URLs in QUICKSTART; add committed example scripts
QUICKSTART.md had the author's personal domain as the example anchor URL
(wss://waste.dev.xplwd.com/ws) which would confuse anyone reading it.
Replaced with wss://YOUR_ANCHOR_DOMAIN/ws and added a new Option 3
section explaining the example scripts.

Added committed *.example versions of the four local-workflow scripts
(launch-tui, launch-web, deploy-web, serve-web). The real filenames are
gitignored so local edits (HOST, ANCHOR, etc.) are never accidentally
committed; the .example files serve as templates users copy once.
Each script fails fast if the placeholder URL/host is still set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 11:51:02 +02:00
Fredrik Johansson
f425e0bb8e fix: stop leaking TURN secret to browser clients
All checks were successful
Build / Build & release (push) Successful in 13m40s
WASTE_CONFIG.turnSecret was shipped in plaintext config.js and used to
compute coturn HMAC credentials client-side in browser.ts. Anyone reading
the PWA's JS could read the secret and mint unlimited long-lived TURN
credentials, turning the relay into an open proxy.

The anchor now mints short-lived (1h) credentials server-side via a new
GET /turn-credentials endpoint (-turn-secret flag), mirroring what the
daemon already does. The browser fetches credentials instead of holding
the secret. Daemon mode was unaffected (already server-side).

Docs updated to drop turnSecret from config.js examples, document the
new nginx route, and instruct anyone with an old config.js to rotate
the coturn secret since it was previously exposed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 18:48:59 +02:00
10 changed files with 350 additions and 29 deletions

View File

@@ -151,9 +151,13 @@ entries from all applicable share roots, with relative `path` fields
**Status:** implemented (browser mode + daemon mode)
**Affects:** ICE server configuration only, no wire changes
The browser adapter reads `WASTE_CONFIG.turnURL` and `WASTE_CONFIG.turnSecret`
and adds a TURN server to the WebRTC `ICEServers` list. Credentials are
generated using HMAC-SHA1 of the username (coturn `use-auth-secret` scheme).
The browser adapter reads `WASTE_CONFIG.turnURL` and fetches short-lived
credentials from the anchor's `GET /turn-credentials` endpoint (derived from
`WASTE_CONFIG.signalURL`, or overridden via `WASTE_CONFIG.turnCredentialsURL`).
The anchor computes the credential using HMAC-SHA1 of the username (coturn
`use-auth-secret` scheme) — the shared secret itself is never sent to the
browser. Daemon mode does the equivalent computation locally, since the
daemon already holds `-turn-secret` server-side.
YAW/2 §0 explicitly declines TURN ("No relay (TURN)"). This extension is
opt-in via server configuration and does not affect peers that omit it.

View File

@@ -41,7 +41,9 @@ Solved by using WebRTC DataChannels via pion. ICE gathers host + server-reflexiv
### TURN relay ✅ (shipped)
Both browser and daemon modes support TURN relay.
**Browser mode:** `iceServers()` in `browser.ts` reads `WASTE_CONFIG.turnURL` and `WASTE_CONFIG.turnSecret`, generates time-limited HMAC-SHA1 credentials (compatible with coturn `use-auth-secret`), and adds the TURN server to the ICE candidate list. The peer dot turns yellow for relayed connections (`candidate_type: relay`).
**Browser mode:** `iceServers()` in `browser.ts` reads `WASTE_CONFIG.turnURL` and fetches a time-limited credential from the anchor's `GET /turn-credentials` endpoint (HMAC-SHA1, compatible with coturn `use-auth-secret`) rather than holding the shared secret client-side. The peer dot turns yellow for relayed connections (`candidate_type: relay`).
> **Security fix:** earlier this previously embedded `turnSecret` directly in `WASTE_CONFIG`, which let anyone reading the PWA's JS mint unlimited long-lived TURN credentials. The secret now lives only on the anchor (`-turn-secret` flag); the anchor mints short-lived credentials per-request instead.
**Daemon mode:** `-turn-url` and `-turn-secret` flags on `cmd/daemon`. `turnICEServers()` in `internal/netmgr/manager.go` generates HMAC-SHA1 credentials and injects them into the ICE server list for every new peer connection.

View File

@@ -41,13 +41,33 @@ On Linux and Windows a tray icon appears — closing the window hides to tray ra
---
## Option 3 — Run the daemon manually (headless / power users)
## Option 3 — Run the daemon + TUI or web UI locally (power users / dev)
Example scripts are provided for the common local workflows. Copy them and fill in your anchor URL:
```bash
# TUI (terminal UI):
cp launch-tui.sh.example launch-tui.sh
$EDITOR launch-tui.sh # set ANCHOR=wss://your-anchor/ws
./launch-tui.sh
# Web UI in daemon mode (Vite dev server + daemon):
cp launch-web.sh.example launch-web.sh
$EDITOR launch-web.sh # set ANCHOR=wss://your-anchor/ws
./launch-web.sh
```
The real script files are gitignored so your local edits (anchor URL, alias, network) are never accidentally committed.
---
## Option 4 — Run the daemon manually (headless)
If you want the daemon running in the background without the desktop UI — on a server, over SSH, or with the web UI in a browser pointed at your local machine:
```bash
# Download waste-daemon from the releases page, then:
./waste-daemon -alias yourname -anchor wss://your-anchor-server/ws
./waste-daemon -alias yourname -anchor wss://YOUR_ANCHOR_DOMAIN/ws
```
Then open the web UI in a browser at the anchor URL, or point the web UI's daemon mode at `ws://127.0.0.1:17338`.
@@ -83,7 +103,7 @@ The anchor is a tiny signaling server that helps peers find each other — it ne
```bash
# On your VPS:
./waste-anchor -bind 127.0.0.1:8080
./waste-anchor -bind 127.0.0.1:8080 -turn-secret YOUR_COTURN_SECRET
```
Put it behind nginx with a `/ws` WebSocket proxy and serve the web UI static files at `/`. See [README.md](README.md#hosting-on-a-vps) for the full nginx setup.
Put it behind nginx with `/ws` and `/turn-credentials` proxied to the anchor, and the web UI static files at `/`. See [README.md](README.md#hosting-on-a-vps) for the full nginx setup.

View File

@@ -134,7 +134,7 @@ This tells the browser where to connect for signaling. Without it the join form
### 3. Nginx Proxy Manager setup
Create one **Proxy Host** for your domain (e.g. `waste.example.com`) with TLS enabled. You need two locations:
Create one **Proxy Host** for your domain (e.g. `waste.example.com`) with TLS enabled. You need these locations:
**Location 1 — WebSocket signaling (`/ws`)**
- Location: `/ws`
@@ -142,6 +142,12 @@ Create one **Proxy Host** for your domain (e.g. `waste.example.com`) with TLS en
- Forward port: `8080`
- Enable: WebSockets Support
**Location 1b — TURN credentials (`/turn-credentials`, only if using TURN — see [step 4](#4-turn-relay-optional-fixes-mobile--cgnat))**
- Location: `/turn-credentials`
- Forward hostname/IP: `127.0.0.1`
- Forward port: `8080`
- Plain HTTP, no WebSockets toggle needed
**Location 2 — Web UI (catch-all)**
- Location: `/`
- Choose "Serve Static Files" (or point to a local HTTP server serving `/var/www/waste-web`)
@@ -162,6 +168,7 @@ Or use `serve-web.sh` which handles PID tracking and restart:
The key requirements:
- `/ws` → anchor process (WebSocket, keep-alive)
- `/turn-credentials` → anchor process (plain HTTP; only needed if using TURN)
- `/*` → static file server (SPA fallback: return `index.html` for unknown paths)
### 4. TURN relay (optional, fixes mobile / CGNAT)
@@ -200,21 +207,32 @@ systemctl enable coturn
systemctl start coturn
```
**Update `config.js`** to tell browsers about the TURN server:
**Start the anchor with the same secret**, so it can mint short-lived credentials on your behalf:
```bash
./waste-anchor -bind 0.0.0.0:8080 -turn-secret YOUR_SECRET_HERE
```
This enables `GET /turn-credentials` on the anchor, which returns a fresh `{username, credential}` pair (1-hour TTL) computed from the shared secret — the secret itself never leaves the server.
**Update `config.js`** to tell browsers about the TURN server (no secret here — only the public relay address):
```js
window.WASTE_CONFIG = {
signalURL: 'wss://your-domain.com/ws',
turnURL: 'turn:your-domain.com:3478',
turnSecret: 'YOUR_SECRET_HERE',
}
```
The `use-auth-secret` mode generates short-lived TURN credentials from the shared secret — no user database required. The relay only sees opaque DTLS-encrypted blobs.
> **Security note:** earlier versions of this doc had you put `turnSecret` directly in `config.js`. Don't — anyone reading the PWA's JS bundle could read it and mint unlimited, long-lived TURN credentials, turning your relay into an open proxy for anyone. The browser now calls the anchor's `/turn-credentials` endpoint instead and only ever sees a credential that expires in an hour. If you have an old `config.js` with `turnSecret` set, remove it and rotate the coturn secret (`static-auth-secret` in `turnserver.conf` and the anchor's `-turn-secret` flag) since the old one was exposed.
> The browser adapter reads `turnURL` and `turnSecret` from `WASTE_CONFIG` and adds the TURN server to the WebRTC `ICEServers` list automatically. If not configured, STUN-only is used (works for most desktop/home NAT situations).
The browser adapter calls `signalURL` with `/ws` swapped for `/turn-credentials` to find the anchor's endpoint by default; set `turnCredentialsURL` explicitly in `WASTE_CONFIG` if the anchor is reachable at a different path. If `turnURL` is set but the credentials endpoint is unreachable, the browser falls back to STUN-only.
**Daemon mode TURN:** pass `-turn-url turn:your-domain.com:3478 -turn-secret YOUR_SECRET_HERE` when starting the daemon. The same coturn `use-auth-secret` HMAC-SHA1 scheme is used — no extra config required beyond what you set up for browser mode.
You'll also need nginx to route the new path to the anchor, alongside `/ws` (see [step 3](#3-nginx-proxy-manager-setup)):
- `/turn-credentials` → anchor process (plain HTTP, no WebSocket upgrade needed)
**Daemon mode TURN:** pass `-turn-url turn:your-domain.com:3478 -turn-secret YOUR_SECRET_HERE` when starting the daemon. This is unaffected by the above — the daemon computes credentials itself server-side and never exposes the secret, same as the anchor now does for browser mode.
---

View File

@@ -6,12 +6,17 @@ package main
import (
"context"
"crypto/ed25519"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"flag"
"log"
"net/http"
"strconv"
"sync"
"time"
@@ -23,16 +28,40 @@ import (
func main() {
bind := flag.String("bind", "0.0.0.0:17339", "address to listen on")
turnSecret := flag.String("turn-secret", "", "coturn use-auth-secret shared secret; enables GET /turn-credentials")
flag.Parse()
a := newAnchor()
http.HandleFunc("/ws", a.handleWS)
if *turnSecret != "" {
http.HandleFunc("/turn-credentials", turnCredentialsHandler(*turnSecret))
log.Printf("anchor: /turn-credentials enabled")
}
log.Printf("anchor: listening on %s", *bind)
if err := http.ListenAndServe(*bind, nil); err != nil {
log.Fatalf("anchor: %v", err)
}
}
// turnCredentialsHandler mints short-lived coturn use-auth-secret credentials
// server-side, so the shared secret never reaches the browser. Mirrors the
// scheme in internal/netmgr.Manager.turnICEServers (daemon mode).
func turnCredentialsHandler(secret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
expiry := strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10)
mac := hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(expiry))
credential := base64.StdEncoding.EncodeToString(mac.Sum(nil))
json.NewEncoder(w).Encode(struct {
Username string `json:"username"`
Credential string `json:"credential"`
TTL int `json:"ttl"`
}{Username: expiry, Credential: credential, TTL: 3600})
}
}
// ── Anchor ────────────────────────────────────────────────────────────────────
type client struct {
@@ -126,8 +155,8 @@ func (a *anchor) handleWS(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
// Send a challenge nonce immediately.
nonce := make([]byte, 16)
// Send a challenge nonce immediately. §5.1 requires 32 bytes.
nonce := make([]byte, 32)
rand.Read(nonce)
nonceHex := hex.EncodeToString(nonce)
if err := wsjson.Write(ctx, conn, proto.AnchorMessage{

32
deploy-web.sh.example Normal file
View File

@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# deploy-web.sh — build and push the web UI to the VPS.
# Assumes SSH agent forwarding is set up.
#
# SETUP: copy this file to deploy-web.sh (gitignored) and set HOST below.
#
# Usage:
# ./deploy-web.sh
#
# Optional env vars:
# HOST SSH target (user@host) (required — edit below)
# REMOTE_DIR path on VPS (default: ~/waste-www)
set -euo pipefail
HOST="${HOST:-user@YOUR_VPS_IP}" # ← edit this
REMOTE_DIR="${REMOTE_DIR:-~/waste-www}"
if [[ "$HOST" == *YOUR_VPS_IP* ]]; then
echo "error: edit HOST in this script (or export HOST=user@your-vps before running)" >&2
exit 1
fi
echo "→ building web UI…"
"$(dirname "$0")/build-web.sh"
echo "→ syncing to $HOST:$REMOTE_DIR"
rsync -azv --delete \
--exclude='config.js' \
web/dist/ "$HOST:$REMOTE_DIR/"
echo "✓ done"

96
launch-tui.sh.example Normal file
View File

@@ -0,0 +1,96 @@
#!/usr/bin/env bash
# launch-tui.sh — build and launch the TUI against a remote anchor.
# Starts a local daemon then opens the Bubble Tea terminal UI.
#
# SETUP: copy this file to launch-tui.sh (gitignored) and set ANCHOR below.
#
# Usage:
# ./launch-tui.sh
# ALIAS=alice NETWORK=friends ./launch-tui.sh
#
# Optional env vars (all have defaults):
# ANCHOR anchor WebSocket URL (required — edit below)
# NETWORK network name to join (default: "friends")
# ALIAS display name (default: $USER)
# DATA_DIR identity + message store dir (default: ~/.waste-$ALIAS)
# IPC_PORT local daemon IPC port (default: 17337)
# SHARE_DIR directory to share with peers (optional)
set -euo pipefail
ANCHOR="${ANCHOR:-wss://YOUR_ANCHOR_DOMAIN/ws}" # ← edit this
NETWORK="${NETWORK:-friends}"
ALIAS="${ALIAS:-${USER:-anon}}"
DATA_DIR="${DATA_DIR:-${HOME}/.waste-${ALIAS}}"
_DEFAULT_ALIAS="${USER:-anon}"
if [ "${ALIAS}" = "${_DEFAULT_ALIAS}" ]; then
IPC_PORT="${IPC_PORT:-17337}"
else
_HASH=$(printf '%d' "0x$(printf '%s' "$ALIAS" | md5sum | cut -c1-4)")
IPC_PORT="${IPC_PORT:-$(( 17400 + _HASH % 1000 ))}"
fi
SHARE_DIR="${SHARE_DIR:-}"
RED='\033[0;31m'; GREEN='\033[0;32m'; DIM='\033[2m'; BOLD='\033[1m'; RESET='\033[0m'
if [[ "$ANCHOR" == *YOUR_ANCHOR_DOMAIN* ]]; then
echo -e "${RED}error: edit ANCHOR in this script (or export ANCHOR=wss://... before running)${RESET}" >&2
exit 1
fi
mkdir -p "$DATA_DIR"
echo ""
echo -e "${BOLD}waste TUI${RESET}"
echo -e "${DIM}anchor : ${BOLD}${ANCHOR}${RESET}"
echo -e "${DIM}network : ${BOLD}${NETWORK}${RESET}"
echo -e "${DIM}alias : ${BOLD}${ALIAS}${RESET}"
echo -e "${DIM}data : ${DATA_DIR}${RESET}"
[ -n "$SHARE_DIR" ] && echo -e "${DIM}share : ${SHARE_DIR}${RESET}"
echo ""
echo -e "${DIM}building binaries…${RESET}"
go build -o /tmp/waste-daemon-run ./cmd/daemon
go build -o /tmp/waste-tui-run ./cmd/tui
echo -e "${GREEN}✓ built${RESET}"
echo ""
existing=$(lsof -ti tcp:"$IPC_PORT" 2>/dev/null || true)
[ -n "$existing" ] && kill "$existing" 2>/dev/null && sleep 0.3 || true
echo -e "${DIM}starting daemon on :${IPC_PORT}…${RESET}"
WS_PORT=$(( IPC_PORT + 1 ))
/tmp/waste-daemon-run \
-alias "$ALIAS" -data-dir "$DATA_DIR" \
-ipc-port "$IPC_PORT" -ws-port "$WS_PORT" \
-anchor "$ANCHOR" \
2>/tmp/waste-daemon.log &
DAEMON_PID=$!
n=0
while ! nc -z 127.0.0.1 "$IPC_PORT" 2>/dev/null; do
sleep 0.1; n=$(( n + 1 ))
[ "$n" -gt 80 ] && echo -e "${RED}daemon failed — check /tmp/waste-daemon.log${RESET}" >&2 && exit 1
done
echo -e "${GREEN}✓ daemon started (pid ${DAEMON_PID})${RESET}"
sleep 0.3
if [ -n "$SHARE_DIR" ]; then
JOIN=$(jq -cn --arg net "$NETWORK" --arg dir "$SHARE_DIR" \
'{"type":"join_network","network_name":$net,"share_dir":$dir}')
else
JOIN=$(jq -cn --arg net "$NETWORK" '{"type":"join_network","network_name":$net}')
fi
echo "$JOIN" | nc -q 0 127.0.0.1 "$IPC_PORT" >/dev/null 2>&1 || true
echo -e "${DIM}joined network: ${BOLD}${NETWORK}${RESET}"
cleanup() { kill "$DAEMON_PID" 2>/dev/null || true; }
trap cleanup EXIT INT TERM
echo ""
echo -e "${BOLD}launching TUI${RESET} — ${DIM}ctrl+c to quit${RESET}"
echo ""
exec /tmp/waste-tui-run -ipc "$IPC_PORT" -network "$NETWORK"

74
launch-web.sh.example Normal file
View File

@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# launch-web.sh — start the daemon and open the web UI Vite dev server.
# For local development / daemon-mode browsing.
#
# SETUP: copy this file to launch-web.sh (gitignored) and set ANCHOR below.
#
# Usage:
# ./launch-web.sh
# ALIAS=alice NETWORK=friends ./launch-web.sh
set -euo pipefail
ANCHOR="${ANCHOR:-wss://YOUR_ANCHOR_DOMAIN/ws}" # ← edit this
NETWORK="${NETWORK:-friends}"
ALIAS="${ALIAS:-${USER:-anon}}"
DATA_DIR="${DATA_DIR:-${HOME}/.waste-${ALIAS}}"
IPC_PORT="${IPC_PORT:-17337}"
WS_PORT=$(( IPC_PORT + 1 ))
if [[ "$ANCHOR" == *YOUR_ANCHOR_DOMAIN* ]]; then
echo "error: edit ANCHOR in this script (or export ANCHOR=wss://... before running)" >&2
exit 1
fi
PIDS=()
cleanup() {
for pid in "${PIDS[@]:-}"; do kill "$pid" 2>/dev/null || true; done
wait 2>/dev/null || true
}
trap cleanup EXIT INT TERM
for port in "$IPC_PORT" "$WS_PORT"; do
existing=$(lsof -ti tcp:"$port" 2>/dev/null || true)
[ -n "$existing" ] && kill "$existing" 2>/dev/null || true
done
for port in "$IPC_PORT" "$WS_PORT"; do
n=0
while lsof -ti tcp:"$port" >/dev/null 2>&1; do
sleep 0.1; n=$(( n + 1 )); [ "$n" -gt 30 ] && break
done
done
mkdir -p "$DATA_DIR"
echo "alias : $ALIAS"
echo "network : $NETWORK"
echo "anchor : $ANCHOR"
echo "ws-port : $WS_PORT"
echo ""
echo "building daemon…"
go build -o /tmp/waste-daemon-web ./cmd/daemon
/tmp/waste-daemon-web \
-alias "$ALIAS" -data-dir "$DATA_DIR" \
-ipc-port "$IPC_PORT" -ws-port "$WS_PORT" \
-anchor "$ANCHOR" \
2>/tmp/waste-daemon-web.log &
PIDS+=($!)
n=0
while ! nc -z 127.0.0.1 "$IPC_PORT" 2>/dev/null; do
sleep 0.1; n=$(( n + 1 ))
[ "$n" -gt 80 ] && echo "daemon failed to start — check /tmp/waste-daemon-web.log" >&2 && exit 1
done
sleep 0.2
jq -cn --arg net "$NETWORK" '{"type":"join_network","network_name":$net}' \
| nc -q0 127.0.0.1 "$IPC_PORT" >/dev/null 2>&1 || true
echo "daemon ready — joined $NETWORK"
echo ""
npm run dev --prefix "$(dirname "$0")/web"

38
serve-web.sh.example Normal file
View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# serve-web.sh — start (or restart) the static file server on the VPS.
# Runs `npx serve` in the background, logs to ~/waste-www.log.
#
# SETUP: copy this file to serve-web.sh (gitignored) and set HOST below.
#
# Usage:
# ./serve-web.sh
#
# Optional env vars:
# HOST SSH target (user@host) (required — edit below)
# REMOTE_DIR path on VPS (default: ~/waste-www)
# PORT local port on VPS (default: 1337)
set -euo pipefail
HOST="${HOST:-user@YOUR_VPS_IP}" # ← edit this
REMOTE_DIR="${REMOTE_DIR:-~/waste-www}"
REMOTE_LOG="~/waste-www.log"
REMOTE_PID="~/waste-www.pid"
PORT="${PORT:-1337}"
if [[ "$HOST" == *YOUR_VPS_IP* ]]; then
echo "error: edit HOST in this script (or export HOST=user@your-vps before running)" >&2
exit 1
fi
ssh "$HOST" bash <<EOF
if [ -f $REMOTE_PID ]; then
kill \$(cat $REMOTE_PID) 2>/dev/null || true
rm -f $REMOTE_PID
fi
echo "[\$(date)] starting npx serve on port $PORT" >> $REMOTE_LOG
nohup npx serve -s $REMOTE_DIR -l $PORT >> $REMOTE_LOG 2>&1 &
echo \$! > $REMOTE_PID
echo "→ started (pid \$(cat $REMOTE_PID)), logging to $REMOTE_LOG"
EOF

View File

@@ -16,23 +16,31 @@ const EKEY_PREFIX = 'yaw/2.1 ekey'
const FS_TIMEOUT = 2000
const STUN = 'stun:stun.l.google.com:19302'
async function turnCredential(secret: string, username: string): Promise<string> {
const key = await crypto.subtle.importKey(
'raw', new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-1' },
false, ['sign']
)
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(username))
return btoa(String.fromCharCode(...new Uint8Array(sig)))
// TURN credentials are short-lived and minted server-side by the anchor's
// GET /turn-credentials endpoint (see cmd/anchor). The shared coturn secret
// never reaches the browser — only a time-limited username/credential pair.
async function fetchTurnCredentials(credentialsURL: string): Promise<{ username: string; credential: string } | null> {
try {
const res = await fetch(credentialsURL)
if (!res.ok) return null
const data = await res.json()
if (!data.username || !data.credential) return null
return { username: data.username, credential: data.credential }
} catch {
return null
}
}
async function iceServers(): Promise<RTCIceServer[]> {
const cfg = (window as unknown as { WASTE_CONFIG?: { turnURL?: string; turnSecret?: string } }).WASTE_CONFIG
const cfg = (window as unknown as { WASTE_CONFIG?: { turnURL?: string; turnCredentialsURL?: string; signalURL?: string } }).WASTE_CONFIG
const servers: RTCIceServer[] = [{ urls: STUN }]
if (cfg?.turnURL && cfg?.turnSecret) {
const user = Math.floor(Date.now() / 1000) + 3600 + ':waste'
const credential = await turnCredential(cfg.turnSecret, user)
servers.push({ urls: cfg.turnURL, username: user, credential })
if (cfg?.turnURL) {
const credentialsURL = cfg.turnCredentialsURL
?? cfg.signalURL?.replace(/^ws/, 'http').replace(/\/ws\/?$/, '/turn-credentials')
if (credentialsURL) {
const creds = await fetchTurnCredentials(credentialsURL)
if (creds) servers.push({ urls: cfg.turnURL, username: creds.username, credential: creds.credential })
}
}
return servers
}