Nav hint from own grants and roles (never a control); RequireCatalog, RequireAdmin (no admin read before aal2), Accès non autorisé page, placeholder routes; TOTP factor list, enrolment with QR and one-time secret, removal, inline step-up for aal2 actions, step-up in password reset; auth kind aal2_required. App 601, e2e:ui 227.
258 lines
7.8 KiB
TypeScript
258 lines
7.8 KiB
TypeScript
/**
|
|
* In-memory stand-in for the parts of the Supabase client the identity and
|
|
* files steps use: auth events, profile select/update, profile_roles and
|
|
* assets selects, rpc, storage upload / download. Tests mock
|
|
* `@/lib/supabase` to hand this object out.
|
|
*/
|
|
import { vi } from 'vitest'
|
|
import type {
|
|
AssetRow,
|
|
AuthChangeEvent,
|
|
FaunosteoClient,
|
|
Profile,
|
|
Session,
|
|
User,
|
|
} from '@faunosteo/supabase'
|
|
|
|
type Listener = (event: AuthChangeEvent, session: Session | null) => void
|
|
type Row = Record<string, unknown>
|
|
|
|
export function fakeUser(patch: Partial<User> = {}): User {
|
|
return {
|
|
id: 'user-1',
|
|
aud: 'authenticated',
|
|
email: 'alice@example.test',
|
|
email_confirmed_at: '2026-10-11T10:00:00Z',
|
|
created_at: '2026-10-01T10:00:00Z',
|
|
app_metadata: {},
|
|
user_metadata: {},
|
|
...patch,
|
|
} as User
|
|
}
|
|
|
|
export function fakeSession(user: User = fakeUser()): Session {
|
|
return {
|
|
access_token: 'at',
|
|
refresh_token: 'rt',
|
|
token_type: 'bearer',
|
|
expires_in: 3600,
|
|
user,
|
|
} as Session
|
|
}
|
|
|
|
export function fakeProfile(patch: Partial<Profile> = {}): Profile {
|
|
return {
|
|
id: 'user-1',
|
|
display_name: 'Alice Local',
|
|
first_name: null,
|
|
last_name: null,
|
|
phone: null,
|
|
phone_verified_at: null,
|
|
locale: 'fr',
|
|
timezone: 'Europe/Paris',
|
|
active: true,
|
|
practice_name: null,
|
|
professional_title: null,
|
|
siret: null,
|
|
created_at: '2026-10-01T10:00:00Z',
|
|
updated_at: '2026-10-01T10:00:00Z',
|
|
...patch,
|
|
}
|
|
}
|
|
|
|
export function fakeAssetRow(patch: Partial<AssetRow> = {}): AssetRow {
|
|
return {
|
|
id: 'asset-1',
|
|
owner_id: 'user-1',
|
|
kind: 'profile_avatar',
|
|
bucket_id: 'avatars',
|
|
object_key: 'profiles/user-1/asset-1/avatar.webp',
|
|
status: 'clean',
|
|
declared_mime: 'image/jpeg',
|
|
declared_size: 1000,
|
|
byte_size: 900,
|
|
sha256: null,
|
|
rejection_reason: null,
|
|
created_at: '2026-10-13T10:00:00Z',
|
|
updated_at: '2026-10-13T10:00:00Z',
|
|
...patch,
|
|
}
|
|
}
|
|
|
|
/** Minimal PostgREST builder: filters, order, limit, then select / update, awaitable. */
|
|
function builder(tables: Record<string, Row[]>, table: string) {
|
|
const filters: Array<(row: Row) => boolean> = []
|
|
let patch: Row | null = null
|
|
let order: { col: string; ascending: boolean } | null = null
|
|
let max: number | null = null
|
|
const rows = () => {
|
|
let hit = (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
|
|
if (order) {
|
|
const { col, ascending } = order
|
|
hit = [...hit].sort((a, b) =>
|
|
(String(a[col]) < String(b[col]) ? -1 : String(a[col]) > String(b[col]) ? 1 : 0) *
|
|
(ascending ? 1 : -1),
|
|
)
|
|
}
|
|
return max === null ? hit : hit.slice(0, max)
|
|
}
|
|
const apply = () => {
|
|
if (!patch) return rows()
|
|
const hit = rows()
|
|
hit.forEach((r) => Object.assign(r, patch))
|
|
return hit
|
|
}
|
|
const api = {
|
|
select: () => api,
|
|
update: (values: Row) => {
|
|
patch = values
|
|
return api
|
|
},
|
|
eq: (col: string, value: unknown) => {
|
|
filters.push((r) => r[col] === value)
|
|
return api
|
|
},
|
|
is: (col: string, value: unknown) => {
|
|
filters.push((r) => r[col] === value)
|
|
return api
|
|
},
|
|
in: (col: string, values: unknown[]) => {
|
|
filters.push((r) => values.includes(r[col]))
|
|
return api
|
|
},
|
|
order: (col: string, opts?: { ascending?: boolean }) => {
|
|
order = { col, ascending: opts?.ascending ?? true }
|
|
return api
|
|
},
|
|
limit: (n: number) => {
|
|
max = n
|
|
return api
|
|
},
|
|
maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }),
|
|
single: async () => {
|
|
const [first] = apply()
|
|
return first
|
|
? { data: first, error: null }
|
|
: { data: null, error: { message: 'no row', code: 'PGRST116' } }
|
|
},
|
|
then: (resolve: (v: { data: Row[]; error: null }) => void) =>
|
|
resolve({ data: apply(), error: null }),
|
|
}
|
|
return api
|
|
}
|
|
|
|
export interface FakeSupabase {
|
|
client: FaunosteoClient
|
|
tables: Record<string, Row[]>
|
|
emit: (event: AuthChangeEvent, session: Session | null) => void
|
|
/** Recorded rpc calls; program results with `rpcResults[name]`. */
|
|
rpcCalls: Array<[string, unknown]>
|
|
rpcResults: Record<string, { data?: unknown; error?: unknown } | (() => { data?: unknown; error?: unknown })>
|
|
storage: {
|
|
upload: ReturnType<typeof vi.fn>
|
|
download: ReturnType<typeof vi.fn>
|
|
}
|
|
auth: {
|
|
initialize: ReturnType<typeof vi.fn>
|
|
signInWithPassword: ReturnType<typeof vi.fn>
|
|
signUp: ReturnType<typeof vi.fn>
|
|
signOut: ReturnType<typeof vi.fn>
|
|
updateUser: ReturnType<typeof vi.fn>
|
|
resetPasswordForEmail: ReturnType<typeof vi.fn>
|
|
signInWithOAuth: ReturnType<typeof vi.fn>
|
|
mfa: {
|
|
listFactors: ReturnType<typeof vi.fn>
|
|
enroll: ReturnType<typeof vi.fn>
|
|
challengeAndVerify: ReturnType<typeof vi.fn>
|
|
unenroll: ReturnType<typeof vi.fn>
|
|
getAuthenticatorAssuranceLevel: ReturnType<typeof vi.fn>
|
|
}
|
|
}
|
|
}
|
|
|
|
/** A GoTrue factor row as `listFactors().all` returns it. */
|
|
export function fakeFactor(patch: Record<string, unknown> = {}) {
|
|
return {
|
|
id: 'factor-1',
|
|
friendly_name: 'Phone',
|
|
factor_type: 'totp',
|
|
status: 'verified',
|
|
created_at: '2026-11-01T10:00:00Z',
|
|
updated_at: '2026-11-01T10:00:00Z',
|
|
...patch,
|
|
}
|
|
}
|
|
|
|
/** Programs the account's factors (listFactors) and the session level. */
|
|
export function setMfa(
|
|
fake: FakeSupabase,
|
|
factors: Array<Record<string, unknown>>,
|
|
currentLevel: 'aal1' | 'aal2' = 'aal1',
|
|
) {
|
|
fake.auth.mfa.listFactors.mockResolvedValue({ data: { all: factors, totp: [] }, error: null })
|
|
const nextLevel = factors.some((f) => f.status === 'verified') ? 'aal2' : 'aal1'
|
|
fake.auth.mfa.getAuthenticatorAssuranceLevel.mockResolvedValue({
|
|
data: { currentLevel, nextLevel, currentAuthenticationMethods: [] },
|
|
error: null,
|
|
})
|
|
}
|
|
|
|
export function createFakeSupabase(
|
|
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [], assets: [] },
|
|
): FakeSupabase {
|
|
tables.assets ??= []
|
|
const listeners: Listener[] = []
|
|
const rpcCalls: Array<[string, unknown]> = []
|
|
const rpcResults: FakeSupabase['rpcResults'] = {}
|
|
const storage = {
|
|
upload: vi.fn(async () => ({ data: null, error: null })),
|
|
download: vi.fn(async () => ({ data: new Blob([new Uint8Array([82, 73, 70, 70])]), error: null })),
|
|
}
|
|
const auth = {
|
|
initialize: vi.fn(async () => ({ error: null })),
|
|
onAuthStateChange: vi.fn((cb: Listener) => {
|
|
listeners.push(cb)
|
|
return { data: { subscription: { unsubscribe: vi.fn() } } }
|
|
}),
|
|
signInWithPassword: vi.fn(),
|
|
signUp: vi.fn(),
|
|
signOut: vi.fn(async () => ({ error: null })),
|
|
updateUser: vi.fn(),
|
|
resetPasswordForEmail: vi.fn(),
|
|
signInWithOAuth: vi.fn(),
|
|
mfa: {
|
|
listFactors: vi.fn(async () => ({ data: { all: [], totp: [] }, error: null })),
|
|
enroll: vi.fn(),
|
|
challengeAndVerify: vi.fn(async () => ({ data: {}, error: null })),
|
|
unenroll: vi.fn(async () => ({ data: {}, error: null })),
|
|
getAuthenticatorAssuranceLevel: vi.fn(async () => ({
|
|
data: { currentLevel: 'aal1', nextLevel: 'aal1', currentAuthenticationMethods: [] },
|
|
error: null,
|
|
})),
|
|
},
|
|
}
|
|
const client = {
|
|
auth,
|
|
from: (table: string) => builder(tables, table),
|
|
rpc: async (name: string, args?: unknown) => {
|
|
rpcCalls.push([name, args])
|
|
const entry = rpcResults[name]
|
|
const result = typeof entry === 'function' ? entry() : (entry ?? {})
|
|
return { data: result.data ?? null, error: result.error ?? null }
|
|
},
|
|
storage: { from: () => storage },
|
|
} as unknown as FaunosteoClient
|
|
return {
|
|
client,
|
|
tables,
|
|
auth,
|
|
rpcCalls,
|
|
rpcResults,
|
|
storage,
|
|
emit: (event, session) => listeners.forEach((cb) => cb(event, session)),
|
|
}
|
|
}
|
|
|
|
/** Resolves once the store has run its deferred account load. */
|
|
export const flush = () => new Promise((r) => setTimeout(r, 0))
|