-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.js
More file actions
298 lines (256 loc) · 9.18 KB
/
Copy pathsecurity.js
File metadata and controls
298 lines (256 loc) · 9.18 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Lightweight security middleware for miso-chat.
// Provides baseline security headers + per-session CSRF tokens + origin checks
// for state-changing browser requests.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
function normalizeOrigin(value) {
const raw = String(value || '').trim();
if (!raw) return '';
if (raw === 'null') return 'null';
try {
const parsed = new URL(raw);
if (parsed.origin && parsed.origin !== 'null') {
return parsed.origin.toLowerCase();
}
// URL.origin is "null" for custom schemes (capacitor://, ionic://, app://).
if (parsed.protocol && parsed.host) {
return `${parsed.protocol}//${parsed.host}`.toLowerCase();
}
return '';
} catch {
return '';
}
}
function loadAllowedOrigins() {
const defaults = [
'http://localhost',
'https://localhost',
'http://127.0.0.1',
'https://127.0.0.1',
'http://localhost:3000',
'http://127.0.0.1:3000',
'capacitor://localhost',
'ionic://localhost',
'app://localhost',
'null',
];
const configured = [
process.env.CORS_ORIGIN,
process.env.ALLOWED_ORIGINS,
process.env.CSRF_TRUSTED_ORIGINS,
]
.filter(Boolean)
.flatMap((value) => String(value).split(','));
const allowed = new Set();
for (const origin of [...defaults, ...configured]) {
const normalized = normalizeOrigin(origin);
if (normalized) allowed.add(normalized);
}
return allowed;
}
const allowedOrigins = loadAllowedOrigins();
function getRequestOrigin(req) {
const origin = normalizeOrigin(req.get('origin'));
if (origin) return origin;
const referer = req.get('referer');
if (!referer) return '';
try {
return new URL(referer).origin.toLowerCase();
} catch {
return '';
}
}
function getServerOrigin(req) {
const forwardedProto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim();
const protocol = forwardedProto || req.protocol || 'http';
const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
const host = forwardedHost || req.get('host') || '';
return normalizeOrigin(`${protocol}://${host}`);
}
/**
* Inline-script CSP hash manifest (audit #629).
*
* `public/csp-hashes.json` is generated by `scripts/build-csp-hashes.js` and
* lists the SHA-256 hashes of every non-empty inline `<script>` block in
* `public/*.html`. We pin those hashes in `script-src` instead of
* `'unsafe-inline'` so the CSP defense-in-depth that catches future XSS bugs
* is restored without requiring per-request nonces.
*
* If the manifest is missing or malformed we log a warning and fall back to
* `'unsafe-inline'`. In production (`NODE_ENV=production`) we keep that
* fallback, but startup emits a one-line warning so the failure is loud.
*/
const CSP_HASH_MANIFEST_PATH = path.join(__dirname, 'public', 'csp-hashes.json');
function loadInlineScriptHashes() {
try {
const raw = fs.readFileSync(CSP_HASH_MANIFEST_PATH, 'utf8');
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return null;
if (parsed.algorithm !== 'sha256') return null;
const files = parsed.files || {};
const hashes = new Set();
for (const entry of Object.values(files)) {
if (!entry || !Array.isArray(entry.hashes)) continue;
for (const h of entry.hashes) {
if (typeof h === 'string' && h.startsWith("'sha256-")) {
hashes.add(h);
}
}
}
return hashes;
} catch (err) {
if (err.code !== 'ENOENT') {
console.warn('[security] failed to read CSP hash manifest:', err.message);
}
return null;
}
}
const inlineScriptHashes = loadInlineScriptHashes();
if (!inlineScriptHashes || inlineScriptHashes.size === 0) {
const msg =
'[security] public/csp-hashes.json missing or empty — falling back to ' +
"'unsafe-inline' for script-src. Run `node scripts/build-csp-hashes.js` " +
'and commit the result.';
if (process.env.NODE_ENV === 'production') {
console.warn(msg);
} else {
console.warn(msg);
}
}
function getScriptSrcDirective() {
const sources = ["'self'"];
if (inlineScriptHashes && inlineScriptHashes.size > 0) {
for (const h of inlineScriptHashes) sources.push(h);
} else {
sources.push("'unsafe-inline'");
}
return `script-src ${sources.join(' ')}`;
}
// ---------------------------------------------------------------------------
// CSRF Token system — route-level per-session tokens for browser clients.
// ---------------------------------------------------------------------------
const CSRF_TOKEN_LENGTH = 32; // bytes → 64 hex chars
/**
* Generate a cryptographically random CSRF token and store it in the session.
* Returns the token string.
*/
function generateCsrfToken(req) {
if (!req.session) return null;
const token = crypto.randomBytes(CSRF_TOKEN_LENGTH).toString('hex');
req.session.csrfToken = token;
return token;
}
/**
* Check whether a request appears to be from a browser (has Origin or Referer).
* Non-browser callers (mobile apps, API clients) typically omit these headers.
*/
function isBrowserRequest(req) {
const origin = req.get('origin');
const referer = req.get('referer');
return Boolean(origin || referer);
}
/**
* Frontend integration notes:
* - The frontend MUST fetch a fresh CSRF token on page load via GET /api/csrf-token.
* - The frontend MUST include the token in the X-CSRF-Token header for all
* state-changing browser requests (POST/PUT/PATCH/DELETE).
* - After each successful state-changing request, the server rotates the token.
* The frontend should either:
* (a) Fetch a new token before each state-changing request, or
* (b) Handle 403 responses by fetching a fresh token and retrying.
* - Non-browser callers (mobile apps, API clients) are exempt — they use other auth.
* - If no csrfToken exists in the session yet (e.g., before first /api/csrf-token call),
* the check is skipped to avoid blocking unauthenticated requests.
*/
/**
* CSRF token validation middleware for state-changing requests from browsers.
*
* - Skipped entirely for non-browser callers (no Origin/Referer) — they use
* other auth mechanisms (session cookies, mobile auth tokens, etc.).
* - For browser requests on POST/PUT/PATCH/DELETE, requires the `X-CSRF-Token`
* header to match the current per-session token.
* - On success, rotates the token (old token is invalidated).
*/
function csrfTokenCheck(req, res, next) {
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
return next();
}
// Skip CSRF check for non-browser callers (mobile apps, API clients, etc.).
// These use session cookies or mobile auth tokens as their primary auth.
if (!isBrowserRequest(req)) {
return next();
}
// Must have a session to validate CSRF tokens.
if (!req.session || !req.session.csrfToken) {
return next();
}
const providedToken = String(req.get('x-csrf-token') || '').trim();
if (!providedToken) {
return res.status(403).json({
error: 'Forbidden: CSRF token required',
detail: 'State-changing browser requests require an X-CSRF-Token header.',
});
}
// Constant-time comparison to prevent timing attacks.
const expected = req.session.csrfToken;
if (providedToken.length !== expected.length) {
return res.status(403).json({
error: 'Forbidden: invalid CSRF token',
});
}
let match = true;
for (let i = 0; i < providedToken.length; i++) {
match &= providedToken.charCodeAt(i) === expected.charCodeAt(i);
}
if (!match) {
return res.status(403).json({
error: 'Forbidden: invalid CSRF token',
});
}
// Rotate the token after successful validation.
req.session.csrfToken = crypto.randomBytes(CSRF_TOKEN_LENGTH).toString('hex');
next();
}
function securityHeaders(req, res, next) {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
res.setHeader('Content-Security-Policy', [
"default-src 'self'",
"base-uri 'self'",
"object-src 'none'",
"frame-ancestors 'none'",
"img-src 'self' data:",
`style-src 'self' 'unsafe-inline'`,
getScriptSrcDirective(),
"connect-src 'self' ws: wss:",
"form-action 'self'",
"media-src 'self'",
"worker-src 'self'",
].join('; '));
next();
}
function csrfOriginCheck(req, res, next) {
if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
return next();
}
const requestOrigin = getRequestOrigin(req);
// Allow non-browser callers (no origin/referer).
if (!requestOrigin) {
return next();
}
const serverOrigin = getServerOrigin(req);
if (requestOrigin === serverOrigin || allowedOrigins.has(requestOrigin)) {
return next();
}
return res.status(403).json({
error: 'Forbidden: untrusted request origin',
});
}
module.exports = [securityHeaders, csrfTokenCheck, csrfOriginCheck];
module.exports.generateCsrfToken = generateCsrfToken;
module.exports.getScriptSrcDirective = getScriptSrcDirective;
module.exports.loadInlineScriptHashes = loadInlineScriptHashes;
module.exports.CSP_HASH_MANIFEST_PATH = CSP_HASH_MANIFEST_PATH;