Files
faunosteo/apps/app/e2e/support/admin.ts
T
bchanot 4f6c0ba407 test(app): V1-2.5 browser journeys A0, A1, S1, P1 on the sandbox (J)
Owner bootstrap with two factors, step-up, rights; sheet creation; species activation seen by the animal form; catalogue reader with search, zone panel, withdrawn and archived versions; access per right; axe and widths 320-430 / 375 / desktop, FR and EN. Shell suite 108 passed, 6 skipped by design.
2026-11-02 17:44:14 +01:00

136 lines
5.1 KiB
TypeScript

/**
* 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,
verifyTotp,
} from '../../../../packages/supabase/tests/sandbox/mfa'
import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
import {
totpCode,
TOTP_STEP_SECONDS,
} from '../../../../packages/supabase/tests/sandbox/totp'
import { expect } from './browser'
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<void> {
await sql(
`select private.assign_platform_role(null, '${account.id}', '${role}')`,
)
}
/** A right granted earlier by the owner (a prior action, written as postgres). */
export async function seedGrant(
account: SandboxAccount,
kind: GrantKind,
): Promise<void> {
const note = kind === 'catalog_reader' ? 'null' : "'sandbox'"
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
values ('${account.id}', '${kind}', 'sandbox', ${note}, '${account.id}')`)
}
/** A password session of the account on GoTrue: always aal1. */
async function passwordToken(account: SandboxAccount): Promise<string> {
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
}
/**
* 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<string> {
const token = await passwordToken(account)
const enrolment = await enrolTotp(token, name)
if (!enrolment.factor)
throw new Error(`sandbox enrol: HTTP ${enrolment.status}`)
const verified = await verifyTotp(token, enrolment.factor)
if (verified.status !== 200)
throw new Error(`sandbox verify: HTTP ${verified.status}`)
return enrolment.factor.secret
}
/**
* A code the authenticator would show now, never one about to change: a code
* typed in its last seconds may reach GoTrue in the next step.
*/
export async function currentCode(secret: string): Promise<string> {
const step = TOTP_STEP_SECONDS * 1000
const left = step - (Date.now() % step)
if (left < 3000)
await new Promise((resolve) => setTimeout(resolve, left + 200))
return totpCode(secret)
}
/** 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<void> {
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<string | null> {
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'] })
/** Completes the administration step-up; the page behind it then renders. */
export async function stepUpAdmin(page: Page, dict: Dict, secret: string) {
const heading = stepUpHeading(page, 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(page.getByRole('main'), dict, secret)
await expect(heading).toBeHidden()
}