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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: require purpose-specific, revocable consent before broker scans and opt-outs (#8332)
[._.]/ Adam Eivy5e6e7b007ca6
diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsxindex 5e23fdb604..bcf0c569b8 100644--- a/client/src/components/privacy/PrivacyBrokersTab.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx@@ -15,10 +15,11 @@ import { timeAgo, formatDateShort } from '../../utils/formatters';import BrokerCaseDrawer from './BrokerCaseDrawer';import {CASE_STATES, CASE_STATE_TONE, EXPOSURE_MAP_STATES, BROKER_SOURCES, BROKER_CONFIDENCE,- ACTION_TONES, manualCaseActions, labelFor,+ ACTION_TONES, BROKER_CONSENT_PURPOSES, CONSENT_SCOPES, manualCaseActions, labelFor,} from './constants';import { isHttpUrl } from '../../utils/urlNormalize';import CronSchedulePicker from '../CronSchedulePicker';+import Banner from '../ui/Banner';// Digest action icon by descriptor `icon` token (positive resolution vs dismiss).const ACTION_ICONS = { check: CheckCircle2, x: XCircle };@@ -33,7 +34,7 @@ function StatChip({ label, count, tone }) {);}-export default function PrivacyBrokersTab({ subjectId }) {+export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageConsent }) {const [searchParams, setSearchParams] = useSearchParams();const openCaseId = searchParams.get('case');@@ -85,27 +86,34 @@ export default function PrivacyBrokersTab({ subjectId }) {return times.length ? times[times.length - 1] : null;}, [cases]);+ // Broker purposes this subject has no active grant for. `consentScopes` is+ // undefined until the parent's subject list loads — unknown is not "none+ // granted", so no warning until the grants are actually known.+ const missingPurposes = Array.isArray(consentScopes)+ ? BROKER_CONSENT_PURPOSES.filter((p) => !consentScopes.includes(p.id))+ : [];+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) ─────────- // The engine refuses to scan or submit for a subject with no active consent- // row (403 SUBJECT_CONSENT_REQUIRED). Its raw message names the subject UUID,+ // The engine refuses to scan (`broker_scan`) or submit (`broker_optout`) for+ // a subject without an active grant of that exact purpose (403+ // SUBJECT_CONSENT_REQUIRED, #8332). Its raw message names the subject UUID,// so restate it as the action the user can actually take — the fix is- // recording consent, not retrying.+ // granting that purpose under Household, not retrying.// Restate, don't replace: the code/status ride along so a future surface can- // act on the refusal (deep-link to Household, disable the button) instead of- // re-parsing a sentence.- const runPass = (fn) => fn({ silent: true, subjectId }).catch((err) => {+ // act on the refusal instead of re-parsing a sentence.+ const runPass = (fn, scope) => fn({ silent: true, subjectId }).catch((err) => {if (err?.code !== 'SUBJECT_CONSENT_REQUIRED') throw err;- const friendly = new Error('No consent on record for this person — add it under Household first');+ const friendly = new Error(`No active consent for ${labelFor(CONSENT_SCOPES, scope).toLowerCase()} for this person — grant it under Household first`);friendly.code = err.code;friendly.status = err.status;throw friendly;});const [scanNow, scanRunning] = useAsyncAction(async () => {- const r = await runPass(runPrivacyScan);+ const r = await runPass(runPrivacyScan, 'broker_scan');load();const verdicts = Object.entries(r?.verdicts || {}).map(([k, v]) => `${v} ${labelFor(CASE_STATES, k).toLowerCase()}`).join(', ');toast.success(r?.reason === 'no_scan_vectors'@@ -115,7 +123,7 @@ export default function PrivacyBrokersTab({ subjectId }) {}, { errorMessage: 'Scan failed' });const [optOutNow, optOutRunning] = useAsyncAction(async () => {- const r = await runPass(runPrivacyOptOut);+ const r = await runPass(runPrivacyOptOut, 'broker_optout');load();toast.success(r?.reason === 'no_disclosure_identity'? 'Add a scan-eligible name to the vault to run an opt-out pass'@@ -208,6 +216,24 @@ export default function PrivacyBrokersTab({ subjectId }) {{/* ── 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>+ {missingPurposes.length > 0 && (+ <Banner+ tone="warning"+ icon={AlertTriangle}+ actions={onManageConsent && (+ <button+ onClick={onManageConsent}+ className="px-2.5 py-1 text-xs rounded border border-port-warning/40 hover:bg-port-warning/10"+ >+ Manage consent+ </button>+ )}+ >+ No active consent for {missingPurposes.map((p) => p.label.toLowerCase()).join(' or ')} for this person+ — {missingPurposes.length === 1 ? 'that purpose is' : 'those purposes are'} refused, including on the automatic+ schedule, until granted under Household.+ </Banner>+ )}<div className="flex flex-wrap gap-2"><buttononClick={() => scanNow()}@@ -241,7 +267,7 @@ export default function PrivacyBrokersTab({ subjectId }) {/><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>+ <span className="text-[11px] text-gray-500">runs a scan + opt-out pass on the cron below for each person with that consent</span>)}</label>diff --git a/client/src/components/privacy/PrivacyBrokersTab.test.jsx b/client/src/components/privacy/PrivacyBrokersTab.test.jsxindex e0359058ce..7ac8d03030 100644--- a/client/src/components/privacy/PrivacyBrokersTab.test.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.test.jsx@@ -53,7 +53,7 @@ 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>);+const renderTab = (props = {}) => render(<MemoryRouter initialEntries={['/privacy/brokers']}><PrivacyBrokersTab {...props} /></MemoryRouter>);describe('PrivacyBrokersTab', () => {beforeEach(() => {@@ -120,4 +120,29 @@ describe('PrivacyBrokersTab', () => {fireEvent.click(brokerToggle);await waitFor(() => expect(apiMod.setPrivacyBrokerEnabled).toHaveBeenCalledWith('spokeo', false, expect.anything()));});++ // ── Purpose-scoped broker consent (#8332) ──+ it('warns which broker purposes are not granted and links to Household', async () => {+ const onManageConsent = vi.fn();+ renderTab({ consentScopes: ['broker_scan', 'pii_vault'], onManageConsent });+ const banner = await screen.findByText(/No active consent for broker opt-out requests for this person/);+ expect(banner.textContent).not.toMatch(/exposure scan/);+ fireEvent.click(screen.getByRole('button', { name: 'Manage consent' }));+ expect(onManageConsent).toHaveBeenCalled();+ });++ it('shows no consent warning until the grants are known', async () => {+ renderTab();+ await screen.findByText('Spokeo');+ expect(screen.queryByText(/No active consent/)).toBeNull();+ });++ it('restates a refused opt-out pass as the missing purpose grant', async () => {+ const toast = (await import('../ui/Toast')).default;+ apiMod.runPrivacyOptOut.mockRejectedValueOnce(Object.assign(new Error('raw 403'), { code: 'SUBJECT_CONSENT_REQUIRED', status: 403 }));+ renderTab();+ await screen.findByText('Spokeo');+ fireEvent.click(screen.getByRole('button', { name: /Run opt-out pass/ }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/^No active consent for broker opt-out requests/)));+ });});diff --git a/client/src/components/privacy/SubjectsDrawer.jsx b/client/src/components/privacy/SubjectsDrawer.jsxindex e8b27eb2f6..b6b017cae6 100644--- a/client/src/components/privacy/SubjectsDrawer.jsx+++ b/client/src/components/privacy/SubjectsDrawer.jsx@@ -1,5 +1,5 @@import { useState, useEffect } from 'react';-import { Plus, Trash2, ShieldCheck, ChevronDown, ChevronRight } from 'lucide-react';+import { Plus, Trash2, ShieldCheck, ShieldOff, ChevronDown, ChevronRight } from 'lucide-react';import Drawer from '../Drawer';import FormField from '../ui/FormField';import InlineConfirmRow from '../ui/InlineConfirmRow';@@ -8,11 +8,13 @@ import { useAsyncAction } from '../../hooks/useAsyncAction';import useConfirmDelete from '../../hooks/useConfirmDelete';import {createPrivacySubject, deletePrivacySubject, getPrivacySubjectConsents,+ grantPrivacySubjectConsent, revokePrivacySubjectConsent,} from '../../services/api';import toast from '../ui/Toast';import { formatDateShort } from '../../utils/formatters';import {- SUBJECT_RELATIONSHIPS, CONSENT_METHODS, CONSENT_SCOPES, INPUT_CLS, labelFor,+ SUBJECT_RELATIONSHIPS, CONSENT_METHODS, CONSENT_SCOPES, BROKER_CONSENT_PURPOSES,+ INPUT_CLS, labelFor,} from './constants';// `self` is excluded — you are always your own subject and consent is implied.@@ -21,8 +23,9 @@ const ADDABLE_RELATIONSHIPS = SUBJECT_RELATIONSHIPS.filter((r) => r.id !== 'selfconst EMPTY = { displayName: '', relationship: 'partner', consentMethod: 'verbal', consentNote: '' };// Consent audit trail for one subject — loaded lazily on expand so opening the-// drawer costs one request, not one per household member.-function ConsentTrail({ subjectId }) {+// drawer costs one request, not one per household member. `version` changes+// after a grant/revoke so an open trail refetches instead of going stale.+function ConsentTrail({ subjectId, version }) {// null = not fetched · [] = fetched-and-empty · 'error' = fetch failed. A// failed read must NOT collapse into the empty case: "no consent on record"// is an assertion about the engine's state, and saying it because a request@@ -30,6 +33,8 @@ function ConsentTrail({ subjectId }) {const [consents, setConsents] = useState(null);const [open, setOpen] = useState(false);+ useEffect(() => { setConsents(null); }, [version]);+useEffect(() => {if (!open || consents !== null) return undefined;let active = true;@@ -70,7 +75,8 @@ function ConsentTrail({ subjectId }) {<li key={c.id} className="text-[11px] text-gray-500"><span className="text-gray-300">{labelFor(CONSENT_METHODS, c.method)}</span>{' · '}{labelFor(CONSENT_SCOPES, c.scope)}- {c.grantedAt ? ` · ${formatDateShort(c.grantedAt)}` : ''}+ {c.grantedAt ? ` · granted ${formatDateShort(c.grantedAt)}` : ''}+ {c.revokedAt ? <span className="text-port-warning">{` · revoked ${formatDateShort(c.revokedAt)}`}</span> : null}{c.note ? <span className="italic"> — {c.note}</span> : null}</li>))}@@ -81,11 +87,87 @@ function ConsentTrail({ subjectId }) {);}+// One broker purpose's grant state for one subject. Granting WIDENS disclosure,+// so it goes through an inline confirm that names what is sent and records how+// consent was captured; revoking narrows it and runs immediately. The server+// gate is authoritative — this only drives the grant/revoke endpoints.+function BrokerPurposeRow({ subject, purpose, granted, onChanged }) {+ const [confirming, setConfirming] = useState(false);+ const [method, setMethod] = useState(subject.isSelf ? 'self' : 'verbal');++ const [grant, granting] = useAsyncAction(async () => {+ const row = await grantPrivacySubjectConsent(subject.id, { scope: purpose.id, method }, { silent: true });+ if (row) {+ toast.success(`${purpose.label} granted for ${subject.displayName}`);+ setConfirming(false);+ onChanged(purpose.id, true);+ }+ return row;+ }, { errorMessage: `Failed to grant ${purpose.label.toLowerCase()}` });++ const [revoke, revoking] = useAsyncAction(async () => {+ const result = await revokePrivacySubjectConsent(subject.id, purpose.id, { silent: true });+ if (result) {+ toast.success(`${purpose.label} revoked for ${subject.displayName}`);+ onChanged(purpose.id, false);+ }+ return result;+ }, { errorMessage: `Failed to revoke ${purpose.label.toLowerCase()}` });++ return (+ <div className="py-2 border-t border-port-border/60 first:border-t-0">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-xs text-gray-200">{purpose.label}</span>+ {granted+ ? <Pill size="xs" tone="success" icon={ShieldCheck}>Granted</Pill>+ : <Pill size="xs" icon={ShieldOff}>Not granted</Pill>}+ </div>+ {granted ? (+ <button+ onClick={() => revoke()}+ disabled={revoking}+ aria-label={`Revoke ${purpose.label.toLowerCase()} for ${subject.displayName}`}+ 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-50"+ >+ {revoking ? 'Revoking…' : 'Revoke'}+ </button>+ ) : !confirming && (+ <button+ onClick={() => setConfirming(true)}+ aria-label={`Grant ${purpose.label.toLowerCase()} for ${subject.displayName}`}+ className="px-2.5 py-1 text-xs rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-border/40"+ >+ Grant…+ </button>+ )}+ </div>+ <p className="mt-1 text-[11px] text-gray-500">{purpose.disclosure}</p>+ {confirming && !granted && (+ <div className="mt-2 space-y-2">+ <FormField label="Consent captured via" labelClassName="block text-[11px] text-gray-400 mb-1">+ <select value={method} onChange={(e) => setMethod(e.target.value)} className={INPUT_CLS}>+ {CONSENT_METHODS.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}+ </select>+ </FormField>+ <InlineConfirmRow+ tone="warning"+ confirmText={granting ? 'Granting…' : 'Grant'}+ question={`Allow ${purpose.label.toLowerCase()} for ${subject.displayName}? This sends their data to external data brokers.`}+ onConfirm={() => { if (!granting) grant(); }}+ onCancel={() => setConfirming(false)}+ />+ </div>+ )}+ </div>+ );+}+// Manage the household: who the Privacy Center tracks, on what consent.// Consent is captured at creation because the engine refuses to scan or submit// opt-outs for a subject with no consent row — the form cannot create a subject// that the rest of the feature would then silently refuse to act on.-export default function SubjectsDrawer({ open, subjects, onClose, onCreated, onDeleted }) {+export default function SubjectsDrawer({ open, subjects, onClose, onCreated, onDeleted, onConsentChanged }) {const [form, setForm] = useState(EMPTY);const [adding, setAdding] = useState(false);const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();@@ -134,8 +216,9 @@ export default function SubjectsDrawer({ open, subjects, onClose, onCreated, onD<div className="space-y-4"><p className="text-xs text-gray-500">Each person is scoped separately — their vault records, organizations, changes, and broker- cases never mix. Broker scans and opt-out submissions are refused for anyone without a- consent record.+ cases never mix. Vault consent is local-only: broker scans and opt-out requests each need+ their own grant, can be revoked at any time without removing the person, and are refused+ — including on the automatic schedule — for anyone without an active grant.</p><div className="space-y-2">@@ -146,14 +229,25 @@ export default function SubjectsDrawer({ open, subjects, onClose, onCreated, onD<div className="flex items-center gap-2 flex-wrap"><span className="text-sm font-medium text-white truncate">{s.displayName}</span><Pill size="xs">{labelFor(SUBJECT_RELATIONSHIPS, s.relationship)}</Pill>- {s.consentCount > 0 && (- <Pill size="xs" tone="success" icon={ShieldCheck}>Consented</Pill>+ {(s.activeScopes ?? []).includes('pii_vault') && (+ <Pill size="xs" tone="success" icon={ShieldCheck}>Vault consent</Pill>)}</div><div className="mt-0.5 text-[11px] text-gray-500">{s.recordCount ?? 0} vault record{s.recordCount === 1 ? '' : 's'}</div>- <ConsentTrail subjectId={s.id} />+ <div className="mt-2">+ {BROKER_CONSENT_PURPOSES.map((purpose) => (+ <BrokerPurposeRow+ key={purpose.id}+ subject={s}+ purpose={purpose}+ granted={(s.activeScopes ?? []).includes(purpose.id)}+ onChanged={(scope, granted) => onConsentChanged?.(s.id, scope, granted)}+ />+ ))}+ </div>+ <ConsentTrail subjectId={s.id} version={(s.activeScopes ?? []).join(',')} /></div>{!s.isSelf && (<buttondiff --git a/client/src/components/privacy/SubjectsDrawer.test.jsx b/client/src/components/privacy/SubjectsDrawer.test.jsxindex f0749bcdc1..dd6921c8b2 100644--- a/client/src/components/privacy/SubjectsDrawer.test.jsx+++ b/client/src/components/privacy/SubjectsDrawer.test.jsx@@ -7,18 +7,21 @@ vi.mock('../../services/api', () => ({createPrivacySubject: vi.fn(),deletePrivacySubject: vi.fn(),getPrivacySubjectConsents: vi.fn(),+ grantPrivacySubjectConsent: vi.fn(),+ revokePrivacySubjectConsent: vi.fn(),}));vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));import SubjectsDrawer from './SubjectsDrawer';import {createPrivacySubject, deletePrivacySubject, getPrivacySubjectConsents,+ grantPrivacySubjectConsent, revokePrivacySubjectConsent,} from '../../services/api';import { SELF_SUBJECT_ID } from './constants';const SUBJECTS = [- { id: SELF_SUBJECT_ID, displayName: 'Me', relationship: 'self', isSelf: true, consentCount: 1, recordCount: 3 },- { id: 'sub-2', displayName: 'Alex', relationship: 'partner', isSelf: false, consentCount: 1, recordCount: 1 },+ { id: SELF_SUBJECT_ID, displayName: 'Me', relationship: 'self', isSelf: true, consentCount: 2, recordCount: 3, activeScopes: ['broker_scan', 'pii_vault'] },+ { id: 'sub-2', displayName: 'Alex', relationship: 'partner', isSelf: false, consentCount: 1, recordCount: 1, activeScopes: ['pii_vault'] },];function renderDrawer(props = {}) {@@ -106,4 +109,42 @@ describe('SubjectsDrawer', () => {await waitFor(() => expect(deletePrivacySubject).toHaveBeenCalledWith('sub-2', { silent: true }));expect(onDeleted).toHaveBeenCalledWith('sub-2');});++ // ── Purpose-scoped broker consent (#8332) ──+ it('grants a broker purpose only after a confirm that names the external disclosure', async () => {+ grantPrivacySubjectConsent.mockResolvedValue({ id: 'c-9', scope: 'broker_optout' });+ const onConsentChanged = vi.fn();+ renderDrawer({ onConsentChanged });++ fireEvent.click(screen.getByLabelText('Grant broker opt-out requests for Alex'));+ expect(grantPrivacySubjectConsent).not.toHaveBeenCalled();+ expect(screen.getByText(/sends their data to external data brokers/i)).toBeInTheDocument();+ fireEvent.change(screen.getByLabelText(/Consent captured via/i), { target: { value: 'written' } });+ fireEvent.click(screen.getByRole('button', { name: 'Grant' }));++ await waitFor(() => expect(grantPrivacySubjectConsent).toHaveBeenCalledWith(+ 'sub-2', { scope: 'broker_optout', method: 'written' }, { silent: true },+ ));+ expect(onConsentChanged).toHaveBeenCalledWith('sub-2', 'broker_optout', true);+ });++ it('revokes a broker purpose without removing the person', async () => {+ revokePrivacySubjectConsent.mockResolvedValue({ subjectId: SELF_SUBJECT_ID, scope: 'broker_scan', revoked: 1 });+ const onConsentChanged = vi.fn();+ renderDrawer({ onConsentChanged });++ fireEvent.click(screen.getByLabelText('Revoke broker exposure scan for Me'));+ await waitFor(() => expect(revokePrivacySubjectConsent).toHaveBeenCalledWith(SELF_SUBJECT_ID, 'broker_scan', { silent: true }));+ expect(onConsentChanged).toHaveBeenCalledWith(SELF_SUBJECT_ID, 'broker_scan', false);+ expect(deletePrivacySubject).not.toHaveBeenCalled();+ });++ it('shows revocation timestamps in the consent record', async () => {+ getPrivacySubjectConsents.mockResolvedValue([+ { id: 'c-2', subjectId: 'sub-2', scope: 'broker_scan', method: 'written', note: '', grantedAt: '2026-01-01T00:00:00Z', revokedAt: '2026-02-01T00:00:00Z' },+ ]);+ renderDrawer();+ fireEvent.click(screen.getAllByRole('button', { name: /Consent record/i })[1]);+ await waitFor(() => expect(screen.getByText(/revoked/)).toBeInTheDocument());+ });});diff --git a/client/src/components/privacy/constants.js b/client/src/components/privacy/constants.jsindex 42370d8642..e960fef78f 100644--- a/client/src/components/privacy/constants.js+++ b/client/src/components/privacy/constants.js@@ -30,10 +30,28 @@ export const CONSENT_METHODS = [{ id: 'other', label: 'Other' },];-// Mirrors PRIVACY_CONSENT_SCOPES.+// Mirrors PRIVACY_CONSENT_SCOPES — each purpose is granted separately (#8332).export const CONSENT_SCOPES = [- { id: 'pii_vault', label: 'PII vault' },- { id: 'broker_optout', label: 'Broker opt-out' },+ { id: 'pii_vault', label: 'PII vault (local only)' },+ { id: 'broker_scan', label: 'Broker exposure scan' },+ { id: 'broker_optout', label: 'Broker opt-out requests' },+];++// The revocable external-disclosure purposes (mirrors+// PRIVACY_BROKER_CONSENT_SCOPES), with the disclosure each one makes — the+// Household drawer states it next to the grant control so the person granting+// knows exactly what leaves this machine and to whom.+export const BROKER_CONSENT_PURPOSES = [+ {+ id: 'broker_scan',+ label: 'Broker exposure scan',+ disclosure: 'Searches each enabled data broker’s site using this person’s scan-eligible name and city/state, so those values are sent to the broker in its search URL. Read-only — nothing is submitted.',+ },+ {+ id: 'broker_optout',+ label: 'Broker opt-out requests',+ disclosure: 'Sends removal requests (email or web form) to data brokers that list this person, disclosing their full name, email, phone, and city/state — plus date of birth when a broker requires it — and re-checks those brokers to verify removal.',+ },];export const VAULT_TYPES = [diff --git a/client/src/pages/Privacy.jsx b/client/src/pages/Privacy.jsxindex c09250b6f6..9076622778 100644--- a/client/src/pages/Privacy.jsx+++ b/client/src/pages/Privacy.jsx@@ -56,7 +56,9 @@ export default function Privacy() {}, [updateParams]);const handleCreated = (subject) => {- setSubjects((prev) => [...prev, { ...subject, consentCount: 1, recordCount: 0 }]);+ // Creation writes exactly one local-only `pii_vault` grant — broker+ // purposes start ungranted (#8332).+ setSubjects((prev) => [...prev, { ...subject, consentCount: 1, recordCount: 0, activeScopes: ['pii_vault'] }]);selectSubject(subject.id);};@@ -66,6 +68,26 @@ export default function Privacy() {if (deletedId === subjectId) selectSubject(SELF_SUBJECT_ID);};+ // A broker purpose was granted/revoked in the Household drawer — mirror it+ // into the subject list so the drawer and the Brokers tab reflect it without+ // a refetch. A grant also appends an audit row (revocation only stamps one).+ const handleConsentChanged = (changedId, scope, granted) => {+ setSubjects((prev) => prev.map((s) => {+ if (s.id !== changedId) return s;+ const scopes = new Set(s.activeScopes ?? []);+ if (granted) scopes.add(scope); else scopes.delete(scope);+ return {+ ...s,+ activeScopes: [...scopes].sort(),+ ...(granted ? { consentCount: (s.consentCount ?? 0) + 1 } : {}),+ };+ }));+ };++ // `undefined` until the subject list loads — the Brokers tab only warns about+ // missing broker consent once it actually knows the grants.+ const activeSubject = subjects.find((s) => s.id === subjectId);+// Carry the subject across tabs, but drop tab-local params (e.g. the brokers// tab's `?case=`) so switching tabs can't reopen a stale drawer.const goToTab = (id) => navigate(privacyTabPath(id, subjectId));@@ -75,7 +97,13 @@ export default function Privacy() {case 'vault': return <PrivacyVaultTab subjectId={subjectId} />;case 'organizations': return <PrivacyOrgsTab subjectId={subjectId} />;case 'changes': return <PrivacyChangesTab subjectId={subjectId} />;- case 'brokers': return <PrivacyBrokersTab subjectId={subjectId} />;+ case 'brokers': return (+ <PrivacyBrokersTab+ subjectId={subjectId}+ consentScopes={activeSubject?.activeScopes}+ onManageConsent={() => setDrawerOpen(true)}+ />+ );case 'overview':default: return <PrivacyOverviewTab subjectId={subjectId} />;}@@ -118,6 +146,7 @@ export default function Privacy() {onClose={() => setDrawerOpen(false)}onCreated={handleCreated}onDeleted={handleDeleted}+ onConsentChanged={handleConsentChanged}/></div>);diff --git a/client/src/pages/Privacy.test.jsx b/client/src/pages/Privacy.test.jsxindex 9f19551b93..e2ad80af16 100644--- a/client/src/pages/Privacy.test.jsx+++ b/client/src/pages/Privacy.test.jsx@@ -8,16 +8,23 @@ vi.mock('../services/api', () => ({getPrivacySubjects: vi.fn().mockResolvedValue([{id: '00000000-0000-4000-8000-000000000001', displayName: 'Me', relationship: 'self',- isSelf: true, consentCount: 1, recordCount: 2,+ isSelf: true, consentCount: 1, recordCount: 2, activeScopes: ['pii_vault'],},{id: 'sub-2', displayName: 'Alex', relationship: 'partner',- isSelf: false, consentCount: 1, recordCount: 1,+ isSelf: false, consentCount: 1, recordCount: 1, activeScopes: ['pii_vault'],},]),createPrivacySubject: vi.fn(),deletePrivacySubject: vi.fn(),getPrivacySubjectConsents: vi.fn().mockResolvedValue([]),+ grantPrivacySubjectConsent: vi.fn().mockResolvedValue({ id: 'c-9', scope: 'broker_scan' }),+ revokePrivacySubjectConsent: vi.fn(),+ // Brokers tab (#8332 consent banner).+ getPrivacyBrokerCases: vi.fn().mockResolvedValue([]),+ getPrivacyBrokers: vi.fn().mockResolvedValue([]),+ getPrivacyOptOutDigest: vi.fn().mockResolvedValue({ total: 0, humanTasks: 0, blocked: 0, items: [] }),+ getPrivacyOptOutSchedule: vi.fn().mockResolvedValue(null),getPrivacyStatus: vi.fn().mockResolvedValue({keyConfigured: true,recordCounts: { address: 1, email: 1 },@@ -203,6 +210,16 @@ describe('Privacy Center', () => {await waitFor(() => expect(screen.getByText(/not your own/i)).toBeInTheDocument());});+ it('a broker grant made in the Household drawer clears that purpose from the Brokers warning (#8332)', async () => {+ renderAt('/privacy/brokers');+ await screen.findByText(/No active consent for broker exposure scan or broker opt-out requests/);+ fireEvent.click(screen.getByRole('button', { name: 'Manage consent' }));+ fireEvent.click(await screen.findByLabelText('Grant broker exposure scan for Me'));+ fireEvent.click(screen.getByRole('button', { name: 'Grant' }));+ await screen.findByText(/No active consent for broker opt-out requests for this person/);+ expect(screen.getByLabelText('Revoke broker exposure scan for Me')).toBeInTheDocument();+ });+it('keeps a stale ?subject deep link labeled rather than blank', async () => {renderAt('/privacy/vault?subject=deleted-subject');const select = await screen.findByLabelText('Subject');diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.jsindex 0a2d1b184e..47edf2bbde 100644--- a/client/src/services/apiPrivacy.js+++ b/client/src/services/apiPrivacy.js@@ -30,7 +30,7 @@ const scopedPost = (path, { subjectId, ...rest } = {}) => [path, {}];// ── Household subjects (#3658) ──────────────────────────────────────────────-/** All subjects, `self` first, each with `consentCount` + `recordCount`. */+/** All subjects, `self` first, each with `consentCount`, `recordCount`, and `activeScopes`. */export const getPrivacySubjects = (options) => request('/privacy/subjects', options);/** Create: { displayName, relationship?, consentMethod, consentNote? } — consent is mandatory. */export const createPrivacySubject = (data, options) => request('/privacy/subjects', {@@ -43,9 +43,23 @@ export const deletePrivacySubject = (id, options) => request(`/privacy/subjects/method: 'DELETE',...options,});-/** Consent audit trail for one subject, newest first. */+/** Consent audit trail for one subject, newest first (revoked grants carry `revokedAt`). */export const getPrivacySubjectConsents = (id, options) =>request(`/privacy/subjects/${id}/consents`, options);+/** Grant one purpose: { scope, method, note? } (#8332). */+export const grantPrivacySubjectConsent = (id, data, options) =>+ request(`/privacy/subjects/${id}/consents`, {+ method: 'POST',+ body: JSON.stringify(data),+ ...options,+ });+/** Revoke one broker purpose (`broker_scan` | `broker_optout`); the subject and records stay. */+export const revokePrivacySubjectConsent = (id, scope, options) =>+ request(`/privacy/subjects/${id}/consents/revoke`, {+ method: 'POST',+ body: JSON.stringify({ scope }),+ ...options,+ });// ── Status (doctor-style readout) ───────────────────────────────────────────export const getPrivacyStatus = (options) => request(...scoped('/privacy/status', options));diff --git a/docs/features/privacy-center.md b/docs/features/privacy-center.mdindex 1e14ee4f63..06246c9c46 100644--- a/docs/features/privacy-center.md+++ b/docs/features/privacy-center.md@@ -35,6 +35,16 @@ The **Data Brokers** module tracks exposure on data brokers, people-search sites- Direct opt-out URL shortcuts and template letters- Status verification dates and follow-up reminders+**Consent is per purpose and revocable.** Each household subject holds separate grants (Household drawer), and the scan/opt-out engines refuse — on direct calls and on the automatic recheck schedule alike — without an active grant of the exact purpose:++| Scope | Unlocks | Leaves this machine |+|---|---|---|+| `pii_vault` | Local encrypted vault storage (granted at subject creation) | Nothing |+| `broker_scan` | The read-only exposure scan | Scan-eligible name and city/state, in broker search URLs |+| `broker_optout` | Opt-out submissions and their verification re-probes | Full name, email, phone, city/state (and DOB when a broker requires it) |++A vault grant never implies a broker purpose, and a scan grant never implies submissions. Revoking a broker purpose stamps `revoked_at` on its grant rows — the subject, their vault records, and the audit trail stay — so even the undeletable `self` subject can withdraw it.+---## Security Model & Data Flow@@ -42,7 +52,7 @@ The **Data Brokers** module tracks exposure on data brokers, people-search sites```mermaidflowchart TDUser["User Interface (Settings / Privacy)"]- Vault["Vault Storage (data/vault.json)"]+ Vault["Vault Storage (Postgres privacy_vault_records)"]Crypto["AES-256-GCM Encryption (vaultCrypto.js)"]Orgs["Organizations & Changes (Postgres DB)"]Federation["Federation & Peer Sync"]diff --git a/server/lib/db/schema/privacy.js b/server/lib/db/schema/privacy.jsindex af77c625c3..3a63a68030 100644--- a/server/lib/db/schema/privacy.js+++ b/server/lib/db/schema/privacy.js@@ -81,11 +81,13 @@ export const privacyDdl = [)`,// Type is the primary list filter (all addresses, all emails, ...).`CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_records (type)`,- // Explicit consent audit rows, one per subject; the broker opt-out engine- // builds on this trail and REFUSES to act for a subject with no row here- // (privacySubjects.assertSubjectConsent, #3658). Append-only. The legacy- // free-text `subject` column is kept for the historical audit trail —- // `subject_id` is the FK the engine and every query scope on.+ // Explicit consent audit rows, one per (subject, purpose) grant; the scan+ // and opt-out engines REFUSE to act for a subject without an ACTIVE row of+ // the exact purpose scope (privacySubjects.assertSubjectConsent, #3658,+ // #8332). Rows are never deleted while the subject exists: revoking a+ // broker purpose stamps `revoked_at`, and a later re-grant appends a new+ // row. The legacy free-text `subject` column is kept for the historical+ // audit trail — `subject_id` is the FK the engine and every query scope on.`CREATE TABLE IF NOT EXISTS privacy_consents (id UUID PRIMARY KEY,subject TEXT NOT NULL DEFAULT 'self',@@ -93,7 +95,8 @@ export const privacyDdl = [scope TEXT NOT NULL,method TEXT NOT NULL,note TEXT NOT NULL DEFAULT '',- granted_at TIMESTAMPTZ DEFAULT NOW()+ granted_at TIMESTAMPTZ DEFAULT NOW(),+ revoked_at TIMESTAMPTZ)`,// ─── Privacy Center: Trusted Organizations registry (issue #2141, epic@@ -229,9 +232,16 @@ export const privacyDdl = [// Free-text context for a consent row (who witnessed it, where the signed// form lives). Added with the table's subject scope (#3658).`ALTER TABLE privacy_consents ADD COLUMN IF NOT EXISTS note TEXT NOT NULL DEFAULT ''`,+ // Purpose revocation (#8332): NULL = active grant. Additive and nullable, so+ // every pre-#8332 row reads as an unrevoked grant of its ORIGINAL scope — an+ // existing `pii_vault` row stays local-only and is never widened to a broker+ // purpose.+ `ALTER TABLE privacy_consents ADD COLUMN IF NOT EXISTS revoked_at TIMESTAMPTZ`,...subjectScopeUpgrades,- // `self` always consents — the install owner IS the self subject, so the- // engine guard must never refuse them. Written once (guarded by NOT EXISTS)+ // `self` always holds local-vault consent — the install owner IS the self+ // subject. Broker purposes (`broker_scan` / `broker_optout`) are NOT seeded,+ // even for `self`: disclosing identity to external brokers is an explicit+ // grant from the Household drawer (#8332). Written once (guarded by NOT EXISTS)// so an install that predates #3658 and never created a vault record still// has a consent row, and so re-running the DDL never appends duplicates.`INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.jsindex 00df324ec3..163bff40fc 100644--- a/server/lib/privacyValidation.js+++ b/server/lib/privacyValidation.js@@ -32,16 +32,30 @@ export const PRIVACY_SUBJECT_RELATIONSHIPS = Object.freeze([// How a subject's consent was captured. Carried verbatim from unbroker's// no-consent-no-action rule: the engine refuses to scan or submit for a subject-// without at least one consent row, so this is an audit fact, not a UI label.+// without an active consent row of that purpose's scope, so this is an audit+// fact, not a UI label.export const PRIVACY_CONSENT_METHODS = Object.freeze(['self', 'verbal', 'written', 'signed_form', 'guardian', 'power_of_attorney', 'other',]);-// Scope of a consent row. `pii_vault` is what the v1 vault-create path already-// writes; `broker_optout` narrows to the removal engine. The guard treats ANY-// row for the subject as active consent (no revocation column exists — a-// revoked subject is deleted, which hard-deletes their records).-export const PRIVACY_CONSENT_SCOPES = Object.freeze(['pii_vault', 'broker_optout']);+// Scope (purpose) of a consent row (#8332). Each purpose is granted and gated+// independently — a grant for one NEVER implies another:+// - `pii_vault` — local-only storage in the encrypted vault. Written at+// subject creation / first vault record. Discloses nothing.+// - `broker_scan` — the read-only exposure scan: scan-eligible identity+// values fill external broker search URLs.+// - `broker_optout` — the removal workflow: opt-out emails / web forms that+// SEND name, email, phone, city/state (and DOB when a+// broker requires it) to the broker, plus the verification+// re-probes of those brokers.+// The engine requires an ACTIVE (unrevoked) row of the EXACT scope before each+// purpose's work. Existing `pii_vault` rows stay local-only — never widened.+export const PRIVACY_CONSENT_SCOPES = Object.freeze(['pii_vault', 'broker_scan', 'broker_optout']);++// The external-disclosure purposes — the only scopes that can be revoked+// without deleting the subject. Revoking `pii_vault` (local storage) still+// means deleting the subject, which hard-deletes their records.+export const PRIVACY_BROKER_CONSENT_SCOPES = Object.freeze(['broker_scan', 'broker_optout']);// A subject reference on an existing input/query. Optional everywhere — omitted// means `self`, so every pre-#3658 client keeps working unchanged.@@ -81,6 +95,13 @@ export const privacySubjectConsentSchema = z.object({note: z.string().max(2000).optional(),}).strict();+// POST /api/privacy/subjects/:id/consents/revoke — withdraw one broker-processing+// purpose. Timestamps the active grant rows (audit trail kept); the subject and+// their vault records are untouched (#8332).+export const privacySubjectConsentRevokeSchema = z.object({+ scope: z.enum(PRIVACY_BROKER_CONSENT_SCOPES),+}).strict();+export const PRIVACY_VAULT_TYPES = Object.freeze(['legal_name', 'address', 'phone', 'email', 'dob','ssn', 'passport', 'drivers_license', 'financial_account', 'custom',diff --git a/server/lib/privacyValidation.mirror.test.js b/server/lib/privacyValidation.mirror.test.jsindex b4135da46c..1dd45eed46 100644--- a/server/lib/privacyValidation.mirror.test.js+++ b/server/lib/privacyValidation.mirror.test.js@@ -28,6 +28,7 @@ const MIRRORED_ENUMS = [['SUBJECT_RELATIONSHIPS', 'PRIVACY_SUBJECT_RELATIONSHIPS'],['CONSENT_METHODS', 'PRIVACY_CONSENT_METHODS'],['CONSENT_SCOPES', 'PRIVACY_CONSENT_SCOPES'],+ ['BROKER_CONSENT_PURPOSES', 'PRIVACY_BROKER_CONSENT_SCOPES'],['VAULT_TYPES', 'PRIVACY_VAULT_TYPES'],['VAULT_STATUSES', 'PRIVACY_VAULT_STATUSES'],['ORG_CATEGORIES', 'PRIVACY_ORG_CATEGORIES'],diff --git a/server/routes/privacy.js b/server/routes/privacy.jsindex d9bbf6ae6e..59f8629de1 100644--- a/server/routes/privacy.js+++ b/server/routes/privacy.js@@ -20,6 +20,7 @@ import {privacySubjectUpdateSchema,privacySubjectIdParamsSchema,privacySubjectConsentSchema,+ privacySubjectConsentRevokeSchema,privacyChangeListQuerySchema,privacySubjectScopeQuerySchema,privacyVaultCreateSchema,@@ -54,6 +55,7 @@ import {deleteSubject,listSubjectConsents,recordConsent,+ revokeConsent,assertSubject,} from '../services/privacySubjects.js';import {@@ -105,7 +107,8 @@ const router = Router();// ─── Household subjects (issue #3658) ──────────────────────────────────────// The people the Privacy Center works on behalf of. `self` is seeded and// undeletable; every other subject requires a recorded consent method at-// creation, and the scan/opt-out engines refuse to act without one.+// creation. Broker purposes are separate, revocable grants — the scan/opt-out+// engines refuse to act without an active grant of their exact scope (#8332).router.get('/subjects', asyncHandler(async (_req, res) => {res.json(await listSubjects());@@ -142,15 +145,26 @@ router.get('/subjects/:id/consents', asyncHandler(async (req, res) => {res.json(await listSubjectConsents(id));}));-// Append a further consent row (e.g. the subject later agreed to broker-// opt-outs). Append-only — there is no revoke endpoint: revoking consent means-// deleting the subject, which hard-deletes their records.+// Grant one purpose (e.g. the subject later agreed to broker scans or opt-outs).+// Appends a grant row; the scope defaults to the local-only `pii_vault`, so a+// broker purpose is only ever granted by naming it (#8332).router.post('/subjects/:id/consents', asyncHandler(async (req, res) => {const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);const { scope, method, note } = validateRequest(privacySubjectConsentSchema, req.body);res.status(201).json(await recordConsent({ subjectId: id, scope, method, note }));}));+// Withdraw one broker purpose (`broker_scan` | `broker_optout`) WITHOUT deleting+// the subject: the active grant rows get a `revoked_at` timestamp (audit trail+// kept), and every later direct or scheduled call for that purpose is refused+// by the engine gate (#8332). Local-vault consent is still withdrawn by deleting+// the subject.+router.post('/subjects/:id/consents/revoke', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);+ const { scope } = validateRequest(privacySubjectConsentRevokeSchema, req.body);+ res.json(await revokeConsent({ subjectId: id, scope }));+}));+router.get('/status', asyncHandler(async (req, res) => {const { subjectId } = validateRequest(privacySubjectScopeQuerySchema, req.query);res.json(await getVaultStatus({ subjectId }));diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsindex 35cfadb892..962b274b8a 100644--- a/server/routes/privacy.test.js+++ b/server/routes/privacy.test.js@@ -82,6 +82,7 @@ vi.mock('../services/privacySubjects.js', () => ({deleteSubject: vi.fn(async () => ({ ok: true })),listSubjectConsents: vi.fn(async () => [{ id: 'consent-1', scope: 'pii_vault', method: 'signed_form', note: '' }]),recordConsent: vi.fn(async (input) => ({ id: 'consent-2', ...input })),+ revokeConsent: vi.fn(async ({ subjectId, scope }) => ({ subjectId, scope, revoked: 1, revokedAt: '2026-01-02T00:00:00Z' })),assertSubject: vi.fn(async (id) => ({ id })),}));@@ -633,6 +634,26 @@ describe('/api/privacy/subjects', () => {expect(subjectService.recordConsent).toHaveBeenCalledWith({subjectId: VALID_UUID, scope: 'broker_optout', method: 'written', note: 'form on file',});++ const scan = await request(makeApp()).post(`/api/privacy/subjects/${VALID_UUID}/consents`)+ .send({ scope: 'broker_scan', method: 'self' });+ expect(scan.status).toBe(201);+ });++ it('revokes one broker purpose without deleting the subject (#8332)', async () => {+ const res = await request(makeApp()).post(`/api/privacy/subjects/${VALID_UUID}/consents/revoke`)+ .send({ scope: 'broker_optout' });+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ scope: 'broker_optout', revoked: 1, revokedAt: '2026-01-02T00:00:00Z' });+ expect(subjectService.revokeConsent).toHaveBeenCalledWith({ subjectId: VALID_UUID, scope: 'broker_optout' });+ expect(subjectService.deleteSubject).not.toHaveBeenCalled();++ // Local-vault consent is not revocable here, and the scope is required.+ for (const body of [{ scope: 'pii_vault' }, {}, { scope: 'broker_scan', extra: 1 }]) {+ const bad = await request(makeApp()).post(`/api/privacy/subjects/${VALID_UUID}/consents/revoke`).send(body);+ expect(bad.status).toBe(400);+ }+ expect(subjectService.revokeConsent).toHaveBeenCalledTimes(1);});});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 0a52e036aa..18f6ccaf8f 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1370,8 +1370,9 @@ CREATE TABLE IF NOT EXISTS privacy_vault_records ();-- Type is the primary list filter (all addresses, all emails, ...).CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_records (type);--- Explicit consent audit rows (v1 subject is always 'self'); the broker--- opt-out engine builds on this trail. Append-only.+-- Explicit consent audit rows, one per (subject, purpose) grant. The scan and+-- opt-out engines require an ACTIVE row of the exact purpose scope; revoking a+-- broker purpose stamps revoked_at instead of deleting the row (#8332).CREATE TABLE IF NOT EXISTS privacy_consents (id UUID PRIMARY KEY,subject TEXT NOT NULL DEFAULT 'self',@@ -1379,7 +1380,8 @@ CREATE TABLE IF NOT EXISTS privacy_consents (scope TEXT NOT NULL,method TEXT NOT NULL,note TEXT NOT NULL DEFAULT '',- granted_at TIMESTAMPTZ DEFAULT NOW()+ granted_at TIMESTAMPTZ DEFAULT NOW(),+ revoked_at TIMESTAMPTZ);-- Privacy Center: Trusted Organizations registry (issue #2141, epic #2138).@@ -1504,8 +1506,8 @@ CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_subject ON privacy_vault_reCREATE INDEX IF NOT EXISTS idx_privacy_orgs_subject ON privacy_orgs (subject_id);CREATE INDEX IF NOT EXISTS idx_privacy_change_events_subject ON privacy_change_events (subject_id);CREATE INDEX IF NOT EXISTS idx_privacy_consents_subject ON privacy_consents (subject_id);--- `self` always consents — the install owner IS the self subject, so the--- engine's no-consent-no-action guard must never refuse them (#3658).+-- `self` always holds local-vault consent — the install owner IS the self+-- subject (#3658). Broker purposes are never seeded, even for `self` (#8332).INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)SELECT gen_random_uuid(), '00000000-0000-4000-8000-000000000001', 'pii_vault', 'self','seeded: the install owner is the self subject', NOW()diff --git a/server/services/privacyBrokers.db.test.js b/server/services/privacyBrokers.db.test.jsindex 8be3af697e..2b0c2c96c8 100644--- a/server/services/privacyBrokers.db.test.js+++ b/server/services/privacyBrokers.db.test.js@@ -47,13 +47,17 @@ describe.skipIf(!runDb)('privacy brokers DB round-trip', () => {svc = await import('./privacyBrokers.js');scan = await import('./privacyScan.js');vault = await import('./privacyVault.js');+ // The scan pass needs an explicit broker_scan grant (#8332) — the seeded+ // `self` row holds only local-vault consent. Removed in afterAll.+ const subjects = await import('./privacySubjects.js');+ await subjects.recordConsent({ scope: 'broker_scan', method: 'self', note: 'privacyBrokers.db.test' });});afterAll(async () => {for (const id of createdVaultIds) {await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});}- await query(`DELETE FROM privacy_consents WHERE scope = 'pii_vault' AND granted_at >= $1`, [testStart]).catch(() => {});+ await query(`DELETE FROM privacy_consents WHERE scope IN ('pii_vault', 'broker_scan') AND granted_at >= $1`, [testStart]).catch(() => {});for (const id of autoBrokerIds) {await query(`DELETE FROM privacy_broker_cases WHERE broker_id = $1`, [id]).catch(() => {});await query(`DELETE FROM privacy_brokers WHERE id = $1`, [id]).catch(() => {});diff --git a/server/services/privacyOptOut.db.test.js b/server/services/privacyOptOut.db.test.jsindex ef345a031a..324993cc6f 100644--- a/server/services/privacyOptOut.db.test.js+++ b/server/services/privacyOptOut.db.test.js@@ -41,6 +41,7 @@ describe.skipIf(!runDb)('privacy opt-out engine DB round-trip', () => {const brokerId = 'test-optout-broker';const emailBrokerId = 'test-optout-email';const createdVaultIds = [];+ let optOutGrantId = null;const account = { id: 'acct-test', type: 'gmail' };const injectedAccounts = async () => [account];@@ -52,6 +53,10 @@ describe.skipIf(!runDb)('privacy opt-out engine DB round-trip', () => {svc = await import('./privacyOptOut.js');brokers = await import('./privacyBrokers.js');vault = await import('./privacyVault.js');+ // The removal workflow needs an explicit broker_optout grant (#8332) — the+ // seeded `self` row holds only local-vault consent. Removed in afterAll.+ const subjects = await import('./privacySubjects.js');+ optOutGrantId = (await subjects.recordConsent({ scope: 'broker_optout', method: 'self', note: 'privacyOptOut.db.test' })).id;// Clean slate for cases so cross-suite ordering can't leak state in.await query(`DELETE FROM privacy_broker_cases`).catch(() => {});// A web-form broker + an email broker, inserted directly (auto source so the@@ -75,6 +80,7 @@ describe.skipIf(!runDb)('privacy opt-out engine DB round-trip', () => {afterAll(async () => {for (const id of createdVaultIds) await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});+ if (optOutGrantId) await query(`DELETE FROM privacy_consents WHERE id = $1`, [optOutGrantId]).catch(() => {});await query(`DELETE FROM privacy_broker_cases WHERE broker_id = ANY($1)`, [[brokerId, emailBrokerId]]).catch(() => {});await query(`DELETE FROM privacy_brokers WHERE id = ANY($1)`, [[brokerId, emailBrokerId]]).catch(() => {});await close();diff --git a/server/services/privacyOptOut.js b/server/services/privacyOptOut.jsindex 2ab15c5ad6..b41828b91a 100644--- a/server/services/privacyOptOut.js+++ b/server/services/privacyOptOut.js@@ -21,8 +21,10 @@** HARD GUARDRAILS (autonomy never overrides — mirrors unbroker):* - NO CONSENT, NO ACTION. `runOptOutPass` / `runVerificationPass` refuse to- * act for a subject with no recorded consent row- * (privacySubjects.assertSubjectConsent, #3658). Like the disclosure+ * act for a subject without an ACTIVE `broker_optout` grant+ * (privacySubjects.assertSubjectConsent, #3658/#8332) — neither the+ * local-only `pii_vault` grant nor the read-only `broker_scan` grant+ * unlocks a submission or its verification probes. Like the disclosure* allowlist below, the guard lives in the SERVICE — a scheduled recheck, a* direct API call, or a future agent path is refused exactly like a hidden* UI button would be.@@ -411,10 +413,11 @@ export async function runVerificationPass({now = new Date(), messagesProvider = getMessages, removalProbe = probeBroker, probeDeps = {},subjectId, maxVerificationRechecks = DEFAULT_MAX_VERIFICATION_RECHECKS,} = {}) {- // CONSENT GATE — the verification pass re-probes brokers for the subject, so- // it is gated exactly like the submission pass.+ // CONSENT GATE — the verification pass re-probes brokers for the subject as+ // part of the removal workflow, so it is gated on `broker_optout` exactly+ // like the submission pass.const resolvedSubjectId = resolveSubjectId(subjectId);- await assertSubjectConsent(resolvedSubjectId, { action: 'opt-out verification pass' });+ await assertSubjectConsent(resolvedSubjectId, { scope: 'broker_optout', action: 'opt-out verification pass' });const cases = await listBrokerCases({ subjectId: resolvedSubjectId });const advanced = [];const confirmed = [];@@ -494,10 +497,10 @@ export async function runOptOutPass({now = new Date(), settingsProvider = getSettings, deps = {}, runVerification = true, subjectId,} = {}) {// CONSENT GATE — BEFORE any vault read, broker fetch, or draft creation. NO- // CONSENT, NO ACTION: a subject without a recorded consent row is refused- // (403) here in the service, not merely in the UI.+ // CONSENT, NO ACTION: a subject without an active `broker_optout` grant is+ // refused (403) here in the service, not merely in the UI.const resolvedSubjectId = resolveSubjectId(subjectId);- await assertSubjectConsent(resolvedSubjectId, { action: 'broker opt-out pass' });+ await assertSubjectConsent(resolvedSubjectId, { scope: 'broker_optout', action: 'broker opt-out pass' });const settings = await settingsProvider();const recheck = settings?.privacy?.recheck || {};const autoApprove = recheck.autoApproveOptOutEmails === true;diff --git a/server/services/privacyOptOut.test.js b/server/services/privacyOptOut.test.jsindex 0c15437e1d..2a314585ff 100644--- a/server/services/privacyOptOut.test.js+++ b/server/services/privacyOptOut.test.js@@ -357,9 +357,13 @@ describe('getOptOutDigest', () => {// NO CONSENT, NO ACTION — carried verbatim from unbroker. The refusal is at the// SERVICE layer, so a cron / direct API / agent caller is refused exactly like a// hidden UI button would be. Asserted here, NOT only in a UI test.-describe('consent gate — engine-enforced (#3658)', () => {+describe('consent gate — engine-enforced (#3658, #8332)', () => {+ // Scope-aware stand-in for the real gate: the subject holds the local-vault+ // AND read-only scan grants but NOT broker_optout — neither may unlock a+ // submission or its verification probes.const refuse = () => {- assertSubjectConsentMock.mockImplementation(async () => {+ assertSubjectConsentMock.mockImplementation(async (id, { scope }) => {+ if (scope === 'pii_vault' || scope === 'broker_scan') return { id };const err = new Error('no consent');err.status = 403;err.code = 'SUBJECT_CONSENT_REQUIRED';@@ -367,7 +371,7 @@ describe('consent gate — engine-enforced (#3658)', () => {});};- it('runOptOutPass refuses a subject with no consent, before reading the vault', async () => {+ it('runOptOutPass refuses a subject without broker_optout consent, before reading the vault', async () => {refuse();const vault = await import('./privacyVault.js');await expect(runOptOutPass({ subjectId: 'subject-2' }))@@ -378,7 +382,7 @@ describe('consent gate — engine-enforced (#3658)', () => {expect(createDraft).not.toHaveBeenCalled();});- it('runVerificationPass refuses a subject with no consent, before reading the ledger', async () => {+ it('runVerificationPass refuses a subject without broker_optout consent, before reading the ledger', async () => {refuse();await expect(runVerificationPass({ subjectId: 'subject-2' })).rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });@@ -389,7 +393,7 @@ describe('consent gate — engine-enforced (#3658)', () => {it('passes the resolved subject through to the guard and the ledger reads', async () => {listBrokerCases.mockResolvedValue([]);await runVerificationPass({ subjectId: 'subject-2' });- expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { action: 'opt-out verification pass' });+ expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { scope: 'broker_optout', action: 'opt-out verification pass' });expect(listBrokerCases).toHaveBeenCalledWith({ subjectId: 'subject-2' });});});diff --git a/server/services/privacyRecheckScheduler.js b/server/services/privacyRecheckScheduler.jsindex aea3811978..95d927a5ef 100644--- a/server/services/privacyRecheckScheduler.js+++ b/server/services/privacyRecheckScheduler.js@@ -46,25 +46,7 @@ export async function startPrivacyRecheckScheduler() {console.log('🛡️ Privacy recheck: disabled since registration — skipping run');return;}- // Run for EVERY consenting subject, not just `self` — a household member- // added to the Privacy Center gets the same scheduled upkeep (#3658). A- // subject with no consent row is skipped here (the engines would refuse- // them anyway); one subject's failure must not abort the others, and this- // handler runs OUTSIDE the request lifecycle, so the per-subject try/catch- // is the sanctioned exception to the no-try/catch rule.- const subjects = await listSubjects();- const consenting = subjects.filter((s) => (s.consentCount ?? 0) > 0);- console.log(`🛡️ Privacy recheck: running scheduled scan + opt-out pass for ${consenting.length} consenting subject(s)`);- for (const subject of consenting) {- try {- // Scan first (re-checks due cases + finds new exposure), then work the- // cases. Both are settings-driven and safe to re-run (idempotent).- await runScanPass({ subjectId: subject.id });- await runOptOutPass({ subjectId: subject.id });- } catch (err) {- console.error(`❌ Privacy recheck failed for subject ${subject.id}: ${err.message}`);- }- }+ await runScheduledRecheck();},metadata: { source: 'privacyRecheckScheduler' },});@@ -72,6 +54,40 @@ export async function startPrivacyRecheckScheduler() {console.log(`🛡️ Privacy recheck scheduler: registered at cron "${cronExpression}"`);}+// Each scheduled purpose, in run order: scan first (re-checks due cases + finds+// new exposure), then work the cases. Both passes are settings-driven and safe+// to re-run (idempotent).+const SCHEDULED_PURPOSES = [+ { scope: 'broker_scan', label: 'scan', run: runScanPass },+ { scope: 'broker_optout', label: 'opt-out', run: runOptOutPass },+];++/**+ * One scheduled recheck over every subject, not just `self` — a household+ * member gets the same upkeep (#3658). Subjects are selected PER PURPOSE from+ * their active grants (#8332): a `broker_scan`-only subject is scanned but+ * never submitted, a `pii_vault`-only (or fully revoked) subject gets neither.+ * The engines re-check the grant themselves, so a revocation racing this loop+ * is still refused. One subject's or purpose's failure must not abort the+ * others, and this runs OUTSIDE the request lifecycle, so the per-pass+ * try/catch is the sanctioned exception to the no-try/catch rule.+ * Exported for tests; the cron handler calls it after the enabled check.+ */+export async function runScheduledRecheck() {+ const subjects = await listSubjects();+ for (const { scope, label, run } of SCHEDULED_PURPOSES) {+ const granted = subjects.filter((s) => (s.activeScopes ?? []).includes(scope));+ console.log(`🛡️ Privacy recheck: ${label} pass for ${granted.length}/${subjects.length} subject(s) with active ${scope} consent`);+ for (const subject of granted) {+ try {+ await run({ subjectId: subject.id });+ } catch (err) {+ console.error(`❌ Privacy recheck ${label} failed for subject ${subject.id}: ${err.message}`);+ }+ }+ }+}+export function stopPrivacyRecheckScheduler() {cancel(EVENT_ID);console.log('🛡️ Privacy recheck scheduler: stopped');diff --git a/server/services/privacyRecheckScheduler.test.js b/server/services/privacyRecheckScheduler.test.jsnew file mode 100644index 0000000000..2c339a81f8--- /dev/null+++ b/server/services/privacyRecheckScheduler.test.js@@ -0,0 +1,54 @@+/**+ * Scheduled broker recheck — per-purpose subject selection (#8332).+ *+ * The scheduled run is the unattended path, so it is where a too-broad consent+ * check would disclose without anyone clicking anything. Pins that each pass+ * runs ONLY for subjects holding an active grant of that exact purpose: a+ * local-vault-only (or revoked) subject gets neither pass, and a scan-only+ * grant never triggers the submission pass.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const { listSubjectsMock, runScanPassMock, runOptOutPassMock } = vi.hoisted(() => ({+ listSubjectsMock: vi.fn(),+ runScanPassMock: vi.fn(async () => ({})),+ runOptOutPassMock: vi.fn(async () => ({})),+}));++vi.mock('./privacySubjects.js', () => ({ listSubjects: listSubjectsMock }));+vi.mock('./privacyScan.js', () => ({ runScanPass: runScanPassMock }));+vi.mock('./privacyOptOut.js', () => ({ runOptOutPass: runOptOutPassMock }));+vi.mock('./eventScheduler.js', () => ({ schedule: vi.fn(), cancel: vi.fn(), parseCronToNextRun: vi.fn() }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+vi.mock('./userTimezone.js', () => ({ getUserTimezone: vi.fn(async () => 'UTC') }));++const { runScheduledRecheck } = await import('./privacyRecheckScheduler.js');++const ranFor = (mock) => mock.mock.calls.map(([arg]) => arg.subjectId);++beforeEach(() => {+ vi.clearAllMocks();+ listSubjectsMock.mockResolvedValue([+ { id: 'vault-only', activeScopes: ['pii_vault'] },+ { id: 'scan-only', activeScopes: ['broker_scan', 'pii_vault'] },+ { id: 'both', activeScopes: ['broker_optout', 'broker_scan', 'pii_vault'] },+ // Revoked grants are excluded from activeScopes by listSubjects.+ { id: 'revoked', activeScopes: [] },+ ]);+});++describe('runScheduledRecheck', () => {+ it('selects subjects per purpose from their active grants', async () => {+ await runScheduledRecheck();+ expect(ranFor(runScanPassMock)).toEqual(['scan-only', 'both']);+ expect(ranFor(runOptOutPassMock)).toEqual(['both']);+ });++ it("one subject's failed pass does not stop the other purpose or subjects", async () => {+ runScanPassMock.mockRejectedValueOnce(new Error('broker down'));+ await runScheduledRecheck();+ expect(ranFor(runScanPassMock)).toEqual(['scan-only', 'both']);+ expect(ranFor(runOptOutPassMock)).toEqual(['both']);+ });+});diff --git a/server/services/privacyScan.js b/server/services/privacyScan.jsindex 41b26f4669..6af0198cbe 100644--- a/server/services/privacyScan.js+++ b/server/services/privacyScan.js@@ -12,10 +12,12 @@* render static HTML), escalating to the SSRF-pinned real-Chrome fetch* (`fetchUrlMainText`) only when the page needs JS. Both lanes are SSRF-vetted.*- * CONSENT: `runScanPass` refuses to probe ANY broker for a subject without a- * recorded consent row (privacySubjects.assertSubjectConsent) — the guard lives- * in the service, not the UI, so a scheduled recheck or a direct API call is- * refused exactly like a hidden button would be (#3658).+ * CONSENT: `runScanPass` / `scanBroker` refuse to probe ANY broker for a+ * subject without an ACTIVE `broker_scan` grant (privacySubjects.+ * assertSubjectConsent, #3658/#8332) — a local-only `pii_vault` grant does not+ * count, because the scan puts identity values into external broker URLs. The+ * guard lives in the service, not the UI, so a scheduled recheck or a direct API+ * call is refused exactly like a hidden button would be.** AI policy: this whole pass runs ONLY from a user-triggered endpoint or a* user-created cron (never at boot). LLM-assisted namesake disambiguation, if@@ -309,7 +311,7 @@ export async function scanBroker(broker, vectors, {subjectId,} = {}) {const resolvedSubjectId = resolveSubjectId(subjectId);- await assertSubjectConsent(resolvedSubjectId, { action: `broker exposure scan (${broker?.id})` });+ await assertSubjectConsent(resolvedSubjectId, { scope: 'broker_scan', action: `broker exposure scan (${broker?.id})` });const probed = await probeBroker(broker, vectors, { fetchImpl, browserFetch, urlSafe });if (probed.skipped) return { skipped: true, reason: probed.reason };const kase = await recordScanVerdict(broker.id, probed.verdict, {@@ -326,11 +328,12 @@ export async function scanBroker(broker, vectors, {* Returns a summary { scanned, verdicts: {<verdict>: n}, skipped, brokers }.*/export async function runScanPass({ concurrency = 3, fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(), subjectId } = {}) {- // CONSENT GATE — BEFORE any vault read or broker fetch. A subject with no- // consent row on file is refused outright (403); the UI hiding the Scan button- // is not sufficient, since a cron/API/agent caller reaches this same function.+ // CONSENT GATE — BEFORE any vault read or broker fetch. A subject without an+ // active `broker_scan` grant is refused outright (403); the UI hiding the Scan+ // button is not sufficient, since a cron/API/agent caller reaches this same+ // function.const resolvedSubjectId = resolveSubjectId(subjectId);- await assertSubjectConsent(resolvedSubjectId, { action: 'broker exposure scan' });+ await assertSubjectConsent(resolvedSubjectId, { scope: 'broker_scan', action: 'broker exposure scan' });const scanValues = await listScanEligibleValues({ subjectId: resolvedSubjectId });const vectors = buildSearchVectors(scanValues);if ((vectors.names || []).length === 0) {diff --git a/server/services/privacyScan.test.js b/server/services/privacyScan.test.jsindex 0eb921d388..9363856238 100644--- a/server/services/privacyScan.test.js+++ b/server/services/privacyScan.test.js@@ -212,9 +212,12 @@ describe('scanBroker — classify → record wiring', () => {// NO CONSENT, NO ACTION. The scan pass must refuse a subject with no consent row// BEFORE it decrypts a single vault value or fetches a single broker page — the// refusal lives in the service, not in the UI that hides the Scan button.-describe('runScanPass consent gate — engine-enforced (#3658)', () => {- it('refuses a subject with no consent, before reading the vault', async () => {- assertSubjectConsentMock.mockImplementationOnce(async () => {+describe('runScanPass consent gate — engine-enforced (#3658, #8332)', () => {+ it('refuses a subject without broker_scan consent (e.g. pii_vault only), before reading the vault', async () => {+ // Scope-aware stand-in for the real gate: this subject holds ONLY the+ // local-vault grant, so any broker purpose is refused.+ assertSubjectConsentMock.mockImplementationOnce(async (id, { scope }) => {+ if (scope === 'pii_vault') return { id };const err = new Error('no consent');err.status = 403;err.code = 'SUBJECT_CONSENT_REQUIRED';@@ -228,12 +231,31 @@ describe('runScanPass consent gate — engine-enforced (#3658)', () => {expect(brokers.recordScanVerdict).not.toHaveBeenCalled();});+ it('scanBroker refuses a direct single-broker call without broker_scan consent, before any fetch', async () => {+ assertSubjectConsentMock.mockImplementationOnce(async () => {+ const err = new Error('no consent');+ err.status = 403;+ err.code = 'SUBJECT_CONSENT_REQUIRED';+ throw err;+ });+ const fetchImpl = vi.fn();+ const browserFetch = vi.fn();+ const broker = { id: 'b1', search: { url_template: 'https://broker.example.com/{firstName}-{lastName}' } };+ await expect(scanBroker(broker, { names: [{ full: 'Jane Doe', firstName: 'Jane', lastName: 'Doe' }], locations: [] }, {+ fetchImpl, browserFetch, urlSafe: async () => true, subjectId: 'subject-2',+ })).rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });+ expect(assertSubjectConsentMock).toHaveBeenLastCalledWith('subject-2', expect.objectContaining({ scope: 'broker_scan' }));+ expect(fetchImpl).not.toHaveBeenCalled();+ expect(browserFetch).not.toHaveBeenCalled();+ expect(brokers.recordScanVerdict).not.toHaveBeenCalled();+ });+it('checks consent for the resolved subject and scopes the vault read to it', async () => {const vault = await import('./privacyVault.js');vault.listScanEligibleValues.mockClear();vault.listScanEligibleValues.mockResolvedValue([]);const result = await runScanPass({ subjectId: 'subject-2' });- expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { action: 'broker exposure scan' });+ expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { scope: 'broker_scan', action: 'broker exposure scan' });expect(vault.listScanEligibleValues).toHaveBeenCalledWith({ subjectId: 'subject-2' });// No name vector ⇒ the pass short-circuits without touching a broker.expect(result.reason).toBe('no_scan_vectors');diff --git a/server/services/privacySubjects.db.test.js b/server/services/privacySubjects.db.test.jsindex 352a99bfff..52bb74aa4f 100644--- a/server/services/privacySubjects.db.test.js+++ b/server/services/privacySubjects.db.test.js@@ -97,7 +97,10 @@ describe.skipIf(!runDb)('privacy household subjects DB round-trip', () => {expect(consents[0]).toMatchObject({subjectId: subject.id, scope: 'pii_vault', method: 'signed_form', note: 'form filed',});- expect(await subjects.hasActiveConsent(subject.id)).toBe(true);+ expect(await subjects.hasActiveConsent(subject.id, 'pii_vault')).toBe(true);+ // Creation grants local-vault use only — never a broker purpose (#8332).+ expect(await subjects.hasActiveConsent(subject.id, 'broker_scan')).toBe(false);+ expect(await subjects.hasActiveConsent(subject.id, 'broker_optout')).toBe(false);});it('reports consent and record counts on the list', async () => {@@ -109,7 +112,7 @@ describe.skipIf(!runDb)('privacy household subjects DB round-trip', () => {});const row = (await subjects.listSubjects()).find((s) => s.id === subject.id);- expect(row).toMatchObject({ consentCount: 1, recordCount: 1 });+ expect(row).toMatchObject({ consentCount: 1, recordCount: 1, activeScopes: ['pii_vault'] });});it('renames without disturbing consent', async () => {@@ -149,21 +152,37 @@ describe.skipIf(!runDb)('privacy household subjects DB round-trip', () => {});});- it('refuses engine actions for a subject whose consent was revoked', async () => {+ it('gates each broker purpose on its own grant and revokes without losing the subject (#8332)', async () => {const subject = track(await subjects.createSubject({displayName: 'Example Revoked', relationship: 'other', consentMethod: 'verbal',}));- // Consent granted → the engine guard lets the action through.- await expect(subjects.assertSubjectConsent(subject.id, { action: 'scan' }))- .resolves.toMatchObject({ id: subject.id });-- await query(`DELETE FROM privacy_consents WHERE subject_id = $1`, [subject.id]);-- expect(await subjects.hasActiveConsent(subject.id)).toBe(false);- await expect(subjects.assertSubjectConsent(subject.id, { action: 'scan' })).rejects.toMatchObject({- status: 403,- code: 'SUBJECT_CONSENT_REQUIRED',+ await vault.createVaultRecord({+ type: 'email', label: 'Their email', value: '[email protected]', subjectId: subject.id,});+ // Vault-only consent → both broker purposes refused.+ await expect(subjects.assertSubjectConsent(subject.id, { scope: 'broker_scan', action: 'scan' }))+ .rejects.toMatchObject({ status: 403, code: 'SUBJECT_CONSENT_REQUIRED' });++ await subjects.recordConsent({ subjectId: subject.id, scope: 'broker_scan', method: 'written' });+ await expect(subjects.assertSubjectConsent(subject.id, { scope: 'broker_scan', action: 'scan' }))+ .resolves.toMatchObject({ id: subject.id });+ // A scan grant does not unlock submissions.+ await expect(subjects.assertSubjectConsent(subject.id, { scope: 'broker_optout', action: 'opt-out' }))+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });++ const revoked = await subjects.revokeConsent({ subjectId: subject.id, scope: 'broker_scan' });+ expect(revoked).toMatchObject({ revoked: 1 });+ expect(revoked.revokedAt).toBeTruthy();+ await expect(subjects.assertSubjectConsent(subject.id, { scope: 'broker_scan', action: 'scan' }))+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });++ // The subject, their vault record, and the timestamped grant all survive.+ await expect(subjects.getSubject(subject.id)).resolves.toMatchObject({ id: subject.id });+ const row = (await subjects.listSubjects()).find((s) => s.id === subject.id);+ expect(row).toMatchObject({ recordCount: 1, activeScopes: ['pii_vault'] });+ const trail = await subjects.listSubjectConsents(subject.id);+ expect(trail.find((c) => c.scope === 'broker_scan').revokedAt).toBeTruthy();+ expect(trail.find((c) => c.scope === 'pii_vault').revokedAt).toBeNull();});it('deleting a subject cascades their consent rows', async () => {diff --git a/server/services/privacySubjects.js b/server/services/privacySubjects.jsindex dbf3e6874e..de1c3f70bb 100644--- a/server/services/privacySubjects.js+++ b/server/services/privacySubjects.js@@ -13,12 +13,18 @@* subject is a hard DELETE that CASCADES their vault records, orgs, holdings,* change events, broker cases, and consent rows.*- * CONSENT IS ENGINE-ENFORCED, NOT UI-ENFORCED. Carried verbatim from unbroker's- * no-consent-no-action rule: `assertSubjectConsent()` is called by- * `privacyScan.runScanPass()` and `privacyOptOut.runOptOutPass()` /- * `runVerificationPass()` before either touches a broker. Hiding the button in- * the UI is NOT sufficient — a scheduled recheck, a direct API call, or a future- * agent path all route through the service, which is where the refusal lives.+ * CONSENT IS ENGINE-ENFORCED, NOT UI-ENFORCED, AND PURPOSE-SCOPED (#8332).+ * Carried verbatim from unbroker's no-consent-no-action rule:+ * `assertSubjectConsent(id, { scope })` is called with `broker_scan` by+ * `privacyScan.runScanPass()` / `scanBroker()` and with `broker_optout` by+ * `privacyOptOut.runOptOutPass()` / `runVerificationPass()` before either+ * touches a broker. Only an ACTIVE (unrevoked) grant of that EXACT scope passes —+ * the local-only `pii_vault` grant never unlocks external disclosure. Hiding the+ * button in the UI is NOT sufficient — a scheduled recheck, a direct API call, or+ * a future agent path all route through the service, which is where the refusal+ * lives. Broker purposes are revocable (`revokeConsent`) without deleting the+ * subject; the revocation is a timestamp on the grant row, so the audit trail+ * survives.** Log lines never carry a subject's `display_name` — a household member's name* is PII in exactly the way the vault's values are (see privacyVault.js's@@ -28,7 +34,9 @@import { randomUUID } from 'crypto';import { query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';-import { PRIVACY_SELF_SUBJECT_ID } from '../lib/privacyValidation.js';+import {+ PRIVACY_SELF_SUBJECT_ID, PRIVACY_CONSENT_SCOPES, PRIVACY_BROKER_CONSENT_SCOPES,+} from '../lib/privacyValidation.js';const SUBJECT_COLUMNS = `id, display_name, relationship, created_at, updated_at`;@@ -44,6 +52,8 @@ function rowToSubject(row) {// Present only on the aggregate list query....(row.consent_count !== undefined ? { consentCount: row.consent_count } : {}),...(row.record_count !== undefined ? { recordCount: row.record_count } : {}),+ // The purposes with an ACTIVE grant — what the scheduler and the UI gate on.+ ...(row.active_scopes !== undefined ? { activeScopes: row.active_scopes } : {}),};}@@ -60,9 +70,13 @@ export function resolveSubjectId(subjectId) {}/**- * Write a consent row for a subject. Append-only audit trail. Asserts the- * subject first so an unknown id is a clean 404 rather than a raw FK violation,- * and defaults `scope` (the column is NOT NULL and the API leaves it optional).+ * Grant one purpose (`scope`) for a subject by appending a consent row. Rows+ * are never deleted while the subject exists — a revocation stamps+ * `revoked_at` (revokeConsent) and a re-grant appends a fresh row, so the trail+ * reads as a history. Asserts the subject first so an unknown id is a clean 404+ * rather than a raw FK violation, and defaults `scope` to the local-only+ * `pii_vault` (the column is NOT NULL and the API leaves it optional) — a+ * broker purpose is only ever granted by naming it.*/export async function recordConsent({ subjectId, scope, method, note }) {const resolved = (await assertSubject(subjectId)).id;@@ -81,14 +95,17 @@ export async function recordConsent({ subjectId, scope, method, note }) {// ─── Subject CRUD ───────────────────────────────────────────────────────────/**- * List every subject with their consent-row count and vault-record count, so- * the UI switcher can badge a subject that has no consent on file (and would- * therefore be refused by the engine).+ * List every subject with their consent-row count, vault-record count, and the+ * purposes they have an ACTIVE grant for (`activeScopes`, sorted), so the UI+ * can show which broker purposes the engine would refuse and the scheduler can+ * pick subjects per purpose.*/export async function listSubjects() {const { rows } = await query(`SELECT s.id, s.display_name, s.relationship, s.created_at, s.updated_at,(SELECT COUNT(*)::int FROM privacy_consents c WHERE c.subject_id = s.id) AS consent_count,+ (SELECT COALESCE(array_agg(DISTINCT c.scope ORDER BY c.scope), '{}'::text[])+ FROM privacy_consents c WHERE c.subject_id = s.id AND c.revoked_at IS NULL) AS active_scopes,(SELECT COUNT(*)::int FROM privacy_vault_records v WHERE v.subject_id = s.id) AS record_countFROM privacy_subjects sORDER BY (s.id <> $1), s.display_name ASC`,@@ -187,11 +204,11 @@ export async function deleteSubject(id) {// ─── Consent gate (engine-enforced) ─────────────────────────────────────────-/** The consent audit trail for one subject, newest first. */+/** The consent audit trail for one subject, newest first (revoked rows included). */export async function listSubjectConsents(subjectId) {const resolved = resolveSubjectId(subjectId);const { rows } = await query(- `SELECT id, subject_id, scope, method, note, granted_at+ `SELECT id, subject_id, scope, method, note, granted_at, revoked_atFROM privacy_consents WHERE subject_id = $1 ORDER BY granted_at DESC`,[resolved],);@@ -202,39 +219,84 @@ export async function listSubjectConsents(subjectId) {method: row.method,note: row.note ?? '',grantedAt: row.granted_at,+ revokedAt: row.revoked_at ?? null,}));}+// A gate call without a known scope is a programming error, never "any consent"+// — the pre-#8332 unscoped check is exactly what let a local-vault grant+// through to a broker. Fail loudly instead of guessing a purpose.+function assertKnownScope(scope) {+ if (!PRIVACY_CONSENT_SCOPES.includes(scope)) {+ throw new ServerError(`Unknown privacy consent scope: ${scope}`, { status: 500, code: 'CONSENT_SCOPE_INVALID' });+ }+}+/**- * Does this subject have active consent on file? ANY consent row counts — there- * is no revocation column, because revoking consent means deleting the subject- * (which hard-deletes their records; see deleteSubject). Callers that need a- * hard stop use assertSubjectConsent instead.+ * Does this subject hold an ACTIVE (unrevoked) grant for exactly `scope`? A+ * grant for a different purpose never counts — `pii_vault` (local storage)+ * does not imply `broker_scan`, and `broker_scan` does not imply+ * `broker_optout`. Callers that need a hard stop use assertSubjectConsent.*/-export async function hasActiveConsent(subjectId) {+export async function hasActiveConsent(subjectId, scope) {+ assertKnownScope(scope);const resolved = resolveSubjectId(subjectId);const { rows } = await query(- `SELECT 1 FROM privacy_consents WHERE subject_id = $1 LIMIT 1`, [resolved],+ `SELECT 1 FROM privacy_consents+ WHERE subject_id = $1 AND scope = $2 AND revoked_at IS NULL LIMIT 1`,+ [resolved, scope],);return rows.length > 0;}/**- * THE consent guard. `privacyScan` and `privacyOptOut` call this before any- * broker work — a subject with no consent row on file gets a hard refusal, at- * the SERVICE layer, so a scheduled recheck / direct API call / future agent+ * Withdraw one broker-processing purpose for a subject (#8332). Stamps+ * `revoked_at` on every active grant of that scope — the rows stay, so the+ * audit trail shows when consent was given and when it was withdrawn, and the+ * subject, their vault records, and their other purposes are untouched. The+ * next direct or scheduled call for that purpose is refused by the gate.+ *+ * Only broker scopes are revocable here; withdrawing local-vault consent still+ * means deleting the subject. Idempotent: revoking an already-inactive purpose+ * returns `revoked: 0`.+ */+export async function revokeConsent({ subjectId, scope }) {+ if (!PRIVACY_BROKER_CONSENT_SCOPES.includes(scope)) {+ throw new ServerError(+ `Consent scope ${scope} cannot be revoked — only broker purposes are revocable`,+ { status: 400, code: 'CONSENT_SCOPE_NOT_REVOCABLE' },+ );+ }+ const resolved = (await assertSubject(subjectId)).id;+ const { rows } = await query(+ `UPDATE privacy_consents SET revoked_at = NOW()+ WHERE subject_id = $1 AND scope = $2 AND revoked_at IS NULL+ RETURNING revoked_at`,+ [resolved, scope],+ );+ const revokedAt = rows[0]?.revoked_at ?? null;+ console.log(`🚫 Revoked privacy consent (subject=${resolved}, scope=${scope}, rows=${rows.length})`);+ return { subjectId: resolved, scope, revoked: rows.length, revokedAt };+}++/**+ * THE consent guard. `privacyScan` (scope `broker_scan`) and `privacyOptOut`+ * (scope `broker_optout`) call this before any vault read or broker contact —+ * a subject without an ACTIVE grant of that exact purpose gets a hard refusal,+ * at the SERVICE layer, so a scheduled recheck / direct API call / future agent* path is refused exactly like a UI click would be. Mirrors the existing* disclosure-allowlist guard in privacyOptOut.js: the engine's guarantees do not- * live in the UI.+ * live in the UI. `scope` is REQUIRED — there is no "any consent" mode.** Returns the subject row so callers can log/annotate without a second read.*/-export async function assertSubjectConsent(subjectId, { action = 'this action' } = {}) {+export async function assertSubjectConsent(subjectId, { scope, action = 'this action' } = {}) {+ assertKnownScope(scope);const subject = await assertSubject(subjectId);- if (await hasActiveConsent(subject.id)) return subject;- console.warn(`⛔ Refused ${action} for privacy subject ${subject.id}: no consent on file`);+ if (await hasActiveConsent(subject.id, scope)) return subject;+ console.warn(`⛔ Refused ${action} for privacy subject ${subject.id}: no active ${scope} consent`);throw new ServerError(- `Privacy subject ${subject.id} has no recorded consent — ${action} refused`,- { status: 403, code: 'SUBJECT_CONSENT_REQUIRED' },+ `Privacy subject ${subject.id} has no active ${scope} consent — ${action} refused`,+ { status: 403, code: 'SUBJECT_CONSENT_REQUIRED', context: { scope } },);}diff --git a/server/services/privacySubjects.test.js b/server/services/privacySubjects.test.jsindex 5b91d2a92d..30fc9ded03 100644--- a/server/services/privacySubjects.test.js+++ b/server/services/privacySubjects.test.js@@ -6,8 +6,12 @@* pre-#3658 caller keeps its old behaviour.* - subject creation writes the consent row in the SAME transaction, so a* subject can never exist without recorded consent.- * - `assertSubjectConsent` REFUSES (403) a subject with no consent row — the- * engine-enforced half of the no-consent-no-action rule.+ * - `assertSubjectConsent` REFUSES (403) a subject without an ACTIVE grant of+ * the EXACT purpose scope — the engine-enforced half of the+ * no-consent-no-action rule (#8332: a `pii_vault` grant never unlocks a+ * broker purpose, and a revoked grant never counts).+ * - `revokeConsent` withdraws one broker purpose by timestamping its grant+ * rows — never by deleting them or the subject.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -22,6 +26,7 @@ vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: withTransactconst {resolveSubjectId, createSubject, updateSubject, deleteSubject,listSubjects, assertSubject, hasActiveConsent, assertSubjectConsent, recordConsent,+ revokeConsent,} = await import('./privacySubjects.js');const { PRIVACY_SELF_SUBJECT_ID } = await import('../lib/privacyValidation.js');@@ -132,14 +137,16 @@ describe('listSubjects', () => {it('returns `self` first and carries consent/record counts for the UI switcher', async () => {queryMock.mockResolvedValue({rows: [- { ...subjectRow(), consent_count: 1, record_count: 4 },- { ...subjectRow({ id: 's2', display_name: 'Alex Example', relationship: 'partner' }), consent_count: 0, record_count: 0 },+ { ...subjectRow(), consent_count: 1, record_count: 4, active_scopes: ['broker_scan', 'pii_vault'] },+ { ...subjectRow({ id: 's2', display_name: 'Alex Example', relationship: 'partner' }), consent_count: 0, record_count: 0, active_scopes: [] },],});const subjects = await listSubjects();expect(subjects[0].isSelf).toBe(true);- expect(subjects[0]).toMatchObject({ consentCount: 1, recordCount: 4 });- expect(subjects[1]).toMatchObject({ isSelf: false, consentCount: 0 });+ expect(subjects[0]).toMatchObject({ consentCount: 1, recordCount: 4, activeScopes: ['broker_scan', 'pii_vault'] });+ expect(subjects[1]).toMatchObject({ isSelf: false, consentCount: 0, activeScopes: [] });+ // Active purposes exclude revoked grants — what the scheduler selects on.+ expect(queryMock.mock.calls[0][0]).toMatch(/revoked_at IS NULL\) AS active_scopes/);// The ORDER BY must put `self` first regardless of display name.expect(queryMock.mock.calls[0][0]).toMatch(/ORDER BY \(s\.id <> \$1\)/);});@@ -179,36 +186,83 @@ describe('recordConsent', () => {});});-describe('consent gate', () => {- it('hasActiveConsent is true when ANY consent row exists for the subject', async () => {- queryMock.mockResolvedValue({ rows: [{ '?column?': 1 }] });- expect(await hasActiveConsent('s2')).toBe(true);- expect(queryMock.mock.calls[0][1]).toEqual(['s2']);+describe('consent gate — purpose-scoped (#8332)', () => {+ // A fake consent table the mocked query() answers from, so the assertions+ // exercise the real SQL predicates' parameters rather than a canned boolean.+ const useConsentRows = (rows) => {+ queryMock.mockImplementation(async (sql, params) => {+ if (/FROM privacy_subjects/.test(sql)) return { rows: [subjectRow({ id: params[0], relationship: 'partner' })] };+ if (/SELECT 1 FROM privacy_consents/.test(sql)) {+ expect(sql).toMatch(/scope = \$2 AND revoked_at IS NULL/);+ const [subjectId, scope] = params;+ return { rows: rows.filter((r) => r.subjectId === subjectId && r.scope === scope && !r.revokedAt) };+ }+ throw new Error(`unexpected query: ${sql}`);+ });+ };++ it('a pii_vault-only subject is refused BOTH broker purposes', async () => {+ useConsentRows([{ subjectId: 's2', scope: 'pii_vault' }]);+ expect(await hasActiveConsent('s2', 'pii_vault')).toBe(true);+ for (const scope of ['broker_scan', 'broker_optout']) {+ await expect(assertSubjectConsent('s2', { scope, action: 'x' }))+ .rejects.toMatchObject({ status: 403, code: 'SUBJECT_CONSENT_REQUIRED' });+ }});- it('hasActiveConsent is false when the subject has no rows', async () => {- queryMock.mockResolvedValue({ rows: [] });- expect(await hasActiveConsent('s2')).toBe(false);+ it('broker_scan unlocks the scan without unlocking submissions', async () => {+ useConsentRows([{ subjectId: 's2', scope: 'pii_vault' }, { subjectId: 's2', scope: 'broker_scan' }]);+ await expect(assertSubjectConsent('s2', { scope: 'broker_scan' })).resolves.toMatchObject({ id: 's2' });+ await expect(assertSubjectConsent('s2', { scope: 'broker_optout' }))+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });});- it('assertSubjectConsent REFUSES a consentless subject with a 403', async () => {- queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)- ? { rows: [subjectRow({ id: 's2', relationship: 'partner' })] }- : { rows: [] }));- await expect(assertSubjectConsent('s2', { action: 'broker opt-out pass' }))- .rejects.toMatchObject({ status: 403, code: 'SUBJECT_CONSENT_REQUIRED' });+ it('a revoked grant no longer counts', async () => {+ useConsentRows([{ subjectId: 's2', scope: 'broker_optout', revokedAt: '2026-01-02' }]);+ await expect(assertSubjectConsent('s2', { scope: 'broker_optout' }))+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });});- it('assertSubjectConsent returns the subject when consent is on file', async () => {- queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)- ? { rows: [subjectRow({ id: 's2', relationship: 'partner' })] }- : { rows: [{ '?column?': 1 }] }));- await expect(assertSubjectConsent('s2')).resolves.toMatchObject({ id: 's2' });+ it('refuses to run an unscoped gate — there is no "any consent" mode', async () => {+ useConsentRows([{ subjectId: 's2', scope: 'pii_vault' }]);+ await expect(assertSubjectConsent('s2', { action: 'scan' })).rejects.toMatchObject({ code: 'CONSENT_SCOPE_INVALID' });+ await expect(hasActiveConsent('s2')).rejects.toMatchObject({ code: 'CONSENT_SCOPE_INVALID' });+ expect(queryMock).not.toHaveBeenCalled();});it('assertSubjectConsent 404s before it ever checks consent for an unknown subject', async () => {queryMock.mockResolvedValue({ rows: [] });- await expect(assertSubjectConsent('s2')).rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });+ await expect(assertSubjectConsent('s2', { scope: 'broker_scan' })).rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });expect(queryMock).toHaveBeenCalledTimes(1); // no consent probe});});++describe('revokeConsent (#8332)', () => {+ it('timestamps the active grants of one scope and keeps the subject', async () => {+ queryMock.mockImplementation(async (sql) => {+ if (/FROM privacy_subjects/.test(sql)) return { rows: [subjectRow({ id: 's2' })] };+ if (/UPDATE privacy_consents/.test(sql)) return { rows: [{ revoked_at: '2026-01-02T00:00:00Z' }] };+ throw new Error(`unexpected query: ${sql}`);+ });+ const result = await revokeConsent({ subjectId: 's2', scope: 'broker_optout' });+ expect(result).toEqual({ subjectId: 's2', scope: 'broker_optout', revoked: 1, revokedAt: '2026-01-02T00:00:00Z' });+ const [sql, params] = queryMock.mock.calls.find(([q]) => /UPDATE privacy_consents/.test(q));+ expect(sql).toMatch(/SET revoked_at = NOW\(\)/);+ expect(sql).toMatch(/scope = \$2 AND revoked_at IS NULL/);+ expect(params).toEqual(['s2', 'broker_optout']);+ // Audit history and the subject survive: no DELETE of any kind.+ expect(queryMock.mock.calls.some(([q]) => /DELETE/.test(q))).toBe(false);+ });++ it('refuses to revoke local-vault consent (that still means deleting the subject)', async () => {+ await expect(revokeConsent({ subjectId: 's2', scope: 'pii_vault' }))+ .rejects.toMatchObject({ status: 400, code: 'CONSENT_SCOPE_NOT_REVOCABLE' });+ expect(queryMock).not.toHaveBeenCalled();+ });++ it('404s an unknown subject', async () => {+ queryMock.mockResolvedValue({ rows: [] });+ await expect(revokeConsent({ subjectId: 's2', scope: 'broker_scan' }))+ .rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });+ });+});diff --git a/server/services/privacyVault.db.test.js b/server/services/privacyVault.db.test.jsindex 44f4cf640d..dd36686e9e 100644--- a/server/services/privacyVault.db.test.js+++ b/server/services/privacyVault.db.test.js@@ -83,7 +83,7 @@ describe.skipIf(!runDb)('privacy vault DB round-trip', () => {it('the seeded self subject always has consent, so a record adds no duplicate (#3658)', async () => {// The boot DDL seeds a consent row for `self`, so the install owner is never// refused by the engine guard and an ordinary create appends nothing.- expect(await subjects.hasActiveConsent(selfSubjectId)).toBe(true);+ expect(await subjects.hasActiveConsent(selfSubjectId, 'pii_vault')).toBe(true);const before = await query(`SELECT COUNT(*)::int AS n FROM privacy_consents WHERE subject_id = $1`, [selfSubjectId],);diff --git a/server/services/privacyVault.js b/server/services/privacyVault.jsindex 597fb5d84c..8614006075 100644--- a/server/services/privacyVault.js+++ b/server/services/privacyVault.js@@ -78,12 +78,15 @@ export async function createVaultRecord(input) {const subjectId = (await assertSubject(input.subjectId)).id;const id = randomUUID();const useForScans = resolveUseForScans(input.type, input.useForScans);- // First record FOR THIS SUBJECT ⇒ write the consent row (audit trail for the- // opt-out engine). Scoped per subject so a household member added directly- // through the vault still gets a consent row of their own rather than riding- // on `self`'s.+ // First record FOR THIS SUBJECT without local-vault consent ⇒ write the+ // `pii_vault` consent row. Scoped per subject so a household member added+ // directly through the vault still gets a consent row of their own rather than+ // riding on `self`'s. This grant is LOCAL-ONLY — it never unlocks broker scans+ // or opt-outs, which need their own explicit grants (#8332) — so keying the+ // check on the scope (not "any row") keeps a broker grant from standing in for+ // the vault's own audit fact.const { rows: countRows } = await query(- `SELECT COUNT(*)::int AS n FROM privacy_consents WHERE subject_id = $1`, [subjectId],+ `SELECT COUNT(*)::int AS n FROM privacy_consents WHERE subject_id = $1 AND scope = 'pii_vault'`, [subjectId],);const needsConsent = countRows[0].n === 0;const { rows } = await query(