mirror of
https://github.com/elicpeter/nyx.git
synced 2026-06-27 20:29:39 +02:00
Prerelease cleanup (#46)
* feat: Add const_bound_vars tracking to prevent false positives in ownership checks
* feat: Introduce field interner and typed bounded vars for enhanced type tracking
* feat: Add typed_call_receivers and typed_bounded_dto_fields for enhanced type tracking
* feat: Centralize method name extraction with bare_method_name helper
* feat: Implement Phase-6 hierarchy fan-out for runtime virtual dispatch
* feat: Enhance C++ taint tracking with additional container operations and inline method resolution
* feat: Introduce field-sensitive points-to analysis for enhanced resource tracking
* feat: Implement Pointer-Phase 6 subscript handling for enhanced container analysis
* test: Add comprehensive tests for JavaScript control flow constructs and lattice operations
* docs: Update advanced analysis documentation with field-sensitive points-to and hierarchy fan-out details
* test: Add comprehensive tests for lattice algebra laws and SSA edge cases
* feat: Add destructured session user handling and safe user ID access patterns
* feat: Implement row-population reverse-walk for enhanced authorization checks
* feat: Enhance authorization checks with local alias chain for self-actor types
* feat: Introduce ActiveRecord query safety checks and enhance snippet extraction
* feat: Implement chained method call inner-gate rebinding for SSRF prevention
* feat: Add observability and error modules, enhance debug functionality, and implement theme context
* feat: Remove Auth Analysis page and update navigation to redirect to Explorer
* feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor
* feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor
* feat: Reset path-safe-suppressed spans before lowering to maintain analysis integrity
* fix(ssa): ungate debug_assert_bfs_ordering for release-tests build
The helper at src/ssa/lower.rs was gated `#[cfg(debug_assertions)]` while
the unit test at the bottom of the file was gated only `#[cfg(test)]`.
Since `cfg(test)` is set in release builds with `--tests` but
`cfg(debug_assertions)` is not, `cargo build --release --tests` failed
with E0425. Removing the gate fixes the build; the body is `debug_assert!`
only, so the helper is free in release. Also drop the gate at the call
site to avoid a `dead_code` warning when the lib is built without
`--tests`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(closure-capture): flip JS/TS fixtures to required-finding
The JS and TS closure-capture fixtures pinned the old broken behaviour
via `forbidden_findings: [{ "id_prefix": "taint-" }]`. The engine now
correctly traces taint through the closure boundary (env source captured
by an arrow function, sunk via `child_process.exec` inside the body), so
the formerly-forbidden finding is a true positive.
Match the Python sibling's shape — `required_findings` with
`id_prefix` + `min_count` plus a small `noise_budget` — and rewrite the
companion READMEs and the phase8_fragility_tests doc-comments from
"known gap" to "regression guard".
Verified:
- cargo test --release --test phase8_fragility_tests → 8/8 pass
- cargo test --release --lib bfs_assertion → pass
- corpus benchmark F1 = 0.9976 (TP=205, FP=1, FN=0) — unchanged
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: Add OWASP mapping and baseline mutation hooks for enhanced security analysis
* feat: Introduce health module and enhance health score computation with calibration tests
* feat: Add expectations configuration and cleanup .gitignore for log files
* feat: Implement theme selection and enhance settings panel for triage sync
* feat: Suppress false positives for strcpy calls with literal sources in AST
* feat: Update analyse_function_ssa to return body CFG for accurate analysis
* feat: Add bug report and feature request templates for improved issue tracking
* feat: removed dev scripts
* feat: update README.md for clarity and consistency in fixture descriptions
* feat: removed dev docs
* feat: clean up error handling and UI elements for improved user experience
* feat: adjust button sizes in HeaderBar for better UI consistency
* feat: enhance taint analysis with additional context for sanitizer and taint findings
* cargo fmt
* prettier
* refactor: simplify conditional checks and improve code readability in AST and screenshot capture scripts
* feat: add script to frame PNG screenshots with brand gradient
* feat: add fuzzing support with new targets and CI workflows
* refactor: streamline match expressions and improve formatting in CLI and output handling
* feat: enhance configuration display with detailed output options
* feat: stage demo configuration for improved CLI screenshot output
* feat: expose merge_configs function for user-configurable settings
* refactor: simplify code structure and improve readability in config handling
* refactor: improve descriptions for vulnerability patterns in various languages
* feat: update MIT License section with additional usage details and copyright information
* feat: update screenshots
* refactor: update build process and paths for frontend assets
* feat: add cross-file taint fuzzing target and supporting dictionary
* refactor: clean up formatting and comments in fuzz configuration and example files
* refactor: remove outdated comments and clean up CI configuration files
* chore: update changelog dates and improve formatting in documentation
* refactor: update Cargo.toml and CI configuration for improved packaging and build process
* refactor: enhance quote-stripping logic to prevent panics and add regression tests
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
79c29b394d
commit
82f18184b1
348 changed files with 48731 additions and 2925 deletions
|
|
@ -2,16 +2,24 @@ import { QueryClientProvider } from '@tanstack/react-query';
|
|||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { queryClient } from './api/queryClient';
|
||||
import { SSEProvider } from './contexts/SSEContext';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { ToastProvider } from './contexts/ToastContext';
|
||||
import { Toaster } from './components/ui/Toaster';
|
||||
import { AppLayout } from './components/layout/AppLayout';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<SSEProvider>
|
||||
<BrowserRouter>
|
||||
<AppLayout />
|
||||
</BrowserRouter>
|
||||
</SSEProvider>
|
||||
</QueryClientProvider>
|
||||
<ThemeProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<SSEProvider>
|
||||
<BrowserRouter>
|
||||
<AppLayout />
|
||||
<Toaster />
|
||||
</BrowserRouter>
|
||||
</SSEProvider>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,13 +3,57 @@ const CSRF_HEADER = 'X-Nyx-CSRF';
|
|||
let csrfTokenPromise: Promise<string> | null = null;
|
||||
|
||||
export class ApiError extends Error {
|
||||
/**
|
||||
* Stable machine-readable code (matches backend `ApiError`'s `code` field).
|
||||
* Falls back to a synthetic value when the response wasn't structured —
|
||||
* `network` for fetch failures, `http_<status>` for plain-text responses.
|
||||
*/
|
||||
public code: string;
|
||||
public detail?: unknown;
|
||||
|
||||
constructor(
|
||||
public status: number,
|
||||
status: number,
|
||||
message: string,
|
||||
code?: string,
|
||||
detail?: unknown,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = code ?? `http_${status}`;
|
||||
this.detail = detail;
|
||||
}
|
||||
|
||||
public status: number;
|
||||
|
||||
/** True when the failure was a network/abort, not an HTTP response. */
|
||||
isNetwork(): boolean {
|
||||
return this.status === 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build an ApiError from a non-OK Response, parsing a JSON error body if present. */
|
||||
async function errorFromResponse(res: Response): Promise<ApiError> {
|
||||
const text = await res.text().catch(() => '');
|
||||
if (text) {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as {
|
||||
error?: unknown;
|
||||
code?: unknown;
|
||||
detail?: unknown;
|
||||
};
|
||||
const msg =
|
||||
typeof parsed.error === 'string' && parsed.error.length > 0
|
||||
? parsed.error
|
||||
: res.statusText || `HTTP ${res.status}`;
|
||||
const code = typeof parsed.code === 'string' ? parsed.code : undefined;
|
||||
return new ApiError(res.status, msg, code, parsed.detail);
|
||||
} catch {
|
||||
// Plain-text body — use as-is.
|
||||
return new ApiError(res.status, text);
|
||||
}
|
||||
}
|
||||
return new ApiError(res.status, res.statusText || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
async function getCsrfToken(): Promise<string> {
|
||||
|
|
@ -17,10 +61,7 @@ async function getCsrfToken(): Promise<string> {
|
|||
csrfTokenPromise = fetch(`${BASE}/session`)
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
throw new ApiError(
|
||||
res.status,
|
||||
await res.text().catch(() => res.statusText),
|
||||
);
|
||||
throw await errorFromResponse(res);
|
||||
}
|
||||
|
||||
const text = await res.text();
|
||||
|
|
@ -31,7 +72,7 @@ async function getCsrfToken(): Promise<string> {
|
|||
typeof payload.csrf_token !== 'string' ||
|
||||
payload.csrf_token.length === 0
|
||||
) {
|
||||
throw new ApiError(500, 'Missing CSRF token');
|
||||
throw new ApiError(500, 'Missing CSRF token', 'missing_csrf_token');
|
||||
}
|
||||
|
||||
return payload.csrf_token;
|
||||
|
|
@ -67,14 +108,23 @@ async function request<T>(path: string, opts: RequestInit = {}): Promise<T> {
|
|||
if (opts.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
const res = await fetch(url, {
|
||||
...rest,
|
||||
headers,
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
...rest,
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'AbortError') {
|
||||
throw err;
|
||||
}
|
||||
const message =
|
||||
err instanceof Error ? err.message : 'Network request failed';
|
||||
throw new ApiError(0, message, 'network');
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
throw new ApiError(res.status, text);
|
||||
throw await errorFromResponse(res);
|
||||
}
|
||||
|
||||
// Handle empty responses
|
||||
|
|
@ -99,6 +149,26 @@ export function apiPost<T>(
|
|||
});
|
||||
}
|
||||
|
||||
export function apiDelete<T>(path: string, signal?: AbortSignal): Promise<T> {
|
||||
return request<T>(path, { method: 'DELETE', signal });
|
||||
export function apiPut<T>(
|
||||
path: string,
|
||||
body?: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
return request<T>(path, {
|
||||
method: 'PUT',
|
||||
body: body != null ? JSON.stringify(body) : undefined,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export function apiDelete<T>(
|
||||
path: string,
|
||||
body?: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
return request<T>(path, {
|
||||
method: 'DELETE',
|
||||
body: body != null ? JSON.stringify(body) : undefined,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
23
frontend/src/api/mutations/baseline.ts
Normal file
23
frontend/src/api/mutations/baseline.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiDelete, apiPost } from '../client';
|
||||
|
||||
export function usePinBaseline() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (scanId: string) =>
|
||||
apiPost<void>('/overview/baseline', { scan_id: scanId }),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['overview'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUnpinBaseline() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => apiDelete<void>('/overview/baseline'),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['overview'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { apiPost, apiDelete } from '../client';
|
||||
import { apiPost, apiPut, apiDelete } from '../client';
|
||||
import type { LabelEntryView, TerminatorView, ProfileView } from '../types';
|
||||
|
||||
// --- Sources ---
|
||||
|
|
@ -18,6 +18,7 @@ export function useAddSource() {
|
|||
apiPost<LabelEntryView>('/config/sources', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sources'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -25,9 +26,11 @@ export function useAddSource() {
|
|||
export function useDeleteSource() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: AddLabelBody) => apiDelete<void>('/config/sources'),
|
||||
mutationFn: (body: AddLabelBody) =>
|
||||
apiDelete<void>('/config/sources', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sources'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -41,6 +44,7 @@ export function useAddSink() {
|
|||
apiPost<LabelEntryView>('/config/sinks', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sinks'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -48,9 +52,10 @@ export function useAddSink() {
|
|||
export function useDeleteSink() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: AddLabelBody) => apiDelete<void>('/config/sinks'),
|
||||
mutationFn: (body: AddLabelBody) => apiDelete<void>('/config/sinks', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sinks'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -64,6 +69,7 @@ export function useAddSanitizer() {
|
|||
apiPost<LabelEntryView>('/config/sanitizers', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sanitizers'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -71,9 +77,11 @@ export function useAddSanitizer() {
|
|||
export function useDeleteSanitizer() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: AddLabelBody) => apiDelete<void>('/config/sanitizers'),
|
||||
mutationFn: (body: AddLabelBody) =>
|
||||
apiDelete<void>('/config/sanitizers', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'sanitizers'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -92,6 +100,7 @@ export function useAddTerminator() {
|
|||
apiPost<TerminatorView>('/config/terminators', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'terminators'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -100,9 +109,10 @@ export function useDeleteTerminator() {
|
|||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: AddTerminatorBody) =>
|
||||
apiDelete<void>('/config/terminators'),
|
||||
apiDelete<void>('/config/terminators', body),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config', 'terminators'] });
|
||||
qc.invalidateQueries({ queryKey: ['rules'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -143,6 +153,21 @@ export function useActivateProfile() {
|
|||
});
|
||||
}
|
||||
|
||||
// --- Raw nyx.local TOML ---
|
||||
|
||||
export function useSaveRawConfig() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (content: string) =>
|
||||
apiPut<{ status: string; path: string; bytes: number }>('/config/raw', {
|
||||
content,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['config'] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// --- Triage Sync ---
|
||||
|
||||
export function useToggleTriageSync() {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,19 @@ export function useConfig() {
|
|||
});
|
||||
}
|
||||
|
||||
export interface RawConfigView {
|
||||
path: string;
|
||||
exists: boolean;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export function useRawConfig() {
|
||||
return useQuery({
|
||||
queryKey: ['config', 'raw'],
|
||||
queryFn: ({ signal }) => apiGet<RawConfigView>('/config/raw', signal),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSources() {
|
||||
return useQuery({
|
||||
queryKey: ['config', 'sources'],
|
||||
|
|
|
|||
|
|
@ -9,6 +9,9 @@ import type {
|
|||
SymexView,
|
||||
CallGraphView,
|
||||
FuncSummaryView,
|
||||
PointerView,
|
||||
TypeFactsView,
|
||||
AuthAnalysisView,
|
||||
} from '../types';
|
||||
|
||||
export function useDebugFunctions(file: string | null) {
|
||||
|
|
@ -109,3 +112,39 @@ export function useDebugSummaries(
|
|||
apiGet<FuncSummaryView[]>(`/debug/summaries?${params}`, signal),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDebugPointer(file: string | null, fn_name: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['debug', 'pointer', file, fn_name],
|
||||
queryFn: ({ signal }) =>
|
||||
apiGet<PointerView>(
|
||||
`/debug/pointer?file=${encodeURIComponent(file!)}&function=${encodeURIComponent(fn_name!)}`,
|
||||
signal,
|
||||
),
|
||||
enabled: !!file && !!fn_name,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDebugTypeFacts(file: string | null, fn_name: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['debug', 'type-facts', file, fn_name],
|
||||
queryFn: ({ signal }) =>
|
||||
apiGet<TypeFactsView>(
|
||||
`/debug/type-facts?file=${encodeURIComponent(file!)}&function=${encodeURIComponent(fn_name!)}`,
|
||||
signal,
|
||||
),
|
||||
enabled: !!file && !!fn_name,
|
||||
});
|
||||
}
|
||||
|
||||
export function useDebugAuth(file: string | null) {
|
||||
return useQuery({
|
||||
queryKey: ['debug', 'auth', file],
|
||||
queryFn: ({ signal }) =>
|
||||
apiGet<AuthAnalysisView>(
|
||||
`/debug/auth?file=${encodeURIComponent(file!)}`,
|
||||
signal,
|
||||
),
|
||||
enabled: !!file,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -228,6 +228,120 @@ export interface OverviewResponse {
|
|||
noisy_rules: NoisyRule[];
|
||||
recent_scans: ScanSummary[];
|
||||
insights: Insight[];
|
||||
|
||||
// Tier 1
|
||||
health?: HealthScore;
|
||||
posture?: PostureSummary;
|
||||
backlog?: BacklogStats;
|
||||
weighted_top_files?: WeightedFile[];
|
||||
confidence_distribution?: ConfidenceDistribution;
|
||||
|
||||
// Tier 2
|
||||
scanner_quality?: ScannerQuality;
|
||||
issue_categories?: IssueCategoryBucket[];
|
||||
hot_sinks?: HotSink[];
|
||||
owasp_buckets?: OwaspBucket[];
|
||||
cross_file_ratio?: number;
|
||||
|
||||
// Tier 3
|
||||
baseline?: BaselineInfo;
|
||||
language_health?: LanguageHealth[];
|
||||
suppression_hygiene?: SuppressionHygiene;
|
||||
}
|
||||
|
||||
export interface HealthComponent {
|
||||
label: string;
|
||||
score: number;
|
||||
weight: number;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface HealthScore {
|
||||
score: number;
|
||||
grade: string;
|
||||
components: HealthComponent[];
|
||||
}
|
||||
|
||||
export interface PostureSummary {
|
||||
trend: 'improving' | 'regressing' | 'stable' | 'unknown' | string;
|
||||
severity: 'success' | 'warning' | 'danger' | 'info' | string;
|
||||
message: string;
|
||||
reintroduced_count: number;
|
||||
}
|
||||
|
||||
export interface BacklogStats {
|
||||
oldest_open_days?: number;
|
||||
median_age_days?: number;
|
||||
stale_count: number;
|
||||
age_buckets: OverviewCount[];
|
||||
}
|
||||
|
||||
export interface WeightedFile {
|
||||
name: string;
|
||||
score: number;
|
||||
high: number;
|
||||
medium: number;
|
||||
low: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ConfidenceDistribution {
|
||||
high: number;
|
||||
medium: number;
|
||||
low: number;
|
||||
none: number;
|
||||
}
|
||||
|
||||
export interface ScannerQuality {
|
||||
files_scanned: number;
|
||||
files_skipped: number;
|
||||
parse_success_rate: number;
|
||||
functions_analyzed: number;
|
||||
call_edges: number;
|
||||
unresolved_calls: number;
|
||||
call_resolution_rate: number;
|
||||
symex_verified_rate: number;
|
||||
symex_breakdown: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface IssueCategoryBucket {
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface HotSink {
|
||||
callee: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface OwaspBucket {
|
||||
code: string;
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface LanguageHealth {
|
||||
language: string;
|
||||
findings: number;
|
||||
high: number;
|
||||
medium: number;
|
||||
low: number;
|
||||
}
|
||||
|
||||
export interface SuppressionHygiene {
|
||||
fingerprint_level: number;
|
||||
rule_level: number;
|
||||
file_level: number;
|
||||
rule_in_file_level: number;
|
||||
blanket_rate: number;
|
||||
}
|
||||
|
||||
export interface BaselineInfo {
|
||||
scan_id: string;
|
||||
started_at?: string;
|
||||
baseline_total: number;
|
||||
drift_new: number;
|
||||
drift_fixed: number;
|
||||
}
|
||||
|
||||
// Rules types
|
||||
|
|
@ -361,7 +475,15 @@ export interface TreeEntry {
|
|||
|
||||
export interface SymbolEntry {
|
||||
name: string;
|
||||
/// Legacy display kind (`"function"` | `"method"`) used by existing
|
||||
/// CSS classes. Prefer `func_kind` for new logic.
|
||||
kind: string;
|
||||
/// Structural FuncKind slug: `"fn"` | `"method"` | `"closure"` |
|
||||
/// `"ctor"` | `"getter"` | `"setter"` | `"toplevel"`.
|
||||
func_kind: string;
|
||||
/// Enclosing container (class / impl / module / outer function).
|
||||
/// Empty for free top-level functions.
|
||||
container: string;
|
||||
line?: number;
|
||||
finding_count: number;
|
||||
namespace?: string;
|
||||
|
|
@ -393,6 +515,10 @@ export interface ScanLogEntry {
|
|||
export interface FunctionInfo {
|
||||
name: string;
|
||||
namespace: string;
|
||||
/// Enclosing container (class / impl / module / outer function).
|
||||
container: string;
|
||||
/// Structural FuncKind slug: `"fn"` | `"method"` | `"closure"` | etc.
|
||||
func_kind: string;
|
||||
param_count: number;
|
||||
line: number;
|
||||
source_caps: string[];
|
||||
|
|
@ -580,6 +706,10 @@ export interface FuncSummaryView {
|
|||
file_path: string;
|
||||
lang: string;
|
||||
namespace: string;
|
||||
/// Enclosing container (class / impl / module / outer function).
|
||||
container: string;
|
||||
/// Structural FuncKind slug: `"fn"` | `"method"` | `"closure"` | etc.
|
||||
func_kind: string;
|
||||
arity?: number;
|
||||
param_count: number;
|
||||
source_caps: string[];
|
||||
|
|
@ -591,3 +721,124 @@ export interface FuncSummaryView {
|
|||
callees: string[];
|
||||
ssa_summary?: SsaSummaryView;
|
||||
}
|
||||
|
||||
// ── Pointer (field-sensitive Steensgaard) ─────────────────────────────────
|
||||
export interface PointerLocationView {
|
||||
id: number;
|
||||
kind: 'Top' | 'Alloc' | 'Param' | 'SelfParam' | 'Field';
|
||||
display: string;
|
||||
parent?: number;
|
||||
field?: string;
|
||||
}
|
||||
|
||||
export interface PointerValueView {
|
||||
ssa_value: number;
|
||||
var_name?: string;
|
||||
points_to: number[];
|
||||
is_top: boolean;
|
||||
}
|
||||
|
||||
export interface PointerFieldEntryView {
|
||||
/// `null` means the implicit receiver.
|
||||
param_index: number | null;
|
||||
field: string;
|
||||
}
|
||||
|
||||
export interface PointerView {
|
||||
locations: PointerLocationView[];
|
||||
values: PointerValueView[];
|
||||
field_reads: PointerFieldEntryView[];
|
||||
field_writes: PointerFieldEntryView[];
|
||||
location_count: number;
|
||||
}
|
||||
|
||||
// ── Type Facts (standalone) ────────────────────────────────────────────────
|
||||
export interface DtoFieldView {
|
||||
name: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
export interface DtoFactView {
|
||||
class_name: string;
|
||||
fields: DtoFieldView[];
|
||||
}
|
||||
|
||||
export interface TypeFactDetailView {
|
||||
ssa_value: number;
|
||||
var_name?: string;
|
||||
line: number;
|
||||
kind: string;
|
||||
nullable: boolean;
|
||||
container?: string;
|
||||
dto?: DtoFactView;
|
||||
}
|
||||
|
||||
export interface TypeFactsView {
|
||||
facts: TypeFactDetailView[];
|
||||
total_values: number;
|
||||
unknown_count: number;
|
||||
}
|
||||
|
||||
// ── Auth Analysis ──────────────────────────────────────────────────────────
|
||||
export interface AuthValueRefView {
|
||||
source_kind: string;
|
||||
name: string;
|
||||
base?: string;
|
||||
field?: string;
|
||||
index?: string;
|
||||
line: number;
|
||||
}
|
||||
|
||||
export interface AuthCheckView {
|
||||
kind: string;
|
||||
callee: string;
|
||||
line: number;
|
||||
subjects: AuthValueRefView[];
|
||||
args: string[];
|
||||
condition_text?: string;
|
||||
}
|
||||
|
||||
export interface AuthOperationView {
|
||||
kind: string;
|
||||
sink_class?: string;
|
||||
callee: string;
|
||||
line: number;
|
||||
text: string;
|
||||
subjects: AuthValueRefView[];
|
||||
}
|
||||
|
||||
export interface AuthCallSiteView {
|
||||
name: string;
|
||||
line: number;
|
||||
args: string[];
|
||||
}
|
||||
|
||||
export interface AuthUnitView {
|
||||
kind: string;
|
||||
name?: string;
|
||||
line: number;
|
||||
params: string[];
|
||||
auth_checks: AuthCheckView[];
|
||||
operations: AuthOperationView[];
|
||||
call_sites: AuthCallSiteView[];
|
||||
self_actor_vars: string[];
|
||||
typed_bounded_vars: string[];
|
||||
authorized_sql_vars: string[];
|
||||
const_bound_vars: string[];
|
||||
}
|
||||
|
||||
export interface AuthRouteView {
|
||||
framework: string;
|
||||
method: string;
|
||||
path: string;
|
||||
middleware: string[];
|
||||
handler_params: string[];
|
||||
line: number;
|
||||
unit_idx: number;
|
||||
}
|
||||
|
||||
export interface AuthAnalysisView {
|
||||
routes: AuthRouteView[];
|
||||
units: AuthUnitView[];
|
||||
enabled: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -108,15 +108,6 @@ export function DebugIcon({ className, size = 18 }: IconProps) {
|
|||
);
|
||||
}
|
||||
|
||||
export function SettingsIcon({ className, size = 18 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 18 18">
|
||||
<circle cx="9" cy="9" r="2.5" />
|
||||
<path d="M9 1.5v2M9 14.5v2M1.5 9h2M14.5 9h2M3.7 3.7l1.4 1.4M12.9 12.9l1.4 1.4M14.3 3.7l-1.4 1.4M5.1 12.9l-1.4 1.4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function FolderIcon({ className, size = 14 }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
|
|
@ -154,6 +145,48 @@ export function TagIcon({ className, size = 14 }: IconProps) {
|
|||
);
|
||||
}
|
||||
|
||||
export function CloseIcon({ className, size = 14 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 14 14">
|
||||
<path d="M3 3l8 8M11 3l-8 8" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function SunIcon({ className, size = 16 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 16 16">
|
||||
<circle cx="8" cy="8" r="3" />
|
||||
<path d="M8 1.5v1.5M8 13v1.5M1.5 8h1.5M13 8h1.5M3.5 3.5l1 1M11.5 11.5l1 1M3.5 12.5l1-1M11.5 4.5l1-1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function MoonIcon({ className, size = 16 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 16 16">
|
||||
<path d="M13.5 9.5A6 6 0 0 1 6.5 2.5 6 6 0 1 0 13.5 9.5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function RefreshIcon({ className, size = 16 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 16 16">
|
||||
<path d="M14 8a6 6 0 1 1-1.76-4.24" />
|
||||
<path d="M14 2v4h-4" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CommandIcon({ className, size = 16 }: IconProps) {
|
||||
return (
|
||||
<svg {...svgProps({ className, size })} viewBox="0 0 16 16">
|
||||
<path d="M5 3a2 2 0 1 0 0 4h6a2 2 0 1 0 0-4 2 2 0 0 0-2 2v6a2 2 0 1 0 2 2 2 2 0 0 0-2-2H5a2 2 0 1 0 0 4 2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Map of icon name to component, for dynamic lookup */
|
||||
export const ICONS: Record<string, FC<IconProps>> = {
|
||||
overview: OverviewIcon,
|
||||
|
|
@ -164,7 +197,6 @@ export const ICONS: Record<string, FC<IconProps>> = {
|
|||
config: ConfigIcon,
|
||||
explorer: ExplorerIcon,
|
||||
debug: DebugIcon,
|
||||
settings: SettingsIcon,
|
||||
folder: FolderIcon,
|
||||
tag: TagIcon,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
import { useState, useCallback } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import { HeaderBar } from './HeaderBar';
|
||||
import { NewScanModal } from '../../modals/NewScanModal';
|
||||
import { CommandPalette, type PaletteCommand } from '../ui/CommandPalette';
|
||||
import { ShortcutsHelp } from '../ui/ShortcutsHelp';
|
||||
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
|
||||
import { useChordNavigation } from '../../hooks/useChordNavigation';
|
||||
import { OverviewPage } from '../../pages/OverviewPage';
|
||||
import { FindingsPage } from '../../pages/FindingsPage';
|
||||
import { FindingDetailPage } from '../../pages/FindingDetailPage';
|
||||
|
|
@ -12,7 +16,6 @@ import { ScanComparePage } from '../../pages/ScanComparePage';
|
|||
import { RulesPage } from '../../pages/RulesPage';
|
||||
import { TriagePage } from '../../pages/TriagePage';
|
||||
import { ConfigPage } from '../../pages/ConfigPage';
|
||||
import { StubPage } from '../../pages/StubPage';
|
||||
import { ExplorerPage } from '../../pages/ExplorerPage';
|
||||
import { DebugLayout } from '../../pages/debug/DebugLayout';
|
||||
import { CallGraphPage } from '../../pages/debug/CallGraphPage';
|
||||
|
|
@ -20,16 +23,108 @@ import { SummaryExplorerPage } from '../../pages/debug/SummaryExplorerPage';
|
|||
|
||||
export function AppLayout() {
|
||||
const [scanModalOpen, setScanModalOpen] = useState(false);
|
||||
const [paletteOpen, setPaletteOpen] = useState(false);
|
||||
const [helpOpen, setHelpOpen] = useState(false);
|
||||
|
||||
const handleStartScan = useCallback(() => {
|
||||
setScanModalOpen(true);
|
||||
}, []);
|
||||
|
||||
const commands = useMemo<PaletteCommand[]>(
|
||||
() => [
|
||||
// Navigation
|
||||
{ id: 'go-overview', group: 'Navigate', label: 'Overview', to: '/' },
|
||||
{
|
||||
id: 'go-findings',
|
||||
group: 'Navigate',
|
||||
label: 'Findings',
|
||||
to: '/findings',
|
||||
},
|
||||
{ id: 'go-scans', group: 'Navigate', label: 'Scans', to: '/scans' },
|
||||
{ id: 'go-rules', group: 'Navigate', label: 'Rules', to: '/rules' },
|
||||
{ id: 'go-triage', group: 'Navigate', label: 'Triage', to: '/triage' },
|
||||
{ id: 'go-config', group: 'Navigate', label: 'Config', to: '/config' },
|
||||
{
|
||||
id: 'go-explorer',
|
||||
group: 'Navigate',
|
||||
label: 'Explorer',
|
||||
to: '/explorer',
|
||||
},
|
||||
{
|
||||
id: 'go-debug-cg',
|
||||
group: 'Navigate',
|
||||
label: 'Call Graph',
|
||||
hint: 'Debug',
|
||||
to: '/debug/call-graph',
|
||||
},
|
||||
{
|
||||
id: 'go-debug-summaries',
|
||||
group: 'Navigate',
|
||||
label: 'Summary Explorer',
|
||||
hint: 'Debug',
|
||||
to: '/debug/summaries',
|
||||
},
|
||||
// Actions
|
||||
{
|
||||
id: 'start-scan',
|
||||
group: 'Actions',
|
||||
label: 'Start new scan',
|
||||
keywords: ['scan', 'run'],
|
||||
action: () => setScanModalOpen(true),
|
||||
},
|
||||
{
|
||||
id: 'show-shortcuts',
|
||||
group: 'Actions',
|
||||
label: 'Show keyboard shortcuts',
|
||||
keywords: ['help', 'keys'],
|
||||
shortcut: '?',
|
||||
action: () => setHelpOpen(true),
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
useChordNavigation();
|
||||
|
||||
const shortcuts = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: 'k',
|
||||
meta: true,
|
||||
description: 'Open command palette',
|
||||
handler: () => setPaletteOpen(true),
|
||||
allowInInput: true,
|
||||
},
|
||||
{
|
||||
key: '?',
|
||||
shift: true,
|
||||
description: 'Show keyboard shortcuts',
|
||||
handler: () => setHelpOpen(true),
|
||||
},
|
||||
{
|
||||
key: 'Escape',
|
||||
description: 'Close modal / palette',
|
||||
handler: () => {
|
||||
if (paletteOpen) setPaletteOpen(false);
|
||||
else if (helpOpen) setHelpOpen(false);
|
||||
else if (scanModalOpen) setScanModalOpen(false);
|
||||
},
|
||||
allowInInput: true,
|
||||
},
|
||||
],
|
||||
[paletteOpen, helpOpen, scanModalOpen],
|
||||
);
|
||||
|
||||
useKeyboardShortcuts(shortcuts);
|
||||
|
||||
return (
|
||||
<div id="app">
|
||||
<Sidebar />
|
||||
<div className="main-panel">
|
||||
<HeaderBar onStartScan={handleStartScan} />
|
||||
<HeaderBar
|
||||
onStartScan={handleStartScan}
|
||||
onOpenPalette={() => setPaletteOpen(true)}
|
||||
/>
|
||||
<main className="content">
|
||||
<Routes>
|
||||
<Route path="/" element={<OverviewPage />} />
|
||||
|
|
@ -53,8 +148,11 @@ export function AppLayout() {
|
|||
/>
|
||||
<Route path="call-graph" element={<CallGraphPage />} />
|
||||
<Route path="summaries" element={<SummaryExplorerPage />} />
|
||||
<Route
|
||||
path="auth"
|
||||
element={<Navigate to="/explorer?view=auth" replace />}
|
||||
/>
|
||||
</Route>
|
||||
<Route path="/settings" element={<StubPage />} />
|
||||
</Routes>
|
||||
</main>
|
||||
</div>
|
||||
|
|
@ -62,6 +160,12 @@ export function AppLayout() {
|
|||
open={scanModalOpen}
|
||||
onClose={() => setScanModalOpen(false)}
|
||||
/>
|
||||
<CommandPalette
|
||||
open={paletteOpen}
|
||||
onClose={() => setPaletteOpen(false)}
|
||||
commands={commands}
|
||||
/>
|
||||
<ShortcutsHelp open={helpOpen} onClose={() => setHelpOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { CommandIcon } from '../icons/Icons';
|
||||
|
||||
const SECTION_TITLES: Record<string, string> = {
|
||||
overview: 'Overview',
|
||||
|
|
@ -9,7 +10,6 @@ const SECTION_TITLES: Record<string, string> = {
|
|||
config: 'Config',
|
||||
explorer: 'Explorer',
|
||||
debug: 'Debug',
|
||||
settings: 'Settings',
|
||||
};
|
||||
|
||||
const ROUTE_TITLES: Record<string, string> = {
|
||||
|
|
@ -17,6 +17,7 @@ const ROUTE_TITLES: Record<string, string> = {
|
|||
'/debug/ssa': 'SSA Viewer',
|
||||
'/debug/call-graph': 'Call Graph',
|
||||
'/debug/taint': 'Taint Debugger',
|
||||
'/debug/summaries': 'Summaries',
|
||||
};
|
||||
|
||||
function pathToSection(pathname: string): string {
|
||||
|
|
@ -30,17 +31,14 @@ function buildBreadcrumbs(pathname: string) {
|
|||
const sectionTitle = SECTION_TITLES[section] ?? section;
|
||||
const crumbs: Array<{ label: string; path?: string }> = [];
|
||||
|
||||
// Always show section as root breadcrumb
|
||||
const sectionPath = section === 'overview' ? '/' : `/${section}`;
|
||||
crumbs.push({ label: sectionTitle, path: sectionPath });
|
||||
|
||||
// If we have a sub-route, show it
|
||||
if (ROUTE_TITLES[pathname]) {
|
||||
crumbs.push({ label: ROUTE_TITLES[pathname] });
|
||||
} else {
|
||||
const parts = pathname.split('/').filter(Boolean);
|
||||
if (parts.length > 1) {
|
||||
// e.g. /findings/123 or /scans/compare/1/2
|
||||
const sub = parts.slice(1).join('/');
|
||||
crumbs.push({ label: sub });
|
||||
}
|
||||
|
|
@ -51,23 +49,38 @@ function buildBreadcrumbs(pathname: string) {
|
|||
|
||||
interface HeaderBarProps {
|
||||
onStartScan?: () => void;
|
||||
onOpenPalette?: () => void;
|
||||
}
|
||||
|
||||
export function HeaderBar({ onStartScan }: HeaderBarProps) {
|
||||
const PALETTE_HINT =
|
||||
typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform)
|
||||
? '⌘K'
|
||||
: 'Ctrl K';
|
||||
|
||||
export function HeaderBar({ onStartScan, onOpenPalette }: HeaderBarProps) {
|
||||
const { pathname } = useLocation();
|
||||
const crumbs = buildBreadcrumbs(pathname);
|
||||
|
||||
return (
|
||||
<header className="header-bar">
|
||||
<div className="header-left">
|
||||
<nav className="breadcrumbs">
|
||||
<nav className="breadcrumbs" aria-label="Breadcrumb">
|
||||
{crumbs.map((crumb, i) => {
|
||||
const isLast = i === crumbs.length - 1;
|
||||
return (
|
||||
<span key={i}>
|
||||
{i > 0 && <span className="breadcrumb-sep">/</span>}
|
||||
{i > 0 && (
|
||||
<span className="breadcrumb-sep" aria-hidden="true">
|
||||
/
|
||||
</span>
|
||||
)}
|
||||
{isLast || !crumb.path ? (
|
||||
<span className="breadcrumb-current">{crumb.label}</span>
|
||||
<span
|
||||
className="breadcrumb-current"
|
||||
aria-current={isLast ? 'page' : undefined}
|
||||
>
|
||||
{crumb.label}
|
||||
</span>
|
||||
) : (
|
||||
<Link to={crumb.path} className="breadcrumb-link">
|
||||
{crumb.label}
|
||||
|
|
@ -79,8 +92,25 @@ export function HeaderBar({ onStartScan }: HeaderBarProps) {
|
|||
</nav>
|
||||
</div>
|
||||
<div className="header-right">
|
||||
{onOpenPalette && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm palette-trigger"
|
||||
onClick={onOpenPalette}
|
||||
aria-label="Open command palette"
|
||||
title={`Command palette (${PALETTE_HINT})`}
|
||||
>
|
||||
<CommandIcon size={12} />
|
||||
<span>Search</span>
|
||||
<kbd>{PALETTE_HINT}</kbd>
|
||||
</button>
|
||||
)}
|
||||
{onStartScan && (
|
||||
<button className="btn btn-primary btn-sm" onClick={onStartScan}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
onClick={onStartScan}
|
||||
>
|
||||
Start Scan
|
||||
</button>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import {
|
|||
ConfigIcon,
|
||||
ExplorerIcon,
|
||||
DebugIcon,
|
||||
SettingsIcon,
|
||||
FolderIcon,
|
||||
TagIcon,
|
||||
} from '../icons/Icons';
|
||||
|
|
@ -61,13 +60,6 @@ const NAV_SECTIONS: NavItem[] = [
|
|||
Icon: TriageIcon,
|
||||
group: 'primary',
|
||||
},
|
||||
{
|
||||
id: 'config',
|
||||
label: 'Config',
|
||||
path: '/config',
|
||||
Icon: ConfigIcon,
|
||||
group: 'secondary',
|
||||
},
|
||||
{
|
||||
id: 'explorer',
|
||||
label: 'Explorer',
|
||||
|
|
@ -83,10 +75,10 @@ const NAV_SECTIONS: NavItem[] = [
|
|||
group: 'secondary',
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: 'Settings',
|
||||
path: '/settings',
|
||||
Icon: SettingsIcon,
|
||||
id: 'config',
|
||||
label: 'Config',
|
||||
path: '/config',
|
||||
Icon: ConfigIcon,
|
||||
group: 'footer',
|
||||
},
|
||||
];
|
||||
|
|
|
|||
615
frontend/src/components/overview/OverviewWidgets.tsx
Normal file
615
frontend/src/components/overview/OverviewWidgets.tsx
Normal file
|
|
@ -0,0 +1,615 @@
|
|||
import { useNavigate } from 'react-router-dom';
|
||||
import type {
|
||||
HealthScore,
|
||||
PostureSummary,
|
||||
BacklogStats,
|
||||
ConfidenceDistribution,
|
||||
ScannerQuality,
|
||||
HotSink,
|
||||
OwaspBucket,
|
||||
LanguageHealth,
|
||||
SuppressionHygiene,
|
||||
BaselineInfo,
|
||||
WeightedFile,
|
||||
OverviewCount,
|
||||
} from '../../api/types';
|
||||
import { truncPath } from '../../utils/truncPath';
|
||||
|
||||
// ── HealthScoreCard ─────────────────────────────────────────────────────────
|
||||
|
||||
export function HealthScoreCard({
|
||||
health,
|
||||
posture,
|
||||
}: {
|
||||
health: HealthScore;
|
||||
posture?: PostureSummary;
|
||||
}) {
|
||||
const gradeClass = `grade-${health.grade.toLowerCase()}`;
|
||||
return (
|
||||
<div className="card health-card">
|
||||
<div className="health-eyebrow">Health Score</div>
|
||||
<div className="health-headline">
|
||||
<div className={`health-grade-block ${gradeClass}`}>
|
||||
<span className="health-grade-letter">{health.grade}</span>
|
||||
</div>
|
||||
<div className="health-headline-text">
|
||||
<div className="health-summary">
|
||||
<span className="health-number">{health.score}</span>
|
||||
<span className="health-of">/ 100</span>
|
||||
</div>
|
||||
{posture && (
|
||||
<div className={`health-posture posture-${posture.severity}`}>
|
||||
{posture.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="health-components">
|
||||
{health.components.map((c) => (
|
||||
<div className="health-component" key={c.label} title={c.detail}>
|
||||
<div className="health-component-score">{c.score}</div>
|
||||
<div className="health-component-label">{c.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── PostureBanner ──────────────────────────────────────────────────────────
|
||||
|
||||
export function PostureBanner({ posture }: { posture: PostureSummary }) {
|
||||
return (
|
||||
<div className={`posture-banner posture-${posture.severity}`}>
|
||||
<span className="posture-dot" aria-hidden />
|
||||
<span className="posture-message">{posture.message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── BacklogCard ────────────────────────────────────────────────────────────
|
||||
|
||||
export function BacklogCard({ backlog }: { backlog: BacklogStats }) {
|
||||
const total = backlog.age_buckets.reduce((s, b) => s + b.count, 0);
|
||||
const noHistory =
|
||||
backlog.oldest_open_days == null && backlog.age_buckets.length === 0;
|
||||
if (noHistory) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="card backlog-card">
|
||||
<div className="card-header">Backlog Age</div>
|
||||
<div className="backlog-body">
|
||||
<div className="backlog-stat">
|
||||
<div className="backlog-stat-value">
|
||||
{backlog.oldest_open_days != null
|
||||
? `${backlog.oldest_open_days}d`
|
||||
: '–'}
|
||||
</div>
|
||||
<div className="backlog-stat-label">Oldest open</div>
|
||||
</div>
|
||||
<div className="backlog-stat">
|
||||
<div className="backlog-stat-value">
|
||||
{backlog.median_age_days != null
|
||||
? `${backlog.median_age_days}d`
|
||||
: '–'}
|
||||
</div>
|
||||
<div className="backlog-stat-label">Median age</div>
|
||||
</div>
|
||||
<div className="backlog-stat">
|
||||
<div className="backlog-stat-value">{backlog.stale_count}</div>
|
||||
<div className="backlog-stat-label">Older than 30 days</div>
|
||||
</div>
|
||||
{total > 0 && (
|
||||
<div className="backlog-bucket">
|
||||
<BucketBar buckets={backlog.age_buckets} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BucketBar({ buckets }: { buckets: OverviewCount[] }) {
|
||||
const total = buckets.reduce((s, b) => s + b.count, 0);
|
||||
if (total === 0) return null;
|
||||
const colors = ['#3498db', '#2ecc71', '#f1c40f', '#e67e22', '#e74c3c'];
|
||||
return (
|
||||
<div
|
||||
className="bucket-bar"
|
||||
title={buckets.map((b) => `${b.name}: ${b.count}`).join(' · ')}
|
||||
>
|
||||
{buckets.map((b, i) => (
|
||||
<div
|
||||
key={b.name}
|
||||
className="bucket-segment"
|
||||
style={{
|
||||
width: `${(b.count / total) * 100}%`,
|
||||
background: colors[i] || 'var(--accent)',
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── ConfidenceDistributionChart ────────────────────────────────────────────
|
||||
|
||||
export function ConfidenceDistributionChart({
|
||||
dist,
|
||||
}: {
|
||||
dist: ConfidenceDistribution;
|
||||
}) {
|
||||
const total = dist.high + dist.medium + dist.low + dist.none;
|
||||
if (total === 0) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<p>No data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const segments = [
|
||||
{ label: 'High', value: dist.high, color: '#27ae60' },
|
||||
{ label: 'Medium', value: dist.medium, color: '#f39c12' },
|
||||
{ label: 'Low', value: dist.low, color: '#95a5a6' },
|
||||
{ label: 'None', value: dist.none, color: '#bdc3c7' },
|
||||
];
|
||||
return (
|
||||
<div className="confidence-dist">
|
||||
<div className="confidence-bar">
|
||||
{segments.map((s) =>
|
||||
s.value > 0 ? (
|
||||
<div
|
||||
key={s.label}
|
||||
className="confidence-segment"
|
||||
style={{
|
||||
width: `${(s.value / total) * 100}%`,
|
||||
background: s.color,
|
||||
}}
|
||||
title={`${s.label}: ${s.value}`}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</div>
|
||||
<div className="confidence-legend">
|
||||
{segments.map((s) => (
|
||||
<div key={s.label} className="confidence-legend-item">
|
||||
<span
|
||||
className="confidence-swatch"
|
||||
style={{ background: s.color }}
|
||||
/>
|
||||
<span>{s.label}</span>
|
||||
<span className="confidence-count">{s.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── ScannerQualityPanel ────────────────────────────────────────────────────
|
||||
|
||||
export function ScannerQualityPanel({
|
||||
quality,
|
||||
crossFileRatio,
|
||||
}: {
|
||||
quality: ScannerQuality;
|
||||
crossFileRatio?: number;
|
||||
}) {
|
||||
const symexAttempted = Object.entries(quality.symex_breakdown || {})
|
||||
.filter(([k]) => k !== 'not_attempted')
|
||||
.reduce((s, [, v]) => s + v, 0);
|
||||
const symexTotal = Object.values(quality.symex_breakdown || {}).reduce(
|
||||
(s, v) => s + v,
|
||||
0,
|
||||
);
|
||||
const totalFiles = quality.files_scanned + quality.files_skipped;
|
||||
const filesValue = totalFiles.toLocaleString();
|
||||
const filesDetail =
|
||||
quality.files_skipped > 0
|
||||
? `${quality.files_scanned.toLocaleString()} fresh · ${quality.files_skipped.toLocaleString()} from cache`
|
||||
: quality.files_scanned > 0
|
||||
? `${quality.files_scanned.toLocaleString()} freshly indexed`
|
||||
: undefined;
|
||||
|
||||
const rows: Array<{
|
||||
label: string;
|
||||
hint: string;
|
||||
value: string;
|
||||
detail?: string;
|
||||
}> = [
|
||||
{
|
||||
label: 'Files',
|
||||
hint: 'Files the scanner saw on this run.',
|
||||
value: filesValue,
|
||||
detail: filesDetail,
|
||||
},
|
||||
{
|
||||
label: 'Functions analyzed',
|
||||
hint: 'Function bodies the call graph saw.',
|
||||
value: quality.functions_analyzed.toLocaleString(),
|
||||
},
|
||||
{
|
||||
label: 'Call edges resolved',
|
||||
hint: 'Share of call sites that the scanner resolved to a known callee. The remainder are typically external/library calls.',
|
||||
value: `${(quality.call_resolution_rate * 100).toFixed(1)}%`,
|
||||
detail:
|
||||
quality.unresolved_calls > 0
|
||||
? `${quality.unresolved_calls.toLocaleString()} unresolved`
|
||||
: undefined,
|
||||
},
|
||||
{
|
||||
label: 'Cross-file flows',
|
||||
hint: 'Findings whose taint path crosses a file boundary.',
|
||||
value:
|
||||
crossFileRatio != null ? `${(crossFileRatio * 100).toFixed(1)}%` : '0%',
|
||||
detail: 'of findings',
|
||||
},
|
||||
{
|
||||
label: 'Symbolic verification',
|
||||
hint: 'Taint findings the symbolic engine attempted to verify (confirmed, infeasible, or inconclusive).',
|
||||
value:
|
||||
symexTotal > 0
|
||||
? `${(quality.symex_verified_rate * 100).toFixed(1)}%`
|
||||
: 'n/a',
|
||||
detail:
|
||||
symexTotal > 0
|
||||
? `${symexAttempted} of ${symexTotal} taint findings`
|
||||
: 'no taint findings',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<dl className="kv-list">
|
||||
{rows.map((r) => (
|
||||
<div className="kv-row" key={r.label}>
|
||||
<dt className="kv-label" title={r.hint}>
|
||||
{r.label}
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{r.value}</div>
|
||||
{r.detail && <div className="kv-detail">{r.detail}</div>}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
// ── HotSinksList ───────────────────────────────────────────────────────────
|
||||
|
||||
export function HotSinksList({ sinks }: { sinks: HotSink[] }) {
|
||||
if (!sinks.length) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<p>No data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Sink</th>
|
||||
<th>Findings</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sinks.map((s) => (
|
||||
<tr key={s.callee} title={s.callee}>
|
||||
<td className="font-mono">{s.callee}</td>
|
||||
<td>{s.count}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
// ── OwaspChart ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function OwaspChart({ buckets }: { buckets: OwaspBucket[] }) {
|
||||
if (!buckets.length) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<p>No data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const max = Math.max(...buckets.map((b) => b.count), 1);
|
||||
return (
|
||||
<ul className="owasp-list">
|
||||
{buckets.map((b) => (
|
||||
<li key={b.code} className="owasp-row" title={b.label}>
|
||||
<span className="owasp-code">{b.code}</span>
|
||||
<span className="owasp-label">{b.label}</span>
|
||||
<div className="owasp-bar">
|
||||
<div
|
||||
className="owasp-fill"
|
||||
style={{ width: `${(b.count / max) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="owasp-count">{b.count}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
// ── WeightedTopFiles ───────────────────────────────────────────────────────
|
||||
|
||||
export function WeightedTopFiles({
|
||||
files,
|
||||
onRowClick,
|
||||
}: {
|
||||
files: WeightedFile[];
|
||||
onRowClick?: (name: string) => void;
|
||||
}) {
|
||||
if (!files.length) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<p>No data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>File</th>
|
||||
<th>Severity</th>
|
||||
<th>Score</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{files.map((f) => (
|
||||
<tr
|
||||
key={f.name}
|
||||
title={f.name}
|
||||
className={onRowClick ? 'clickable' : undefined}
|
||||
onClick={onRowClick ? () => onRowClick(f.name) : undefined}
|
||||
>
|
||||
<td>{truncPath(f.name, 45)}</td>
|
||||
<td>
|
||||
<SeverityStack high={f.high} medium={f.medium} low={f.low} />
|
||||
</td>
|
||||
<td className="font-mono">{f.score}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function SeverityStack({
|
||||
high,
|
||||
medium,
|
||||
low,
|
||||
}: {
|
||||
high: number;
|
||||
medium: number;
|
||||
low: number;
|
||||
}) {
|
||||
const total = high + medium + low;
|
||||
if (total === 0) return null;
|
||||
return (
|
||||
<div
|
||||
className="severity-stack"
|
||||
title={`${high} High · ${medium} Medium · ${low} Low`}
|
||||
>
|
||||
{high > 0 && (
|
||||
<div
|
||||
className="sev-segment sev-high"
|
||||
style={{ width: `${(high / total) * 100}%` }}
|
||||
>
|
||||
{high}
|
||||
</div>
|
||||
)}
|
||||
{medium > 0 && (
|
||||
<div
|
||||
className="sev-segment sev-medium"
|
||||
style={{ width: `${(medium / total) * 100}%` }}
|
||||
>
|
||||
{medium}
|
||||
</div>
|
||||
)}
|
||||
{low > 0 && (
|
||||
<div
|
||||
className="sev-segment sev-low"
|
||||
style={{ width: `${(low / total) * 100}%` }}
|
||||
>
|
||||
{low}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── LanguageHealthTable ────────────────────────────────────────────────────
|
||||
|
||||
export function LanguageHealthTable({ rows }: { rows: LanguageHealth[] }) {
|
||||
if (!rows.length) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<p>No data</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Language</th>
|
||||
<th>Findings</th>
|
||||
<th>Severity</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={r.language}>
|
||||
<td>{r.language}</td>
|
||||
<td>{r.findings}</td>
|
||||
<td>
|
||||
<SeverityStack high={r.high} medium={r.medium} low={r.low} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
// ── SuppressionHygieneCard ─────────────────────────────────────────────────
|
||||
|
||||
export function SuppressionHygieneCard({
|
||||
hygiene,
|
||||
}: {
|
||||
hygiene: SuppressionHygiene;
|
||||
}) {
|
||||
const total =
|
||||
hygiene.fingerprint_level +
|
||||
hygiene.rule_level +
|
||||
hygiene.file_level +
|
||||
hygiene.rule_in_file_level;
|
||||
const blanket =
|
||||
hygiene.rule_level + hygiene.file_level + hygiene.rule_in_file_level;
|
||||
const blanketDisplay =
|
||||
total > 0 ? `${(hygiene.blanket_rate * 100).toFixed(0)}%` : 'n/a';
|
||||
const blanketDetail =
|
||||
total > 0
|
||||
? `${blanket} of ${total} suppressions are not pinned to a specific finding`
|
||||
: 'No suppressions yet';
|
||||
return (
|
||||
<dl className="kv-list">
|
||||
<div className="kv-row kv-row-emphasis">
|
||||
<dt
|
||||
className="kv-label"
|
||||
title="Share of suppressions that are not pinned to a specific finding fingerprint. Lower is better — it means triage is decisive rather than blanket-silencing whole rules or files."
|
||||
>
|
||||
Blanket rate
|
||||
<span className="kv-hint">Lower is better</span>
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{blanketDisplay}</div>
|
||||
<div className="kv-detail">{blanketDetail}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="kv-row">
|
||||
<dt
|
||||
className="kv-label"
|
||||
title="Suppressions that target one specific finding by its fingerprint. Most precise."
|
||||
>
|
||||
By fingerprint
|
||||
<span className="kv-hint">Most specific</span>
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{hygiene.fingerprint_level}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="kv-row">
|
||||
<dt
|
||||
className="kv-label"
|
||||
title="Suppressions that silence a rule only inside a specific file."
|
||||
>
|
||||
By rule in a file
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{hygiene.rule_in_file_level}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="kv-row">
|
||||
<dt
|
||||
className="kv-label"
|
||||
title="Suppressions that silence an entire rule across the project."
|
||||
>
|
||||
By rule
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{hygiene.rule_level}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="kv-row">
|
||||
<dt
|
||||
className="kv-label"
|
||||
title="Suppressions that silence everything in a file."
|
||||
>
|
||||
By file
|
||||
<span className="kv-hint">Least specific</span>
|
||||
</dt>
|
||||
<dd className="kv-value">
|
||||
<div className="kv-number">{hygiene.file_level}</div>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
// ── BaselinePinControl ─────────────────────────────────────────────────────
|
||||
|
||||
interface BaselinePinControlProps {
|
||||
baseline?: BaselineInfo;
|
||||
latestScanId?: string;
|
||||
onPin: (scanId: string) => void;
|
||||
onUnpin: () => void;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
export function BaselinePinControl({
|
||||
baseline,
|
||||
latestScanId,
|
||||
onPin,
|
||||
onUnpin,
|
||||
isPending,
|
||||
}: BaselinePinControlProps) {
|
||||
const navigate = useNavigate();
|
||||
if (baseline) {
|
||||
const net = baseline.drift_new - baseline.drift_fixed;
|
||||
const driftClass =
|
||||
net > 0
|
||||
? 'baseline-drift-bad'
|
||||
: net < 0
|
||||
? 'baseline-drift-good'
|
||||
: 'baseline-drift-flat';
|
||||
return (
|
||||
<div className="baseline-strip">
|
||||
<span className="baseline-label">Baseline:</span>
|
||||
<button
|
||||
type="button"
|
||||
className="baseline-link"
|
||||
onClick={() => navigate(`/scans/${baseline.scan_id}`)}
|
||||
>
|
||||
{baseline.started_at
|
||||
? new Date(baseline.started_at).toLocaleDateString()
|
||||
: baseline.scan_id.slice(0, 8)}
|
||||
</button>
|
||||
<span className={driftClass}>
|
||||
drift: +{baseline.drift_new} new / -{baseline.drift_fixed} fixed (
|
||||
{net >= 0 ? '+' : ''}
|
||||
{net})
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="baseline-action"
|
||||
onClick={onUnpin}
|
||||
disabled={isPending}
|
||||
>
|
||||
Unpin
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!latestScanId) return null;
|
||||
return (
|
||||
<div className="baseline-strip baseline-strip-empty">
|
||||
<span className="baseline-label">No baseline pinned.</span>
|
||||
<button
|
||||
type="button"
|
||||
className="baseline-action"
|
||||
onClick={() => onPin(latestScanId)}
|
||||
disabled={isPending}
|
||||
>
|
||||
Pin latest scan as baseline
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
183
frontend/src/components/ui/CommandPalette.tsx
Normal file
183
frontend/src/components/ui/CommandPalette.tsx
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export interface PaletteCommand {
|
||||
id: string;
|
||||
/** Visible label. */
|
||||
label: string;
|
||||
/** Optional secondary line — section, hint, shortcut. */
|
||||
hint?: string;
|
||||
/** Group label for visual separation. */
|
||||
group?: string;
|
||||
/** Search aliases beyond the label. */
|
||||
keywords?: string[];
|
||||
/** Optional leading icon. */
|
||||
icon?: ReactNode;
|
||||
/** Optional trailing keyboard hint. */
|
||||
shortcut?: string;
|
||||
/** Either a route to navigate to, or an action callback. One must be set. */
|
||||
to?: string;
|
||||
action?: () => void;
|
||||
}
|
||||
|
||||
interface CommandPaletteProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
commands: PaletteCommand[];
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
function rank(query: string, cmd: PaletteCommand): number {
|
||||
if (!query) return 0;
|
||||
const q = query.toLowerCase();
|
||||
const haystacks = [cmd.label, cmd.hint ?? '', ...(cmd.keywords ?? [])].map(
|
||||
(s) => s.toLowerCase(),
|
||||
);
|
||||
let best = -1;
|
||||
for (const h of haystacks) {
|
||||
if (h.startsWith(q)) return 100;
|
||||
const idx = h.indexOf(q);
|
||||
if (idx >= 0 && (best < 0 || idx < best)) best = idx;
|
||||
}
|
||||
if (best < 0) return -1;
|
||||
return 50 - best;
|
||||
}
|
||||
|
||||
export function CommandPalette({
|
||||
open,
|
||||
onClose,
|
||||
commands,
|
||||
placeholder = 'Type a command or page...',
|
||||
}: CommandPaletteProps) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [highlight, setHighlight] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Reset state on each open so the palette feels fresh and the highlight
|
||||
// doesn't stick to a now-filtered-out item.
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setQuery('');
|
||||
setHighlight(0);
|
||||
requestAnimationFrame(() => inputRef.current?.focus());
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!query) return commands;
|
||||
return commands
|
||||
.map((cmd) => [cmd, rank(query, cmd)] as const)
|
||||
.filter(([, r]) => r >= 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([cmd]) => cmd);
|
||||
}, [commands, query]);
|
||||
|
||||
// Keep highlight inside the filtered range.
|
||||
useEffect(() => {
|
||||
if (highlight >= filtered.length) setHighlight(0);
|
||||
}, [filtered.length, highlight]);
|
||||
|
||||
const run = useCallback(
|
||||
(cmd: PaletteCommand) => {
|
||||
onClose();
|
||||
if (cmd.action) cmd.action();
|
||||
else if (cmd.to) navigate(cmd.to);
|
||||
},
|
||||
[navigate, onClose],
|
||||
);
|
||||
|
||||
const onKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose();
|
||||
} else if (event.key === 'ArrowDown') {
|
||||
event.preventDefault();
|
||||
setHighlight((h) => Math.min(h + 1, filtered.length - 1));
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
event.preventDefault();
|
||||
setHighlight((h) => Math.max(h - 1, 0));
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
const cmd = filtered[highlight];
|
||||
if (cmd) run(cmd);
|
||||
}
|
||||
},
|
||||
[filtered, highlight, onClose, run],
|
||||
);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
// Group while preserving filtered order.
|
||||
const groups = new Map<string, PaletteCommand[]>();
|
||||
for (const cmd of filtered) {
|
||||
const g = cmd.group ?? '';
|
||||
const arr = groups.get(g) ?? [];
|
||||
arr.push(cmd);
|
||||
groups.set(g, arr);
|
||||
}
|
||||
|
||||
let runningIndex = 0;
|
||||
return (
|
||||
<div className="palette-overlay" role="dialog" aria-label="Command palette">
|
||||
<div className="palette-backdrop" onClick={onClose} />
|
||||
<div className="palette" role="combobox" aria-expanded="true">
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="palette-input"
|
||||
placeholder={placeholder}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
aria-label="Command search"
|
||||
aria-autocomplete="list"
|
||||
/>
|
||||
<ul className="palette-list" role="listbox">
|
||||
{filtered.length === 0 && (
|
||||
<li className="palette-empty">No matches</li>
|
||||
)}
|
||||
{Array.from(groups.entries()).map(([group, items]) => (
|
||||
<li key={group || '_'} className="palette-group">
|
||||
{group && <div className="palette-group-label">{group}</div>}
|
||||
<ul>
|
||||
{items.map((cmd) => {
|
||||
const idx = runningIndex++;
|
||||
const active = idx === highlight;
|
||||
return (
|
||||
<li
|
||||
key={cmd.id}
|
||||
role="option"
|
||||
aria-selected={active}
|
||||
className={`palette-item${active ? ' active' : ''}`}
|
||||
onMouseEnter={() => setHighlight(idx)}
|
||||
onClick={() => run(cmd)}
|
||||
>
|
||||
{cmd.icon && (
|
||||
<span className="palette-icon">{cmd.icon}</span>
|
||||
)}
|
||||
<span className="palette-label">{cmd.label}</span>
|
||||
{cmd.hint && (
|
||||
<span className="palette-hint">{cmd.hint}</span>
|
||||
)}
|
||||
{cmd.shortcut && (
|
||||
<kbd className="palette-shortcut">{cmd.shortcut}</kbd>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,13 +1,73 @@
|
|||
import { ApiError } from '../../api/client';
|
||||
import { RefreshIcon } from '../icons/Icons';
|
||||
|
||||
interface ErrorStateProps {
|
||||
title?: string;
|
||||
message: string;
|
||||
/** Either a plain message string or any thrown value (Error, ApiError, unknown). */
|
||||
message?: string;
|
||||
error?: unknown;
|
||||
onRetry?: () => void;
|
||||
retryLabel?: string;
|
||||
}
|
||||
|
||||
export function ErrorState({ title = 'Error', message }: ErrorStateProps) {
|
||||
interface FriendlyError {
|
||||
title: string;
|
||||
message: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
/** Translate a thrown value into a title + message + hint we can render. */
|
||||
function friendly(error: unknown, fallbackTitle: string): FriendlyError {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.isNetwork()) {
|
||||
return {
|
||||
title: 'Network error',
|
||||
message: error.message || 'Could not reach the Nyx server.',
|
||||
};
|
||||
}
|
||||
if (error.status === 404) {
|
||||
return { title: 'Not found', message: error.message };
|
||||
}
|
||||
if (error.status === 403) {
|
||||
return { title: 'Forbidden', message: error.message };
|
||||
}
|
||||
if (error.status === 409) {
|
||||
return { title: 'Conflict', message: error.message };
|
||||
}
|
||||
if (error.status >= 500) {
|
||||
return {
|
||||
title: 'Server error',
|
||||
message: error.message || 'The Nyx server returned an error.',
|
||||
hint: 'Server logs may have more detail.',
|
||||
};
|
||||
}
|
||||
return { title: fallbackTitle, message: error.message };
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return { title: fallbackTitle, message: error.message };
|
||||
}
|
||||
if (typeof error === 'string') {
|
||||
return { title: fallbackTitle, message: error };
|
||||
}
|
||||
return { title: fallbackTitle, message: 'An unknown error occurred.' };
|
||||
}
|
||||
|
||||
export function ErrorState({
|
||||
title,
|
||||
message,
|
||||
error,
|
||||
onRetry,
|
||||
retryLabel = 'Try again',
|
||||
}: ErrorStateProps) {
|
||||
const fallbackTitle = title ?? 'Error';
|
||||
const resolved = error
|
||||
? friendly(error, fallbackTitle)
|
||||
: { title: fallbackTitle, message: message ?? 'An error occurred.' };
|
||||
|
||||
return (
|
||||
<div className="error-state">
|
||||
<h3>{title}</h3>
|
||||
<p>{message}</p>
|
||||
<div className="error-state" role="alert">
|
||||
<h3>{resolved.title}</h3>
|
||||
<p>{resolved.message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,19 @@
|
|||
interface LoadingStateProps {
|
||||
message?: string;
|
||||
/**
|
||||
* Suppresses the spinner for the first ~150ms so trivially-fast queries
|
||||
* don't flash a spinner on screen. The text shows instantly so there's
|
||||
* always *something* — but the visible spin only kicks in if work is
|
||||
* actually slow.
|
||||
*/
|
||||
delaySpinnerMs?: number;
|
||||
}
|
||||
|
||||
export function LoadingState({ message = 'Loading...' }: LoadingStateProps) {
|
||||
return <div className="loading">{message}</div>;
|
||||
return (
|
||||
<div className="loading" role="status" aria-live="polite">
|
||||
<span className="spinner" aria-hidden="true" />
|
||||
<span className="loading-message">{message}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
87
frontend/src/components/ui/ShortcutsHelp.tsx
Normal file
87
frontend/src/components/ui/ShortcutsHelp.tsx
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
interface ShortcutsHelpProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface Row {
|
||||
keys: string[];
|
||||
description: string;
|
||||
}
|
||||
|
||||
const ROWS: { section: string; rows: Row[] }[] = [
|
||||
{
|
||||
section: 'Global',
|
||||
rows: [
|
||||
{ keys: ['⌘', 'K'], description: 'Open command palette' },
|
||||
{ keys: ['/'], description: 'Focus search (on findings page)' },
|
||||
{ keys: ['?'], description: 'Show this help' },
|
||||
{ keys: ['Esc'], description: 'Close modal / palette' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'Findings list',
|
||||
rows: [
|
||||
{ keys: ['j'], description: 'Next finding' },
|
||||
{ keys: ['k'], description: 'Previous finding' },
|
||||
{ keys: ['Enter'], description: 'Open highlighted finding' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'Navigation',
|
||||
rows: [
|
||||
{ keys: ['g', 'o'], description: 'Go to Overview' },
|
||||
{ keys: ['g', 'f'], description: 'Go to Findings' },
|
||||
{ keys: ['g', 's'], description: 'Go to Scans' },
|
||||
{ keys: ['g', 'r'], description: 'Go to Rules' },
|
||||
{ keys: ['g', 't'], description: 'Go to Triage' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function ShortcutsHelp({ open, onClose }: ShortcutsHelpProps) {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div
|
||||
className="palette-overlay"
|
||||
role="dialog"
|
||||
aria-label="Keyboard shortcuts"
|
||||
>
|
||||
<div className="palette-backdrop" onClick={onClose} />
|
||||
<div className="shortcuts-modal">
|
||||
<div className="shortcuts-header">
|
||||
<h2>Keyboard shortcuts</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
onClick={onClose}
|
||||
aria-label="Close shortcuts help"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<div className="shortcuts-body">
|
||||
{ROWS.map((section) => (
|
||||
<section key={section.section}>
|
||||
<h3>{section.section}</h3>
|
||||
<dl>
|
||||
{section.rows.map((row) => (
|
||||
<div key={row.description} className="shortcut-row">
|
||||
<dt>
|
||||
{row.keys.map((k, i) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <span className="shortcut-sep">then</span>}
|
||||
<kbd>{k}</kbd>
|
||||
</span>
|
||||
))}
|
||||
</dt>
|
||||
<dd>{row.description}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
38
frontend/src/components/ui/Toaster.tsx
Normal file
38
frontend/src/components/ui/Toaster.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { useToast } from '../../contexts/ToastContext';
|
||||
import { CloseIcon } from '../icons/Icons';
|
||||
|
||||
export function Toaster() {
|
||||
const { toasts, dismiss } = useToast();
|
||||
|
||||
if (toasts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="toaster"
|
||||
role="region"
|
||||
aria-label="Notifications"
|
||||
aria-live="polite"
|
||||
>
|
||||
{toasts.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
className={`toast toast-${t.tone}`}
|
||||
role={t.tone === 'error' || t.tone === 'warning' ? 'alert' : 'status'}
|
||||
>
|
||||
<div className="toast-body">
|
||||
{t.title && <div className="toast-title">{t.title}</div>}
|
||||
<div className="toast-message">{t.message}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="toast-close"
|
||||
aria-label="Dismiss notification"
|
||||
onClick={() => dismiss(t.id)}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
91
frontend/src/contexts/ThemeContext.tsx
Normal file
91
frontend/src/contexts/ThemeContext.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { usePersistedState } from '../hooks/usePersistedState';
|
||||
|
||||
export type ThemePreference =
|
||||
| 'light'
|
||||
| 'dark'
|
||||
| 'system'
|
||||
| 'hc-light'
|
||||
| 'hc-dark';
|
||||
export type ResolvedTheme = 'light' | 'dark' | 'hc-light' | 'hc-dark';
|
||||
|
||||
interface ThemeContextValue {
|
||||
preference: ThemePreference;
|
||||
resolved: ResolvedTheme;
|
||||
setPreference: (next: ThemePreference) => void;
|
||||
/** Cycle light → dark → system → light. Used by the toolbar toggle. */
|
||||
cycle: () => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
function systemPrefersDark(): boolean {
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
||||
}
|
||||
|
||||
function resolve(pref: ThemePreference): ResolvedTheme {
|
||||
if (pref === 'system') return systemPrefersDark() ? 'dark' : 'light';
|
||||
return pref;
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [preference, setPreference] = usePersistedState<ThemePreference>(
|
||||
'theme',
|
||||
'system',
|
||||
);
|
||||
|
||||
const resolved = useMemo(() => resolve(preference), [preference]);
|
||||
|
||||
// Reflect the resolved theme onto <html> so CSS rules under
|
||||
// [data-theme="dark"] take effect.
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-theme', resolved);
|
||||
}, [resolved]);
|
||||
|
||||
// When the user picks "system", react to OS-level changes live.
|
||||
useEffect(() => {
|
||||
if (preference !== 'system') return;
|
||||
const mq = window.matchMedia?.('(prefers-color-scheme: dark)');
|
||||
if (!mq) return;
|
||||
const handler = () => {
|
||||
document.documentElement.setAttribute(
|
||||
'data-theme',
|
||||
systemPrefersDark() ? 'dark' : 'light',
|
||||
);
|
||||
};
|
||||
mq.addEventListener('change', handler);
|
||||
return () => mq.removeEventListener('change', handler);
|
||||
}, [preference]);
|
||||
|
||||
const cycle = useCallback(() => {
|
||||
setPreference((prev) => {
|
||||
if (prev === 'hc-light') return 'hc-dark';
|
||||
if (prev === 'hc-dark') return 'hc-light';
|
||||
if (prev === 'light') return 'dark';
|
||||
if (prev === 'dark') return 'system';
|
||||
return 'light';
|
||||
});
|
||||
}, [setPreference]);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(
|
||||
() => ({ preference, resolved, setPreference, cycle }),
|
||||
[preference, resolved, setPreference, cycle],
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
const ctx = useContext(ThemeContext);
|
||||
if (!ctx) throw new Error('useTheme must be used inside <ThemeProvider>');
|
||||
return ctx;
|
||||
}
|
||||
97
frontend/src/contexts/ToastContext.tsx
Normal file
97
frontend/src/contexts/ToastContext.tsx
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
|
||||
export type ToastTone = 'info' | 'success' | 'warning' | 'error';
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
tone: ToastTone;
|
||||
title?: string;
|
||||
message: string;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
interface ToastContextValue {
|
||||
toasts: Toast[];
|
||||
push: (
|
||||
t: Omit<Toast, 'id' | 'durationMs'> & { durationMs?: number },
|
||||
) => number;
|
||||
dismiss: (id: number) => void;
|
||||
/** Convenience helpers — call sites read more naturally as toast.error('…'). */
|
||||
info: (message: string, title?: string) => number;
|
||||
success: (message: string, title?: string) => number;
|
||||
warning: (message: string, title?: string) => number;
|
||||
error: (message: string, title?: string) => number;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||
|
||||
const DEFAULT_DURATION: Record<ToastTone, number> = {
|
||||
info: 4000,
|
||||
success: 4000,
|
||||
warning: 6000,
|
||||
// Error toasts stick longer — failures usually need a deliberate read.
|
||||
error: 8000,
|
||||
};
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
const nextId = useRef(1);
|
||||
const timers = useRef(new Map<number, number>());
|
||||
|
||||
const dismiss = useCallback((id: number) => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
const handle = timers.current.get(id);
|
||||
if (handle !== undefined) {
|
||||
window.clearTimeout(handle);
|
||||
timers.current.delete(id);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const push = useCallback<ToastContextValue['push']>(
|
||||
({ tone, title, message, durationMs }) => {
|
||||
const id = nextId.current++;
|
||||
const duration = durationMs ?? DEFAULT_DURATION[tone];
|
||||
setToasts((prev) => [
|
||||
...prev,
|
||||
{ id, tone, title, message, durationMs: duration },
|
||||
]);
|
||||
if (duration > 0) {
|
||||
const handle = window.setTimeout(() => dismiss(id), duration);
|
||||
timers.current.set(id, handle);
|
||||
}
|
||||
return id;
|
||||
},
|
||||
[dismiss],
|
||||
);
|
||||
|
||||
const value = useMemo<ToastContextValue>(
|
||||
() => ({
|
||||
toasts,
|
||||
push,
|
||||
dismiss,
|
||||
info: (message, title) => push({ tone: 'info', message, title }),
|
||||
success: (message, title) => push({ tone: 'success', message, title }),
|
||||
warning: (message, title) => push({ tone: 'warning', message, title }),
|
||||
error: (message, title) => push({ tone: 'error', message, title }),
|
||||
}),
|
||||
[toasts, push, dismiss],
|
||||
);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={value}>{children}</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast(): ToastContextValue {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) throw new Error('useToast must be used inside <ToastProvider>');
|
||||
return ctx;
|
||||
}
|
||||
62
frontend/src/hooks/useChordNavigation.ts
Normal file
62
frontend/src/hooks/useChordNavigation.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const CHORD_TIMEOUT_MS = 800;
|
||||
|
||||
const ROUTES: Record<string, string> = {
|
||||
o: '/',
|
||||
f: '/findings',
|
||||
s: '/scans',
|
||||
r: '/rules',
|
||||
t: '/triage',
|
||||
c: '/config',
|
||||
e: '/explorer',
|
||||
d: '/debug',
|
||||
};
|
||||
|
||||
function isTypingTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
const tag = target.tagName;
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
|
||||
if (target.isContentEditable) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vim-style "g then X" navigation: press `g`, then within 800ms press a
|
||||
* letter to jump to that section. Cancels if the user types in an input.
|
||||
*/
|
||||
export function useChordNavigation() {
|
||||
const navigate = useNavigate();
|
||||
const armed = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (isTypingTarget(event.target)) return;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
|
||||
if (armed.current !== null) {
|
||||
const route = ROUTES[event.key.toLowerCase()];
|
||||
window.clearTimeout(armed.current);
|
||||
armed.current = null;
|
||||
if (route) {
|
||||
event.preventDefault();
|
||||
navigate(route);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'g') {
|
||||
event.preventDefault();
|
||||
armed.current = window.setTimeout(() => {
|
||||
armed.current = null;
|
||||
}, CHORD_TIMEOUT_MS);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
if (armed.current !== null) window.clearTimeout(armed.current);
|
||||
};
|
||||
}, [navigate]);
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { usePersistedState } from './usePersistedState';
|
||||
|
||||
export interface FindingsURLState {
|
||||
page: string;
|
||||
|
|
@ -29,6 +30,21 @@ const FINDINGS_DEFAULTS: FindingsURLState = {
|
|||
search: '',
|
||||
};
|
||||
|
||||
/** Subset of state we remember across sessions. Filters intentionally are
|
||||
* NOT persisted — they're scan-specific and should reset by default, but the
|
||||
* URL still reflects them so a shared link reproduces them exactly. */
|
||||
interface PersistedFindingsPrefs {
|
||||
per_page: string;
|
||||
sort_by: string;
|
||||
sort_dir: string;
|
||||
}
|
||||
|
||||
const DEFAULT_PREFS: PersistedFindingsPrefs = {
|
||||
per_page: '50',
|
||||
sort_by: '',
|
||||
sort_dir: 'asc',
|
||||
};
|
||||
|
||||
const FILTER_KEYS: ReadonlySet<string> = new Set([
|
||||
'severity',
|
||||
'category',
|
||||
|
|
@ -49,16 +65,42 @@ const NON_RESET_KEYS: ReadonlySet<string> = new Set([
|
|||
|
||||
export function useFindingsURLState() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [prefs, setPrefs] = usePersistedState<PersistedFindingsPrefs>(
|
||||
'findings:prefs',
|
||||
DEFAULT_PREFS,
|
||||
);
|
||||
|
||||
const state: FindingsURLState = useMemo(() => {
|
||||
const s = {} as FindingsURLState;
|
||||
for (const key of Object.keys(
|
||||
FINDINGS_DEFAULTS,
|
||||
) as (keyof FindingsURLState)[]) {
|
||||
s[key] = searchParams.get(key) || FINDINGS_DEFAULTS[key];
|
||||
// URL wins; fall back to remembered prefs for keys we persist;
|
||||
// last resort is the global default.
|
||||
const fromUrl = searchParams.get(key);
|
||||
if (fromUrl) {
|
||||
s[key] = fromUrl;
|
||||
} else if (
|
||||
key === 'per_page' ||
|
||||
key === 'sort_by' ||
|
||||
key === 'sort_dir'
|
||||
) {
|
||||
s[key] = prefs[key] || FINDINGS_DEFAULTS[key];
|
||||
} else {
|
||||
s[key] = FINDINGS_DEFAULTS[key];
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}, [searchParams]);
|
||||
}, [searchParams, prefs]);
|
||||
|
||||
// Persist user-driven changes to per_page / sort_*.
|
||||
useEffect(() => {
|
||||
setPrefs({
|
||||
per_page: state.per_page,
|
||||
sort_by: state.sort_by,
|
||||
sort_dir: state.sort_dir,
|
||||
});
|
||||
}, [state.per_page, state.sort_by, state.sort_dir, setPrefs]);
|
||||
|
||||
const updateState = useCallback(
|
||||
(updates: Partial<FindingsURLState>) => {
|
||||
|
|
|
|||
63
frontend/src/hooks/useKeyboardShortcuts.ts
Normal file
63
frontend/src/hooks/useKeyboardShortcuts.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
export interface Shortcut {
|
||||
/** Key string per `KeyboardEvent.key` (e.g. "k", "/", "Escape"). */
|
||||
key: string;
|
||||
/** Require Cmd/Ctrl (matches the same on each OS). */
|
||||
meta?: boolean;
|
||||
/** Require Shift. */
|
||||
shift?: boolean;
|
||||
/** Require Alt. */
|
||||
alt?: boolean;
|
||||
description: string;
|
||||
handler: (event: KeyboardEvent) => void;
|
||||
/**
|
||||
* If true, the shortcut still fires when focus is in an input/textarea/
|
||||
* contenteditable. Default is false — shortcuts shouldn't hijack typing.
|
||||
*/
|
||||
allowInInput?: boolean;
|
||||
}
|
||||
|
||||
function isTypingTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
const tag = target.tagName;
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
|
||||
if (target.isContentEditable) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
|
||||
if (event.key !== shortcut.key) return false;
|
||||
const wantMeta = !!shortcut.meta;
|
||||
const hasMeta = event.metaKey || event.ctrlKey;
|
||||
if (wantMeta !== hasMeta) return false;
|
||||
if (!!shortcut.shift !== event.shiftKey) return false;
|
||||
if (!!shortcut.alt !== event.altKey) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a list of keyboard shortcuts at the document level.
|
||||
*
|
||||
* Pass a stable array (memoize or hoist outside the component) to avoid
|
||||
* unnecessary re-binding. Shortcuts with `meta: true` match either Cmd or
|
||||
* Ctrl so the same binding works on macOS and Linux/Windows.
|
||||
*/
|
||||
export function useKeyboardShortcuts(shortcuts: Shortcut[]) {
|
||||
useEffect(() => {
|
||||
if (shortcuts.length === 0) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
const typing = isTypingTarget(event.target);
|
||||
for (const sc of shortcuts) {
|
||||
if (typing && !sc.allowInInput) continue;
|
||||
if (matches(event, sc)) {
|
||||
event.preventDefault();
|
||||
sc.handler(event);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => document.removeEventListener('keydown', onKeyDown);
|
||||
}, [shortcuts]);
|
||||
}
|
||||
19
frontend/src/hooks/usePageTitle.ts
Normal file
19
frontend/src/hooks/usePageTitle.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
const APP_NAME = 'Nyx';
|
||||
|
||||
/**
|
||||
* Sets `document.title` to `<page> · Nyx`. Restores the previous title on
|
||||
* unmount so transient pages (e.g. modals that re-render the page) don't
|
||||
* leave the title stuck.
|
||||
*/
|
||||
export function usePageTitle(title: string | null | undefined) {
|
||||
useEffect(() => {
|
||||
if (!title) return;
|
||||
const prev = document.title;
|
||||
document.title = `${title} · ${APP_NAME}`;
|
||||
return () => {
|
||||
document.title = prev;
|
||||
};
|
||||
}, [title]);
|
||||
}
|
||||
59
frontend/src/hooks/usePersistedState.ts
Normal file
59
frontend/src/hooks/usePersistedState.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
const STORAGE_PREFIX = 'nyx:';
|
||||
|
||||
function storageKey(key: string) {
|
||||
return `${STORAGE_PREFIX}${key}`;
|
||||
}
|
||||
|
||||
function read<T>(key: string, fallback: T): T {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey(key));
|
||||
if (raw === null) return fallback;
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function write<T>(key: string, value: T): void {
|
||||
try {
|
||||
window.localStorage.setItem(storageKey(key), JSON.stringify(value));
|
||||
} catch {
|
||||
// Quota exceeded or storage disabled — silently degrade.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `useState` that persists to `localStorage` under `nyx:<key>`.
|
||||
*
|
||||
* Suitable for view preferences (theme, sidebar collapse, default page size).
|
||||
* Not suitable for sensitive data — `localStorage` is not encrypted.
|
||||
*
|
||||
* Cross-tab sync is not implemented; if the user opens two tabs they get
|
||||
* independent state until next load. That's the common-case ergonomic.
|
||||
*/
|
||||
export function usePersistedState<T>(
|
||||
key: string,
|
||||
initial: T,
|
||||
): [T, (next: T | ((prev: T) => T)) => void] {
|
||||
const [state, setState] = useState<T>(() => read(key, initial));
|
||||
|
||||
// Avoid writing back the initial value on first mount when nothing changed.
|
||||
const hydrated = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!hydrated.current) {
|
||||
hydrated.current = true;
|
||||
return;
|
||||
}
|
||||
write(key, state);
|
||||
}, [key, state]);
|
||||
|
||||
const set = useCallback((next: T | ((prev: T) => T)) => {
|
||||
setState((prev) =>
|
||||
typeof next === 'function' ? (next as (p: T) => T)(prev) : next,
|
||||
);
|
||||
}, []);
|
||||
|
||||
return [state, set];
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@ import { useState } from 'react';
|
|||
import { useNavigate } from 'react-router-dom';
|
||||
import { Modal } from '../components/ui/Modal';
|
||||
import { useHealth } from '../api/queries/health';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import { ApiError } from '../api/client';
|
||||
import {
|
||||
useStartScan,
|
||||
type ScanMode,
|
||||
|
|
@ -31,6 +33,7 @@ export function NewScanModal({ open, onClose }: NewScanModalProps) {
|
|||
const { data: health } = useHealth();
|
||||
const startScan = useStartScan();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const defaultRoot = health?.scan_root || '';
|
||||
const [scanRoot, setScanRoot] = useState('');
|
||||
const [mode, setMode] = useState<ScanMode>('full');
|
||||
|
|
@ -45,10 +48,17 @@ export function NewScanModal({ open, onClose }: NewScanModalProps) {
|
|||
const payload = Object.keys(body).length ? body : undefined;
|
||||
try {
|
||||
await startScan.mutateAsync(payload);
|
||||
toast.success('Scan started', 'Started');
|
||||
onClose();
|
||||
navigate('/scans');
|
||||
} catch (e) {
|
||||
alert(e instanceof Error ? e.message : 'Failed to start scan');
|
||||
const msg =
|
||||
e instanceof ApiError && e.status === 409
|
||||
? 'A scan is already running'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Failed to start scan';
|
||||
toast.error(msg, 'Could not start scan');
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -10,6 +10,7 @@ import { ApiError } from '../api/client';
|
|||
import { FileTree } from '../components/data-display/FileTree';
|
||||
import { CodeViewer } from '../components/data-display/CodeViewer';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import { EmptyState } from '../components/ui/EmptyState';
|
||||
import { ExplorerIcon } from '../components/icons/Icons';
|
||||
import { useFileTree } from '../hooks/useFileTree';
|
||||
|
|
@ -20,6 +21,9 @@ import { TaintAnalysisPanel } from './debug/TaintViewerPage';
|
|||
import { SummaryAnalysisPanel } from './debug/SummaryExplorerPage';
|
||||
import { AbstractInterpAnalysisPanel } from './debug/AbstractInterpPage';
|
||||
import { SymexAnalysisPanel } from './debug/SymexPage';
|
||||
import { PointerAnalysisPanel } from './debug/PointerViewerPage';
|
||||
import { TypeFactsAnalysisPanel } from './debug/TypeFactsPage';
|
||||
import { AuthAnalysisPanel } from './debug/AuthAnalysisPage';
|
||||
import type { TreeEntry, FlowStep, FindingView } from '../api/types';
|
||||
|
||||
type ExplorerMode = 'tree' | 'symbols' | 'hotspots';
|
||||
|
|
@ -30,7 +34,10 @@ type ExplorerView =
|
|||
| 'taint'
|
||||
| 'summaries'
|
||||
| 'abstract-interp'
|
||||
| 'symex';
|
||||
| 'symex'
|
||||
| 'pointer'
|
||||
| 'type-facts'
|
||||
| 'auth';
|
||||
|
||||
const FLOW_KIND_COLORS: Record<string, string> = {
|
||||
source: 'var(--success)',
|
||||
|
|
@ -76,13 +83,28 @@ const VIEW_CONFIG: Array<{
|
|||
requiresFunction: true,
|
||||
supportsFunction: true,
|
||||
},
|
||||
{
|
||||
id: 'pointer',
|
||||
label: 'Pointer',
|
||||
requiresFunction: true,
|
||||
supportsFunction: true,
|
||||
},
|
||||
{
|
||||
id: 'type-facts',
|
||||
label: 'Type Facts',
|
||||
requiresFunction: true,
|
||||
supportsFunction: true,
|
||||
},
|
||||
{ id: 'auth', label: 'Auth' },
|
||||
];
|
||||
|
||||
const VIEW_CONFIG_BY_ID = new Map(VIEW_CONFIG.map((view) => [view.id, view]));
|
||||
|
||||
export function ExplorerPage() {
|
||||
usePageTitle('Explorer');
|
||||
const [params, setParams] = useSearchParams();
|
||||
const [explorerMode, setExplorerMode] = useState<ExplorerMode>('tree');
|
||||
const [showClosures, setShowClosures] = useState(false);
|
||||
const [highlightLine, setHighlightLine] = useState<number | undefined>();
|
||||
const [selectedFindingIndex, setSelectedFindingIndex] = useState<
|
||||
number | null
|
||||
|
|
@ -130,6 +152,18 @@ export function ExplorerPage() {
|
|||
|
||||
const { data: symbolEntries, error: symbolsError } =
|
||||
useExplorerSymbols(rawFile);
|
||||
|
||||
const closureSymbolCount = useMemo(
|
||||
() => symbolEntries?.filter((s) => s.func_kind === 'closure').length ?? 0,
|
||||
[symbolEntries],
|
||||
);
|
||||
|
||||
const visibleSymbolEntries = useMemo(() => {
|
||||
if (!symbolEntries) return symbolEntries;
|
||||
return showClosures
|
||||
? symbolEntries
|
||||
: symbolEntries.filter((s) => s.func_kind !== 'closure');
|
||||
}, [symbolEntries, showClosures]);
|
||||
const hasInvalidFile = Boolean(
|
||||
rawFile && isPathResolutionError(symbolsError),
|
||||
);
|
||||
|
|
@ -315,8 +349,21 @@ export function ExplorerPage() {
|
|||
{selectedFile && symbolEntries && symbolEntries.length === 0 && (
|
||||
<div className="explorer-hint">No symbols found</div>
|
||||
)}
|
||||
{selectedFile && closureSymbolCount > 0 && (
|
||||
<label className="explorer-symbol-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showClosures}
|
||||
onChange={(e) => setShowClosures(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
Show {closureSymbolCount} anonymous closure
|
||||
{closureSymbolCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
{selectedFile &&
|
||||
symbolEntries?.map((sym, index) => (
|
||||
visibleSymbolEntries?.map((sym, index) => (
|
||||
<div
|
||||
key={`${sym.name}-${index}`}
|
||||
className="explorer-symbol-item"
|
||||
|
|
@ -328,6 +375,16 @@ export function ExplorerPage() {
|
|||
{sym.arity !== undefined && sym.arity !== null && (
|
||||
<span className="symbol-arity">({sym.arity})</span>
|
||||
)}
|
||||
{sym.func_kind === 'closure' && (
|
||||
<span
|
||||
className="text-secondary"
|
||||
style={{ marginLeft: 6, fontSize: '0.85em' }}
|
||||
>
|
||||
{sym.container
|
||||
? `[closure in ${sym.container}]`
|
||||
: '[closure]'}
|
||||
</span>
|
||||
)}
|
||||
{sym.finding_count > 0 && (
|
||||
<span className="tree-node-badge">
|
||||
{sym.finding_count}
|
||||
|
|
@ -378,14 +435,12 @@ export function ExplorerPage() {
|
|||
</span>
|
||||
</div>
|
||||
{selectedFile && currentViewConfig.supportsFunction && (
|
||||
<div className="explorer-function-picker">
|
||||
<FunctionSelector
|
||||
file={selectedFile}
|
||||
selectedFunction={selectedFunction}
|
||||
onFunctionChange={handleFunctionChange}
|
||||
showFilePath={false}
|
||||
/>
|
||||
</div>
|
||||
<FunctionSelector
|
||||
file={selectedFile}
|
||||
selectedFunction={selectedFunction}
|
||||
onFunctionChange={handleFunctionChange}
|
||||
showFilePath={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
|
|
@ -500,7 +555,7 @@ export function ExplorerPage() {
|
|||
{symbolEntries && symbolEntries.length === 0 && (
|
||||
<div className="explorer-hint">No symbols found</div>
|
||||
)}
|
||||
{symbolEntries?.map((sym, index) => (
|
||||
{visibleSymbolEntries?.map((sym, index) => (
|
||||
<div
|
||||
key={`${sym.name}-${index}`}
|
||||
className="explorer-symbol-item compact"
|
||||
|
|
@ -509,8 +564,26 @@ export function ExplorerPage() {
|
|||
{sym.kind === 'function' ? 'ƒ' : 'm'}
|
||||
</span>
|
||||
<span className="symbol-name">{sym.name}</span>
|
||||
{sym.func_kind === 'closure' && (
|
||||
<span
|
||||
className="text-secondary"
|
||||
style={{ marginLeft: 6, fontSize: '0.85em' }}
|
||||
>
|
||||
[closure]
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!showClosures && closureSymbolCount > 0 && (
|
||||
<button
|
||||
className="explorer-symbol-toggle-link"
|
||||
type="button"
|
||||
onClick={() => setShowClosures(true)}
|
||||
>
|
||||
Show {closureSymbolCount} closure
|
||||
{closureSymbolCount === 1 ? '' : 's'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="explorer-right-section">
|
||||
|
|
@ -601,6 +674,14 @@ function renderAnalysisContent({
|
|||
);
|
||||
}
|
||||
|
||||
if (currentView === 'auth') {
|
||||
return (
|
||||
<div className="explorer-analysis-content">
|
||||
<AuthAnalysisPanel file={selectedFile} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (functionsLoading) {
|
||||
return <LoadingState message="Loading functions..." />;
|
||||
}
|
||||
|
|
@ -664,6 +745,24 @@ function renderAnalysisContent({
|
|||
/>
|
||||
</div>
|
||||
);
|
||||
case 'pointer':
|
||||
return (
|
||||
<div className="explorer-analysis-content">
|
||||
<PointerAnalysisPanel
|
||||
file={selectedFile}
|
||||
functionName={selectedFunction}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
case 'type-facts':
|
||||
return (
|
||||
<div className="explorer-analysis-content">
|
||||
<TypeFactsAnalysisPanel
|
||||
file={selectedFile}
|
||||
functionName={selectedFunction}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
case 'code':
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useState, useCallback } from 'react';
|
|||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { useFinding } from '../api/queries/findings';
|
||||
import { useBulkTriage } from '../api/mutations/triage';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import { truncPath } from '../utils/truncPath';
|
||||
import { escapeHtml, highlightSyntax } from '../utils/syntaxHighlight';
|
||||
import { parseNoteText } from '../utils/parseNote';
|
||||
|
|
@ -816,6 +817,11 @@ export function FindingDetailPage() {
|
|||
const { id } = useParams<{ id: string }>();
|
||||
|
||||
const { data: finding, isLoading, isError, error } = useFinding(id ?? '');
|
||||
usePageTitle(
|
||||
finding
|
||||
? `${finding.rule_id} · ${finding.path}:${finding.line}`
|
||||
: 'Finding',
|
||||
);
|
||||
|
||||
const bulkTriage = useBulkTriage();
|
||||
const [codeModalOpen, setCodeModalOpen] = useState(false);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import { useState, useCallback, useMemo, useEffect } from 'react';
|
||||
import { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useFindingsURLState } from '../hooks/useFindingsURLState';
|
||||
import { useDebounce } from '../hooks/useDebounce';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
||||
import { useToast } from '../contexts/ToastContext';
|
||||
import {
|
||||
useFindings,
|
||||
useFindingFilters,
|
||||
|
|
@ -11,9 +14,12 @@ import {
|
|||
import { useBulkTriage, useAddSuppression } from '../api/mutations/triage';
|
||||
import { Pagination } from '../components/ui/Pagination';
|
||||
import { Dropdown, DropdownItem } from '../components/ui/Dropdown';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { CopyMarkdownButton } from '../components/CopyMarkdownButton';
|
||||
import { truncPath } from '../utils/truncPath';
|
||||
import { findingsToMarkdown } from '../utils/findingMarkdown';
|
||||
import { ApiError } from '../api/client';
|
||||
import type { FindingView, FilterValues } from '../api/types';
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
|
@ -279,8 +285,10 @@ function SortableTh({
|
|||
// ── Main Component ──────────────────────────────────────────────────────────
|
||||
|
||||
export function FindingsPage() {
|
||||
usePageTitle('Findings');
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const toast = useToast();
|
||||
const { state, updateState, resetFilters, hasActiveFilters } =
|
||||
useFindingsURLState();
|
||||
|
||||
|
|
@ -388,10 +396,22 @@ export function FindingsPage() {
|
|||
if (fingerprints.length === 0) return;
|
||||
bulkTriage.mutate(
|
||||
{ fingerprints, state: triageState, note: '' },
|
||||
{ onSuccess: () => setSelected(new Set()) },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setSelected(new Set());
|
||||
toast.success(
|
||||
`Marked ${fingerprints.length} finding${fingerprints.length === 1 ? '' : 's'} as ${triageState.replace('_', ' ')}`,
|
||||
);
|
||||
},
|
||||
onError: (err) =>
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : 'Bulk triage failed',
|
||||
'Could not update findings',
|
||||
),
|
||||
},
|
||||
);
|
||||
},
|
||||
[getSelectedFingerprints, bulkTriage],
|
||||
[getSelectedFingerprints, bulkTriage, toast],
|
||||
);
|
||||
|
||||
const handleSuppressByPattern = useCallback(() => {
|
||||
|
|
@ -435,7 +455,13 @@ export function FindingsPage() {
|
|||
onSuccess: () => {
|
||||
setSuppressModalOpen(false);
|
||||
setSelected(new Set());
|
||||
toast.success(`Added suppression by ${by}`);
|
||||
},
|
||||
onError: (err) =>
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : 'Suppression failed',
|
||||
'Could not add suppression',
|
||||
),
|
||||
},
|
||||
);
|
||||
},
|
||||
|
|
@ -470,15 +496,61 @@ export function FindingsPage() {
|
|||
[navigate],
|
||||
);
|
||||
|
||||
// ── Keyboard navigation: j/k row cursor + / search + Enter to open ──
|
||||
|
||||
const searchInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [cursor, setCursor] = useState(-1);
|
||||
|
||||
// Reset cursor whenever the visible page changes.
|
||||
useEffect(() => {
|
||||
setCursor(-1);
|
||||
}, [data]);
|
||||
|
||||
const shortcuts = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: '/',
|
||||
description: 'Focus search',
|
||||
handler: () => searchInputRef.current?.focus(),
|
||||
},
|
||||
{
|
||||
key: 'j',
|
||||
description: 'Next finding',
|
||||
handler: () => {
|
||||
if (!data || data.findings.length === 0) return;
|
||||
setCursor((c) => Math.min(c + 1, data.findings.length - 1));
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'k',
|
||||
description: 'Previous finding',
|
||||
handler: () => {
|
||||
if (!data || data.findings.length === 0) return;
|
||||
setCursor((c) => Math.max(c - 1, 0));
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'Enter',
|
||||
description: 'Open highlighted finding',
|
||||
handler: () => {
|
||||
const f = data?.findings[cursor];
|
||||
if (f) navigate(`/findings/${f.index}`);
|
||||
},
|
||||
},
|
||||
],
|
||||
[data, cursor, navigate],
|
||||
);
|
||||
|
||||
useKeyboardShortcuts(shortcuts);
|
||||
|
||||
// ── Render ──
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="loading">Loading findings...</div>;
|
||||
return <LoadingState message="Loading findings..." />;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
const msg = error instanceof Error ? error.message : 'Unknown error';
|
||||
if (msg.includes('404')) {
|
||||
if (error instanceof ApiError && error.status === 404) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<h3>No scan results yet</h3>
|
||||
|
|
@ -486,12 +558,7 @@ export function FindingsPage() {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="error-state">
|
||||
<h3>Error</h3>
|
||||
<p>{msg}</p>
|
||||
</div>
|
||||
);
|
||||
return <ErrorState title="Error" error={error} />;
|
||||
}
|
||||
|
||||
if (!data) return null;
|
||||
|
|
@ -513,6 +580,7 @@ export function FindingsPage() {
|
|||
<div className="filter-bar">
|
||||
<input
|
||||
type="text"
|
||||
ref={searchInputRef}
|
||||
placeholder="Search findings... (/)"
|
||||
className="search-input"
|
||||
value={searchInput}
|
||||
|
|
@ -654,10 +722,11 @@ export function FindingsPage() {
|
|||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.findings.map((f) => (
|
||||
{data.findings.map((f, i) => (
|
||||
<tr
|
||||
key={f.index}
|
||||
className={`clickable${selected.has(f.index) ? ' selected' : ''}`}
|
||||
className={`clickable${selected.has(f.index) ? ' selected' : ''}${i === cursor ? ' cursor' : ''}`}
|
||||
aria-current={i === cursor ? 'true' : undefined}
|
||||
onClick={(e) => handleRowClick(e, f)}
|
||||
>
|
||||
<td className="col-checkbox">
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useNavigate } from 'react-router-dom';
|
||||
import { useOverview, useOverviewTrends } from '../api/queries/overview';
|
||||
import { usePinBaseline, useUnpinBaseline } from '../api/mutations/baseline';
|
||||
import { StatCard } from '../components/ui/StatCard';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
|
|
@ -7,12 +8,28 @@ import { HorizontalBarChart } from '../components/charts/HorizontalBarChart';
|
|||
import { LineChart } from '../components/charts/LineChart';
|
||||
import { OverviewIcon } from '../components/icons/Icons';
|
||||
import { truncPath } from '../utils/truncPath';
|
||||
import {
|
||||
HealthScoreCard,
|
||||
BacklogCard,
|
||||
ConfidenceDistributionChart,
|
||||
ScannerQualityPanel,
|
||||
HotSinksList,
|
||||
OwaspChart,
|
||||
WeightedTopFiles,
|
||||
LanguageHealthTable,
|
||||
SuppressionHygieneCard,
|
||||
BaselinePinControl,
|
||||
} from '../components/overview/OverviewWidgets';
|
||||
import type { OverviewCount, ScanSummary, Insight } from '../api/types';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
|
||||
export function OverviewPage() {
|
||||
usePageTitle('Overview');
|
||||
const navigate = useNavigate();
|
||||
const { data: overview, isLoading, error } = useOverview();
|
||||
const { data: overview, isLoading, error, refetch } = useOverview();
|
||||
const { data: trends } = useOverviewTrends();
|
||||
const pinBaseline = usePinBaseline();
|
||||
const unpinBaseline = useUnpinBaseline();
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingState message="Loading overview..." />;
|
||||
|
|
@ -22,7 +39,8 @@ export function OverviewPage() {
|
|||
return (
|
||||
<ErrorState
|
||||
title="Error loading overview"
|
||||
message={(error as Error).message}
|
||||
error={error}
|
||||
onRetry={() => refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -37,41 +55,43 @@ export function OverviewPage() {
|
|||
<div className="overview-empty">
|
||||
<OverviewIcon size={48} />
|
||||
<h2>Welcome to Nyx</h2>
|
||||
<p>Start your first scan to see security findings and analytics.</p>
|
||||
<p>Run your first scan to see security findings and analytics.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Data preparation
|
||||
const netDelta = overview.new_since_last - overview.fixed_since_last;
|
||||
|
||||
const sevItems = (['HIGH', 'MEDIUM', 'LOW'] as const).map((s) => ({
|
||||
label: s.charAt(0) + s.slice(1).toLowerCase(),
|
||||
value: overview.by_severity[s] || 0,
|
||||
color: s === 'HIGH' ? '#e74c3c' : s === 'MEDIUM' ? '#e67e22' : '#3498db',
|
||||
}));
|
||||
|
||||
const catItems = Object.entries(overview.by_category || {})
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
const categoryItems = (overview.issue_categories || [])
|
||||
.slice(0, 8)
|
||||
.map(([k, v]) => ({ label: k, value: v, color: '#5856d6' }));
|
||||
|
||||
const langItems = Object.entries(overview.by_language || {})
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 8)
|
||||
.map(([k, v]) => ({ label: k, value: v, color: '#5856d6' }));
|
||||
.map((b) => ({ label: b.label, value: b.count, color: '#5856d6' }));
|
||||
|
||||
const trendData = (trends || []).map((t) => ({
|
||||
label: t.timestamp,
|
||||
value: t.total,
|
||||
}));
|
||||
|
||||
const hotSinks = overview.hot_sinks || [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="page-header">
|
||||
<h2>Overview</h2>
|
||||
</div>
|
||||
|
||||
{/* Baseline strip */}
|
||||
<BaselinePinControl
|
||||
baseline={overview.baseline}
|
||||
latestScanId={overview.latest_scan_id}
|
||||
onPin={(id) => pinBaseline.mutate(id)}
|
||||
onUnpin={() => unpinBaseline.mutate()}
|
||||
isPending={pinBaseline.isPending || unpinBaseline.isPending}
|
||||
/>
|
||||
|
||||
{overview.health && (
|
||||
<HealthScoreCard health={overview.health} posture={overview.posture} />
|
||||
)}
|
||||
|
||||
{/* Fresh banner */}
|
||||
{overview.state === 'fresh' && (
|
||||
<div className="overview-fresh-banner">
|
||||
|
|
@ -97,8 +117,9 @@ export function OverviewPage() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{/* Stat cards */}
|
||||
<div className="overview-stat-grid">
|
||||
{/* Stat cards — kept lean: 5 cards, severity stacks live in Top Files
|
||||
and Per-Language. Cross-file / Symex moved into Scanner Quality. */}
|
||||
<div className="overview-stat-grid overview-stat-grid-5">
|
||||
<StatCard
|
||||
label="Total Findings"
|
||||
value={overview.total_findings}
|
||||
|
|
@ -122,50 +143,77 @@ export function OverviewPage() {
|
|||
label="Triage Coverage"
|
||||
value={`${(overview.triage_coverage * 100).toFixed(0)}%`}
|
||||
/>
|
||||
<StatCard
|
||||
label="Scan Duration"
|
||||
value={
|
||||
overview.latest_scan_duration_secs != null
|
||||
? `${overview.latest_scan_duration_secs.toFixed(1)}s`
|
||||
: '-'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Charts */}
|
||||
<div className="overview-chart-grid">
|
||||
<div className="card">
|
||||
<div className="card-header">Findings Over Time</div>
|
||||
<LineChart points={trendData} />
|
||||
{trendData.length >= 2 ? (
|
||||
<LineChart points={trendData} />
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>Run a second scan to see trends.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">By Severity</div>
|
||||
<HorizontalBarChart items={sevItems} />
|
||||
<div className="card-header">OWASP Top 10 (2021)</div>
|
||||
{overview.owasp_buckets && overview.owasp_buckets.length > 0 ? (
|
||||
<OwaspChart buckets={overview.owasp_buckets} />
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>No OWASP-mapped findings.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">By Category</div>
|
||||
<HorizontalBarChart items={catItems} />
|
||||
<div className="card-header">Confidence Distribution</div>
|
||||
{overview.confidence_distribution ? (
|
||||
<ConfidenceDistributionChart
|
||||
dist={overview.confidence_distribution}
|
||||
/>
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>No data</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">By Language</div>
|
||||
<HorizontalBarChart items={langItems} />
|
||||
<div className="card-header">Issue Categories</div>
|
||||
<HorizontalBarChart items={categoryItems} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tables */}
|
||||
{/* Per-language + Top Files */}
|
||||
<div className="overview-table-grid">
|
||||
<div className="card">
|
||||
<div className="card-header">Top Affected Files</div>
|
||||
<CompactTable
|
||||
items={overview.top_files}
|
||||
nameLabel="File"
|
||||
countLabel="Findings"
|
||||
truncate
|
||||
onRowClick={(item) =>
|
||||
navigate(`/findings?search=${encodeURIComponent(item.name)}`)
|
||||
<div className="card-header">Per-Language Posture</div>
|
||||
<LanguageHealthTable rows={overview.language_health || []} />
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
Top Affected Files (severity-weighted)
|
||||
</div>
|
||||
<WeightedTopFiles
|
||||
files={overview.weighted_top_files || []}
|
||||
onRowClick={(name) =>
|
||||
navigate(`/findings?search=${encodeURIComponent(name)}`)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top Rules + Top Directories (or Hot Sinks when taint findings exist) */}
|
||||
<div className="overview-table-grid">
|
||||
<div className="card">
|
||||
<div className="card-header">Top Rules Triggered</div>
|
||||
<CompactTable
|
||||
items={overview.top_rules}
|
||||
nameLabel="Rule"
|
||||
countLabel="Findings"
|
||||
/>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">Top Directories</div>
|
||||
<CompactTable
|
||||
|
|
@ -175,36 +223,72 @@ export function OverviewPage() {
|
|||
truncate
|
||||
/>
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">Top Rules Triggered</div>
|
||||
<CompactTable
|
||||
items={overview.top_rules}
|
||||
nameLabel="Rule"
|
||||
countLabel="Findings"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hotSinks.length > 0 && (
|
||||
<div className="overview-table-grid">
|
||||
<div className="card card-full">
|
||||
<div className="card-header">Hot Sinks (taint flow)</div>
|
||||
<HotSinksList sinks={hotSinks} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{overview.backlog && <BacklogCard backlog={overview.backlog} />}
|
||||
|
||||
{/* Scanner Quality + Hygiene */}
|
||||
<div className="overview-table-grid">
|
||||
<div className="card">
|
||||
<div className="card-header">Scanner Quality</div>
|
||||
{overview.scanner_quality ? (
|
||||
<ScannerQualityPanel
|
||||
quality={overview.scanner_quality}
|
||||
crossFileRatio={overview.cross_file_ratio}
|
||||
/>
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>No engine metrics available</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card">
|
||||
<div className="card-header">Suppression Hygiene</div>
|
||||
{overview.suppression_hygiene ? (
|
||||
<SuppressionHygieneCard hygiene={overview.suppression_hygiene} />
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>No suppressions</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent scans */}
|
||||
<div className="overview-table-grid">
|
||||
<div className="card">
|
||||
<div className="card-header">Recent Scans</div>
|
||||
<RecentScansTable
|
||||
scans={overview.recent_scans}
|
||||
currentBaselineId={overview.baseline?.scan_id}
|
||||
onRowClick={(scan) => navigate(`/scans/${scan.id}`)}
|
||||
onPinBaseline={(scanId) => pinBaseline.mutate(scanId)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Insights */}
|
||||
{overview.insights.length > 0 && (
|
||||
<div className="overview-insights">
|
||||
<div className="card">
|
||||
<div className="card-header">Insights</div>
|
||||
<div className="card">
|
||||
<div className="card-header">Insights</div>
|
||||
{overview.insights.length > 0 ? (
|
||||
<div className="insight-list">
|
||||
{overview.insights.map((insight, i) => (
|
||||
<InsightCard key={i} insight={insight} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
<p>Nothing to flag.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -264,10 +348,17 @@ function CompactTable({
|
|||
|
||||
interface RecentScansTableProps {
|
||||
scans: ScanSummary[];
|
||||
currentBaselineId?: string;
|
||||
onRowClick: (scan: ScanSummary) => void;
|
||||
onPinBaseline?: (scanId: string) => void;
|
||||
}
|
||||
|
||||
function RecentScansTable({ scans, onRowClick }: RecentScansTableProps) {
|
||||
function RecentScansTable({
|
||||
scans,
|
||||
currentBaselineId,
|
||||
onRowClick,
|
||||
onPinBaseline,
|
||||
}: RecentScansTableProps) {
|
||||
if (!scans || scans.length === 0) {
|
||||
return (
|
||||
<div className="empty-state" style={{ padding: 16 }}>
|
||||
|
|
@ -284,31 +375,50 @@ function RecentScansTable({ scans, onRowClick }: RecentScansTableProps) {
|
|||
<th>Duration</th>
|
||||
<th>Findings</th>
|
||||
<th>Time</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{scans.slice(0, 5).map((scan) => (
|
||||
<tr
|
||||
key={scan.id}
|
||||
className="clickable"
|
||||
onClick={() => onRowClick(scan)}
|
||||
>
|
||||
<td>
|
||||
<span className={`status-dot ${scan.status}`} /> {scan.status}
|
||||
</td>
|
||||
<td>
|
||||
{scan.duration_secs != null
|
||||
? `${scan.duration_secs.toFixed(1)}s`
|
||||
: '-'}
|
||||
</td>
|
||||
<td>{scan.finding_count ?? '-'}</td>
|
||||
<td>
|
||||
{scan.started_at
|
||||
? new Date(scan.started_at).toLocaleString()
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{scans.slice(0, 5).map((scan) => {
|
||||
const isBaseline = scan.id === currentBaselineId;
|
||||
const canPin =
|
||||
!isBaseline && onPinBaseline && scan.status === 'completed';
|
||||
return (
|
||||
<tr
|
||||
key={scan.id}
|
||||
className="clickable"
|
||||
onClick={() => onRowClick(scan)}
|
||||
>
|
||||
<td>
|
||||
<span className={`status-dot ${scan.status}`} /> {scan.status}
|
||||
</td>
|
||||
<td>
|
||||
{scan.duration_secs != null
|
||||
? `${scan.duration_secs.toFixed(1)}s`
|
||||
: '-'}
|
||||
</td>
|
||||
<td>{scan.finding_count ?? '-'}</td>
|
||||
<td>
|
||||
{scan.started_at
|
||||
? new Date(scan.started_at).toLocaleString()
|
||||
: '-'}
|
||||
</td>
|
||||
<td onClick={(e) => e.stopPropagation()}>
|
||||
{isBaseline ? (
|
||||
<span className="baseline-label">baseline</span>
|
||||
) : canPin ? (
|
||||
<button
|
||||
type="button"
|
||||
className="baseline-action"
|
||||
onClick={() => onPinBaseline!(scan.id)}
|
||||
>
|
||||
Pin
|
||||
</button>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { useRules } from '../api/queries/rules';
|
|||
import { useToggleRule, useCloneRule } from '../api/mutations/rules';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import type { RuleListItem } from '../api/types';
|
||||
|
||||
function useDebounce(value: string, delay: number): string {
|
||||
|
|
@ -200,6 +201,7 @@ function RulesTable({
|
|||
// ── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function RulesPage() {
|
||||
usePageTitle('Rules');
|
||||
const params = useParams<{ id?: string }>();
|
||||
const { data: rules, isLoading, error } = useRules();
|
||||
const toggleRule = useToggleRule();
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';
|
|||
import { useScanCompare } from '../api/queries/scans';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import type {
|
||||
CompareResponse,
|
||||
ComparedFinding,
|
||||
|
|
@ -275,14 +276,24 @@ function CompareByGroup({
|
|||
type CompareTab = 'status' | 'rule' | 'file';
|
||||
|
||||
export function ScanComparePage() {
|
||||
usePageTitle('Compare scans');
|
||||
const { left, right } = useParams<{ left: string; right: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { data, isLoading, error } = useScanCompare(left || '', right || '');
|
||||
const { data, isLoading, error, refetch } = useScanCompare(
|
||||
left || '',
|
||||
right || '',
|
||||
);
|
||||
const [activeTab, setActiveTab] = useState<CompareTab>('status');
|
||||
|
||||
if (isLoading) return <LoadingState message="Loading comparison..." />;
|
||||
if (error)
|
||||
return <ErrorState title="Comparison failed" message={error.message} />;
|
||||
return (
|
||||
<ErrorState
|
||||
title="Comparison failed"
|
||||
error={error}
|
||||
onRetry={() => refetch()}
|
||||
/>
|
||||
);
|
||||
if (!data) return <ErrorState message="No comparison data" />;
|
||||
|
||||
const severities = ['HIGH', 'MEDIUM', 'LOW'];
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
} from '../api/queries/scans';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import type { ScanView, ScanLogEntry, ScanMetricsSnapshot } from '../api/types';
|
||||
|
||||
function truncPath(p?: string, max = 50): string {
|
||||
|
|
@ -384,6 +385,7 @@ export function ScanDetailPage() {
|
|||
const { data: scan, isLoading, error } = useScan(id || '');
|
||||
const { data: allScans } = useScans();
|
||||
const [activeTab, setActiveTab] = useState<TabId>('summary');
|
||||
usePageTitle(scan ? `Scan ${scan.id.slice(0, 8)}` : 'Scan');
|
||||
|
||||
const prevScanId = useMemo(() => {
|
||||
if (!scan || scan.status !== 'completed' || !allScans) return null;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { useDeleteScan } from '../api/mutations/scans';
|
|||
import { useSSE } from '../contexts/SSEContext';
|
||||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import type { ScanView } from '../api/types';
|
||||
|
||||
function relTime(iso?: string): string {
|
||||
|
|
@ -123,6 +124,7 @@ function ScanProgress({
|
|||
}
|
||||
|
||||
export function ScansPage() {
|
||||
usePageTitle('Scans');
|
||||
const navigate = useNavigate();
|
||||
const { data: scans, isLoading, error } = useScans();
|
||||
const deleteScan = useDeleteScan();
|
||||
|
|
|
|||
|
|
@ -1,56 +0,0 @@
|
|||
import { useLocation } from 'react-router-dom';
|
||||
import { ICONS } from '../components/icons/Icons';
|
||||
|
||||
const STUB_DESCRIPTIONS: Record<string, string> = {
|
||||
'/explorer':
|
||||
'Browse the scanned codebase, view file trees, and inspect individual files with inline annotations.',
|
||||
'/debug':
|
||||
'Inspect internal analysis state — control flow graphs, SSA IR, call graphs, and taint propagation.',
|
||||
'/debug/cfg':
|
||||
'Visualize control flow graphs for individual functions with block-level detail.',
|
||||
'/debug/ssa':
|
||||
'Inspect SSA intermediate representation including phi nodes, value numbering, and taint state.',
|
||||
'/debug/call-graph':
|
||||
'Explore the inter-procedural call graph with SCC highlighting and topo-order visualization.',
|
||||
'/debug/taint':
|
||||
'Step through taint propagation with per-instruction state snapshots and path tracking.',
|
||||
'/settings': 'Application settings and preferences.',
|
||||
};
|
||||
|
||||
const ROUTE_LABELS: Record<string, string> = {
|
||||
'/explorer': 'Explorer',
|
||||
'/debug': 'Debug',
|
||||
'/debug/cfg': 'CFG Viewer',
|
||||
'/debug/ssa': 'SSA Viewer',
|
||||
'/debug/call-graph': 'Call Graph',
|
||||
'/debug/taint': 'Taint Debugger',
|
||||
'/settings': 'Settings',
|
||||
};
|
||||
|
||||
function sectionFromPath(pathname: string): string {
|
||||
if (pathname === '/') return 'overview';
|
||||
const first = pathname.split('/')[1];
|
||||
return first || 'overview';
|
||||
}
|
||||
|
||||
export function StubPage() {
|
||||
const { pathname } = useLocation();
|
||||
const label = ROUTE_LABELS[pathname] ?? sectionFromPath(pathname);
|
||||
const description =
|
||||
STUB_DESCRIPTIONS[pathname] ?? 'This page is under construction.';
|
||||
const section = sectionFromPath(pathname);
|
||||
const IconComponent = ICONS[section];
|
||||
|
||||
return (
|
||||
<div className="stub-page">
|
||||
{IconComponent && (
|
||||
<div className="stub-icon">
|
||||
<IconComponent size={48} />
|
||||
</div>
|
||||
)}
|
||||
<h2 className="stub-title">{label}</h2>
|
||||
<p className="stub-description">{description}</p>
|
||||
<span className="stub-badge">Coming Soon</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
import { LoadingState } from '../components/ui/LoadingState';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { Dropdown, DropdownItem } from '../components/ui/Dropdown';
|
||||
import { usePageTitle } from '../hooks/usePageTitle';
|
||||
import type { FindingView, AuditEntry, SuppressionRule } from '../api/types';
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
|
@ -917,6 +918,7 @@ function AuditLogTab({ entries }: { entries: AuditEntry[] }) {
|
|||
type TriageTab = 'findings' | 'rules' | 'audit';
|
||||
|
||||
export function TriagePage() {
|
||||
usePageTitle('Triage');
|
||||
const [triageFilter, setTriageFilter] = useState('needs_attention');
|
||||
const [activeTab, setActiveTab] = useState<TriageTab>('findings');
|
||||
const [selectedRules, setSelectedRules] = useState<Set<string>>(new Set());
|
||||
|
|
|
|||
309
frontend/src/pages/debug/AuthAnalysisPage.tsx
Normal file
309
frontend/src/pages/debug/AuthAnalysisPage.tsx
Normal file
|
|
@ -0,0 +1,309 @@
|
|||
import { useDebugAuth } from '../../api/queries/debug';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { EmptyState } from '../../components/ui/EmptyState';
|
||||
import { ErrorState } from '../../components/ui/ErrorState';
|
||||
import { LoadingState } from '../../components/ui/LoadingState';
|
||||
import type {
|
||||
AuthAnalysisView,
|
||||
AuthCheckView,
|
||||
AuthOperationView,
|
||||
AuthRouteView,
|
||||
AuthUnitView,
|
||||
AuthValueRefView,
|
||||
} from '../../api/types';
|
||||
|
||||
interface AuthAnalysisPanelProps {
|
||||
file: string;
|
||||
}
|
||||
|
||||
export function AuthAnalysisPanel({ file }: AuthAnalysisPanelProps) {
|
||||
const { data, isLoading, error } = useDebugAuth(file);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingState message="Running authorization extraction..." />;
|
||||
}
|
||||
if (error) {
|
||||
if (error instanceof ApiError && error.status === 400) {
|
||||
return (
|
||||
<EmptyState message="Auth analysis only runs on supported source files. Try a .ts / .py / .rb / .rs / .go / .java / .php file." />
|
||||
);
|
||||
}
|
||||
return <ErrorState message="Failed to run authorization extraction." />;
|
||||
}
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!data.enabled) {
|
||||
return (
|
||||
<EmptyState message="Authorization analysis is disabled for this file's language. Toggle scanner.auth_analysis.enable in your nyx.toml to opt in." />
|
||||
);
|
||||
}
|
||||
|
||||
if (data.routes.length === 0 && data.units.length === 0) {
|
||||
return (
|
||||
<EmptyState message="No routes or analysis units were extracted from this file. Auth analysis fires on framework route handlers and helper functions whose body matches an authorization-check pattern." />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="abstract-interp-viewer">
|
||||
<AuthSummaryHeader data={data} />
|
||||
{data.routes.length > 0 && <AuthRoutesBlock routes={data.routes} />}
|
||||
{data.units.length > 0 && <AuthUnitsBlock units={data.units} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthSummaryHeader({ data }: { data: AuthAnalysisView }) {
|
||||
const totalChecks = data.units.reduce(
|
||||
(acc, u) => acc + u.auth_checks.length,
|
||||
0,
|
||||
);
|
||||
const totalOps = data.units.reduce((acc, u) => acc + u.operations.length, 0);
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>Authorization Model</h3>
|
||||
<span className="text-secondary">
|
||||
{data.routes.length} route{data.routes.length === 1 ? '' : 's'} ·{' '}
|
||||
{data.units.length} unit{data.units.length === 1 ? '' : 's'} ·{' '}
|
||||
{totalChecks} auth check{totalChecks === 1 ? '' : 's'} · {totalOps}{' '}
|
||||
sensitive op{totalOps === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthRoutesBlock({ routes }: { routes: AuthRouteView[] }) {
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>Routes</h3>
|
||||
<span className="text-secondary">
|
||||
{routes.length} registration{routes.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Method</th>
|
||||
<th>Path</th>
|
||||
<th>Framework</th>
|
||||
<th>Middleware</th>
|
||||
<th>Handler Params</th>
|
||||
<th>Line</th>
|
||||
<th>Unit</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{routes.map((r, i) => (
|
||||
<tr key={`${r.method}-${r.path}-${i}`}>
|
||||
<td>
|
||||
<span className="cap-badge cap-badge-source">{r.method}</span>
|
||||
</td>
|
||||
<td className="mono">{r.path}</td>
|
||||
<td>{r.framework}</td>
|
||||
<td className="mono">
|
||||
{r.middleware.length > 0 ? r.middleware.join(', ') : '-'}
|
||||
</td>
|
||||
<td className="mono">
|
||||
{r.handler_params.length > 0
|
||||
? r.handler_params.join(', ')
|
||||
: '-'}
|
||||
</td>
|
||||
<td className="mono">L{r.line}</td>
|
||||
<td className="mono">#{r.unit_idx}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthUnitsBlock({ units }: { units: AuthUnitView[] }) {
|
||||
return (
|
||||
<>
|
||||
{units.map((u, i) => (
|
||||
<AuthUnitCard key={`${u.name ?? '<anon>'}-${i}`} unit={u} index={i} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthUnitCard({ unit, index }: { unit: AuthUnitView; index: number }) {
|
||||
const hasDetails =
|
||||
unit.params.length > 0 ||
|
||||
unit.self_actor_vars.length > 0 ||
|
||||
unit.typed_bounded_vars.length > 0 ||
|
||||
unit.authorized_sql_vars.length > 0 ||
|
||||
unit.const_bound_vars.length > 0;
|
||||
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>
|
||||
#{index} {unit.name ?? '<anonymous>'}
|
||||
<span className="text-secondary" style={{ marginLeft: 8 }}>
|
||||
{unit.kind} · L{unit.line}
|
||||
</span>
|
||||
</h3>
|
||||
<span className="text-secondary">
|
||||
{unit.auth_checks.length} check
|
||||
{unit.auth_checks.length === 1 ? '' : 's'} · {unit.operations.length}{' '}
|
||||
op
|
||||
{unit.operations.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
{hasDetails && (
|
||||
<div className="auth-detail-list">
|
||||
{unit.params.length > 0 && (
|
||||
<DetailRow label="Params" value={unit.params.join(', ')} />
|
||||
)}
|
||||
{unit.self_actor_vars.length > 0 && (
|
||||
<DetailRow
|
||||
label="Self-actor vars"
|
||||
value={unit.self_actor_vars.join(', ')}
|
||||
/>
|
||||
)}
|
||||
{unit.typed_bounded_vars.length > 0 && (
|
||||
<DetailRow
|
||||
label="Typed-bounded params"
|
||||
value={unit.typed_bounded_vars.join(', ')}
|
||||
/>
|
||||
)}
|
||||
{unit.authorized_sql_vars.length > 0 && (
|
||||
<DetailRow
|
||||
label="Authorized SQL vars"
|
||||
value={unit.authorized_sql_vars.join(', ')}
|
||||
/>
|
||||
)}
|
||||
{unit.const_bound_vars.length > 0 && (
|
||||
<DetailRow
|
||||
label="Const-bound vars"
|
||||
value={unit.const_bound_vars.join(', ')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{unit.auth_checks.length > 0 && (
|
||||
<AuthCheckTable checks={unit.auth_checks} />
|
||||
)}
|
||||
{unit.operations.length > 0 && (
|
||||
<OperationTable operations={unit.operations} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="auth-detail-row">
|
||||
<span className="auth-detail-label">{label}</span>
|
||||
<span className="auth-detail-value mono">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthCheckTable({ checks }: { checks: AuthCheckView[] }) {
|
||||
return (
|
||||
<div className="auth-subsection">
|
||||
<div className="auth-subsection-title">Auth Checks</div>
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kind</th>
|
||||
<th>Callee</th>
|
||||
<th>Subjects</th>
|
||||
<th>Line</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{checks.map((c, i) => (
|
||||
<tr key={`${c.callee}-${c.line}-${i}`}>
|
||||
<td>
|
||||
<span className="cap-badge cap-badge-source">{c.kind}</span>
|
||||
</td>
|
||||
<td className="mono">{c.callee}</td>
|
||||
<td>
|
||||
{c.subjects.length === 0 ? (
|
||||
'-'
|
||||
) : (
|
||||
<SubjectChips subjects={c.subjects} />
|
||||
)}
|
||||
</td>
|
||||
<td className="mono">L{c.line}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OperationTable({ operations }: { operations: AuthOperationView[] }) {
|
||||
return (
|
||||
<div className="auth-subsection">
|
||||
<div className="auth-subsection-title">Sensitive Operations</div>
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kind</th>
|
||||
<th>Sink Class</th>
|
||||
<th>Callee</th>
|
||||
<th>Subjects</th>
|
||||
<th>Line</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{operations.map((op, i) => (
|
||||
<tr key={`${op.callee}-${op.line}-${i}`}>
|
||||
<td>
|
||||
<span className="cap-badge cap-badge-sanitizer">{op.kind}</span>
|
||||
</td>
|
||||
<td>
|
||||
{op.sink_class ? (
|
||||
<span className="cap-badge cap-badge-sink">
|
||||
{op.sink_class}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</td>
|
||||
<td className="mono" title={op.text}>
|
||||
{op.callee}
|
||||
</td>
|
||||
<td>
|
||||
{op.subjects.length === 0 ? (
|
||||
'-'
|
||||
) : (
|
||||
<SubjectChips subjects={op.subjects} />
|
||||
)}
|
||||
</td>
|
||||
<td className="mono">L{op.line}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubjectChips({ subjects }: { subjects: AuthValueRefView[] }) {
|
||||
return (
|
||||
<div className="auth-subject-chips">
|
||||
{subjects.map((s, i) => (
|
||||
<span
|
||||
key={`${s.name}-${i}`}
|
||||
className="cap-badge"
|
||||
title={`${s.source_kind}${s.base ? ` (base: ${s.base})` : ''}`}
|
||||
>
|
||||
{s.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { useMemo, useState } from 'react';
|
||||
import { useDebugFunctions } from '../../api/queries/debug';
|
||||
import type { FunctionInfo } from '../../api/types';
|
||||
|
||||
|
|
@ -15,9 +16,24 @@ export function FunctionSelector({
|
|||
showFilePath = true,
|
||||
}: Props) {
|
||||
const { data: functions, isLoading } = useDebugFunctions(file || null);
|
||||
const [showClosures, setShowClosures] = useState(false);
|
||||
|
||||
const closureCount = useMemo(
|
||||
() => functions?.filter((fn) => fn.func_kind === 'closure').length ?? 0,
|
||||
[functions],
|
||||
);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
if (!functions) return functions;
|
||||
return showClosures
|
||||
? functions
|
||||
: functions.filter((fn) => fn.func_kind !== 'closure');
|
||||
}, [functions, showClosures]);
|
||||
|
||||
return (
|
||||
<div className="function-selector">
|
||||
<div
|
||||
className={`function-selector${showFilePath ? '' : ' function-selector-flat'}`}
|
||||
>
|
||||
{showFilePath && (
|
||||
<div className="function-selector-path">
|
||||
<span className="function-selector-path-label">File:</span>
|
||||
|
|
@ -31,19 +47,19 @@ export function FunctionSelector({
|
|||
<select
|
||||
value={selectedFunction ?? ''}
|
||||
onChange={(e) => onFunctionChange(e.target.value || null)}
|
||||
disabled={!functions || functions.length === 0}
|
||||
disabled={!visible || visible.length === 0}
|
||||
className="function-selector-select"
|
||||
>
|
||||
<option value="">
|
||||
{isLoading
|
||||
? 'Loading...'
|
||||
: !functions || functions.length === 0
|
||||
: !visible || visible.length === 0
|
||||
? 'No functions found'
|
||||
: 'Select function'}
|
||||
</option>
|
||||
{functions?.map((fn: FunctionInfo) => (
|
||||
{visible?.map((fn: FunctionInfo) => (
|
||||
<option key={fn.name} value={fn.name}>
|
||||
{fn.name}({fn.param_count} params) — L{fn.line}
|
||||
{formatFunctionLabel(fn)}
|
||||
{fn.source_caps.length > 0 &&
|
||||
` [src: ${fn.source_caps.join(',')}]`}
|
||||
{fn.sink_caps.length > 0 && ` [sink: ${fn.sink_caps.join(',')}]`}
|
||||
|
|
@ -51,6 +67,30 @@ export function FunctionSelector({
|
|||
))}
|
||||
</select>
|
||||
</div>
|
||||
{closureCount > 0 && (
|
||||
<label className="function-selector-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showClosures}
|
||||
onChange={(e) => setShowClosures(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
Show {closureCount} anonymous closure
|
||||
{closureCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatFunctionLabel(fn: FunctionInfo): string {
|
||||
const sig = `(${fn.param_count} params) — L${fn.line}`;
|
||||
if (fn.func_kind === 'closure' && fn.container) {
|
||||
return `${fn.name} [closure in ${fn.container}] ${sig}`;
|
||||
}
|
||||
if (fn.func_kind === 'closure') {
|
||||
return `${fn.name} [closure] ${sig}`;
|
||||
}
|
||||
return `${fn.name}${sig}`;
|
||||
}
|
||||
|
|
|
|||
200
frontend/src/pages/debug/PointerViewerPage.tsx
Normal file
200
frontend/src/pages/debug/PointerViewerPage.tsx
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import { useMemo } from 'react';
|
||||
import { useDebugPointer } from '../../api/queries/debug';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { EmptyState } from '../../components/ui/EmptyState';
|
||||
import { ErrorState } from '../../components/ui/ErrorState';
|
||||
import { LoadingState } from '../../components/ui/LoadingState';
|
||||
import type {
|
||||
PointerLocationView,
|
||||
PointerValueView,
|
||||
PointerFieldEntryView,
|
||||
} from '../../api/types';
|
||||
|
||||
interface PointerAnalysisPanelProps {
|
||||
file: string;
|
||||
functionName: string;
|
||||
}
|
||||
|
||||
export function PointerAnalysisPanel({
|
||||
file,
|
||||
functionName,
|
||||
}: PointerAnalysisPanelProps) {
|
||||
const { data, isLoading, error } = useDebugPointer(file, functionName);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingState message="Loading points-to facts..." />;
|
||||
}
|
||||
if (error) {
|
||||
if (error instanceof ApiError && error.status === 404) {
|
||||
return (
|
||||
<EmptyState message="Pointer analysis is not available for the selected function." />
|
||||
);
|
||||
}
|
||||
return <ErrorState message="Failed to load pointer analysis." />;
|
||||
}
|
||||
if (
|
||||
!data ||
|
||||
(data.values.length === 0 &&
|
||||
data.field_reads.length === 0 &&
|
||||
data.field_writes.length === 0)
|
||||
) {
|
||||
return (
|
||||
<EmptyState message="No points-to facts were derived for this function. Pointer analysis flags up parameters, allocation sites, and field projections; functions that only manipulate scalars will appear empty." />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="abstract-interp-viewer">
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>Per-Value Points-To</h3>
|
||||
<span className="text-secondary">
|
||||
{data.values.length} value
|
||||
{data.values.length === 1 ? '' : 's'} · {data.location_count}{' '}
|
||||
location
|
||||
{data.location_count === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
{data.values.length === 0 ? (
|
||||
<p className="abstract-empty">
|
||||
All SSA values point to nothing tracked.
|
||||
</p>
|
||||
) : (
|
||||
<PointerValueTable values={data.values} locations={data.locations} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.field_reads.length > 0 && (
|
||||
<FieldEntriesBlock
|
||||
title="Field Reads"
|
||||
entries={data.field_reads}
|
||||
emptyHint="(no parameter field reads recorded)"
|
||||
/>
|
||||
)}
|
||||
|
||||
{data.field_writes.length > 0 && (
|
||||
<FieldEntriesBlock
|
||||
title="Field Writes"
|
||||
entries={data.field_writes}
|
||||
emptyHint="(no parameter field writes recorded)"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PointerValueTable({
|
||||
values,
|
||||
locations,
|
||||
}: {
|
||||
values: PointerValueView[];
|
||||
locations: PointerLocationView[];
|
||||
}) {
|
||||
const locById = useMemo(() => {
|
||||
const map = new Map<number, PointerLocationView>();
|
||||
for (const loc of locations) map.set(loc.id, loc);
|
||||
return map;
|
||||
}, [locations]);
|
||||
|
||||
return (
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Value</th>
|
||||
<th>Name</th>
|
||||
<th>Points-To</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{values.map((v) => (
|
||||
<tr key={v.ssa_value}>
|
||||
<td className="mono">v{v.ssa_value}</td>
|
||||
<td className="mono">{v.var_name ?? '-'}</td>
|
||||
<td>
|
||||
{v.is_top ? (
|
||||
<span
|
||||
className="cap-badge cap-badge-sink"
|
||||
title="Over-approximation"
|
||||
>
|
||||
⊤ (top)
|
||||
</span>
|
||||
) : (
|
||||
v.points_to.map((id) => (
|
||||
<LocationChip key={id} loc={locById.get(id)} />
|
||||
))
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function LocationChip({ loc }: { loc?: PointerLocationView }) {
|
||||
if (!loc) {
|
||||
return (
|
||||
<span className="cap-badge" title="Unknown location id">
|
||||
?
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const className =
|
||||
loc.kind === 'Top'
|
||||
? 'cap-badge cap-badge-sink'
|
||||
: loc.kind === 'Field'
|
||||
? 'cap-badge cap-badge-sanitizer'
|
||||
: 'cap-badge cap-badge-source';
|
||||
return (
|
||||
<span
|
||||
className={className}
|
||||
title={`${loc.kind} (loc#${loc.id})`}
|
||||
style={{ marginRight: 4 }}
|
||||
>
|
||||
{loc.display}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldEntriesBlock({
|
||||
title,
|
||||
entries,
|
||||
emptyHint,
|
||||
}: {
|
||||
title: string;
|
||||
entries: PointerFieldEntryView[];
|
||||
emptyHint: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>{title}</h3>
|
||||
<span className="text-secondary">
|
||||
{entries.length} entr{entries.length === 1 ? 'y' : 'ies'}
|
||||
</span>
|
||||
</div>
|
||||
{entries.length === 0 ? (
|
||||
<p className="abstract-empty">{emptyHint}</p>
|
||||
) : (
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Target</th>
|
||||
<th>Field</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((e, i) => (
|
||||
<tr key={`${e.param_index ?? 'self'}-${e.field}-${i}`}>
|
||||
<td className="mono">
|
||||
{e.param_index === null ? 'self' : `param[${e.param_index}]`}
|
||||
</td>
|
||||
<td className="mono">{e.field}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useDebugSummaries } from '../../api/queries/debug';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { EmptyState } from '../../components/ui/EmptyState';
|
||||
|
|
@ -22,6 +22,17 @@ export function SummaryAnalysisPanel({
|
|||
scope === 'global' ? null : (functionName ?? null),
|
||||
);
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const [showClosures, setShowClosures] = useState(false);
|
||||
|
||||
const closureCount = useMemo(
|
||||
() => data?.filter((s) => s.func_kind === 'closure').length ?? 0,
|
||||
[data],
|
||||
);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
if (!data) return data;
|
||||
return showClosures ? data : data.filter((s) => s.func_kind !== 'closure');
|
||||
}, [data, showClosures]);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingState message="Loading summaries..." />;
|
||||
|
|
@ -48,15 +59,32 @@ export function SummaryAnalysisPanel({
|
|||
);
|
||||
}
|
||||
|
||||
const visibleCount = visible?.length ?? 0;
|
||||
const totalCount = data.length;
|
||||
|
||||
return (
|
||||
<div className="summary-explorer">
|
||||
<div className="summary-header">
|
||||
<span className="text-secondary">
|
||||
{data.length}{' '}
|
||||
{visibleCount}
|
||||
{visibleCount !== totalCount && ` of ${totalCount}`}{' '}
|
||||
{scope === 'global'
|
||||
? 'functions across the project'
|
||||
: 'functions in this file'}
|
||||
</span>
|
||||
{closureCount > 0 && (
|
||||
<label className="summary-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showClosures}
|
||||
onChange={(e) => setShowClosures(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
Show {closureCount} anonymous closure
|
||||
{closureCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<table className="summary-table">
|
||||
<thead>
|
||||
|
|
@ -71,20 +99,19 @@ export function SummaryAnalysisPanel({
|
|||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.map((s) => (
|
||||
<SummaryRow
|
||||
key={`${s.namespace}::${s.name}`}
|
||||
summary={s}
|
||||
isExpanded={expanded === `${s.namespace}::${s.name}`}
|
||||
onToggle={() =>
|
||||
setExpanded(
|
||||
expanded === `${s.namespace}::${s.name}`
|
||||
? null
|
||||
: `${s.namespace}::${s.name}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{visible?.map((s) => {
|
||||
const rowKey = `${s.namespace}::${s.container}::${s.name}`;
|
||||
return (
|
||||
<SummaryRow
|
||||
key={rowKey}
|
||||
summary={s}
|
||||
isExpanded={expanded === rowKey}
|
||||
onToggle={() =>
|
||||
setExpanded(expanded === rowKey ? null : rowKey)
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
|
@ -104,10 +131,23 @@ function SummaryRow({
|
|||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const isClosure = summary.func_kind === 'closure';
|
||||
return (
|
||||
<>
|
||||
<tr onClick={onToggle} style={{ cursor: 'pointer' }}>
|
||||
<td className="mono">{summary.name}</td>
|
||||
<td className="mono">
|
||||
{summary.name}
|
||||
{isClosure && (
|
||||
<span
|
||||
className="text-secondary"
|
||||
style={{ marginLeft: 8, fontSize: '0.85em' }}
|
||||
>
|
||||
{summary.container
|
||||
? `[closure in ${summary.container}]`
|
||||
: '[closure]'}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>{summary.lang}</td>
|
||||
<td>{summary.param_count}</td>
|
||||
<td>
|
||||
|
|
|
|||
202
frontend/src/pages/debug/TypeFactsPage.tsx
Normal file
202
frontend/src/pages/debug/TypeFactsPage.tsx
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
import { useDebugTypeFacts } from '../../api/queries/debug';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { EmptyState } from '../../components/ui/EmptyState';
|
||||
import { ErrorState } from '../../components/ui/ErrorState';
|
||||
import { LoadingState } from '../../components/ui/LoadingState';
|
||||
import type { TypeFactDetailView, DtoFactView } from '../../api/types';
|
||||
|
||||
interface TypeFactsAnalysisPanelProps {
|
||||
file: string;
|
||||
functionName: string;
|
||||
}
|
||||
|
||||
const SECURITY_TYPES = new Set([
|
||||
'HttpClient',
|
||||
'HttpResponse',
|
||||
'DatabaseConnection',
|
||||
'FileHandle',
|
||||
'Url',
|
||||
'LocalCollection',
|
||||
]);
|
||||
|
||||
export function TypeFactsAnalysisPanel({
|
||||
file,
|
||||
functionName,
|
||||
}: TypeFactsAnalysisPanelProps) {
|
||||
const { data, isLoading, error } = useDebugTypeFacts(file, functionName);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingState message="Loading type facts..." />;
|
||||
}
|
||||
if (error) {
|
||||
if (error instanceof ApiError && error.status === 404) {
|
||||
return (
|
||||
<EmptyState message="Type facts are not available for the selected function." />
|
||||
);
|
||||
}
|
||||
return <ErrorState message="Failed to load type facts." />;
|
||||
}
|
||||
if (!data || data.facts.length === 0) {
|
||||
return (
|
||||
<EmptyState message="No type facts were inferred for this function. Type analysis fires when constructors, framework extractors, or constant literals reveal a value's type." />
|
||||
);
|
||||
}
|
||||
|
||||
const securityFacts = data.facts.filter((f) => SECURITY_TYPES.has(f.kind));
|
||||
const dtoFacts = data.facts.filter((f) => f.kind === 'Dto');
|
||||
const scalarFacts = data.facts.filter(
|
||||
(f) => !SECURITY_TYPES.has(f.kind) && f.kind !== 'Dto',
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="abstract-interp-viewer">
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>Inferred Types</h3>
|
||||
<span className="text-secondary">
|
||||
{data.facts.length} of {data.total_values} SSA values typed ·{' '}
|
||||
{data.unknown_count} unknown
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{securityFacts.length > 0 && (
|
||||
<TypeFactGroup
|
||||
title="Security-Relevant Types"
|
||||
subtitle="HttpClient, DatabaseConnection, Url, … — drive type-qualified callee resolution and sink suppression"
|
||||
facts={securityFacts}
|
||||
highlight
|
||||
/>
|
||||
)}
|
||||
|
||||
{dtoFacts.length > 0 && (
|
||||
<DtoFactGroup
|
||||
title="DTO Types"
|
||||
subtitle="Framework-injected DTO bodies with known field shapes (Phase 6)"
|
||||
facts={dtoFacts}
|
||||
/>
|
||||
)}
|
||||
|
||||
{scalarFacts.length > 0 && (
|
||||
<TypeFactGroup
|
||||
title="Scalar Types"
|
||||
subtitle="String / Int / Bool / Object / Array / Null inferences"
|
||||
facts={scalarFacts}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TypeFactGroup({
|
||||
title,
|
||||
subtitle,
|
||||
facts,
|
||||
highlight,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
facts: TypeFactDetailView[];
|
||||
highlight?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>{title}</h3>
|
||||
<span className="text-secondary">
|
||||
{facts.length} value{facts.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
{subtitle && <p className="abstract-subtitle">{subtitle}</p>}
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Value</th>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Container</th>
|
||||
<th>Nullable</th>
|
||||
<th>Line</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{facts.map((f) => (
|
||||
<tr key={f.ssa_value}>
|
||||
<td className="mono">v{f.ssa_value}</td>
|
||||
<td className="mono">{f.var_name ?? '-'}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`cap-badge ${
|
||||
highlight ? 'cap-badge-sink' : 'cap-badge-source'
|
||||
}`}
|
||||
>
|
||||
{f.kind}
|
||||
</span>
|
||||
</td>
|
||||
<td className="mono">{f.container ?? '-'}</td>
|
||||
<td>{f.nullable ? 'Yes' : 'No'}</td>
|
||||
<td className="mono">{f.line > 0 ? `L${f.line}` : '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DtoFactGroup({
|
||||
title,
|
||||
subtitle,
|
||||
facts,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
facts: TypeFactDetailView[];
|
||||
}) {
|
||||
return (
|
||||
<div className="abstract-block">
|
||||
<div className="abstract-block-header">
|
||||
<h3 style={{ margin: 0 }}>{title}</h3>
|
||||
<span className="text-secondary">
|
||||
{facts.length} DTO{facts.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
{subtitle && <p className="abstract-subtitle">{subtitle}</p>}
|
||||
{facts.map((f) => (
|
||||
<div key={f.ssa_value} style={{ padding: '8px 12px' }}>
|
||||
<div className="debug-detail-row">
|
||||
<span className="debug-detail-label">DTO</span>
|
||||
<span className="debug-detail-value mono">
|
||||
v{f.ssa_value} {f.var_name ? `(${f.var_name}) ` : ''}:{' '}
|
||||
{f.dto?.class_name ?? '?'}
|
||||
</span>
|
||||
</div>
|
||||
{f.dto && f.dto.fields.length > 0 && <DtoFieldTable dto={f.dto} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DtoFieldTable({ dto }: { dto: DtoFactView }) {
|
||||
return (
|
||||
<table className="abstract-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Kind</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{dto.fields.map((f) => (
|
||||
<tr key={f.name}>
|
||||
<td className="mono">{f.name}</td>
|
||||
<td>
|
||||
<span className="cap-badge cap-badge-source">{f.kind}</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue