Skip to content

Instantly share code, notes, and snippets.

@roryprimrose
Created June 2, 2016 00:29
Show Gist options
  • Save roryprimrose/9d6a225df31e2dc24fb5f2322a043994 to your computer and use it in GitHub Desktop.
Save roryprimrose/9d6a225df31e2dc24fb5f2322a043994 to your computer and use it in GitHub Desktop.
node issues
var express = require('express');
var helmet = require('helmet');
var compression = require('compression');
var serveStatic = require('serve-static');
var https = require('https');
var pem = require('pem');
var forceSSL = require('express-force-ssl');
var app = express();
function includeHeaderSecurity(app) {
app.use(helmet.csp({
// Specify directives as normal.
directives: {
defaultSrc: ["'none'"],
scriptSrc: ["'self'", "ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"],
styleSrc: ["'self'"],
connectSrc: ["'self'"],
imgSrc: ["'self'", "'data:'"],
objectSrc: [], // An empty array allows nothing through
},
// Set to true if you only want browsers to report errors, not block them
reportOnly: false,
// Set to true if you want to blindly set all headers: Content-Security-Policy,
// X-WebKit-CSP, and X-Content-Security-Policy.
setAllHeaders: false,
// Set to true if you want to disable CSP on Android where it can be buggy.
disableAndroid: false,
// Set to false if you want to completely disable any user-agent sniffing.
// This may make the headers less compatible but it will be much faster.
// This defaults to `true`.
browserSniff: true
}));
app.use(helmet.xssFilter());
app.use(helmet.frameguard({ action: 'deny' }));
app.use(helmet.hsts({
maxAge: 10886400000, // Must be at least 18 weeks to be approved by Google
//includeSubdomains: true, // Must be enabled to be approved by Google
preload: true
}));
app.use(helmet.hidePoweredBy());
app.use(helmet.noSniff());
};
function requireEncryption(app, port) {
app.set('forceSSLOptions', {
enable301Redirects: true,
trustXFPHeader: false,
httpsPort: port,
sslRequiredMessage: 'SSL Required.'
});
app.use(forceSSL);
}
function registerRoutes(app) {
app.head('/', function (req, res) {
res.send('Success');
});
// Allow static access to the following folders
app.use('/content', serveStatic(__dirname + '/content'));
app.use('/images', serveStatic(__dirname + '/images'));
app.use('/scripts', serveStatic(__dirname + '/scripts'));
app.use('/views', serveStatic(__dirname + '/views'));
// Any other request gets the website
app.use(function (req, res, next) {
// If the request is for one of the static paths then we should return a 404 instead
if (req.url.indexOf("/content/") > -1
|| req.url.indexOf('/images/') > -1
|| req.url.indexOf('/scripts/') > -1
|| req.url.indexOf('/views/') > -1)
{
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.send('404: Page not Found');
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
}
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
};
//app.use(compression());
var port = process.env.port || 443;
var environment = process.env.environment || "production";
console.log("Configuring " + environment + " website to listening on port " + port + " for path " + __dirname);
//requireEncryption(app, port);
//registerRoutes(app);
app.get('/', function(req, res){
res.send('hello world using port' + port + " for environment " + environment);
});
if (environment === "production") {
//includeHeaderSecurity(app);
app.listen(port, function () {
console.log("Website listening on port " + port + " for path " + __dirname);
});
}
else {
pem.createCertificate({days:1, selfSigned:true}, function(err, keys){
if (err)
{
console.log(err.message);
}
else
{
https.createServer({key: keys.serviceKey, cert: keys.certificate}, app).listen(port);
console.log("Website listening on port " + port + " for path " + __dirname);
}
});
}
<?xml version="1.0" encoding="utf-8"?>
<!--
This configuration file is required if iisnode is used to run node processes behind
IIS or IIS Express. For more information, visit:
https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->
<configuration>
<system.web>
<customErrors mode="off" />
<httpRuntime maxQueryStringLength="2097151" maxUrlLength="2097151" />
</system.web>
<system.webServer>
<!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
<webSocket enabled="false" />
<modules runAllManagedModulesForAllRequests="false" />
<handlers>
<!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
<add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
</handlers>
<rewrite>
<rules>
<!-- Do not interfere with requests for node-inspector debugging -->
<!--<rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
<match url="^server.js\/debug[\/]?" />
</rule>-->
<!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
<!--<rule name="StaticContent">
<action type="Rewrite" url="public{REQUEST_URI}"/>
</rule>-->
<!-- All other URLs are mapped to the node.js site entry point -->
<!--<rule name="DynamicContent">
<match url="/*" />
<action type="Rewrite" url="server.js"/>
</rule>-->
<clear />
<rule name="app" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
<match url="iisnode.+" negate="true" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="server.js" />
</rule>
</rules>
</rewrite>
<!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
<security>
<requestFiltering>
<hiddenSegments>
<remove segment="bin"/>
</hiddenSegments>
</requestFiltering>
</security>
<!-- Make sure error responses are left untouched -->
<httpErrors existingResponse="PassThrough" />
<!--
You can control how Node is hosted within IIS using the following options:
* watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
* node_env: will be propagated to node as NODE_ENV environment variable
* debuggingEnabled - controls whether the built-in debugger is enabled
See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
-->
<!--<iisnode node_env="production" nodeProcessCountPerApplication="0" promoteServerVars="HTTPS,REMOTE_ADDR" />-->
<iisnode debuggingEnabled="true" devErrorsEnabled="true" logDirectory="../../LogFiles/iisnode" loggingEnabled="true" watchedFiles="web.config;*.js"/>
</system.webServer>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment