Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: seal broker-case identity evidence and let users erase it (#8333)
[._.]/ Adam Eivyb9a3e567b509
diff --git a/client/src/components/privacy/BrokerCaseDrawer.jsx b/client/src/components/privacy/BrokerCaseDrawer.jsxindex fac297ef40..3f1720cf78 100644--- a/client/src/components/privacy/BrokerCaseDrawer.jsx+++ b/client/src/components/privacy/BrokerCaseDrawer.jsx@@ -1,5 +1,7 @@-import { RotateCw, ExternalLink, CheckCircle2, XCircle, ListChecks } from 'lucide-react';+import { useState } from 'react';+import { RotateCw, ExternalLink, CheckCircle2, XCircle, ListChecks, Eraser } from 'lucide-react';import Drawer from '../Drawer';+import InlineConfirmRow from '../ui/InlineConfirmRow';import { timeAgo, formatDateShort } from '../../utils/formatters';import { CASE_STATE_TONE, ACTION_TONES, manualCaseActions, labelFor, CASE_STATES } from './constants';import { isHttpUrl } from '../../utils/urlNormalize';@@ -12,17 +14,27 @@ const ACTION_ICONS = { check: CheckCircle2, x: XCircle };// is a pure controlled view. The backend does not persist a full state-history// log, so "history" here is the timeline we DO have: created → last-updated →// next-recheck, plus the current reason/channel/disclosure/evidence.+//+// Identity evidence (#8333) — the matched name/location and the search/listing+// URLs built from them — is sealed server-side and absent from `caseData`.+// The parent reveals it for the open case and passes it as `identity`+// (null while loading, erased, or never recorded); `onEraseEvidence` drops it.export default function BrokerCaseDrawer({- open, onClose, caseData, broker, onRecheck, onTransition, busy = false,+ open, onClose, caseData, broker, onRecheck, onTransition, identity = null, onEraseEvidence, busy = false,}) {+ // Keyed by case id so an armed confirm never carries over to another case.+ const [confirmEraseId, setConfirmEraseId] = useState(null);+ const confirmErase = Boolean(caseData?.id) && confirmEraseId === caseData.id;// Stale/deleted deep link — the case is gone but the URL still points at it.const notFound = open && !caseData;const evidence = caseData?.evidence || {};- const listingUrls = Array.isArray(evidence.listing_urls) ? evidence.listing_urls : [];+ const listingUrls = Array.isArray(identity?.listing_urls) ? identity.listing_urls : [];const playbook = Array.isArray(broker?.optout?.playbook) ? broker.optout.playbook : [];const optoutUrl = broker?.optout?.url || evidence.optout_url || null;- const searchUrl = evidence.search_url || null;+ const searchUrl = identity?.search_url || null;+ const matched = [identity?.matched_name, identity?.matched_location].filter(Boolean).join(' · ');+ const hasSealedEvidence = Boolean(caseData?.identityEvidence?.sealed);// Which manual transitions make sense from the current state. The action// descriptors (label/tone/icon) live in the shared CASE_ACTIONS presentation@@ -108,6 +120,7 @@ export default function BrokerCaseDrawer({{evidence.match_basis && (<div className="text-xs text-gray-400 mb-1">Match basis: {evidence.match_basis}</div>)}+ {matched && <div className="text-xs text-gray-400 mb-1">Matched: {matched}</div>}{listingUrls.length ? (<ul className="space-y-1">{listingUrls.map((u) => (@@ -123,13 +136,35 @@ export default function BrokerCaseDrawer({))}</ul>) : (- <span className="text-gray-500 text-xs">No listing URLs recorded</span>+ <span className="text-gray-500 text-xs">+ {hasSealedEvidence && !identity ? 'Loading sealed evidence…' : 'No listing URLs recorded'}+ </span>)}{evidence.screenshot && isHttpUrl(evidence.screenshot) && (<a href={evidence.screenshot} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline mt-1"><ExternalLink size={12} /> Confirmation screenshot</a>)}+ {hasSealedEvidence && onEraseEvidence && (+ confirmErase ? (+ <InlineConfirmRow+ className="mt-2"+ question="Erase the matched name, location, and search/listing links for this case? A later scan can record them again."+ confirmText="Erase"+ onConfirm={() => { setConfirmEraseId(null); onEraseEvidence(caseData); }}+ onCancel={() => setConfirmEraseId(null)}+ />+ ) : (+ <button+ type="button"+ onClick={() => setConfirmEraseId(caseData.id)}+ disabled={busy}+ className="mt-2 inline-flex items-center gap-1 text-xs text-gray-400 hover:text-port-error disabled:opacity-50"+ >+ <Eraser size={12} /> Erase identity evidence+ </button>+ )+ )}</Row>{playbook.length > 0 && (diff --git a/client/src/components/privacy/BrokerCaseDrawer.test.jsx b/client/src/components/privacy/BrokerCaseDrawer.test.jsxindex c88be73c46..bba9162095 100644--- a/client/src/components/privacy/BrokerCaseDrawer.test.jsx+++ b/client/src/components/privacy/BrokerCaseDrawer.test.jsx@@ -3,7 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react';import BrokerCaseDrawer from './BrokerCaseDrawer.jsx';// Pins the blocked-case contract: an explainer with a manual-check link built-// from evidence.search_url, an "I'm listed" (→ found) action, and NO+// from the revealed identity evidence's search_url (#8333), an "I'm listed" (→ found) action, and NO// "Mark done" (blocked → submitted is not a legal server transition).const broker = { id: 'rad', name: 'Radaris', tier: 2, optout: { url: 'https://rad/optout', playbook: ['step one'] } };@@ -19,11 +19,13 @@ const renderDrawer = (caseData, props = {}) => {describe('BrokerCaseDrawer — blocked case', () => {const blockedCase = {id: 'b1', brokerId: 'rad', brokerName: 'Radaris', state: 'blocked',- evidence: { match_basis: 'antibot_wall', search_url: 'https://rad/p/Jane/Doe/' },+ evidence: { match_basis: 'antibot_wall' },+ identityEvidence: { sealed: true, listingCount: 0 },};+ const identity = { search_url: 'https://rad/p/Jane/Doe/' };it('shows the manual-check explainer with the filled search URL', () => {- renderDrawer(blockedCase);+ renderDrawer(blockedCase, { identity });expect(screen.getByText(/blocks automated checks/i)).toBeTruthy();const link = screen.getByRole('link', { name: /check manually in your browser/i });expect(link.getAttribute('href')).toBe('https://rad/p/Jane/Doe/');@@ -36,13 +38,40 @@ describe('BrokerCaseDrawer — blocked case', () => {expect(onTransition).toHaveBeenCalledWith(blockedCase, 'found');});- it('omits the manual-check link for a pre-existing case without search_url evidence', () => {- renderDrawer({ ...blockedCase, evidence: { match_basis: 'antibot_wall' } });+ it('omits the manual-check link while no identity evidence is revealed', () => {+ renderDrawer(blockedCase);expect(screen.getByText(/blocks automated checks/i)).toBeTruthy();expect(screen.queryByRole('link', { name: /check manually in your browser/i })).toBeNull();});});+describe('BrokerCaseDrawer — sealed identity evidence (#8333)', () => {+ const foundCase = {+ id: 'f1', brokerId: 'rad', brokerName: 'Radaris', state: 'found',+ evidence: { match_basis: 'name+location' },+ identityEvidence: { sealed: true, listingCount: 1 },+ };++ it('renders revealed listing links and erases only after the inline confirm', () => {+ const onEraseEvidence = vi.fn();+ renderDrawer(foundCase, {+ identity: { matched_name: 'Example Person', listing_urls: ['https://rad/p/example'] },+ onEraseEvidence,+ });+ expect(screen.getByRole('link', { name: /rad\/p\/example/ }).getAttribute('href')).toBe('https://rad/p/example');+ fireEvent.click(screen.getByRole('button', { name: /erase identity evidence/i }));+ expect(onEraseEvidence).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /^erase$/i }));+ expect(onEraseEvidence).toHaveBeenCalledWith(foundCase);+ });++ it('offers no erase control once the evidence is gone', () => {+ renderDrawer({ ...foundCase, identityEvidence: null }, { onEraseEvidence: vi.fn() });+ expect(screen.queryByRole('button', { name: /erase identity evidence/i })).toBeNull();+ expect(screen.getByText(/no listing urls recorded/i)).toBeTruthy();+ });+});+describe('BrokerCaseDrawer — human task case', () => {it('offers "Mark done" (→ submitted) and no blocked explainer', () => {const kase = { id: 'h1', brokerId: 'rad', brokerName: 'Radaris', state: 'human_task_queued', evidence: {} };diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsxindex bcf0c569b8..84c32d8bc6 100644--- a/client/src/components/privacy/PrivacyBrokersTab.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx@@ -8,6 +8,7 @@ import {getPrivacyScanStatus, getPrivacyBrokerCases, getPrivacyBrokers, getPrivacyOptOutDigest,getPrivacyOptOutSchedule, updatePrivacyOptOutSchedule, runPrivacyScan, runPrivacyOptOut,refreshPrivacyBrokers, recheckPrivacyCase, transitionPrivacyCase, setPrivacyBrokerEnabled,+ getPrivacyCaseEvidence, erasePrivacyCaseEvidence,} from '../../services/api';import { useAsyncAction } from '../../hooks/useAsyncAction';import toast from '../ui/Toast';@@ -96,6 +97,24 @@ export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageCoconst visibleCases = stateFilter ? cases.filter((c) => c.state === stateFilter) : cases;const openCase = openCaseId ? cases.find((c) => c.id === openCaseId) : null;+ // Sealed identity evidence (#8333) is not in the case list — the drawer+ // reveals it for the one open case. Keyed by case id so a stale response for+ // a previously-open case never renders under the current one.+ const [revealed, setRevealed] = useState(null);+ const openCaseSealed = Boolean(openCase?.identityEvidence?.sealed);+ const openCaseRowId = openCase?.id;+ // A re-scan/transition while the drawer is open bumps updatedAt → re-reveal.+ const openCaseUpdatedAt = openCase?.updatedAt;+ useEffect(() => {+ if (!openCaseRowId || !openCaseSealed) return undefined;+ let active = true;+ getPrivacyCaseEvidence(openCaseRowId)+ .then((r) => { if (active) setRevealed(r); })+ .catch(() => { if (active) setRevealed(null); });+ return () => { active = false; };+ }, [openCaseRowId, openCaseSealed, openCaseUpdatedAt]);+ const openCaseIdentity = openCaseSealed && revealed?.caseId === openCaseRowId ? revealed.evidence : null;+// ── Run controls (synchronous passes — gate both while either runs) ─────────// The engine refuses to scan (`broker_scan`) or submit (`broker_optout`) for// a subject without an active grant of that exact purpose (403@@ -179,6 +198,14 @@ export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageCoelse toast.error('Transition not allowed');};+ const doEraseEvidence = async (kase) => {+ setCaseBusy(true);+ const r = await erasePrivacyCaseEvidence(kase.id, { silent: true }).catch(() => null);+ setCaseBusy(false);+ if (r) { setRevealed(null); toast.success('Identity evidence erased'); load(); }+ else toast.error('Failed to erase identity evidence');+ };+const openDrawer = (id) => { searchParams.set('case', id); setSearchParams(searchParams, { replace: false }); };const closeDrawer = () => { searchParams.delete('case'); setSearchParams(searchParams, { replace: false }); };@@ -374,7 +401,7 @@ export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageCo<div className="space-y-1.5">{visibleCases.map((c) => {const broker = brokerById.get(c.brokerId);- const listingCount = Array.isArray(c.evidence?.listing_urls) ? c.evidence.listing_urls.length : 0;+ const listingCount = c.identityEvidence?.listingCount ?? 0;return (<buttonkey={c.id}@@ -453,6 +480,8 @@ export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageCoonClose={closeDrawer}onRecheck={doRecheck}onTransition={doTransition}+ identity={openCaseIdentity}+ onEraseEvidence={doEraseEvidence}busy={caseBusy}/></div>diff --git a/client/src/components/privacy/PrivacyBrokersTab.test.jsx b/client/src/components/privacy/PrivacyBrokersTab.test.jsxindex 7ac8d03030..fc9fe7e125 100644--- a/client/src/components/privacy/PrivacyBrokersTab.test.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.test.jsx@@ -16,7 +16,7 @@ const api = vi.hoisted(() => ({dueForRecheck: 1,},cases: [- { id: 'c1', brokerId: 'spokeo', brokerName: 'Spokeo', brokerTier: 1, state: 'found', evidence: { listing_urls: ['http://x/1'] }, nextRecheckAt: '2026-08-01T00:00:00.000Z', updatedAt: '2026-07-01T00:00:00.000Z' },+ { id: 'c1', brokerId: 'spokeo', brokerName: 'Spokeo', brokerTier: 1, state: 'found', evidence: { match_basis: 'name+location' }, identityEvidence: { sealed: true, listingCount: 1 }, nextRecheckAt: '2026-08-01T00:00:00.000Z', updatedAt: '2026-07-01T00:00:00.000Z' },{ id: 'c2', brokerId: 'wp', brokerName: 'WhitePages', state: 'confirmed_removed', evidence: {}, updatedAt: '2026-07-02T00:00:00.000Z' },],brokers: [{ id: 'spokeo', name: 'Spokeo', tier: 1, source: 'curated', confidence: 'documented', enabled: true, clusterParent: null, optout: {} }],@@ -45,6 +45,8 @@ vi.mock('../../services/api', () => ({refreshPrivacyBrokers: vi.fn(async () => ({ added: 0, fetched: 0 })),recheckPrivacyCase: vi.fn(async () => ({ id: 'c1' })),transitionPrivacyCase: vi.fn(async (id, toState) => ({ id, state: toState })),+ getPrivacyCaseEvidence: vi.fn(async (id) => ({ caseId: id, sealed: true, evidence: { listing_urls: ['https://spokeo.example/p/example'] } })),+ erasePrivacyCaseEvidence: vi.fn(async (id) => ({ id, state: 'found', identityEvidence: null })),setPrivacyBrokerEnabled: vi.fn(async (id, enabled) => ({ id, name: 'Spokeo', enabled, tier: 1, source: 'curated', confidence: 'documented', clusterParent: null })),}));@@ -73,6 +75,19 @@ describe('PrivacyBrokersTab', () => {expect(screen.getByText('WhitePages')).toBeTruthy();});+ it('reveals the open case\'s sealed evidence in the drawer and erases it (#8333)', async () => {+ render(<MemoryRouter initialEntries={['/privacy/brokers?case=c1']}><PrivacyBrokersTab /></MemoryRouter>);+ // The list shows only the non-identifying listing count; the drawer+ // decrypts the links for the one open case.+ const link = await screen.findByRole('link', { name: /spokeo\.example\/p\/example/ });+ expect(link.getAttribute('href')).toBe('https://spokeo.example/p/example');+ expect(apiMod.getPrivacyCaseEvidence).toHaveBeenCalledWith('c1');+ fireEvent.click(screen.getByRole('button', { name: /erase identity evidence/i }));+ fireEvent.click(screen.getByRole('button', { name: /^erase$/i }));+ await waitFor(() => expect(apiMod.erasePrivacyCaseEvidence).toHaveBeenCalledWith('c1', expect.anything()));+ await waitFor(() => expect(screen.queryByRole('link', { name: /spokeo\.example\/p\/example/ })).toBeNull());+ });+it('actions a human-task digest item (done → submitted)', async () => {renderTab();await screen.findByText('BeenVerified');diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.jsindex 47edf2bbde..3e32ec1247 100644--- a/client/src/services/apiPrivacy.js+++ b/client/src/services/apiPrivacy.js@@ -152,6 +152,15 @@ export const getPrivacyBrokerCases = (state, options) =>/** Force a case due for recheck now. */export const recheckPrivacyCase = (id, options) =>request(`/privacy/broker-cases/${id}/recheck`, { method: 'POST', ...options });+/**+ * Reveal a case's sealed identity evidence (matched name/location, search ++ * listing URLs) for the case drawer: `{ caseId, sealed, evidence }` (#8333).+ */+export const getPrivacyCaseEvidence = (id, options) =>+ request(`/privacy/broker-cases/${id}/evidence`, options);+/** Erase a case's identity evidence; state + verdict metadata stay. Returns the case. */+export const erasePrivacyCaseEvidence = (id, options) =>+ request(`/privacy/broker-cases/${id}/evidence`, { method: 'DELETE', ...options });/** Manual case transition (digest done/dismiss, drawer controls): { toState, reason? }. */export const transitionPrivacyCase = (id, toState, reason, options) => request(`/privacy/broker-cases/${id}/transition`, {method: 'POST',diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 8821b05fd3..f056cc2592 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -51,7 +51,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`; PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.-- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.+- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). Broker-case `evidence` follows the same rule (#8333): the matched name/location and the identity-bearing search/listing URLs a scan records are sealed under `evidence.sealed_identity` with the same key, erased on `confirmed_removed`, on the per-case erase action, and when the source `legal_name`/`address` vault record is deleted. **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)diff --git a/server/lib/db/schema/privacy.js b/server/lib/db/schema/privacy.jsindex 3a63a68030..e7dda96a36 100644--- a/server/lib/db/schema/privacy.js+++ b/server/lib/db/schema/privacy.js@@ -176,9 +176,10 @@ export const privacyDdl = [// Per-broker exposure/opt-out case ledger with a service-enforced state// machine. `state` is validated app-side (privacyBrokers.js); every write// stamps `next_recheck_at` (state-dependent backoff). `evidence` holds- // listing URLs / match basis / screenshot refs — NOT plaintext PII (the- // engine records only least-disclosure identifiers). A broker delete- // cascades its cases.+ // match basis / lane / playbook / screenshot refs in the clear; the+ // identity-bearing fields (matched name + location, search/listing URLs)+ // are sealed under `evidence.sealed_identity` with the vault key (#8333,+ // privacyBrokers.js). A broker delete cascades its cases.`CREATE TABLE IF NOT EXISTS privacy_broker_cases (id UUID PRIMARY KEY,subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,diff --git a/server/routes/privacy.js b/server/routes/privacy.jsindex 59f8629de1..0fd45d165b 100644--- a/server/routes/privacy.js+++ b/server/routes/privacy.js@@ -85,6 +85,8 @@ import {setBrokerEnabled,forceRecheckCase,transitionCase,+ revealCaseEvidence,+ clearCaseIdentityEvidence,} from '../services/privacyBrokers.js';import { runScanPass } from '../services/privacyScan.js';import { runOptOutPass, runVerificationPass, getOptOutDigest } from '../services/privacyOptOut.js';@@ -328,6 +330,19 @@ router.post('/broker-cases/:id/recheck', asyncHandler(async (req, res) => {res.json(await forceRecheckCase(id));}));+// Sealed identity evidence (#8333): the case list projects only a summary; the+// case drawer reveals the matched name/location + search/listing URLs through+// this explicit action, and can erase them outright.+router.get('/broker-cases/:id/evidence', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyCaseIdParamsSchema, req.params);+ res.json(await revealCaseEvidence(id));+}));++router.delete('/broker-cases/:id/evidence', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyCaseIdParamsSchema, req.params);+ res.json(await clearCaseIdentityEvidence(id));+}));+// Manual case transition (digest done/dismiss, case-drawer controls, #2146).// Only human-reachable targets are accepted (schema); the service's state// machine enforces validity of the specific from→to move on top of that.diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsindex 962b274b8a..aa1c06709a 100644--- a/server/routes/privacy.test.js+++ b/server/routes/privacy.test.js@@ -39,6 +39,8 @@ vi.mock('../services/privacyBrokers.js', () => ({setBrokerEnabled: vi.fn(async (id, enabled) => ({ id, name: 'Spokeo', enabled })),forceRecheckCase: vi.fn(async (id) => ({ id, state: 'found', nextRecheckAt: '2020-01-01T00:00:00.000Z' })),transitionCase: vi.fn(async (id, toState) => ({ id, state: toState })),+ revealCaseEvidence: vi.fn(async (id) => ({ caseId: id, sealed: true, evidence: { search_url: 'https://b.example/s' } })),+ clearCaseIdentityEvidence: vi.fn(async (id) => ({ id, state: 'found', identityEvidence: null })),}));vi.mock('../services/privacyRecheckScheduler.js', () => ({@@ -540,6 +542,24 @@ describe('POST /api/privacy/broker-cases/:id/recheck (#2146)', () => {});});+describe('/api/privacy/broker-cases/:id/evidence (#8333)', () => {+ it('reveals the sealed identity evidence and erases it', async () => {+ const shown = await request(makeApp()).get(`/api/privacy/broker-cases/${VALID_UUID}/evidence`);+ expect(shown.status).toBe(200);+ expect(shown.body.evidence.search_url).toBe('https://b.example/s');+ expect(brokerService.revealCaseEvidence).toHaveBeenCalledWith(VALID_UUID);+ const erased = await request(makeApp()).delete(`/api/privacy/broker-cases/${VALID_UUID}/evidence`);+ expect(erased.status).toBe(200);+ expect(erased.body.identityEvidence).toBe(null);+ expect(brokerService.clearCaseIdentityEvidence).toHaveBeenCalledWith(VALID_UUID);+ });++ it('rejects a non-uuid id on both verbs', async () => {+ expect((await request(makeApp()).get('/api/privacy/broker-cases/not-a-uuid/evidence')).status).toBe(400);+ expect((await request(makeApp()).delete('/api/privacy/broker-cases/not-a-uuid/evidence')).status).toBe(400);+ });+});+describe('POST /api/privacy/broker-cases/:id/transition (#2146)', () => {it('transitions a case to a manual target state', async () => {const res = await request(makeApp()).post(`/api/privacy/broker-cases/${VALID_UUID}/transition`).send({ toState: 'submitted' });diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 3ecd8e2198..84011684f3 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1456,9 +1456,11 @@ CREATE INDEX IF NOT EXISTS idx_privacy_brokers_enabled ON privacy_brokers (enablCREATE INDEX IF NOT EXISTS idx_privacy_brokers_cluster_parent ON privacy_brokers (cluster_parent);-- Per-broker exposure/opt-out case ledger with a service-enforced state machine.-- `state` is validated app-side (privacyBrokers.js); every write stamps--- `next_recheck_at` (state-dependent backoff). `evidence` holds listing URLs /--- match basis / screenshot refs — NOT plaintext PII. A broker delete cascades--- its cases.+-- `next_recheck_at` (state-dependent backoff). `evidence` holds match basis /+-- lane / screenshot refs in the clear; the identity-bearing fields (matched+-- name + location, search/listing URLs) are sealed under+-- `evidence.sealed_identity` with the vault key (#8333). A broker delete+-- cascades its cases.CREATE TABLE IF NOT EXISTS privacy_broker_cases (id UUID PRIMARY KEY,subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,diff --git a/server/services/privacyBrokers.db.test.js b/server/services/privacyBrokers.db.test.jsindex 2b0c2c96c8..6ceb39e9ad 100644--- a/server/services/privacyBrokers.db.test.js+++ b/server/services/privacyBrokers.db.test.js@@ -10,6 +10,9 @@import { describe, it, expect, afterAll, beforeAll } from 'vitest';import { checkHealth, ensureSchema, query, close } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { mkdtempSync, writeFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';// A valid vault key BEFORE privacyVault is imported so the runScanPass test can// create a scan-eligible name without touching the repo's real .env.@@ -38,7 +41,10 @@ describe.skipIf(!runDb)('privacy brokers DB round-trip', () => {let svc;let scan;let vault;- const autoBrokerIds = ['test-auto-alpha', 'ca-test-beta-inc', 'test-auto-upgrade'];+ const autoBrokerIds = [+ 'test-auto-alpha', 'ca-test-beta-inc', 'test-auto-upgrade',+ 'test-evidence-seal', 'test-evidence-erase', 'test-evidence-legacy', 'test-evidence-vault',+ ];const createdVaultIds = [];const vaultTableWasEmpty = false;const testStart = new Date().toISOString();@@ -211,6 +217,130 @@ describe.skipIf(!runDb)('privacy brokers DB round-trip', () => {expect(owned.state).toBe('confirmed_removed');});+ // ─── Sealed identity evidence (#8333) ─────────────────────────────────────+ // Fake identity values, distinctive enough that a substring hit on the raw+ // JSONB column (what pg_dump writes) can only mean a plaintext copy.+ const IDENTITY = {+ matched_name: 'Jane Q Sealtest',+ matched_location: 'Sealville',+ search_url: 'https://seal-broker.example/Jane-Sealtest/Sealville',+ listing_urls: ['https://seal-broker.example/p/jane-sealtest'],+ };+ const insertTestBroker = (id) => query(+ `INSERT INTO privacy_brokers (id, name, source, confidence, enabled, created_at, updated_at)+ VALUES ($1, $1, 'badbool', 'auto', FALSE, NOW(), NOW()) ON CONFLICT (id) DO NOTHING`, [id],+ );+ const rawEvidence = async (caseId) => (await query(+ `SELECT evidence::text AS t FROM privacy_broker_cases WHERE id = $1`, [caseId],+ )).rows[0].t;+ const expectNoPlaintextIdentity = (text) => {+ for (const needle of ['Sealtest', 'Sealville', 'seal-broker.example']) expect(text).not.toContain(needle);+ };++ it('stores scan identity evidence sealed, reveals it on request, and erases it on confirmed_removed', async () => {+ await insertTestBroker('test-evidence-seal');+ const kase = await svc.recordScanVerdict('test-evidence-seal', 'found', {+ evidence: { match_basis: 'name+location', ...IDENTITY }, found: true,+ });+ // At rest (and so in every dump): no plaintext name, location, or URL.+ expectNoPlaintextIdentity(await rawEvidence(kase.id));+ // The API projection carries the verdict metadata + a summary, never the identity.+ expect(kase.evidence).toEqual({ match_basis: 'name+location' });+ expect(kase.identityEvidence).toEqual({ sealed: true, listingCount: 1 });+ expect((await svc.revealCaseEvidence(kase.id)).evidence).toEqual(IDENTITY);++ // Lifecycle transitions that restate workflow metadata carry the envelope forward.+ await svc.transitionCase(kase.id, 'optout_in_progress', { evidence: { lane: 'web_form' } });+ await svc.transitionCase(kase.id, 'submitted');+ const pending = await svc.transitionCase(kase.id, 'verification_pending');+ expect(pending.identityEvidence).toEqual({ sealed: true, listingCount: 1 });+ expect((await svc.revealCaseEvidence(kase.id)).evidence.search_url).toBe(IDENTITY.search_url);++ // The verifying re-scan's confirmed_removed erases the identity copy but+ // keeps the non-identifying evidence, the state, and the case history.+ const removed = await svc.transitionCase(kase.id, 'confirmed_removed', { viaRescan: true });+ expect(removed.state).toBe('confirmed_removed');+ expect(removed.identityEvidence).toBe(null);+ expect(removed.evidence).toEqual({ lane: 'web_form' });+ expect(new Date(removed.createdAt).getTime()).toBe(new Date(kase.createdAt).getTime());+ expect(await rawEvidence(kase.id)).not.toContain('sealed_identity');+ expect(await svc.revealCaseEvidence(kase.id)).toEqual({ caseId: kase.id, sealed: false, evidence: {} });+ });++ it('erases one case\'s identity evidence on request, keeping its state and verdict', async () => {+ await insertTestBroker('test-evidence-erase');+ const kase = await svc.recordScanVerdict('test-evidence-erase', 'blocked', {+ evidence: { match_basis: 'antibot_wall', search_url: IDENTITY.search_url },+ });+ const cleared = await svc.clearCaseIdentityEvidence(kase.id);+ expect(cleared).toMatchObject({ state: 'blocked', evidence: { match_basis: 'antibot_wall' }, identityEvidence: null });+ // Gone from later API responses too.+ const listed = (await svc.listBrokerCases()).find((c) => c.id === kase.id);+ expect(listed.identityEvidence).toBe(null);+ expect((await svc.revealCaseEvidence(kase.id)).evidence).toEqual({});+ await expect(svc.clearCaseIdentityEvidence('00000000-0000-4000-8000-00000000dead')).rejects.toMatchObject({ status: 404 });+ });++ it('converts a legacy plaintext case idempotently, and a failed conversion changes nothing', async () => {+ await insertTestBroker('test-evidence-legacy');+ const legacyId = '00000000-0000-4000-8000-0000000833aa';+ await query(+ `INSERT INTO privacy_broker_cases (id, broker_id, state, found, evidence, next_recheck_at, created_at, updated_at)+ VALUES ($1, 'test-evidence-legacy', 'found', TRUE, $2, NOW(), NOW(), NOW())`,+ [legacyId, JSON.stringify({ match_basis: 'name+location', ...IDENTITY })],+ );+ const before = await rawEvidence(legacyId);++ // No usable key and an unwritable .env: the conversion cannot seal, so the+ // read that triggered it fails and the row is left exactly as it was.+ const vaultCrypto = await import('../lib/vaultCrypto.js');+ const blockerDir = mkdtempSync(join(tmpdir(), 'portos-8333-'));+ writeFileSync(join(blockerDir, 'not-a-dir'), '');+ const savedKey = process.env.PRIVACY_VAULT_KEY;+ delete process.env.PRIVACY_VAULT_KEY;+ vaultCrypto.__setVaultEnvPathForTests(join(blockerDir, 'not-a-dir', '.env'));+ svc.__resetCaseEvidenceSealForTests();+ try {+ await expect(svc.listBrokerCases()).rejects.toThrow();+ expect(await rawEvidence(legacyId)).toBe(before);+ } finally {+ process.env.PRIVACY_VAULT_KEY = savedKey;+ vaultCrypto.__setVaultEnvPathForTests(null);+ rmSync(blockerDir, { recursive: true, force: true });+ }++ // With the key back, the next read converts before returning anything.+ const listed = (await svc.listBrokerCases()).find((c) => c.id === legacyId);+ expect(listed.evidence).toEqual({ match_basis: 'name+location' });+ expect(listed.identityEvidence).toEqual({ sealed: true, listingCount: 1 });+ expectNoPlaintextIdentity(await rawEvidence(legacyId));+ expect((await svc.revealCaseEvidence(legacyId)).evidence).toEqual(IDENTITY);+ // Idempotent: a second conversion pass leaves the sealed row byte-identical+ // (it is not re-encrypted, which would mint a new IV).+ const sealed = await rawEvidence(legacyId);+ svc.__resetCaseEvidenceSealForTests();+ await svc.listBrokerCases();+ expect(await rawEvidence(legacyId)).toBe(sealed);+ });++ it('deleting the source vault record leaves no identity copy in the case API or the stored row', async () => {+ await insertTestBroker('test-evidence-vault');+ const nameRec = await vault.createVaultRecord({ type: 'legal_name', label: 'Seal test name', value: IDENTITY.matched_name });+ const kase = await svc.recordScanVerdict('test-evidence-vault', 'found', {+ evidence: { match_basis: 'name+location', ...IDENTITY }, found: true,+ });+ expect(kase.identityEvidence?.sealed).toBe(true);++ await vault.deleteVaultRecord(nameRec.id);+ const after = await svc.getCaseForBroker('test-evidence-vault');+ expect(after.state).toBe('found');+ expect(after.identityEvidence).toBe(null);+ expect(after.evidence).toEqual({ match_basis: 'name+location' });+ const raw = await rawEvidence(kase.id);+ expectNoPlaintextIdentity(raw);+ expect(raw).not.toContain('sealed_identity');+ });+it('reports scan status counts', async () => {const status = await svc.getScanStatus();expect(status.enabledBrokers).toBeGreaterThan(0);diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.jsindex 2398948af7..9d0d1a6979 100644--- a/server/services/privacyBrokers.js+++ b/server/services/privacyBrokers.js@@ -29,6 +29,7 @@ import { ServerError } from '../lib/errorHandler.js';import { PATHS } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { resolveSubjectId } from './privacySubjects.js';+import { encryptValue, decryptValue, ensureVaultKey } from '../lib/vaultCrypto.js';// Cap on each registry fetch so a hung broker source can't stall a// user-triggered refresh indefinitely (both fetchers run under Promise.all).@@ -420,8 +421,133 @@ export async function refreshBrokers({ fetchBadbool = defaultFetchBadbool, fetchconst CASE_COLUMNS = `id, subject_id, broker_id, state, found, evidence, disclosed_fields,channel, reason, next_recheck_at, created_at, updated_at`;+// ─── Identity-bearing case evidence (#8333) ─────────────────────────────────+//+// A scan's evidence names the person it matched: the legal name and city/state+// it found, and the broker search/listing URLs built from them. Those copies+// must not sit in plaintext JSONB beside the encrypted vault (or in every+// pg_dump of it), so they live in a sealed envelope under `sealed_identity`,+// encrypted with the vault's own key (lib/vaultCrypto.js). Everything else in+// `evidence` (match_basis, lane, playbook, verification metadata…) stays+// plain — it identifies the broker and the workflow, not the person.+//+// Envelope: `{ v: 1, ciphertext: 'v1:<iv>:<tag>:<ct>', listing_count }`. The+// ciphertext is JSON of the identity fields; `listing_count` is a+// non-identifying tally so the case list can say "2 listings" without a+// decrypt. The envelope is dropped wholesale on an explicit erase, on+// `confirmed_removed`, and when the vault record it was derived from is+// deleted.++export const IDENTITY_EVIDENCE_KEYS = Object.freeze(['matched_name', 'matched_location', 'search_url', 'listing_urls']);+const SEALED_EVIDENCE_KEY = 'sealed_identity';+const EVIDENCE_ENVELOPE_VERSION = 1;+// Every key that must be gone from a row whose identity evidence is erased.+const ERASABLE_EVIDENCE_KEYS = Object.freeze([...IDENTITY_EVIDENCE_KEYS, SEALED_EVIDENCE_KEY]);++const hasIdentityValue = (v) => (Array.isArray(v) ? v.length > 0 : (v !== undefined && v !== null && v !== ''));++/**+ * Split raw evidence into its plain (non-identifying) part and the identity+ * fields that carry a value. A caller-supplied `sealed_identity` is never+ * trusted as input — the only envelope a write keeps is the one already stored.+ */+function splitEvidence(evidence) {+ const plain = {};+ const identity = {};+ const source = evidence && typeof evidence === 'object' && !Array.isArray(evidence) ? evidence : {};+ for (const [key, value] of Object.entries(source)) {+ if (key === SEALED_EVIDENCE_KEY) continue;+ if (IDENTITY_EVIDENCE_KEYS.includes(key)) {+ if (hasIdentityValue(value)) identity[key] = value;+ } else {+ plain[key] = value;+ }+ }+ return { plain, identity };+}++/**+ * The evidence object to PERSIST: plain fields + (optionally) the sealed+ * envelope. Identity fields present in `evidence` are sealed fresh (a new scan+ * replaces the old match); when there are none, `existingEnvelope` is kept so+ * a lifecycle transition that only restates workflow metadata doesn't silently+ * drop the scan's search link. `clearIdentity` drops identity outright.+ */+async function prepareEvidenceForStorage(evidence, { existingEnvelope = null, clearIdentity = false } = {}) {+ const { plain, identity } = splitEvidence(evidence);+ if (clearIdentity) return plain;+ if (Object.keys(identity).length === 0) {+ return existingEnvelope ? { ...plain, [SEALED_EVIDENCE_KEY]: existingEnvelope } : plain;+ }+ await ensureVaultKey();+ const envelope = {+ v: EVIDENCE_ENVELOPE_VERSION,+ ciphertext: encryptValue(JSON.stringify(identity)),+ listing_count: Array.isArray(identity.listing_urls) ? identity.listing_urls.length : 0,+ };+ return { ...plain, [SEALED_EVIDENCE_KEY]: envelope };+}++/** Decrypt a stored envelope → the identity fields. Throws on an unknown version or tampering. */+function openEvidenceEnvelope(envelope) {+ if (!envelope) return {};+ if (envelope.v !== EVIDENCE_ENVELOPE_VERSION || typeof envelope.ciphertext !== 'string') {+ throw new ServerError('Unsupported broker case evidence envelope', { status: 500, code: 'EVIDENCE_ENVELOPE_UNSUPPORTED' });+ }+ return JSON.parse(decryptValue(envelope.ciphertext));+}++// Legacy-row conversion runs once per process (single-flight), before the+// first ledger read returns anything. A failure leaves the flag unset, so the+// read that triggered it fails loudly and the next read retries.+let evidenceSealed = false;+let evidenceSealFlight = null;++/**+ * Seal any case row still holding plaintext identity evidence (rows written+ * before #8333). Idempotent: a converted row no longer matches the key probe.+ * One transaction — either every matched row is converted or none is.+ */+async function sealLegacyCaseEvidence() {+ return withTransaction(async (client) => {+ const { rows } = await client.query(+ `SELECT id, evidence FROM privacy_broker_cases WHERE evidence ?| $1::text[] FOR UPDATE`,+ [IDENTITY_EVIDENCE_KEYS],+ );+ for (const row of rows) {+ const evidence = parseEvidence(row.evidence);+ const stored = await prepareEvidenceForStorage(evidence, { existingEnvelope: evidence[SEALED_EVIDENCE_KEY] ?? null });+ await client.query(`UPDATE privacy_broker_cases SET evidence = $1 WHERE id = $2`, [JSON.stringify(stored), row.id]);+ }+ if (rows.length) console.log(`🔐 Sealed identity evidence on ${rows.length} legacy broker case(s)`);+ return { converted: rows.length };+ });+}++async function ensureCaseEvidenceSealed() {+ if (evidenceSealed) return;+ if (!evidenceSealFlight) {+ evidenceSealFlight = sealLegacyCaseEvidence()+ .then(() => { evidenceSealed = true; })+ .finally(() => { evidenceSealFlight = null; });+ }+ await evidenceSealFlight;+}++export function __resetCaseEvidenceSealForTests() {+ evidenceSealed = false;+ evidenceSealFlight = null;+}++function parseEvidence(raw) {+ if (typeof raw === 'string') return JSON.parse(raw);+ return raw && typeof raw === 'object' ? raw : {};+}+function rowToCase(row) {if (!row) return null;+ const storedEvidence = parseEvidence(row.evidence);+ const envelope = storedEvidence[SEALED_EVIDENCE_KEY] ?? null;return {id: row.id,subjectId: row.subject_id,@@ -431,7 +557,12 @@ function rowToCase(row) {// strips render only actions whose target is in this list (issue #2417).allowedTransitions: allowedTransitionsFor(row.state),found: row.found ?? null,- evidence: row.evidence ?? {},+ // Non-identifying evidence only — identity fields are never projected,+ // even from a row the legacy conversion hasn't reached yet.+ evidence: splitEvidence(storedEvidence).plain,+ // Summary of the sealed identity evidence (null once erased). Revealing it+ // is the explicit `revealCaseEvidence` action.+ identityEvidence: envelope ? { sealed: true, listingCount: envelope.listing_count ?? 0 } : null,disclosedFields: row.disclosed_fields ?? [],channel: row.channel ?? null,reason: row.reason ?? null,@@ -444,7 +575,32 @@ function rowToCase(row) {};}-export async function listBrokerCases({ state, subjectId } = {}) {+/**+ * The identity fields a stored row's envelope holds, for SERVER-SIDE engine use+ * (the opt-out planner's listing URLs, the digest's manual-check link). A+ * decrypt failure (rotated/missing key, tampering) degrades to `null` with a+ * warning rather than failing the whole pass — the explicit reveal action is+ * where that failure surfaces to the user.+ */+function readIdentityForEngine(row) {+ const envelope = parseEvidence(row.evidence)[SEALED_EVIDENCE_KEY];+ if (!envelope) return null;+ try {+ return openEvidenceEnvelope(envelope);+ } catch (err) {+ console.warn(`⚠️ Broker case ${row.id}: sealed identity evidence unreadable (${err.message})`);+ return null;+ }+}++/**+ * List a subject's cases. `includeIdentity` is for in-process engines only+ * (opt-out planner, digest): it attaches the decrypted identity fields as+ * `identity` on each case. Route handlers never pass it — the API projection+ * carries only `identityEvidence` (a summary) and the reveal action decrypts.+ */+export async function listBrokerCases({ state, subjectId, includeIdentity = false } = {}) {+ await ensureCaseEvidenceSealed();// Always scoped to ONE subject (defaulting to `self`): two household members// hold independent cases against the same broker, and the opt-out engine must// never plan a submission for one using the other's ledger.@@ -462,10 +618,12 @@ export async function listBrokerCases({ state, subjectId } = {}) {ORDER BY b.name ASC`,params,);- return rows.map(rowToCase);+ if (!includeIdentity) return rows.map(rowToCase);+ return rows.map((row) => ({ ...rowToCase(row), identity: readIdentityForEngine(row) }));}export async function getCaseForBroker(brokerId, { subjectId } = {}) {+ await ensureCaseEvidenceSealed();const { rows } = await query(`SELECT ${CASE_COLUMNS} FROM privacy_broker_cases WHERE broker_id = $1 AND subject_id = $2`,[brokerId, resolveSubjectId(subjectId)],@@ -483,6 +641,9 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, founthrow new ServerError(`Not a scan verdict: "${verdict}"`, { status: 400, code: 'INVALID_SCAN_VERDICT' });}const resolvedSubjectId = resolveSubjectId(subjectId);+ // A fresh scan REPLACES the identity match (a re-scan that no longer finds a+ // listing must not keep the old one), so no existing envelope is carried.+ const storedEvidence = JSON.stringify(await prepareEvidenceForStorage(evidence));return withTransaction(async (client) => {const broker = await client.query(`SELECT id FROM privacy_brokers WHERE id = $1`, [brokerId]);if (!broker.rows[0]) throw new ServerError('Broker not found', { status: 404, code: 'NOT_FOUND' });@@ -503,7 +664,7 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun(id, subject_id, broker_id, state, found, evidence, next_recheck_at, created_at, updated_at)VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), NOW())RETURNING ${CASE_COLUMNS}`,- [id, resolvedSubjectId, brokerId, verdict, found, JSON.stringify(evidence), nextRecheck],+ [id, resolvedSubjectId, brokerId, verdict, found, storedEvidence, nextRecheck],);await client.query('RELEASE SAVEPOINT sp_insert_scan_verdict');console.log(`🔎 Broker ${brokerId}: new case → ${verdict} (subject=${resolvedSubjectId})`);@@ -521,7 +682,7 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun`UPDATE privacy_broker_casesSET state = $1, found = $2, evidence = $3, next_recheck_at = $4, updated_at = NOW()WHERE id = $5 RETURNING ${CASE_COLUMNS}`,- [verdict, found, JSON.stringify(evidence), nextRecheck, raceExisting.rows[0].id],+ [verdict, found, storedEvidence, nextRecheck, raceExisting.rows[0].id],);console.log(`🔎 Broker ${brokerId}: case ${raceExisting.rows[0].state} → ${verdict} (subject=${resolvedSubjectId})`);return rowToCase(rows[0]);@@ -536,7 +697,7 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun`UPDATE privacy_broker_casesSET state = $1, found = $2, evidence = $3, next_recheck_at = $4, updated_at = NOW()WHERE id = $5 RETURNING ${CASE_COLUMNS}`,- [verdict, found, JSON.stringify(evidence), nextRecheck, existing.rows[0].id],+ [verdict, found, storedEvidence, nextRecheck, existing.rows[0].id],);console.log(`🔎 Broker ${brokerId}: case ${existing.rows[0].state} → ${verdict} (subject=${resolvedSubjectId})`);return rowToCase(rows[0]);@@ -548,12 +709,18 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun* Enforces the state machine + stamps `next_recheck_at`. `patch` may carry* `channel`, `reason`, `disclosedFields`, `evidence`, and a `viaRescan` flag* (verification-only targets). Used by the Phase 6 opt-out engine.+ *+ * Evidence (#8333): identity fields in `patch.evidence` are sealed; without+ * any, the case's existing sealed envelope is carried forward. Reaching+ * `confirmed_removed` ERASES the identity envelope — the listing is gone, so+ * the only remaining copy of the matched name/location/URLs is ours — while the+ * plain verdict metadata, state, and timestamps are kept.*/export async function transitionCase(caseId, toState, patch = {}) {const { viaRescan = false, now = new Date() } = patch;return withTransaction(async (client) => {const existing = await client.query(- `SELECT id, state FROM privacy_broker_cases WHERE id = $1 FOR UPDATE`, [caseId],+ `SELECT id, state, evidence FROM privacy_broker_cases WHERE id = $1 FOR UPDATE`, [caseId],);if (!existing.rows[0]) throw new ServerError('Case not found', { status: 404, code: 'NOT_FOUND' });assertTransition(existing.rows[0].state, toState, { viaRescan });@@ -571,7 +738,13 @@ export async function transitionCase(caseId, toState, patch = {}) {if (patch.channel !== undefined) add('channel', patch.channel);if (patch.reason !== undefined) add('reason', patch.reason);if (patch.disclosedFields !== undefined) add('disclosed_fields', patch.disclosedFields);- if (patch.evidence !== undefined) add('evidence', JSON.stringify(patch.evidence));+ const clearIdentity = toState === 'confirmed_removed';+ if (patch.evidence !== undefined || clearIdentity) {+ const stored = parseEvidence(existing.rows[0].evidence);+ add('evidence', JSON.stringify(await prepareEvidenceForStorage(patch.evidence ?? stored, {+ existingEnvelope: stored[SEALED_EVIDENCE_KEY] ?? null, clearIdentity,+ })));+ }params.push(caseId);const { rows } = await client.query(`UPDATE privacy_broker_cases SET ${sets.join(', ')} WHERE id = $${params.length} RETURNING ${CASE_COLUMNS}`,@@ -582,6 +755,57 @@ export async function transitionCase(caseId, toState, patch = {}) {});}+/**+ * Explicit per-case evidence ERASE (#8333): drop the sealed identity envelope+ * (and any legacy plaintext identity field) from one case, keeping its state,+ * verdict metadata, and timestamps. Idempotent — erasing an already-clear case+ * returns it unchanged apart from `updated_at`. 404 if the case is unknown.+ */+export async function clearCaseIdentityEvidence(caseId) {+ const { rows } = await query(+ `UPDATE privacy_broker_cases SET evidence = evidence - $1::text[], updated_at = NOW()+ WHERE id = $2 RETURNING ${CASE_COLUMNS}`,+ [ERASABLE_EVIDENCE_KEYS, caseId],+ );+ if (!rows[0]) throw new ServerError('Case not found', { status: 404, code: 'NOT_FOUND' });+ console.log(`🗑️ Case ${caseId}: identity evidence erased`);+ return rowToCase(rows[0]);+}++/**+ * Erase the identity evidence on EVERY case of a subject — called when a vault+ * record that feeds scan vectors is deleted, so the name/location the user just+ * removed from the vault doesn't survive in the case ledger (or its backups).+ * The next scan re-derives search links from whatever the vault still holds.+ * Accepts the caller's transaction client so the erase commits with the delete.+ */+export async function clearSubjectIdentityEvidence(subjectId, { client = null } = {}) {+ const run = client ? (sql, params) => client.query(sql, params) : query;+ const { rowCount } = await run(+ `UPDATE privacy_broker_cases SET evidence = evidence - $1::text[], updated_at = NOW()+ WHERE subject_id = $2 AND evidence ?| $1::text[]`,+ [ERASABLE_EVIDENCE_KEYS, resolveSubjectId(subjectId)],+ );+ if (rowCount) console.log(`🗑️ Erased identity evidence on ${rowCount} broker case(s) (subject=${resolveSubjectId(subjectId)})`);+ return { cleared: rowCount ?? 0 };+}++/**+ * The ONE user-facing decrypt path for case evidence: the case drawer's+ * search/listing links. Returns `{ caseId, sealed, evidence }` where+ * `evidence` holds the identity fields (empty once erased). Logs the id only.+ */+export async function revealCaseEvidence(caseId) {+ await ensureCaseEvidenceSealed();+ const { rows } = await query(`SELECT id, evidence FROM privacy_broker_cases WHERE id = $1`, [caseId]);+ if (!rows[0]) throw new ServerError('Case not found', { status: 404, code: 'NOT_FOUND' });+ const envelope = parseEvidence(rows[0].evidence)[SEALED_EVIDENCE_KEY];+ if (!envelope) return { caseId, sealed: false, evidence: {} };+ const identity = openEvidenceEnvelope(envelope);+ console.log(`🔓 Revealed broker case evidence ${caseId}`);+ return { caseId, sealed: true, evidence: identity };+}+/*** Force a case due for recheck NOW (Brokers-tab manual "Re-check" control,* #2146): stamp `next_recheck_at` in the past so the next scan/opt-out passdiff --git a/server/services/privacyOptOut.js b/server/services/privacyOptOut.jsindex b41828b91a..0514c3dd6a 100644--- a/server/services/privacyOptOut.js+++ b/server/services/privacyOptOut.js@@ -513,7 +513,7 @@ export async function runOptOutPass({return { submitted: [], skipped: 0, verification: null, subjectId: resolvedSubjectId, reason: 'no_disclosure_identity' };}- const [brokers, cases] = await Promise.all([listBrokers({ enabled: true }), listBrokerCases({ subjectId: resolvedSubjectId })]);+ const [brokers, cases] = await Promise.all([listBrokers({ enabled: true }), listBrokerCases({ subjectId: resolvedSubjectId, includeIdentity: true })]);const brokerById = new Map(brokers.map((b) => [b.id, b]));const casesWithBroker = cases.map((c) => ({ case: c, broker: brokerById.get(c.brokerId) }))@@ -523,7 +523,8 @@ export async function runOptOutPass({const submitted = [];let skipped = 0;for (const { case: kase, broker } of submit) {- const listingUrls = Array.isArray(kase.evidence?.listing_urls) ? kase.evidence.listing_urls : [];+ // Listing URLs live in the case's sealed identity evidence (#8333).+ const listingUrls = Array.isArray(kase.identity?.listing_urls) ? kase.identity.listing_urls : [];const disclosedFields = computeDisclosedFields(broker, payload, { listingUrls });const lane = chooseLane(broker);if (lane === 'human') {@@ -561,8 +562,8 @@ export async function runOptOutPass({export async function getOptOutDigest({ subjectId } = {}) {const resolvedSubjectId = resolveSubjectId(subjectId);const [human, blocked] = await Promise.all([- listBrokerCases({ state: 'human_task_queued', subjectId: resolvedSubjectId }),- listBrokerCases({ state: 'blocked', subjectId: resolvedSubjectId }),+ listBrokerCases({ state: 'human_task_queued', subjectId: resolvedSubjectId, includeIdentity: true }),+ listBrokerCases({ state: 'blocked', subjectId: resolvedSubjectId, includeIdentity: true }),]);const toItem = (c) => ({caseId: c.id,@@ -578,7 +579,8 @@ export async function getOptOutDigest({ subjectId } = {}) {optoutUrl: c.evidence?.optout_url || null,// Filled broker-search URL for blocked cases — lets the digest offer// "check manually in your browser" (the sanctioned path past a bot wall).- searchUrl: c.evidence?.search_url || null,+ // Decrypted from the sealed identity evidence (#8333); null once erased.+ searchUrl: c.identity?.search_url || null,playbook: c.evidence?.playbook || [],nextRecheckAt: c.nextRecheckAt,});diff --git a/server/services/privacyOptOut.test.js b/server/services/privacyOptOut.test.jsindex 2a314585ff..859a9373f1 100644--- a/server/services/privacyOptOut.test.js+++ b/server/services/privacyOptOut.test.js@@ -336,7 +336,7 @@ describe('getOptOutDigest', () => {it('aggregates human-task + blocked cases with playbook + reason', async () => {listBrokerCases.mockImplementation(async ({ state } = {}) => {if (state === 'human_task_queued') return [{ id: 'h1', brokerId: 'wp', brokerName: 'Whitepages', state, allowedTransitions: ['submitted', 'not_found', 'human_task_queued'], reason: 'auto_submit_disabled', evidence: { optout_url: 'https://wp/o', playbook: ['call back'] } }];- if (state === 'blocked') return [{ id: 'b1', brokerId: 'rad', brokerName: 'Radaris', state, allowedTransitions: ['found', 'not_found', 'human_task_queued'], reason: 'antibot_wall', evidence: { search_url: 'https://rad/p/Jane/Doe/' } }];+ if (state === 'blocked') return [{ id: 'b1', brokerId: 'rad', brokerName: 'Radaris', state, allowedTransitions: ['found', 'not_found', 'human_task_queued'], reason: 'antibot_wall', evidence: { match_basis: 'antibot_wall' }, identity: { search_url: 'https://rad/p/Jane/Doe/' } }];return [];});const digest = await getOptOutDigest();@@ -348,8 +348,12 @@ describe('getOptOutDigest', () => {// same as the drawer (issue #2417).expect(digest.items[0].allowedTransitions).toEqual(['submitted', 'not_found', 'human_task_queued']);expect(digest.items[1].allowedTransitions).toEqual(['found', 'not_found', 'human_task_queued']);- // Blocked items surface the filled search URL for a manual browser check.+ // Blocked items surface the filled search URL for a manual browser check —+ // decrypted from the case's sealed identity evidence, never read from the+ // plain evidence projection (#8333).expect(digest.items[1].searchUrl).toBe('https://rad/p/Jane/Doe/');+ expect(digest.items[0].searchUrl).toBe(null);+ expect(listBrokerCases).toHaveBeenCalledWith(expect.objectContaining({ state: 'blocked', includeIdentity: true }));});});diff --git a/server/services/privacyVault.js b/server/services/privacyVault.jsindex 8614006075..06a1f4f18a 100644--- a/server/services/privacyVault.js+++ b/server/services/privacyVault.js@@ -176,11 +176,30 @@ export async function updateVaultRecord(id, patch) {});}+// Vault types whose values a scan copies into broker-case evidence (the+// matched name, the matched city/state, and the search/listing URLs built from+// both) — deleting one of these must not leave that copy behind (#8333).+const EVIDENCE_SOURCE_TYPES = new Set(['legal_name', 'address']);+export async function deleteVaultRecord(id) {- const { rows } = await query(`DELETE FROM privacy_vault_records WHERE id = $1 RETURNING id, type`, [id]);- if (!rows[0]) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });- console.log(`🗑️ Deleted vault record ${id} (type=${rows[0].type})`);- return { ok: true };+ // Lazy: privacyBrokers is only needed on this path, and most suites that+ // reach the vault never delete a record.+ const { clearSubjectIdentityEvidence } = await import('./privacyBrokers.js');+ return withTransaction(async (client) => {+ const { rows } = await client.query(+ `DELETE FROM privacy_vault_records WHERE id = $1 RETURNING id, type, subject_id`, [id],+ );+ const deleted = rows[0];+ if (!deleted) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });+ // Same transaction: the vault row and every case-evidence copy derived from+ // it go together, or neither does. Not gated on the CURRENT use_for_scans:+ // a record toggled out of scans after a scan used it still left a copy.+ if (EVIDENCE_SOURCE_TYPES.has(deleted.type)) {+ await clearSubjectIdentityEvidence(deleted.subject_id, { client });+ }+ console.log(`🗑️ Deleted vault record ${id} (type=${deleted.type})`);+ return { ok: true };+ });}/** The ONE decrypt path — explicit reveal. Returns plaintext; logs id/type only. */