Files
faunosteo/apps/app/tests/unit/state.authStore.test.ts
bchanot e1c1980949 fix(app): a re-read of the same account keeps its workspace on screen
USER_UPDATED (or a retry) set the workspace back to loading, which unmounted
the client routes and lost an open form's typed values. A ready workspace now
stays until the answer; found by the V1-1.5 security audit.
2026-10-26 02:08:25 +01:00

328 lines
11 KiB
TypeScript

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 },
}
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('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('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<void>((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<unknown>
}
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' })
})
})
})