Skip to content

Instantly share code, notes, and snippets.

@watson
Last active January 15, 2020 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watson/be632d939064620e4af29adb981d6f60 to your computer and use it in GitHub Desktop.
Save watson/be632d939064620e4af29adb981d6f60 to your computer and use it in GitHub Desktop.
Using Node.js worker threads to guard against ReDoS attacks
'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