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
+1550 -31

No files matched your search

+3 -1
View File
@@ -17,11 +17,13 @@
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"assets:upload": "node scripts/upload-sheet-assets.ts"
},
"dependencies": {
"@faunosteo/domain": "workspace:*",
"@supabase/supabase-js": "^2.100.0"
"@supabase/supabase-js": "^2.100.0",
"zod": "^3.24.1"
},
"devDependencies": {
"@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. */
export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles'
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. */
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')
})
})