Skip to content

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

feat([issue-2143]): Privacy Center change-of-address events + inventory workflow

Adam Eivya3ffdd6a19e1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 03d3420647..cb3f6d535f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,7 @@
- **[issue-2142] A new Privacy Center UI puts your encrypted PII vault and the organizations that hold it in one place.** Building on the Phase 1 encrypted vault (#2140) and Phase 2 trusted-organizations registry (#2141), a deep-linkable `/privacy/:tab` page (Identity → Privacy, `⌘K`/voice-navigable) ships three tabs: **Overview** — a doctor-style readout of whether AES-256-GCM encryption is engaged, vault record counts by type, and org counts by trust stance, with quick-jump cards into the other tabs; **Vault** — records grouped by type showing only the precomputed masked value (`•••, Portland OR` / `a•••@example.com`), with per-record "Share with Twin" / "Use for scans" optimistic toggles (hard-disabled for sensitive SSN/passport/license/financial types), a create/edit `Drawer`, and an explicit per-record **Reveal** action that decrypts plaintext only on click (never cached in list state) — plaintext never renders until you ask for it; **Organizations** — a trust/category/status chip-filtered list with per-org holdings status badges and a create/edit drawer whose holdings picker checkboxes over your vault records (masked) to record which fields each org holds. All mutations update local state directly (no full-list refetch), deletes use an inline confirm row (no `window.confirm`), and every tab is usable at 360px. Each tab path is registered in the nav manifest (`nav.identity.privacy-*`). (`client/src/pages/Privacy.jsx`, `client/src/components/privacy/`, `client/src/services/apiPrivacy.js`, `server/lib/navManifest.js`)
- **[issue-2144] The Privacy Center can now find where you're exposed on people-search sites.** Phase 5 of the Privacy Center (epic #2138) adds a database of ~20 major data brokers (Spokeo, Whitepages, BeenVerified, Radaris, MyLife, and the PeopleConnect cluster — Intelius/TruthFinder/Instant Checkmate/US Search), a read-only exposure scan that searches each broker using only the identity facts you've marked as scan-eligible in the vault (never your SSN, passport, license, or financial details), and a per-broker case ledger that tracks each listing through its removal lifecycle. Scans respect a hard rule: a CAPTCHA or bot-wall is recorded as "blocked" and never bypassed, and a broker can only be marked "removed" by a fresh scan that confirms your listing is actually gone — never by a submission page saying so. Nothing runs on startup: the broker list loads on first view and you can grow it on demand from the public BADBOOL and California data-broker registries (your curated brokers are never overwritten), and scans run only when you start one or schedule them. This is the data + scan backbone for the upcoming opt-out automation (Phase 6) and Brokers UI tab.
+- **[issue-2143] Moved, changed your number, or got a new email? The Privacy Center now tracks who still needs updating.** Phase 4 of the Privacy Center (epic #2138) adds a change-of-address inventory: a new **Changes** tab (`/privacy/changes`, `⌘K`/voice-navigable under Identity) where you declare "this field changed from A to B" — the old vault record is retired to `previous` (with an end date), a new encrypted record is created for the new value, and every organization recorded as holding the old value is automatically flagged **update pending**. You then work the checklist per organization — mark **updated** once they've got the new value, mark **removed** if they dropped the field entirely — with a live progress bar per change that reads "done" only when zero orgs are still pending. For any org with a contact email you can draft a plain "please update my records" email (old → new) straight into the Comms drafts queue as an **unapproved** draft you review before it ever sends (template-only, no AI, no auto-send). Works for any field, not just addresses — phone, email, and name changes get their own change type. All privacy records stay encrypted-at-rest and machine-local; the inventory joins only masked values, never plaintext. (`server/services/privacyChanges.js`, `server/routes/privacy.js`, `server/lib/privacyValidation.js`, `server/lib/db.js`, `client/src/pages/Privacy.jsx`, `client/src/components/privacy/{PrivacyChangesTab,DeclareChangeDrawer}.jsx`, `client/src/services/apiPrivacy.js`, `server/lib/navManifest.js`)
## Layered Intelligence
diff --git a/client/src/components/privacy/DeclareChangeDrawer.jsx b/client/src/components/privacy/DeclareChangeDrawer.jsx
new file mode 100644
index 0000000000..ac09ae128f
--- /dev/null
+++ b/client/src/components/privacy/DeclareChangeDrawer.jsx
@@ -0,0 +1,137 @@
+import { useState, useEffect, useMemo } from 'react';
+import Drawer from '../Drawer';
+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';
+
+// 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
+// `update_pending`. The replacement record is created inline (type inherited
+// from the old record). Only `current` records are eligible — a `previous`
+// record has already been retired.
+export default function DeclareChangeDrawer({ open, vaultRecords, onClose, onDeclared }) {
+ const eligible = useMemo(
+ () => (vaultRecords || []).filter((r) => r.status === 'current'),
+ [vaultRecords],
+ );
+
+ const [oldRecordId, setOldRecordId] = useState('');
+ const [label, setLabel] = useState('');
+ const [value, setValue] = useState('');
+ const [note, setNote] = useState('');
+
+ useEffect(() => {
+ if (!open) return;
+ const first = eligible[0]?.id ?? '';
+ setOldRecordId(first);
+ setLabel('');
+ setValue('');
+ setNote('');
+ }, [open, eligible]);
+
+ const oldRecord = eligible.find((r) => r.id === oldRecordId) || null;
+ const derivedKind = oldRecord ? (KIND_FOR_TYPE[oldRecord.type] ?? 'other') : 'other';
+
+ const [declare, declaring] = useAsyncAction(async () => {
+ if (!oldRecordId) { toast.error('Pick the record that changed'); return null; }
+ if (!label.trim()) { toast.error('New value label is required'); return null; }
+ if (!value.trim()) { toast.error('New value is required'); return null; }
+ const event = await declarePrivacyChange({
+ vaultRecordId: oldRecordId,
+ replacement: { label: label.trim(), value: value.trim() },
+ kind: derivedKind,
+ note: note.trim() || undefined,
+ }, { silent: true });
+ if (!event) return null;
+ toast.success('Change declared — orgs flagged for update');
+ onDeclared(event);
+ return event;
+ }, { errorMessage: 'Failed to declare change' });
+
+ return (
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="Declare a change"
+ subtitle="Flag every org holding the old value for an update"
+ size="md"
+ closeOnEsc={false}
+ closeOnBackdrop={false}
+ >
+ {eligible.length === 0 ? (
+ <p className="text-sm text-gray-500">
+ No current vault records yet. Add a record in the Vault tab first, then declare a change when its value updates.
+ </p>
+ ) : (
+ <form className="space-y-4" onSubmit={(e) => { e.preventDefault(); declare(); }}>
+ <FormField label="Record that changed">
+ <select
+ id="declare-old-record"
+ value={oldRecordId}
+ onChange={(e) => setOldRecordId(e.target.value)}
+ className={inputCls}
+ >
+ {eligible.map((r) => (
+ <option key={r.id} value={r.id}>
+ {labelFor(VAULT_TYPES, r.type)} — {r.label} ({r.maskedValue})
+ </option>
+ ))}
+ </select>
+ </FormField>
+
+ <div className="text-xs text-gray-500">
+ Change type: <span className="text-gray-300">{labelFor(CHANGE_KINDS, derivedKind)}</span>
+ </div>
+
+ <FormField label="New value label">
+ <input
+ id="declare-new-label"
+ type="text"
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ placeholder="e.g. New home address"
+ className={inputCls}
+ maxLength={200}
+ />
+ </FormField>
+
+ <FormField label="New value">
+ <input
+ id="declare-new-value"
+ type="text"
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder="The new value (encrypted at rest)"
+ className={inputCls}
+ maxLength={10000}
+ />
+ </FormField>
+
+ <FormField label="Note (optional)">
+ <textarea
+ id="declare-note"
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ rows={2}
+ className={inputCls}
+ maxLength={5000}
+ />
+ </FormField>
+
+ <div className="flex justify-end gap-2 pt-2">
+ <button type="button" onClick={onClose} className="px-3 py-2 text-sm rounded border border-port-border text-gray-300 hover:text-white">
+ Cancel
+ </button>
+ <button type="submit" disabled={declaring} className="px-3 py-2 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">
+ {declaring ? 'Declaring…' : 'Declare change'}
+ </button>
+ </div>
+ </form>
+ )}
+ </Drawer>
+ );
+}
diff --git a/client/src/components/privacy/PrivacyChangesTab.jsx b/client/src/components/privacy/PrivacyChangesTab.jsx
new file mode 100644
index 0000000000..e842352c7b
--- /dev/null
+++ b/client/src/components/privacy/PrivacyChangesTab.jsx
@@ -0,0 +1,238 @@
+import { useState, useEffect, useCallback } from 'react';
+import {
+ Plus, Repeat, ChevronDown, ChevronRight, ExternalLink, Check, Ban, Mail, ArrowRight,
+} from 'lucide-react';
+import {
+ getPrivacyChanges, getPrivacyChange, getVaultRecords,
+ markChangeOrgUpdated, markChangeOrgRemoved, draftChangeUpdateEmail,
+} from '../../services/api';
+import toast from '../ui/Toast';
+import DeclareChangeDrawer from './DeclareChangeDrawer';
+import { VAULT_TYPES, CHANGE_KINDS, labelFor } from './constants';
+
+// A slim progress bar over pending/updated/removed. Done = zero pending.
+function ProgressBar({ progress }) {
+ const { total = 0, pending = 0, updated = 0, removed = 0 } = progress || {};
+ const done = updated + removed;
+ const pct = total === 0 ? 0 : Math.round((done / total) * 100);
+ return (
+ <div className="min-w-[140px]">
+ <div className="h-1.5 rounded bg-port-border overflow-hidden">
+ <div
+ className={`h-full ${total > 0 && pending === 0 ? 'bg-port-success' : 'bg-port-accent'}`}
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <div className="mt-1 text-[10px] text-gray-500">
+ {total === 0 ? 'No orgs held this value' : `${done}/${total} handled${pending === 0 ? ' — done' : ''}`}
+ </div>
+ </div>
+ );
+}
+
+// One org row inside an expanded event's checklist.
+function OrgRow({ org, status, eventId, hasReplacement, onChanged }) {
+ const [busy, setBusy] = useState(false);
+
+ const act = async (fn, okMsg) => {
+ setBusy(true);
+ const res = await fn().catch(() => null);
+ setBusy(false);
+ if (res) { onChanged(res); if (okMsg) toast.success(okMsg); }
+ else toast.error('Action failed');
+ };
+
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2 py-2 border-b border-port-border/40 last:border-0">
+ <div className="min-w-0 flex-1">
+ <span className="text-sm text-white truncate">{org.orgName}</span>
+ {org.contactEmail && <span className="ml-2 text-[11px] text-gray-500">{org.contactEmail}</span>}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ {org.website && (
+ <a href={org.website} target="_blank" rel="noreferrer" title="Open website" aria-label="Open website"
+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50">
+ <ExternalLink size={14} />
+ </a>
+ )}
+ {status === 'pending' ? (
+ <>
+ {hasReplacement && org.contactEmail && (
+ <button
+ onClick={() => act(() => draftChangeUpdateEmail(eventId, org.orgId, { silent: true }), 'Draft added to Comms queue')}
+ disabled={busy} title="Draft update email" aria-label="Draft update email"
+ className="p-1.5 rounded text-gray-400 hover:text-port-accent hover:bg-port-border/50 disabled:opacity-50">
+ <Mail size={14} />
+ </button>
+ )}
+ <button
+ onClick={() => act(() => markChangeOrgUpdated(eventId, org.orgId, { silent: true }), 'Marked updated')}
+ disabled={busy} title="Mark updated" aria-label="Mark updated"
+ className="p-1.5 rounded text-gray-400 hover:text-port-success hover:bg-port-border/50 disabled:opacity-50">
+ <Check size={15} />
+ </button>
+ <button
+ onClick={() => act(() => markChangeOrgRemoved(eventId, org.orgId, { silent: true }), 'Marked removed')}
+ disabled={busy} title="Mark removed (org dropped this data)" aria-label="Mark removed"
+ className="p-1.5 rounded text-gray-400 hover:text-port-error hover:bg-port-border/50 disabled:opacity-50">
+ <Ban size={15} />
+ </button>
+ </>
+ ) : (
+ <span className={`text-[10px] px-1.5 py-0.5 rounded border ${status === 'updated' ? 'bg-port-success/15 text-port-success border-port-success/30' : 'bg-gray-700/40 text-gray-400 border-gray-600/40'}`}>
+ {status === 'updated' ? 'Updated' : 'Removed'}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Group heading + rows for one status bucket in an expanded event.
+function StatusGroup({ title, orgs, status, eventId, hasReplacement, onChanged }) {
+ if (!orgs || orgs.length === 0) return null;
+ return (
+ <div className="mt-3">
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1">{title} ({orgs.length})</div>
+ <div>
+ {orgs.map((org) => (
+ <OrgRow key={org.orgId} org={org} status={status} eventId={eventId} hasReplacement={hasReplacement} onChanged={onChanged} />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export default function PrivacyChangesTab() {
+ const [events, setEvents] = useState([]);
+ const [vaultRecords, setVaultRecords] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [drawerOpen, setDrawerOpen] = useState(false);
+ const [expanded, setExpanded] = useState(null); // eventId
+ const [detail, setDetail] = useState(null); // { event, oldRecord, replacementRecord, progress }
+ const [detailLoading, setDetailLoading] = useState(false);
+
+ const load = useCallback(() => {
+ setLoading(true);
+ Promise.allSettled([getPrivacyChanges(), getVaultRecords()]).then(([e, v]) => {
+ setEvents(e.status === 'fulfilled' ? e.value : []);
+ setVaultRecords(v.status === 'fulfilled' ? v.value : []);
+ setLoading(false);
+ });
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const toggle = async (eventId) => {
+ if (expanded === eventId) { setExpanded(null); setDetail(null); return; }
+ setExpanded(eventId);
+ setDetail(null);
+ setDetailLoading(true);
+ const d = await getPrivacyChange(eventId, { silent: true }).catch(() => null);
+ setDetailLoading(false);
+ setDetail(d);
+ };
+
+ const handleDeclared = (event) => {
+ setDrawerOpen(false);
+ setEvents((prev) => [
+ { ...event, progress: { pending: 0, updated: 0, removed: 0, total: 0 } },
+ ...prev,
+ ]);
+ // Refresh so the new event's progress counts + masked values are populated.
+ load();
+ };
+
+ // A per-org action returns the fresh progress groups — recompute counts for
+ // both the expanded detail and the collapsed list bar.
+ const applyProgress = (eventId, groups) => {
+ setDetail((prev) => (prev && prev.event.id === eventId ? { ...prev, progress: groups } : prev));
+ const counts = {
+ pending: groups.pending.length,
+ updated: groups.updated.length,
+ removed: groups.removed.length,
+ total: groups.pending.length + groups.updated.length + groups.removed.length,
+ };
+ setEvents((prev) => prev.map((ev) => (ev.id === eventId ? { ...ev, progress: counts } : ev)));
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-xs text-gray-500 max-w-lg">
+ Declare "field X changed from A to B" — every org holding the old value is flagged for an update, and you work the checklist until everyone is current.
+ </p>
+ <button onClick={() => setDrawerOpen(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 self-start">
+ <Plus size={16} /> Declare change
+ </button>
+ </div>
+
+ {loading ? (
+ <div className="text-gray-500 text-sm py-8 text-center">Loading changes…</div>
+ ) : events.length === 0 ? (
+ <div className="border border-dashed border-port-border rounded-lg p-8 text-center text-gray-500 text-sm">
+ No changes declared yet. When an address, phone, or email changes, declare it here to track who still needs updating.
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {events.map((ev) => {
+ const isOpen = expanded === ev.id;
+ return (
+ <div key={ev.id} className="bg-port-card border border-port-border rounded-lg">
+ <button onClick={() => toggle(ev.id)} className="w-full flex flex-wrap items-center gap-3 p-3 text-left">
+ {isOpen ? <ChevronDown size={16} className="text-gray-500 shrink-0" /> : <ChevronRight size={16} className="text-gray-500 shrink-0" />}
+ <Repeat size={15} className="text-gray-500 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 flex-wrap text-sm">
+ <span className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ {labelFor(CHANGE_KINDS, ev.kind)}
+ </span>
+ <span className="text-gray-300 truncate">{ev.oldRecord?.maskedValue}</span>
+ <ArrowRight size={13} className="text-gray-600 shrink-0" />
+ <span className="text-white truncate">{ev.replacementRecord?.maskedValue ?? 'removed'}</span>
+ </div>
+ <div className="text-[11px] text-gray-600 mt-0.5">
+ {labelFor(VAULT_TYPES, ev.oldRecord?.type)} · {ev.declaredAt ? new Date(ev.declaredAt).toLocaleDateString() : ''}
+ </div>
+ </div>
+ <ProgressBar progress={ev.progress} />
+ </button>
+
+ {isOpen && (
+ <div className="px-3 pb-3 border-t border-port-border/40">
+ {detailLoading || !detail ? (
+ <div className="text-gray-500 text-xs py-4 text-center">Loading inventory…</div>
+ ) : (
+ <>
+ {ev.note && <p className="text-xs text-gray-500 mt-3 italic">{ev.note}</p>}
+ {(detail.progress.pending.length + detail.progress.updated.length + detail.progress.removed.length) === 0 ? (
+ <p className="text-xs text-gray-500 py-4">No organizations were recorded as holding this value.</p>
+ ) : (
+ <>
+ <StatusGroup title="Needs update" orgs={detail.progress.pending} status="pending" eventId={ev.id}
+ hasReplacement={!!ev.replacementRecordId} onChanged={(g) => applyProgress(ev.id, g)} />
+ <StatusGroup title="Updated" orgs={detail.progress.updated} status="updated" eventId={ev.id}
+ hasReplacement={!!ev.replacementRecordId} onChanged={(g) => applyProgress(ev.id, g)} />
+ <StatusGroup title="Removed" orgs={detail.progress.removed} status="removed" eventId={ev.id}
+ hasReplacement={!!ev.replacementRecordId} onChanged={(g) => applyProgress(ev.id, g)} />
+ </>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ <DeclareChangeDrawer
+ open={drawerOpen}
+ vaultRecords={vaultRecords}
+ onClose={() => setDrawerOpen(false)}
+ onDeclared={handleDeclared}
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/privacy/constants.js b/client/src/components/privacy/constants.js
index c987172574..f0ccab0f48 100644
--- a/client/src/components/privacy/constants.js
+++ b/client/src/components/privacy/constants.js
@@ -56,6 +56,24 @@ export const ORG_HOLDING_STATUSES = [
{ id: 'unknown', label: 'Unknown' },
];
+// Change-of-address event kinds (issue #2143) — mirrors PRIVACY_CHANGE_KINDS.
+export const CHANGE_KINDS = [
+ { id: 'address_change', label: 'Address change' },
+ { id: 'phone_change', label: 'Phone change' },
+ { id: 'email_change', label: 'Email change' },
+ { id: 'name_change', label: 'Name change' },
+ { id: 'other', label: 'Other' },
+];
+
+// Which vault type each change kind operates on — drives the Declare drawer's
+// record picker and the derived default kind.
+export const KIND_FOR_TYPE = {
+ address: 'address_change',
+ phone: 'phone_change',
+ email: 'email_change',
+ legal_name: 'name_change',
+};
+
// Tailwind tone classes per trust level (pre-composed — the JIT needs whole tokens).
export const TRUST_TONE = {
trusted: 'bg-port-success/15 text-port-success border-port-success/30',
diff --git a/client/src/pages/Privacy.jsx b/client/src/pages/Privacy.jsx
index 0c56bfbab0..efce44cc85 100644
--- a/client/src/pages/Privacy.jsx
+++ b/client/src/pages/Privacy.jsx
@@ -1,11 +1,12 @@
import { useNavigate } from 'react-router-dom';
-import { Shield, LayoutDashboard, KeyRound, Building2 } from 'lucide-react';
+import { Shield, LayoutDashboard, KeyRound, Building2, Repeat } from 'lucide-react';
import { useValidTab } from '../hooks/useValidTab';
import PageHeader from '../components/PageHeader';
import TabPills from '../components/ui/TabPills';
import PrivacyOverviewTab from '../components/privacy/PrivacyOverviewTab';
import PrivacyVaultTab from '../components/privacy/PrivacyVaultTab';
import PrivacyOrgsTab from '../components/privacy/PrivacyOrgsTab';
+import PrivacyChangesTab from '../components/privacy/PrivacyChangesTab';
// 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.
@@ -13,6 +14,7 @@ export const TABS = [
{ id: 'overview', label: 'Overview', icon: LayoutDashboard },
{ id: 'vault', label: 'Vault', icon: KeyRound },
{ id: 'organizations', label: 'Organizations', icon: Building2 },
+ { id: 'changes', label: 'Changes', icon: Repeat },
];
export default function Privacy() {
@@ -23,6 +25,7 @@ export default function Privacy() {
switch (activeTab) {
case 'vault': return <PrivacyVaultTab />;
case 'organizations': return <PrivacyOrgsTab />;
+ case 'changes': return <PrivacyChangesTab />;
case 'overview':
default: return <PrivacyOverviewTab />;
}
diff --git a/client/src/pages/Privacy.test.jsx b/client/src/pages/Privacy.test.jsx
index 4efe74e1c3..59ceb7e7c3 100644
--- a/client/src/pages/Privacy.test.jsx
+++ b/client/src/pages/Privacy.test.jsx
@@ -31,6 +31,25 @@ vi.mock('../services/api', () => ({
deletePrivacyOrg: vi.fn().mockResolvedValue({ ok: true }),
getOrgHoldings: vi.fn().mockResolvedValue([]),
setOrgHoldings: vi.fn(),
+ getPrivacyChanges: vi.fn().mockResolvedValue([
+ {
+ id: 'ev-1', vaultRecordId: 'rec-1', replacementRecordId: 'rec-9', kind: 'address_change',
+ declaredAt: '2026-07-04T00:00:00Z', note: '',
+ oldRecord: { type: 'address', label: 'Home address', maskedValue: '•••, Portland OR' },
+ replacementRecord: { type: 'address', label: 'New home', maskedValue: '•••, Seattle WA' },
+ progress: { pending: 1, updated: 0, removed: 0, total: 1 },
+ },
+ ]),
+ getPrivacyChange: vi.fn().mockResolvedValue({
+ event: { id: 'ev-1', kind: 'address_change' },
+ oldRecord: { type: 'address', maskedValue: '•••, Portland OR' },
+ replacementRecord: { type: 'address', maskedValue: '•••, Seattle WA' },
+ progress: { pending: [{ orgId: 'org-1', orgName: 'Acme Bank', website: null, contactEmail: '[email protected]' }], updated: [], removed: [] },
+ }),
+ declarePrivacyChange: vi.fn(),
+ markChangeOrgUpdated: vi.fn(),
+ markChangeOrgRemoved: vi.fn(),
+ draftChangeUpdateEmail: vi.fn(),
}));
import Privacy from './Privacy';
@@ -80,6 +99,15 @@ describe('Privacy Center', () => {
expect(screen.getAllByText('Trusted').length).toBeGreaterThanOrEqual(1);
});
+ it('renders the Changes tab with a declared change and its progress', async () => {
+ renderAt('/privacy/changes');
+ // Masked old → new values render; the change kind badge shows.
+ await waitFor(() => expect(screen.getByText('•••, Portland OR')).toBeInTheDocument());
+ expect(screen.getByText('•••, Seattle WA')).toBeInTheDocument();
+ expect(screen.getByText('Address change')).toBeInTheDocument();
+ expect(screen.getByText(/handled/i)).toBeInTheDocument();
+ });
+
it('stale :tab param falls back to Overview', async () => {
renderAt('/privacy/bogus');
await waitFor(() => expect(screen.getByText(/system of record/i)).toBeInTheDocument());
diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.js
index 1a74cca202..6718a2dcd8 100644
--- a/client/src/services/apiPrivacy.js
+++ b/client/src/services/apiPrivacy.js
@@ -65,6 +65,23 @@ export const setOrgHoldings = (id, holdings, options) => request(`/privacy/orgs/
...options,
});
+// ── Change-of-address events + inventory (#2143) ────────────────────────────
+export const getPrivacyChanges = (options) => request('/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', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...options,
+});
+export const markChangeOrgUpdated = (id, orgId, options) =>
+ request(`/privacy/changes/${id}/orgs/${orgId}/updated`, { method: 'POST', ...options });
+export const markChangeOrgRemoved = (id, orgId, options) =>
+ request(`/privacy/changes/${id}/orgs/${orgId}/removed`, { method: 'POST', ...options });
+// Drafts a "please update my records" email into the Comms queue (unapproved).
+export const draftChangeUpdateEmail = (id, orgId, options) =>
+ request(`/privacy/changes/${id}/orgs/${orgId}/draft-email`, { method: 'POST', ...options });
+
// ── Digital Twin cross-link (#2147) ─────────────────────────────────────────
/** Social-account → org links for the Twin's "in org registry" badges. */
export const getSocialAccountOrgLinks = (options) =>
diff --git a/scripts/migrations/178-privacy-change-events-table.js b/scripts/migrations/178-privacy-change-events-table.js
new file mode 100644
index 0000000000..fa32c5ca0e
--- /dev/null
+++ b/scripts/migrations/178-privacy-change-events-table.js
@@ -0,0 +1,26 @@
+/**
+ * Registration stub for the Privacy Center change-of-address events table
+ * (issue #2143, epic #2138).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS privacy_change_events` (+ its
+ * index) — is idempotent and lives in `ensureSchema()` (`server/lib/db.js`) and
+ * the fresh-install seed (`server/scripts/init-db.sql`), both of which run at
+ * server boot AFTER the DB pool is up. The `scripts/migrations/` runner executes
+ * BEFORE the pool is initialized, so a DB-table create cannot live here — the
+ * same reason migrations 048–052, 108, 160/161/162, and 176 are boot-time +
+ * stub-registered.
+ *
+ * This stub exists so the new-table change is *registered the standard way*: it
+ * lands in `data/migrations.applied.json` so the migration ledger and `git log`
+ * show when the change-events table was introduced. The table is additive
+ * (brand-new, machine-local db-primary store) with no data backfill — the
+ * privacyChanges service populates it lazily as the user declares changes.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('📮 privacy_change_events: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/db.js b/server/lib/db.js
index 4bf11783c9..8537a8c859 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -1412,6 +1412,25 @@ async function ensureSchemaImpl() {
// "Which cases are due for a recheck" — the run-loop's primary query.
`CREATE INDEX IF NOT EXISTS idx_privacy_broker_cases_recheck ON privacy_broker_cases (next_recheck_at)`,
+ // ─── Privacy Center: change-of-address events (issue #2143, epic #2138) ──
+ // One row per "field X changed from A to B" declaration. `vault_record_id`
+ // is the OLD record (marked `previous` on declare); `replacement_record_id`
+ // is the NEW one (nullable for a removal-only change). Declaring an event
+ // flips every `current` holding of the old record to `update_pending` (see
+ // privacyChanges.js). Both FKs cascade so removing a vault record cleans up
+ // its change events. Machine-local — no federation, no tombstones (same
+ // deferred scope as the vault, #2148). Mirrors the block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_change_events (
+ id UUID PRIMARY KEY,
+ vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
+ replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
+ kind TEXT NOT NULL DEFAULT 'other',
+ declared_at TIMESTAMPTZ DEFAULT NOW(),
+ note TEXT NOT NULL DEFAULT ''
+ )`,
+ // "Changes touching this record" — the inventory groups by the old record.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id)`,
+
// ─── Deletion audit log (incident #1248-follow-up) ──────────────────────
// Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone
// (recovery), and hard-delete of user-authored records — written by a DB
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index a3ad2e3b0d..a56b84161c 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -145,6 +145,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.identity.privacy-overview', path: '/privacy/overview', label: 'Privacy', section: 'Identity', aliases: ['privacy', 'privacy-center', 'my-data'], keywords: ['pii', 'privacy', 'personal data', 'identity facts', 'who has my data'] },
{ id: 'nav.identity.privacy-vault', path: '/privacy/vault', label: 'Vault', section: 'Identity', aliases: ['vault', 'pii-vault', 'privacy-vault'], keywords: ['pii', 'vault', 'encrypted', 'ssn', 'address', 'passport', 'identity'] },
{ id: 'nav.identity.privacy-organizations', path: '/privacy/organizations', label: 'Organizations', section: 'Identity', aliases: ['organizations', 'orgs', 'trusted-orgs'], keywords: ['organizations', 'banks', 'utilities', 'who holds my data', 'registry', 'holdings'] },
+ { id: 'nav.identity.privacy-changes', path: '/privacy/changes', label: 'Changes', section: 'Identity', aliases: ['changes', 'change-of-address', 'address-change', 'privacy-changes'], keywords: ['change of address', 'moved', 'update address', 'inventory', 'who needs updating', 'new phone', 'new email'] },
{ id: 'nav.meatspace.overview', path: '/meatspace/overview', label: 'Overview', section: 'Health', aliases: ['meatspace'] },
{ id: 'nav.meatspace.health', path: '/meatspace/health', label: 'Body Health', section: 'Health', aliases: ['meatspace-health', 'body-health'], keywords: ['health', 'vitals', 'wellbeing', 'biometrics'] },
diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.js
index a3dc972b97..3dc1880025 100644
--- a/server/lib/privacyValidation.js
+++ b/server/lib/privacyValidation.js
@@ -146,6 +146,56 @@ export const privacyOrgHoldingsSetSchema = z.object({
}).strict()).max(500),
}).strict();
+// =============================================================================
+// CHANGE-OF-ADDRESS EVENTS + INVENTORY SCHEMAS (issue #2143, epic #2138)
+// =============================================================================
+// Zod schemas for `privacy_change_events` — db-primary Postgres, machine-local
+// (same federation-deferred scope as the vault, #2148). Declaring a change flips
+// every `current` holding of the old vault record to `update_pending`; the
+// Changes tab then works that per-org checklist.
+
+export const PRIVACY_CHANGE_KINDS = Object.freeze([
+ 'address_change', 'phone_change', 'email_change', 'name_change', 'other',
+]);
+
+// The replacement value can be supplied inline (a brand-new vault record is
+// created for it) — the same shape as a vault create MINUS status (always
+// 'current') and validTo (an active replacement has no end date yet). `type`
+// defaults to the OLD record's type in the service when omitted.
+const privacyChangeReplacementSchema = z.object({
+ type: z.enum(PRIVACY_VAULT_TYPES).optional(),
+ label: z.string().trim().min(1).max(200),
+ value: z.string().min(1).max(10000),
+ validFrom: isoDateSchema,
+ shareWithTwin: z.boolean().optional(),
+ useForScans: z.boolean().optional(),
+ notes: z.string().max(5000).optional(),
+}).strict();
+
+// POST /api/privacy/changes — declare a change. Supply the replacement EITHER
+// inline (`replacement`) OR by id (`replacementRecordId`), never both; omit both
+// for a removal-only change (the field went away with no successor). `kind`
+// defaults in the service from the old record's type when omitted.
+export const privacyChangeDeclareSchema = z.object({
+ vaultRecordId: z.string().uuid(),
+ replacement: privacyChangeReplacementSchema.optional(),
+ replacementRecordId: z.string().uuid().optional(),
+ kind: z.enum(PRIVACY_CHANGE_KINDS).optional(),
+ note: z.string().max(5000).optional(),
+}).strict().refine(
+ (v) => !(v.replacement && v.replacementRecordId),
+ { message: 'provide either replacement or replacementRecordId, not both', path: ['replacement'] },
+);
+
+export const privacyChangeIdParamsSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
+export const privacyChangeOrgParamsSchema = z.object({
+ id: z.string().uuid(),
+ orgId: z.string().uuid(),
+}).strict();
+
// =============================================================================
// DATA-BROKER DATABASE + CASE LEDGER SCHEMAS (issue #2144, epic #2138)
// =============================================================================
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index 5f9801d891..8f489304cd 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -25,6 +25,9 @@ import {
privacyBrokerCaseListQuerySchema,
privacyBrokerRefreshSchema,
privacyScanStartSchema,
+ privacyChangeDeclareSchema,
+ privacyChangeIdParamsSchema,
+ privacyChangeOrgParamsSchema,
} from '../lib/privacyValidation.js';
import {
createVaultRecord,
@@ -52,6 +55,14 @@ import {
getScanStatus,
} from '../services/privacyBrokers.js';
import { runScanPass } from '../services/privacyScan.js';
+import {
+ declareChange,
+ listChangeEvents,
+ getChange,
+ markOrgUpdated,
+ markOrgRemoved,
+ draftUpdateEmail,
+} from '../services/privacyChanges.js';
const router = Router();
@@ -141,6 +152,37 @@ router.put('/orgs/:id/holdings', asyncHandler(async (req, res) => {
res.json(await setOrgHoldings(id, holdings));
}));
+// ─── Change-of-address events + inventory workflow (issue #2143) ────────────
+
+router.get('/changes', asyncHandler(async (_req, res) => {
+ res.json(await listChangeEvents());
+}));
+
+router.post('/changes', asyncHandler(async (req, res) => {
+ const data = validateRequest(privacyChangeDeclareSchema, req.body);
+ res.status(201).json(await declareChange(data));
+}));
+
+router.get('/changes/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyChangeIdParamsSchema, req.params);
+ res.json(await getChange(id));
+}));
+
+router.post('/changes/:id/orgs/:orgId/updated', asyncHandler(async (req, res) => {
+ const { id, orgId } = validateRequest(privacyChangeOrgParamsSchema, req.params);
+ res.json(await markOrgUpdated(id, orgId));
+}));
+
+router.post('/changes/:id/orgs/:orgId/removed', asyncHandler(async (req, res) => {
+ const { id, orgId } = validateRequest(privacyChangeOrgParamsSchema, req.params);
+ res.json(await markOrgRemoved(id, orgId));
+}));
+
+router.post('/changes/:id/orgs/:orgId/draft-email', asyncHandler(async (req, res) => {
+ const { id, orgId } = validateRequest(privacyChangeOrgParamsSchema, req.params);
+ res.status(201).json(await draftUpdateEmail(id, orgId));
+}));
+
// ─── Data-broker database + exposure scan + case ledger (issue #2144) ───────
router.get('/brokers', asyncHandler(async (req, res) => {
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index 4a38cf3f8d..fd7311bf52 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -42,11 +42,21 @@ vi.mock('../services/privacyScan.js', () => ({
runScanPass: vi.fn(async (opts) => ({ scanned: 2, verdicts: { found: 1, not_found: 1 }, skipped: 0, brokers: 20, _opts: opts })),
}));
+vi.mock('../services/privacyChanges.js', () => ({
+ declareChange: vi.fn(async (input) => ({ id: 'c0ffee00-0000-4000-8000-000000000003', ...input })),
+ listChangeEvents: vi.fn(async () => [{ id: 'ev1', kind: 'address_change', progress: { pending: 1, updated: 0, removed: 0, total: 1 } }]),
+ getChange: vi.fn(async () => ({ event: { id: 'ev1' }, progress: { pending: [], updated: [], removed: [] } })),
+ markOrgUpdated: vi.fn(async () => ({ pending: [], updated: [{ orgId: 'o1' }], removed: [] })),
+ markOrgRemoved: vi.fn(async () => ({ pending: [], updated: [], removed: [{ orgId: 'o1' }] })),
+ draftUpdateEmail: vi.fn(async () => ({ draftId: 'draft-1', status: 'draft' })),
+}));
+
const privacyRoutes = (await import('./privacy.js')).default;
const service = await import('../services/privacyVault.js');
const orgService = await import('../services/privacyOrgs.js');
const brokerService = await import('../services/privacyBrokers.js');
const scanService = await import('../services/privacyScan.js');
+const changeService = await import('../services/privacyChanges.js');
const VALID_UUID = 'c0ffee00-0000-4000-8000-000000000001';
@@ -245,6 +255,67 @@ describe('PUT /api/privacy/orgs/:id/holdings', () => {
});
});
+// ─── Change-of-address events + inventory workflow (issue #2143) ────────────
+
+describe('GET /api/privacy/changes', () => {
+ it('lists change events with progress', async () => {
+ const res = await request(makeApp()).get('/api/privacy/changes');
+ expect(res.status).toBe(200);
+ expect(res.body[0]).toMatchObject({ id: 'ev1', kind: 'address_change' });
+ expect(changeService.listChangeEvents).toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/privacy/changes', () => {
+ it('declares a change from a valid inline-replacement body', async () => {
+ const body = { vaultRecordId: VALID_UUID, replacement: { label: 'New', value: '742 New Ave' }, kind: 'address_change' };
+ const res = await request(makeApp()).post('/api/privacy/changes').send(body);
+ expect(res.status).toBe(201);
+ expect(changeService.declareChange).toHaveBeenCalledWith(body);
+ });
+
+ it('rejects a non-uuid record, both-replacement-forms, and unknown keys', async () => {
+ expect((await request(makeApp()).post('/api/privacy/changes').send({ vaultRecordId: 'nope' })).status).toBe(400);
+ expect((await request(makeApp()).post('/api/privacy/changes')
+ .send({ vaultRecordId: VALID_UUID, replacement: { label: 'x', value: 'y' }, replacementRecordId: VALID_UUID })).status).toBe(400);
+ expect((await request(makeApp()).post('/api/privacy/changes')
+ .send({ vaultRecordId: VALID_UUID, extra: 1 })).status).toBe(400);
+ });
+
+ it('accepts a removal-only change (no replacement) and a linked replacementRecordId', async () => {
+ expect((await request(makeApp()).post('/api/privacy/changes').send({ vaultRecordId: VALID_UUID, kind: 'other' })).status).toBe(201);
+ expect((await request(makeApp()).post('/api/privacy/changes')
+ .send({ vaultRecordId: VALID_UUID, replacementRecordId: VALID_UUID })).status).toBe(201);
+ });
+});
+
+describe('GET /api/privacy/changes/:id', () => {
+ it('returns the event + inventory and validates the uuid', async () => {
+ expect((await request(makeApp()).get(`/api/privacy/changes/${VALID_UUID}`)).status).toBe(200);
+ expect(changeService.getChange).toHaveBeenCalledWith(VALID_UUID);
+ expect((await request(makeApp()).get('/api/privacy/changes/not-a-uuid')).status).toBe(400);
+ });
+});
+
+describe('per-org change actions', () => {
+ const base = `/api/privacy/changes/${VALID_UUID}/orgs/${VALID_UUID}`;
+
+ it('marks an org updated / removed', async () => {
+ expect((await request(makeApp()).post(`${base}/updated`)).status).toBe(200);
+ expect(changeService.markOrgUpdated).toHaveBeenCalledWith(VALID_UUID, VALID_UUID);
+ expect((await request(makeApp()).post(`${base}/removed`)).status).toBe(200);
+ expect(changeService.markOrgRemoved).toHaveBeenCalledWith(VALID_UUID, VALID_UUID);
+ });
+
+ it('drafts an update email (201) and validates both uuids', async () => {
+ const res = await request(makeApp()).post(`${base}/draft-email`);
+ expect(res.status).toBe(201);
+ expect(res.body).toEqual({ draftId: 'draft-1', status: 'draft' });
+ expect((await request(makeApp()).post(`/api/privacy/changes/nope/orgs/${VALID_UUID}/updated`)).status).toBe(400);
+ expect((await request(makeApp()).post(`/api/privacy/changes/${VALID_UUID}/orgs/nope/updated`)).status).toBe(400);
+ });
+});
+
// ─── Data-broker database + scan + case ledger (issue #2144) ────────────────
describe('GET /api/privacy/brokers', () => {
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index ff91659fc2..59b1eee9b7 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1187,6 +1187,25 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker ON privacy_bro
-- "Which cases are due for a recheck" — the run-loop's primary query.
CREATE INDEX IF NOT EXISTS idx_privacy_broker_cases_recheck ON privacy_broker_cases (next_recheck_at);
+-- Privacy Center: change-of-address events (issue #2143, epic #2138). One row
+-- per "field X changed from A to B" declaration. `vault_record_id` is the OLD
+-- record (marked `previous` on declare); `replacement_record_id` is the NEW one
+-- (nullable for a removal-only change). Declaring an event flips every `current`
+-- holding of the old record to `update_pending` (see privacyChanges.js). Both
+-- FKs cascade-delete so removing a vault record cleans up its change events.
+-- Machine-local — no federation, no tombstones (same deferred scope as the
+-- vault, #2148). Mirrors the block in server/lib/db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS privacy_change_events (
+ id UUID PRIMARY KEY,
+ vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
+ replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
+ kind TEXT NOT NULL DEFAULT 'other',
+ declared_at TIMESTAMPTZ DEFAULT NOW(),
+ note TEXT NOT NULL DEFAULT ''
+);
+-- "Changes touching this record" — the inventory view groups by the old record.
+CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id);
+
-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of
-- every tombstone / un-tombstone / hard-delete of user-authored records, written
-- by a DB trigger so it captures deletions from ANY source (app, a test suite's
diff --git a/server/services/privacyChanges.db.test.js b/server/services/privacyChanges.db.test.js
new file mode 100644
index 0000000000..a8542f5bde
--- /dev/null
+++ b/server/services/privacyChanges.db.test.js
@@ -0,0 +1,169 @@
+/**
+ * Postgres-backed round-trip for the change-of-address inventory workflow
+ * (issue #2143). Like privacyOrgs.db.test.js, this needs a live PostgreSQL with
+ * the schema applied; if none is reachable it SKIPS cleanly. Exercises the
+ * declare transaction (old record retired, holdings flipped, forward holdings
+ * mirrored, event written), progress grouping + math, idempotent per-org marks,
+ * removal dropping the replacement holding, and draft-email creating an
+ * unapproved draft. The messages subsystem is mocked so no file writes touch
+ * real data/. Runs via `npm run test:db` (→ portos_test) ONLY.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+
+vi.mock('./messageAccounts.js', () => ({
+ listAccounts: vi.fn(async () => [{ id: 'acct-test', type: 'gmail', name: 'Test' }]),
+}));
+vi.mock('./messageDrafts.js', () => ({
+ createDraft: vi.fn(async (data) => ({ id: 'draft-test', status: 'draft', ...data })),
+}));
+
+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_change_events') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'privacy_change_events table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ privacyChanges.db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('privacy changes DB round-trip', () => {
+ let changes;
+ let orgs;
+ let vault;
+ const createdOrgs = [];
+ const createdVaultRecords = [];
+ const createdEvents = [];
+
+ beforeAll(async () => {
+ changes = await import('./privacyChanges.js');
+ orgs = await import('./privacyOrgs.js');
+ vault = await import('./privacyVault.js');
+ });
+
+ afterAll(async () => {
+ for (const id of createdEvents) await query(`DELETE FROM privacy_change_events WHERE id = $1`, [id]).catch(() => {});
+ for (const id of createdOrgs) await query(`DELETE FROM privacy_orgs WHERE id = $1`, [id]).catch(() => {});
+ for (const id of createdVaultRecords) await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});
+ await close();
+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;
+ else process.env.PRIVACY_VAULT_KEY = originalKey;
+ });
+
+ it('declares a change: retires the old record, flips holdings, mirrors forward holdings, writes the event', async () => {
+ const oldRec = await vault.createVaultRecord({ type: 'address', label: 'Old home', value: '1 Old Rd' });
+ createdVaultRecords.push(oldRec.id);
+ const orgA = await orgs.createOrg({ name: 'Bank A' });
+ const orgB = await orgs.createOrg({ name: 'Bank B', contact: { email: '[email protected]' } });
+ createdOrgs.push(orgA.id, orgB.id);
+ await orgs.setOrgHoldings(orgA.id, [{ vaultRecordId: oldRec.id, status: 'current' }]);
+ await orgs.setOrgHoldings(orgB.id, [{ vaultRecordId: oldRec.id, status: 'current' }]);
+
+ const event = await changes.declareChange({
+ vaultRecordId: oldRec.id,
+ replacement: { label: 'New home', value: '742 New Ave' },
+ note: 'moved cross-town',
+ });
+ createdEvents.push(event.id);
+ createdVaultRecords.push(event.replacementRecordId);
+
+ expect(event.kind).toBe('address_change');
+ expect(event.replacementRecordId).toBeTruthy();
+
+ // Old record marked previous with a valid_to stamp; new record is current.
+ const oldAfter = await vault.getVaultRecord(oldRec.id);
+ expect(oldAfter.status).toBe('previous');
+ expect(oldAfter.validTo).toBeTruthy();
+ const newRec = await vault.getVaultRecord(event.replacementRecordId);
+ expect(newRec.status).toBe('current');
+ expect(newRec.type).toBe('address'); // inherited from the old record
+ expect(newRec.maskedValue).not.toContain('742 New Ave'); // masked, never plaintext
+
+ // Both orgs flipped to update_pending on the old record.
+ const progress = await changes.getChangeProgress(event.id);
+ expect(progress.pending).toHaveLength(2);
+ expect(progress.updated).toHaveLength(0);
+
+ // Forward-looking current holdings exist on the NEW record for both orgs.
+ const holdersOfNew = await orgs.getOrgsHoldingRecord(event.replacementRecordId);
+ expect(holdersOfNew).toHaveLength(2);
+ expect(holdersOfNew.every((h) => h.status === 'current')).toBe(true);
+ });
+
+ it('drives progress to done via mark updated / removed, idempotently', async () => {
+ const oldRec = await vault.createVaultRecord({ type: 'phone', label: 'Cell', value: '+1 555 0100' });
+ createdVaultRecords.push(oldRec.id);
+ const orgA = await orgs.createOrg({ name: 'Carrier A' });
+ const orgB = await orgs.createOrg({ name: 'Carrier B' });
+ createdOrgs.push(orgA.id, orgB.id);
+ await orgs.setOrgHoldings(orgA.id, [{ vaultRecordId: oldRec.id, status: 'current' }]);
+ await orgs.setOrgHoldings(orgB.id, [{ vaultRecordId: oldRec.id, status: 'current' }]);
+
+ const event = await changes.declareChange({
+ vaultRecordId: oldRec.id,
+ replacement: { label: 'New cell', value: '+1 555 0200' },
+ });
+ createdEvents.push(event.id);
+ createdVaultRecords.push(event.replacementRecordId);
+
+ await changes.markOrgUpdated(event.id, orgA.id);
+ // Idempotent: a second mark on the same org is a no-op, not a 404.
+ const p1 = await changes.markOrgUpdated(event.id, orgA.id);
+ expect(p1.updated).toHaveLength(1);
+ expect(p1.pending).toHaveLength(1);
+
+ const p2 = await changes.markOrgRemoved(event.id, orgB.id);
+ expect(p2.pending).toHaveLength(0); // done — zero pending
+ expect(p2.updated).toHaveLength(1);
+ expect(p2.removed).toHaveLength(1);
+
+ // Removal dropped orgB's forward holding on the new record; orgA's remains.
+ const holdersOfNew = await orgs.getOrgsHoldingRecord(event.replacementRecordId);
+ expect(holdersOfNew.map((h) => h.orgId)).toEqual([orgA.id]);
+ });
+
+ it('lists events with progress counts and masked values (never plaintext)', async () => {
+ const list = await changes.listChangeEvents();
+ expect(Array.isArray(list)).toBe(true);
+ expect(list.length).toBeGreaterThanOrEqual(2);
+ expect(JSON.stringify(list)).not.toContain('742 New Ave');
+ expect(list[0].progress).toHaveProperty('total');
+ });
+
+ it('drafts an unapproved update email to the org contact', async () => {
+ const oldRec = await vault.createVaultRecord({ type: 'email', label: 'Old email', value: '[email protected]' });
+ createdVaultRecords.push(oldRec.id);
+ const org = await orgs.createOrg({ name: 'Subscription Co', contact: { email: '[email protected]' } });
+ createdOrgs.push(org.id);
+ await orgs.setOrgHoldings(org.id, [{ vaultRecordId: oldRec.id, status: 'current' }]);
+
+ const event = await changes.declareChange({
+ vaultRecordId: oldRec.id,
+ replacement: { label: 'New email', value: '[email protected]' },
+ });
+ createdEvents.push(event.id);
+ createdVaultRecords.push(event.replacementRecordId);
+
+ const result = await changes.draftUpdateEmail(event.id, org.id);
+ expect(result.status).toBe('draft'); // unapproved
+ const { createDraft } = await import('./messageDrafts.js');
+ const draftArg = createDraft.mock.calls.at(-1)[0];
+ expect(draftArg.to).toEqual(['[email protected]']);
+ expect(draftArg.body).toContain('[email protected]'); // new value plaintext for the org
+ expect(draftArg.generatedBy).toBe('privacy-change');
+ });
+});
diff --git a/server/services/privacyChanges.js b/server/services/privacyChanges.js
new file mode 100644
index 0000000000..34f1bb3006
--- /dev/null
+++ b/server/services/privacyChanges.js
@@ -0,0 +1,355 @@
+/**
+ * Change-of-address inventory workflow (issue #2143, epic #2138).
+ *
+ * db-primary Postgres per docs/STORAGE.md: one row per declared change in
+ * `privacy_change_events`. The workflow is: the user declares "field X changed
+ * from A to B" — the OLD vault record is marked `previous` (+ `valid_to`), a
+ * replacement record is created/linked, and EVERY `current` holding of the old
+ * record flips to `update_pending`. The Changes tab then works that per-org
+ * checklist to done (zero `update_pending`).
+ *
+ * Machine-local: NO federation, NO tombstones (same deferred scope as the
+ * vault, #2148). Plaintext PII is NEVER stored here and NEVER logged — the
+ * inventory joins masked vault values only. The ONE place plaintext surfaces is
+ * `draftUpdateEmail`, which decrypts the NEW value into an email draft the user
+ * explicitly requested and must still approve before it sends (never auto-send
+ * in this phase).
+ *
+ * The declare path runs as ONE transaction (atomic): a partial failure must not
+ * leave the old record `previous` with holdings un-flipped, or an orphaned
+ * replacement record. It uses the transaction client for every write rather
+ * than the pool-level `privacyOrgs.setHoldingsStatus`, so the flip both sees the
+ * FOR UPDATE lock and rolls back with the rest on error.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { encryptValue, maskValue, ensureVaultKey } from '../lib/vaultCrypto.js';
+import { resolveUseForScans, getVaultRecord, revealValue } from './privacyVault.js';
+import { getOrg } from './privacyOrgs.js';
+import { listAccounts } from './messageAccounts.js';
+import { createDraft } from './messageDrafts.js';
+
+const EVENT_COLUMNS = `id, vault_record_id, replacement_record_id, kind, declared_at, note`;
+
+// Holdings statuses that make up the per-event inventory (a `current` holding is
+// only relevant to a NEW record, not the change checklist).
+const INVENTORY_STATUSES = ['update_pending', 'updated', 'removed'];
+
+// Human-facing field label per change kind — used in the update-email template.
+const KIND_FIELD_LABEL = Object.freeze({
+ address_change: 'mailing address',
+ phone_change: 'phone number',
+ email_change: 'email address',
+ name_change: 'legal name',
+ other: 'information on file',
+});
+
+// Default change kind derived from the OLD record's vault type when the caller
+// omits `kind` (the UI derives it from the selected record, but the API stays
+// forgiving). Anything without a dedicated kind is a generic `other`.
+const TYPE_TO_KIND = Object.freeze({
+ address: 'address_change',
+ phone: 'phone_change',
+ email: 'email_change',
+ legal_name: 'name_change',
+});
+
+export function kindForType(type) {
+ return TYPE_TO_KIND[type] ?? 'other';
+}
+
+function rowToEvent(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ vaultRecordId: row.vault_record_id,
+ replacementRecordId: row.replacement_record_id,
+ kind: row.kind,
+ declaredAt: row.declared_at,
+ note: row.note,
+ };
+}
+
+/** Pure: assemble the update-email body from old→new (masked old, plain new). */
+export function renderUpdateEmailBody({ orgName, fieldLabel, oldMasked, newValue }) {
+ const lines = [
+ `Hello${orgName ? ` ${orgName}` : ''},`,
+ '',
+ `I am writing to update my ${fieldLabel} on file with your organization.`,
+ '',
+ `New ${fieldLabel}: ${newValue}`,
+ ];
+ if (oldMasked) lines.push(`Previous ${fieldLabel} on record: ${oldMasked}`);
+ lines.push(
+ '',
+ 'Please update your records accordingly and confirm once the change has been applied.',
+ '',
+ 'Thank you.',
+ );
+ return lines.join('\n');
+}
+
+/**
+ * Declare a change: mark the old record `previous`, create/link the replacement,
+ * flip every `current` holding of the old record to `update_pending` (recording
+ * a forward-looking `current` holding on the new record for each flipped org so
+ * "org has old value" and "org needs new value" are both queryable), and write
+ * the event row. All in ONE transaction.
+ */
+export async function declareChange({ vaultRecordId, replacement, replacementRecordId, kind, note }) {
+ // ensureVaultKey may append to .env — do it before opening the transaction
+ // so the transaction body is pure DB work (a replacement is encrypted inside).
+ if (replacement) await ensureVaultKey();
+ return withTransaction(async (client) => {
+ const { rows: oldRows } = await client.query(
+ `SELECT id, type FROM privacy_vault_records WHERE id = $1 FOR UPDATE`, [vaultRecordId],
+ );
+ const oldRecord = oldRows[0];
+ if (!oldRecord) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });
+
+ // Resolve the replacement record id (inline-create, link-existing, or none).
+ let replacementId = null;
+ if (replacementRecordId) {
+ const { rows } = await client.query(
+ `SELECT id FROM privacy_vault_records WHERE id = $1`, [replacementRecordId],
+ );
+ if (!rows[0]) {
+ throw new ServerError('Replacement vault record not found', { status: 400, code: 'REPLACEMENT_NOT_FOUND' });
+ }
+ replacementId = replacementRecordId;
+ } else if (replacement) {
+ replacementId = randomUUID();
+ const type = replacement.type ?? oldRecord.type;
+ const useForScans = resolveUseForScans(type, replacement.useForScans);
+ await client.query(
+ `INSERT INTO privacy_vault_records
+ (id, type, label, value_enc, masked_value, status, valid_from, valid_to,
+ share_with_twin, use_for_scans, notes, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, 'current', $6, NULL, $7, $8, $9, NOW(), NOW())`,
+ [
+ replacementId, type, replacement.label,
+ encryptValue(replacement.value), maskValue(type, replacement.value),
+ replacement.validFrom ?? null,
+ replacement.shareWithTwin === true, useForScans, replacement.notes ?? '',
+ ],
+ );
+ }
+
+ // Retire the old record. COALESCE keeps an already-set valid_to intact.
+ await client.query(
+ `UPDATE privacy_vault_records
+ SET status = 'previous', valid_to = COALESCE(valid_to, CURRENT_DATE), updated_at = NOW()
+ WHERE id = $1`,
+ [vaultRecordId],
+ );
+
+ // Flip every current holding of the old record → update_pending, capturing
+ // the affected orgs so we can mirror a forward-looking holding on the new one.
+ const { rows: flipped } = await client.query(
+ `UPDATE privacy_org_holdings SET status = 'update_pending', updated_at = NOW()
+ WHERE vault_record_id = $1 AND status = 'current'
+ RETURNING org_id`,
+ [vaultRecordId],
+ );
+ if (replacementId) {
+ for (const row of flipped) {
+ await client.query(
+ `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
+ VALUES ($1, $2, 'current', NOW(), NOW())
+ ON CONFLICT (org_id, vault_record_id) DO UPDATE SET status = 'current', updated_at = NOW()`,
+ [row.org_id, replacementId],
+ );
+ }
+ }
+
+ const eventId = randomUUID();
+ const resolvedKind = kind ?? kindForType(oldRecord.type);
+ const { rows: evRows } = await client.query(
+ `INSERT INTO privacy_change_events (id, vault_record_id, replacement_record_id, kind, declared_at, note)
+ VALUES ($1, $2, $3, $4, NOW(), $5)
+ RETURNING ${EVENT_COLUMNS}`,
+ [eventId, vaultRecordId, replacementId, resolvedKind, note ?? ''],
+ );
+ console.log(`📮 Declared privacy change ${eventId} (kind=${resolvedKind}, orgs flipped=${flipped.length}, replacement=${replacementId ? 'yes' : 'none'})`);
+ return rowToEvent(evRows[0]);
+ });
+}
+
+/** List all change events, newest first, with per-event progress counts + masked old/new values. */
+export async function listChangeEvents() {
+ const { rows } = await query(
+ `SELECT e.id, e.vault_record_id, e.replacement_record_id, e.kind, e.declared_at, e.note,
+ ov.type AS old_type, ov.label AS old_label, ov.masked_value AS old_masked,
+ rv.type AS new_type, rv.label AS new_label, rv.masked_value AS new_masked,
+ COUNT(h.org_id) FILTER (WHERE h.status = 'update_pending')::int AS pending_count,
+ COUNT(h.org_id) FILTER (WHERE h.status = 'updated')::int AS updated_count,
+ COUNT(h.org_id) FILTER (WHERE h.status = 'removed')::int AS removed_count
+ FROM privacy_change_events e
+ JOIN privacy_vault_records ov ON ov.id = e.vault_record_id
+ LEFT JOIN privacy_vault_records rv ON rv.id = e.replacement_record_id
+ LEFT JOIN privacy_org_holdings h
+ ON h.vault_record_id = e.vault_record_id AND h.status = ANY($1::text[])
+ GROUP BY e.id, ov.type, ov.label, ov.masked_value, rv.type, rv.label, rv.masked_value
+ ORDER BY e.declared_at DESC`,
+ [INVENTORY_STATUSES],
+ );
+ return rows.map((row) => ({
+ ...rowToEvent(row),
+ oldRecord: { type: row.old_type, label: row.old_label, maskedValue: row.old_masked },
+ replacementRecord: row.replacement_record_id
+ ? { type: row.new_type, label: row.new_label, maskedValue: row.new_masked }
+ : null,
+ progress: {
+ pending: row.pending_count,
+ updated: row.updated_count,
+ removed: row.removed_count,
+ total: row.pending_count + row.updated_count + row.removed_count,
+ },
+ }));
+}
+
+export async function getChangeEvent(eventId) {
+ const { rows } = await query(`SELECT ${EVENT_COLUMNS} FROM privacy_change_events WHERE id = $1`, [eventId]);
+ return rowToEvent(rows[0]);
+}
+
+async function requireEvent(eventId) {
+ const event = await getChangeEvent(eventId);
+ if (!event) throw new ServerError('Change event not found', { status: 404, code: 'NOT_FOUND' });
+ return event;
+}
+
+/**
+ * Per-org inventory for a change event, grouped by holding status of the OLD
+ * record: `{ pending[], updated[], removed[] }`. Each entry carries the org's
+ * name, website, and contact email (for the per-org actions + draft-email).
+ */
+export async function getChangeProgress(eventId) {
+ const event = await requireEvent(eventId);
+ const { rows } = await query(
+ `SELECT h.org_id, h.status, o.name AS org_name, o.website, o.contact
+ FROM privacy_org_holdings h
+ JOIN privacy_orgs o ON o.id = h.org_id
+ WHERE h.vault_record_id = $1 AND h.status = ANY($2::text[])
+ ORDER BY o.name`,
+ [event.vaultRecordId, INVENTORY_STATUSES],
+ );
+ const groups = { pending: [], updated: [], removed: [] };
+ for (const r of rows) {
+ const entry = {
+ orgId: r.org_id,
+ orgName: r.org_name,
+ website: r.website || null,
+ contactEmail: r.contact?.email || null,
+ };
+ if (r.status === 'update_pending') groups.pending.push(entry);
+ else if (r.status === 'updated') groups.updated.push(entry);
+ else if (r.status === 'removed') groups.removed.push(entry);
+ }
+ return groups;
+}
+
+/** Event + inventory in one payload — powers GET /changes/:id (event detail). */
+export async function getChange(eventId) {
+ const event = await requireEvent(eventId);
+ const [oldRecord, replacementRecord] = await Promise.all([
+ getVaultRecord(event.vaultRecordId),
+ event.replacementRecordId ? getVaultRecord(event.replacementRecordId) : Promise.resolve(null),
+ ]);
+ const progress = await getChangeProgress(eventId);
+ return { event, oldRecord, replacementRecord, progress };
+}
+
+// Flip ONE org's old-record holding to a terminal inventory status. Idempotent:
+// a holding already in an inventory status re-settles to the requested one, so a
+// double-click is a no-op rather than a 404.
+async function setOrgHoldingStatus(event, orgId, toStatus) {
+ const { rows } = await query(
+ `UPDATE privacy_org_holdings SET status = $1, updated_at = NOW()
+ WHERE vault_record_id = $2 AND org_id = $3 AND status = ANY($4::text[])
+ RETURNING org_id`,
+ [toStatus, event.vaultRecordId, orgId, INVENTORY_STATUSES],
+ );
+ if (!rows[0]) {
+ throw new ServerError('Organization is not part of this change', { status: 404, code: 'HOLDING_NOT_FOUND' });
+ }
+}
+
+export async function markOrgUpdated(eventId, orgId) {
+ const event = await requireEvent(eventId);
+ await setOrgHoldingStatus(event, orgId, 'updated');
+ console.log(`✅ Change ${eventId}: org ${orgId} marked updated`);
+ return getChangeProgress(eventId);
+}
+
+export async function markOrgRemoved(eventId, orgId) {
+ const event = await requireEvent(eventId);
+ await withTransaction(async (client) => {
+ const { rows } = await client.query(
+ `UPDATE privacy_org_holdings SET status = 'removed', updated_at = NOW()
+ WHERE vault_record_id = $1 AND org_id = $2 AND status = ANY($3::text[])
+ RETURNING org_id`,
+ [event.vaultRecordId, orgId, INVENTORY_STATUSES],
+ );
+ if (!rows[0]) {
+ throw new ServerError('Organization is not part of this change', { status: 404, code: 'HOLDING_NOT_FOUND' });
+ }
+ // The org dropped the field entirely — retire the forward-looking holding we
+ // created on the replacement record at declare time so the Organizations tab
+ // stays honest (this org does not hold the new value either).
+ if (event.replacementRecordId) {
+ await client.query(
+ `DELETE FROM privacy_org_holdings WHERE vault_record_id = $1 AND org_id = $2`,
+ [event.replacementRecordId, orgId],
+ );
+ }
+ });
+ console.log(`🚫 Change ${eventId}: org ${orgId} marked removed`);
+ return getChangeProgress(eventId);
+}
+
+/**
+ * Draft a plain "please update my records" email for one org in the inventory,
+ * old→new, into the messages drafts queue as an UNAPPROVED draft (status
+ * `draft`). Template-only (no LLM), runs only on an explicit user click. The
+ * new value is decrypted for the body (the org needs the actual new address);
+ * the draft still requires user approval before it can send.
+ */
+export async function draftUpdateEmail(eventId, orgId) {
+ const event = await requireEvent(eventId);
+ if (!event.replacementRecordId) {
+ throw new ServerError('No replacement record to update to', { status: 400, code: 'REPLACEMENT_REQUIRED' });
+ }
+ const org = await getOrg(orgId);
+ if (!org) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ const to = org.contact?.email;
+ if (!to) throw new ServerError('Organization has no contact email', { status: 400, code: 'ORG_EMAIL_MISSING' });
+
+ const accounts = await listAccounts();
+ const account = accounts.find((a) => a.type === 'gmail') ?? accounts[0];
+ if (!account) throw new ServerError('No message account configured', { status: 400, code: 'NO_MESSAGE_ACCOUNT' });
+
+ const oldRecord = await getVaultRecord(event.vaultRecordId);
+ const newReveal = await revealValue(event.replacementRecordId);
+ const fieldLabel = KIND_FIELD_LABEL[event.kind] ?? KIND_FIELD_LABEL.other;
+ const subject = `Request to update my ${fieldLabel}`;
+ const body = renderUpdateEmailBody({
+ orgName: org.name,
+ fieldLabel,
+ oldMasked: oldRecord?.maskedValue,
+ newValue: newReveal.value,
+ });
+
+ const draft = await createDraft({
+ accountId: account.id,
+ to: [to],
+ subject,
+ body,
+ generatedBy: 'privacy-change',
+ sendVia: account.type === 'gmail' ? 'api' : 'playwright',
+ });
+ console.log(`📧 Drafted privacy update email for org ${orgId} (change ${eventId}, draft ${draft.id})`);
+ return { draftId: draft.id, status: draft.status };
+}
diff --git a/server/services/privacyChanges.test.js b/server/services/privacyChanges.test.js
new file mode 100644
index 0000000000..91e566758c
--- /dev/null
+++ b/server/services/privacyChanges.test.js
@@ -0,0 +1,271 @@
+/**
+ * Change-of-address inventory service unit tests (issue #2143) — DB + sibling
+ * services mocked; the live-DB round trip lives in privacyChanges.db.test.js
+ * (test:db → portos_test only). Pins the declare transaction sequence (old
+ * record retired, holdings flipped, forward-holding mirrored, event written),
+ * the idempotent per-org marks, the removal-drops-replacement-holding rule,
+ * the draft-email unapproved-draft contract, and the pure helpers.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { queryMock, withTransactionMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+ withTransactionMock: vi.fn(),
+}));
+
+vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: withTransactionMock }));
+vi.mock('../lib/vaultCrypto.js', () => ({
+ encryptValue: (v) => `enc(${v})`,
+ maskValue: (t, v) => `mask(${t}:${v})`,
+ ensureVaultKey: vi.fn(async () => {}),
+}));
+vi.mock('./privacyVault.js', () => ({
+ resolveUseForScans: (_t, req) => req ?? true,
+ getVaultRecord: vi.fn(async (id) => ({ id, type: 'address', label: 'Old', maskedValue: 'mask-old' })),
+ revealValue: vi.fn(async (id) => ({ id, type: 'address', value: '742 New Ave' })),
+}));
+vi.mock('./privacyOrgs.js', () => ({
+ getOrg: vi.fn(async (id) => ({ id, name: 'Acme Bank', contact: { email: '[email protected]' } })),
+}));
+vi.mock('./messageAccounts.js', () => ({
+ listAccounts: vi.fn(async () => [{ id: 'acct-1', type: 'gmail', name: 'Primary' }]),
+}));
+vi.mock('./messageDrafts.js', () => ({
+ createDraft: vi.fn(async (data) => ({ id: 'draft-1', status: 'draft', ...data })),
+}));
+
+const {
+ declareChange, listChangeEvents, getChangeProgress, markOrgUpdated, markOrgRemoved,
+ draftUpdateEmail, renderUpdateEmailBody, kindForType,
+} = await import('./privacyChanges.js');
+
+const privacyVault = await import('./privacyVault.js');
+const privacyOrgs = await import('./privacyOrgs.js');
+const messageAccounts = await import('./messageAccounts.js');
+
+beforeEach(() => {
+ queryMock.mockReset();
+ withTransactionMock.mockReset();
+ privacyVault.getVaultRecord.mockClear();
+ privacyVault.revealValue.mockClear();
+ privacyOrgs.getOrg.mockClear();
+ messageAccounts.listAccounts.mockClear();
+});
+
+function mockTransaction(handler) {
+ const client = { query: vi.fn(handler) };
+ withTransactionMock.mockImplementation(async (fn) => fn(client));
+ return client;
+}
+
+const eventRow = (overrides = {}) => ({
+ id: 'ev1', vault_record_id: 'old1', replacement_record_id: 'new1',
+ kind: 'address_change', declared_at: 'now', note: '', ...overrides,
+});
+
+describe('kindForType', () => {
+ it('maps vault types to change kinds and defaults to other', () => {
+ expect(kindForType('address')).toBe('address_change');
+ expect(kindForType('phone')).toBe('phone_change');
+ expect(kindForType('email')).toBe('email_change');
+ expect(kindForType('legal_name')).toBe('name_change');
+ expect(kindForType('passport')).toBe('other');
+ });
+});
+
+describe('renderUpdateEmailBody', () => {
+ it('includes the new value and masked old value', () => {
+ const body = renderUpdateEmailBody({
+ orgName: 'Acme', fieldLabel: 'mailing address', oldMasked: '••• Old St', newValue: '742 New Ave',
+ });
+ expect(body).toContain('Acme');
+ expect(body).toContain('New mailing address: 742 New Ave');
+ expect(body).toContain('Previous mailing address on record: ••• Old St');
+ });
+
+ it('omits the previous line when no masked old value is supplied', () => {
+ const body = renderUpdateEmailBody({ fieldLabel: 'phone number', newValue: '555-0100' });
+ expect(body).toContain('New phone number: 555-0100');
+ expect(body).not.toContain('Previous');
+ });
+});
+
+describe('declareChange', () => {
+ it('retires the old record, creates the inline replacement, flips holdings, mirrors forward holdings, and writes the event', async () => {
+ const client = mockTransaction(async (sql) => {
+ if (/FROM privacy_vault_records WHERE id = \$1 FOR UPDATE/.test(sql)) return { rows: [{ id: 'old1', type: 'address' }] };
+ if (/INSERT INTO privacy_vault_records/.test(sql)) return { rows: [] };
+ if (/UPDATE privacy_vault_records\s+SET status = 'previous'/.test(sql)) return { rows: [] };
+ if (/UPDATE privacy_org_holdings SET status = 'update_pending'/.test(sql)) return { rows: [{ org_id: 'o1' }, { org_id: 'o2' }] };
+ if (/INSERT INTO privacy_org_holdings/.test(sql)) return { rows: [] };
+ if (/INSERT INTO privacy_change_events/.test(sql)) return { rows: [eventRow()] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+
+ const event = await declareChange({
+ vaultRecordId: 'old1',
+ replacement: { label: 'New home', value: '742 New Ave' },
+ note: 'moved',
+ });
+
+ expect(event).toMatchObject({ id: 'ev1', vaultRecordId: 'old1', replacementRecordId: 'new1', kind: 'address_change' });
+ // Old record retired.
+ const retire = client.query.mock.calls.find(([s]) => /SET status = 'previous'/.test(s));
+ expect(retire[0]).toMatch(/valid_to = COALESCE\(valid_to, CURRENT_DATE\)/);
+ // Replacement created with inherited type + encrypted value.
+ const insertRec = client.query.mock.calls.find(([s]) => /INSERT INTO privacy_vault_records/.test(s));
+ expect(insertRec[1]).toContain('enc(742 New Ave)');
+ // Both flipped orgs got a forward-looking current holding on the new record.
+ const forwardInserts = client.query.mock.calls.filter(([s]) => /INSERT INTO privacy_org_holdings/.test(s));
+ expect(forwardInserts).toHaveLength(2);
+ // Event kind derived from the old record type when none supplied.
+ const insertEvent = client.query.mock.calls.find(([s]) => /INSERT INTO privacy_change_events/.test(s));
+ expect(insertEvent[1]).toContain('address_change');
+ });
+
+ it('404s when the old record does not exist', async () => {
+ mockTransaction(async (sql) => {
+ if (/FOR UPDATE/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ await expect(declareChange({ vaultRecordId: 'missing', replacement: { label: 'x', value: 'y' } }))
+ .rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+
+ it('400s when linking a replacementRecordId that does not exist', async () => {
+ mockTransaction(async (sql) => {
+ if (/FOR UPDATE/.test(sql)) return { rows: [{ id: 'old1', type: 'email' }] };
+ if (/FROM privacy_vault_records WHERE id = \$1$/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ await expect(declareChange({ vaultRecordId: 'old1', replacementRecordId: 'bad', kind: 'email_change' }))
+ .rejects.toMatchObject({ status: 400, code: 'REPLACEMENT_NOT_FOUND' });
+ });
+
+ it('skips forward holdings for a removal-only change (no replacement)', async () => {
+ const client = mockTransaction(async (sql) => {
+ if (/FOR UPDATE/.test(sql)) return { rows: [{ id: 'old1', type: 'address' }] };
+ if (/SET status = 'previous'/.test(sql)) return { rows: [] };
+ if (/UPDATE privacy_org_holdings SET status = 'update_pending'/.test(sql)) return { rows: [{ org_id: 'o1' }] };
+ if (/INSERT INTO privacy_change_events/.test(sql)) return { rows: [eventRow({ replacement_record_id: null })] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ const event = await declareChange({ vaultRecordId: 'old1', kind: 'other' });
+ expect(event.replacementRecordId).toBe(null);
+ expect(client.query.mock.calls.filter(([s]) => /INSERT INTO privacy_org_holdings/.test(s))).toHaveLength(0);
+ });
+});
+
+describe('getChangeProgress', () => {
+ it('groups the old record holdings by inventory status', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ if (/FROM privacy_org_holdings h/.test(sql)) {
+ return { rows: [
+ { org_id: 'o1', status: 'update_pending', org_name: 'Bank A', website: 'https://a', contact: { email: 'a@a' } },
+ { org_id: 'o2', status: 'updated', org_name: 'Bank B', website: null, contact: {} },
+ { org_id: 'o3', status: 'removed', org_name: 'Bank C', website: null, contact: null },
+ ] };
+ }
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ const groups = await getChangeProgress('ev1');
+ expect(groups.pending).toEqual([{ orgId: 'o1', orgName: 'Bank A', website: 'https://a', contactEmail: 'a@a' }]);
+ expect(groups.updated[0]).toMatchObject({ orgId: 'o2', contactEmail: null });
+ expect(groups.removed[0]).toMatchObject({ orgId: 'o3', website: null, contactEmail: null });
+ });
+
+ it('404s an unknown event', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(getChangeProgress('missing')).rejects.toMatchObject({ status: 404 });
+ });
+});
+
+describe('markOrgUpdated', () => {
+ it('flips the org holding to updated and returns fresh progress', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ if (/UPDATE privacy_org_holdings SET status = \$1/.test(sql)) return { rows: [{ org_id: 'o1' }] };
+ if (/FROM privacy_org_holdings h/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ const groups = await markOrgUpdated('ev1', 'o1');
+ const updateCall = queryMock.mock.calls.find(([s]) => /SET status = \$1/.test(s));
+ expect(updateCall[1][0]).toBe('updated');
+ expect(groups).toEqual({ pending: [], updated: [], removed: [] });
+ });
+
+ it('404s when the org is not part of this change (idempotent guard also covers already-terminal)', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ if (/UPDATE privacy_org_holdings SET status = \$1/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ await expect(markOrgUpdated('ev1', 'nope')).rejects.toMatchObject({ status: 404, code: 'HOLDING_NOT_FOUND' });
+ });
+});
+
+describe('markOrgRemoved', () => {
+ it('flips to removed and drops the forward holding on the replacement record', async () => {
+ // getChangeEvent (pool query) then a transaction.
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ if (/FROM privacy_org_holdings h/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected pool query: ${sql}`);
+ });
+ const client = mockTransaction(async (sql) => {
+ if (/UPDATE privacy_org_holdings SET status = 'removed'/.test(sql)) return { rows: [{ org_id: 'o1' }] };
+ if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected client query: ${sql}`);
+ });
+ await markOrgRemoved('ev1', 'o1');
+ const del = client.query.mock.calls.find(([s]) => /DELETE FROM privacy_org_holdings/.test(s));
+ expect(del[1]).toEqual(['new1', 'o1']); // replacement record + org
+ });
+});
+
+describe('listChangeEvents', () => {
+ it('maps rows with progress counts + masked old/new values', async () => {
+ queryMock.mockResolvedValue({ rows: [{
+ ...eventRow(),
+ old_type: 'address', old_label: 'Old', old_masked: 'mask-old',
+ new_type: 'address', new_label: 'New', new_masked: 'mask-new',
+ pending_count: 2, updated_count: 1, removed_count: 0,
+ }] });
+ const list = await listChangeEvents();
+ expect(list[0]).toMatchObject({
+ id: 'ev1',
+ oldRecord: { type: 'address', maskedValue: 'mask-old' },
+ replacementRecord: { maskedValue: 'mask-new' },
+ progress: { pending: 2, updated: 1, removed: 0, total: 3 },
+ });
+ expect(JSON.stringify(list)).not.toContain('value_enc');
+ });
+});
+
+describe('draftUpdateEmail', () => {
+ it('creates an UNAPPROVED draft (status draft) to the org contact email', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ const result = await draftUpdateEmail('ev1', 'o1');
+ expect(result).toEqual({ draftId: 'draft-1', status: 'draft' });
+ expect(privacyVault.revealValue).toHaveBeenCalledWith('new1');
+ });
+
+ it('400s a removal-only change with no replacement to update to', async () => {
+ queryMock.mockResolvedValue({ rows: [eventRow({ replacement_record_id: null })] });
+ await expect(draftUpdateEmail('ev1', 'o1')).rejects.toMatchObject({ status: 400, code: 'REPLACEMENT_REQUIRED' });
+ });
+
+ it('400s when the org has no contact email', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_change_events WHERE id/.test(sql)) return { rows: [eventRow()] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ privacyOrgs.getOrg.mockResolvedValueOnce({ id: 'o1', name: 'NoEmail', contact: {} });
+ await expect(draftUpdateEmail('ev1', 'o1')).rejects.toMatchObject({ status: 400, code: 'ORG_EMAIL_MISSING' });
+ });
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index b63b6a7987..8563660ffb 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -14,6 +14,7 @@ export const DB_TEST_INCLUDE = [
'services/humanActivity.db.test.js',
'services/privacyVault.db.test.js',
'services/privacyOrgs.db.test.js',
+ 'services/privacyChanges.db.test.js',
'services/privacyBrokers.db.test.js',
'services/catalogCanonProjection.test.js',
'services/catalogRefResolver.test.js',