2019-12-09 12:43:13 +09:00
|
|
|
import {spawnSync, SpawnSyncReturns} from 'child_process'
|
2019-12-13 12:18:28 +09:00
|
|
|
import stripAnsi from 'strip-ansi'
|
2019-12-09 12:43:13 +09:00
|
|
|
|
2020-07-14 02:59:28 -07:00
|
|
|
const SPAWN_PROCESS_BUFFER_SIZE = 10485760 // 10MiB
|
|
|
|
|
|
2019-12-09 12:43:13 +09:00
|
|
|
export class Audit {
|
2020-03-14 19:21:06 +09:00
|
|
|
stdout = ''
|
2019-12-13 16:09:10 +09:00
|
|
|
private status: number | null = null
|
2019-12-09 12:43:13 +09:00
|
|
|
|
2020-12-12 13:56:05 +02:00
|
|
|
public run(auditLevel: string, productionFlag: string, jsonFlag: string): void {
|
2020-03-14 15:46:51 +09:00
|
|
|
try {
|
2020-11-12 10:45:24 +00:00
|
|
|
const auditOptions: Array<string> = ['audit', '--audit-level', auditLevel]
|
|
|
|
|
|
|
|
|
|
if (productionFlag === 'true') {
|
|
|
|
|
auditOptions.push('--production')
|
2020-11-12 12:33:56 +02:00
|
|
|
}
|
|
|
|
|
|
2020-12-12 13:56:05 +02:00
|
|
|
if (jsonFlag === 'true') {
|
|
|
|
|
auditOptions.push('--json')
|
|
|
|
|
}
|
|
|
|
|
|
2020-11-12 10:45:24 +00:00
|
|
|
const result: SpawnSyncReturns<string> = spawnSync('npm', auditOptions, {
|
|
|
|
|
encoding: 'utf-8',
|
|
|
|
|
maxBuffer: SPAWN_PROCESS_BUFFER_SIZE
|
|
|
|
|
})
|
2019-12-09 12:43:13 +09:00
|
|
|
|
2020-03-14 15:46:51 +09:00
|
|
|
if (result.error) {
|
|
|
|
|
throw result.error
|
|
|
|
|
}
|
|
|
|
|
if (result.status === null) {
|
|
|
|
|
throw new Error('the subprocess terminated due to a signal.')
|
|
|
|
|
}
|
|
|
|
|
if (result.stderr && result.stderr.length > 0) {
|
|
|
|
|
throw new Error(result.stderr)
|
|
|
|
|
}
|
2019-12-09 12:43:13 +09:00
|
|
|
|
2020-03-14 15:46:51 +09:00
|
|
|
this.status = result.status
|
|
|
|
|
this.stdout = result.stdout
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw error
|
|
|
|
|
}
|
2019-12-09 12:43:13 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public foundVulnerability(): boolean {
|
|
|
|
|
// `npm audit` return 1 when it found vulnerabilities
|
|
|
|
|
return this.status === 1
|
|
|
|
|
}
|
2019-12-13 12:18:28 +09:00
|
|
|
|
|
|
|
|
public strippedStdout(): string {
|
|
|
|
|
return `\`\`\`\n${stripAnsi(this.stdout)}\n\`\`\``
|
|
|
|
|
}
|
2019-12-09 12:43:13 +09:00
|
|
|
}
|