sueta / server / turncreds.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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,
		})
	}
}