juice-shop

Форк
0
/
rsnUtil.ts 
153 строки · 5.0 Кб
1
import { retrieveCodeSnippet } from '../routes/vulnCodeSnippet'
2
import colors from 'colors/safe'
3
const Diff = require('diff')
4
const fs = require('fs')
5
const fixesPath = 'data/static/codefixes'
6
const cacheFile = 'rsn/cache.json'
7

8
type CacheData = Record<string, {
9
  added: number[]
10
  removed: number[]
11
}>
12

13
function readFiles () {
14
  const files = fs.readdirSync(fixesPath)
15
  const keys = files.filter((file: string) => !file.endsWith('.info.yml') && !file.endsWith('.editorconfig'))
16
  return keys
17
}
18

19
function writeToFile (json: CacheData) {
20
  fs.writeFileSync(cacheFile, JSON.stringify(json, null, '\t'))
21
}
22

23
function getDataFromFile () {
24
  const data = fs.readFileSync(cacheFile).toString()
25
  return JSON.parse(data)
26
}
27

28
function filterString (text: string) {
29
  text = text.replace(/\r/g, '')
30
  return text
31
}
32

33
const checkDiffs = async (keys: string[]) => {
34
  const data: CacheData = keys.reduce((prev, curr) => {
35
    return {
36
      ...prev,
37
      [curr]: {
38
        added: [],
39
        removed: []
40
      }
41
    }
42
  }, {})
43
  for (const val of keys) {
44
    await retrieveCodeSnippet(val.split('_')[0])
45
      .then(snippet => {
46
        if (snippet == null) return
47
        process.stdout.write(val + ': ')
48
        const fileData = fs.readFileSync(fixesPath + '/' + val).toString()
49
        const diff = Diff.diffLines(filterString(fileData), filterString(snippet.snippet))
50
        let line = 0
51
        for (const part of diff) {
52
          if (part.removed) continue
53
          const prev = line
54
          line += part.count
55
          if (!(part.added)) continue
56
          for (let i = 0; i < part.count; i++) {
57
            if (!snippet.vulnLines.includes(prev + i + 1) && !snippet.neutralLines.includes(prev + i + 1)) {
58
              process.stdout.write(colors.red(colors.inverse(prev + i + 1 + '')))
59
              process.stdout.write(' ')
60
              data[val].added.push(prev + i + 1)
61
            } else if (snippet.vulnLines.includes(prev + i + 1)) {
62
              process.stdout.write(colors.red(colors.bold(prev + i + 1 + ' ')))
63
            } else if (snippet.neutralLines.includes(prev + i + 1)) {
64
              process.stdout.write(colors.red(prev + i + 1 + ' '))
65
            }
66
          }
67
        }
68
        line = 0
69
        let norm = 0
70
        for (const part of diff) {
71
          if (part.added) {
72
            norm--
73
            continue
74
          }
75
          const prev = line
76
          line += part.count
77
          if (!(part.removed)) continue
78
          let temp = norm
79
          for (let i = 0; i < part.count; i++) {
80
            if (!snippet.vulnLines.includes(prev + i + 1 - norm) && !snippet.neutralLines.includes(prev + i + 1 - norm)) {
81
              process.stdout.write(colors.green(colors.inverse((prev + i + 1 - norm + ''))))
82
              process.stdout.write(' ')
83
              data[val].removed.push(prev + i + 1 - norm)
84
            } else if (snippet.vulnLines.includes(prev + i + 1 - norm)) {
85
              process.stdout.write(colors.green(colors.bold(prev + i + 1 - norm + ' ')))
86
            } else if (snippet.neutralLines.includes(prev + i + 1 - norm)) {
87
              process.stdout.write(colors.green(prev + i + 1 - norm + ' '))
88
            }
89
            temp++
90
          }
91
          norm = temp
92
        }
93
        process.stdout.write('\n')
94
      })
95
      .catch(err => {
96
        console.log(err)
97
      })
98
  }
99
  return data
100
}
101

102
async function seePatch (file: string) {
103
  const fileData = fs.readFileSync(fixesPath + '/' + file).toString()
104
  const snippet = await retrieveCodeSnippet(file.split('_')[0])
105
  if (snippet == null) return
106
  const patch = Diff.structuredPatch(file, file, filterString(snippet.snippet), filterString(fileData))
107
  console.log(colors.bold(file + '\n'))
108
  for (const hunk of patch.hunks) {
109
    for (const line of hunk.lines) {
110
      if (line[0] === '-') {
111
        console.log(colors.red(line))
112
      } else if (line[0] === '+') {
113
        console.log(colors.green(line))
114
      } else {
115
        console.log(line)
116
      }
117
    }
118
  }
119
  console.log('---------------------------------------')
120
}
121

122
function checkData (data: CacheData, fileData: CacheData) {
123
  const filesWithDiff = []
124
  for (const key in data) {
125
    const fileDataValueAdded = fileData[key].added.sort((a, b) => a - b)
126
    const dataValueAdded = data[key].added.sort((a, b) => a - b)
127
    const fileDataValueRemoved = fileData[key].added.sort((a, b) => a - b)
128
    const dataValueAddedRemoved = data[key].added.sort((a, b) => a - b)
129
    if (fileDataValueAdded.length === dataValueAdded.length && fileDataValueRemoved.length === dataValueAddedRemoved.length) {
130
      if (!dataValueAdded.every((val: number, ind: number) => fileDataValueAdded[ind] === val)) {
131
        console.log(colors.red(key))
132
        filesWithDiff.push(key)
133
      }
134
      if (!dataValueAddedRemoved.every((val: number, ind: number) => fileDataValueRemoved[ind] === val)) {
135
        console.log(colors.red(key))
136
        filesWithDiff.push(key)
137
      }
138
    } else {
139
      console.log(colors.red(key))
140
      filesWithDiff.push(key)
141
    }
142
  }
143
  return filesWithDiff
144
}
145

146
export {
147
  checkDiffs,
148
  writeToFile,
149
  getDataFromFile,
150
  readFiles,
151
  seePatch,
152
  checkData
153
}
154

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.