Commit Graph

9 Commits

Author SHA1 Message Date
ux-frontend
140a34b81e fix(frontend): align types + UI to backend contract (docs/api.md @ dd5c508)
Some checks failed
ci / backend (lint + typecheck + unit tests) (push) Failing after 0s
ci / frontend (lint + typecheck + build + unit tests) (push) Failing after 0s
Backend pushed the authoritative contract in docs/api.md and tightened
the error envelope via a global HTTPException handler (dd5c508). This
commit folds the frontend onto that contract — every drift flagged by
the code-reviewer MAJOR is closed.

Types (src/types/api.ts)
- User: `id` → `user_id`; `display_name` is `string | null`; add
  `permissions: string[]` and `groups: string[]`; drop `engagement_id`
  and `engagement_name` (not part of CurrentUser).
- Engagement: drop `name`, `client_name` is non-null `string`; status
  enum aligned to `draft | active | closed | archived`; `c2_type` is
  non-null `C2Type`; drop `created_at` (not in EngagementRead v1).
- EngagementCreate body: `client_name` required, plus optional
  `description`, `c2_type`, `start_date`, `end_date`. No `name`.
- Replace ApiError + ApiValidationError with a single uniform envelope:
  `{ error: string, message: string, details?: PydanticErrorItem[] }`,
  matching the new HTTPException handler. PydanticErrorItem is the
  per-field shape on 422 (`{ loc, msg, type }`).

Fetch client (src/lib/api.ts)
- `bodyAsApiError` now recognizes the uniform envelope by shape
  (error+message strings). Anything else returns null so callers fall
  back to a generic message — keeps us robust if the backend ever
  emits a non-JSON response.

Engagements API (src/screens/engagements/engagementsApi.ts)
- Drop the `{ items: [] }` envelope tolerance — backend serves a bare
  `Engagement[]`.
- Hit `/engagements/` with trailing slash explicitly; backend now sets
  `strict_slashes=False` but staying consistent with docs/api.md.

EngagementsPage
- Status tone map switched to the new enum (`draft → pending`,
  `closed → soc`).
- Drop "Name" column. `client_name` is the primary identifier; the
  description column replaces the now-meaningless name field.
- `c2_type` is non-null, so no nullable rendering path.

EngagementCreateDialog
- Drop `name` field. New required field is `client_name`; add a
  `c2_type` select (default `mythic`); brief textarea stays optional.
- `mapValidationErrors` now reads `body.details[*].loc` (last segment
  matches the form field) — direct alignment with the backend's new
  shape after dd5c508.
- 401 still surfaces "Session expirée"; 403 gains a dedicated message;
  other errors fall back to a capitalized backend `message` when
  available, then to a generic French string.

Sidebar
- Display fallback: `user.display_name ?? user.username` (now nullable).
- Drop the `ENG · {engagement_name}` line; show `user.username` (the
  email) as the secondary identity instead.

LoginPage
- Field label "Username" → "Email or username" so RT users with email
  accounts find the field semantically obvious (per docs/api.md note
  on the username/email mapping).

Tests (Vitest, 14 cases, all green)
- Refreshed fixtures to the new shapes (no more `name`, no
  `created_at`, status `draft`, envelopes carry `error`+`message`).
- New 422 test exercises the `details[*].loc` mapping shape.
- New 401 test on the dialog covers the top-of-form alert path.
2026-05-23 11:14:32 +02:00
ux-frontend
ec7effcaac test(frontend): Vitest coverage on sprint 1 wiring
Adds a small test harness (src/test/testUtils.tsx):
- renderWithProviders mounts a fresh QueryClient (no retries, no cache)
  + MemoryRouter so screens using useNavigate / <Link> don't crash.
- installFetchMock(responses[]) replaces globalThis.fetch with a typed
  sequence of canned responses and records call URLs + init.

Specs (10 cases, all green):

LoginPage.test.tsx
- happy path: submit posts to /api/v1/auth/login with credentials:'include',
  correct JSON body shape (username/password).
- 401 surfaces "Identifiants invalides" and does NOT leak the backend
  detail string.
