-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-packets.js
More file actions
1043 lines (932 loc) · 35.7 KB
/
test-packets.js
File metadata and controls
1043 lines (932 loc) · 35.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
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
/* Unit tests for packets.js functions (tested via VM sandbox) */
'use strict';
const vm = require('vm');
const fs = require('fs');
const assert = require('assert');
let passed = 0, failed = 0;
function test(name, fn) {
try {
fn();
passed++;
console.log(` ✅ ${name}`);
} catch (e) {
failed++;
console.log(` ❌ ${name}: ${e.message}`);
}
}
// Build a browser-like sandbox with all deps packets.js needs
function makeSandbox() {
const registeredPages = {};
const ctx = {
window: {
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => {},
innerWidth: 1200,
PacketFilter: null,
},
document: {
readyState: 'complete',
createElement: (tag) => ({
tagName: tag.toUpperCase(), id: '', textContent: '', innerHTML: '',
className: '', style: {}, appendChild: () => {}, setAttribute: () => {},
addEventListener: () => {}, querySelectorAll: () => [], querySelector: () => null,
classList: { add: () => {}, remove: () => {}, contains: () => false },
}),
head: { appendChild: () => {} },
getElementById: () => null,
addEventListener: () => {},
removeEventListener: () => {},
querySelectorAll: () => [],
querySelector: () => null,
body: { appendChild: () => {} },
},
console,
Date,
Infinity,
Math,
Array,
Object,
String,
Number,
JSON,
RegExp,
Error,
TypeError,
RangeError,
parseInt,
parseFloat,
isNaN,
isFinite,
encodeURIComponent,
decodeURIComponent,
setTimeout: () => {},
clearTimeout: () => {},
setInterval: () => {},
clearInterval: () => {},
fetch: () => Promise.resolve({ ok: true, json: () => Promise.resolve({}) }),
performance: { now: () => Date.now() },
localStorage: (() => {
const store = {};
return {
getItem: k => store[k] || null,
setItem: (k, v) => { store[k] = String(v); },
removeItem: k => { delete store[k]; },
};
})(),
location: { hash: '' },
history: { replaceState: () => {} },
CustomEvent: class CustomEvent {},
Map,
Set,
Promise,
URLSearchParams,
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => {},
requestAnimationFrame: (cb) => setTimeout(cb, 0),
_registeredPages: registeredPages,
// Stub global functions packets.js depends on
registerPage: (name, handler) => { registeredPages[name] = handler; },
};
vm.createContext(ctx);
return ctx;
}
function loadInCtx(ctx, file) {
vm.runInContext(fs.readFileSync(file, 'utf8'), ctx, { filename: file });
for (const k of Object.keys(ctx.window)) {
ctx[k] = ctx.window[k];
}
}
function loadPacketsSandbox() {
const ctx = makeSandbox();
// Load dependencies first
loadInCtx(ctx, 'public/roles.js');
loadInCtx(ctx, 'public/app.js');
loadInCtx(ctx, 'public/packet-helpers.js');
// HopDisplay stub (simpler than loading real file which may have DOM deps)
vm.runInContext(`
window.HopDisplay = {
renderHop: function(h, entry, opts) {
if (entry && entry.name) return '<span class="hop-named">' + entry.name + '</span>';
return '<span class="hop-hex">' + h + '</span>';
},
_showFromBtn: function() {}
};
`, ctx);
loadInCtx(ctx, 'public/packets.js');
return ctx;
}
// ===== TESTS =====
console.log('\n=== packets.js: typeName ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('typeName returns known type', () => {
assert.strictEqual(api.typeName(0), 'Request');
assert.strictEqual(api.typeName(4), 'Advert');
assert.strictEqual(api.typeName(5), 'Channel Msg');
});
test('typeName returns fallback for unknown', () => {
assert.strictEqual(api.typeName(99), 'Type 99');
assert.strictEqual(api.typeName(undefined), 'Type undefined');
});
}
console.log('\n=== packets.js: obsName ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('obsName returns dash for falsy id', () => {
assert.strictEqual(api.obsName(null), '—');
assert.strictEqual(api.obsName(''), '—');
assert.strictEqual(api.obsName(undefined), '—');
});
test('obsName returns id when not in observerMap', () => {
assert.strictEqual(api.obsName('unknown-id'), 'unknown-id');
});
}
console.log('\n=== packets.js: kv ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('kv produces correct HTML', () => {
const result = api.kv('Route', 'Direct');
assert(result.includes('byop-key'));
assert(result.includes('Route'));
assert(result.includes('Direct'));
assert(result.includes('byop-val'));
});
}
console.log('\n=== packets.js: sectionRow / fieldRow ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('sectionRow produces section HTML', () => {
const result = api.sectionRow('Header');
assert(result.includes('section-row'));
assert(result.includes('Header'));
assert(result.includes('colspan="4"'));
});
test('fieldRow produces field HTML', () => {
const result = api.fieldRow(0, 'Header Byte', '0xFF', 'some desc');
assert(result.includes('0'));
assert(result.includes('Header Byte'));
assert(result.includes('0xFF'));
assert(result.includes('some desc'));
assert(result.includes('mono'));
});
test('fieldRow handles empty description', () => {
const result = api.fieldRow(5, 'Test', 'val', '');
assert(result.includes('text-muted'));
});
}
console.log('\n=== packets.js: getDetailPreview ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('getDetailPreview returns empty for null/undefined', () => {
assert.strictEqual(api.getDetailPreview(null), '');
assert.strictEqual(api.getDetailPreview(undefined), '');
});
test('getDetailPreview handles CHAN type', () => {
const result = api.getDetailPreview({ type: 'CHAN', text: 'hello world', channel: 'general' });
assert(result.includes('💬'));
assert(result.includes('hello world'));
assert(result.includes('chan-tag'));
assert(result.includes('general'));
});
test('getDetailPreview truncates long CHAN text', () => {
const longText = 'x'.repeat(100);
const result = api.getDetailPreview({ type: 'CHAN', text: longText });
assert(result.includes('…'));
assert(!result.includes('x'.repeat(100)));
});
test('getDetailPreview handles ADVERT type', () => {
const result = api.getDetailPreview({
type: 'ADVERT', name: 'TestNode', pubKey: 'abc123',
flags: { repeater: true }
});
assert(result.includes('📡'));
assert(result.includes('TestNode'));
assert(result.includes('hop-link'));
});
test('getDetailPreview handles ADVERT room', () => {
const result = api.getDetailPreview({
type: 'ADVERT', name: 'RoomNode', pubKey: 'abc',
flags: { room: true }
});
assert(result.includes('🏠'));
});
test('getDetailPreview handles ADVERT sensor', () => {
const result = api.getDetailPreview({
type: 'ADVERT', name: 'Sensor1', pubKey: 'abc',
flags: { sensor: true }
});
assert(result.includes('🌡'));
});
test('getDetailPreview handles ADVERT companion (default)', () => {
const result = api.getDetailPreview({
type: 'ADVERT', name: 'Comp', pubKey: 'abc',
flags: {}
});
assert(result.includes('📻'));
});
test('getDetailPreview handles GRP_TXT with channelHash (no_key)', () => {
const result = api.getDetailPreview({
type: 'GRP_TXT', channelHash: 0xAB, decryptionStatus: 'no_key'
});
assert(result.includes('🔒'));
assert(result.includes('0xAB'));
assert(result.includes('no key'));
});
test('getDetailPreview handles GRP_TXT decryption_failed', () => {
const result = api.getDetailPreview({
type: 'GRP_TXT', channelHash: 5, decryptionStatus: 'decryption_failed'
});
assert(result.includes('decryption failed'));
});
test('getDetailPreview handles GRP_TXT with channelHashHex', () => {
const result = api.getDetailPreview({
type: 'GRP_TXT', channelHash: 0xFF, channelHashHex: 'FF'
});
assert(result.includes('0xFF'));
});
test('getDetailPreview handles TXT_MSG', () => {
const result = api.getDetailPreview({
type: 'TXT_MSG', srcHash: 'abcdef01', destHash: '12345678'
});
assert(result.includes('✉️'));
assert(result.includes('abcdef01'));
assert(result.includes('12345678'));
});
test('getDetailPreview handles PATH', () => {
const result = api.getDetailPreview({
type: 'PATH', srcHash: 'aabb', destHash: 'ccdd'
});
assert(result.includes('🔀'));
});
test('getDetailPreview handles REQ', () => {
const result = api.getDetailPreview({
type: 'REQ', srcHash: 'aa', destHash: 'bb'
});
assert(result.includes('🔒'));
assert(result.includes('aa'));
});
test('getDetailPreview handles RESPONSE', () => {
const result = api.getDetailPreview({
type: 'RESPONSE', srcHash: 'aa', destHash: 'bb'
});
assert(result.includes('🔒'));
});
test('getDetailPreview handles ANON_REQ', () => {
const result = api.getDetailPreview({
type: 'ANON_REQ', destHash: 'dd'
});
assert(result.includes('anon'));
assert(result.includes('dd'));
});
test('getDetailPreview handles text fallback', () => {
const result = api.getDetailPreview({ text: 'some message' });
assert(result.includes('some message'));
});
test('getDetailPreview truncates long text fallback', () => {
const result = api.getDetailPreview({ text: 'z'.repeat(100) });
assert(result.includes('…'));
});
test('getDetailPreview handles public_key fallback', () => {
const result = api.getDetailPreview({ public_key: 'abcdef1234567890abcdef' });
assert(result.includes('📡'));
assert(result.includes('abcdef1234567890'));
});
test('getDetailPreview returns empty for empty decoded', () => {
assert.strictEqual(api.getDetailPreview({}), '');
});
}
console.log('\n=== packets.js: getPathHopCount ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('getPathHopCount with valid path', () => {
assert.strictEqual(api.getPathHopCount({ path_json: '["a","b","c"]' }), 3);
});
test('getPathHopCount with empty path', () => {
assert.strictEqual(api.getPathHopCount({ path_json: '[]' }), 0);
});
test('getPathHopCount with null/missing', () => {
assert.strictEqual(api.getPathHopCount({}), 0);
assert.strictEqual(api.getPathHopCount({ path_json: null }), 0);
});
test('getPathHopCount with invalid JSON', () => {
assert.strictEqual(api.getPathHopCount({ path_json: 'not json' }), 0);
});
}
console.log('\n=== packets.js: sortGroupChildren ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('sortGroupChildren handles null/empty gracefully', () => {
api.sortGroupChildren(null);
api.sortGroupChildren({});
api.sortGroupChildren({ _children: [] });
// No throw
});
test('sortGroupChildren default sort groups by observer earliest-first', () => {
// Need to set obsSortMode — it reads from closure. Default is 'observer'.
const group = {
_children: [
{ observer_name: 'B', timestamp: '2024-01-01T02:00:00Z' },
{ observer_name: 'A', timestamp: '2024-01-01T01:00:00Z' },
{ observer_name: 'B', timestamp: '2024-01-01T01:30:00Z' },
]
};
api.sortGroupChildren(group);
// A has earliest timestamp, should be first
assert.strictEqual(group._children[0].observer_name, 'A');
// Then B entries
assert.strictEqual(group._children[1].observer_name, 'B');
assert.strictEqual(group._children[2].observer_name, 'B');
// B entries should be time-ascending within group
assert(group._children[1].timestamp < group._children[2].timestamp);
});
test('sortGroupChildren updates header from first child', () => {
const group = {
observer_id: 'old',
_children: [
{ observer_name: 'A', observer_id: 'new-id', timestamp: '2024-01-01T01:00:00Z', snr: 10, rssi: -50, path_json: '["x"]', direction: 'rx' },
]
};
api.sortGroupChildren(group);
assert.strictEqual(group.observer_id, 'new-id');
assert.strictEqual(group.snr, 10);
assert.strictEqual(group.rssi, -50);
assert.strictEqual(group.path_json, '["x"]');
assert.strictEqual(group.direction, 'rx');
});
}
console.log('\n=== packets.js: renderTimestampCell ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('renderTimestampCell produces HTML with timestamp-text', () => {
const result = api.renderTimestampCell('2024-01-15T10:30:00Z');
assert(result.includes('timestamp-text'));
});
test('renderTimestampCell handles null gracefully', () => {
const result = api.renderTimestampCell(null);
// Should not throw, produces some output
assert(typeof result === 'string');
});
}
console.log('\n=== packets.js: renderPath ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('renderPath returns dash for empty/null', () => {
assert.strictEqual(api.renderPath(null, null), '—');
assert.strictEqual(api.renderPath([], null), '—');
});
test('renderPath renders hops with arrows', () => {
const result = api.renderPath(['aa', 'bb'], null);
assert(result.includes('arrow'));
assert(result.includes('aa'));
assert(result.includes('bb'));
});
test('renderPath renders single hop without arrow', () => {
const result = api.renderPath(['cc'], null);
assert(result.includes('cc'));
assert(!result.includes('arrow'));
});
}
console.log('\n=== packets.js: renderDecodedPacket ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('renderDecodedPacket produces header section', () => {
const decoded = {
header: { routeType: 0, payloadType: 4, payloadVersion: 1 },
payload: { name: 'TestNode' },
path: { hops: [] }
};
const hex = 'aabbccdd';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('byop-decoded'));
assert(result.includes('Header'));
assert(result.includes('4 bytes'));
});
test('renderDecodedPacket renders path hops', () => {
const decoded = {
header: { routeType: 0, payloadType: 4 },
payload: {},
path: { hops: ['aa', 'bb'] }
};
const hex = 'aabbccdd';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('Path (2 hops)'));
assert(result.includes('aa'));
assert(result.includes('bb'));
});
test('renderDecodedPacket renders payload fields', () => {
const decoded = {
header: { routeType: 0, payloadType: 5 },
payload: { channel: 'general', text: 'hello' },
path: { hops: [] }
};
const hex = 'aabb';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('channel'));
assert(result.includes('general'));
assert(result.includes('hello'));
});
test('renderDecodedPacket renders nested objects as JSON', () => {
const decoded = {
header: { routeType: 0, payloadType: 0 },
payload: { flags: { repeater: true } },
path: { hops: [] }
};
const hex = 'aa';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('byop-pre'));
assert(result.includes('repeater'));
});
test('renderDecodedPacket skips null payload values', () => {
const decoded = {
header: { routeType: 0, payloadType: 0 },
payload: { a: null, b: undefined, c: 'visible' },
path: { hops: [] }
};
const hex = 'aa';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('visible'));
// null/undefined values should be skipped
const kvCount = (result.match(/byop-row/g) || []).length;
// Only 'c' should appear in payload (a and b are null/undefined), plus header fields
assert(kvCount >= 1);
});
test('renderDecodedPacket renders raw hex', () => {
const decoded = {
header: { routeType: 0, payloadType: 0 },
payload: {},
path: { hops: [] }
};
const hex = 'aabbcc';
const result = api.renderDecodedPacket(decoded, hex);
assert(result.includes('AA BB CC'));
assert(result.includes('byop-hex'));
});
}
console.log('\n=== packets.js: buildFieldTable ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('buildFieldTable produces table HTML', () => {
const pkt = { raw_hex: 'c0400102', route_type: 1, payload_type: 4 };
const decoded = { type: 'ADVERT', name: 'Node', pubKey: 'abc', flags: { type: 2, hasLocation: false, hasName: true, raw: 0x22 } };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('field-table'));
assert(result.includes('Header'));
assert(result.includes('Header Byte'));
assert(result.includes('Path Length'));
});
test('buildFieldTable handles transport codes (route_type 0)', () => {
const pkt = { raw_hex: 'c0400102030405060708', route_type: 0, payload_type: 0 };
const decoded = { destHash: 'aa', srcHash: 'bb', mac: 'cc', encryptedData: 'dd' };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Transport Codes'));
assert(result.includes('Next Hop'));
assert(result.includes('Last Hop'));
});
test('buildFieldTable renders path hops', () => {
const pkt = { raw_hex: 'c042aabb', route_type: 1, payload_type: 0 };
const decoded = { destHash: 'xx' };
const result = api.buildFieldTable(pkt, decoded, ['aa', 'bb'], []);
assert(result.includes('Path (2 hops)'));
assert(result.includes('Hop 0'));
assert(result.includes('Hop 1'));
});
test('buildFieldTable renders ADVERT payload', () => {
const pkt = { raw_hex: 'c040', route_type: 1, payload_type: 4 };
const decoded = {
type: 'ADVERT', pubKey: 'abc123', timestamp: 1234567890,
timestampISO: '2009-02-13T23:31:30Z', signature: 'sig',
name: 'TestNode',
flags: { type: 1, hasLocation: true, hasName: true, raw: 0x55 }
};
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Public Key'));
assert(result.includes('Timestamp'));
assert(result.includes('Signature'));
assert(result.includes('App Flags'));
assert(result.includes('Companion'));
assert(result.includes('Latitude'));
assert(result.includes('Node Name'));
});
test('buildFieldTable renders GRP_TXT payload', () => {
const pkt = { raw_hex: 'c040', route_type: 1, payload_type: 5 };
const decoded = { type: 'GRP_TXT', channelHash: 0xAB, mac: 'AABB', encryptedData: 'data', decryptionStatus: 'no_key' };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Channel Hash'));
assert(result.includes('MAC'));
assert(result.includes('Encrypted Data'));
});
test('buildFieldTable renders CHAN payload', () => {
const pkt = { raw_hex: 'c040', route_type: 1, payload_type: 5 };
const decoded = { type: 'CHAN', channel: 'general', sender: 'Alice', sender_timestamp: '12:00' };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Channel'));
assert(result.includes('general'));
assert(result.includes('Sender'));
assert(result.includes('Sender Time'));
});
test('buildFieldTable renders ACK payload', () => {
const pkt = { raw_hex: 'c040', route_type: 1, payload_type: 3 };
const decoded = { type: 'ACK', ackChecksum: 'DEADBEEF' };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Checksum'));
assert(result.includes('DEADBEEF'));
});
test('buildFieldTable renders destHash-based payload', () => {
const pkt = { raw_hex: 'c040', route_type: 1, payload_type: 2 };
const decoded = { destHash: 'DD', srcHash: 'SS', mac: 'MM', encryptedData: 'EE' };
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Dest Hash'));
assert(result.includes('Src Hash'));
});
test('buildFieldTable renders raw fallback for unknown payload', () => {
const pkt = { raw_hex: 'c040aabbccdd', route_type: 1, payload_type: 99 };
const decoded = {};
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('Raw'));
});
test('buildFieldTable hash_size calculation', () => {
// Path byte 0xC0 → bits 7-6 = 3 → hash_size = 4, but hash_count = 0
// Since #653: when hashCount == 0, shows "hash_count=0 (direct advert)" instead of hash_size
const pkt = { raw_hex: '00C0', route_type: 1, payload_type: 0 };
const decoded = {};
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('hash_count=0 (direct advert)'));
});
test('buildFieldTable hash_size shown when hash_count > 0', () => {
// Path byte 0xC1 → bits 7-6 = 3 → hash_size = 4, hash_count = 1
const pkt = { raw_hex: '00C1aabbccdd', route_type: 1, payload_type: 0 };
const decoded = {};
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('hash_size=4'));
});
test('buildFieldTable handles empty raw_hex', () => {
const pkt = { raw_hex: '', route_type: 1, payload_type: 0 };
const decoded = {};
const result = api.buildFieldTable(pkt, decoded, [], []);
assert(result.includes('field-table'));
assert(result.includes('0B') || result.includes('0 bytes') || result.includes('??'));
});
}
console.log('\n=== packets.js: _getRowCount ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('_getRowCount returns 1 for ungrouped', () => {
// _displayGrouped is internal, but when not grouped, should return 1
// Since we can't easily control _displayGrouped, test the function behavior
const result = api._getRowCount({ hash: 'abc', _children: [{ observer_id: '1' }] });
// Default _displayGrouped depends on initialization, but the function should not throw
assert(typeof result === 'number');
assert(result >= 1);
});
}
console.log('\n=== packets.js: buildFlatRowHtml ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('buildFlatRowHtml produces table row', () => {
const p = {
id: 1, hash: 'abc123', timestamp: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aabb', payload_type: 4,
route_type: 1, decoded_json: '{}', path_json: '[]'
};
const result = api.buildFlatRowHtml(p);
assert(result.includes('<tr'));
assert(result.includes('data-id="1"'));
assert(result.includes('data-hash="abc123"'));
});
test('buildFlatRowHtml calculates size from hex', () => {
const p = {
id: 2, hash: 'x', timestamp: '', observer_id: null,
raw_hex: 'aabbccdd', payload_type: 0, route_type: 0,
decoded_json: '{}', path_json: '[]'
};
const result = api.buildFlatRowHtml(p);
assert(result.includes('4B')); // 8 hex chars = 4 bytes
});
test('buildFlatRowHtml handles missing raw_hex', () => {
const p = {
id: 3, hash: 'y', timestamp: '', observer_id: null,
raw_hex: null, payload_type: 0, route_type: 0,
decoded_json: '{}', path_json: '[]'
};
const result = api.buildFlatRowHtml(p);
assert(result.includes('0B'));
});
test('buildFlatRowHtml emits data-entry-idx when provided', () => {
const p = {
id: 4, hash: 'z', timestamp: '', observer_id: null,
raw_hex: 'aabb', payload_type: 0, route_type: 0,
decoded_json: '{}', path_json: '[]'
};
const result = api.buildFlatRowHtml(p, 42);
assert(result.includes('data-entry-idx="42"'));
});
test('buildFlatRowHtml emits data-entry-idx=-1 by default', () => {
const p = {
id: 5, hash: 'w', timestamp: '', observer_id: null,
raw_hex: 'aabb', payload_type: 0, route_type: 0,
decoded_json: '{}', path_json: '[]'
};
const result = api.buildFlatRowHtml(p);
assert(result.includes('data-entry-idx="-1"'));
});
}
console.log('\n=== packets.js: buildGroupRowHtml ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('buildGroupRowHtml renders single-count group', () => {
const p = {
hash: 'abc', count: 1, latest: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aabb', payload_type: 4,
route_type: 1, decoded_json: '{}', path_json: '[]',
observation_count: 1, observer_count: 1
};
const result = api.buildGroupRowHtml(p);
assert(result.includes('<tr'));
assert(result.includes('data-hash="abc"'));
// Single count: no expand arrow, no group-header class
assert(!result.includes('group-header'));
});
test('buildGroupRowHtml renders multi-count group with expand arrow', () => {
const p = {
hash: 'xyz', count: 3, latest: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aabbcc', payload_type: 0,
route_type: 0, decoded_json: '{}', path_json: '[]',
observation_count: 3, observer_count: 2
};
const result = api.buildGroupRowHtml(p);
assert(result.includes('group-header'));
assert(result.includes('▶')); // collapsed arrow
});
test('buildGroupRowHtml shows observation count badge', () => {
const p = {
hash: 'obs', count: 1, latest: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aa', payload_type: 0,
route_type: 0, decoded_json: '{}', path_json: '[]',
observation_count: 5, observer_count: 1
};
const result = api.buildGroupRowHtml(p);
assert(result.includes('badge-obs'));
assert(result.includes('👁'));
assert(result.includes('5'));
});
test('buildGroupRowHtml emits data-entry-idx on header row', () => {
const p = {
hash: 'ei1', count: 1, latest: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aa', payload_type: 0,
route_type: 0, decoded_json: '{}', path_json: '[]',
observation_count: 1, observer_count: 1
};
const result = api.buildGroupRowHtml(p, 7);
assert(result.includes('data-entry-idx="7"'));
});
test('buildGroupRowHtml emits data-entry-idx on child rows', () => {
const ctx2 = loadPacketsSandbox();
const api2 = ctx2._packetsTestAPI;
// Simulate expandedHashes having this hash
// We can't easily toggle expandedHashes from outside, so test via the
// fact that children only render when isExpanded is true.
// For this test, just verify the header row has the attribute (child rows
// are conditional on expandedHashes which we can't set from tests).
const p = {
hash: 'ei2', count: 3, latest: '2024-01-01T00:00:00Z',
observer_id: null, raw_hex: 'aabb', payload_type: 0,
route_type: 0, decoded_json: '{}', path_json: '[]',
observation_count: 3, observer_count: 2,
_children: []
};
const result = api2.buildGroupRowHtml(p, 15);
assert(result.includes('data-entry-idx="15"'));
});
}
console.log('\n=== packets.js: page registration ===');
{
const ctx = loadPacketsSandbox();
// registerPage is defined in app.js and stores in its own `pages` closure.
// We verify via the navigateTo mechanism or by checking the pages object isn't empty.
// Since we can't easily access the closure, just verify the test API is exposed.
test('_packetsTestAPI is exposed on window', () => {
assert(ctx._packetsTestAPI);
assert(typeof ctx._packetsTestAPI.typeName === 'function');
assert(typeof ctx._packetsTestAPI.getDetailPreview === 'function');
assert(typeof ctx._packetsTestAPI.sortGroupChildren === 'function');
assert(typeof ctx._packetsTestAPI.buildFieldTable === 'function');
});
}
console.log('\n=== packets.js: _invalidateRowCounts / _refreshRowCountsIfDirty (#410) ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
test('_invalidateRowCounts and _refreshRowCountsIfDirty are exported', () => {
assert(typeof api._invalidateRowCounts === 'function');
assert(typeof api._refreshRowCountsIfDirty === 'function');
});
test('_invalidateRowCounts does not throw', () => {
api._invalidateRowCounts();
});
test('_refreshRowCountsIfDirty does not throw when no display packets', () => {
api._invalidateRowCounts();
api._refreshRowCountsIfDirty();
});
test('_cumulativeRowOffsets returns valid offsets after invalidation cycle', () => {
// Even with no display packets, should return valid array
const offsets = api._cumulativeRowOffsets();
assert(Array.isArray(offsets));
assert(offsets[0] === 0);
});
}
console.log('\n=== packets.js: buildPacketsParams ===');
{
const ctx = loadPacketsSandbox();
const api = ctx._packetsTestAPI;
assert(typeof api.buildPacketsParams === 'function', 'buildPacketsParams must be exported');
test('hash filter suppresses region — direct hash links work regardless of saved region', () => {
// This is the bug from URL https://analyzer.../#/packets?hash=178525e9f693aa7e
// when the user's saved RegionFilter excludes the packet's observer region.
// The hash is an exact identifier; ALL other filters must be ignored.
const p = api.buildPacketsParams({
filters: { hash: 'abc123' },
regionParam: 'SJC,SFO,OAK,MRY',
windowMin: 60,
groupByHash: false,
limit: 200,
});
assert.strictEqual(p.get('hash'), 'abc123');
assert.strictEqual(p.get('region'), null, 'region must NOT be set when hash is present');
assert.strictEqual(p.get('since'), null, 'since must NOT be set when hash is present');
});
test('hash filter suppresses ALL other filters — observer, node, channel too', () => {
const p = api.buildPacketsParams({
filters: { hash: 'h', node: 'n', observer: 'o', channel: 'c' },
regionParam: 'SJC',
windowMin: 60,
groupByHash: false,
limit: 200,
});
assert.strictEqual(p.get('hash'), 'h');
assert.strictEqual(p.get('node'), null);
assert.strictEqual(p.get('observer'), null);
assert.strictEqual(p.get('channel'), null);
assert.strictEqual(p.get('region'), null);
assert.strictEqual(p.get('since'), null);
});
test('hash filter suppresses region with default windowMin=0', () => {
const p = api.buildPacketsParams({
filters: { hash: 'deadbeef' },
regionParam: 'COA',
windowMin: 0,
groupByHash: false,
limit: 50,
});
assert.strictEqual(p.get('hash'), 'deadbeef');
assert.strictEqual(p.get('region'), null);
});
test('region applied normally when hash filter is absent', () => {
const p = api.buildPacketsParams({
filters: {},
regionParam: 'SJC,SFO',
windowMin: 60,
groupByHash: false,
limit: 200,
});
assert.strictEqual(p.get('region'), 'SJC,SFO', 'region must apply when no hash');
assert.strictEqual(p.get('hash'), null);
assert(p.get('since'), 'since must apply when no hash and windowMin>0');
});
test('observer/node/channel pass through normally when no hash', () => {
const p = api.buildPacketsParams({
filters: { observer: 'obs1', node: 'node1', channel: '#test' },
regionParam: '',
windowMin: 0,
groupByHash: false,
limit: 50,
});
assert.strictEqual(p.get('observer'), 'obs1');
assert.strictEqual(p.get('node'), 'node1');
assert.strictEqual(p.get('channel'), '#test');
});
test('region absent when regionParam empty — no spurious empty region= param', () => {
const p = api.buildPacketsParams({
filters: {},
regionParam: '',
windowMin: 0,
groupByHash: false,
limit: 50,
});
assert.strictEqual(p.get('region'), null);
});
test('groupByHash=true with hash sets groupByHash and omits expand', () => {
const p = api.buildPacketsParams({
filters: { hash: 'h' }, regionParam: '', windowMin: 0, groupByHash: true, limit: 50,
});
assert.strictEqual(p.get('groupByHash'), 'true');
assert.strictEqual(p.get('expand'), null);
assert.strictEqual(p.get('hash'), 'h');
});
test('groupByHash=false with hash sets expand=observations', () => {
const p = api.buildPacketsParams({
filters: { hash: 'h' }, regionParam: '', windowMin: 0, groupByHash: false, limit: 50,
});
assert.strictEqual(p.get('expand'), 'observations');
assert.strictEqual(p.get('groupByHash'), null);
assert.strictEqual(p.get('hash'), 'h');
});
test('groupByHash=false without hash sets expand=observations', () => {
const p = api.buildPacketsParams({
filters: {}, regionParam: '', windowMin: 0, groupByHash: false, limit: 50,
});
assert.strictEqual(p.get('expand'), 'observations');
assert.strictEqual(p.get('groupByHash'), null);
});
}
console.log('\n=== packets.js: scroll position preserved across renderTableRows (#431) ===');
{
// Build a richer sandbox with DOM elements that renderTableRows needs
const ctx = makeSandbox();
// Mock DOM elements needed by renderTableRows and renderVisibleRows
let pktLeftScrollTop = 500;
const pktBody = {
tagName: 'TBODY', id: 'pktBody', _innerHTML: '', children: [],
get innerHTML() { return this._innerHTML; },
set innerHTML(v) { this._innerHTML = v; pktLeftScrollTop = 0; }, // Simulate browser scroll reset on DOM rebuild
appendChild: () => {}, insertBefore: () => {}, removeChild: () => {},
querySelectorAll: () => [], querySelector: () => null,
style: {},
};
const pktLeft = {
tagName: 'DIV', id: 'pktLeft', className: '',
get scrollTop() { return pktLeftScrollTop; },
set scrollTop(v) { pktLeftScrollTop = v; },
clientHeight: 800,
offsetHeight: 800,
querySelector: (sel) => {
if (sel === 'thead') return { offsetHeight: 40 };
if (sel === '.count' || sel === '#pktLeft .count') return { textContent: '' };
return null;
},
querySelectorAll: () => [],
addEventListener: () => {},
removeEventListener: () => {},
style: {},
};
const origGetById = ctx.document.getElementById;
ctx.document.getElementById = (id) => {
if (id === 'pktBody') return pktBody;
if (id === 'pktLeft') return pktLeft;
if (id === 'fGroup') return { classList: { toggle: () => {}, add: () => {}, remove: () => {}, contains: () => false } };
if (id === 'packetFilterCount') return { style: {}, textContent: '' };
if (id === 'vscroll-top') return null;
if (id === 'vscroll-bottom') return null;
return null;
};