deploy / deploy (push) Successful in 46s
- Double authentification : l'écran du code se ferme bien après un code juste (la session « aal2 » prévient maintenant l'app) ; plus d'affichage furtif de l'app avant la vérification ; revérification au retour du réseau - Serveur (migration 20261128170000, appliquée) : les lectures par fonction (profil, bibliothèque, fil, notifications, listes partagées, avis, recherche, blocages) exigent aussi le code pour un compte protégé ; une fiche restaurée ne compte plus comme « a noté » ; une demande d'abonnement refusée disparaît des notifications - Catalogue : la grille continue de se charger après un passage par Journal / Listes - Moyenne des notes de saison arrondie à la demi-étoile (et plus à l'étoile entière) - Double tap sur « +1 » : plus de double message de fin de revisionnage ; « −1 » jamais ignoré - Bouton « Ouvrir les Réglages » (clé TMDB retirée) supprimé de la recherche - Pluriels russe, polonais et arabe complétés pour les notifications Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
519 lines
21 KiB
TypeScript
519 lines
21 KiB
TypeScript
import { t, type TKey } from '../../i18n'
|
|
import { SUPABASE_ANON_KEY, SUPABASE_URL, withTimeout } from './config'
|
|
import { isPwnedPassword } from '../pwned'
|
|
|
|
/**
|
|
* Connexion aux comptes (Supabase Auth), sans dépendance.
|
|
* La session (jetons) est gardée sur l'appareil pour que l'app s'ouvre même hors-ligne ;
|
|
* le mot de passe, lui, n'est jamais stocké.
|
|
*/
|
|
|
|
export interface Session {
|
|
accessToken: string
|
|
refreshToken: string
|
|
/** Expiration du jeton d'accès (ms) */
|
|
expiresAt: number
|
|
user: { id: string; email: string }
|
|
}
|
|
|
|
export class AuthError extends Error {
|
|
/** Code d'erreur Supabase Auth (ex. « user_already_exists ») */
|
|
code?: string
|
|
}
|
|
|
|
const KEY = 'azuucine:session'
|
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
const TOKEN = /^[A-Za-z0-9._~+/=-]{10,8192}$/
|
|
export const PASSWORD_MIN = 8
|
|
|
|
function isSession(v: unknown): v is Session {
|
|
if (!v || typeof v !== 'object') return false
|
|
const s = v as Session
|
|
return (
|
|
typeof s.accessToken === 'string' &&
|
|
TOKEN.test(s.accessToken) &&
|
|
typeof s.refreshToken === 'string' &&
|
|
/^[A-Za-z0-9._~+/=-]{4,1024}$/.test(s.refreshToken) &&
|
|
typeof s.expiresAt === 'number' &&
|
|
Number.isFinite(s.expiresAt) &&
|
|
!!s.user &&
|
|
typeof s.user.id === 'string' &&
|
|
UUID.test(s.user.id) &&
|
|
typeof s.user.email === 'string' &&
|
|
s.user.email.length <= 320
|
|
)
|
|
}
|
|
|
|
function load(): Session | null {
|
|
try {
|
|
const raw = localStorage.getItem(KEY)
|
|
const parsed = raw ? JSON.parse(raw) : null
|
|
return isSession(parsed) ? parsed : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
let current: Session | null = load()
|
|
const listeners = new Set<(s: Session | null) => void>()
|
|
|
|
function setSession(s: Session | null) {
|
|
// Changement de compte, ou nouveau jeton (renouvellement, code de double authentification validé)
|
|
const changed = current?.user.id !== s?.user.id || current?.accessToken !== s?.accessToken
|
|
current = s
|
|
try {
|
|
if (s) localStorage.setItem(KEY, JSON.stringify(s))
|
|
else localStorage.removeItem(KEY)
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
if (changed) for (const fn of listeners) fn(s)
|
|
}
|
|
|
|
// Connexion / déconnexion dans un autre onglet
|
|
if (typeof window !== 'undefined') {
|
|
window.addEventListener('storage', (e) => {
|
|
if (e.key !== KEY) return
|
|
const next = load()
|
|
const changedUser = current?.user.id !== next?.user.id
|
|
current = next
|
|
if (changedUser) for (const fn of listeners) fn(next)
|
|
})
|
|
}
|
|
|
|
export const getSession = () => current
|
|
|
|
export function onSessionChange(fn: (s: Session | null) => void): () => void {
|
|
listeners.add(fn)
|
|
return () => listeners.delete(fn)
|
|
}
|
|
|
|
// ───────────────────────────── Appels à Supabase Auth ─────────────────────────────
|
|
|
|
const CODE_KEYS: Record<string, TKey> = {
|
|
invalid_credentials: 'auth.err.credentials',
|
|
invalid_grant: 'auth.err.credentials',
|
|
email_not_confirmed: 'auth.err.notConfirmed',
|
|
weak_password: 'auth.err.weak',
|
|
same_password: 'auth.err.samePassword',
|
|
over_email_send_rate_limit: 'auth.err.emailRate',
|
|
over_request_rate_limit: 'auth.err.rate',
|
|
signup_disabled: 'auth.err.signupDisabled',
|
|
email_address_invalid: 'auth.err.emailInvalid',
|
|
validation_failed: 'auth.err.invalid',
|
|
session_not_found: 'auth.err.session',
|
|
refresh_token_not_found: 'auth.err.session',
|
|
refresh_token_already_used: 'auth.err.session',
|
|
}
|
|
const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWORD_MIN }) : undefined)
|
|
|
|
async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> {
|
|
let res: Response
|
|
try {
|
|
// Délai maximal : sans réponse, on fait comme hors-ligne plutôt que d'attendre indéfiniment
|
|
res = await withTimeout((signal) =>
|
|
fetch(`${SUPABASE_URL}/auth/v1${path}`, {
|
|
method: init.method ?? 'POST',
|
|
headers: {
|
|
apikey: SUPABASE_ANON_KEY,
|
|
'Content-Type': 'application/json',
|
|
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
|
|
},
|
|
body: init.body ? JSON.stringify(init.body) : undefined,
|
|
credentials: 'omit',
|
|
referrerPolicy: 'no-referrer',
|
|
signal,
|
|
}),
|
|
)
|
|
} catch {
|
|
throw new Error(t('common.offline'))
|
|
}
|
|
let data: Record<string, unknown> = {}
|
|
try {
|
|
data = (await res.json()) as Record<string, unknown>
|
|
} catch {
|
|
/* réponse vide */
|
|
}
|
|
if (!res.ok) {
|
|
const code = String(data.error_code ?? data.code ?? data.error ?? '')
|
|
const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status })))
|
|
;(err as AuthError & { status: number }).status = res.status
|
|
err.code = code || undefined
|
|
throw err
|
|
}
|
|
return data
|
|
}
|
|
|
|
function toSession(data: Record<string, unknown>): Session | null {
|
|
const user = data.user as { id?: unknown; email?: unknown } | undefined
|
|
const expiresIn = typeof data.expires_in === 'number' ? data.expires_in : 3600
|
|
const s = {
|
|
accessToken: data.access_token,
|
|
refreshToken: data.refresh_token,
|
|
expiresAt: typeof data.expires_at === 'number' ? data.expires_at * 1000 : Date.now() + expiresIn * 1000,
|
|
user: { id: user?.id, email: typeof user?.email === 'string' ? user.email : '' },
|
|
}
|
|
return isSession(s) ? s : null
|
|
}
|
|
|
|
const cleanEmail = (email: string) => email.trim().toLowerCase().slice(0, 320)
|
|
const appUrl = () => `${location.origin}${location.pathname}`
|
|
|
|
export async function signIn(email: string, password: string): Promise<void> {
|
|
const data = await gotrue('/token?grant_type=password', { body: { email: cleanEmail(email), password } })
|
|
const s = toSession(data)
|
|
if (!s) throw new AuthError(t('auth.err.response'))
|
|
setSession(s)
|
|
}
|
|
|
|
/**
|
|
* Inscription. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). Le pseudo choisi est repris par la base à la création du profil (s'il est libre).
|
|
*/
|
|
export async function signUp(email: string, password: string, username?: string): Promise<boolean> {
|
|
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
|
|
if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned'))
|
|
let data: Record<string, unknown>
|
|
try {
|
|
data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, {
|
|
body: { email: cleanEmail(email), password, ...(username ? { data: { username } } : {}) },
|
|
})
|
|
} catch (e) {
|
|
// Adresse déjà inscrite : même réponse qu'une inscription normale (« regarde tes emails »),
|
|
// pour ne jamais révéler qui a un compte
|
|
if (e instanceof AuthError && (e.code === 'user_already_exists' || e.code === 'email_exists')) return true
|
|
throw e
|
|
}
|
|
const s = toSession(data)
|
|
if (s) {
|
|
setSession(s)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
export async function requestPasswordReset(email: string): Promise<void> {
|
|
await gotrue(`/recover?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email) } })
|
|
}
|
|
|
|
export async function updatePassword(password: string): Promise<void> {
|
|
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
|
|
if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned'))
|
|
const token = await getAccessToken()
|
|
if (!token) throw new AuthError(t('auth.err.session'))
|
|
await gotrue('/user', { method: 'PUT', body: { password }, token })
|
|
}
|
|
|
|
/** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */
|
|
export async function signOut(): Promise<void> {
|
|
let s = current
|
|
// Jeton d'accès expiré (ou presque) : on tente d'abord de le renouveler, sinon le serveur refuserait
|
|
// la déconnexion et la session resterait ouverte côté serveur. Effacée sur l'appareil quoi qu'il arrive.
|
|
if (s && navigator.onLine && s.expiresAt - 60_000 <= Date.now()) {
|
|
try {
|
|
const next = await refresh()
|
|
if (next && next.user.id === s.user.id) s = next
|
|
} catch {
|
|
/* au mieux */
|
|
}
|
|
}
|
|
setSession(null)
|
|
if (s && navigator.onLine) {
|
|
try {
|
|
await gotrue('/logout?scope=local', { token: s.accessToken })
|
|
} catch {
|
|
/* jeton déjà expiré : rien à faire */
|
|
}
|
|
}
|
|
}
|
|
|
|
// ───────────────────────────── Connexion avec Google (OAuth + PKCE) ─────────────────────────────
|
|
// Google renvoie vers l'app avec un code à usage unique (?code=…) que seul cet appareil peut échanger,
|
|
// grâce au « vérificateur » gardé ici le temps de l'aller-retour. Aucun jeton ne passe dans l'adresse.
|
|
|
|
const VERIFIER_KEY = 'azuucine:pkce'
|
|
|
|
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
|
|
export async function signInWithGoogle(): Promise<void> {
|
|
const verifier = b64url(crypto.getRandomValues(new Uint8Array(48)))
|
|
const challenge = b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))
|
|
try {
|
|
localStorage.setItem(VERIFIER_KEY, JSON.stringify({ verifier, at: Date.now() }))
|
|
} catch {
|
|
throw new AuthError(t('auth.err.storage'))
|
|
}
|
|
const params = new URLSearchParams({
|
|
provider: 'google',
|
|
redirect_to: appUrl(),
|
|
code_challenge: challenge,
|
|
code_challenge_method: 's256',
|
|
})
|
|
location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`)
|
|
}
|
|
|
|
/** Vérificateur gardé pendant l'aller-retour vers Google (null s'il n'y en a pas). */
|
|
function readVerifier(): { verifier?: unknown; at?: unknown } | null {
|
|
try {
|
|
const raw = localStorage.getItem(VERIFIER_KEY)
|
|
const parsed: unknown = raw ? JSON.parse(raw) : null
|
|
return parsed && typeof parsed === 'object' ? (parsed as { verifier?: unknown; at?: unknown }) : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Retour de Google : adresse avec ?code=… (ou ?error=…), seulement si une connexion Google a été lancée
|
|
* depuis cet appareil (vérificateur présent) — une autre adresse avec ?code= n'est pas un retour de Google.
|
|
*/
|
|
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) && readVerifier() !== null
|
|
|
|
async function consumeOAuthRedirect(): Promise<{ error?: string }> {
|
|
const params = new URLSearchParams(location.search)
|
|
const code = params.get('code') ?? ''
|
|
const oauthError = params.get('error_description') ?? params.get('error')
|
|
history.replaceState(null, '', `${location.pathname}#/`)
|
|
const stored = readVerifier()
|
|
const saved = {
|
|
verifier: typeof stored?.verifier === 'string' ? stored.verifier : undefined,
|
|
at: typeof stored?.at === 'number' ? stored.at : undefined,
|
|
}
|
|
try {
|
|
localStorage.removeItem(VERIFIER_KEY)
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
if (oauthError) return { error: t('auth.err.google') }
|
|
// Vérificateur absent ou trop vieux (> 10 min) : on ne tente rien
|
|
if (!/^[A-Za-z0-9_-]{43,128}$/.test(saved.verifier ?? '') || !saved.at || Date.now() - saved.at > 600_000) {
|
|
return { error: t('auth.err.google') }
|
|
}
|
|
if (!/^[A-Za-z0-9_-]{8,256}$/.test(code)) return { error: t('auth.err.google') }
|
|
try {
|
|
const data = await gotrue('/token?grant_type=pkce', { body: { auth_code: code, code_verifier: saved.verifier } })
|
|
const s = toSession(data)
|
|
if (!s) return { error: t('auth.err.response') }
|
|
setSession(s)
|
|
return {}
|
|
} catch (e) {
|
|
return { error: (e as Error).message }
|
|
}
|
|
}
|
|
|
|
let refreshing: Promise<Session | null> | null = null
|
|
|
|
/**
|
|
* Session plus récente laissée par un autre onglet (même compte, jeton de renouvellement différent,
|
|
* ou nouveau jeton d'accès encore valable) : à reprendre plutôt que de renouveler avec un jeton périmé.
|
|
*/
|
|
function newerStored(s: Session): Session | null {
|
|
const stored = load()
|
|
if (!stored || stored.user.id !== s.user.id) return null
|
|
// Seulement une session plus récente que la nôtre (si notre propre écriture avait échoué, le stockage est en retard)
|
|
if (stored.expiresAt <= s.expiresAt) return null
|
|
if (stored.refreshToken !== s.refreshToken) return stored
|
|
if (stored.accessToken !== s.accessToken && stored.expiresAt - 60_000 > Date.now()) return stored
|
|
return null
|
|
}
|
|
|
|
async function refresh(): Promise<Session | null> {
|
|
if (!current) return null
|
|
refreshing ??= (async () => {
|
|
const s = current
|
|
if (!s) return null
|
|
// Un autre onglet a peut-être déjà renouvelé la session (le jeton de renouvellement ne sert qu'une fois)
|
|
const adopted = newerStored(s)
|
|
if (adopted) {
|
|
setSession(adopted)
|
|
return adopted
|
|
}
|
|
const sent = s.refreshToken
|
|
try {
|
|
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: sent } })
|
|
const next = toSession(data)
|
|
// Déconnexion (ou autre compte) pendant le renouvellement : on ne ressuscite pas l'ancienne session
|
|
if (!next || next.user.id !== s.user.id || current?.user.id !== s.user.id) return null
|
|
// Session plus récente entre-temps (nouvelle connexion, autre onglet) : on ne l'écrase pas
|
|
if (current.refreshToken !== sent) return current
|
|
setSession(next)
|
|
return next
|
|
} catch (e) {
|
|
// Un autre onglet a renouvelé pendant ce temps : notre jeton était simplement périmé
|
|
if (current?.user.id === s.user.id && current.refreshToken !== sent) return current
|
|
const adoptedLate = newerStored(s)
|
|
if (adoptedLate && current?.user.id === s.user.id) {
|
|
setSession(adoptedLate)
|
|
return adoptedLate
|
|
}
|
|
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
|
|
const status = (e as { status?: number }).status
|
|
const stored = load()
|
|
if (
|
|
(status === 400 || status === 401 || status === 403) &&
|
|
current?.user.id === s.user.id &&
|
|
current.refreshToken === sent &&
|
|
(!stored || stored.refreshToken === sent)
|
|
) {
|
|
setSession(null)
|
|
}
|
|
return null
|
|
}
|
|
})().finally(() => {
|
|
refreshing = null
|
|
})
|
|
return refreshing
|
|
}
|
|
|
|
/** Jeton d'accès valide (renouvelé si besoin). null si déconnecté ou hors-ligne avec un jeton expiré. */
|
|
export async function getAccessToken(force = false): Promise<string | null> {
|
|
const s = current
|
|
if (!s) return null
|
|
if (!force && s.expiresAt - 60_000 > Date.now()) return s.accessToken
|
|
const next = await refresh()
|
|
return next?.accessToken ?? null
|
|
}
|
|
|
|
/**
|
|
* Liens reçus par email (confirmation d'inscription, mot de passe oublié) :
|
|
* Supabase renvoie vers l'app avec les jetons après le « # ». On ouvre la session puis on nettoie l'adresse.
|
|
*/
|
|
export async function consumeAuthRedirect(): Promise<{ type?: string; error?: string }> {
|
|
if (hasOAuthRedirect()) return consumeOAuthRedirect()
|
|
const hash = location.hash.startsWith('#') ? location.hash.slice(1) : ''
|
|
if (!/(^|&)(access_token|error)=/.test(hash)) return {}
|
|
const params = new URLSearchParams(hash)
|
|
history.replaceState(null, '', `${location.pathname}${location.search}#/`)
|
|
const error = params.get('error_description') ?? params.get('error')
|
|
if (error) {
|
|
const code = params.get('error_code') ?? ''
|
|
return { error: code === 'otp_expired' ? t('auth.err.linkExpired') : t('auth.err.linkUsed') }
|
|
}
|
|
const accessToken = params.get('access_token') ?? ''
|
|
if (!TOKEN.test(accessToken)) return { error: t('auth.err.linkInvalid') }
|
|
try {
|
|
const user = await gotrue('/user', { method: 'GET', token: accessToken })
|
|
const s = toSession({
|
|
access_token: accessToken,
|
|
refresh_token: params.get('refresh_token'),
|
|
expires_at: Number(params.get('expires_at')) || undefined,
|
|
expires_in: Number(params.get('expires_in')) || 3600,
|
|
user,
|
|
})
|
|
if (!s) return { error: t('auth.err.linkInvalid') }
|
|
// Un lien ne doit jamais remplacer en douce le compte déjà ouvert sur cet appareil
|
|
if (current && current.user.id !== s.user.id) return { error: t('auth.err.linkInvalid') }
|
|
setSession(s)
|
|
return { type: params.get('type') ?? undefined }
|
|
} catch (e) {
|
|
return { error: (e as Error).message }
|
|
}
|
|
}
|
|
|
|
// ───────────────────────────── Double authentification (TOTP) ─────────────────────────────
|
|
|
|
/** Niveau d'assurance de la session : « aal2 » une fois le code de l'application d'authentification saisi. */
|
|
export function sessionAal(): string | undefined {
|
|
const token = current?.accessToken
|
|
if (!token) return undefined
|
|
try {
|
|
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
|
const claims = JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { aal?: unknown }
|
|
return typeof claims.aal === 'string' ? claims.aal : undefined
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|
|
export interface MfaFactor {
|
|
id: string
|
|
verified: boolean
|
|
}
|
|
|
|
const FACTOR_ID = /^[0-9a-f-]{36}$/i
|
|
|
|
async function mfaToken(): Promise<string> {
|
|
const token = await getAccessToken()
|
|
if (!token) throw new AuthError(t('auth.err.session'))
|
|
return token
|
|
}
|
|
|
|
/** Facteurs TOTP du compte (vérifiés ou en cours d'activation). */
|
|
export async function listTotpFactors(): Promise<MfaFactor[]> {
|
|
const user = await gotrue('/user', { method: 'GET', token: await mfaToken() })
|
|
const factors = Array.isArray(user.factors) ? (user.factors as { id?: unknown; status?: unknown; factor_type?: unknown }[]) : []
|
|
return factors
|
|
.filter((f) => typeof f.id === 'string' && FACTOR_ID.test(f.id) && f.factor_type === 'totp')
|
|
.map((f) => ({ id: f.id as string, verified: f.status === 'verified' }))
|
|
}
|
|
|
|
const mfaKey = (userId: string) => `azuucine:mfa:${userId}`
|
|
/** Dernier état connu (pour ne pas bloquer le lancement quand le compte n'a pas de double authentification). */
|
|
export function knownMfa(): boolean | undefined {
|
|
if (!current) return undefined
|
|
try {
|
|
const v = localStorage.getItem(mfaKey(current.user.id))
|
|
return v === '1' ? true : v === '0' ? false : undefined
|
|
} catch {
|
|
return undefined
|
|
}
|
|
}
|
|
function rememberMfa(on: boolean) {
|
|
if (!current) return
|
|
try {
|
|
localStorage.setItem(mfaKey(current.user.id), on ? '1' : '0')
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
/** Facteur à valider avant d'entrer dans l'app (null : rien à faire). */
|
|
export async function pendingMfaFactor(): Promise<string | null> {
|
|
const factors = await listTotpFactors()
|
|
const verified = factors.find((f) => f.verified)
|
|
rememberMfa(!!verified)
|
|
if (!verified || sessionAal() === 'aal2') return null
|
|
return verified.id
|
|
}
|
|
|
|
/** Valide un code à 6 chiffres : la session passe au niveau « aal2 ». */
|
|
export async function verifyTotp(factorId: string, code: string): Promise<void> {
|
|
if (!FACTOR_ID.test(factorId)) throw new AuthError(t('auth.err.invalid'))
|
|
const clean = code.replace(/\s/g, '')
|
|
if (!/^\d{6}$/.test(clean)) throw new AuthError(t('mfa.err.code'))
|
|
const token = await mfaToken()
|
|
const challenge = await gotrue(`/factors/${factorId}/challenge`, { token })
|
|
if (typeof challenge.id !== 'string') throw new AuthError(t('auth.err.response'))
|
|
let data: Record<string, unknown>
|
|
try {
|
|
data = await gotrue(`/factors/${factorId}/verify`, { token, body: { challenge_id: challenge.id, code: clean } })
|
|
} catch (e) {
|
|
if (e instanceof AuthError && (e.code === 'mfa_verification_failed' || e.code === 'invalid_credentials')) throw new AuthError(t('mfa.err.code'))
|
|
throw e
|
|
}
|
|
const s = toSession({ ...data, user: data.user ?? { id: current?.user.id, email: current?.user.email } })
|
|
if (!s || (current && s.user.id !== current.user.id)) throw new AuthError(t('auth.err.response'))
|
|
setSession(s)
|
|
rememberMfa(true)
|
|
}
|
|
|
|
/** Début d'activation : QR code et clé à recopier dans l'application d'authentification. */
|
|
export async function enrollTotp(): Promise<{ id: string; qr: string; secret: string }> {
|
|
const token = await mfaToken()
|
|
// Une activation abandonnée laisse un facteur non vérifié : on repart de zéro
|
|
for (const f of await listTotpFactors()) if (!f.verified) await gotrue(`/factors/${f.id}`, { method: 'DELETE', token }).catch(() => {})
|
|
const data = await gotrue('/factors', { token, body: { factor_type: 'totp', friendly_name: `Bobinoo ${Date.now().toString(36)}` } })
|
|
const totp = data.totp as { qr_code?: unknown; secret?: unknown } | undefined
|
|
const qr = typeof totp?.qr_code === 'string' && totp.qr_code.startsWith('data:image/svg+xml') ? totp.qr_code : ''
|
|
if (typeof data.id !== 'string' || !FACTOR_ID.test(data.id) || typeof totp?.secret !== 'string') throw new AuthError(t('auth.err.response'))
|
|
return { id: data.id, qr, secret: totp.secret }
|
|
}
|
|
|
|
/** Désactive la double authentification (demande une session « aal2 »). */
|
|
export async function removeTotp(factorId: string): Promise<void> {
|
|
if (!FACTOR_ID.test(factorId)) throw new AuthError(t('auth.err.invalid'))
|
|
await gotrue(`/factors/${factorId}`, { method: 'DELETE', token: await mfaToken() })
|
|
// La session « aal2 » reste valable ; on rafraîchit pour repartir d'un jeton à jour
|
|
await getAccessToken(true).catch(() => null)
|
|
rememberMfa(false)
|
|
}
|