-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathindex.test.ts
More file actions
1229 lines (1123 loc) · 46.7 KB
/
Copy pathindex.test.ts
File metadata and controls
1229 lines (1123 loc) · 46.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
atomicCopyFile,
createCommandInvocation,
createPackageManagerInvocation,
createProcessStampArgs,
mergeProxyAwareEnv,
matchesStampedProcess,
parseMacosScutilProxyOutput,
parseWindowsInternetSettingsProxyOutput,
pathContains,
readProcessStampFromCommand,
removePathBestEffort,
resolveSystemProxyEnv,
wellKnownUserToolchainBins,
type ProcessStampContract,
} from "../src/index.js";
type FakeStamp = {
app: "api" | "ui";
ipc: string;
mode: "dev" | "runtime";
namespace: string;
source: "tool" | "pack";
};
const fakeContract: ProcessStampContract<FakeStamp> = {
stampFields: ["app", "mode", "namespace", "ipc", "source"],
stampFlags: {
app: "--fake-app",
ipc: "--fake-ipc",
mode: "--fake-mode",
namespace: "--fake-namespace",
source: "--fake-source",
},
normalizeStamp(input) {
const value = input as Partial<FakeStamp>;
if (value.app !== "api" && value.app !== "ui") throw new Error("invalid app");
if (value.mode !== "dev" && value.mode !== "runtime") throw new Error("invalid mode");
if (typeof value.namespace !== "string" || value.namespace.length === 0) throw new Error("invalid namespace");
if (typeof value.ipc !== "string" || value.ipc.length === 0) throw new Error("invalid ipc");
if (value.source !== "tool" && value.source !== "pack") throw new Error("invalid source");
return {
app: value.app,
ipc: value.ipc,
mode: value.mode,
namespace: value.namespace,
source: value.source,
};
},
normalizeStampCriteria(input = {}) {
const value = input as Partial<FakeStamp>;
return {
...(value.app == null ? {} : { app: value.app }),
...(value.ipc == null ? {} : { ipc: value.ipc }),
...(value.mode == null ? {} : { mode: value.mode }),
...(value.namespace == null ? {} : { namespace: value.namespace }),
...(value.source == null ? {} : { source: value.source }),
};
},
};
const stamp: FakeStamp = {
app: "ui",
ipc: "/tmp/fake-product/ipc/stamp-boundary-a/ui.sock",
mode: "dev",
namespace: "stamp-boundary-a",
source: "tool",
};
describe("generic process stamp primitives", () => {
it("serializes descriptor-defined stamp flags", () => {
const args = createProcessStampArgs(stamp, fakeContract);
expect(args).toHaveLength(5);
expect(args.join(" ")).toContain("--fake-app=ui");
expect(args.join(" ")).toContain("--fake-mode=dev");
expect(args.join(" ")).toContain("--fake-namespace=stamp-boundary-a");
expect(args.join(" ")).toContain("--fake-ipc=/tmp/fake-product/ipc/stamp-boundary-a/ui.sock");
expect(args.join(" ")).toContain("--fake-source=tool");
});
it("reads and matches stamped process commands using the descriptor", () => {
const command = ["node", "ui.js", ...createProcessStampArgs(stamp, fakeContract)].join(" ");
expect(readProcessStampFromCommand(command, fakeContract)).toEqual(stamp);
expect(matchesStampedProcess({ command }, { app: "ui", namespace: stamp.namespace, source: "tool" }, fakeContract)).toBe(true);
expect(matchesStampedProcess({ command }, { namespace: "stamp-boundary-b" }, fakeContract)).toBe(false);
expect(matchesStampedProcess({ command }, { source: "pack" }, fakeContract)).toBe(false);
});
});
describe("generic filesystem primitives", () => {
it("recognizes paths contained by a resolved root", () => {
const root = join(tmpdir(), "platform-path-root");
expect(pathContains(root, join(root, "child", "file.txt"))).toBe(true);
expect(pathContains(root, root)).toBe(true);
expect(pathContains(root, join(root, "..", "outside.txt"))).toBe(false);
});
it("copies through a destination-local temporary file", async () => {
const root = mkdtempSync(join(tmpdir(), "platform-atomic-copy-"));
try {
const source = join(root, "source.bin");
const destination = join(root, "nested", "destination.bin");
writeFileSync(source, "atomic copy payload");
const result = await atomicCopyFile(source, destination);
expect(result).toEqual({ bytesCopied: "atomic copy payload".length, replaced: false });
expect(readFileSync(destination, "utf8")).toBe("atomic copy payload");
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("refuses to replace an existing destination unless overwrite is explicit", async () => {
const root = mkdtempSync(join(tmpdir(), "platform-atomic-copy-exists-"));
try {
const source = join(root, "source.bin");
const destination = join(root, "destination.bin");
writeFileSync(source, "new payload");
writeFileSync(destination, "old payload");
await expect(atomicCopyFile(source, destination)).rejects.toMatchObject({ code: "EEXIST" });
expect(readFileSync(destination, "utf8")).toBe("old payload");
const overwritten = await atomicCopyFile(source, destination, { overwrite: true });
expect(overwritten.replaced).toBe(true);
expect(readFileSync(destination, "utf8")).toBe("new payload");
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("removes paths best-effort without throwing on missing paths", async () => {
const root = mkdtempSync(join(tmpdir(), "platform-best-effort-rm-"));
const target = join(root, "target");
mkdirSync(target);
try {
expect((await removePathBestEffort(target)).removed).toBe(true);
expect(existsSync(target)).toBe(false);
expect((await removePathBestEffort(target)).removed).toBe(true);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
describe("system proxy env resolution", () => {
it("enables Node env proxy support when merging user proxy variables", () => {
const env = mergeProxyAwareEnv("darwin", {
http_proxy: "http://user-proxy:7890",
});
expect(env).toMatchObject({
HTTP_PROXY: "http://user-proxy:7890",
NODE_USE_ENV_PROXY: "1",
http_proxy: "http://user-proxy:7890",
});
});
it("preserves an explicit NODE_USE_ENV_PROXY value when merging user proxy variables", () => {
const env = mergeProxyAwareEnv("darwin", {
HTTPS_PROXY: "http://user-proxy:7891",
NODE_USE_ENV_PROXY: "0",
});
expect(env.HTTPS_PROXY).toBe("http://user-proxy:7891");
expect(env.NODE_USE_ENV_PROXY).toBe("0");
});
it("parses macOS scutil output into standard proxy env vars", () => {
const env = parseMacosScutilProxyOutput(`
<dictionary> {
ExceptionsList : <array> {
0 : *.local
1 : localhost
}
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : 127.0.0.1
HTTPSEnable : 1
HTTPSPort : 7891
HTTPSProxy : corp-proxy.internal
SOCKSEnable : 1
SOCKSPort : 1080
SOCKSProxy : 127.0.0.1
}
`);
expect(env).toMatchObject({
HTTP_PROXY: "http://127.0.0.1:7890",
HTTPS_PROXY: "http://corp-proxy.internal:7891",
ALL_PROXY: "socks5://127.0.0.1:1080",
NO_PROXY: ".local,localhost,127.0.0.1,[::1]",
NODE_USE_ENV_PROXY: "1",
http_proxy: "http://127.0.0.1:7890",
https_proxy: "http://corp-proxy.internal:7891",
all_proxy: "socks5://127.0.0.1:1080",
no_proxy: ".local,localhost,127.0.0.1,[::1]",
});
});
it("brackets IPv6 system proxy hosts before composing proxy URLs", () => {
const env = parseMacosScutilProxyOutput(`
<dictionary> {
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : ::1
HTTPSEnable : 1
HTTPSPort : 7891
HTTPSProxy : 2001:db8::10
SOCKSEnable : 1
SOCKSPort : 1080
SOCKSProxy : fe80::1
}
`);
expect(env).toMatchObject({
HTTP_PROXY: "http://[::1]:7890",
HTTPS_PROXY: "http://[2001:db8::10]:7891",
ALL_PROXY: "socks5://[fe80::1]:1080",
http_proxy: "http://[::1]:7890",
https_proxy: "http://[2001:db8::10]:7891",
all_proxy: "socks5://[fe80::1]:1080",
});
});
it("parses Windows Internet Settings proxy registry values", () => {
const env = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ http=10.0.0.2:8080;https=10.0.0.3:8443;socks=10.0.0.4:1080
`,
proxyOverride: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyOverride REG_SZ localhost;<local>;*.corp
`,
});
expect(env).toEqual({
HTTP_PROXY: "http://10.0.0.2:8080",
HTTPS_PROXY: "http://10.0.0.3:8443",
ALL_PROXY: "socks5://10.0.0.4:1080",
NO_PROXY: "localhost,<local>,127.0.0.1,[::1],.local,.corp",
NODE_USE_ENV_PROXY: "1",
});
});
it("brackets Windows IPv6 proxy hosts before composing proxy URLs", () => {
const segmented = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ http=::1:8080;https=2001:db8::10:8443;socks=fe80::1:1080
`,
});
const shared = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ ::1:8080
`,
});
expect(segmented).toMatchObject({
HTTP_PROXY: "http://[::1]:8080",
HTTPS_PROXY: "http://[2001:db8::10]:8443",
ALL_PROXY: "socks5://[fe80::1]:1080",
});
expect(shared).toMatchObject({
HTTP_PROXY: "http://[::1]:8080",
HTTPS_PROXY: "http://[::1]:8080",
});
});
it("normalizes bare IPv6 loopback bypass entries to bracketed form", () => {
const env = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ http=10.0.0.2:8080
`,
proxyOverride: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyOverride REG_SZ ::1;localhost
`,
});
expect(env.NO_PROXY).toBe("[::1],localhost,127.0.0.1");
});
it("preserves a wildcard macOS bypass list", () => {
const env = parseMacosScutilProxyOutput(`
<dictionary> {
ExceptionsList : <array> {
0 : *
}
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : 127.0.0.1
}
`);
expect(env.NO_PROXY).toBe("*");
expect(env.no_proxy).toBe("*");
});
it("preserves a wildcard macOS bypass list when other entries are present", () => {
const env = parseMacosScutilProxyOutput(`
<dictionary> {
ExceptionsList : <array> {
0 : *
1 : <local>
}
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : 127.0.0.1
}
`);
expect(env.NO_PROXY).toBe("*");
expect(env.no_proxy).toBe("*");
});
it("adds <local> to the macOS bypass list when simple hostnames are excluded", () => {
const env = parseMacosScutilProxyOutput(`
<dictionary> {
ExcludeSimpleHostnames : 1
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : 127.0.0.1
}
`);
expect(env.NO_PROXY).toBe("<local>,localhost,127.0.0.1,[::1],.local");
expect(env.no_proxy).toBe("<local>,localhost,127.0.0.1,[::1],.local");
});
it("preserves a wildcard Windows bypass list", () => {
const env = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ http=10.0.0.2:8080
`,
proxyOverride: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyOverride REG_SZ *
`,
});
expect(env.NO_PROXY).toBe("*");
});
it("preserves a wildcard Windows bypass list when other entries are present", () => {
const env = parseWindowsInternetSettingsProxyOutput({
proxyEnable: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyEnable REG_DWORD 0x1
`,
proxyServer: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyServer REG_SZ http=10.0.0.2:8080
`,
proxyOverride: `
HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings
ProxyOverride REG_SZ *;<local>
`,
});
expect(env.NO_PROXY).toBe("*");
});
it("resolves macOS system proxy env through the command runner", () => {
const env = resolveSystemProxyEnv({
platform: "darwin",
runCommand(command, args) {
expect(command).toBe("scutil");
expect(args).toEqual(["--proxy"]);
return `
<dictionary> {
HTTPEnable : 1
HTTPPort : 8888
HTTPProxy : 127.0.0.1
}
`;
},
});
expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
expect(env.NODE_USE_ENV_PROXY).toBe("1");
});
it("returns an empty object when the platform has no system proxy adapter", () => {
expect(resolveSystemProxyEnv({ platform: "linux" })).toEqual({});
});
it("does not cache system proxy resolution across calls", () => {
const values = [
"\n<dictionary> {\n HTTPEnable : 1\n HTTPPort : 8001\n HTTPProxy : 127.0.0.1\n}\n",
"\n<dictionary> {\n HTTPEnable : 1\n HTTPPort : 8002\n HTTPProxy : 127.0.0.1\n}\n",
];
let callCount = 0;
const runCommand = () => values[callCount++] ?? values.at(-1) ?? "";
const first = resolveSystemProxyEnv({ platform: "darwin", runCommand });
const second = resolveSystemProxyEnv({ platform: "darwin", runCommand });
expect(first.HTTP_PROXY).toBe("http://127.0.0.1:8001");
expect(second.HTTP_PROXY).toBe("http://127.0.0.1:8002");
expect(callCount).toBe(2);
});
it("makes the last proxy env source win case-insensitively", () => {
const env = mergeProxyAwareEnv(
"linux",
{ HTTPS_PROXY: "http://system:8443", https_proxy: "http://system:8443" },
{ https_proxy: "http://user:9443" },
);
expect(env.HTTPS_PROXY).toBe("http://user:9443");
expect(env.https_proxy).toBe("http://user:9443");
});
it("makes lowercase proxy vars win within a single POSIX source", () => {
const env = mergeProxyAwareEnv("linux", {
http_proxy: "http://new:8080",
HTTP_PROXY: "http://old:8080",
HTTPS_PROXY: "http://older:8443",
https_proxy: "http://newer:8443",
});
expect(env.HTTP_PROXY).toBe("http://new:8080");
expect(env.http_proxy).toBe("http://new:8080");
expect(env.HTTPS_PROXY).toBe("http://newer:8443");
expect(env.https_proxy).toBe("http://newer:8443");
});
});
// `createCommandInvocation` makes a platform-conditional choice based on
// `process.platform`. These tests stub it both ways so we exercise the
// Windows .cmd / .bat shim path on every CI runner, not just Windows.
describe("createCommandInvocation", () => {
const originalPlatform = process.platform;
function setPlatform(value: NodeJS.Platform): void {
Object.defineProperty(process, "platform", { configurable: true, value });
}
afterEach(() => {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
});
it("returns the raw command and args unchanged on POSIX", () => {
setPlatform("linux");
const invocation = createCommandInvocation({
command: "/usr/local/bin/codex",
args: ["--help"],
});
expect(invocation).toEqual({
args: ["--help"],
command: "/usr/local/bin/codex",
});
expect(invocation.windowsVerbatimArguments).toBeUndefined();
});
it("returns the raw command and args unchanged on Windows for non-shim binaries", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "C:\\Program Files\\node\\node.exe",
args: ["script.js"],
});
expect(invocation).toEqual({
args: ["script.js"],
command: "C:\\Program Files\\node\\node.exe",
});
expect(invocation.windowsVerbatimArguments).toBeUndefined();
});
it("wraps a Windows .CMD shim through cmd.exe with verbatim arguments", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "C:\\Users\\Ethical Byte\\AppData\\Local\\Programs\\nodejs\\codex.CMD",
args: ["--version"],
env: { ComSpec: "C:\\Windows\\System32\\cmd.exe" } as NodeJS.ProcessEnv,
});
expect(invocation.command).toBe("C:\\Windows\\System32\\cmd.exe");
expect(invocation.windowsVerbatimArguments).toBe(true);
// Critical: the inner command line is wrapped in extra `"…"` so that
// cmd.exe's `/s /c` quote-stripping (strip first + last `"`) leaves the
// path quoting intact. Without the outer wrap, `Ethical Byte` gets
// split on the space and cmd reports "not recognized" (issue #315).
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'""C:\\Users\\Ethical Byte\\AppData\\Local\\Programs\\nodejs\\codex.CMD" --version"',
]);
});
it("treats .bat shims the same as .cmd shims", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "C:\\tools\\bin\\my tool.bat",
args: [],
env: { ComSpec: "cmd.exe" } as NodeJS.ProcessEnv,
});
expect(invocation.windowsVerbatimArguments).toBe(true);
expect(invocation.args).toEqual(["/d", "/s", "/c", '""C:\\tools\\bin\\my tool.bat""']);
});
it("quotes argv elements containing spaces alongside the shim path", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "C:\\Users\\First Last\\codex.cmd",
args: ["--cwd", "C:\\Some Path\\proj", "exec", "echo hi"],
env: { ComSpec: "cmd.exe" } as NodeJS.ProcessEnv,
});
// After the outer wrap and `/s /c` stripping, cmd will see:
// "C:\Users\First Last\codex.cmd" --cwd "C:\Some Path\proj" exec "echo hi"
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'""C:\\Users\\First Last\\codex.cmd" --cwd "C:\\Some Path\\proj" exec "echo hi""',
]);
});
it("does not quote argv elements without whitespace or shell metacharacters", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "codex.cmd",
args: ["--model", "claude-opus-4", "--max-tokens=4096"],
env: { ComSpec: "cmd.exe" } as NodeJS.ProcessEnv,
});
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'"codex.cmd --model claude-opus-4 --max-tokens=4096"',
]);
});
// cmd.exe runs percent-expansion on the inner command line of `cmd /s /c
// "..."` regardless of inner quote state, so a `.cmd` shim spawn whose
// argv carries an attacker-influenced `%DEEPSEEK_API_KEY%` substring would
// otherwise have the daemon environment substituted into the child's
// command line before the child saw the prompt. Pin that the constructed
// invocation breaks every potential `%var%` pair with `"^%"` so cmd has no
// chance to expand it, while `CommandLineToArgvW` still concatenates the
// surrounding quote segments back into the original arg.
it("escapes %var% sequences in argv so cmd.exe cannot expand them on a .cmd shim", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "C:\\Users\\Tester\\AppData\\Roaming\\npm\\deepseek.cmd",
args: ["exec", "--auto", "write a function that reads %DEEPSEEK_API_KEY% from env"],
env: { ComSpec: "cmd.exe" } as NodeJS.ProcessEnv,
});
expect(invocation.command).toBe("cmd.exe");
expect(invocation.windowsVerbatimArguments).toBe(true);
// The full inner line cmd.exe receives after `/s` strips its outer wrap.
const innerLine = invocation.args[3];
if (typeof innerLine !== "string") throw new Error("expected an inner cmd line");
// The literal `%DEEPSEEK_API_KEY%` pair must NOT survive intact in the
// inner line — if it did, cmd would expand it before the child runs.
expect(innerLine).not.toContain("%DEEPSEEK_API_KEY%");
// Each `%` must be wrapped in `"^%"` so cmd's `^` escape neutralizes the
// percent and `CommandLineToArgvW` rejoins the quote segments. Two `%`
// chars in the prompt → two escaped occurrences.
const escapedOccurrences = innerLine.split('"^%"').length - 1;
expect(escapedOccurrences).toBe(2);
// Sanity: the literal env-var name still appears (the prompt itself is
// not corrupted, only the surrounding `%` are escaped).
expect(innerLine).toContain("DEEPSEEK_API_KEY");
});
it("does not perturb argv quoting when no %var% sequence is present", () => {
setPlatform("win32");
const invocation = createCommandInvocation({
command: "deepseek.cmd",
args: ["exec", "--auto", "write hello world"],
env: { ComSpec: "cmd.exe" } as NodeJS.ProcessEnv,
});
// Pre-fix shape — adding the `%` escape must not change the line for
// ordinary prompts that happen not to mention env-var names.
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'"deepseek.cmd exec --auto "write hello world""',
]);
});
it("falls back to process.env.ComSpec when env override is absent", () => {
setPlatform("win32");
const original = process.env.ComSpec;
process.env.ComSpec = "C:\\Windows\\System32\\cmd.exe";
try {
const invocation = createCommandInvocation({
command: "tool.cmd",
args: [],
});
expect(invocation.command).toBe("C:\\Windows\\System32\\cmd.exe");
} finally {
if (original == null) delete process.env.ComSpec;
else process.env.ComSpec = original;
}
});
});
describe("wellKnownUserToolchainBins Windows fnm node discovery", () => {
// Issue #3517: a GUI-launched packaged app on Windows inherits a stripped
// PATH and never sees fnm-managed Node. fnm on Windows keeps its installs
// under %APPDATA%\fnm\node-versions\<version>\installation, with node.exe
// directly in `installation` (no POSIX-style `bin` subdir). The toolchain
// bin list only probed ~/.fnm and ~/.local/share/fnm with [installation,
// bin] segments, so Windows fnm Node was silently undetected.
const originalPlatform = process.platform;
function setPlatform(value: NodeJS.Platform): void {
Object.defineProperty(process, "platform", { configurable: true, value });
}
afterEach(() => {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
});
it("surfaces the Windows fnm installation dir under %APPDATA%\\fnm", () => {
const home = mkdtempSync(join(tmpdir(), "od-fnm-home-"));
const appData = mkdtempSync(join(tmpdir(), "od-fnm-appdata-"));
const installDir = join(appData, "fnm", "node-versions", "v22.13.1", "installation");
mkdirSync(installDir, { recursive: true });
setPlatform("win32");
try {
const dirs = wellKnownUserToolchainBins({ home, env: { APPDATA: appData } });
expect(dirs).toContain(installDir);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(appData, { recursive: true, force: true });
}
});
it("honors FNM_DIR over %APPDATA% for the Windows fnm root", () => {
const home = mkdtempSync(join(tmpdir(), "od-fnm-home-"));
const fnmDir = mkdtempSync(join(tmpdir(), "od-fnm-dir-"));
const installDir = join(fnmDir, "node-versions", "v20.11.0", "installation");
mkdirSync(installDir, { recursive: true });
setPlatform("win32");
try {
const dirs = wellKnownUserToolchainBins({
home,
env: { APPDATA: join(home, "AppData", "Roaming"), FNM_DIR: fnmDir },
});
expect(dirs).toContain(installDir);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(fnmDir, { recursive: true, force: true });
}
});
it("surfaces the Windows fnm installation dir under %LOCALAPPDATA%\\fnm", () => {
// fnm on Windows can keep its root under %LOCALAPPDATA%\fnm (not only
// %APPDATA%\fnm). A globally `npm i -g`'d CLI (e.g. Codex) lands in the
// node install's `installation` dir, so probing this root makes that CLI
// discoverable from a GUI launch. See issue #3062.
const home = mkdtempSync(join(tmpdir(), "od-fnm-home-"));
const localAppData = mkdtempSync(join(tmpdir(), "od-fnm-localappdata-"));
const installDir = join(localAppData, "fnm", "node-versions", "v22.13.1", "installation");
mkdirSync(installDir, { recursive: true });
setPlatform("win32");
try {
const dirs = wellKnownUserToolchainBins({ home, env: { LOCALAPPDATA: localAppData } });
expect(dirs).toContain(installDir);
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(localAppData, { recursive: true, force: true });
}
});
});
describe("createPackageManagerInvocation", () => {
const originalPlatform = process.platform;
function setPlatform(value: NodeJS.Platform): void {
Object.defineProperty(process, "platform", { configurable: true, value });
}
afterEach(() => {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
});
it("uses Node-loadable npm_execpath via process.execPath when set", () => {
setPlatform("win32");
const invocation = createPackageManagerInvocation(["install"], {
npm_execpath: "C:\\Users\\u\\.nvm\\pnpm.cjs",
} as NodeJS.ProcessEnv);
expect(invocation.command).toBe(process.execPath);
expect(invocation.args[0]).toBe("C:\\Users\\u\\.nvm\\pnpm.cjs");
expect(invocation.args.slice(1)).toEqual(["install"]);
expect(invocation.windowsVerbatimArguments).toBeUndefined();
});
it("executes native npm_execpath directly instead of loading it through Node", () => {
setPlatform("linux");
const invocation = createPackageManagerInvocation(["--filter", "@open-design/desktop", "build"], {
npm_execpath: "/home/u/.local/share/pnpm/.tools/@pnpm+linux-x64/10.33.2/node_modules/@pnpm/linux-x64/pnpm",
} as NodeJS.ProcessEnv);
expect(invocation).toEqual({
args: ["--filter", "@open-design/desktop", "build"],
command: "/home/u/.local/share/pnpm/.tools/@pnpm+linux-x64/10.33.2/node_modules/@pnpm/linux-x64/pnpm",
});
});
it("uses binary npm_execpath directly on POSIX", () => {
setPlatform("linux");
const invocation = createPackageManagerInvocation(["install"], {
npm_execpath: "/home/runner/setup-pnpm/node_modules/.bin/pnpm",
} as NodeJS.ProcessEnv);
expect(invocation).toEqual({
args: ["install"],
command: "/home/runner/setup-pnpm/node_modules/.bin/pnpm",
});
});
it("wraps binary npm_execpath shims through cmd.exe on Windows", () => {
setPlatform("win32");
const invocation = createPackageManagerInvocation(["install"], {
ComSpec: "cmd.exe",
npm_execpath: "C:\\Users\\u\\setup-pnpm\\pnpm.cmd",
} as NodeJS.ProcessEnv);
expect(invocation.command).toBe("cmd.exe");
expect(invocation.windowsVerbatimArguments).toBe(true);
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'"C:\\Users\\u\\setup-pnpm\\pnpm.cmd install"',
]);
});
it("returns corepack pnpm invocation on POSIX without npm_execpath", () => {
setPlatform("linux");
const invocation = createPackageManagerInvocation(["install"], {} as NodeJS.ProcessEnv);
expect(invocation).toEqual({ args: ["pnpm", "install"], command: "corepack" });
});
it("wraps corepack pnpm through cmd.exe with verbatim arguments on Windows", () => {
setPlatform("win32");
const invocation = createPackageManagerInvocation(["--filter", "@open-design/desktop", "build"], {
ComSpec: "cmd.exe",
} as NodeJS.ProcessEnv);
expect(invocation.command).toBe("cmd.exe");
expect(invocation.windowsVerbatimArguments).toBe(true);
expect(invocation.args).toEqual([
"/d",
"/s",
"/c",
'"corepack pnpm --filter @open-design/desktop build"',
]);
});
});
describe("wellKnownUserToolchainBins", () => {
// Filesystem-backed cases use a sandboxed home so we don't depend on the
// real machine's toolchain layout. PATHEXT-style Windows quirks aren't
// relevant here — the helper returns directories, not resolved binaries.
it("returns the documented user-level CLI install locations under home", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-home-"));
try {
const dirs = wellKnownUserToolchainBins({ home, env: {}, includeSystemBins: false });
expect(dirs).toContain(join(home, ".local", "bin"));
expect(dirs).toContain(join(home, ".kimi-code", "bin"));
expect(dirs).toContain(join(home, ".opencode", "bin"));
expect(dirs).toContain(join(home, ".bun", "bin"));
expect(dirs).toContain(join(home, ".volta", "bin"));
expect(dirs).toContain(join(home, ".asdf", "shims"));
expect(dirs).toContain(join(home, "Library", "pnpm"));
expect(dirs).toContain(join(home, ".cargo", "bin"));
expect(dirs).toContain(join(home, ".nix-profile", "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("includes ~/.grok/bin when PATH is stripped so Windows Grok Build resolves", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-grok-"));
try {
const dirs = wellKnownUserToolchainBins({ home, env: { PATH: "" }, includeSystemBins: false });
expect(dirs).toContain(join(home, ".grok", "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
}
});
// Non-Node user toolchains that still ship agent CLIs (or their deps):
// Deno's install root, Go's default GOBIN, and pyenv's shim dir. GUI
// launches inherit a stripped PATH, so these must be searched explicitly.
it("includes Deno, Go, and pyenv user toolchain dirs", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-extra-"));
try {
const dirs = wellKnownUserToolchainBins({ home, env: {}, includeSystemBins: false });
expect(dirs).toContain(join(home, ".deno", "bin"));
expect(dirs).toContain(join(home, "go", "bin"));
expect(dirs).toContain(join(home, ".pyenv", "shims"));
} finally {
rmSync(home, { recursive: true, force: true });
}
});
// Regression for #442. The two dominant non-canonical npm prefixes used
// by sudo-free tutorials (~/.npm-global, ~/.npm-packages) must always
// appear, otherwise GUI-launched daemons miss `npm i -g`'d CLIs.
it("includes both ~/.npm-global/bin and ~/.npm-packages/bin (issue #442)", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-npm-"));
try {
const dirs = wellKnownUserToolchainBins({ home, env: {}, includeSystemBins: false });
expect(dirs).toContain(join(home, ".npm-global", "bin"));
expect(dirs).toContain(join(home, ".npm-packages", "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("includes ~/.vite-plus/bin so vp-managed global shims resolve under GUI launchers", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-vp-"));
try {
const dirs = wellKnownUserToolchainBins({ home, env: {}, includeSystemBins: false });
expect(dirs).toContain(join(home, ".vite-plus", "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("appends $NPM_CONFIG_PREFIX/bin when set so corporate prefixes resolve", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-prefix-"));
const customPrefix = mkdtempSync(join(tmpdir(), "wkutb-custom-"));
try {
const dirs = wellKnownUserToolchainBins({
home,
env: { NPM_CONFIG_PREFIX: customPrefix },
includeSystemBins: false,
});
expect(dirs).toContain(join(customPrefix, "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(customPrefix, { recursive: true, force: true });
}
});
it("falls back to lower-case npm_config_prefix when NPM_CONFIG_PREFIX is absent", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-prefix-lc-"));
const customPrefix = mkdtempSync(join(tmpdir(), "wkutb-custom-lc-"));
try {
const dirs = wellKnownUserToolchainBins({
home,
env: { npm_config_prefix: customPrefix },
includeSystemBins: false,
});
expect(dirs).toContain(join(customPrefix, "bin"));
} finally {
rmSync(home, { recursive: true, force: true });
rmSync(customPrefix, { recursive: true, force: true });
}
});
// Windows: npm installs global binaries directly into the prefix root, not
// a <prefix>/bin subdirectory. The helper must surface BOTH the canonical
// Unix <prefix>/bin (cross-platform parity, no regression) AND the Windows
// prefix root so `npm i -g`'d CLIs like `pi` resolve under GUI launchers.
it("adds the npm prefix root alongside <prefix>/bin on Windows", () => {
const originalPlatform = process.platform;
const home = mkdtempSync(join(tmpdir(), "wkutb-win-prefix-"));
const customPrefix = mkdtempSync(join(tmpdir(), "wkutb-win-custom-"));
try {
Object.defineProperty(process, "platform", {
configurable: true,
value: "win32",
});
const dirs = wellKnownUserToolchainBins({
home,
env: { NPM_CONFIG_PREFIX: customPrefix },
includeSystemBins: false,
});
// <prefix>/bin is preserved (contract unchanged) AND the root is added.
expect(dirs).toContain(join(customPrefix, "bin"));
expect(dirs).toContain(customPrefix);
} finally {
Object.defineProperty(process, "platform", {
configurable: true,
value: originalPlatform,
});
rmSync(home, { recursive: true, force: true });
rmSync(customPrefix, { recursive: true, force: true });
}
});
// Regression for #3691. NPM_CONFIG_PREFIX / npm_config_prefix are npm-internal
// env vars usually absent in Electron child processes, so the env-driven block
// no-ops for most Windows users. %APPDATA%\npm (npm's default global prefix)
// must still be surfaced so globally-installed agent CLIs are detected.
it("always adds %APPDATA%\\npm as a fallback on Windows even without a prefix env var", () => {
const originalPlatform = process.platform;
const home = mkdtempSync(join(tmpdir(), "wkutb-win-appdata-"));
try {
Object.defineProperty(process, "platform", {
configurable: true,
value: "win32",
});
const dirs = wellKnownUserToolchainBins({
home,
env: {},
includeSystemBins: false,
});
expect(dirs).toContain(join(home, "AppData", "Roaming", "npm"));
} finally {
Object.defineProperty(process, "platform", {
configurable: true,
value: originalPlatform,
});
rmSync(home, { recursive: true, force: true });
}
});
// Guards the no-regression promise: the Windows-only additions must never
// leak onto POSIX hosts, where <prefix>/bin is the only correct entry.
it("does not add the npm prefix root or %APPDATA%\\npm on POSIX", () => {
const originalPlatform = process.platform;
const home = mkdtempSync(join(tmpdir(), "wkutb-posix-prefix-"));
const customPrefix = mkdtempSync(join(tmpdir(), "wkutb-posix-custom-"));
try {
Object.defineProperty(process, "platform", {
configurable: true,
value: "linux",
});
const dirs = wellKnownUserToolchainBins({
home,
env: { NPM_CONFIG_PREFIX: customPrefix },
includeSystemBins: false,
});
expect(dirs).toContain(join(customPrefix, "bin"));
expect(dirs).not.toContain(customPrefix);
expect(dirs).not.toContain(join(home, "AppData", "Roaming", "npm"));
} finally {
Object.defineProperty(process, "platform", {
configurable: true,
value: originalPlatform,
});
rmSync(home, { recursive: true, force: true });
rmSync(customPrefix, { recursive: true, force: true });
}
});
it("prepends $VP_HOME/bin and expands ~/ so custom Vite+ homes outrank the default", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-vp-home-"));
try {
const dirs = wellKnownUserToolchainBins({
home,
env: { VP_HOME: "~/custom-vp-home" },
includeSystemBins: false,
});
expect(dirs[0]).toBe(join(home, "custom-vp-home", "bin"));
expect(dirs).toContain(join(home, ".vite-plus", "bin"));
expect(dirs.indexOf(join(home, ".vite-plus", "bin"))).toBeGreaterThan(0);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
it("places $VP_HOME/bin before $NPM_CONFIG_PREFIX/bin when both explicit homes are set", () => {
const home = mkdtempSync(join(tmpdir(), "wkutb-vp-npm-order-"));
const npmPrefix = mkdtempSync(join(tmpdir(), "wkutb-vp-npm-prefix-"));
try {
const dirs = wellKnownUserToolchainBins({
home,
env: { NPM_CONFIG_PREFIX: npmPrefix, VP_HOME: "~/custom-vp-home" },
includeSystemBins: false,
});