/** * Client HTTP unique vers l'API StreakFit. * Auth = cookie de session Sanctum (credentials: 'include') + en-tête X-XSRF-TOKEN. * Le front ne stocke AUCUN token : tout est piloté par le back. */ function readCookie(name: string): string | null { if (import.meta.server) return null const m = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)')) return m ? decodeURIComponent(m[2]!) : null } export function useApi() { const base = useRuntimeConfig().public.apiBase as string const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']) const api = $fetch.create({ baseURL: base, credentials: 'include', headers: { Accept: 'application/json' }, async onRequest({ options }) { const method = String(options.method || 'GET').toUpperCase() let xsrf = readCookie('XSRF-TOKEN') // Requête mutante sans cookie XSRF (ex : session ouverte via OIDC/pocket-id qui n'est jamais // passée par /sanctum/csrf-cookie) → on pose le cookie avant, sinon Sanctum renvoie 419. if (!xsrf && !SAFE_METHODS.has(method)) { await ensureCsrf() xsrf = readCookie('XSRF-TOKEN') } const headers = new Headers(options.headers as HeadersInit) if (xsrf) headers.set('X-XSRF-TOKEN', xsrf) options.headers = headers } }) /** Pose le cookie XSRF avant toute requête mutante (login, register, POST…). */ async function ensureCsrf() { await $fetch('/sanctum/csrf-cookie', { baseURL: base, credentials: 'include' }) } return { api, ensureCsrf, base } }