-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-session-manager.js
More file actions
1989 lines (1660 loc) · 62.9 KB
/
test-session-manager.js
File metadata and controls
1989 lines (1660 loc) · 62.9 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
'use strict';
/**
* Magic Session Manager - Test Suite
*
* Tests User API, Admin API, and Security (JWT invalidation) separately.
* Structured into phases with clear pass/fail reporting.
*
* Usage:
* node test-session-manager.js
* node test-session-manager.js --phase=security (run only security tests)
* node test-session-manager.js --phase=user (run only user tests)
* node test-session-manager.js --phase=admin (run only admin tests)
* node test-session-manager.js --phase=fixes (run only fix verification + false positive tests)
*
* Required ENV vars:
* TEST_USER_EMAIL, TEST_USER_PASSWORD, ADMIN_EMAIL, ADMIN_PASSWORD
*
* Optional ENV vars:
* STRAPI_URL (default: http://localhost:1337)
*/
// Load .env if available
try { require('dotenv').config({ path: '../../../.env' }); } catch (_) { /* ok */ }
// -------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------
const BASE_URL = process.env.STRAPI_URL || process.env.BASE_URL || 'http://localhost:1337';
const USER_CREDS = {
identifier: process.env.TEST_USER_EMAIL,
password: process.env.TEST_USER_PASSWORD,
};
const ADMIN_CREDS = {
email: process.env.ADMIN_EMAIL,
password: process.env.ADMIN_PASSWORD,
};
const USER_AGENTS = {
chromeWin: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
safariMac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',
iphoneSafari: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1',
firefoxWin: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0',
edgeWin: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
androidChrome:'Mozilla/5.0 (Linux; Android 13; SM-S911B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.43 Mobile Safari/537.36',
};
/** Rate-limit delay between logins (ms) */
const LOGIN_DELAY = 3000;
/** Delay between test phases (ms) */
const PHASE_DELAY = 5000;
// -------------------------------------------------------------------
// Console helpers (no emojis)
// -------------------------------------------------------------------
const C = {
reset: '\x1b[0m',
green: '\x1b[32m',
red: '\x1b[31m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
bold: '\x1b[1m',
dim: '\x1b[2m',
};
/** Prints colored text */
function print(msg, color = C.reset) { console.log(`${color}${msg}${C.reset}`); }
/** Prints a section header */
function header(title) {
print(`\n${'='.repeat(70)}`, C.cyan);
print(` ${title}`, `${C.cyan}${C.bold}`);
print(`${'='.repeat(70)}`, C.cyan);
}
/** Prints a phase header */
function phaseHeader(title) {
print(`\n${'#'.repeat(70)}`, C.magenta);
print(` ${title}`, `${C.magenta}${C.bold}`);
print(`${'#'.repeat(70)}\n`, C.magenta);
}
/** Async sleep */
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
/** Wait with visible countdown */
async function waitCountdown(seconds, reason) {
process.stdout.write(`${C.yellow} [WAIT] ${reason}: `);
for (let i = seconds; i > 0; i--) {
process.stdout.write(`${i}s `);
await sleep(1000);
}
console.log(`${C.green}GO${C.reset}`);
}
// -------------------------------------------------------------------
// Test runner
// -------------------------------------------------------------------
const results = { user: [], admin: [], security: [], fixes: [] };
/**
* Runs a single test and records the result
* @param {string} category - 'user' | 'admin' | 'security'
* @param {string} name - Human-readable test name
* @param {Function} fn - Async test function, must return true/false/null(skip)
*/
async function runTest(category, name, fn) {
header(name);
try {
const result = await fn();
if (result === true) {
print(` [PASS] ${name}`, C.green);
results[category].push({ name, status: 'pass' });
} else if (result === false) {
print(` [FAIL] ${name}`, C.red);
results[category].push({ name, status: 'fail' });
} else {
print(` [SKIP] ${name}`, C.yellow);
results[category].push({ name, status: 'skip' });
}
} catch (err) {
print(` [FAIL] ${name}: ${err.message}`, C.red);
results[category].push({ name, status: 'fail', error: err.message });
}
}
// -------------------------------------------------------------------
// HTTP helpers
// -------------------------------------------------------------------
/**
* Makes an authenticated API request
* @param {string} path - URL path (appended to BASE_URL)
* @param {object} opts - { method, body, token, userAgent, isAdmin }
* @returns {Promise<{ok: boolean, status: number, data: object}>}
*/
async function api(path, opts = {}) {
const { method = 'GET', body, token, userAgent } = opts;
/** @type {Record<string, string>} */
const headers = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
if (body) headers['Content-Type'] = 'application/json';
if (userAgent) headers['User-Agent'] = String(USER_AGENTS[userAgent] || userAgent);
const url = `${BASE_URL}${path}`;
const response = await fetch(url, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
const data = await response.json().catch(() => ({}));
return { ok: response.ok, status: response.status, data };
}
/**
* Login with retry on rate-limiting
* @param {object} creds - { identifier, password }
* @param {string} userAgent - Optional user agent key
* @param {number} maxRetries - Max retries on rate limit
* @returns {Promise<object|null>} { jwt, refreshToken, user } or null
*/
async function login(creds, userAgent = null, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const res = await api('/api/auth/local', {
method: 'POST',
body: creds,
userAgent,
});
if (res.ok && res.data.jwt) {
return res.data;
}
if (res.status === 429 && attempt < maxRetries) {
const wait = 30 + (attempt * 15);
await waitCountdown(wait, `Rate limited, retry ${attempt + 1}/${maxRetries}`);
continue;
}
print(` [INFO] Login failed: ${res.data?.error?.message || res.status}`, C.dim);
return null;
}
return null;
}
/**
* Login as Strapi admin
* @returns {Promise<string|null>} Admin JWT or null
*/
async function adminLogin() {
const res = await api('/admin/login', {
method: 'POST',
body: ADMIN_CREDS,
});
if (res.ok && res.data?.data?.token) {
return res.data.data.token;
}
print(` [INFO] Admin login failed: ${res.data?.error?.message || res.status}`, C.dim);
return null;
}
// -------------------------------------------------------------------
// Shared state
// -------------------------------------------------------------------
let userJwt = null;
let userRefreshToken = null;
let userDocumentId = null;
let adminJwt = null;
let testSessionId = null;
// -------------------------------------------------------------------
// USER API TESTS
// -------------------------------------------------------------------
/** Login and store JWT */
async function testUserLogin() {
const data = await login(USER_CREDS);
if (!data) return false;
userJwt = data.jwt;
userRefreshToken = data.refreshToken || null;
userDocumentId = data.user.documentId || null;
print(` [INFO] User: ${data.user.email} (documentId: ${userDocumentId})`, C.blue);
print(` [INFO] JWT: ${userJwt.substring(0, 40)}...`, C.blue);
if (userRefreshToken) print(` [INFO] Refresh token received`, C.blue);
return true;
}
/** Create sessions with multiple device User-Agents */
async function testMultiDeviceLogin() {
const devices = [['chromeWin', 'Chrome/Windows'], ['safariMac', 'Safari/macOS'], ['iphoneSafari', 'Safari/iPhone']];
let ok = 0;
for (const [key, label] of devices) {
const data = await login(USER_CREDS, key);
if (data) {
ok++;
print(` [OK] ${label}`, C.dim);
} else {
print(` [SKIP] ${label} (rate limited)`, C.yellow);
}
await sleep(LOGIN_DELAY);
}
print(` [INFO] Created ${ok}/${devices.length} device sessions`, C.blue);
return ok > 0;
}
/** Get own sessions via Content API */
async function testGetOwnSessions() {
const res = await api('/api/magic-sessionmanager/my-sessions', { token: userJwt });
if (!res.ok) return false;
const sessions = res.data.data;
const active = sessions.filter(s => s.isTrulyActive).length;
print(` [INFO] Total: ${sessions.length}, Active: ${active}`, C.blue);
if (sessions.length > 0) {
testSessionId = sessions[0].documentId;
print(` [INFO] Test session ID: ${testSessionId}`, C.blue);
}
return true;
}
/** Get current session info */
async function testGetCurrentSession() {
const res = await api('/api/magic-sessionmanager/current-session', { token: userJwt });
if (!res.ok) return false;
const session = res.data.data;
print(` [INFO] Device: ${session.deviceType}, Browser: ${session.browserName}, OS: ${session.osName}`, C.blue);
print(` [INFO] Is current: ${session.isCurrentSession}, Active: ${session.isTrulyActive}`, C.blue);
return session.isCurrentSession === true;
}
/** Logout via plugin endpoint */
async function testPluginLogout() {
const res = await api('/api/magic-sessionmanager/logout', { method: 'POST', token: userJwt });
if (!res.ok) return false;
print(` [INFO] ${res.data.message}`, C.blue);
return true;
}
/** Logout via standard /api/auth/logout */
async function testStandardLogout() {
// Need fresh login first
const data = await login(USER_CREDS);
if (!data) return false;
userJwt = data.jwt;
await sleep(500);
const res = await api('/api/auth/logout', {
method: 'POST',
token: data.jwt,
body: {},
});
if (res.ok) {
print(` [INFO] ${res.data.message || 'OK'}`, C.blue);
return true;
}
if (res.status === 404 || res.status === 401) {
print(` [INFO] Endpoint returned ${res.status} (may not be configured)`, C.yellow);
return null; // Skip
}
return false;
}
/** Test refresh token if available */
async function testRefreshToken() {
// Need fresh login
const data = await login(USER_CREDS);
if (!data) return false;
userJwt = data.jwt;
userRefreshToken = data.refreshToken;
await sleep(500);
if (!userRefreshToken) {
print(` [INFO] Refresh tokens not enabled - skipping`, C.yellow);
return null;
}
const res = await api('/api/auth/refresh', {
method: 'POST',
body: { refreshToken: userRefreshToken },
});
if (res.ok && res.data.jwt) {
userJwt = res.data.jwt;
userRefreshToken = res.data.refreshToken || userRefreshToken;
print(` [INFO] New JWT received`, C.blue);
return true;
}
if (res.status === 404) {
print(` [INFO] Refresh endpoint not found (404)`, C.yellow);
return null;
}
return false;
}
/** Terminate own session (not current) */
async function testTerminateOwnSession() {
// Need fresh login + session list
const data = await login(USER_CREDS);
if (!data) return false;
userJwt = data.jwt;
await sleep(500);
const sessRes = await api('/api/magic-sessionmanager/my-sessions', { token: userJwt });
if (!sessRes.ok || !sessRes.data.data?.length) return false;
// Find a non-current session to terminate
const other = sessRes.data.data.find(s => !s.isCurrentSession && s.documentId);
if (!other) {
print(` [INFO] No non-current session available to terminate`, C.yellow);
return null;
}
const res = await api(`/api/magic-sessionmanager/my-sessions/${other.documentId}`, {
method: 'DELETE',
token: userJwt,
});
if (res.ok) {
print(` [INFO] Terminated session ${other.documentId}`, C.blue);
return true;
}
return false;
}
// -------------------------------------------------------------------
// ADMIN API TESTS
// -------------------------------------------------------------------
/** Admin login */
async function testAdminLogin() {
adminJwt = await adminLogin();
if (!adminJwt) return false;
print(` [INFO] Admin JWT: ${adminJwt.substring(0, 40)}...`, C.blue);
return true;
}
/** Get all sessions (admin) */
async function testAdminGetAllSessions() {
const res = await api('/magic-sessionmanager/sessions', { token: adminJwt });
if (!res.ok) return false;
print(` [INFO] Total: ${res.data.meta.count}, Active: ${res.data.meta.active}, Inactive: ${res.data.meta.inactive}`, C.blue);
if (res.data.data.length > 0 && !testSessionId) {
testSessionId = res.data.data[0].documentId;
}
return true;
}
/** Get active sessions only (admin) */
async function testAdminGetActiveSessions() {
const res = await api('/magic-sessionmanager/sessions/active', { token: adminJwt });
if (!res.ok) return false;
print(` [INFO] Active sessions: ${res.data.meta.count}`, C.blue);
return true;
}
/** Get user sessions (admin) */
async function testAdminGetUserSessions() {
if (!userDocumentId) return null;
const res = await api(`/magic-sessionmanager/user/${userDocumentId}/sessions`, { token: adminJwt });
if (!res.ok) return false;
print(` [INFO] User sessions: ${res.data.meta.count}`, C.blue);
return true;
}
/** IP Geolocation (premium) */
async function testAdminGeolocation() {
const res = await api('/magic-sessionmanager/geolocation/8.8.8.8', { token: adminJwt });
if (res.ok && res.data.data) {
const geo = res.data.data;
print(` [INFO] 8.8.8.8 -> ${geo.city}, ${geo.country} (Score: ${geo.securityScore}/100)`, C.blue);
return true;
}
if (res.status === 403) {
print(` [INFO] Premium license required (403)`, C.yellow);
return null;
}
return false;
}
/** License status */
async function testAdminLicenseStatus() {
const res = await api('/magic-sessionmanager/license/status', { token: adminJwt });
if (!res.ok) return false;
print(` [INFO] Valid: ${res.data.valid}, Demo: ${res.data.demo}`, C.blue);
if (res.data.data?.features) {
const f = res.data.data.features;
print(` [INFO] Features: Premium=${f.premium}, Advanced=${f.advanced}`, C.blue);
}
return true;
}
/** Terminate a session (admin) */
async function testAdminTerminateSession() {
if (!testSessionId) {
print(` [INFO] No session ID available`, C.yellow);
return null;
}
const res = await api(`/magic-sessionmanager/sessions/${testSessionId}/terminate`, {
method: 'POST',
token: adminJwt,
});
if (res.ok) {
print(` [INFO] Session ${testSessionId} terminated`, C.blue);
return true;
}
return false;
}
/** Delete an inactive session permanently (admin) */
async function testAdminDeleteSession() {
const sessRes = await api('/magic-sessionmanager/sessions', { token: adminJwt });
if (!sessRes.ok) return false;
const inactive = sessRes.data.data.find(s => !s.isActive);
if (!inactive) {
print(` [INFO] No inactive session to delete`, C.yellow);
return null;
}
const res = await api(`/magic-sessionmanager/sessions/${inactive.documentId}`, {
method: 'DELETE',
token: adminJwt,
});
if (res.ok) {
print(` [INFO] Session ${inactive.documentId} permanently deleted`, C.blue);
return true;
}
return false;
}
/** Clean all inactive sessions (admin) */
async function testAdminCleanInactive() {
const res = await api('/magic-sessionmanager/sessions/clean-inactive', {
method: 'POST',
token: adminJwt,
});
if (res.ok) {
print(` [INFO] Cleaned ${res.data.deletedCount} inactive sessions`, C.blue);
return true;
}
return false;
}
/** Toggle user block (admin) - toggles and reverts */
async function testAdminToggleBlock() {
const userId = userDocumentId;
if (!userId) return null;
const res1 = await api(`/magic-sessionmanager/user/${userId}/toggle-block`, {
method: 'POST',
token: adminJwt,
});
if (!res1.ok) return false;
print(` [INFO] User ${res1.data.blocked ? 'blocked' : 'unblocked'}`, C.blue);
// Revert
await sleep(500);
await api(`/magic-sessionmanager/user/${userId}/toggle-block`, {
method: 'POST',
token: adminJwt,
});
print(` [INFO] Reverted to original state`, C.blue);
return true;
}
/** Terminate all sessions for a user (admin) */
async function testAdminTerminateAll() {
const userId = userDocumentId;
if (!userId) return null;
const res = await api(`/magic-sessionmanager/user/${userId}/terminate-all`, {
method: 'POST',
token: adminJwt,
});
if (res.ok) {
print(` [INFO] All sessions for user ${userId} terminated`, C.blue);
return true;
}
return false;
}
/** Settings: get and update */
async function testAdminSettings() {
// Get settings
const getRes = await api('/magic-sessionmanager/settings', { token: adminJwt });
if (!getRes.ok) return false;
const settings = getRes.data.settings;
print(` [INFO] Current inactivityTimeout: ${settings.inactivityTimeout}m`, C.blue);
// Update with same values (roundtrip test)
const putRes = await api('/magic-sessionmanager/settings', {
method: 'PUT',
token: adminJwt,
body: settings,
});
if (putRes.ok) {
print(` [INFO] Settings roundtrip successful`, C.blue);
return true;
}
return false;
}
// -------------------------------------------------------------------
// SECURITY TESTS
// -------------------------------------------------------------------
/**
* SECURITY 1: JWT blocked after single session terminate
* - Login -> verify JWT works -> terminate session -> verify JWT blocked
*/
async function testSecJwtBlockedAfterTerminate() {
// Step 1: Login
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
const docId = data.user.documentId;
await sleep(500);
// Step 2: Verify JWT works
const before = await api('/api/users/me', { token: jwt });
if (!before.ok) {
print(` [FAIL] JWT does not work before termination`, C.red);
return false;
}
print(` [INFO] BEFORE: /api/users/me -> ${before.status} (${before.data.email})`, C.blue);
await sleep(500);
// Step 3: Get session ID
const sessRes = await api('/api/magic-sessionmanager/my-sessions', { token: jwt });
if (!sessRes.ok || !sessRes.data.data?.length) return false;
const sessionId = sessRes.data.data[0].documentId;
await sleep(500);
// Step 4: Admin terminates the session
const termRes = await api(`/magic-sessionmanager/sessions/${sessionId}/terminate`, {
method: 'POST',
token: adminJwt,
});
if (!termRes.ok) return false;
print(` [INFO] Session ${sessionId} terminated by admin`, C.blue);
await sleep(500);
// Step 5: CRITICAL - JWT should be blocked
const after = await api('/api/users/me', { token: jwt });
if (after.status === 401 || after.status === 403) {
print(` [PASS] JWT correctly BLOCKED (${after.status})`, C.green);
return true;
}
if (after.ok) {
print(` [FAIL] JWT still works after termination - SECURITY VULNERABILITY`, C.red);
return false;
}
print(` [INFO] Unexpected status: ${after.status}`, C.yellow);
return null;
}
/**
* SECURITY 2: All JWTs blocked after terminate-all
* - Create 3 sessions -> terminate all -> verify all blocked
*/
async function testSecJwtBlockedAfterTerminateAll() {
// Step 1: Create multiple sessions
const jwts = [];
const agents = ['chromeWin', 'safariMac', 'iphoneSafari'];
for (const ua of agents) {
const data = await login(USER_CREDS, ua);
if (data) {
jwts.push({ jwt: data.jwt, device: ua });
print(` [INFO] Session created: ${ua}`, C.dim);
}
await sleep(PHASE_DELAY);
}
if (jwts.length < 2) {
print(` [INFO] Only ${jwts.length} sessions created (need 2+)`, C.yellow);
return null;
}
// Step 2: Verify all work
for (const { jwt, device } of jwts) {
const res = await api('/api/users/me', { token: jwt });
if (!res.ok) print(` [WARN] ${device}: JWT already invalid`, C.yellow);
}
await sleep(500);
// Step 3: Terminate all
const userId = userDocumentId;
await api(`/magic-sessionmanager/user/${userId}/terminate-all`, {
method: 'POST',
token: adminJwt,
});
print(` [INFO] All sessions terminated for user ${userId}`, C.blue);
await sleep(500);
// Step 4: Verify all blocked
let blocked = 0;
let works = 0;
for (const { jwt, device } of jwts) {
const res = await api('/api/users/me', { token: jwt });
if (res.status === 401 || res.status === 403) {
blocked++;
print(` [OK] ${device}: BLOCKED (${res.status})`, C.dim);
} else if (res.ok) {
works++;
print(` [FAIL] ${device}: STILL WORKS`, C.red);
}
}
if (blocked === jwts.length) {
print(` [PASS] All ${blocked} JWTs correctly blocked`, C.green);
return true;
}
if (works > 0) {
print(` [FAIL] ${works}/${jwts.length} JWTs still work after terminate-all`, C.red);
return false;
}
return null;
}
/**
* SECURITY 3: Plugin endpoints also block terminated JWTs
*/
async function testSecPluginEndpointBlocked() {
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
await sleep(500);
// Verify plugin endpoint works
const before = await api('/api/magic-sessionmanager/my-sessions', { token: jwt });
if (!before.ok) return false;
print(` [INFO] BEFORE: Plugin endpoint -> ${before.status}`, C.blue);
await sleep(500);
// Terminate all
await api(`/magic-sessionmanager/user/${userDocumentId}/terminate-all`, {
method: 'POST',
token: adminJwt,
});
await sleep(500);
// Verify blocked
const after = await api('/api/magic-sessionmanager/my-sessions', { token: jwt });
if (after.status === 401 || after.status === 403) {
print(` [PASS] Plugin endpoint correctly blocked (${after.status})`, C.green);
return true;
}
if (after.ok) {
print(` [FAIL] Plugin endpoint still accepts terminated JWT`, C.red);
return false;
}
return null;
}
/**
* SECURITY 4: Session reactivation after timeout (terminatedManually: false)
* Timed-out sessions should be reactivated when user returns
*/
async function testSecReactivationAfterTimeout() {
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
await sleep(500);
// Get session ID
const sessRes = await api('/api/magic-sessionmanager/my-sessions', { token: jwt });
if (!sessRes.ok || !sessRes.data.data?.length) return false;
const sessionId = sessRes.data.data[0].documentId;
await sleep(500);
// Simulate timeout via admin endpoint
const simRes = await api(`/magic-sessionmanager/sessions/${sessionId}/simulate-timeout`, {
method: 'POST',
token: adminJwt,
});
if (simRes.status === 404) {
print(` [INFO] simulate-timeout endpoint not available`, C.yellow);
return null;
}
if (!simRes.ok) return null;
print(` [INFO] Session marked as timed out (terminatedManually: false)`, C.blue);
await sleep(500);
// JWT should be reactivated (not blocked)
const after = await api('/api/users/me', { token: jwt });
if (after.ok) {
print(` [PASS] Session correctly reactivated after timeout`, C.green);
return true;
}
if (after.status === 401 || after.status === 403) {
print(` [FAIL] Session blocked instead of reactivated`, C.red);
return false;
}
return null;
}
/**
* SECURITY 5: Manual logout permanently blocks access (terminatedManually: true)
*/
async function testSecManualLogoutBlocks() {
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
await sleep(500);
// Verify JWT works
const before = await api('/api/users/me', { token: jwt });
if (!before.ok) return false;
await sleep(500);
// Manual logout
await api('/api/magic-sessionmanager/logout', { method: 'POST', token: jwt });
await sleep(500);
// JWT should be BLOCKED (not reactivated)
const after = await api('/api/users/me', { token: jwt });
if (after.status === 401 || after.status === 403) {
print(` [PASS] Manual logout correctly blocks access (${after.status})`, C.green);
return true;
}
if (after.ok) {
print(` [FAIL] JWT still works after manual logout`, C.red);
return false;
}
return null;
}
/**
* SECURITY 6: Fresh login creates a working session (positive test)
*/
async function testSecFreshLoginWorks() {
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
userJwt = jwt;
userDocumentId = data.user.documentId;
await sleep(500);
// Verify on /api/users/me
const usersRes = await api('/api/users/me', { token: jwt });
if (!usersRes.ok) {
print(` [FAIL] Fresh JWT does not work on /api/users/me`, C.red);
return false;
}
// Verify on plugin endpoint
const pluginRes = await api('/api/magic-sessionmanager/my-sessions', { token: jwt });
if (!pluginRes.ok) {
print(` [FAIL] Fresh JWT does not work on plugin endpoint`, C.red);
return false;
}
print(` [PASS] Fresh login creates valid working session`, C.green);
return true;
}
/**
* SECURITY 7: Blocked refresh token after session termination
*/
async function testSecBlockedRefreshToken() {
if (!userRefreshToken) {
print(` [INFO] Refresh tokens not enabled`, C.yellow);
return null;
}
const data = await login(USER_CREDS);
if (!data || !data.refreshToken) return null;
const refreshToken = data.refreshToken;
await sleep(500);
// Get session and terminate it
const sessRes = await api('/api/magic-sessionmanager/my-sessions', { token: data.jwt });
if (!sessRes.ok || !sessRes.data.data?.length) return false;
await api(`/magic-sessionmanager/sessions/${sessRes.data.data[0].documentId}/terminate`, {
method: 'POST',
token: adminJwt,
});
await sleep(500);
// Try refresh - should be blocked
const refreshRes = await api('/api/auth/refresh', {
method: 'POST',
body: { refreshToken },
});
if (refreshRes.status === 401) {
print(` [PASS] Refresh token correctly blocked after termination`, C.green);
return true;
}
if (refreshRes.ok) {
print(` [FAIL] Refresh token still works after session termination`, C.red);
return false;
}
return null;
}
// -------------------------------------------------------------------
// PHASE 4: FIX VERIFICATION & FALSE POSITIVE TESTS
// -------------------------------------------------------------------
/**
* FIX-1: IDOR Protection - User cannot access another user's sessions
* Verifies that Content API enforces ownership check on /user/:userId/sessions
*/
async function testFixIdorProtection() {
const data = await login(USER_CREDS);
if (!data) return false;
const jwt = data.jwt;
await sleep(500);
// Try to access sessions of a fake/different user ID
const fakeUserId = 'aaaa0000bbbb1111cccc2222';
const res = await api(`/api/magic-sessionmanager/user/${fakeUserId}/sessions`, { token: jwt });
if (res.status === 403) {
print(` [PASS] IDOR blocked: Cannot access other user's sessions (403)`, C.green);
return true;
}
if (res.ok) {
print(` [FAIL] IDOR vulnerability: Can access other user's sessions!`, C.red);
return false;
}
// 404 or other error is also acceptable (user doesn't exist)
print(` [PASS] IDOR blocked: Got ${res.status} (not 200)`, C.green);
return true;
}
/**
* FIX-2: Block-reason NOT exposed to client
* Verifies login block response has generic message, no details.reason
* (We can't trigger a real block, but we verify response format on normal login)
*/
async function testFixNoBlockReasonExposed() {
// This test verifies the response structure - a blocked login should NOT
// contain details.reason. We test by checking normal login doesn't have it
// and that the error format is clean.
const data = await login(USER_CREDS);
if (!data) return false;
// Verify normal login response doesn't contain any security details
const hasNoSecurityLeak = !data.securityScore && !data.blockReason && !data.geoData;
if (hasNoSecurityLeak) {
print(` [PASS] Login response contains no security internals`, C.green);
return true;
}
print(` [FAIL] Login response leaks security data`, C.red);
return false;
}
/**
* FIX-3: Session responses strip sensitive fields
* Verifies token, tokenHash, refreshToken are NOT in API responses
*/
async function testFixNoTokenLeakInResponse() {
const data = await login(USER_CREDS);
if (!data) return false;
await sleep(500);
// Get own sessions
const res = await api('/api/magic-sessionmanager/my-sessions', { token: data.jwt });
if (!res.ok || !res.data.data?.length) return false;
const session = res.data.data[0];
const leakedFields = [];
if (session.token) leakedFields.push('token');
if (session.tokenHash) leakedFields.push('tokenHash');
if (session.refreshToken) leakedFields.push('refreshToken');
if (session.refreshTokenHash) leakedFields.push('refreshTokenHash');
if (leakedFields.length === 0) {
print(` [PASS] No sensitive fields leaked in session response`, C.green);
// Verify useful fields ARE present
const hasDeviceInfo = session.deviceType && session.browserName && session.osName;
const hasTimestamps = session.loginTime && session.lastActive !== undefined;
const hasFlags = session.isCurrentSession !== undefined && session.isTrulyActive !== undefined;
if (hasDeviceInfo && hasTimestamps && hasFlags) {
print(` [INFO] Device: ${session.deviceType}, Browser: ${session.browserName}`, C.blue);
print(` [INFO] Required fields present: deviceType, browserName, osName, loginTime, isCurrentSession`, C.blue);
} else {
print(` [WARN] Some expected fields missing from response`, C.yellow);
}
return true;
}
print(` [FAIL] Sensitive fields leaked: ${leakedFields.join(', ')}`, C.red);
return false;
}
/**
* FIX-4: Settings webhook URL SSRF protection
* Verifies that invalid webhook URLs are rejected/sanitized
*/
async function testFixWebhookSsrfProtection() {
if (!adminJwt) return null;
// Get current settings
const getRes = await api('/magic-sessionmanager/settings', { token: adminJwt });
if (!getRes.ok) return false;
const originalSettings = getRes.data.settings;
// Try to set an SSRF webhook URL
const maliciousSettings = {
...originalSettings,
enableWebhooks: true,
discordWebhookUrl: 'http://169.254.169.254/metadata/v1/',
slackWebhookUrl: 'https://evil-attacker.com/steal-data',
};
const putRes = await api('/magic-sessionmanager/settings', {
method: 'PUT',
token: adminJwt,
body: maliciousSettings,
});