Repository navigation
Expand file tree
/
Copy pathloopback.test.js
More file actions
3407 lines (3196 loc) · 144 KB
/
Copy pathloopback.test.js
File metadata and controls
3407 lines (3196 loc) · 144 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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
SyncAuthenticationError,
SyncBridgeClient,
SyncPairingDeniedError,
SyncUnavailableError,
} from "../../browser/client.js";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const DEFAULT_SYNCD = path.join(ROOT, "build", "syncd");
function resolveDaemonPath(value = process.env.SYNC_DAEMON_PATH) {
if (value === undefined || value.length === 0) return DEFAULT_SYNCD;
return path.isAbsolute(value) ? value : path.resolve(ROOT, value);
}
const SYNCD = resolveDaemonPath();
const PAIRING_TEST_SERVER = path.join(path.dirname(SYNCD), "sync_pairing_test_server");
const AUDIO_TEST_SERVER = path.join(
path.dirname(SYNCD),
`sync_audio_test_server${path.extname(SYNCD).toLowerCase() === ".exe" ? ".exe" : ""}`,
);
const SYPHON_PROBE = path.join(path.dirname(SYNCD), "sync_syphon_discovery_probe");
const FIXTURE = path.join(ROOT, "test", "fixtures", "frame-v1.bin");
const ORIGIN = "https://client.example";
const POLYMORPHIC_ORIGIN = "app://polymorphic";
const VISUALIZE_ORIGIN = "app://visualize";
const TOKEN = "test-token-123";
const TIMEOUT_MS = 3_000;
// Pairing answers can legitimately take longer than everything else here: the
// deliberate timeout cases only answer once the daemon's prompt deadline
// fires, and that deadline bounds a real store commit. Kept well clear of
// sync_pairing_test_server's SYNC_PAIRING_PROMPT_DEADLINE_MS (CMakeLists.txt)
// so the client never times out first and reports the wrong failure.
const PAIRING_TIMEOUT_MS = 10_000;
const EXPECTED_PRODUCT_VERSION = process.env.SYNC_VERSION ?? "0.2.0";
// The providers a daemon configures when no --publisher is named. NDI is on
// both platforms because its send path takes a CPU frame and needs no
// platform-specific GPU layer; Syphon and Spout are each platform-bound.
// Naming no publisher selects every provider the platform implements. Both
// Every platform offers a camera publisher, but the GPU-sharing providers are
// native to their respective desktop OSes. Linux exposes camera and NDI only.
const DEFAULT_PROVIDER_IDS = process.platform === "win32"
? ["spout", "ndi", "camera", "audio"]
: process.platform === "darwin"
? ["syphon", "ndi", "camera", "audio"]
: ["ndi", "camera", "audio"];
function withTimeout(promise, description, timeoutMs = TIMEOUT_MS) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${description}`)), timeoutMs);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
function onceEvent(emitter, successEvent, errorEvents = ["error"]) {
return new Promise((resolve, reject) => {
const cleanups = [];
const cleanup = () => {
for (const [event, listener] of cleanups) emitter.off(event, listener);
};
const success = (...args) => {
cleanup();
resolve(args);
};
emitter.once(successEvent, success);
cleanups.push([successEvent, success]);
for (const event of errorEvents) {
const failure = (error) => {
cleanup();
reject(error instanceof Error ? error : new Error(String(error)));
};
emitter.once(event, failure);
cleanups.push([event, failure]);
}
});
}
async function connect(host, port) {
const socket = net.createConnection({ host, port });
try {
await withTimeout(onceEvent(socket, "connect"), `TCP connection to ${host}`);
return socket;
} catch (error) {
socket.destroy();
throw error;
}
}
async function readHttpResponse(socket) {
let bytes = Buffer.alloc(0);
for await (const chunk of socket) {
bytes = Buffer.concat([bytes, chunk]);
if (bytes.length > 65_536) throw new Error("HTTP response exceeded test bound");
}
const marker = bytes.indexOf("\r\n\r\n");
assert.notEqual(marker, -1, "HTTP response terminates its headers");
const headerText = bytes.subarray(0, marker).toString("ascii");
const body = bytes.subarray(marker + 4);
const lines = headerText.split("\r\n");
const status = Number(lines[0].split(" ")[1]);
const headers = new Map();
for (const line of lines.slice(1)) {
const colon = line.indexOf(":");
assert.ok(colon > 0, `valid response header: ${line}`);
headers.set(line.slice(0, colon).toLowerCase(), line.slice(colon + 1).trim());
}
return { status, headers, body };
}
async function health(host, port, origin) {
const socket = await connect(host, port);
try {
const hostHeader = host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
const originHeader = origin === undefined ? "" : `Origin: ${origin}\r\n`;
socket.end(`GET /health HTTP/1.1\r\nHost: ${hostHeader}\r\n${originHeader}Connection: close\r\n\r\n`);
return await withTimeout(readHttpResponse(socket), `health response from ${host}`);
} catch (error) {
socket.destroy();
throw error;
}
}
function healthFetchForOrigin(origin) {
return async (url, options) => {
const requestUrl = new URL(url);
assert.equal(requestUrl.protocol, "http:");
assert.equal(requestUrl.pathname, "/health");
assert.equal(options.method, "GET");
assert.equal(options.credentials, "omit");
assert.equal(options.targetAddressSpace, "loopback");
const response = await health(
requestUrl.hostname,
Number(requestUrl.port),
origin,
);
assert.equal(response.headers.get("access-control-allow-origin"), origin);
return new Response(response.body, {
status: response.status,
headers: Object.fromEntries(response.headers),
});
};
}
async function status(host, port, origin) {
const socket = await connect(host, port);
try {
const hostHeader = host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
const originHeader = origin === undefined ? "" : `Origin: ${origin}\r\n`;
socket.end(`GET /status HTTP/1.1\r\nHost: ${hostHeader}\r\n${originHeader}Connection: close\r\n\r\n`);
return await withTimeout(readHttpResponse(socket), `status response from ${host}`);
} catch (error) {
socket.destroy();
throw error;
}
}
async function preflight(host, port, origin, requestPrivateNetwork = false) {
const socket = await connect(host, port);
try {
const hostHeader = host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
const privateNetworkHeader = requestPrivateNetwork
? "Access-Control-Request-Private-Network: true\r\n"
: "";
socket.end(
`OPTIONS /health HTTP/1.1\r\nHost: ${hostHeader}\r\n` +
`Origin: ${origin}\r\nAccess-Control-Request-Method: GET\r\n` +
privateNetworkHeader +
"Connection: close\r\n\r\n",
);
return await withTimeout(readHttpResponse(socket), `health preflight from ${host}`);
} catch (error) {
socket.destroy();
throw error;
}
}
function parseHeaderBlock(headerBytes) {
const lines = headerBytes.toString("ascii").split("\r\n");
const status = Number(lines[0].split(" ")[1]);
const headers = new Map();
for (const line of lines.slice(1)) {
const colon = line.indexOf(":");
assert.ok(colon > 0, `valid upgrade response header: ${line}`);
headers.set(line.slice(0, colon).toLowerCase(), line.slice(colon + 1).trim());
}
return { status, headers };
}
async function upgrade({
host = "127.0.0.1",
port,
route,
origin,
subprotocol,
socket: suppliedSocket,
pipelined,
}) {
const socket = suppliedSocket ?? await connect(host, port);
try {
const key = randomBytes(16).toString("base64");
const hostHeader = host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
const protocolHeader = subprotocol === undefined
? ""
: `Sec-WebSocket-Protocol: ${subprotocol}\r\n`;
const head = Buffer.from(
`GET ${route} HTTP/1.1\r\n` +
`Host: ${hostHeader}\r\n` +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
`Origin: ${origin}\r\n` +
"Sec-WebSocket-Version: 13\r\n" +
`Sec-WebSocket-Key: ${key}\r\n` +
protocolHeader +
"\r\n",
);
// `pipelined` lands in the same write as the handshake so the daemon reads
// request head and WebSocket payload together.
socket.write(pipelined === undefined ? head : Buffer.concat([head, pipelined]));
const chunks = [];
let total = 0;
let marker = -1;
while (marker < 0) {
const [chunk] = await withTimeout(
onceEvent(socket, "data", ["error", "close"]), "upgrade response",
);
chunks.push(chunk);
total += chunk.length;
assert.ok(total <= 65_536, "upgrade response stays bounded");
marker = Buffer.concat(chunks, total).indexOf("\r\n\r\n");
}
const bytes = Buffer.concat(chunks, total);
const parsed = parseHeaderBlock(bytes.subarray(0, marker));
const remainder = bytes.subarray(marker + 4);
if (parsed.status === 101) {
const expectedAccept = createHash("sha1")
.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
.digest("base64");
assert.equal(parsed.headers.get("sec-websocket-accept"), expectedAccept);
return { ...parsed, socket, client: new WebSocketClient(socket, remainder) };
}
socket.destroy();
return { ...parsed, socket, client: null };
} catch (error) {
socket.destroy();
throw error;
}
}
function maskedClientFrame(opcode, payload = Buffer.alloc(0)) {
payload = Buffer.from(payload);
const mask = randomBytes(4);
let header;
if (payload.length <= 125) {
header = Buffer.from([0x80 | opcode, 0x80 | payload.length]);
} else if (payload.length <= 0xffff) {
header = Buffer.alloc(4);
header[0] = 0x80 | opcode;
header[1] = 0x80 | 126;
header.writeUInt16BE(payload.length, 2);
} else {
header = Buffer.alloc(10);
header[0] = 0x80 | opcode;
header[1] = 0x80 | 127;
header.writeBigUInt64BE(BigInt(payload.length), 2);
}
const masked = Buffer.alloc(payload.length);
for (let index = 0; index < payload.length; index += 1) {
masked[index] = payload[index] ^ mask[index % mask.length];
}
return Buffer.concat([header, mask, masked]);
}
function maskedClientFrameHeader(opcode, payloadBytes, final = true) {
const first = Buffer.from([(final ? 0x80 : 0) | opcode]);
let length;
if (payloadBytes <= 125) {
length = Buffer.from([0x80 | payloadBytes]);
} else if (payloadBytes <= 65_535) {
length = Buffer.alloc(3);
length[0] = 0xfe;
length.writeUInt16BE(payloadBytes, 1);
} else {
length = Buffer.alloc(9);
length[0] = 0xff;
length.writeBigUInt64BE(BigInt(payloadBytes), 1);
}
return Buffer.concat([
first,
length,
Buffer.from([0x11, 0x22, 0x33, 0x44]),
]);
}
class WebSocketClient {
constructor(socket, initialBytes) {
this.socket = socket;
this.buffer = Buffer.from(initialBytes);
this.frames = [];
this.waiters = [];
this.closed = socket.destroyed;
socket.on("data", (chunk) => {
this.buffer = Buffer.concat([this.buffer, chunk]);
this.#decode();
});
socket.on("close", () => {
this.closed = true;
for (const waiter of this.waiters.splice(0)) waiter.reject(new Error("WebSocket closed"));
});
this.#decode();
}
#decode() {
while (this.buffer.length >= 2) {
const first = this.buffer[0];
const second = this.buffer[1];
assert.equal(first & 0x70, 0, "server frame has no reserved bits");
assert.equal(second & 0x80, 0, "server frame is unmasked");
let length = second & 0x7f;
let headerBytes = 2;
if (length === 126) {
if (this.buffer.length < 4) return;
length = this.buffer.readUInt16BE(2);
headerBytes = 4;
} else if (length === 127) {
if (this.buffer.length < 10) return;
const wide = this.buffer.readBigUInt64BE(2);
assert.ok(wide <= BigInt(Number.MAX_SAFE_INTEGER));
length = Number(wide);
headerBytes = 10;
}
if (this.buffer.length < headerBytes + length) return;
const frame = {
final: (first & 0x80) !== 0,
opcode: first & 0x0f,
payload: Buffer.from(this.buffer.subarray(headerBytes, headerBytes + length)),
};
this.buffer = this.buffer.subarray(headerBytes + length);
const waiter = this.waiters.shift();
if (waiter) waiter.resolve(frame);
else this.frames.push(frame);
}
}
send(opcode, payload) {
assert.equal(this.closed, false, "cannot send after close");
this.socket.write(maskedClientFrame(opcode, payload));
}
sendJson(value) {
this.send(0x1, Buffer.from(JSON.stringify(value), "utf8"));
}
async nextFrame(description = "WebSocket frame", timeoutMs = TIMEOUT_MS) {
if (this.frames.length > 0) return this.frames.shift();
const promise = new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
return withTimeout(promise, description, timeoutMs);
}
async nextJson(description = "control response", timeoutMs = TIMEOUT_MS) {
const frame = await this.nextFrame(description, timeoutMs);
assert.equal(frame.final, true);
assert.equal(frame.opcode, 0x1);
return JSON.parse(frame.payload.toString("utf8"));
}
async waitClosed() {
if (this.closed) return;
await withTimeout(onceEvent(this.socket, "close", ["error"]), "WebSocket close");
}
destroy() {
this.socket.destroy();
}
}
function webSocketForOrigin(origin) {
return class OriginWebSocket {
static CONNECTING = 0;
static OPEN = 1;
static CLOSING = 2;
static CLOSED = 3;
constructor(url, protocols) {
this.url = url;
this.protocol = "";
this.readyState = OriginWebSocket.CONNECTING;
this.bufferedAmount = 0;
this._protocols = protocols;
this._listeners = new Map();
this._client = null;
this._closeRequested = false;
void this._connect();
}
addEventListener(type, listener) {
const listeners = this._listeners.get(type) ?? new Set();
listeners.add(listener);
this._listeners.set(type, listeners);
}
removeEventListener(type, listener) {
this._listeners.get(type)?.delete(listener);
}
send(value) {
if (this.readyState !== OriginWebSocket.OPEN || !this._client) {
throw new Error("WebSocket is not open");
}
if (typeof value === "string") {
this._client.send(0x1, Buffer.from(value, "utf8"));
} else if (value instanceof ArrayBuffer) {
this._client.send(0x2, Buffer.from(value));
} else if (ArrayBuffer.isView(value)) {
this._client.send(0x2, Buffer.from(value.buffer, value.byteOffset, value.byteLength));
} else {
throw new TypeError("test WebSocket accepts text or binary data");
}
}
close() {
if (this.readyState === OriginWebSocket.CLOSED || this._closeRequested) return;
this._closeRequested = true;
this.readyState = OriginWebSocket.CLOSING;
if (this._client) {
try { this._client.send(0x8, Buffer.alloc(0)); } catch {}
this._client.destroy();
this._finishClose();
}
}
_emit(type, event = {}) {
for (const listener of [...(this._listeners.get(type) ?? [])]) {
listener.call(this, event);
}
}
_finishClose() {
if (this.readyState === OriginWebSocket.CLOSED) return;
this.readyState = OriginWebSocket.CLOSED;
this._emit("close", { code: 1000, reason: "" });
}
async _connect() {
try {
const url = new URL(this.url);
assert.equal(url.protocol, "ws:");
const host = url.hostname.startsWith("[")
? url.hostname.slice(1, -1)
: url.hostname;
const protocols = Array.isArray(this._protocols) ? this._protocols : [this._protocols];
const subprotocol = protocols.find((value) => value !== undefined);
const upgraded = await upgrade({
host,
port: Number(url.port),
route: `${url.pathname}${url.search}`,
origin,
subprotocol,
});
if (this._closeRequested) {
upgraded.client?.destroy();
this._finishClose();
return;
}
if (upgraded.status !== 101 || !upgraded.client) {
throw new Error(`WebSocket upgrade failed with HTTP ${upgraded.status}`);
}
this._client = upgraded.client;
this.protocol = upgraded.headers.get("sec-websocket-protocol") ?? "";
this.readyState = OriginWebSocket.OPEN;
this._emit("open");
void this._pump();
} catch (error) {
if (!this._closeRequested) this._emit("error", { error });
this._finishClose();
}
}
async _pump() {
try {
while (this.readyState === OriginWebSocket.OPEN) {
const frame = await this._client.nextFrame("SDK WebSocket frame");
if (frame.opcode === 0x1) {
this._emit("message", { data: frame.payload.toString("utf8") });
} else if (frame.opcode === 0x2) {
this._emit("message", {
data: frame.payload.buffer.slice(
frame.payload.byteOffset,
frame.payload.byteOffset + frame.payload.byteLength,
),
});
} else if (frame.opcode === 0x8) {
this.readyState = OriginWebSocket.CLOSING;
try { this._client.send(0x8, frame.payload); } catch {}
await this._client.waitClosed().catch(() => {});
this._finishClose();
return;
} else if (frame.opcode === 0x9) {
this._client.send(0xa, frame.payload);
}
}
} catch (error) {
if (!this._closeRequested && this.readyState === OriginWebSocket.OPEN &&
!this._client.closed) {
this._emit("error", { error });
}
this._finishClose();
}
}
};
}
async function spawnDaemon({
executable = SYNCD,
arguments: daemonArguments = [
"--port", "0",
"--test-origin", ORIGIN,
"--test-token", TOKEN,
"--test-receiver",
],
env = process.env,
} = {}) {
const child = spawn(executable, daemonArguments,
{ cwd: ROOT, env, stdio: ["ignore", "pipe", "pipe"] });
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => { stdout += chunk; });
child.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-16_384); });
let removeReadyListeners = () => {};
try {
const readyPromise = new Promise((resolve, reject) => {
const inspect = () => {
const newline = stdout.indexOf("\n");
if (newline < 0) return;
try {
assert.equal(stdout.slice(newline + 1), "", "syncd emits only one startup stdout line");
resolve(JSON.parse(stdout.slice(0, newline)));
} catch (error) {
reject(error);
}
};
const failed = (error) => reject(error);
const exited = (code, signal) => {
reject(new Error(`syncd exited before ready: code=${code} signal=${signal} stderr=${stderr}`));
};
removeReadyListeners = () => {
child.stdout.off("data", inspect);
child.off("error", failed);
child.off("exit", exited);
};
child.stdout.on("data", inspect);
child.once("error", failed);
child.once("exit", exited);
});
const ready = await withTimeout(readyPromise, "syncd ready record");
removeReadyListeners();
return { child, ready, stderr: () => stderr, stdout: () => stdout };
} catch (error) {
removeReadyListeners();
await terminateChild(child);
throw error;
}
}
async function spawnPairingDaemon(storePath, mode) {
return spawnDaemon({
executable: PAIRING_TEST_SERVER,
arguments: [storePath, mode],
});
}
async function terminateChild(child, cleanupTimeoutMs = 1_000) {
if (child.exitCode !== null || child.signalCode !== null || child.pid === undefined) return;
let exitPromise = onceEvent(child, "exit", ["error"]);
child.kill("SIGTERM");
try {
await withTimeout(exitPromise, "failed child cleanup", cleanupTimeoutMs);
} catch {
if (child.exitCode !== null || child.signalCode !== null) return;
exitPromise = onceEvent(child, "exit", ["error"]);
child.kill("SIGKILL");
await withTimeout(exitPromise, "forced child cleanup", cleanupTimeoutMs);
}
}
async function pairWithDaemon(ready, origin, name = "Noisedeck") {
const upgraded = await upgrade({ port: ready.port, route: "/pair", origin });
assert.equal(upgraded.status, 101);
upgraded.client.sendJson({ type: "pair", protocolVersions: [1], name });
const response = await upgraded.client.nextJson("pairing response", PAIRING_TIMEOUT_MS);
const close = await upgraded.client.nextFrame("pairing close", PAIRING_TIMEOUT_MS);
assert.equal(close.opcode, 0x8);
upgraded.client.send(0x8, close.payload);
await upgraded.client.waitClosed();
return response;
}
async function authenticateControl(ready, origin, token) {
const upgraded = await upgrade({ port: ready.port, route: "/control", origin });
assert.equal(upgraded.status, 101);
upgraded.client.sendJson({ type: "hello", token, protocolVersions: [1] });
return upgraded;
}
async function createTestSender(control, port, name) {
control.sendJson({ type: "createSender", name });
const created = await control.nextJson(`${name} creation`);
assert.equal(created.type, "senderCreated");
const upgraded = await upgrade({
port,
route: created.path,
origin: ORIGIN,
subprotocol: `sync.sender.${created.ticket}`,
});
assert.equal(upgraded.status, 101);
return { created, data: upgraded.client };
}
// Windows has no deliverable SIGTERM. Node's child.kill() there is always
// TerminateProcess regardless of the signal name passed, and the one event
// that does reach a libuv loop -- CTRL_BREAK_EVENT -- can only be sent by a
// process sharing the target's console, which Node cannot do. So on Windows
// these tests stop the daemon by terminating it and assert only that it
// stops; they cannot assert it shut down gracefully.
//
// Graceful shutdown IS covered on Windows, by scripts/smoke-windows-app.ps1:
// the tray app spawns its helper into a new process group and stops it with
// CTRL_BREAK_EVENT, which the daemon receives as SIGBREAK. That is the real
// shipped path, exercised against the real binaries.
const GRACEFUL_SHUTDOWN_IS_OBSERVABLE = process.platform !== "win32";
// The default pairing store lives under $HOME on POSIX and %LOCALAPPDATA%
// on Windows. Linux production mode also owns a control socket under
// $XDG_RUNTIME_DIR, so the same mode-0700 temporary directory isolates both.
// Setting only HOME would silently let a Windows run touch the real user store.
function isolatedStoreEnvironment(directory) {
return process.platform === "win32"
? { ...process.env, LOCALAPPDATA: directory }
: { ...process.env, HOME: directory,
...(process.platform === "linux" ? { XDG_RUNTIME_DIR: directory } : {}) };
}
function escapeForRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Builds the exact stderr a daemon owes for the providers it just reported:
// one line per unavailable provider, in the order /health lists them, each
// naming a reason, and nothing else.
//
// Both the set and the order come from /health rather than from a local
// constant, so this also asserts that stderr and /health agree on which
// providers failed and in what order -- an invariant nothing else checks,
// since the health assertions sort before comparing. It stays correct on a
// machine that has a runtime installed and on one that does not, with no
// platform branch to rot.
//
// `reasons` pins the exact phrase for a provider whose failure the caller
// fully determines. Without it any non-empty reason satisfies the line, which
// is enough to prove the daemon spoke but not enough to prove it said the
// right thing -- so a test that knows what it earned should say so.
function expectedProviderDiagnostics(providers, reasons = {}) {
const lines = providers
.filter((provider) => !provider.available)
.map((provider) => `syncd: provider "${escapeForRegExp(provider.id)}" `
+ "is selected but unavailable: "
+ (reasons[provider.id] === undefined
? "\\S.*"
: escapeForRegExp(reasons[provider.id]))
+ "\\n");
return new RegExp(`^${lines.join("")}$`);
}
// `expectedStderr` stays "" for every ordinary run, so unexpected noise is
// still a failure everywhere. A caller that selects a provider it knows is
// unavailable passes the diagnostic it requires instead: the daemon is
// obliged to say why it degraded, and silence there is the bug this option
// exists to catch.
async function stopDaemon(child, stderr, stdout, ready, options) {
const {
shutdownTimeoutMs = TIMEOUT_MS,
cleanupTimeoutMs = 1_000,
expectedStderr = "",
} = options ?? {};
const assertStderr = () => {
if (expectedStderr instanceof RegExp) {
assert.match(stderr(), expectedStderr, "syncd explains the diagnostic it emitted");
return;
}
assert.equal(stderr(), expectedStderr, "syncd emits no diagnostics during a clean run");
};
if (child.exitCode !== null || child.signalCode !== null) {
if (GRACEFUL_SHUTDOWN_IS_OBSERVABLE) {
assert.equal(child.signalCode, null, `syncd handles shutdown itself; stderr=${stderr()}`);
assert.equal(child.exitCode, 0, `syncd exited cleanly; stderr=${stderr()}`);
}
assert.equal(stdout(), `${JSON.stringify(ready)}\n`, "syncd emits exactly one stdout record");
assertStderr();
return;
}
const exitPromise = onceEvent(child, "exit", ["error"]);
child.kill("SIGTERM");
let code;
let signal;
try {
[code, signal] = await withTimeout(exitPromise, "syncd shutdown", shutdownTimeoutMs);
} catch (shutdownError) {
try {
await terminateChild(child, cleanupTimeoutMs);
} catch (cleanupError) {
if (shutdownError instanceof Error) shutdownError.cause = cleanupError;
}
throw shutdownError;
}
if (GRACEFUL_SHUTDOWN_IS_OBSERVABLE) {
assert.equal(signal, null, `syncd handles SIGTERM itself; stderr=${stderr()}`);
assert.equal(code, 0, `syncd exits cleanly; stderr=${stderr()}`);
} else {
// Terminated rather than asked to stop, so there is no exit code to
// check -- only that it is no longer running.
assert.ok(signal !== null || code !== null, "syncd stopped");
}
assert.equal(stdout(), `${JSON.stringify(ready)}\n`, "syncd emits exactly one stdout record");
assertStderr();
}
function fnv1a32(bytes) {
let hash = 0x811c9dc5;
for (const byte of bytes) {
hash ^= byte;
hash = Math.imul(hash, 0x01000193) >>> 0;
}
return hash;
}
async function runToExit(executable, arguments_, { env = process.env } = {}) {
const child = spawn(executable, arguments_, {
cwd: ROOT,
env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => { stdout += chunk; });
child.stderr.on("data", (chunk) => { stderr += chunk; });
const [code, signal] = await withTimeout(
onceEvent(child, "close", ["error"]), `process exit: ${path.basename(executable)}`,
);
return { code, signal, stdout, stderr };
}
async function listenGuard(host, port) {
const server = net.createServer();
const listening = onceEvent(server, "listening", ["error"]);
server.listen({ host, port, ipv6Only: host === "::1" });
await withTimeout(listening, `guard listener on ${host}:${port}`);
return server;
}
async function closeGuard(server) {
if (!server.listening) return;
const closed = onceEvent(server, "close", ["error"]);
server.close();
await withTimeout(closed, "guard listener close");
}
async function unusedDualLoopbackPort() {
for (let attempt = 0; attempt < 20; attempt += 1) {
const ipv4 = await listenGuard("127.0.0.1", 0);
const port = ipv4.address().port;
let ipv6;
try {
ipv6 = await listenGuard("::1", port);
await closeGuard(ipv6);
await closeGuard(ipv4);
return port;
} catch {
if (ipv6) await closeGuard(ipv6);
await closeGuard(ipv4);
}
}
throw new Error("could not reserve a dual-loopback test port");
}
test("daemon path override accepts absolute and workspace-relative paths", () => {
assert.equal(resolveDaemonPath(), SYNCD);
assert.equal(resolveDaemonPath("/tmp/custom-syncd"), "/tmp/custom-syncd");
assert.equal(resolveDaemonPath("build-sanitize/syncd"),
path.join(ROOT, "build-sanitize", "syncd"));
});
test("malformed readiness output rejects only after the spawned child is cleaned up", async () => {
const outcome = await spawnDaemon({
executable: process.execPath,
arguments: ["-e", "process.stdout.write('not-json\\n'); setInterval(() => {}, 1000)"],
}).then((daemon) => ({ daemon }), (error) => ({ error }));
if (outcome.daemon) {
await stopDaemon(outcome.daemon.child,
outcome.daemon.stderr,
outcome.daemon.stdout,
outcome.daemon.ready);
}
assert.ok(outcome.error instanceof SyntaxError,
"malformed readiness is rejected after terminating its child");
});
test("browser SDK performs a bounded health probe against the real loopback daemon", async () => {
const daemon = await spawnDaemon();
try {
const bridge = new SyncBridgeClient({
endpoint: `http://127.0.0.1:${daemon.ready.port}`,
token: TOKEN,
timeoutMs: TIMEOUT_MS,
});
const result = await bridge.probe();
assert.equal(result.available, true, result.message);
assert.equal(result.health.product, "Sync");
assert.equal(result.health.instanceId, daemon.ready.instanceId);
assert.equal(result.health.protocolVersions.includes(1), true);
assert.equal(result.health.capabilities.providers.length, 1);
bridge.close();
} finally {
await stopDaemon(daemon.child, daemon.stderr, daemon.stdout, daemon.ready);
}
});
test("all four explicit video providers preserve the legacy capability bound", async () => {
const providerIds = ["syphon", "spout", "ndi", "camera"];
const daemon = await spawnDaemon({ arguments: [
"--port", "0", "--test-origin", ORIGIN, "--test-token", TOKEN,
...providerIds.flatMap((id) => ["--publisher", id]),
] });
let providers = [];
const bridge = new SyncBridgeClient({
endpoint: `http://127.0.0.1:${daemon.ready.port}`, token: TOKEN, timeoutMs: TIMEOUT_MS,
});
try {
const result = await bridge.probe();
assert.equal(result.available, true, result.message);
providers = result.health.capabilities.providers;
assert.deepEqual(providers.map((provider) => provider.id), providerIds);
assert.equal(providers.length, 4);
} finally {
bridge.close();
const diagnostics = expectedProviderDiagnostics(providers).source.replace(/\$$/, "");
await stopDaemon(daemon.child, daemon.stderr, daemon.stdout, daemon.ready, {
expectedStderr: new RegExp(diagnostics +
"syncd: native audio is unavailable when all four video providers are explicitly selected\\n$"),
});
}
});
test("native audio transport preserves 1, 2, 8, and 32 ordered float32 channels", async () => {
const daemon = await spawnDaemon({ executable: AUDIO_TEST_SERVER, arguments: [] });
const bridge = new SyncBridgeClient({
endpoint: `http://127.0.0.1:${daemon.ready.port}`,
token: "audio-test-token",
fetch: healthFetchForOrigin("http://127.0.0.1:8000"),
WebSocket: webSocketForOrigin("http://127.0.0.1:8000"),
timeoutMs: TIMEOUT_MS,
});
const expectedValues = [
0.03125, 0.0625, 0.09375, 0.125, 0.15625, 0.1875, 0.21875, 0.25,
0.28125, 0.3125, 0.34375, 0.375, 0.40625, 0.4375, 0.46875, 0.5,
0.53125, 0.5625, 0.59375, 0.625, 0.65625, 0.6875, 0.71875, 0.75,
0.78125, 0.8125, 0.84375, 0.875, 0.90625, 0.9375, 0.96875, 1,
];
try {
const sources = await bridge.listAudioSources();
for (const channelCount of [1, 2, 8, 32]) {
const sourceId = `audio_${channelCount}`;
assert.deepEqual(sources.find((source) => source.id === sourceId), {
id: sourceId,
name: `${channelCount} channel fixture`,
channelCount,
sampleRate: 48_000,
});
assert.deepEqual(await bridge.openAudioSource(sourceId), {
type: "audioSourceOpened",
id: sourceId,
channelCount,
sampleRate: 48_000,
});
const deadline = Date.now() + TIMEOUT_MS;
let packet;
do {
packet = await bridge.readAudioSource(sourceId);
} while (packet.frameCount === 0 && Date.now() < deadline);
assert.ok(packet.frameCount > 0, `${sourceId} produces frames within the bound`);
assert.equal(packet.channelCount, channelCount);
assert.equal(packet.sampleRate, 48_000);
assert.equal(packet.planes.length, channelCount);
assert.equal(typeof packet.firstFrame, "bigint");
assert.equal(typeof packet.droppedFrames, "bigint");
for (let channel = 0; channel < channelCount; channel += 1) {
assert.equal(packet.planes[channel].length, packet.frameCount);
for (const sample of packet.planes[channel]) {
assert.equal(sample, expectedValues[channel],
`channel ${channel + 1} keeps its exact float32 value`);
}
}
assert.deepEqual(await bridge.closeAudioSource(sourceId), {
type: "audioSourceClosed",
id: sourceId,
});
}
const status = await bridge.listAudioSources();
assert.equal(status.find(source => source.id === "audio_active")?.name, "0");
assert.equal(status.find(source => source.id === "audio_wrong_thread_closes")?.name,
"0", "explicit close destroys every capture on its opening thread");
assert.equal(status.find(source => source.id === "audio_wrong_thread_reads")?.name,
"0", "reads stay on the capture's opening thread");
} finally {
bridge.close();
await stopDaemon(daemon.child, daemon.stderr, daemon.stdout, daemon.ready);
}
});
test("native audio close during a slow open releases the connection-owned capture", async () => {
const daemon = await spawnDaemon({ executable: AUDIO_TEST_SERVER, arguments: [] });
let opening;
let observer;
try {
opening = await authenticateControl(
daemon.ready, "http://127.0.0.1:8000", "audio-test-token",
);
assert.equal((await opening.client.nextJson("audio fixture welcome")).type, "welcome");
opening.client.sendJson({ type: "openAudioSource", sourceId: "audio_slow" });
opening.client.sendJson({ type: "listAudioSources" });
const busy = await opening.client.nextJson("overlapping audio request rejection");
assert.deepEqual(busy, {
type: "error",
code: "audio_busy",
message: "Audio request already pending",
});
const close = await opening.client.nextFrame("audio busy close");
assert.equal(close.opcode, 0x8);
opening.client.send(0x8, close.payload);
await opening.client.waitClosed();
observer = await authenticateControl(
daemon.ready, "http://127.0.0.1:8000", "audio-test-token",
);
assert.equal((await observer.client.nextJson("audio cleanup observer welcome")).type,
"welcome");
const deadline = Date.now() + TIMEOUT_MS;
let active;
let completed;
let wrongThreadCloses;
do {
observer.client.sendJson({ type: "listAudioSources" });
const listed = await observer.client.nextJson("audio cleanup status");
assert.equal(listed.type, "audioSources");
active = listed.sources.find((source) => source.id === "audio_active")?.name;
wrongThreadCloses = listed.sources.find(
source => source.id === "audio_wrong_thread_closes",
)?.name;
completed = listed.sources.find(
(source) => source.id === "audio_slow_completed",
)?.name;
if (active !== "0" || completed !== "1") {
await new Promise((resolve) => setTimeout(resolve, 5));
}
} while ((active !== "0" || completed !== "1") && Date.now() < deadline);
assert.equal(completed, "1", "the pending driver open completed exactly once");
assert.equal(active, "0", "its capture was destroyed after the owner disconnected");
assert.equal(wrongThreadCloses, "0", "disconnect cleanup stays on the opening thread");
} finally {
opening?.client.destroy();
observer?.client.destroy();
await stopDaemon(daemon.child, daemon.stderr, daemon.stdout, daemon.ready);
}
});
test("native audio reads stay below 66 ms while an independent source opens", async () => {
const daemon = await spawnDaemon({ executable: AUDIO_TEST_SERVER, arguments: [] });
const controls = [];
try {
// Non-audio connections must not make two independent captures share a
// blocked worker simply because their connection slots happen to collide.
for (let i = 0; i < 6; i++) {
const control = await authenticateControl(
daemon.ready, "http://127.0.0.1:8000", "audio-test-token",
);