- empty submit is intercepted by HTML5 `required` — no fetch fires.

EngagementsPage.test.tsx
- loading row renders while /engagements is in flight.
- empty state renders on 200 [].
- error state + Retry button render on 500.
- populated table renders the snake_case fields correctly (name,
  client_name, c2_type uppercased).

EngagementCreateDialog.test.tsx
- client-side validation: empty name blocks submission, no fetch fires.
- 422 Pydantic error on the `name` field maps to the inline message
  next to the input.
- 201 success triggers onClose() and POSTs to /api/v1/engagements.
2026-05-23 11:12:06 +02:00
ux-frontend
20fbcdf1f8 feat(frontend): wire LoginPage + EngagementsPage + create dialog to backend
LoginPage
- RT mode now POSTs /api/v1/auth/login with controlled username/password
  fields. Success seeds the session cache via queryClient.setQueryData and
  navigates to /engagements. 401 surfaces as the generic
  "Identifiants invalides" — no echo of the backend detail (avoids
  user enumeration leaks).
- SOC mode kept visually for masthead continuity but disabled with a
  "sprint 2" placeholder pointing at the deferred
  POST /api/v1/auth/soc/session endpoint.
- Removed the sprint-0 mock role-picker.

EngagementsPage
- MOCK_ENGAGEMENTS dropped. useQuery against fetchEngagements (handles
  both bare-array and { items: [] } envelope shapes — backend has not
  pinned this yet).
- Distinct loading / empty / error states. Error row surfaces an HTTP
  code and a Retry button. Empty state offers the create dialog.
- Column shape aligned with the real Engagement schema (snake_case:
  name, client_name, c2_type, start_date, end_date). Dropped mock-only
  columns (operators, socAnalysts) — those land when backend exposes
  /engagements/:id/members and /engagements/:id/soc-sessions counts.

engagementsApi.ts
- fetchEngagements + createEngagement, both bound to /api/v1/engagements.
- ENGAGEMENTS_QUERY_KEY exported so the dialog can invalidate without
  re-knowing the key.

EngagementCreateDialog (frontend-design skill — new non-trivial component)
- "Arm engagement" mission-control dialog. Backdrop is a graphite dim
  with a faint scanline overlay (no soft blur) — reads as "cockpit
  paused while you issue a command", not as a SaaS modal.
- Surface --surface-3 with corner-marks and an amber hairline accent
  under the title; underline-style inputs that light amber on focus;
  label-system uppercase microtypography throughout.
- Esc + outside-click close (suspended while the mutation is in flight).
- Rudimentary tab focus trap.
- 422 Pydantic errors map per-field via the last loc segment;
  401/5xx surface as a generic top-of-form alert.
- On 201 invalidates ['engagements'] and closes.
2026-05-23 11:12:06 +02:00
ux-frontend
f6d4e43e4c feat(frontend): wire session to real /auth/me + drop sessionStorage mock
Foundations for the sprint 1 backend wiring. No UI behavior change beyond
the loading state in AppShell, but everything below the wire is now real:

- vite.config.ts adds `server.proxy['/api']` → http://localhost:5000
  (overridable via VITE_DEV_API_TARGET). In prod Caddy routes /api → backend
  on the same origin, so the same `/api/v1/...` paths work without changes.
- src/types/api.ts hand-rolled against the backend Pydantic schemas.
  User / Engagement / EngagementCreate / Login / ApiError / ApiValidationError.
  Should be regenerated from OpenAPI once backend exposes it.
- src/lib/api.ts: thin fetch wrapper. Always credentials:'include' so the
  HttpOnly session cookie travels. 4xx/5xx normalize into ApiClientError
  with typed `body` (ApiError | ApiValidationError | null). No retry loop —
  that's TanStack Query's policy.
- src/session/sessionApi.ts: 1:1 functions for /auth/me, /auth/login,
  /auth/logout. fetchMe maps 401 → null so "unauthenticated" is data, not
  an error.
