Skip to content

Latest commit

 

History

History
223 lines (185 loc) · 16.1 KB

frontend-bff.md

File metadata and controls

223 lines (185 loc) · 16.1 KB

Frontend and BFF

SvelteKit renders pages on the server and enhances forms in the browser. All account API calls run through frontend/src/lib/server/; browser dashboard requests use same-origin BFF endpoints. FastAPI remains the authority for passwords, sessions, roles, validation, account lifecycle and rate limits. There is no additional BFF session or JWT.

Local stack

Use the existing private root .env and secret directory. Do not create additional environment templates or place credentials in frontend variables.

docker compose -f compose.yaml -f compose.local.yaml up -d --build

Open http://localhost:3000. FastAPI is published only on loopback, normally at http://localhost:8000/docs, /redoc and /openapi.json. PostgreSQL is also loopback-only. Swagger executes requests; ReDoc documents them. Add the X-CSRF-Protection: 1 header in Swagger. The local overlay keeps real authentication, CSRF and rate limits; it only permits HTTP cookies and the configured development origins. Origin matching is exact: use localhost:3000 for the UI. BACKEND_PORT and DB_PUBLISHED_PORT contain port numbers, without a host prefix.

For native frontend development, run npm run dev -- --port 3000 from frontend/, with ORIGIN=http://localhost:3000 and BACKEND_ORIGIN=http://127.0.0.1:8000 in that process environment. Do not run it on the same port as the Docker frontend. Native frontend calls to the Docker backend retain the host/Docker-gateway IP for limits; per-client forwarded addresses are trusted only from the configured Docker BFF. The supported full proxy-chain verification uses the Docker frontend.

A protected page redirects anonymous visitors to /login?next=…. Successful login returns to that local path, preserving query parameters; direct logins default to /. External, malformed and cyclic login/logout destinations are rejected. Expired dashboard/course sessions retain their current page. Page authorization still runs after login. Homepage content is identical for guests and accounts. Only the header changes: guests see the logo and login button; accounts see permission-based navigation with icon capsules and an active-page marker. A single identity button opens the account disclosure: full name, username, existing colored role badges, a link to /me, and a separately styled logout form that retains POST semantics. Outside clicks and Escape close the disclosure; Escape returns focus to its trigger. On mobile the account stays in the first row alongside a navigation toggle; navigation opens underneath with touch targets of at least 44 px. The menus are mutually exclusive and close after navigation. /lessons requires authentication; /dashboard accepts permanent staff with administrator or teaching-directory capabilities. /admin redirects to the shared workspace and /admin/users/new opens its account modal for administrators. Checks run in server loads as well as on every protected API operation. /lessons provides the course catalogue and authorized course content.

/me displays first/family names, generated username, email, own promotions, roles, status, creation/update dates, last successful login, password-change date, email-verification date and login count. Administrators can also read account activity in authorized account detail responses; teacher cards omit these private security fields. Credential hashes and session secrets are never returned. Changing the password uses a compact button opening a modal on /me; the existing /change-password route remains compatible. Identity/promotions and school information appear first; account activity and security timestamps appear at the end of the personal page.

The bootstrap account logs in through /login, then completes /setup using the link on /me. Setup requires first/family names, email and password; the generated permanent username appears on success before the operator logs in again. Bootstrap remains the sole manually named account. Setup and password changes revoke sessions and require a fresh login. An administrator creates a member, then explicitly generates an invitation. Creation and delivery are separate operations so an invitation failure can be retried without creating another account.

Responsive workspace

Curriculum workspace

/curricula and its header link require curricula.read; server loads and backend services both enforce this. Administrators manage metadata, while current subject assignments scope teacher competency/import actions. Kholleurs receive a read-only view. Promotions may reference a curriculum without changing their free name or calendar identity.

The desktop graph uses Three.js and existing subject badges/modals. Concentric rings are recalculated for visible branches; direct links join block borders. The compact parent-first outline is the only view at widths up to 650 px, with no WebGL initialization there. Returning to desktop recreates the canvas/context. Subject headings add a root competency only when authorized. Other editors retain keyboard handling, inherited colors, fullscreen toggling and reduced-motion behavior.

POST /curricula/data relays allowlisted metadata, graph, node and undo commands. The dedicated POST /curricula/transfer accepts only import/export commands with positive numeric IDs. The latter alone has an 8 MiB + 4 KiB bounded-body guard for escaped original JSON file text; ordinary JSON writes retain 16 KiB. Backend parsing and live permissions remain authoritative. Exports use the chosen subject name as a safe .json basename; imports append atomically and can be undone as a lot. The file modal reuses the course document dropzone. No uploaded file or teaching text is executed.

