askrobots / network-computer
Public
Your phone is the terminal. Stream a Linux/Mac desktop to an iPhone over WebRTC through NAT, with audio and input. Open source, single binaries.
Dan Quellhorst
Firefox policy: no WebRTC mDNS (a page using WebRTC made Firefox listen on UDP 5353)
a1d92f3
1 month, 3 weeks ago
History
main.go · 17.5 KB · 588 lines
| 1 | // nc-rendezvous: the one public piece. Signaling over WebSocket, STUN and TURN |
| 2 | // on one UDP port, and the browser test client. Single static binary. |
| 3 | package main |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/hmac" |
| 8 | "crypto/rand" |
| 9 | "crypto/sha256" |
| 10 | "crypto/subtle" |
| 11 | "crypto/tls" |
| 12 | "embed" |
| 13 | "encoding/base64" |
| 14 | "encoding/json" |
| 15 | "flag" |
| 16 | "fmt" |
| 17 | "io" |
| 18 | "io/fs" |
| 19 | "log" |
| 20 | "net" |
| 21 | "net/http" |
| 22 | "os" |
| 23 | "path/filepath" |
| 24 | "strconv" |
| 25 | "strings" |
| 26 | "sync" |
| 27 | "sync/atomic" |
| 28 | "time" |
| 29 | |
| 30 | "github.com/coder/websocket" |
| 31 | "github.com/pion/turn/v4" |
| 32 | "golang.org/x/crypto/acme/autocert" |
| 33 | |
| 34 | "github.com/askrobots/network-computer/internal/proto" |
| 35 | ) |
| 36 | |
| 37 | //go:embed web |
| 38 | var webFS embed.FS |
| 39 | |
| 40 | type client struct { |
| 41 | id string |
| 42 | name string // set when registered as a host |
| 43 | conn *websocket.Conn |
| 44 | mu sync.Mutex |
| 45 | } |
| 46 | |
| 47 | func (c *client) send(ctx context.Context, m proto.Message) error { |
| 48 | b, _ := json.Marshal(m) |
| 49 | c.mu.Lock() |
| 50 | defer c.mu.Unlock() |
| 51 | return c.conn.Write(ctx, websocket.MessageText, b) |
| 52 | } |
| 53 | |
| 54 | type hub struct { |
| 55 | mu sync.RWMutex |
| 56 | clients map[string]*client // by id |
| 57 | hosts map[string]*client // by name |
| 58 | seq atomic.Int64 |
| 59 | } |
| 60 | |
| 61 | func newHub() *hub { |
| 62 | return &hub{clients: map[string]*client{}, hosts: map[string]*client{}} |
| 63 | } |
| 64 | |
| 65 | func (h *hub) add(c *client) { |
| 66 | h.mu.Lock() |
| 67 | defer h.mu.Unlock() |
| 68 | h.clients[c.id] = c |
| 69 | } |
| 70 | |
| 71 | func (h *hub) remove(c *client) { |
| 72 | h.mu.Lock() |
| 73 | defer h.mu.Unlock() |
| 74 | delete(h.clients, c.id) |
| 75 | if c.name != "" && h.hosts[c.name] == c { |
| 76 | delete(h.hosts, c.name) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | func (h *hub) register(c *client, name string) { |
| 81 | h.mu.Lock() |
| 82 | defer h.mu.Unlock() |
| 83 | c.name = name |
| 84 | h.hosts[name] = c |
| 85 | } |
| 86 | |
| 87 | func (h *hub) lookup(to string) *client { |
| 88 | h.mu.RLock() |
| 89 | defer h.mu.RUnlock() |
| 90 | if c, ok := h.hosts[to]; ok { |
| 91 | return c |
| 92 | } |
| 93 | return h.clients[to] |
| 94 | } |
| 95 | |
| 96 | func (h *hub) hostNames() []string { |
| 97 | h.mu.RLock() |
| 98 | defer h.mu.RUnlock() |
| 99 | out := make([]string, 0, len(h.hosts)) |
| 100 | for n := range h.hosts { |
| 101 | out = append(out, n) |
| 102 | } |
| 103 | return out |
| 104 | } |
| 105 | |
| 106 | func (h *hub) serveWS(w http.ResponseWriter, r *http.Request) { |
| 107 | conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ |
| 108 | OriginPatterns: []string{"*"}, // spike: any origin |
| 109 | }) |
| 110 | if err != nil { |
| 111 | log.Printf("ws accept: %v", err) |
| 112 | return |
| 113 | } |
| 114 | c := &client{id: fmt.Sprintf("c%d", h.seq.Add(1)), conn: conn} |
| 115 | h.add(c) |
| 116 | defer func() { |
| 117 | h.remove(c) |
| 118 | conn.Close(websocket.StatusNormalClosure, "bye") |
| 119 | log.Printf("[%s] disconnected (host=%q)", c.id, c.name) |
| 120 | }() |
| 121 | log.Printf("[%s] connected from %s", c.id, r.RemoteAddr) |
| 122 | |
| 123 | ctx := r.Context() |
| 124 | for { |
| 125 | _, data, err := conn.Read(ctx) |
| 126 | if err != nil { |
| 127 | return |
| 128 | } |
| 129 | var m proto.Message |
| 130 | if err := json.Unmarshal(data, &m); err != nil { |
| 131 | c.send(ctx, proto.Message{Type: "error", Error: "bad json"}) |
| 132 | continue |
| 133 | } |
| 134 | m.From = c.id |
| 135 | switch m.Type { |
| 136 | case "register": |
| 137 | if m.Name == "" { |
| 138 | c.send(ctx, proto.Message{Type: "error", Error: "register needs name"}) |
| 139 | continue |
| 140 | } |
| 141 | h.register(c, m.Name) |
| 142 | log.Printf("[%s] registered host %q", c.id, m.Name) |
| 143 | c.send(ctx, proto.Message{Type: "registered", Name: m.Name}) |
| 144 | case "hosts": |
| 145 | c.send(ctx, proto.Message{Type: "hosts", Hosts: h.hostNames()}) |
| 146 | case "offer", "answer", "ice", "error": |
| 147 | if m.Type == "error" && m.To == "" { |
| 148 | continue |
| 149 | } |
| 150 | dst := h.lookup(m.To) |
| 151 | if dst == nil { |
| 152 | c.send(ctx, proto.Message{Type: "error", Error: "no such peer: " + m.To}) |
| 153 | continue |
| 154 | } |
| 155 | if m.Type != "ice" { |
| 156 | log.Printf("[%s] %s -> %s", c.id, m.Type, m.To) |
| 157 | } |
| 158 | if err := dst.send(ctx, m); err != nil { |
| 159 | c.send(ctx, proto.Message{Type: "error", Error: "peer gone: " + m.To}) |
| 160 | } |
| 161 | default: |
| 162 | c.send(ctx, proto.Message{Type: "error", Error: "unknown type " + m.Type}) |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // startTURN runs STUN and TURN on one UDP socket using pion/turn. Relay access |
| 168 | // uses short-lived TURN REST credentials (username "<expiry>:<id>", password an |
| 169 | // HMAC of it under a secret only this process knows), minted per /config |
| 170 | // request. A leaked credential stops working when it expires. |
| 171 | func startTURN(addr, publicIP, realm, secret string) (*turn.Server, error) { |
| 172 | pc, err := net.ListenPacket("udp4", addr) |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | return turn.NewServer(turn.ServerConfig{ |
| 177 | Realm: realm, |
| 178 | AuthHandler: turn.LongTermTURNRESTAuthHandler(secret, nil), |
| 179 | PacketConnConfigs: []turn.PacketConnConfig{{ |
| 180 | PacketConn: pc, |
| 181 | RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{ |
| 182 | RelayAddress: net.ParseIP(publicIP), |
| 183 | Address: "0.0.0.0", |
| 184 | }, |
| 185 | }}, |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | func main() { |
| 190 | httpAddr := flag.String("http", ":8080", "listen address (signaling + web client)") |
| 191 | turnAddr := flag.String("turn", ":3478", "STUN/TURN UDP listen address ('' to disable)") |
| 192 | publicIP := flag.String("public-ip", "", "public IP of this machine, advertised for TURN relay and in /config") |
| 193 | publicHost := flag.String("public-host", "", "public hostname for /config ice urls (defaults to -public-ip)") |
| 194 | realm := flag.String("realm", "nc", "TURN realm") |
| 195 | turnSecret := flag.String("turn-secret", os.Getenv("NC_TURN_SECRET"), "secret for minting per-session TURN credentials (env NC_TURN_SECRET); random if empty") |
| 196 | mode := flag.String("mode", "auto", "auto | secure | insecure. secure forces TLS (self-signed if no cert is given); insecure forces plain HTTP") |
| 197 | tlsSelf := flag.Bool("tls-self", false, "serve TLS with a persisted self-signed cert; clients pin its fingerprint") |
| 198 | certFile := flag.String("tls-cert", "", "TLS cert file (optional)") |
| 199 | keyFile := flag.String("tls-key", "", "TLS key file (optional)") |
| 200 | stateDir := flag.String("state-dir", defaultStateDir(), "where the self-signed cert and ACME cache live") |
| 201 | authUser := flag.String("user", envOr("NC_USER", "nc"), "username (env NC_USER)") |
| 202 | authPass := flag.String("password", os.Getenv("NC_PASSWORD"), "password (env NC_PASSWORD); generated and printed if empty") |
| 203 | acmeDomain := flag.String("acme-domain", os.Getenv("NC_DOMAIN"), "get a Let's Encrypt cert for this domain, listening on :443 and :80 (env NC_DOMAIN)") |
| 204 | talkback := flag.String("talkback", "", "let phones read what the desk says back to a live stream (/talkback/...) from this local address, e.g. http://127.0.0.1:8078 ('' = off)") |
| 205 | sites := flag.String("sites", "", "serve the object server's published sites (/s/...) from this local address, e.g. http://127.0.0.1:8001 ('' = off)") |
| 206 | localAddr := flag.String("local", "", "with TLS on, also serve plain HTTP on this loopback address (e.g. 127.0.0.1:8765) for an nc-host on the same machine") |
| 207 | flag.Parse() |
| 208 | |
| 209 | if *authPass == "" { |
| 210 | *authPass = randomToken(12) |
| 211 | log.Printf("no -password given, generated one: %s (pass it to nc-host and nc-probe as -password, or set NC_PASSWORD)", *authPass) |
| 212 | } |
| 213 | if *turnSecret == "" { |
| 214 | *turnSecret = randomToken(24) |
| 215 | } |
| 216 | |
| 217 | switch *mode { |
| 218 | case "auto": |
| 219 | case "secure": |
| 220 | if *acmeDomain == "" && *certFile == "" { |
| 221 | *tlsSelf = true |
| 222 | } |
| 223 | case "insecure": |
| 224 | if *acmeDomain != "" || *certFile != "" || *tlsSelf { |
| 225 | log.Fatal("-mode insecure conflicts with -acme-domain / -tls-cert / -tls-self") |
| 226 | } |
| 227 | default: |
| 228 | log.Fatalf("-mode must be auto, secure or insecure, not %q", *mode) |
| 229 | } |
| 230 | |
| 231 | if *publicIP == "" { |
| 232 | *publicIP = guessLocalIP() |
| 233 | log.Printf("no -public-ip given, guessing %s (fine on a LAN, wrong on a VPS behind NAT)", *publicIP) |
| 234 | } |
| 235 | if *publicHost == "" { |
| 236 | *publicHost = *publicIP |
| 237 | } |
| 238 | _, turnPort, _ := net.SplitHostPort(*turnAddr) |
| 239 | |
| 240 | fingerprint := "" |
| 241 | if *tlsSelf { |
| 242 | var err error |
| 243 | *certFile, *keyFile, fingerprint, err = selfSignedCert(filepath.Join(*stateDir, "tls"), |
| 244 | []string{*publicHost, *publicIP, guessLocalIP(), "127.0.0.1", "localhost"}) |
| 245 | if err != nil { |
| 246 | log.Fatalf("self-signed cert: %v", err) |
| 247 | } |
| 248 | } |
| 249 | secure := *acmeDomain != "" || *certFile != "" |
| 250 | |
| 251 | h := newHub() |
| 252 | |
| 253 | if *turnAddr != "" { |
| 254 | srv, err := startTURN(*turnAddr, *publicIP, *realm, *turnSecret) |
| 255 | if err != nil { |
| 256 | log.Fatalf("turn: %v", err) |
| 257 | } |
| 258 | defer srv.Close() |
| 259 | log.Printf("STUN/TURN on udp %s, relay address %s, per-session credentials", *turnAddr, *publicIP) |
| 260 | } |
| 261 | |
| 262 | auth := newAuthority(*authUser, *authPass) |
| 263 | postureName := "insecure" |
| 264 | if secure { |
| 265 | postureName = "secure" |
| 266 | } |
| 267 | |
| 268 | // configFor builds /config for one caller, with fresh relay credentials. |
| 269 | configFor := func() proto.Config { |
| 270 | cfg := proto.Config{Mode: postureName} |
| 271 | if *turnAddr == "" { |
| 272 | return cfg |
| 273 | } |
| 274 | hp := net.JoinHostPort(*publicHost, turnPort) |
| 275 | user, pass, err := turn.GenerateLongTermTURNRESTCredentials(*turnSecret, randomToken(8), tokenTTL) |
| 276 | if err != nil { |
| 277 | log.Printf("turn creds: %v", err) |
| 278 | return cfg |
| 279 | } |
| 280 | cfg.ICEServers = []proto.ICEServer{ |
| 281 | {URLs: []string{"stun:" + hp}}, |
| 282 | {URLs: []string{"turn:" + hp + "?transport=udp"}, Username: user, Credential: pass}, |
| 283 | } |
| 284 | return cfg |
| 285 | } |
| 286 | |
| 287 | sub, _ := fs.Sub(webFS, "web") |
| 288 | mux := http.NewServeMux() |
| 289 | |
| 290 | // POST /auth {user,password} -> {token}. The only place credentials go. |
| 291 | mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) { |
| 292 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 293 | w.Header().Set("Access-Control-Allow-Headers", "content-type,authorization") |
| 294 | if r.Method == http.MethodOptions { |
| 295 | return |
| 296 | } |
| 297 | if r.Method != http.MethodPost { |
| 298 | http.Error(w, "POST only", http.StatusMethodNotAllowed) |
| 299 | return |
| 300 | } |
| 301 | var body struct{ User, Password string } |
| 302 | json.NewDecoder(io.LimitReader(r.Body, 4<<10)).Decode(&body) |
| 303 | ok, limited := auth.checkCredsFrom(r, body.User, body.Password) |
| 304 | if limited { |
| 305 | http.Error(w, `{"error":"too many wrong passwords; try again in 10 minutes"}`, http.StatusTooManyRequests) |
| 306 | return |
| 307 | } |
| 308 | if !ok { |
| 309 | http.Error(w, `{"error":"bad credentials"}`, http.StatusUnauthorized) |
| 310 | return |
| 311 | } |
| 312 | w.Header().Set("Content-Type", "application/json") |
| 313 | json.NewEncoder(w).Encode(map[string]any{ |
| 314 | "token": auth.mint(), |
| 315 | "expiresIn": int(tokenTTL.Seconds()), |
| 316 | "mode": postureName, |
| 317 | }) |
| 318 | }) |
| 319 | |
| 320 | mux.Handle("/ws", auth.guard(http.HandlerFunc(h.serveWS))) |
| 321 | mux.Handle("/config", auth.guard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 322 | w.Header().Set("Content-Type", "application/json") |
| 323 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 324 | w.Header().Set("Cache-Control", "no-store") // relay creds are per request |
| 325 | json.NewEncoder(w).Encode(configFor()) |
| 326 | }))) |
| 327 | mux.Handle("/hosts", auth.guard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 328 | w.Header().Set("Content-Type", "application/json") |
| 329 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 330 | json.NewEncoder(w).Encode(h.hostNames()) |
| 331 | }))) |
| 332 | if *sites != "" { |
| 333 | sp, err := sitesProxy(*sites) |
| 334 | if err != nil { |
| 335 | log.Fatalf("-sites: %v", err) |
| 336 | } |
| 337 | mux.Handle("/s/", sp) |
| 338 | log.Printf("published sites: /s/ -> %s", *sites) |
| 339 | } |
| 340 | if *talkback != "" { |
| 341 | tp, err := talkbackProxy(*talkback) |
| 342 | if err != nil { |
| 343 | log.Fatalf("-talkback: %v", err) |
| 344 | } |
| 345 | mux.Handle("/talkback/", tp) |
| 346 | log.Printf("talkback: /talkback/ -> %s", *talkback) |
| 347 | } |
| 348 | // the page itself is public: no browser login dialog, the app's form asks once |
| 349 | files := http.FileServer(http.FS(sub)) |
| 350 | mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 351 | w.Header().Set("Cache-Control", "no-cache") // the client changes with the server: always revalidate |
| 352 | files.ServeHTTP(w, r) |
| 353 | })) |
| 354 | |
| 355 | srv := &http.Server{Addr: *httpAddr, Handler: mux, ReadHeaderTimeout: 10 * time.Second} |
| 356 | |
| 357 | // A plain listener for processes on this machine (the co-located nc-host) |
| 358 | // when the public side is TLS. Loopback only: it never leaves the box. |
| 359 | startLocal := func() { |
| 360 | if *localAddr == "" { |
| 361 | return |
| 362 | } |
| 363 | host, _, err := net.SplitHostPort(*localAddr) |
| 364 | if ip := net.ParseIP(host); err != nil || ip == nil || !ip.IsLoopback() { |
| 365 | log.Fatalf("-local must be a loopback address like 127.0.0.1:8765, not %q", *localAddr) |
| 366 | } |
| 367 | log.Printf("local plain HTTP on %s (loopback only)", *localAddr) |
| 368 | go func() { |
| 369 | ls := &http.Server{Addr: *localAddr, Handler: mux, ReadHeaderTimeout: 10 * time.Second} |
| 370 | log.Fatal(ls.ListenAndServe()) |
| 371 | }() |
| 372 | } |
| 373 | |
| 374 | switch { |
| 375 | case *acmeDomain != "": |
| 376 | m := &autocert.Manager{ |
| 377 | Prompt: autocert.AcceptTOS, |
| 378 | HostPolicy: autocert.HostWhitelist(*acmeDomain), |
| 379 | Cache: autocert.DirCache(filepath.Join(*stateDir, "acme")), |
| 380 | } |
| 381 | srv.Addr = ":443" |
| 382 | // m.TLSConfig advertises acme-tls/1, which the tls-alpn-01 challenge |
| 383 | // needs; a hand-built config without it fails certificate issuance. |
| 384 | srv.TLSConfig = m.TLSConfig() |
| 385 | srv.TLSConfig.MinVersion = tls.VersionTLS12 |
| 386 | go http.ListenAndServe(":80", m.HTTPHandler(nil)) |
| 387 | log.Printf("secure mode: HTTPS on :443 for %s (ACME)", *acmeDomain) |
| 388 | startLocal() |
| 389 | log.Fatal(srv.ListenAndServeTLS("", "")) |
| 390 | case *certFile != "": |
| 391 | srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} |
| 392 | startLocal() |
| 393 | log.Printf("secure mode: HTTPS on %s (web client: https://%s%s/)", *httpAddr, *publicHost, portSuffix(*httpAddr)) |
| 394 | if fingerprint != "" { |
| 395 | log.Printf("self-signed cert. Pin this fingerprint in clients (-tls-fingerprint / NC_TLS_FP):") |
| 396 | log.Printf(" sha256 %s", fingerprint) |
| 397 | log.Printf("browsers will ask once to accept the certificate") |
| 398 | } |
| 399 | log.Fatal(srv.ListenAndServeTLS(*certFile, *keyFile)) |
| 400 | default: |
| 401 | log.Printf("insecure mode: plain HTTP on %s (web client: http://%s%s/). Signaling is unencrypted; use -mode secure off a trusted LAN.", |
| 402 | *httpAddr, *publicHost, portSuffix(*httpAddr)) |
| 403 | log.Fatal(srv.ListenAndServe()) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | // authority authenticates callers. It deliberately never sends a |
| 408 | // WWW-Authenticate header, so a browser shows no native login dialog: the |
| 409 | // client's own form is the single place credentials are entered. Three ways in: |
| 410 | // a Bearer token from POST /auth, HTTP Basic (for headless nc-host/nc-probe), |
| 411 | // or ?token= on the WebSocket, which browsers cannot give headers to. |
| 412 | type authority struct { |
| 413 | user, pass string |
| 414 | secret []byte |
| 415 | |
| 416 | mu sync.Mutex |
| 417 | fails map[string]*failCount // wrong passwords per client address |
| 418 | } |
| 419 | |
| 420 | type failCount struct { |
| 421 | n int |
| 422 | since time.Time |
| 423 | } |
| 424 | |
| 425 | // Wrong passwords: after maxFails from one address within failWindow, that |
| 426 | // address is refused until the window passes. The desk itself (loopback) is |
| 427 | // never refused, so its own host can't be locked out. |
| 428 | const ( |
| 429 | maxFails = 10 |
| 430 | failWindow = 10 * time.Minute |
| 431 | ) |
| 432 | |
| 433 | func clientAddr(r *http.Request) string { |
| 434 | host, _, err := net.SplitHostPort(r.RemoteAddr) |
| 435 | if err != nil { |
| 436 | return r.RemoteAddr |
| 437 | } |
| 438 | return host |
| 439 | } |
| 440 | |
| 441 | func (a *authority) blocked(addr string) bool { |
| 442 | if ip := net.ParseIP(addr); ip != nil && ip.IsLoopback() { |
| 443 | return false |
| 444 | } |
| 445 | a.mu.Lock() |
| 446 | defer a.mu.Unlock() |
| 447 | f := a.fails[addr] |
| 448 | if f == nil || time.Since(f.since) > failWindow { |
| 449 | return false |
| 450 | } |
| 451 | return f.n >= maxFails |
| 452 | } |
| 453 | |
| 454 | func (a *authority) failed(addr string) { |
| 455 | a.mu.Lock() |
| 456 | defer a.mu.Unlock() |
| 457 | f := a.fails[addr] |
| 458 | if f == nil || time.Since(f.since) > failWindow { |
| 459 | if len(a.fails) > 10000 { // bounded: forget everyone rather than grow forever |
| 460 | a.fails = map[string]*failCount{} |
| 461 | } |
| 462 | f = &failCount{since: time.Now()} |
| 463 | a.fails[addr] = f |
| 464 | } |
| 465 | f.n++ |
| 466 | if f.n == maxFails { |
| 467 | log.Printf("auth: %d wrong passwords from %s; refusing it for %v", maxFails, addr, failWindow) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | // checkCredsFrom checks a password from a client, counting failures. |
| 472 | func (a *authority) checkCredsFrom(r *http.Request, u, p string) (ok, limited bool) { |
| 473 | addr := clientAddr(r) |
| 474 | if a.blocked(addr) { |
| 475 | return false, true |
| 476 | } |
| 477 | if a.checkCreds(u, p) { |
| 478 | return true, false |
| 479 | } |
| 480 | a.failed(addr) |
| 481 | return false, false |
| 482 | } |
| 483 | |
| 484 | const tokenTTL = 12 * time.Hour |
| 485 | |
| 486 | func newAuthority(user, pass string) *authority { |
| 487 | secret := make([]byte, 32) |
| 488 | rand.Read(secret) |
| 489 | return &authority{user: user, pass: pass, secret: secret, fails: map[string]*failCount{}} |
| 490 | } |
| 491 | |
| 492 | func (a *authority) checkCreds(u, p string) bool { |
| 493 | return subtle.ConstantTimeCompare([]byte(u), []byte(a.user)) == 1 && |
| 494 | subtle.ConstantTimeCompare([]byte(p), []byte(a.pass)) == 1 |
| 495 | } |
| 496 | |
| 497 | func (a *authority) sign(payload []byte) string { |
| 498 | m := hmac.New(sha256.New, a.secret) |
| 499 | m.Write(payload) |
| 500 | return base64.RawURLEncoding.EncodeToString(m.Sum(nil)) |
| 501 | } |
| 502 | |
| 503 | func (a *authority) mint() string { |
| 504 | payload := []byte(fmt.Sprintf("%s|%d", a.user, time.Now().Add(tokenTTL).Unix())) |
| 505 | return base64.RawURLEncoding.EncodeToString(payload) + "." + a.sign(payload) |
| 506 | } |
| 507 | |
| 508 | func (a *authority) validToken(tok string) bool { |
| 509 | dot := strings.LastIndex(tok, ".") |
| 510 | if dot < 0 { |
| 511 | return false |
| 512 | } |
| 513 | payload, err := base64.RawURLEncoding.DecodeString(tok[:dot]) |
| 514 | if err != nil { |
| 515 | return false |
| 516 | } |
| 517 | if subtle.ConstantTimeCompare([]byte(a.sign(payload)), []byte(tok[dot+1:])) != 1 { |
| 518 | return false |
| 519 | } |
| 520 | i := strings.LastIndex(string(payload), "|") |
| 521 | if i < 0 { |
| 522 | return false |
| 523 | } |
| 524 | exp, err := strconv.ParseInt(string(payload)[i+1:], 10, 64) |
| 525 | return err == nil && time.Now().Unix() <= exp |
| 526 | } |
| 527 | |
| 528 | func (a *authority) ok(r *http.Request) bool { |
| 529 | if h := r.Header.Get("Authorization"); h != "" { |
| 530 | if strings.HasPrefix(h, "Bearer ") { |
| 531 | return a.validToken(strings.TrimPrefix(h, "Bearer ")) |
| 532 | } |
| 533 | if u, p, isBasic := r.BasicAuth(); isBasic { |
| 534 | ok, _ := a.checkCredsFrom(r, u, p) |
| 535 | return ok |
| 536 | } |
| 537 | } |
| 538 | if t := r.URL.Query().Get("token"); t != "" { |
| 539 | return a.validToken(t) |
| 540 | } |
| 541 | return false |
| 542 | } |
| 543 | |
| 544 | // guard protects a handler. 401 with no WWW-Authenticate: no browser dialog. |
| 545 | func (a *authority) guard(next http.Handler) http.Handler { |
| 546 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 547 | if !a.ok(r) { |
| 548 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 549 | http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized) |
| 550 | return |
| 551 | } |
| 552 | next.ServeHTTP(w, r) |
| 553 | }) |
| 554 | } |
| 555 | |
| 556 | func randomToken(n int) string { |
| 557 | b := make([]byte, n) |
| 558 | rand.Read(b) |
| 559 | return base64.RawURLEncoding.EncodeToString(b)[:n] |
| 560 | } |
| 561 | |
| 562 | func envOr(k, def string) string { |
| 563 | if v := os.Getenv(k); v != "" { |
| 564 | return v |
| 565 | } |
| 566 | return def |
| 567 | } |
| 568 | |
| 569 | func portSuffix(addr string) string { |
| 570 | _, p, _ := net.SplitHostPort(addr) |
| 571 | if p == "80" || p == "" { |
| 572 | return "" |
| 573 | } |
| 574 | return ":" + p |
| 575 | } |
| 576 | |
| 577 | func guessLocalIP() string { |
| 578 | conn, err := net.Dial("udp", "10.255.255.255:1") |
| 579 | if err != nil { |
| 580 | return "127.0.0.1" |
| 581 | } |
| 582 | defer conn.Close() |
| 583 | ip := conn.LocalAddr().(*net.UDPAddr).IP.String() |
| 584 | if strings.Contains(ip, ":") { |
| 585 | return "127.0.0.1" |
| 586 | } |
| 587 | return ip |
| 588 | } |