diff --git a/backend/routes/__init__.py b/backend/routes/__init__.py index 696dece..8605384 100644 --- a/backend/routes/__init__.py +++ b/backend/routes/__init__.py @@ -17,6 +17,7 @@ from routes.organizations import router as organizations_router from routes.personas import router as personas_router from routes.quizzes import router as quizzes_router +from routes.readiness import router as readiness_router from routes.report_inbox import router as report_inbox_router from routes.reports import router as reports_router from routes.risk_profile import router as risk_profile_router @@ -56,5 +57,6 @@ "live_router", "audit_router", "attack_surface_router", + "readiness_router", "report_inbox_router", ] diff --git a/backend/routes/readiness.py b/backend/routes/readiness.py new file mode 100644 index 0000000..83dc482 --- /dev/null +++ b/backend/routes/readiness.py @@ -0,0 +1,21 @@ +from fastapi import APIRouter, Depends + +from models.schemas import User +from services import readiness +from services.auth import require_trainer + +router = APIRouter(prefix="/readiness", tags=["readiness"]) + + +@router.get("") +async def get_readiness(user: User = Depends(require_trainer)): + """Cohort-level readiness overview: index, report-rate trend, remediation loop, + weakest principles and attack-surface posture. Admins see every organization; + trainers only their own.""" + scope = {} if user.role == "admin" else {"organization_id": user.organization_id} + return await readiness.overview( + user_scope=scope, + campaign_scope=scope, + # Same workspace the Attack Surface Map uses for this user. + org_id=user.organization_id or f"org-{user.id}", + ) diff --git a/backend/server.py b/backend/server.py index d9e9874..3b3c0ee 100644 --- a/backend/server.py +++ b/backend/server.py @@ -32,6 +32,7 @@ organizations_router, personas_router, quizzes_router, + readiness_router, report_inbox_router, reports_router, risk_profile_router, @@ -487,6 +488,7 @@ async def health_check(): api_router.include_router(audit_router) api_router.include_router(attack_surface_router) api_router.include_router(report_inbox_router) +api_router.include_router(readiness_router) app.include_router(api_router) diff --git a/backend/services/readiness.py b/backend/services/readiness.py new file mode 100644 index 0000000..1717e29 --- /dev/null +++ b/backend/services/readiness.py @@ -0,0 +1,181 @@ +""" +Readiness overview — the first screen a commander or trainer sees. + +One read-only aggregate that tells the Pretexta story on a single page: +measure (live report rate, lab discrimination) -> remediate (targeted +practice for the principle someone fell for) -> retest. Everything here is +cohort-level; no individual is named (G13), and live results never feed +gamification (G15). +""" + +from statistics import mean +from typing import Any + +from services import attack_surface +from services.database import db +from services.live import launch as launch_svc + +PRINCIPLES = ("reciprocity", "scarcity", "authority", "commitment", "liking", "social_proof") + +# How much each component contributes to the readiness index. Report rate leads: +# it is the defensive behaviour we are training for. Components without data are +# left out and the remaining weights renormalised, so an org that has only run +# lab exercises still gets a meaningful number. +WEIGHTS = {"report_rate": 0.4, "no_click": 0.2, "principles": 0.2, "triage": 0.2} + +# The trend uses this many most-recent launched campaigns. +TREND_CAMPAIGNS = 8 + + +async def _live(scope: dict) -> dict[str, Any]: + campaigns = ( + await db.live_campaigns.find( + {**scope, "launched_at": {"$ne": None}}, + {"_id": 0, "id": 1, "name": 1, "launched_at": 1}, + ) + .sort("launched_at", -1) + .to_list(TREND_CAMPAIGNS) + ) + campaigns.reverse() # oldest -> newest for the trend line + + trend, recipients, reported, clicked = [], 0, 0, 0 + for c in campaigns: + m = await launch_svc.report_rate(c["id"]) + trend.append( + { + "name": c["name"], + "launched_at": c["launched_at"], + "report_rate": m["report_rate"], + "click_rate": m["click_rate"], + "median_time_to_report_min": m["median_time_to_report_min"], + } + ) + recipients += m["recipients"] + reported += m["reported"] + clicked += m["clicked"] + + rates = [t["report_rate"] for t in trend if t["report_rate"] is not None] + return { + "campaigns": len(campaigns), + "recipients": recipients, + "reported": reported, + "clicked": clicked, + "report_rate": round(reported / recipients, 3) if recipients else None, + "click_rate": round(clicked / recipients, 3) if recipients else None, + # Change between the first and the latest campaign in the window. + "report_rate_delta": round(rates[-1] - rates[0], 3) if len(rates) >= 2 else None, + "trend": trend, + } + + +async def _principles(user_ids: list[str]) -> dict[str, float | None]: + profiles = await db.risk_profiles.find( + {"user_id": {"$in": user_ids}}, {"_id": 0, "current_vector": 1} + ).to_list(5000) + out: dict[str, float | None] = {} + for p in PRINCIPLES: + values = [ + prof["current_vector"][p] + for prof in profiles + if isinstance(prof.get("current_vector"), dict) and p in prof["current_vector"] + ] + out[p] = round(mean(values), 1) if values else None + return out + + +async def _lab(user_ids: list[str]) -> dict[str, Any]: + sims = await db.simulations.find( + {"user_id": {"$in": user_ids}, "simulation_type": "triage", "status": "completed"}, + {"_id": 0, "score": 1, "events": 1}, + ).to_list(5000) + d_primes = [ + e["payload"]["d_prime"] + for s in sims + for e in s.get("events") or [] + if e.get("event_type") == "triage_graded" and "d_prime" in (e.get("payload") or {}) + ] + scores = [s["score"] for s in sims if s.get("score") is not None] + return { + "triage_runs": len(sims), + "avg_triage_score": round(mean(scores), 1) if scores else None, + "avg_d_prime": round(mean(d_primes), 2) if d_primes else None, + } + + +async def _loop(user_ids: list[str]) -> dict[str, Any]: + base = {"trainee_id": {"$in": user_ids}} + + async def count(extra: dict) -> int: + return await db.assignments.count_documents({**base, **extra}) + + loop = { + "remediation_assigned": await count({"source": "remediation"}), + "remediation_passed": await count({"source": "remediation", "status": "completed"}), + "retest_assigned": await count({"source": "retest"}), + "retest_passed": await count({"source": "retest", "status": "completed"}), + } + # Anonymous activity feed: what the loop did, never who it did it to. + recent = ( + await db.assignments.find( + {**base, "source": {"$in": ["remediation", "retest"]}}, + {"_id": 0, "source": 1, "principle": 1, "status": 1, "created_at": 1}, + ) + .sort("created_at", -1) + .to_list(8) + ) + loop["recent"] = recent + return loop + + +def _index(live: dict, principles: dict, lab: dict) -> dict[str, Any]: + known = [v for v in principles.values() if v is not None] + components = { + "report_rate": None if live["report_rate"] is None else live["report_rate"] * 100, + "no_click": None if live["click_rate"] is None else (1 - live["click_rate"]) * 100, + "principles": mean(known) if known else None, + "triage": lab["avg_triage_score"], + } + available = {k: v for k, v in components.items() if v is not None} + weight = sum(WEIGHTS[k] for k in available) + score = round(sum(WEIGHTS[k] * v for k, v in available.items()) / weight) if weight else None + return { + "score": score, + "components": {k: None if v is None else round(v) for k, v in components.items()}, + "weights": WEIGHTS, + } + + +async def overview(*, user_scope: dict, campaign_scope: dict, org_id: str) -> dict[str, Any]: + users = await db.users.find({**user_scope, "role": "user"}, {"_id": 0, "id": 1}).to_list(10000) + user_ids = [u["id"] for u in users] + + live = await _live(campaign_scope) + principles = await _principles(user_ids) + lab = await _lab(user_ids) + loop = await _loop(user_ids) + + known = {k: v for k, v in principles.items() if v is not None} + weakest = sorted(known, key=known.get)[:2] + + surface = None + graph = await attack_surface.build_graph(org_id, refresh=False) + if any(n.get("is_asset") for n in graph.get("nodes", [])): + analysis = await attack_surface.analyze(org_id) + top = (analysis.get("attack_paths") or [None])[0] + surface = { + "posture": analysis.get("posture"), + "counts": analysis.get("counts"), + # Asset and probability only — the entry person stays on the staff-only map. + "top_path": top and {"asset": top["asset_name"], "probability": top["probability"]}, + } + + return { + "index": _index(live, principles, lab), + "people": len(user_ids), + "live": live, + "principles": principles, + "weakest_principles": weakest, + "lab": lab, + "loop": loop, + "attack_surface": surface, + } diff --git a/backend/tests/test_readiness.py b/backend/tests/test_readiness.py new file mode 100644 index 0000000..7ba7b8c --- /dev/null +++ b/backend/tests/test_readiness.py @@ -0,0 +1,127 @@ +"""Readiness overview: cohort aggregate, org scoping, no individual names.""" + +from datetime import UTC, datetime + +from services.database import db +from tests.conftest import make_user + + +async def _campaign(org, cid, recipients, launched="2026-10-01T00:00:00+00:00"): + await db.live_campaigns.insert_one( + {"id": cid, "name": cid, "organization_id": org, "launched_at": launched} + ) + for i, (state, reported) in enumerate(recipients): + await db.live_recipients.insert_one( + { + "campaign_id": cid, + "email": f"{cid}-{i}@acme.test", + "state": state, + "reported": reported, + } + ) + + +async def test_requires_staff(api): + _, h = await make_user("user") + assert (await api.get("/api/readiness", headers=h)).status_code == 403 + + +async def test_empty_org_has_no_index(api): + _, h = await make_user("trainer", organization_id="org-a") + body = (await api.get("/api/readiness", headers=h)).json() + assert body["index"]["score"] is None + assert body["live"]["campaigns"] == 0 + assert body["attack_surface"] is None + + +async def test_index_and_loop(api): + trainee, _ = await make_user("user", organization_id="org-a") + _, h = await make_user("trainer", organization_id="org-a") + + # Two campaigns: report rate goes 25% -> 75%; one click in each. + await _campaign( + "org-a", + "c1", + [("clicked", False), ("sent", True), ("sent", False), ("sent", False)], + launched="2026-09-01T00:00:00+00:00", + ) + await _campaign( + "org-a", + "c2", + [("clicked", False), ("sent", True), ("sent", True), ("sent", True)], + launched="2026-10-01T00:00:00+00:00", + ) + vector = dict.fromkeys( + ("reciprocity", "scarcity", "commitment", "liking", "social_proof"), 80.0 + ) + await db.risk_profiles.insert_one( + {"user_id": trainee.id, "current_vector": {**vector, "authority": 20.0}} + ) + await db.simulations.insert_one( + { + "user_id": trainee.id, + "simulation_type": "triage", + "status": "completed", + "score": 90, + "events": [{"event_type": "triage_graded", "payload": {"d_prime": 2.0}}], + } + ) + now = datetime.now(UTC).isoformat() + for source, status in ( + ("remediation", "completed"), + ("remediation", "active"), + ("retest", "completed"), + ): + await db.assignments.insert_one( + { + "trainee_id": trainee.id, + "source": source, + "status": status, + "principle": "authority", + "reason": "secret detail about the person", + "created_at": now, + } + ) + + body = (await api.get("/api/readiness", headers=h)).json() + + live = body["live"] + assert live["report_rate"] == 0.5 and live["click_rate"] == 0.25 + assert live["report_rate_delta"] == 0.5 + assert [t["name"] for t in live["trend"]] == ["c1", "c2"] + + assert body["weakest_principles"][0] == "authority" + assert body["lab"] == {"triage_runs": 1, "avg_triage_score": 90.0, "avg_d_prime": 2.0} + + comps = body["index"]["components"] + assert comps == {"report_rate": 50, "no_click": 75, "principles": 70, "triage": 90} + # 0.4*50 + 0.2*75 + 0.2*70 + 0.2*90 = 67 + assert body["index"]["score"] == 67 + + loop = body["loop"] + assert (loop["remediation_assigned"], loop["remediation_passed"]) == (2, 1) + assert (loop["retest_assigned"], loop["retest_passed"]) == (1, 1) + # The feed is anonymous: no person, no free-text reason. + for item in loop["recent"]: + assert set(item) <= {"source", "principle", "status", "created_at"} + + +async def test_trainer_sees_only_own_org(api): + await _campaign("org-b", "other", [("clicked", False), ("sent", False)]) + _, h = await make_user("trainer", organization_id="org-a") + body = (await api.get("/api/readiness", headers=h)).json() + assert body["live"]["campaigns"] == 0 + + _, admin_h = await make_user("admin") + assert (await api.get("/api/readiness", headers=admin_h)).json()["live"]["campaigns"] == 1 + + +async def test_weights_renormalise_without_live_data(api): + trainee, _ = await make_user("user", organization_id="org-a") + _, h = await make_user("trainer", organization_id="org-a") + await db.simulations.insert_one( + {"user_id": trainee.id, "simulation_type": "triage", "status": "completed", "score": 60} + ) + index = (await api.get("/api/readiness", headers=h)).json()["index"] + assert index["components"]["report_rate"] is None + assert index["score"] == 60 # triage is the only component with data diff --git a/frontend/src/App.js b/frontend/src/App.js index a40d3ee..7dfe1e4 100644 --- a/frontend/src/App.js +++ b/frontend/src/App.js @@ -31,6 +31,7 @@ const MyAssignmentsPage = lazy(() => import('./pages/MyAssignmentsPage')); // ── Trainer/Admin pages ──────────────────────────────────────────────────── const InstructorDashboard = lazy(() => import('./pages/InstructorDashboard')); +const ReadinessPage = lazy(() => import('./pages/ReadinessPage')); const TraineesPage = lazy(() => import('./pages/TraineesPage')); const AssignmentsPage = lazy(() => import('./pages/AssignmentsPage')); const InstructorReportsPage = lazy(() => import('./pages/InstructorReportsPage')); @@ -59,7 +60,8 @@ function PageLoader() { function AdminRoutes() { return ( - } /> + } /> + } /> {/* User management — admin only */} } /> {/* Trainer management */} @@ -100,7 +102,8 @@ function AdminRoutes() { function TrainerRoutes() { return ( - } /> + } /> + } /> {/* Trainer tools */} } /> } /> diff --git a/frontend/src/components/Layout.js b/frontend/src/components/Layout.js index 5cd8ba4..773dd79 100644 --- a/frontend/src/components/Layout.js +++ b/frontend/src/components/Layout.js @@ -8,7 +8,7 @@ import { Terminal, LayoutDashboard, FileCode, ListChecks, Activity, Settings, LogOut, BookOpen, Trophy, BarChart3, Flag, Pencil, Sun, Moon, User, Globe, Menu, X, Users, ClipboardList, ShieldAlert, Radio, Target, Inbox, MessageSquare, PenLine, - Shield, UserCog, History, BookMarked, Share2, + Shield, ShieldCheck, UserCog, History, BookMarked, Share2, } from 'lucide-react'; const LANGUAGES = [ @@ -23,13 +23,14 @@ function buildAdminNav(t) { { section: 'COMMAND', items: [ - { name: 'Command Center', path: '/', icon: Radio }, - { name: 'All Users', path: '/users', icon: UserCog }, + { name: t('nav.readiness'), path: '/', icon: ShieldCheck }, + { name: t('instructor.cc.title'), path: '/command', icon: Radio }, + { name: t('nav.all_users'), path: '/users', icon: UserCog }, { name: t('instructor.groups'), path: '/trainer/groups', icon: Users }, { name: t('instructor.assignments'), path: '/trainer/assignments', icon: ClipboardList }, { name: t('instructor.reports'), path: '/trainer/reports', icon: ShieldAlert }, - { name: 'Riwayat User', path: '/trainer/user-history', icon: History }, - { name: 'Peta Serangan', path: '/attack-surface', icon: Share2 }, + { name: t('nav.user_history'), path: '/trainer/user-history', icon: History }, + { name: t('nav.attack_surface'), path: '/attack-surface', icon: Share2 }, ], }, { @@ -47,15 +48,15 @@ function buildAdminNav(t) { items: [ { name: t('nav.live_campaigns'), path: '/live', icon: Radio }, { name: t('nav.reply_review'), path: '/live/review', icon: MessageSquare }, - { name: 'Laporan Phishing', path: '/live/reports', icon: ShieldAlert }, - { name: 'Analitik Live', path: '/live/analytics', icon: BarChart3 }, + { name: t('nav.report_inbox'), path: '/live/reports', icon: ShieldAlert }, + { name: t('nav.live_analytics'), path: '/live/analytics', icon: BarChart3 }, ], }, { section: 'SYSTEM', items: [ { name: t('nav.analytics'), path: '/analytics', icon: BarChart3 }, - { name: 'Glosarium', path: '/glossary', icon: BookMarked }, + { name: t('nav.glossary'), path: '/glossary', icon: BookMarked }, { name: t('nav.settings'), path: '/settings', icon: Settings }, ], }, @@ -67,13 +68,14 @@ function buildTrainerNav(t) { { section: 'TRAINING MGMT', items: [ - { name: 'Command Center', path: '/', icon: Radio }, - { name: 'Users', path: '/users', icon: UserCog }, + { name: t('nav.readiness'), path: '/', icon: ShieldCheck }, + { name: t('instructor.cc.title'), path: '/command', icon: Radio }, + { name: t('nav.users'), path: '/users', icon: UserCog }, { name: t('instructor.groups'), path: '/trainer/groups', icon: Users }, { name: t('instructor.assignments'), path: '/trainer/assignments', icon: ClipboardList }, { name: t('instructor.reports'), path: '/trainer/reports', icon: ShieldAlert }, - { name: 'Riwayat User', path: '/trainer/user-history', icon: History }, - { name: 'Peta Serangan', path: '/attack-surface', icon: Share2 }, + { name: t('nav.user_history'), path: '/trainer/user-history', icon: History }, + { name: t('nav.attack_surface'), path: '/attack-surface', icon: Share2 }, ], }, { @@ -91,15 +93,15 @@ function buildTrainerNav(t) { items: [ { name: t('nav.live_campaigns'), path: '/live', icon: Radio }, { name: t('nav.reply_review'), path: '/live/review', icon: MessageSquare }, - { name: 'Laporan Phishing', path: '/live/reports', icon: ShieldAlert }, - { name: 'Analitik Live', path: '/live/analytics', icon: BarChart3 }, + { name: t('nav.report_inbox'), path: '/live/reports', icon: ShieldAlert }, + { name: t('nav.live_analytics'), path: '/live/analytics', icon: BarChart3 }, ], }, { section: 'ACCOUNT', items: [ { name: t('nav.analytics'), path: '/analytics', icon: BarChart3 }, - { name: 'Glosarium', path: '/glossary', icon: BookMarked }, + { name: t('nav.glossary'), path: '/glossary', icon: BookMarked }, { name: t('nav.settings'), path: '/settings', icon: Settings }, ], }, diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index de3469d..f07d96b 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -41,7 +41,14 @@ "reply_review": "Reply Review", "triage": "Inbox Triage", "write_reply": "Write Your Reply", - "my_assignments": "My Assignments" + "my_assignments": "My Assignments", + "readiness": "Readiness", + "all_users": "All Users", + "users": "Users", + "user_history": "User History", + "attack_surface": "Attack Surface Map", + "report_inbox": "Phish Reports", + "live_analytics": "Live Analytics" }, "dashboard": { "welcome": "Welcome to Pretexta", @@ -656,5 +663,64 @@ "select": "Select a message.", "progress": "{{done}}/{{total}} reviewed — you can submit any time", "submit": "Submit triage" + }, + "readiness": { + "title": "Readiness", + "desc": "How well your people resist social engineering — measured by behaviour, closed by remediation", + "index": "Readiness index", + "band": { + "none": "no data yet", + "strong": "resilient", + "alert": "alert", + "vulnerable": "vulnerable", + "critical": "critical" + }, + "component": { + "report_rate": "Report rate", + "no_click": "Did not click", + "principles": "Principle resistance", + "triage": "Inbox Triage score" + }, + "no_data": "no data", + "report_title": "Report rate — the behaviour we train for", + "reported_of": "{{reported}}/{{total}} reported · last {{campaigns}} campaigns", + "points_since_first": "pts since the first campaign", + "click_rate": "Click rate", + "series": { + "report": "Report rate", + "click": "Click rate" + }, + "trend_needs_two": "Run two campaigns to see a trend", + "loop_title": "The loop: measure → remediate → retest", + "loop_desc": "Every failure triggers targeted practice for the exact principle used, then a variant retest.", + "step": { + "failed": "clicked in a campaign", + "assigned": "practice assigned", + "passed": "practice passed", + "retested": "retest passed" + }, + "principles_title": "Resistance by influence principle", + "resistance": "Resistance", + "weakest": "Weakest", + "surface_title": "Attack surface", + "surface_empty": "Model people, trust and crown jewels to see the easiest attack path.", + "open_map": "Open the map", + "score": "score", + "top_path": "Easiest crown jewel: {{asset}} ({{probability}} modelled success)", + "lab_title": "Lab discrimination", + "d_prime": "avg d′", + "triage_score": "avg triage", + "triage_runs": "runs", + "d_prime_hint": "d′ measures telling phish from legitimate mail; over-flagging does not raise it.", + "feed_title": "Loop activity", + "feed_empty": "No remediation yet.", + "feed_privacy": "Anonymous — individual results stay with the person and their trainer.", + "feed": { + "remediation_open": "Practice assigned for {{principle}}", + "remediation_done": "Practice on {{principle}} passed", + "retest_open": "Retest scheduled for {{principle}}", + "retest_done": "Retest on {{principle}} passed" + }, + "cohort_note": "Cohort of {{people}} trainees. Weights: report rate 40%, did not click 20%, principle resistance 20%, Inbox Triage 20%; missing parts are left out." } } diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index 30af8a2..31102a8 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -41,7 +41,14 @@ "reply_review": "Tinjau Balasan", "triage": "Triase Inbox", "write_reply": "Tulis Balasan", - "my_assignments": "Tugas Saya" + "my_assignments": "Tugas Saya", + "readiness": "Ketahanan", + "all_users": "Semua Pengguna", + "users": "Pengguna", + "user_history": "Riwayat Pengguna", + "attack_surface": "Peta Serangan", + "report_inbox": "Laporan Phishing", + "live_analytics": "Analitik Live" }, "dashboard": { "welcome": "Selamat Datang di Pretexta", @@ -656,5 +663,64 @@ "select": "Pilih sebuah pesan.", "progress": "{{done}}/{{total}} ditinjau — Anda bisa mengirim kapan saja", "submit": "Kirim hasil triase" + }, + "readiness": { + "title": "Ketahanan", + "desc": "Seberapa tahan personel terhadap rekayasa sosial — diukur dari perilaku, ditutup dengan remediasi", + "index": "Indeks ketahanan", + "band": { + "none": "belum ada data", + "strong": "tangguh", + "alert": "siaga", + "vulnerable": "rentan", + "critical": "kritis" + }, + "component": { + "report_rate": "Report rate", + "no_click": "Tidak mengklik", + "principles": "Resistansi prinsip", + "triage": "Skor Triase Inbox" + }, + "no_data": "belum ada data", + "report_title": "Report rate — perilaku yang kita latih", + "reported_of": "{{reported}}/{{total}} melapor · {{campaigns}} kampanye terakhir", + "points_since_first": "poin sejak kampanye pertama", + "click_rate": "Click rate", + "series": { + "report": "Report rate", + "click": "Click rate" + }, + "trend_needs_two": "Jalankan dua kampanye untuk melihat tren", + "loop_title": "Siklus: ukur → remediasi → tes ulang", + "loop_desc": "Setiap kegagalan memicu latihan terarah untuk prinsip yang dipakai, lalu tes ulang dengan varian.", + "step": { + "failed": "klik di kampanye", + "assigned": "latihan ditugaskan", + "passed": "latihan lulus", + "retested": "tes ulang lulus" + }, + "principles_title": "Resistansi per prinsip pengaruh", + "resistance": "Resistansi", + "weakest": "Terlemah", + "surface_title": "Permukaan serangan", + "surface_empty": "Petakan orang, relasi kepercayaan, dan aset kritis untuk melihat jalur serangan termudah.", + "open_map": "Buka peta", + "score": "skor", + "top_path": "Aset kritis termudah: {{asset}} ({{probability}} peluang berhasil dalam model)", + "lab_title": "Diskriminasi lab", + "d_prime": "rata-rata d′", + "triage_score": "rata-rata triase", + "triage_runs": "percobaan", + "d_prime_hint": "d′ mengukur kemampuan membedakan phishing dari email sah; menandai semuanya tidak menaikkannya.", + "feed_title": "Aktivitas siklus", + "feed_empty": "Belum ada remediasi.", + "feed_privacy": "Anonim — hasil individu hanya untuk yang bersangkutan dan pelatihnya.", + "feed": { + "remediation_open": "Latihan {{principle}} ditugaskan", + "remediation_done": "Latihan {{principle}} lulus", + "retest_open": "Tes ulang {{principle}} dijadwalkan", + "retest_done": "Tes ulang {{principle}} lulus" + }, + "cohort_note": "Kohort {{people}} peserta. Bobot: report rate 40%, tidak mengklik 20%, resistansi prinsip 20%, Triase Inbox 20%; komponen tanpa data tidak dihitung." } } diff --git a/frontend/src/pages/ReadinessPage.js b/frontend/src/pages/ReadinessPage.js new file mode 100644 index 0000000..9e1743b --- /dev/null +++ b/frontend/src/pages/ReadinessPage.js @@ -0,0 +1,342 @@ +import React from 'react'; +import { Link } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { + ShieldCheck, Flag, MousePointerClick, ArrowRight, TrendingUp, TrendingDown, Repeat, + GraduationCap, CheckCircle2, Crosshair, Inbox, Activity, Radio, Share2, Info, +} from 'lucide-react'; +import { + ResponsiveContainer, LineChart, Line, XAxis, YAxis, Tooltip, + RadarChart, PolarGrid, PolarAngleAxis, Radar, +} from 'recharts'; +import { Button } from '../components/ui/button'; +import PageHeader from '../components/PageHeader'; +import SectionCard from '../components/SectionCard'; +import { useApi } from '../hooks/useApi'; + +// Same palette as the Attack Surface Map so the two screens read as one system. +const GOOD = '#6f8f3f'; +const WARN = '#d39a22'; +const BAD = '#c0453f'; +const ACCENT = '#e0b84a'; +const POSTURE_COLOR = { + SECURE: '#6f8f3f', GUARDED: '#9fae3a', ELEVATED: '#d39a22', HIGH: '#d9772a', SEVERE: '#c0453f', +}; +const TICK = { fill: 'rgba(234,234,230,0.55)', fontSize: 10, fontFamily: 'monospace' }; +const TOOLTIP = { + background: '#151812', border: '1px solid rgba(143,159,94,0.3)', fontSize: 11, fontFamily: 'monospace', +}; + +const pct = (v) => (v == null ? '—' : `${Math.round(v * 100)}%`); + +function band(score) { + if (score == null) return { key: 'none', color: 'rgba(234,234,230,0.35)' }; + if (score >= 80) return { key: 'strong', color: GOOD }; + if (score >= 60) return { key: 'alert', color: '#9fae3a' }; + if (score >= 40) return { key: 'vulnerable', color: WARN }; + return { key: 'critical', color: BAD }; +} + +// Half-circle gauge, 0–100. +function Gauge({ score }) { + const { color } = band(score); + const r = 80; + const len = Math.PI * r; + const filled = score == null ? 0 : (len * score) / 100; + return ( + + + + + {score == null ? '—' : score} + + / 100 + + ); +} + +function IndexCard({ index, t }) { + const b = band(index.score); + return ( + +
+ + + {t(`readiness.band.${b.key}`)} + +
+ {/* The formula is shown, not hidden: every part of the number is inspectable. */} +
+ {Object.entries(index.components).map(([key, value]) => ( +
+
+ {t(`readiness.component.${key}`)} · {Math.round(index.weights[key] * 100)}% + {value == null ? t('readiness.no_data') : value} +
+
+
+
+
+ ))} +
+ + ); +} + +function ReportCard({ live, t }) { + const delta = live.report_rate_delta; + const Trend = delta != null && delta < 0 ? TrendingDown : TrendingUp; + const trend = live.trend.map((c) => ({ + name: c.name, + report: c.report_rate == null ? null : Math.round(c.report_rate * 100), + click: c.click_rate == null ? null : Math.round(c.click_rate * 100), + })); + return ( + + {t('dashboard.view_all')}}> +
+
+
+ {pct(live.report_rate)} +
+
+ {t('readiness.reported_of', { reported: live.reported, total: live.recipients, campaigns: live.campaigns })} +
+ {delta != null && ( +
= 0 ? GOOD : BAD }}> + + {delta >= 0 ? '+' : ''}{Math.round(delta * 100)} {t('readiness.points_since_first')} +
+ )} +
+ + {t('readiness.click_rate')}: {pct(live.click_rate)} +
+
+
+ {trend.length >= 2 ? ( + + + + + [`${v}%`, t(`readiness.series.${k}`)]} /> + + + + + ) : ( +
+ {t('readiness.trend_needs_two')} +
+ )} +
+
+
+ ); +} + +function LoopCard({ live, loop, t }) { + const steps = [ + { key: 'failed', value: live.clicked, icon: MousePointerClick, color: BAD }, + { key: 'assigned', value: loop.remediation_assigned, icon: GraduationCap, color: WARN }, + { key: 'passed', value: loop.remediation_passed, icon: CheckCircle2, color: '#9fae3a' }, + { key: 'retested', value: loop.retest_passed, icon: Repeat, color: GOOD }, + ]; + return ( + +

{t('readiness.loop_desc')}

+
+ {steps.map((s, i) => { + const Icon = s.icon; + return ( +
+
+ +
+ {s.value} +
+
+ {t(`readiness.step.${s.key}`)} +
+
+ {i < steps.length - 1 && ( + + )} +
+ ); + })} +
+
+ ); +} + +function PrinciplesCard({ principles, weakest, t }) { + const data = Object.entries(principles).map(([key, value]) => ({ + key, label: t(`principles.${key}`, { defaultValue: key }), value: value ?? 0, + })); + const hasData = Object.values(principles).some((v) => v != null); + return ( + + {hasData ? ( + <> +
+ + + + + + [`${v}/100`, t('readiness.resistance')]} /> + + +
+ {weakest.length > 0 && ( +

+ {t('readiness.weakest')}: + {weakest.map((p) => ( + + {t(`principles.${p}`, { defaultValue: p })} ({principles[p]}) + + ))} +

+ )} + + ) :

{t('readiness.no_data')}

} +
+ ); +} + +function SurfaceCard({ surface, t }) { + if (!surface) { + return ( + +

{t('readiness.surface_empty')}

+ +
+ ); + } + const color = POSTURE_COLOR[surface.posture?.label] || WARN; + return ( + +
+ + {surface.posture?.label} + + + DEFCON {surface.posture?.condition} · {t('readiness.score')} {surface.posture?.score} + +
+ {surface.top_path && ( +

+ {t('readiness.top_path', { asset: surface.top_path.asset, probability: pct(surface.top_path.probability) })} +

+ )} + + + +
+ ); +} + +function LabCard({ lab, t }) { + return ( + +
+ {[ + [lab.avg_d_prime ?? '—', t('readiness.d_prime')], + [lab.avg_triage_score ?? '—', t('readiness.triage_score')], + [lab.triage_runs, t('readiness.triage_runs')], + ].map(([value, label]) => ( +
+
{value}
+
{label}
+
+ ))} +
+

{t('readiness.d_prime_hint')}

+
+ ); +} + +function FeedCard({ recent, t }) { + return ( + + {recent.length === 0 ? ( +

{t('readiness.feed_empty')}

+ ) : ( +
    + {recent.map((r, i) => ( +
  • + {r.source === 'retest' + ? + : } + + {t(`readiness.feed.${r.source}_${r.status === 'completed' ? 'done' : 'open'}`, + { principle: t(`principles.${r.principle}`, { defaultValue: r.principle }) })} + + + {r.created_at ? new Date(r.created_at).toLocaleDateString() : ''} + +
  • + ))} +
+ )} +

+ {t('readiness.feed_privacy')} +

+
+ ); +} + +export default function ReadinessPage() { + const { t } = useTranslation(); + const { data, loading } = useApi('/readiness'); + + return ( +
+ + + + + + + {loading || !data ? ( +
+ {[1, 2, 3].map((i) =>
)} +
+ ) : ( + <> +
+ + +
+ +
+ +
+ + +
+ +
+

+ {t('readiness.cohort_note', { people: data.people })} +

+ + )} +
+ ); +}