import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createFakeSupabase, fakeAssetRow, fakeProfile, fakeSession, fakeUser, flush, type FakeSupabase, } from '../helpers/fakeSupabase' const mocks = vi.hoisted(() => ({ fake: null as unknown })) vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, isSupabaseConfigured: () => mocks.fake !== null, })) import { useAuthStore } from '@/state/authStore' const INITIAL = { status: 'loading' as const, session: null, user: null, profile: null, roles: [], recovery: false, urlFailure: null, avatar: null, avatarUrl: null, workspace: { status: 'idle' as const }, catalogGrants: [], catalogGrantsStatus: 'loading' as const, } let fake: FakeSupabase let stop: () => void = () => undefined beforeEach(() => { useAuthStore.setState(INITIAL) fake = createFakeSupabase() fake.tables.profile_roles = [ { user_id: 'user-1', role: 'admin', revoked_at: null }, { user_id: 'user-1', role: 'support', revoked_at: '2026-01-01' }, ] mocks.fake = fake }) afterEach(() => stop()) describe('authStore', () => { it('is unavailable when no backend is configured', () => { mocks.fake = null stop = useAuthStore.getState().start() expect(useAuthStore.getState().status).toBe('unavailable') }) it('loads the profile and active roles after SIGNED_IN', async () => { stop = useAuthStore.getState().start() expect(fake.auth.initialize).toHaveBeenCalled() fake.emit('SIGNED_IN', fakeSession()) expect(useAuthStore.getState().status).toBe('signed_in') await flush() const s = useAuthStore.getState() expect(s.profile?.display_name).toBe('Alice Local') expect(s.roles).toEqual(['admin']) }) it('clears everything on SIGNED_OUT and on an INITIAL_SESSION without session', async () => { stop = useAuthStore.getState().start() fake.emit('INITIAL_SESSION', null) expect(useAuthStore.getState().status).toBe('signed_out') fake.emit('SIGNED_IN', fakeSession()) await flush() fake.emit('SIGNED_OUT', null) expect(useAuthStore.getState()).toMatchObject({ status: 'signed_out', user: null, profile: null, roles: [], }) }) it('flags a recovery link until the password is saved', () => { stop = useAuthStore.getState().start() fake.emit('PASSWORD_RECOVERY', fakeSession()) expect(useAuthStore.getState().recovery).toBe(true) useAuthStore.getState().clearRecovery() expect(useAuthStore.getState().recovery).toBe(false) }) it('records a URL exchange failure for the landing routes', async () => { fake.auth.initialize.mockResolvedValueOnce({ error: { code: 'flow_state_expired', message: 'x', status: 400 }, }) stop = useAuthStore.getState().start() await flush() expect(useAuthStore.getState().urlFailure).toBe('link_expired') }) it('loads the own grant rows for the navigation hint and drops them on a change of account', async () => { const grant = { user_id: 'user-1', kind: 'catalog_reader', expires_at: null, revoked_at: null } fake.tables.anatomical_catalog_grants = [grant] fake.tables.profiles = [fakeProfile(), fakeProfile({ id: 'user-2' })] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().catalogGrants).toEqual([grant]) expect(useAuthStore.getState().catalogGrantsStatus).toBe('ready') fake.emit('SIGNED_IN', fakeSession(fakeUser({ id: 'user-2' }))) expect(useAuthStore.getState().catalogGrants).toEqual([]) expect(useAuthStore.getState().catalogGrantsStatus).toBe('loading') await flush() await flush() expect(useAuthStore.getState().catalogGrants).toEqual([]) fake.emit('SIGNED_OUT', null) expect(useAuthStore.getState().catalogGrants).toEqual([]) expect(useAuthStore.getState().catalogGrantsStatus).toBe('loading') }) describe('reloadAccess', () => { type Answer = { data: unknown; error: unknown; status?: number } const FAILED: Answer = { data: null, error: { code: '', message: 'FetchError' }, status: 0 } const GRANT = { user_id: 'user-1', kind: 'sheet_editor', expires_at: null, revoked_at: null } /** Every chain on `table` ends in `answer()`, as a dropped request or a late reply would. */ function answerTable(table: string, answer: () => Answer | Promise) { const from = fake.client.from.bind(fake.client) const chain: unknown = new Proxy(() => undefined, { get: (_, key) => key === 'then' ? (resolve: (v: unknown) => void, reject: (e: unknown) => void) => Promise.resolve(answer()).then(resolve, reject) : () => chain, }) ;(fake.client as unknown as { from: (t: string) => unknown }).from = (t: string) => t === table ? chain : from(t as never) } async function signedIn() { fake.tables.profiles = [fakeProfile(), fakeProfile({ id: 'user-2' })] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() } it('goes loading then ready, replacing the roles and the grants', async () => { await signedIn() expect(useAuthStore.getState().roles).toEqual(['admin']) fake.tables.profile_roles = [{ user_id: 'user-1', role: 'owner', revoked_at: null }] fake.tables.anatomical_catalog_grants = [GRANT] const reload = useAuthStore.getState().reloadAccess() expect(useAuthStore.getState().catalogGrantsStatus).toBe('loading') await reload const s = useAuthStore.getState() expect(s.catalogGrantsStatus).toBe('ready') expect(s.roles).toEqual(['owner']) expect(s.catalogGrants).toEqual([GRANT]) }) it.each(['anatomical_catalog_grants', 'profile_roles'])( 'ends failed with no grants and keeps the roles, profile and workspace when the %s read rejects', async (table) => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] fake.tables.anatomical_catalog_grants = [GRANT] await signedIn() const before = useAuthStore.getState() expect(before.catalogGrants).toEqual([GRANT]) answerTable(table, () => FAILED) await expect(useAuthStore.getState().reloadAccess()).resolves.toBeUndefined() const s = useAuthStore.getState() expect(s.catalogGrantsStatus).toBe('failed') expect(s.catalogGrants).toEqual([]) expect(s.roles).toEqual(['admin']) expect(s.profile).toEqual(before.profile) expect(s.workspace).toEqual({ status: 'ready', id: 'ws-1' }) }, ) it('ends failed and resolves without a user', async () => { useAuthStore.setState({ catalogGrants: [], catalogGrantsStatus: 'ready' }) await expect(useAuthStore.getState().reloadAccess()).resolves.toBeUndefined() expect(useAuthStore.getState().catalogGrantsStatus).toBe('failed') }) it('drops a late answer once another account signed in', async () => { await signedIn() const releases: Array<(a: Answer) => void> = [] answerTable( 'anatomical_catalog_grants', () => new Promise((resolve) => releases.push(resolve)), ) const reload = useAuthStore.getState().reloadAccess() await flush() fake.emit('SIGNED_IN', fakeSession(fakeUser({ id: 'user-2' }))) releases.forEach((release) => release({ data: [GRANT], error: null })) await reload await flush() expect(useAuthStore.getState().catalogGrants).toEqual([]) expect(useAuthStore.getState().roles).not.toEqual(['owner']) expect(useAuthStore.getState().user?.id).toBe('user-2') }) }) it('updateProfile writes the row and keeps the store in sync', async () => { stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await useAuthStore.getState().updateProfile({ first_name: 'Alice' }) expect(useAuthStore.getState().profile?.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 () => { stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await useAuthStore.getState().signOut() expect(fake.auth.signOut).toHaveBeenCalled() expect(useAuthStore.getState().status).toBe('signed_out') }) describe('personal workspace', () => { it('is read with the account and ready by its id', async () => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) expect(useAuthStore.getState().workspace).toEqual({ status: 'loading' }) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1', }) }) it('is missing when RLS returns no row for an active, confirmed account', async () => { stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'missing' }) }) it('tells a deactivated profile and an unconfirmed email apart, without asking for the workspace', async () => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] fake.tables.profiles = [fakeProfile({ active: false })] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'inactive' }) fake.tables.profiles = [fakeProfile()] fake.emit( 'SIGNED_IN', fakeSession(fakeUser({ id: 'user-1', email_confirmed_at: undefined })), ) fake.emit( 'USER_UPDATED', fakeSession(fakeUser({ email_confirmed_at: undefined })), ) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'unconfirmed', }) }) it('marks the own grants failed when the account itself cannot be read', async () => { const from = fake.client.from.bind(fake.client) // Any chain on profile_roles answers an error, as a dropped request would. const failed: unknown = new Proxy(() => undefined, { get: (_, key) => key === 'then' ? (resolve: (v: unknown) => void) => resolve({ data: null, error: { code: '', message: 'FetchError' }, status: 0 }) : () => failed, }) ;(fake.client as unknown as { from: (t: string) => unknown }).from = (table: string) => table === 'profile_roles' ? failed : from(table as never) stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().catalogGrantsStatus).toBe('failed') expect(useAuthStore.getState().catalogGrants).toEqual([]) }) it('reports a failed read as an error kind and reads again on refresh', async () => { const from = fake.client.from.bind(fake.client) let failing = true ;(fake.client as unknown as { from: (t: string) => unknown }).from = ( table: string, ) => table === 'workspaces' && failing ? { select: () => ({ eq: () => ({ maybeSingle: async () => ({ data: null, error: { code: '', message: 'FetchError' }, status: 0, }), }), }), } : from(table as never) fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'error', failure: 'network', }) failing = false await useAuthStore.getState().refreshWorkspace() expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1', }) }) it('drops the previous account at once on a change of account, and ignores its late answers', async () => { fake.tables.workspaces = [ { id: 'ws-1', personal_user_id: 'user-1' }, { id: 'ws-2', personal_user_id: 'user-2' }, ] fake.tables.profiles = [ fakeProfile(), fakeProfile({ id: 'user-2', display_name: 'Bob Local' }), ] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1', }) // Account 1's next load is held back, then answers after account 2 signed in. let release: () => void = () => undefined const held = new Promise((resolve) => (release = resolve)) const from = fake.client.from.bind(fake.client) ;(fake.client as unknown as { from: (t: string) => unknown }).from = ( table: string, ) => { const query = from(table as never) as unknown as { maybeSingle: () => Promise } const original = query.maybeSingle query.maybeSingle = async () => { const answer = (await original()) as { data: { id?: string } | null } if (table === 'profiles' && answer.data?.id === 'user-1') await held return answer } return query } fake.emit('USER_UPDATED', fakeSession()) await flush() fake.emit( 'SIGNED_IN', fakeSession(fakeUser({ id: 'user-2', email: 'bob@example.test' })), ) const switched = useAuthStore.getState() expect(switched.profile).toBeNull() expect(switched.workspace).toEqual({ status: 'loading' }) await flush() await flush() expect(useAuthStore.getState().profile?.display_name).toBe('Bob Local') expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-2', }) release() await flush() await flush() expect(useAuthStore.getState().profile?.display_name).toBe('Bob Local') expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-2', }) }) it('keeps a ready workspace on screen while the same account is read again', async () => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() const seen: string[] = [] const unsubscribe = useAuthStore.subscribe((s) => seen.push(s.workspace.status)) fake.emit('USER_UPDATED', fakeSession()) await flush() await flush() unsubscribe() expect(seen).not.toContain('loading') expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1' }) }) it('forgets the workspace on sign-out', async () => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) await flush() await flush() fake.emit('SIGNED_OUT', null) expect(useAuthStore.getState().workspace).toEqual({ status: 'idle' }) }) }) })