Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2146]): Privacy Center Brokers tab — exposure map, case board, run controls

Adam Eivy33646086bfc1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5232e2058a..38d04b40fd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -38,6 +38,7 @@
## Privacy Center
+- **[issue-2146] The Privacy Center now has a Brokers cockpit — see where you're exposed and drive removals from the UI.** Phase 7 of the Privacy Center (epic #2138) puts a front-end over the Phase 5 scan engine + case ledger and the Phase 6 opt-out automation. A new **Brokers** tab (`/privacy/brokers`, `⌘K`/voice-navigable under Identity) opens on an **exposure map** — stat chips counting your cases per state (found, in-progress, submitted, verifying, awaiting, removed, blocked, human tasks), plus how many brokers are enabled, how many cases are due for re-check, and the next scheduled run. A **case board** lists every case (state badge, broker, cluster-child badge, listing count, next re-check date), filterable by state, and each case opens a detail drawer (deep-linked via `?case=<id>`) with its evidence (listing URLs, match basis, confirmation screenshot), disclosed fields, the broker's opt-out playbook, and manual controls: force re-check, mark submitted, dismiss, open the opt-out page. **Run controls** start a scan or an opt-out pass on demand with a live spinner — and both buttons disable while either pass is in flight so you can't kick off overlapping runs. A **human-task digest** panel surfaces every case that needs you (blocked walls, phone/fax/gov-ID channels) with per-item done/dismiss and a jump to the broker's opt-out page. The recheck **schedule** is a UI toggle that creates the cron on the spot and says when it'll next run (disabling removes it), alongside a cron-expression field and the auto-approve-emails autonomy toggle; a **broker database** section lists every broker with source/confidence/tier and a per-broker enable/disable switch and a user-triggered "Refresh broker list". The Overview tab gains a broker case-summary card. Mobile-usable at 360px. (`client/src/pages/Privacy.jsx`, `client/src/components/privacy/{PrivacyBrokersTab,BrokerCaseDrawer,PrivacyOverviewTab}.jsx`, `client/src/components/privacy/constants.js`, `client/src/services/apiPrivacy.js`, `server/routes/privacy.js`, `server/services/{privacyBrokers,privacyRecheckScheduler}.js`, `server/lib/privacyValidation.js`, `server/lib/navManifest.js`)
- **[issue-2145] The Privacy Center can now work your data-broker removals for you.** Phase 6 of the Privacy Center (epic #2138) adds the opt-out automation engine on top of the Phase 5 broker scan + case ledger. It drives each exposed case through removal on two lanes: an **email lane** that renders a CCPA/CPRA/GDPR/generic rights-request (recipient locked to the broker's own declared address) into the Comms drafts queue as an **unapproved** draft you review before it sends, and a **web-form lane** that — by default — prepares the request and surfaces it as a human task with the broker's playbook and exactly which identifiers to submit. A **verification loop** scans your synced inbox for the broker's confirmation email (anti-phishing gated: the link's domain must actually match the broker's) to advance a case, and a case can only reach "confirmed removed" when a fresh read-only re-scan proves your listing is gone — never from a confirmation page. Everything is opt-in and default-safe: auto-sending emails and auto-submitting forms are two separate settings toggles that both ship **off**, the engine never emits anything outside a fixed least-disclosure allowlist (`full_name, email, phone, city, state, dob, listing_url`) intersected with what each broker asks for (your SSN/passport/financial data can never reach a broker), and a CAPTCHA or bot-wall is recorded as **blocked** and never bypassed. A **human-task digest** collects every case that needs you (blocked walls, phone/fax/gov-ID channels, forms awaiting manual submit) with the prepared request attached. Nothing runs on startup; passes run only when you trigger one (`POST /api/privacy/optout`) or turn on the user-configured recheck schedule (Settings → Privacy, off by default). (`server/services/privacyOptOut.js`, `server/services/privacyRecheckScheduler.js`, `server/services/privacyScan.js`, `server/routes/privacy.js`, `server/lib/privacyValidation.js`, `data.reference/privacy/email-templates/`, `server/index.js`)
- **[issue-2147] The Privacy Center org drawer now cross-links to your Digital Twin social accounts — from both sides.** Completing Phase 8 (epic #2138): the create/edit organization drawer gains a **Linked social account (Digital Twin)** picker that lets you point any org at one of your twin's social accounts. It pairs with the twin's existing "Add to org registry" / "in org registry" badge so the link is visible and editable from either surface, and a stale link to a since-deleted account is preserved rather than silently dropped. (`client/src/components/privacy/OrgDrawer.jsx`)
- **[issue-2142] A new Privacy Center UI puts your encrypted PII vault and the organizations that hold it in one place.** Building on the Phase 1 encrypted vault (#2140) and Phase 2 trusted-organizations registry (#2141), a deep-linkable `/privacy/:tab` page (Identity → Privacy, `⌘K`/voice-navigable) ships three tabs: **Overview** — a doctor-style readout of whether AES-256-GCM encryption is engaged, vault record counts by type, and org counts by trust stance, with quick-jump cards into the other tabs; **Vault** — records grouped by type showing only the precomputed masked value (`•••, Portland OR` / `a•••@example.com`), with per-record "Share with Twin" / "Use for scans" optimistic toggles (hard-disabled for sensitive SSN/passport/license/financial types), a create/edit `Drawer`, and an explicit per-record **Reveal** action that decrypts plaintext only on click (never cached in list state) — plaintext never renders until you ask for it; **Organizations** — a trust/category/status chip-filtered list with per-org holdings status badges and a create/edit drawer whose holdings picker checkboxes over your vault records (masked) to record which fields each org holds. All mutations update local state directly (no full-list refetch), deletes use an inline confirm row (no `window.confirm`), and every tab is usable at 360px. Each tab path is registered in the nav manifest (`nav.identity.privacy-*`). (`client/src/pages/Privacy.jsx`, `client/src/components/privacy/`, `client/src/services/apiPrivacy.js`, `server/lib/navManifest.js`)
diff --git a/client/src/components/privacy/BrokerCaseDrawer.jsx b/client/src/components/privacy/BrokerCaseDrawer.jsx
new file mode 100644
index 0000000000..82a9db0dde
--- /dev/null
+++ b/client/src/components/privacy/BrokerCaseDrawer.jsx
@@ -0,0 +1,155 @@
+import { RotateCw, ExternalLink, CheckCircle2, XCircle, ListChecks } from 'lucide-react';
+import Drawer from '../Drawer';
+import { timeAgo, formatDateShort } from '../../utils/formatters';
+import { CASE_STATE_TONE, labelFor, CASE_STATES } from './constants';
+
+// Read-only case inspector + manual controls (issue #2146). Deep-linked open
+// state is owned by the parent (a `?case=<id>` search param), so this component
+// is a pure controlled view. The backend does not persist a full state-history
+// log, so "history" here is the timeline we DO have: created → last-updated →
+// next-recheck, plus the current reason/channel/disclosure/evidence.
+export default function BrokerCaseDrawer({
+ open, onClose, caseData, broker, onRecheck, onTransition, busy = false,
+}) {
+ // Stale/deleted deep link — the case is gone but the URL still points at it.
+ const notFound = open && !caseData;
+
+ const evidence = caseData?.evidence || {};
+ const listingUrls = Array.isArray(evidence.listing_urls) ? evidence.listing_urls : [];
+ const playbook = Array.isArray(broker?.optout?.playbook) ? broker.optout.playbook : [];
+ const optoutUrl = broker?.optout?.url || evidence.optout_url || null;
+
+ // Which manual transitions make sense from the current state.
+ const state = caseData?.state;
+ const canMarkDone = state === 'human_task_queued' || state === 'blocked';
+ const canDismiss = state === 'human_task_queued' || state === 'blocked' || state === 'found' || state === 'indirect_exposure';
+
+ const Row = ({ label, children }) => (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">{label}</span>
+ <div className="text-sm text-gray-200 break-words">{children}</div>
+ </div>
+ );
+
+ return (
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="Broker case"
+ subtitle={caseData?.brokerName || broker?.name}
+ size="md"
+ >
+ {notFound ? (
+ <div className="text-center text-sm text-gray-500 py-10">
+ This case no longer exists. It may have been re-scanned or removed.
+ </div>
+ ) : caseData ? (
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={`text-xs px-2 py-0.5 rounded border ${CASE_STATE_TONE[state] || ''}`}>
+ {labelFor(CASE_STATES, state)}
+ </span>
+ {broker?.tier !== undefined && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">Tier {broker.tier}</span>
+ )}
+ {broker?.clusterParent && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-accent/30 text-port-accent">
+ child of {broker.clusterParent}
+ </span>
+ )}
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <Row label="First seen">{caseData.createdAt ? formatDateShort(caseData.createdAt) : '—'}</Row>
+ <Row label="Last updated">{caseData.updatedAt ? timeAgo(caseData.updatedAt) : '—'}</Row>
+ <Row label="Next re-check">{caseData.nextRecheckAt ? formatDateShort(caseData.nextRecheckAt) : '—'}</Row>
+ <Row label="Channel">{caseData.channel || '—'}</Row>
+ </div>
+
+ {caseData.reason && <Row label="Reason">{caseData.reason}</Row>}
+
+ <Row label="Disclosed fields">
+ {(caseData.disclosedFields || []).length
+ ? (caseData.disclosedFields || []).map((f) => (
+ <span key={f} className="inline-block text-[10px] px-1.5 py-0.5 mr-1 mb-1 rounded border border-port-border text-gray-400">{f}</span>
+ ))
+ : <span className="text-gray-500">None disclosed</span>}
+ </Row>
+
+ <Row label="Evidence">
+ {evidence.match_basis && (
+ <div className="text-xs text-gray-400 mb-1">Match basis: {evidence.match_basis}</div>
+ )}
+ {listingUrls.length ? (
+ <ul className="space-y-1">
+ {listingUrls.map((u) => (
+ <li key={u}>
+ <a href={u} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline break-all">
+ <ExternalLink size={12} /> {u}
+ </a>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <span className="text-gray-500 text-xs">No listing URLs recorded</span>
+ )}
+ {evidence.screenshot && (
+ <a href={evidence.screenshot} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline mt-1">
+ <ExternalLink size={12} /> Confirmation screenshot
+ </a>
+ )}
+ </Row>
+
+ {playbook.length > 0 && (
+ <div>
+ <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-gray-500 mb-1">
+ <ListChecks size={13} /> Broker opt-out playbook
+ </div>
+ <ol className="list-decimal list-inside space-y-1 text-xs text-gray-300">
+ {playbook.map((step, i) => <li key={i}>{step}</li>)}
+ </ol>
+ </div>
+ )}
+
+ <div className="flex flex-wrap gap-2 pt-2 border-t border-port-border">
+ <button
+ onClick={() => onRecheck?.(caseData)}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-card disabled:opacity-50"
+ >
+ <RotateCw size={14} /> Force re-check
+ </button>
+ {canMarkDone && (
+ <button
+ onClick={() => onTransition?.(caseData, 'submitted')}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded border border-port-success/40 text-port-success hover:bg-port-success/10 disabled:opacity-50"
+ >
+ <CheckCircle2 size={14} /> Mark submitted
+ </button>
+ )}
+ {canDismiss && (
+ <button
+ onClick={() => onTransition?.(caseData, 'not_found')}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded border border-port-border text-gray-400 hover:text-white hover:bg-port-card disabled:opacity-50"
+ >
+ <XCircle size={14} /> Dismiss (not found)
+ </button>
+ )}
+ {optoutUrl && (
+ <a
+ href={optoutUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-card"
+ >
+ <ExternalLink size={14} /> Open opt-out page
+ </a>
+ )}
+ </div>
+ </div>
+ ) : null}
+ </Drawer>
+ );
+}
diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsx
new file mode 100644
index 0000000000..8e66b0cbc3
--- /dev/null
+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx
@@ -0,0 +1,401 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import {
+ Search, ShieldOff, RefreshCw, CalendarClock, AlertTriangle,
+ CheckCircle2, XCircle, ExternalLink, Loader2, Database, ChevronDown, ChevronRight,
+} from 'lucide-react';
+import {
+ getPrivacyScanStatus, getPrivacyBrokerCases, getPrivacyBrokers, getPrivacyOptOutDigest,
+ getPrivacyOptOutSchedule, updatePrivacyOptOutSchedule, runPrivacyScan, runPrivacyOptOut,
+ refreshPrivacyBrokers, recheckPrivacyCase, transitionPrivacyCase, setPrivacyBrokerEnabled,
+} from '../../services/api';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import toast from '../ui/Toast';
+import { timeAgo, formatDateShort } from '../../utils/formatters';
+import BrokerCaseDrawer from './BrokerCaseDrawer';
+import {
+ CASE_STATES, CASE_STATE_TONE, EXPOSURE_MAP_STATES, BROKER_SOURCES, BROKER_CONFIDENCE, labelFor,
+} from './constants';
+
+// Stat chip for the exposure-map header.
+function StatChip({ label, count, tone }) {
+ return (
+ <div className={`flex items-center gap-2 px-3 py-2 rounded-lg border ${tone || 'border-port-border'}`}>
+ <span className="text-lg font-bold leading-none">{count}</span>
+ <span className="text-[11px] uppercase tracking-wide opacity-80">{label}</span>
+ </div>
+ );
+}
+
+export default function PrivacyBrokersTab() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const openCaseId = searchParams.get('case');
+
+ const [scanStatus, setScanStatus] = useState(null);
+ const [cases, setCases] = useState([]);
+ const [brokers, setBrokers] = useState([]);
+ const [digest, setDigest] = useState({ total: 0, humanTasks: 0, blocked: 0, items: [] });
+ const [schedule, setSchedule] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [stateFilter, setStateFilter] = useState('');
+ const [cronDraft, setCronDraft] = useState('');
+ const [brokerListOpen, setBrokerListOpen] = useState(false);
+
+ const load = useCallback(() => {
+ setLoading(true);
+ Promise.allSettled([
+ getPrivacyScanStatus(), getPrivacyBrokerCases(), getPrivacyBrokers(),
+ getPrivacyOptOutDigest(), getPrivacyOptOutSchedule(),
+ ]).then(([s, c, b, d, sch]) => {
+ setScanStatus(s.status === 'fulfilled' ? s.value : { enabledBrokers: 0, caseCounts: {}, dueForRecheck: 0 });
+ setCases(c.status === 'fulfilled' ? c.value : []);
+ setBrokers(b.status === 'fulfilled' ? b.value : []);
+ setDigest(d.status === 'fulfilled' ? d.value : { total: 0, humanTasks: 0, blocked: 0, items: [] });
+ const schVal = sch.status === 'fulfilled' ? sch.value : null;
+ setSchedule(schVal);
+ if (schVal) setCronDraft(schVal.cronExpression || '');
+ setLoading(false);
+ });
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const brokerById = useMemo(() => new Map(brokers.map((b) => [b.id, b])), [brokers]);
+ const caseCounts = scanStatus?.caseCounts || {};
+ const lastActivity = useMemo(() => {
+ const times = cases.map((c) => c.updatedAt).filter(Boolean).sort();
+ return times.length ? times[times.length - 1] : null;
+ }, [cases]);
+
+ const visibleCases = stateFilter ? cases.filter((c) => c.state === stateFilter) : cases;
+ const openCase = openCaseId ? cases.find((c) => c.id === openCaseId) : null;
+
+ // ── Run controls (synchronous passes — gate both while either runs) ─────────
+ const [scanNow, scanRunning] = useAsyncAction(async () => {
+ const r = await runPrivacyScan({ silent: true });
+ load();
+ const verdicts = Object.entries(r?.verdicts || {}).map(([k, v]) => `${v} ${labelFor(CASE_STATES, k).toLowerCase()}`).join(', ');
+ toast.success(r?.reason === 'no_scan_vectors'
+ ? 'Add a name to the vault (scan-eligible) to run a scan'
+ : `Scan complete: ${r?.scanned || 0} verdicts${verdicts ? ` (${verdicts})` : ''}`);
+ return r;
+ }, { errorMessage: 'Scan failed' });
+
+ const [optOutNow, optOutRunning] = useAsyncAction(async () => {
+ const r = await runPrivacyOptOut({ silent: true });
+ load();
+ toast.success(r?.reason === 'no_disclosure_identity'
+ ? 'Add a scan-eligible name to the vault to run an opt-out pass'
+ : `Opt-out pass: ${r?.submitted?.length || 0} actioned, ${r?.skipped || 0} skipped`);
+ return r;
+ }, { errorMessage: 'Opt-out pass failed' });
+
+ const [refreshList, refreshing] = useAsyncAction(async () => {
+ const r = await refreshPrivacyBrokers({ silent: true });
+ load();
+ toast.success(`Broker list refreshed: ${r?.added || 0} new (${r?.fetched || 0} fetched)`);
+ return r;
+ }, { errorMessage: 'Broker refresh failed' });
+
+ const passRunning = scanRunning || optOutRunning;
+
+ // ── Schedule / autonomy toggles (persist immediately, restart the cron) ─────
+ const [saveSchedule, scheduleSaving] = useAsyncAction(async (patch) => {
+ const next = await updatePrivacyOptOutSchedule(patch, { silent: true });
+ setSchedule(next);
+ if (next?.cronExpression) setCronDraft(next.cronExpression);
+ return next;
+ }, { errorMessage: 'Failed to update schedule' });
+
+ const toggleEnabled = async () => {
+ const next = await saveSchedule({ enabled: !schedule.enabled });
+ if (next) toast.success(next.enabled ? `Recheck scheduled (${next.cronExpression})` : 'Recheck schedule disabled');
+ };
+ const toggleAutoApprove = async () => {
+ const next = await saveSchedule({ autoApproveOptOutEmails: !schedule.autoApproveOptOutEmails });
+ if (next) toast.success(next.autoApproveOptOutEmails ? 'Auto-approve opt-out emails ON' : 'Auto-approve opt-out emails OFF');
+ };
+ const saveCron = async () => {
+ const next = await saveSchedule({ cronExpression: cronDraft.trim() });
+ if (next) toast.success(`Schedule set to "${next.cronExpression}"`);
+ };
+ const cronDirty = schedule && cronDraft.trim() !== (schedule.cronExpression || '');
+
+ // ── Case controls ───────────────────────────────────────────────────────────
+ const [caseBusy, setCaseBusy] = useState(false);
+ const doRecheck = async (kase) => {
+ setCaseBusy(true);
+ const r = await recheckPrivacyCase(kase.id, { silent: true }).catch(() => null);
+ setCaseBusy(false);
+ if (r) { toast.success('Case queued for re-check'); load(); }
+ else toast.error('Failed to queue re-check');
+ };
+ const doTransition = async (kase, toState) => {
+ setCaseBusy(true);
+ const r = await transitionPrivacyCase(kase.id, toState, undefined, { silent: true }).catch(() => null);
+ setCaseBusy(false);
+ if (r) { toast.success(`Case → ${labelFor(CASE_STATES, toState)}`); load(); }
+ else toast.error('Transition not allowed');
+ };
+
+ const openDrawer = (id) => { searchParams.set('case', id); setSearchParams(searchParams, { replace: false }); };
+ const closeDrawer = () => { searchParams.delete('case'); setSearchParams(searchParams, { replace: false }); };
+
+ // ── Broker enable/disable ─────────────────────────────────────────────────
+ const toggleBroker = async (broker) => {
+ const updated = await setPrivacyBrokerEnabled(broker.id, !broker.enabled, { silent: true }).catch(() => null);
+ if (updated) setBrokers((prev) => prev.map((b) => (b.id === broker.id ? updated : b)));
+ else toast.error('Failed to toggle broker');
+ };
+
+ if (loading) return <div className="text-gray-500 text-sm py-8 text-center">Loading broker exposure…</div>;
+
+ return (
+ <div className="space-y-6">
+ {/* ── Exposure map header ── */}
+ <section>
+ <div className="flex flex-wrap items-center justify-between gap-2 mb-3">
+ <h2 className="text-sm font-semibold text-white">Exposure map</h2>
+ <div className="flex flex-wrap items-center gap-3 text-xs text-gray-500">
+ <span>{scanStatus?.enabledBrokers || 0} brokers enabled</span>
+ <span>{scanStatus?.dueForRecheck || 0} due for re-check</span>
+ {lastActivity && <span>Last activity {timeAgo(lastActivity)}</span>}
+ {schedule?.enabled && schedule.nextRun && (
+ <span className="inline-flex items-center gap-1"><CalendarClock size={12} /> Next run {formatDateShort(schedule.nextRun)}</span>
+ )}
+ </div>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
+ {EXPOSURE_MAP_STATES.map((st) => (
+ <StatChip key={st} label={labelFor(CASE_STATES, st)} count={caseCounts[st] || 0} tone={CASE_STATE_TONE[st]} />
+ ))}
+ </div>
+ </section>
+
+ {/* ── Run controls ── */}
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
+ <h2 className="text-sm font-semibold text-white">Run controls</h2>
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => scanNow()}
+ disabled={passRunning}
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {scanRunning ? <Loader2 size={16} className="animate-spin" /> : <Search size={16} />}
+ {scanRunning ? 'Scanning…' : 'Scan now'}
+ </button>
+ <button
+ onClick={() => optOutNow()}
+ disabled={passRunning}
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded border border-port-border text-gray-200 hover:text-white hover:bg-port-border/40 disabled:opacity-50"
+ >
+ {optOutRunning ? <Loader2 size={16} className="animate-spin" /> : <ShieldOff size={16} />}
+ {optOutRunning ? 'Running…' : 'Run opt-out pass'}
+ </button>
+ </div>
+
+ {/* Schedule + autonomy */}
+ {schedule && (
+ <div className="space-y-3 border-t border-port-border pt-3">
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ id="privacy-recheck-enabled"
+ type="checkbox"
+ checked={schedule.enabled}
+ onChange={toggleEnabled}
+ disabled={scheduleSaving}
+ className="accent-port-accent"
+ />
+ <span className="text-sm text-gray-200">Automatic recheck schedule</span>
+ {schedule.enabled && (
+ <span className="text-[11px] text-gray-500">runs a scan + opt-out pass on the cron below</span>
+ )}
+ </label>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor="privacy-recheck-cron" className="text-[11px] uppercase tracking-wide text-gray-500">Cron</label>
+ <input
+ id="privacy-recheck-cron"
+ type="text"
+ value={cronDraft}
+ onChange={(e) => setCronDraft(e.target.value)}
+ placeholder="0 4 * * 0"
+ className="px-2 py-1 text-sm rounded bg-port-bg border border-port-border text-gray-200 font-mono w-36"
+ />
+ <button
+ onClick={saveCron}
+ disabled={!cronDirty || scheduleSaving}
+ className="px-2.5 py-1 text-xs rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-border/40 disabled:opacity-40"
+ >
+ Save cron
+ </button>
+ <span className="text-[11px] text-gray-600">min hour dom month dow</span>
+ </div>
+
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ id="privacy-auto-approve"
+ type="checkbox"
+ checked={schedule.autoApproveOptOutEmails}
+ onChange={toggleAutoApprove}
+ disabled={scheduleSaving}
+ className="accent-port-accent"
+ />
+ <span className="text-sm text-gray-200">Auto-approve opt-out emails</span>
+ <span className="text-[11px] text-gray-500">standing authorization — off means each draft waits for approval in Comms</span>
+ </label>
+ </div>
+ )}
+ </section>
+
+ {/* ── Human-task digest ── */}
+ {digest.total > 0 && (
+ <section className="bg-port-warning/5 border border-port-warning/30 rounded-lg p-4 space-y-3">
+ <div className="flex items-center gap-2">
+ <AlertTriangle size={16} className="text-port-warning" />
+ <h2 className="text-sm font-semibold text-white">Human tasks ({digest.total})</h2>
+ <span className="text-[11px] text-gray-500">{digest.humanTasks} manual · {digest.blocked} blocked</span>
+ </div>
+ <div className="space-y-2">
+ {digest.items.map((item) => (
+ <div key={item.caseId} className="flex flex-wrap items-center justify-between gap-2 bg-port-card border border-port-border rounded p-2.5">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm text-white truncate">{item.brokerName || item.brokerId}</span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded border ${CASE_STATE_TONE[item.state] || ''}`}>
+ {labelFor(CASE_STATES, item.state)}
+ </span>
+ </div>
+ {item.reason && <div className="text-[11px] text-gray-500 mt-0.5">{item.reason}{item.channel ? ` · ${item.channel}` : ''}</div>}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ {item.optoutUrl && (
+ <a href={item.optoutUrl} target="_blank" rel="noreferrer" title="Open opt-out page" aria-label="Open opt-out page" className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50">
+ <ExternalLink size={15} />
+ </a>
+ )}
+ <button onClick={() => doTransition({ id: item.caseId }, 'submitted')} disabled={caseBusy} title="Mark done" aria-label="Mark done" className="p-1.5 rounded text-port-success hover:bg-port-success/10 disabled:opacity-50">
+ <CheckCircle2 size={15} />
+ </button>
+ <button onClick={() => doTransition({ id: item.caseId }, 'not_found')} disabled={caseBusy} title="Dismiss" aria-label="Dismiss" className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50">
+ <XCircle size={15} />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* ── Case board ── */}
+ <section className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h2 className="text-sm font-semibold text-white">Case board</h2>
+ <div className="flex items-center gap-2">
+ <label htmlFor="privacy-case-filter" className="text-[11px] uppercase tracking-wide text-gray-500">State</label>
+ <select
+ id="privacy-case-filter"
+ value={stateFilter}
+ onChange={(e) => setStateFilter(e.target.value)}
+ className="px-2 py-1 text-sm rounded bg-port-bg border border-port-border text-gray-200"
+ >
+ <option value="">All ({cases.length})</option>
+ {CASE_STATES.filter((s) => caseCounts[s.id]).map((s) => (
+ <option key={s.id} value={s.id}>{s.label} ({caseCounts[s.id]})</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {visibleCases.length === 0 ? (
+ <div className="border border-dashed border-port-border rounded-lg p-8 text-center text-gray-500 text-sm">
+ {cases.length === 0 ? 'No cases yet. Run a scan to check your exposure across data brokers.' : 'No cases match this filter.'}
+ </div>
+ ) : (
+ <div className="space-y-1.5">
+ {visibleCases.map((c) => {
+ const broker = brokerById.get(c.brokerId);
+ const listingCount = Array.isArray(c.evidence?.listing_urls) ? c.evidence.listing_urls.length : 0;
+ return (
+ <button
+ key={c.id}
+ onClick={() => openDrawer(c.id)}
+ className="w-full text-left bg-port-card border border-port-border rounded-lg p-3 hover:border-port-accent/50 transition-colors"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span className={`text-[10px] px-1.5 py-0.5 rounded border ${CASE_STATE_TONE[c.state] || ''}`}>
+ {labelFor(CASE_STATES, c.state)}
+ </span>
+ <span className="text-sm text-white truncate flex-1 min-w-0">{c.brokerName || c.brokerId}</span>
+ {broker?.clusterParent && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-accent/30 text-port-accent">cluster child</span>
+ )}
+ {c.brokerTier !== undefined && (
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-500">T{c.brokerTier}</span>
+ )}
+ {listingCount > 0 && (
+ <span className="text-[10px] text-gray-500">{listingCount} listing{listingCount > 1 ? 's' : ''}</span>
+ )}
+ {c.nextRecheckAt && (
+ <span className="text-[10px] text-gray-500">recheck {formatDateShort(c.nextRecheckAt)}</span>
+ )}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </section>
+
+ {/* ── Broker database ── */}
+ <section className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <button
+ onClick={() => setBrokerListOpen((o) => !o)}
+ className="inline-flex items-center gap-1.5 text-sm font-semibold text-white"
+ >
+ {brokerListOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <Database size={15} className="text-gray-500" /> Broker database ({brokers.length})
+ </button>
+ <button
+ onClick={() => refreshList()}
+ disabled={refreshing}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-border/40 disabled:opacity-50"
+ >
+ {refreshing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ Refresh broker list
+ </button>
+ </div>
+ {brokerListOpen && (
+ <div className="space-y-1.5">
+ {brokers.map((b) => (
+ <div key={b.id} className="flex flex-wrap items-center justify-between gap-2 bg-port-card border border-port-border rounded-lg p-2.5">
+ <div className="min-w-0 flex items-center gap-2 flex-wrap">
+ <span className="text-sm text-white truncate">{b.name}</span>
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-500">T{b.tier}</span>
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-500">{labelFor(BROKER_SOURCES, b.source)}</span>
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-500">{labelFor(BROKER_CONFIDENCE, b.confidence)}</span>
+ {b.clusterParent && <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-accent/30 text-port-accent">child of {b.clusterParent}</span>}
+ </div>
+ <label className="flex items-center gap-1.5 cursor-pointer select-none shrink-0">
+ <input type="checkbox" checked={b.enabled} onChange={() => toggleBroker(b)} className="accent-port-accent" aria-label={`Enable ${b.name}`} />
+ <span className="text-[11px] text-gray-400">{b.enabled ? 'Enabled' : 'Disabled'}</span>
+ </label>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
+ <BrokerCaseDrawer
+ open={!!openCaseId}
+ caseData={openCase}
+ broker={openCase ? brokerById.get(openCase.brokerId) : null}
+ onClose={closeDrawer}
+ onRecheck={doRecheck}
+ onTransition={doTransition}
+ busy={caseBusy}
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/privacy/PrivacyBrokersTab.test.jsx b/client/src/components/privacy/PrivacyBrokersTab.test.jsx
new file mode 100644
index 0000000000..366f8ea9f0
--- /dev/null
+++ b/client/src/components/privacy/PrivacyBrokersTab.test.jsx
@@ -0,0 +1,104 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+// Deferred promise helper for asserting in-flight (disable-while-running) gating.
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+};
+
+const api = vi.hoisted(() => ({
+ scanStatus: {
+ enabledBrokers: 2,
+ caseCounts: { found: 1, confirmed_removed: 1, human_task_queued: 1 },
+ dueForRecheck: 1,
+ },
+ cases: [
+ { id: 'c1', brokerId: 'spokeo', brokerName: 'Spokeo', brokerTier: 1, state: 'found', evidence: { listing_urls: ['http://x/1'] }, nextRecheckAt: '2026-08-01T00:00:00.000Z', updatedAt: '2026-07-01T00:00:00.000Z' },
+ { id: 'c2', brokerId: 'wp', brokerName: 'WhitePages', state: 'confirmed_removed', evidence: {}, updatedAt: '2026-07-02T00:00:00.000Z' },
+ ],
+ brokers: [{ id: 'spokeo', name: 'Spokeo', tier: 1, source: 'curated', confidence: 'documented', enabled: true, clusterParent: null, optout: {} }],
+ digest: { total: 1, humanTasks: 1, blocked: 0, items: [{ caseId: 'h1', brokerId: 'bv', brokerName: 'BeenVerified', state: 'human_task_queued', reason: 'human_only_channel' }] },
+ schedule: { enabled: false, cronExpression: '0 4 * * 0', autoApproveOptOutEmails: false, autoSubmitWebForms: false, nextRun: null },
+ runScanDeferred: null,
+}));
+
+vi.mock('../../services/api', () => ({
+ getPrivacyScanStatus: vi.fn(async () => api.scanStatus),
+ getPrivacyBrokerCases: vi.fn(async () => api.cases),
+ getPrivacyBrokers: vi.fn(async () => api.brokers),
+ getPrivacyOptOutDigest: vi.fn(async () => api.digest),
+ getPrivacyOptOutSchedule: vi.fn(async () => api.schedule),
+ updatePrivacyOptOutSchedule: vi.fn(async (patch) => ({ ...api.schedule, ...patch })),
+ runPrivacyScan: vi.fn(() => (api.runScanDeferred ? api.runScanDeferred.promise : Promise.resolve({ scanned: 1, verdicts: { found: 1 }, skipped: 0 }))),
+ runPrivacyOptOut: vi.fn(async () => ({ submitted: [], skipped: 0 })),
+ refreshPrivacyBrokers: vi.fn(async () => ({ added: 0, fetched: 0 })),
+ recheckPrivacyCase: vi.fn(async () => ({ id: 'c1' })),
+ transitionPrivacyCase: vi.fn(async (id, toState) => ({ id, state: toState })),
+ setPrivacyBrokerEnabled: vi.fn(async (id, enabled) => ({ id, name: 'Spokeo', enabled, tier: 1, source: 'curated', confidence: 'documented', clusterParent: null })),
+}));
+
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+import PrivacyBrokersTab from './PrivacyBrokersTab.jsx';
+import * as apiMod from '../../services/api';
+
+const renderTab = () => render(<MemoryRouter initialEntries={['/privacy/brokers']}><PrivacyBrokersTab /></MemoryRouter>);
+
+describe('PrivacyBrokersTab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.runScanDeferred = null;
+ });
+
+ it('renders the case board and filters by state', async () => {
+ renderTab();
+ // Both cases visible initially.
+ expect(await screen.findByText('Spokeo')).toBeTruthy();
+ expect(screen.getByText('WhitePages')).toBeTruthy();
+
+ // Filter to confirmed_removed — Spokeo (found) drops out.
+ fireEvent.change(screen.getByLabelText('State'), { target: { value: 'confirmed_removed' } });
+ await waitFor(() => expect(screen.queryByText('Spokeo')).toBeNull());
+ expect(screen.getByText('WhitePages')).toBeTruthy();
+ });
+
+ it('actions a human-task digest item (done → submitted)', async () => {
+ renderTab();
+ await screen.findByText('BeenVerified');
+ fireEvent.click(screen.getByLabelText('Mark done'));
+ await waitFor(() => expect(apiMod.transitionPrivacyCase).toHaveBeenCalledWith('h1', 'submitted', undefined, expect.anything()));
+ });
+
+ it('disables both run buttons while a pass is in flight', async () => {
+ api.runScanDeferred = deferred();
+ renderTab();
+ const scanBtn = await screen.findByRole('button', { name: /scan now/i });
+ const optOutBtn = screen.getByRole('button', { name: /run opt-out pass/i });
+ fireEvent.click(scanBtn);
+ await waitFor(() => expect(optOutBtn.disabled).toBe(true));
+ expect(scanBtn.disabled).toBe(true);
+ // Resolve the pass — buttons re-enable.
+ api.runScanDeferred.resolve({ scanned: 1, verdicts: { found: 1 }, skipped: 0 });
+ await waitFor(() => expect(optOutBtn.disabled).toBe(false));
+ });
+
+ it('enables the recheck schedule via the toggle', async () => {
+ renderTab();
+ const checkbox = await screen.findByLabelText(/Automatic recheck schedule/i);
+ expect(checkbox.checked).toBe(false);
+ fireEvent.click(checkbox);
+ await waitFor(() => expect(apiMod.updatePrivacyOptOutSchedule).toHaveBeenCalledWith({ enabled: true }, expect.anything()));
+ });
+
+ it('toggles a broker enabled flag from the database list', async () => {
+ renderTab();
+ // Expand the collapsed broker database section.
+ fireEvent.click(await screen.findByText(/Broker database/i));
+ const brokerToggle = await screen.findByLabelText('Enable Spokeo');
+ fireEvent.click(brokerToggle);
+ await waitFor(() => expect(apiMod.setPrivacyBrokerEnabled).toHaveBeenCalledWith('spokeo', false, expect.anything()));
+ });
+});
diff --git a/client/src/components/privacy/PrivacyOverviewTab.jsx b/client/src/components/privacy/PrivacyOverviewTab.jsx
index 9de42f658f..c91a999845 100644
--- a/client/src/components/privacy/PrivacyOverviewTab.jsx
+++ b/client/src/components/privacy/PrivacyOverviewTab.jsx
@@ -1,19 +1,26 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
-import { ShieldCheck, ShieldAlert, KeyRound, Building2, ArrowRight } from 'lucide-react';
-import { getPrivacyStatus, getPrivacyOrgs } from '../../services/api';
-import { VAULT_TYPES, ORG_TRUST_LEVELS, TRUST_TONE, labelFor } from './constants';
+import { ShieldCheck, ShieldAlert, KeyRound, Building2, ArrowRight, ShieldOff } from 'lucide-react';
+import { getPrivacyStatus, getPrivacyOrgs, getPrivacyScanStatus } from '../../services/api';
+import {
+ VAULT_TYPES, ORG_TRUST_LEVELS, TRUST_TONE, labelFor, CASE_STATES, CASE_STATE_TONE,
+} from './constants';
+
+// Broker case states surfaced on the Overview summary (#2146).
+const OVERVIEW_BROKER_STATES = ['found', 'optout_in_progress', 'human_task_queued', 'confirmed_removed'];
export default function PrivacyOverviewTab() {
const navigate = useNavigate();
const [status, setStatus] = useState(null);
const [orgs, setOrgs] = useState([]);
+ const [scanStatus, setScanStatus] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
- Promise.allSettled([getPrivacyStatus(), getPrivacyOrgs()]).then(([s, o]) => {
+ Promise.allSettled([getPrivacyStatus(), getPrivacyOrgs(), getPrivacyScanStatus()]).then(([s, o, b]) => {
setStatus(s.status === 'fulfilled' ? s.value : { keyConfigured: false, recordCounts: {} });
setOrgs(o.status === 'fulfilled' ? o.value : []);
+ setScanStatus(b.status === 'fulfilled' ? b.value : { caseCounts: {}, enabledBrokers: 0 });
setLoading(false);
});
}, []);
@@ -29,6 +36,9 @@ export default function PrivacyOverviewTab() {
count: orgs.filter((o) => o.trust === t.id).length,
}));
+ const caseCounts = scanStatus?.caseCounts || {};
+ const totalCases = Object.values(caseCounts).reduce((a, b) => a + b, 0);
+
return (
<div className="space-y-6">
<p className="text-sm text-gray-500 max-w-2xl">
@@ -100,6 +110,32 @@ export default function PrivacyOverviewTab() {
</button>
</div>
+ {/* Data-broker exposure summary (#2146) */}
+ <button
+ onClick={() => navigate('/privacy/brokers')}
+ className="w-full text-left bg-port-card border border-port-border rounded-lg p-5 hover:border-port-accent/50 transition-colors group"
+ >
+ <div className="flex items-center justify-between mb-3">
+ <span className="inline-flex items-center gap-1.5 text-sm font-semibold text-white">
+ <ShieldOff size={16} className="text-gray-500" /> Data brokers
+ </span>
+ <ArrowRight size={16} className="text-gray-600 group-hover:text-port-accent transition-colors" />
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {totalCases === 0 ? (
+ <span className="text-xs text-gray-500">
+ {scanStatus?.enabledBrokers || 0} brokers tracked — no scan run yet
+ </span>
+ ) : (
+ OVERVIEW_BROKER_STATES.filter((st) => caseCounts[st]).map((st) => (
+ <span key={st} className={`text-[10px] px-1.5 py-0.5 rounded border ${CASE_STATE_TONE[st] || ''}`}>
+ {caseCounts[st]} {labelFor(CASE_STATES, st).toLowerCase()}
+ </span>
+ ))
+ )}
+ </div>
+ </button>
+
<div className="flex flex-wrap gap-2">
<button onClick={() => navigate('/privacy/vault')} className="px-3 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80">
Manage vault
diff --git a/client/src/components/privacy/constants.js b/client/src/components/privacy/constants.js
index f0ccab0f48..22a93bbf3e 100644
--- a/client/src/components/privacy/constants.js
+++ b/client/src/components/privacy/constants.js
@@ -89,4 +89,56 @@ export const HOLDING_TONE = {
unknown: 'bg-gray-700/40 text-gray-400 border-gray-600/40',
};
+// ── Data-broker opt-out (issue #2146) ───────────────────────────────────────
+// Case states — mirrors CASE_STATES / PRIVACY_BROKER_CASE_STATES on the server.
+export const CASE_STATES = [
+ { id: 'unscanned', label: 'Unscanned' },
+ { id: 'found', label: 'Found' },
+ { id: 'not_found', label: 'Not found' },
+ { id: 'indirect_exposure', label: 'Indirect exposure' },
+ { id: 'blocked', label: 'Blocked' },
+ { id: 'optout_in_progress', label: 'In progress' },
+ { id: 'submitted', label: 'Submitted' },
+ { id: 'verification_pending', label: 'Verifying' },
+ { id: 'awaiting_processing', label: 'Awaiting' },
+ { id: 'confirmed_removed', label: 'Removed' },
+ { id: 'human_task_queued', label: 'Human task' },
+ { id: 'reappeared', label: 'Reappeared' },
+];
+
+// Pre-composed Tailwind tone tokens per case state (JIT needs whole class names).
+export const CASE_STATE_TONE = {
+ unscanned: 'bg-gray-700/40 text-gray-400 border-gray-600/40',
+ found: 'bg-port-error/15 text-port-error border-port-error/30',
+ not_found: 'bg-gray-700/40 text-gray-400 border-gray-600/40',
+ indirect_exposure: 'bg-port-warning/15 text-port-warning border-port-warning/30',
+ blocked: 'bg-port-error/15 text-port-error border-port-error/30',
+ optout_in_progress: 'bg-port-accent/15 text-port-accent border-port-accent/30',
+ submitted: 'bg-port-accent/15 text-port-accent border-port-accent/30',
+ verification_pending: 'bg-port-accent/15 text-port-accent border-port-accent/30',
+ awaiting_processing: 'bg-port-warning/15 text-port-warning border-port-warning/30',
+ confirmed_removed: 'bg-port-success/15 text-port-success border-port-success/30',
+ human_task_queued: 'bg-port-warning/15 text-port-warning border-port-warning/30',
+ reappeared: 'bg-port-error/15 text-port-error border-port-error/30',
+};
+
+// The exposure-map header chips, in display order (a curated subset + grouping).
+export const EXPOSURE_MAP_STATES = [
+ 'found', 'indirect_exposure', 'optout_in_progress', 'submitted',
+ 'verification_pending', 'awaiting_processing', 'confirmed_removed',
+ 'blocked', 'human_task_queued', 'not_found',
+];
+
+export const BROKER_SOURCES = [
+ { id: 'curated', label: 'Curated' },
+ { id: 'badbool', label: 'BADBOOL' },
+ { id: 'ca_registry', label: 'CA registry' },
+];
+
+export const BROKER_CONFIDENCE = [
+ { id: 'field_verified', label: 'Field-verified' },
+ { id: 'documented', label: 'Documented' },
+ { id: 'auto', label: 'Auto' },
+];
+
export const labelFor = (list, id) => list.find((x) => x.id === id)?.label ?? id;
diff --git a/client/src/pages/Privacy.jsx b/client/src/pages/Privacy.jsx
index efce44cc85..a128948a78 100644
--- a/client/src/pages/Privacy.jsx
+++ b/client/src/pages/Privacy.jsx
@@ -1,5 +1,5 @@
import { useNavigate } from 'react-router-dom';
-import { Shield, LayoutDashboard, KeyRound, Building2, Repeat } from 'lucide-react';
+import { Shield, LayoutDashboard, KeyRound, Building2, Repeat, ShieldOff } from 'lucide-react';
import { useValidTab } from '../hooks/useValidTab';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
@@ -7,6 +7,7 @@ import PrivacyOverviewTab from '../components/privacy/PrivacyOverviewTab';
import PrivacyVaultTab from '../components/privacy/PrivacyVaultTab';
import PrivacyOrgsTab from '../components/privacy/PrivacyOrgsTab';
import PrivacyChangesTab from '../components/privacy/PrivacyChangesTab';
+import PrivacyBrokersTab from '../components/privacy/PrivacyBrokersTab';
// Exported for the nav-manifest tab-coverage guard (server/lib/navManifest.test.js).
// Each id maps to `/privacy/<id>` and needs a NAV_COMMANDS entry.
@@ -15,6 +16,7 @@ export const TABS = [
{ id: 'vault', label: 'Vault', icon: KeyRound },
{ id: 'organizations', label: 'Organizations', icon: Building2 },
{ id: 'changes', label: 'Changes', icon: Repeat },
+ { id: 'brokers', label: 'Brokers', icon: ShieldOff },
];
export default function Privacy() {
@@ -26,6 +28,7 @@ export default function Privacy() {
case 'vault': return <PrivacyVaultTab />;
case 'organizations': return <PrivacyOrgsTab />;
case 'changes': return <PrivacyChangesTab />;
+ case 'brokers': return <PrivacyBrokersTab />;
case 'overview':
default: return <PrivacyOverviewTab />;
}
diff --git a/client/src/pages/Privacy.test.jsx b/client/src/pages/Privacy.test.jsx
index e9a407ad01..c381888061 100644
--- a/client/src/pages/Privacy.test.jsx
+++ b/client/src/pages/Privacy.test.jsx
@@ -25,6 +25,8 @@ vi.mock('../services/api', () => ({
getPrivacyOrgs: vi.fn().mockResolvedValue([
{ id: 'org-1', name: 'Acme Bank', category: 'bank', trust: 'trusted', status: 'active', website: '', contact: {} },
]),
+ // Broker case summary chips on the Overview tab (#2146).
+ getPrivacyScanStatus: vi.fn().mockResolvedValue({ enabledBrokers: 2, caseCounts: { found: 1 }, dueForRecheck: 0 }),
getPrivacyOrg: vi.fn(),
createPrivacyOrg: vi.fn(),
updatePrivacyOrg: vi.fn(),
diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.js
index 6718a2dcd8..c58760d129 100644
--- a/client/src/services/apiPrivacy.js
+++ b/client/src/services/apiPrivacy.js
@@ -82,6 +82,50 @@ export const markChangeOrgRemoved = (id, orgId, options) =>
export const draftChangeUpdateEmail = (id, orgId, options) =>
request(`/privacy/changes/${id}/orgs/${orgId}/draft-email`, { method: 'POST', ...options });
+// ── Data-broker database + case ledger + opt-out engine (#2144/#2145; UI #2146) ─
+/** Broker database rows. `enabled` filters to enabled-only when true/false. */
+export const getPrivacyBrokers = (enabled, options) =>
+ request(`/privacy/brokers${enabled === undefined ? '' : `?enabled=${enabled ? 'true' : 'false'}`}`, options);
+/** Toggle a broker on/off (skips it in scan + opt-out passes). */
+export const setPrivacyBrokerEnabled = (id, enabled, options) => request(`/privacy/brokers/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify({ enabled }),
+ ...options,
+});
+/** User-triggered broker-list refresh (BADBOOL + CA registry; never clobbers curated). */
+export const refreshPrivacyBrokers = (options) => request('/privacy/brokers/refresh', {
+ method: 'POST',
+ ...options,
+});
+/** Case ledger rows (joined with broker name/tier). `state` filters when set. */
+export const getPrivacyBrokerCases = (state, options) =>
+ request(`/privacy/broker-cases${state ? `?state=${encodeURIComponent(state)}` : ''}`, options);
+/** Force a case due for recheck now. */
+export const recheckPrivacyCase = (id, options) =>
+ request(`/privacy/broker-cases/${id}/recheck`, { method: 'POST', ...options });
+/** Manual case transition (digest done/dismiss, drawer controls): { toState, reason? }. */
+export const transitionPrivacyCase = (id, toState, reason, options) => request(`/privacy/broker-cases/${id}/transition`, {
+ method: 'POST',
+ body: JSON.stringify(reason ? { toState, reason } : { toState }),
+ ...options,
+});
+/** Aggregate exposure readout: enabledBrokers, caseCounts (per state), dueForRecheck. */
+export const getPrivacyScanStatus = (options) => request('/privacy/scan/status', options);
+/** Run a read-only exposure scan pass over enabled brokers. */
+export const runPrivacyScan = (options) => request('/privacy/scan', { method: 'POST', ...options });
+/** Run one opt-out pass (submit found/indirect cases via the chosen lane, poll verifications). */
+export const runPrivacyOptOut = (options) => request('/privacy/optout', { method: 'POST', ...options });
+/** Human-task digest: cases needing a person (blocked / human-only channels). */
+export const getPrivacyOptOutDigest = (options) => request('/privacy/optout/digest', options);
+/** Recheck-schedule status: { enabled, cronExpression, autoApproveOptOutEmails, autoSubmitWebForms, nextRun }. */
+export const getPrivacyOptOutSchedule = (options) => request('/privacy/optout/schedule', options);
+/** Update the recheck cron + autonomy toggles; restarts the scheduler. Returns the new status. */
+export const updatePrivacyOptOutSchedule = (patch, options) => request('/privacy/optout/schedule', {
+ method: 'PUT',
+ body: JSON.stringify(patch),
+ ...options,
+});
+
// ── Digital Twin cross-link (#2147) ─────────────────────────────────────────
/** Social-account → org links for the Twin's "in org registry" badges. */
export const getSocialAccountOrgLinks = (options) =>
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index a66d976228..3878d9a47d 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -147,6 +147,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.identity.privacy-vault', path: '/privacy/vault', label: 'Vault', section: 'Identity', aliases: ['vault', 'pii-vault', 'privacy-vault'], keywords: ['pii', 'vault', 'encrypted', 'ssn', 'address', 'passport', 'identity'] },
{ id: 'nav.identity.privacy-organizations', path: '/privacy/organizations', label: 'Organizations', section: 'Identity', aliases: ['organizations', 'orgs', 'trusted-orgs'], keywords: ['organizations', 'banks', 'utilities', 'who holds my data', 'registry', 'holdings'] },
{ id: 'nav.identity.privacy-changes', path: '/privacy/changes', label: 'Changes', section: 'Identity', aliases: ['changes', 'change-of-address', 'address-change', 'privacy-changes'], keywords: ['change of address', 'moved', 'update address', 'inventory', 'who needs updating', 'new phone', 'new email'] },
+ { id: 'nav.identity.privacy-brokers', path: '/privacy/brokers', label: 'Brokers', section: 'Identity', aliases: ['brokers', 'data brokers', 'opt out', 'remove my data', 'privacy-brokers'], keywords: ['data brokers', 'opt out', 'remove my data', 'people search', 'exposure', 'spokeo', 'whitepages', 'ccpa', 'delete my data'] },
{ id: 'nav.meatspace.overview', path: '/meatspace/overview', label: 'Overview', section: 'Health', aliases: ['meatspace'] },
{ id: 'nav.meatspace.health', path: '/meatspace/health', label: 'Body Health', section: 'Health', aliases: ['meatspace-health', 'body-health'], keywords: ['health', 'vitals', 'wellbeing', 'biometrics'] },
diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.js
index 77ee7686e3..77a96ece79 100644
--- a/server/lib/privacyValidation.js
+++ b/server/lib/privacyValidation.js
@@ -229,6 +229,35 @@ export const privacyBrokerCaseListQuerySchema = z.object({
// POST /api/privacy/brokers/refresh — no body; empty object.
export const privacyBrokerRefreshSchema = z.object({}).strict();
+// PUT /api/privacy/brokers/:id — broker ids are slugs (curated) or `ca-`/badbool
+// tokens (auto), NOT uuids. Only the `enabled` toggle is user-writable — the
+// rest of a broker row is curated seed / auto-refresh, never user-edited (#2146).
+export const privacyBrokerIdParamsSchema = z.object({
+ id: z.string().min(1).max(128),
+}).strict();
+
+export const privacyBrokerUpdateSchema = z.object({
+ enabled: z.boolean(),
+}).strict();
+
+// Case-id path param (a uuid) — force-recheck + manual transition controls.
+export const privacyCaseIdParamsSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
+// POST /api/privacy/broker-cases/:id/transition — manual case controls from the
+// digest / case drawer. Only the human-reachable targets are exposed here; the
+// verification-only targets (`confirmed_removed`, `reappeared`) are NOT — they
+// stay reachable ONLY from a verifying re-scan inside the engine. The service's
+// assertTransition still enforces the full state machine on top of this.
+export const PRIVACY_MANUAL_CASE_TARGETS = Object.freeze([
+ 'submitted', 'not_found', 'human_task_queued', 'optout_in_progress', 'blocked',
+]);
+export const privacyCaseTransitionSchema = z.object({
+ toState: z.enum(PRIVACY_MANUAL_CASE_TARGETS),
+ reason: z.string().max(2000).optional(),
+}).strict();
+
// POST /api/privacy/scan — optional concurrency knob.
export const privacyScanStartSchema = z.object({
concurrency: z.number().int().min(1).max(6).optional(),
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index e12e45661f..0e3f7acc36 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -24,12 +24,17 @@ import {
privacyBrokerListQuerySchema,
privacyBrokerCaseListQuerySchema,
privacyBrokerRefreshSchema,
+ privacyBrokerIdParamsSchema,
+ privacyBrokerUpdateSchema,
+ privacyCaseIdParamsSchema,
+ privacyCaseTransitionSchema,
privacyScanStartSchema,
privacyChangeDeclareSchema,
privacyChangeIdParamsSchema,
privacyChangeOrgParamsSchema,
privacyOptOutPassSchema,
privacyOptOutVerifySchema,
+ privacyRecheckConfigSchema,
} from '../lib/privacyValidation.js';
import {
createVaultRecord,
@@ -55,9 +60,17 @@ import {
refreshBrokers,
listBrokerCases,
getScanStatus,
+ setBrokerEnabled,
+ forceRecheckCase,
+ transitionCase,
} from '../services/privacyBrokers.js';
import { runScanPass } from '../services/privacyScan.js';
import { runOptOutPass, runVerificationPass, getOptOutDigest } from '../services/privacyOptOut.js';
+import {
+ getPrivacyRecheckStatus,
+ restartPrivacyRecheckScheduler,
+} from '../services/privacyRecheckScheduler.js';
+import { getSettings, updateSettingsWith } from '../services/settings.js';
import {
declareChange,
listChangeEvents,
@@ -200,11 +213,34 @@ router.post('/brokers/refresh', asyncHandler(async (req, res) => {
res.json(await refreshBrokers());
}));
+// Per-broker enable/disable toggle (Brokers-tab, #2146). A disabled broker is
+// skipped by the scan + opt-out passes.
+router.put('/brokers/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyBrokerIdParamsSchema, req.params);
+ const { enabled } = validateRequest(privacyBrokerUpdateSchema, req.body);
+ res.json(await setBrokerEnabled(id, enabled));
+}));
+
router.get('/broker-cases', asyncHandler(async (req, res) => {
const { state } = validateRequest(privacyBrokerCaseListQuerySchema, req.query);
res.json(await listBrokerCases({ state }));
}));
+// Force a case due for recheck NOW (case drawer "Re-check" control, #2146).
+router.post('/broker-cases/:id/recheck', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyCaseIdParamsSchema, req.params);
+ res.json(await forceRecheckCase(id));
+}));
+
+// Manual case transition (digest done/dismiss, case-drawer controls, #2146).
+// Only human-reachable targets are accepted (schema); the service's state
+// machine enforces validity of the specific from→to move on top of that.
+router.post('/broker-cases/:id/transition', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyCaseIdParamsSchema, req.params);
+ const { toState, reason } = validateRequest(privacyCaseTransitionSchema, req.body);
+ res.json(await transitionCase(id, toState, reason === undefined ? {} : { reason }));
+}));
+
router.get('/scan/status', asyncHandler(async (_req, res) => {
res.json(await getScanStatus());
}));
@@ -237,4 +273,26 @@ router.get('/optout/digest', asyncHandler(async (_req, res) => {
res.json(await getOptOutDigest());
}));
+// Recheck-schedule status: enabled, cron, autonomy toggles, next fire time.
+router.get('/optout/schedule', asyncHandler(async (_req, res) => {
+ res.json(await getPrivacyRecheckStatus());
+}));
+
+// Enable/disable the recheck cron + autonomy toggles (Brokers-tab run controls,
+// #2146). Deep-merges the `privacy.recheck` settings slice, then restarts the
+// scheduler so the change takes effect immediately (the cron expression is
+// locked in at registration). Enabling creates the cron; disabling removes it.
+router.put('/optout/schedule', asyncHandler(async (req, res) => {
+ const patch = validateRequest(privacyRecheckConfigSchema, req.body ?? {});
+ await updateSettingsWith((current) => ({
+ ...current,
+ privacy: {
+ ...(current.privacy || {}),
+ recheck: { ...(current.privacy?.recheck || {}), ...patch },
+ },
+ }));
+ await restartPrivacyRecheckScheduler();
+ res.json(await getPrivacyRecheckStatus());
+}));
+
export default router;
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index 9b3596c87b..ce6ba2518c 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -36,6 +36,21 @@ vi.mock('../services/privacyBrokers.js', () => ({
refreshBrokers: vi.fn(async () => ({ fetched: 3, added: 2, sources: { badbool: 2, caRegistry: 1 } })),
listBrokerCases: vi.fn(async () => [{ id: 'case-1', brokerId: 'spokeo', state: 'found' }]),
getScanStatus: vi.fn(async () => ({ enabledBrokers: 20, caseCounts: { found: 1 }, dueForRecheck: 3 })),
+ setBrokerEnabled: vi.fn(async (id, enabled) => ({ id, name: 'Spokeo', enabled })),
+ forceRecheckCase: vi.fn(async (id) => ({ id, state: 'found', nextRecheckAt: '2020-01-01T00:00:00.000Z' })),
+ transitionCase: vi.fn(async (id, toState) => ({ id, state: toState })),
+}));
+
+vi.mock('../services/privacyRecheckScheduler.js', () => ({
+ getPrivacyRecheckStatus: vi.fn(async () => ({
+ enabled: false, cronExpression: '0 4 * * 0', autoApproveOptOutEmails: false, autoSubmitWebForms: false, nextRun: null,
+ })),
+ restartPrivacyRecheckScheduler: vi.fn(async () => {}),
+}));
+
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => ({ privacy: { recheck: {} } })),
+ updateSettingsWith: vi.fn(async (mutate) => mutate({ privacy: { recheck: {} } })),
}));
vi.mock('../services/privacyScan.js', () => ({
@@ -418,3 +433,65 @@ describe('GET /api/privacy/optout/digest', () => {
expect(res.body.items[0].playbook).toEqual(['call back']);
});
});
+
+describe('PUT /api/privacy/brokers/:id (#2146)', () => {
+ it('toggles a broker enabled flag', async () => {
+ const res = await request(makeApp()).put('/api/privacy/brokers/spokeo').send({ enabled: false });
+ expect(res.status).toBe(200);
+ expect(brokerService.setBrokerEnabled).toHaveBeenCalledWith('spokeo', false);
+ expect(res.body).toMatchObject({ id: 'spokeo', enabled: false });
+ });
+
+ it('rejects a non-boolean / unknown-key body', async () => {
+ expect((await request(makeApp()).put('/api/privacy/brokers/spokeo').send({ enabled: 'yes' })).status).toBe(400);
+ expect((await request(makeApp()).put('/api/privacy/brokers/spokeo').send({ enabled: true, x: 1 })).status).toBe(400);
+ });
+});
+
+describe('POST /api/privacy/broker-cases/:id/recheck (#2146)', () => {
+ it('forces a case due for recheck', async () => {
+ const res = await request(makeApp()).post(`/api/privacy/broker-cases/${VALID_UUID}/recheck`).send({});
+ expect(res.status).toBe(200);
+ expect(brokerService.forceRecheckCase).toHaveBeenCalledWith(VALID_UUID);
+ });
+
+ it('rejects a non-uuid id', async () => {
+ expect((await request(makeApp()).post('/api/privacy/broker-cases/not-a-uuid/recheck')).status).toBe(400);
+ });
+});
+
+describe('POST /api/privacy/broker-cases/:id/transition (#2146)', () => {
+ it('transitions a case to a manual target state', async () => {
+ const res = await request(makeApp()).post(`/api/privacy/broker-cases/${VALID_UUID}/transition`).send({ toState: 'submitted' });
+ expect(res.status).toBe(200);
+ expect(brokerService.transitionCase).toHaveBeenCalledWith(VALID_UUID, 'submitted', {});
+ expect(res.body).toMatchObject({ state: 'submitted' });
+ });
+
+ it('rejects a verification-only / unknown target state', async () => {
+ expect((await request(makeApp()).post(`/api/privacy/broker-cases/${VALID_UUID}/transition`).send({ toState: 'confirmed_removed' })).status).toBe(400);
+ expect((await request(makeApp()).post(`/api/privacy/broker-cases/${VALID_UUID}/transition`).send({ toState: 'bogus' })).status).toBe(400);
+ });
+});
+
+describe('privacy recheck schedule (#2146)', () => {
+ it('GET returns the schedule status', async () => {
+ const res = await request(makeApp()).get('/api/privacy/optout/schedule');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ enabled: false, cronExpression: '0 4 * * 0' });
+ });
+
+ it('PUT persists the slice + restarts the scheduler', async () => {
+ const res = await request(makeApp()).put('/api/privacy/optout/schedule').send({ enabled: true, cronExpression: '0 6 * * 1' });
+ expect(res.status).toBe(200);
+ const settingsService = await import('../services/settings.js');
+ const scheduler = await import('../services/privacyRecheckScheduler.js');
+ expect(settingsService.updateSettingsWith).toHaveBeenCalled();
+ expect(scheduler.restartPrivacyRecheckScheduler).toHaveBeenCalled();
+ });
+
+ it('PUT rejects a malformed cron / unknown key', async () => {
+ expect((await request(makeApp()).put('/api/privacy/optout/schedule').send({ cronExpression: 'nope' })).status).toBe(400);
+ expect((await request(makeApp()).put('/api/privacy/optout/schedule').send({ bogus: 1 })).status).toBe(400);
+ });
+});
diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.js
index 6efe50bf68..ebe35fe0d3 100644
--- a/server/services/privacyBrokers.js
+++ b/server/services/privacyBrokers.js
@@ -258,6 +258,21 @@ export async function getBroker(id) {
return rowToBroker(rows[0]);
}
+/**
+ * Toggle a broker's `enabled` flag (Brokers-tab per-broker on/off, #2146). A
+ * disabled broker is skipped by the scan + opt-out passes. Returns the updated
+ * broker row (404 if the id is unknown).
+ */
+export async function setBrokerEnabled(id, enabled) {
+ const { rows } = await query(
+ `UPDATE privacy_brokers SET enabled = $1, updated_at = NOW() WHERE id = $2 RETURNING ${BROKER_COLUMNS}`,
+ [enabled, id],
+ );
+ if (!rows[0]) throw new ServerError('Broker not found', { status: 404, code: 'NOT_FOUND' });
+ console.log(`🗂️ Broker ${id}: enabled → ${enabled}`);
+ return rowToBroker(rows[0]);
+}
+
// Parse the CA Data Broker Registry CSV (id/name-bearing rows) defensively.
// Returns [] on any shape we can't recognize rather than throwing.
export function parseCaRegistryCsv(csv) {
@@ -478,6 +493,23 @@ export async function transitionCase(caseId, toState, patch = {}) {
});
}
+/**
+ * Force a case due for recheck NOW (Brokers-tab manual "Re-check" control,
+ * #2146): stamp `next_recheck_at` in the past so the next scan/opt-out pass
+ * picks it up regardless of its backoff. Read-only otherwise — does not change
+ * the case state. Returns the updated case row (404 if unknown).
+ */
+export async function forceRecheckCase(caseId, { now = new Date() } = {}) {
+ const { rows } = await query(
+ `UPDATE privacy_broker_cases SET next_recheck_at = $1, updated_at = NOW()
+ WHERE id = $2 RETURNING ${CASE_COLUMNS}`,
+ [new Date(now.getTime() - 1000).toISOString(), caseId],
+ );
+ if (!rows[0]) throw new ServerError('Case not found', { status: 404, code: 'NOT_FOUND' });
+ console.log(`📋 Case ${caseId}: forced due for recheck`);
+ return rowToCase(rows[0]);
+}
+
/**
* Aggregate readout for the scan/status endpoint + Brokers UI: total enabled
* brokers, case counts per state, and how many cases are due for a recheck.
diff --git a/server/services/privacyRecheckScheduler.js b/server/services/privacyRecheckScheduler.js
index 9c6329747e..a2b89ee6c3 100644
--- a/server/services/privacyRecheckScheduler.js
+++ b/server/services/privacyRecheckScheduler.js
@@ -13,13 +13,14 @@
* without a restart.
*/
-import { schedule, cancel } from './eventScheduler.js';
+import { schedule, cancel, parseCronToNextRun } from './eventScheduler.js';
import { getSettings } from './settings.js';
import { getUserTimezone } from '../lib/timezone.js';
import { runScanPass } from './privacyScan.js';
import { runOptOutPass } from './privacyOptOut.js';
const EVENT_ID = 'privacy-recheck';
+const DEFAULT_CRON = '0 4 * * 0'; // weekly, Sun 4am
export async function startPrivacyRecheckScheduler() {
const settings = await getSettings();
@@ -30,7 +31,7 @@ export async function startPrivacyRecheckScheduler() {
return;
}
- const cronExpression = recheck.cronExpression || '0 4 * * 0'; // weekly, Sun 4am
+ const cronExpression = recheck.cronExpression || DEFAULT_CRON;
const timezone = await getUserTimezone();
schedule({
@@ -60,3 +61,39 @@ export function stopPrivacyRecheckScheduler() {
cancel(EVENT_ID);
console.log('🛡️ Privacy recheck scheduler: stopped');
}
+
+/**
+ * Restart the scheduler so a Settings save (enable/disable, new cron) takes
+ * effect immediately without a server restart — the cron expression is locked
+ * in at registration, so a change needs a cancel + re-register. Called by the
+ * PUT /api/privacy/optout/schedule route after it persists the settings slice.
+ */
+export async function restartPrivacyRecheckScheduler() {
+ stopPrivacyRecheckScheduler();
+ await startPrivacyRecheckScheduler();
+}
+
+/**
+ * Read-only schedule status for the Brokers-tab run controls: whether the cron
+ * is enabled, its expression, the autonomy toggles, and the next fire time
+ * (null when disabled or the cron can't be parsed). Never triggers work.
+ */
+export async function getPrivacyRecheckStatus() {
+ const settings = await getSettings();
+ const recheck = settings.privacy?.recheck || {};
+ const enabled = recheck.enabled === true;
+ const cronExpression = recheck.cronExpression || DEFAULT_CRON;
+ const timezone = await getUserTimezone();
+ let nextRun = null;
+ if (enabled) {
+ // parseCronToNextRun returns null on an unparseable expression — never throw.
+ nextRun = parseCronToNextRun(cronExpression, new Date(), timezone)?.toISOString?.() ?? null;
+ }
+ return {
+ enabled,
+ cronExpression,
+ autoApproveOptOutEmails: recheck.autoApproveOptOutEmails === true,
+ autoSubmitWebForms: recheck.autoSubmitWebForms === true,
+ nextRun,
+ };
+}