app.js 2.3 KB

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