/
yarn-auditer.ts
223 lines (203 loc) · 6.11 KB
/
yarn-auditer.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
import type { YarnAudit, YarnBerryAuditReport } from "audit-types";
import { execSync } from "child_process";
import * as semver from "semver";
import { blue, red, yellow } from "./colors";
import { reportAudit, runProgram } from "./common";
import type { AuditCiConfig } from "./config";
import Model, { type Summary } from "./model";
const MINIMUM_YARN_CLASSIC_VERSION = "1.12.3";
const MINIMUM_YARN_BERRY_VERSION = "2.4.0";
/**
* Change this to the appropriate version when
* yarn audit --registry is supported:
* @see https://github.com/yarnpkg/yarn/issues/7012
*/
const MINIMUM_YARN_AUDIT_REGISTRY_VERSION = "99.99.99";
function getYarnVersion(cwd?: string) {
const version = execSync("yarn -v", { cwd }).toString().replace("\n", "");
return version;
}
function yarnSupportsClassicAudit(yarnVersion: string | semver.SemVer) {
return semver.satisfies(yarnVersion, `^${MINIMUM_YARN_CLASSIC_VERSION}`);
}
function yarnSupportsBerryAudit(yarnVersion: string | semver.SemVer) {
return semver.gte(yarnVersion, MINIMUM_YARN_BERRY_VERSION);
}
function yarnSupportsAudit(yarnVersion: string | semver.SemVer) {
return (
yarnSupportsClassicAudit(yarnVersion) || yarnSupportsBerryAudit(yarnVersion)
);
}
function yarnAuditSupportsRegistry(yarnVersion: string | semver.SemVer) {
return semver.gte(yarnVersion, MINIMUM_YARN_AUDIT_REGISTRY_VERSION);
}
const printJson = (data: unknown) => {
console.log(JSON.stringify(data, undefined, 2));
};
/**
* Audit your Yarn project!
*
* @returns Returns the audit report summary on resolve, `Error` on rejection.
*/
export async function audit(
config: AuditCiConfig,
reporter = reportAudit
): Promise<Summary> {
const {
levels,
registry,
"report-type": reportType,
"skip-dev": skipDevelopmentDependencies,
"output-format": outputFormat,
_yarn,
directory,
} = config;
const yarnExec = _yarn || "yarn";
let missingLockFile = false;
const model = new Model(config);
const yarnVersion = getYarnVersion(directory);
const isYarnVersionSupported = yarnSupportsAudit(yarnVersion);
if (!isYarnVersionSupported) {
throw new Error(
`Yarn ${yarnVersion} not supported, must be ^${MINIMUM_YARN_CLASSIC_VERSION} or >=${MINIMUM_YARN_BERRY_VERSION}`
);
}
const isYarnClassic = yarnSupportsClassicAudit(yarnVersion);
const yarnName = isYarnClassic ? `Yarn` : `Yarn Berry`;
function isClassicGuard(
response: YarnAudit.AuditResponse | YarnBerryAuditReport.AuditResponse
): response is YarnAudit.AuditResponse {
return isYarnClassic;
}
const printHeader = (text: string) => {
if (outputFormat === "text") {
console.log(blue, text);
}
};
switch (reportType) {
case "full":
printHeader(`${yarnName} audit report JSON:`);
break;
case "important":
printHeader(`${yarnName} audit report results:`);
break;
case "summary":
printHeader(`${yarnName} audit report summary:`);
break;
default:
throw new Error(
`Invalid report type: ${reportType}. Should be \`['important', 'full', 'summary']\`.`
);
}
// Define a function to print based on the report type.
let printAuditData;
switch (reportType) {
case "full":
printAuditData = (line: unknown) => {
printJson(line);
};
break;
case "important":
printAuditData = isYarnClassic
? ({ type, data }) => {
if (
(type === "auditAdvisory" && levels[data.advisory.severity]) ||
type === "auditSummary"
) {
printJson(data);
}
}
: ({ metadata }) => {
printJson(metadata);
};
break;
case "summary":
printAuditData = isYarnClassic
? ({ type, data }: { type: string; data: any }) => {
if (type === "auditSummary") {
printJson(data);
}
}
: ({ metadata }: { metadata: any }) => {
printJson(metadata);
};
break;
default:
throw new Error(
`Invalid report type: ${reportType}. Should be \`['important', 'full', 'summary']\`.`
);
}
function outListener(
line: YarnAudit.AuditResponse | YarnBerryAuditReport.AuditResponse
) {
try {
if (isClassicGuard(line)) {
const { type, data } = line;
printAuditData(line);
if (type === "info" && data === "No lockfile found.") {
missingLockFile = true;
return;
}
if (type !== "auditAdvisory") {
return;
}
model.process(data.advisory);
} else {
printAuditData(line);
if ("advisories" in line) {
for (const advisory of Object.values<YarnBerryAuditReport.Advisory>(
line.advisories
)) {
model.process(advisory);
}
}
}
} catch (error) {
console.error(red, `ERROR: Cannot JSONStream.parse response:`);
console.error(line);
throw error;
}
}
const stderrBuffer: any[] = [];
function errorListener(line) {
stderrBuffer.push(line);
if (line.type === "error") {
throw new Error(line.data);
}
}
const options = { cwd: directory };
const arguments_ = isYarnClassic
? [
"audit",
"--json",
...(skipDevelopmentDependencies ? ["--groups", "dependencies"] : []),
]
: [
"npm",
"audit",
"--recursive",
"--json",
"--all",
...(skipDevelopmentDependencies ? ["--environment", "production"] : []),
];
if (registry) {
const auditRegistrySupported = yarnAuditSupportsRegistry(yarnVersion);
if (auditRegistrySupported) {
arguments_.push("--registry", registry);
} else {
console.warn(
yellow,
"Yarn audit does not support the registry flag yet."
);
}
}
await runProgram(yarnExec, arguments_, options, outListener, errorListener);
if (missingLockFile) {
console.warn(
yellow,
"No yarn.lock file. This does not affect auditing, but it may be a mistake."
);
}
const summary = model.getSummary((a) => a.github_advisory_id);
return reporter(summary, config);
}