See curriculum behavior and limits and ADR 0011.

Administration workspace

The administrator overview shows a half-doughnut of active, pending-activation and archived accounts, the total and active promotion counts, promotion shortcuts and a journal of 15 events per page. Journal entries use newest timestamps first with ID tie-breaking; arrows navigate opaque cursors. The total excludes the bootstrap. Pending activation includes accounts without an issued invitation.

A static desktop sidebar switches overview, promotions and accounts in place. On smaller screens, navigation becomes horizontal and content stacks. Shared account/promotion components implement loading, empty and error states, keyboard-accessible native dialogs, focus return and mobile drawers. Management uses dialogs/drawers rather than one route per action:

  • Create consecutive accounts with required names/email, a valid role combination and optional promotion checkboxes. The username is generated by the backend; invitations are a separate retryable action.
  • Search names approximately or usernames literally, with 220 ms debounce and stale-request cancellation. Administrators can filter by role/status; ordinary lists are paginated.
  • Open an account drawer for identity, real login/security statistics, invitation state, promotion assignments, password reset and archive/reactivation. Self-archiving is disabled in UI and rejected by API.
  • Follow "Voir la fiche complète" to /dashboard/user?id=… for private birth/location/contact, previous-school, baccalaureate/options/marks, orientation and reference-adult information. The drawer and list do not fetch these new fields. Admins may edit identity and school fields; teachers may edit only orientation for their shared students, including archived accounts. Full-profile access is explicitly authorized by the API and does not expose security/login history to teachers.
  • Create/edit promotions using a native color picker and validated hex input, search/filter them, archive/reactivate, open a roster in place and add multiple existing accounts atomically.
  • Teacher-only accounts see assigned promotions and their students, including archived accounts, with compact read-only student cards and shared promotions. They cannot see the global overview/journal or invoke administration commands. Their sole profile mutation is orientation editing on the complete student page. Unassigned students stay inaccessible through direct API calls.

Teacher/admin accounts use the administrator workspace; admin alone gains no teacher permission. Pedagogical statistics use scoped aggregate endpoints and shared interactive charts; see statistics for measurement and access rules. Unavailable history has an explicit empty state rather than fabricated numbers. Promotion rosters and student cards are reusable components intended for later enrichment.

ProfileEditor.svelte saves one patch with expected_version and retains drafts on errors; stale versions return 409 instead of overwriting another editor. One save button sits below the form. Internal navigation with unsaved changes opens a confirmation modal; reload/tab closure uses the browser's native confirmation, whose text is controlled by the browser. Drafts are not persisted in browser storage. Free official commune search selects coherent commune/postcode pairs, validated again by the backend. Cancel an unfinished search to keep the current location and save other edits.

GET /dashboard/data exposes an allowlisted resource vocabulary. POST /dashboard/command exposes allowlisted mutations; the BFF constructs backend paths and query strings and checks safe integer IDs. Backend PATCH/PUT/DELETE operations are forwarded only from protected incoming POST requests. No arbitrary browser-supplied backend URL is accepted. API permissions and SQL teacher scope remain the final access controls. Private identity payloads and manual invitation links are not persisted in browser storage.

Production topology

compose.yaml is the production base. It publishes neither PostgreSQL nor FastAPI. The frontend binds to 127.0.0.1:3000, for an HTTPS reverse proxy running on the host. Do not apply the local overlay in production. Set SOPHIKRON_ORIGIN to the exact HTTPS public origin before building and starting the stack; the placeholder https://sophikron.invalid must be replaced. Rebuild after an origin change because SvelteKit's origin check is compiled with that origin.

infra/nginx.conf is a location snippet for the host's existing HTTPS server block. Configure the domain, certificates and HTTP redirect on that proxy. It replaces forwarding headers with the socket peer's address. If another proxy/CDN precedes it, configure that provider's trusted addresses explicitly before using its client address. Never open the frontend listener to untrusted peers while trusting ADDRESS_HEADER.

