diff --git a/apps/app/src/lib/id.ts b/apps/app/src/lib/id.ts index e66860e0..16e48667 100644 --- a/apps/app/src/lib/id.ts +++ b/apps/app/src/lib/id.ts @@ -11,3 +11,18 @@ export function generateId(): string { } return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}` } + +/** + * A random version 4 uuid, also on an origin that is not a secure context + * (the DEV origin is plain HTTP on the LAN, where crypto.randomUUID is + * missing but crypto.getRandomValues is not). Used for request ids the + * database stores as uuid. + */ +export function generateUuid(): string { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID() + const bytes = crypto.getRandomValues(new Uint8Array(16)) + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` +} diff --git a/apps/app/src/state/authStore.ts b/apps/app/src/state/authStore.ts index f688ff30..7669c1fe 100644 --- a/apps/app/src/state/authStore.ts +++ b/apps/app/src/state/authStore.ts @@ -13,7 +13,10 @@ import { type AvatarState, downloadAvatar, fetchOwnAvatarState, + fetchPersonalWorkspaceId, + classifyRecordError, type FaunosteoClient, + type RecordFailureKind, type OwnProfilePatch, type PlatformRole, type Profile, @@ -26,6 +29,21 @@ import { getSupabaseClient } from '@/lib/supabase' */ export type AuthStatus = 'loading' | 'unavailable' | 'signed_out' | 'signed_in' +/** + * The account's personal workspace (contract ยง4): created by the server at + * sign-up, read once with the account, never created here. RLS hides it from + * a deactivated profile and an unconfirmed email, told apart before reading; + * `missing` is an active, confirmed account whose workspace does not answer. + */ +export type WorkspaceState = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'ready'; id: string } + | { status: 'inactive' } + | { status: 'unconfirmed' } + | { status: 'missing' } + | { status: 'error'; failure: RecordFailureKind } + export interface AuthState { status: AuthStatus session: Session | null @@ -41,9 +59,12 @@ export interface AuthState { avatar: AvatarState | null /** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */ avatarUrl: string | null + workspace: WorkspaceState /** Subscribes to the client; returns the unsubscribe. Safe to call twice. */ start: () => () => void refreshAccount: () => Promise + /** Reads the personal workspace again (after a failure). */ + refreshWorkspace: () => Promise updateProfile: (patch: OwnProfilePatch) => Promise /** Re-reads the own rows; downloads the clean photo when it changed. */ refreshAvatar: () => Promise @@ -83,13 +104,53 @@ async function syncAvatar(client: FaunosteoClient, user: User, set: Set, get: Ge return avatar } +/** A setter that drops the patch once another account has signed in: no late response leaks across accounts. */ +function setForUser(user: User, set: Set, get: Get): Set { + return (patch) => { + if (get().user?.id === user.id) set(patch) + } +} + +async function loadWorkspace( + client: FaunosteoClient, + user: User, + profile: Profile | null, + set: Set, +) { + if (!user.email_confirmed_at) return set({ workspace: { status: 'unconfirmed' } }) + if (profile && !profile.active) return set({ workspace: { status: 'inactive' } }) + set({ workspace: { status: 'loading' } }) + try { + const id = await fetchPersonalWorkspaceId(client, user.id) + set({ workspace: id ? { status: 'ready', id } : { status: 'missing' } }) + } catch (error) { + set({ workspace: { status: 'error', failure: classifyRecordError(error) } }) + } +} + async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: Get) { + const setOwn = setForUser(user, set, get) const [profile, roles] = await Promise.all([ fetchOwnProfile(client, user.id), fetchOwnPlatformRoles(client, user.id), ]) - set({ profile, roles }) - await syncAvatar(client, user, set, get).catch(() => set({ avatar: null })) + setOwn({ profile, roles }) + await Promise.all([ + loadWorkspace(client, user, profile, setOwn), + syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })), + ]) +} + +/** Everything the store holds about one account: dropped together on sign-out and on a change of account. */ +function accountReset(get: Get): Partial { + revokeUrl(get().avatarUrl) + return { + profile: null, + roles: [], + avatar: null, + avatarUrl: null, + workspace: { status: 'idle' }, + } } /** @@ -105,30 +166,33 @@ function applyAuthEvent( ) { const previousUserId = get().user?.id if (event === 'SIGNED_OUT' || session === null) { - revokeUrl(get().avatarUrl) set({ + ...accountReset(get), status: 'signed_out', session: null, user: null, - profile: null, - roles: [], recovery: false, - avatar: null, - avatarUrl: null, }) return } + const changedAccount = session.user.id !== previousUserId const patch: Partial = { + // Another account: nothing of the previous one stays on screen while the new one loads. + ...(changedAccount ? { ...accountReset(get), workspace: { status: 'loading' } } : {}), status: 'signed_in', session, user: session.user, } if (event === 'PASSWORD_RECOVERY') patch.recovery = true set(patch) - if (session.user.id !== previousUserId || event === 'USER_UPDATED') { + if (changedAccount || event === 'USER_UPDATED') { setTimeout(() => { - void loadAccount(client, session.user, set, get).catch(() => { - set({ profile: null, roles: [] }) + void loadAccount(client, session.user, set, get).catch((error: unknown) => { + setForUser(session.user, set, get)({ + profile: null, + roles: [], + workspace: { status: 'error', failure: classifyRecordError(error) }, + }) }) }, 0) } @@ -155,6 +219,7 @@ export const useAuthStore = create((set, get) => ({ urlFailure: null, avatar: null, avatarUrl: null, + workspace: { status: 'idle' }, start: () => { const client = getSupabaseClient() @@ -175,6 +240,11 @@ export const useAuthStore = create((set, get) => ({ await loadAccount(requireClient(), requireUser(get().user), set, get) }, + refreshWorkspace: async () => { + const user = requireUser(get().user) + await loadWorkspace(requireClient(), user, get().profile, setForUser(user, set, get)) + }, + refreshAvatar: async () => { return syncAvatar(requireClient(), requireUser(get().user), set, get) }, @@ -197,16 +267,12 @@ export const useAuthStore = create((set, get) => ({ signOut: async () => { const clear = () => { - revokeUrl(get().avatarUrl) set({ + ...accountReset(get), status: 'signed_out', session: null, user: null, - profile: null, - roles: [], recovery: false, - avatar: null, - avatarUrl: null, }) } try { diff --git a/apps/app/tests/unit/lib.id.test.ts b/apps/app/tests/unit/lib.id.test.ts index 1dfd464d..840c6178 100644 --- a/apps/app/tests/unit/lib.id.test.ts +++ b/apps/app/tests/unit/lib.id.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { generateId } from '@/lib/id' +import { generateId, generateUuid } from '@/lib/id' describe('generateId', () => { it('returns a non-empty string', () => { @@ -12,3 +12,23 @@ describe('generateId', () => { expect(a).not.toBe(b) }) }) + +describe('generateUuid', () => { + const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + + it('returns a version 4 uuid', () => { + expect(generateUuid()).toMatch(V4) + }) + + it('still returns one where crypto.randomUUID is missing (plain HTTP on the LAN)', () => { + const original = crypto.randomUUID + Object.defineProperty(crypto, 'randomUUID', { value: undefined, configurable: true }) + try { + const ids = new Set(Array.from({ length: 50 }, () => generateUuid())) + expect([...ids].every((id) => V4.test(id))).toBe(true) + expect(ids.size).toBe(50) + } finally { + Object.defineProperty(crypto, 'randomUUID', { value: original, configurable: true }) + } + }) +}) diff --git a/apps/app/tests/unit/state.authStore.test.ts b/apps/app/tests/unit/state.authStore.test.ts index 7a499b16..54d47bda 100644 --- a/apps/app/tests/unit/state.authStore.test.ts +++ b/apps/app/tests/unit/state.authStore.test.ts @@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createFakeSupabase, fakeAssetRow, + fakeProfile, fakeSession, + fakeUser, flush, type FakeSupabase, } from '../helpers/fakeSupabase' @@ -25,6 +27,7 @@ const INITIAL = { urlFailure: null, avatar: null, avatarUrl: null, + workspace: { status: 'idle' as const }, } let fake: FakeSupabase @@ -112,10 +115,18 @@ describe('authStore', () => { 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.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') + 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 () => { @@ -129,7 +140,10 @@ describe('authStore', () => { expect(useAuthStore.getState().avatar?.clean).toBeNull() await useAuthStore.getState().refreshAvatar() fake.emit('SIGNED_OUT', null) - expect(useAuthStore.getState()).toMatchObject({ avatar: null, avatarUrl: null }) + expect(useAuthStore.getState()).toMatchObject({ + avatar: null, + avatarUrl: null, + }) }) it('signOut calls the client and resets the state', async () => { @@ -139,4 +153,159 @@ describe('authStore', () => { 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((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('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' }) + }) + }) })