Fix DoS in CSV parser (#1467)

* Fix DoS in CSV parser

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2021-08-31 22:23:18 +02:00 committed by GitHub
parent 553e9f8ead
commit 90ae3c1f76
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,11 +4,27 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
/**
* Parses a given text as comma separated values (CSV).
*
* @param csvText The raw csv text
* @param csvColumnDelimiter The delimiter for the columns
* @return the values splitted by rows and columns
*/
export const parseCsv = (csvText: string, csvColumnDelimiter: string): string[][] => {
const rows = csvText.split('\n')
if (!rows || rows.length === 0) {
return []
}
const splitRegex = new RegExp(`${csvColumnDelimiter}(?=(?:[^"]*"[^"]*")*[^"]*$)`)
const splitRegex = new RegExp(`${escapeRegexCharacters(csvColumnDelimiter)}(?=(?:[^"]*"[^"]*")*[^"]*$)`)
return rows.filter((row) => row !== '').map((row) => row.split(splitRegex))
}
/**
* Escapes regex characters in the given string so it can be used as literal string in another regex.
* @param unsafe The unescaped string
* @return The escaped string
*/
const escapeRegexCharacters = (unsafe: string): string => {
return unsafe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}