/** * The V1-2.5 access layer through real supabase-js against the throwaway * stack (real GoTrue v2.197.0, PostgREST, Storage, PostgreSQL): the TOTP * wrappers (enrol, verify to aal2, the aal1 refusals of IDENTITY.md ยง4.1, * removal), the M7 admin reads at aal2 and their aal1 refusal, species * creation by an editor, the account lookup by the owner, the catalogue * reads. Run through `pnpm db:sandbox test tests/sandbox/sheets-admin.sandbox.ts`; * the accounts and the species it creates are removed afterwards, so it runs * again on the same stack. */ import { randomUUID } from 'node:crypto' import { createClient } from '@supabase/supabase-js' import { MfaFailure, SheetFailure, assuranceLevel, createSheetWorkingCopy, createSpecies, downloadSheetDrawing, enrollTotp, getOfficialSheetAdmin, listCatalogGrants, listCatalogSpecies, listOfficialSheetsAdmin, listOwnCatalogGrants, listSheetVersions, listTotpFactors, lookupCatalogAccount, unenrollFactor, updateInactiveSpecies, verifyTotp, type Database, type FaunosteoClient, } from '../../src' import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack' import { totpCode } from './totp' const BASE = 'http://sandbox.faunosteo.invalid' const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916' /** The browser client of the app, its requests replayed on the sandbox ports. */ function browserClient(): FaunosteoClient { const mapped: typeof fetch = (input, init) => { const url = String(input instanceof Request ? input.url : input) .replace(`${BASE}/auth/v1`, stack.authUrl) .replace(`${BASE}/rest/v1`, stack.restUrl) .replace(`${BASE}/storage/v1`, stack.storageUrl) return fetch(url, init) } return createClient(BASE, stack.anonKey, { auth: { persistSession: false, autoRefreshToken: false }, global: { fetch: mapped }, }) } /** A new password session of the account: always aal1. */ async function signedIn(account: Account): Promise { const client = browserClient() const { error } = await client.auth.signInWithPassword({ email: account.email, password: PASSWORD }) if (error) throw error return client } /** Enrols and verifies a TOTP factor through the wrappers; the client ends at aal2. */ async function stepUp(client: FaunosteoClient, name = 'device') { const enrolment = await enrollTotp(client, name) await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret)) return enrolment } async function kindOf(promise: Promise) { try { await promise return 'no failure' } catch (error) { if (error instanceof SheetFailure || error instanceof MfaFailure) return error.kind return `other: ${String(error)}` } } /** A code of the same length that is not the current one. */ const wrongCode = (secret: string) => totpCode(secret).replace(/.$/, (digit) => String((Number(digit) + 5) % 10)) const created: string[] = [] const species: string[] = [] async function account(tag: string, role: 'owner' | 'admin' | null = null): Promise { const a = await confirmedAccount(tag) created.push(a.id) if (role) await sql(`select private.assign_platform_role(null, '${a.id}', '${role}')`) return a } afterAll(async () => { if (species.length > 0) await sql(`delete from public.species where id in (${species.map((id) => `'${id}'`).join(', ')})`) if (created.length === 0) return const ids = created.map((id) => `'${id}'`).join(', ') // Grants are never deleted by design (guard trigger): the run's own rows are // removed with the triggers off for this transaction only, then the accounts. await sql(`begin; set local session_replication_role = replica; delete from public.anatomical_catalog_grants where user_id in (${ids}); set local session_replication_role = origin; delete from auth.users where id in (${ids}); commit;`) }) describe('TOTP wrappers on real GoTrue', () => { it('enrols, verifies to aal2, refuses the aal1 changes, removes', async () => { const a = await account('admin-mfa') const client = await signedIn(a) expect(await assuranceLevel(client)).toEqual({ current: 'aal1', next: 'aal1' }) const enrolment = await enrollTotp(client, 'Phone') expect(enrolment.qrCode.startsWith('data:image/svg+xml;utf-8,')).toBe(true) expect(enrolment.uri.startsWith('otpauth://totp/')).toBe(true) // supabase-js keeps unverified factors out of `totp`: the wrapper still lists them. expect(await listTotpFactors(client)).toEqual([ expect.objectContaining({ id: enrolment.factorId, friendlyName: 'Phone', status: 'unverified' }), ]) expect(await kindOf(verifyTotp(client, enrolment.factorId, wrongCode(enrolment.secret)))).toBe('invalid_code') await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret)) expect(await assuranceLevel(client)).toEqual({ current: 'aal2', next: 'aal2' }) expect((await listTotpFactors(client)).map((f) => f.status)).toEqual(['verified']) // A new password session is aal1: no second factor, no removal of the verified one. const aal1 = await signedIn(a) expect(await assuranceLevel(aal1)).toEqual({ current: 'aal1', next: 'aal2' }) expect(await kindOf(enrollTotp(aal1, 'Second'))).toBe('aal2_required') expect(await kindOf(unenrollFactor(aal1, enrolment.factorId))).toBe('aal2_required') expect(await kindOf(unenrollFactor(client, randomUUID()))).toBe('factor_not_found') await unenrollFactor(client, enrolment.factorId) expect(await listTotpFactors(client)).toEqual([]) }) }) describe('administration reads, species and account lookup', () => { let editor: Account let editorAal2: FaunosteoClient beforeAll(async () => { editor = await account('admin-editor', 'admin') await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values ('${editor.id}', 'sheet_editor', 'sandbox', 'sandbox', '${editor.id}')`) editorAal2 = await signedIn(editor) await stepUp(editorAal2) }) it('an editor reads the admin list and an overview at aal2, refused at aal1', async () => { const sheets = await listOfficialSheetsAdmin(editorAal2) expect(sheets.find((s) => s.sheet_id === HISTORICAL)).toMatchObject({ historical: true, working_copy: false }) const overview = await getOfficialSheetAdmin(editorAal2, HISTORICAL) expect(overview.versions.length).toBeGreaterThan(0) expect(await kindOf(getOfficialSheetAdmin(editorAal2, randomUUID()))).toBe('not_found') const aal1 = await signedIn(editor) expect(await kindOf(listOfficialSheetsAdmin(aal1))).toBe('rights.mfa') expect(await kindOf(getOfficialSheetAdmin(aal1, HISTORICAL))).toBe('rights.mfa') // The navigation hint reads the own rows at any level. expect(await listOwnCatalogGrants(aal1, editor.id)).toEqual([ { kind: 'sheet_editor', expires_at: null, revoked_at: null }, ]) }) it('an editor creates an inactive species and edits it', async () => { const id = `sbx-${randomUUID().slice(0, 8)}` species.push(id) expect(await createSpecies(editorAal2, { id, name_fr: 'Essai', name_en: 'Trial' })).toBe(id) expect(await updateInactiveSpecies(editorAal2, { id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900 })) .toBe(id) expect((await listCatalogSpecies(editorAal2)).find((s) => s.id === id)).toEqual({ id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900, active: false, }) expect(await kindOf(createSpecies(editorAal2, { id, name_fr: 'X', name_en: 'X' }))).toBe('species.exists') }) it('the working copy and the catalogue reads answer their closed kinds', async () => { const source = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${HISTORICAL}' order by version_number limit 1`) // A fresh sandbox has no working copy yet, so the first call may create it: both outcomes are valid. const name = () => `wc-${randomUUID().slice(0, 8)}` const first = await kindOf(createSheetWorkingCopy(editorAal2, source, name())) if (first === 'no failure') { expect(await kindOf(createSheetWorkingCopy(editorAal2, source, name()))).toBe('working_copy.exists') } else { expect(['working_copy.exists', 'working_copy.assets_missing']).toContain(first) } const versions = await listSheetVersions(editorAal2, HISTORICAL) expect(versions.every((v) => v.status === 'published' || v.status === 'deprecated')).toBe(true) expect(await kindOf(downloadSheetDrawing(editorAal2, 'f'.repeat(64)))).toBe('not_found') }) it('the owner looks an account up at aal2, refused at aal1', async () => { const owner = await account('admin-owner', 'owner') const ownerAal2 = await signedIn(owner) await stepUp(ownerAal2) expect(await lookupCatalogAccount(ownerAal2, editor.email.toUpperCase())).toEqual({ user_id: editor.id, display_name: expect.any(String), active: true, email_confirmed: true, verified_totp: true, platform_roles: ['admin'], }) expect(await kindOf(lookupCatalogAccount(ownerAal2, `none-${randomUUID()}@sandbox.local`))).toBe('not_found') expect((await listCatalogGrants(ownerAal2)).find((g) => g.user_id === editor.id)).toMatchObject({ kind: 'sheet_editor', state: 'active', effective: true, }) expect(await kindOf(lookupCatalogAccount(await signedIn(owner), editor.email))).toBe('rights.mfa') }) })