forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.test.ts
More file actions
2161 lines (1869 loc) · 74.5 KB
/
security.test.ts
File metadata and controls
2161 lines (1869 loc) · 74.5 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
// src/lib/__tests__/security.test.ts
//
// Security invariant tests: auth enforcement, token leakage,
// input validation, setup protection, crypto integrity
import { NextResponse } from "next/server"
import { beforeEach, describe, expect, it, vi } from "vitest"
// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------
vi.mock("@/lib/api-helpers", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api-helpers")>()
return {
...actual,
authenticate: vi.fn(),
parseTrackerId: vi.fn(),
parseRouteId: vi.fn(),
parseJsonBody: vi.fn(),
}
})
vi.mock("@/lib/db", () => ({
db: {
select: vi.fn(),
selectDistinctOn: vi.fn(),
insert: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
execute: vi.fn().mockResolvedValue([]),
transaction: vi.fn(),
},
}))
vi.mock("@/lib/crypto", () => ({
encrypt: vi.fn().mockReturnValue("encrypted-token"),
decrypt: vi.fn().mockReturnValue("decrypted"),
deriveKey: vi.fn().mockResolvedValue(Buffer.from("a".repeat(32))),
generateSalt: vi.fn().mockReturnValue("a".repeat(64)),
}))
vi.mock("@/lib/tracker-scheduler", () => ({
pollTracker: vi.fn(),
startTrackerPolling: vi.fn(),
stopTrackerPolling: vi.fn(),
isTrackerPollingRunning: vi.fn(() => false),
fetchTrackerStats: vi.fn(),
}))
vi.mock("@/lib/scheduler", () => ({
startScheduler: vi.fn(),
stopScheduler: vi.fn(),
ensureSchedulerRunning: vi.fn(),
}))
vi.mock("@/lib/transit-papers/report-generator", () => ({
generateReportPng: vi.fn().mockResolvedValue(Buffer.from("fake-png")),
}))
vi.mock("@/lib/transit-papers/combined-seal", () => ({
renderCombinedSeal: vi.fn().mockReturnValue({ pixels: new Uint8ClampedArray(4) }),
}))
vi.mock("@/lib/transit-papers/png", () => ({
rgbaToPng: vi.fn().mockReturnValue(Buffer.from("fake-png")),
}))
vi.mock("@/lib/image-hosting", () => ({
getImageHostAdapter: vi.fn().mockReturnValue({
upload: vi.fn().mockResolvedValue({ url: "https://example.com/image.png" }),
}),
}))
vi.mock("@/lib/auth", () => ({
hashPassword: vi.fn().mockResolvedValue("hashed"),
verifyPassword: vi.fn().mockResolvedValue(false),
createSetupToken: vi.fn().mockResolvedValue("setup-token"),
verifySetupToken: vi.fn().mockResolvedValue(null),
createPendingToken: vi.fn().mockResolvedValue("pending-token"),
verifyPendingToken: vi.fn().mockResolvedValue(null),
clearSession: vi.fn().mockResolvedValue(undefined),
getSession: vi.fn().mockResolvedValue(null),
}))
vi.mock("@/lib/totp", () => ({
generateTotpSecret: vi.fn().mockReturnValue({
secret: "JBSWY3DPEHPK3PXP",
uri: "otpauth://totp/test",
}),
generateBackupCodes: vi.fn().mockReturnValue(["AAAA-1111"]),
hashBackupCode: vi.fn().mockReturnValue({ hash: "abc", salt: "def", used: false }),
verifyTotpCode: vi.fn().mockReturnValue(false),
verifyAndConsumeBackupCode: vi.fn().mockReturnValue({ valid: false, updatedEntries: [] }),
TOTP_CODE_RE: /^\d{6}$/,
BACKUP_CODE_PATTERN: /^[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}$/,
}))
vi.mock("@/lib/db/schema", () => ({
appSettings: {},
trackers: {},
trackerSnapshots: {},
trackerRoles: {},
downloadClients: {},
tagGroups: {},
tagGroupMembers: {},
clientSnapshots: {},
backupHistory: {},
dismissedAlerts: {},
notificationTargets: {},
notificationDeliveryState: {},
clientUptimeBuckets: {},
}))
vi.mock("@/lib/backup", () => ({
generateBackupPayload: vi.fn(),
encryptBackupPayload: vi.fn(),
decryptBackupPayload: vi.fn(),
validateBackupJson: vi.fn(),
CURRENT_BACKUP_VERSION: 1,
}))
vi.mock("@/lib/logger", () => ({
log: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
debug: vi.fn(),
},
}))
vi.mock("@/lib/lockout", () => ({
checkLockout: vi.fn().mockReturnValue(null),
recordFailedAttempt: vi.fn(),
resetFailedAttempts: vi.fn(),
}))
vi.mock("@/lib/nuke", () => ({
scrubAndDeleteAll: vi.fn(),
}))
vi.mock("@/lib/download-client-scheduler", () => ({
startClientScheduler: vi.fn(),
stopClientScheduler: vi.fn(),
}))
vi.mock("@/lib/backup-scheduler", () => ({
startBackupScheduler: vi.fn(),
stopBackupScheduler: vi.fn(),
}))
vi.mock("@/lib/privacy", () => ({
maskUsername: vi.fn((u: string) => u),
isRedacted: vi.fn(() => false),
}))
vi.mock("@/lib/tunnel", () => ({
VALID_PROXY_TYPES: new Set(["socks5", "http", "https"]),
PROXY_HOST_PATTERN: /^[\w.\-:[\]]+$/,
buildProxyAgentFromSettings: vi.fn().mockReturnValue(undefined),
proxyFetch: vi.fn(),
}))
vi.mock("@/lib/download-clients", () => ({
buildBaseUrl: vi.fn().mockReturnValue("http://localhost:8080"),
getSession: vi.fn(),
getTorrents: vi.fn().mockResolvedValue([]),
getTransferInfo: vi.fn().mockResolvedValue({}),
invalidateSession: vi.fn(),
clearAllSessions: vi.fn(),
login: vi.fn().mockResolvedValue("sid"),
withSessionRetry: vi.fn().mockResolvedValue([]),
aggregateByTag: vi.fn().mockReturnValue({}),
getSpeedSnapshots: vi.fn().mockReturnValue([]),
pushSpeedSnapshot: vi.fn(),
clearSpeedCache: vi.fn(),
mergeTorrentLists: vi.fn().mockReturnValue([]),
aggregateCrossSeedTags: vi.fn().mockReturnValue([]),
fetchAndMergeTorrents: vi.fn().mockResolvedValue({
torrents: [],
crossSeedTags: [],
clientErrors: [],
clientCount: 0,
sessionExpired: false,
}),
stripSensitiveTorrentFields: vi.fn((t: Record<string, unknown>) => {
const { tracker: _t, content_path: _cp, save_path: _sp, ...rest } = t
return rest
}),
CLIENT_CONNECTION_COLUMNS: {},
decryptClientCredentials: vi.fn().mockReturnValue({ username: "admin", password: "pass" }),
parseCrossSeedTags: vi.fn((raw: string[] | null) => raw ?? []),
slimTorrentForCache: vi.fn((t: Record<string, unknown>) => t),
parseCachedTorrents: vi.fn().mockReturnValue([]),
STORE_MAX_AGE_MS: 600000,
isStoreFresh: vi.fn().mockReturnValue(false),
getFilteredTorrents: vi.fn().mockReturnValue([]),
VALID_CLIENT_TYPES: ["qbittorrent"],
}))
vi.mock("@/lib/privacy-db", () => ({
createPrivacyMask: vi.fn(async () => (v: string | null | undefined) => v ?? null),
createPrivacyMaskSync: vi.fn().mockReturnValue((v: string | null | undefined) => v ?? null),
}))
vi.mock("@/data/tracker-registry", () => ({
findRegistryEntry: vi.fn(),
}))
vi.mock("@/lib/notifications/validate", () => ({
validateNotificationConfig: vi.fn().mockReturnValue(null),
}))
vi.mock("@/lib/notifications/decrypt", () => ({
decryptNotificationConfig: vi
.fn()
.mockReturnValue({ webhookUrl: "https://discord.com/api/webhooks/123/abc" }),
}))
vi.mock("@/lib/notifications/deliver", () => ({
deliverDiscordWebhook: vi.fn().mockResolvedValue({ success: true, status: "delivered" }),
}))
// ---------------------------------------------------------------------------
// Route imports
// ---------------------------------------------------------------------------
import {
DELETE as AlertDismissedDELETE,
GET as AlertDismissedGET,
POST as AlertDismissedPOST,
} from "@/app/api/alerts/dismissed/route"
import { POST as ChangePasswordPOST } from "@/app/api/auth/change-password/route"
import { POST as LoginPOST } from "@/app/api/auth/login/route"
import { POST as LogoutPOST } from "@/app/api/auth/logout/route"
import { POST as TotpConfirmPOST } from "@/app/api/auth/totp/confirm/route"
import { POST as TotpDisablePOST } from "@/app/api/auth/totp/disable/route"
import { POST as TotpSetupPOST } from "@/app/api/auth/totp/setup/route"
import { POST as TotpVerifyPOST } from "@/app/api/auth/totp/verify/route"
import { GET as ChangelogGET } from "@/app/api/changelog/route"
import { DELETE as ClientDELETE, PATCH as ClientPATCH } from "@/app/api/clients/[id]/route"
import { GET as ClientSnapshotsGET } from "@/app/api/clients/[id]/snapshots/route"
import { GET as ClientSpeedsGET } from "@/app/api/clients/[id]/speeds/route"
import { POST as ClientTestPOST } from "@/app/api/clients/[id]/test/route"
import { GET as ClientTorrentsGET } from "@/app/api/clients/[id]/torrents/route"
import { GET as ClientsGET, POST as ClientsPOST } from "@/app/api/clients/route"
import { GET as FleetSnapshotsGET } from "@/app/api/fleet/snapshots/route"
import { GET as FleetTorrentsGET } from "@/app/api/fleet/torrents/route"
import {
DELETE as NotificationDELETE,
PATCH as NotificationPATCH,
} from "@/app/api/notifications/[id]/route"
import { POST as NotificationTestPOST } from "@/app/api/notifications/[id]/test/route"
import { GET as NotificationsGET, POST as NotificationsPOST } from "@/app/api/notifications/route"
import {
DELETE as BackupDeleteDELETE,
GET as BackupGetGET,
} from "@/app/api/settings/backup/[id]/route"
import { POST as BackupExportPOST } from "@/app/api/settings/backup/export/route"
import { GET as BackupHistoryGET } from "@/app/api/settings/backup/history/route"
import { POST as BackupRestorePOST } from "@/app/api/settings/backup/restore/route"
import { GET as DashboardGET, PUT as DashboardPUT } from "@/app/api/settings/dashboard/route"
import { GET as DbSizeGET } from "@/app/api/settings/db-size/route"
import { GET as EventsGET } from "@/app/api/settings/events/route"
import { GET as ImageHostsGET } from "@/app/api/settings/image-hosts/route"
import { POST as LockdownPOST } from "@/app/api/settings/lockdown/route"
import { GET as LogsDownloadGET } from "@/app/api/settings/logs/download/route"
import { DELETE as LogsDELETE, GET as LogsGET } from "@/app/api/settings/logs/route"
import { POST as NukePOST } from "@/app/api/settings/nuke/route"
import { POST as ProxyTestPOST } from "@/app/api/settings/proxy-test/route"
import { GET as QuicklinksGET, PUT as QuicklinksPUT } from "@/app/api/settings/quicklinks/route"
import { POST as ResetStatsPOST } from "@/app/api/settings/reset-stats/route"
import { GET as SettingsGET, PATCH as SettingsPATCH } from "@/app/api/settings/route"
import {
DELETE as MemberDELETE,
PATCH as MemberPATCH,
} from "@/app/api/tag-groups/[id]/members/[memberId]/route"
import { GET as MembersGET, POST as MembersPOST } from "@/app/api/tag-groups/[id]/members/route"
import { DELETE as TagGroupDELETE, PATCH as TagGroupPATCH } from "@/app/api/tag-groups/[id]/route"
import { GET as TagGroupsGET, POST as TagGroupsPOST } from "@/app/api/tag-groups/route"
import { GET as TrackerAvatarGET } from "@/app/api/trackers/[id]/avatar/route"
import { POST as DebugPOST } from "@/app/api/trackers/[id]/debug/route"
import { POST as PollPOST } from "@/app/api/trackers/[id]/poll/route"
// Transit papers routes. Unimplemented for now.
// import { GET as ReportGET } from "@/app/api/trackers/[id]/report/route"
import { POST as ResumePOST } from "@/app/api/trackers/[id]/resume/route"
import { GET as RolesGET, POST as RolesPOST } from "@/app/api/trackers/[id]/roles/route"
import { DELETE, PATCH, GET as TrackerDetailGET } from "@/app/api/trackers/[id]/route"
// import { GET as SealGET } from "@/app/api/trackers/[id]/seal/route"
import { GET as SnapshotsGET } from "@/app/api/trackers/[id]/snapshots/route"
import { GET as TrackerTorrentsGET } from "@/app/api/trackers/[id]/torrents/route"
import { POST as PollAllPOST } from "@/app/api/trackers/poll-all/route"
import { PATCH as ReorderPATCH } from "@/app/api/trackers/reorder/route"
import { GET, POST } from "@/app/api/trackers/route"
import { POST as TestPOST } from "@/app/api/trackers/test-connection/route"
import { POST as UploadImagePOST } from "@/app/api/upload-image/route"
// ---------------------------------------------------------------------------
// Lib imports
// ---------------------------------------------------------------------------
import { authenticate, parseJsonBody, parseRouteId, parseTrackerId } from "@/lib/api-helpers"
import { getSession } from "@/lib/auth"
import { db } from "@/lib/db"
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const VALID_KEY = "abcd1234".repeat(8)
const MOCK_PARAMS = Promise.resolve({ id: "1" })
function makeRequest(url: string, body?: Record<string, unknown>, method = "GET"): Request {
return new Request(url, {
method,
headers: { "Content-Type": "application/json" },
body: body !== undefined ? JSON.stringify(body) : undefined,
})
}
function mockAuthFail() {
;(authenticate as ReturnType<typeof vi.fn>).mockResolvedValue(
NextResponse.json({ error: "Unauthorized" }, { status: 401 })
)
}
function mockAuthSuccess() {
;(authenticate as ReturnType<typeof vi.fn>).mockResolvedValue({
encryptionKey: VALID_KEY,
})
}
// ---------------------------------------------------------------------------
// 1. Authentication required on all protected API routes
// ---------------------------------------------------------------------------
describe("Auth enforcement: every protected route returns 401 without valid session", () => {
beforeEach(() => {
vi.restoreAllMocks()
mockAuthFail()
;(parseTrackerId as ReturnType<typeof vi.fn>).mockResolvedValue(1)
;(parseRouteId as ReturnType<typeof vi.fn>).mockResolvedValue(1)
;(parseJsonBody as ReturnType<typeof vi.fn>).mockResolvedValue({})
})
it("GET /api/trackers returns 401", async () => {
const res = await GET()
expect(res.status).toBe(401)
})
it("POST /api/trackers returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers", { name: "test" }, "POST")
const res = await POST(req)
expect(res.status).toBe(401)
})
it("PATCH /api/trackers/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1", { name: "test" }, "PATCH")
const res = await PATCH(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("DELETE /api/trackers/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1", undefined, "DELETE")
const res = await DELETE(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/trackers/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1")
const res = await TrackerDetailGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/[id]/debug returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/debug", undefined, "POST")
const res = await DebugPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/[id]/poll returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/poll", undefined, "POST")
const res = await PollPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/[id]/resume returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/resume", undefined, "POST")
const res = await ResumePOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/trackers/[id]/snapshots returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/snapshots")
const res = await SnapshotsGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/trackers/[id]/roles returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/roles")
const res = await RolesGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/[id]/roles returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/roles", { roleName: "test" }, "POST")
const res = await RolesPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/test returns 401", async () => {
const req = makeRequest(
"http://localhost/api/trackers/test",
{ baseUrl: "https://example.com", apiToken: "tok" },
"POST"
)
const res = await TestPOST(req)
expect(res.status).toBe(401)
})
it("PATCH /api/trackers/reorder returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/reorder", { ids: [1, 2] }, "PATCH")
const res = await ReorderPATCH(req)
expect(res.status).toBe(401)
})
it("GET /api/settings returns 401", async () => {
const res = await SettingsGET()
expect(res.status).toBe(401)
})
it("PATCH /api/settings returns 401", async () => {
const req = makeRequest("http://localhost/api/settings", { storeUsernames: false }, "PATCH")
const res = await SettingsPATCH(req)
expect(res.status).toBe(401)
})
it("POST /api/auth/totp/setup returns 401", async () => {
const res = await TotpSetupPOST()
expect(res.status).toBe(401)
})
it("POST /api/auth/totp/confirm returns 401", async () => {
const req = makeRequest(
"http://localhost/api/auth/totp/confirm",
{ setupToken: "t", code: "123456" },
"POST"
)
const res = await TotpConfirmPOST(req)
expect(res.status).toBe(401)
})
it("POST /api/auth/totp/disable returns 401", async () => {
const req = makeRequest("http://localhost/api/auth/totp/disable", { code: "123456" }, "POST")
const res = await TotpDisablePOST(req)
expect(res.status).toBe(401)
})
it("POST /api/auth/change-password returns 401", async () => {
const req = makeRequest(
"http://localhost/api/auth/change-password",
{ currentPassword: "old", newPassword: "newpass123" },
"POST"
)
const res = await ChangePasswordPOST(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/lockdown returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/lockdown", { password: "test" }, "POST")
const res = await LockdownPOST(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/nuke returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/nuke", { password: "test" }, "POST")
const res = await NukePOST(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/proxy-test returns 401", async () => {
const req = makeRequest(
"http://localhost/api/settings/proxy-test",
{ proxyType: "socks5", proxyHost: "127.0.0.1", proxyPort: 1080 },
"POST"
)
const res = await ProxyTestPOST(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/backup/export returns 401", async () => {
const req = new Request("http://localhost/api/settings/backup/export", {
method: "POST",
body: new FormData(), // Empty form data
})
const res = await BackupExportPOST(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/backup/restore returns 401", async () => {
const formData = new FormData()
formData.append("file", new Blob(["{}"], { type: "application/json" }), "backup.json")
formData.append("password", "test")
const req = new Request("http://localhost/api/settings/backup/restore", {
method: "POST",
body: formData,
})
const res = await BackupRestorePOST(req)
expect(res.status).toBe(401)
})
it("GET /api/settings/backup/history returns 401", async () => {
const res = await BackupHistoryGET()
expect(res.status).toBe(401)
})
it("DELETE /api/settings/backup/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/backup/1", undefined, "DELETE")
const res = await BackupDeleteDELETE(req, {
params: Promise.resolve({ id: "1" }),
})
expect(res.status).toBe(401)
})
it("POST /api/auth/logout returns 401 when no session", async () => {
;(getSession as ReturnType<typeof vi.fn>).mockResolvedValue(null)
const res = await LogoutPOST()
expect(res.status).toBe(401)
})
it("GET /api/clients returns 401", async () => {
const res = await ClientsGET()
expect(res.status).toBe(401)
})
it("POST /api/clients returns 401", async () => {
const req = makeRequest("http://localhost/api/clients", { name: "test" }, "POST")
const res = await ClientsPOST(req)
expect(res.status).toBe(401)
})
it("PATCH /api/clients/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1", { name: "test" }, "PATCH")
const res = await ClientPATCH(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("DELETE /api/clients/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1", undefined, "DELETE")
const res = await ClientDELETE(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/clients/[id]/test returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1/test", undefined, "POST")
const res = await ClientTestPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/clients/[id]/torrents returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1/torrents?tag=test")
const res = await ClientTorrentsGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/clients/[id]/snapshots returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1/snapshots")
const res = await ClientSnapshotsGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/clients/[id]/speeds returns 401", async () => {
const req = makeRequest("http://localhost/api/clients/1/speeds")
const res = await ClientSpeedsGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/tag-groups returns 401", async () => {
const res = await TagGroupsGET()
expect(res.status).toBe(401)
})
it("POST /api/tag-groups returns 401", async () => {
const req = makeRequest("http://localhost/api/tag-groups", { name: "test" }, "POST")
const res = await TagGroupsPOST(req)
expect(res.status).toBe(401)
})
it("PATCH /api/tag-groups/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/tag-groups/1", { name: "test" }, "PATCH")
const res = await TagGroupPATCH(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("DELETE /api/tag-groups/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/tag-groups/1", undefined, "DELETE")
const res = await TagGroupDELETE(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/tag-groups/[id]/members returns 401", async () => {
const req = makeRequest("http://localhost/api/tag-groups/1/members")
const res = await MembersGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/tag-groups/[id]/members returns 401", async () => {
const req = makeRequest(
"http://localhost/api/tag-groups/1/members",
{ tag: "test", label: "Test" },
"POST"
)
const res = await MembersPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("PATCH /api/tag-groups/[id]/members/[memberId] returns 401", async () => {
const req = makeRequest(
"http://localhost/api/tag-groups/1/members/1",
{ label: "test" },
"PATCH"
)
const res = await MemberPATCH(req, {
params: Promise.resolve({ id: "1", memberId: "1" }),
})
expect(res.status).toBe(401)
})
it("DELETE /api/tag-groups/[id]/members/[memberId] returns 401", async () => {
const req = makeRequest("http://localhost/api/tag-groups/1/members/1", undefined, "DELETE")
const res = await MemberDELETE(req, {
params: Promise.resolve({ id: "1", memberId: "1" }),
})
expect(res.status).toBe(401)
})
it("GET /api/trackers/[id]/torrents returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/torrents")
const res = await TrackerTorrentsGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("GET /api/trackers/[id]/avatar returns 401", async () => {
const req = makeRequest("http://localhost/api/trackers/1/avatar")
const res = await TrackerAvatarGET(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/trackers/poll-all returns 401", async () => {
const res = await PollAllPOST()
expect(res.status).toBe(401)
})
it("GET /api/settings/dashboard returns 401", async () => {
const res = await DashboardGET()
expect(res.status).toBe(401)
})
it("PUT /api/settings/dashboard returns 401", async () => {
const req = makeRequest(
"http://localhost/api/settings/dashboard",
{ showHealthIndicators: true },
"PUT"
)
const res = await DashboardPUT(req)
expect(res.status).toBe(401)
})
it("GET /api/settings/quicklinks returns 401", async () => {
const res = await QuicklinksGET()
expect(res.status).toBe(401)
})
it("PUT /api/settings/quicklinks returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/quicklinks", { slugs: [] }, "PUT")
const res = await QuicklinksPUT(req)
expect(res.status).toBe(401)
})
it("POST /api/settings/reset-stats returns 401", async () => {
const req = makeRequest(
"http://localhost/api/settings/reset-stats",
{ password: "test" },
"POST"
)
const res = await ResetStatsPOST(req)
expect(res.status).toBe(401)
})
it("GET /api/settings/logs returns 401", async () => {
const res = await LogsGET()
expect(res.status).toBe(401)
})
it("GET /api/changelog returns 401", async () => {
const res = await ChangelogGET()
expect(res.status).toBe(401)
})
it("GET /api/fleet/snapshots returns 401", async () => {
const req = makeRequest("http://localhost/api/fleet/snapshots")
const res = await FleetSnapshotsGET(req)
expect(res.status).toBe(401)
})
it("GET /api/fleet/torrents returns 401", async () => {
const res = await FleetTorrentsGET()
expect(res.status).toBe(401)
})
it("GET /api/settings/backup/[id] returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/backup/1")
const res = await BackupGetGET(req, {
params: Promise.resolve({ id: "1" }),
})
expect(res.status).toBe(401)
})
it("GET /api/alerts/dismissed returns 401", async () => {
const res = await AlertDismissedGET()
expect(res.status).toBe(401)
})
it("POST /api/alerts/dismissed returns 401", async () => {
const req = makeRequest(
"http://localhost/api/alerts/dismissed",
{ key: "test", type: "error" },
"POST"
)
const res = await AlertDismissedPOST(req)
expect(res.status).toBe(401)
})
it("DELETE /api/alerts/dismissed returns 401", async () => {
const req = makeRequest("http://localhost/api/alerts/dismissed", undefined, "DELETE")
const res = await AlertDismissedDELETE(req)
expect(res.status).toBe(401)
})
// Notification target routes
it("GET /api/notifications returns 401 without session", async () => {
const res = await NotificationsGET()
expect(res.status).toBe(401)
})
it("POST /api/notifications returns 401 without session", async () => {
const req = makeRequest(
"http://localhost/api/notifications",
{
name: "test",
type: "discord",
config: { webhookUrl: "https://discord.com/api/webhooks/123/abc" },
},
"POST"
)
const res = await NotificationsPOST(req)
expect(res.status).toBe(401)
})
it("PATCH /api/notifications/1 returns 401 without session", async () => {
const req = makeRequest("http://localhost/api/notifications/1", { name: "updated" }, "PATCH")
const res = await NotificationPATCH(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("DELETE /api/notifications/1 returns 401 without session", async () => {
const req = makeRequest("http://localhost/api/notifications/1", undefined, "DELETE")
const res = await NotificationDELETE(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/notifications/1/test returns 401 without session", async () => {
const req = makeRequest("http://localhost/api/notifications/1/test", undefined, "POST")
const res = await NotificationTestPOST(req, { params: MOCK_PARAMS })
expect(res.status).toBe(401)
})
it("POST /api/upload-image returns 401", async () => {
const formData = new FormData()
formData.append("host", "ptpimg")
formData.append("image", new Blob(["fake"], { type: "image/png" }), "test.png")
const req = new Request("http://localhost/api/upload-image", {
method: "POST",
body: formData,
})
const res = await UploadImagePOST(req)
expect(res.status).toBe(401)
})
it("GET /api/settings/image-hosts returns 401", async () => {
const res = await ImageHostsGET()
expect(res.status).toBe(401)
})
it("GET /api/settings/db-size returns 401", async () => {
const res = await DbSizeGET()
expect(res.status).toBe(401)
})
it("GET /api/settings/events returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/events")
const res = await EventsGET(req)
expect(res.status).toBe(401)
})
it("DELETE /api/settings/logs returns 401", async () => {
const req = makeRequest("http://localhost/api/settings/logs", { password: "test" }, "DELETE")
const res = await LogsDELETE(req)
expect(res.status).toBe(401)
})
it("GET /api/settings/logs/download returns 401", async () => {
const res = await LogsDownloadGET()
expect(res.status).toBe(401)
})
// Transit papers routes — stashed, uncomment when restored
// it("GET /api/trackers/[id]/report returns 401", async () => {
// const req = makeRequest("http://localhost/api/trackers/1/report")
// const res = await ReportGET(req, { params: MOCK_PARAMS })
// expect(res.status).toBe(401)
// })
// it("GET /api/trackers/[id]/seal returns 401", async () => {
// const req = makeRequest("http://localhost/api/trackers/1/seal")
// const res = await SealGET(req, { params: MOCK_PARAMS })
// expect(res.status).toBe(401)
// })
})
// ---------------------------------------------------------------------------
// 2. Public endpoint documentation
// ---------------------------------------------------------------------------
// NOTE: POST /api/verify-report and /api/verify-report/fetch-image are
// intentionally public endpoints. They use in-memory rate limiting instead of
// authentication. Moderators verify reports without needing an account.
// Do NOT add authenticate() to these routes.
// ---------------------------------------------------------------------------
// 3. Encrypted tokens never leak in API responses
// ---------------------------------------------------------------------------
describe("Token leakage prevention", () => {
beforeEach(() => {
vi.restoreAllMocks()
mockAuthSuccess()
})
it("GET /api/trackers does not include encryptedApiToken in response", async () => {
const tracker = {
id: 1,
name: "Aither",
baseUrl: "https://aither.cc",
platformType: "unit3d",
isActive: true,
lastPolledAt: null,
lastError: null,
color: "#00d4ff",
qbtTag: null,
sortOrder: 0,
joinedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
apiPath: "/api/user",
encryptedApiToken: "SUPER_SECRET_SHOULD_NOT_APPEAR",
}
// Call 1: db.select().from(trackers).orderBy(trackers.createdAt)
const mockOrderBy = vi.fn().mockResolvedValue([tracker])
const mockFrom = vi.fn().mockReturnValue({ orderBy: mockOrderBy })
// Call 2: db.select({storeUsernames}).from(appSettings).limit(1)
const mockSettingsLimit = vi.fn().mockResolvedValue([{ storeUsernames: true }])
const mockSettingsFrom = vi.fn().mockReturnValue({ limit: mockSettingsLimit })
;(db.select as ReturnType<typeof vi.fn>)
.mockReturnValueOnce({ from: mockFrom })
.mockReturnValueOnce({ from: mockSettingsFrom })
// DISTINCT ON query via db.selectDistinctOn
;(db.selectDistinctOn as ReturnType<typeof vi.fn>).mockReturnValueOnce({
from: vi.fn().mockReturnValue({
orderBy: vi.fn().mockResolvedValue([]),
}),
})
const res = await GET()
const body = await res.json()
const json = JSON.stringify(body)
expect(json).not.toContain("SUPER_SECRET_SHOULD_NOT_APPEAR")
expect(json).not.toContain("encryptedApiToken")
})
it("GET /api/notifications never includes encryptedConfig in responses", async () => {
// Mock returns the shape produced by notificationTargetColumns projection.
// encryptedConfig is never selected; hasConfig is a SQL boolean computed at query level.
const target = {
id: 1,
name: "My Discord",
type: "discord",
enabled: true,
hasConfig: true,
notifyRatioDrop: true,
notifyHitAndRun: false,
notifyTrackerDown: true,
notifyBufferMilestone: false,
notifyWarned: false,
notifyRatioDanger: false,
notifyZeroSeeding: false,
notifyRankChange: false,
notifyAnniversary: false,
notifyBonusCap: false,
notifyVipExpiring: false,
notifyUnsatisfiedLimit: false,
notifyActiveHnrs: false,
notifyDownloadDisabled: false,
thresholds: null,
includeTrackerName: true,
scope: null,
lastDeliveryStatus: null,
lastDeliveryAt: null,
lastDeliveryError: null,
createdAt: new Date(),
updatedAt: new Date(),
}
const mockFrom = vi.fn().mockResolvedValue([target])
;(db.select as ReturnType<typeof vi.fn>).mockReturnValueOnce({ from: mockFrom })
const res = await NotificationsGET()
expect(res.status).toBe(200)
const body = await res.json()
const json = JSON.stringify(body)
expect(json).not.toContain("encryptedConfig")
expect(body[0]).toHaveProperty("hasConfig", true)
expect(body[0]).toHaveProperty("name", "My Discord")
expect(body[0]).toHaveProperty("notifyDownloadDisabled", false)
})
it("GET /api/trackers/[id] does not include encryptedApiToken or apiPath in response", async () => {
;(parseTrackerId as ReturnType<typeof vi.fn>).mockResolvedValue(1)
// DB row with secrets present — the route's .select() projection must strip them
const trackerRow = {
id: 1,
name: "TestTracker",
baseUrl: "https://test.example.com",
platformType: "unit3d",
isActive: true,
lastPolledAt: null,
lastError: null,
color: "#00d4ff",
qbtTag: null,
useProxy: false,
countCrossSeedUnsatisfied: false,
isFavorite: false,
sortOrder: 0,
joinedAt: null,
lastAccessAt: null,
remoteUserId: null,
platformMeta: null,
createdAt: new Date(),
// Secrets that MUST NOT appear in the response
encryptedApiToken: "SECRET_API_TOKEN_CIPHERTEXT",
apiPath: "/api/user",
}
// Call 1: tracker detail with explicit column allowlist
const mockTrackerWhere = vi
.fn()
.mockReturnValue({ limit: vi.fn().mockResolvedValue([trackerRow]) })
const mockTrackerFrom = vi.fn().mockReturnValue({ where: mockTrackerWhere })
// Call 2: latest snapshot
const mockSnapshotWhere = vi.fn().mockReturnValue({
orderBy: vi.fn().mockReturnValue({ limit: vi.fn().mockResolvedValue([]) }),
})
const mockSnapshotFrom = vi.fn().mockReturnValue({ where: mockSnapshotWhere })
// Call 3: appSettings for privacy
const mockSettingsLimit = vi.fn().mockResolvedValue([{ storeUsernames: true }])
const mockSettingsFrom = vi.fn().mockReturnValue({ limit: mockSettingsLimit })
;(db.select as ReturnType<typeof vi.fn>)
.mockReturnValueOnce({ from: mockTrackerFrom })
.mockReturnValueOnce({ from: mockSnapshotFrom })
.mockReturnValueOnce({ from: mockSettingsFrom })
const req = makeRequest("http://localhost/api/trackers/1")
const res = await TrackerDetailGET(req, { params: MOCK_PARAMS })
const body = await res.json()
const json = JSON.stringify(body)
expect(res.status).toBe(200)
expect(json).not.toContain("SECRET_API_TOKEN_CIPHERTEXT")
expect(json).not.toContain("encryptedApiToken")
expect(json).not.toContain("apiPath")
// Verify slot-critical fields ARE present
expect(body).toHaveProperty("lastAccessAt")