Files
Metamorph/frontend/src/pages/RegisterPage.tsx

164 lines
4.8 KiB
TypeScript
Raw Normal View History

feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages Crypto + tokens - app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost= 64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown once, only the hash lives in the DB). - app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access 1h, refresh 30d. Services - services/auth.py: login, refresh with token rotation + reuse-detection chain revoke, logout (idempotent), change_password (forces logout-all). - services/invitations.py: create, preview, accept, revoke. Default 7d TTL. - services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam), consumes the install token, attaches the first user to admin. - core/install_token.py: mints, persists in settings, marks consumed, regenerate hook for /diag/reset. API - POST /setup (consume install token, create 1st admin) + GET /setup (status). - POST /auth/{login,refresh,logout,change-password} + GET /auth/me. - POST /invitations + GET /invitations + GET /invitations/preview/<token> + POST /invitations/accept/<token> + POST /invitations/<id>/revoke. - POST /diag/reset: test-only kill switch (truncate auth tables + mint fresh install token). Allowed in dev too (with WARNING log) so the e2e suite can run against a make-up stack; production locked out. Middleware - @require_auth populates g.current_user (snapshot dataclass, session closed before request handler runs). - @require_perm(*codes): atomic perm union check; admin group bypasses. Perm catalogue lands in M3, scaffolding here. - flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on /auth/change-password & /setup, 10–20/min on invitation endpoints. Disabled in APP_ENV=test. CLI - flask --app app.cli metamorph print-install-token [--force] - flask --app app.cli metamorph seed-mitre (M4 placeholder) Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/. Email validation: app.api._validation.Email permissive RFC-shape regex so internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's deliverability check is too strict for red-team labs. Frontend - lib/{api,auth}.ts: access token in module memory, refresh cookie, automatic 401-retry via /auth/refresh, useAuth() hook. - components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx. - pages/{Login,Setup,Register,Profile}. Testing - tests/test_auth_flow.py: 15 integration tests (24 backend total). - e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total). - tasks/testing-m2.md. DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass applied (Secure unconditional, refresh limit 10/min/IP). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 06:16:48 +02:00
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>
);
}