Last active
January 15, 2020 08:42
-
-
Save watson/be632d939064620e4af29adb981d6f60 to your computer and use it in GitHub Desktop.
Using Node.js worker threads to guard against ReDoS attacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const { Worker } = require('worker_threads') | |
const worker = new Worker(` | |
const { workerData, parentPort } = require('worker_threads') | |
const result = workerData.str.match(workerData.regex) | |
parentPort.postMessage(result) | |
`, { | |
workerData: { | |
regex: /([a-z]+)+$/, | |
str: 'aaaaaaaaaaaaaaaaaaaaaaaaaaa a' // without the space, the regex is fast, with the space it takes over 1s | |
}, | |
eval: true | |
}) | |
worker.on('message', result => { | |
console.log(result) | |
}) | |
worker.on('exit', code => { | |
console.log('exit code', code) | |
clearTimeout(timer) | |
}) | |
const timer = setTimeout(() => { | |
console.log('terminating worker') | |
worker.terminate() | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment