Milestone 3

This commit is contained in:
Knacky
2026-05-11 06:05:27 +02:00
commit 4c25e198fc
125 changed files with 13489 additions and 0 deletions

7
frontend/.dockerignore Normal file
View File

@@ -0,0 +1,7 @@
node_modules
dist
.vite
*.log
.env
.env.*
!.env.example

18
frontend/.eslintrc.cjs Normal file
View File

@@ -0,0 +1,18 @@
/* eslint-env node */
module.exports = {
root: true,
env: { browser: true, es2022: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs', 'node_modules'],
parser: '@typescript-eslint/parser',
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
};

8
frontend/.prettierrc Normal file
View File

@@ -0,0 +1,8 @@
{
"singleQuote": true,
"semi": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always"
}

31
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,31 @@
# syntax=docker/dockerfile:1.7
# === Stage 1: build the SPA bundle ===
FROM docker.io/library/node:20-alpine AS builder
ARG VITE_API_BASE_URL=/api/v1
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
WORKDIR /app
COPY package.json ./
# When a lockfile is committed (npm/pnpm/yarn), prefer `npm ci` for reproducibility.
RUN if [ -f package-lock.json ]; then npm ci; else npm install --no-audit --no-fund; fi
COPY tsconfig*.json vite.config.ts tailwind.config.ts postcss.config.js index.html ./
COPY src ./src
RUN npm run build
# === Stage 2: serve via nginx ===
FROM docker.io/library/nginx:1.27-alpine AS runtime
# Drop the default config and use ours.
RUN rm -f /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/metamorph.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget -qO- http://127.0.0.1/healthz || exit 1

39
frontend/README.md Normal file
View File

@@ -0,0 +1,39 @@
# Metamorph frontend
Vite + React 18 + TypeScript + TailwindCSS. Design tokens from `../tasks/design.md` are in `tailwind.config.ts`.
## Local dev
```bash
npm install
npm run dev # http://localhost:5173 (proxies /api/* to http://localhost:8000)
```
## Build
```bash
npm run build # outputs to dist/
npm run preview # serves dist/ on http://localhost:8080
```
## Quality
```bash
npm run typecheck
npm run lint
npm run format
```
## Layout
```
src/
├── App.tsx # M0 home page (health check + design tokens demo)
├── main.tsx
├── index.css # Tailwind base + tinted-accent utilities
├── components/ui/ # RTOps design primitives: Card, Tag, SectionHeader, FlowNode, Button
├── lib/
│ ├── api.ts # fetch wrapper (M2 will replace with auth-aware client)
│ └── cn.ts # classnames + ACCENTS palette
└── vite-env.d.ts
```

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark" />
<title>Metamorph</title>
</head>
<body class="bg-bg text-text font-sans">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

45
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,45 @@
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Reasonable hardening — TLS is terminated by an external reverse proxy
# so we don't add HSTS here (let the edge own that header).
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "same-origin" always;
# Internal liveness for the docker healthcheck.
location = /healthz {
access_log off;
return 200 "ok\n";
add_header Content-Type text/plain;
}
# Proxy API calls to the Flask service on the compose network.
location /api/ {
proxy_pass http://api:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
client_max_body_size 64m;
}
# SPA fallback — every unknown route returns index.html.
location / {
try_files $uri $uri/ /index.html;
}
# Long cache for hashed assets.
location ~* \.(?:js|css|woff2?|svg|png|jpg|jpeg|webp|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
}

43
frontend/package.json Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "metamorph-front",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview --port 8080",
"lint": "eslint .",
"typecheck": "tsc -b --pretty",
"format": "prettier --write \"src/**/*.{ts,tsx,css,json,html}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,json,html}\""
},
"dependencies": {
"@fontsource/ibm-plex-sans": "^5.0.20",
"@fontsource/jetbrains-mono": "^5.0.20",
"@tanstack/react-query": "^5.51.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
},
"engines": {
"node": ">=20"
},
"devDependencies": {
"@types/node": "^20.12.7",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.13.0",
"@typescript-eslint/parser": "^7.13.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"postcss": "^8.4.38",
"prettier": "^3.3.0",
"tailwindcss": "^3.4.4",
"typescript": "^5.4.5",
"vite": "^5.3.1"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

85
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,85 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { Layout } from '@/components/Layout';
import { RequireAdmin } from '@/components/RequireAdmin';
import { RequireAuth } from '@/components/RequireAuth';
import { AdminGroupsPage } from '@/pages/AdminGroupsPage';
import { AdminInvitationsPage } from '@/pages/AdminInvitationsPage';
import { AdminUsersPage } from '@/pages/AdminUsersPage';
import { HomePage } from '@/pages/HomePage';
import { LoginPage } from '@/pages/LoginPage';
import { ProfilePage } from '@/pages/ProfilePage';
import { RegisterPage } from '@/pages/RegisterPage';
import { SetupPage } from '@/pages/SetupPage';
import { AuthContext, useProvideAuth } from '@/lib/auth';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
refetchOnWindowFocus: false,
staleTime: 30_000,
},
},
});
function AuthProvider({ children }: { children: React.ReactNode }) {
const auth = useProvideAuth();
return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider>
<Routes>
<Route element={<Layout />}>
<Route path="/login" element={<LoginPage />} />
<Route path="/setup" element={<SetupPage />} />
<Route path="/register" element={<RegisterPage />} />
{/* Home page stays public — it's an ops dashboard, not sensitive. */}
<Route path="/" element={<HomePage />} />
<Route
path="/profile"
element={
<RequireAuth>
<ProfilePage />
</RequireAuth>
}
/>
<Route
path="/admin/users"
element={
<RequireAdmin>
<AdminUsersPage />
</RequireAdmin>
}
/>
<Route
path="/admin/groups"
element={
<RequireAdmin>
<AdminGroupsPage />
</RequireAdmin>
}
/>
<Route
path="/admin/invitations"
element={
<RequireAdmin>
<AdminInvitationsPage />
</RequireAdmin>
}
/>
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
);
}
export default App;

View File

@@ -0,0 +1,76 @@
import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { useAuth } from '@/lib/auth';
import { cn } from '@/lib/cn';
export function Layout() {
const { state, logout } = useAuth();
const navigate = useNavigate();
const navItem = (to: string, label: string) => (
<NavLink
to={to}
end
className={({ isActive }) =>
cn(
'font-mono text-xs uppercase tracking-wider2 px-3 py-1 rounded',
isActive ? 'text-cyan accent-fill-cyan' : 'text-text-dim hover:text-text-bright',
)
}
>
{label}
</NavLink>
);
return (
<div className="px-[60px] py-10">
<div className="mx-auto max-w-page">
<header className="flex items-baseline justify-between mb-12">
<Link to="/" className="font-mono text-[24px] font-bold tracking-tight text-text-bright">
<span className="text-red">Meta</span>
<span>morph</span>
</Link>
<nav className="flex items-center gap-2" aria-label="Primary">
{state.user ? (
<>
{navItem('/', 'Home')}
{navItem('/profile', 'Profile')}
{state.user.is_admin && (
<>
{navItem('/admin/users', 'Users')}
{navItem('/admin/groups', 'Groups')}
{navItem('/admin/invitations', 'Invitations')}
</>
)}
<span className="font-mono text-2xs text-text-dim ml-2" data-testid="me-email">
{state.user.email}
</span>
<Button
accent="rose"
onClick={async () => {
await logout();
navigate('/login', { replace: true });
}}
>
Logout
</Button>
</>
) : (
<>
{navItem('/login', 'Login')}
{navItem('/setup', 'Setup')}
</>
)}
</nav>
</header>
<Outlet />
<footer className="mt-[60px] py-8 border-t border-border text-center font-mono text-xs text-text-dim">
metamorph · M0 bootstrap · M1 db schema · M2 auth · M3 rbac · design system from tasks/design.md
</footer>
</div>
</div>
);
}

View File

@@ -0,0 +1,19 @@
import type { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '@/lib/auth';
/** Server still arbitrates — this is a UI gate so non-admins don't see admin routes. */
export function RequireAdmin({ children }: { children: ReactNode }) {
const { state } = useAuth();
if (state.loading) {
return <p className="font-mono text-xs text-text-dim p-8">Loading session</p>;
}
if (!state.user) {
return <Navigate to="/login" replace />;
}
if (!state.user.is_admin) {
return <Navigate to="/" replace />;
}
return <>{children}</>;
}

View File

@@ -0,0 +1,16 @@
import type { ReactNode } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '@/lib/auth';
export function RequireAuth({ children }: { children: ReactNode }) {
const { state } = useAuth();
const loc = useLocation();
if (state.loading) {
return <p className="font-mono text-xs text-text-dim p-8">Loading session</p>;
}
if (!state.user) {
return <Navigate to="/login" state={{ from: loc.pathname }} replace />;
}
return <>{children}</>;
}

View File

@@ -0,0 +1,39 @@
import type { ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface AlertProps {
accent: Accent;
children: ReactNode;
className?: string;
/** Optional ARIA role override; defaults to "alert" for errors. */
role?: string;
}
const ACCENT_FILL: Record<Accent, string> = {
red: 'accent-fill-red',
orange: 'accent-fill-orange',
yellow: 'accent-fill-yellow',
green: 'accent-fill-green',
cyan: 'accent-fill-cyan',
blue: 'accent-fill-blue',
purple: 'accent-fill-purple',
pink: 'accent-fill-pink',
rose: 'accent-fill-rose',
teal: 'accent-fill-teal',
};
export function Alert({ accent, children, className, role }: AlertProps) {
return (
<div
role={role ?? (accent === 'red' || accent === 'rose' ? 'alert' : 'status')}
className={cn(
'rounded-md border border-current/30 px-3 py-2 font-mono text-xs',
ACCENT_FILL[accent],
className,
)}
>
{children}
</div>
);
}

View File

@@ -0,0 +1,45 @@
import type { ButtonHTMLAttributes, ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
accent?: Accent;
variant?: 'solid' | 'outline' | 'ghost';
children: ReactNode;
}
const ACCENT_OUTLINE: Record<Accent, string> = {
red: 'border-red text-red hover:bg-red/10',
orange: 'border-orange text-orange hover:bg-orange/10',
yellow: 'border-yellow text-yellow hover:bg-yellow/10',
green: 'border-green text-green hover:bg-green/10',
cyan: 'border-cyan text-cyan hover:bg-cyan/10',
blue: 'border-blue text-blue hover:bg-blue/10',
purple: 'border-purple text-purple hover:bg-purple/10',
pink: 'border-pink text-pink hover:bg-pink/10',
rose: 'border-rose text-rose hover:bg-rose/10',
teal: 'border-teal text-teal hover:bg-teal/10',
};
/** Minimal button matching the briefing aesthetic — no shadows, thin borders. */
export function Button({
accent = 'cyan',
variant = 'outline',
className,
children,
...rest
}: ButtonProps) {
const base =
'inline-flex items-center justify-center rounded-md border px-3 py-2 font-mono text-xs font-medium uppercase tracking-wider2 disabled:opacity-50 disabled:pointer-events-none';
const variantCls =
variant === 'outline'
? ACCENT_OUTLINE[accent]
: variant === 'ghost'
? 'border-transparent text-text hover:bg-bg-card'
: 'border-transparent bg-bg-card text-text-bright';
return (
<button className={cn(base, variantCls, className)} {...rest}>
{children}
</button>
);
}

View File

@@ -0,0 +1,50 @@
import type { HTMLAttributes, ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface CardProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
/** Accent border color — distinguishes the card's category. */
accent?: Accent;
/** Card heading. Renamed from the native HTMLAttributes.title (string-only). */
title?: ReactNode;
/** Subtitle / metadata line below the title. */
sub?: ReactNode;
children?: ReactNode;
}
const ACCENT_BORDER: Record<Accent, string> = {
red: 'border-red',
orange: 'border-orange',
yellow: 'border-yellow',
green: 'border-green',
cyan: 'border-cyan',
blue: 'border-blue',
purple: 'border-purple',
pink: 'border-pink',
rose: 'border-rose',
teal: 'border-teal',
};
/** Card from design.md §5.3 — shared chrome, accent-only differentiation. */
export function Card({ accent, title, sub, children, className, ...rest }: CardProps) {
return (
<div
className={cn(
'bg-bg-card rounded-lg border p-5',
accent ? ACCENT_BORDER[accent] : 'border-border',
className,
)}
{...rest}
>
{title && (
<h3 className="font-mono text-sm font-semibold text-text-bright mb-1">{title}</h3>
)}
{sub && (
<div className="font-mono text-4xs uppercase tracking-wider2 text-text-dim mb-3">
{sub}
</div>
)}
{children && <div className="text-xs leading-[1.7]">{children}</div>}
</div>
);
}

View File

@@ -0,0 +1,37 @@
import type { ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface FlowNodeProps {
accent?: Accent;
children: ReactNode;
className?: string;
}
const ACCENT_BORDER_TEXT: Record<Accent, string> = {
red: 'border-red text-red',
orange: 'border-orange text-orange',
yellow: 'border-yellow text-yellow',
green: 'border-green text-green',
cyan: 'border-cyan text-cyan',
blue: 'border-blue text-blue',
purple: 'border-purple text-purple',
pink: 'border-pink text-pink',
rose: 'border-rose text-rose',
teal: 'border-teal text-teal',
};
/** Flow node from design.md §5.5 — chained horizontally with arrows in flex rows. */
export function FlowNode({ accent, children, className }: FlowNodeProps) {
return (
<span
className={cn(
'inline-block bg-bg-card rounded-md border px-3 py-2 font-mono text-4xs whitespace-nowrap shrink-0',
accent ? ACCENT_BORDER_TEXT[accent] : 'border-border text-text',
className,
)}
>
{children}
</span>
);
}

View File

@@ -0,0 +1,62 @@
import { useEffect, useRef, type ReactNode } from 'react';
import { Button } from '@/components/ui/Button';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { type Accent } from '@/lib/cn';
interface ModalProps {
open: boolean;
title: string;
accent?: Accent;
onClose: () => void;
children: ReactNode;
/** Optional name to give the dialog role for screen readers / Playwright. */
testid?: string;
}
/**
* Centered modal with a backdrop. Closes on Escape and on backdrop click.
* The accessible name comes from the SectionHeader's `highlight`, so the dialog
* can be located via `getByRole('dialog', { name: ... })`.
*/
export function Modal({ open, title, accent = 'cyan', onClose, children, testid }: ModalProps) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') onClose();
}
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [open, onClose]);
if (!open) return null;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
onMouseDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
role="presentation"
>
<div
ref={ref}
role="dialog"
aria-modal="true"
aria-label={title}
data-testid={testid}
className="w-full max-w-2xl rounded-lg border border-border bg-bg-base p-6 shadow-2xl"
>
<div className="flex items-start justify-between gap-4">
<SectionHeader prefix="Edit" highlight={title} accent={accent} className="mt-0 mb-4" />
<Button variant="ghost" onClick={onClose} aria-label="Close dialog">
</Button>
</div>
{children}
</div>
</div>
);
}

View File

@@ -0,0 +1,51 @@
import type { ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface SectionHeaderProps {
/** Plain text leading the colored word. */
prefix?: string;
/** The single colored word in the title. */
highlight: string;
accent?: Accent;
description?: ReactNode;
className?: string;
}
const ACCENT_TEXT: Record<Accent, string> = {
red: 'text-red',
orange: 'text-orange',
yellow: 'text-yellow',
green: 'text-green',
cyan: 'text-cyan',
blue: 'text-blue',
purple: 'text-purple',
pink: 'text-pink',
rose: 'text-rose',
teal: 'text-teal',
};
/**
* Section header from design.md §5.2 — every h2 starts with a cyan `//`,
* a plain word, and exactly one colored word.
*/
export function SectionHeader({
prefix,
highlight,
accent = 'red',
description,
className,
}: SectionHeaderProps) {
return (
<div className={cn('mt-[60px] mb-[30px]', className)}>
<h2 className="font-mono text-lg font-semibold text-text-bright pb-3 border-b border-border">
<span className="text-cyan">{'// '}</span>
{prefix && <span>{prefix} </span>}
<span className={ACCENT_TEXT[accent]}>{highlight}</span>
</h2>
{description && (
<p className="font-mono text-xs text-text-dim mt-2">{description}</p>
)}
</div>
);
}

View File

@@ -0,0 +1,37 @@
import type { ReactNode } from 'react';
import { cn, type Accent } from '@/lib/cn';
interface TagProps {
accent: Accent;
children: ReactNode;
className?: string;
}
const ACCENT_FILL: Record<Accent, string> = {
red: 'accent-fill-red',
orange: 'accent-fill-orange',
yellow: 'accent-fill-yellow',
green: 'accent-fill-green',
cyan: 'accent-fill-cyan',
blue: 'accent-fill-blue',
purple: 'accent-fill-purple',
pink: 'accent-fill-pink',
rose: 'accent-fill-rose',
teal: 'accent-fill-teal',
};
/** Tag/pill from design.md §5.4 — 9px uppercase mono, tinted fill. */
export function Tag({ accent, children, className }: TagProps) {
return (
<span
className={cn(
'inline-block rounded font-mono text-3xs font-semibold uppercase tracking-wider2 px-2 py-[3px] mr-1 mb-2',
ACCENT_FILL[accent],
className,
)}
>
{children}
</span>
);
}

View File

@@ -0,0 +1,48 @@
import { forwardRef, useId, type InputHTMLAttributes } from 'react';
import { cn } from '@/lib/cn';
interface TextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
label: string;
hint?: string;
errorText?: string;
}
/**
* Form field with explicit label/input association via `htmlFor` / `id`.
* The hint and error text are rendered as siblings, NOT inside the `<label>`,
* so the accessible name of the input remains exactly the `label` prop —
* crucial for `getByLabel(...)` selectors in Playwright.
*/
export const TextField = forwardRef<HTMLInputElement, TextFieldProps>(function TextField(
{ label, hint, errorText, className, id, ...rest },
ref,
) {
const fallbackId = useId();
const inputId = id ?? fallbackId;
return (
<div className="block">
<label
htmlFor={inputId}
className="block font-mono text-3xs font-semibold uppercase tracking-wider2 text-text-dim"
>
{label}
</label>
<input
ref={ref}
id={inputId}
className={cn(
'mt-1 w-full rounded-md border bg-bg-card px-3 py-2 font-mono text-xs text-text-bright placeholder:text-text-dim',
errorText ? 'border-red' : 'border-border focus:border-cyan',
'focus:outline-none',
className,
)}
{...rest}
/>
{hint && !errorText && (
<p className="mt-1 font-mono text-2xs text-text-dim">{hint}</p>
)}
{errorText && <p className="mt-1 font-mono text-2xs text-red">{errorText}</p>}
</div>
);
});

