Skip to content

Instantly share code, notes, and snippets.

@geek0x23
Created February 18, 2013 22:52
Show Gist options
  • Save geek0x23/4981505 to your computer and use it in GitHub Desktop.
Save geek0x23/4981505 to your computer and use it in GitHub Desktop.
browserify middleware with a file whitelist and very rudamentary caching.
"use strict";
var browserify = require("browserify"),
b = browserify(),
bundles = [];
module.exports = {
browserify: function(app) {
return function(req, res, next) {
// whitelist what we bundle.
var body, fileName,
isWhitelisted = false,
whitelist = ["customer.js"];
// make sure that it's a validator url, and that we
// the requested path is whitelisted. this is just
// a simple means of protecting against directory
// traversal attacks and exposing application logic.
if (req.url.indexOf("/validators/") === 0) {
var counter = 0;
fileName = req.url.substring("12");
for (counter = 0; counter < whitelist.length; counter += 1) {
if (fileName === whitelist[counter]) {
isWhitelisted = true;
break;
}
}
if (isWhitelisted === true) {
// check our cache first
if (app.enabled("browserifyCaching") && bundles[fileName]) {
body = bundles[fileName];
} else {
// no cache entry, so bundle this and create one.
body = bundles[fileName] = b.require("./validators/" + fileName).bundle();
}
res.setHeader("Content-Type", "application/javascript");
res.setHeader("Content-Length", body.length);
res.end(body);
} else {
next();
}
} else {
next();
}
};
}
};
@katanacrimson
Copy link

replace for loop with

if(whitelist.indexOf(fileName) !== -1) {
    isWhitelisted = true
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment