Repository navigation
Expand file tree
/
Copy pathrelay-client.ts
More file actions
812 lines (756 loc) · 33.7 KB
/
Copy pathrelay-client.ts
File metadata and controls
812 lines (756 loc) · 33.7 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/**
* The box's half of the blind relay (`docs/relay.md`).
*
* One outbound WebSocket to the relay, held open forever: the relay challenges,
* the box signs with its identity, and from then on every phone that reaches
* the relay under this box's id arrives as a numbered **link** on this one
* socket. Nothing is opened on the box, and the relay never learns a key, a
* path or a byte of a terminal — it forwards frames it cannot read.
*
* Each link is a phone: a hello in the clear naming a device or a pairing
* code, then sealed frames on keys only that phone and this box can derive
* (`shared/src/e2e.ts`). Inside the seal, a link is both a request channel and
* the dashboard stream, and the rest of the server does not know the
* difference: a request becomes an in-process `Request` for the same handler
* the port serves, and the link is registered with the HTTP layer as a
* `StreamClient`, so `session`, `frame`, `log_changed` and the rest reach it
* exactly as they reach a `/ws` socket. A revoked device closes its links the
* same way it closes its sockets.
*
* Logged: connection state and link opens and closes. Never a frame.
*/
import {
BOX_AUTH_PREFIX,
LINK_PREFIX_BYTES,
RELAY_LIMITS,
RELAY_PROTOCOL,
RELAY_RESPONSE_HEADERS,
type BoxHello,
type BoxToPhone,
type BoxToRelay,
type PhoneHello,
type PhoneToBox,
type RelayRequest,
type RelayToBox,
} from "@shahi/shared";
import { PUBLIC_KEY_LEN, ephemeral, open, seal, serverSession, type Session } from "@shahi/shared/e2e";
import { retryDelay } from "../../shared/src/retry";
import { BodyLimitError, boundedBody } from "../../shared/src/bounded-body";
import { SESSION_COOKIE, type Auth } from "./auth";
import { CLOSE_SESSION_EXPIRED, type ShahiServer, type SocketData, type StreamClient } from "./http";
import type { ServerIdentity } from "./identity";
import type { Devices, Pairing } from "./pairing";
export interface RelayClientDeps {
/** `RELAY_URL`: http(s), the Worker's address. */
url: string;
identity: ServerIdentity;
devices: Pick<Devices, "secret" | "revokedSecret">;
pairing: Pick<Pairing, "secretByHash">;
auth: Pick<Auth, "issue">;
server: Pick<ShahiServer, "dispatch" | "attach" | "detach" | "receive">;
log?: (event: string, fields?: Record<string, number | string | boolean>) => void;
}
export interface RelayClientOptions {
/** First retry delay after a drop; doubles to `maxBackoffMs`. */
minBackoffMs?: number;
maxBackoffMs?: number;
/** How long to wait for `ready` before treating the connection as dead. */
authTimeoutMs?: number;
/** Deadline from link open to proof of the pairing/device secret. */
phoneAuthMs?: number;
/**
* How often to send the relay a text `ping` once ready. The Workers runtime
* cannot originate a ping from a Durable Object, so liveness is the box's
* job: the relay answers `pong` without waking, and drops a box silent for
* five minutes. Twenty seconds detects interrupted routes sooner.
*/
pingMs?: number;
/**
* How long the relay may be silent before the box gives up on the socket and
* redials. The pings above are only half of liveness: they prove the box can
* *write*, not that the relay still answers. A half-open or wedged socket —
* the relay gone, a middlebox holding the connection open — leaves the box
* believing it is reachable while no phone can get to it and it never
* redials. So the box watches the read side too, exactly as the phone does
* (`mobile/src/lib/relay.ts`): if nothing arrives (not even the runtime's
* `pong`) within this window, drop the socket and reconnect.
*/
silenceMs?: number;
/** How often to check the read-side silence above. */
watchdogMs?: number;
/** A delayed event-loop tick after sleep forces a fresh connection. */
resumeGapMs?: number;
/** A phone must send authenticated traffic even when only reading a dashboard. */
phoneSilenceMs?: number;
}
/**
* Request headers a phone cannot set through a link. The session is the
* link's own (minted after secret possession is proved, bound to its device), the Origin check is
* satisfied by having no Origin, and the forwarded-for headers would let a
* link choose its rate-limit bucket.
*/
const REQUEST_HEADERS_DROPPED = new Set(["cookie", "origin", "host", "x-forwarded-for", "x-forwarded-host"]);
/**
* The largest response body a `res` can carry inside one relay frame: the
* relay's limit less room for the seal, the JSON around it and base64url's
* expansion. A bigger one — a large file from `/api/file` — is answered 413
* here rather than dropped by the relay with the link.
*/
const MAX_RESPONSE_BODY_BYTES = RELAY_LIMITS.maxBodyBytes;
/**
* How much a link may hold back, unsent, while the phone catches up on
* acknowledgments: every answer its request slots allow, each as large as a
* frame can be, plus one frame of dashboard pushes. A phone that acknowledges
* reaches it only if pushes outrun its connection; one that stops
* acknowledging fills it and loses the link, as it did at the window before.
*/
const MAX_HELD_BYTES = (RELAY_LIMITS.maxRequestsPerLink + 1) * RELAY_LIMITS.maxFrameBytes;
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const b64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64url");
const unb64 = (text: string) => new Uint8Array(Buffer.from(text, "base64url"));
export class RelayClient {
readonly #deps: RelayClientDeps;
readonly #log: NonNullable<RelayClientDeps["log"]>;
#readySince = 0;
#activeRequests = 0;
readonly #minBackoffMs: number;
readonly #maxBackoffMs: number;
readonly #authTimeoutMs: number;
readonly #phoneAuthMs: number;
#ws: WebSocket | null = null;
#ready = false;
#challenged = false;
#stopped = true;
#backoffMs: number;
#reconnectTimer: ReturnType<typeof setTimeout> | undefined;
#authTimer: ReturnType<typeof setTimeout> | undefined;
#pingTimer: ReturnType<typeof setInterval> | undefined;
#watchdogTimer: ReturnType<typeof setInterval> | undefined;
/** When the last frame of any kind — a pong, a phone frame — arrived. */
#lastFrameAt = 0;
#lastTickAt = 0;
readonly #resumeGapMs: number;
readonly #pingMs: number;
readonly #silenceMs: number;
readonly #watchdogMs: number;
readonly #phoneSilenceMs: number;
readonly #links = new Map<number, Link>();
constructor(deps: RelayClientDeps, options: RelayClientOptions = {}) {
this.#deps = deps;
this.#log = deps.log ?? (() => {});
this.#minBackoffMs = options.minBackoffMs ?? 500;
this.#maxBackoffMs = options.maxBackoffMs ?? 30_000;
this.#authTimeoutMs = options.authTimeoutMs ?? RELAY_LIMITS.boxAuthTimeoutMs;
this.#phoneAuthMs = options.phoneAuthMs ?? RELAY_LIMITS.phoneAuthMs;
this.#pingMs = options.pingMs ?? 20_000;
// Three missed pings detect a silently broken route before the relay's
// own five-minute deadline.
this.#silenceMs = options.silenceMs ?? 60_000;
this.#watchdogMs = options.watchdogMs ?? 5_000;
this.#resumeGapMs = options.resumeGapMs ?? Math.max(15_000, this.#watchdogMs * 3);
this.#phoneSilenceMs = options.phoneSilenceMs ?? 150_000;
this.#backoffMs = this.#minBackoffMs;
}
/** Authenticated and holding the socket the relay will send phones on. */
get connected(): boolean {
return this.#ready;
}
start(): void {
if (!this.#stopped) return;
this.#stopped = false;
this.#lastTickAt = Date.now();
this.#watchdogTimer = setInterval(() => this.#checkConnection(), this.#watchdogMs);
this.#connect();
}
stop(): void {
this.#stopped = true;
clearTimeout(this.#reconnectTimer);
this.#reconnectTimer = undefined;
clearInterval(this.#pingTimer);
this.#pingTimer = undefined;
clearInterval(this.#watchdogTimer);
this.#watchdogTimer = undefined;
clearTimeout(this.#authTimer); this.#authTimer = undefined;
this.#releaseAll();
if (this.#ws) this.#disconnect(this.#ws, 1001);
this.#ready = false;
}
#connect(): void {
if (this.#stopped) return;
this.#reconnectTimer = undefined;
let ws: WebSocket;
try { ws = new WebSocket(boxUrl(this.#deps.url, this.#deps.identity.serverId)); }
catch { this.#scheduleRetry(1006, false); return; }
ws.binaryType = "arraybuffer";
this.#ws = ws;
this.#ready = false;
this.#challenged = false;
// The relay closes an unauthenticated box after ten seconds; this is the
// same limit from our side, for a relay that accepted the socket and then
// said nothing — a half-open connection would otherwise look like a
// healthy one forever.
this.#authTimer = setTimeout(() => {
if (this.#ws === ws && !this.#ready) {
this.#log("relay.auth_timeout");
this.#disconnect(ws, 4000);
}
}, this.#authTimeoutMs);
ws.onmessage = (event) => {
if (this.#ws !== ws) return;
// Any frame is proof the relay is still answering: a phone frame, or the
// runtime's own `pong` (text that is not JSON, dropped below but counted
// here). This is the read-side liveness the watchdog reads.
this.#lastFrameAt = Date.now();
try {
if (typeof event.data === "string") this.#control(ws, event.data);
else if (this.#ready && event.data instanceof ArrayBuffer && event.data.byteLength <= RELAY_LIMITS.maxFrameBytes + LINK_PREFIX_BYTES) {
this.#frame(new Uint8Array(event.data));
} else this.#disconnect(ws, 1002);
} catch {
// A hostile relay must not turn a malformed control or a send race
// into a process-wide failure of the local HTTP/SSH access path.
this.#disconnect(ws, 1002);
}
};
ws.onerror = () => this.#disconnect(ws, 1006);
ws.onclose = (event) => this.#disconnect(ws, event.code);
}
#disconnect(ws: WebSocket, code: number, immediate = false): void {
if (this.#ws !== ws) return;
clearTimeout(this.#authTimer); this.#authTimer = undefined;
clearInterval(this.#pingTimer); this.#pingTimer = undefined;
const wasReady = this.#ready;
this.#ws = null; this.#ready = false;
ws.onopen = null; ws.onmessage = null; ws.onerror = null; ws.onclose = null;
this.#releaseAll();
try { ws.close(); } catch { /* Redial even when the old socket cannot close. */ }
this.#scheduleRetry(code, wasReady, immediate);
}
#scheduleRetry(code: number, wasReady: boolean, immediate = false): void {
if (this.#stopped || this.#reconnectTimer) return;
if (wasReady && Date.now() - this.#readySince >= 30_000) this.#backoffMs = this.#minBackoffMs;
const delay = immediate ? 0 : retryDelay(this.#backoffMs);
this.#log("relay.retry", { code, retryMs: delay, connected: wasReady });
this.#reconnectTimer = setTimeout(() => this.#connect(), delay);
this.#backoffMs = Math.min(this.#backoffMs * 2, this.#maxBackoffMs);
}
#checkConnection(): void {
if (this.#stopped) return;
const now = Date.now();
const gap = now - this.#lastTickAt;
this.#lastTickAt = now;
// Timers pause during sleep. Incoming buffered frames may run before this
// tick, so lastFrameAt alone cannot establish that the old route is alive.
// Keep this timer running during handshakes and retry waits as well.
if (gap > this.#resumeGapMs || gap < 0) {
this.#log("relay.resumed");
clearTimeout(this.#reconnectTimer); this.#reconnectTimer = undefined;
this.#backoffMs = this.#minBackoffMs;
if (this.#ws) this.#disconnect(this.#ws, 4000, true);
else this.#connect();
return;
}
const ws = this.#ws;
if (!ws || !this.#ready) return;
if (ws.readyState !== WebSocket.OPEN) { this.#disconnect(ws, 1006); return; }
for (const link of this.#links.values()) link.checkAlive(this.#phoneSilenceMs);
if (now - this.#lastFrameAt < this.#silenceMs) return;
this.#log("relay.silent");
this.#disconnect(ws, 4000);
}
#control(ws: WebSocket, text: string): void {
if (text === "pong" && this.#ready) return;
const msg = parseControl(text);
if (!msg || (msg.t !== "challenge" && msg.t !== "ready" && !this.#ready)) {
this.#disconnect(ws, 1002);
return;
}
switch (msg.t) {
case "challenge": {
if (this.#challenged || this.#ready) { this.#disconnect(ws, 1002); return; }
this.#challenged = true;
const { identity } = this.#deps;
const signed = encoder.encode(BOX_AUTH_PREFIX + identity.serverId + msg.nonce);
// `proofs`: this box reports each link that proves itself (see
// `Wire.proven`). A relay that predates it ignores the field.
const auth: BoxToRelay = { t: "auth", pub: b64(identity.publicKey), sig: b64(identity.sign(signed)), proofs: true };
ws.send(JSON.stringify(auth));
return;
}
case "ready":
if (!this.#challenged || this.#ready) { this.#disconnect(ws, 1002); return; }
clearTimeout(this.#authTimer); this.#authTimer = undefined;
this.#ready = true;
this.#readySince = Date.now();
this.#lastFrameAt = Date.now();
this.#log("relay.connected");
clearInterval(this.#pingTimer);
this.#pingTimer = setInterval(() => {
if (this.#ws !== ws) return;
if (ws.readyState !== WebSocket.OPEN) { this.#disconnect(ws, 1006); return; }
try { ws.send("ping"); } catch { this.#disconnect(ws, 1006); }
}, this.#pingMs);
return;
case "open":
// A relay reusing a number still held here is a relay that lost track;
// whatever that link was, it is gone.
this.#links.get(msg.link)?.release();
// The relay enforces maxPhonesPerBox, so more open links than that means
// a relay that has lost track or a hostile one trying to grow this map
// without bound and take the sidecar down with it (pentest L4). Refuse
// the surplus rather than trust the far end's count.
if (!this.#links.has(msg.link) && this.#links.size >= RELAY_LIMITS.maxPhonesPerBox) {
this.#log("relay.link_refused", { links: this.#links.size });
const message: BoxToRelay = { t: "close", link: msg.link };
if (this.#ws && this.#ready) this.#ws.send(JSON.stringify(message));
return;
}
this.#links.set(msg.link, new Link(msg.link, this.#wire, this.#deps, this.#log, this.#phoneAuthMs));
this.#log("relay.link_open", { links: this.#links.size });
return;
case "close":
this.#links.get(msg.link)?.release();
this.#links.delete(msg.link);
this.#log("relay.link_closed", { links: this.#links.size });
return;
}
}
#frame(bytes: Uint8Array): void {
if (bytes.length < LINK_PREFIX_BYTES) return;
const link = new DataView(bytes.buffer, bytes.byteOffset, LINK_PREFIX_BYTES).getUint32(0, false);
this.#links.get(link)?.receive(bytes.subarray(LINK_PREFIX_BYTES));
}
/** What a link can do to the socket: send a frame on its number, or end itself. */
readonly #wire: Wire = {
acquire: () => {
if (this.#activeRequests >= RELAY_LIMITS.maxRequestsPerBox) return false;
this.#activeRequests++;
return true;
},
release: () => { this.#activeRequests--; },
send: (link, payload) => {
const ws = this.#ws;
if (!ws || !this.#ready || ws.readyState !== WebSocket.OPEN) return;
if (payload.length > RELAY_LIMITS.maxFrameBytes || ws.bufferedAmount + payload.length > RELAY_LIMITS.maxSocketBufferedBytes) {
this.#links.get(link)?.end("backpressure");
return;
}
const frame = new Uint8Array(LINK_PREFIX_BYTES + payload.length);
new DataView(frame.buffer).setUint32(0, link, false);
frame.set(payload, LINK_PREFIX_BYTES);
try { ws.send(frame); }
catch { this.#disconnect(ws, 1006); }
},
end: (link) => {
this.#links.delete(link);
this.#tell({ t: "close", link });
},
proven: (link) => this.#tell({ t: "proven", link }),
};
#tell(message: BoxToRelay): void {
const ws = this.#ws;
if (ws?.readyState === WebSocket.OPEN && this.#ready) {
try { ws.send(JSON.stringify(message)); } catch { this.#disconnect(ws, 1006); }
}
}
#releaseAll(): void {
for (const link of this.#links.values()) link.release();
this.#links.clear();
}
}
interface Wire {
acquire(): boolean;
release(): void;
send(link: number, payload: Uint8Array): void;
end(link: number): void;
/**
* Tells the relay this link holds the secret its hello named. Only the box
* can know that, and without it the relay could not tell the owner's phone
* from someone who knows a device id but not its secret: such a hello kept
* its slot until the proof deadline ended it, and eight of them kept the
* owner's phones out (review 2026-09-22, F33). With it, a full relay makes
* room by closing a link that has not proven itself.
*/
proven(link: number): void;
}
/**
* One phone, from the relay's `open` to its `close`.
*
* Implements `StreamClient` so the HTTP layer pushes to it and closes it as it
* would a socket: `send` seals the push as `{"t":"ws","data":…}`, `close`
* ends the link. `data` is the same record a socket carries — the device
* behind it (so revoking closes it) and the token the heartbeat re-verifies.
*/
class Link implements StreamClient {
readonly data: SocketData = { deviceId: null, watchedPaneId: null, releaseWatch: null, releaseLog: null, token: undefined };
#session: Session | null = null;
#activeRequests = 0;
#unacknowledgedBytes = 0;
/**
* Frames waiting for acknowledgments to free the window, in order. They are
* held unsealed and sealed only as they leave, so counters stay in sequence
* and dropping them on release skips none.
*/
readonly #held: { plain: Uint8Array; bytes: number; sent: () => void }[] = [];
#heldBytes = 0;
#kind: PhoneHello["auth"]["kind"] | null = null;
#rateKey = "";
#attached = false;
#released = false;
#helloAuth: PhoneHello["auth"] | null = null;
#confirmed = false;
#lastReceivedAt = Date.now();
readonly #authTimer: ReturnType<typeof setTimeout>;
constructor(
readonly id: number,
private readonly wire: Wire,
private readonly deps: RelayClientDeps,
private readonly log: NonNullable<RelayClientDeps["log"]>,
authMs: number,
) {
this.#authTimer = setTimeout(() => this.end("authentication timeout"), authMs);
}
receive(payload: Uint8Array): void {
if (this.#released) return;
if (!this.#session) {
this.#hello(payload);
return;
}
let plain: Uint8Array;
try {
plain = open(this.#session, payload);
} catch {
// The other side does not hold the secret, or is replaying. Either way
// this link cannot continue; closing it is the signal (`4403` is what
// the relay would say, but from the box the close is the message).
this.end("a frame did not open");
return;
}
let msg: PhoneToBox;
try {
msg = JSON.parse(decoder.decode(plain));
} catch {
this.end("a frame was not JSON");
return;
}
if (!msg || typeof msg !== "object" || Array.isArray(msg) || (msg.t !== "req" && msg.t !== "ws" && msg.t !== "ack")) {
this.end("a malformed message");
return;
}
this.#lastReceivedAt = Date.now();
if (msg.t === "ack") {
if (!this.#confirmed || !Number.isSafeInteger(msg.bytes) || msg.bytes <= 0 || msg.bytes > this.#unacknowledgedBytes) {
this.end("invalid acknowledgement");
return;
}
this.#unacknowledgedBytes -= msg.bytes;
this.#flush();
return;
}
if (!this.#confirmed) {
// Deriving a key is not proof the caller holds it. Only a valid sealed
// frame earns a session. Recheck revocation after the hello/claim race.
const auth = this.#helloAuth!;
if (auth.kind === "device") {
// Revoked between the hello and this frame. Rows are never deleted,
// so a device that is no longer active was revoked: say so.
if (!this.deps.devices.secret(auth.deviceId)) { this.#dismiss("device revoked"); return; }
this.data.deviceId = auth.deviceId;
this.data.token = this.deps.auth.issue(Date.now(), auth.deviceId);
this.deps.server.attach(this);
this.#attached = true;
}
this.#confirmed = true;
clearTimeout(this.#authTimer);
this.wire.proven(this.id);
}
if (msg.t === "req") {
// Not awaited: requests on a link are concurrent and answered by id.
void this.#request(msg);
} else if (msg.t === "ws" && this.#attached) {
this.deps.server.receive(this, msg.data);
}
}
checkAlive(silenceMs: number): void {
if (this.#confirmed && !this.#released && Date.now() - this.#lastReceivedAt >= silenceMs) this.end("phone silent");
}
#hello(payload: Uint8Array): void {
if (payload.byteLength > RELAY_LIMITS.maxControlBytes) { this.end("an oversized hello"); return; }
const hello = parseHello(payload);
if (!hello) {
try {
const version = JSON.parse(decoder.decode(payload))?.v;
if (Number.isSafeInteger(version) && version !== RELAY_PROTOCOL) this.log("relay.protocol_mismatch", { code: version });
} catch {}
this.end("a malformed hello");
return;
}
// The secret never travels: the hello names it, and only a box that has
// it can derive the keys the phone is about to use.
let secret: Uint8Array | null;
let revoked = false;
if (hello.auth.kind === "device") {
secret = this.deps.devices.secret(hello.auth.deviceId);
// A phone revoked while its link was down (an app in the background)
// used to be ended here like a stranger. The relay turns that into a
// routine 1000, which a paired phone must retry, so it reconnected
// forever and never learned it was unpaired (September 2026
// pre-release review). The revoked row's secret keys one sealed `bye`,
// which the relay cannot forge, and is used for nothing else.
if (!secret) {
secret = this.deps.devices.revokedSecret(hello.auth.deviceId);
revoked = secret !== null;
}
} else {
secret = this.deps.pairing.secretByHash(hello.auth.id);
}
if (!secret) {
this.end(hello.auth.kind === "device" ? "unknown device" : "unknown pairing code");
return;
}
// A hello whose public key is a low-order point makes noble throw, which
// is the right refusal — but uncaught inside `ws.onmessage` it was the
// whole sidecar exiting, resendable on every reconnect by anyone who
// knows a serverId and a device id (2026-09-02 review, R1). It ends the
// link, like every other bad frame.
const self = ephemeral(crypto.getRandomValues(new Uint8Array(32)));
try {
this.#session = serverSession(self, unb64(hello.pub), secret);
} catch {
this.end("a hello did not derive");
return;
}
this.#kind = hello.auth.kind;
this.#helloAuth = hello.auth;
const answer: BoxHello = { t: "hello", v: RELAY_PROTOCOL, pub: b64(self.pub) };
this.wire.send(this.id, encoder.encode(JSON.stringify(answer)));
if (revoked) {
this.#dismiss("device revoked");
return;
}
if (hello.auth.kind === "device") {
this.#rateKey = `relay:${hello.auth.deviceId}`;
} else {
// A pairing link gets no session and no stream: it may claim, and that
// is all, until it comes back as the device the claim made.
this.#rateKey = `relay:pair:${hello.auth.id}`;
}
}
async #request(req: RelayRequest): Promise<void> {
// Shape before meaning: a sealed frame is from a phone that holds the
// secret, but a `path` that is not a string still used to throw out of
// `onmessage` and take the process with it (R1's second trigger).
if (typeof req.path !== "string" || typeof req.method !== "string" || typeof req.id !== "number") {
this.end("a request without a path");
return;
}
// A pairing link may look at `/api/meta` (unauthenticated over HTTP too:
// the phone checks the serverId in the code against the box it reached
// before it hands over the secret) and claim. Nothing else.
const allowed =
(req.method === "GET" && req.path.split("?")[0] === "/api/meta") ||
(req.method === "POST" && req.path === "/api/pair/claim");
if (this.#kind === "pairing" && !allowed) {
this.#answer(req.id, jsonResponse(403, { error: "a pairing link may only read /api/meta and claim its code" }));
return;
}
let request: Request;
try {
request = buildRequest(req, this.data.token);
} catch {
this.#answer(req.id, jsonResponse(400, { error: "malformed request" }));
return;
}
if (this.#activeRequests >= RELAY_LIMITS.maxRequestsPerLink || !this.wire.acquire()) {
this.log("relay.request_rejected");
await this.#answer(req.id, jsonResponse(429, { error: "this box is busy; try again shortly" }));
return;
}
this.#activeRequests++;
let response: Response;
try {
response = await this.deps.server.dispatch(request, this.#rateKey);
} catch {
response = jsonResponse(500, { error: "internal error" });
}
try { await this.#answer(req.id, response); }
finally { this.#activeRequests--; this.wire.release(); }
}
async #answer(id: number, response: Response): Promise<void> {
try {
if (this.#released) { await response.body?.cancel(); return; }
let body: Uint8Array;
let { status } = response;
try { body = await boundedBody(response, MAX_RESPONSE_BODY_BYTES); }
catch (error) {
if (!(error instanceof BodyLimitError)) throw error;
this.log("relay.response_oversized");
status = 413;
body = encoder.encode(JSON.stringify({ error: "too large to send through the relay" }));
}
const headers: Record<string, string> = {};
for (const name of RELAY_RESPONSE_HEADERS) {
const value = response.headers.get(name);
if (value !== null) headers[name] = value;
}
if (status === 413) headers["content-type"] = "application/json";
const res: BoxToPhone = { t: "res", id, status, headers, body: body.length > 0 ? b64(body) : null };
// The request keeps its slot until its answer has left: excess work is
// still refused with 429, never piled up behind a slow phone.
await this.#sendSealed(JSON.stringify(res));
} catch { this.end("response failed"); }
}
/* ------------------------------------------------------- StreamClient */
send(payload: string): void {
// `payload` is one JSON object, already serialised by the broadcaster;
// wrapping it as text avoids parsing it only to stringify it again.
void this.#sendSealed(`{"t":"ws","data":${payload}}`);
}
close(code: number, reason: string): void {
// The HTTP layer closes a `StreamClient` with 4001 when its session no
// longer verifies — the device was revoked in Settings, or the session
// expired. On a `/ws` socket that code reaches the phone and signs it out;
// through the relay it cannot, because a box-driven close is flattened to
// 1000 (a routine drop the phone retries). Without this a revoked phone
// reconnected on a backoff loop forever — cut off, but never told to sign
// out. So the terminal reason travels as a sealed `bye` the phone acts on,
// sent before the link ends.
//
// The same code also means only that this link's own token stopped
// verifying (the heartbeat's expiry check) while the device is still
// paired. A `bye` there erased a valid pairing; the phone needs nothing
// but a new link, which mints a new token. So the `bye` goes only to a
// device this box no longer has as paired (September 2026 review).
const paired = this.data.deviceId !== null && this.deps.devices.secret(this.data.deviceId) !== null;
if (code === CLOSE_SESSION_EXPIRED && !paired) this.#dismiss(reason);
else this.end(reason);
}
/**
* Tells the phone, in a sealed frame it can trust, that it is no longer
* paired; then ends the link. Anything still held for it is dropped rather
* than delivered after the fact, and the bye goes out ahead of the window:
* it is a few bytes and the last frame this link will carry.
*/
#dismiss(reason: string): void {
if (!this.#released && this.#session) {
this.#dropHeld();
this.wire.send(this.id, seal(this.#session, encoder.encode(`{"t":"bye"}`)));
}
this.end(reason);
}
/* ---------------------------------------------------------- lifecycle */
/** Ends the link from this side: tells the relay, releases what it held. */
end(reason: string): void {
if (this.#released) return;
this.log("relay.link_closed", { reason });
this.wire.end(this.id);
this.release();
}
/** The link is gone (the relay said so, or the socket dropped): let go of everything it held. */
release(): void {
if (this.#released) return;
this.#released = true;
clearTimeout(this.#authTimer);
this.#session = null;
this.#dropHeld();
if (this.#attached) {
this.#attached = false;
this.deps.server.detach(this);
}
}
/**
* Sends a sealed frame, or holds it until the phone has acknowledged enough
* of what it was already sent. Resolves once the frame has left, or the
* link has gone.
*
* A frame that would overrun the 2 MiB window used to end the link on the
* spot. But a link may run four requests and each answer may be close to a
* full 1 MiB frame, while acknowledgments need a round trip through the
* relay. So three large screenshots answered together cost the phone its
* link and every request on it, including an uncertain prompt send (found by
* the September 2026 pre-release review). The window still bounds what the
* relay has to buffer for this phone. Only a phone that stops acknowledging
* altogether loses the link, once MAX_HELD_BYTES is full.
*/
#sendSealed(text: string): Promise<void> {
return new Promise((sent) => {
if (this.#released || !this.#session) { sent(); return; }
// Check before sealing: dropping a sealed frame would skip a crypto counter.
if (text.length > RELAY_LIMITS.maxFrameBytes) { sent(); this.end("frame too large"); return; }
const plain = encoder.encode(text);
const bytes = plain.byteLength + 24;
if (bytes > RELAY_LIMITS.maxFrameBytes) { sent(); this.end("frame too large"); return; }
if (this.#heldBytes + bytes > MAX_HELD_BYTES) { sent(); this.end("backpressure"); return; }
this.#held.push({ plain, bytes, sent });
this.#heldBytes += bytes;
this.#flush();
});
}
/** Sends held frames, in order, while the window has room for the next. */
#flush(): void {
while (this.#held.length > 0 && !this.#released && this.#session) {
const next = this.#held[0]!;
if (this.#unacknowledgedBytes + next.bytes > RELAY_LIMITS.maxUnacknowledgedBytes) return;
this.#held.shift();
this.#heldBytes -= next.bytes;
this.#unacknowledgedBytes += next.bytes;
this.wire.send(this.id, seal(this.#session, next.plain));
next.sent();
}
}
#dropHeld(): void {
for (const frame of this.#held.splice(0)) frame.sent();
this.#heldBytes = 0;
}
}
/* -------------------------------------------------------------------------- */
function parseControl(text: string): RelayToBox | null {
if (text.length > RELAY_LIMITS.maxControlBytes) return null;
try {
const msg: unknown = JSON.parse(text);
if (!msg || typeof msg !== "object" || Array.isArray(msg)) return null;
const m = msg as Record<string, unknown>;
if (m.t === "challenge" && typeof m.nonce === "string" && /^[A-Za-z0-9_-]{43}$/.test(m.nonce)) return m as RelayToBox;
if (m.t === "ready") return { t: "ready" };
if ((m.t === "open" || m.t === "close") && typeof m.link === "number" && Number.isInteger(m.link) && m.link > 0 && m.link <= 0xffffffff) return m as RelayToBox;
} catch { /* Invalid JSON is a protocol error, just like invalid fields. */ }
return null;
}
/** `${RELAY_URL}/v1/box/${serverId}`, over ws(s). */
export function boxUrl(relayUrl: string, serverId: string): string {
const base = relayUrl.replace(/^http/, "ws").replace(/\/+$/, "");
return `${base}/v1/box/${serverId}`;
}
/** The hello, or null for anything that is not one — a malformed first frame is never guessed at. */
function parseHello(payload: Uint8Array): PhoneHello | null {
let value: unknown;
try {
value = JSON.parse(decoder.decode(payload));
} catch {
return null;
}
if (typeof value !== "object" || value === null) return null;
const hello = value as Partial<PhoneHello>;
if (hello.t !== "hello" || hello.v !== RELAY_PROTOCOL || typeof hello.pub !== "string") return null;
if (unb64(hello.pub).length !== PUBLIC_KEY_LEN) return null;
const auth = hello.auth as Partial<PhoneHello["auth"]> | undefined;
if (typeof auth !== "object" || auth === null) return null;
if (auth.kind === "device" && typeof auth.deviceId === "string" && auth.deviceId !== "") return hello as PhoneHello;
if (auth.kind === "pairing" && typeof auth.id === "string" && auth.id !== "") return hello as PhoneHello;
return null;
}
/** The in-process request a `req` becomes. Throws for anything `Request` refuses. */
function buildRequest(req: RelayRequest, token: string | undefined): Request {
if (typeof req.path !== "string" || !req.path.startsWith("/")) throw new Error("path");
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers ?? {})) {
if (typeof value === "string" && !REQUEST_HEADERS_DROPPED.has(name.toLowerCase())) headers.set(name, value);
}
if (token) headers.set("cookie", `${SESSION_COOKIE}=${token}`);
const body = typeof req.body === "string" ? unb64(req.body) : null;
return new Request(`http://relay.local${req.path}`, { method: req.method, headers, body });
}
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}