import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import { getAdminSCEPIntuneStats, reloadAdminSCEPIntuneTrust, getAuditEvents } from '../api/client'; import PageHeader from '../components/PageHeader'; import ErrorState from '../components/ErrorState'; import { useAuth } from '../components/AuthProvider'; import { useTrackedMutation } from '../hooks/useTrackedMutation'; import { formatDateTime } from '../api/utils'; import type { IntuneStatsSnapshot, IntuneTrustAnchorInfo, AuditEvent } from '../api/types'; // SCEP RFC 8894 + Intune master bundle Phase 9.4: per-profile Intune // Monitoring tab. // // Surfaces: // - Status banner per profile (trust anchor expiry countdown, rotates // when < 30 days; the soonest-to-expire anchor wins). // - Live counters table per profile (success / signature_invalid / // claim_mismatch / expired / wrong_audience / replay / rate_limited / // malformed / compliance_failed / not_yet_valid / unknown_version). // Polled every 30s via TanStack Query. // - Recent failures table (last 50) populated from the audit log // filtered to action=scep_pkcsreq_intune (and the renewal sibling). // - Trust anchor reload button (per-profile) with confirmation modal; // calls POST /api/v1/admin/scep/intune/reload-trust under the hood // (the SIGHUP-equivalent path). // // Admin-gated: the page itself renders an "Admin access required" banner // for non-admin callers and never issues the underlying admin requests. // Server-side enforcement is the M-008 admin gate; this is a UX hint. const COUNTER_LABEL_ORDER = [ 'success', 'signature_invalid', 'expired', 'not_yet_valid', 'wrong_audience', 'replay', 'rate_limited', 'claim_mismatch', 'compliance_failed', 'malformed', 'unknown_version', ] as const; const COUNTER_PRESENTATION: Record = { success: { label: 'Success', tone: 'good' }, signature_invalid: { label: 'Signature invalid', tone: 'bad' }, expired: { label: 'Expired', tone: 'warn' }, not_yet_valid: { label: 'Not yet valid', tone: 'warn' }, wrong_audience: { label: 'Wrong audience', tone: 'bad' }, replay: { label: 'Replay', tone: 'bad' }, rate_limited: { label: 'Rate-limited', tone: 'warn' }, claim_mismatch: { label: 'Claim mismatch', tone: 'bad' }, compliance_failed: { label: 'Compliance failed', tone: 'warn' }, malformed: { label: 'Malformed', tone: 'bad' }, unknown_version: { label: 'Unknown version', tone: 'warn' }, }; const TONE_CLASS: Record<'good' | 'warn' | 'bad', string> = { good: 'text-emerald-600', warn: 'text-amber-600', bad: 'text-red-600', }; // soonestExpiryDays returns the smallest days_to_expiry across the // profile's trust anchor pool. Returns null when the pool is empty (the // per-profile preflight should have refused this state at boot, but // defensive in case the holder is reloaded mid-flight to an empty file). function soonestExpiryDays(anchors?: IntuneTrustAnchorInfo[]): number | null { if (!anchors || anchors.length === 0) return null; let min = Number.POSITIVE_INFINITY; for (const a of anchors) { if (a.expired) return -1; // any expired wins if (a.days_to_expiry < min) min = a.days_to_expiry; } return min === Number.POSITIVE_INFINITY ? null : min; } function expiryBadge(days: number | null): { text: string; tone: 'good' | 'warn' | 'bad' } { if (days === null) return { text: 'No trust anchors', tone: 'warn' }; if (days < 0) return { text: 'EXPIRED', tone: 'bad' }; if (days < 7) return { text: `${days}d remaining`, tone: 'bad' }; if (days < 30) return { text: `${days}d remaining (rotate soon)`, tone: 'warn' }; return { text: `${days}d remaining`, tone: 'good' }; } interface ConfirmReloadModalProps { profile: IntuneStatsSnapshot; onCancel: () => void; onConfirm: () => void; pending: boolean; errorMessage?: string; } function ConfirmReloadModal({ profile, onCancel, onConfirm, pending, errorMessage }: ConfirmReloadModalProps) { const pathLabel = profile.path_id || '(legacy /scep root)'; return (

Reload Intune trust anchor

This re-reads {profile.trust_anchor_path} from disk and atomically swaps the trust pool for SCEP profile {pathLabel}. Equivalent to sending SIGHUP to the server. If the new file fails to parse, the previous trust pool stays in place — enrollments keep working off the old trust anchor while you fix the file.

