Files
faunosteo/apps/app/src/state/authStore.ts
T
bchanot f04bfdd040 fix(app): creation page waits for own grants; e2e never prints setup keys
Delta verifier: two remaining setup-key assertions now booleans. Its observation: the editor rule read grants before they loaded; authStore.catalogGrantsStatus (loading, ready, failed): the page waits, and a failed read leaves the decision to the server. App 654, e2e:ui 227, admin shell spec 14 + 6 skipped.
2026-11-02 18:33:57 +01:00

309 lines
9.8 KiB
TypeScript

import { create } from 'zustand'
import {
AuthFailure,
type AuthChangeEvent,
type Session,
type User,
classifyAuthError,
fetchOwnPlatformRoles,
fetchOwnProfile,
signOut as signOutRequest,
updateOwnProfile,
type AuthFailureKind,
type AvatarState,
downloadAvatar,
fetchOwnAvatarState,
fetchPersonalWorkspaceId,
listOwnCatalogGrants,
type OwnCatalogGrant,
classifyRecordError,
type FaunosteoClient,
type RecordFailureKind,
type OwnProfilePatch,
type PlatformRole,
type Profile,
} from '@faunosteo/supabase'
import { getSupabaseClient } from '@/lib/supabase'
/**
* unavailable = no Supabase configured (local-only deployment); loading until
* the client has read the persisted session and the URL (OAuth / email links).
*/
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
user: User | null
/** Null until loaded, or when the profile row is missing. */
profile: Profile | null
roles: PlatformRole[]
/** Set by a password-recovery link until the new password is saved. */
recovery: boolean
/** Failure while reading the URL (expired link, bad code): shown by the landing routes. */
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
workspace: WorkspaceState
/**
* The account's own catalogue grant rows, for the navigation hint only
* (contract §5.3, `navigationHint`): never a control, the server decides.
* Empty until loaded and when the read fails.
*/
catalogGrants: OwnCatalogGrant[]
/** Whether `catalogGrants` is read yet: a display rule waits for `ready`, and a `failed` read leaves the decision to the server. */
catalogGrantsStatus: 'loading' | 'ready' | 'failed'
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void
refreshAccount: () => Promise<void>
/** Reads the personal workspace again (after a failure). */
refreshWorkspace: () => Promise<void>
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>
clearRecovery: () => void
}
type Set = (patch: Partial<AuthState>) => void
type Get = () => AuthState
/** 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
}
/** 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,
get: Get,
) {
if (!user.email_confirmed_at) return set({ workspace: { status: 'unconfirmed' } })
if (profile && !profile.active) return set({ workspace: { status: 'inactive' } })
// A re-read (USER_UPDATED, retry) keeps a ready workspace on screen until the
// answer, so the routes under it, an open form included, stay mounted.
if (get().workspace.status !== 'ready') 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),
])
setOwn({ profile, roles })
await Promise.all([
loadWorkspace(client, user, profile, setOwn, get),
syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })),
listOwnCatalogGrants(client, user.id)
.then((catalogGrants) => setOwn({ catalogGrants, catalogGrantsStatus: 'ready' }))
.catch(() => setOwn({ catalogGrants: [], catalogGrantsStatus: 'failed' })),
])
}
/** Everything the store holds about one account: dropped together on sign-out and on a change of account. */
function accountReset(get: Get): Partial<AuthState> {
revokeUrl(get().avatarUrl)
return {
profile: null,
roles: [],
avatar: null,
avatarUrl: null,
workspace: { status: 'idle' },
catalogGrants: [],
catalogGrantsStatus: 'loading',
}
}
/**
* Applies one GoTrue event. The account load runs outside the callback: the
* client serialises its callbacks, awaiting a request inside one deadlocks.
*/
function applyAuthEvent(
client: FaunosteoClient,
event: AuthChangeEvent,
session: Session | null,
set: Set,
get: Get,
) {
const previousUserId = get().user?.id
if (event === 'SIGNED_OUT' || session === null) {
set({
...accountReset(get),
status: 'signed_out',
session: null,
user: null,
recovery: false,
})
return
}
const changedAccount = session.user.id !== previousUserId
const patch: Partial<AuthState> = {
// 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 (changedAccount || event === 'USER_UPDATED') {
setTimeout(() => {
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)
}
}
function requireClient(): FaunosteoClient {
const client = getSupabaseClient()
if (!client) throw new AuthFailure('unknown')
return client
}
function requireUser(user: User | null): User {
if (!user) throw new AuthFailure('session_expired')
return user
}
export const useAuthStore = create<AuthState>((set, get) => ({
status: 'loading',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
avatar: null,
avatarUrl: null,
workspace: { status: 'idle' },
catalogGrants: [],
catalogGrantsStatus: 'loading',
start: () => {
const client = getSupabaseClient()
if (!client) {
set({ status: 'unavailable' })
return () => undefined
}
void client.auth.initialize().then(({ error }) => {
if (error) set({ urlFailure: classifyAuthError(error) })
})
const { data } = client.auth.onAuthStateChange((event, session) => {
applyAuthEvent(client, event, session, set, get)
})
return () => data.subscription.unsubscribe()
},
refreshAccount: async () => {
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), 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) => {
const user = requireUser(get().user)
const profile = await updateOwnProfile(requireClient(), user.id, patch)
set({ profile })
return profile
},
signOut: async () => {
const clear = () => {
set({
...accountReset(get),
status: 'signed_out',
session: null,
user: null,
recovery: false,
})
}
try {
// auth-js clears the local session even when the server call fails.
await signOutRequest(requireClient())
} finally {
// SIGNED_OUT also arrives through the subscription; this keeps the UI honest if it does not.
clear()
}
},
clearRecovery: () => set({ recovery: false }),
}))