@tianacloud/dsh-remote 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1711 @@
1
+ package main
2
+
3
+ import (
4
+ "bufio"
5
+ "bytes"
6
+ "crypto/ed25519"
7
+ "crypto/rand"
8
+ "crypto/sha1"
9
+ "crypto/sha256"
10
+ "crypto/subtle"
11
+ "encoding/base64"
12
+ "encoding/binary"
13
+ "encoding/hex"
14
+ "encoding/json"
15
+ "errors"
16
+ "io"
17
+ "log"
18
+ "net"
19
+ "net/http"
20
+ "net/url"
21
+ "os"
22
+ "strings"
23
+ "sync"
24
+ "sync/atomic"
25
+ "time"
26
+ )
27
+
28
+ const (
29
+ wsGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
30
+ maxFramePayload = 1 << 20
31
+ maxQueuedBytes = 2 << 20
32
+ maxHostQueuedBytes = 4 << 20
33
+ maxClientHostQueueBytes = 512 << 10
34
+ maxPreAuthPayload = 4 << 10
35
+ maxPreAuthQueueBytes = 8 << 10
36
+ maxPreAuthFrames = 12
37
+ maxWaitingCtrlPerMin = 12
38
+ maxConfigFileBytes = 256 << 10
39
+ defaultUnauthTimeout = 30 * time.Second
40
+ maxPeers = 24
41
+ maxClients = 8
42
+ maxSessionAge = 2 * time.Hour
43
+ readTimeout = 70 * time.Second
44
+ pingInterval = 25 * time.Second
45
+ writeTimeout = 15 * time.Second
46
+
47
+ opCont = 0x0
48
+ opText = 0x1
49
+ opBinary = 0x2
50
+ opClose = 0x8
51
+ opPing = 0x9
52
+ opPong = 0xA
53
+
54
+ msgControlJSON = 0x01
55
+ )
56
+
57
+ type wsFrame struct {
58
+ opcode byte
59
+ payload []byte
60
+ release func()
61
+ }
62
+
63
+ type wsConn struct {
64
+ readWindow time.Time
65
+ readFrames int
66
+ readBytes uint64
67
+ maxQueued int64
68
+ netConn net.Conn
69
+ br *bufio.Reader
70
+ sendCh chan wsFrame
71
+ writeMu sync.Mutex
72
+ queuedBytes atomic.Int64
73
+ lifetime *time.Timer
74
+ closed atomic.Bool
75
+ closeCh chan struct{}
76
+ once sync.Once
77
+ }
78
+
79
+ func acceptWebSocket(w http.ResponseWriter, r *http.Request) (*wsConn, error) {
80
+ return acceptWebSocketWithQueue(w, r, 24, maxQueuedBytes, maxSessionAge)
81
+ }
82
+
83
+ func isWebSocketUpgrade(r *http.Request) bool {
84
+ return r.Method == http.MethodGet &&
85
+ r.Header.Get("Sec-WebSocket-Version") == "13" &&
86
+ headerContainsToken(r.Header, "Connection", "upgrade") &&
87
+ strings.EqualFold(strings.TrimSpace(r.Header.Get("Upgrade")), "websocket")
88
+ }
89
+
90
+ func acceptWebSocketWithQueue(w http.ResponseWriter, r *http.Request, slots int, maxQueue int64, maxAge time.Duration) (*wsConn, error) {
91
+ if !isWebSocketUpgrade(r) {
92
+ http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired)
93
+ return nil, errors.New("not a websocket upgrade")
94
+ }
95
+ key := strings.TrimSpace(r.Header.Get("Sec-WebSocket-Key"))
96
+ if decoded, err := base64.StdEncoding.DecodeString(key); err != nil || len(decoded) != 16 {
97
+ http.Error(w, "invalid websocket key", http.StatusBadRequest)
98
+ return nil, errors.New("missing websocket key")
99
+ }
100
+ hijacker, ok := w.(http.Hijacker)
101
+ if !ok {
102
+ http.Error(w, "hijack unsupported", http.StatusInternalServerError)
103
+ return nil, errors.New("hijack unsupported")
104
+ }
105
+ conn, brw, err := hijacker.Hijack()
106
+ if err != nil {
107
+ return nil, err
108
+ }
109
+
110
+ h := sha1.Sum([]byte(key + wsGUID))
111
+ accept := base64.StdEncoding.EncodeToString(h[:])
112
+
113
+ var resp strings.Builder
114
+ resp.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
115
+ resp.WriteString("Upgrade: websocket\r\n")
116
+ resp.WriteString("Connection: Upgrade\r\n")
117
+ resp.WriteString("Sec-WebSocket-Accept: ")
118
+ resp.WriteString(accept)
119
+ resp.WriteString("\r\n")
120
+ if proto := strings.TrimSpace(r.Header.Get("Sec-WebSocket-Protocol")); proto != "" {
121
+ first := strings.TrimSpace(strings.Split(proto, ",")[0])
122
+ if first != "" && !strings.ContainsAny(first, "\r\n") {
123
+ resp.WriteString("Sec-WebSocket-Protocol: ")
124
+ resp.WriteString(first)
125
+ resp.WriteString("\r\n")
126
+ }
127
+ }
128
+ resp.WriteString("\r\n")
129
+
130
+ _ = conn.SetWriteDeadline(time.Now().Add(writeTimeout))
131
+ if _, err := io.WriteString(conn, resp.String()); err != nil {
132
+ _ = conn.Close()
133
+ return nil, err
134
+ }
135
+
136
+ wc := &wsConn{
137
+ maxQueued: maxQueue,
138
+ netConn: conn,
139
+ br: brw.Reader,
140
+ sendCh: make(chan wsFrame, slots),
141
+ closeCh: make(chan struct{}),
142
+ }
143
+ _ = conn.SetReadDeadline(time.Now().Add(readTimeout))
144
+ wc.lifetime = time.AfterFunc(maxAge, func() { wc.close(1001, "session expired") })
145
+ go wc.writeLoop()
146
+ return wc, nil
147
+ }
148
+
149
+ func headerContainsToken(h http.Header, key, token string) bool {
150
+ for _, v := range h.Values(key) {
151
+ for _, part := range strings.Split(v, ",") {
152
+ if strings.EqualFold(strings.TrimSpace(part), token) {
153
+ return true
154
+ }
155
+ }
156
+ }
157
+ return false
158
+ }
159
+
160
+ func (c *wsConn) close(code uint16, reason string) {
161
+ c.once.Do(func() {
162
+ c.closed.Store(true)
163
+ close(c.closeCh)
164
+ c.lifetime.Stop()
165
+ if code != 0 && c.writeMu.TryLock() {
166
+ payload := make([]byte, 2+len(reason))
167
+ binary.BigEndian.PutUint16(payload[:2], code)
168
+ copy(payload[2:], reason)
169
+ _ = c.writeFrame(opClose, payload, 100*time.Millisecond)
170
+ c.writeMu.Unlock()
171
+ }
172
+ _ = c.netConn.Close()
173
+ })
174
+ }
175
+
176
+ func (c *wsConn) sendBinary(payload []byte) bool {
177
+ return c.enqueue(wsFrame{opcode: opBinary, payload: payload}, true)
178
+ }
179
+
180
+ func (c *wsConn) tryEnqueueBinary(payload []byte, release func()) bool {
181
+ return c.enqueue(wsFrame{opcode: opBinary, payload: payload, release: release}, false)
182
+ }
183
+
184
+ func (c *wsConn) enqueue(frame wsFrame, closeOnOverflow bool) bool {
185
+ if c.closed.Load() {
186
+ return false
187
+ }
188
+ size := int64(len(frame.payload))
189
+ limit := c.maxQueued
190
+ if limit <= 0 {
191
+ limit = maxQueuedBytes
192
+ }
193
+ if c.queuedBytes.Add(size) <= limit {
194
+ select {
195
+ case c.sendCh <- frame:
196
+ return true
197
+ case <-c.closeCh:
198
+ default:
199
+ }
200
+ }
201
+ c.queuedBytes.Add(-size)
202
+ if closeOnOverflow {
203
+ c.close(0, "")
204
+ }
205
+ return false
206
+ }
207
+
208
+ func (c *wsConn) drainReleases() {
209
+ for {
210
+ select {
211
+ case f := <-c.sendCh:
212
+ c.queuedBytes.Add(-int64(len(f.payload)))
213
+ if f.release != nil {
214
+ f.release()
215
+ }
216
+ default:
217
+ return
218
+ }
219
+ }
220
+ }
221
+
222
+ func (c *wsConn) writeLoop() {
223
+ ticker := time.NewTicker(pingInterval)
224
+ defer func() {
225
+ ticker.Stop()
226
+ c.drainReleases()
227
+ }()
228
+ for {
229
+ select {
230
+ case <-c.closeCh:
231
+ return
232
+ case f := <-c.sendCh:
233
+ c.queuedBytes.Add(-int64(len(f.payload)))
234
+ if f.release != nil {
235
+ f.release()
236
+ }
237
+ if err := c.writeRawFrame(f.opcode, f.payload); err != nil {
238
+ c.close(0, "")
239
+ return
240
+ }
241
+ case <-ticker.C:
242
+ if err := c.writeRawFrame(opPing, []byte("hb")); err != nil {
243
+ c.close(0, "")
244
+ return
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ func (c *wsConn) writeRawFrame(opcode byte, payload []byte) error {
251
+ c.writeMu.Lock()
252
+ defer c.writeMu.Unlock()
253
+ return c.writeFrame(opcode, payload, writeTimeout)
254
+ }
255
+
256
+ func (c *wsConn) writeFrame(opcode byte, payload []byte, timeout time.Duration) error {
257
+ _ = c.netConn.SetWriteDeadline(time.Now().Add(timeout))
258
+ var hdr [10]byte
259
+ hdr[0] = 0x80 | (opcode & 0x0f)
260
+ n := len(payload)
261
+ hlen := 2
262
+ switch {
263
+ case n < 126:
264
+ hdr[1] = byte(n)
265
+ case n <= 65535:
266
+ hdr[1] = 126
267
+ binary.BigEndian.PutUint16(hdr[2:4], uint16(n))
268
+ hlen = 4
269
+ default:
270
+ hdr[1] = 127
271
+ binary.BigEndian.PutUint64(hdr[2:10], uint64(n))
272
+ hlen = 10
273
+ }
274
+ if _, err := c.netConn.Write(hdr[:hlen]); err != nil {
275
+ return err
276
+ }
277
+ if n > 0 {
278
+ if _, err := c.netConn.Write(payload); err != nil {
279
+ return err
280
+ }
281
+ }
282
+ return nil
283
+ }
284
+
285
+ func (c *wsConn) readMessage() (byte, []byte, error) {
286
+ var msgOpcode byte
287
+ var buf bytes.Buffer
288
+ for {
289
+ var hdr [2]byte
290
+ if _, err := io.ReadFull(c.br, hdr[:]); err != nil {
291
+ return 0, nil, err
292
+ }
293
+ fin := (hdr[0] & 0x80) != 0
294
+ opcode := hdr[0] & 0x0f
295
+ masked := (hdr[1] & 0x80) != 0
296
+ plen := uint64(hdr[1] & 0x7f)
297
+ if !masked || hdr[0]&0x70 != 0 {
298
+ return 0, nil, errors.New("invalid websocket frame flags")
299
+ }
300
+ if opcode >= 0x8 && (!fin || plen > 125 || opcode > opPong) {
301
+ return 0, nil, errors.New("invalid websocket control frame")
302
+ }
303
+ if opcode < 0x8 && (opcode > opBinary || (opcode == opCont) != (msgOpcode != 0)) {
304
+ return 0, nil, errors.New("invalid websocket fragmentation")
305
+ }
306
+
307
+ switch plen {
308
+ case 126:
309
+ var ext [2]byte
310
+ if _, err := io.ReadFull(c.br, ext[:]); err != nil {
311
+ return 0, nil, err
312
+ }
313
+ plen = uint64(binary.BigEndian.Uint16(ext[:]))
314
+ case 127:
315
+ var ext [8]byte
316
+ if _, err := io.ReadFull(c.br, ext[:]); err != nil {
317
+ return 0, nil, err
318
+ }
319
+ plen = binary.BigEndian.Uint64(ext[:])
320
+ }
321
+
322
+ if plen > maxFramePayload || uint64(buf.Len())+plen > maxFramePayload {
323
+ return 0, nil, errors.New("frame exceeds max payload")
324
+ }
325
+
326
+ now := time.Now()
327
+ if now.Sub(c.readWindow) >= time.Second {
328
+ c.readWindow, c.readFrames, c.readBytes = now, 0, 0
329
+ }
330
+ c.readFrames++
331
+ c.readBytes += plen
332
+ if c.readFrames > 512 || c.readBytes > 32<<20 {
333
+ return 0, nil, errors.New("websocket rate limit")
334
+ }
335
+ var maskKey [4]byte
336
+ if masked {
337
+ if _, err := io.ReadFull(c.br, maskKey[:]); err != nil {
338
+ return 0, nil, err
339
+ }
340
+ }
341
+
342
+ payload := make([]byte, plen)
343
+ if plen > 0 {
344
+ if _, err := io.ReadFull(c.br, payload); err != nil {
345
+ return 0, nil, err
346
+ }
347
+ if masked {
348
+ for i := range payload {
349
+ payload[i] ^= maskKey[i%4]
350
+ }
351
+ }
352
+ }
353
+
354
+ // Control frames may be interleaved between fragments.
355
+ if opcode >= 0x8 {
356
+ switch opcode {
357
+ case opClose:
358
+ c.close(1000, "")
359
+ return 0, nil, io.EOF
360
+ case opPing:
361
+ c.enqueue(wsFrame{opcode: opPong, payload: payload}, true)
362
+ case opPong:
363
+ if string(payload) == "hb" {
364
+ _ = c.netConn.SetReadDeadline(time.Now().Add(readTimeout))
365
+ }
366
+ }
367
+ continue
368
+ }
369
+
370
+ if opcode != opCont {
371
+ msgOpcode = opcode
372
+ }
373
+ buf.Write(payload)
374
+ if fin {
375
+ return msgOpcode, buf.Bytes(), nil
376
+ }
377
+ }
378
+ }
379
+
380
+ type hostInfo struct {
381
+ HostID string `json:"hostId"`
382
+ Name string `json:"name"`
383
+ TenantID string `json:"tenantId,omitempty"`
384
+ UserID string `json:"userId,omitempty"`
385
+ ConnectedAt int64 `json:"connectedAt"`
386
+ Clients int `json:"clients"`
387
+ }
388
+
389
+ type hostEntry struct {
390
+ id string
391
+ name string
392
+ tenantID string
393
+ userID string
394
+ webID string
395
+ policyEpoch uint64
396
+ connectedAt int64
397
+ conn *wsConn
398
+ mu sync.Mutex
399
+ sessions map[uint32]*clientSession
400
+ }
401
+
402
+ type callerIdentity struct {
403
+ UserID string `json:"userId"`
404
+ TenantID string `json:"tenantId"`
405
+ WebID string `json:"webId,omitempty"`
406
+ AppOwnerID string `json:"appOwnerId,omitempty"`
407
+ }
408
+
409
+ func (c callerIdentity) IsAppOwner() bool {
410
+ return c.AppOwnerID != "" && c.UserID == c.AppOwnerID
411
+ }
412
+
413
+ func validCallerID(s string) bool {
414
+ if len(s) == 0 || len(s) > 128 {
415
+ return false
416
+ }
417
+ for i := 0; i < len(s); i++ {
418
+ ch := s[i]
419
+ alnum := (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')
420
+ if i == 0 {
421
+ if !alnum {
422
+ return false
423
+ }
424
+ continue
425
+ }
426
+ if !alnum && ch != '.' && ch != '_' && ch != ':' && ch != '-' {
427
+ return false
428
+ }
429
+ }
430
+ return true
431
+ }
432
+
433
+ func validHostID(s string) bool {
434
+ if len(s) == 0 || len(s) > 48 {
435
+ return false
436
+ }
437
+ for i := 0; i < len(s); i++ {
438
+ ch := s[i]
439
+ if !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-') {
440
+ return false
441
+ }
442
+ }
443
+ return true
444
+ }
445
+
446
+ func validOrigin(raw string) bool {
447
+ if raw == "" || strings.TrimSpace(raw) != raw {
448
+ return false
449
+ }
450
+ u, err := url.Parse(raw)
451
+ if err != nil || u.User != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
452
+ return false
453
+ }
454
+ if u.Path != "" && u.Path != "/" {
455
+ return false
456
+ }
457
+ if u.Path == "/" {
458
+ return false
459
+ }
460
+ if u.Scheme == "https" {
461
+ return true
462
+ }
463
+ if u.Scheme == "http" {
464
+ host := u.Hostname()
465
+ return host == "127.0.0.1" || host == "::1" || host == "localhost"
466
+ }
467
+ return false
468
+ }
469
+
470
+ func singleHeaderExact(h http.Header, target string) (string, int) {
471
+ count := 0
472
+ var val string
473
+ for k, vals := range h {
474
+ if strings.EqualFold(k, target) {
475
+ count += len(vals)
476
+ if len(vals) == 1 {
477
+ val = vals[0]
478
+ }
479
+ }
480
+ }
481
+ return val, count
482
+ }
483
+
484
+ func callerFromRequest(r *http.Request) (callerIdentity, bool) {
485
+ uid, uidCount := singleHeaderExact(r.Header, "Tiana-Caller-User-Id")
486
+ tid, tidCount := singleHeaderExact(r.Header, "Tiana-Caller-Tenant-Id")
487
+ ownerID, ownerCount := singleHeaderExact(r.Header, "Tiana-Caller-App-Owner-Id")
488
+ webID, webCount := singleHeaderExact(r.Header, "Tiana-Caller-Web-Id")
489
+ if uidCount != 1 || tidCount != 1 || ownerCount > 1 || webCount > 1 {
490
+ return callerIdentity{}, false
491
+ }
492
+ if !validCallerID(uid) || !validCallerID(tid) {
493
+ return callerIdentity{}, false
494
+ }
495
+ if ownerCount == 1 && !validCallerID(ownerID) {
496
+ return callerIdentity{}, false
497
+ }
498
+ if webCount == 1 && !validCallerID(webID) {
499
+ return callerIdentity{}, false
500
+ }
501
+ return callerIdentity{
502
+ UserID: uid,
503
+ TenantID: tid,
504
+ WebID: webID,
505
+ AppOwnerID: ownerID,
506
+ }, true
507
+ }
508
+
509
+ func hasAnyCallerHeader(h http.Header) bool {
510
+ for k := range h {
511
+ if strings.HasPrefix(strings.ToLower(k), "tiana-caller-") {
512
+ return true
513
+ }
514
+ }
515
+ return false
516
+ }
517
+
518
+ type clientSession struct {
519
+ id uint32
520
+ conn *wsConn
521
+ identity callerIdentity
522
+ origin string
523
+ challenge string
524
+ admittedAt time.Time
525
+ maxAge time.Duration
526
+ unauthTimer *time.Timer
527
+ authenticated atomic.Bool
528
+ preAuthFrames atomic.Int32
529
+ inflightToHost atomic.Int64
530
+ waitCtrlWindow time.Time
531
+ waitCtrlCount int
532
+ mu sync.Mutex
533
+ host *hostEntry
534
+ }
535
+
536
+ func (s *clientSession) armUnauthTimer(timeout time.Duration) {
537
+ if timeout <= 0 {
538
+ return
539
+ }
540
+ s.mu.Lock()
541
+ defer s.mu.Unlock()
542
+ if s.unauthTimer != nil || s.authenticated.Load() {
543
+ return
544
+ }
545
+ s.unauthTimer = time.AfterFunc(timeout, func() {
546
+ if !s.authenticated.Load() {
547
+ s.conn.close(1008, "authentication timeout")
548
+ }
549
+ })
550
+ }
551
+
552
+ func (s *clientSession) stopUnauthTimer() {
553
+ s.mu.Lock()
554
+ t := s.unauthTimer
555
+ s.unauthTimer = nil
556
+ s.mu.Unlock()
557
+ if t != nil {
558
+ t.Stop()
559
+ }
560
+ }
561
+
562
+ func (s *clientSession) markAuthenticated() {
563
+ if s.authenticated.CompareAndSwap(false, true) {
564
+ s.stopUnauthTimer()
565
+ }
566
+ }
567
+
568
+ func (s *clientSession) forwardToHost(host *hostEntry, payload []byte) bool {
569
+ authed := s.authenticated.Load()
570
+ if !authed {
571
+ if len(payload) > maxPreAuthPayload || s.preAuthFrames.Add(1) > maxPreAuthFrames {
572
+ return false
573
+ }
574
+ }
575
+ fwd := make([]byte, 4+len(payload))
576
+ binary.BigEndian.PutUint32(fwd[0:4], s.id)
577
+ copy(fwd[4:], payload)
578
+
579
+ size := int64(len(fwd))
580
+ quota := int64(maxClientHostQueueBytes)
581
+ if !authed {
582
+ quota = maxPreAuthQueueBytes
583
+ }
584
+ if s.inflightToHost.Add(size) > quota {
585
+ s.inflightToHost.Add(-size)
586
+ return false
587
+ }
588
+ released := atomic.Bool{}
589
+ release := func() {
590
+ if released.CompareAndSwap(false, true) {
591
+ s.inflightToHost.Add(-size)
592
+ }
593
+ }
594
+ if !host.conn.tryEnqueueBinary(fwd, release) {
595
+ release()
596
+ return false
597
+ }
598
+ return true
599
+ }
600
+
601
+ type relayAccess struct {
602
+ Version int `json:"version,omitempty"`
603
+ HostID string `json:"hostId"`
604
+ HostName string `json:"hostName,omitempty"`
605
+ HostDigest string `json:"hostDigest"`
606
+ HostPublicKey string `json:"hostPublicKey,omitempty"`
607
+ OwnerUserID string `json:"ownerUserId"`
608
+ OwnerTenantID string `json:"ownerTenantId"`
609
+ WebID string `json:"webId"`
610
+ Origin string `json:"origin"`
611
+ UpdatedAt string `json:"updatedAt,omitempty"`
612
+ }
613
+
614
+ // Provisioning or template installation may set these compile-time defaults.
615
+ // Neither contains any registration key, E2EE key or platform credential.
616
+ var relayConfigJSON = ""
617
+ var defaultWebID = ""
618
+
619
+ func effectiveDefaultWebID(raw string) string {
620
+ v := strings.TrimSpace(raw)
621
+ if v == "" || strings.HasPrefix(v, "__TIANA_WEB_ID_") {
622
+ return ""
623
+ }
624
+ return v
625
+ }
626
+
627
+ type resolvedPolicy struct {
628
+ Paired bool
629
+ Access relayAccess
630
+ Key string
631
+ }
632
+
633
+ func policyComparisonKey(paired bool, a relayAccess) string {
634
+ if !paired {
635
+ return "unpaired:" + a.WebID
636
+ }
637
+ return strings.Join([]string{
638
+ "paired", a.HostID, a.HostDigest, a.HostPublicKey, a.OwnerUserID, a.OwnerTenantID, a.WebID, a.Origin,
639
+ }, "|")
640
+ }
641
+
642
+ func validatePairedAccess(a relayAccess, requireVersion bool, pinnedWebID string) error {
643
+ if requireVersion && a.Version != 1 {
644
+ return errors.New("unsupported policy version")
645
+ }
646
+ if !validHostID(a.HostID) {
647
+ return errors.New("invalid hostId")
648
+ }
649
+ if len(a.HostName) > 128 {
650
+ return errors.New("invalid hostName")
651
+ }
652
+ if !validCallerID(a.OwnerUserID) || !validCallerID(a.OwnerTenantID) || !validCallerID(a.WebID) {
653
+ return errors.New("invalid owner or webId")
654
+ }
655
+ if pinnedWebID != "" && a.WebID != pinnedWebID {
656
+ return errors.New("policy webId mismatch")
657
+ }
658
+ if !validOrigin(a.Origin) {
659
+ return errors.New("invalid policy origin")
660
+ }
661
+ if a.HostDigest == "" {
662
+ return errors.New("missing hostDigest")
663
+ }
664
+ if len(a.HostDigest) != sha256.Size*2 {
665
+ return errors.New("invalid hostDigest length")
666
+ }
667
+ if _, err := hex.DecodeString(a.HostDigest); err != nil {
668
+ return errors.New("invalid hostDigest hex")
669
+ }
670
+ if a.HostPublicKey != "" {
671
+ pub, err := base64.RawURLEncoding.DecodeString(a.HostPublicKey)
672
+ if err != nil || len(pub) != ed25519.PublicKeySize {
673
+ return errors.New("invalid hostPublicKey")
674
+ }
675
+ }
676
+ return nil
677
+ }
678
+
679
+ type policySource struct {
680
+ mu sync.Mutex
681
+ configFile string
682
+ fallbackJSON string
683
+ defaultWebID string
684
+ staticPolicy *resolvedPolicy
685
+ cachedPath string
686
+ cachedMod time.Time
687
+ cachedSize int64
688
+ lastGood resolvedPolicy
689
+ hasLastGood bool
690
+ }
691
+
692
+ func (ps *policySource) resolve() (resolvedPolicy, error) {
693
+ ps.mu.Lock()
694
+ defer ps.mu.Unlock()
695
+
696
+ if ps.staticPolicy != nil {
697
+ return *ps.staticPolicy, nil
698
+ }
699
+
700
+ pinnedWeb := effectiveDefaultWebID(ps.defaultWebID)
701
+ cfgPath := ps.configFile
702
+ if cfgPath == "" {
703
+ cfgPath = strings.TrimSpace(os.Getenv("FUNCTION_CONFIG_FILE"))
704
+ }
705
+
706
+ if cfgPath != "" {
707
+ info, err := os.Stat(cfgPath)
708
+ if err == nil {
709
+ if ps.hasLastGood && ps.cachedPath == cfgPath && ps.cachedMod.Equal(info.ModTime()) && ps.cachedSize == info.Size() {
710
+ return ps.lastGood, nil
711
+ }
712
+ f, openErr := os.Open(cfgPath)
713
+ if openErr != nil {
714
+ if ps.hasLastGood {
715
+ return ps.lastGood, nil
716
+ }
717
+ return resolvedPolicy{}, openErr
718
+ }
719
+ raw, readErr := io.ReadAll(io.LimitReader(f, maxConfigFileBytes+1))
720
+ _ = f.Close()
721
+ if readErr != nil || len(raw) > maxConfigFileBytes {
722
+ if ps.hasLastGood {
723
+ return ps.lastGood, nil
724
+ }
725
+ return resolvedPolicy{}, errors.New("failed to read function config")
726
+ }
727
+ var cfgMap map[string]struct {
728
+ Kind string `json:"kind"`
729
+ Value string `json:"value"`
730
+ }
731
+ if unmarshalErr := json.Unmarshal(raw, &cfgMap); unmarshalErr != nil {
732
+ if ps.hasLastGood {
733
+ return ps.lastGood, nil
734
+ }
735
+ return resolvedPolicy{}, errors.New("invalid function config json")
736
+ }
737
+ if entry, ok := cfgMap["DSH_REMOTE_POLICY"]; ok && strings.TrimSpace(entry.Value) != "" {
738
+ if entry.Kind != "plain" {
739
+ return resolvedPolicy{}, errors.New("DSH_REMOTE_POLICY must be plain")
740
+ }
741
+ var access relayAccess
742
+ if err := json.Unmarshal([]byte(entry.Value), &access); err != nil {
743
+ return resolvedPolicy{}, errors.New("invalid DSH_REMOTE_POLICY json")
744
+ }
745
+ if err := validatePairedAccess(access, true, pinnedWeb); err != nil {
746
+ return resolvedPolicy{}, err
747
+ }
748
+ pol := resolvedPolicy{
749
+ Paired: true,
750
+ Access: access,
751
+ Key: policyComparisonKey(true, access),
752
+ }
753
+ ps.cachedPath = cfgPath
754
+ ps.cachedMod = info.ModTime()
755
+ ps.cachedSize = info.Size()
756
+ ps.lastGood = pol
757
+ ps.hasLastGood = true
758
+ return pol, nil
759
+ }
760
+ // Config file exists without DSH_REMOTE_POLICY; fall through to fallback/unpaired.
761
+ pol, err := ps.resolveFallbackLocked(pinnedWeb)
762
+ if err == nil {
763
+ ps.cachedPath = cfgPath
764
+ ps.cachedMod = info.ModTime()
765
+ ps.cachedSize = info.Size()
766
+ ps.lastGood = pol
767
+ ps.hasLastGood = true
768
+ }
769
+ return pol, err
770
+ } else if os.IsNotExist(err) {
771
+ // Preserve lastGood across transient ENOENT during atomic config replacement.
772
+ if ps.hasLastGood && ps.cachedPath == cfgPath {
773
+ return ps.lastGood, nil
774
+ }
775
+ } else {
776
+ if ps.hasLastGood {
777
+ return ps.lastGood, nil
778
+ }
779
+ return resolvedPolicy{}, err
780
+ }
781
+ }
782
+
783
+ return ps.resolveFallbackLocked(pinnedWeb)
784
+ }
785
+
786
+ func (ps *policySource) resolveFallbackLocked(pinnedWeb string) (resolvedPolicy, error) {
787
+ if strings.TrimSpace(ps.fallbackJSON) != "" {
788
+ var access relayAccess
789
+ if err := json.Unmarshal([]byte(ps.fallbackJSON), &access); err != nil {
790
+ return resolvedPolicy{}, errors.New("invalid relayConfigJSON")
791
+ }
792
+ if err := validatePairedAccess(access, false, pinnedWeb); err != nil {
793
+ return resolvedPolicy{}, err
794
+ }
795
+ return resolvedPolicy{
796
+ Paired: true,
797
+ Access: access,
798
+ Key: policyComparisonKey(true, access),
799
+ }, nil
800
+ }
801
+ if envHost := strings.TrimSpace(os.Getenv("DSH_REMOTE_EXPECTED_HOST_ID")); envHost != "" {
802
+ access := relayAccess{
803
+ HostID: envHost,
804
+ HostName: strings.TrimSpace(os.Getenv("DSH_REMOTE_HOST_NAME")),
805
+ HostDigest: strings.TrimSpace(os.Getenv("DSH_REMOTE_HOST_DIGEST")),
806
+ HostPublicKey: strings.TrimSpace(os.Getenv("DSH_REMOTE_HOST_PUBLIC_KEY")),
807
+ OwnerUserID: strings.TrimSpace(os.Getenv("DSH_REMOTE_OWNER_USER_ID")),
808
+ OwnerTenantID: strings.TrimSpace(os.Getenv("DSH_REMOTE_OWNER_TENANT_ID")),
809
+ WebID: strings.TrimSpace(os.Getenv("DSH_REMOTE_WEB_ID")),
810
+ Origin: strings.TrimSpace(os.Getenv("DSH_REMOTE_ORIGIN")),
811
+ }
812
+ if err := validatePairedAccess(access, false, pinnedWeb); err != nil {
813
+ return resolvedPolicy{}, err
814
+ }
815
+ return resolvedPolicy{
816
+ Paired: true,
817
+ Access: access,
818
+ Key: policyComparisonKey(true, access),
819
+ }, nil
820
+ }
821
+ unpaired := relayAccess{WebID: pinnedWeb}
822
+ return resolvedPolicy{
823
+ Paired: false,
824
+ Access: unpaired,
825
+ Key: policyComparisonKey(false, unpaired),
826
+ }, nil
827
+ }
828
+
829
+ type relayHub struct {
830
+ syncMu sync.Mutex
831
+ policy policySource
832
+ policyEpoch uint64
833
+ paired bool
834
+ access relayAccess
835
+ policyKey string
836
+ sessionMaxAge time.Duration
837
+ unauthTimeout time.Duration
838
+ peers chan struct{}
839
+ clients chan struct{}
840
+ mu sync.RWMutex
841
+ hosts map[string]*hostEntry
842
+ allClients map[uint32]*clientSession
843
+ nextSID atomic.Uint64
844
+ }
845
+
846
+ func newRelayHub(access relayAccess) *relayHub {
847
+ paired := access.HostID != ""
848
+ pol := resolvedPolicy{
849
+ Paired: paired,
850
+ Access: access,
851
+ Key: policyComparisonKey(paired, access),
852
+ }
853
+ return &relayHub{
854
+ policy: policySource{staticPolicy: &pol},
855
+ policyEpoch: 1,
856
+ paired: paired,
857
+ access: access,
858
+ policyKey: pol.Key,
859
+ hosts: make(map[string]*hostEntry),
860
+ allClients: make(map[uint32]*clientSession),
861
+ sessionMaxAge: maxSessionAge,
862
+ unauthTimeout: defaultUnauthTimeout,
863
+ peers: make(chan struct{}, maxPeers),
864
+ clients: make(chan struct{}, maxClients),
865
+ }
866
+ }
867
+
868
+ func newDynamicRelayHub(configFile, fallbackJSON, pinnedWebID string) *relayHub {
869
+ h := &relayHub{
870
+ policy: policySource{
871
+ configFile: configFile,
872
+ fallbackJSON: fallbackJSON,
873
+ defaultWebID: pinnedWebID,
874
+ },
875
+ policyEpoch: 1,
876
+ hosts: make(map[string]*hostEntry),
877
+ allClients: make(map[uint32]*clientSession),
878
+ sessionMaxAge: maxSessionAge,
879
+ unauthTimeout: defaultUnauthTimeout,
880
+ peers: make(chan struct{}, maxPeers),
881
+ clients: make(chan struct{}, maxClients),
882
+ }
883
+ if pol, err := h.policy.resolve(); err == nil {
884
+ h.paired = pol.Paired
885
+ h.access = pol.Access
886
+ h.policyKey = pol.Key
887
+ }
888
+ return h
889
+ }
890
+
891
+ func (h *relayHub) syncPolicy() (resolvedPolicy, uint64, error) {
892
+ h.syncMu.Lock()
893
+ defer h.syncMu.Unlock()
894
+
895
+ pol, err := h.policy.resolve()
896
+ if err != nil {
897
+ return resolvedPolicy{}, 0, err
898
+ }
899
+ epoch := h.applyPolicy(pol)
900
+ return pol, epoch, nil
901
+ }
902
+
903
+ func (h *relayHub) applyPolicy(pol resolvedPolicy) uint64 {
904
+ var evictHosts []*hostEntry
905
+ var evictClients []*clientSession
906
+
907
+ h.mu.Lock()
908
+ if h.policyKey == pol.Key {
909
+ epoch := h.policyEpoch
910
+ h.mu.Unlock()
911
+ return epoch
912
+ }
913
+ wasPaired := h.paired
914
+ h.policyEpoch++
915
+ epoch := h.policyEpoch
916
+ h.paired = pol.Paired
917
+ h.access = pol.Access
918
+ h.policyKey = pol.Key
919
+
920
+ if wasPaired {
921
+ for id, entry := range h.hosts {
922
+ evictHosts = append(evictHosts, entry)
923
+ delete(h.hosts, id)
924
+ }
925
+ for _, s := range h.allClients {
926
+ evictClients = append(evictClients, s)
927
+ }
928
+ } else if pol.Paired {
929
+ // Unpaired -> Paired transition: keep waiting Owner clients matching the new policy
930
+ // so they receive host_online seamlessly; evict any non-matching sessions.
931
+ for _, s := range h.allClients {
932
+ if s.identity.UserID != pol.Access.OwnerUserID ||
933
+ s.identity.TenantID != pol.Access.OwnerTenantID ||
934
+ s.identity.WebID != pol.Access.WebID ||
935
+ s.origin != pol.Access.Origin {
936
+ evictClients = append(evictClients, s)
937
+ }
938
+ }
939
+ }
940
+ h.mu.Unlock()
941
+
942
+ for _, entry := range evictHosts {
943
+ entry.disconnectClients("policy updated")
944
+ entry.conn.close(1012, "policy updated")
945
+ }
946
+ for _, s := range evictClients {
947
+ s.conn.close(1012, "policy updated")
948
+ }
949
+ return epoch
950
+ }
951
+
952
+ func (h *relayHub) isHostConnected(hostID string) bool {
953
+ if hostID == "" {
954
+ return false
955
+ }
956
+ h.mu.RLock()
957
+ defer h.mu.RUnlock()
958
+ return h.hosts[hostID] != nil
959
+ }
960
+
961
+ func (h *relayHub) listHosts() []hostInfo {
962
+ h.mu.RLock()
963
+ defer h.mu.RUnlock()
964
+ out := make([]hostInfo, 0, len(h.hosts))
965
+ for _, entry := range h.hosts {
966
+ entry.mu.Lock()
967
+ clients := len(entry.sessions)
968
+ entry.mu.Unlock()
969
+ out = append(out, hostInfo{
970
+ HostID: entry.id,
971
+ Name: entry.name,
972
+ TenantID: entry.tenantID,
973
+ UserID: entry.userID,
974
+ ConnectedAt: entry.connectedAt,
975
+ Clients: clients,
976
+ })
977
+ }
978
+ return out
979
+ }
980
+
981
+ func marshalClientControlFrame(obj any) ([]byte, bool) {
982
+ body, err := json.Marshal(obj)
983
+ if err != nil {
984
+ return nil, false
985
+ }
986
+ frame := make([]byte, 5+len(body))
987
+ binary.BigEndian.PutUint32(frame[0:4], 0)
988
+ frame[4] = msgControlJSON
989
+ copy(frame[5:], body)
990
+ return frame, true
991
+ }
992
+
993
+ func (h *relayHub) enqueueHostOnlineLocked(entry *hostEntry, hostDigest string) []*wsConn {
994
+ if !h.paired || h.policyEpoch != entry.policyEpoch || h.hosts[entry.id] != entry {
995
+ return nil
996
+ }
997
+ if len(h.allClients) == 0 {
998
+ return nil
999
+ }
1000
+ frame, ok := marshalClientControlFrame(map[string]any{
1001
+ "type": "host_online",
1002
+ "paired": true,
1003
+ "hostConnected": true,
1004
+ "hostId": entry.id,
1005
+ "hostName": entry.name,
1006
+ "hostDigest": hostDigest,
1007
+ "ts": time.Now().UnixMilli(),
1008
+ })
1009
+ if !ok {
1010
+ return nil
1011
+ }
1012
+ var overflowed []*wsConn
1013
+ for _, s := range h.allClients {
1014
+ if s.identity.UserID != entry.userID ||
1015
+ s.identity.TenantID != entry.tenantID ||
1016
+ s.identity.WebID != entry.webID {
1017
+ continue
1018
+ }
1019
+ if s.conn == nil || s.conn.closed.Load() {
1020
+ continue
1021
+ }
1022
+ frameCopy := append([]byte(nil), frame...)
1023
+ if !s.conn.tryEnqueueBinary(frameCopy, nil) && !s.conn.closed.Load() {
1024
+ overflowed = append(overflowed, s.conn)
1025
+ }
1026
+ }
1027
+ return overflowed
1028
+ }
1029
+
1030
+ func (h *relayHub) broadcastHostOnline(entry *hostEntry, hostDigest string) {
1031
+ h.mu.RLock()
1032
+ overflowed := h.enqueueHostOnlineLocked(entry, hostDigest)
1033
+ h.mu.RUnlock()
1034
+
1035
+ for _, c := range overflowed {
1036
+ c.close(1008, "control queue overflow")
1037
+ }
1038
+ }
1039
+
1040
+ func (h *relayHub) registerHost(id, name, tenantID, userID string, conn *wsConn, expectedEpoch uint64, expectedPolicyKey string) (*hostEntry, bool) {
1041
+ if id == "" {
1042
+ id = "default"
1043
+ }
1044
+ if name == "" {
1045
+ name = id
1046
+ }
1047
+ entry := &hostEntry{
1048
+ id: id,
1049
+ name: name,
1050
+ tenantID: tenantID,
1051
+ userID: userID,
1052
+ connectedAt: time.Now().UnixMilli(),
1053
+ conn: conn,
1054
+ sessions: make(map[uint32]*clientSession),
1055
+ }
1056
+
1057
+ h.mu.Lock()
1058
+ if h.policyEpoch != expectedEpoch || !h.paired || h.policyKey != expectedPolicyKey ||
1059
+ h.access.HostID != id || h.access.OwnerUserID != userID || h.access.OwnerTenantID != tenantID {
1060
+ h.mu.Unlock()
1061
+ return nil, false
1062
+ }
1063
+ entry.webID = h.access.WebID
1064
+ entry.policyEpoch = h.policyEpoch
1065
+ hostDigest := h.access.HostDigest
1066
+ prev := h.hosts[id]
1067
+ h.hosts[id] = entry
1068
+ overflowed := h.enqueueHostOnlineLocked(entry, hostDigest)
1069
+ h.mu.Unlock()
1070
+
1071
+ if prev != nil {
1072
+ prev.disconnectClients("host reconnected")
1073
+ prev.conn.close(1000, "replaced by newer host connection")
1074
+ }
1075
+ for _, c := range overflowed {
1076
+ c.close(1008, "control queue overflow")
1077
+ }
1078
+ return entry, true
1079
+ }
1080
+
1081
+ func (h *relayHub) registerClient(session *clientSession, expectedEpoch uint64, expectedPolicyKey string, expectedPaired bool) bool {
1082
+ h.mu.Lock()
1083
+ defer h.mu.Unlock()
1084
+ if h.policyEpoch != expectedEpoch || h.policyKey != expectedPolicyKey || h.paired != expectedPaired {
1085
+ return false
1086
+ }
1087
+ if h.paired {
1088
+ if session.identity.UserID != h.access.OwnerUserID ||
1089
+ session.identity.TenantID != h.access.OwnerTenantID ||
1090
+ session.identity.WebID != h.access.WebID ||
1091
+ session.origin != h.access.Origin {
1092
+ return false
1093
+ }
1094
+ }
1095
+ h.allClients[session.id] = session
1096
+ return true
1097
+ }
1098
+
1099
+ func (h *relayHub) unregisterHost(entry *hostEntry) {
1100
+ h.mu.Lock()
1101
+ if h.hosts[entry.id] == entry {
1102
+ delete(h.hosts, entry.id)
1103
+ }
1104
+ h.mu.Unlock()
1105
+ entry.disconnectClients("host disconnected")
1106
+ }
1107
+
1108
+ func (e *hostEntry) disconnectClients(reason string) {
1109
+ e.mu.Lock()
1110
+ sessions := make([]*clientSession, 0, len(e.sessions))
1111
+ for _, s := range e.sessions {
1112
+ sessions = append(sessions, s)
1113
+ }
1114
+ e.sessions = make(map[uint32]*clientSession)
1115
+ e.mu.Unlock()
1116
+
1117
+ for _, s := range sessions {
1118
+ s.mu.Lock()
1119
+ if s.host == e {
1120
+ s.host = nil
1121
+ }
1122
+ s.mu.Unlock()
1123
+ sendClientControl(s.conn, map[string]any{
1124
+ "type": "host_disconnected",
1125
+ "hostId": e.id,
1126
+ "reason": reason,
1127
+ })
1128
+ s.conn.close(1012, reason)
1129
+ }
1130
+ }
1131
+
1132
+ func (h *relayHub) bindSession(s *clientSession, hostID string, expectedEpoch uint64) (*hostEntry, error) {
1133
+ h.mu.RLock()
1134
+ if expectedEpoch > 0 && h.policyEpoch != expectedEpoch {
1135
+ h.mu.RUnlock()
1136
+ return nil, errors.New("policy updated")
1137
+ }
1138
+ paired := h.paired
1139
+ configuredHostID := h.access.HostID
1140
+ if !paired || configuredHostID == "" {
1141
+ h.mu.RUnlock()
1142
+ return nil, errors.New("relay is not paired")
1143
+ }
1144
+ if s.identity.UserID != h.access.OwnerUserID ||
1145
+ s.identity.TenantID != h.access.OwnerTenantID ||
1146
+ s.identity.WebID != h.access.WebID ||
1147
+ s.origin != h.access.Origin {
1148
+ h.mu.RUnlock()
1149
+ return nil, errors.New("policy identity mismatch")
1150
+ }
1151
+ if hostID != "" && hostID != configuredHostID {
1152
+ h.mu.RUnlock()
1153
+ return nil, errors.New("host unavailable")
1154
+ }
1155
+ target := h.hosts[configuredHostID]
1156
+ if target == nil {
1157
+ h.mu.RUnlock()
1158
+ return nil, errors.New("host is offline")
1159
+ }
1160
+ s.mu.Lock()
1161
+ if s.host == target {
1162
+ s.mu.Unlock()
1163
+ h.mu.RUnlock()
1164
+ return target, nil
1165
+ }
1166
+ // A disconnected or replaced host closes its clients. Only a new
1167
+ // WebSocket can bind to the replacement.
1168
+ if s.host != nil {
1169
+ s.mu.Unlock()
1170
+ h.mu.RUnlock()
1171
+ return nil, errors.New("client must reconnect")
1172
+ }
1173
+ s.host = target
1174
+ target.mu.Lock()
1175
+ target.sessions[s.id] = s
1176
+ target.mu.Unlock()
1177
+ s.mu.Unlock()
1178
+ h.mu.RUnlock()
1179
+
1180
+ remainingMs := (s.maxAge - time.Since(s.admittedAt)).Milliseconds()
1181
+ if remainingMs <= 0 {
1182
+ h.closeSession(s)
1183
+ return nil, errors.New("client session expired")
1184
+ }
1185
+
1186
+ s.armUnauthTimer(h.unauthTimeout)
1187
+
1188
+ if !sendHostControl(target.conn, map[string]any{
1189
+ "type": "open_session", "sessionId": s.id, "hostId": target.id,
1190
+ "userId": s.identity.UserID, "tenantId": s.identity.TenantID, "webId": s.identity.WebID,
1191
+ "challenge": s.challenge, "admittedAt": s.admittedAt.UnixMilli(), "remainingMs": remainingMs,
1192
+ }) {
1193
+ h.closeSession(s)
1194
+ return nil, errors.New("host is disconnected")
1195
+ }
1196
+ return target, nil
1197
+ }
1198
+
1199
+ func (h *relayHub) closeSession(s *clientSession) {
1200
+ s.mu.Lock()
1201
+ host := s.host
1202
+ s.host = nil
1203
+ s.mu.Unlock()
1204
+ if host != nil {
1205
+ host.mu.Lock()
1206
+ delete(host.sessions, s.id)
1207
+ host.mu.Unlock()
1208
+ sendHostControl(host.conn, map[string]any{
1209
+ "type": "close_session",
1210
+ "sessionId": s.id,
1211
+ })
1212
+ }
1213
+ }
1214
+
1215
+ // Client wire frame: [4B streamId][1B msgType][payload]
1216
+ func sendClientControl(conn *wsConn, obj any) {
1217
+ body, err := json.Marshal(obj)
1218
+ if err != nil {
1219
+ return
1220
+ }
1221
+ frame := make([]byte, 5+len(body))
1222
+ binary.BigEndian.PutUint32(frame[0:4], 0)
1223
+ frame[4] = msgControlJSON
1224
+ copy(frame[5:], body)
1225
+ conn.sendBinary(frame)
1226
+ }
1227
+
1228
+ // Host wire frame: [4B sessionId][4B streamId][1B msgType][payload]
1229
+ func sendHostControl(conn *wsConn, obj any) bool {
1230
+ body, err := json.Marshal(obj)
1231
+ if err != nil {
1232
+ return false
1233
+ }
1234
+ frame := make([]byte, 9+len(body))
1235
+ binary.BigEndian.PutUint32(frame[0:4], 0)
1236
+ binary.BigEndian.PutUint32(frame[4:8], 0)
1237
+ frame[8] = msgControlJSON
1238
+ copy(frame[9:], body)
1239
+ return conn.tryEnqueueBinary(frame, nil)
1240
+ }
1241
+
1242
+ func acquire(slot chan struct{}) bool {
1243
+ select {
1244
+ case slot <- struct{}{}:
1245
+ return true
1246
+ default:
1247
+ return false
1248
+ }
1249
+ }
1250
+
1251
+ func verifyHostAuth(r *http.Request, hostID string, access relayAccess) bool {
1252
+ if hostID == "" || hostID != access.HostID {
1253
+ return false
1254
+ }
1255
+ if len(r.Header.Values("Origin")) != 0 || hasAnyCallerHeader(r.Header) {
1256
+ return false
1257
+ }
1258
+ if access.HostDigest != "" {
1259
+ want, err := hex.DecodeString(access.HostDigest)
1260
+ key, keyCount := singleHeaderExact(r.Header, "Dsh-Host-Registration")
1261
+ if err != nil || len(want) != sha256.Size || keyCount != 1 || len(key) != 43 {
1262
+ return false
1263
+ }
1264
+ actual := sha256.Sum256([]byte(key))
1265
+ if subtle.ConstantTimeCompare(want, actual[:]) != 1 {
1266
+ return false
1267
+ }
1268
+ }
1269
+ if access.HostPublicKey != "" {
1270
+ pubBytes, err := base64.RawURLEncoding.DecodeString(access.HostPublicKey)
1271
+ if err != nil || len(pubBytes) != ed25519.PublicKeySize {
1272
+ return false
1273
+ }
1274
+ sigHeader, sigCount := singleHeaderExact(r.Header, "Dsh-Host-Signature")
1275
+ tsHeader, tsCount := singleHeaderExact(r.Header, "Dsh-Host-Timestamp")
1276
+ if sigCount != 1 || tsCount != 1 {
1277
+ return false
1278
+ }
1279
+ sigBytes, err := base64.RawURLEncoding.DecodeString(sigHeader)
1280
+ if err != nil || len(sigBytes) != ed25519.SignatureSize {
1281
+ return false
1282
+ }
1283
+ msg := []byte("dsh-remote-host:" + hostID + ":" + tsHeader)
1284
+ if !ed25519.Verify(ed25519.PublicKey(pubBytes), msg, sigBytes) {
1285
+ return false
1286
+ }
1287
+ }
1288
+ return true
1289
+ }
1290
+
1291
+ func (h *relayHub) handleHostWS(w http.ResponseWriter, r *http.Request) {
1292
+ pol, epoch, err := h.syncPolicy()
1293
+ if err != nil {
1294
+ http.Error(w, "invalid relay policy", http.StatusServiceUnavailable)
1295
+ return
1296
+ }
1297
+ if !pol.Paired {
1298
+ http.Error(w, "forbidden", http.StatusForbidden)
1299
+ return
1300
+ }
1301
+ hostID := r.URL.Query().Get("host_id")
1302
+ if !verifyHostAuth(r, hostID, pol.Access) {
1303
+ http.Error(w, "forbidden", http.StatusForbidden)
1304
+ return
1305
+ }
1306
+ if !acquire(h.peers) {
1307
+ http.Error(w, "relay at capacity", http.StatusTooManyRequests)
1308
+ return
1309
+ }
1310
+ defer func() { <-h.peers }()
1311
+ conn, err := acceptWebSocketWithQueue(w, r, 256, maxHostQueuedBytes, h.sessionMaxAge)
1312
+ if err != nil {
1313
+ return
1314
+ }
1315
+ name := strings.TrimSpace(r.URL.Query().Get("name"))
1316
+ if name == "" {
1317
+ name = pol.Access.HostName
1318
+ }
1319
+ if len(name) > 128 {
1320
+ name = hostID
1321
+ }
1322
+ tenantID, userID := pol.Access.OwnerTenantID, pol.Access.OwnerUserID
1323
+
1324
+ entry, ok := h.registerHost(hostID, name, tenantID, userID, conn, epoch, pol.Key)
1325
+ if !ok {
1326
+ conn.close(1012, "policy updated")
1327
+ return
1328
+ }
1329
+ defer func() {
1330
+ h.unregisterHost(entry)
1331
+ conn.close(1000, "")
1332
+ }()
1333
+
1334
+ sendHostControl(conn, map[string]any{
1335
+ "type": "host_registered",
1336
+ "version": 2,
1337
+ "hostId": entry.id,
1338
+ "name": entry.name,
1339
+ "tenantId": entry.tenantID,
1340
+ "userId": entry.userID,
1341
+ })
1342
+
1343
+ for {
1344
+ opcode, payload, err := conn.readMessage()
1345
+ if err != nil {
1346
+ return
1347
+ }
1348
+ if opcode != opBinary || len(payload) < 9 {
1349
+ continue
1350
+ }
1351
+ sid := binary.BigEndian.Uint32(payload[0:4])
1352
+ if sid == 0 {
1353
+ streamID := binary.BigEndian.Uint32(payload[4:8])
1354
+ if streamID == 0 && payload[8] == msgControlJSON && len(payload) <= 1024 {
1355
+ var ctrl struct {
1356
+ Type string `json:"type"`
1357
+ SessionID uint32 `json:"sessionId"`
1358
+ }
1359
+ if json.Unmarshal(payload[9:], &ctrl) == nil && ctrl.Type == "session_authenticated" && ctrl.SessionID > 0 {
1360
+ entry.mu.Lock()
1361
+ s := entry.sessions[ctrl.SessionID]
1362
+ entry.mu.Unlock()
1363
+ if s != nil {
1364
+ s.markAuthenticated()
1365
+ }
1366
+ }
1367
+ }
1368
+ continue
1369
+ }
1370
+ entry.mu.Lock()
1371
+ session := entry.sessions[sid]
1372
+ entry.mu.Unlock()
1373
+ if session != nil {
1374
+ session.conn.sendBinary(payload[4:])
1375
+ }
1376
+ }
1377
+ }
1378
+
1379
+ func (h *relayHub) handleClientWS(w http.ResponseWriter, r *http.Request) {
1380
+ pol, epoch, err := h.syncPolicy()
1381
+ if err != nil {
1382
+ http.Error(w, "invalid relay policy", http.StatusServiceUnavailable)
1383
+ return
1384
+ }
1385
+ caller, ok := callerFromRequest(r)
1386
+ origin, originCount := singleHeaderExact(r.Header, "Origin")
1387
+ if !ok || originCount != 1 || !validOrigin(origin) {
1388
+ http.Error(w, "forbidden", http.StatusForbidden)
1389
+ return
1390
+ }
1391
+
1392
+ if !pol.Paired {
1393
+ if !caller.IsAppOwner() || caller.WebID == "" {
1394
+ http.Error(w, "forbidden", http.StatusForbidden)
1395
+ return
1396
+ }
1397
+ if pol.Access.WebID != "" && caller.WebID != pol.Access.WebID {
1398
+ http.Error(w, "forbidden", http.StatusForbidden)
1399
+ return
1400
+ }
1401
+ // Non-WebSocket probes to /ws/client when unpaired receive 409 Conflict;
1402
+ // authenticated Owner WebSocket connections enter waiting mode for host_online.
1403
+ if !isWebSocketUpgrade(r) {
1404
+ http.Error(w, "relay not paired", http.StatusConflict)
1405
+ return
1406
+ }
1407
+ } else {
1408
+ if origin != pol.Access.Origin ||
1409
+ caller.UserID != pol.Access.OwnerUserID ||
1410
+ caller.TenantID != pol.Access.OwnerTenantID ||
1411
+ caller.WebID != pol.Access.WebID ||
1412
+ (caller.AppOwnerID != "" && !caller.IsAppOwner()) {
1413
+ http.Error(w, "forbidden", http.StatusForbidden)
1414
+ return
1415
+ }
1416
+ }
1417
+
1418
+ if !acquire(h.clients) {
1419
+ http.Error(w, "relay at capacity", http.StatusTooManyRequests)
1420
+ return
1421
+ }
1422
+ defer func() { <-h.clients }()
1423
+ conn, err := acceptWebSocketWithQueue(w, r, 24, maxQueuedBytes, h.sessionMaxAge)
1424
+ if err != nil {
1425
+ return
1426
+ }
1427
+
1428
+ sid := h.nextSID.Add(1)
1429
+ if sid > uint64(^uint32(0)) {
1430
+ conn.close(1008, "relay session exhausted")
1431
+ return
1432
+ }
1433
+
1434
+ var challenge [16]byte
1435
+ if _, err := rand.Read(challenge[:]); err != nil {
1436
+ conn.close(1011, "session unavailable")
1437
+ return
1438
+ }
1439
+ session := &clientSession{
1440
+ challenge: base64.RawURLEncoding.EncodeToString(challenge[:]),
1441
+ id: uint32(sid),
1442
+ conn: conn,
1443
+ identity: caller,
1444
+ origin: origin,
1445
+ admittedAt: time.Now(),
1446
+ maxAge: h.sessionMaxAge,
1447
+ }
1448
+
1449
+ if !h.registerClient(session, epoch, pol.Key, pol.Paired) {
1450
+ conn.close(1012, "policy updated")
1451
+ return
1452
+ }
1453
+
1454
+ defer func() {
1455
+ session.stopUnauthTimer()
1456
+ h.mu.Lock()
1457
+ delete(h.allClients, session.id)
1458
+ h.mu.Unlock()
1459
+ h.closeSession(session)
1460
+ conn.close(1000, "")
1461
+ }()
1462
+
1463
+ if !pol.Paired {
1464
+ sendClientControl(conn, map[string]any{
1465
+ "type": "welcome",
1466
+ "version": 2,
1467
+ "paired": false,
1468
+ "hostConnected": false,
1469
+ "webId": caller.WebID,
1470
+ "sessionId": sid,
1471
+ "challenge": session.challenge,
1472
+ "user": caller,
1473
+ "hosts": []hostInfo{},
1474
+ })
1475
+ } else {
1476
+ reqHostID := strings.TrimSpace(r.URL.Query().Get("host_id"))
1477
+ hosts := h.listHosts()
1478
+ var selectedHostID string
1479
+ var bindErr string
1480
+
1481
+ if reqHostID != "" || len(hosts) == 1 {
1482
+ target, bErr := h.bindSession(session, reqHostID, epoch)
1483
+ if bErr != nil {
1484
+ bindErr = bErr.Error()
1485
+ } else {
1486
+ selectedHostID = target.id
1487
+ }
1488
+ }
1489
+
1490
+ hostName := pol.Access.HostName
1491
+ if hostName == "" {
1492
+ hostName = pol.Access.HostID
1493
+ }
1494
+ sendClientControl(conn, map[string]any{
1495
+ "type": "welcome",
1496
+ "version": 2,
1497
+ "paired": true,
1498
+ "hostConnected": selectedHostID != "" || h.isHostConnected(pol.Access.HostID),
1499
+ "webId": pol.Access.WebID,
1500
+ "configuredHost": map[string]string{
1501
+ "hostId": pol.Access.HostID,
1502
+ "hostName": hostName,
1503
+ "hostDigest": pol.Access.HostDigest,
1504
+ },
1505
+ "sessionId": sid,
1506
+ "challenge": session.challenge,
1507
+ "user": caller,
1508
+ "hosts": hosts,
1509
+ "selectedHostId": selectedHostID,
1510
+ "error": bindErr,
1511
+ })
1512
+ }
1513
+
1514
+ for {
1515
+ opcode, payload, err := conn.readMessage()
1516
+ if err != nil {
1517
+ return
1518
+ }
1519
+ if opcode != opBinary || len(payload) < 5 {
1520
+ continue
1521
+ }
1522
+ streamID := binary.BigEndian.Uint32(payload[0:4])
1523
+ msgType := payload[4]
1524
+ if streamID == 0 && msgType == msgControlJSON {
1525
+ if len(payload) > 1024 {
1526
+ return
1527
+ }
1528
+ session.mu.Lock()
1529
+ bound := session.host != nil
1530
+ session.mu.Unlock()
1531
+ if !bound {
1532
+ now := time.Now()
1533
+ if now.Sub(session.waitCtrlWindow) >= time.Minute {
1534
+ session.waitCtrlWindow = now
1535
+ session.waitCtrlCount = 0
1536
+ }
1537
+ session.waitCtrlCount++
1538
+ if session.waitCtrlCount > maxWaitingCtrlPerMin {
1539
+ conn.close(1008, "control rate limit exceeded")
1540
+ return
1541
+ }
1542
+ }
1543
+ var cmd struct {
1544
+ Type string `json:"type"`
1545
+ HostID string `json:"hostId"`
1546
+ }
1547
+ if json.Unmarshal(payload[5:], &cmd) != nil {
1548
+ continue
1549
+ }
1550
+ switch cmd.Type {
1551
+ case "list_hosts":
1552
+ curPol, _, pErr := h.syncPolicy()
1553
+ if pErr != nil {
1554
+ continue
1555
+ }
1556
+ sendClientControl(conn, map[string]any{
1557
+ "type": "hosts_list",
1558
+ "paired": curPol.Paired,
1559
+ "hosts": h.listHosts(),
1560
+ })
1561
+ case "select_host":
1562
+ curPol, curEpoch, pErr := h.syncPolicy()
1563
+ if pErr != nil || !curPol.Paired {
1564
+ sendClientControl(conn, map[string]any{
1565
+ "type": "error",
1566
+ "code": "HOST_UNAVAILABLE",
1567
+ "message": "relay is not paired",
1568
+ })
1569
+ continue
1570
+ }
1571
+ target, bErr := h.bindSession(session, strings.TrimSpace(cmd.HostID), curEpoch)
1572
+ if bErr != nil {
1573
+ sendClientControl(conn, map[string]any{
1574
+ "type": "error",
1575
+ "code": "HOST_UNAVAILABLE",
1576
+ "message": bErr.Error(),
1577
+ })
1578
+ } else {
1579
+ sendClientControl(conn, map[string]any{
1580
+ "type": "host_selected",
1581
+ "selectedHostId": target.id,
1582
+ "hostName": target.name,
1583
+ })
1584
+ }
1585
+ }
1586
+ continue
1587
+ }
1588
+
1589
+ session.mu.Lock()
1590
+ host := session.host
1591
+ session.mu.Unlock()
1592
+ if host == nil {
1593
+ sendClientControl(conn, map[string]any{
1594
+ "type": "error",
1595
+ "code": "NO_HOST_BOUND",
1596
+ "message": "no host selected or host offline",
1597
+ })
1598
+ continue
1599
+ }
1600
+
1601
+ if !session.forwardToHost(host, payload) {
1602
+ conn.close(1008, "relay send limit exceeded")
1603
+ return
1604
+ }
1605
+ }
1606
+ }
1607
+
1608
+ func (h *relayHub) handleHealth(w http.ResponseWriter, _ *http.Request) {
1609
+ pol, _, err := h.syncPolicy()
1610
+ w.Header().Set("Content-Type", "application/json")
1611
+ w.Header().Set("Cache-Control", "no-store")
1612
+ if err != nil {
1613
+ w.WriteHeader(http.StatusServiceUnavailable)
1614
+ _ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": "invalid policy"})
1615
+ return
1616
+ }
1617
+ _ = json.NewEncoder(w).Encode(map[string]any{
1618
+ "ok": true,
1619
+ "paired": pol.Paired,
1620
+ })
1621
+ }
1622
+
1623
+ func (h *relayHub) handleStatus(w http.ResponseWriter, r *http.Request) {
1624
+ pol, _, err := h.syncPolicy()
1625
+ w.Header().Set("Content-Type", "application/json")
1626
+ w.Header().Set("Cache-Control", "no-store")
1627
+ if err != nil {
1628
+ w.WriteHeader(http.StatusServiceUnavailable)
1629
+ _ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": "invalid policy"})
1630
+ return
1631
+ }
1632
+ caller, ok := callerFromRequest(r)
1633
+ if !ok || !caller.IsAppOwner() {
1634
+ http.Error(w, "forbidden", http.StatusForbidden)
1635
+ return
1636
+ }
1637
+ if pol.Paired {
1638
+ if caller.UserID != pol.Access.OwnerUserID ||
1639
+ caller.TenantID != pol.Access.OwnerTenantID ||
1640
+ (pol.Access.WebID != "" && caller.WebID != pol.Access.WebID) {
1641
+ http.Error(w, "forbidden", http.StatusForbidden)
1642
+ return
1643
+ }
1644
+ hostName := pol.Access.HostName
1645
+ if hostName == "" {
1646
+ hostName = pol.Access.HostID
1647
+ }
1648
+ _ = json.NewEncoder(w).Encode(map[string]any{
1649
+ "ok": true,
1650
+ "paired": true,
1651
+ "hostConnected": h.isHostConnected(pol.Access.HostID),
1652
+ "hostId": pol.Access.HostID,
1653
+ "hostName": hostName,
1654
+ "hostDigest": pol.Access.HostDigest,
1655
+ "webId": pol.Access.WebID,
1656
+ "updatedAt": pol.Access.UpdatedAt,
1657
+ })
1658
+ return
1659
+ }
1660
+ if pol.Access.WebID != "" && caller.WebID != "" && caller.WebID != pol.Access.WebID {
1661
+ http.Error(w, "forbidden", http.StatusForbidden)
1662
+ return
1663
+ }
1664
+ _ = json.NewEncoder(w).Encode(map[string]any{
1665
+ "ok": true,
1666
+ "paired": false,
1667
+ "hostConnected": false,
1668
+ "webId": caller.WebID,
1669
+ })
1670
+ }
1671
+
1672
+ func newMux(hub *relayHub) *http.ServeMux {
1673
+ mux := http.NewServeMux()
1674
+ mux.HandleFunc("/health", hub.handleHealth)
1675
+ mux.HandleFunc("/healthz", hub.handleHealth)
1676
+ mux.HandleFunc("/status", hub.handleStatus)
1677
+ mux.HandleFunc("/info", hub.handleStatus)
1678
+ mux.HandleFunc("/host", hub.handleHostWS)
1679
+ mux.HandleFunc("/ws/host", hub.handleHostWS)
1680
+ mux.HandleFunc("/client", hub.handleClientWS)
1681
+ mux.HandleFunc("/ws/client", hub.handleClientWS)
1682
+ return mux
1683
+ }
1684
+
1685
+ func main() {
1686
+ port := strings.TrimSpace(os.Getenv("PORT"))
1687
+ if port == "" {
1688
+ port = "8080"
1689
+ }
1690
+ hub := newDynamicRelayHub(
1691
+ strings.TrimSpace(os.Getenv("FUNCTION_CONFIG_FILE")),
1692
+ relayConfigJSON,
1693
+ defaultWebID,
1694
+ )
1695
+ if pol, _, err := hub.syncPolicy(); err != nil {
1696
+ log.Printf("[dsh-remote-relay] warning: initial policy invalid (fail-closed): %v", err)
1697
+ } else if !pol.Paired {
1698
+ log.Printf("[dsh-remote-relay] starting in unpaired standby mode (awaiting DSH_REMOTE_POLICY)")
1699
+ }
1700
+ srv := &http.Server{
1701
+ Addr: ":" + port,
1702
+ Handler: newMux(hub),
1703
+ ReadHeaderTimeout: 10 * time.Second,
1704
+ IdleTimeout: 15 * time.Second,
1705
+ MaxHeaderBytes: 16 * 1024,
1706
+ }
1707
+ log.Printf("[dsh-remote-relay] listening on :%s", port)
1708
+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
1709
+ log.Fatalf("relay server failed: %v", err)
1710
+ }
1711
+ }