package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"net"
"net/http"
"strconv"
"time"
)
const turnTTL = 3600 // seconds
// turnCredsHandler mints ephemeral credentials in the coturn REST-API scheme
// (use-auth-secret): username is an expiry unix timestamp, password is
// base64(HMAC-SHA1(static-auth-secret, username)).
func turnCredsHandler(cfg *Config) http.HandlerFunc {
limiter := newIPRateLimiter(10, time.Minute)
return func(w http.ResponseWriter, r *http.Request) {
// The app is also reachable via IPFS gateway origins, so CORS stays open;
// abuse is bounded by the TTL, this rate limit, and coturn's own quotas.
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
return
}
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
if !limiter.allow(ip) {
http.Error(w, "rate limited", http.StatusTooManyRequests)
return
}
if cfg.AuthSecret == "" {
http.Error(w, "turn not configured", http.StatusServiceUnavailable)
return
}
username := strconv.FormatInt(time.Now().Unix()+turnTTL, 10)
mac := hmac.New(sha1.New, []byte(cfg.AuthSecret))
mac.Write([]byte(username))
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"username": username,
"credential": base64.StdEncoding.EncodeToString(mac.Sum(nil)),
"ttl": turnTTL,
"urls": cfg.TurnURLs,
})
}
}