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: scope the Privacy Center UI to a household subject (#3658)

[._.]/ Adam Eivya71492b035bd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 68ad0fe83d..e535afe218 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -61,6 +61,8 @@
- **The Privacy Center can now hold more than one person — with consent enforced by the engine, not the UI.** Everything in the suite (vault records, organizations, holdings, change-of-address events, broker cases, consent rows) is now scoped to a *household subject*, so a partner, child or parent you have permission to act for gets their own vault and their own broker opt-out ledger, worked independently of yours. Adding someone requires recording *how* their consent was captured (verbal, written, signed form, guardian, power of attorney), and the exposure-scan and opt-out engines **refuse** to scan or submit for a subject with no consent on file — a hard 403 in the service, so a scheduled recheck, a direct API call or a future agent path is refused exactly like a hidden button would be. Deleting a subject is a hard delete that removes everything of theirs, and the `self` subject can't be deleted. Existing installs are unaffected: a `self` subject is seeded, every existing row backfills to it, and every endpoint still defaults to it, so an install that never adds a second person behaves exactly as before. The Digital Twin's privacy context and the org cross-link stay scoped to `self` — a household member's data never enters a prompt. This is the multi-person half of #2148; it stays machine-local like the rest of the Privacy Center, with no federation.
+- **The Privacy Center now has the UI for those household members.** A subject bar above the tabs names whose records are on screen and switches between them; every tab — Overview, Vault, Organizations, Changes, Brokers — refetches under the selected person, and new vault records and organizations are filed to them. The choice lives in the URL (`?subject=…`), so a view of one person's data is shareable, bookmarkable and survives a reload, and it follows you across tabs and drill-downs instead of silently snapping back to you. Scoping to anyone other than yourself tints the bar and says so in words, and any revealed plaintext is dropped the moment you switch — the two ways a multi-person vault could otherwise let you read the wrong person's address and not notice. A **Household** panel adds and removes members, records how each person's consent was captured, and shows the full consent trail per person; removing someone spells out that their vault records, organizations, changes and broker cases go with them. There is deliberately no per-tab subject filter and no subject column: the API scopes to exactly one person per request, so the switcher *is* the filter and a column would print the same name on every row. Running a scan or opt-out pass for someone with no consent on file now says so in a sentence you can act on rather than surfacing the engine's raw refusal.
+
- A `/do:review` (or `/do:scan`, `/do:plan-task`, `/do:replan`) run queued from the **CoS quick templates** is no longer failed as `idle-no-changes`. The deliverable posture each slashdo workflow declares on its catalog entry reached the Agent Operations buttons but was silently dropped by the quick-template form, which read only the three run-shape toggles off a template's settings block — so the exact clean-tree misfire that posture exists to prevent still happened from the other surface. The flag now rides the template through the form as hidden state and into the create-task payload, and the strict template-settings schema accepts it so a user can save such a template back without a 400.
- **Series Pipeline runs can now pick a reasoning effort.** Pipeline stage LLM calls never emitted one, so a run's thinking effort was whatever the provider's configured CLI args (or an effort-encoding model id) happened to bake in — making a cheaper or harder-thinking autopilot run a global provider edit. Effort is now threaded exactly like the run provider and model: the Autonomous-mode Options popover (and a scheduled run's setup) offers it next to the provider/model picker for effort-capable providers, names the level the run resolves to, and applies it as a soft per-run default. A deliberate per-stage `effort` pin still wins, a level the chosen provider doesn't offer is clamped down its ladder rather than dropped, and a provider with no effort control simply gets no flag.
diff --git a/client/src/components/privacy/DeclareChangeDrawer.jsx b/client/src/components/privacy/DeclareChangeDrawer.jsx
index ac09ae128f..71c0a0e31a 100644
--- a/client/src/components/privacy/DeclareChangeDrawer.jsx
+++ b/client/src/components/privacy/DeclareChangeDrawer.jsx
@@ -4,9 +4,7 @@ import FormField from '../ui/FormField';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { declarePrivacyChange } from '../../services/api';
import toast from '../ui/Toast';
-import { VAULT_TYPES, CHANGE_KINDS, KIND_FOR_TYPE, labelFor } from './constants';
-
-const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent';
+import { VAULT_TYPES, CHANGE_KINDS, KIND_FOR_TYPE, INPUT_CLS, labelFor } from './constants';
// Declare a change-of-address (or any field change): pick the OLD vault record,
// enter the NEW value, and every org holding the old value flips to
@@ -73,7 +71,7 @@ export default function DeclareChangeDrawer({ open, vaultRecords, onClose, onDec
id="declare-old-record"
value={oldRecordId}
onChange={(e) => setOldRecordId(e.target.value)}
- className={inputCls}
+ className={INPUT_CLS}
>
{eligible.map((r) => (
<option key={r.id} value={r.id}>
@@ -94,7 +92,7 @@ export default function DeclareChangeDrawer({ open, vaultRecords, onClose, onDec
value={label}
onChange={(e) => setLabel(e.target.value)}
placeholder="e.g. New home address"
- className={inputCls}
+ className={INPUT_CLS}
maxLength={200}
/>
</FormField>
@@ -106,7 +104,7 @@ export default function DeclareChangeDrawer({ open, vaultRecords, onClose, onDec
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="The new value (encrypted at rest)"
- className={inputCls}
+ className={INPUT_CLS}
maxLength={10000}
/>
</FormField>
@@ -117,7 +115,7 @@ export default function DeclareChangeDrawer({ open, vaultRecords, onClose, onDec
value={note}
onChange={(e) => setNote(e.target.value)}
rows={2}
- className={inputCls}
+ className={INPUT_CLS}
maxLength={5000}
/>
</FormField>
diff --git a/client/src/components/privacy/OrgDrawer.jsx b/client/src/components/privacy/OrgDrawer.jsx
index 0fd1b7350d..e87617ef34 100644
--- a/client/src/components/privacy/OrgDrawer.jsx
+++ b/client/src/components/privacy/OrgDrawer.jsx
@@ -6,9 +6,7 @@ import {
createPrivacyOrg, updatePrivacyOrg, getOrgHoldings, setOrgHoldings, getSocialAccounts,
} from '../../services/api';
import toast from '../ui/Toast';
-import { ORG_CATEGORIES, ORG_TRUST_LEVELS, ORG_STATUSES, VAULT_TYPES, labelFor } from './constants';
-
-const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent';
+import { ORG_CATEGORIES, ORG_TRUST_LEVELS, ORG_STATUSES, VAULT_TYPES, INPUT_CLS, labelFor } from './constants';
const EMPTY = {
name: '', category: 'other', website: '', trust: 'trusted', status: 'active',
@@ -26,7 +24,7 @@ const accountLabel = (a) => {
// picker is a checkbox list over the user's vault records (masked values only).
// Holdings are saved via the replace-set endpoint after the org exists (on
// create we POST the org first, then set holdings against the returned id).
-export default function OrgDrawer({ open, org, vaultRecords, onClose, onSaved }) {
+export default function OrgDrawer({ open, org, subjectId, vaultRecords, onClose, onSaved }) {
const editing = !!org;
const [form, setForm] = useState(EMPTY);
const [selected, setSelected] = useState(() => new Set()); // vaultRecordId set
@@ -86,9 +84,12 @@ export default function OrgDrawer({ open, org, vaultRecords, onClose, onSaved })
socialAccountId: form.socialAccountId || null,
};
+ // The org belongs to whichever household subject was in scope when it was
+ // created; the server rejects holdings that cross subjects, so it is not
+ // re-assignable on edit.
const savedOrg = editing
? await updatePrivacyOrg(org.id, payload, { silent: true })
- : await createPrivacyOrg(payload, { silent: true });
+ : await createPrivacyOrg({ ...payload, subjectId }, { silent: true });
if (!savedOrg) return null;
// Persist holdings (replace-set). Skip the call on create when nothing is selected.
@@ -116,36 +117,36 @@ export default function OrgDrawer({ open, org, vaultRecords, onClose, onSaved })
>
<form className="space-y-4" onSubmit={(e) => { e.preventDefault(); save(); }}>
<FormField label="Name">
- <input type="text" value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="e.g. Acme Bank" className={inputCls} maxLength={200} />
+ <input type="text" value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="e.g. Acme Bank" className={INPUT_CLS} maxLength={200} />
</FormField>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<FormField label="Category">
- <select value={form.category} onChange={(e) => set('category', e.target.value)} className={inputCls}>
+ <select value={form.category} onChange={(e) => set('category', e.target.value)} className={INPUT_CLS}>
{ORG_CATEGORIES.map((c) => <option key={c.id} value={c.id}>{c.label}</option>)}
</select>
</FormField>
<FormField label="Trust">
- <select value={form.trust} onChange={(e) => set('trust', e.target.value)} className={inputCls}>
+ <select value={form.trust} onChange={(e) => set('trust', e.target.value)} className={INPUT_CLS}>
{ORG_TRUST_LEVELS.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
</select>
</FormField>
<FormField label="Status">
- <select value={form.status} onChange={(e) => set('status', e.target.value)} className={inputCls}>
+ <select value={form.status} onChange={(e) => set('status', e.target.value)} className={INPUT_CLS}>
{ORG_STATUSES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
</FormField>
</div>
<FormField label="Website">
- <input type="text" value={form.website} onChange={(e) => set('website', e.target.value)} placeholder="https://…" className={inputCls} maxLength={2000} />
+ <input type="text" value={form.website} onChange={(e) => set('website', e.target.value)} placeholder="https://…" className={INPUT_CLS} maxLength={2000} />
</FormField>
<FormField label="Linked social account (Digital Twin)">
<select
value={form.socialAccountId}
onChange={(e) => set('socialAccountId', e.target.value)}
- className={inputCls}
+ className={INPUT_CLS}
>
<option value="">— None —</option>
{/* Preserve a stale link (account since deleted) so the select isn't blank. */}
@@ -163,10 +164,10 @@ export default function OrgDrawer({ open, org, vaultRecords, onClose, onSaved })
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<FormField label="Contact email">
- <input type="email" value={form.contactEmail} onChange={(e) => set('contactEmail', e.target.value)} className={inputCls} maxLength={320} />
+ <input type="email" value={form.contactEmail} onChange={(e) => set('contactEmail', e.target.value)} className={INPUT_CLS} maxLength={320} />
</FormField>
<FormField label="Contact phone">
- <input type="tel" value={form.contactPhone} onChange={(e) => set('contactPhone', e.target.value)} className={inputCls} maxLength={64} />
+ <input type="tel" value={form.contactPhone} onChange={(e) => set('contactPhone', e.target.value)} className={INPUT_CLS} maxLength={64} />
</FormField>
</div>
@@ -189,7 +190,7 @@ export default function OrgDrawer({ open, org, vaultRecords, onClose, onSaved })
</div>
<FormField label="Notes">
- <textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={3} className={inputCls} maxLength={5000} />
+ <textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={3} className={INPUT_CLS} maxLength={5000} />
</FormField>
<div className="flex items-center justify-end gap-2 pt-2">
diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsx
index 32e9f571ea..ebaf496c04 100644
--- a/client/src/components/privacy/PrivacyBrokersTab.jsx
+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx
@@ -32,7 +32,7 @@ function StatChip({ label, count, tone }) {
);
}
-export default function PrivacyBrokersTab() {
+export default function PrivacyBrokersTab({ subjectId }) {
const [searchParams, setSearchParams] = useSearchParams();
const openCaseId = searchParams.get('case');
@@ -46,24 +46,36 @@ export default function PrivacyBrokersTab() {
const [cronDraft, setCronDraft] = useState('');
const [brokerListOpen, setBrokerListOpen] = useState(false);
+ // Cases, exposure counts, and the digest are per-subject — `load` is also the
+ // post-action refresh, so it runs after every scan/recheck/transition.
const load = useCallback(() => {
setLoading(true);
Promise.allSettled([
- getPrivacyScanStatus(), getPrivacyBrokerCases(), getPrivacyBrokers(),
- getPrivacyOptOutDigest(), getPrivacyOptOutSchedule(),
- ]).then(([s, c, b, d, sch]) => {
+ getPrivacyScanStatus({ subjectId }), getPrivacyBrokerCases(undefined, { subjectId }),
+ getPrivacyOptOutDigest({ subjectId }),
+ ]).then(([s, c, d]) => {
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: [] });
+ setLoading(false);
+ });
+ }, [subjectId]);
+
+ useEffect(() => { load(); }, [load]);
+
+ // The broker database and the recheck schedule are install-wide: they can't
+ // change when the subject does, and re-pulling the whole broker list on every
+ // case transition was pure waste.
+ const loadInstallWide = useCallback(() => {
+ Promise.allSettled([getPrivacyBrokers(), getPrivacyOptOutSchedule()]).then(([b, sch]) => {
+ setBrokers(b.status === 'fulfilled' ? b.value : []);
const schVal = sch.status === 'fulfilled' ? sch.value : null;
setSchedule(schVal);
if (schVal) setCronDraft(schVal.cronExpression || '');
- setLoading(false);
});
}, []);
- useEffect(() => { load(); }, [load]);
+ useEffect(() => { loadInstallWide(); }, [loadInstallWide]);
const brokerById = useMemo(() => new Map(brokers.map((b) => [b.id, b])), [brokers]);
const caseCounts = scanStatus?.caseCounts || {};
@@ -76,8 +88,23 @@ export default function PrivacyBrokersTab() {
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,
+ // so restate it as the action the user can actually take — the fix is
+ // recording consent, 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) => {
+ if (err?.code !== 'SUBJECT_CONSENT_REQUIRED') throw err;
+ const friendly = new Error('No consent on record for this person — add it under Household first');
+ friendly.code = err.code;
+ friendly.status = err.status;
+ throw friendly;
+ });
+
const [scanNow, scanRunning] = useAsyncAction(async () => {
- const r = await runPrivacyScan({ silent: true });
+ const r = await runPass(runPrivacyScan);
load();
const verdicts = Object.entries(r?.verdicts || {}).map(([k, v]) => `${v} ${labelFor(CASE_STATES, k).toLowerCase()}`).join(', ');
toast.success(r?.reason === 'no_scan_vectors'
@@ -87,7 +114,7 @@ export default function PrivacyBrokersTab() {
}, { errorMessage: 'Scan failed' });
const [optOutNow, optOutRunning] = useAsyncAction(async () => {
- const r = await runPrivacyOptOut({ silent: true });
+ const r = await runPass(runPrivacyOptOut);
load();
toast.success(r?.reason === 'no_disclosure_identity'
? 'Add a scan-eligible name to the vault to run an opt-out pass'
@@ -97,7 +124,7 @@ export default function PrivacyBrokersTab() {
const [refreshList, refreshing] = useAsyncAction(async () => {
const r = await refreshPrivacyBrokers({ silent: true });
- load();
+ loadInstallWide();
toast.success(`Broker list refreshed: ${r?.added || 0} new (${r?.fetched || 0} fetched)`);
return r;
}, { errorMessage: 'Broker refresh failed' });
diff --git a/client/src/components/privacy/PrivacyChangesTab.jsx b/client/src/components/privacy/PrivacyChangesTab.jsx
index 9f52884fa9..017f8b044a 100644
--- a/client/src/components/privacy/PrivacyChangesTab.jsx
+++ b/client/src/components/privacy/PrivacyChangesTab.jsx
@@ -104,7 +104,7 @@ function StatusGroup({ title, orgs, status, eventId, hasReplacement, onChanged }
);
}
-export default function PrivacyChangesTab() {
+export default function PrivacyChangesTab({ subjectId }) {
const [events, setEvents] = useState([]);
const [vaultRecords, setVaultRecords] = useState([]);
const [loading, setLoading] = useState(true);
@@ -115,12 +115,16 @@ export default function PrivacyChangesTab() {
const load = useCallback(() => {
setLoading(true);
- Promise.allSettled([getPrivacyChanges(), getVaultRecords()]).then(([e, v]) => {
+ // A change event inherits its subject from the vault record it replaces, so
+ // scoping the record list is what keeps the Declare form on one person.
+ Promise.allSettled([
+ getPrivacyChanges({ subjectId }), getVaultRecords(undefined, { subjectId }),
+ ]).then(([e, v]) => {
setEvents(e.status === 'fulfilled' ? e.value : []);
setVaultRecords(v.status === 'fulfilled' ? v.value : []);
setLoading(false);
});
- }, []);
+ }, [subjectId]);
useEffect(() => { load(); }, [load]);
diff --git a/client/src/components/privacy/PrivacyOrgsTab.jsx b/client/src/components/privacy/PrivacyOrgsTab.jsx
index 2bbf8882d1..fbbdc8ab9c 100644
--- a/client/src/components/privacy/PrivacyOrgsTab.jsx
+++ b/client/src/components/privacy/PrivacyOrgsTab.jsx
@@ -36,7 +36,7 @@ function ChipFilter({ label, options, value, onChange }) {
);
}
-export default function PrivacyOrgsTab() {
+export default function PrivacyOrgsTab({ subjectId }) {
const [orgs, setOrgs] = useState([]);
const [vaultRecords, setVaultRecords] = useState([]);
const [holdingsByOrg, setHoldingsByOrg] = useState({}); // orgId -> [holdings]
@@ -48,19 +48,26 @@ export default function PrivacyOrgsTab() {
const load = useCallback(() => {
setLoading(true);
- Promise.allSettled([getPrivacyOrgs(), getVaultRecords()]).then(async ([o, v]) => {
- const orgList = o.status === 'fulfilled' ? o.value : [];
- setOrgs(orgList);
- setVaultRecords(v.status === 'fulfilled' ? v.value : []);
- // Fetch holdings per org (single-user scale — a handful of orgs).
- const entries = await Promise.all(orgList.map(async (org) => {
- const h = await getOrgHoldings(org.id, { silent: true }).catch(() => []);
- return [org.id, h || []];
- }));
- setHoldingsByOrg(Object.fromEntries(entries));
- setLoading(false);
- });
- }, []);
+ // Holdings depend only on the org list, so they chain off it directly — the
+ // vault read runs alongside rather than gating the fan-out.
+ const orgsThenHoldings = getPrivacyOrgs({}, { subjectId })
+ .then(async (orgList) => {
+ setOrgs(orgList);
+ // One request per org (single-user scale — a handful of orgs).
+ const entries = await Promise.all(orgList.map(async (org) => {
+ const h = await getOrgHoldings(org.id, { silent: true }).catch(() => []);
+ return [org.id, h || []];
+ }));
+ setHoldingsByOrg(Object.fromEntries(entries));
+ })
+ .catch(() => { setOrgs([]); setHoldingsByOrg({}); });
+
+ const vault = getVaultRecords(undefined, { subjectId })
+ .then((v) => setVaultRecords(v || []))
+ .catch(() => setVaultRecords([]));
+
+ Promise.all([orgsThenHoldings, vault]).then(() => setLoading(false));
+ }, [subjectId]);
useEffect(() => { load(); }, [load]);
@@ -193,6 +200,7 @@ export default function PrivacyOrgsTab() {
<OrgDrawer
open={drawerOpen}
org={editing}
+ subjectId={subjectId}
vaultRecords={vaultRecords}
onClose={() => setDrawerOpen(false)}
onSaved={handleSaved}
diff --git a/client/src/components/privacy/PrivacyOverviewTab.jsx b/client/src/components/privacy/PrivacyOverviewTab.jsx
index 9aa16ea84c..fef20c6b01 100644
--- a/client/src/components/privacy/PrivacyOverviewTab.jsx
+++ b/client/src/components/privacy/PrivacyOverviewTab.jsx
@@ -4,12 +4,13 @@ import { ShieldCheck, ShieldAlert, KeyRound, Building2, ArrowRight, ShieldOff }
import { getPrivacyStatus, getPrivacyOrgs, getPrivacyScanStatus } from '../../services/api';
import {
VAULT_TYPES, ORG_TRUST_LEVELS, TRUST_TONE, labelFor, CASE_STATES, CASE_STATE_TONE,
+ privacyTabPath,
} 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() {
+export default function PrivacyOverviewTab({ subjectId }) {
const navigate = useNavigate();
const [status, setStatus] = useState(null);
const [orgs, setOrgs] = useState([]);
@@ -17,13 +18,21 @@ export default function PrivacyOverviewTab() {
const [loading, setLoading] = useState(true);
useEffect(() => {
- Promise.allSettled([getPrivacyStatus(), getPrivacyOrgs(), getPrivacyScanStatus()]).then(([s, o, b]) => {
+ setLoading(true);
+ Promise.allSettled([
+ getPrivacyStatus({ subjectId }), getPrivacyOrgs({}, { subjectId }),
+ getPrivacyScanStatus({ subjectId }),
+ ]).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);
});
- }, []);
+ }, [subjectId]);
+
+ // Cross-tab links carry the active subject so a drill-down never silently
+ // snaps back to `self`.
+ const goTo = (tab) => navigate(privacyTabPath(tab, subjectId));
if (loading) return <div className="text-gray-500 text-sm py-8 text-center">Loading privacy status…</div>;
@@ -69,7 +78,7 @@ export default function PrivacyOverviewTab() {
{/* Vault records */}
<button
- onClick={() => navigate('/privacy/vault')}
+ onClick={() => goTo('vault')}
className="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">
@@ -89,7 +98,7 @@ export default function PrivacyOverviewTab() {
{/* Organizations */}
<button
- onClick={() => navigate('/privacy/organizations')}
+ onClick={() => goTo('organizations')}
className="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">
@@ -112,7 +121,7 @@ export default function PrivacyOverviewTab() {
{/* Data-broker exposure summary (#2146) */}
<button
- onClick={() => navigate('/privacy/brokers')}
+ onClick={() => goTo('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">
@@ -137,10 +146,10 @@ export default function PrivacyOverviewTab() {
</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">
+ <button onClick={() => goTo('vault')} className="px-3 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80">
Manage vault
</button>
- <button onClick={() => navigate('/privacy/organizations')} className="px-3 py-2 text-sm rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-card">
+ <button onClick={() => goTo('organizations')} className="px-3 py-2 text-sm rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-card">
Manage organizations
</button>
</div>
diff --git a/client/src/components/privacy/PrivacyVaultTab.jsx b/client/src/components/privacy/PrivacyVaultTab.jsx
index 1d269a5e8f..b03cad7a3a 100644
--- a/client/src/components/privacy/PrivacyVaultTab.jsx
+++ b/client/src/components/privacy/PrivacyVaultTab.jsx
@@ -19,7 +19,7 @@ function Toggle({ checked, disabled, onChange, label }) {
);
}
-export default function PrivacyVaultTab() {
+export default function PrivacyVaultTab({ subjectId }) {
const [records, setRecords] = useState([]);
const [loading, setLoading] = useState(true);
const [drawerOpen, setDrawerOpen] = useState(false);
@@ -30,12 +30,14 @@ export default function PrivacyVaultTab() {
const load = useCallback(() => {
setLoading(true);
- Promise.allSettled([getVaultRecords(), getPrivacyStatus()]).then(([recs, status]) => {
+ Promise.allSettled([
+ getVaultRecords(undefined, { subjectId }), getPrivacyStatus({ subjectId }),
+ ]).then(([recs, status]) => {
setRecords(recs.status === 'fulfilled' ? recs.value : []);
if (status.status === 'fulfilled') setKeyConfigured(status.value.keyConfigured !== false);
setLoading(false);
});
- }, []);
+ }, [subjectId]);
useEffect(() => { load(); }, [load]);
@@ -204,6 +206,7 @@ export default function PrivacyVaultTab() {
<VaultRecordDrawer
open={drawerOpen}
record={editing}
+ subjectId={subjectId}
onClose={() => setDrawerOpen(false)}
onSaved={handleSaved}
/>
diff --git a/client/src/components/privacy/SubjectSwitcher.jsx b/client/src/components/privacy/SubjectSwitcher.jsx
new file mode 100644
index 0000000000..7971e1e5c2
--- /dev/null
+++ b/client/src/components/privacy/SubjectSwitcher.jsx
@@ -0,0 +1,54 @@
+import { Users, Settings2 } from 'lucide-react';
+import { SUBJECT_RELATIONSHIPS, labelFor } from './constants';
+
+// Whose PII is on screen (#3658). The API scopes each read to ONE subject, so
+// this switcher IS the Privacy Center's subject filter, not a per-tab control.
+//
+// Scoping to someone other than `self` tints the control: this bar sits directly
+// above the tab content, which is what keeps "whose address is this?" from ever
+// being ambiguous.
+export default function SubjectSwitcher({ subjects, subjectId, onChange, onManage }) {
+ const active = subjects.find((s) => s.id === subjectId);
+ const isSelf = !active || active.isSelf;
+
+ return (
+ <div className={`flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg border ${
+ isSelf ? 'border-port-border bg-port-card' : 'border-port-warning/40 bg-port-warning/5'
+ }`}
+ >
+ <Users size={15} className={isSelf ? 'text-gray-500' : 'text-port-warning'} />
+ <label htmlFor="privacy-subject-select" className="text-[11px] uppercase tracking-wide text-gray-500">
+ Subject
+ </label>
+ <select
+ id="privacy-subject-select"
+ value={subjectId}
+ onChange={(e) => onChange(e.target.value)}
+ className="px-2 py-1 text-sm rounded bg-port-bg border border-port-border text-gray-200"
+ >
+ {/* A stale ?subject= deep link (subject since deleted) keeps a labeled
+ option so the select never renders blank. Gated on the list having
+ loaded — before that, EVERY id looks unknown. */}
+ {subjects.length > 0 && !active && <option value={subjectId}>Unknown subject</option>}
+ {subjects.map((s) => (
+ <option key={s.id} value={s.id}>
+ {s.displayName}{s.isSelf ? '' : ` · ${labelFor(SUBJECT_RELATIONSHIPS, s.relationship)}`}
+ </option>
+ ))}
+ </select>
+
+ {!isSelf && (
+ <span className="text-[11px] text-port-warning">
+ Viewing {active.displayName}&rsquo;s records — not your own
+ </span>
+ )}
+
+ <button
+ onClick={onManage}
+ className="ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-border/40"
+ >
+ <Settings2 size={14} /> Household
+ </button>
+ </div>
+ );
+}
diff --git a/client/src/components/privacy/SubjectsDrawer.jsx b/client/src/components/privacy/SubjectsDrawer.jsx
new file mode 100644
index 0000000000..b8d56c3666
--- /dev/null
+++ b/client/src/components/privacy/SubjectsDrawer.jsx
@@ -0,0 +1,236 @@
+import { useState, useEffect } from 'react';
+import { Plus, Trash2, ShieldCheck, ChevronDown, ChevronRight } from 'lucide-react';
+import Drawer from '../Drawer';
+import FormField from '../ui/FormField';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import Pill from '../ui/Pill';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import useConfirmDelete from '../../hooks/useConfirmDelete';
+import {
+ createPrivacySubject, deletePrivacySubject, getPrivacySubjectConsents,
+} from '../../services/api';
+import toast from '../ui/Toast';
+import { formatDateShort } from '../../utils/formatters';
+import {
+ SUBJECT_RELATIONSHIPS, CONSENT_METHODS, CONSENT_SCOPES, INPUT_CLS, labelFor,
+} from './constants';
+
+// `self` is excluded — you are always your own subject and consent is implied.
+const ADDABLE_RELATIONSHIPS = SUBJECT_RELATIONSHIPS.filter((r) => r.id !== 'self');
+
+const 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 }) {
+ // 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
+ // failed would be a lie the user acts on.
+ const [consents, setConsents] = useState(null);
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ if (!open || consents !== null) return;
+ getPrivacySubjectConsents(subjectId, { silent: true })
+ .then((rows) => setConsents(rows || []))
+ .catch(() => setConsents('error'));
+ }, [open, consents, subjectId]);
+
+ return (
+ <div className="mt-2">
+ <button
+ onClick={() => setOpen((o) => !o)}
+ className="inline-flex items-center gap-1 text-[11px] text-gray-500 hover:text-gray-300"
+ >
+ {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />} Consent record
+ </button>
+ {open && (
+ consents === null ? (
+ <div className="text-[11px] text-gray-600 mt-1">Loading…</div>
+ ) : consents === 'error' ? (
+ <div className="text-[11px] text-gray-500 mt-1">Couldn&rsquo;t load the consent record.</div>
+ ) : consents.length === 0 ? (
+ <div className="text-[11px] text-port-warning mt-1">
+ No consent on record — scans and opt-outs are refused for this person.
+ </div>
+ ) : (
+ <ul className="mt-1 space-y-1">
+ {consents.map((c) => (
+ <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.note ? <span className="italic"> — {c.note}</span> : null}
+ </li>
+ ))}
+ </ul>
+ )
+ )}
+ </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 }) {
+ const [form, setForm] = useState(EMPTY);
+ const [adding, setAdding] = useState(false);
+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
+
+ useEffect(() => { if (open) { setForm(EMPTY); setAdding(false); cancelDelete(); } }, [open, cancelDelete]);
+
+ const set = (k, v) => setForm((prev) => ({ ...prev, [k]: v }));
+
+ const [save, saving] = useAsyncAction(async () => {
+ if (!form.displayName.trim()) { toast.error('Name is required'); return null; }
+ const created = await createPrivacySubject({
+ displayName: form.displayName.trim(),
+ relationship: form.relationship,
+ consentMethod: form.consentMethod,
+ ...(form.consentNote.trim() ? { consentNote: form.consentNote.trim() } : {}),
+ }, { silent: true });
+ if (created) {
+ toast.success(`${created.displayName} added to the household`);
+ setForm(EMPTY);
+ setAdding(false);
+ onCreated(created);
+ }
+ return created;
+ }, { errorMessage: 'Failed to add household member' });
+
+ const handleDelete = async (subject) => {
+ const ok = await deletePrivacySubject(subject.id, { silent: true }).catch(() => null);
+ if (ok) {
+ toast.success(`${subject.displayName} removed`);
+ onDeleted(subject.id);
+ } else {
+ toast.error('Failed to remove household member');
+ }
+ };
+
+ return (
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="Household"
+ subtitle="Everyone whose PII this install tracks"
+ size="md"
+ closeOnEsc={false}
+ closeOnBackdrop={false}
+ >
+ <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.
+ </p>
+
+ <div className="space-y-2">
+ {subjects.map((s) => (
+ <div key={s.id} className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0 flex-1">
+ <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>
+ )}
+ </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>
+ {!s.isSelf && (
+ <button
+ onClick={() => requestDelete(s.id)}
+ title={`Remove ${s.displayName}`}
+ aria-label={`Remove ${s.displayName}`}
+ className="p-2 rounded text-gray-400 hover:text-port-error hover:bg-port-border/50 shrink-0"
+ >
+ <Trash2 size={16} />
+ </button>
+ )}
+ </div>
+ {isConfirming(s.id) && (
+ <InlineConfirmRow
+ className="mt-3"
+ confirmText="Remove"
+ question={`Remove ${s.displayName}? Their vault records, organizations, changes, and broker cases are deleted too. This can't be undone.`}
+ onConfirm={() => confirmDelete(() => handleDelete(s))}
+ onCancel={cancelDelete}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+
+ {adding ? (
+ <form
+ className="space-y-3 border border-port-border rounded-lg p-3"
+ onSubmit={(e) => { e.preventDefault(); save(); }}
+ >
+ <FormField label="Name">
+ <input
+ type="text"
+ value={form.displayName}
+ onChange={(e) => set('displayName', e.target.value)}
+ placeholder="e.g. Alex"
+ className={INPUT_CLS}
+ maxLength={200}
+ />
+ </FormField>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <FormField label="Relationship">
+ <select value={form.relationship} onChange={(e) => set('relationship', e.target.value)} className={INPUT_CLS}>
+ {ADDABLE_RELATIONSHIPS.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}
+ </select>
+ </FormField>
+ <FormField label="Consent captured via" hint="Required — the engine refuses to act without it.">
+ <select value={form.consentMethod} onChange={(e) => set('consentMethod', e.target.value)} className={INPUT_CLS}>
+ {CONSENT_METHODS.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
+ </select>
+ </FormField>
+ </div>
+
+ <FormField label="Consent note">
+ <textarea
+ value={form.consentNote}
+ onChange={(e) => set('consentNote', e.target.value)}
+ rows={2}
+ placeholder="e.g. signed form filed 2026-08-01"
+ className={INPUT_CLS}
+ maxLength={2000}
+ />
+ </FormField>
+
+ <div className="flex items-center justify-end gap-2">
+ <button type="button" onClick={() => setAdding(false)} className="px-3 py-2 text-sm text-gray-400 hover:text-white">
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={saving}
+ className="px-4 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {saving ? 'Adding…' : 'Add member'}
+ </button>
+ </div>
+ </form>
+ ) : (
+ <button
+ onClick={() => setAdding(true)}
+ 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"
+ >
+ <Plus size={16} /> Add household member
+ </button>
+ )}
+ </div>
+ </Drawer>
+ );
+}
diff --git a/client/src/components/privacy/SubjectsDrawer.test.jsx b/client/src/components/privacy/SubjectsDrawer.test.jsx
new file mode 100644
index 0000000000..c756aabdaa
--- /dev/null
+++ b/client/src/components/privacy/SubjectsDrawer.test.jsx
@@ -0,0 +1,91 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+
+// Household subjects drawer (#3658). Consent is captured at creation because the
+// engine refuses to scan/opt-out for a subject with no consent row.
+vi.mock('../../services/api', () => ({
+ createPrivacySubject: vi.fn(),
+ deletePrivacySubject: vi.fn(),
+ getPrivacySubjectConsents: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+import SubjectsDrawer from './SubjectsDrawer';
+import {
+ createPrivacySubject, deletePrivacySubject, getPrivacySubjectConsents,
+} 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 },
+];
+
+function renderDrawer(props = {}) {
+ return render(
+ <SubjectsDrawer
+ open
+ subjects={SUBJECTS}
+ onClose={vi.fn()}
+ onCreated={vi.fn()}
+ onDeleted={vi.fn()}
+ {...props}
+ />,
+ );
+}
+
+describe('SubjectsDrawer', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('lists household members with their relationship', () => {
+ renderDrawer();
+ expect(screen.getByText('Me')).toBeInTheDocument();
+ expect(screen.getByText('Alex')).toBeInTheDocument();
+ expect(screen.getByText('Partner')).toBeInTheDocument();
+ });
+
+ it('never offers to delete the self subject', () => {
+ renderDrawer();
+ expect(screen.queryByLabelText('Remove Me')).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Remove Alex')).toBeInTheDocument();
+ });
+
+ it('creates a member with the captured consent method', async () => {
+ createPrivacySubject.mockResolvedValue({ id: 'sub-3', displayName: 'Sam', relationship: 'child' });
+ const onCreated = vi.fn();
+ renderDrawer({ onCreated });
+
+ fireEvent.click(screen.getByRole('button', { name: /Add household member/i }));
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Sam' } });
+ fireEvent.change(screen.getByLabelText(/Relationship/i), { target: { value: 'child' } });
+ fireEvent.change(screen.getByLabelText(/Consent captured via/i), { target: { value: 'guardian' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Add member$/i }));
+
+ await waitFor(() => expect(createPrivacySubject).toHaveBeenCalledWith(
+ { displayName: 'Sam', relationship: 'child', consentMethod: 'guardian' },
+ { silent: true },
+ ));
+ expect(onCreated).toHaveBeenCalledWith(expect.objectContaining({ id: 'sub-3' }));
+ });
+
+ it('warns when a member has no consent on record', async () => {
+ getPrivacySubjectConsents.mockResolvedValue([]);
+ renderDrawer();
+ fireEvent.click(screen.getAllByRole('button', { name: /Consent record/i })[1]);
+ await waitFor(() => expect(screen.getByText(/scans and opt-outs are refused/i)).toBeInTheDocument());
+ });
+
+ it('warns that deleting a member cascades their records', async () => {
+ deletePrivacySubject.mockResolvedValue({ ok: true });
+ const onDeleted = vi.fn();
+ renderDrawer({ onDeleted });
+
+ fireEvent.click(screen.getByLabelText('Remove Alex'));
+ expect(screen.getByText(/vault records, organizations, changes, and broker cases are deleted too/i))
+ .toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ await waitFor(() => expect(deletePrivacySubject).toHaveBeenCalledWith('sub-2', { silent: true }));
+ expect(onDeleted).toHaveBeenCalledWith('sub-2');
+ });
+});
diff --git a/client/src/components/privacy/VaultRecordDrawer.jsx b/client/src/components/privacy/VaultRecordDrawer.jsx
index 403ec16554..42fc493472 100644
--- a/client/src/components/privacy/VaultRecordDrawer.jsx
+++ b/client/src/components/privacy/VaultRecordDrawer.jsx
@@ -4,21 +4,19 @@ import FormField from '../ui/FormField';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { createVaultRecord, updateVaultRecord } from '../../services/api';
import toast from '../ui/Toast';
-import { VAULT_TYPES, VAULT_STATUSES, SENSITIVE_TYPES } from './constants';
+import { VAULT_TYPES, VAULT_STATUSES, SENSITIVE_TYPES, INPUT_CLS } from './constants';
// Create/edit a single encrypted vault record. Form state is hoisted into this
// component (never left in uncontrolled inputs) per the drawer convention. On
// edit the plaintext `value` is NOT prefilled (the list only ever holds the
// masked value) — an empty value on edit means "leave the stored value
// unchanged"; typing a new value re-encrypts it server-side.
-const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent';
-
const EMPTY = {
type: 'legal_name', label: '', value: '', status: 'current',
validFrom: '', validTo: '', shareWithTwin: false, useForScans: null, notes: '',
};
-export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
+export default function VaultRecordDrawer({ open, record, subjectId, onClose, onSaved }) {
const editing = !!record;
const [form, setForm] = useState(EMPTY);
@@ -64,7 +62,11 @@ export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
if (form.value.trim()) payload.value = form.value;
result = await updateVaultRecord(record.id, payload, { silent: true });
} else {
- result = await createVaultRecord({ type: form.type, value: form.value, ...payload }, { silent: true });
+ // The subject is fixed at creation by the active scope — like `type`, it is
+ // immutable afterwards (move a record by deleting and re-creating it).
+ result = await createVaultRecord({
+ type: form.type, value: form.value, ...payload, subjectId,
+ }, { silent: true });
}
if (result) {
toast.success(editing ? 'Vault record updated' : 'Vault record created');
@@ -92,7 +94,7 @@ export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
value={form.type}
onChange={(e) => set('type', e.target.value)}
disabled={editing}
- className={`${inputCls} ${editing ? 'opacity-60 cursor-not-allowed' : ''}`}
+ className={`${INPUT_CLS} ${editing ? 'opacity-60 cursor-not-allowed' : ''}`}
>
{VAULT_TYPES.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
</select>
@@ -105,7 +107,7 @@ export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
value={form.label}
onChange={(e) => set('label', e.target.value)}
placeholder="e.g. Home address"
- className={inputCls}
+ className={INPUT_CLS}
maxLength={200}
/>
</FormField>
@@ -120,21 +122,21 @@ export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
onChange={(e) => set('value', e.target.value)}
placeholder={editing ? '••••••••' : ''}
autoComplete="off"
- className={inputCls}
+ className={INPUT_CLS}
/>
</FormField>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<FormField label="Status">
- <select value={form.status} onChange={(e) => set('status', e.target.value)} className={inputCls}>
+ <select value={form.status} onChange={(e) => set('status', e.target.value)} className={INPUT_CLS}>
{VAULT_STATUSES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
</FormField>
<FormField label="Valid from">
- <input type="date" value={form.validFrom || ''} onChange={(e) => set('validFrom', e.target.value)} className={inputCls} />
+ <input type="date" value={form.validFrom || ''} onChange={(e) => set('validFrom', e.target.value)} className={INPUT_CLS} />
</FormField>
<FormField label="Valid to">
- <input type="date" value={form.validTo || ''} onChange={(e) => set('validTo', e.target.value)} className={inputCls} />
+ <input type="date" value={form.validTo || ''} onChange={(e) => set('validTo', e.target.value)} className={INPUT_CLS} />
</FormField>
</div>
@@ -159,7 +161,7 @@ export default function VaultRecordDrawer({ open, record, onClose, onSaved }) {
value={form.notes}
onChange={(e) => set('notes', e.target.value)}
rows={3}
- className={inputCls}
+ className={INPUT_CLS}
maxLength={5000}
/>
</FormField>
diff --git a/client/src/components/privacy/constants.js b/client/src/components/privacy/constants.js
index 855ddf812b..42370d8642 100644
--- a/client/src/components/privacy/constants.js
+++ b/client/src/components/privacy/constants.js
@@ -2,6 +2,40 @@
// the server Zod schemas in server/lib/privacyValidation.js — a mismatch would
// let the UI offer a value the API rejects.
+// ── Household subjects (#3658) ──────────────────────────────────────────────
+// Mirrors PRIVACY_SELF_SUBJECT_ID — the seeded subject every pre-#3658 record
+// backfilled to. The UI treats it as undeletable and as the default scope.
+export const SELF_SUBJECT_ID = '00000000-0000-4000-8000-000000000001';
+
+// Mirrors PRIVACY_SUBJECT_RELATIONSHIPS.
+export const SUBJECT_RELATIONSHIPS = [
+ { id: 'self', label: 'Self' },
+ { id: 'partner', label: 'Partner' },
+ { id: 'child', label: 'Child' },
+ { id: 'parent', label: 'Parent' },
+ { id: 'dependent', label: 'Dependent' },
+ { id: 'other', label: 'Other' },
+];
+
+// Mirrors PRIVACY_CONSENT_METHODS — how this person's consent was captured.
+// The engine refuses to scan or submit opt-outs for a subject with no consent
+// row, so this is a required field when adding a household member.
+export const CONSENT_METHODS = [
+ { id: 'self', label: 'Self (my own data)' },
+ { id: 'verbal', label: 'Verbal' },
+ { id: 'written', label: 'Written' },
+ { id: 'signed_form', label: 'Signed form' },
+ { id: 'guardian', label: 'Guardian' },
+ { id: 'power_of_attorney', label: 'Power of attorney' },
+ { id: 'other', label: 'Other' },
+];
+
+// Mirrors PRIVACY_CONSENT_SCOPES.
+export const CONSENT_SCOPES = [
+ { id: 'pii_vault', label: 'PII vault' },
+ { id: 'broker_optout', label: 'Broker opt-out' },
+];
+
export const VAULT_TYPES = [
{ id: 'legal_name', label: 'Legal name' },
{ id: 'address', label: 'Address' },
@@ -198,3 +232,14 @@ export const BROKER_CONFIDENCE = [
];
export const labelFor = (list, id) => list.find((x) => x.id === id)?.label ?? id;
+
+// Shared form-input styling for the Privacy drawers (was copy-pasted verbatim
+// in each of them).
+export const INPUT_CLS = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white text-sm focus:outline-none focus:border-port-accent';
+
+// Path to a Privacy tab under the active household subject (#3658). `self` is
+// the server's default scope, so it is elided from the URL. Deliberately drops
+// any other search param (e.g. the brokers tab's `?case=`) — a cross-tab link
+// must not reopen a drawer belonging to the tab you just left.
+export const privacyTabPath = (tab, subjectId) =>
+ `/privacy/${tab}${!subjectId || subjectId === SELF_SUBJECT_ID ? '' : `?subject=${subjectId}`}`;
diff --git a/client/src/pages/Privacy.jsx b/client/src/pages/Privacy.jsx
index 7e84f66d08..7a55f79af9 100644
--- a/client/src/pages/Privacy.jsx
+++ b/client/src/pages/Privacy.jsx
@@ -1,6 +1,9 @@
+import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { Shield, LayoutDashboard, KeyRound, Building2, Repeat, ShieldOff } from 'lucide-react';
import { useValidTab } from '../hooks/useValidTab';
+import useUrlParams from '../hooks/useUrlParams';
+import { getPrivacySubjects } from '../services/api';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
import PrivacyOverviewTab from '../components/privacy/PrivacyOverviewTab';
@@ -8,6 +11,9 @@ import PrivacyVaultTab from '../components/privacy/PrivacyVaultTab';
import PrivacyOrgsTab from '../components/privacy/PrivacyOrgsTab';
import PrivacyChangesTab from '../components/privacy/PrivacyChangesTab';
import PrivacyBrokersTab from '../components/privacy/PrivacyBrokersTab';
+import SubjectSwitcher from '../components/privacy/SubjectSwitcher';
+import SubjectsDrawer from '../components/privacy/SubjectsDrawer';
+import { SELF_SUBJECT_ID, privacyTabPath } from '../components/privacy/constants';
// 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.
@@ -22,15 +28,50 @@ export const TABS = [
export default function Privacy() {
const navigate = useNavigate();
const activeTab = useValidTab(TABS, 'overview');
+ const [searchParams, updateParams] = useUrlParams();
+ const [subjects, setSubjects] = useState([]);
+ const [drawerOpen, setDrawerOpen] = useState(false);
+
+ // Which household subject is in scope lives in the URL (#3658), so a view of
+ // a specific person's records is shareable and reload-safe — same rule as any
+ // other selection. An absent param means `self`, matching the server default.
+ const subjectId = searchParams.get('subject') || SELF_SUBJECT_ID;
+
+ useEffect(() => {
+ getPrivacySubjects({ silent: true })
+ .then((rows) => setSubjects(rows || []))
+ .catch(() => setSubjects([]));
+ }, []);
+
+ // `self` is the default scope, so it stays out of the URL entirely — a null
+ // patch value is `useUrlParams`'s delete signal.
+ const selectSubject = useCallback((id) => {
+ updateParams({ subject: id === SELF_SUBJECT_ID ? null : id }, { replace: true });
+ }, [updateParams]);
+
+ const handleCreated = (subject) => {
+ setSubjects((prev) => [...prev, { ...subject, consentCount: 1, recordCount: 0 }]);
+ selectSubject(subject.id);
+ };
+
+ const handleDeleted = (deletedId) => {
+ setSubjects((prev) => prev.filter((s) => s.id !== deletedId));
+ // Never strand the view on a subject that no longer exists.
+ if (deletedId === subjectId) selectSubject(SELF_SUBJECT_ID);
+ };
+
+ // 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));
const renderTab = () => {
switch (activeTab) {
- case 'vault': return <PrivacyVaultTab />;
- case 'organizations': return <PrivacyOrgsTab />;
- case 'changes': return <PrivacyChangesTab />;
- case 'brokers': return <PrivacyBrokersTab />;
+ 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 'overview':
- default: return <PrivacyOverviewTab />;
+ default: return <PrivacyOverviewTab subjectId={subjectId} />;
}
};
@@ -44,14 +85,35 @@ export default function Privacy() {
<TabPills
tabs={TABS}
activeTab={activeTab}
- onChange={(id) => navigate(`/privacy/${id}`)}
+ onChange={goToTab}
mobileDropdown
mobileSelectId="privacy-tab-select"
ariaLabel="Privacy Center sections"
/>
<div className="pt-4">
+ <SubjectSwitcher
+ subjects={subjects}
+ subjectId={subjectId}
+ onChange={selectSubject}
+ onManage={() => setDrawerOpen(true)}
+ />
+ </div>
+ {/* Keying on the subject remounts the tab when the scope changes, so ALL
+ of its local state resets at once — revealed plaintext, open drawers,
+ expanded rows, filters. Clearing those by hand inside each tab's
+ `load()` both missed some and fired on ordinary post-mutation
+ refetches, collapsing rows the user had just opened. */}
+ <div className="pt-4" key={subjectId}>
{renderTab()}
</div>
+
+ <SubjectsDrawer
+ open={drawerOpen}
+ subjects={subjects}
+ onClose={() => setDrawerOpen(false)}
+ onCreated={handleCreated}
+ onDeleted={handleDeleted}
+ />
</div>
);
}
diff --git a/client/src/pages/Privacy.test.jsx b/client/src/pages/Privacy.test.jsx
index e79b482db0..f20797cdc6 100644
--- a/client/src/pages/Privacy.test.jsx
+++ b/client/src/pages/Privacy.test.jsx
@@ -4,6 +4,20 @@ import { MemoryRouter, Routes, Route } from 'react-router';
// ── Mock the API surface ─────────────────────────────────────────────────────
vi.mock('../services/api', () => ({
+ // Household subjects (#3658) — `self` plus one consenting partner.
+ getPrivacySubjects: vi.fn().mockResolvedValue([
+ {
+ id: '00000000-0000-4000-8000-000000000001', displayName: 'Me', relationship: 'self',
+ isSelf: true, consentCount: 1, recordCount: 2,
+ },
+ {
+ id: 'sub-2', displayName: 'Alex', relationship: 'partner',
+ isSelf: false, consentCount: 1, recordCount: 1,
+ },
+ ]),
+ createPrivacySubject: vi.fn(),
+ deletePrivacySubject: vi.fn(),
+ getPrivacySubjectConsents: vi.fn().mockResolvedValue([]),
getPrivacyStatus: vi.fn().mockResolvedValue({
keyConfigured: true,
recordCounts: { address: 1, email: 1 },
@@ -60,7 +74,9 @@ vi.mock('../services/api', () => ({
}));
import Privacy from './Privacy';
-import { revealVaultRecord } from '../services/api';
+import { revealVaultRecord, getVaultRecords, getPrivacyStatus } from '../services/api';
+
+const SELF_ID = '00000000-0000-4000-8000-000000000001';
function renderAt(path) {
return render(
@@ -128,4 +144,43 @@ describe('Privacy Center', () => {
renderAt('/privacy/bogus');
await waitFor(() => expect(screen.getByText(/system of record/i)).toBeInTheDocument());
});
+
+ // ── Household subjects (#3658) ────────────────────────────────────────────
+ describe('household subjects', () => {
+ it('defaults the scope to self and lists the household in the switcher', async () => {
+ renderAt('/privacy/vault');
+ await waitFor(() => expect(screen.getByText('Home address')).toBeInTheDocument());
+ const select = await screen.findByLabelText('Subject');
+ expect(select).toHaveValue(SELF_ID);
+ expect(screen.getByRole('option', { name: /Alex · Partner/ })).toBeInTheDocument();
+ expect(getVaultRecords).toHaveBeenCalledWith(undefined, { subjectId: SELF_ID });
+ });
+
+ it('scopes every read to the subject named in the URL', async () => {
+ renderAt('/privacy/vault?subject=sub-2');
+ await waitFor(() => expect(getVaultRecords).toHaveBeenCalledWith(undefined, { subjectId: 'sub-2' }));
+ expect(getPrivacyStatus).toHaveBeenCalledWith({ subjectId: 'sub-2' });
+ });
+
+ it('flags when the view is scoped to someone other than self', async () => {
+ renderAt('/privacy/vault?subject=sub-2');
+ await waitFor(() => expect(screen.getByText(/not your own/i)).toBeInTheDocument());
+ expect(screen.getByText(/Viewing Alex/)).toBeInTheDocument();
+ });
+
+ it('switching subjects refetches under the new scope and lands in the URL', async () => {
+ renderAt('/privacy/vault');
+ await waitFor(() => screen.getByLabelText('Subject'));
+ fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'sub-2' } });
+ await waitFor(() => expect(getVaultRecords).toHaveBeenCalledWith(undefined, { subjectId: 'sub-2' }));
+ expect(screen.getByLabelText('Subject')).toHaveValue('sub-2');
+ });
+
+ it('keeps a stale ?subject deep link labeled rather than blank', async () => {
+ renderAt('/privacy/vault?subject=deleted-subject');
+ const select = await screen.findByLabelText('Subject');
+ await waitFor(() => expect(select).toHaveValue('deleted-subject'));
+ expect(screen.getByRole('option', { name: 'Unknown subject' })).toBeInTheDocument();
+ });
+ });
});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index d621ceae05..54a94119f0 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -131,7 +131,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiPalette.js` | Command-palette manifest + action dispatch. |
| `apiVoice.js` | Voice synthesis / processing. |
| `apiCity.js` | CyberCity snapshots — historical city-state series for the timeline scrubber (GET /snapshots, GET /config, POST /capture). |
-| `apiPrivacy.js` | Privacy Center — encrypted PII Vault + Trusted Organizations registry (status, vault CRUD + reveal, org CRUD, org holdings replace-set) + Digital Twin social-account cross-link. |
+| `apiPrivacy.js` | Privacy Center — encrypted PII Vault + Trusted Organizations registry (status, vault CRUD + reveal, org CRUD, org holdings replace-set) + Digital Twin social-account cross-link + household subjects (subject CRUD, consent audit, and a `subjectId` scope passed in each wrapper's trailing `options`). |
## Browser-facing (DOM, voice, build) — not pure API wrappers
diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.js
index c58760d129..d57ac7ad62 100644
--- a/client/src/services/apiPrivacy.js
+++ b/client/src/services/apiPrivacy.js
@@ -6,12 +6,49 @@ import { request } from './apiCore.js';
// UI (useAsyncAction, custom catch) can pass `{ silent: true }` per the toasting
// convention.
+// Household subjects (#3658): every scoped read/write takes an optional
+// `subjectId` inside that same trailing `options` object, so no pre-#3658 caller
+// changed signature. The server resolves an absent `subjectId` to the seeded
+// `self` subject, so omitting it reproduces the single-subject v1 behavior
+// exactly. There is no "all subjects" mode — the API scopes to exactly one.
+const scoped = (path, { subjectId, ...rest } = {}, params = {}) => {
+ const qs = new URLSearchParams(
+ Object.entries({ ...params, subjectId }).filter(([, v]) => v != null && v !== ''),
+ ).toString();
+ return [qs ? `${path}?${qs}` : path, rest];
+};
+
+// POST bodies carry `subjectId` inline instead of as a query param.
+const scopedPost = (path, { subjectId, ...rest } = {}) => [path, {
+ method: 'POST',
+ ...(subjectId ? { body: JSON.stringify({ subjectId }) } : {}),
+ ...rest,
+}];
+
+// ── Household subjects (#3658) ──────────────────────────────────────────────
+/** All subjects, `self` first, each with `consentCount` + `recordCount`. */
+export const getPrivacySubjects = (options) => request('/privacy/subjects', options);
+/** Create: { displayName, relationship?, consentMethod, consentNote? } — consent is mandatory. */
+export const createPrivacySubject = (data, options) => request('/privacy/subjects', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...options,
+});
+/** Hard delete — cascades this subject's vault records, orgs, changes, and cases. */
+export const deletePrivacySubject = (id, options) => request(`/privacy/subjects/${id}`, {
+ method: 'DELETE',
+ ...options,
+});
+/** Consent audit trail for one subject, newest first. */
+export const getPrivacySubjectConsents = (id, options) =>
+ request(`/privacy/subjects/${id}/consents`, options);
+
// ── Status (doctor-style readout) ───────────────────────────────────────────
-export const getPrivacyStatus = (options) => request('/privacy/status', options);
+export const getPrivacyStatus = (options) => request(...scoped('/privacy/status', options));
// ── Vault records ───────────────────────────────────────────────────────────
export const getVaultRecords = (type, options) =>
- request(`/privacy/vault${type ? `?type=${encodeURIComponent(type)}` : ''}`, options);
+ request(...scoped('/privacy/vault', options, { type }));
export const getVaultRecord = (id, options) => request(`/privacy/vault/${id}`, options);
export const createVaultRecord = (data, options) => request('/privacy/vault', {
method: 'POST',
@@ -34,12 +71,8 @@ export const revealVaultRecord = (id, options) => request(`/privacy/vault/${id}/
});
// ── Trusted Organizations registry ──────────────────────────────────────────
-export const getPrivacyOrgs = (filters = {}, options) => {
- const qs = new URLSearchParams(
- Object.entries(filters).filter(([, v]) => v != null && v !== ''),
- ).toString();
- return request(`/privacy/orgs${qs ? `?${qs}` : ''}`, options);
-};
+export const getPrivacyOrgs = (filters = {}, options) =>
+ request(...scoped('/privacy/orgs', options, filters));
export const getPrivacyOrg = (id, options) => request(`/privacy/orgs/${id}`, options);
export const createPrivacyOrg = (data, options) => request('/privacy/orgs', {
method: 'POST',
@@ -66,7 +99,7 @@ export const setOrgHoldings = (id, holdings, options) => request(`/privacy/orgs/
});
// ── Change-of-address events + inventory (#2143) ────────────────────────────
-export const getPrivacyChanges = (options) => request('/privacy/changes', options);
+export const getPrivacyChanges = (options) => request(...scoped('/privacy/changes', options));
export const getPrivacyChange = (id, options) => request(`/privacy/changes/${id}`, options);
// Declare a change: { vaultRecordId, replacement?|replacementRecordId?, kind?, note? }.
export const declarePrivacyChange = (data, options) => request('/privacy/changes', {
@@ -99,7 +132,7 @@ export const refreshPrivacyBrokers = (options) => request('/privacy/brokers/refr
});
/** 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);
+ request(...scoped('/privacy/broker-cases', options, { state }));
/** Force a case due for recheck now. */
export const recheckPrivacyCase = (id, options) =>
request(`/privacy/broker-cases/${id}/recheck`, { method: 'POST', ...options });
@@ -110,13 +143,13 @@ export const transitionPrivacyCase = (id, toState, reason, options) => request(`
...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 });
+export const getPrivacyScanStatus = (options) => request(...scoped('/privacy/scan/status', options));
+/** Run a read-only exposure scan pass over enabled brokers. Refused without consent. */
+export const runPrivacyScan = (options) => request(...scopedPost('/privacy/scan', 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 });
+export const runPrivacyOptOut = (options) => request(...scopedPost('/privacy/optout', options));
/** Human-task digest: cases needing a person (blocked / human-only channels). */
-export const getPrivacyOptOutDigest = (options) => request('/privacy/optout/digest', options);
+export const getPrivacyOptOutDigest = (options) => request(...scoped('/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. */
diff --git a/server/lib/privacyValidation.mirror.test.js b/server/lib/privacyValidation.mirror.test.js
new file mode 100644
index 0000000000..b4135da46c
--- /dev/null
+++ b/server/lib/privacyValidation.mirror.test.js
@@ -0,0 +1,84 @@
+/**
+ * Mirror parity: server/lib/privacyValidation.js ↔ client/src/components/privacy/constants.js
+ *
+ * The client's constants file opens by claiming it is "kept in sync with the
+ * server Zod schemas — a mismatch would let the UI offer a value the API
+ * rejects." Until now nothing enforced that claim, so the sync was a comment.
+ *
+ * Household subjects (#3658) made the drift expensive rather than cosmetic: the
+ * consent-method list is what a user picks when adding a person, and a method
+ * the server enum doesn't carry means the add fails at the last click — after
+ * they've typed a name and chosen how consent was captured.
+ *
+ * The two sides intentionally differ in SHAPE: the server holds bare id arrays
+ * for `z.enum()`, the client holds `[{ id, label }]` so the UI has display text.
+ * Only the id sets are compared, so adding or rewording a label is free.
+ *
+ * Safe to import the client module from a server suite: constants.js has zero
+ * imports (a dep-free leaf), so this does not drag client-only packages into
+ * the server job's dependency set.
+ */
+
+import { describe, it, expect } from 'vitest';
+import * as server from './privacyValidation.js';
+import * as client from '../../client/src/components/privacy/constants.js';
+
+// [client export, server export] — every enum the UI offers as a choice.
+const MIRRORED_ENUMS = [
+ ['SUBJECT_RELATIONSHIPS', 'PRIVACY_SUBJECT_RELATIONSHIPS'],
+ ['CONSENT_METHODS', 'PRIVACY_CONSENT_METHODS'],
+ ['CONSENT_SCOPES', 'PRIVACY_CONSENT_SCOPES'],
+ ['VAULT_TYPES', 'PRIVACY_VAULT_TYPES'],
+ ['VAULT_STATUSES', 'PRIVACY_VAULT_STATUSES'],
+ ['ORG_CATEGORIES', 'PRIVACY_ORG_CATEGORIES'],
+ ['ORG_TRUST_LEVELS', 'PRIVACY_ORG_TRUST_LEVELS'],
+ ['ORG_STATUSES', 'PRIVACY_ORG_STATUSES'],
+ ['ORG_HOLDING_STATUSES', 'PRIVACY_ORG_HOLDING_STATUSES'],
+ ['CHANGE_KINDS', 'PRIVACY_CHANGE_KINDS'],
+ ['CASE_STATES', 'PRIVACY_BROKER_CASE_STATES'],
+];
+
+describe('privacy enums server↔client mirror parity', () => {
+ it.each(MIRRORED_ENUMS)('%s matches %s', (clientName, serverName) => {
+ const clientList = client[clientName];
+ const serverList = server[serverName];
+ expect(Array.isArray(clientList), `client ${clientName} missing`).toBe(true);
+ expect(Array.isArray(serverList), `server ${serverName} missing`).toBe(true);
+ // Order is a UI concern (display order); membership is the contract.
+ expect([...clientList.map((x) => x.id)].sort()).toEqual([...serverList].sort());
+ });
+
+ it.each(MIRRORED_ENUMS)('%s entries all carry a display label', (clientName) => {
+ for (const entry of client[clientName]) {
+ expect(typeof entry.label, `${clientName}.${entry.id} label`).toBe('string');
+ expect(entry.label.length).toBeGreaterThan(0);
+ }
+ });
+
+ // Flat id arrays on both sides — no { id, label } shape to unwrap.
+ it('SENSITIVE_TYPES matches PRIVACY_SENSITIVE_TYPES', () => {
+ expect([...client.SENSITIVE_TYPES].sort()).toEqual([...server.PRIVACY_SENSITIVE_TYPES].sort());
+ });
+
+ // Not an enum, but the same class of drift: the client defaults its subject
+ // scope to this id, so a mismatch would scope the whole UI to a subject the
+ // server has never heard of.
+ it('SELF_SUBJECT_ID matches PRIVACY_SELF_SUBJECT_ID', () => {
+ expect(client.SELF_SUBJECT_ID).toBe(server.PRIVACY_SELF_SUBJECT_ID);
+ });
+
+ it('every sensitive type is a real vault type', () => {
+ const vaultIds = client.VAULT_TYPES.map((t) => t.id);
+ for (const t of client.SENSITIVE_TYPES) expect(vaultIds).toContain(t);
+ });
+
+ // The tone tables are pre-composed Tailwind tokens keyed by enum id; a state
+ // added to one side and not the other renders an unstyled badge.
+ it('CASE_STATE_TONE covers every case state', () => {
+ for (const s of client.CASE_STATES) expect(client.CASE_STATE_TONE).toHaveProperty(s.id);
+ });
+
+ it('TRUST_TONE covers every trust level', () => {
+ for (const t of client.ORG_TRUST_LEVELS) expect(client.TRUST_TONE).toHaveProperty(t.id);
+ });
+});
diff --git a/server/services/privacySubjects.db.test.js b/server/services/privacySubjects.db.test.js
new file mode 100644
index 0000000000..07f0cc7fe9
--- /dev/null
+++ b/server/services/privacySubjects.db.test.js
@@ -0,0 +1,181 @@
+/**
+ * Postgres-backed round-trip for household subjects (issue #3658).
+ *
+ * Covers the subject lifecycle itself — CRUD, the `self` invariants, the
+ * consent audit trail, and the engine-level consent guard that `privacyScan`
+ * and `privacyOptOut` rely on. The vault-side scoping/cascade assertions live
+ * in privacyVault.db.test.js; this file owns the subject surface.
+ *
+ * SKIPS cleanly when no DB is reachable. Cleans up only rows it created — no
+ * global table mutation. Runs via `npm run test:db` (→ portos_test) ONLY; the
+ * db.js guards refuse writes to a non-test DB.
+ */
+
+import { describe, it, expect, afterAll, beforeAll } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+
+// A valid key BEFORE the service is imported/called so ensureVaultKey never
+// touches the repo's real .env during the run (createVaultRecord encrypts).
+const HEX_KEY = 'e'.repeat(64);
+const originalKey = process.env.PRIVACY_VAULT_KEY;
+process.env.PRIVACY_VAULT_KEY = HEX_KEY;
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'privacy_subjects') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'privacy_subjects table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ privacySubjects.db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('privacy household subjects DB round-trip', () => {
+ let subjects;
+ let vault;
+ let selfSubjectId = '';
+ const createdSubjects = [];
+
+ // Register for cleanup BEFORE asserting, so a mid-test failure still tidies up.
+ const track = (subject) => { createdSubjects.push(subject.id); return subject; };
+
+ beforeAll(async () => {
+ subjects = await import('./privacySubjects.js');
+ vault = await import('./privacyVault.js');
+ selfSubjectId = (await import('../lib/privacyValidation.js')).PRIVACY_SELF_SUBJECT_ID;
+ });
+
+ afterAll(async () => {
+ // Child rows (vault records, consents, orgs, cases) go by FK CASCADE.
+ for (const id of createdSubjects) {
+ await query(`DELETE FROM privacy_subjects WHERE id = $1`, [id]).catch(() => {});
+ }
+ await close();
+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;
+ else process.env.PRIVACY_VAULT_KEY = originalKey;
+ });
+
+ it('seeds a self subject that lists first and is flagged isSelf', async () => {
+ const list = await subjects.listSubjects();
+ expect(list.length).toBeGreaterThan(0);
+ expect(list[0].id).toBe(selfSubjectId);
+ expect(list[0].isSelf).toBe(true);
+ // Every other subject is explicitly not-self — the flag is derived, not stored.
+ expect(list.slice(1).every((s) => s.isSelf === false)).toBe(true);
+ });
+
+ it('refuses to delete the self subject', async () => {
+ await expect(subjects.deleteSubject(selfSubjectId)).rejects.toMatchObject({
+ status: 400,
+ code: 'SELF_SUBJECT_UNDELETABLE',
+ });
+ // Still there — the guard must not have half-deleted anything.
+ expect(await subjects.getSubject(selfSubjectId)).toMatchObject({ id: selfSubjectId });
+ });
+
+ it('creates a subject with its consent row in one transaction', async () => {
+ const subject = track(await subjects.createSubject({
+ displayName: 'Example Partner',
+ relationship: 'partner',
+ consentMethod: 'signed_form',
+ consentNote: 'form filed',
+ }));
+
+ expect(subject).toMatchObject({ displayName: 'Example Partner', relationship: 'partner', isSelf: false });
+
+ const consents = await subjects.listSubjectConsents(subject.id);
+ expect(consents).toHaveLength(1);
+ expect(consents[0]).toMatchObject({
+ subjectId: subject.id, scope: 'pii_vault', method: 'signed_form', note: 'form filed',
+ });
+ expect(await subjects.hasActiveConsent(subject.id)).toBe(true);
+ });
+
+ it('reports consent and record counts on the list', async () => {
+ const subject = track(await subjects.createSubject({
+ displayName: 'Example Counted', relationship: 'parent', consentMethod: 'verbal',
+ }));
+ await vault.createVaultRecord({
+ type: 'email', label: 'Their email', value: '[email protected]', subjectId: subject.id,
+ });
+
+ const row = (await subjects.listSubjects()).find((s) => s.id === subject.id);
+ expect(row).toMatchObject({ consentCount: 1, recordCount: 1 });
+ });
+
+ it('renames without disturbing consent', async () => {
+ const subject = track(await subjects.createSubject({
+ displayName: 'Example Before', relationship: 'other', consentMethod: 'verbal',
+ }));
+ const updated = await subjects.updateSubject(subject.id, {
+ displayName: 'Example After', relationship: 'dependent',
+ });
+
+ expect(updated).toMatchObject({ displayName: 'Example After', relationship: 'dependent' });
+ // A rename is not a re-consent — the audit trail is untouched.
+ expect(await subjects.listSubjectConsents(subject.id)).toHaveLength(1);
+ });
+
+ it('appends to the consent audit trail newest-first', async () => {
+ const subject = track(await subjects.createSubject({
+ displayName: 'Example Audited', relationship: 'partner', consentMethod: 'verbal',
+ }));
+ await subjects.recordConsent({
+ subjectId: subject.id, scope: 'broker_optout', method: 'written', note: 'second scope',
+ });
+
+ // Appending a second scope never replaces the first — consent accretes.
+ const consents = await subjects.listSubjectConsents(subject.id);
+ expect(consents).toHaveLength(2);
+ expect(consents.map((c) => c.scope).sort()).toEqual(['broker_optout', 'pii_vault']);
+ expect(consents.find((c) => c.scope === 'broker_optout')).toMatchObject({
+ method: 'written', note: 'second scope',
+ });
+ });
+
+ it('404s an unknown subject rather than leaking a raw FK violation', async () => {
+ await expect(subjects.assertSubject('00000000-0000-4000-8000-0000000000ff')).rejects.toMatchObject({
+ status: 404,
+ code: 'SUBJECT_NOT_FOUND',
+ });
+ });
+
+ it('refuses engine actions for a subject whose consent was revoked', 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',
+ });
+ });
+
+ it('deleting a subject cascades their consent rows', async () => {
+ const subject = track(await subjects.createSubject({
+ displayName: 'Example Doomed', relationship: 'child', consentMethod: 'guardian',
+ }));
+ await subjects.deleteSubject(subject.id);
+ createdSubjects.pop(); // deleted here — nothing left for afterAll to clean.
+
+ const { rows } = await query(
+ `SELECT id FROM privacy_consents WHERE subject_id = $1`, [subject.id],
+ );
+ expect(rows).toHaveLength(0);
+ await expect(subjects.getSubject(subject.id)).resolves.toBeNull();
+ });
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 92d2c45f5c..bdc0609d98 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -14,6 +14,7 @@ export const DB_TEST_INCLUDE = [
'services/catalogDB.facets.db.test.js',
'services/humanActivity.db.test.js',
'services/memoryDB.db.test.js',
+ 'services/privacySubjects.db.test.js',
'services/privacyVault.db.test.js',
'services/privacyOrgs.db.test.js',
'services/privacyChanges.db.test.js',