diff --git a/apps/app/e2e/lan/trial-lan.spec.ts b/apps/app/e2e/lan/trial-lan.spec.ts new file mode 100644 index 00000000..8c40d0d6 --- /dev/null +++ b/apps/app/e2e/lan/trial-lan.spec.ts @@ -0,0 +1,154 @@ +import { readFileSync } from 'node:fs' +import { fr } from '@/i18n/fr' +import type { Page } from '@playwright/test' +import { totpCode } from '../../../../packages/supabase/tests/sandbox/totp' +import { expect, test } from '../support/browser' + +// Owner trial through its LAN origin (C47): sign-in, TOTP enrolment and challenge, the +// catalogue, a non-equine sheet, an SVG import, save and reload. The request guard of +// support/browser.ts fails on any request outside the origin; the listener below also +// names 127.0.0.1 and localhost. TRIAL_EMAIL and TRIAL_PW_FILE (first line, mode 600). + +const dict = fr +const email = process.env.TRIAL_EMAIL ?? '' +const password = + (process.env.TRIAL_PW_FILE ?? '') + ? readFileSync(process.env.TRIAL_PW_FILE ?? '', 'utf8').split('\n')[0] + : '' + +const SVG = + '' + + '' + + '' + +const revisionLine = (page: Page) => + page.getByRole('status').filter({ hasText: /^Révision \d+/ }) + +async function revisionShown(page: Page): Promise { + const text = (await revisionLine(page).textContent()) ?? '' + return Number(/Révision (\d+)/.exec(text)?.[1]) +} + +async function nextCode(secret: string): Promise { + const left = 30_000 - (Date.now() % 30_000) + if (left < 3000) await new Promise((r) => setTimeout(r, left + 200)) + return totpCode(secret) +} + +async function signIn(page: Page) { + await page.goto('/login') + await page.getByLabel(dict['auth.email']).fill(email) + await page.getByLabel(dict['auth.password'], { exact: true }).fill(password) + await page.getByRole('button', { name: dict['auth.login.submit'] }).click() + await expect(page).toHaveURL(/\/app\/?$/) +} + +async function enrol(page: Page): Promise { + await page.goto('/app/account') + await page.getByRole('button', { name: dict['mfa.enrol.start'] }).click() + await page.getByLabel(dict['mfa.enrol.name']).fill('Essai LAN') + await page.getByRole('button', { name: dict['mfa.enrol.continue'] }).click() + const key = page.getByText(/^[A-Z2-7]{16,}$/) + await expect(key).toBeVisible() + const secret = ((await key.textContent()) ?? '').trim() + await page.getByLabel(dict['mfa.code.label']).fill(await nextCode(secret)) + await page.getByRole('button', { name: dict['mfa.code.verify'] }).click() + await expect(page.getByText(dict['mfa.enrol.done'])).toBeVisible() + return secret +} + +async function challenge(page: Page, secret: string) { + await page.goto('/app/admin') + const field = page.getByRole('main').getByLabel(dict['mfa.code.label']) + await expect(field).toBeVisible() + await page.waitForLoadState('networkidle') + await field.fill(await nextCode(secret)) + await page + .getByRole('main') + .getByRole('button', { name: dict['mfa.code.verify'] }) + .click() + await expect(field).toBeHidden() +} + +async function createNonEquineSheet(page: Page, tag: string) { + await page.goto('/app/admin/sheets') + await expect( + page.getByRole('heading', { name: dict['admin.sheets.title'] }), + ).toBeVisible() + await page.getByRole('link', { name: dict['admin.sheets.new'] }).click() + const species = page.getByLabel(dict['admin.sheet_form.species'], { + exact: true, + }) + const nonEquine = species.locator( + 'option:not([value=""]):not([value="equine"])', + ) + await expect(nonEquine.first()).toBeAttached() + await page.waitForLoadState('networkidle') + const chosen = (await nonEquine.first().getAttribute('value')) ?? '' + await species.selectOption(chosen) + await expect(species).toHaveValue(chosen) + await page + .getByLabel(dict['admin.sheet_form.name_fr']) + .fill(`Fiche LAN ${tag}`) + await page + .getByLabel(dict['admin.sheet_form.name_en']) + .fill(`LAN sheet ${tag}`) + await page + .getByRole('button', { name: dict['admin.sheet_form.submit'] }) + .click() + await expect(page).toHaveURL(/\/app\/admin\/sheets\/[0-9a-f-]{36}\/draft$/) +} + +test('trial through the LAN origin: MFA, new sheet, SVG import, save, reload', async ({ + page, +}) => { + test.skip(!email || !password, 'TRIAL_EMAIL and TRIAL_PW_FILE are required') + test.setTimeout(120_000) + const local: string[] = [] + page.on('request', (request) => { + if (/\/\/(127\.0\.0\.1|localhost)/.test(request.url())) + local.push(request.url()) + }) + const tag = Date.now().toString(36) + await signIn(page) + const secret = await enrol(page) + // Enrolment leaves an aal2 session: a new sign-in brings the real challenge. + await page + .getByRole('button', { name: dict['shell.sign_out'] }) + .first() + .click() + await expect(page).not.toHaveURL(/\/app/) + await signIn(page) + await challenge(page, secret) + await createNonEquineSheet(page, tag) + await page + .getByRole('tab', { name: dict['editor.tab.views'], exact: true }) + .click() + await page + .locator('[data-testid$="-file"]') + .first() + .setInputFiles({ + name: 'lan.svg', + mimeType: 'image/svg+xml', + buffer: Buffer.from(SVG), + }) + const dialog = page.getByRole('dialog', { + name: dict['editor.cleaning.title'], + }) + await expect(dialog).toBeVisible() + await dialog + .getByRole('button', { name: dict['editor.cleaning.confirm'] }) + .click() + await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() + const before = await revisionShown(page) + await page.getByRole('button', { name: dict['common.save'] }).click() + await expect(revisionLine(page)).toHaveText(`Révision ${before + 1}`) + await page.reload() + await page + .getByRole('tab', { name: dict['editor.tab.views'], exact: true }) + .click() + await expect( + page.getByRole('tabpanel').getByText(dict['editor.views.drawing.ok']), + ).toBeVisible() + expect(local, 'requests to 127.0.0.1 or localhost').toEqual([]) +}) diff --git a/apps/app/e2e/playwright.lan.config.ts b/apps/app/e2e/playwright.lan.config.ts new file mode 100644 index 00000000..e91293c4 --- /dev/null +++ b/apps/app/e2e/playwright.lan.config.ts @@ -0,0 +1,28 @@ +/** + * `playwright test -c e2e/playwright.lan.config.ts` (docs/development/V1-2-6_OWNER_TRIAL.md): + * the owner's trial reached through its LAN origin, which is a non-secure context like a + * phone's browser. It needs a running `pnpm db:sandbox trial` and a trial account; the + * page may reach that origin only. No trace, no report: they would hold the session tokens + * and the password. Run by hand, never part of check:all. + */ +import { defineConfig } from '@playwright/test' +import type { GuardOptions } from './support/browser' + +const ORIGIN = process.env.TRIAL_ORIGIN ?? 'http://192.168.1.100:5193' + +export default defineConfig({ + testDir: './lan', + outputDir: './test-results/lan', + forbidOnly: true, + retries: 0, + expect: { timeout: 15_000 }, + reporter: [['list']], + use: { + baseURL: ORIGIN, + locale: 'fr-FR', + allowedOrigins: [ORIGIN], + trace: 'off', + screenshot: 'off', + viewport: { width: 1280, height: 900 }, + }, +}) diff --git a/apps/app/vite/trial.config.ts b/apps/app/vite/trial.config.ts index 1db0b709..431e950a 100644 --- a/apps/app/vite/trial.config.ts +++ b/apps/app/vite/trial.config.ts @@ -5,20 +5,33 @@ import base from '../vite.config' * Dev server of `pnpm db:sandbox trial` (docs/development/V1-2-6_OWNER_TRIAL.md). * The browser talks to this origin only: the three Supabase routes are * forwarded to the trial gateway on loopback, so no CORS rule is involved. + * The server binds the one host that scripts/db-sandbox.sh validated (loopback or a private + * address of this machine) and refuses any other Host header. */ const target = process.env.FAUNOSTEO_TRIAL_GATEWAY const url = target ? new URL(target) : null if (!url || url.protocol !== 'http:' || url.hostname !== '127.0.0.1') - throw new Error('FAUNOSTEO_TRIAL_GATEWAY must be an http://127.0.0.1: URL') + throw new Error( + 'FAUNOSTEO_TRIAL_GATEWAY must be an http://127.0.0.1: URL', + ) + +const host = process.env.FAUNOSTEO_TRIAL_HOST ?? '' +const PRIVATE_IPV4 = + /^(127\.0\.0\.1|10(\.\d{1,3}){3}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|192\.168(\.\d{1,3}){2})$/ +if (!PRIVATE_IPV4.test(host)) + throw new Error( + 'FAUNOSTEO_TRIAL_HOST must be 127.0.0.1 or a private IPv4 address', + ) const SUPABASE_ROUTES = ['/auth/v1', '/rest/v1', '/storage/v1'] export default defineConfig((env) => mergeConfig(base(env), { - // Loopback even when started by hand: the proxy carries the trial account's session. + // One validated host, never 0.0.0.0: the proxy carries the trial account's session. server: { - host: '127.0.0.1', + host, strictPort: true, + allowedHosts: [host], proxy: Object.fromEntries( SUPABASE_ROUTES.map((route) => [route, { target }]), ), diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 8088b0b6..d85c112e 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -805,7 +805,7 @@ Docker. | `pnpm db:sandbox e2e-shell` (= `pnpm e2e:shell`) | the authenticated `/app` shell in Chromium (`apps/app/e2e/shell`, `docs/development/BROWSER_TESTS.md`): a loopback dev server whose Supabase calls are replayed on the sandbox, fictitious accounts per test | | `pnpm db:sandbox verify-e2e` | V1-2.3: a gateway (`nginx:1.31-alpine`, sandbox network only, no host port) and the real verification worker `faunosteo_worker:dev run --jobs sheet-verify` against the sandbox, then `packages/supabase/tests/sandbox/sheet-verification.sandbox.ts`; both containers removed at the end, the service key passed through a 600 file deleted at start | | `pnpm db:sandbox avatar-e2e` | V1-2.3: the same gateway, published on `127.0.0.1:57800` only and routing `/auth/v1/` too, the real worker `faunosteo_worker:dev run` (default mode: avatars and sweep, 5 s sweep, no quarantine grace, 512 MiB as the compose `worker`) against the sandbox, then `packages/supabase/tests/e2e/avatar-flow.e2e.ts` through that port; the suite's psql calls go to the sandbox database container, which it requires by name; its two accounts are made per run with random passwords and deleted after; both containers removed at the end | -| `pnpm db:sandbox trial` / `trial-account ` / `trial-grant ` | V1-2.6 owner trial (`docs/development/V1-2-6_OWNER_TRIAL.md`): the app on `127.0.0.1:5193` behind a trial gateway on `127.0.0.1:57801` (refuses to start when `faunosteo_dbsandbox_trial_gateway` exists), a confirmed account (hidden password prompt), a catalogue right (email and kind checked, passed as psql variables; editor and publisher also get the admin role) | +| `pnpm db:sandbox trial` / `trial-account ` / `trial-grant ` | V1-2.6 owner trial (`docs/development/V1-2-6_OWNER_TRIAL.md`): the app on `http://$FAUNOSTEO_TRIAL_HOST:5193` (default the LAN address of this machine, `127.0.0.1` = host-only; loopback or private IPv4 of an interface only, Host header allowlisted) behind a trial gateway on `127.0.0.1:57801` (refuses to start when `faunosteo_dbsandbox_trial_gateway` exists), a confirmed account (hidden password prompt), a catalogue right (email and kind checked, passed as psql variables; editor and publisher also get the admin role) | | `pnpm db:sandbox sql` / `down` | psql as postgres on stdin / remove the stack | Every CLI call passes `--db-url` with `sslmode=disable` (the sandbox has no diff --git a/docs/development/V1-2-6_OWNER_TRIAL.md b/docs/development/V1-2-6_OWNER_TRIAL.md index c7e80899..5bcd5611 100644 --- a/docs/development/V1-2-6_OWNER_TRIAL.md +++ b/docs/development/V1-2-6_OWNER_TRIAL.md @@ -50,14 +50,34 @@ Dans un terminal que vous laissez ouvert : pnpm db:sandbox trial ``` -Attendu : `== trial: http://127.0.0.1:5193`, puis les lignes de Vite. L'application est servie sur -`http://127.0.0.1:5193` et la même adresse relaie `/auth/v1`, `/rest/v1` et `/storage/v1` vers une passerelle -de l'essai, publiée sur `127.0.0.1:57801` uniquement : le navigateur ne parle qu'à une seule origine. La -commande refuse de démarrer si la passerelle de l'essai existe déjà ou si l'un des ports est pris. +Attendu : `== trial: http://192.168.1.100:5193`, puis les lignes de Vite. L'adresse d'essai est celle de cette +machine sur le réseau local, déduite comme pour DEV (`FAUNOSTEO_DEV_HOST`). Pour la fixer, ou pour un essai +limité à cette machine : -Ouvrez `http://127.0.0.1:5193/login` et connectez-vous avec le compte de l'étape 2. Le site n'est joignable que -depuis cette machine (pas depuis un téléphone du réseau local). Pour l'ouvrir depuis un autre ordinateur, voir -la section « Accès depuis une autre machine (tunnel SSH) ». +```bash +FAUNOSTEO_TRIAL_HOST=127.0.0.1 pnpm db:sandbox trial +``` + +Seules sont acceptées l'adresse de bouclage ou une adresse privée (`10/8`, `172.16/12`, `192.168/16`) portée par +une interface de cette machine ; `0.0.0.0`, un nom et une adresse publique sont refusés avec un message. + +Un seul port est ouvert au réseau local : **5193**, sur cette adresse uniquement (pas sur `0.0.0.0`). Vite relaie +`/auth/v1`, `/rest/v1` et `/storage/v1` vers une passerelle de l'essai publiée sur `127.0.0.1:57801` ; tous les +services de la pile jetable restent sur `127.0.0.1`. Vite refuse tout en-tête `Host` autre que l'adresse d'essai. +La commande refuse de démarrer si la passerelle de l'essai existe déjà ou si l'un des ports est pris. + +Ouvrez `http://192.168.1.100:5193/login`, depuis cette machine ou depuis un appareil du réseau local (téléphone +compris), et connectez-vous avec le compte de l'étape 2. Si `192.168.1.100:5193` ne répond pas depuis un autre +appareil, un pare-feu de la machine peut demander une règle pour ce port depuis le réseau local ; la commande +est la vôtre, elle n'est jamais lancée par les outils : + +```bash +sudo ufw allow from 192.168.1.0/24 to any port 5193 proto tcp +``` + +Protections : réseau local de confiance uniquement (jamais d'exposition publique), compte à mot de passe et +double authentification pour l'administration, RLS sur toutes les tables, pile jetable. DEV (`supabase_*_faunosteo`) +n'est ni lu ni arrêté. Le site est servi en HTTP simple : ne réutilisez pas ici un mot de passe qui compte. ### Double authentification (TOTP) @@ -200,6 +220,7 @@ une annotation sur cette vue (onglet Annotations). - Risque résiduel RR-12 : les opérations du catalogue lisent la mention `aal2` du jeton, pas la session vivante. Un jeton émis à `aal2` reste accepté après la suppression du facteur, jusqu'à son expiration (une heure). - Les e-mails ne partent nulle part (l'interface de courrier de la pile jetable est sur `127.0.0.1:57025`). +- Un appareil du réseau local ne reçoit pas de contexte sécurisé (HTTP) : l'essai n'en a pas besoin. - Les mots de passe créés ici n'ont de valeur que pour cette pile. - La pile est jetable : tout ce que vous créez (comptes, fiches, brouillons) est perdu à `down`. - Juste après un `down`, `up fresh` peut échouer sur `address already in use` (un port pas encore libéré par @@ -212,17 +233,16 @@ une annotation sur cette vue (onglet Annotations). au centre du cadre (« Remplacer par un polygone ») : sa forme est perdue. Ce cas ne s'obtient pas depuis une fiche construite avec ce guide : il n'a pas d'étape et n'est couvert que par les tests automatiques. -## Accès depuis une autre machine (tunnel SSH) -Le serveur d'essai n'écoute que sur `127.0.0.1` (`apps/app/vite/trial.config.ts`). Depuis un autre ordinateur, -ouvrez un tunnel : +## Repli facultatif : tunnel SSH +Le réseau local suffit normalement. Hors de ce réseau, ou si l'essai tourne en `FAUNOSTEO_TRIAL_HOST=127.0.0.1`, +ouvrez un tunnel depuis l'autre ordinateur : ```bash ssh -N -L 5193:127.0.0.1:5193 @ ``` -Puis ouvrez `http://127.0.0.1:5193` sur cet ordinateur. Seul le port 5193 est nécessaire : Vite relaie les trois -routes Supabase vers la passerelle de l'essai sur `127.0.0.1:57801`. Laissez ce terminal ouvert ; Ctrl+C ferme -le tunnel. N'exposez jamais le port sur le réseau. +Puis ouvrez `http://127.0.0.1:5193` sur cet ordinateur. Laissez ce terminal ouvert ; Ctrl+C ferme le tunnel. +Ce repli ne marche que si l'essai écoute sur `127.0.0.1`. ## 6. Arrêt et nettoyage 1. Dans le terminal de `trial` : Ctrl+C. Vite et la passerelle de l'essai s'arrêtent ensemble. diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh index 1093bad0..831d5cc0 100755 --- a/scripts/db-sandbox.sh +++ b/scripts/db-sandbox.sh @@ -23,7 +23,8 @@ # pnpm db:sandbox sheet-assets-e2e (= pnpm e2e:sheet-assets) the sheet-asset upload tool against the sandbox: # a gateway on 127.0.0.1:$PORT_GATEWAY, then scripts/sheet-assets-e2e.sh # pnpm db:sandbox trial the owner's trial (docs/development/V1-2-6_OWNER_TRIAL.md): a gateway on -# 127.0.0.1:$PORT_TRIAL_GATEWAY and the app on http://127.0.0.1:$PORT_TRIAL_APP, +# 127.0.0.1:$PORT_TRIAL_GATEWAY and the app on http://$FAUNOSTEO_TRIAL_HOST:$PORT_TRIAL_APP +# (default: this machine's LAN address; 127.0.0.1 = host-only), # foreground, Ctrl+C stops both # pnpm db:sandbox trial-account a confirmed account, password at a hidden prompt (12 characters min.) # pnpm db:sandbox trial-grant @@ -385,6 +386,27 @@ cmd_sheet_assets_e2e() { # ---- Owner trial (docs/development/V1-2-6_OWNER_TRIAL.md) ------------------- port_taken() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +# The one place the trial host is decided: FAUNOSTEO_TRIAL_HOST, default the DEV host (the LAN +# address); 127.0.0.1 = host-only. Loopback or a private IPv4 of an interface of this machine, +# nothing else (no 0.0.0.0, no name, no public address). +trial_host() { + local host="${FAUNOSTEO_TRIAL_HOST:-$FAUNOSTEO_DEV_HOST}" a b c d + [[ "$host" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] \ + || die "FAUNOSTEO_TRIAL_HOST must be an IPv4 address (not a name, not 0.0.0.0): $host" + a=$((10#${BASH_REMATCH[1]})) b=$((10#${BASH_REMATCH[2]})) + c=$((10#${BASH_REMATCH[3]})) d=$((10#${BASH_REMATCH[4]})) + [ "$a" -le 255 ] && [ "$b" -le 255 ] && [ "$c" -le 255 ] && [ "$d" -le 255 ] \ + || die "FAUNOSTEO_TRIAL_HOST is not an IPv4 address: $host" + [ "$host" = "$a.$b.$c.$d" ] || die "FAUNOSTEO_TRIAL_HOST: write the address without leading zeros" + if [ "$a" -eq 127 ]; then host=127.0.0.1 + elif [ "$a" -eq 10 ] || { [ "$a" -eq 172 ] && [ "$b" -ge 16 ] && [ "$b" -le 31 ]; } \ + || { [ "$a" -eq 192 ] && [ "$b" -eq 168 ]; }; then : + else die "FAUNOSTEO_TRIAL_HOST must be loopback or a private address (10/8, 172.16/12, 192.168/16): $host" + fi + ip -4 -o addr | grep -qF "inet $host/" || die "FAUNOSTEO_TRIAL_HOST $host is not an address of this machine" + TRIAL_HOST="$host" +} + trial_email() { # email: one fixed shape, nothing else reaches curl or psql [[ "${1:-}" =~ ^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,120}\.[A-Za-z]{2,24}$ ]] \ || die "an e-mail address is expected" @@ -411,6 +433,7 @@ trial_stop() { # through its environment, never argv. cmd_trial() { load_secrets + trial_host [ -z "$(docker ps -a -q -f "name=^${TRIAL_GATEWAY}\$")" ] \ || die "$TRIAL_GATEWAY exists (stop the running trial, or pnpm db:sandbox down)" for port in $PORT_TRIAL_GATEWAY $PORT_TRIAL_APP; do @@ -419,10 +442,11 @@ cmd_trial() { trap trial_stop EXIT trap 'exit 130' INT TERM start_trial_gateway - echo "== trial: http://127.0.0.1:$PORT_TRIAL_APP (Ctrl+C stops the app and its gateway)" + echo "== trial: http://$TRIAL_HOST:$PORT_TRIAL_APP (Ctrl+C stops the app and its gateway)" ( cd apps/app && FAUNOSTEO_TRIAL_GATEWAY="http://127.0.0.1:$PORT_TRIAL_GATEWAY" \ - VITE_SUPABASE_URL="http://127.0.0.1:$PORT_TRIAL_APP" VITE_SUPABASE_ANON_KEY="$SB_ANON_KEY" \ - exec node_modules/.bin/vite --config vite/trial.config.ts --host 127.0.0.1 \ + FAUNOSTEO_TRIAL_HOST="$TRIAL_HOST" \ + VITE_SUPABASE_URL="http://$TRIAL_HOST:$PORT_TRIAL_APP" VITE_SUPABASE_ANON_KEY="$SB_ANON_KEY" \ + exec node_modules/.bin/vite --config vite/trial.config.ts --host "$TRIAL_HOST" \ --port $PORT_TRIAL_APP --strictPort ) & trial_pid=$! wait "$trial_pid"