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.
This commit is contained in:
bchanot committed 2026-11-02 17:44:14 +01:00
1 parent a897dd8876
commit 4f6c0ba407
4 files changed
+1328

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
/**
* 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()
}
+180
View File
@@ -0,0 +1,180 @@
/**
* Official sheets of the catalogue journeys (contract §16.6 Acceptance: « a
* sheet published on the sandbox through SQL fixtures »): prior owner actions
* written as postgres, never through a path the app has. Each sheet carries
* the curated equine draft (document and its stored-form drawing,
* supabase/seed/anatomical-sheets/equine/draft) under names of its own; the
* drawing goes to the private bucket under its content key, and the
* fingerprint of each published or retired version is the core's own,
* computed in Node by the module the page runs (`preview.state`).
*/
import { createHash, randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import {
CoreRuntime,
parseOutcome,
type GlueModule,
} from '@faunosteo/core-wasm'
import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
import { literal } from './records'
const REPO = join(__dirname, '../../../..')
const SEED = join(REPO, 'supabase/seed/anatomical-sheets/equine/draft')
// The shipped build of the module (`pnpm wasm:build`), the one the page fetches.
const PKG = join(REPO, 'packages/core-wasm/pkg')
const SEED_ASSET = '7f767f74-3b36-51a7-8465-52dd7e2ead4a'
const BUCKET = 'anatomical-sheet-assets'
/** The seed owner (supabase/seed.sql): the actor a content write records. */
const SEED_OWNER = '10000000-0000-0000-0000-000000000001'
export interface SheetNames {
fr: string
en: string
}
export interface FixtureSheet {
id: string
names: SheetNames
}
/**
* The core in this Node process. `@faunosteo/core-wasm/node` reads its own
* location through `import.meta`, which this CommonJS suite cannot load: the
* same source, from the repository root.
*/
async function loadCore(): Promise<CoreRuntime> {
const runtime = new CoreRuntime({
compile: async () =>
WebAssembly.compile(await readFile(join(PKG, 'faunosteo_wasm_bg.wasm'))),
importGlue: async (instance) =>
(await import(
`${pathToFileURL(join(PKG, 'faunosteo_wasm.js')).href}?instance=${instance}`
)) as GlueModule,
})
if (!(await runtime.ready()))
throw new Error('fixture: the core module did not load')
return runtime
}
let runtime: Promise<CoreRuntime> | null = null
const core = () => (runtime ??= loadCore())
async function seedFiles() {
const [drawing, document] = await Promise.all([
readFile(join(SEED, 'assets/horse.svg')),
readFile(join(SEED, 'document.json'), 'utf8'),
])
return {
drawing,
document,
sha: createHash('sha256').update(drawing).digest('hex'),
}
}
/** The equine draft renamed, its drawing re-pointed at the fixture's asset row. */
function documentFor(text: string, asset: string, names: SheetNames): string {
const document = JSON.parse(text.replaceAll(SEED_ASSET, asset)) as Record<
string,
unknown
>
document.name = names
return JSON.stringify(document)
}
/** The fingerprint the core computes for this document and drawing (as at publication). */
async function fingerprintOf(
document: string,
asset: string,
sha: string,
bytes: Buffer,
) {
const loaded = await core()
const state = loaded.invoke<{ fingerprint: string | null }>((glue) => {
const builder = new glue.PreviewBuilder()
builder.add_drawing(asset, sha, new Uint8Array(bytes))
const preview = builder.build(JSON.stringify({ status: 'draft', document }))
try {
return parseOutcome<{ fingerprint: string | null }>(
preview.call('preview.state', '{}'),
)
} finally {
preview.free()
}
})
if (!state.ok || !state.value.fingerprint)
throw new Error(
`fixture fingerprint: ${state.ok ? 'integrity error' : state.kind}`,
)
return state.value.fingerprint
}
/** The drawing under its content key; an object already there (another fixture) is kept. */
async function storeDrawing(sha: string, bytes: Buffer): Promise<void> {
const response = await fetch(
`${stack.storageUrl}/object/${BUCKET}/${sha}.svg`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${stack.serviceKey}`,
'Content-Type': 'image/svg+xml',
},
body: new Uint8Array(bytes),
},
)
const text = await response.text()
if (!response.ok && !/Duplicate|already exists/i.test(text))
throw new Error(`fixture drawing upload: HTTP ${response.status}`)
}
export type SheetShape =
/** Active, v1 retired and v2 published: listed, v2 current. */
| 'listed'
/** Archived after publishing v1: out of the list, readable by id. */
| 'archived'
/** Active with a draft v1 only: never listed, never readable in the catalogue. */
| 'draft'
/** One official equine sheet in `shape`, its versions as an owner's earlier actions left them. */
export async function seedOfficialSheet(
names: SheetNames,
shape: SheetShape,
): Promise<FixtureSheet> {
const { drawing, document: text, sha } = await seedFiles()
await storeDrawing(sha, drawing)
const id = randomUUID()
const asset = randomUUID()
const [v1, v2] = [randomUUID(), randomUUID()]
const document = documentFor(text, asset, names)
const fingerprint =
shape === 'draft'
? null
: await fingerprintOf(document, asset, sha, drawing)
const slug = `e2e-${id.slice(0, 12)}`
const archived = shape === 'archived'
const content = `${literal(document)}::jsonb`
const versions =
shape === 'listed'
? `('${v1}', '${id}', 1, 'deprecated', 2, ${content}, now() - interval '2 days', now(), ${literal(fingerprint)}),
('${v2}', '${id}', 2, 'published', 2, ${content}, now(), null, ${literal(fingerprint)})`
: shape === 'archived'
? `('${v1}', '${id}', 1, 'published', 2, ${content}, now(), null, ${literal(fingerprint)})`
: `('${v1}', '${id}', 1, 'draft', 2, ${content}, null, null, null)`
const current =
shape === 'listed' ? `'${v2}'` : shape === 'archived' ? `'${v1}'` : 'null'
await sql(`begin;
select set_config('request.jwt.claims', '{"sub":"${SEED_OWNER}"}', true);
insert into public.anatomical_sheets (id, species_id, name, slug, is_official, visibility, status, archived_at)
values ('${id}', 'equine', ${literal(names.fr)}, '${slug}', true, 'private',
'${archived ? 'archived' : 'active'}', ${archived ? 'now()' : 'null'});
insert into public.anatomical_sheet_assets (id, sheet_id, sha256, byte_size, file_name, uploaded_at)
values ('${asset}', '${id}', '${sha}', ${drawing.length}, 'horse.svg', now());
insert into public.anatomical_sheet_versions (id, sheet_id, version_number, status, document_schema_version, content,
published_at, deprecated_at, document_fingerprint)
values ${versions};
update public.anatomical_sheets set current_version_id = ${current},
last_version_number = ${shape === 'listed' ? 2 : 1} where id = '${id}';
commit;`)
return { id, names }
}