The BFF uses its socket peer locally, and the host proxy's replaced X-Real-IP in production. It normalizes the address and overwrites X-Forwarded-For on internal requests. Uvicorn trusts only the fixed BFF address on the dedicated BFF network. BFF_SUBNET, BFF_ADDRESS and API_ADDRESS may be changed together if 172.30.85.0/24 conflicts with the host's networks. The default BFF/API addresses are .2 and .3; both are reserved to avoid dynamic allocation conflicts. The database network is internal and is not attached to the frontend. Backend authorization remains mandatory on every operation.

Production forces secure cookies and disables browser CORS. AUTH_ALLOWED_ORIGINS still governs FastAPI's CSRF validation independently of CORS. SvelteKit checks the exact request Origin before any write reaches FastAPI, then supplies the backend's required origin and custom CSRF header. Native SvelteKit form protection remains enabled. This explicit BFF check also runs in development. The response policy is Referrer-Policy: same-origin: native POST forms retain their Origin header, while cross-origin referrers are withheld. Null/missing and foreign origins remain rejected; logout stays a POST and redirects to the shared home.

Only the expected session cookie is relayed, with its HttpOnly, Secure, SameSite=Lax, host-only, Path=/ attributes and expiry/deletion. It never appears in page data or action results. Cookie clearing on 401 is relayed too. No server-global cookie jar or user state is shared across requests. 429 status and numeric Retry-After headers are preserved on form failures. Account pages and action responses use private, no-store caching. The proxy must not override this policy.

Invitations and password resets

The dashboard calls POST /api/v1/admin/users/{id}/access-invitation. SMTP delivery is selected when configured and returns no token; otherwise the response contains a new token/expiry and the UI shows a copyable manual link. The legacy manual-only endpoint still follows AUTH_MANUAL_INVITATIONS_ENABLED; that flag does not disable the unified endpoint's configured fallback. SMTP failure returns an error and revokes that link, without silently switching to manual delivery.

Pending accounts receive an activation invitation; active accounts receive a reset invitation. The account drawer distinguishes absent, outstanding, expired, consumed and revoked invitations. Issuing a replacement invalidates previous unused links. Consuming a reset changes the password and revokes all sessions; archived accounts cannot receive or consume links. Creation is never retried implicitly.

A manual invitation credential is intentionally visible to its issuer and recipient; session credentials remain HttpOnly. No token is written to logs, persistent browser storage, URL queries or plaintext database fields. Keep it out of screenshots and support reports. Closing/reloading the dialog loses the displayed token; reopen the existing account to generate a replacement.

Activation reads #token=… in the browser, removes the fragment from the current history entry, and submits the token in a form body through the BFF. Pasting a token manually also works without JavaScript. The token is single-use, expires, and is replaced by explicit regeneration. Manual delivery does not verify the email.

Code and verification

+layout.svelte, Header and Footer define the shell. Page components contain form markup and interaction state; adjacent +page.server.ts files handle submissions. hooks.server.ts loads the current profile per request. FastAPI routes remain the source of business decisions. app.css centralizes design tokens over Bulma. Font Awesome Free 7 solid icons are imported individually and rendered as local SVGs, with no CDN. The package uses MIT code licensing and CC BY 4.0 for icons; retain its notices. No external fonts, analytics or consent banner are loaded. The common home remains SSR because the header depends on the session. Only / appears in the sitemap. Account routes have noindex metadata/headers; robots.txt is not an authorization boundary.

See release verification for the shared commands, Node/browser requirements and disposable BFF journey options. Playwright is a development-only dependency; it does not run in production or require a hosted service. The BFF tests exercise cookie relay, CSRF rejection, replacement of forged IP headers, session expiry, page-role permissions and Retry-After. A native browser form regression test runs when a local Chrome/Edge/Chromium binary is available (or BROWSER_EXECUTABLE is set), using an isolated temporary profile; otherwise that browser-specific test is explicitly skipped. Backend integration tests exercise actual PostgreSQL invitation, archive, role/scope and account activity semantics. The real BFF journey (frontend/tests/journey.mjs) covers HTTP setup, profiles, account/promotion creation, invitations, active-account reset, archiving, journal and teacher scope.

Health endpoints

The frontend GET /health is unauthenticated and returns only ok. Docker probes it directly on container localhost; it checks frontend availability without calling the API. The backend GET /health checks a bounded PostgreSQL SELECT 1 and returns 503 on failure. The API is unpublished in the production base and loopback-only with the local overlay. The frontend route remains accessible through any proxy that forwards it; healthcheck use of localhost is not an access-control rule. PostgreSQL readiness and successful migration completion gate application startup.