Swadhin Biswas Feature/ai code reviewer (#80) · 8/17/2026
9740d3d
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
/**
* CSRF Protection Middleware
* Protects against Cross-Site Request Forgery attacks
* Uses double-submit cookie pattern for stateless operation
*/
import { nanoid } from "nanoid";
import { timingSafeEqual as nodeTimingSafeEqual } from "crypto";
const CSRF_TOKEN_LENGTH = 32;
const CSRF_COOKIE_NAME = "csrf_token";
const CSRF_HEADER_NAME = "x-csrf-token";
/**
* Generate a new CSRF token
*/
export function generateCsrfToken(): string {
return nanoid(CSRF_TOKEN_LENGTH);
}
/**
* Extract CSRF token from cookies
*/
function getCsrfTokenFromCookie(request: Request): string | null {
const cookieHeader = request.headers.get("cookie");
if (!cookieHeader) return null;
const cookies = cookieHeader.split(";").map((c) => c.trim());
for (const cookie of cookies) {
const eqIndex = cookie.indexOf("=");
if (eqIndex === -1) continue;
const name = cookie.substring(0, eqIndex).trim();
const value = cookie.substring(eqIndex + 1).trim();
if (name === CSRF_COOKIE_NAME) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
}
return null;
}
/**
* Extract CSRF token from request headers or body
* Uses request.clone() to avoid consuming the body stream
*/
async function getCsrfTokenFromRequest(request: Request): Promise<string | null> {
// Check header first
const headerToken = request.headers.get(CSRF_HEADER_NAME);
if (headerToken) return headerToken;
// For form submissions, check _csrf form field
// Clone the request so we don't consume the body stream
const contentType = request.headers.get("content-type") || "";
if (contentType.includes("application/x-www-form-urlencoded")) {
try {
const cloned = request.clone();
const body = await cloned.text();
const params = new URLSearchParams(body);
const formToken = params.get("_csrf");
if (formToken) return formToken;
} catch {
// Ignore errors parsing body
}
}
return null;
}
/**
* Validate CSRF token
*/
export async function validateCsrfToken(request: Request): Promise<boolean> {
// GET, HEAD, OPTIONS are safe methods - no CSRF protection needed
if (["GET", "HEAD", "OPTIONS"].includes(request.method)) {
return true;
}
// Skip for internal hooks (they use different auth)
const url = new URL(request.url);
if (url.pathname.startsWith("/api/internal/")) {
return true;
}
// Skip in development if configured
if (
process.env.NODE_ENV === "development" &&
process.env.CSRF_SKIP_DEV === "true"
) {
return true;
}
const cookieToken = getCsrfTokenFromCookie(request);
const requestToken = await getCsrfTokenFromRequest(request);
// Both must exist and match
if (!cookieToken || !requestToken) {
return false;
}
// Constant-time comparison to prevent timing attacks
return timingSafeEqual(cookieToken, requestToken);
}
/**
* Timing-safe string comparison using Node.js crypto
* Pads both strings to a fixed length to prevent length leakage
*/
const COMPARISON_FIXED_LENGTH = 64;
function timingSafeEqual(a: string, b: string): boolean {
const paddedA = a.padEnd(COMPARISON_FIXED_LENGTH, "\0");
const paddedB = b.padEnd(COMPARISON_FIXED_LENGTH, "\0");
const bufA = Buffer.from(paddedA, "utf8");
const bufB = Buffer.from(paddedB, "utf8");
return nodeTimingSafeEqual(bufA, bufB);
}
/**
* Create Set-Cookie header for CSRF token
*/
export function createCsrfCookie(token: string, secure: boolean = false): string {
const maxAge = 86400; // 24 hours
// Use Lax instead of Strict — Strict cookies are not sent on same-site
// form POSTs in some browser configurations, causing CSRF failures
const sameSite = "Lax";
return [
`${CSRF_COOKIE_NAME}=${encodeURIComponent(token)}`,
`Max-Age=${maxAge}`,
`Path=/`,
`SameSite=${sameSite}`,
`HttpOnly`,
secure ? "Secure" : "",
]
.filter(Boolean)
.join("; ");
}
/**
* CSRF middleware for Astro API routes
*/
export async function applyCsrfProtection(
request: Request
): Promise<Response | null> {
const isValid = await validateCsrfToken(request);
if (!isValid) {
return new Response(
JSON.stringify({
error: "CSRF token validation failed",
message: "Invalid or missing CSRF token. Please refresh and try again.",
}),
{
status: 403,
headers: {
"Content-Type": "application/json",
},
}
);
}
return null; // Continue to next handler
}
/**
* Helper to get or create CSRF token for a request
* Use this in page handlers to inject token into forms
*/
export function getCsrfToken(request: Request): { token: string; cookie: string } {
let token = getCsrfTokenFromCookie(request);
if (!token) {
token = generateCsrfToken();
}
const isSecure = process.env.NODE_ENV === "production";
const cookie = createCsrfCookie(token, isSecure);
return { token, cookie };
}