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-2144]): data-broker database, exposure scan engine, case ledger

Adam Eivy53689172c337
diff --git a/data.reference/privacy/brokers.json b/data.reference/privacy/brokers.json
new file mode 100644
index 0000000000..8b3a4b4158
--- /dev/null
+++ b/data.reference/privacy/brokers.json
@@ -0,0 +1,306 @@
+{
+ "_comment": "Curated people-search broker seed for the Privacy Center opt-out engine (issue #2144, epic #2138). Shipped in data.reference/ (data/ is gitignored); loaded/upserted into Postgres privacy_brokers on first use — NO network at boot. Curated rows carry source=curated, confidence=field_verified|documented and are NEVER overwritten by the auto refresh (BADBOOL / CA registry). `urls.search` is a template with {firstName} {lastName} {state} {city} tokens; the scan engine fills them from vault scan vectors and never discloses anything outside disclosure_fields ∩ the fixed allowlist {full_name,email,phone,city,state,dob,listing_url}. cluster_parent groups sibling brands under one suppression (PeopleConnect covers Intelius/TruthFinder/InstantCheckmate/US Search); prefer_suppression on the parent because a per-brand deletion wipes the cluster suppression.",
+ "schemaVersion": 1,
+ "brokers": [
+ {
+ "id": "spokeo",
+ "name": "Spokeo",
+ "urls": { "home": "https://www.spokeo.com", "search": "https://www.spokeo.com/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.spokeo.com/optout", "email": null, "playbook": ["Search for your listing and copy its profile URL", "Paste the profile URL into the opt-out form", "Enter your email and submit", "Click the confirmation link in the email Spokeo sends"], "notes": "Confirmation email required to complete." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "whitepages",
+ "name": "Whitepages",
+ "urls": { "home": "https://www.whitepages.com", "search": "https://www.whitepages.com/name/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.whitepages.com/suppression-requests", "email": null, "playbook": ["Find your listing and copy the profile URL", "Submit the suppression request with the profile URL", "Complete the phone-verification callback if prompted"], "notes": "May require a phone callback to verify — that step is a human task." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "phone", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": true,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "beenverified",
+ "name": "BeenVerified",
+ "urls": { "home": "https://www.beenverified.com", "search": "https://www.beenverified.com/people/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.beenverified.com/app/optout/search", "email": null, "playbook": ["Search for your record on the opt-out page", "Select your listing", "Enter your email and submit", "Confirm via the emailed link"], "notes": "Confirmation email required." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "radaris",
+ "name": "Radaris",
+ "urls": { "home": "https://radaris.com", "search": "https://radaris.com/p/{firstName}/{lastName}/" },
+ "optout": { "method": "web_form", "url": "https://radaris.com/control/privacy", "email": "[email protected]", "playbook": ["Locate your profile and open it", "Use the profile control panel to request removal", "Verify ownership via the emailed/SMS code"], "notes": "Ownership verification step; falls back to email request." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": true,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "mylife",
+ "name": "MyLife",
+ "urls": { "home": "https://www.mylife.com", "search": "https://www.mylife.com/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "email", "url": "https://www.mylife.com/ccpa/index.pubview", "email": "[email protected]", "playbook": ["Send a removal request naming the exact profile URL", "Include the identifiers MyLife needs to match the listing", "Follow up if no confirmation within 10 business days"], "notes": "Email lane (CCPA); web form is unreliable." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "peoplefinders",
+ "name": "PeopleFinders",
+ "urls": { "home": "https://www.peoplefinders.com", "search": "https://www.peoplefinders.com/people/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.peoplefinders.com/opt-out", "email": null, "playbook": ["Search for your record on the opt-out page", "Select the matching listing", "Submit with your email", "Confirm via the emailed link"], "notes": "Confirmation email required." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "truepeoplesearch",
+ "name": "TruePeopleSearch",
+ "urls": { "home": "https://www.truepeoplesearch.com", "search": "https://www.truepeoplesearch.com/results?name={firstName}%20{lastName}&citystatezip={state}" },
+ "optout": { "method": "web_form", "url": "https://www.truepeoplesearch.com/removal", "email": null, "playbook": ["Find your record and copy the record URL", "Paste the record URL into the removal form", "Complete the human-verification step"], "notes": "CAPTCHA / human verification — never bypassed; routes to a human task if it walls." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": true,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "fastpeoplesearch",
+ "name": "FastPeopleSearch",
+ "urls": { "home": "https://www.fastpeoplesearch.com", "search": "https://www.fastpeoplesearch.com/name/{firstName}-{lastName}_{state}" },
+ "optout": { "method": "web_form", "url": "https://www.fastpeoplesearch.com/removal", "email": null, "playbook": ["Copy your record URL", "Submit it on the removal page", "Complete the verification step"], "notes": "Human verification step; routes to a human task if it walls." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": true,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "usphonebook",
+ "name": "USPhoneBook",
+ "urls": { "home": "https://www.usphonebook.com", "search": "https://www.usphonebook.com/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.usphonebook.com/opt-out", "email": null, "playbook": ["Search for and copy your listing URL", "Enter it on the opt-out page with your email", "Confirm via the emailed link"], "notes": "Confirmation email required." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "phone", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "searchpeoplefree",
+ "name": "SearchPeopleFree",
+ "urls": { "home": "https://www.searchpeoplefree.com", "search": "https://www.searchpeoplefree.com/find/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://www.searchpeoplefree.com/opt-out", "email": null, "playbook": ["Copy your record URL", "Submit it with your email on the opt-out page", "Confirm via the emailed link"], "notes": "Confirmation email required." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "nuwber",
+ "name": "Nuwber",
+ "urls": { "home": "https://nuwber.com", "search": "https://nuwber.com/search?name={firstName}+{lastName}&state={state}" },
+ "optout": { "method": "web_form", "url": "https://nuwber.com/removal/link", "email": "[email protected]", "playbook": ["Find your profile and copy the URL", "Request the removal link on the removal page", "Follow the emailed removal link"], "notes": "Email-driven removal link." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "clustrmaps",
+ "name": "ClustrMaps",
+ "urls": { "home": "https://clustrmaps.com", "search": "https://clustrmaps.com/persons/{firstName}-{lastName}" },
+ "optout": { "method": "web_form", "url": "https://clustrmaps.com/bl/opt-out", "email": null, "playbook": ["Copy your record URL", "Submit it on the opt-out page with your email", "Confirm via the emailed link"], "notes": "Confirmation email required." },
+ "tier": 1,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "peekyou",
+ "name": "PeekYou",
+ "urls": { "home": "https://www.peekyou.com", "search": "https://www.peekyou.com/{firstName}_{lastName}" },
+ "optout": { "method": "web_form", "url": "https://www.peekyou.com/about/contact/optout/", "email": null, "playbook": ["Find your PeekYou unique ID from the profile URL", "Enter the ID and your email on the opt-out form", "Confirm via the emailed link"], "notes": "Needs the profile's unique ID." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "advanced-background-checks",
+ "name": "Advanced Background Checks",
+ "urls": { "home": "https://www.advancedbackgroundchecks.com", "search": "https://www.advancedbackgroundchecks.com/name/{firstName}-{lastName}_{state}" },
+ "optout": { "method": "web_form", "url": "https://www.advancedbackgroundchecks.com/removal", "email": null, "playbook": ["Copy your record URL", "Submit it on the removal page", "Complete the verification step"], "notes": "Human verification step." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": true,
+ "source": "curated",
+ "confidence": "documented",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "peoplelookup",
+ "name": "PeopleLookup",
+ "urls": { "home": "https://www.peoplelookup.com", "search": "https://www.peoplelookup.com/name/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "email", "url": "https://www.peoplelookup.com/optout", "email": "[email protected]", "playbook": ["Send a removal request naming the profile URL", "Include the identifiers needed to match the listing", "Follow up if no confirmation within 10 business days"], "notes": "Email (CCPA/CPRA) lane." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "email", "listing_url"],
+ "cluster_parent": null,
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "auto",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "peopleconnect",
+ "name": "PeopleConnect",
+ "urls": { "home": "https://www.peopleconnect.us", "search": null },
+ "optout": { "method": "web_form", "url": "https://suppression.peopleconnect.us/login", "email": "[email protected]", "playbook": ["Create a suppression account", "Verify your identity with the least-disclosure fields", "Add each identifier to suppress across all PeopleConnect brands"], "notes": "SUPPRESSION covers all child brands (Intelius, TruthFinder, InstantCheckmate, US Search). prefer_suppression: a per-brand deletion wipes the umbrella suppression, so always suppress at the parent." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "email"],
+ "cluster_parent": null,
+ "prefer_suppression": true,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "intelius",
+ "name": "Intelius",
+ "urls": { "home": "https://www.intelius.com", "search": "https://www.intelius.com/people-search/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://suppression.peopleconnect.us/login", "email": "[email protected]", "playbook": ["Suppress via the PeopleConnect parent portal — do NOT request a per-brand deletion"], "notes": "PeopleConnect brand; handled by the parent suppression." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": "peopleconnect",
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "truthfinder",
+ "name": "TruthFinder",
+ "urls": { "home": "https://www.truthfinder.com", "search": "https://www.truthfinder.com/people-search/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://suppression.peopleconnect.us/login", "email": "[email protected]", "playbook": ["Suppress via the PeopleConnect parent portal — do NOT request a per-brand deletion"], "notes": "PeopleConnect brand; handled by the parent suppression." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": "peopleconnect",
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "instantcheckmate",
+ "name": "Instant Checkmate",
+ "urls": { "home": "https://www.instantcheckmate.com", "search": "https://www.instantcheckmate.com/people/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://suppression.peopleconnect.us/login", "email": "[email protected]", "playbook": ["Suppress via the PeopleConnect parent portal — do NOT request a per-brand deletion"], "notes": "PeopleConnect brand; handled by the parent suppression." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": "peopleconnect",
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ },
+ {
+ "id": "ussearch",
+ "name": "US Search",
+ "urls": { "home": "https://www.ussearch.com", "search": "https://www.ussearch.com/people/{firstName}-{lastName}/{state}" },
+ "optout": { "method": "web_form", "url": "https://suppression.peopleconnect.us/login", "email": "[email protected]", "playbook": ["Suppress via the PeopleConnect parent portal — do NOT request a per-brand deletion"], "notes": "PeopleConnect brand; handled by the parent suppression." },
+ "tier": 2,
+ "disclosure_fields": ["full_name", "city", "state", "listing_url"],
+ "cluster_parent": "peopleconnect",
+ "prefer_suppression": false,
+ "antibot": false,
+ "source": "curated",
+ "confidence": "field_verified",
+ "last_verified": "2026-07-04",
+ "enabled": true
+ }
+ ]
+}
diff --git a/scripts/migrations/176-privacy-broker-tables.js b/scripts/migrations/176-privacy-broker-tables.js
new file mode 100644
index 0000000000..563bcc9dd3
--- /dev/null
+++ b/scripts/migrations/176-privacy-broker-tables.js
@@ -0,0 +1,29 @@
+/**
+ * Registration stub for the Privacy Center data-broker database + case ledger
+ * (issue #2144, epic #2138).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS privacy_brokers` and
+ * `privacy_broker_cases` (+ their indexes) — 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, and 160/161/162 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 broker tables were introduced. Both tables are additive (brand-
+ * new, machine-local db-primary stores) with no data backfill — the
+ * privacyBrokers service SEEDS `privacy_brokers` LAZILY from
+ * data.reference/privacy/brokers.json on first read (never at boot, no network),
+ * and the scan engine populates `privacy_broker_cases` on the first user-
+ * triggered scan pass.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('🗂️ privacy_brokers/privacy_broker_cases: tables created idempotently by ensureSchema at boot; curated seed loads lazily on first read — nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index 979da22d84..e9225f5fc2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -42,7 +42,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). |
| `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. |
-| `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. |
+| `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. Data-broker database + case ledger (issue #2144): broker list/case-list query filters, the scan-start + refresh action bodies, and the `PRIVACY_BROKER_CASE_STATES` vocabulary. |
| `socketValidation.js` | Socket event payload schemas. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 907d479cc7..4bf11783c9 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -1356,6 +1356,62 @@ async function ensureSchemaImpl() {
// Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
`CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id)`,
+ // ─── Privacy Center: data-broker database + case ledger (issue #2144,
+ // epic #2138) ──────────────────────────────────────────────────────────
+ // `privacy_brokers` is the curated (+ later BADBOOL / CA-registry) database
+ // of people-search brokers the exposure-scan/opt-out engine works. Seeded
+ // idempotently from data.reference/privacy/brokers.json on first use (NO
+ // network at boot). `source`/`confidence` gate the refresh: curated rows
+ // (field_verified/documented) are never clobbered by an auto refresh.
+ // `cluster_parent` groups sibling brands under one suppression;
+ // `disclosure_fields` caps what the engine may ever submit to that broker.
+ // Machine-local — no federation, no tombstones (same deferred scope as the
+ // vault, #2148). Mirrors the privacy blocks in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_brokers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ urls JSONB NOT NULL DEFAULT '{}'::jsonb,
+ optout JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tier SMALLINT NOT NULL DEFAULT 2,
+ disclosure_fields TEXT[] NOT NULL DEFAULT '{}',
+ cluster_parent TEXT REFERENCES privacy_brokers (id) ON DELETE SET NULL,
+ prefer_suppression BOOLEAN NOT NULL DEFAULT FALSE,
+ antibot BOOLEAN NOT NULL DEFAULT FALSE,
+ source TEXT NOT NULL DEFAULT 'curated',
+ confidence TEXT NOT NULL DEFAULT 'documented',
+ last_verified DATE,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // Planner walks enabled brokers, cluster-parents first.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_brokers_enabled ON privacy_brokers (enabled)`,
+ `CREATE 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 (the
+ // engine records only least-disclosure identifiers). A broker delete
+ // cascades its cases.
+ `CREATE TABLE IF NOT EXISTS privacy_broker_cases (
+ id UUID PRIMARY KEY,
+ broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'unscanned',
+ found BOOLEAN,
+ evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
+ disclosed_fields TEXT[] NOT NULL DEFAULT '{}',
+ channel TEXT,
+ reason TEXT,
+ next_recheck_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // One live case per broker in v1 (self-only subject) — unique so the
+ // scan-pass upsert can ON CONFLICT the broker id.
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker ON privacy_broker_cases (broker_id)`,
+ // "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)`,
+
// ─── 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/privacyValidation.js b/server/lib/privacyValidation.js
index 17da9720dd..a3dc972b97 100644
--- a/server/lib/privacyValidation.js
+++ b/server/lib/privacyValidation.js
@@ -145,3 +145,41 @@ export const privacyOrgHoldingsSetSchema = z.object({
status: z.enum(PRIVACY_ORG_HOLDING_STATUSES).optional(),
}).strict()).max(500),
}).strict();
+
+// =============================================================================
+// DATA-BROKER DATABASE + CASE LEDGER SCHEMAS (issue #2144, epic #2138)
+// =============================================================================
+// Zod schemas for `privacy_brokers` / `privacy_broker_cases` — db-primary
+// Postgres, machine-local (same federation-deferred scope as the vault, #2148).
+// The broker rows themselves are curated seed / auto-refresh, not user-created,
+// so there is no broker create/update input schema — only read filters and the
+// scan/refresh action bodies.
+
+export const PRIVACY_BROKER_CASE_STATES = Object.freeze([
+ 'unscanned',
+ 'found', 'not_found', 'indirect_exposure', 'blocked',
+ 'optout_in_progress', 'submitted', 'verification_pending', 'awaiting_processing',
+ 'confirmed_removed', 'human_task_queued', 'reappeared',
+]);
+
+// GET /api/privacy/brokers?enabled=true — z.coerce so the string query "true"/
+// "false" becomes a boolean (matches the storage of the enabled column).
+export const privacyBrokerListQuerySchema = z.object({
+ enabled: z.preprocess(
+ (v) => (v === undefined ? undefined : v === 'true' || v === true),
+ z.boolean().optional(),
+ ),
+}).strict();
+
+// GET /api/privacy/broker-cases?state=found
+export const privacyBrokerCaseListQuerySchema = z.object({
+ state: z.enum(PRIVACY_BROKER_CASE_STATES).optional(),
+}).strict();
+
+// POST /api/privacy/brokers/refresh — no body; empty object.
+export const privacyBrokerRefreshSchema = z.object({}).strict();
+
+// POST /api/privacy/scan — optional concurrency knob.
+export const privacyScanStartSchema = z.object({
+ concurrency: z.number().int().min(1).max(6).optional(),
+}).strict();
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index a27c7af8b2..857a6a49b6 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -21,6 +21,10 @@ import {
privacyOrgListQuerySchema,
privacyOrgIdParamsSchema,
privacyOrgHoldingsSetSchema,
+ privacyBrokerListQuerySchema,
+ privacyBrokerCaseListQuerySchema,
+ privacyBrokerRefreshSchema,
+ privacyScanStartSchema,
} from '../lib/privacyValidation.js';
import {
createVaultRecord,
@@ -40,6 +44,13 @@ import {
setOrgHoldings,
getHoldingsForOrg,
} from '../services/privacyOrgs.js';
+import {
+ listBrokers,
+ refreshBrokers,
+ listBrokerCases,
+ getScanStatus,
+} from '../services/privacyBrokers.js';
+import { runScanPass } from '../services/privacyScan.js';
const router = Router();
@@ -123,4 +134,33 @@ router.put('/orgs/:id/holdings', asyncHandler(async (req, res) => {
res.json(await setOrgHoldings(id, holdings));
}));
+// ─── Data-broker database + exposure scan + case ledger (issue #2144) ───────
+
+router.get('/brokers', asyncHandler(async (req, res) => {
+ const { enabled } = validateRequest(privacyBrokerListQuerySchema, req.query);
+ res.json(await listBrokers({ enabled }));
+}));
+
+// User-triggered refresh (never at boot) — pulls BADBOOL + CA registry, never
+// clobbers curated rows.
+router.post('/brokers/refresh', asyncHandler(async (req, res) => {
+ validateRequest(privacyBrokerRefreshSchema, req.body ?? {});
+ res.json(await refreshBrokers());
+}));
+
+router.get('/broker-cases', asyncHandler(async (req, res) => {
+ const { state } = validateRequest(privacyBrokerCaseListQuerySchema, req.query);
+ res.json(await listBrokerCases({ state }));
+}));
+
+router.get('/scan/status', asyncHandler(async (_req, res) => {
+ res.json(await getScanStatus());
+}));
+
+// User-triggered read-only exposure scan pass over enabled brokers.
+router.post('/scan', asyncHandler(async (req, res) => {
+ const { concurrency } = validateRequest(privacyScanStartSchema, req.body ?? {});
+ res.json(await runScanPass(concurrency ? { concurrency } : {}));
+}));
+
export default router;
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index e43b3e4e81..4fd0153c38 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -30,9 +30,22 @@ vi.mock('../services/privacyOrgs.js', () => ({
getHoldingsForOrg: vi.fn(async () => [{ orgId: 'o1', vaultRecordId: 'v1', vaultMaskedValue: 'a•••@b.com' }]),
}));
+vi.mock('../services/privacyBrokers.js', () => ({
+ listBrokers: vi.fn(async () => [{ id: 'spokeo', name: 'Spokeo', enabled: true }]),
+ refreshBrokers: vi.fn(async () => ({ fetched: 3, added: 2, sources: { badbool: 2, caRegistry: 1 } })),
+ listBrokerCases: vi.fn(async () => [{ id: 'case-1', brokerId: 'spokeo', state: 'found' }]),
+ getScanStatus: vi.fn(async () => ({ enabledBrokers: 20, caseCounts: { found: 1 }, dueForRecheck: 3 })),
+}));
+
+vi.mock('../services/privacyScan.js', () => ({
+ runScanPass: vi.fn(async (opts) => ({ scanned: 2, verdicts: { found: 1, not_found: 1 }, skipped: 0, brokers: 20, _opts: opts })),
+}));
+
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 VALID_UUID = 'c0ffee00-0000-4000-8000-000000000001';
@@ -214,3 +227,64 @@ describe('PUT /api/privacy/orgs/:id/holdings', () => {
.send({ holdings: [{ vaultRecordId: VALID_UUID, status: 'nope' }] })).status).toBe(400);
});
});
+
+// ─── Data-broker database + scan + case ledger (issue #2144) ────────────────
+
+describe('GET /api/privacy/brokers', () => {
+ it('lists brokers and coerces the enabled query flag to a boolean', async () => {
+ const res = await request(makeApp()).get('/api/privacy/brokers?enabled=true');
+ expect(res.status).toBe(200);
+ expect(brokerService.listBrokers).toHaveBeenCalledWith({ enabled: true });
+ expect(res.body[0].id).toBe('spokeo');
+ });
+
+ it('lists all brokers when no filter is given', async () => {
+ const res = await request(makeApp()).get('/api/privacy/brokers');
+ expect(res.status).toBe(200);
+ expect(brokerService.listBrokers).toHaveBeenCalledWith({ enabled: undefined });
+ });
+});
+
+describe('POST /api/privacy/brokers/refresh', () => {
+ it('runs the user-triggered refresh', async () => {
+ const res = await request(makeApp()).post('/api/privacy/brokers/refresh').send({});
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ added: 2 });
+ expect(brokerService.refreshBrokers).toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/privacy/broker-cases', () => {
+ it('lists cases and filters by state', async () => {
+ const res = await request(makeApp()).get('/api/privacy/broker-cases?state=found');
+ expect(res.status).toBe(200);
+ expect(brokerService.listBrokerCases).toHaveBeenCalledWith({ state: 'found' });
+ });
+
+ it('rejects an unknown case state', async () => {
+ expect((await request(makeApp()).get('/api/privacy/broker-cases?state=bogus')).status).toBe(400);
+ });
+});
+
+describe('GET /api/privacy/scan/status', () => {
+ it('returns the scan status readout', async () => {
+ const res = await request(makeApp()).get('/api/privacy/scan/status');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ enabledBrokers: 20, dueForRecheck: 3 });
+ });
+});
+
+describe('POST /api/privacy/scan', () => {
+ it('starts a scan pass and returns the summary', async () => {
+ const res = await request(makeApp()).post('/api/privacy/scan').send({});
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ scanned: 2, verdicts: { found: 1, not_found: 1 } });
+ expect(scanService.runScanPass).toHaveBeenCalled();
+ });
+
+ it('passes a valid concurrency knob through and rejects an out-of-range one', async () => {
+ await request(makeApp()).post('/api/privacy/scan').send({ concurrency: 4 });
+ expect(scanService.runScanPass).toHaveBeenCalledWith({ concurrency: 4 });
+ expect((await request(makeApp()).post('/api/privacy/scan').send({ concurrency: 99 })).status).toBe(400);
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 2150bb29b2..ff91659fc2 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1135,6 +1135,58 @@ CREATE TABLE IF NOT EXISTS privacy_org_holdings (
-- Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id);
+-- Privacy Center: data-broker database + case ledger (issue #2144, epic #2138).
+-- `privacy_brokers` is the curated (+ later BADBOOL / CA-registry) database of
+-- people-search brokers the exposure-scan/opt-out engine works. Seeded
+-- idempotently from data.reference/privacy/brokers.json on first use (NO network
+-- at boot). `source`/`confidence` gate the refresh: curated rows are never
+-- clobbered by an auto refresh. `cluster_parent` groups sibling brands under one
+-- suppression; `disclosure_fields` caps what the engine may submit. Machine-local
+-- — no federation, no tombstones (#2148). Mirrors the privacy blocks in
+-- server/lib/db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS privacy_brokers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ urls JSONB NOT NULL DEFAULT '{}'::jsonb,
+ optout JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tier SMALLINT NOT NULL DEFAULT 2,
+ disclosure_fields TEXT[] NOT NULL DEFAULT '{}',
+ cluster_parent TEXT REFERENCES privacy_brokers (id) ON DELETE SET NULL,
+ prefer_suppression BOOLEAN NOT NULL DEFAULT FALSE,
+ antibot BOOLEAN NOT NULL DEFAULT FALSE,
+ source TEXT NOT NULL DEFAULT 'curated',
+ confidence TEXT NOT NULL DEFAULT 'documented',
+ last_verified DATE,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+-- Planner walks enabled brokers, cluster-parents first.
+CREATE INDEX IF NOT EXISTS idx_privacy_brokers_enabled ON privacy_brokers (enabled);
+CREATE 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.
+CREATE TABLE IF NOT EXISTS privacy_broker_cases (
+ id UUID PRIMARY KEY,
+ broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
+ state TEXT NOT NULL DEFAULT 'unscanned',
+ found BOOLEAN,
+ evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
+ disclosed_fields TEXT[] NOT NULL DEFAULT '{}',
+ channel TEXT,
+ reason TEXT,
+ next_recheck_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+-- One live case per broker in v1 (self-only subject).
+CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker ON privacy_broker_cases (broker_id);
+-- "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);
+
-- 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/privacyBrokers.db.test.js b/server/services/privacyBrokers.db.test.js
new file mode 100644
index 0000000000..4513ad0211
--- /dev/null
+++ b/server/services/privacyBrokers.db.test.js
@@ -0,0 +1,161 @@
+/**
+ * Postgres-backed round-trip for the data-broker database + case ledger
+ * (issue #2144). Skips cleanly when no DB is reachable (CI, fresh checkout);
+ * runs the seed/refresh/ledger surface when one is. Cleans up only the auto
+ * (non-curated) brokers + cases it creates — the curated seed is idempotent and
+ * left in place. Runs via `npm run test:db` (→ portos_test) ONLY; db.js guards
+ * refuse writes to a non-test DB.
+ */
+
+import { describe, it, expect, afterAll, beforeAll } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+
+// A valid vault key BEFORE privacyVault is imported so the runScanPass test can
+// create a scan-eligible name without touching the repo's real .env.
+const originalKey = process.env.PRIVACY_VAULT_KEY;
+process.env.PRIVACY_VAULT_KEY = 'd'.repeat(64);
+
+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_brokers') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'privacy_brokers table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ privacyBrokers.db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('privacy brokers DB round-trip', () => {
+ let svc;
+ let scan;
+ let vault;
+ const autoBrokerIds = ['test-auto-alpha', 'ca-test-beta-inc'];
+ const createdVaultIds = [];
+ const vaultTableWasEmpty = false;
+ const testStart = new Date().toISOString();
+
+ beforeAll(async () => {
+ svc = await import('./privacyBrokers.js');
+ scan = await import('./privacyScan.js');
+ vault = await import('./privacyVault.js');
+ });
+
+ afterAll(async () => {
+ for (const id of createdVaultIds) {
+ await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});
+ }
+ await query(`DELETE FROM privacy_consents WHERE scope = 'pii_vault' AND granted_at >= $1`, [testStart]).catch(() => {});
+ for (const id of autoBrokerIds) {
+ await query(`DELETE FROM privacy_broker_cases WHERE broker_id = $1`, [id]).catch(() => {});
+ await query(`DELETE FROM privacy_brokers WHERE id = $1`, [id]).catch(() => {});
+ }
+ // Drop the curated brokers' cases this suite created so a re-run starts clean.
+ await query(`DELETE FROM privacy_broker_cases`).catch(() => {});
+ await close();
+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;
+ else process.env.PRIVACY_VAULT_KEY = originalKey;
+ });
+
+ it('seeds the curated brokers idempotently with the cluster wired up', async () => {
+ const first = await svc.seedCuratedBrokers();
+ const { rows: c1 } = await query(`SELECT COUNT(*)::int AS n FROM privacy_brokers WHERE source = 'curated'`);
+ await svc.seedCuratedBrokers(); // second run must not duplicate
+ const { rows: c2 } = await query(`SELECT COUNT(*)::int AS n FROM privacy_brokers WHERE source = 'curated'`);
+ expect(first.seeded).toBeGreaterThan(0);
+ expect(c2[0].n).toBe(c1[0].n);
+
+ const parent = await svc.getBroker('peopleconnect');
+ expect(parent.preferSuppression).toBe(true);
+ const child = await svc.getBroker('truthfinder');
+ expect(child.clusterParent).toBe('peopleconnect');
+ });
+
+ it('refresh adds auto brokers and NEVER clobbers a curated row', async () => {
+ const before = await svc.getBroker('spokeo');
+ expect(before.source).toBe('curated');
+
+ const res = await svc.refreshBrokers({
+ // A collision on the curated `spokeo` id (must be ignored) + one genuinely
+ // new auto broker.
+ fetchBadbool: async () => [
+ { id: 'spokeo', name: 'HIJACKED', source: 'badbool', confidence: 'auto' },
+ { id: 'test-auto-alpha', name: 'Test Auto Alpha', url: 'https://alpha.example' },
+ ],
+ fetchCaRegistry: async () => [
+ { id: 'ca-test-beta-inc', name: 'Beta Inc', urls: { home: 'https://beta.example' }, source: 'ca_registry', confidence: 'auto' },
+ ],
+ });
+ expect(res.added).toBe(2);
+
+ const afterSpokeo = await svc.getBroker('spokeo');
+ expect(afterSpokeo.name).toBe(before.name); // curated name preserved
+ expect(afterSpokeo.source).toBe('curated');
+
+ const auto = await svc.getBroker('test-auto-alpha');
+ expect(auto).toMatchObject({ name: 'Test Auto Alpha', source: 'badbool', confidence: 'auto' });
+ });
+
+ it('records a scan verdict, stamps next_recheck_at, and enforces the state machine', async () => {
+ const now = new Date('2026-07-08T00:00:00.000Z');
+ // Fresh verdict on a curated broker.
+ const kase = await svc.recordScanVerdict('test-auto-alpha', 'found', {
+ evidence: { match_basis: 'name+location', listing_urls: ['https://alpha.example/jane'] },
+ found: true, now,
+ });
+ expect(kase.state).toBe('found');
+ // found → +1 day recheck.
+ expect(new Date(kase.nextRecheckAt).toISOString()).toBe('2026-07-09T00:00:00.000Z');
+
+ // Lifecycle forward via transitionCase.
+ const submitted = await svc.transitionCase(kase.id, 'optout_in_progress');
+ expect(submitted.state).toBe('optout_in_progress');
+ const s2 = await svc.transitionCase(kase.id, 'submitted', { channel: 'web_form', now });
+ expect(s2.state).toBe('submitted');
+ expect(new Date(s2.nextRecheckAt).toISOString()).toBe('2026-07-11T00:00:00.000Z'); // +3d
+
+ // confirmed_removed is refused from a submission path (no rescan).
+ await expect(svc.transitionCase(kase.id, 'confirmed_removed'))
+ .rejects.toMatchObject({ code: 'CONFIRMED_REQUIRES_RESCAN' });
+
+ // Reach awaiting_processing, then confirm via a verifying rescan.
+ await svc.transitionCase(kase.id, 'verification_pending');
+ await svc.transitionCase(kase.id, 'awaiting_processing');
+ const removed = await svc.transitionCase(kase.id, 'confirmed_removed', { viaRescan: true, now });
+ expect(removed.state).toBe('confirmed_removed');
+ expect(new Date(removed.nextRecheckAt).toISOString()).toBe('2026-08-07T00:00:00.000Z'); // +30d
+ });
+
+ it('runScanPass scans due brokers, records verdicts, and skips opt-out-owned cases', async () => {
+ // A scan-eligible name so buildSearchVectors is non-empty.
+ const nameRec = await vault.createVaultRecord({ type: 'legal_name', label: 'Legal name', value: 'Jane Q Publictest' });
+ createdVaultIds.push(nameRec.id);
+ const addrRec = await vault.createVaultRecord({ type: 'address', label: 'Home', value: '1 Oak Ave, Portland, OR 97201' });
+ createdVaultIds.push(addrRec.id);
+
+ // Every broker's static page returns a no-match body → not_found verdicts.
+ const fetchImpl = async () => ({ status: 200, text: async () => 'No results found for that search. '.repeat(40) });
+ const summary = await scan.runScanPass({ fetchImpl, browserFetch: async () => null, urlSafe: async () => true });
+ expect(summary.scanned).toBeGreaterThan(0);
+ expect(summary.verdicts.not_found).toBeGreaterThan(0);
+
+ // The confirmed_removed case (opt-out-owned) from the previous test must be
+ // untouched — the pass never overwrites it with a raw scan verdict.
+ const owned = await svc.getCaseForBroker('test-auto-alpha');
+ expect(owned.state).toBe('confirmed_removed');
+ });
+
+ it('reports scan status counts', async () => {
+ const status = await svc.getScanStatus();
+ expect(status.enabledBrokers).toBeGreaterThan(0);
+ expect(typeof status.caseCounts).toBe('object');
+ expect(typeof status.dueForRecheck).toBe('number');
+ });
+});
diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.js
new file mode 100644
index 0000000000..25ae1ba6a6
--- /dev/null
+++ b/server/services/privacyBrokers.js
@@ -0,0 +1,512 @@
+/**
+ * Data-broker database + case ledger (issue #2144, epic #2138).
+ *
+ * db-primary Postgres per docs/STORAGE.md: `privacy_brokers` is the curated
+ * (+ later BADBOOL / CA-registry) database of people-search brokers the
+ * exposure-scan / opt-out engine works; `privacy_broker_cases` is the per-broker
+ * ledger with a SERVICE-ENFORCED state machine. Machine-local — no federation,
+ * no tombstones (same deferred scope as the vault, #2148).
+ *
+ * Boot policy (CLAUDE.md — no cold-bootstrap network/LLM): NOTHING here runs at
+ * server boot. The curated seed is loaded LAZILY from
+ * data.reference/privacy/brokers.json on first read (`ensureSeeded`); the
+ * `refreshBrokers()` network pull is user-triggered ONLY. Curated rows
+ * (`source=curated`) are never clobbered by an auto refresh.
+ *
+ * This module also owns the PURE case state machine + recheck backoff
+ * (exported for the scan/opt-out engines and unit tests) — the issue allows it
+ * to live here rather than a separate privacyCaseStates.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
+
+// ─── Case state machine (pure) ──────────────────────────────────────────────
+
+export const CASE_STATES = Object.freeze([
+ 'unscanned',
+ 'found', 'not_found', 'indirect_exposure', 'blocked',
+ 'optout_in_progress', 'submitted', 'verification_pending', 'awaiting_processing',
+ 'confirmed_removed', 'human_task_queued', 'reappeared',
+]);
+
+// Verdicts a scan pass may record on an `unscanned` (or re-scanned) case.
+export const SCAN_VERDICTS = Object.freeze(['found', 'not_found', 'indirect_exposure', 'blocked']);
+
+// Normal (non-special) transitions. `human_task_queued` (reachable from ANY
+// state), `confirmed_removed` (rescan-verification ONLY), and `reappeared`
+// (confirmed_removed + rescan ONLY) are handled as special cases in
+// assertTransition — they are intentionally NOT listed here.
+const STATE_TRANSITIONS = Object.freeze({
+ unscanned: ['found', 'not_found', 'indirect_exposure', 'blocked'],
+ // A re-scan of a settled verdict can change it.
+ found: ['optout_in_progress', 'not_found', 'indirect_exposure', 'blocked'],
+ indirect_exposure: ['optout_in_progress', 'found', 'not_found', 'blocked'],
+ not_found: ['found', 'indirect_exposure', 'blocked'],
+ blocked: ['found', 'not_found', 'indirect_exposure', 'optout_in_progress'],
+ optout_in_progress: ['submitted'],
+ submitted: ['verification_pending'],
+ verification_pending: ['awaiting_processing'],
+ awaiting_processing: [],
+ // Post-removal / requeue paths resume opt-out work.
+ human_task_queued: [
+ 'found', 'not_found', 'indirect_exposure', 'blocked',
+ 'optout_in_progress', 'submitted', 'verification_pending', 'awaiting_processing',
+ ],
+ reappeared: ['optout_in_progress'],
+ confirmed_removed: [],
+});
+
+// State-dependent recheck backoff (days). `unscanned` → recheck immediately.
+const RECHECK_BACKOFF_DAYS = Object.freeze({
+ unscanned: 0,
+ found: 1,
+ indirect_exposure: 1,
+ optout_in_progress: 1,
+ submitted: 3,
+ verification_pending: 3,
+ awaiting_processing: 7,
+ confirmed_removed: 30,
+ not_found: 60,
+ blocked: 14,
+ human_task_queued: 14,
+ reappeared: 1,
+});
+
+/**
+ * Assert a case may move `from → to`. Throws a 400 ServerError on an invalid
+ * transition. `viaRescan` gates the two verification-only targets:
+ * - `confirmed_removed` is reachable ONLY from a verifying re-scan (never from
+ * a submission confirmation page) — the design's hard rule.
+ * - `reappeared` is reachable ONLY from `confirmed_removed` via a re-scan hit.
+ */
+export function assertTransition(from, to, { viaRescan = false } = {}) {
+ if (!CASE_STATES.includes(to)) {
+ throw new ServerError(`Unknown case state "${to}"`, { status: 400, code: 'INVALID_CASE_STATE' });
+ }
+ if (!CASE_STATES.includes(from)) {
+ throw new ServerError(`Unknown case state "${from}"`, { status: 400, code: 'INVALID_CASE_STATE' });
+ }
+ if (from === to) return; // idempotent re-stamp
+ if (to === 'human_task_queued') return; // any state → human task digest
+ if (to === 'confirmed_removed') {
+ if (!viaRescan) {
+ throw new ServerError(
+ 'confirmed_removed is only reachable from a verifying re-scan',
+ { status: 400, code: 'CONFIRMED_REQUIRES_RESCAN' },
+ );
+ }
+ if (!['verification_pending', 'awaiting_processing', 'human_task_queued'].includes(from)) {
+ throw new ServerError(
+ `Invalid transition ${from} → confirmed_removed`,
+ { status: 400, code: 'INVALID_STATE_TRANSITION' },
+ );
+ }
+ return;
+ }
+ if (to === 'reappeared') {
+ if (from !== 'confirmed_removed' || !viaRescan) {
+ throw new ServerError(
+ 'reappeared is only reachable from confirmed_removed via a re-scan hit',
+ { status: 400, code: 'INVALID_STATE_TRANSITION' },
+ );
+ }
+ return;
+ }
+ if (!(STATE_TRANSITIONS[from] || []).includes(to)) {
+ throw new ServerError(
+ `Invalid transition ${from} → ${to}`,
+ { status: 400, code: 'INVALID_STATE_TRANSITION' },
+ );
+ }
+}
+
+/** ISO timestamp for the next recheck given the state (state-dependent backoff). */
+export function computeNextRecheckAt(state, now = new Date()) {
+ const days = RECHECK_BACKOFF_DAYS[state] ?? 14;
+ return new Date(now.getTime() + days * 24 * 60 * 60 * 1000).toISOString();
+}
+
+// ─── Broker rows ────────────────────────────────────────────────────────────
+
+const BROKER_COLUMNS = `id, name, urls, optout, tier, disclosure_fields,
+ cluster_parent, prefer_suppression, antibot, source, confidence,
+ to_char(last_verified, 'YYYY-MM-DD') AS last_verified, enabled,
+ created_at, updated_at`;
+
+function rowToBroker(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ name: row.name,
+ urls: row.urls ?? {},
+ optout: row.optout ?? {},
+ tier: row.tier,
+ disclosureFields: row.disclosure_fields ?? [],
+ clusterParent: row.cluster_parent,
+ preferSuppression: row.prefer_suppression,
+ antibot: row.antibot,
+ source: row.source,
+ confidence: row.confidence,
+ lastVerified: row.last_verified ?? null,
+ enabled: row.enabled,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+// A broker record from any source, normalized to the row shape. Defensive:
+// tolerates a sparse auto-discovered entry (BADBOOL / CA registry).
+function normalizeBroker(b) {
+ return {
+ id: String(b.id),
+ name: b.name ?? b.id,
+ urls: b.urls ?? {},
+ optout: b.optout ?? {},
+ tier: Number.isInteger(b.tier) ? b.tier : 2,
+ disclosureFields: Array.isArray(b.disclosure_fields) ? b.disclosure_fields
+ : (Array.isArray(b.disclosureFields) ? b.disclosureFields : []),
+ clusterParent: b.cluster_parent ?? b.clusterParent ?? null,
+ preferSuppression: b.prefer_suppression ?? b.preferSuppression ?? false,
+ antibot: b.antibot ?? false,
+ source: b.source ?? 'curated',
+ confidence: b.confidence ?? 'documented',
+ lastVerified: b.last_verified ?? b.lastVerified ?? null,
+ enabled: b.enabled !== false,
+ };
+}
+
+// Upsert one broker; when `onlyIfNotCurated` is set the DO UPDATE is skipped for
+// a row already marked curated (the refresh never clobbers field-verified data).
+async function upsertBroker(client, b, { onlyIfNotCurated = false } = {}) {
+ const guard = onlyIfNotCurated ? `WHERE privacy_brokers.source <> 'curated'` : '';
+ await client.query(
+ `INSERT INTO privacy_brokers
+ (id, name, urls, optout, tier, disclosure_fields, cluster_parent,
+ prefer_suppression, antibot, source, confidence, last_verified, enabled,
+ created_at, updated_at)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13, NOW(), NOW())
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name, urls = EXCLUDED.urls, optout = EXCLUDED.optout,
+ tier = EXCLUDED.tier, disclosure_fields = EXCLUDED.disclosure_fields,
+ cluster_parent = EXCLUDED.cluster_parent,
+ prefer_suppression = EXCLUDED.prefer_suppression, antibot = EXCLUDED.antibot,
+ source = EXCLUDED.source, confidence = EXCLUDED.confidence,
+ last_verified = EXCLUDED.last_verified, enabled = EXCLUDED.enabled,
+ updated_at = NOW()
+ ${guard}`,
+ [
+ b.id, b.name, JSON.stringify(b.urls), JSON.stringify(b.optout), b.tier,
+ b.disclosureFields, b.clusterParent, b.preferSuppression, b.antibot,
+ b.source, b.confidence, b.lastVerified, b.enabled,
+ ],
+ );
+}
+
+/** Read the shipped curated seed. Exported for tests. */
+export async function loadCuratedSeed() {
+ const path = join(PATHS.root, 'data.reference', 'privacy', 'brokers.json');
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
+ return Array.isArray(parsed.brokers) ? parsed.brokers.map(normalizeBroker) : [];
+}
+
+/**
+ * Seed the curated brokers idempotently. Parents (no cluster_parent) are
+ * inserted first so a child's self-FK is satisfiable. Curated rows always
+ * upsert (so a shipped correction propagates).
+ */
+export async function seedCuratedBrokers() {
+ const brokers = await loadCuratedSeed();
+ const ordered = [...brokers].sort((a, b) => (a.clusterParent ? 1 : 0) - (b.clusterParent ? 1 : 0));
+ await withTransaction(async (client) => {
+ for (const b of ordered) await upsertBroker(client, b);
+ });
+ console.log(`🗂️ Seeded ${ordered.length} curated privacy brokers`);
+ return { seeded: ordered.length };
+}
+
+// Lazy first-use seed — never at boot. Only seeds an empty table.
+async function ensureSeeded() {
+ const { rows } = await query(`SELECT COUNT(*)::int AS n FROM privacy_brokers`);
+ if (rows[0].n === 0) await seedCuratedBrokers();
+}
+
+export async function listBrokers({ enabled } = {}) {
+ await ensureSeeded();
+ const clauses = [];
+ const params = [];
+ if (typeof enabled === 'boolean') { params.push(enabled); clauses.push(`enabled = $${params.length}`); }
+ const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
+ // Cluster parents first (a parent suppression covers its children), then name.
+ const { rows } = await query(
+ `SELECT ${BROKER_COLUMNS} FROM privacy_brokers ${where}
+ ORDER BY (cluster_parent IS NOT NULL), name ASC`,
+ params,
+ );
+ return rows.map(rowToBroker);
+}
+
+export async function getBroker(id) {
+ const { rows } = await query(`SELECT ${BROKER_COLUMNS} FROM privacy_brokers WHERE id = $1`, [id]);
+ return rowToBroker(rows[0]);
+}
+
+// Parse the CA Data Broker Registry CSV (id/name-bearing rows) defensively.
+// Returns [] on any shape we can't recognize rather than throwing.
+export function parseCaRegistryCsv(csv) {
+ if (typeof csv !== 'string' || !csv.trim()) return [];
+ const lines = csv.split(/\r?\n/).filter((l) => l.trim());
+ if (lines.length < 2) return [];
+ const header = lines[0].split(',').map((h) => h.trim().toLowerCase());
+ const nameIdx = header.findIndex((h) => h.includes('name') || h.includes('business'));
+ const urlIdx = header.findIndex((h) => h.includes('url') || h.includes('website'));
+ if (nameIdx === -1) return [];
+ return lines.slice(1).map((line) => {
+ const cols = line.split(',');
+ const name = (cols[nameIdx] || '').trim().replace(/^"|"$/g, '');
+ if (!name) return null;
+ const website = urlIdx !== -1 ? (cols[urlIdx] || '').trim().replace(/^"|"$/g, '') : '';
+ return normalizeBroker({
+ id: `ca-${name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`,
+ name,
+ urls: website ? { home: website } : {},
+ source: 'ca_registry',
+ confidence: 'auto',
+ });
+ }).filter(Boolean);
+}
+
+// Parse the BADBOOL people-search list (a JSON array of {id?,name,url?} entries).
+export function parseBadboolList(payload) {
+ const arr = Array.isArray(payload) ? payload : (Array.isArray(payload?.brokers) ? payload.brokers : []);
+ return arr.map((b) => {
+ const name = b.name || b.id;
+ if (!name) return null;
+ return normalizeBroker({
+ id: b.id || name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''),
+ name,
+ urls: b.url ? { home: b.url } : (b.urls || {}),
+ optout: b.optout || {},
+ source: 'badbool',
+ confidence: 'auto',
+ });
+ }).filter(Boolean);
+}
+
+// Default network fetchers — injected so tests never hit the network AND boot
+// never does either (refreshBrokers is user-triggered only).
+const BADBOOL_URL = 'https://raw.githubusercontent.com/bugbounty-zz/data-broker-list/main/brokers.json';
+const CA_REGISTRY_URL = 'https://cppa.ca.gov/data_broker_registry.csv';
+
+async function defaultFetchBadbool() {
+ const res = await fetch(BADBOOL_URL).catch(() => null);
+ if (!res || !res.ok) return [];
+ return parseBadboolList(await res.json().catch(() => null));
+}
+
+async function defaultFetchCaRegistry() {
+ const res = await fetch(CA_REGISTRY_URL).catch(() => null);
+ if (!res || !res.ok) return [];
+ return parseCaRegistryCsv(await res.text().catch(() => ''));
+}
+
+/**
+ * USER-TRIGGERED refresh: pull the BADBOOL people-search list + the CA Data
+ * Broker Registry and upsert them with `source`/`confidence: auto`. NEVER
+ * overwrites a curated row (the ON CONFLICT guard skips `source=curated`).
+ * Fetchers are injectable for tests. NOT called at boot.
+ */
+export async function refreshBrokers({ fetchBadbool = defaultFetchBadbool, fetchCaRegistry = defaultFetchCaRegistry } = {}) {
+ await ensureSeeded();
+ const [badbool, caRegistry] = await Promise.all([
+ fetchBadbool().catch(() => []),
+ fetchCaRegistry().catch(() => []),
+ ]);
+ // Normalize + tag every fetched entry per lane (defensive — an injected/raw
+ // fetcher may return a sparse shape, and a refreshed broker is ALWAYS an auto
+ // source, never curated). `clusterParent: null` because auto brokers never
+ // join a curated cluster (avoids a dangling self-FK to a non-existent parent).
+ // De-dupe by id: a broker on both lists is inserted once.
+ const tag = (arr, source) => arr
+ .map(normalizeBroker)
+ .filter((b) => b?.id)
+ .map((b) => ({ ...b, clusterParent: null, source, confidence: 'auto' }));
+ const byId = new Map();
+ for (const b of [...tag(badbool, 'badbool'), ...tag(caRegistry, 'ca_registry')]) {
+ if (!byId.has(b.id)) byId.set(b.id, b);
+ }
+ let added = 0;
+ await withTransaction(async (client) => {
+ for (const b of byId.values()) {
+ const before = await client.query(`SELECT 1 FROM privacy_brokers WHERE id = $1`, [b.id]);
+ await upsertBroker(client, b, { onlyIfNotCurated: true });
+ if (before.rowCount === 0) added += 1;
+ }
+ });
+ console.log(`🔄 Broker refresh: ${badbool.length} badbool + ${caRegistry.length} ca_registry → ${added} new, curated preserved`);
+ return { fetched: byId.size, added, sources: { badbool: badbool.length, caRegistry: caRegistry.length } };
+}
+
+// ─── Case ledger ────────────────────────────────────────────────────────────
+
+const CASE_COLUMNS = `id, broker_id, state, found, evidence, disclosed_fields,
+ channel, reason, next_recheck_at, created_at, updated_at`;
+
+function rowToCase(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ brokerId: row.broker_id,
+ state: row.state,
+ found: row.found ?? null,
+ evidence: row.evidence ?? {},
+ disclosedFields: row.disclosed_fields ?? [],
+ channel: row.channel ?? null,
+ reason: row.reason ?? null,
+ nextRecheckAt: row.next_recheck_at,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ // Present only on the joined list query.
+ ...(row.broker_name !== undefined ? { brokerName: row.broker_name } : {}),
+ ...(row.tier !== undefined ? { brokerTier: row.tier } : {}),
+ };
+}
+
+export async function listBrokerCases({ state } = {}) {
+ const clauses = [];
+ const params = [];
+ if (state) { params.push(state); clauses.push(`c.state = $${params.length}`); }
+ const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
+ const { rows } = await query(
+ `SELECT c.id, c.broker_id, c.state, c.found, c.evidence, c.disclosed_fields,
+ c.channel, c.reason, c.next_recheck_at, c.created_at, c.updated_at,
+ b.name AS broker_name, b.tier
+ FROM privacy_broker_cases c
+ JOIN privacy_brokers b ON b.id = c.broker_id
+ ${where}
+ ORDER BY b.name ASC`,
+ params,
+ );
+ return rows.map(rowToCase);
+}
+
+export async function getCaseForBroker(brokerId) {
+ const { rows } = await query(
+ `SELECT ${CASE_COLUMNS} FROM privacy_broker_cases WHERE broker_id = $1`, [brokerId],
+ );
+ return rowToCase(rows[0]);
+}
+
+/**
+ * Record a scan verdict on a broker's case — creates the case if absent, else
+ * transitions the existing case. Enforces the state machine (a re-scan sets
+ * `viaRescan`). Every write stamps `next_recheck_at`. Returns the case row.
+ */
+export async function recordScanVerdict(brokerId, verdict, { evidence = {}, found = null, now = new Date() } = {}) {
+ if (!SCAN_VERDICTS.includes(verdict)) {
+ throw new ServerError(`Not a scan verdict: "${verdict}"`, { status: 400, code: 'INVALID_SCAN_VERDICT' });
+ }
+ 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' });
+ const existing = await client.query(
+ `SELECT id, state FROM privacy_broker_cases WHERE broker_id = $1 FOR UPDATE`, [brokerId],
+ );
+ const nextRecheck = computeNextRecheckAt(verdict, now);
+ if (!existing.rows[0]) {
+ assertTransition('unscanned', verdict);
+ const id = randomUUID();
+ const { rows } = await client.query(
+ `INSERT INTO privacy_broker_cases
+ (id, broker_id, state, found, evidence, next_recheck_at, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
+ RETURNING ${CASE_COLUMNS}`,
+ [id, brokerId, verdict, found, JSON.stringify(evidence), nextRecheck],
+ );
+ console.log(`🔎 Broker ${brokerId}: new case → ${verdict}`);
+ return rowToCase(rows[0]);
+ }
+ // Re-scan of an existing case. A settled verdict flipping is a rescan.
+ assertTransition(existing.rows[0].state, verdict, { viaRescan: true });
+ const { rows } = await client.query(
+ `UPDATE privacy_broker_cases
+ SET state = $1, found = $2, evidence = $3, next_recheck_at = $4, updated_at = NOW()
+ WHERE broker_id = $5 RETURNING ${CASE_COLUMNS}`,
+ [verdict, found, JSON.stringify(evidence), nextRecheck, brokerId],
+ );
+ console.log(`🔎 Broker ${brokerId}: case ${existing.rows[0].state} → ${verdict}`);
+ return rowToCase(rows[0]);
+ });
+}
+
+/**
+ * Transition a case by id through the opt-out lifecycle (submitted, etc.).
+ * 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.
+ */
+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],
+ );
+ if (!existing.rows[0]) throw new ServerError('Case not found', { status: 404, code: 'NOT_FOUND' });
+ assertTransition(existing.rows[0].state, toState, { viaRescan });
+ const sets = ['state = $1', 'next_recheck_at = $2', 'updated_at = NOW()'];
+ const params = [toState, computeNextRecheckAt(toState, now)];
+ const add = (column, value) => { params.push(value); sets.push(`${column} = $${params.length}`); };
+ if (patch.found !== undefined) add('found', patch.found);
+ 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));
+ params.push(caseId);
+ const { rows } = await client.query(
+ `UPDATE privacy_broker_cases SET ${sets.join(', ')} WHERE id = $${params.length} RETURNING ${CASE_COLUMNS}`,
+ params,
+ );
+ console.log(`📋 Case ${caseId}: ${existing.rows[0].state} → ${toState}`);
+ return rowToCase(rows[0]);
+ });
+}
+
+/**
+ * Aggregate readout for the scan/status endpoint + Brokers UI: total enabled
+ * brokers, case counts per state, and how many cases are due for a recheck.
+ * Seeds lazily so a fresh install reports the full curated broker count.
+ */
+export async function getScanStatus({ now = new Date() } = {}) {
+ await ensureSeeded();
+ const [brokerCount, byState, due] = await Promise.all([
+ query(`SELECT COUNT(*)::int AS n FROM privacy_brokers WHERE enabled = TRUE`),
+ query(`SELECT state, COUNT(*)::int AS n FROM privacy_broker_cases GROUP BY state`),
+ query(
+ `SELECT COUNT(*)::int AS n FROM privacy_broker_cases
+ WHERE next_recheck_at IS NULL OR next_recheck_at <= $1`,
+ [now.toISOString()],
+ ),
+ ]);
+ const caseCounts = {};
+ for (const row of byState.rows) caseCounts[row.state] = row.n;
+ return {
+ enabledBrokers: brokerCount.rows[0].n,
+ caseCounts,
+ dueForRecheck: due.rows[0].n,
+ };
+}
+
+/** Cases whose next_recheck_at is due (or unscanned/never-stamped). */
+export async function getDueCases({ now = new Date() } = {}) {
+ const { rows } = await query(
+ `SELECT ${CASE_COLUMNS} FROM privacy_broker_cases
+ WHERE next_recheck_at IS NULL OR next_recheck_at <= $1
+ ORDER BY next_recheck_at NULLS FIRST`,
+ [now.toISOString()],
+ );
+ return rows.map(rowToCase);
+}
diff --git a/server/services/privacyBrokers.test.js b/server/services/privacyBrokers.test.js
new file mode 100644
index 0000000000..0ebe8d6132
--- /dev/null
+++ b/server/services/privacyBrokers.test.js
@@ -0,0 +1,140 @@
+/**
+ * Pure-logic tests for the broker case state machine + recheck backoff +
+ * refresh parsers (issue #2144). No DB — the DB round-trip lives in
+ * privacyBrokers.db.test.js.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ CASE_STATES,
+ SCAN_VERDICTS,
+ assertTransition,
+ computeNextRecheckAt,
+ parseCaRegistryCsv,
+ parseBadboolList,
+} from './privacyBrokers.js';
+
+describe('assertTransition — valid paths', () => {
+ it('allows every scan verdict from unscanned', () => {
+ for (const to of SCAN_VERDICTS) {
+ expect(() => assertTransition('unscanned', to)).not.toThrow();
+ }
+ });
+
+ it('walks the opt-out lifecycle forward', () => {
+ const chain = [
+ ['found', 'optout_in_progress'],
+ ['optout_in_progress', 'submitted'],
+ ['submitted', 'verification_pending'],
+ ['verification_pending', 'awaiting_processing'],
+ ];
+ for (const [from, to] of chain) expect(() => assertTransition(from, to)).not.toThrow();
+ });
+
+ it('allows any state → human_task_queued', () => {
+ for (const from of CASE_STATES) {
+ if (from === 'human_task_queued') continue;
+ expect(() => assertTransition(from, 'human_task_queued')).not.toThrow();
+ }
+ });
+
+ it('allows idempotent same-state re-stamp', () => {
+ expect(() => assertTransition('submitted', 'submitted')).not.toThrow();
+ });
+});
+
+describe('assertTransition — confirmed_removed is rescan-only', () => {
+ it('rejects confirmed_removed without viaRescan even from awaiting_processing', () => {
+ expect(() => assertTransition('awaiting_processing', 'confirmed_removed'))
+ .toThrowError(/only reachable from a verifying re-scan/i);
+ });
+
+ it('accepts confirmed_removed from awaiting_processing WITH viaRescan', () => {
+ expect(() => assertTransition('awaiting_processing', 'confirmed_removed', { viaRescan: true })).not.toThrow();
+ });
+
+ it('rejects confirmed_removed from a submission state even with viaRescan', () => {
+ // A submission page can never confirm removal — only verification_pending /
+ // awaiting_processing / human_task_queued may.
+ expect(() => assertTransition('submitted', 'confirmed_removed', { viaRescan: true }))
+ .toThrowError(/invalid transition/i);
+ });
+
+ it('rejects a bare submitted → confirmed_removed (the classic hole)', () => {
+ let code;
+ try { assertTransition('submitted', 'confirmed_removed'); } catch (e) { code = e.code; }
+ expect(code).toBe('CONFIRMED_REQUIRES_RESCAN');
+ });
+});
+
+describe('assertTransition — reappeared is confirmed_removed + rescan only', () => {
+ it('accepts confirmed_removed → reappeared via rescan', () => {
+ expect(() => assertTransition('confirmed_removed', 'reappeared', { viaRescan: true })).not.toThrow();
+ });
+ it('rejects reappeared from any other state', () => {
+ expect(() => assertTransition('found', 'reappeared', { viaRescan: true })).toThrow();
+ });
+ it('rejects reappeared without rescan', () => {
+ expect(() => assertTransition('confirmed_removed', 'reappeared')).toThrow();
+ });
+});
+
+describe('assertTransition — invalid transitions rejected', () => {
+ it('rejects skipping the lifecycle (found → submitted)', () => {
+ expect(() => assertTransition('found', 'submitted')).toThrowError(/invalid transition/i);
+ });
+ it('rejects an unknown target state', () => {
+ let code;
+ try { assertTransition('unscanned', 'banana'); } catch (e) { code = e.code; }
+ expect(code).toBe('INVALID_CASE_STATE');
+ });
+ it('rejects an unknown source state', () => {
+ expect(() => assertTransition('bogus', 'found')).toThrowError(/unknown case state/i);
+ });
+});
+
+describe('computeNextRecheckAt — state-dependent backoff', () => {
+ const now = new Date('2026-07-08T00:00:00.000Z');
+ const days = (state) => (new Date(computeNextRecheckAt(state, now)) - now) / (24 * 60 * 60 * 1000);
+
+ it('uses the documented backoffs', () => {
+ expect(days('submitted')).toBe(3);
+ expect(days('awaiting_processing')).toBe(7);
+ expect(days('confirmed_removed')).toBe(30);
+ expect(days('not_found')).toBe(60);
+ });
+ it('rechecks unscanned immediately (0 days)', () => {
+ expect(days('unscanned')).toBe(0);
+ });
+ it('falls back to 14 days for an unmapped state', () => {
+ expect(days('weird')).toBe(14);
+ });
+});
+
+describe('parseCaRegistryCsv', () => {
+ it('extracts name + url rows', () => {
+ const csv = 'Business Name,Website URL\nAcme Data,https://acme.example\n"Beta, Inc.",https://beta.example';
+ const out = parseCaRegistryCsv(csv);
+ expect(out.length).toBe(2);
+ expect(out[0]).toMatchObject({ name: 'Acme Data', source: 'ca_registry', confidence: 'auto' });
+ expect(out[0].id).toBe('ca-acme-data');
+ expect(out[0].urls).toEqual({ home: 'https://acme.example' });
+ });
+ it('returns [] on empty / headerless input', () => {
+ expect(parseCaRegistryCsv('')).toEqual([]);
+ expect(parseCaRegistryCsv('just one line')).toEqual([]);
+ });
+});
+
+describe('parseBadboolList', () => {
+ it('normalizes a JSON array of broker entries', () => {
+ const out = parseBadboolList([{ name: 'Foo Search', url: 'https://foo.example' }, { id: 'bar', name: 'Bar' }]);
+ expect(out.length).toBe(2);
+ expect(out[0]).toMatchObject({ id: 'foo-search', name: 'Foo Search', source: 'badbool', confidence: 'auto' });
+ expect(out[1].id).toBe('bar');
+ });
+ it('accepts a { brokers: [...] } wrapper and drops nameless rows', () => {
+ const out = parseBadboolList({ brokers: [{ url: 'https://x.example' }, { name: 'Yes' }] });
+ expect(out.map((b) => b.name)).toEqual(['Yes']);
+ });
+});
diff --git a/server/services/privacyScan.js b/server/services/privacyScan.js
new file mode 100644
index 0000000000..b4b9a170b0
--- /dev/null
+++ b/server/services/privacyScan.js
@@ -0,0 +1,300 @@
+/**
+ * Exposure scan engine (issue #2144, epic #2138).
+ *
+ * READ-ONLY probe of each people-search broker for the user's exposure, using
+ * search vectors DERIVED FROM THE VAULT (scan-eligible records only — the vault
+ * hard-excludes ssn/passport/etc.). Records a per-broker verdict in the case
+ * ledger (`found | not_found | indirect_exposure | blocked`); a 404 is
+ * INCONCLUSIVE (leaves the case unscanned) and an antibot wall records `blocked`
+ * — NEVER bypassed (no CAPTCHA/anti-bot defeat, per the design's hard rule).
+ *
+ * Two lanes: a plain HTTP GET of the broker's search URL first (most brokers
+ * render static HTML), escalating to the SSRF-pinned real-Chrome fetch
+ * (`fetchUrlMainText`) only when the page needs JS. Both lanes are SSRF-vetted.
+ *
+ * AI policy: this whole pass runs ONLY from a user-triggered endpoint or a
+ * user-created cron (never at boot). LLM-assisted namesake disambiguation, if
+ * added, is therefore inside a sanctioned user-triggered pass — v1 uses a pure
+ * heuristic (name + location-token co-occurrence), no LLM call.
+ */
+
+import { lookup } from 'dns/promises';
+import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';
+import { fetchUrlMainText } from './catalogIngestSources.js';
+import { listScanEligibleValues } from './privacyVault.js';
+import { listBrokers, listBrokerCases, recordScanVerdict } from './privacyBrokers.js';
+
+// Case states a scan pass may (re)touch: no case yet, or a settled SCAN verdict.
+// Cases mid-opt-out (optout_in_progress…awaiting_processing), confirmed_removed,
+// reappeared, and human_task_queued are OWNED by the opt-out/verification engine
+// (Phase 6) — a raw scan verdict must never overwrite them, so the pass skips
+// them (avoids an invalid-transition throw and preserves opt-out progress).
+const RESCANNABLE_STATES = new Set(['unscanned', 'found', 'not_found', 'indirect_exposure', 'blocked']);
+
+const HTTP_FETCH_TIMEOUT_MS = 15000;
+// Below this HTML length (or with an explicit JS wall marker) the static fetch
+// likely saw an SPA shell — escalate to the browser lane.
+const JS_SHELL_MAX_LEN = 600;
+const JS_WALL_MARKERS = ['enable javascript', 'please enable js', 'noscript', '__next_data__'];
+// Antibot / hard-challenge markers — record `blocked`, never solve.
+const ANTIBOT_MARKERS = [
+ 'captcha', 'recaptcha', 'hcaptcha', 'px-captcha', 'unusual traffic',
+ 'are you a human', 'cf-browser-verification', 'access denied', 'request blocked',
+ 'verify you are human', 'cloudflare', 'bot detection',
+];
+
+// ─── Search vectors (pure) ──────────────────────────────────────────────────
+
+const US_STATES = new Set([
+ 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA',
+ 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
+ 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT',
+ 'VA', 'WA', 'WV', 'WI', 'WY', 'DC',
+]);
+
+/**
+ * Parse an address value into { city, state } best-effort. Handles the common
+ * "123 Main St, Portland, OR 97201" and "Portland, OR" shapes; returns nulls
+ * when it can't find a 2-letter state token.
+ */
+export function parseCityState(address) {
+ if (typeof address !== 'string' || !address.trim()) return { city: null, state: null };
+ const parts = address.split(',').map((p) => p.trim()).filter(Boolean);
+ let state = null;
+ let city = null;
+ for (let i = parts.length - 1; i >= 0; i -= 1) {
+ const tokens = parts[i].split(/\s+/);
+ const stTok = tokens.find((t) => US_STATES.has(t.toUpperCase()));
+ if (stTok) {
+ state = stTok.toUpperCase();
+ // City is the comma-part immediately before the state part (or the part's
+ // leading tokens if state shares the part).
+ if (i > 0) city = parts[i - 1];
+ else if (tokens.length > 1) city = tokens.slice(0, tokens.indexOf(stTok)).join(' ') || null;
+ break;
+ }
+ }
+ return { city: city || null, state };
+}
+
+function splitName(fullName) {
+ const tokens = String(fullName).trim().split(/\s+/).filter(Boolean);
+ if (tokens.length === 0) return { firstName: '', lastName: '' };
+ if (tokens.length === 1) return { firstName: tokens[0], lastName: '' };
+ return { firstName: tokens[0], lastName: tokens[tokens.length - 1] };
+}
+
+/**
+ * Build broker search vectors from scan-eligible vault values (the output of
+ * privacyVault.listScanEligibleValues). Pure — testable without a DB. Includes
+ * `previous` addresses (a broker may still carry an old one). Sensitive types
+ * never appear here because the vault excludes them from `use_for_scans`.
+ */
+export function buildSearchVectors(scanValues = []) {
+ const names = [];
+ const emails = [];
+ const phones = [];
+ const locations = [];
+ for (const v of scanValues) {
+ if (!v || typeof v.value !== 'string' || !v.value.trim()) continue;
+ if (v.type === 'legal_name') names.push({ full: v.value.trim(), ...splitName(v.value) });
+ else if (v.type === 'email') emails.push(v.value.trim());
+ else if (v.type === 'phone') phones.push(v.value.trim());
+ else if (v.type === 'address') {
+ const { city, state } = parseCityState(v.value);
+ if (city || state) locations.push({ city, state, status: v.status ?? 'current' });
+ }
+ }
+ return { names, emails, phones, locations };
+}
+
+const enc = (s) => encodeURIComponent(String(s ?? '').trim());
+
+/**
+ * Fill a broker search-URL template ({firstName}{lastName}{city}{state} tokens)
+ * from one name + optional location. Returns null when the template lacks the
+ * name tokens it needs. Pure.
+ */
+export function fillSearchUrl(template, { name, location } = {}) {
+ if (typeof template !== 'string' || !template) return null;
+ const first = name?.firstName || '';
+ const last = name?.lastName || '';
+ if (!first && !last) return null;
+ return template
+ .replace(/\{firstName\}/g, enc(first))
+ .replace(/\{lastName\}/g, enc(last))
+ .replace(/\{city\}/g, enc(location?.city || ''))
+ .replace(/\{state\}/g, enc(location?.state || ''));
+}
+
+// ─── Verdict classification (pure) ──────────────────────────────────────────
+
+function containsAntibot(html) {
+ const h = html.toLowerCase();
+ return ANTIBOT_MARKERS.some((m) => h.includes(m));
+}
+
+function looksLikeJsShell(html) {
+ if (!html || html.length < JS_SHELL_MAX_LEN) return true;
+ const h = html.toLowerCase();
+ return JS_WALL_MARKERS.some((m) => h.includes(m));
+}
+
+/**
+ * Classify a fetched broker page against the search vectors. Pure.
+ * - HTTP 404 → INCONCLUSIVE (verdict null): the case stays `unscanned`.
+ * - antibot wall (or a 403) → `blocked` (never bypassed).
+ * - name + a location token (city/state) co-occur → `found`.
+ * - name alone → `indirect_exposure` (a listing may exist but the match is
+ * weaker — namesake risk).
+ * - otherwise → `not_found`.
+ * `broker.antibot` tips a short/blank page toward `blocked` rather than
+ * `not_found` (the wall likely hid the result).
+ */
+export function classifyScanResult({ status, html = '', vectors = {}, broker = {} }) {
+ if (status === 404) return { verdict: null, inconclusive: true, evidence: { match_basis: 'http_404' } };
+ if (status === 403 || containsAntibot(html)) {
+ return { verdict: 'blocked', evidence: { match_basis: 'antibot_wall', http_status: status } };
+ }
+ if (status && status >= 500) return { verdict: null, inconclusive: true, evidence: { match_basis: `http_${status}` } };
+
+ const h = html.toLowerCase();
+ const names = vectors.names || [];
+ const locations = vectors.locations || [];
+ const nameHit = names.find((n) => n.full && h.includes(n.full.toLowerCase()));
+ if (nameHit) {
+ const locHit = locations.find((l) => (l.city && h.includes(l.city.toLowerCase())) || (l.state && h.includes(l.state.toLowerCase())));
+ if (locHit) {
+ return {
+ verdict: 'found',
+ found: true,
+ evidence: { match_basis: 'name+location', matched_name: nameHit.full, matched_location: locHit.city || locHit.state },
+ };
+ }
+ return { verdict: 'indirect_exposure', found: null, evidence: { match_basis: 'name_only', matched_name: nameHit.full } };
+ }
+ if (broker.antibot && looksLikeJsShell(html)) {
+ return { verdict: 'blocked', evidence: { match_basis: 'antibot_shell' } };
+ }
+ return { verdict: 'not_found', found: false, evidence: { match_basis: 'no_match' } };
+}
+
+// ─── Fetch lanes ────────────────────────────────────────────────────────────
+
+// SSRF-vet a broker URL before the HTTP lane touches it (mirrors the catalog
+// ingest gate; the browser lane vets internally via fetchUrlMainText).
+async function isScanUrlSafe(target) {
+ if (!isSafeIngestUrl(target)) return false;
+ const { hostname } = new URL(target);
+ const isIpLiteral = /^[\d.]+$/.test(hostname) || hostname.includes(':');
+ if (isIpLiteral) return true;
+ const resolved = await lookup(hostname).catch(() => null);
+ return !(resolved?.address && isBlockedIngestHost(resolved.address));
+}
+
+// Plain HTTP GET lane. Returns { status, html } or null on network failure.
+async function httpFetchLane(url, fetchImpl) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), HTTP_FETCH_TIMEOUT_MS);
+ const res = await fetchImpl(url, {
+ signal: controller.signal,
+ redirect: 'follow',
+ headers: { 'User-Agent': 'Mozilla/5.0 (compatible; PortOS-PrivacyScan/1.0)' },
+ }).catch(() => null);
+ clearTimeout(timer);
+ if (!res) return null;
+ const html = await res.text().catch(() => '');
+ return { status: res.status, html };
+}
+
+/**
+ * Scan ONE broker for exposure and record the verdict. `deps` are injectable so
+ * tests never hit the network/browser:
+ * - `fetchImpl` (default global fetch) — the HTTP lane.
+ * - `browserFetch` (default fetchUrlMainText) — the JS-required escalation.
+ * Returns the recorded case, or `{ skipped: true, reason }` when the broker has
+ * no usable search URL (blind scan not possible) or the URL is unsafe.
+ */
+export async function scanBroker(broker, vectors, {
+ fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(),
+} = {}) {
+ const template = broker?.urls?.search;
+ const name = (vectors.names || [])[0];
+ const location = (vectors.locations || [])[0];
+ if (!template || !name) {
+ return { skipped: true, reason: !template ? 'no_search_url' : 'no_name_vector' };
+ }
+ const url = fillSearchUrl(template, { name, location });
+ if (!url || !(await urlSafe(url))) {
+ return { skipped: true, reason: 'unsafe_or_unfillable_url' };
+ }
+
+ let result = await httpFetchLane(url, fetchImpl);
+ let html = result?.html ?? '';
+ let status = result?.status ?? null;
+
+ // Escalate to the pinned browser lane when the static fetch saw a JS shell.
+ if (result && result.status >= 200 && result.status < 400 && looksLikeJsShell(html) && !containsAntibot(html)) {
+ const browsed = await browserFetch(url).catch(() => null);
+ if (browsed?.text) { html = browsed.text; status = 200; }
+ }
+
+ if (!result && !html) {
+ // Total network failure — inconclusive, leave case unscanned.
+ return { skipped: true, reason: 'fetch_failed' };
+ }
+
+ const classified = classifyScanResult({ status, html, vectors, broker });
+ const evidence = { ...classified.evidence, listing_urls: classified.verdict === 'found' ? [url] : [] };
+ if (classified.inconclusive || !classified.verdict) {
+ return { skipped: true, reason: classified.evidence?.match_basis || 'inconclusive' };
+ }
+ const kase = await recordScanVerdict(broker.id, classified.verdict, {
+ evidence, found: classified.found ?? null, now,
+ });
+ return kase;
+}
+
+/**
+ * Run a full scan pass over enabled brokers using vault-derived vectors. Read-
+ * only + idempotent (safe to re-run). Sequential with modest concurrency.
+ * USER-TRIGGERED only (route / user cron) — never at boot.
+ *
+ * Returns a summary { scanned, verdicts: {<verdict>: n}, skipped, brokers }.
+ */
+export async function runScanPass({ concurrency = 3, fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date() } = {}) {
+ const scanValues = await listScanEligibleValues();
+ const vectors = buildSearchVectors(scanValues);
+ if ((vectors.names || []).length === 0) {
+ console.log('🔎 Scan pass aborted: no scan-eligible name in the vault');
+ return { scanned: 0, verdicts: {}, skipped: 0, brokers: 0, reason: 'no_scan_vectors' };
+ }
+ const allBrokers = await listBrokers({ enabled: true });
+ // Skip brokers whose case is owned by the opt-out engine, or whose settled
+ // verdict isn't yet due for a recheck — the pass is idempotent + cheap to
+ // re-run because of this filter.
+ const casesByBroker = new Map((await listBrokerCases()).map((c) => [c.brokerId, c]));
+ const nowMs = now.getTime();
+ const brokers = allBrokers.filter((b) => {
+ const kase = casesByBroker.get(b.id);
+ if (!kase) return true; // never scanned
+ if (!RESCANNABLE_STATES.has(kase.state)) return false; // opt-out-owned
+ return !kase.nextRecheckAt || new Date(kase.nextRecheckAt).getTime() <= nowMs; // due
+ });
+ const verdicts = {};
+ let scanned = 0;
+ let skipped = 0;
+
+ // Small concurrency pool — brokers are independent, but keep it modest so we
+ // don't hammer many hosts at once.
+ for (let i = 0; i < brokers.length; i += concurrency) {
+ const batch = brokers.slice(i, i + concurrency);
+ const results = await Promise.all(batch.map((b) => scanBroker(b, vectors, { fetchImpl, browserFetch, urlSafe, now })));
+ for (const r of results) {
+ if (r?.skipped) { skipped += 1; continue; }
+ if (r?.state) { verdicts[r.state] = (verdicts[r.state] || 0) + 1; scanned += 1; }
+ }
+ }
+ console.log(`🔎 Scan pass complete: ${scanned} verdicts, ${skipped} skipped across ${brokers.length} brokers`);
+ return { scanned, verdicts, skipped, brokers: brokers.length };
+}
diff --git a/server/services/privacyScan.test.js b/server/services/privacyScan.test.js
new file mode 100644
index 0000000000..99114d600a
--- /dev/null
+++ b/server/services/privacyScan.test.js
@@ -0,0 +1,135 @@
+/**
+ * Pure-logic tests for the exposure scan engine (issue #2144): search-vector
+ * derivation (excludes non-scan types), URL fill, and verdict classification.
+ * No network/DB — recordScanVerdict is mocked so scanBroker's classify→record
+ * wiring is exercised without Postgres.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('./privacyBrokers.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, recordScanVerdict: vi.fn(async (brokerId, verdict, opts) => ({ id: 'case-1', brokerId, state: verdict, ...opts })) };
+});
+vi.mock('./catalogIngestSources.js', () => ({ fetchUrlMainText: vi.fn(async () => null) }));
+vi.mock('./privacyVault.js', () => ({ listScanEligibleValues: vi.fn(async () => []) }));
+
+const {
+ parseCityState, buildSearchVectors, fillSearchUrl, classifyScanResult, scanBroker,
+} = await import('./privacyScan.js');
+const brokers = await import('./privacyBrokers.js');
+
+describe('parseCityState', () => {
+ it('parses the full street form', () => {
+ expect(parseCityState('123 Main St, Portland, OR 97201')).toEqual({ city: 'Portland', state: 'OR' });
+ });
+ it('parses a bare city, state', () => {
+ expect(parseCityState('Salem, OR')).toEqual({ city: 'Salem', state: 'OR' });
+ });
+ it('returns nulls when no state token', () => {
+ expect(parseCityState('somewhere unknown')).toEqual({ city: null, state: null });
+ });
+});
+
+describe('buildSearchVectors — excludes non-scan types', () => {
+ it('groups name/email/phone/address and IGNORES ssn/passport/etc.', () => {
+ const v = buildSearchVectors([
+ { type: 'legal_name', value: 'Jane Q Doe' },
+ { type: 'email', value: '[email protected]' },
+ { type: 'phone', value: '+1 503 555 0100' },
+ { type: 'address', value: '1 Oak Ave, Portland, OR 97201', status: 'current' },
+ { type: 'address', value: '9 Old Rd, Salem, OR 97301', status: 'previous' },
+ // These must never appear in the vectors even if handed in:
+ { type: 'ssn', value: '123-45-6789' },
+ { type: 'passport', value: 'P123' },
+ { type: 'financial_account', value: 'acct-9' },
+ ]);
+ expect(v.names).toEqual([{ full: 'Jane Q Doe', firstName: 'Jane', lastName: 'Doe' }]);
+ expect(v.emails).toEqual(['[email protected]']);
+ expect(v.phones).toEqual(['+1 503 555 0100']);
+ expect(v.locations).toEqual([
+ { city: 'Portland', state: 'OR', status: 'current' },
+ { city: 'Salem', state: 'OR', status: 'previous' },
+ ]);
+ // No ssn/passport/financial value leaked anywhere.
+ expect(JSON.stringify(v)).not.toContain('123-45-6789');
+ expect(JSON.stringify(v)).not.toContain('P123');
+ });
+});
+
+describe('fillSearchUrl', () => {
+ it('fills name + location tokens URL-encoded', () => {
+ const url = fillSearchUrl('https://b.example/{firstName}-{lastName}/{state}', {
+ name: { firstName: 'Jane', lastName: 'Doe' }, location: { state: 'OR' },
+ });
+ expect(url).toBe('https://b.example/Jane-Doe/OR');
+ });
+ it('returns null with no name', () => {
+ expect(fillSearchUrl('https://b.example/{firstName}', { name: { firstName: '', lastName: '' } })).toBe(null);
+ });
+});
+
+describe('classifyScanResult', () => {
+ const vectors = { names: [{ full: 'Jane Q Doe' }], locations: [{ city: 'Portland', state: 'OR' }] };
+
+ it('404 is INCONCLUSIVE (no verdict)', () => {
+ const r = classifyScanResult({ status: 404, html: 'nope', vectors });
+ expect(r.verdict).toBe(null);
+ expect(r.inconclusive).toBe(true);
+ });
+ it('antibot wall → blocked (never bypassed)', () => {
+ const r = classifyScanResult({ status: 200, html: 'Please complete the reCAPTCHA', vectors });
+ expect(r.verdict).toBe('blocked');
+ });
+ it('403 → blocked', () => {
+ expect(classifyScanResult({ status: 403, html: '', vectors }).verdict).toBe('blocked');
+ });
+ it('name + location → found', () => {
+ const r = classifyScanResult({ status: 200, html: 'Results for Jane Q Doe of Portland OR', vectors });
+ expect(r.verdict).toBe('found');
+ expect(r.found).toBe(true);
+ expect(r.evidence.match_basis).toBe('name+location');
+ });
+ it('name only → indirect_exposure', () => {
+ const r = classifyScanResult({ status: 200, html: 'A page mentioning Jane Q Doe somewhere', vectors });
+ expect(r.verdict).toBe('indirect_exposure');
+ });
+ it('no match → not_found', () => {
+ const r = classifyScanResult({ status: 200, html: 'Nobody here by that description', vectors });
+ expect(r.verdict).toBe('not_found');
+ });
+});
+
+describe('scanBroker — classify → record wiring', () => {
+ const vectors = { names: [{ full: 'Jane Q Doe', firstName: 'Jane', lastName: 'Doe' }], locations: [{ city: 'Portland', state: 'OR' }] };
+ const broker = { id: 'spokeo', urls: { search: 'https://b.example/{firstName}-{lastName}/{state}' } };
+
+ it('records a found verdict from the HTTP lane', async () => {
+ const fetchImpl = vi.fn(async () => ({ status: 200, text: async () => 'Found: Jane Q Doe in Portland, OR — full profile' }));
+ const kase = await brokers.recordScanVerdict;
+ kase.mockClear();
+ const res = await scanBroker(broker, vectors, { fetchImpl, urlSafe: async () => true });
+ expect(brokers.recordScanVerdict).toHaveBeenCalledWith('spokeo', 'found', expect.objectContaining({ found: true }));
+ expect(res.state).toBe('found');
+ });
+
+ it('skips a broker with no search URL (blind-scan not possible here)', async () => {
+ brokers.recordScanVerdict.mockClear();
+ const res = await scanBroker({ id: 'x', urls: {} }, vectors, { urlSafe: async () => true });
+ expect(res).toEqual({ skipped: true, reason: 'no_search_url' });
+ expect(brokers.recordScanVerdict).not.toHaveBeenCalled();
+ });
+
+ it('does NOT record on a 404 (inconclusive → stays unscanned)', async () => {
+ brokers.recordScanVerdict.mockClear();
+ const fetchImpl = vi.fn(async () => ({ status: 404, text: async () => 'not found' }));
+ const res = await scanBroker(broker, vectors, { fetchImpl, urlSafe: async () => true });
+ expect(res.skipped).toBe(true);
+ expect(brokers.recordScanVerdict).not.toHaveBeenCalled();
+ });
+
+ it('skips when the URL is unsafe (SSRF guard)', async () => {
+ const res = await scanBroker(broker, vectors, { urlSafe: async () => false });
+ expect(res).toEqual({ skipped: true, reason: 'unsafe_or_unfillable_url' });
+ });
+});
diff --git a/server/services/privacyVault.js b/server/services/privacyVault.js
index aba7db8d0a..51470fe2aa 100644
--- a/server/services/privacyVault.js
+++ b/server/services/privacyVault.js
@@ -176,6 +176,37 @@ export async function revealValue(id) {
return { id: rows[0].id, type: rows[0].type, value };
}
+/**
+ * Decrypted values for every scan-eligible record — the ONLY bulk-decrypt path,
+ * used solely to build broker-scan search vectors (privacyScan.js) inside a
+ * USER-TRIGGERED scan pass. Excludes sensitive types by construction:
+ * `use_for_scans` is hard-false for ssn/passport/drivers_license/financial_account
+ * (enforced on write + re-enforced here via the WHERE clause), so a plaintext
+ * SSN can never reach a broker form. Includes `previous` addresses (a broker may
+ * still list an old address). Plaintext is returned to the caller but never
+ * logged — the count is.
+ */
+export async function listScanEligibleValues() {
+ const { rows } = await query(
+ `SELECT id, type, value_enc, status,
+ to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
+ to_char(valid_to, 'YYYY-MM-DD') AS valid_to
+ FROM privacy_vault_records
+ WHERE use_for_scans = TRUE
+ ORDER BY type, created_at`,
+ );
+ const values = rows.map((row) => ({
+ id: row.id,
+ type: row.type,
+ value: decryptValue(row.value_enc),
+ status: row.status,
+ validFrom: row.valid_from ?? null,
+ validTo: row.valid_to ?? null,
+ }));
+ console.log(`🔎 Assembled ${values.length} scan-eligible vault values`);
+ return values;
+}
+
/** Doctor-style readout: { keyConfigured, recordCounts: { <type>: n } }. */
export async function getVaultStatus() {
const { rows } = await query(
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index dcd60051b8..b63b6a7987 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/privacyBrokers.db.test.js',
'services/catalogCanonProjection.test.js',
'services/catalogRefResolver.test.js',
'services/creativeDirector/projectsDB.test.js',