49
frontend/src/index.css Normal file
View File

@@ -0,0 +1,49 @@
/* Self-hosted webfonts — no runtime CDN (cf. spec §7). */
@import '@fontsource/jetbrains-mono/300.css';
@import '@fontsource/jetbrains-mono/400.css';
@import '@fontsource/jetbrains-mono/500.css';
@import '@fontsource/jetbrains-mono/600.css';
@import '@fontsource/jetbrains-mono/700.css';
@import '@fontsource/ibm-plex-sans/300.css';
@import '@fontsource/ibm-plex-sans/400.css';
@import '@fontsource/ibm-plex-sans/500.css';
@import '@fontsource/ibm-plex-sans/600.css';
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
html,
body,
#root {
@apply min-h-screen;
}
body {
@apply bg-bg text-text font-sans;
line-height: 1.6;
}
/* No transitions / hovers / animations baseline (cf. design.md §7). */
*:focus-visible {
outline: 1px solid theme('colors.cyan');
outline-offset: 2px;
}
::selection {
background: rgb(6 182 212 / 0.25);
color: theme('colors.text-bright');
}
}
@layer utilities {
/* Tinted accent fill — see design.md §2 "tinted fills". */
.accent-fill-red { background: rgb(239 68 68 / 0.15); color: theme('colors.red'); }
.accent-fill-orange { background: rgb(245 158 11 / 0.15); color: theme('colors.orange'); }
.accent-fill-yellow { background: rgb(234 179 8 / 0.15); color: theme('colors.yellow'); }
.accent-fill-green { background: rgb(16 185 129 / 0.15); color: theme('colors.green'); }
.accent-fill-cyan { background: rgb(6 182 212 / 0.15); color: theme('colors.cyan'); }
.accent-fill-blue { background: rgb(59 130 246 / 0.15); color: theme('colors.blue'); }
.accent-fill-purple { background: rgb(139 92 246 / 0.15); color: theme('colors.purple'); }
.accent-fill-pink { background: rgb(236 72 153 / 0.15); color: theme('colors.pink'); }
.accent-fill-rose { background: rgb(244 63 94 / 0.15); color: theme('colors.rose'); }
.accent-fill-teal { background: rgb(20 184 166 / 0.15); color: theme('colors.teal'); }
}

72
frontend/src/lib/admin.ts Normal file
View File

@@ -0,0 +1,72 @@
/**
* Shared types + query keys for admin pages (users / groups / invitations).
* Keeps the React Query cache coherent across the 3 admin pages.
*/
export interface AdminUser {
id: string;
email: string;
display_name: string | null;
locale: string;
is_active: boolean;
deleted_at: string | null;
created_at: string;
updated_at: string;
groups: Array<{ id: string; name: string }>;
}
export interface AdminUserListResponse {
items: AdminUser[];
total: number;
limit: number;
offset: number;
}
export interface AdminGroup {
id: string;
name: string;
description: string | null;
is_system: boolean;
members_count: number;
permissions: string[];
created_at: string;
updated_at: string;
}
export interface AdminGroupListResponse {
items: AdminGroup[];
total: number;
}
export interface AdminPermission {
id: string;
code: string;
description: string | null;
}
export interface AdminInvitation {
id: string;
email_hint: string | null;
expires_at: string;
groups: string[];
}
export const adminKeys = {
users: ['admin', 'users'] as const,
user: (id: string) => ['admin', 'users', id] as const,
groups: ['admin', 'groups'] as const,
group: (id: string) => ['admin', 'groups', id] as const,
permissions: ['admin', 'permissions'] as const,
invitations: ['admin', 'invitations'] as const,
};
/** Group permission codes by family for the multi-select UI. */
export function groupPermsByFamily(codes: string[]): Record<string, string[]> {
const out: Record<string, string[]> = {};
for (const code of codes) {
const [family] = code.split('.', 1);
(out[family] ??= []).push(code);
}
for (const family of Object.keys(out)) out[family].sort();
return out;
}

141
frontend/src/lib/api.ts Normal file
View File

@@ -0,0 +1,141 @@
/**
* Auth-aware fetch wrapper.
*
* Strategy:
* - Access token kept in module memory (never in localStorage).
* - Refresh token lives in an HTTPOnly cookie set by the backend.
* - On 401, we try ONE silent refresh via /auth/refresh, retry, then give up.
*
* Consumers go through `apiFetch`, `apiGet`, `apiPost` helpers.
*/
const BASE_URL = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
type AccessTokenListener = (token: string | null) => void;
let accessToken: string | null = null;
const listeners = new Set<AccessTokenListener>();
export function setAccessToken(t: string | null) {
accessToken = t;
for (const l of listeners) l(t);
}
export function getAccessToken(): string | null {
return accessToken;
}
export function onAccessTokenChange(fn: AccessTokenListener): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
/** Returns true if the refresh succeeded and `accessToken` is updated. */
async function silentRefresh(): Promise<boolean> {
try {
const res = await fetch(`${BASE_URL}/auth/refresh`, {
method: 'POST',
credentials: 'include',
});
if (!res.ok) return false;
const body = (await res.json()) as { access_token: string };
if (!body.access_token) return false;
setAccessToken(body.access_token);
return true;
} catch {
return false;
}
}
interface ApiOptions extends RequestInit {
/** Skip the silent-refresh path — used by /auth/* endpoints themselves. */
noRefresh?: boolean;
/** Skip Authorization header — used for /setup and unauthenticated probes. */
anonymous?: boolean;
}
export async function apiFetch(path: string, opts: ApiOptions = {}): Promise<Response> {
const headers = new Headers(opts.headers);
headers.set('Accept', 'application/json');
if (!headers.has('Content-Type') && opts.body && !(opts.body instanceof FormData)) {
headers.set('Content-Type', 'application/json');
}
if (!opts.anonymous && accessToken) {
headers.set('Authorization', `Bearer ${accessToken}`);
}
let res = await fetch(`${BASE_URL}${path}`, {
...opts,
headers,
credentials: 'include',
});
if (res.status === 401 && !opts.noRefresh && !opts.anonymous) {
const refreshed = await silentRefresh();
if (refreshed) {
headers.set('Authorization', `Bearer ${accessToken}`);
res = await fetch(`${BASE_URL}${path}`, {
...opts,
headers,
credentials: 'include',
});
}
}
return res;
}
export class ApiError extends Error {
constructor(
public status: number,
public payload: unknown,
message?: string,
) {
super(message ?? `HTTP ${status}`);
}
}
async function parseOrThrow<T>(res: Response): Promise<T> {
if (res.status === 204) return undefined as T;
const isJson = (res.headers.get('content-type') ?? '').includes('application/json');
const body = isJson ? await res.json() : await res.text();
if (!res.ok) throw new ApiError(res.status, body);
return body as T;
}
export async function apiGet<T>(path: string, opts?: ApiOptions): Promise<T> {
return parseOrThrow<T>(await apiFetch(path, { ...opts, method: 'GET' }));
}
export async function apiPost<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
return parseOrThrow<T>(
await apiFetch(path, {
...opts,
method: 'POST',
body: body !== undefined ? JSON.stringify(body) : undefined,
}),
);
}
export async function apiPatch<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
return parseOrThrow<T>(
await apiFetch(path, {
...opts,
method: 'PATCH',
body: body !== undefined ? JSON.stringify(body) : undefined,
}),
);
}
export async function apiPut<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
return parseOrThrow<T>(
await apiFetch(path, {
...opts,
method: 'PUT',
body: body !== undefined ? JSON.stringify(body) : undefined,
}),
);
}
export async function apiDelete<T>(path: string, opts?: ApiOptions): Promise<T> {
return parseOrThrow<T>(await apiFetch(path, { ...opts, method: 'DELETE' }));
}

125
frontend/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,125 @@
/**
* Auth state hook + login/logout helpers.
*
* The hook tries a silent /auth/refresh on mount so a returning user sees
* "logged in" without typing credentials again. If that fails, the SPA
* renders /login.
*/
import { createContext, useContext, useEffect, useState } from 'react';
import { apiPost, getAccessToken, onAccessTokenChange, setAccessToken } from '@/lib/api';
export interface MeResponse {
id: string;
email: string;
display_name: string | null;
locale: string;
is_admin: boolean;
groups: string[];
permissions: string[];
}
export interface AuthState {
loading: boolean;
user: MeResponse | null;
hasAccessToken: boolean;
}
export interface AuthApi {
state: AuthState;
login: (email: string, password: string) => Promise<MeResponse>;
logout: () => Promise<void>;
reload: () => Promise<void>;
}
interface LoginResponse {
access_token: string;
user_id: string;
}
async function fetchMe(): Promise<MeResponse> {
const { apiGet } = await import('@/lib/api');
return apiGet<MeResponse>('/auth/me');
}
export const AuthContext = createContext<AuthApi | null>(null);
export function useAuth(): AuthApi {
const v = useContext(AuthContext);
if (!v) throw new Error('useAuth must be used inside <AuthProvider>');
return v;
}
export function useProvideAuth(): AuthApi {
const [user, setUser] = useState<MeResponse | null>(null);
const [loading, setLoading] = useState(true);
const [hasToken, setHasToken] = useState<boolean>(getAccessToken() !== null);
useEffect(() => onAccessTokenChange((t) => setHasToken(t !== null)), []);
const reload = async () => {
if (!getAccessToken()) {
// Try a silent refresh — if a refresh cookie exists from a prior session.
try {
const r = await apiPost<{ access_token: string }>('/auth/refresh', undefined, {
noRefresh: true,
anonymous: true,
});
if (r.access_token) setAccessToken(r.access_token);
} catch {
/* no cookie, no big deal */
}
}
if (!getAccessToken()) {
setUser(null);
return;
}
try {
setUser(await fetchMe());
} catch {
setAccessToken(null);
setUser(null);
}
};
useEffect(() => {
let cancelled = false;
(async () => {
await reload();
if (!cancelled) setLoading(false);
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const login = async (email: string, password: string): Promise<MeResponse> => {
const r = await apiPost<LoginResponse>(
'/auth/login',
{ email, password },
{ noRefresh: true, anonymous: true },
);
setAccessToken(r.access_token);
const me = await fetchMe();
setUser(me);
return me;
};
const logout = async () => {
try {
await apiPost('/auth/logout', undefined, { noRefresh: true });
} catch {
/* idempotent */
}
setAccessToken(null);
setUser(null);
};
return {
state: { loading, user, hasAccessToken: hasToken },
login,
logout,
reload,
};
}

19
frontend/src/lib/cn.ts Normal file
View File

@@ -0,0 +1,19 @@
/** Tiny classnames helper — keeps deps minimal. */
export function cn(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(' ');
}
export const ACCENTS = [
'red',
'orange',
'yellow',
'green',
'cyan',
'blue',
'purple',
'pink',
'rose',
'teal',
] as const;
export type Accent = (typeof ACCENTS)[number];

14
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,14 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from '@/App';
import '@/index.css';
const root = document.getElementById('root');
if (!root) throw new Error('#root not found in index.html');
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,348 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Modal } from '@/components/ui/Modal';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { Tag } from '@/components/ui/Tag';
import { TextField } from '@/components/ui/TextField';
import {
ApiError,
apiDelete,
apiGet,
apiPatch,
apiPost,
apiPut,
} from '@/lib/api';
import {
adminKeys,
groupPermsByFamily,
type AdminGroup,
type AdminGroupListResponse,
type AdminPermission,
} from '@/lib/admin';
function usePermissions() {
return useQuery({
queryKey: adminKeys.permissions,
queryFn: () => apiGet<{ items: AdminPermission[] }>('/permissions'),
});
}
function useGroups() {
return useQuery({
queryKey: adminKeys.groups,
queryFn: () => apiGet<AdminGroupListResponse>('/groups'),
});
}
export function AdminGroupsPage() {
const groups = useGroups();
const perms = usePermissions();
const [editing, setEditing] = useState<AdminGroup | null>(null);
const [creating, setCreating] = useState(false);
return (
<>
<SectionHeader
prefix="Admin"
highlight="Groups"
accent="purple"
description="Compose custom groups; combine atomic permissions to express any role."
/>
<div className="mb-6 flex items-center justify-between">
<span className="font-mono text-2xs text-text-dim">
{groups.data ? `${groups.data.total} group${groups.data.total === 1 ? '' : 's'}` : ''}
</span>
<Button accent="purple" onClick={() => setCreating(true)} data-testid="create-group">
+ New group
</Button>
</div>
{(groups.isError || perms.isError) && (
<Alert accent="red">Failed to load groups or permissions.</Alert>
)}
<div className="grid gap-3" data-testid="groups-table">
{(groups.isLoading || perms.isLoading) && (
<p className="font-mono text-xs text-text-dim">Loading</p>
)}
{groups.data?.items.map((g) => (
<Card key={g.id} accent={g.is_system ? 'yellow' : 'purple'} title={g.name} sub={g.description ?? '—'}>
<div className="flex flex-wrap items-center gap-2">
{g.is_system && <Tag accent="yellow">SYSTEM</Tag>}
<Tag accent="cyan">{g.members_count} member{g.members_count === 1 ? '' : 's'}</Tag>
<Tag accent="orange">{g.permissions.length} perm{g.permissions.length === 1 ? '' : 's'}</Tag>
<div className="ml-auto flex gap-2">
<Button accent="purple" onClick={() => setEditing(g)} data-testid={`edit-group-${g.name}`}>
Edit
</Button>
</div>
</div>
</Card>
))}
{groups.data && groups.data.items.length === 0 && (
<p className="font-mono text-xs text-text-dim">No groups yet.</p>
)}
</div>
{creating && perms.data && (
<GroupCreateModal allPerms={perms.data.items} onClose={() => setCreating(false)} />
)}
{editing && perms.data && (
<GroupEditModal
group={editing}
allPerms={perms.data.items}
onClose={() => setEditing(null)}
/>
)}
</>
);
}
interface PermsMultiSelectProps {
allPerms: AdminPermission[];
selected: Set<string>;
onToggle: (code: string) => void;
}
function PermsMultiSelect({ allPerms, selected, onToggle }: PermsMultiSelectProps) {
const byFamily = useMemo(
() => groupPermsByFamily(allPerms.map((p) => p.code)),
[allPerms],
);
return (
<div className="max-h-72 overflow-y-auto rounded border border-border bg-bg-card p-3" data-testid="perms-multiselect">
{Object.entries(byFamily).map(([family, codes]) => (
<div key={family} className="mb-3 last:mb-0">
<p className="font-mono text-3xs uppercase tracking-wider2 text-text-dim mb-2">
{family}
</p>
<div className="flex flex-wrap gap-2">
{codes.map((code) => (
<label
key={code}
className="inline-flex items-center gap-2 rounded border border-border px-2 py-1 cursor-pointer hover:border-cyan"
>
<input
type="checkbox"
checked={selected.has(code)}
onChange={() => onToggle(code)}
data-testid={`perm-${code}`}
/>
<span className="font-mono text-2xs">{code}</span>
</label>
))}
</div>
</div>
))}
</div>
);
}
function GroupCreateModal({
allPerms,
onClose,
}: {
allPerms: AdminPermission[];
onClose: () => void;
}) {
const qc = useQueryClient();
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [selected, setSelected] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
const createGroup = useMutation({
mutationFn: () =>
apiPost<AdminGroup>('/groups', {
name: name.trim(),
description: description.trim() || null,
}),
});
const setPerms = useMutation({
mutationFn: (groupId: string) =>
apiPut(`/groups/${groupId}/permissions`, { codes: Array.from(selected) }),
});
async function save() {
setError(null);
try {
const g = await createGroup.mutateAsync();
if (selected.size) await setPerms.mutateAsync(g.id);
await qc.invalidateQueries({ queryKey: adminKeys.groups });
onClose();
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Save failed');
}
}
}
return (
<Modal open onClose={onClose} title="new group" accent="purple" testid="group-create-modal">
<div className="space-y-4">
<TextField
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
hint="Lower-case-with-dashes recommended (e.g. pentest-2026-Q2)"
required
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div>
<p className="font-mono text-3xs uppercase tracking-wider2 text-text-dim mb-2">
Permissions
</p>
<PermsMultiSelect
allPerms={allPerms}
selected={selected}
onToggle={(code) =>
setSelected((prev) => {
const next = new Set(prev);
if (next.has(code)) next.delete(code);
else next.add(code);
return next;
})
}
/>
</div>
{error && <Alert accent="red">{error}</Alert>}
<div className="flex justify-end gap-2 pt-2">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button accent="purple" onClick={save} data-testid="group-create-save">
Create group
</Button>
</div>
</div>
</Modal>
);
}
function GroupEditModal({
group,
allPerms,
onClose,
}: {
group: AdminGroup;
allPerms: AdminPermission[];
onClose: () => void;
}) {
const qc = useQueryClient();
const [name, setName] = useState(group.name);
const [description, setDescription] = useState(group.description ?? '');
const [selected, setSelected] = useState<Set<string>>(new Set(group.permissions));
const [error, setError] = useState<string | null>(null);
const patchGroup = useMutation({
mutationFn: () =>
apiPatch(`/groups/${group.id}`, {
name: group.is_system ? undefined : name.trim(),
description: description.trim() || null,
}),
});
const setPerms = useMutation({
mutationFn: () =>
apiPut(`/groups/${group.id}/permissions`, { codes: Array.from(selected) }),
});
const del = useMutation({
mutationFn: () => apiDelete(`/groups/${group.id}`),
});
async function save() {
setError(null);
try {
await patchGroup.mutateAsync();
await setPerms.mutateAsync();
await qc.invalidateQueries({ queryKey: adminKeys.groups });
onClose();
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Save failed');
}
}
}
async function handleDelete() {
if (!confirm(`Soft-delete group "${group.name}"?`)) return;
try {
await del.mutateAsync();
await qc.invalidateQueries({ queryKey: adminKeys.groups });
onClose();
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Delete failed');
}
}
}
return (
<Modal open onClose={onClose} title={group.name} accent="purple" testid="group-edit-modal">
<div className="space-y-4">
<TextField
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={group.is_system}
hint={group.is_system ? 'System groups cannot be renamed.' : undefined}
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<div>
<p className="font-mono text-3xs uppercase tracking-wider2 text-text-dim mb-2">
Permissions
</p>
<PermsMultiSelect
allPerms={allPerms}
selected={selected}
onToggle={(code) =>
setSelected((prev) => {
const next = new Set(prev);
if (next.has(code)) next.delete(code);
else next.add(code);
return next;
})
}
/>
</div>
{error && <Alert accent="red">{error}</Alert>}
<div className="flex items-center justify-between gap-3 pt-2">
{!group.is_system && (
<Button accent="rose" onClick={handleDelete}>
Delete group
</Button>
)}
<div className="ml-auto flex gap-2">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button accent="purple" onClick={save} data-testid="group-edit-save">
Save changes
</Button>
</div>
</div>
</div>
</Modal>
);
}

View File

@@ -0,0 +1,233 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Modal } from '@/components/ui/Modal';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { Tag } from '@/components/ui/Tag';
import { TextField } from '@/components/ui/TextField';
import { ApiError, apiGet, apiPost } from '@/lib/api';
import {
adminKeys,
type AdminGroupListResponse,
type AdminInvitation,
} from '@/lib/admin';
function useInvitations() {
return useQuery({
queryKey: adminKeys.invitations,
queryFn: () => apiGet<AdminInvitation[]>('/invitations'),
});
}
function useGroups() {
return useQuery({
queryKey: adminKeys.groups,
queryFn: () => apiGet<AdminGroupListResponse>('/groups'),
});
}
export function AdminInvitationsPage() {
const invs = useInvitations();
const groups = useGroups();
const [creating, setCreating] = useState(false);
const [showLink, setShowLink] = useState<string | null>(null);
const qc = useQueryClient();
const revoke = useMutation({
mutationFn: (id: string) => apiPost(`/invitations/${id}/revoke`),
onSuccess: () => qc.invalidateQueries({ queryKey: adminKeys.invitations }),
});
function buildLink(token: string): string {
return `${window.location.origin}/register?token=${encodeURIComponent(token)}`;
}
return (
<>
<SectionHeader
prefix="Admin"
highlight="Invitations"
accent="green"
description="Issue one-shot URLs to onboard new operators. Links expire after 7 days by default."
/>
<div className="mb-6 flex items-center justify-between">
<span className="font-mono text-2xs text-text-dim">
{invs.data ? `${invs.data.length} active invitation${invs.data.length === 1 ? '' : 's'}` : ''}
</span>
<Button accent="green" onClick={() => setCreating(true)} data-testid="create-invitation">
+ New invitation
</Button>
</div>
{invs.isError && <Alert accent="red">Failed to load invitations.</Alert>}
<div className="grid gap-3" data-testid="invitations-table">
{invs.isLoading && <p className="font-mono text-xs text-text-dim">Loading</p>}
{invs.data?.map((inv) => (
<Card
key={inv.id}
accent="green"
title={inv.email_hint ?? '(no email hint)'}
sub={`expires ${new Date(inv.expires_at).toLocaleString()}`}
>
<div className="flex flex-wrap items-center gap-2">
{inv.groups.map((g) => (
<Tag key={g} accent="purple">
{g}
</Tag>
))}
{inv.groups.length === 0 && <Tag accent="orange">no pre-assigned groups</Tag>}
<Button
accent="rose"
className="ml-auto"
onClick={() => {
if (!confirm(`Revoke invitation for ${inv.email_hint ?? '(no email)'}?`)) return;
revoke.mutate(inv.id);
}}
data-testid={`revoke-${inv.id}`}
>
Revoke
</Button>
</div>
</Card>
))}
{invs.data && invs.data.length === 0 && (
<p className="font-mono text-xs text-text-dim">No active invitations.</p>
)}
</div>
{creating && groups.data && (
<InvitationCreateModal
allGroups={groups.data.items}
onClose={() => setCreating(false)}
onCreated={(token) => setShowLink(buildLink(token))}
/>
)}
{showLink && (
<Modal open onClose={() => setShowLink(null)} title="invitation link" accent="green">
<div className="space-y-3">
<p className="font-mono text-xs text-text-dim">
Copy this URL and send it to the invitee. It will be shown <strong>only once</strong>.
</p>
<code
className="block break-all rounded border border-green bg-bg-card p-3 font-mono text-2xs text-text-bright"
data-testid="invitation-link"
>
{showLink}
</code>
<div className="flex justify-end gap-2">
<Button
accent="green"
onClick={async () => {
await navigator.clipboard.writeText(showLink);
}}
>
Copy
</Button>
<Button variant="ghost" onClick={() => setShowLink(null)}>
Close
</Button>
</div>
</div>
</Modal>
)}
</>
);
}
function InvitationCreateModal({
allGroups,
onClose,
onCreated,
}: {
allGroups: AdminGroupListResponse['items'];
onClose: () => void;
onCreated: (token: string) => void;
}) {
const qc = useQueryClient();
const [emailHint, setEmailHint] = useState('');
const [groupIds, setGroupIds] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const create = useMutation({
mutationFn: () =>
apiPost<{ id: string; token: string; expires_at: string }>('/invitations', {
email_hint: emailHint.trim() || null,
group_ids: groupIds,
}),
});
async function save() {
setError(null);
try {
const r = await create.mutateAsync();
await qc.invalidateQueries({ queryKey: adminKeys.invitations });
onClose();
onCreated(r.token);
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Create failed');
}
}
}
return (
<Modal open onClose={onClose} title="new invitation" accent="green" testid="invitation-create-modal">
<div className="space-y-4">
<TextField
label="Email hint"
placeholder="alice@metamorph.local"
value={emailHint}
onChange={(e) => setEmailHint(e.target.value)}
hint="Optional — purely informative, shown in the admin list."
/>
<div>
<p className="font-mono text-3xs uppercase tracking-wider2 text-text-dim mb-2">
Pre-assigned groups
</p>
<div className="flex flex-wrap gap-2" data-testid="invitation-groups">
{allGroups.map((g) => {
const checked = groupIds.includes(g.id);
return (
<label
key={g.id}
className="inline-flex items-center gap-2 rounded border border-border bg-bg-card px-3 py-1 cursor-pointer hover:border-cyan"
>
<input
type="checkbox"
checked={checked}
onChange={(e) =>
setGroupIds((prev) =>
e.target.checked ? [...prev, g.id] : prev.filter((id) => id !== g.id),
)
}
data-testid={`invitation-group-${g.name}`}
/>
<span className="font-mono text-xs">{g.name}</span>
{g.is_system && <Tag accent="yellow">SYSTEM</Tag>}
</label>
);
})}
</div>
</div>
{error && <Alert accent="red">{error}</Alert>}
<div className="flex justify-end gap-2 pt-2">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button accent="green" onClick={save} data-testid="invitation-create-save">
Generate link
</Button>
</div>
</div>
</Modal>
);
}

