feat(app): profile photo — avatar upload in Mon compte, photo in the sidebar, drawer and top bar

packages/supabase assets module: closed AssetFailure kinds, begin / quarantine
upload (upsert off) / confirm / remove, own-row state read with an explicit
column list, download under the SELECT policy. App: client transport (magic
byte sniff, never SVG, createImageBitmap, canvas 1024 px, JPEG 0.9, 5 MiB
cap), AvatarSection (preview, save, 1 s polling up to 30 s, rejection and
failure messages per closed code, removal with confirmation, in-flight row
resumed at mount), auth store blob URL revoked on change and sign-out,
AvatarCircle in UserBadge and the top bar link to Mon compte (D3), FR/EN
strings, fake client extended, 27 new tests (app 300).
This commit is contained in:
bchanot committed 2026-10-13 19:32:37 +02:00
1 parent 614887470c
commit 926dd7df8c
18 files changed
+1543 -24

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
import { AssetFailure } from '@faunosteo/supabase'
/**
* Browser-side preparation of a profile photo (docs/development/STORAGE.md
* §4): sniff the real type, decode, downscale to a transport size, re-encode
* as JPEG. Transport only: the worker re-decodes and judges the bytes again.
*/
export type SniffedImageType = 'image/jpeg' | 'image/png' | 'image/webp'
/** Largest file accepted at the picker (sanity bound before decoding). */
export const MAX_PICKED_BYTES = 20 * 1024 * 1024
/** Largest blob actually transferred (the bucket cap and the RPC CHECK). */
export const MAX_TRANSPORT_BYTES = 5 * 1024 * 1024
/** Longest side after the canvas downscale. */
export const TRANSPORT_MAX_SIDE = 1024
const JPEG_QUALITY = 0.9
function startsWith(bytes: Uint8Array, prefix: number[], at = 0): boolean {
if (bytes.length < at + prefix.length) return false
return prefix.every((b, i) => bytes[at + i] === b)
}
/** Magic bytes only: SVG, GIF, BMP or any text are null. */
export function sniffImageType(bytes: Uint8Array): SniffedImageType | null {
if (startsWith(bytes, [0xff, 0xd8, 0xff])) return 'image/jpeg'
if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
return 'image/png'
}
if (
startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) &&
startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)
) {
return 'image/webp'
}
return null
}
/** Canvas size for a bitmap: longest side capped, never upscaled. */
export function transportSize(
width: number,
height: number,
maxSide = TRANSPORT_MAX_SIDE,
): { width: number; height: number } {
const longest = Math.max(width, height)
if (longest <= maxSide) return { width, height }
const scale = maxSide / longest
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
}
}
export interface BitmapLike {
width: number
height: number
close?: () => void
}
export interface CanvasLike {
width: number
height: number
getContext: (kind: '2d') => { drawImage: (image: unknown, x: number, y: number, w: number, h: number) => void } | null
toBlob: (cb: (blob: Blob | null) => void, type: string, quality: number) => void
}
/** The browser APIs involved, injectable for tests under happy-dom. */
export interface TransportDeps {
createImageBitmap: (file: Blob) => Promise<BitmapLike>
createCanvas: () => CanvasLike
createObjectURL: (blob: Blob) => string
}
function defaultDeps(): TransportDeps {
return {
createImageBitmap: (file) => createImageBitmap(file),
createCanvas: () => document.createElement('canvas') as unknown as CanvasLike,
createObjectURL: (blob) => URL.createObjectURL(blob),
}
}
export interface PreparedAvatar {
blob: Blob
previewUrl: string
}
async function readHead(file: Blob): Promise<Uint8Array> {
return new Uint8Array(await file.slice(0, 16).arrayBuffer())
}
function encodeJpeg(canvas: CanvasLike): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => (blob ? resolve(blob) : reject(new AssetFailure('unsupported_type'))),
'image/jpeg',
JPEG_QUALITY,
)
})
}
/**
* Sniff → decode → downscale → JPEG. Throws AssetFailure('too_large' |
* 'unsupported_type'); never uploads anything.
*/
export async function prepareAvatarUpload(
file: File,
deps: TransportDeps = defaultDeps(),
): Promise<PreparedAvatar> {
if (file.size > MAX_PICKED_BYTES) throw new AssetFailure('too_large')
if (sniffImageType(await readHead(file)) === null) {
throw new AssetFailure('unsupported_type')
}
let bitmap: BitmapLike
try {
bitmap = await deps.createImageBitmap(file)
} catch (cause) {
throw new AssetFailure('unsupported_type', cause)
}
try {
const size = transportSize(bitmap.width, bitmap.height)
const canvas = deps.createCanvas()
canvas.width = size.width
canvas.height = size.height
const context = canvas.getContext('2d')
if (!context) throw new AssetFailure('unsupported_type')
context.drawImage(bitmap, 0, 0, size.width, size.height)
const blob = await encodeJpeg(canvas)
if (blob.size > MAX_TRANSPORT_BYTES) throw new AssetFailure('too_large')
return { blob, previewUrl: deps.createObjectURL(blob) }
} finally {
bitmap.close?.()
}
}
@@ -0,0 +1,280 @@
import { useEffect, useRef, useState, type ChangeEvent } from 'react'
import {
beginAvatarUpload,
classifyAssetError,
confirmAssetUpload,
isAvatarRejectionCode,
removeAvatar,
uploadToQuarantine,
type AssetFailureKind,
type AvatarRejectionCode,
type AvatarState,
} from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { monogram } from '@/components/shell/UserBadge'
import { prepareAvatarUpload, type PreparedAvatar } from '@/account/avatarTransport'
import { getSupabaseClient } from '@/lib/supabase'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/** Polling of the own row after a save (docs/development/STORAGE.md §4 step 4). */
export const POLL_INTERVAL_MS = 1000
export const POLL_MAX_MS = 30_000
const ACCEPT = 'image/jpeg,image/png,image/webp'
type Phase =
| { kind: 'idle' }
| { kind: 'picked'; prepared: PreparedAvatar }
| { kind: 'saving' }
| { kind: 'processing'; long: boolean }
| { kind: 'saved' }
| { kind: 'removed' }
| { kind: 'rejected'; code: AvatarRejectionCode }
| { kind: 'failed'; failure: AssetFailureKind }
function revoke(url: string | undefined) {
if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url)
}
/** Photo, preview or monogram in the circle; the busy state replaces it with a label. */
function Circle({
src,
label,
busy,
busyLabel,
}: {
src: string | null
label: string
busy: boolean
busyLabel: string
}) {
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const base =
'grid h-24 w-24 shrink-0 place-items-center overflow-hidden rounded-full bg-[var(--color-accent)] text-2xl font-semibold text-white'
if (busy) {
return (
<div className={`${base} bg-[var(--color-surface-strong)] text-xs font-medium text-[var(--color-ink-muted)]`} role="status">
<span className="px-2 text-center leading-tight">{busyLabel}</span>
</div>
)
}
if (src) {
return (
<div className={base}>
<img src={src} alt={label} className="h-full w-full object-cover" />
</div>
)
}
return (
<div className={base} aria-hidden="true">
{monogram(profile?.display_name, user?.email)}
</div>
)
}
/**
* Profile photo block of "Mon compte": pick → local preview → save (begin,
* quarantine upload, confirm) → poll until the worker's verdict → photo.
* Removal asks once. Every message is a closed i18n key.
*/
export default function AvatarSection() {
const t = useT()
const avatarUrl = useAuthStore((s) => s.avatarUrl)
const avatar = useAuthStore((s) => s.avatar)
const refreshAvatar = useAuthStore((s) => s.refreshAvatar)
const clearAvatar = useAuthStore((s) => s.clearAvatar)
const [phase, setPhase] = useState<Phase>(() =>
avatar?.inFlight ? { kind: 'processing', long: false } : { kind: 'idle' },
)
const [confirmOpen, setConfirmOpen] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const pollRef = useRef<number | null>(null)
const stopPolling = () => {
if (pollRef.current !== null) {
window.clearInterval(pollRef.current)
pollRef.current = null
}
}
/** One tick per second until the row leaves `uploaded`, 30 s at most. */
const startPolling = () => {
stopPolling()
const startedAt = Date.now()
pollRef.current = window.setInterval(() => {
void refreshAvatar()
.then((state: AvatarState) => {
if (state.inFlight === null) {
stopPolling()
setPhase(settledPhase(state))
} else if (Date.now() - startedAt >= POLL_MAX_MS) {
stopPolling()
setPhase({ kind: 'processing', long: true })
}
})
.catch((error: unknown) => {
stopPolling()
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
})
}, POLL_INTERVAL_MS)
}
// A row already in flight at mount resumes the bounded polling (refs: no stale closure, no deps).
const startPollingRef = useRef(startPolling)
startPollingRef.current = startPolling
const resumeOnMount = useRef(phase.kind === 'processing')
useEffect(() => {
if (resumeOnMount.current) startPollingRef.current()
return () => {
if (pollRef.current !== null) window.clearInterval(pollRef.current)
}
}, [])
useEffect(() => {
return () => {
if (phase.kind === 'picked') revoke(phase.prepared.previewUrl)
}
}, [phase])
async function onPick(e: ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
try {
const prepared = await prepareAvatarUpload(file)
setPhase({ kind: 'picked', prepared })
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
async function onSave() {
if (phase.kind !== 'picked') return
const client = getSupabaseClient()
if (!client) return
const { blob } = phase.prepared
setPhase({ kind: 'saving' })
try {
const ticket = await beginAvatarUpload(client, {
declaredMime: 'image/jpeg',
declaredSize: blob.size,
})
await uploadToQuarantine(client, { ...ticket, blob })
await confirmAssetUpload(client, ticket.assetId)
setPhase({ kind: 'processing', long: false })
startPolling()
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
async function onRemove() {
const client = getSupabaseClient()
setConfirmOpen(false)
if (!client) return
try {
await removeAvatar(client)
clearAvatar()
setPhase({ kind: 'removed' })
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
}
}
const busy = phase.kind === 'saving' || phase.kind === 'processing'
const picked = phase.kind === 'picked'
const shown = picked ? phase.prepared.previewUrl : avatarUrl
const rejected =
phase.kind === 'rejected'
? phase.code
: phase.kind === 'idle' && avatar?.lastRejected && isAvatarRejectionCode(avatar.lastRejected.rejection_reason)
? avatar.lastRejected.rejection_reason
: null
return (
<div className="space-y-3" data-testid="avatar-section">
<h3 className="text-sm font-medium text-[var(--color-ink)]">{t('account.avatar.title')}</h3>
<div className="flex flex-wrap items-center gap-4">
<Circle
src={shown}
label={t('account.avatar.alt')}
busy={busy}
busyLabel={phase.kind === 'saving' ? t('account.avatar.saving') : t('account.avatar.processing')}
/>
<div className="flex flex-wrap items-center gap-2">
<input
ref={inputRef}
type="file"
accept={ACCEPT}
onChange={onPick}
className="sr-only"
aria-label={t('account.avatar.change')}
disabled={busy}
/>
{picked ? (
<>
<Button type="button" onClick={onSave}>
{t('account.avatar.save')}
</Button>
<Button type="button" variant="ghost" onClick={() => setPhase({ kind: 'idle' })}>
{t('account.avatar.cancel')}
</Button>
</>
) : (
<>
<Button
type="button"
variant="secondary"
disabled={busy}
onClick={() => inputRef.current?.click()}
>
{t('account.avatar.change')}
</Button>
{avatarUrl && !busy && (
<Button type="button" variant="danger" onClick={() => setConfirmOpen(true)}>
{t('account.avatar.remove')}
</Button>
)}
</>
)}
</div>
</div>
<p className="text-xs text-[var(--color-ink-muted)]">
{phase.kind === 'processing' && !phase.long
? t('account.avatar.processing_hint')
: t('account.avatar.hint')}
</p>
{phase.kind === 'processing' && phase.long && (
<Notice tone="info">{t('account.avatar.processing_long')}</Notice>
)}
{phase.kind === 'saved' && <Notice tone="success">{t('account.avatar.saved')}</Notice>}
{phase.kind === 'removed' && <Notice tone="success">{t('account.avatar.removed')}</Notice>}
{phase.kind === 'failed' && (
<Notice tone="error">{t(`account.avatar.error.${phase.failure}`)}</Notice>
)}
{rejected && <Notice tone="error">{t(`account.avatar.rejected.${rejected}`)}</Notice>}
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm">
<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>
<div className="mt-4 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => setConfirmOpen(false)}>
{t('common.cancel')}
</Button>
<Button type="button" variant="danger" onClick={onRemove}>
{t('account.avatar.remove_confirm')}
</Button>
</div>
</Dialog>
</div>
)
}
/** The verdict once no row is in flight: the clean photo, a rejection, or nothing new. */
function settledPhase(state: AvatarState): Phase {
if (state.lastRejected && isAvatarRejectionCode(state.lastRejected.rejection_reason)) {
return { kind: 'rejected', code: state.lastRejected.rejection_reason }
}
return state.clean ? { kind: 'saved' } : { kind: 'idle' }
}
@@ -1,6 +1,7 @@
import type { Profile } from '@faunosteo/supabase' import type { Profile } from '@faunosteo/supabase'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField' import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input' import Input from '@/components/ui/Input'
import AvatarSection from './AvatarSection'
import SaveRow from './SaveRow' import SaveRow from './SaveRow'
import SectionCard from './SectionCard' import SectionCard from './SectionCard'
import { personalPatch, personalSchema, translateFieldError, type PersonalValues } from '@/account/validation' import { personalPatch, personalSchema, translateFieldError, type PersonalValues } from '@/account/validation'
@@ -27,7 +28,8 @@ export default function PersonalInfoForm({ profile }: { profile: Profile }) {
title={t('account.personal.title')} title={t('account.personal.title')}
description={t('account.personal.description')} description={t('account.personal.description')}
> >
<form onSubmit={form.submit} noValidate className="space-y-4"> <AvatarSection />
<form onSubmit={form.submit} noValidate className="mt-6 space-y-4 border-t border-[var(--color-border)] pt-6">
<FormField id="display_name" label={t('account.personal.display_name')} error={err('display_name')}> <FormField id="display_name" label={t('account.personal.display_name')} error={err('display_name')}>
<Input <Input
id="display_name" id="display_name"
+15 -2
View File
@@ -6,7 +6,8 @@ import Icon from '@/components/ui/Icon'
import MobileDrawer from './MobileDrawer' import MobileDrawer from './MobileDrawer'
import SidebarNav, { NAV_ITEMS } from './SidebarNav' import SidebarNav, { NAV_ITEMS } from './SidebarNav'
import SignOutButton from './SignOutButton' import SignOutButton from './SignOutButton'
import UserBadge from './UserBadge' import UserBadge, { AvatarCircle } from './UserBadge'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
/** Title of the current /app page for the top bar, from the nav table. */ /** Title of the current /app page for the top bar, from the nav table. */
@@ -25,6 +26,9 @@ export default function AppLayout() {
const t = useT() const t = useT()
const location = useLocation() const location = useLocation()
const [drawerOpen, setDrawerOpen] = useState(false) const [drawerOpen, setDrawerOpen] = useState(false)
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const displayName = profile?.display_name ?? user?.email ?? ''
return ( return (
<div className="flex min-h-dvh bg-[var(--color-bg)]"> <div className="flex min-h-dvh bg-[var(--color-bg)]">
@@ -60,8 +64,17 @@ export default function AppLayout() {
<h1 className="hidden lg:block text-sm font-medium text-[var(--color-ink-muted)]"> <h1 className="hidden lg:block text-sm font-medium text-[var(--color-ink-muted)]">
{t(pageTitleKey(location.pathname))} {t(pageTitleKey(location.pathname))}
</h1> </h1>
<div className="ml-auto flex items-center gap-2"> <div className="ml-auto flex items-center gap-2 sm:gap-3">
<LanguageSwitcher /> <LanguageSwitcher />
<Link
to="/app/account"
aria-label={t('shell.nav.account')}
data-testid="topbar-account"
className="flex min-h-11 items-center gap-2 rounded-full pr-1 pl-1 text-sm text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] sm:pr-3"
>
<AvatarCircle size="sm" />
<span className="hidden max-w-[12rem] truncate sm:inline">{displayName}</span>
</Link>
</div> </div>
</header> </header>
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8"> <main className="flex-1 px-4 py-6 sm:px-8 sm:py-8">
+27 -7
View File
@@ -1,4 +1,5 @@
import { useAuthStore } from '@/state/authStore' import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/** Two-letter monogram from the display name, else the email. */ /** Two-letter monogram from the display name, else the email. */
export function monogram(name: string | undefined, email: string | undefined) { export function monogram(name: string | undefined, email: string | undefined) {
@@ -10,19 +11,38 @@ export function monogram(name: string | undefined, email: string | undefined) {
return letters.toUpperCase() return letters.toUpperCase()
} }
/** Avatar monogram + display name + email, as shown at the bottom of the sidebar. */ const CIRCLE =
'grid shrink-0 place-items-center overflow-hidden rounded-full bg-[var(--color-accent)] font-semibold text-white'
/** The photo when the store holds one, the monogram otherwise; decorative. */
export function AvatarCircle({ size = 'md' }: { size?: 'sm' | 'md' }) {
const t = useT()
const avatarUrl = useAuthStore((s) => s.avatarUrl)
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const dims = size === 'sm' ? 'h-8 w-8 text-xs' : 'h-9 w-9 text-sm'
if (avatarUrl) {
return (
<span className={`${CIRCLE} ${dims}`}>
<img src={avatarUrl} alt={t('account.avatar.alt')} className="h-full w-full object-cover" />
</span>
)
}
return (
<span aria-hidden="true" className={`${CIRCLE} ${dims}`}>
{monogram(profile?.display_name, user?.email)}
</span>
)
}
/** Avatar + display name + email, as shown at the bottom of the sidebar. */
export default function UserBadge() { export default function UserBadge() {
const profile = useAuthStore((s) => s.profile) const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user) const user = useAuthStore((s) => s.user)
const name = profile?.display_name ?? user?.email ?? '' const name = profile?.display_name ?? user?.email ?? ''
return ( return (
<div className="flex items-center gap-3 min-w-0"> <div className="flex items-center gap-3 min-w-0">
<span <AvatarCircle />
aria-hidden="true"
className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[var(--color-accent)] text-sm font-semibold text-white"
>
{monogram(profile?.display_name, user?.email)}
</span>
<span className="flex min-w-0 flex-col leading-tight"> <span className="flex min-w-0 flex-col leading-tight">
<span className="truncate text-sm font-medium text-[var(--color-ink)]"> <span className="truncate text-sm font-medium text-[var(--color-ink)]">
{name} {name}
+42
View File
@@ -372,4 +372,46 @@ export const en: Dict = {
'Not available in this version yet. It will be offered, then required for platform roles.', 'Not available in this version yet. It will be offered, then required for platform roles.',
'account.security.sign_out_everywhere_note': 'account.security.sign_out_everywhere_note':
'Signing out closes the session on this device.', 'Signing out closes the session on this device.',
'account.avatar.title': 'Profile photo',
'account.avatar.alt': 'Profile photo',
'account.avatar.change': 'Change photo',
'account.avatar.save': 'Save photo',
'account.avatar.saving': 'Uploading…',
'account.avatar.cancel': 'Cancel',
'account.avatar.remove': 'Remove photo',
'account.avatar.remove_title': 'Remove the photo?',
'account.avatar.remove_body':
'Your profile photo will be removed. You can add another one at any time.',
'account.avatar.remove_confirm': 'Remove',
'account.avatar.removed': 'Photo removed.',
'account.avatar.processing': 'Processing…',
'account.avatar.processing_hint':
'Your photo is being checked and resized. This takes a few seconds.',
'account.avatar.processing_long':
'Processing is taking longer than expected. Come back in a moment.',
'account.avatar.saved': 'Photo saved.',
'account.avatar.hint': 'JPEG, PNG or WebP, 5 MB at most once reduced.',
'account.avatar.error.too_large': 'Image too large (5 MB at most).',
'account.avatar.error.unsupported_type':
'Unsupported format: choose a JPEG, PNG or WebP image.',
'account.avatar.error.rate_limited':
'Too many attempts. Try again in an hour.',
'account.avatar.error.storage_full':
'Storage is full. Try again later.',
'account.avatar.error.upload_missing':
'The upload did not complete. Try again.',
'account.avatar.error.invalid_state':
'This action no longer matches your current photo. Reload the page.',
'account.avatar.error.not_found': 'Photo not found. Reload the page.',
'account.avatar.error.network':
'Cannot reach the server. Check your connection and try again.',
'account.avatar.error.unknown': 'Something went wrong. Try again.',
'account.avatar.rejected.unsupported_type':
'Photo refused: the file is not a JPEG, PNG or WebP image.',
'account.avatar.rejected.decode_failed':
'Photo refused: the file is corrupt or unreadable.',
'account.avatar.rejected.dimensions':
'Photo refused: between 64 and 4096 pixels per side.',
'account.avatar.rejected.processing_error':
'Photo refused: processing failed. Try another image.',
} }
+42
View File
@@ -390,4 +390,46 @@ export const fr: Dict = {
'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.', 'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.',
'account.security.sign_out_everywhere_note': 'account.security.sign_out_everywhere_note':
'Se déconnecter ferme la session sur cet appareil.', 'Se déconnecter ferme la session sur cet appareil.',
'account.avatar.title': 'Photo de profil',
'account.avatar.alt': 'Photo de profil',
'account.avatar.change': 'Modifier la photo',
'account.avatar.save': 'Enregistrer la photo',
'account.avatar.saving': 'Envoi…',
'account.avatar.cancel': 'Annuler',
'account.avatar.remove': 'Supprimer la photo',
'account.avatar.remove_title': 'Supprimer la photo ?',
'account.avatar.remove_body':
'Votre photo de profil sera retirée. Vous pourrez en ajouter une autre à tout moment.',
'account.avatar.remove_confirm': 'Supprimer',
'account.avatar.removed': 'Photo supprimée.',
'account.avatar.processing': 'Traitement en cours…',
'account.avatar.processing_hint':
'Votre photo est vérifiée puis redimensionnée. Cela prend quelques secondes.',
'account.avatar.processing_long':
'Le traitement prend plus de temps que prévu. Revenez dans un instant.',
'account.avatar.saved': 'Photo enregistrée.',
'account.avatar.hint': 'JPEG, PNG ou WebP, 5 Mo maximum une fois réduite.',
'account.avatar.error.too_large': 'Image trop volumineuse (5 Mo maximum).',
'account.avatar.error.unsupported_type':
'Format non pris en charge : choisissez une image JPEG, PNG ou WebP.',
'account.avatar.error.rate_limited':
'Trop de tentatives. Réessayez dans une heure.',
'account.avatar.error.storage_full':
'Espace de stockage saturé. Réessayez plus tard.',
'account.avatar.error.upload_missing':
"L'envoi ne s'est pas terminé. Réessayez.",
'account.avatar.error.invalid_state':
'Cette opération ne correspond plus à votre photo actuelle. Rechargez la page.',
'account.avatar.error.not_found': 'Photo introuvable. Rechargez la page.',
'account.avatar.error.network':
"Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.",
'account.avatar.error.unknown': 'Une erreur est survenue. Réessayez.',
'account.avatar.rejected.unsupported_type':
'Photo refusée : le fichier n’est pas une image JPEG, PNG ou WebP.',
'account.avatar.rejected.decode_failed':
'Photo refusée : le fichier est corrompu ou illisible.',
'account.avatar.rejected.dimensions':
'Photo refusée : entre 64 et 4096 pixels de côté.',
'account.avatar.rejected.processing_error':
'Photo refusée : le traitement a échoué. Réessayez avec une autre image.',
} }
+70 -6
View File
@@ -10,6 +10,9 @@ import {
signOut as signOutRequest, signOut as signOutRequest,
updateOwnProfile, updateOwnProfile,
type AuthFailureKind, type AuthFailureKind,
type AvatarState,
downloadAvatar,
fetchOwnAvatarState,
type FaunosteoClient, type FaunosteoClient,
type OwnProfilePatch, type OwnProfilePatch,
type PlatformRole, type PlatformRole,
@@ -34,22 +37,59 @@ export interface AuthState {
recovery: boolean recovery: boolean
/** Failure while reading the URL (expired link, bad code): shown by the landing routes. */ /** Failure while reading the URL (expired link, bad code): shown by the landing routes. */
urlFailure: AuthFailureKind | null urlFailure: AuthFailureKind | null
/** Own avatar rows reduced to clean / in flight / last rejected; null until loaded. */
avatar: AvatarState | null
/** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */
avatarUrl: string | null
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */ /** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void start: () => () => void
refreshAccount: () => Promise<void> refreshAccount: () => Promise<void>
updateProfile: (patch: OwnProfilePatch) => Promise<Profile> updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
/** Re-reads the own rows; downloads the clean photo when it changed. */
refreshAvatar: () => Promise<AvatarState>
/** Forgets the photo locally (after remove_avatar or on sign-out). */
clearAvatar: () => void
signOut: () => Promise<void> signOut: () => Promise<void>
clearRecovery: () => void clearRecovery: () => void
} }
type Set = (patch: Partial<AuthState>) => void type Set = (patch: Partial<AuthState>) => void
type Get = () => AuthState
async function loadAccount(client: FaunosteoClient, user: User, set: Set) { /** Blob URLs are a browser feature; tests under happy-dom may lack them. */
function revokeUrl(url: string | null) {
if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url)
}
/**
* Reads the avatar state and keeps `avatarUrl` in step with the clean row:
* a new clean id downloads once, no clean row drops the URL.
*/
async function syncAvatar(client: FaunosteoClient, user: User, set: Set, get: Get) {
const avatar = await fetchOwnAvatarState(client, user.id)
const previous = get().avatar?.clean?.id ?? null
const current = avatar.clean?.id ?? null
if (current === previous && (current === null || get().avatarUrl)) {
set({ avatar })
return avatar
}
let avatarUrl: string | null = null
if (avatar.clean && typeof URL.createObjectURL === 'function') {
const blob = await downloadAvatar(client, avatar.clean.object_key)
avatarUrl = URL.createObjectURL(blob)
}
revokeUrl(get().avatarUrl)
set({ avatar, avatarUrl })
return avatar
}
async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: Get) {
const [profile, roles] = await Promise.all([ const [profile, roles] = await Promise.all([
fetchOwnProfile(client, user.id), fetchOwnProfile(client, user.id),
fetchOwnPlatformRoles(client, user.id), fetchOwnPlatformRoles(client, user.id),
]) ])
set({ profile, roles }) set({ profile, roles })
await syncAvatar(client, user, set, get).catch(() => set({ avatar: null }))
} }
/** /**
@@ -61,9 +101,11 @@ function applyAuthEvent(
event: AuthChangeEvent, event: AuthChangeEvent,
session: Session | null, session: Session | null,
set: Set, set: Set,
previousUserId: string | undefined, get: Get,
) { ) {
const previousUserId = get().user?.id
if (event === 'SIGNED_OUT' || session === null) { if (event === 'SIGNED_OUT' || session === null) {
revokeUrl(get().avatarUrl)
set({ set({
status: 'signed_out', status: 'signed_out',
session: null, session: null,
@@ -71,6 +113,8 @@ function applyAuthEvent(
profile: null, profile: null,
roles: [], roles: [],
recovery: false, recovery: false,
avatar: null,
avatarUrl: null,
}) })
return return
} }
@@ -83,7 +127,7 @@ function applyAuthEvent(
set(patch) set(patch)
if (session.user.id !== previousUserId || event === 'USER_UPDATED') { if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
setTimeout(() => { setTimeout(() => {
void loadAccount(client, session.user, set).catch(() => { void loadAccount(client, session.user, set, get).catch(() => {
set({ profile: null, roles: [] }) set({ profile: null, roles: [] })
}) })
}, 0) }, 0)
@@ -109,6 +153,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
roles: [], roles: [],
recovery: false, recovery: false,
urlFailure: null, urlFailure: null,
avatar: null,
avatarUrl: null,
start: () => { start: () => {
const client = getSupabaseClient() const client = getSupabaseClient()
@@ -120,13 +166,26 @@ export const useAuthStore = create<AuthState>((set, get) => ({
if (error) set({ urlFailure: classifyAuthError(error) }) if (error) set({ urlFailure: classifyAuthError(error) })
}) })
const { data } = client.auth.onAuthStateChange((event, session) => { const { data } = client.auth.onAuthStateChange((event, session) => {
applyAuthEvent(client, event, session, set, get().user?.id) applyAuthEvent(client, event, session, set, get)
}) })
return () => data.subscription.unsubscribe() return () => data.subscription.unsubscribe()
}, },
refreshAccount: async () => { refreshAccount: async () => {
await loadAccount(requireClient(), requireUser(get().user), set) await loadAccount(requireClient(), requireUser(get().user), set, get)
},
refreshAvatar: async () => {
return syncAvatar(requireClient(), requireUser(get().user), set, get)
},
clearAvatar: () => {
revokeUrl(get().avatarUrl)
const avatar = get().avatar
set({
avatarUrl: null,
avatar: avatar ? { ...avatar, clean: null, inFlight: null } : null,
})
}, },
updateProfile: async (patch) => { updateProfile: async (patch) => {
@@ -137,14 +196,19 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}, },
signOut: async () => { signOut: async () => {
const clear = () => set({ const clear = () => {
revokeUrl(get().avatarUrl)
set({
status: 'signed_out', status: 'signed_out',
session: null, session: null,
user: null, user: null,
profile: null, profile: null,
roles: [], roles: [],
recovery: false, recovery: false,
avatar: null,
avatarUrl: null,
}) })
}
try { try {
// auth-js clears the local session even when the server call fails. // auth-js clears the local session even when the server call fails.
await signOutRequest(requireClient()) await signOutRequest(requireClient())
+74 -5
View File
@@ -1,10 +1,12 @@
/** /**
* In-memory stand-in for the parts of the Supabase client the identity step * In-memory stand-in for the parts of the Supabase client the identity and
* uses: auth events, profile select/update, profile_roles select. Tests mock * files steps use: auth events, profile select/update, profile_roles and
* assets selects, rpc, storage upload / download. Tests mock
* `@/lib/supabase` to hand this object out. * `@/lib/supabase` to hand this object out.
*/ */
import { vi } from 'vitest' import { vi } from 'vitest'
import type { import type {
AssetRow,
AuthChangeEvent, AuthChangeEvent,
FaunosteoClient, FaunosteoClient,
Profile, Profile,
@@ -58,11 +60,42 @@ export function fakeProfile(patch: Partial<Profile> = {}): Profile {
} }
} }
/** Minimal PostgREST builder: filters, then select / update, awaitable. */ export function fakeAssetRow(patch: Partial<AssetRow> = {}): AssetRow {
return {
id: 'asset-1',
owner_id: 'user-1',
kind: 'profile_avatar',
bucket_id: 'avatars',
object_key: 'profiles/user-1/asset-1/avatar.webp',
status: 'clean',
declared_mime: 'image/jpeg',
declared_size: 1000,
byte_size: 900,
sha256: null,
rejection_reason: null,
created_at: '2026-10-13T10:00:00Z',
updated_at: '2026-10-13T10:00:00Z',
...patch,
}
}
/** Minimal PostgREST builder: filters, order, limit, then select / update, awaitable. */
function builder(tables: Record<string, Row[]>, table: string) { function builder(tables: Record<string, Row[]>, table: string) {
const filters: Array<(row: Row) => boolean> = [] const filters: Array<(row: Row) => boolean> = []
let patch: Row | null = null let patch: Row | null = null
const rows = () => (tables[table] ?? []).filter((r) => filters.every((f) => f(r))) let order: { col: string; ascending: boolean } | null = null
let max: number | null = null
const rows = () => {
let hit = (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
if (order) {
const { col, ascending } = order
hit = [...hit].sort((a, b) =>
(String(a[col]) < String(b[col]) ? -1 : String(a[col]) > String(b[col]) ? 1 : 0) *
(ascending ? 1 : -1),
)
}
return max === null ? hit : hit.slice(0, max)
}
const apply = () => { const apply = () => {
if (!patch) return rows() if (!patch) return rows()
const hit = rows() const hit = rows()
@@ -83,6 +116,18 @@ function builder(tables: Record<string, Row[]>, table: string) {
filters.push((r) => r[col] === value) filters.push((r) => r[col] === value)
return api return api
}, },
in: (col: string, values: unknown[]) => {
filters.push((r) => values.includes(r[col]))
return api
},
order: (col: string, opts?: { ascending?: boolean }) => {
order = { col, ascending: opts?.ascending ?? true }
return api
},
limit: (n: number) => {
max = n
return api
},
maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }), maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }),
single: async () => { single: async () => {
const [first] = apply() const [first] = apply()
@@ -100,6 +145,13 @@ export interface FakeSupabase {
client: FaunosteoClient client: FaunosteoClient
tables: Record<string, Row[]> tables: Record<string, Row[]>
emit: (event: AuthChangeEvent, session: Session | null) => void emit: (event: AuthChangeEvent, session: Session | null) => void
/** Recorded rpc calls; program results with `rpcResults[name]`. */
rpcCalls: Array<[string, unknown]>
rpcResults: Record<string, { data?: unknown; error?: unknown } | (() => { data?: unknown; error?: unknown })>
storage: {
upload: ReturnType<typeof vi.fn>
download: ReturnType<typeof vi.fn>
}
auth: { auth: {
initialize: ReturnType<typeof vi.fn> initialize: ReturnType<typeof vi.fn>
signInWithPassword: ReturnType<typeof vi.fn> signInWithPassword: ReturnType<typeof vi.fn>
@@ -112,9 +164,16 @@ export interface FakeSupabase {
} }
export function createFakeSupabase( export function createFakeSupabase(
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [] }, tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [], assets: [] },
): FakeSupabase { ): FakeSupabase {
tables.assets ??= []
const listeners: Listener[] = [] const listeners: Listener[] = []
const rpcCalls: Array<[string, unknown]> = []
const rpcResults: FakeSupabase['rpcResults'] = {}
const storage = {
upload: vi.fn(async () => ({ data: null, error: null })),
download: vi.fn(async () => ({ data: new Blob([new Uint8Array([82, 73, 70, 70])]), error: null })),
}
const auth = { const auth = {
initialize: vi.fn(async () => ({ error: null })), initialize: vi.fn(async () => ({ error: null })),
onAuthStateChange: vi.fn((cb: Listener) => { onAuthStateChange: vi.fn((cb: Listener) => {
@@ -131,11 +190,21 @@ export function createFakeSupabase(
const client = { const client = {
auth, auth,
from: (table: string) => builder(tables, table), from: (table: string) => builder(tables, table),
rpc: async (name: string, args?: unknown) => {
rpcCalls.push([name, args])
const entry = rpcResults[name]
const result = typeof entry === 'function' ? entry() : (entry ?? {})
return { data: result.data ?? null, error: result.error ?? null }
},
storage: { from: () => storage },
} as unknown as FaunosteoClient } as unknown as FaunosteoClient
return { return {
client, client,
tables, tables,
auth, auth,
rpcCalls,
rpcResults,
storage,
emit: (event, session) => listeners.forEach((cb) => cb(event, session)), emit: (event, session) => listeners.forEach((cb) => cb(event, session)),
} }
} }
@@ -0,0 +1,120 @@
import { describe, expect, it, vi } from 'vitest'
import { AssetFailure } from '@faunosteo/supabase'
import {
MAX_PICKED_BYTES,
prepareAvatarUpload,
sniffImageType,
transportSize,
type TransportDeps,
} from '@/account/avatarTransport'
const JPEG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0, 0, 0, 0, 0])
const WEBP = new Uint8Array([...'RIFF'].map((c) => c.charCodeAt(0)).concat([0, 0, 0, 0], [...'WEBP'].map((c) => c.charCodeAt(0)), [0, 0, 0, 0]))
function file(bytes: Uint8Array, name = 'photo.jpg', type = 'image/jpeg', size?: number): File {
const f = new File([bytes as BlobPart], name, { type })
if (size !== undefined) Object.defineProperty(f, 'size', { value: size })
return f
}
function deps(bitmap: { width: number; height: number } | Error, blobSize = 1000): TransportDeps & { canvas: { width: number; height: number }; drawn: unknown[] } {
const canvas = { width: 0, height: 0 }
const drawn: unknown[] = []
return {
canvas,
drawn,
createImageBitmap: async () => {
if (bitmap instanceof Error) throw bitmap
return { ...bitmap, close: vi.fn() }
},
createCanvas: () => ({
get width() {
return canvas.width
},
set width(v: number) {
canvas.width = v
},
get height() {
return canvas.height
},
set height(v: number) {
canvas.height = v
},
getContext: () => ({ drawImage: (...args: unknown[]) => drawn.push(args) }),
toBlob: (cb: (b: Blob | null) => void) => {
const blob = new Blob([new Uint8Array(blobSize)], { type: 'image/jpeg' })
cb(blob)
},
}),
createObjectURL: () => 'blob:preview',
}
}
async function failureKind(p: Promise<unknown>) {
try {
await p
return null
} catch (e) {
return e instanceof AssetFailure ? e.kind : String(e)
}
}
describe('sniffImageType', () => {
it('recognises JPEG, PNG and WebP by magic bytes only', () => {
expect(sniffImageType(JPEG)).toBe('image/jpeg')
expect(sniffImageType(PNG)).toBe('image/png')
expect(sniffImageType(WEBP)).toBe('image/webp')
})
it('refuses SVG, GIF, a RIFF that is not WEBP and empty input', () => {
const svg = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>')
expect(sniffImageType(svg)).toBeNull()
expect(sniffImageType(new TextEncoder().encode('GIF89a......'))).toBeNull()
expect(sniffImageType(new TextEncoder().encode('RIFF....WAVE....'))).toBeNull()
expect(sniffImageType(new Uint8Array())).toBeNull()
})
})
describe('transportSize', () => {
it('caps the longest side at 1024 and never upscales', () => {
expect(transportSize(4000, 3000)).toEqual({ width: 1024, height: 768 })
expect(transportSize(3000, 4000)).toEqual({ width: 768, height: 1024 })
expect(transportSize(500, 500)).toEqual({ width: 500, height: 500 })
expect(transportSize(1024, 10)).toEqual({ width: 1024, height: 10 })
})
})
describe('prepareAvatarUpload', () => {
it('refuses an oversized file before any decode', async () => {
const d = deps({ width: 10, height: 10 })
const spy = vi.spyOn(d, 'createImageBitmap')
expect(await failureKind(prepareAvatarUpload(file(JPEG, 'big.jpg', 'image/jpeg', MAX_PICKED_BYTES + 1), d))).toBe('too_large')
expect(spy).not.toHaveBeenCalled()
})
it('refuses a file whose bytes are not a raster image, whatever its name or type', async () => {
const d = deps({ width: 10, height: 10 })
const svg = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>')
expect(await failureKind(prepareAvatarUpload(file(svg, 'logo.jpg', 'image/jpeg'), d))).toBe('unsupported_type')
})
it('maps a bitmap decode failure to unsupported_type', async () => {
const d = deps(new Error('not decodable'))
expect(await failureKind(prepareAvatarUpload(file(JPEG), d))).toBe('unsupported_type')
})
it('draws a downscaled canvas and returns a JPEG blob with a preview URL', async () => {
const d = deps({ width: 4000, height: 3000 })
const result = await prepareAvatarUpload(file(PNG, 'p.png', 'image/png'), d)
expect(d.canvas).toEqual({ width: 1024, height: 768 })
expect(d.drawn[0]).toEqual([expect.objectContaining({ width: 4000 }), 0, 0, 1024, 768])
expect(result.blob.type).toBe('image/jpeg')
expect(result.previewUrl).toBe('blob:preview')
})
it('keeps a small image at its size', async () => {
const d = deps({ width: 500, height: 500 })
await prepareAvatarUpload(file(JPEG), d)
expect(d.canvas).toEqual({ width: 500, height: 500 })
})
it('refuses a transport blob over 5 MiB', async () => {
const d = deps({ width: 1000, height: 1000 }, 5 * 1024 * 1024 + 1)
expect(await failureKind(prepareAvatarUpload(file(JPEG), d))).toBe('too_large')
})
})
@@ -0,0 +1,172 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AssetFailure } from '@faunosteo/supabase'
import {
createFakeSupabase,
fakeAssetRow,
fakeProfile,
fakeUser,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({
fake: null as unknown,
prepare: vi.fn(),
}))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
vi.mock('@/account/avatarTransport', () => ({
prepareAvatarUpload: (...args: unknown[]) => mocks.prepare(...args),
}))
import AvatarSection, { POLL_INTERVAL_MS } from '@/components/account/AvatarSection'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
const TICKET = {
asset_id: '11111111-1111-4111-8111-111111111111',
bucket_id: 'avatars',
quarantine_key: 'quarantine/user-1/11111111-1111-4111-8111-111111111111/upload',
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
mocks.prepare.mockReset()
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile(),
roles: [],
avatar: { clean: null, inFlight: null, lastRejected: null },
avatarUrl: null,
})
fake.rpcResults.begin_avatar_upload = { data: TICKET }
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
function pick(file = new File([new Uint8Array([0xff, 0xd8, 0xff])], 'p.jpg', { type: 'image/jpeg' })) {
const input = screen.getByLabelText(fr['account.avatar.change'])
fireEvent.change(input, { target: { files: [file] } })
}
describe('AvatarSection', () => {
it('shows the monogram and no remove button without a photo', () => {
render(<AvatarSection />)
expect(screen.getByText('AL')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: fr['account.avatar.remove'] })).toBeNull()
})
it('refuses a bad pick with the phrased message and makes no request', async () => {
mocks.prepare.mockRejectedValue(new AssetFailure('unsupported_type'))
render(<AvatarSection />)
pick()
expect(await screen.findByText(fr['account.avatar.error.unsupported_type'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
expect(fake.storage.upload).not.toHaveBeenCalled()
})
it('shows the preview with save / cancel before any request', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x'], { type: 'image/jpeg' }), previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
const img = await screen.findByRole('img', { name: fr['account.avatar.alt'] })
expect(img).toHaveAttribute('src', 'blob:preview')
expect(screen.getByRole('button', { name: fr['account.avatar.save'] })).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.cancel'] }))
expect(screen.queryByRole('img')).toBeNull()
})
it('saves in order begin → upload → confirm, polls, then shows the photo', async () => {
const blob = new Blob([new Uint8Array(1234)], { type: 'image/jpeg' })
mocks.prepare.mockResolvedValue({ blob, previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.map((c) => c[0])).toEqual(['begin_avatar_upload', 'confirm_asset_upload']))
expect(fake.rpcCalls[0][1]).toEqual({ declared_mime: 'image/jpeg', declared_size: 1234 })
expect(fake.storage.upload).toHaveBeenCalledWith(TICKET.quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' })
expect(fake.rpcCalls[1][1]).toEqual({ asset_id: TICKET.asset_id })
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
// The worker finishes: the next poll sees the clean row and downloads it.
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.saved'])).toBeInTheDocument())
expect(fake.storage.download).toHaveBeenCalledWith('profiles/user-1/asset-1/avatar.webp')
expect(screen.getByRole('button', { name: fr['account.avatar.remove'] })).toBeInTheDocument()
})
it('phrases a rejection per code once the poll settles', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.length).toBe(2))
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, status: 'rejected', rejection_reason: 'dimensions', created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.rejected.dimensions'])).toBeInTheDocument())
})
it('phrases an RPC refusal and keeps the circle usable', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
fake.rpcResults.begin_avatar_upload = { error: { code: 'P0001', message: 'rate_limited', status: 400 } }
render(<AvatarSection />)
pick()
await userEvent.click(await screen.findByRole('button', { name: fr['account.avatar.save'] }))
expect(await screen.findByText(fr['account.avatar.error.rate_limited'])).toBeInTheDocument()
expect(fake.storage.upload).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeEnabled()
})
it('removes the photo after the dialog confirmation', async () => {
useAuthStore.setState({ avatarUrl: 'blob:current', avatar: { clean: fakeAssetRow(), inFlight: null, lastRejected: null } })
fake.rpcResults.remove_avatar = { data: 1 }
render(<AvatarSection />)
expect(screen.getByRole('img', { name: fr['account.avatar.alt'] })).toHaveAttribute('src', 'blob:current')
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['account.avatar.remove_title'] })
expect(dialog).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove_confirm'] }))
expect(await screen.findByText(fr['account.avatar.removed'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([['remove_avatar', undefined]])
expect(useAuthStore.getState().avatarUrl).toBeNull()
expect(screen.queryByRole('img')).toBeNull()
})
it('resumes the processing state for a row in flight at mount', async () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: fakeAssetRow({ status: 'uploaded' }), lastRejected: null } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
})
it('shows the last rejection of a fresh mount', () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: null, lastRejected: fakeAssetRow({ status: 'rejected', rejection_reason: 'decode_failed' }) } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.rejected.decode_failed'])).toBeInTheDocument()
})
})
+29 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react' import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom' import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase' import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
@@ -27,6 +27,8 @@ beforeEach(() => {
user: fakeUser(), user: fakeUser(),
profile: fakeProfile({ display_name: 'Alice Local' }), profile: fakeProfile({ display_name: 'Alice Local' }),
roles: [], roles: [],
avatar: null,
avatarUrl: null,
}) })
}) })
afterEach(cleanup) afterEach(cleanup)
@@ -56,9 +58,34 @@ describe('AppLayout', () => {
expect(screen.getByText('dashboard page')).toBeInTheDocument() expect(screen.getByText('dashboard page')).toBeInTheDocument()
}) })
it('links the top-bar avatar and name to the account page', async () => {
const user = userEvent.setup()
mount()
const link = screen.getByTestId('topbar-account')
expect(link).toHaveAttribute('href', '/app/account')
expect(link).toHaveTextContent('Alice Local')
expect(link).toHaveAttribute('aria-label', fr['shell.nav.account'])
await user.click(link)
expect(await screen.findByText('account page')).toBeInTheDocument()
})
it('shows the photo everywhere once the store holds a blob URL, the monogram otherwise', () => {
mount()
expect(screen.queryAllByRole('img', { name: fr['account.avatar.alt'] })).toHaveLength(0)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
cleanup()
useAuthStore.setState({ avatarUrl: 'blob:photo' })
mount()
const imgs = screen.getAllByRole('img', { name: fr['account.avatar.alt'] })
expect(imgs.length).toBeGreaterThanOrEqual(2)
imgs.forEach((img) => expect(img).toHaveAttribute('src', 'blob:photo'))
expect(screen.queryByText('AL')).toBeNull()
})
it('marks the active destination', () => { it('marks the active destination', () => {
mount('/app/account') mount('/app/account')
const link = screen.getByRole('link', { name: new RegExp(fr['shell.nav.account']) }) const nav = screen.getByRole('navigation', { name: fr['shell.nav_label'] })
const link = within(nav).getByRole('link', { name: new RegExp(fr['shell.nav.account']) })
expect(link).toHaveAttribute('aria-current', 'page') expect(link).toHaveAttribute('aria-current', 'page')
}) })
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { import {
createFakeSupabase, createFakeSupabase,
fakeAssetRow,
fakeSession, fakeSession,
flush, flush,
type FakeSupabase, type FakeSupabase,
@@ -22,6 +23,8 @@ const INITIAL = {
roles: [], roles: [],
recovery: false, recovery: false,
urlFailure: null, urlFailure: null,
avatar: null,
avatarUrl: null,
} }
let fake: FakeSupabase let fake: FakeSupabase
@@ -97,6 +100,38 @@ describe('authStore', () => {
expect(fake.tables.profiles[0].first_name).toBe('Alice') expect(fake.tables.profiles[0].first_name).toBe('Alice')
}) })
it('loads the avatar state and downloads the clean photo once', async () => {
fake.tables.assets.push(fakeAssetRow())
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await flush()
const s = useAuthStore.getState()
expect(s.avatar?.clean?.id).toBe('asset-1')
expect(s.avatarUrl).toMatch(/^blob:/)
expect(fake.storage.download).toHaveBeenCalledTimes(1)
await useAuthStore.getState().refreshAvatar()
expect(fake.storage.download).toHaveBeenCalledTimes(1)
fake.tables.assets.push(fakeAssetRow({ id: 'asset-2', object_key: 'profiles/user-1/asset-2/avatar.webp', created_at: '2026-10-13T12:00:00Z' }))
fake.tables.assets[0].status = 'deleted'
await useAuthStore.getState().refreshAvatar()
expect(fake.storage.download).toHaveBeenLastCalledWith('profiles/user-1/asset-2/avatar.webp')
})
it('clearAvatar drops the URL and the clean row; sign-out clears it too', async () => {
fake.tables.assets.push(fakeAssetRow())
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await flush()
useAuthStore.getState().clearAvatar()
expect(useAuthStore.getState().avatarUrl).toBeNull()
expect(useAuthStore.getState().avatar?.clean).toBeNull()
await useAuthStore.getState().refreshAvatar()
fake.emit('SIGNED_OUT', null)
expect(useAuthStore.getState()).toMatchObject({ avatar: null, avatarUrl: null })
})
it('signOut calls the client and resets the state', async () => { it('signOut calls the client and resets the state', async () => {
stop = useAuthStore.getState().start() stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession()) fake.emit('SIGNED_IN', fakeSession())
+3 -1
View File
@@ -17,11 +17,13 @@
"test:run": "vitest run", "test:run": "vitest run",
"lint": "eslint . --max-warnings 0", "lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit", "build": "tsc -p tsconfig.json --noEmit",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"assets:upload": "node scripts/upload-sheet-assets.ts" "assets:upload": "node scripts/upload-sheet-assets.ts"
}, },
"dependencies": { "dependencies": {
"@faunosteo/domain": "workspace:*", "@faunosteo/domain": "workspace:*",
"@supabase/supabase-js": "^2.100.0" "@supabase/supabase-js": "^2.100.0",
"zod": "^3.24.1"
}, },
"devDependencies": { "devDependencies": {
"@electric-sql/pglite": "^0.3.0", "@electric-sql/pglite": "^0.3.0",
+247
View File
@@ -0,0 +1,247 @@
import { z } from 'zod'
import type { FaunosteoClient } from './client'
import type { Enums, Tables } from './database.types'
/**
* Browser side of the files foundation (docs/development/STORAGE.md §2.1,
* §4): the three avatar RPCs, the quarantine upload under the INSERT policy,
* the own-row read for polling and the download under the SELECT policy.
* Every failure is folded into a closed kind the UI knows how to phrase.
*/
export type AssetStatus = Enums<'asset_status'>
/** Columns the owner may read (column grant); the lease columns stay server-side. */
export const ASSET_OWNER_COLUMNS =
'id, owner_id, kind, bucket_id, object_key, status, declared_mime, declared_size, byte_size, sha256, rejection_reason, created_at, updated_at'
export type AssetRow = Pick<
Tables<'assets'>,
| 'id'
| 'owner_id'
| 'kind'
| 'bucket_id'
| 'object_key'
| 'status'
| 'declared_mime'
| 'declared_size'
| 'byte_size'
| 'sha256'
| 'rejection_reason'
| 'created_at'
| 'updated_at'
>
export const AVATAR_REJECTION_CODES = [
'unsupported_type',
'decode_failed',
'dimensions',
'processing_error',
] as const
export type AvatarRejectionCode = (typeof AVATAR_REJECTION_CODES)[number]
export function isAvatarRejectionCode(
value: string | null | undefined,
): value is AvatarRejectionCode {
return (AVATAR_REJECTION_CODES as readonly string[]).includes(value ?? '')
}
export const ASSET_FAILURE_KINDS = [
'too_large',
'unsupported_type',
'rate_limited',
'storage_full',
'upload_missing',
'invalid_state',
'not_found',
'network',
'unknown',
] as const
export type AssetFailureKind = (typeof ASSET_FAILURE_KINDS)[number]
export class AssetFailure extends Error {
readonly kind: AssetFailureKind
constructor(kind: AssetFailureKind, cause?: unknown) {
super(`asset: ${kind}`, { cause })
this.name = 'AssetFailure'
this.kind = kind
}
}
/** Codes the RPCs raise as SQLSTATE P0001 messages (STORAGE.md §2). */
const RPC_MESSAGE_KINDS: ReadonlySet<string> = new Set([
'too_large',
'unsupported_type',
'rate_limited',
'storage_full',
'upload_missing',
'invalid_state',
'not_found',
])
interface PostgrestLikeError {
code?: string | null
message?: string
status?: number
}
/**
* Folds a PostgREST / storage / fetch error into a closed kind. `42501`
* (authorisation) becomes `unknown` on purpose: the UI never reaches an RPC
* without a session, so it is a bug, not a state to phrase.
*/
export function classifyAssetError(error: unknown): AssetFailureKind {
if (error instanceof AssetFailure) return error.kind
if (error instanceof TypeError) return 'network'
const e = (error ?? {}) as PostgrestLikeError
if (e.code === 'P0001' && e.message && RPC_MESSAGE_KINDS.has(e.message)) {
return e.message as AssetFailureKind
}
if (e.status === undefined || e.status === 0) {
return e.code ? 'unknown' : 'network'
}
return 'unknown'
}
function fail(error: unknown): never {
throw new AssetFailure(classifyAssetError(error), error)
}
const BeginResultSchema = z.object({
asset_id: z.string().uuid(),
bucket_id: z.literal('avatars'),
quarantine_key: z.string().min(1),
})
export interface BeginAvatarUploadInput {
declaredMime: 'image/jpeg' | 'image/png' | 'image/webp'
declaredSize: number
}
export interface AvatarUploadTicket {
assetId: string
bucketId: 'avatars'
quarantineKey: string
}
export async function beginAvatarUpload(
client: FaunosteoClient,
input: BeginAvatarUploadInput,
): Promise<AvatarUploadTicket> {
const { data, error } = await client.rpc('begin_avatar_upload', {
declared_mime: input.declaredMime,
declared_size: input.declaredSize,
})
if (error) fail(error)
const parsed = BeginResultSchema.safeParse(data)
if (!parsed.success) throw new AssetFailure('unknown', parsed.error)
return {
assetId: parsed.data.asset_id,
bucketId: parsed.data.bucket_id,
quarantineKey: parsed.data.quarantine_key,
}
}
export interface QuarantineUploadInput {
bucketId: string
quarantineKey: string
blob: Blob
}
/** Direct upload with the user JWT; only the caller's pending quarantine key passes the INSERT policy. */
export async function uploadToQuarantine(
client: FaunosteoClient,
input: QuarantineUploadInput,
): Promise<void> {
const { error } = await client.storage
.from(input.bucketId)
.upload(input.quarantineKey, input.blob, {
upsert: false,
contentType: 'image/jpeg',
})
if (error) throw new AssetFailure(classifyStorageUploadError(error), error)
}
/**
* storage-js answers with a StorageApiError (status + statusCode) for a
* refused upload; a policy refusal (the row is no longer pending, or the key
* is not ours) is a state problem, not a network one.
*/
function classifyStorageUploadError(error: {
message: string
status?: number
statusCode?: string
}): AssetFailureKind {
if (/already exists|duplicate/i.test(error.message)) return 'invalid_state'
if (error.status === 413 || error.statusCode === '413') return 'too_large'
if (error.status === undefined) return 'network'
return 'invalid_state'
}
export async function confirmAssetUpload(
client: FaunosteoClient,
assetId: string,
): Promise<void> {
const { error } = await client.rpc('confirm_asset_upload', {
asset_id: assetId,
})
if (error) fail(error)
}
/** Every avatar row of the caller still alive → deleted; returns the count. */
export async function removeAvatar(client: FaunosteoClient): Promise<number> {
const { data, error } = await client.rpc('remove_avatar')
if (error) fail(error)
return typeof data === 'number' ? data : 0
}
export interface AvatarState {
/** The single clean avatar, if any. */
clean: AssetRow | null
/** Newest pending / uploaded row newer than the clean one. */
inFlight: AssetRow | null
/** Newest rejected row newer than the clean one (shown once). */
lastRejected: AssetRow | null
}
const IN_FLIGHT: ReadonlySet<AssetStatus> = new Set(['pending_upload', 'uploaded'])
/** Reduces the newest-first rows of an owner to the three states the UI shows. */
export function reduceAvatarRows(rows: readonly AssetRow[]): AvatarState {
const clean = rows.find((r) => r.status === 'clean') ?? null
const newerThanClean = (r: AssetRow) =>
clean === null || r.created_at > clean.created_at
const inFlight =
rows.find((r) => IN_FLIGHT.has(r.status) && newerThanClean(r)) ?? null
const lastRejected =
rows.find((r) => r.status === 'rejected' && newerThanClean(r)) ?? null
return { clean, inFlight, lastRejected }
}
export async function fetchOwnAvatarState(
client: FaunosteoClient,
userId: string,
): Promise<AvatarState> {
const { data, error } = await client
.from('assets')
.select(ASSET_OWNER_COLUMNS)
.eq('owner_id', userId)
.eq('kind', 'profile_avatar')
.in('status', ['clean', 'pending_upload', 'uploaded', 'rejected'])
.order('created_at', { ascending: false })
.limit(5)
if (error) fail(error)
return reduceAvatarRows((data ?? []) as AssetRow[])
}
/** Download under the SELECT policy: only the owner's clean object answers. */
export async function downloadAvatar(
client: FaunosteoClient,
objectKey: string,
): Promise<Blob> {
const { data, error } = await client.storage
.from('avatars')
.download(objectKey)
if (error || !data) fail(error ?? new Error('empty download'))
return data
}
+23
View File
@@ -44,6 +44,29 @@ export {
/** owner | admin | moderator | support. Not a professional status. */ /** owner | admin | moderator | support. Not a professional status. */
export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles' export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles'
export { publishSheetVersion } from './anatomical-sheets' export { publishSheetVersion } from './anatomical-sheets'
export {
ASSET_FAILURE_KINDS,
ASSET_OWNER_COLUMNS,
AVATAR_REJECTION_CODES,
AssetFailure,
beginAvatarUpload,
classifyAssetError,
confirmAssetUpload,
downloadAvatar,
fetchOwnAvatarState,
isAvatarRejectionCode,
reduceAvatarRows,
removeAvatar,
uploadToQuarantine,
type AssetFailureKind,
type AssetRow,
type AssetStatus,
type AvatarRejectionCode,
type AvatarState,
type AvatarUploadTicket,
type BeginAvatarUploadInput,
type QuarantineUploadInput,
} from './assets'
/** Row of public.species. */ /** Row of public.species. */
export type Species = Tables<'species'> export type Species = Tables<'species'>
+225
View File
@@ -0,0 +1,225 @@
import {
AssetFailure,
beginAvatarUpload,
classifyAssetError,
confirmAssetUpload,
downloadAvatar,
fetchOwnAvatarState,
reduceAvatarRows,
removeAvatar,
uploadToQuarantine,
type AssetRow,
} from '../src'
import type { FaunosteoClient } from '../src'
/**
* Stub of the client surface the assets module touches: rpc, the assets
* select chain, storage upload / download. The RPC bodies are covered by
* supabase/tests/010_files_foundation.sql; here the point is the call shape
* and the closed failure kinds.
*/
function stubClient(options: {
rpc?: Record<string, { data?: unknown; error?: unknown }>
rows?: AssetRow[]
selectError?: unknown
upload?: { error?: { message: string; status?: number; statusCode?: string } | null }
download?: { data?: Blob | null; error?: unknown }
} = {}) {
const calls: Array<[string, unknown]> = []
const query: Record<string, unknown> = {}
const chain = {
select: (cols: string) => {
query.select = cols
return chain
},
eq: (col: string, value: unknown) => {
query[`eq:${col}`] = value
return chain
},
in: (col: string, values: unknown) => {
query[`in:${col}`] = values
return chain
},
order: (col: string, opts: unknown) => {
query.order = [col, opts]
return chain
},
limit: async (n: number) => {
query.limit = n
return options.selectError
? { data: null, error: options.selectError }
: { data: options.rows ?? [], error: null }
},
}
const storageCalls: Array<[string, unknown[]]> = []
const client = {
rpc: async (name: string, args?: unknown) => {
calls.push([name, args])
const r = options.rpc?.[name] ?? {}
return { data: r.data ?? null, error: r.error ?? null }
},
from: () => chain,
storage: {
from: (bucket: string) => ({
upload: async (...args: unknown[]) => {
storageCalls.push([`upload:${bucket}`, args])
return { data: null, error: options.upload?.error ?? null }
},
download: async (...args: unknown[]) => {
storageCalls.push([`download:${bucket}`, args])
return {
data: options.download?.data ?? null,
error: options.download?.error ?? null,
}
},
}),
},
}
return { client: client as unknown as FaunosteoClient, calls, query, storageCalls }
}
function row(patch: Partial<AssetRow>): AssetRow {
return {
id: 'a1',
owner_id: 'u1',
kind: 'profile_avatar',
bucket_id: 'avatars',
object_key: 'profiles/u1/a1/avatar.webp',
status: 'clean',
declared_mime: 'image/jpeg',
declared_size: 1000,
byte_size: null,
sha256: null,
rejection_reason: null,
created_at: '2026-10-13T10:00:00Z',
updated_at: '2026-10-13T10:00:00Z',
...patch,
}
}
const TICKET = {
asset_id: '11111111-1111-4111-8111-111111111111',
bucket_id: 'avatars',
quarantine_key: 'quarantine/u1/11111111-1111-4111-8111-111111111111/upload',
}
async function kindOf(p: Promise<unknown>) {
try {
await p
return null
} catch (e) {
return e instanceof AssetFailure ? e.kind : 'not-an-asset-failure'
}
}
describe('classifyAssetError', () => {
it('maps P0001 closed messages to their kind', () => {
for (const m of ['too_large', 'unsupported_type', 'rate_limited', 'storage_full', 'upload_missing', 'invalid_state', 'not_found']) {
expect(classifyAssetError({ code: 'P0001', message: m, status: 400 })).toBe(m)
}
})
it('never trusts an unknown message, authorisation is unknown, fetch failures are network', () => {
expect(classifyAssetError({ code: 'P0001', message: 'drop table', status: 400 })).toBe('unknown')
expect(classifyAssetError({ code: '42501', message: 'permission denied', status: 403 })).toBe('unknown')
expect(classifyAssetError(new TypeError('Failed to fetch'))).toBe('network')
expect(classifyAssetError({ message: 'offline' })).toBe('network')
expect(classifyAssetError(new AssetFailure('too_large'))).toBe('too_large')
})
})
describe('beginAvatarUpload', () => {
it('calls the RPC with the declared transport and validates the ticket', async () => {
const stub = stubClient({ rpc: { begin_avatar_upload: { data: TICKET } } })
const ticket = await beginAvatarUpload(stub.client, { declaredMime: 'image/jpeg', declaredSize: 1234 })
expect(stub.calls).toEqual([['begin_avatar_upload', { declared_mime: 'image/jpeg', declared_size: 1234 }]])
expect(ticket).toEqual({ assetId: TICKET.asset_id, bucketId: 'avatars', quarantineKey: TICKET.quarantine_key })
})
it('refuses a malformed ticket and folds RPC errors', async () => {
const bad = stubClient({ rpc: { begin_avatar_upload: { data: { asset_id: 'x' } } } })
expect(await kindOf(beginAvatarUpload(bad.client, { declaredMime: 'image/jpeg', declaredSize: 1 }))).toBe('unknown')
const limited = stubClient({ rpc: { begin_avatar_upload: { error: { code: 'P0001', message: 'rate_limited', status: 400 } } } })
expect(await kindOf(beginAvatarUpload(limited.client, { declaredMime: 'image/jpeg', declaredSize: 1 }))).toBe('rate_limited')
})
})
describe('uploadToQuarantine / confirm / remove', () => {
it('uploads with upsert off and the JPEG content type', async () => {
const stub = stubClient()
const blob = new Blob([new Uint8Array([1, 2, 3])], { type: 'image/jpeg' })
await uploadToQuarantine(stub.client, { bucketId: 'avatars', quarantineKey: TICKET.quarantine_key, blob })
expect(stub.storageCalls).toEqual([
['upload:avatars', [TICKET.quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' }]],
])
})
it('maps a duplicate or a policy refusal to invalid_state, a transport failure to network', async () => {
const blob = new Blob([])
const dup = stubClient({ upload: { error: { message: 'The resource already exists' } } })
expect(await kindOf(uploadToQuarantine(dup.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('invalid_state')
const refused = stubClient({
upload: { error: { message: 'new row violates row-level security policy', status: 400, statusCode: '42501' } },
})
expect(await kindOf(uploadToQuarantine(refused.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('invalid_state')
const big = stubClient({ upload: { error: { message: 'Payload too large', status: 413, statusCode: '413' } } })
expect(await kindOf(uploadToQuarantine(big.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('too_large')
const down = stubClient({ upload: { error: { message: 'fetch failed' } } })
expect(await kindOf(uploadToQuarantine(down.client, { bucketId: 'avatars', quarantineKey: 'k', blob }))).toBe('network')
})
it('confirm and remove call their RPCs', async () => {
const stub = stubClient({ rpc: { remove_avatar: { data: 2 } } })
await confirmAssetUpload(stub.client, TICKET.asset_id)
expect(await removeAvatar(stub.client)).toBe(2)
expect(stub.calls.map((c) => c[0])).toEqual(['confirm_asset_upload', 'remove_avatar'])
expect(stub.calls[0][1]).toEqual({ asset_id: TICKET.asset_id })
const missing = stubClient({ rpc: { confirm_asset_upload: { error: { code: 'P0001', message: 'upload_missing', status: 400 } } } })
expect(await kindOf(confirmAssetUpload(missing.client, TICKET.asset_id))).toBe('upload_missing')
})
})
describe('fetchOwnAvatarState', () => {
it('reads the explicit column list, never *, for the owner', async () => {
const stub = stubClient({ rows: [row({})] })
const state = await fetchOwnAvatarState(stub.client, 'u1')
expect(stub.query.select).not.toContain('*')
expect(stub.query.select).toContain('object_key')
expect(stub.query.select).not.toContain('lock_token')
expect(stub.query['eq:owner_id']).toBe('u1')
expect(stub.query['eq:kind']).toBe('profile_avatar')
expect(stub.query['in:status']).toEqual(['clean', 'pending_upload', 'uploaded', 'rejected'])
expect(stub.query.limit).toBe(5)
expect(state.clean?.id).toBe('a1')
expect(state.inFlight).toBeNull()
})
it('folds a select error', async () => {
const stub = stubClient({ selectError: { code: '42501', message: 'denied', status: 403 } })
expect(await kindOf(fetchOwnAvatarState(stub.client, 'u1'))).toBe('unknown')
})
})
describe('reduceAvatarRows', () => {
const clean = row({ id: 'c', status: 'clean', created_at: '2026-10-13T10:00:00Z' })
it('only rows newer than the clean one count as in flight or rejected', () => {
const older = row({ id: 'o', status: 'rejected', rejection_reason: 'dimensions', created_at: '2026-10-13T09:00:00Z' })
const newer = row({ id: 'n', status: 'uploaded', created_at: '2026-10-13T11:00:00Z' })
const rejected = row({ id: 'r', status: 'rejected', rejection_reason: 'decode_failed', created_at: '2026-10-13T12:00:00Z' })
const state = reduceAvatarRows([rejected, newer, clean, older])
expect(state.clean?.id).toBe('c')
expect(state.inFlight?.id).toBe('n')
expect(state.lastRejected?.id).toBe('r')
})
it('without a clean row every newer row counts', () => {
const state = reduceAvatarRows([row({ id: 'p', status: 'pending_upload' })])
expect(state).toEqual({ clean: null, inFlight: expect.objectContaining({ id: 'p' }), lastRejected: null })
expect(reduceAvatarRows([])).toEqual({ clean: null, inFlight: null, lastRejected: null })
})
})
describe('downloadAvatar', () => {
it('downloads from the avatars bucket and folds a refusal', async () => {
const blob = new Blob([new Uint8Array([82, 73, 70, 70])])
const ok = stubClient({ download: { data: blob } })
expect(await downloadAvatar(ok.client, 'profiles/u1/a1/avatar.webp')).toBe(blob)
expect(ok.storageCalls[0]).toEqual(['download:avatars', ['profiles/u1/a1/avatar.webp']])
const denied = stubClient({ download: { error: { message: 'Object not found', status: 400 } } })
expect(await kindOf(downloadAvatar(denied.client, 'k'))).toBe('unknown')
})
})
+3
View File
@@ -246,6 +246,9 @@ importers:
'@supabase/supabase-js': '@supabase/supabase-js':
specifier: ^2.100.0 specifier: ^2.100.0
version: 2.117.3 version: 2.117.3
zod:
specifier: ^3.24.1
version: 3.25.76
devDependencies: devDependencies:
'@electric-sql/pglite': '@electric-sql/pglite':
specifier: ^0.3.0 specifier: ^0.3.0