Folkwise-io / mintbean-cli

MIT License
13 stars 9 forks source link

implement safer ejs compile by checking for file mimetype #14

Closed clairefro closed 4 years ago

clairefro commented 4 years ago

Previously only checked for /<%=.*%>/ pattern to determine whether to ejs compile. now make check with mimetypes to only run ejs.compile() on mimetypes 'text/...' and 'application/...'

const mime = require ('mime');
...
const isEjsTemplatable = (file) => {
  const ext = path.extname(file).replace('.','');
  const mimetype= mime.getType(ext);
  return (/^(text\/)|(application\/)/).test(mimetype)
}

...

files.forEach(({ absolutePath, pathFromDirectoryRoot }) => {
      const templateBuffer = fs.readFileSync(absolutePath)

      // only run ejs.compile on text files
      const isTemplatable = isEjsTemplatable(absolutePath)
      const output = isTemplatable ?
                   ejs.compile(templateBuffer.toString('utf-8'))(options) :
                   templateBuffer;
      const tmpDestination = path.join(temporaryDirectory, pathFromDirectoryRoot);
      ensureDirectoryExistence(tmpDestination);
      fs.writeFileSync(tmpDestination, output);
    });