-
-
Notifications
You must be signed in to change notification settings - Fork 932
/
audit.ts
241 lines (228 loc) · 7.33 KB
/
audit.ts
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
import { audit, AuditReport, AuditVulnerabilityCounts } from '@pnpm/audit'
import { createGetAuthHeaderByURI } from '@pnpm/network.auth-header'
import { docsUrl, TABLE_OPTIONS } from '@pnpm/cli-utils'
import { Config, types as allTypes, UniversalOptions } from '@pnpm/config'
import { WANTED_LOCKFILE } from '@pnpm/constants'
import { PnpmError } from '@pnpm/error'
import { readWantedLockfile } from '@pnpm/lockfile-file'
import { Registries } from '@pnpm/types'
import { table } from '@zkochan/table'
import chalk from 'chalk'
import difference from 'ramda/src/difference'
import pick from 'ramda/src/pick'
import pickBy from 'ramda/src/pickBy'
import renderHelp from 'render-help'
import { fix } from './fix'
// eslint-disable
const AUDIT_LEVEL_NUMBER = {
low: 0,
moderate: 1,
high: 2,
critical: 3,
}
const AUDIT_COLOR = {
low: chalk.bold,
moderate: chalk.bold.yellow,
high: chalk.bold.red,
critical: chalk.bold.red,
}
// eslint-enable
export const rcOptionsTypes = cliOptionsTypes
export function cliOptionsTypes () {
return {
...pick([
'dev',
'json',
'only',
'optional',
'production',
'registry',
], allTypes),
'audit-level': ['low', 'moderate', 'high', 'critical'],
fix: Boolean,
'ignore-registry-errors': Boolean,
}
}
export const shorthands = {
D: '--dev',
P: '--production',
}
export const commandNames = ['audit']
export function help () {
return renderHelp({
description: 'Checks for known security issues with the installed packages.',
descriptionLists: [
{
title: 'Options',
list: [
{
description: 'Add overrides to the package.json file in order to force non-vulnerable versions of the dependencies',
name: '--fix',
},
{
description: 'Output audit report in JSON format',
name: '--json',
},
{
description: 'Only print advisories with severity greater than or equal to one of the following: low|moderate|high|critical. Default: low',
name: '--audit-level <severity>',
},
{
description: 'Only audit "devDependencies"',
name: '--dev',
shortAlias: '-D',
},
{
description: 'Only audit "dependencies" and "optionalDependencies"',
name: '--prod',
shortAlias: '-P',
},
{
description: 'Don\'t audit "optionalDependencies"',
name: '--no-optional',
},
{
description: 'Use exit code 0 if the registry responds with an error. Useful when audit checks are used in CI. A build should fail because the registry has issues.',
name: '--ignore-registry-errors',
},
],
},
],
url: docsUrl('audit'),
usages: ['pnpm audit [options]'],
})
}
export async function handler (
opts: Pick<UniversalOptions, 'dir'> & {
auditLevel?: 'low' | 'moderate' | 'high' | 'critical'
fix?: boolean
ignoreRegistryErrors?: boolean
json?: boolean
lockfileDir?: string
registries: Registries
} & Pick<Config, 'ca'
| 'cert'
| 'httpProxy'
| 'httpsProxy'
| 'key'
| 'localAddress'
| 'maxSockets'
| 'noProxy'
| 'strictSsl'
| 'fetchRetries'
| 'fetchRetryMaxtimeout'
| 'fetchRetryMintimeout'
| 'fetchRetryFactor'
| 'fetchTimeout'
| 'production'
| 'dev'
| 'optional'
| 'userConfig'
| 'rawConfig'
| 'rootProjectManifest'
>
) {
const lockfileDir = opts.lockfileDir ?? opts.dir
const lockfile = await readWantedLockfile(lockfileDir, { ignoreIncompatible: true })
if (lockfile == null) {
throw new PnpmError('AUDIT_NO_LOCKFILE', `No ${WANTED_LOCKFILE} found: Cannot audit a project without a lockfile`)
}
const include = {
dependencies: opts.production !== false,
devDependencies: opts.dev !== false,
optionalDependencies: opts.optional !== false,
}
let auditReport!: AuditReport
const getAuthHeader = createGetAuthHeaderByURI({ allSettings: opts.rawConfig, userSettings: opts.userConfig })
try {
auditReport = await audit(lockfile, getAuthHeader, {
agentOptions: {
ca: opts.ca,
cert: opts.cert,
httpProxy: opts.httpProxy,
httpsProxy: opts.httpsProxy,
key: opts.key,
localAddress: opts.localAddress,
maxSockets: opts.maxSockets,
noProxy: opts.noProxy,
strictSsl: opts.strictSsl,
timeout: opts.fetchTimeout,
},
include,
lockfileDir,
registry: opts.registries.default,
retry: {
factor: opts.fetchRetryFactor,
maxTimeout: opts.fetchRetryMaxtimeout,
minTimeout: opts.fetchRetryMintimeout,
retries: opts.fetchRetries,
},
timeout: opts.fetchTimeout,
})
} catch (err: any) { // eslint-disable-line
if (opts.ignoreRegistryErrors) {
return {
exitCode: 0,
output: err.message,
}
}
throw err
}
if (opts.fix) {
const newOverrides = await fix(opts.dir, auditReport)
if (Object.values(newOverrides).length === 0) {
return {
exitCode: 0,
output: 'No fixes were made',
}
}
return {
exitCode: 0,
output: `${Object.values(newOverrides).length} overrides were added to package.json to fix vulnerabilities.
Run "pnpm install" to apply the fixes.
The added overrides:
${JSON.stringify(newOverrides, null, 2)}`,
}
}
const vulnerabilities = auditReport.metadata.vulnerabilities
const totalVulnerabilityCount = Object.values(vulnerabilities)
.reduce((sum: number, vulnerabilitiesCount: number) => sum + vulnerabilitiesCount, 0)
const ignoreCves = opts.rootProjectManifest?.pnpm?.auditConfig?.ignoreCves
if (ignoreCves) {
auditReport.advisories = pickBy(({ cves }) => cves.length === 0 || difference(cves, ignoreCves).length > 0, auditReport.advisories)
}
if (opts.json) {
return {
exitCode: totalVulnerabilityCount > 0 ? 1 : 0,
output: JSON.stringify(auditReport, null, 2),
}
}
let output = ''
const auditLevel = AUDIT_LEVEL_NUMBER[opts.auditLevel ?? 'low']
let advisories = Object.values(auditReport.advisories)
advisories = advisories
.filter(({ severity }) => AUDIT_LEVEL_NUMBER[severity] >= auditLevel)
.sort((a1, a2) => AUDIT_LEVEL_NUMBER[a2.severity] - AUDIT_LEVEL_NUMBER[a1.severity])
for (const advisory of advisories) {
output += table([
[AUDIT_COLOR[advisory.severity](advisory.severity), chalk.bold(advisory.title)],
['Package', advisory.module_name],
['Vulnerable versions', advisory.vulnerable_versions],
['Patched versions', advisory.patched_versions],
['More info', advisory.url],
], TABLE_OPTIONS)
}
return {
exitCode: output ? 1 : 0,
output: `${output}${reportSummary(auditReport.metadata.vulnerabilities, totalVulnerabilityCount)}`,
}
}
function reportSummary (vulnerabilities: AuditVulnerabilityCounts, totalVulnerabilityCount: number) {
if (totalVulnerabilityCount === 0) return 'No known vulnerabilities found\n'
return `${chalk.red(totalVulnerabilityCount)} vulnerabilities found\nSeverity: ${
Object.entries(vulnerabilities)
.filter(([auditLevel, vulnerabilitiesCount]) => vulnerabilitiesCount > 0)
.map(([auditLevel, vulnerabilitiesCount]: [string, number]) => AUDIT_COLOR[auditLevel](`${vulnerabilitiesCount} ${auditLevel}`))
.join(' | ')
}`
}