app.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const fileUpload = require('express-fileupload');
  4. const compression = require('compression');
  5. const config = require('./lib/config');
  6. const log = require('./logger').express;
  7. /**
  8. * App
  9. */
  10. const app = express();
  11. app.use(fileUpload());
  12. app.use(bodyParser.json());
  13. app.use(bodyParser.urlencoded({extended: true}));
  14. // Gzip
  15. app.use(compression());
  16. /**
  17. * General Logging, BEFORE routes
  18. */
  19. app.disable('x-powered-by');
  20. app.enable('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);
  21. app.enable('strict routing');
  22. // pretty print JSON when not live
  23. if (config.debug()) {
  24. app.set('json spaces', 2);
  25. }
  26. // CORS for everything
  27. app.use(require('./lib/express/cors'));
  28. // General security/cache related headers + server header
  29. app.use(function (req, res, next) {
  30. let x_frame_options = 'DENY';
  31. if (typeof process.env.X_FRAME_OPTIONS !== 'undefined' && process.env.X_FRAME_OPTIONS) {
  32. x_frame_options = process.env.X_FRAME_OPTIONS;
  33. }
  34. res.set({
  35. 'X-XSS-Protection': '1; mode=block',
  36. 'X-Content-Type-Options': 'nosniff',
  37. 'X-Frame-Options': x_frame_options,
  38. 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
  39. Pragma: 'no-cache',
  40. Expires: 0
  41. });
  42. next();
  43. });
  44. app.use(require('./lib/express/jwt')());
  45. app.use('/', require('./routes/main'));
  46. // production error handler
  47. // no stacktraces leaked to user
  48. // eslint-disable-next-line
  49. app.use(function (err, req, res, next) {
  50. let payload = {
  51. error: {
  52. code: err.status,
  53. message: err.public ? err.message : 'Internal Error'
  54. }
  55. };
  56. if (config.debug() || (req.baseUrl + req.path).includes('nginx/certificates')) {
  57. payload.debug = {
  58. stack: typeof err.stack !== 'undefined' && err.stack ? err.stack.split('\n') : null,
  59. previous: err.previous
  60. };
  61. }
  62. // Not every error is worth logging - but this is good for now until it gets annoying.
  63. if (typeof err.stack !== 'undefined' && err.stack) {
  64. if (config.debug()) {
  65. log.debug(err.stack);
  66. } else if (typeof err.public == 'undefined' || !err.public) {
  67. log.warn(err.message);
  68. }
  69. }
  70. res
  71. .status(err.status || 500)
  72. .send(payload);
  73. });
  74. module.exports = app;