-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
78 lines (74 loc) · 2.71 KB
/
index.js
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
const axios = require('axios').default
const unzipper = require('unzipper')
const fs = require('fs')
const parser = require('xml2json')
const path = require('path')
const zipFileName = path.join(__dirname, 'output', 'cwec_latest.xml.zip')
const xmlFileName = path.join(__dirname, 'output', 'cwec_v4.9.xml')
const filePath = path.join(__dirname, 'output')
let externalReferenceAry = []
const options = {
object: false,
reversible: false,
coerce: false,
sanitize: true,
trim: true,
arrayNotation: false,
alternateTextNode: false
}
const fetchCwecLatest = () => {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
const response = await axios.get('https://cwe.mitre.org/data/xml/cwec_latest.xml.zip', {
responseType: 'arraybuffer'
})
fs.writeFile(zipFileName, response.data, async () => {
const readStream = fs.createReadStream(zipFileName).pipe(unzipper.Extract({ path: filePath }))
await new Promise((resolve) => readStream.on('close', resolve))
fs.readdirSync(filePath).forEach((file) => {
// The version changes but the intial file name is usually the same
if (file.includes('cwec_v')) {
const xmlFileName = file
const xmlPath = path.join(__dirname, 'output', xmlFileName)
fs.readFile(`${xmlPath}`, (err, data) => {
if (err) {
console.error(err)
}
const cweJson = parser.toJson(data)
const cweParsed = JSON.parse(cweJson, options)
const cweWeaknessAry = cweParsed.Weakness_Catalog.Weaknesses.Weakness.map((x) => x)
externalReferenceAry = cweParsed.Weakness_Catalog.External_References.External_Reference
resolve(cweWeaknessAry)
})
}
})
})
} catch (error) {
console.error(error)
reject(error)
}
})
}
const getExternalReferencesByCwe = (cwe) => {
if (Array.isArray(cwe.References.Reference)) {
cwe.References.Full_Details = []
for (const externalReferenceId of cwe.References.Reference) {
const fullReferenceDetails = externalReferenceAry.find(
(reference) => externalReferenceId.External_Reference_ID === reference.Reference_ID
)
cwe.References.Full_Details.push(fullReferenceDetails)
}
}
}
// TODO add optional parameters for deleting items and where to store them
const fetchCweList = async () => {
const cweWeaknessAry = await fetchCwecLatest()
for (const cwe of cweWeaknessAry) {
if (cwe.References) getExternalReferencesByCwe(cwe)
}
fs.unlinkSync(zipFileName)
fs.unlinkSync(`${xmlFileName}`)
return cweWeaknessAry
}
module.exports = fetchCweList