-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathmeshcoreVirtualNodeServer.test.ts
More file actions
1190 lines (1062 loc) · 50.8 KB
/
Copy pathmeshcoreVirtualNodeServer.test.ts
File metadata and controls
1190 lines (1062 loc) · 50.8 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 { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { EventEmitter } from 'events';
import { Socket } from 'net';
import { Connection, Constants } from '@liamcottle/meshcore.js';
import { MeshCoreVirtualNodeServer, type MeshCoreVirtualNodeManager } from './meshcoreVirtualNodeServer.js';
import {
CommandCodes,
ResponseCodes,
ErrorCodes,
PushCodes,
BinaryRequestTypes,
FRAME_APP_TO_NODE,
FRAME_NODE_TO_APP,
SUPPORTED_COMPANION_PROTOCOL_VERSION,
degreesToFixed,
} from './meshcoreCompanionCodec.js';
import type { MeshCoreNode, MeshCoreContact, MeshCoreMessage } from './meshcoreManager.js';
// Audit logging is fire-and-forget; stub it so the test doesn't touch the DB.
vi.mock('../services/database.js', () => ({
default: { auditLogAsync: vi.fn().mockResolvedValue(undefined) },
}));
const LOCAL_NODE: MeshCoreNode = {
publicKey: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2',
name: 'Phase0 Node',
advType: Constants.AdvType.Chat,
txPower: 20,
maxTxPower: 30,
radioFreq: 917.375, // MHz
radioBw: 250, // kHz
radioSf: 11,
radioCr: 5,
latitude: 29.7604,
longitude: -95.3698,
manualAddContacts: 1,
};
const SAMPLE_CONTACTS: MeshCoreContact[] = [
{
publicKey: 'b1'.repeat(32),
advName: 'Repeater North',
advType: Constants.AdvType.Repeater,
latitude: 40.1,
longitude: -105.2,
lastAdvert: 1_750_000_000,
lastSeen: 1_750_000_500,
pathLen: 2,
outPath: 'a3,7f',
},
];
/** A fake manager backed by a real EventEmitter so the server can subscribe. */
class FakeManager extends EventEmitter implements MeshCoreVirtualNodeManager {
readonly sourceId = 'src-test';
private localNode: MeshCoreNode | null;
private contacts: MeshCoreContact[];
constructor(localNode: MeshCoreNode | null = LOCAL_NODE, contacts = SAMPLE_CONTACTS) {
super();
this.localNode = localNode;
this.contacts = contacts;
}
sendMessageMock = vi.fn().mockResolvedValue(true);
sendMessageWithResultMock = vi.fn().mockResolvedValue({ ok: true });
// Config-mutation mocks (issue #3904).
setNameMock = vi.fn().mockResolvedValue(true);
setRadioMock = vi.fn().mockResolvedValue(true);
setTxPowerMock = vi.fn().mockResolvedValue(true);
setCoordsMock = vi.fn().mockResolvedValue(true);
setChannelMock = vi.fn().mockResolvedValue(undefined);
setOtherParamsMock = vi.fn().mockResolvedValue(true);
sendAdvertMock = vi.fn().mockResolvedValue(true);
loginToNodeMock = vi.fn().mockResolvedValue(true);
tracePathRawMock = vi.fn().mockResolvedValue({ pathSnrs: [8, 12], lastSnr: 5.5, pathLen: 2, flags: 0 });
requestRemoteTelemetryRawMock = vi.fn().mockResolvedValue(Buffer.from([0x01, 0x67, 0x00, 0xdc]));
requestNodeStatusMock = vi.fn().mockResolvedValue({
batteryMv: 4100,
queueLen: 3,
noiseFloor: -120,
lastRssi: -85,
packetsRecv: 1000,
packetsSent: 900,
airTimeSecs: 500,
uptimeSecs: 86400,
sentFlood: 100,
sentDirect: 200,
recvFlood: 300,
recvDirect: 400,
errors: 5,
lastSnr: 24, // int16 quarter-dB raw value as the wire carries it
directDups: 6,
floodDups: 7,
});
isConnected() { return this.localNode !== null; }
getLocalNode() { return this.localNode; }
getContacts() { return this.contacts; }
sendMessage(text: string, toPublicKey?: string, channelIdx?: number) {
return this.sendMessageMock(text, toPublicKey, channelIdx) as Promise<boolean>;
}
sendMessageWithResult(text: string, toPublicKey?: string, channelIdx?: number) {
return this.sendMessageWithResultMock(text, toPublicKey, channelIdx) as Promise<{ ok: boolean; expectedAckCrc?: number; estTimeout?: number }>;
}
setName(name: string) { return this.setNameMock(name) as Promise<boolean>; }
setRadio(freq: number, bw: number, sf: number, cr: number) {
return this.setRadioMock(freq, bw, sf, cr) as Promise<boolean>;
}
setTxPower(power: number) { return this.setTxPowerMock(power) as Promise<boolean>; }
setCoords(lat: number, lon: number) { return this.setCoordsMock(lat, lon) as Promise<boolean>; }
setChannel(idx: number, name: string, secretHex: string, scope?: string | null) {
return this.setChannelMock(idx, name, secretHex, scope) as Promise<void>;
}
setOtherParams(params: {
manualAddContacts: number;
telemetryModeBase: number;
telemetryModeLoc: number;
telemetryModeEnv: number;
advLocPolicy: number;
}) {
return this.setOtherParamsMock(params) as Promise<boolean>;
}
sendAdvert() { return this.sendAdvertMock() as Promise<boolean>; }
loginToNode(publicKey: string, password: string) {
return this.loginToNodeMock(publicKey, password) as Promise<boolean>;
}
tracePathRaw(path: Uint8Array) {
return this.tracePathRawMock(path) as Promise<{ pathSnrs: number[]; lastSnr: number; pathLen: number; flags: number } | null>;
}
requestRemoteTelemetryRaw(publicKey: string) {
return this.requestRemoteTelemetryRawMock(publicKey) as Promise<Buffer | null>;
}
requestNodeStatus(publicKey: string) {
return this.requestNodeStatusMock(publicKey) as Promise<Record<string, number> | null>;
}
getNeighboursMock = vi.fn().mockResolvedValue({
total: 3,
neighbours: [
{ publicKeyPrefix: 'aabbccddeeff0011', heardSecondsAgo: 42, snr: 5.25 },
{ publicKeyPrefix: '1122334455667788', heardSecondsAgo: 3600, snr: -2.5 },
],
});
getNeighbours(publicKey: string, opts?: { count?: number; offset?: number; orderBy?: number }) {
return this.getNeighboursMock(publicKey, opts) as Promise<{
total: number;
neighbours: { publicKeyPrefix: string; heardSecondsAgo: number; snr: number }[];
} | null>;
}
emitMessage(msg: MeshCoreMessage) { this.emit('message', msg); }
emitSendConfirmed(data: { ackCode: number; roundTripMs: number }) { this.emit('send_confirmed', data); }
emitOtaPacket(data: { snr?: number | null; rssi?: number | null; raw_hex?: string | null }) {
this.emit('ota_packet', data);
}
}
const CHANNELS_DB = {
channels: {
getAllChannels: vi.fn().mockResolvedValue([
{ id: 0, name: 'Public', psk: Buffer.from('0123456789abcdef0123456789abcdef', 'hex').toString('base64') },
]),
},
};
function makeManager(overrides: Partial<MeshCoreVirtualNodeManager> = {}): MeshCoreVirtualNodeManager {
const base = new FakeManager(
'getLocalNode' in overrides ? (overrides.getLocalNode as () => MeshCoreNode | null)() : LOCAL_NODE,
);
return Object.assign(base, overrides) as MeshCoreVirtualNodeManager;
}
/** Frame an app→node command (the byte layout the MeshCore app would send). */
function frameCommand(payload: number[]): Buffer {
const header = Buffer.alloc(3);
header[0] = FRAME_APP_TO_NODE;
header.writeUInt16LE(payload.length, 1);
return Buffer.concat([header, Buffer.from(payload)]);
}
/**
* Tiny client: connects, lets you send command frames, and resolves the next
* complete node→app (0x3e) response frame's payload (response code byte first).
*/
class TestClient {
private socket = new Socket();
private buffer = Buffer.alloc(0);
private waiters: Array<(payload: Buffer) => void> = [];
async connect(port: number): Promise<void> {
await new Promise<void>((resolve, reject) => {
this.socket.once('error', reject);
this.socket.connect(port, '127.0.0.1', () => resolve());
});
this.socket.on('data', (data) => this.onData(data));
}
private onData(data: Buffer): void {
this.buffer = Buffer.concat([this.buffer, data]);
while (this.buffer.length >= 3) {
if (this.buffer[0] !== FRAME_NODE_TO_APP) {
this.buffer = this.buffer.subarray(1);
continue;
}
const len = this.buffer.readUInt16LE(1);
if (this.buffer.length < 3 + len) break;
const payload = Buffer.from(this.buffer.subarray(3, 3 + len));
this.buffer = this.buffer.subarray(3 + len);
this.waiters.shift()?.(payload);
}
}
/** Send a command and await the next response payload. */
request(payload: number[]): Promise<Buffer> {
const p = new Promise<Buffer>((resolve) => this.waiters.push(resolve));
this.socket.write(frameCommand(payload));
return p;
}
/** Await the next N response payloads (for commands that reply with several frames). */
expectFrames(n: number): Promise<Buffer[]> {
return Promise.all(Array.from({ length: n }, () => new Promise<Buffer>((resolve) => this.waiters.push(resolve))));
}
send(payload: number[]): void {
this.socket.write(frameCommand(payload));
}
close(): void {
this.socket.destroy();
}
}
describe('MeshCoreVirtualNodeServer — Phase 0 handshake', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
beforeEach(async () => {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
});
afterEach(async () => {
client.close();
await server.stop();
});
it('replies to AppStart with SelfInfo carrying the real node identity', async () => {
const payload = await client.request([CommandCodes.AppStart, 1, 0, 0, 0, 0, 0, 0]); // appVer + 6 reserved
expect(payload[0]).toBe(ResponseCodes.SelfInfo);
// name is the remainder of the frame after the fixed SelfInfo fields
expect(payload.subarray(-LOCAL_NODE.name.length).toString('utf8')).toBe('Phase0 Node');
});
it('reports the real manualAddContacts in SelfInfo instead of hardcoding 0 (#3904 follow-up)', async () => {
// LOCAL_NODE.manualAddContacts = 1; decode the SelfInfo via meshcore.js's own
// parser and assert the field round-trips rather than being pinned to 0.
const payload = await client.request([CommandCodes.AppStart, 1, 0, 0, 0, 0, 0, 0]);
expect(payload[0]).toBe(ResponseCodes.SelfInfo);
const decoded = await new Promise<any>((resolve) => {
const conn: any = new (Connection as any)();
conn.once(ResponseCodes.SelfInfo, (event: any) => resolve(event));
conn.onFrameReceived(new Uint8Array(payload));
});
expect(decoded.manualAddContacts).toBe(1);
});
it('replies to GetDeviceTime with a plausible CurrTime', async () => {
const before = Math.floor(Date.now() / 1000);
const payload = await client.request([CommandCodes.GetDeviceTime]);
expect(payload[0]).toBe(ResponseCodes.CurrTime);
const epoch = payload.readUInt32LE(1);
expect(epoch).toBeGreaterThanOrEqual(before);
expect(epoch).toBeLessThanOrEqual(Math.floor(Date.now() / 1000) + 1);
});
it('replies to DeviceQuery with DeviceInfo advertising the supported protocol version', async () => {
const payload = await client.request([CommandCodes.DeviceQuery, 1]);
expect(payload[0]).toBe(ResponseCodes.DeviceInfo);
// Byte 1 is the companion protocol version the app must use to talk to us.
expect(payload.readInt8(1)).toBe(SUPPORTED_COMPANION_PROTOCOL_VERSION);
});
it('pins DeviceInfo protocol version to v1 even when the real node reports a higher firmwareVer (regression #3705)', async () => {
// Once the manager's background deviceQuery() caches the real node's
// firmware-version byte, that value must NOT leak into the VN's DeviceInfo
// version field — the VN only speaks v1 frames, and the meshcore-flutter app
// aborts the handshake (never sending AppStart) when it sees a version it
// can't reconcile. Stand up a fresh server whose local node reports fw ver 7.
const realNode: MeshCoreNode = { ...LOCAL_NODE, firmwareVer: 7, firmwareBuild: '25-Jun-2026', model: 'Heltec V3' };
const realManager = new FakeManager(realNode);
const realServer = new MeshCoreVirtualNodeServer({ port: 0, manager: realManager, databaseService: CHANNELS_DB });
await realServer.start();
const realClient = new TestClient();
await realClient.connect(realServer.getListeningPort()!);
try {
const payload = await realClient.request([CommandCodes.DeviceQuery, 1]);
expect(payload[0]).toBe(ResponseCodes.DeviceInfo);
expect(payload.readInt8(1)).toBe(SUPPORTED_COMPANION_PROTOCOL_VERSION);
expect(payload.readInt8(1)).not.toBe(7);
} finally {
realClient.close();
await realServer.stop();
}
});
it('replies to GetContacts with ContactsStart(N), Contact frames, then EndOfContacts', async () => {
client.send([CommandCodes.GetContacts, 0, 0, 0, 0]); // since:u32
const [start, contact, end] = await client.expectFrames(3);
expect(start[0]).toBe(ResponseCodes.ContactsStart);
expect(start.readUInt32LE(1)).toBe(1);
expect(contact[0]).toBe(ResponseCodes.Contact);
// public key is the 32 bytes right after the response code
expect(contact.subarray(1, 33).toString('hex')).toBe('b1'.repeat(32));
expect(end[0]).toBe(ResponseCodes.EndOfContacts);
});
it('replies to GetChannel(0) with ChannelInfo from the channels DB', async () => {
const payload = await client.request([CommandCodes.GetChannel, 0]);
expect(payload[0]).toBe(ResponseCodes.ChannelInfo);
expect(payload[1]).toBe(0); // channel index
});
it('replies to GetChannel for an unknown slot with Err(NotFound)', async () => {
const payload = await client.request([CommandCodes.GetChannel, 7]);
expect(payload[0]).toBe(ResponseCodes.Err);
expect(payload[1]).toBe(Constants.ErrorCodes.NotFound);
});
it('replies to GetBatteryVoltage with BatteryVoltage', async () => {
const payload = await client.request([CommandCodes.GetBatteryVoltage]);
expect(payload[0]).toBe(ResponseCodes.BatteryVoltage);
});
it('acknowledges SetFloodScope with Ok (read-only no-op)', async () => {
const payload = await client.request([0x36 /* SetFloodScope=54 */, 0]);
expect(payload[0]).toBe(ResponseCodes.Ok);
});
it('SyncNextMessage returns NoMoreMessages when the queue is empty', async () => {
const payload = await client.request([CommandCodes.SyncNextMessage]);
expect(payload[0]).toBe(ResponseCodes.NoMoreMessages);
});
it('pushes MsgWaiting on a live incoming message and delivers it via SyncNextMessage', async () => {
const push = new Promise<Buffer>((resolve) => (client as any).waiters.push(resolve));
manager.emitMessage({
id: 'm1',
fromPublicKey: 'b1'.repeat(32),
toPublicKey: undefined,
text: 'incoming dm',
timestamp: 1_750_000_000_000,
});
const pushFrame = await push;
expect(pushFrame[0]).toBe(PushCodes.MsgWaiting);
const recv = await client.request([CommandCodes.SyncNextMessage]);
expect(recv[0]).toBe(ResponseCodes.ContactMsgRecv);
expect(recv.subarray(-'incoming dm'.length).toString('utf8')).toBe('incoming dm');
});
it('delivers an incoming CHANNEL message as ChannelMsgRecv (marker in fromPublicKey)', async () => {
const push = new Promise<Buffer>((resolve) => (client as any).waiters.push(resolve));
// Incoming channel messages carry the channel marker in fromPublicKey, with
// toPublicKey unset, and the sender name in fromName.
manager.emitMessage({
id: 'c1',
fromPublicKey: 'channel-1',
fromName: 'Yeraze MC Sandbox',
text: '🤖 Copy that',
timestamp: 1_750_000_000_000,
});
expect((await push)[0]).toBe(PushCodes.MsgWaiting);
const recv = await client.request([CommandCodes.SyncNextMessage]);
expect(recv[0]).toBe(ResponseCodes.ChannelMsgRecv);
expect(recv.readInt8(1)).toBe(1); // channel index
// sender name is reconstructed into the channel body the firmware would deliver.
// ChannelMsgRecv header = code + channelIdx + pathLen + txtType + senderTs(4) = 8 bytes.
expect(recv.subarray(8).toString('utf8')).toBe('Yeraze MC Sandbox: 🤖 Copy that');
});
it('does not echo our own channel transmission heard back (matching local name)', async () => {
manager.emitMessage({
id: 'c2',
fromPublicKey: 'channel-1',
fromName: LOCAL_NODE.name, // our own node's name → our transmission
text: 'my own msg',
timestamp: 1_750_000_000_000,
});
const payload = await client.request([CommandCodes.SyncNextMessage]);
expect(payload[0]).toBe(ResponseCodes.NoMoreMessages);
});
it('does not echo a message our own node originated', async () => {
manager.emitMessage({
id: 'm2',
fromPublicKey: LOCAL_NODE.publicKey, // self
text: 'our own send',
timestamp: 1_750_000_000_000,
});
// No MsgWaiting push should arrive; the queue stays empty.
const payload = await client.request([CommandCodes.SyncNextMessage]);
expect(payload[0]).toBe(ResponseCodes.NoMoreMessages);
});
it('replies to an unsupported command with Err(UnsupportedCmd)', async () => {
const payload = await client.request([0x7f]); // not a Phase-0 command
expect(payload[0]).toBe(ResponseCodes.Err);
expect(payload[1]).toBe(Constants.ErrorCodes.UnsupportedCmd);
});
it('forwards SendChannelTxtMsg to the node and replies Ok (not Sent)', async () => {
// The app's sendChannelTextMessage awaits Ok(0), not Sent(6).
// [code=3][txtType=0][channelIdx=1][senderTimestamp:u32=0][text]
const frame = [CommandCodes.SendChannelTxtMsg, 0, 1, 0, 0, 0, 0, ...Buffer.from('hi chan', 'utf8')];
const payload = await client.request(frame);
expect(payload[0]).toBe(ResponseCodes.Ok);
expect(manager.sendMessageMock).toHaveBeenCalledWith('hi chan', undefined, 1);
});
it('forwards SendTxtMsg as a DM after resolving the contact prefix, replies Sent with the real ack CRC (#3869)', async () => {
manager.sendMessageWithResultMock.mockResolvedValueOnce({ ok: true, expectedAckCrc: 0xdeadbeef, estTimeout: 9000 });
const prefix = Buffer.from('b1'.repeat(6), 'hex'); // first 6 bytes of the sample contact
// [code=2][txtType=0][attempt=0][senderTimestamp:u32=0][prefix:6][text]
const frame = [CommandCodes.SendTxtMsg, 0, 0, 0, 0, 0, 0, ...prefix, ...Buffer.from('hi dm', 'utf8')];
const payload = await client.request(frame);
expect(payload[0]).toBe(ResponseCodes.Sent);
// The Sent response must carry the firmware's real ack CRC so the app can
// correlate the later SendConfirmed push (not the old hardcoded 0).
expect(Buffer.from(payload).readUInt32LE(2)).toBe(0xdeadbeef);
expect(manager.sendMessageWithResultMock).toHaveBeenCalledWith('hi dm', 'b1'.repeat(32), undefined);
});
it('replies Err(NotFound) for a DM to an unknown contact prefix', async () => {
const prefix = Buffer.from('ff'.repeat(6), 'hex'); // no matching contact
const frame = [CommandCodes.SendTxtMsg, 0, 0, 0, 0, 0, 0, ...prefix, ...Buffer.from('x', 'utf8')];
const payload = await client.request(frame);
expect(payload[0]).toBe(ResponseCodes.Err);
expect(payload[1]).toBe(Constants.ErrorCodes.NotFound);
expect(manager.sendMessageMock).not.toHaveBeenCalled();
});
it('replies Err when the node rejects the channel send', async () => {
manager.sendMessageMock.mockResolvedValueOnce(false);
const frame = [CommandCodes.SendChannelTxtMsg, 0, 0, 0, 0, 0, 0, ...Buffer.from('nope', 'utf8')];
const payload = await client.request(frame);
expect(payload[0]).toBe(ResponseCodes.Err);
});
it('counts connected clients', () => {
expect(server.getClientCount()).toBe(1);
});
it('pushes SendConfirmed(0x82) to the originating client when its DM is acked (#3869)', async () => {
manager.sendMessageWithResultMock.mockResolvedValueOnce({ ok: true, expectedAckCrc: 0x1234, estTimeout: 9000 });
const prefix = Buffer.from('b1'.repeat(6), 'hex');
const frame = [CommandCodes.SendTxtMsg, 0, 0, 0, 0, 0, 0, ...prefix, ...Buffer.from('hi dm', 'utf8')];
expect((await client.request(frame))[0]).toBe(ResponseCodes.Sent);
// The mesh acks the DM → the server pushes an unsolicited SendConfirmed.
const pushP = client.expectFrames(1);
manager.emitSendConfirmed({ ackCode: 0x1234, roundTripMs: 1500 });
const [push] = await pushP;
expect(push[0]).toBe(0x82); // PushCodes.SendConfirmed
expect(Buffer.from(push).readUInt32LE(1)).toBe(0x1234); // ack CRC matches the Sent response
expect(Buffer.from(push).readUInt32LE(5)).toBe(1500); // round-trip ms
});
it('ignores a send_confirmed whose CRC no connected client is awaiting (#3869)', async () => {
let pushed = false;
void client.expectFrames(1).then(() => { pushed = true; });
manager.emitSendConfirmed({ ackCode: 0x9999, roundTripMs: 10 }); // never sent by this client
await new Promise((r) => setTimeout(r, 40));
expect(pushed).toBe(false);
});
it('bridges a raw OTA packet to the client as a LogRxData(0x88) push (#3963)', async () => {
const pushP = client.expectFrames(1);
manager.emitOtaPacket({ snr: -7.25, rssi: -95, raw_hex: '0102030405aabbccddeeff' });
const [push] = await pushP;
expect(push[0]).toBe(0x88); // PushCodes.LogRxData
expect(Buffer.from(push).readInt8(1)).toBe(-29); // snr×4 (−7.25 → −29)
expect(Buffer.from(push).readInt8(2)).toBe(-95); // rssi dBm
// Bytes 3..end are the whole OTA frame, forwarded verbatim.
expect(Buffer.from(push).subarray(3).toString('hex')).toBe('0102030405aabbccddeeff');
});
it('does not push a LogRxData frame for an OTA packet with no raw bytes (#3963)', async () => {
let pushed = false;
void client.expectFrames(1).then(() => { pushed = true; });
manager.emitOtaPacket({ snr: 5, rssi: -80, raw_hex: null });
manager.emitOtaPacket({ snr: 5, rssi: -80, raw_hex: '' });
await new Promise((r) => setTimeout(r, 40));
expect(pushed).toBe(false);
});
it('forwards the real hop count (pathLen) on an incoming channel message instead of "direct" (#3871)', () => {
const frame = (server as unknown as { encodeIncomingMessage(m: MeshCoreMessage): Buffer }).encodeIncomingMessage({
id: 'm1', fromPublicKey: 'channel-2', fromName: 'Alice', text: 'hi', timestamp: Date.now(), pathLen: 3,
} as MeshCoreMessage);
// ChannelMsgRecv frame: [code][channelIdx][pathLen][txtType][ts:4][text]
expect(frame[0]).toBe(ResponseCodes.ChannelMsgRecv);
expect(frame[1]).toBe(2); // channelIdx
expect(frame[2]).toBe(3); // real pathLen (was hardcoded 0xff before #3871)
});
it('falls back to 0xff (direct) when an incoming message has no pathLen (#3871)', () => {
const frame = (server as unknown as { encodeIncomingMessage(m: MeshCoreMessage): Buffer }).encodeIncomingMessage({
id: 'm2', fromPublicKey: 'channel-0', text: 'x', timestamp: Date.now(),
} as MeshCoreMessage);
expect(frame[2]).toBe(0xff);
});
});
describe('MeshCoreVirtualNodeServer — local node not ready', () => {
it('replies to AppStart with Err(BadState) when no local node', async () => {
const server = new MeshCoreVirtualNodeServer({
port: 0,
manager: makeManager({ getLocalNode: () => null, isConnected: () => false }),
});
await server.start();
const client = new TestClient();
await client.connect(server.getListeningPort()!);
const payload = await client.request([CommandCodes.AppStart, 1, 0, 0, 0, 0, 0, 0]);
expect(payload[0]).toBe(ResponseCodes.Err);
expect(payload[1]).toBe(Constants.ErrorCodes.BadState);
client.close();
await server.stop();
});
});
// ─────────────── config-command forwarding (issue #3904) ───────────────
// The VN forwards config-mutating companion commands to the real node via the
// manager's typed setters, gated on allowAdminCommands. Before this, every such
// command fell through to Err(UnsupportedCmd) unconditionally.
const toNums = (b: Buffer): number[] => Array.from(b);
function radioParamsFrame(freqKhz: number, bwHz: number, sf: number, cr: number): number[] {
const b = Buffer.alloc(11);
b[0] = CommandCodes.SetRadioParams;
b.writeUInt32LE(freqKhz, 1);
b.writeUInt32LE(bwHz, 5);
b[9] = sf;
b[10] = cr;
return toNums(b);
}
function latLonFrame(latDeg: number, lonDeg: number): number[] {
const b = Buffer.alloc(9);
b[0] = CommandCodes.SetAdvertLatLon;
b.writeInt32LE(degreesToFixed(latDeg), 1);
b.writeInt32LE(degreesToFixed(lonDeg), 5);
return toNums(b);
}
function setChannelFrame(idx: number, name: string, secret: Buffer): number[] {
const b = Buffer.alloc(50);
b[0] = CommandCodes.SetChannel;
b[1] = idx;
b.write(name, 2, 31, 'utf8'); // cstring(32), leave final byte null
secret.copy(b, 34, 0, 16);
return toNums(b);
}
const nameFrame = (name: string): number[] => [CommandCodes.SetAdvertName, ...Buffer.from(name, 'utf8')];
function otherParamsFrame(manualAdd: number, base: number, loc: number, env: number, advLoc: number): number[] {
const packed = (base & 0b11) | ((loc & 0b11) << 2) | ((env & 0b11) << 4);
return [CommandCodes.SetOtherParams, manualAdd, packed, advLoc];
}
describe('MeshCoreVirtualNodeServer — config-command forwarding (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
async function startWith(allowAdminCommands: boolean): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => {
client?.close();
await server?.stop();
});
it('forwards SetAdvertName to manager.setName and replies Ok', async () => {
await startWith(true);
const res = await client.request(nameFrame('Rover'));
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.setNameMock).toHaveBeenCalledWith('Rover');
});
it('forwards SetRadioParams in manager units (MHz / kHz) and replies Ok', async () => {
await startWith(true);
const res = await client.request(radioParamsFrame(917375, 250000, 11, 5));
expect(res[0]).toBe(ResponseCodes.Ok);
const [freq, bw, sf, cr] = manager.setRadioMock.mock.calls[0];
expect(freq).toBeCloseTo(917.375, 6);
expect(bw).toBeCloseTo(250, 6);
expect(sf).toBe(11);
expect(cr).toBe(5);
});
it('forwards SetTxPower and replies Ok', async () => {
await startWith(true);
const res = await client.request([CommandCodes.SetTxPower, 20]);
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.setTxPowerMock).toHaveBeenCalledWith(20);
});
it('forwards SetAdvertLatLon as decimal degrees and replies Ok', async () => {
await startWith(true);
const res = await client.request(latLonFrame(29.7604, -95.3698));
expect(res[0]).toBe(ResponseCodes.Ok);
const [lat, lon] = manager.setCoordsMock.mock.calls[0];
expect(lat).toBeCloseTo(29.7604, 5);
expect(lon).toBeCloseTo(-95.3698, 5);
});
it('forwards SetChannel (idx, name, hex secret, no scope) and replies Ok', async () => {
await startWith(true);
const secret = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex');
const res = await client.request(setChannelFrame(1, 'gauntlet', secret));
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.setChannelMock).toHaveBeenCalledWith(1, 'gauntlet', '000102030405060708090a0b0c0d0e0f', undefined);
});
it('forwards SetOtherParams (unpacked telemetry modes) and replies Ok', async () => {
await startWith(true);
const res = await client.request(otherParamsFrame(1, 2, 1, 2, 1));
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.setOtherParamsMock).toHaveBeenCalledWith({
manualAddContacts: 1,
telemetryModeBase: 2,
telemetryModeLoc: 1,
telemetryModeEnv: 2,
advLocPolicy: 1,
});
});
it('blocks config commands with Err(UnsupportedCmd) when allowAdminCommands is off, without touching the node', async () => {
await startWith(false);
const res = await client.request(nameFrame('Rover'));
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.UnsupportedCmd);
expect(manager.setNameMock).not.toHaveBeenCalled();
});
it('replies Err(BadState) when the node rejects the change (manager returns false)', async () => {
await startWith(true);
manager.setTxPowerMock.mockResolvedValueOnce(false);
const res = await client.request([CommandCodes.SetTxPower, 20]);
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.BadState);
});
it('replies Err(BadState) when the manager throws', async () => {
await startWith(true);
manager.setRadioMock.mockRejectedValueOnce(new Error('invalid radio'));
const res = await client.request(radioParamsFrame(917375, 250000, 11, 5));
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.BadState);
});
it('replies Err(IllegalArg) on a malformed config payload, without calling the manager', async () => {
await startWith(true);
const res = await client.request([CommandCodes.SetRadioParams, 1, 2]); // too short
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.IllegalArg);
expect(manager.setRadioMock).not.toHaveBeenCalled();
});
});
// SendSelfAdvert(7) is a normal broadcast operation (like messaging), NOT an
// admin/config mutation — a real node accepts it unconditionally, so the VN
// forwards it regardless of allowAdminCommands (issue #3904 follow-up: the app
// reported "Adverts to sending" failing with Err(UnsupportedCmd)).
describe('MeshCoreVirtualNodeServer — SendSelfAdvert forwarding (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
async function startWith(allowAdminCommands: boolean): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => {
client?.close();
await server?.stop();
});
// [code, type] — type 1 = flood; the manager always floods so the byte is ignored.
const advertFrame: number[] = [CommandCodes.SendSelfAdvert, 1];
it('forwards SendSelfAdvert to manager.sendAdvert and replies Ok', async () => {
await startWith(true);
const res = await client.request(advertFrame);
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.sendAdvertMock).toHaveBeenCalledTimes(1);
});
it('forwards SendSelfAdvert even when allowAdminCommands is off (not an admin op)', async () => {
await startWith(false);
const res = await client.request(advertFrame);
expect(res[0]).toBe(ResponseCodes.Ok);
expect(manager.sendAdvertMock).toHaveBeenCalledTimes(1);
});
it('replies Err(BadState) when the node fails to send the advert', async () => {
await startWith(true);
manager.sendAdvertMock.mockResolvedValueOnce(false);
const res = await client.request(advertFrame);
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.BadState);
});
it('replies Err(BadState) when manager.sendAdvert throws', async () => {
await startWith(true);
manager.sendAdvertMock.mockRejectedValueOnce(new Error('radio busy'));
const res = await client.request(advertFrame);
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.BadState);
});
});
// SendLogin(26) relays a remote-node login (issue #3904). The app's contract is
// Sent → LoginSuccess push correlated by the remote's 6-byte pubkey prefix. Login
// is a normal unlock step, so it is NOT gated on allowAdminCommands.
describe('MeshCoreVirtualNodeServer — SendLogin relay (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
const REMOTE_KEY = 'b1'.repeat(32); // 32 bytes → 64 hex chars
const REMOTE_KEY_BYTES = Buffer.from(REMOTE_KEY, 'hex');
function loginFrame(publicKeyHex: string, password: string): number[] {
return [CommandCodes.SendLogin, ...Buffer.from(publicKeyHex, 'hex'), ...Buffer.from(password, 'utf8')];
}
async function startWith(allowAdminCommands: boolean): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => {
client?.close();
await server?.stop();
});
it('replies Sent then pushes LoginSuccess with the remote key prefix on success', async () => {
await startWith(false); // ungated
const frames = client.expectFrames(2);
client.send(loginFrame(REMOTE_KEY, 'hunter2'));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
expect(push[0]).toBe(PushCodes.LoginSuccess);
// [0x85][reserved:1][pubKeyPrefix:6]
expect(push.subarray(2, 8)).toEqual(REMOTE_KEY_BYTES.subarray(0, 6));
expect(manager.loginToNodeMock).toHaveBeenCalledWith(REMOTE_KEY, 'hunter2');
});
it('accepts an empty (guest) password', async () => {
await startWith(false);
const frames = client.expectFrames(2);
client.send(loginFrame(REMOTE_KEY, ''));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
expect(push[0]).toBe(PushCodes.LoginSuccess);
expect(manager.loginToNodeMock).toHaveBeenCalledWith(REMOTE_KEY, '');
});
it('replies Sent but pushes nothing when the login fails (app times out on its own)', async () => {
await startWith(true);
manager.loginToNodeMock.mockResolvedValueOnce(false);
const sent = await client.request(loginFrame(REMOTE_KEY, 'bad'));
expect(sent[0]).toBe(ResponseCodes.Sent);
// Give the (resolved-false) login a tick; assert no second frame arrived.
const second = await Promise.race([
client.expectFrames(1).then((f) => f[0]),
new Promise<null>((r) => setTimeout(() => r(null), 100)),
]);
expect(second).toBeNull();
});
it('replies Err(IllegalArg) on a short SendLogin payload, without logging in', async () => {
await startWith(true);
const res = await client.request([CommandCodes.SendLogin, 1, 2, 3]); // < 33 bytes
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.IllegalArg);
expect(manager.loginToNodeMock).not.toHaveBeenCalled();
});
});
// SendTracePath(36): reply Sent, then push TraceData echoing the app's own tag
// and path with the measured SNRs (#3904).
describe('MeshCoreVirtualNodeServer — SendTracePath relay (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
async function start(): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands: false, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => { client?.close(); await server?.stop(); });
// [36][tag:u32LE][auth:u32LE][flags:u8][path…]
function traceFrame(tag: number, auth: number, path: number[]): number[] {
const head = Buffer.alloc(8); // tag:u32 + auth:u32
head.writeUInt32LE(tag >>> 0, 0);
head.writeUInt32LE(auth >>> 0, 4);
return [CommandCodes.SendTracePath, ...head, 0 /* flags */, ...path];
}
it('replies Sent (carrying the tag) then pushes TraceData with the app tag/path + SNRs', async () => {
await start();
const frames = client.expectFrames(2);
client.send(traceFrame(0xdeadbeef, 0, [0xa3, 0x7f]));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
expect(sent.readUInt32LE(2)).toBe(0xdeadbeef); // expectedAckCrc echoes the tag
// [0x89][reserved][pathLen][flags][tag:u32][auth:u32][hashes:pathLen][snrs:pathLen][lastSnr:i8]
expect(push[0]).toBe(PushCodes.TraceData);
expect(push[2]).toBe(2); // pathLen
expect(push.readUInt32LE(4)).toBe(0xdeadbeef); // tag echoed
expect([push[12], push[13]]).toEqual([0xa3, 0x7f]); // pathHashes = app path
expect([push[14], push[15]]).toEqual([8, 12]); // pathSnrs from manager
expect(push.readInt8(16)).toBe(22); // lastSnr 5.5 dB → 5.5*4
expect(manager.tracePathRawMock).toHaveBeenCalledWith(Buffer.from([0xa3, 0x7f]));
});
it('replies Sent but pushes nothing when the trace returns null', async () => {
await start();
manager.tracePathRawMock.mockResolvedValueOnce(null);
const sent = await client.request(traceFrame(1, 0, [0x01]));
expect(sent[0]).toBe(ResponseCodes.Sent);
const second = await Promise.race([
client.expectFrames(1).then((f) => f[0]),
new Promise<null>((r) => setTimeout(() => r(null), 100)),
]);
expect(second).toBeNull();
});
it('replies Err(IllegalArg) on a short SendTracePath payload', async () => {
await start();
const res = await client.request([CommandCodes.SendTracePath, 1, 2]); // too short
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.IllegalArg);
expect(manager.tracePathRawMock).not.toHaveBeenCalled();
});
});
// SendTelemetryReq(39): reply Sent, then push TelemetryResponse with the remote
// key prefix + raw LPP bytes (#3904).
describe('MeshCoreVirtualNodeServer — SendTelemetryReq relay (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
const REMOTE_KEY = 'c4'.repeat(32);
const REMOTE_KEY_BYTES = Buffer.from(REMOTE_KEY, 'hex');
async function start(): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands: false, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => { client?.close(); await server?.stop(); });
// [39][reserved:3][publicKey:32]
function telemetryFrame(publicKeyHex: string): number[] {
return [CommandCodes.SendTelemetryReq, 0, 0, 0, ...Buffer.from(publicKeyHex, 'hex')];
}
it('replies Sent then pushes TelemetryResponse with key prefix + raw LPP', async () => {
await start();
const frames = client.expectFrames(2);
client.send(telemetryFrame(REMOTE_KEY));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
// [0x8B][reserved:1][pubKeyPrefix:6][lpp…]
expect(push[0]).toBe(PushCodes.TelemetryResponse);
expect(push.subarray(2, 8)).toEqual(REMOTE_KEY_BYTES.subarray(0, 6));
expect(push.subarray(8)).toEqual(Buffer.from([0x01, 0x67, 0x00, 0xdc])); // raw LPP from manager
expect(manager.requestRemoteTelemetryRawMock).toHaveBeenCalledWith(REMOTE_KEY);
});
it('replies Sent but pushes nothing when telemetry returns null', async () => {
await start();
manager.requestRemoteTelemetryRawMock.mockResolvedValueOnce(null);
const sent = await client.request(telemetryFrame(REMOTE_KEY));
expect(sent[0]).toBe(ResponseCodes.Sent);
const second = await Promise.race([
client.expectFrames(1).then((f) => f[0]),
new Promise<null>((r) => setTimeout(() => r(null), 100)),
]);
expect(second).toBeNull();
});
it('replies Err(IllegalArg) on a short SendTelemetryReq payload', async () => {
await start();
const res = await client.request([CommandCodes.SendTelemetryReq, 0, 0, 0, 1, 2]); // too short
expect(res[0]).toBe(ResponseCodes.Err);
expect(res[1]).toBe(ErrorCodes.IllegalArg);
expect(manager.requestRemoteTelemetryRawMock).not.toHaveBeenCalled();
});
});
// SendStatusReq(27): reply Sent, then push StatusResponse(0x87) with the remote
// key prefix + the 48-byte RepeaterStats blob re-encoded from the manager's
// parsed status (#3904). Read-only follow-up to login → not gated.
describe('MeshCoreVirtualNodeServer — SendStatusReq relay (#3904)', () => {
let server: MeshCoreVirtualNodeServer;
let client: TestClient;
let manager: FakeManager;
const REMOTE_KEY = 'd2'.repeat(32);
const REMOTE_KEY_BYTES = Buffer.from(REMOTE_KEY, 'hex');
async function startWith(allowAdminCommands: boolean): Promise<void> {
manager = new FakeManager();
server = new MeshCoreVirtualNodeServer({ port: 0, manager, allowAdminCommands, databaseService: CHANNELS_DB });
await server.start();
client = new TestClient();
await client.connect(server.getListeningPort()!);
}
afterEach(async () => { client?.close(); await server?.stop(); });
// [27][publicKey:32] — no reserved bytes (unlike SendTelemetryReq).
function statusFrame(publicKeyHex: string): number[] {
return [CommandCodes.SendStatusReq, ...Buffer.from(publicKeyHex, 'hex')];
}
it('replies Sent then pushes StatusResponse with key prefix + the 48-byte stats blob', async () => {
await startWith(false); // ungated
const frames = client.expectFrames(2);
client.send(statusFrame(REMOTE_KEY));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
// [0x87][reserved:1][pubKeyPrefix:6][statusData:48]
expect(push[0]).toBe(PushCodes.StatusResponse);
expect(push[1]).toBe(0); // reserved
expect(push.subarray(2, 8)).toEqual(REMOTE_KEY_BYTES.subarray(0, 6));
expect(push.length).toBe(1 + 1 + 6 + 48);
// Spot-check the little-endian RepeaterStats layout (offsets relative to
// the statusData start at byte 8).
const s = push.subarray(8);
expect(s.readUInt16LE(0)).toBe(4100); // batt_milli_volts
expect(s.readUInt16LE(2)).toBe(3); // curr_tx_queue_len
expect(s.readInt16LE(4)).toBe(-120); // noise_floor
expect(s.readInt16LE(6)).toBe(-85); // last_rssi
expect(s.readUInt32LE(8)).toBe(1000); // n_packets_recv
expect(s.readUInt32LE(12)).toBe(900); // n_packets_sent
expect(s.readUInt32LE(16)).toBe(500); // total_air_time_secs
expect(s.readUInt32LE(20)).toBe(86400); // total_up_time_secs
expect(s.readUInt16LE(40)).toBe(5); // err_events
expect(s.readInt16LE(42)).toBe(24); // last_snr
expect(s.readUInt16LE(44)).toBe(6); // n_direct_dups
expect(s.readUInt16LE(46)).toBe(7); // n_flood_dups
expect(manager.requestNodeStatusMock).toHaveBeenCalledWith(REMOTE_KEY);
});
it('relays status even when allowAdminCommands is off (read-only follow-up to login)', async () => {
await startWith(true);
const frames = client.expectFrames(2);
client.send(statusFrame(REMOTE_KEY));
const [sent, push] = await frames;
expect(sent[0]).toBe(ResponseCodes.Sent);
expect(push[0]).toBe(PushCodes.StatusResponse);
});
it('replies Sent but pushes nothing when the status request returns null', async () => {
await startWith(false);
manager.requestNodeStatusMock.mockResolvedValueOnce(null);
const sent = await client.request(statusFrame(REMOTE_KEY));
expect(sent[0]).toBe(ResponseCodes.Sent);
const second = await Promise.race([
client.expectFrames(1).then((f) => f[0]),