View File

@@ -0,0 +1,260 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { Modal } from '@/components/ui/Modal';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { Tag } from '@/components/ui/Tag';
import { TextField } from '@/components/ui/TextField';
import {
ApiError,
apiDelete,
apiGet,
apiPatch,
apiPut,
} from '@/lib/api';
import {
adminKeys,
type AdminGroupListResponse,
type AdminUser,
type AdminUserListResponse,
} from '@/lib/admin';
function useUsers(q: string) {
return useQuery({
queryKey: [...adminKeys.users, q],
queryFn: () => apiGet<AdminUserListResponse>(`/users${q ? `?q=${encodeURIComponent(q)}` : ''}`),
});
}
function useGroups() {
return useQuery({
queryKey: adminKeys.groups,
queryFn: () => apiGet<AdminGroupListResponse>('/groups'),
});
}
export function AdminUsersPage() {
const [q, setQ] = useState('');
const [editing, setEditing] = useState<AdminUser | null>(null);
const { data, isLoading, isError, error } = useUsers(q);
const groupsQuery = useGroups();
return (
<>
<SectionHeader
prefix="Admin"
highlight="Users"
accent="cyan"
description="Manage operator accounts, group memberships, and active status."
/>
<div className="mb-6 flex items-end gap-3">
<TextField
label="Search"
placeholder="email or display name"
value={q}
onChange={(e) => setQ(e.target.value)}
className="max-w-sm"
/>
<span className="font-mono text-2xs text-text-dim mb-3">
{data ? `${data.total} user${data.total === 1 ? '' : 's'}` : ''}
</span>
</div>
{isError && (
<Alert accent="red">
{(error instanceof ApiError && (error.payload as { error?: string })?.error) ||
'Failed to load users.'}
</Alert>
)}
<div className="grid gap-3" data-testid="users-table">
{isLoading && <p className="font-mono text-xs text-text-dim">Loading</p>}
{data?.items.map((u) => (
<Card
key={u.id}
accent={u.is_active ? 'cyan' : 'rose'}
title={u.email}
sub={u.display_name ?? '—'}
>
<div className="flex flex-wrap items-center gap-2">
{u.groups.map((g) => (
<Tag key={g.id} accent="purple">
{g.name}
</Tag>
))}
{!u.is_active && <Tag accent="rose">DISABLED</Tag>}
<div className="ml-auto flex gap-2">
<Button
accent="cyan"
onClick={() => setEditing(u)}
data-testid={`edit-user-${u.email}`}
>
Edit
</Button>
</div>
</div>
</Card>
))}
{data && data.items.length === 0 && (
<p className="font-mono text-xs text-text-dim">No users match.</p>
)}
</div>
{editing && groupsQuery.data && (
<UserEditModal
user={editing}
allGroups={groupsQuery.data.items}
onClose={() => setEditing(null)}
/>
)}
</>
);
}
interface UserEditModalProps {
user: AdminUser;
allGroups: AdminGroupListResponse['items'];
onClose: () => void;
}
function UserEditModal({ user, allGroups, onClose }: UserEditModalProps) {
const qc = useQueryClient();
const [displayName, setDisplayName] = useState(user.display_name ?? '');
const [locale, setLocale] = useState(user.locale);
const [isActive, setIsActive] = useState(user.is_active);
const [groupIds, setGroupIds] = useState<string[]>(user.groups.map((g) => g.id));
const [error, setError] = useState<string | null>(null);
const invalidate = () =>
Promise.all([
qc.invalidateQueries({ queryKey: adminKeys.users }),
qc.invalidateQueries({ queryKey: adminKeys.groups }),
]);
const updateMeta = useMutation({
mutationFn: () =>
apiPatch(`/users/${user.id}`, {
display_name: displayName.trim() || null,
locale,
is_active: isActive,
}),
onSuccess: invalidate,
});
const updateGroups = useMutation({
mutationFn: () => apiPut(`/users/${user.id}/groups`, { group_ids: groupIds }),
onSuccess: invalidate,
});
const softDelete = useMutation({
mutationFn: () => apiDelete(`/users/${user.id}`),
onSuccess: () => invalidate().then(onClose),
});
async function handleSave() {
setError(null);
try {
await updateMeta.mutateAsync();
await updateGroups.mutateAsync();
onClose();
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Save failed');
}
}
}
async function handleDelete() {
setError(null);
if (!confirm(`Soft-delete user ${user.email}? They will be deactivated and hidden.`)) return;
try {
await softDelete.mutateAsync();
} catch (e) {
if (e instanceof ApiError) {
const p = e.payload as { error?: string; message?: string } | null;
setError(p?.message ?? p?.error ?? `HTTP ${e.status}`);
} else {
setError(e instanceof Error ? e.message : 'Delete failed');
}
}
}
return (
<Modal open onClose={onClose} title={user.email} accent="cyan" testid="user-edit-modal">
<div className="space-y-4">
<TextField
label="Display name"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
/>
<TextField
label="Locale"
value={locale}
onChange={(e) => setLocale(e.target.value)}
hint="ISO-639-1 (fr or en)"
/>
<label className="flex items-center gap-2 font-mono text-xs text-text-dim">
<input
type="checkbox"
checked={isActive}
onChange={(e) => setIsActive(e.target.checked)}
/>
<span>Account active</span>
</label>
<div>
<p className="font-mono text-3xs uppercase tracking-wider2 text-text-dim mb-2">
Groups
</p>
<div className="flex flex-wrap gap-2" data-testid="group-checkboxes">
{allGroups.map((g) => {
const checked = groupIds.includes(g.id);
return (
<label
key={g.id}
className="inline-flex items-center gap-2 rounded border border-border bg-bg-card px-3 py-1 cursor-pointer hover:border-cyan"
>
<input
type="checkbox"
checked={checked}
onChange={(e) =>
setGroupIds((prev) =>
e.target.checked ? [...prev, g.id] : prev.filter((id) => id !== g.id),
)
}
data-testid={`group-checkbox-${g.name}`}
/>
<span className="font-mono text-xs">{g.name}</span>
{g.is_system && <Tag accent="yellow">SYSTEM</Tag>}
</label>
);
})}
</div>
</div>
{error && <Alert accent="red">{error}</Alert>}
<div className="flex items-center justify-between gap-3 pt-2">
<Button accent="rose" onClick={handleDelete}>
Soft-delete user
</Button>
<div className="flex gap-2">
<Button variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button accent="cyan" onClick={handleSave} data-testid="user-save">
Save changes
</Button>
</div>
</div>
</div>
</Modal>
);
}

View File

