-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathexecuteAddDependency.test.ts
More file actions
640 lines (593 loc) · 19.2 KB
/
Copy pathexecuteAddDependency.test.ts
File metadata and controls
640 lines (593 loc) · 19.2 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
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
CommandExecutionError,
PNPM_INSTALL_POLICY_ARGS,
SOCKET_FIREWALL_WARNING_MESSAGE,
} from "@/ipc/utils/socket_firewall";
import {
executeAddDependency,
ExecuteAddDependencyError,
} from "./executeAddDependency";
const {
commitPnpmAllowBuildsConfigIfChangedMock,
ensureSocketFirewallInstalledMock,
getPnpmMinimumReleaseAgeSupportMock,
readPnpmIgnoredBuildsMock,
recordDeniedPnpmBuildsMock,
runCommandMock,
sendTelemetryEventMock,
readEffectiveSettingsMock,
dbUpdateSetMock,
dbUpdateWhereMock,
} = vi.hoisted(() => ({
commitPnpmAllowBuildsConfigIfChangedMock: vi.fn(),
ensureSocketFirewallInstalledMock: vi.fn(),
getPnpmMinimumReleaseAgeSupportMock: vi.fn(),
readPnpmIgnoredBuildsMock: vi.fn(),
recordDeniedPnpmBuildsMock: vi.fn(),
runCommandMock: vi.fn(),
sendTelemetryEventMock: vi.fn(),
readEffectiveSettingsMock: vi.fn(),
dbUpdateSetMock: vi.fn(),
dbUpdateWhereMock: vi.fn(),
}));
vi.mock("../../db", () => ({
db: {
update: vi.fn(() => ({
set: dbUpdateSetMock,
})),
},
}));
vi.mock("../../db/schema", () => ({
messages: {},
}));
vi.mock("@/main/settings", () => ({
readEffectiveSettings: readEffectiveSettingsMock,
}));
vi.mock("@/ipc/utils/socket_firewall", async () => {
const actual = await vi.importActual<
typeof import("@/ipc/utils/socket_firewall")
>("@/ipc/utils/socket_firewall");
return {
...actual,
commitPnpmAllowBuildsConfigIfChanged:
commitPnpmAllowBuildsConfigIfChangedMock,
ensureSocketFirewallInstalled: ensureSocketFirewallInstalledMock,
getPnpmMinimumReleaseAgeSupport: getPnpmMinimumReleaseAgeSupportMock,
readPnpmIgnoredBuilds: readPnpmIgnoredBuildsMock,
recordDeniedPnpmBuilds: recordDeniedPnpmBuildsMock,
runCommand: runCommandMock,
};
});
vi.mock("@/ipc/utils/telemetry", () => ({
sendTelemetryEvent: sendTelemetryEventMock,
}));
describe("executeAddDependency", () => {
beforeEach(() => {
vi.clearAllMocks();
dbUpdateSetMock.mockReturnValue({
where: dbUpdateWhereMock,
});
dbUpdateWhereMock.mockResolvedValue(undefined);
getPnpmMinimumReleaseAgeSupportMock.mockResolvedValue({
available: true,
minimumReleaseAgeSupported: true,
version: "10.16.0",
});
commitPnpmAllowBuildsConfigIfChangedMock.mockResolvedValue({
promotedPackages: [],
});
readPnpmIgnoredBuildsMock.mockResolvedValue([]);
recordDeniedPnpmBuildsMock.mockResolvedValue({ deniedBuilds: [] });
readEffectiveSettingsMock.mockResolvedValue({
blockUnsafeNpmPackages: true,
});
});
it("preserves the firewall warning when package installation later fails", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockRejectedValueOnce(new Error("pnpm failed"));
let caughtError: unknown;
try {
await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
} catch (error) {
caughtError = error;
}
expect(caughtError).toBeInstanceOf(ExecuteAddDependencyError);
expect(caughtError).toMatchObject({
warningMessages: [SOCKET_FIREWALL_WARNING_MESSAGE],
message: "pnpm failed",
});
expect(commitPnpmAllowBuildsConfigIfChangedMock).toHaveBeenCalledWith(
"/tmp/app",
);
});
it("uses the most relevant combined PTY output line as the display summary", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: true,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "pnpm blocked",
stdout:
"Progress: resolved 12, reused 0, downloaded 0, added 0\nSocket Firewall blocked react\nPolicy: malware",
exitCode: 1,
}),
);
let caughtError: unknown;
try {
await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
} catch (error) {
caughtError = error;
}
expect(caughtError).toBeInstanceOf(ExecuteAddDependencyError);
expect(caughtError).toMatchObject({
displaySummary: "Socket Firewall blocked react",
displayDetails: "Socket Firewall blocked react\nPolicy: malware",
warningMessages: [],
});
});
it("filters PTY progress noise out of expanded display details", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "npm install failed",
stdout: [
"Progress: resolved 1, reused 0, downloaded 0, added 0",
"npm warn deprecated left-pad@1.3.0: use String.prototype.padStart()",
"npm ERR! code ERESOLVE",
"npm ERR! ERESOLVE unable to resolve dependency tree",
"npm ERR! A complete log of this run can be found in:",
"npm ERR! /Users/me/.npm/_logs/2026-04-08-debug-0.log",
].join("\n"),
exitCode: 1,
}),
);
await expect(
executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displayDetails:
"npm ERR! code ERESOLVE\nnpm ERR! ERESOLVE unable to resolve dependency tree",
displaySummary: "npm ERR! ERESOLVE unable to resolve dependency tree",
warningMessages: [SOCKET_FIREWALL_WARNING_MESSAGE],
});
});
it("falls back to the error message when PTY output only contains progress noise", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: true,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "Command 'pnpm add react' was terminated by signal 15",
stdout: [
"Progress: resolved 50, reused 0, downloaded 0, added 0",
"Packages: +1",
].join("\n"),
exitCode: 0,
}),
);
await expect(
executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displayDetails: "Command 'pnpm add react' was terminated by signal 15",
displaySummary: "Command 'pnpm add react' was terminated by signal 15",
warningMessages: [],
});
});
it("ignores npm log-noise lines and keeps the actionable npm ERR summary", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "npm install failed",
stdout: [
"npm ERR! code ERESOLVE",
"npm ERR! ERESOLVE unable to resolve dependency tree",
"npm ERR! A complete log of this run can be found in:",
"npm ERR! /Users/me/.npm/_logs/2026-04-08-debug-0.log",
].join("\n"),
exitCode: 1,
}),
);
await expect(
executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displaySummary: "npm ERR! ERESOLVE unable to resolve dependency tree",
warningMessages: [SOCKET_FIREWALL_WARNING_MESSAGE],
});
});
it("keeps ERR_PNPM summaries instead of falling back to progress output", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "pnpm add failed",
stdout: [
"Progress: resolved 1, reused 0, downloaded 0, added 0",
"ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/react: Not Found",
].join("\n"),
exitCode: 1,
}),
);
await expect(
executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displaySummary:
"ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/react: Not Found",
warningMessages: [SOCKET_FIREWALL_WARNING_MESSAGE],
});
});
it("does not fall back to a direct install when the real sfw cli blocks a dependency", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: true,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "pnpm blocked",
stdout:
" - blocked npm package: name: axois; version: 0.0.1-security; reason: malware (critical)",
exitCode: 1,
}),
);
await expect(
executeAddDependency({
packages: ["axois"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="axois"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displaySummary:
"- blocked npm package: name: axois; version: 0.0.1-security; reason: malware (critical)",
warningMessages: [],
});
expect(runCommandMock).toHaveBeenCalledTimes(1);
});
it("fails closed after sfw runtime failures", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: true,
});
runCommandMock.mockRejectedValueOnce(
new CommandExecutionError({
message: "sfw pnpm failed",
stdout: "Socket Firewall timed out",
exitCode: 1,
}),
);
await expect(
executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displaySummary: "Socket Firewall timed out",
warningMessages: [],
});
expect(runCommandMock).toHaveBeenCalledTimes(1);
});
it("uses pnpm with policy flags when pnpm cannot enforce the release-age policy", async () => {
readEffectiveSettingsMock.mockResolvedValueOnce({
blockUnsafeNpmPackages: true,
enablePnpmMinimumReleaseAgeWarning: true,
});
getPnpmMinimumReleaseAgeSupportMock.mockResolvedValue({
available: true,
minimumReleaseAgeSupported: false,
warningMessage:
"Install pnpm 10.16.0 or newer for the strongest protection",
});
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed via pnpm",
stderr: "",
});
const result = await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content: '<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
expect(runCommandMock).toHaveBeenCalledWith(
"pnpm",
[
...PNPM_INSTALL_POLICY_ARGS,
"add",
"--ignore-workspace-root-check",
"react",
],
{
cwd: "/tmp/app",
env: expect.objectContaining({
COREPACK_ENABLE_PROJECT_SPEC: "0",
COREPACK_ENABLE_STRICT: "0",
npm_config_package_manager_strict: "false",
npm_config_pm_on_fail: "ignore",
}),
timeoutMs: ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
},
);
expect(runCommandMock).toHaveBeenCalledTimes(1);
expect(commitPnpmAllowBuildsConfigIfChangedMock).toHaveBeenCalledWith(
"/tmp/app",
);
expect(result).toMatchObject({
installResults: "installed via pnpm",
warningMessages: [
SOCKET_FIREWALL_WARNING_MESSAGE,
"Install pnpm 10.16.0 or newer for the strongest protection",
],
});
});
it("falls back to npm when pnpm is unavailable", async () => {
getPnpmMinimumReleaseAgeSupportMock.mockResolvedValue({
available: false,
minimumReleaseAgeSupported: false,
warningMessage:
"Install pnpm 10.16.0 or newer for the strongest protection",
});
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed via npm",
stderr: "",
});
const result = await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content: '<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
expect(runCommandMock).toHaveBeenCalledWith(
"npm",
["install", "--legacy-peer-deps", "react"],
{
cwd: "/tmp/app",
env: expect.objectContaining({
COREPACK_ENABLE_PROJECT_SPEC: "0",
COREPACK_ENABLE_STRICT: "0",
npm_config_package_manager_strict: "false",
npm_config_pm_on_fail: "ignore",
}),
timeoutMs: ADD_DEPENDENCY_INSTALL_TIMEOUT_MS,
},
);
expect(commitPnpmAllowBuildsConfigIfChangedMock).not.toHaveBeenCalled();
expect(result).toMatchObject({
installResults: "installed via npm",
warningMessages: [SOCKET_FIREWALL_WARNING_MESSAGE],
});
});
it("uses npm for npm-shaped apps even when pnpm is available", async () => {
const appPath = await mkdtemp(path.join(os.tmpdir(), "dyad-add-dep-"));
try {
await writeFile(path.join(appPath, "package-lock.json"), "{}");
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed via npm",
stderr: "",
});
const result = await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath,
});
expect(runCommandMock).toHaveBeenCalledWith(
"npm",
["install", "--legacy-peer-deps", "react"],
expect.objectContaining({ cwd: appPath }),
);
expect(commitPnpmAllowBuildsConfigIfChangedMock).not.toHaveBeenCalled();
expect(result).toMatchObject({
installResults: "installed via npm",
});
} finally {
await rm(appPath, { recursive: true, force: true });
}
});
it("does not warn about old pnpm for apps that explicitly use npm", async () => {
const appPath = await mkdtemp(path.join(os.tmpdir(), "dyad-add-dep-"));
try {
await writeFile(
path.join(appPath, "package.json"),
JSON.stringify({ packageManager: "npm@10.8.2" }),
);
readEffectiveSettingsMock.mockResolvedValueOnce({
blockUnsafeNpmPackages: true,
enablePnpmMinimumReleaseAgeWarning: true,
});
getPnpmMinimumReleaseAgeSupportMock.mockResolvedValue({
available: true,
minimumReleaseAgeSupported: false,
warningMessage:
"Install pnpm 10.16.0 or newer for the strongest protection",
});
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: true,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed via npm",
stderr: "",
});
const result = await executeAddDependency({
packages: ["react"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react"></dyad-add-dependency>',
} as any,
appPath,
});
expect(result).toMatchObject({
installResults: "installed via npm",
warningMessages: [],
});
} finally {
await rm(appPath, { recursive: true, force: true });
}
});
it("rejects invalid npm package specs before invoking the shell", async () => {
await expect(
executeAddDependency({
packages: ["react@^18.0.0"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react@^18.0.0"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
}),
).rejects.toMatchObject({
displaySummary: "Invalid npm package name: react@^18.0.0",
warningMessages: [],
});
expect(runCommandMock).not.toHaveBeenCalled();
});
it("escapes package attributes and install output before storing the tag", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
warningMessage: SOCKET_FIREWALL_WARNING_MESSAGE,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed <react>",
stderr: "",
});
await executeAddDependency({
packages: ["react-safe"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="react-safe"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
expect(dbUpdateSetMock).toHaveBeenCalledWith({
content:
'<dyad-add-dependency packages="react-safe">installed <react></dyad-add-dependency>',
});
});
it("records denied pnpm builds and surfaces the security-policy note", async () => {
ensureSocketFirewallInstalledMock.mockResolvedValue({
available: false,
});
runCommandMock.mockResolvedValueOnce({
stdout: "installed via pnpm",
stderr: "",
});
readPnpmIgnoredBuildsMock.mockResolvedValue([
{ packageName: "core-js", packageSpec: "core-js@3.49.0" },
]);
recordDeniedPnpmBuildsMock.mockResolvedValue({
deniedBuilds: [{ packageName: "core-js", packageSpec: "core-js@3.49.0" }],
});
const result = await executeAddDependency({
packages: ["core-js"],
message: {
id: 1,
content:
'<dyad-add-dependency packages="core-js"></dyad-add-dependency>',
} as any,
appPath: "/tmp/app",
});
expect(result.installResults).toContain("installed via pnpm");
expect(result.installResults).toContain(
"Note: build scripts for core-js were not run (Dyad security policy).",
);
expect(sendTelemetryEventMock).toHaveBeenCalledWith(
"pnpm:build-auto-denied",
{
packages: ["core-js@3.49.0"],
source: "add-dependency",
},
);
expect(dbUpdateSetMock).toHaveBeenCalledWith({
content: expect.stringContaining(
"Note: build scripts for core-js were not run",
),
});
});
});