-
Notifications
You must be signed in to change notification settings - Fork 309
Expand file tree
/
Copy pathorigin-check.middleware.ts
More file actions
65 lines (57 loc) · 1.96 KB
/
origin-check.middleware.ts
File metadata and controls
65 lines (57 loc) · 1.96 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
import type { Request, Response, NextFunction } from 'express';
import { getTrustedOrigins } from './auth.server';
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
/**
* Paths exempt from Origin validation (webhooks, public endpoints).
* These are called by external services that don't send browser Origin headers.
*/
const EXEMPT_PATH_PREFIXES = [
'/api/auth', // better-auth handles its own CSRF
'/v1/health', // health check
'/api/docs', // swagger
];
/**
* Express middleware that validates the Origin header on state-changing requests.
*
* This is defense-in-depth against CSRF attacks that bypass CORS:
* - HTML form submissions (Content-Type: application/x-www-form-urlencoded)
* don't trigger CORS preflight, so CORS alone doesn't block them.
* - This middleware rejects any state-changing request whose Origin header
* doesn't match a trusted origin.
*
* API keys and service tokens (which don't come from browsers) typically
* don't send an Origin header, so requests without an Origin are allowed
* — they'll be authenticated by HybridAuthGuard instead.
*/
export function originCheckMiddleware(
req: Request,
res: Response,
next: NextFunction,
): void {
// Allow safe (read-only) methods
if (SAFE_METHODS.has(req.method)) {
return next();
}
// Allow exempt paths (webhooks, auth, etc.)
const isExempt = EXEMPT_PATH_PREFIXES.some((prefix) =>
req.path.startsWith(prefix),
);
if (isExempt) {
return next();
}
const origin = req.headers['origin'] as string | undefined;
// No Origin header = not a browser request (API key, service token, curl, etc.)
// These are authenticated via HybridAuthGuard, not cookies, so no CSRF risk.
if (!origin) {
return next();
}
// Validate Origin against trusted origins
const trustedOrigins = getTrustedOrigins();
if (trustedOrigins.includes(origin)) {
return next();
}
res.status(403).json({
statusCode: 403,
message: 'Forbidden',
});
}