Sécurité : double authentification, comptes non révélés, double tap, dépendances figées
deploy / deploy (push) Successful in 36s
deploy / deploy (push) Successful in 36s
D'après les 16 vérifications de sécurité (vidéo) : - Double authentification (application d'authentification, TOTP), optionnelle dans Réglages → Mon compte ; code demandé à la connexion ; imposée côté serveur (migration 20261128160000, appliquée) : règles RLS restrictives, administration, actions sociales et fonctions Edge (delete-account redéployée) - Inscription avec une adresse déjà utilisée : même réponse qu'une inscription normale (aucune fuite) - « +1 » : un double tap involontaire ne compte qu'un épisode - Dépendances : correctifs de sécurité appliqués, versions exactes figées (.npmrc save-exact) - Déploiement : jeton du job limité à la lecture du dépôt - Logo « Kino » restant sur l'écran de connexion et l'invitation à créer un compte corrigé - Vérifiés sans changement : délais sur tous les appels réseau, aucun secret dans le navigateur, pas de redirection libre, en-têtes HTTPS / CSP stricts, boutons sensibles déjà protégés Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
32 files changed
+666
-69
No files matched your search
+124
-6
@@ -16,7 +16,10 @@ export interface Session {
|
||||
user: { id: string; email: string }
|
||||
}
|
||||
|
||||
export class AuthError extends Error {}
|
||||
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
|
||||
@@ -90,8 +93,6 @@ const CODE_KEYS: Record<string, TKey> = {
|
||||
invalid_credentials: 'auth.err.credentials',
|
||||
invalid_grant: 'auth.err.credentials',
|
||||
email_not_confirmed: 'auth.err.notConfirmed',
|
||||
user_already_exists: 'auth.err.exists',
|
||||
email_exists: 'auth.err.exists',
|
||||
weak_password: 'auth.err.weak',
|
||||
same_password: 'auth.err.samePassword',
|
||||
over_email_send_rate_limit: 'auth.err.emailRate',
|
||||
@@ -136,6 +137,7 @@ async function gotrue(path: string, init: { method?: string; body?: unknown; tok
|
||||
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
|
||||
@@ -169,9 +171,17 @@ export async function signIn(email: string, password: string): Promise<void> {
|
||||
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'))
|
||||
const data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, {
|
||||
body: { email: cleanEmail(email), password, ...(username ? { data: { username } } : {}) },
|
||||
})
|
||||
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)
|
||||
@@ -397,3 +407,111 @@ export async function consumeAuthRedirect(): Promise<{ type?: string; error?: st
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user