/** * V1-2.5 setup of the shell suites: platform roles, catalogue rights and TOTP * factors of the fictitious accounts, written the way the sandbox suites do * (packages/supabase/tests/sandbox/{sheet-fixtures,mfa}.ts): roles through the * operator path, grants as postgres, a factor enrolled and verified on the * real GoTrue with the account's own password session. What a test proves * goes through the page; the TOTP secrets stay in the test's memory. */ import type { Dict } from '@/i18n/types' import type { Locator, Page } from '@playwright/test' import { enrolTotp, refusal, verifyTotp, } from '../../../../packages/supabase/tests/sandbox/mfa' import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack' import { currentCode } from '../../../../packages/supabase/tests/sandbox/totp' import { expect, test } from './browser' import { capturedId } from './records' import type { SandboxAccount } from './sandbox' export type GrantKind = | 'catalog_reader' | 'sheet_editor' | 'sheet_reviewer' | 'sheet_publisher' /** The bootstrap path of the owner role (no JWT), as `private.assign_platform_role` allows postgres. */ export async function assignRole( account: SandboxAccount, role: 'owner' | 'admin', ): Promise { await sql( `select private.assign_platform_role(null, '${account.id}', '${role}')`, ) } /** A right granted earlier by the owner (a prior action, written as postgres); resolves with its id. */ export async function seedGrant( account: SandboxAccount, kind: GrantKind, ): Promise { const note = kind === 'catalog_reader' ? 'null' : "'sandbox'" const id = capturedId(account.id) return sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) values ('${id}', '${kind}', 'sandbox', ${note}, '${id}') returning id`) } /** A password session of the account on GoTrue: always aal1. */ export async function passwordToken(account: SandboxAccount): Promise { const response = await fetch(`${stack.authUrl}/token?grant_type=password`, { method: 'POST', headers: { apikey: stack.anonKey, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: account.email, password: account.password }), }) const body = (await response.json()) as { access_token?: string } if (!body.access_token) throw new Error(`sandbox sign-in: HTTP ${response.status}`) return body.access_token } /** * Records a retry on the running test; outside a test (the global setup) it goes to the * console, where `test.info()` would throw. */ function noteRetry(type: string, description: string): void { try { test.info().annotations.push({ type, description }) } catch { console.log(`${type}: ${description}`) } } /** * A verified TOTP factor enrolled by the account itself through the GoTrue * API (as its authenticator app would be set up); resolves with its secret. */ export async function enrolVerifiedFactor( account: SandboxAccount, name = 'Téléphone', ): Promise { const token = await passwordToken(account) const enrolment = await enrolTotp(token, name) if (!enrolment.factor) throw new Error(`sandbox enrol: ${refusal(enrolment)}`) let verified = await verifyTotp(token, enrolment.factor) // The HTTP 500 of the sweep (see `STEP_UP_ATTEMPTS`) is tried once more. if (verified.status >= 500) { noteRetry('verify retried', `HTTP ${verified.status} from GoTrue verify`) verified = await verifyTotp(token, enrolment.factor) } if (verified.status !== 200) throw new Error(`sandbox verify: ${refusal(verified)}`) return enrolment.factor.secret } export { currentCode } /** Types a code from `secret` into the TOTP form inside `scope` and sends it. */ export async function enterCode( scope: Page | Locator, dict: Dict, secret: string, ): Promise { const field = scope.getByLabel(dict['mfa.code.label']) const code = await currentCode(secret) await field.fill(code) await expect(field).toHaveValue(code) await scope.getByRole('button', { name: dict['mfa.code.verify'] }).click() } /** The assurance level of the session the page holds (the access token's `aal` claim). */ export function sessionAal(page: Page): Promise { return page.evaluate(() => { const key = Object.keys(localStorage).find((k) => /^sb-.*-auth-token$/.test(k), ) const stored = key ? localStorage.getItem(key) : null if (!stored) return null const token = (JSON.parse(stored) as { access_token?: string }).access_token const payload = token?.split('.')[1] if (!payload) return null const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/')) return (JSON.parse(json) as { aal?: string }).aal ?? null }) } /** The step-up page of /app/admin/* (RequireAdmin at aal1, with a verified factor). */ export const stepUpHeading = (page: Page, dict: Dict) => page .getByRole('main') .getByRole('heading', { level: 1, name: dict['admin.step_up.title'] }) /** * GoTrue answers some TOTP verifies HTTP 500 `unexpected_failure` under the eight-worker * sweep (gate final.log, BLK-015 family): the step-up then shows the network or the * unavailable failure (supabase-js reads that 500 as a retryable fetch error). The setup * tries again from a reloaded page, at most this many times in all; a refused code * (`invalid_code`) is never retried. */ const STEP_UP_ATTEMPTS = 3 /** The failures of the step-up form that a server or transport fault shows. */ const transientFailure = (main: Locator, dict: Dict) => main .getByText(dict['mfa.failure.unavailable']) .or(main.getByText(dict['mfa.failure.network'])) /** One code sent; resolves once the gate opened (false) or said the server failed (true). */ async function sendStepUpCode(page: Page, dict: Dict, secret: string) { const heading = stepUpHeading(page, dict) const main = page.getByRole('main') const unavailable = transientFailure(main, dict) await expect(heading).toBeVisible() // The gate settles its reads before the code is typed (a re-check remounts the form). await page.waitForLoadState('networkidle') await enterCode(main, dict, secret) await expect(async () => { const settled = (await heading.isHidden()) || (await unavailable.isVisible()) expect(settled).toBe(true) }).toPass({ timeout: 10_000 }) return unavailable.isVisible() } /** Completes the administration step-up; the page behind it then renders. */ export async function stepUpAdmin(page: Page, dict: Dict, secret: string) { for (let attempt = 1; ; attempt += 1) { const unavailable = await sendStepUpCode(page, dict, secret) if (!unavailable || attempt === STEP_UP_ATTEMPTS) break noteRetry( 'step-up retried', `attempt ${attempt}: GoTrue verify failed on the server`, ) await page.reload() } await expect(stepUpHeading(page, dict)).toBeHidden() } /** A text matched literally inside a RegExp. */ export const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') /** * The link of the sheets card to the full list: « Toutes les fiches officielles » * for zero or one sheet, « Voir les {count} fiches » from two (R3, D6), any number. */ export function allSheetsLink(scope: Page | Locator, dict: Dict): Locator { const seeAll = escaped(dict['admin.home.see_all']).replace( '\\{count\\}', '\\d+', ) const name = new RegExp( `^(${escaped(dict['admin.home.all_sheets'])}|${seeAll})$`, ) return scope.getByRole('link', { name }) }