@@ -0,0 +1,185 @@
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { FlowNode } from '@/components/ui/FlowNode';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { Tag } from '@/components/ui/Tag';
import { apiGet } from '@/lib/api';
interface HealthResponse {
status: string;
version: string;
}
interface DbDiagResponse {
reachable: boolean;
alembic_revision?: string | null;
table_count?: number;
error?: string;
}
type HealthState =
| { kind: 'loading' }
| { kind: 'ok'; data: HealthResponse }
| { kind: 'error'; error: string };
type DbState =
| { kind: 'loading' }
| { kind: 'ok'; data: DbDiagResponse }
| { kind: 'error'; error: string };
export function HomePage() {
const [health, setHealth] = useState<HealthState>({ kind: 'loading' });
const [db, setDb] = useState<DbState>({ kind: 'loading' });
useEffect(() => {
let cancelled = false;
apiGet<HealthResponse>('/health', { anonymous: true })
.then((data) => !cancelled && setHealth({ kind: 'ok', data }))
.catch((err: unknown) =>
!cancelled &&
setHealth({ kind: 'error', error: err instanceof Error ? err.message : String(err) }),
);
apiGet<DbDiagResponse>('/diag/db', { anonymous: true })
.then((data) => !cancelled && setDb({ kind: 'ok', data }))
.catch((err: unknown) =>
!cancelled &&
setDb({ kind: 'error', error: err instanceof Error ? err.message : String(err) }),
);
return () => {
cancelled = true;
};
}, []);
return (
<>
<header className="text-center mb-12">
<h1 className="font-mono text-[28px] font-bold tracking-tight text-text-bright">
<span className="text-red">Meta</span>
<span>morph</span>{' '}
<span className="text-purple">Purple Team Platform</span>
</h1>
<p className="font-mono text-sm font-light text-text-dim mt-2">
Collaborative red &amp; blue test orchestration M3 milestone (RBAC)
</p>
</header>
<SectionHeader
prefix="System"
highlight="Health"
accent="cyan"
description="Live status pulled from /api/v1/health and /api/v1/diag/db."
/>
<div className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(420px,1fr))]">
<Card
accent={health.kind === 'ok' ? 'green' : health.kind === 'error' ? 'red' : 'cyan'}
title="API"
sub={
health.kind === 'loading'
? 'probing…'
: health.kind === 'error'
? 'unreachable'
: `version ${health.data.version}`
}
>
{health.kind === 'loading' && <p>Waiting for the backend</p>}
{health.kind === 'ok' && (
<p>
Status:{' '}
<code className="accent-fill-green px-2 py-[2px] rounded-sm font-mono text-4xs">
{health.data.status}
</code>
</p>
)}
{health.kind === 'error' && (
<p>
Error:{' '}
<code className="accent-fill-red px-2 py-[2px] rounded-sm font-mono text-4xs">
{health.error}
</code>
</p>
)}
</Card>
<Card
accent={db.kind === 'ok' && db.data.reachable ? 'blue' : db.kind === 'error' ? 'red' : 'cyan'}
title="Database"
sub={
db.kind === 'loading'
? 'probing…'
: db.kind === 'error'
? 'unreachable'
: db.data.reachable
? `revision ${db.data.alembic_revision?.slice(0, 8) ?? 'unknown'}`
: 'unreachable'
}
>
{db.kind === 'ok' && db.data.reachable && (
<p>
Tables:{' '}
<code
className="accent-fill-blue px-2 py-[2px] rounded-sm font-mono text-4xs"
data-testid="db-table-count"
>
{db.data.table_count}
</code>{' '}
· Alembic head reached.
</p>
)}
{(db.kind === 'loading' || (db.kind === 'ok' && !db.data.reachable)) && (
<p>Querying schema metadata</p>
)}
{db.kind === 'error' && (
<p>
Error:{' '}
<code className="accent-fill-red px-2 py-[2px] rounded-sm font-mono text-4xs">
{db.error}
</code>
</p>
)}
</Card>
<Card accent="purple" title="Roadmap" sub="14 milestones">
<p>
M0 + M1 + M2 + M3 done. Next:{' '}
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
M4 MITRE ATT&amp;CK
</code>
.
</p>
</Card>
</div>
<SectionHeader
prefix="Design"
highlight="Tokens"
accent="orange"
description="Sanity check of the RTOps design system primitives (cf. tasks/design.md)."
/>
<div className="mb-6">
<Tag accent="red">EVASION</Tag>
<Tag accent="purple">C2</Tag>
<Tag accent="cyan">LATERAL</Tag>
<Tag accent="orange">CRED</Tag>
<Tag accent="green">PHISH</Tag>
<Tag accent="teal">PERSIST</Tag>
</div>
<div className="flex items-center gap-1 flex-wrap py-3 mb-6">
<FlowNode accent="orange">recon</FlowNode>
<span className="text-text-dim font-mono text-2xs"></span>
<FlowNode accent="green">phish</FlowNode>
<span className="text-text-dim font-mono text-2xs"></span>
<FlowNode accent="purple">c2</FlowNode>
<span className="text-text-dim font-mono text-2xs"></span>
<FlowNode accent="cyan">lateral</FlowNode>
<span className="text-text-dim font-mono text-2xs"></span>
<FlowNode accent="red">impact</FlowNode>
</div>
<div className="flex gap-2">
<Button accent="cyan">Primary</Button>
<Button accent="red">Danger</Button>
<Button variant="ghost">Cancel</Button>
</div>
</>
);
}

View File

@@ -0,0 +1,95 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { TextField } from '@/components/ui/TextField';
import { ApiError, apiGet } from '@/lib/api';
import { useAuth } from '@/lib/auth';
interface SetupStatus {
completed: boolean;
}
export function LoginPage() {
const auth = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [setupNeeded, setSetupNeeded] = useState(false);
const emailRef = useRef<HTMLInputElement>(null);
useEffect(() => {
apiGet<SetupStatus>('/setup', { anonymous: true })
.then((s) => setSetupNeeded(!s.completed))
.catch(() => setSetupNeeded(false));
emailRef.current?.focus();
}, []);
useEffect(() => {
if (auth.state.user) navigate('/', { replace: true });
}, [auth.state.user, navigate]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await auth.login(email, password);
navigate('/', { replace: true });
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
setError('Invalid email or password.');
} else if (err instanceof ApiError && err.status === 429) {
setError('Too many attempts. Wait a minute.');
} else {
setError(err instanceof Error ? err.message : 'Login failed.');
}
} finally {
setBusy(false);
}
}
return (
<div className="mx-auto max-w-md mt-12">
<SectionHeader prefix="Operator" highlight="Login" accent="cyan" />
{setupNeeded && (
<Alert accent="orange" className="mb-4">
No admin account exists yet.{' '}
<Link to="/setup" className="underline text-cyan">
Run the bootstrap setup
</Link>
</Alert>
)}
<Card accent="cyan">
<form onSubmit={handleSubmit} className="space-y-4">
<TextField
ref={emailRef}
label="Email"
type="email"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<TextField
label="Password"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
{error && <Alert accent="red">{error}</Alert>}
<Button type="submit" accent="cyan" disabled={busy}>
{busy ? 'Signing in…' : 'Sign in'}
</Button>
</form>
</Card>
</div>
);
}

View File

@@ -0,0 +1,137 @@
import { useState } from 'react';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { Tag } from '@/components/ui/Tag';
import { TextField } from '@/components/ui/TextField';
import { ApiError, apiPost } from '@/lib/api';
import { useAuth } from '@/lib/auth';
export function ProfilePage() {
const { state, logout } = useAuth();
const user = state.user!;
const [current, setCurrent] = useState('');
const [next, setNext] = useState('');
const [confirm, setConfirm] = useState('');
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
async function handleChangePassword(e: React.FormEvent) {
e.preventDefault();
setMsg(null);
if (next !== confirm) {
setMsg({ kind: 'err', text: 'New passwords do not match.' });
return;
}
if (next.length < 8) {
setMsg({ kind: 'err', text: 'New password must be at least 8 characters.' });
return;
}
setBusy(true);
try {
await apiPost('/auth/change-password', {
current_password: current,
new_password: next,
});
setMsg({ kind: 'ok', text: 'Password updated. You will be signed out for security.' });
setCurrent('');
setNext('');
setConfirm('');
setTimeout(() => logout(), 1500);
} catch (err) {
if (err instanceof ApiError) {
const payload = err.payload as { error?: string; message?: string } | null;
setMsg({
kind: 'err',
text: payload?.message ?? payload?.error ?? `HTTP ${err.status}`,
});
} else {
setMsg({ kind: 'err', text: err instanceof Error ? err.message : 'Update failed.' });
}
} finally {
setBusy(false);
}
}
return (
<>
<SectionHeader prefix="Account" highlight="Profile" accent="cyan" />
<div className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(420px,1fr))]">
<Card accent="cyan" title="Identity" sub={user.is_admin ? 'admin account' : 'operator account'}>
<p>
<span className="text-text-dim">email&nbsp;</span>
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
{user.email}
</code>
</p>
<p className="mt-2">
<span className="text-text-dim">display&nbsp;</span>
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
{user.display_name ?? '—'}
</code>
</p>
<p className="mt-2">
<span className="text-text-dim">locale&nbsp;</span>
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
{user.locale}
</code>
</p>
</Card>
<Card accent="purple" title="Groups" sub={user.groups.length ? '' : 'no groups assigned'}>
{user.groups.length === 0 && <p className="text-text-dim">No groups yet.</p>}
{user.groups.map((g) => (
<Tag key={g} accent="purple">
{g}
</Tag>
))}
</Card>
<Card accent="orange" title="Permissions" sub={user.permissions.length ? '' : user.is_admin ? 'admin (all)' : 'no perms'}>
{user.is_admin && <Tag accent="orange">ADMIN bypasses checks</Tag>}
{user.permissions.map((p) => (
<Tag key={p} accent="orange">
{p}
</Tag>
))}
</Card>
<Card accent="rose" title="Change password">
<form onSubmit={handleChangePassword} className="space-y-3">
<TextField
label="Current password"
type="password"
autoComplete="current-password"
value={current}
onChange={(e) => setCurrent(e.target.value)}
required
/>
<TextField
label="New password"
type="password"
autoComplete="new-password"
value={next}
onChange={(e) => setNext(e.target.value)}
required
hint="Min 8 characters."
/>
<TextField
label="Confirm new password"
type="password"
autoComplete="new-password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
/>
{msg && <Alert accent={msg.kind === 'ok' ? 'green' : 'red'}>{msg.text}</Alert>}
<Button type="submit" accent="rose" disabled={busy}>
{busy ? 'Updating…' : 'Update password'}
</Button>
</form>
</Card>
</div>
</>
);
}

