feat(security): add CSRF double-submit cookie protection

Add CSRF middleware with double-submit cookie pattern for all
state-changing requests. Integrate cookie-parser, update CORS
headers, and add client-side CSRF token handling.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 05:03:24 +07:00
parent 2a392525a2
commit e5f370ced1
5 changed files with 103 additions and 1 deletions

View File

@@ -14,13 +14,32 @@ type RequestOptions = Omit<RequestInit, 'body'> & {
body?: unknown;
};
function getCsrfToken(): string | undefined {
if (typeof document === 'undefined') return undefined;
const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/);
return match ? decodeURIComponent(match[1]) : undefined;
}
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
async function request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
const { body, headers, ...rest } = options;
const method = options.method?.toUpperCase() ?? 'GET';
const csrfHeaders: HeadersInit = {};
if (!SAFE_METHODS.has(method)) {
const csrfToken = getCsrfToken();
if (csrfToken) {
csrfHeaders['X-CSRF-Token'] = csrfToken;
}
}
const res = await fetch(`${API_BASE_URL}${endpoint}`, {
...rest,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...csrfHeaders,
...headers,
},
body: body ? JSON.stringify(body) : undefined,