{errorMessage && (
{errorMessage}
)}
); } interface ProfileCardProps { profile: IntuneStatsSnapshot; onRequestReload: (profile: IntuneStatsSnapshot) => void; } function ProfileCard({ profile, onRequestReload }: ProfileCardProps) { const pathLabel = profile.path_id || '(legacy /scep root)'; if (!profile.enabled) { return (

{pathLabel}

Issuer: {profile.issuer_id}

Intune disabled

This profile honors only the static challenge password. To enable Intune dispatch, set CERTCTL_SCEP_PROFILE_{(profile.path_id || 'DEFAULT').toUpperCase()}_INTUNE_ENABLED=true plus the matching trust-anchor path env var, then restart the server.

); } const days = soonestExpiryDays(profile.trust_anchors); const badge = expiryBadge(days); return (

{pathLabel}

Issuer: {profile.issuer_id} {profile.audience && <> · Audience: {profile.audience}}

Trust anchor: {badge.text}
{COUNTER_LABEL_ORDER.map(label => { const value = profile.counters?.[label] ?? 0; const presentation = COUNTER_PRESENTATION[label]; return (
{value}
{presentation.label}
); })}
Replay cache size
{profile.replay_cache_size}
Per-device rate limit
{profile.rate_limit_disabled ? 'Disabled' : 'Active'}
Trust anchors
{profile.trust_anchors?.length ?? 0}
{profile.trust_anchors && profile.trust_anchors.length > 0 && (
Trust anchor details {profile.trust_anchors.map(a => ( ))}
Subject Not after Days to expiry
{a.subject || '(empty CN)'} {formatDateTime(a.not_after)} {a.expired ? 'EXPIRED' : a.days_to_expiry}
)}
); } function RecentFailuresTable({ events }: { events: AuditEvent[] }) { if (events.length === 0) { return (

No recent Intune-dispatched enrollment events. Counters stay at zero until the first device hits a SCEP profile with Intune enabled.

); } return ( {events.map(e => ( ))}
Timestamp Action Resource Details
{formatDateTime(e.timestamp)} {e.action} {e.resource_type} · {e.resource_id} {e.details ? Object.entries(e.details).map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v) : String(v)}`).join(' · ') : '-'}
); } export default function SCEPAdminPage() { const auth = useAuth(); const [reloadTarget, setReloadTarget] = useState(null); const [reloadError, setReloadError] = useState(undefined); const statsQuery = useQuery({ queryKey: ['admin', 'scep', 'intune', 'stats'], queryFn: getAdminSCEPIntuneStats, enabled: !auth.authRequired || auth.admin, // skip the request entirely when non-admin refetchInterval: 30_000, }); // Audit-log filter: every Intune-dispatched enrollment (success + failure) // emits action=scep_pkcsreq_intune (initial) or scep_renewalreq_intune // (renewal). The audit endpoint accepts a single action filter; we fetch // both server-side via two queries and merge client-side rather than // adding a comma-separated filter that would require backend changes. const auditPKCSQuery = useQuery({ queryKey: ['audit', { action: 'scep_pkcsreq_intune' }], queryFn: () => getAuditEvents({ action: 'scep_pkcsreq_intune' }), enabled: !auth.authRequired || auth.admin, refetchInterval: 60_000, }); const auditRenewalQuery = useQuery({ queryKey: ['audit', { action: 'scep_renewalreq_intune' }], queryFn: () => getAuditEvents({ action: 'scep_renewalreq_intune' }), enabled: !auth.authRequired || auth.admin, refetchInterval: 60_000, }); // Bundle-8 / M-009 invalidation contract: trust-anchor reload changes // both the per-profile trust pool (reflected in IntuneStats) AND every // recently-failed Intune enrollment counter that might now succeed on // retry. We invalidate the stats key so the per-profile trust-anchor // panel reflects the new pool immediately; the audit log queries // remain on their 60s timer (a SIGHUP-equivalent reload doesn't // backfill new audit rows). const reloadMutation = useTrackedMutation< Awaited>, Error, string >({ mutationFn: (pathID: string) => reloadAdminSCEPIntuneTrust(pathID), invalidates: [['admin', 'scep', 'intune', 'stats']], onSuccess: () => { setReloadTarget(null); setReloadError(undefined); }, onError: (err: Error) => { setReloadError(err.message); }, }); if (auth.authRequired && !auth.admin) { return ( <>
); } if (statsQuery.isLoading) { return ( <>
Loading per-profile stats…
); } if (statsQuery.error) { return ( <>
statsQuery.refetch()} />
); } const profiles = statsQuery.data?.profiles ?? []; const events: AuditEvent[] = [ ...(auditPKCSQuery.data?.data ?? []), ...(auditRenewalQuery.data?.data ?? []), ] .sort((a, b) => b.timestamp.localeCompare(a.timestamp)) .slice(0, 50); return ( <> statsQuery.refetch()} className="text-xs px-3 py-1.5 rounded border border-surface-border bg-surface hover:bg-surface-alt" data-testid="refresh-stats-button" > Refresh now } />
{profiles.length === 0 && (
No SCEP profiles are configured. Set CERTCTL_SCEP_ENABLED=true and either the legacy single-profile env vars or CERTCTL_SCEP_PROFILES=... with the indexed per-profile family to register at least one endpoint.
)} {profiles.map(p => ( { setReloadError(undefined); setReloadTarget(profile); }} /> ))}

Recent Intune-dispatched enrollments (last 50)

Filtered to action=scep_pkcsreq_intune + action=scep_renewalreq_intune. Refreshes every 60s.

{auditPKCSQuery.isLoading || auditRenewalQuery.isLoading ? (

Loading audit log…

) : ( )}
{reloadTarget && ( { setReloadTarget(null); setReloadError(undefined); }} onConfirm={() => reloadMutation.mutate(reloadTarget.path_id)} pending={reloadMutation.isPending} errorMessage={reloadError} /> )} ); }