-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathserver.test.ts
More file actions
1486 lines (1275 loc) · 51.6 KB
/
server.test.ts
File metadata and controls
1486 lines (1275 loc) · 51.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import {
createPdfCache,
createServer,
validateUrl,
isAncestorDir,
allowedLocalFiles,
allowedLocalDirs,
pathToFileUrl,
startFileWatch,
stopFileWatch,
cliLocalFiles,
isWritablePath,
writeFlags,
viewSourcePaths,
CACHE_INACTIVITY_TIMEOUT_MS,
CACHE_MAX_LIFETIME_MS,
CACHE_MAX_PDF_SIZE_BYTES,
type PdfCache,
} from "./server";
describe("PDF Cache with Timeouts", () => {
let pdfCache: PdfCache;
beforeEach(() => {
// Each test gets its own session-local cache
pdfCache = createPdfCache();
});
afterEach(() => {
pdfCache.clearCache();
});
describe("cache configuration", () => {
it("should have 10 second inactivity timeout", () => {
expect(CACHE_INACTIVITY_TIMEOUT_MS).toBe(10_000);
});
it("should have 60 second max lifetime timeout", () => {
expect(CACHE_MAX_LIFETIME_MS).toBe(60_000);
});
it("should have 50MB max PDF size limit", () => {
expect(CACHE_MAX_PDF_SIZE_BYTES).toBe(50 * 1024 * 1024);
});
});
describe("cache management", () => {
it("should start with empty cache", () => {
expect(pdfCache.getCacheSize()).toBe(0);
});
it("should clear all entries", () => {
pdfCache.clearCache();
expect(pdfCache.getCacheSize()).toBe(0);
});
it("should isolate caches between sessions", () => {
// Create two independent cache instances
const cache1 = createPdfCache();
const cache2 = createPdfCache();
// They should be independent (both start empty)
expect(cache1.getCacheSize()).toBe(0);
expect(cache2.getCacheSize()).toBe(0);
});
});
describe("readPdfRange caching behavior", () => {
const testUrl = "https://arxiv.org/pdf/test-pdf";
const testData = new Uint8Array([0x25, 0x50, 0x44, 0x46]); // %PDF header
it("should cache full body when server returns HTTP 200", async () => {
// Mock fetch to return HTTP 200 (full body, no range support)
const mockFetch = spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(testData, {
status: 200,
headers: { "Content-Type": "application/pdf" },
}),
);
try {
// First request - should fetch and cache
const result1 = await pdfCache.readPdfRange(testUrl, 0, 1024);
expect(result1.data).toEqual(testData);
expect(result1.totalBytes).toBe(testData.length);
expect(pdfCache.getCacheSize()).toBe(1);
// Second request - should serve from cache (no new fetch)
const result2 = await pdfCache.readPdfRange(testUrl, 0, 1024);
expect(result2.data).toEqual(testData);
expect(mockFetch).toHaveBeenCalledTimes(1); // Only one fetch call
} finally {
mockFetch.mockRestore();
}
});
it("should not cache when server returns HTTP 206 (range supported)", async () => {
const chunkData = new Uint8Array([0x25, 0x50]); // First 2 bytes
const mockFetch = spyOn(globalThis, "fetch").mockResolvedValue(
new Response(chunkData, {
status: 206,
headers: {
"Content-Type": "application/pdf",
"Content-Range": "bytes 0-1/100",
},
}),
);
try {
await pdfCache.readPdfRange(testUrl, 0, 2);
expect(pdfCache.getCacheSize()).toBe(0); // Not cached when 206
} finally {
mockFetch.mockRestore();
}
});
it("should slice cached data for subsequent range requests", async () => {
const fullData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const mockFetch = spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(fullData, { status: 200 }),
);
try {
// First request caches full body
await pdfCache.readPdfRange(testUrl, 0, 1024);
expect(pdfCache.getCacheSize()).toBe(1);
// Subsequent request gets slice from cache
const result = await pdfCache.readPdfRange(testUrl, 2, 3);
expect(result.data).toEqual(new Uint8Array([3, 4, 5]));
expect(result.totalBytes).toBe(10);
expect(mockFetch).toHaveBeenCalledTimes(1);
} finally {
mockFetch.mockRestore();
}
});
it("should fall back to GET when server returns 501 for Range request", async () => {
const fullData = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]); // %PDF-
const mockFetch = spyOn(globalThis, "fetch")
// First call: Range request returns 501
.mockResolvedValueOnce(
new Response("Unsupported client Range", { status: 501 }),
)
// Second call: plain GET returns full body
.mockResolvedValueOnce(
new Response(fullData, {
status: 200,
headers: { "Content-Type": "application/pdf" },
}),
);
try {
const result = await pdfCache.readPdfRange(testUrl, 0, 1024);
expect(result.data).toEqual(fullData);
expect(result.totalBytes).toBe(fullData.length);
expect(pdfCache.getCacheSize()).toBe(1);
expect(mockFetch).toHaveBeenCalledTimes(2);
} finally {
mockFetch.mockRestore();
}
});
it("should reject PDFs larger than max size limit", async () => {
const hugeUrl = "https://arxiv.org/pdf/huge-pdf";
// Create data larger than the limit
const hugeData = new Uint8Array(CACHE_MAX_PDF_SIZE_BYTES + 1);
const mockFetch = spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(hugeData, {
status: 200,
headers: { "Content-Type": "application/pdf" },
}),
);
try {
await expect(pdfCache.readPdfRange(hugeUrl, 0, 1024)).rejects.toThrow(
/PDF too large to cache/,
);
expect(pdfCache.getCacheSize()).toBe(0); // Should not be cached
} finally {
mockFetch.mockRestore();
}
});
it("should reject when Content-Length header exceeds limit", async () => {
const headerUrl = "https://arxiv.org/pdf/huge-pdf-header";
const smallData = new Uint8Array([1, 2, 3, 4]);
const mockFetch = spyOn(globalThis, "fetch").mockResolvedValueOnce(
new Response(smallData, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Length": String(CACHE_MAX_PDF_SIZE_BYTES + 1),
},
}),
);
try {
await expect(pdfCache.readPdfRange(headerUrl, 0, 1024)).rejects.toThrow(
/PDF too large to cache/,
);
expect(pdfCache.getCacheSize()).toBe(0);
} finally {
mockFetch.mockRestore();
}
});
});
// Note: Timer-based tests (inactivity/max lifetime) would require
// using fake timers which can be complex with async code.
// The timeout behavior is straightforward and can be verified
// through manual testing or E2E tests.
});
describe("validateUrl with MCP roots (allowedLocalDirs)", () => {
const savedFiles = new Set(allowedLocalFiles);
const savedDirs = new Set(allowedLocalDirs);
beforeEach(() => {
allowedLocalFiles.clear();
allowedLocalDirs.clear();
});
afterEach(() => {
allowedLocalFiles.clear();
allowedLocalDirs.clear();
for (const f of savedFiles) allowedLocalFiles.add(f);
for (const d of savedDirs) allowedLocalDirs.add(d);
});
it("should allow a file under an allowed directory", () => {
// Use a real existing directory+file for the existsSync check
const dir = path.resolve(import.meta.dirname);
allowedLocalDirs.add(dir);
const filePath = path.join(dir, "server.ts");
const result = validateUrl(pathToFileUrl(filePath));
expect(result.valid).toBe(true);
});
it("should reject a file outside allowed directories", () => {
allowedLocalDirs.add("/some/allowed/dir");
const result = validateUrl("file:///other/dir/test.pdf");
expect(result.valid).toBe(false);
expect(result.error).toContain("not in allowed list");
});
it("should prevent prefix-based directory traversal", () => {
// /tmp/safe should NOT allow /tmp/safevil/file.pdf
allowedLocalDirs.add("/tmp/safe");
const result = validateUrl("file:///tmp/safevil/file.pdf");
expect(result.valid).toBe(false);
});
it("should still allow exact file matches from allowedLocalFiles", () => {
const filePath = path.resolve(import.meta.dirname, "server.ts");
allowedLocalFiles.add(filePath);
const result = validateUrl(pathToFileUrl(filePath));
expect(result.valid).toBe(true);
});
it("should reject non-existent file even if under allowed dir", () => {
const dir = path.resolve(import.meta.dirname);
allowedLocalDirs.add(dir);
const result = validateUrl(
pathToFileUrl(path.join(dir, "nonexistent-file.pdf")),
);
expect(result.valid).toBe(false);
expect(result.error).toContain("File not found");
});
it("should allow a file under an allowed dir with trailing slash", () => {
const dir = path.resolve(import.meta.dirname);
// Simulate a dir stored with a trailing slash (e.g. from CLI path)
allowedLocalDirs.add(dir + "/");
const filePath = path.join(dir, "server.ts");
const result = validateUrl(pathToFileUrl(filePath));
expect(result.valid).toBe(true);
});
it("should allow a file under a grandparent allowed dir", () => {
// Allow a directory two levels up from the file
const grandparent = path.resolve(path.join(import.meta.dirname, ".."));
allowedLocalDirs.add(grandparent);
const filePath = path.join(import.meta.dirname, "server.ts");
const result = validateUrl(pathToFileUrl(filePath));
expect(result.valid).toBe(true);
});
it("should accept computer:// URLs as local files", () => {
const dir = path.resolve(import.meta.dirname);
allowedLocalDirs.add(dir);
const filePath = path.join(dir, "server.ts");
const encoded = encodeURIComponent(filePath).replace(/%2F/g, "/");
const result = validateUrl(`computer://${encoded}`);
expect(result.valid).toBe(true);
});
it("should accept bare absolute paths as local files", () => {
const dir = path.resolve(import.meta.dirname);
allowedLocalDirs.add(dir);
const filePath = path.join(dir, "server.ts");
const result = validateUrl(filePath);
expect(result.valid).toBe(true);
});
it("should decode percent-encoded bare paths (e.g. %20 for spaces)", () => {
const fs = require("node:fs");
const os = require("node:os");
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdf test "));
const testFile = path.join(tmpDir, "file.txt");
try {
fs.writeFileSync(testFile, "hello");
allowedLocalDirs.add(tmpDir);
// Encode spaces as %20 in the path (as some clients do)
const encoded = testFile.replace(/ /g, "%20");
const result = validateUrl(encoded);
expect(result.valid).toBe(true);
} finally {
fs.rmSync(tmpDir, { recursive: true });
}
});
it("should allow file accessed via symlink when real dir is allowed", () => {
const fs = require("node:fs");
const os = require("node:os");
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdf-test-"));
const realDir = path.join(tmpDir, "real");
const linkDir = path.join(tmpDir, "link");
const testFile = path.join(realDir, "test.txt");
try {
fs.mkdirSync(realDir);
fs.writeFileSync(testFile, "hello");
fs.symlinkSync(realDir, linkDir);
// Allow the REAL directory
allowedLocalDirs.add(realDir);
// Access via the SYMLINK path — should still be allowed
const symlinkPath = path.join(linkDir, "test.txt");
const result = validateUrl(symlinkPath);
expect(result.valid).toBe(true);
} finally {
fs.rmSync(tmpDir, { recursive: true });
}
});
it("should allow file when allowed dir is a symlink to real parent", () => {
const fs = require("node:fs");
const os = require("node:os");
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdf-test-"));
const realDir = path.join(tmpDir, "real");
const linkDir = path.join(tmpDir, "link");
const testFile = path.join(realDir, "test.txt");
try {
fs.mkdirSync(realDir);
fs.writeFileSync(testFile, "hello");
fs.symlinkSync(realDir, linkDir);
// Allow the SYMLINK directory
allowedLocalDirs.add(linkDir);
// Access via the REAL path — should still be allowed
const result = validateUrl(testFile);
expect(result.valid).toBe(true);
} finally {
fs.rmSync(tmpDir, { recursive: true });
}
});
});
describe("isAncestorDir", () => {
it("should return true for a direct child", () => {
expect(isAncestorDir("/Users/test/dir", "/Users/test/dir/file.pdf")).toBe(
true,
);
});
it("should return true for a nested child", () => {
expect(isAncestorDir("/Users/test", "/Users/test/sub/dir/file.pdf")).toBe(
true,
);
});
it("should return false for a file outside the dir", () => {
expect(isAncestorDir("/Users/test/dir", "/Users/test/other/file.pdf")).toBe(
false,
);
});
it("should return false for the dir itself", () => {
expect(isAncestorDir("/Users/test/dir", "/Users/test/dir")).toBe(false);
});
it("should prevent .. traversal", () => {
expect(
isAncestorDir("/Users/test/dir", "/Users/test/dir/../other/file.pdf"),
).toBe(false);
});
it("should prevent prefix-based traversal", () => {
// /tmp/safe should NOT match /tmp/safevil/file.pdf
expect(isAncestorDir("/tmp/safe", "/tmp/safevil/file.pdf")).toBe(false);
});
it("should handle dirs with trailing slash", () => {
expect(isAncestorDir("/Users/test/dir/", "/Users/test/dir/file.pdf")).toBe(
true,
);
});
});
describe("createServer useClientRoots option", () => {
it("should not set up roots handlers by default", () => {
const server = createServer();
// When useClientRoots is false (default), oninitialized should NOT
// be overridden by our roots logic.
expect(server.server.oninitialized).toBeUndefined();
server.close();
});
it("should not set up roots handlers when useClientRoots is false", () => {
const server = createServer({ useClientRoots: false });
expect(server.server.oninitialized).toBeUndefined();
server.close();
});
it("should set up roots handlers when useClientRoots is true", () => {
const server = createServer({ useClientRoots: true });
// When useClientRoots is true, oninitialized should be set to
// the roots refresh handler.
expect(server.server.oninitialized).toBeFunction();
server.close();
});
});
describe("isWritablePath", () => {
let savedFiles: Set<string>;
let savedDirs: Set<string>;
let savedCli: Set<string>;
let savedAllowUploadsRoot: boolean;
beforeEach(() => {
savedFiles = new Set(allowedLocalFiles);
savedDirs = new Set(allowedLocalDirs);
savedCli = new Set(cliLocalFiles);
allowedLocalFiles.clear();
allowedLocalDirs.clear();
cliLocalFiles.clear();
savedAllowUploadsRoot = writeFlags.allowUploadsRoot;
writeFlags.allowUploadsRoot = false;
});
afterEach(() => {
allowedLocalFiles.clear();
allowedLocalDirs.clear();
cliLocalFiles.clear();
for (const x of savedFiles) allowedLocalFiles.add(x);
for (const x of savedDirs) allowedLocalDirs.add(x);
for (const x of savedCli) cliLocalFiles.add(x);
writeFlags.allowUploadsRoot = savedAllowUploadsRoot;
});
it("nothing is writable when no roots and no CLI files", () => {
expect(isWritablePath("/any/path/file.pdf")).toBe(false);
});
it("CLI file is writable", () => {
allowedLocalFiles.add("/tmp/explicit.pdf");
cliLocalFiles.add("/tmp/explicit.pdf");
expect(isWritablePath("/tmp/explicit.pdf")).toBe(true);
});
it("MCP file root is NOT writable", () => {
allowedLocalFiles.add("/tmp/uploaded.pdf"); // from refreshRoots, no CLI
expect(isWritablePath("/tmp/uploaded.pdf")).toBe(false);
});
it("file under a directory root at any depth is writable", () => {
allowedLocalDirs.add("/home/user/docs");
expect(isWritablePath("/home/user/docs/file.pdf")).toBe(true);
expect(isWritablePath("/home/user/docs/sub/deep/file.pdf")).toBe(true);
});
it("the directory root itself is NOT writable", () => {
allowedLocalDirs.add("/home/user/docs");
expect(isWritablePath("/home/user/docs")).toBe(false);
});
it("MCP file root stays read-only even when under a directory root", () => {
// Client sent BOTH the directory and a file inside it as roots.
// The explicit file-root is the stronger signal: treat as upload.
allowedLocalDirs.add("/home/user/docs");
allowedLocalFiles.add("/home/user/docs/uploaded.pdf");
expect(isWritablePath("/home/user/docs/uploaded.pdf")).toBe(false);
// Siblings not sent as file roots remain writable
expect(isWritablePath("/home/user/docs/other.pdf")).toBe(true);
});
it("CLI file wins even if also in allowedLocalFiles", () => {
// CLI file added to both sets (main.ts does this)
allowedLocalFiles.add("/tmp/cli.pdf");
cliLocalFiles.add("/tmp/cli.pdf");
expect(isWritablePath("/tmp/cli.pdf")).toBe(true);
});
it("file outside any directory root is not writable", () => {
allowedLocalDirs.add("/home/user/docs");
expect(isWritablePath("/home/user/other/file.pdf")).toBe(false);
expect(isWritablePath("/home/user/docsevil/file.pdf")).toBe(false);
});
it("dir root named 'uploads' is read-only by default", () => {
// Claude Desktop mounts the conversation's attachment drop folder as a
// directory root literally named 'uploads'. The attached PDF lives
// directly under it.
allowedLocalDirs.add("/var/folders/xy/T/claude/uploads");
expect(isWritablePath("/var/folders/xy/T/claude/uploads/Form.pdf")).toBe(
false,
);
// Deep nesting under the uploads root — still the same root, still no.
expect(
isWritablePath("/var/folders/xy/T/claude/uploads/sub/deep.pdf"),
).toBe(false);
});
it("uploads-root guard matches basename, not substring", () => {
allowedLocalDirs.add("/home/user/my-uploads"); // contains 'uploads' but ≠
allowedLocalDirs.add("/home/user/uploads-archive");
expect(isWritablePath("/home/user/my-uploads/f.pdf")).toBe(true);
expect(isWritablePath("/home/user/uploads-archive/f.pdf")).toBe(true);
});
it("--writeable-uploads-root opts back in", () => {
allowedLocalDirs.add("/var/folders/xy/T/claude/uploads");
writeFlags.allowUploadsRoot = true;
expect(isWritablePath("/var/folders/xy/T/claude/uploads/Form.pdf")).toBe(
true,
);
});
it("CLI file under an uploads root is still writable", () => {
// Explicit CLI intent beats the uploads-basename heuristic.
allowedLocalDirs.add("/tmp/uploads");
allowedLocalFiles.add("/tmp/uploads/explicit.pdf");
cliLocalFiles.add("/tmp/uploads/explicit.pdf");
expect(isWritablePath("/tmp/uploads/explicit.pdf")).toBe(true);
});
});
describe("file watching", () => {
let tmpDir: string;
let tmpFile: string;
const uuid = "test-watch-uuid";
// Long-poll timeout is 30s — tests that poll must complete sooner.
const pollWithTimeout = async (
client: Client,
timeoutMs = 5000,
): Promise<{ type: string; mtimeMs?: number }[]> => {
const result = await Promise.race([
client.callTool({
name: "poll_pdf_commands",
arguments: { viewUUID: uuid },
}),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("poll timeout")), timeoutMs),
),
]);
return (
((result as { structuredContent?: { commands?: unknown[] } })
.structuredContent?.commands as { type: string; mtimeMs?: number }[]) ??
[]
);
};
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdf-watch-"));
tmpFile = path.join(tmpDir, "test.pdf");
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%test\n"));
allowedLocalFiles.add(tmpFile);
cliLocalFiles.add(tmpFile); // save_pdf test needs write scope
});
afterEach(() => {
stopFileWatch(uuid);
allowedLocalFiles.delete(tmpFile);
cliLocalFiles.delete(tmpFile);
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it("enqueues file_changed after external write", async () => {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
startFileWatch(uuid, tmpFile);
await new Promise((r) => setTimeout(r, 50)); // let watcher settle
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%changed\n"));
const cmds = await pollWithTimeout(client);
expect(cmds).toHaveLength(1);
expect(cmds[0].type).toBe("file_changed");
expect(cmds[0].mtimeMs).toBeGreaterThan(0);
await client.close();
await server.close();
});
it("debounces rapid writes into one command", async () => {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
startFileWatch(uuid, tmpFile);
await new Promise((r) => setTimeout(r, 50));
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%a\n"));
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%b\n"));
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%c\n"));
const cmds = await pollWithTimeout(client);
expect(cmds).toHaveLength(1);
await client.close();
await server.close();
});
it("stopFileWatch prevents further commands", async () => {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
startFileWatch(uuid, tmpFile);
await new Promise((r) => setTimeout(r, 50));
stopFileWatch(uuid);
fs.writeFileSync(tmpFile, Buffer.from("%PDF-1.4\n%x\n"));
// Debounce window + margin — no event should fire
await new Promise((r) => setTimeout(r, 300));
// Poll should block (long-poll) → timeout here means no command was queued
await expect(pollWithTimeout(client, 500)).rejects.toThrow("poll timeout");
await client.close();
await server.close();
});
it("save_pdf returns mtimeMs in structuredContent", async () => {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
const before = fs.statSync(tmpFile).mtimeMs;
// Ensure mtime will differ on coarse-granularity filesystems
await new Promise((r) => setTimeout(r, 10));
const r = await client.callTool({
name: "save_pdf",
arguments: {
url: tmpFile,
data: Buffer.from("%PDF-1.4\nnew").toString("base64"),
},
});
expect(r.isError).toBeFalsy();
const sc = r.structuredContent as { filePath: string; mtimeMs: number };
expect(sc.filePath).toBe(tmpFile);
expect(sc.mtimeMs).toBeGreaterThanOrEqual(before);
await client.close();
await server.close();
});
it("save_pdf refuses file roots from MCP client (not CLI)", async () => {
// Simulate: file is readable (in allowedLocalFiles via refreshRoots)
// but NOT in cliLocalFiles — it came from the client, not a CLI arg.
cliLocalFiles.delete(tmpFile);
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
const original = fs.readFileSync(tmpFile);
const r = await client.callTool({
name: "save_pdf",
arguments: {
url: tmpFile,
data: Buffer.from("%PDF-1.4\nshould-not-write").toString("base64"),
},
});
expect(r.isError).toBe(true);
const text = (r.content as { text: string }[])[0].text;
expect(text).toContain("read-only");
// Verify the file was NOT modified
expect(fs.readFileSync(tmpFile)).toEqual(original);
await client.close();
await server.close();
});
it("save_pdf allows files under a directory root", async () => {
// File is under a mounted directory root — but NOT itself a file root
// (a file root, even under a mounted dir, is read-only per isWritablePath).
cliLocalFiles.delete(tmpFile);
allowedLocalFiles.delete(tmpFile);
allowedLocalDirs.add(tmpDir);
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
const r = await client.callTool({
name: "save_pdf",
arguments: {
url: tmpFile,
data: Buffer.from("%PDF-1.4\nvia-dir-root").toString("base64"),
},
});
expect(r.isError).toBeFalsy();
expect(fs.readFileSync(tmpFile, "utf8")).toBe("%PDF-1.4\nvia-dir-root");
allowedLocalDirs.delete(tmpDir);
await client.close();
await server.close();
});
// fs.watch on a file that gets replaced via rename: on macOS (kqueue)
// the watcher reliably fires a "rename" event which our re-attach logic
// handles. On Linux (inotify), a watcher on the old inode often gets no
// event at all — inotify watches inodes, and the rename just atomically
// swaps the directory entry to a NEW inode. Directory-level watching
// would fix this but isn't what we do. Skip on non-darwin.
it.skipIf(process.platform !== "darwin")(
"detects atomic rename (macOS kqueue only)",
async () => {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
startFileWatch(uuid, tmpFile);
await new Promise((r) => setTimeout(r, 50));
// Simulate vim/vscode: write to temp, rename over original
const tmpWrite = tmpFile + ".swp";
fs.writeFileSync(tmpWrite, Buffer.from("%PDF-1.4\n%atomic\n"));
fs.renameSync(tmpWrite, tmpFile);
const cmds = await pollWithTimeout(client);
expect(cmds).toHaveLength(1);
expect(cmds[0].type).toBe("file_changed");
await client.close();
await server.close();
},
);
});
describe("interact tool", () => {
// Helper: connected server+client pair with interact enabled.
// Command queues are MODULE-LEVEL (shared across server instances), so each
// test uses a distinct viewUUID to avoid cross-test interference.
async function connect() {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
return { server, client };
}
// Helper: poll with an outer deadline so a failing test doesn't hang for the
// full 30s long-poll. Safe ONLY when a command is already enqueued — poll
// then returns after the 200ms batch window.
async function poll(client: Client, uuid: string, timeoutMs = 2000) {
const result = await Promise.race([
client.callTool({
name: "poll_pdf_commands",
arguments: { viewUUID: uuid },
}),
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("poll timeout")), timeoutMs),
),
]);
return ((result as { structuredContent?: { commands?: unknown[] } })
.structuredContent?.commands ?? []) as Array<Record<string, unknown>>;
}
function firstText(r: Awaited<ReturnType<Client["callTool"]>>): string {
return (r.content as Array<{ type: string; text: string }>)[0].text;
}
it("enqueue → poll roundtrip delivers the command", async () => {
const { server, client } = await connect();
const uuid = "test-interact-roundtrip";
const r = await client.callTool({
name: "interact",
arguments: { viewUUID: uuid, action: "navigate", page: 5 },
});
expect(r.isError).toBeFalsy();
expect(firstText(r)).toContain("Queued");
expect(firstText(r)).toContain("page 5");
// Core mechanism: the viewer polls for what the model enqueued.
const cmds = await poll(client, uuid);
expect(cmds).toHaveLength(1);
expect(cmds[0].type).toBe("navigate");
expect(cmds[0].page).toBe(5);
await client.close();
await server.close();
});
it("navigate without `page` returns isError with a helpful message", async () => {
const { server, client } = await connect();
const r = await client.callTool({
name: "interact",
arguments: { viewUUID: "test-err-nav", action: "navigate" },
});
expect(r.isError).toBe(true);
expect(firstText(r)).toContain("navigate");
expect(firstText(r)).toContain("page");
await client.close();
await server.close();
});
it("fill_form without `fields` returns isError with a helpful message", async () => {
const { server, client } = await connect();
const r = await client.callTool({
name: "interact",
arguments: { viewUUID: "test-err-fill", action: "fill_form" },
});
expect(r.isError).toBe(true);
expect(firstText(r)).toContain("fill_form");
expect(firstText(r)).toContain("fields");
await client.close();
await server.close();
});
it("add_annotations without `annotations` returns isError with a helpful message", async () => {
const { server, client } = await connect();
const r = await client.callTool({
name: "interact",
arguments: { viewUUID: "test-err-ann", action: "add_annotations" },
});
expect(r.isError).toBe(true);
expect(firstText(r)).toContain("add_annotations");
expect(firstText(r)).toContain("annotations");
await client.close();
await server.close();
});
it("isolates command queues across distinct viewUUIDs", async () => {
const { server, client } = await connect();
const uuidA = "test-isolate-A";
const uuidB = "test-isolate-B";
await client.callTool({
name: "interact",
arguments: { viewUUID: uuidA, action: "navigate", page: 3 },
});
await client.callTool({
name: "interact",
arguments: { viewUUID: uuidB, action: "search", query: "quantum" },
});
const cmdsA = await poll(client, uuidA);
expect(cmdsA).toHaveLength(1);
expect(cmdsA[0].type).toBe("navigate");
expect(cmdsA[0].page).toBe(3);
const cmdsB = await poll(client, uuidB);
expect(cmdsB).toHaveLength(1);
expect(cmdsB[0].type).toBe("search");
expect(cmdsB[0].query).toBe("quantum");
await client.close();
await server.close();
});
// SKIPPED: the unknown-UUID path enters the long-poll branch and blocks for
// the full LONG_POLL_TIMEOUT_MS (30s, module-local const, not configurable).
// The handler does dequeue [] at the end, so the return value IS
// {commands: []} — but there's no fast path to reach it without waiting.
// See the `stopFileWatch prevents further commands` test above for indirect
// coverage of the same blocking behaviour.
it.skip("poll with unknown viewUUID returns {commands: []} after long-poll", () => {});
it("fill_form passes all fields through when viewFieldNames is not registered", async () => {
const { server, client } = await connect();
// Fresh UUID never seen by display_pdf → viewFieldNames.get(uuid) is
// undefined → the known-fields guard (`knownFields && !knownFields.has()`)
// is falsy for every field → everything is enqueued.
const uuid = "test-fillform-passthrough";
const r = await client.callTool({
name: "interact",
arguments: {
viewUUID: uuid,
action: "fill_form",
fields: [
{ name: "anything", value: "goes" },
{ name: "unchecked", value: true },
],
},
});
expect(r.isError).toBeFalsy();
expect(firstText(r)).toContain("Filled 2 field(s)");
// No rejection complaint — the registry has no entry for this UUID
expect(firstText(r)).not.toContain("Unknown");
const cmds = await poll(client, uuid);
expect(cmds).toHaveLength(1);
expect(cmds[0].type).toBe("fill_form");
const fields = cmds[0].fields as Array<{ name: string; value: unknown }>;
expect(fields).toHaveLength(2);
expect(fields.map((f) => f.name).sort()).toEqual(["anything", "unchecked"]);
// Note: the "registered → reject unknown" branch needs viewFieldNames
// populated, which only happens inside display_pdf (requires a real PDF).
// That map isn't exported, so the rejection path is covered by e2e only.
await client.close();
await server.close();
});
// SECURITY: resolveImageAnnotation must not read arbitrary local files.
// The model controls imageUrl; without validation it's an exfil primitive
// (readFile → base64 → iframe → get_screenshot reads it back).
describe("add_annotations image: imageUrl validation", () => {
let savedDirs: Set<string>;
beforeEach(() => {
savedDirs = new Set(allowedLocalDirs);
allowedLocalDirs.clear();
});
afterEach(() => {
allowedLocalDirs.clear();
for (const d of savedDirs) allowedLocalDirs.add(d);
});
it("rejects local path outside allowed roots", async () => {
const { server, client } = await connect();
// Whitelist a harmless temp dir; target a path clearly outside it.
allowedLocalDirs.add(os.tmpdir());
const target = path.join(os.homedir(), ".ssh", "id_rsa");
const r = await client.callTool({
name: "interact",
arguments: {
viewUUID: "sec-local",
action: "add_annotations",
annotations: [{ type: "image", id: "i1", page: 1, imageUrl: target }],
},
});
expect(r.isError).toBe(true);
expect(firstText(r)).toContain("imageUrl rejected");
await client.close();
await server.close();
});
it("rejects http:// URL (SSRF)", async () => {
const { server, client } = await connect();
const r = await client.callTool({
name: "interact",