-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
148 lines (130 loc) · 5.46 KB
/
Copy pathserver.js
File metadata and controls
148 lines (130 loc) · 5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
process.env.TZ = 'America/New_York';
require('dotenv').config();
const express = require('express');
const path = require('path');
const methodOverride = require('method-override');
const morgan = require('morgan');
const helmet = require('helmet');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
global.appRoot = path.resolve(__dirname);
const app = express();
const { webFQDN, webPort, appName } = require('./config/config');
const logger = require('./utils/logger');
const mongooseConnect = require('./config/mongoose');
const sessionConfig = require('./middleware/session');
const buildInfo = require('./utils/buildInfo');
const startScheduler = require('./services/jobs/scheduler');
const { getUpdateStatus } = require('./services/updates/checkForUpdates');
const mergeCategoriesIntoTags = require('./services/migrations/mergeCategoriesIntoTags');
// Database
mongooseConnect().then(() => {
mergeCategoriesIntoTags().catch((err) => logger.error('Category→tag migration failed: ' + err.message));
});
// Background jobs (emergency-access grant promotion — see services/jobs/scheduler.js)
startScheduler();
// View engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('trust proxy', true);
// Security headers. CSP is nonce-based and deliberately strict: this app
// holds decrypted vault secrets in page memory during a session, so an XSS
// bug here is far more dangerous than in a typical app — no inline scripts,
// no eval.
app.use((req, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
next();
});
const helmetMiddleware = helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
imgSrc: ["'self'", 'data:'],
connectSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'none'"],
frameAncestors: ["'none'"],
// helmet enables this by default, which tells the browser to
// rewrite any http: subresource/fetch URL on the page to https:.
// Fine in production (always behind real TLS — see README), but
// it silently breaks plain-HTTP local testing (e.g. an SSH
// tunnel to localhost) since nothing is listening on https for
// that request to land on.
upgradeInsecureRequests: process.env.NODE_ENV === 'production' ? [] : null
}
}
});
app.use(helmetMiddleware);
// Static assets
app.use(express.static(path.join(__dirname, 'public')));
// Body parsing & method override
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: '2mb' }));
app.use(methodOverride('_method'));
app.use(cookieParser());
// HTTP logging (never logs bodies — see utils/logger.js)
app.use(morgan('combined', { stream: { write: msg => logger.info(msg.trim()) } }));
// Session
app.use(sessionConfig);
// Expose common view locals
app.use((req, res, next) => {
res.locals.appName = appName;
res.locals.path = req.path;
res.locals.buildInfo = buildInfo;
res.locals.isAuthenticated = !!req.session.userId;
res.locals.isAdmin = !!req.session.isAdmin;
res.locals.themeColors = req.session.themeColors || null;
res.locals.updateStatus = getUpdateStatus();
next();
});
// Routes
const { doubleCsrfProtection } = require('./middleware/csrf');
const { apiBaselineLimiter } = require('./middleware/rateLimit');
const pagesRoutes = require('./routes/pages');
const statusRoutes = require('./routes/status');
const authPagesRoutes = require('./routes/authPages');
const adminPagesRoutes = require('./routes/admin');
const authApiRoutes = require('./routes/api/auth');
const vaultItemsApiRoutes = require('./routes/api/vaultItems');
const uploadsApiRoutes = require('./routes/api/uploads');
const tagsApiRoutes = require('./routes/api/tags');
const grantsApiRoutes = require('./routes/api/grants');
const adminApiRoutes = require('./routes/api/admin');
const apiRouter = express.Router();
apiRouter.use(apiBaselineLimiter);
apiRouter.use(doubleCsrfProtection);
apiRouter.use('/auth', authApiRoutes);
apiRouter.use('/vault-items', vaultItemsApiRoutes);
apiRouter.use('/uploads', uploadsApiRoutes);
apiRouter.use('/tags', tagsApiRoutes);
apiRouter.use('/grants', grantsApiRoutes);
apiRouter.use('/admin', adminApiRoutes);
app.use('/', pagesRoutes);
app.use('/', statusRoutes);
app.use('/auth', authPagesRoutes);
app.use('/admin', adminPagesRoutes);
app.use('/api', apiRouter);
// 404
app.use((req, res) => {
res.status(404).render('error', { message: 'Page not found' });
});
// Error handler
app.use((err, req, res, next) => {
if (err && err.code === 'EBADCSRFTOKEN') {
return res.status(403).json({ error: 'Invalid or missing CSRF token' });
}
if (err && err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'File is too large (150MB limit)' });
}
logger.error('Unhandled error: ' + err.message);
if (req.path.startsWith('/api/')) {
return res.status(500).json({ error: 'An unexpected error occurred' });
}
res.status(500).render('error', { message: 'An unexpected error occurred' });
});
app.listen(webPort, () => {
logger.info(`Fond Waypoints server running at https://${webFQDN}:${webPort}`);
console.log(`Fond Waypoints server running at https://${webFQDN}:${webPort}`);
});