/** * Client HTTP de l'API Django (sessions + CSRF). * * Le cookie CSRF est déposé par GET /auth/me/ ; il est renvoyé dans l'en-tête X-CSRFToken * pour toutes les requêtes qui modifient l'état. */ import type { Assessment, LoginResult, RegisterPayload, TotpSetup, User } from './types' const BASE = '/api/v1' export class ApiError extends Error { readonly status: number readonly body: Record constructor(status: number, body: Record) { super(typeof body.detail === 'string' ? body.detail : `HTTP ${status}`) this.status = status this.body = body } get code(): string | undefined { return typeof this.body.code === 'string' ? this.body.code : undefined } /** Messages de validation par champ (réponse 400 de DRF). */ fieldErrors(): Record { const errors: Record = {} for (const [field, value] of Object.entries(this.body)) { if (Array.isArray(value) && typeof value[0] === 'string') errors[field] = value.join(' ') } return errors } } export function csrfToken(): string { const match = document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/) return match?.[1] ? decodeURIComponent(match[1]) : '' } async function request(method: string, path: string, body?: unknown): Promise { const headers: Record = { Accept: 'application/json' } if (method !== 'GET') { headers['X-CSRFToken'] = csrfToken() } if (body !== undefined) { headers['Content-Type'] = 'application/json' } const response = await fetch(`${BASE}${path}`, { method, headers, credentials: 'same-origin', body: body === undefined ? undefined : JSON.stringify(body), }) if (response.status === 204) { return undefined as T } const data = await response.json().catch(() => ({})) if (!response.ok) { throw new ApiError(response.status, data) } return data as T } export const api = { me: () => request('GET', '/auth/me/'), login: (email: string, password: string) => request('POST', '/auth/login/', { email, password }), verifyMfa: (code: string) => request('POST', '/auth/2fa/verify/', { code }), logout: () => request('POST', '/auth/logout/'), register: (payload: RegisterPayload) => request('POST', '/auth/register/', payload), verifyEmail: (token: string) => request<{ status: string }>('POST', '/auth/verify-email/', { token }), resendVerification: (target: { email?: string; token?: string }) => request('POST', '/auth/verify-email/resend/', target), changePassword: (current_password: string, new_password: string) => request('POST', '/auth/password/change/', { current_password, new_password }), requestPasswordReset: (email: string) => request('POST', '/auth/password-reset/', { email }), validateResetToken: (token: string) => request('POST', '/auth/password-reset/validate/', { token }), resetPassword: (token: string, new_password: string) => request('POST', '/auth/password-reset/confirm/', { token, new_password }), setupTotp: () => request('POST', '/auth/2fa/setup/'), enableTotp: (code: string) => request<{ recovery_codes: string[] }>('POST', '/auth/2fa/enable/', { code }), disableTotp: (password: string, code: string) => request('POST', '/auth/2fa/disable/', { password, code }), regenerateRecoveryCodes: (code: string) => request<{ recovery_codes: string[] }>('POST', '/auth/2fa/recovery-codes/', { code }), assess: (address: string) => request('POST', '/assessments/', { address }), }