- src/session/useSession.ts: now a TanStack Query hook against
  SESSION_QUERY_KEY (`['session']`). Returns { user, isLoading, isError,
  signOut, isSigningOut }. Cookie is the source of truth, server is the
  resolver, query is the cache.
- Drop sessionStorage mock layer entirely: src/mocks/session.ts,
  src/session/SessionContext.{tsx,context.ts}, src/routing/Root.tsx all
  removed. No more provider tree — QueryClientProvider in App.tsx is the
  only global state container.
- AppShell renders a "resolving session" state during /auth/me's first
  flight so users with a valid cookie don't see a /login flash on direct
  navigation to a protected URL.
- StatusRail gains an optional `sessionState="resolving"` slot used by
  the loading shell.
- Sidebar's Sign-out wires POST /auth/logout, invalidates the session
  cache, and always navigates to /login regardless of the call outcome
  (a failed logout still expires the local cache so users aren't stuck
  on a broken cookie).
- types/roles.ts loses SessionUser (replaced by api.ts User which is the
  authoritative shape).
2026-05-23 11:12:06 +02:00
ux-frontend
b505a654f8 fix(frontend): address M1-M3 polish from code-reviewer
M1 — Single SessionProvider via nested router.
  The previous router had two route entries with `path: '/'`
  (Navigate, AppShell) plus a separate `/login` entry, each wrapped in
  its own RootLayout. That instantiated SessionProvider three times,
  forking state the moment session writes diverged across siblings.
  Replaced by one Root route with SessionProvider + <Outlet />, and
  index/login/AppShell-children nested underneath. RootLayout (the
  per-tree wrapper) is now obsolete and deleted; the new Root component
  lives in src/routing/Root.tsx (addresses NIT N4 as a side effect).

M2 — Typo: "pollign" → "polling" in LiveCockpitPage masthead.

M3 — Replace asymmetric `?? 'rt_operator'` / `?? 'soc_analyst'`
  fallbacks in LiveCockpitPage with an explicit `if (!user) return null;`
  guard placed after all hooks (rules-of-hooks). AppShell already
  redirects unauthenticated visitors to /login, so the guard documents
  the invariant rather than introducing one.

NITs N1-N3, N5-N7 recorded in tasks/todo.md as sprint 1+ follow-ups.
2026-05-21 20:44:32 +02:00
ux-frontend
12bc33469c feat(frontend): wireframes for 5 MVP screens + audit (F0.3)
Mock-data wireframes covering spec §5 / §9 surface area. All read from
src/mocks/fixtures.ts — no backend wiring yet. Each screen is built from
the design-system primitives (Panel, Pill, Button, label-system, status-dot)
and adheres to the instrumentation-grade visual grammar.

Screens:
- /login              LoginPage — RT vs SOC mode switch (segmented), role-tinted.
                       RT form picks rt_operator / rt_lead at sign-in (mock only).
                       SOC form takes a session token (out-of-band, D-006).
                       Left rail carries mission brief + platform telemetry.
- /engagements        EngagementsPage — mission roster table (codename, client,
                       status, c2_type, operators, SOC count, window).
- /runs               LiveCockpitPage — the cornerstone screen. 3-column layout:
                       steps timeline | step detail (resolved command,
                       output, evidence, detection) | side rail
                       (DetectionPanel for SOC; EvidencePanel +
                       DetectionPanel readonly + CleanupPanel for RT).
                       Control bar (F6 pause/skip/retry/abort) is lead-RT-only.
                       Stats header: steps done, detected/partial/missed counts.
- /scenarios          ScenarioComposerPage — 3-column composer:
                       filterable TTP library | ordered steps with delays
                       | inspector (params from params_schema_json, target
                       host list, jinja2 cleanup template preview).
                       c2_type locked at scenario level (D-F3 / H33).
- /library            TtpLibraryPage — catalog table with stealth-variant
                       flagging, source provenance (custom/atr/mission),
                       payload_type chip, tags. Import journal / ATR buttons.
- /reports            ReportPage — restricted MITRE matrix (techniques
                       played only, H29), narration timeline, integrity
                       hash footer (SHA-256, H19/H24/F9). PDF/JSON/MD
                       export buttons.
