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>
79 lines
2.3 KiB
TypeScript
79 lines
2.3 KiB
TypeScript
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001';
|
|
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
public status: number,
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
this.name = 'ApiError';
|
|
}
|
|
}
|
|
|
|
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,
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const error = await res.json().catch(() => ({ message: res.statusText }));
|
|
throw new ApiError(res.status, error.message || 'Request failed');
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
function authHeaders(token: string): HeadersInit {
|
|
return { Authorization: `Bearer ${token}` };
|
|
}
|
|
|
|
export const apiClient = {
|
|
get: <T>(endpoint: string, headers?: HeadersInit) =>
|
|
request<T>(endpoint, { method: 'GET', headers }),
|
|
|
|
post: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
|
request<T>(endpoint, { method: 'POST', body, headers }),
|
|
|
|
patch: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
|
request<T>(endpoint, { method: 'PATCH', body, headers }),
|
|
|
|
authGet: <T>(endpoint: string, token: string) =>
|
|
request<T>(endpoint, { method: 'GET', headers: authHeaders(token) }),
|
|
|
|
authPost: <T>(endpoint: string, token: string, body?: unknown) =>
|
|
request<T>(endpoint, { method: 'POST', body, headers: authHeaders(token) }),
|
|
|
|
authPatch: <T>(endpoint: string, token: string, body?: unknown) =>
|
|
request<T>(endpoint, { method: 'PATCH', body, headers: authHeaders(token) }),
|
|
};
|