View File

@@ -0,0 +1,163 @@
import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { TextField } from '@/components/ui/TextField';
import { ApiError, apiGet, apiPost } from '@/lib/api';
interface InvitationPreview {
is_valid: boolean;
reason: string | null;
email_hint: string | null;
expires_at: string;
groups: string[];
}
export function RegisterPage() {
const [params] = useSearchParams();
const token = params.get('token') ?? '';
const navigate = useNavigate();
const [preview, setPreview] = useState<InvitationPreview | null>(null);
const [previewError, setPreviewError] = useState<string | null>(null);
const [email, setEmail] = useState('');
const [displayName, setDisplayName] = useState('');
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState(false);
useEffect(() => {
if (!token) {
setPreviewError('Missing invitation token in the URL.');
return;
}
apiGet<InvitationPreview>(`/invitations/preview/${encodeURIComponent(token)}`, {
anonymous: true,
})
.then((p) => {
setPreview(p);
if (p.email_hint) setEmail(p.email_hint);
})
.catch((err: unknown) =>
setPreviewError(err instanceof Error ? err.message : 'Could not load invitation.'),
);
}, [token]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (password !== confirm) {
setError('Passwords do not match.');
return;
}
setBusy(true);
try {
await apiPost(
`/invitations/accept/${encodeURIComponent(token)}`,
{ email, password, display_name: displayName || undefined },
{ anonymous: true, noRefresh: true },
);
setDone(true);
setTimeout(() => navigate('/login', { replace: true }), 1500);
} catch (err) {
if (err instanceof ApiError) {
const payload = err.payload as { error?: string; message?: string } | null;
setError(payload?.message ?? payload?.error ?? `HTTP ${err.status}`);
} else {
setError(err instanceof Error ? err.message : 'Registration failed.');
}
} finally {
setBusy(false);
}
}
if (done) {
return (
<div className="mx-auto max-w-md mt-12">
<Alert accent="green">Account created. Redirecting to login</Alert>
</div>
);
}
if (previewError) {
return (
<div className="mx-auto max-w-md mt-12">
<Alert accent="red">{previewError}</Alert>
</div>
);
}
if (!preview) {
return (
<div className="mx-auto max-w-md mt-12">
<Alert accent="cyan">Loading invitation</Alert>
</div>
);
}
if (!preview.is_valid) {
return (
<div className="mx-auto max-w-md mt-12">
<Alert accent="red">
This invitation is not usable: <code>{preview.reason}</code>
</Alert>
</div>
);
}
return (
<div className="mx-auto max-w-xl mt-12">
<SectionHeader
prefix="Account"
highlight="Registration"
accent="green"
description="Welcome — pick a password to join the platform."
/>
<Card accent="green">
<form onSubmit={handleSubmit} className="space-y-4">
<TextField
label="Email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
hint={preview.email_hint ? `Invited as ${preview.email_hint}` : undefined}
required
/>
<TextField
label="Display name (optional)"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
/>
<TextField
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<TextField
label="Confirm password"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
/>
{preview.groups.length > 0 && (
<Alert accent="cyan">
You will be added to: {preview.groups.map((g) => `[${g}]`).join(' ')}
</Alert>
)}
{error && <Alert accent="red">{error}</Alert>}
<Button type="submit" accent="green" disabled={busy}>
{busy ? 'Creating account…' : 'Create account'}
</Button>
</form>
</Card>
</div>
);
}

View File

@@ -0,0 +1,144 @@
import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Alert } from '@/components/ui/Alert';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { TextField } from '@/components/ui/TextField';
import { ApiError, apiGet, apiPost } from '@/lib/api';
interface SetupStatus {
completed: boolean;
}
export function SetupPage() {
const navigate = useNavigate();
const [token, setToken] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [displayName, setDisplayName] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState(false);
const [completed, setCompleted] = useState<boolean | null>(null);
useEffect(() => {
apiGet<SetupStatus>('/setup', { anonymous: true })
.then((s) => setCompleted(s.completed))
.catch(() => setCompleted(null));
}, []);
if (completed) {
return (
<div className="mx-auto max-w-md mt-12">
<SectionHeader prefix="Setup" highlight="Already Done" accent="green" />
<Card accent="green">
<p>An admin account already exists on this instance.</p>
<Link to="/login" className="mt-3 inline-block underline text-cyan">
Go to login
</Link>
</Card>
</div>
);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (password !== confirm) {
setError('Passwords do not match.');
return;
}
if (password.length < 8) {
setError('Password must be at least 8 characters.');
return;
}
setBusy(true);
try {
await apiPost(
'/setup',
{
install_token: token.trim(),
email,
password,
display_name: displayName || undefined,
},
{ anonymous: true, noRefresh: true },
);
setDone(true);
setTimeout(() => navigate('/login', { replace: true }), 1500);
} catch (err) {
if (err instanceof ApiError) {
const payload = err.payload as { error?: string; message?: string } | null;
setError(payload?.message ?? payload?.error ?? `HTTP ${err.status}`);
} else {
setError(err instanceof Error ? err.message : 'Setup failed.');
}
} finally {
setBusy(false);
}
}
if (done) {
return (
<div className="mx-auto max-w-md mt-12">
<Alert accent="green">Admin created. Redirecting to login</Alert>
</div>
);
}
return (
<div className="mx-auto max-w-xl mt-12">
<SectionHeader
prefix="Bootstrap"
highlight="Setup"
accent="orange"
description="One-shot — paste the install token from the api container logs to create the first admin."
/>
<Card accent="orange">
<form onSubmit={handleSubmit} className="space-y-4">
<TextField
label="Install token"
value={token}
onChange={(e) => setToken(e.target.value)}
required
hint="Found in `make logs-api` (banner: 'INSTALL TOKEN: …')."
/>
<TextField
label="Admin email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<TextField
label="Display name (optional)"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
/>
<TextField
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
hint="Min 8 characters."
/>
<TextField
label="Confirm password"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
required
/>
{error && <Alert accent="red">{error}</Alert>}
<Button type="submit" accent="orange" disabled={busy}>
{busy ? 'Creating admin…' : 'Create admin'}
</Button>
</form>
</Card>
</div>
);
}

9
frontend/src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

View File

@@ -0,0 +1,66 @@
import type { Config } from 'tailwindcss';
/**
* Design tokens from `tasks/design.md` — Red Team Operations Map.
* Dark, flat, terminal-inspired. Color-as-taxonomy: each accent maps to a category.
*/
export default {
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: {
extend: {
colors: {
// Surfaces
bg: '#0a0e1a',
'bg-card': '#111827',
border: '#1e2d3d',
// Text
text: '#94a3b8',
'text-bright': '#f8fafc',
'text-dim': '#64748b',
'text-comment': '#475569',
// Accent palette (each one means a category — see tasks/design.md §2)
red: '#ef4444',
orange: '#f59e0b',
yellow: '#eab308',
green: '#10b981',
cyan: '#06b6d4',
blue: '#3b82f6',
purple: '#8b5cf6',
pink: '#ec4899',
rose: '#f43f5e',
teal: '#14b8a6',
},
fontFamily: {
mono: ['"JetBrains Mono"', 'ui-monospace', 'SFMono-Regular', 'monospace'],
sans: ['"IBM Plex Sans"', 'ui-sans-serif', 'system-ui', 'sans-serif'],
},
fontSize: {
// Custom scale matching design.md §3 — extends the default Tailwind ramp.
// 2xs = arrow labels (8px), 3xs = tag/pill (9px), 4xs = card sub-label, flow node, inline code (10px).
// 11px (pre/footer), 12px (body/section desc), 13/14px (card title), 18px (section h2),
// and 28px (page h1) all already exist in the default ramp.
'2xs': ['8px', '1.4'],
'3xs': ['9px', '1.4'],
'4xs': ['10px', '1.4'],
},
borderRadius: {
sm: '3px',
DEFAULT: '4px',
md: '6px',
lg: '10px',
},
maxWidth: {
page: '1400px',
},
letterSpacing: {
wider2: '1px',
},
},
},
// Safelist accent classes used dynamically (tag categories, flow nodes).
safelist: [
{ pattern: /^(border|text|bg)-(red|orange|yellow|green|cyan|blue|purple|pink|rose|teal)$/ },
{ pattern: /^(border|text|bg)-(red|orange|yellow|green|cyan|blue|purple|pink|rose|teal)\/(\d+)$/ },
],
plugins: [],
} satisfies Config;

View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"useDefineForClassFields": true,
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"exactOptionalPropertyTypes": false,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

29
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,29 @@
import path from 'node:path';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
host: '0.0.0.0',
port: 5173,
proxy: {
// In `npm run dev`, proxy /api/* to the local Flask backend.
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: false,
target: 'es2022',
},
});