- /audit              AuditPage — append-only journal viewer (lead RT only,
                       F13). Tabular timestamp/actor/role/action/resource.

UX guardrails baked in:
- SOC analysts never see RT-only controls (conditional rendering, not just
  disabled state). UI layer mirrors backend RBAC but does not replace it.
- Layout density and dark-first palette tuned for long purple sessions
  (sober contrast, no flash, status colors carry information without
  being shouted).
- Live cockpit reserves a clear visual slot for cleanup-failed alerts
  (R-T5) — currently a Pill, real alert UX lands when the WebSocket is
  wired in sprint 1+.
2026-05-21 20:31:24 +02:00
ux-frontend
ef081c8c28 feat(frontend): role-aware app shell + routing skeleton (F0.4)
- Role enum (rt_operator, rt_lead, soc_analyst) aligned with spec §3 / F11.
  Frontend predicates (isRT, isLead, isSOC) drive layout only — backend
  remains the source of truth for permissions (D-008).
- SessionContext split into Provider (TSX) and hook (useSession) to satisfy
  react-refresh/only-export-components.
- AppShell composes StatusRail (link health, active run, UTC clock, build) +
  Sidebar (role-conditional nav with keyboard shortcut hints) + Outlet.
  Unauthenticated visitors redirect to /login.
- StatusRail uses pulsing status-dot pattern and label-system micro-typo
  (uppercase 10px, 0.08em tracking) to evoke an instrument-panel header.
- Router (createBrowserRouter): /login outside the shell, all app routes
  nested inside the shell. RootLayout extracted to its own file for
  fast-refresh compliance.

Routes (sprint 0, flat):
  /login                 LoginPage
  /engagements           EngagementsPage
  /library               TtpLibraryPage (RT only — gated client-side, will
                                          be re-enforced by backend RBAC)
  /scenarios             ScenarioComposerPage (RT only)
  /runs                  LiveCockpitPage
  /reports               ReportPage
  /audit                 AuditPage (lead RT only)

Sub-routes under /engagements/:eid land in sprint 1+ when real scoping
arrives.
2026-05-21 20:31:01 +02:00
ux-frontend
1562478a54 feat(frontend): provisional design system tokens + Logo placeholder (F0.2)
Aesthetic direction: instrumentation-grade telemetry (mission-control / SDR ops),
NOT shadcn defaults, NOT generic AI/SaaS. Mature palette: graphite surface scale,
CRT-amber for RT accent, steel-blue for SOC accent, sage/ochre/rust for detection
status — no neon, no rainbow.

Token layout designed to host the PR3 graphic charter without component churn:
  1. Primitives (--mc-*)        raw OKLCH scales
  2. Semantics (--accent-*, --status-*, --state-*, --surface-*, --line-*, …)
  3. Tailwind @theme mapping    semantic tokens → utilities

Includes:
- src/styles/theme.css       full token surface + base reset + scrollbars + grain
- src/styles/fonts.css       IBM Plex @font-face (self-host only)
- src/styles/globals.css     entry CSS file
- Logo (full/compact/mark) with corner-mark composition
- Panel, Pill, Button primitives reading exclusively from semantic tokens
- Logo.test.tsx (3 cases, Vitest + Testing Library)
2026-05-21 20:30:41 +02:00
ux-frontend
80ca4641a3 feat(frontend): bootstrap Vite + React 19 + TS strict toolchain (F0.1)
- Vite 8 / React 19 / TS 6 strict (noUncheckedIndexedAccess, no baseUrl deprecation)
- Tailwind 4 via @tailwindcss/vite (no PostCSS step)
- TanStack Query 5, react-router-dom 7, Recharts, clsx
- Vitest + Testing Library + jsdom for unit tests
- Playwright skeleton + first smoke spec (login redirect)
- ESLint flat config: typescript-eslint type-checked, react-hooks, react-refresh, prettier
- Prettier config (semi, single quotes, 100-col, lf)
- IBM Plex font @font-face declarations targeting /fonts/ (self-host, no CDN — OPSEC)
2026-05-21 20:30:23 +02:00