-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathnpm-fix.mts
More file actions
581 lines (531 loc) · 18.1 KB
/
npm-fix.mts
File metadata and controls
581 lines (531 loc) · 18.1 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
import path from 'node:path'
import semver from 'semver'
import { getManifestData } from '@socketsecurity/registry'
import { arrayUnique } from '@socketsecurity/registry/lib/arrays'
import { debugFn, isDebug } from '@socketsecurity/registry/lib/debug'
import { logger } from '@socketsecurity/registry/lib/logger'
import { runScript } from '@socketsecurity/registry/lib/npm'
import {
fetchPackagePackument,
readPackageJson,
resolvePackageName,
} from '@socketsecurity/registry/lib/packages'
import { naturalCompare } from '@socketsecurity/registry/lib/sorts'
import { getActiveBranchesForPackage } from './fix-branch-helpers.mts'
import { getCiEnv, getOpenPrsForEnvironment } from './fix-env-helpers.mts'
import {
getSocketBranchName,
getSocketBranchWorkspaceComponent,
getSocketCommitMessage,
gitCreateAndPushBranch,
gitRemoteBranchExists,
gitResetAndClean,
gitUnstagedModifiedFiles,
} from './git.mts'
import {
cleanupOpenPrs,
enablePrAutoMerge,
openPr,
prExistForBranch,
setGitRemoteGithubRepoUrl,
} from './open-pr.mts'
import { getAlertsMapOptions } from './shared.mts'
import constants from '../../constants.mts'
import {
Arborist,
SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES,
} from '../../shadow/npm/arborist/index.mts'
import {
findBestPatchVersion,
findPackageNode,
findPackageNodes,
getAlertsMapFromArborist,
updateNode,
updatePackageJsonFromNode,
} from '../../shadow/npm/arborist-helpers.mts'
import { getAlertsMapFromPurls } from '../../utils/alerts-map.mts'
import { removeNodeModules } from '../../utils/fs.mts'
import { globWorkspace } from '../../utils/glob.mts'
import { getPurlObject } from '../../utils/purl.mts'
import { applyRange } from '../../utils/semver.mts'
import { getCveInfoFromAlertsMap } from '../../utils/socket-package-alert.mts'
import { idToPurl } from '../../utils/spec.mts'
import type {
ArboristInstance,
NodeClass,
} from '../../shadow/npm/arborist/types.mts'
import type { CResult } from '../../types.mts'
import type { EnvDetails } from '../../utils/package-environment.mts'
import type { RangeStyle } from '../../utils/semver.mts'
import type { PackageJson } from '@socketsecurity/registry/lib/packages'
type InstallOptions = {
cwd?: string | undefined
}
async function install(
arb: ArboristInstance,
options: InstallOptions,
): Promise<NodeClass | null> {
const { cwd = process.cwd() } = {
__proto__: null,
...options,
} as InstallOptions
try {
const newArb = new Arborist({ path: cwd })
newArb.idealTree = await arb.buildIdealTree()
const actualTree = await newArb.reify()
arb.actualTree = actualTree
return actualTree
} catch {}
return null
}
export async function npmFix(
pkgEnvDetails: EnvDetails,
{
autoMerge,
cwd,
limit,
purls,
rangeStyle,
test,
testScript,
}: {
autoMerge: boolean
cwd: string
limit: number
purls: string[]
rangeStyle: RangeStyle
test: boolean
testScript: string
},
): Promise<CResult<{ fixed: boolean }>> {
// Lazily access constants.spinner.
const { spinner } = constants
const { pkgPath: rootPath } = pkgEnvDetails
spinner?.start()
const ciEnv = getCiEnv()
const openPrs = ciEnv ? await getOpenPrsForEnvironment(ciEnv) : []
let count = 0
const arb = new Arborist({
path: rootPath,
...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES,
})
// Calling arb.reify() creates the arb.diff object, nulls-out arb.idealTree,
// and populates arb.actualTree.
let actualTree = await arb.reify()
let alertsMap
try {
alertsMap = purls.length
? await getAlertsMapFromPurls(
purls,
getAlertsMapOptions({ limit: Math.max(limit, openPrs.length) }),
)
: await getAlertsMapFromArborist(
arb,
getAlertsMapOptions({ limit: Math.max(limit, openPrs.length) }),
)
} catch (e) {
spinner?.stop()
debugFn('catch: PURL API\n', e)
return {
ok: false,
message: 'API Error',
cause: (e as Error)?.message || 'Unknown Socket batch PURL API error.',
}
}
const infoByPartialPurl = getCveInfoFromAlertsMap(alertsMap, {
limit: Math.max(limit, openPrs.length),
})
if (!infoByPartialPurl) {
spinner?.stop()
logger.info('No fixable vulns found.')
return { ok: true, data: { fixed: false } }
}
// baseBranch and branchParser are now from env
const workspacePkgJsonPaths = await globWorkspace(
pkgEnvDetails.agent,
rootPath,
)
const pkgJsonPaths = [
...workspacePkgJsonPaths,
// Process the workspace root last since it will add an override to package.json.
pkgEnvDetails.editablePkgJson.filename!,
]
const sortedInfoEntries = [...infoByPartialPurl.entries()].sort((a, b) =>
naturalCompare(a[0], b[0]),
)
const handleInstallFail = (): CResult<{ fixed: boolean }> => {
debugFn(`fail: ${pkgEnvDetails.agent} install\n`)
logger.dedent()
spinner?.dedent()
return {
ok: false,
message: 'Installation failure',
cause: `Unexpected condition: ${pkgEnvDetails.agent} install failed.`,
}
}
spinner?.stop()
infoEntriesLoop: for (
let i = 0, { length } = sortedInfoEntries;
i < length;
i += 1
) {
const isLastInfoEntry = i === length - 1
const infoEntry = sortedInfoEntries[i]!
const partialPurlObj = getPurlObject(infoEntry[0])
const name = resolvePackageName(partialPurlObj)
const infos = [...infoEntry[1].values()]
if (!infos.length) {
continue infoEntriesLoop
}
const activeBranches = getActiveBranchesForPackage(
ciEnv,
infoEntry[0],
openPrs,
)
logger.log(`Processing vulns for ${name}:`)
logger.indent()
spinner?.indent()
if (getManifestData(partialPurlObj.type, name)) {
debugFn(`found: Socket Optimize variant for ${name}`)
}
// eslint-disable-next-line no-await-in-loop
const packument = await fetchPackagePackument(name)
if (!packument) {
logger.warn(`Unexpected condition: No packument found for ${name}.\n`)
logger.dedent()
spinner?.dedent()
continue infoEntriesLoop
}
const availableVersions = Object.keys(packument.versions)
const warningsForAfter = new Set<string>()
// eslint-disable-next-line no-unused-labels
pkgJsonPathsLoop: for (
let j = 0, { length: length_j } = pkgJsonPaths;
j < length_j;
j += 1
) {
const isLastPkgJsonPath = j === length_j - 1
const pkgJsonPath = pkgJsonPaths[j]!
const pkgPath = path.dirname(pkgJsonPath)
const isWorkspaceRoot =
pkgJsonPath === pkgEnvDetails.editablePkgJson.filename
const workspace = isWorkspaceRoot
? 'root'
: path.relative(rootPath, pkgPath)
const branchWorkspace = ciEnv
? getSocketBranchWorkspaceComponent(workspace)
: ''
const oldVersions = arrayUnique(
findPackageNodes(actualTree, name)
.map(n => n.target?.version ?? n.version)
.filter(Boolean),
)
if (!oldVersions.length) {
debugFn(`skip: ${name} not found\n`)
// Skip to next package.
logger.dedent()
spinner?.dedent()
continue infoEntriesLoop
}
// Always re-read the editable package.json to avoid stale mutations
// across iterations.
// eslint-disable-next-line no-await-in-loop
const editablePkgJson = await readPackageJson(pkgJsonPath, {
editable: true,
})
let hasAnnouncedWorkspace = false
let workspaceLogCallCount = logger.logCallCount
if (isDebug()) {
debugFn(`check: workspace ${workspace}`)
hasAnnouncedWorkspace = true
workspaceLogCallCount = logger.logCallCount
}
oldVersionsLoop: for (const oldVersion of oldVersions) {
const oldId = `${name}@${oldVersion}`
const oldPurl = idToPurl(oldId, partialPurlObj.type)
const node = findPackageNode(actualTree, name, oldVersion)
if (!node) {
debugFn(`skip: ${oldId} not found`)
continue oldVersionsLoop
}
infosLoop: for (const {
firstPatchedVersionIdentifier,
vulnerableVersionRange,
} of infos.values()) {
const newVersion = findBestPatchVersion(
node,
availableVersions,
vulnerableVersionRange,
)
const newVersionPackument = newVersion
? packument.versions[newVersion]
: undefined
if (!(newVersion && newVersionPackument)) {
warningsForAfter.add(
`${oldId} not updated: requires >=${firstPatchedVersionIdentifier}`,
)
continue infosLoop
}
if (semver.gte(oldVersion, newVersion)) {
debugFn(`skip: ${oldId} is >= ${newVersion}`)
continue infosLoop
}
if (
activeBranches.find(
b =>
b.workspace === branchWorkspace && b.newVersion === newVersion,
)
) {
debugFn(`skip: open PR found for ${name}@${newVersion}`)
if (++count >= limit) {
logger.dedent()
spinner?.dedent()
break infoEntriesLoop
}
continue infosLoop
}
const newVersionRange = applyRange(oldVersion, newVersion, rangeStyle)
const newId = `${name}@${newVersionRange}`
const revertData = {
...(editablePkgJson.content.dependencies && {
dependencies: { ...editablePkgJson.content.dependencies },
}),
...(editablePkgJson.content.optionalDependencies && {
optionalDependencies: {
...editablePkgJson.content.optionalDependencies,
},
}),
...(editablePkgJson.content.peerDependencies && {
peerDependencies: { ...editablePkgJson.content.peerDependencies },
}),
} as PackageJson
updateNode(node, newVersion, newVersionPackument)
updatePackageJsonFromNode(
editablePkgJson,
// eslint-disable-next-line no-await-in-loop
await arb.buildIdealTree(),
node,
newVersion,
rangeStyle,
)
// eslint-disable-next-line no-await-in-loop
if (!(await editablePkgJson.save({ ignoreWhitespace: true }))) {
debugFn(`skip: ${workspace}/package.json unchanged`)
// Reset things just in case.
if (ciEnv) {
// eslint-disable-next-line no-await-in-loop
await gitResetAndClean(ciEnv.baseBranch, cwd)
}
continue infosLoop
}
if (!hasAnnouncedWorkspace) {
hasAnnouncedWorkspace = true
workspaceLogCallCount = logger.logCallCount
}
spinner?.start()
spinner?.info(`Installing ${newId} in ${workspace}.`)
let error
let errored = false
try {
// eslint-disable-next-line no-await-in-loop
const maybeActualTree = await install(arb, { cwd })
if (maybeActualTree) {
actualTree = maybeActualTree
if (test) {
spinner?.info(`Testing ${newId} in ${workspace}.`)
// eslint-disable-next-line no-await-in-loop
await runScript(testScript, [], { spinner, stdio: 'ignore' })
}
spinner?.success(`Fixed ${name} in ${workspace}.`)
} else {
errored = true
}
} catch (e) {
errored = true
error = e
}
spinner?.stop()
// Check repoInfo to make TypeScript happy.
if (!errored && ciEnv?.repoInfo) {
try {
// eslint-disable-next-line no-await-in-loop
const result = await gitUnstagedModifiedFiles(cwd)
if (!result.ok) {
// Do we fail if this fails? If this git command
// fails then probably other git commands do too?
logger.warn(
'Unexpected condition: Nothing to commit, skipping PR creation.',
)
continue infosLoop
}
const moddedFilepaths = result.data.filter(p => {
const basename = path.basename(p)
return (
basename === 'package.json' ||
basename === 'package-lock.json'
)
})
if (!moddedFilepaths.length) {
logger.warn(
'Unexpected condition: Nothing to commit, skipping PR creation.',
)
continue infosLoop
}
const branch = getSocketBranchName(oldPurl, newVersion, workspace)
let skipPr = false
if (
// eslint-disable-next-line no-await-in-loop
await prExistForBranch(
ciEnv.repoInfo.owner,
ciEnv.repoInfo.repo,
branch,
)
) {
skipPr = true
debugFn(`skip: branch "${branch}" exists`)
}
// eslint-disable-next-line no-await-in-loop
else if (await gitRemoteBranchExists(branch, cwd)) {
skipPr = true
debugFn(`skip: remote branch "${branch}" exists`)
} else if (
// eslint-disable-next-line no-await-in-loop
!(await gitCreateAndPushBranch(
branch,
getSocketCommitMessage(oldPurl, newVersion, workspace),
moddedFilepaths,
{
cwd,
email: ciEnv.gitEmail,
user: ciEnv.gitUser,
},
))
) {
skipPr = true
logger.warn(
'Unexpected condition: Push failed, skipping PR creation.',
)
}
if (skipPr) {
// eslint-disable-next-line no-await-in-loop
await gitResetAndClean(ciEnv.baseBranch, cwd)
// eslint-disable-next-line no-await-in-loop
const maybeActualTree = await install(arb, { cwd })
if (!maybeActualTree) {
// Exit early if install fails.
return handleInstallFail()
}
actualTree = maybeActualTree
continue infosLoop
}
// eslint-disable-next-line no-await-in-loop
await Promise.allSettled([
setGitRemoteGithubRepoUrl(
ciEnv.repoInfo.owner,
ciEnv.repoInfo.repo,
ciEnv.githubToken!,
cwd,
),
cleanupOpenPrs(ciEnv.repoInfo.owner, ciEnv.repoInfo.repo, {
newVersion,
purl: oldPurl,
workspace,
}),
])
// eslint-disable-next-line no-await-in-loop
const prResponse = await openPr(
ciEnv.repoInfo.owner,
ciEnv.repoInfo.repo,
branch,
oldPurl,
newVersion,
{
baseBranch: ciEnv.baseBranch,
cwd,
workspace,
},
)
if (prResponse) {
const { data } = prResponse
const prRef = `PR #${data.number}`
logger.success(`Opened ${prRef}.`)
if (autoMerge) {
logger.indent()
spinner?.indent()
// eslint-disable-next-line no-await-in-loop
const { details, enabled } = await enablePrAutoMerge(data)
if (enabled) {
logger.info(`Auto-merge enabled for ${prRef}.`)
} else {
const message = `Failed to enable auto-merge for ${prRef}${
details
? `:\n${details.map(d => ` - ${d}`).join('\n')}`
: '.'
}`
logger.error(message)
}
logger.dedent()
spinner?.dedent()
}
}
} catch (e) {
error = e
errored = true
}
}
if (ciEnv) {
spinner?.start()
// eslint-disable-next-line no-await-in-loop
await gitResetAndClean(ciEnv.baseBranch, cwd)
// eslint-disable-next-line no-await-in-loop
const maybeActualTree = await install(arb, { cwd })
spinner?.stop()
if (maybeActualTree) {
actualTree = maybeActualTree
} else {
errored = true
}
}
if (errored) {
if (!ciEnv) {
spinner?.start()
editablePkgJson.update(revertData)
// eslint-disable-next-line no-await-in-loop
await Promise.all([
removeNodeModules(cwd),
editablePkgJson.save({ ignoreWhitespace: true }),
])
// eslint-disable-next-line no-await-in-loop
const maybeActualTree = await install(arb, { cwd })
spinner?.stop()
if (!maybeActualTree) {
// Exit early if install fails.
return handleInstallFail()
}
actualTree = maybeActualTree
}
logger.fail(`Update failed for ${oldId} in ${workspace}.`, error)
}
if (++count >= limit) {
logger.dedent()
spinner?.dedent()
break infoEntriesLoop
}
}
}
if (!isLastPkgJsonPath && logger.logCallCount > workspaceLogCallCount) {
logger.logNewline()
}
}
for (const warningText of warningsForAfter) {
logger.warn(warningText)
}
if (!isLastInfoEntry) {
logger.logNewline()
}
logger.dedent()
spinner?.dedent()
}
spinner?.stop()
return { ok: true, data: { fixed: true } } // true? did we actually change anything?
}