Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2145]): Privacy Center opt-out automation engine (web-form + email lanes, verification, scheduling, digest)
Adam Eivydd7571908bf4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 25ba60d59f..9bab3b2708 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -33,6 +33,7 @@## Privacy Center+- **[issue-2145] The Privacy Center can now work your data-broker removals for you.** Phase 6 of the Privacy Center (epic #2138) adds the opt-out automation engine on top of the Phase 5 broker scan + case ledger. It drives each exposed case through removal on two lanes: an **email lane** that renders a CCPA/CPRA/GDPR/generic rights-request (recipient locked to the broker's own declared address) into the Comms drafts queue as an **unapproved** draft you review before it sends, and a **web-form lane** that — by default — prepares the request and surfaces it as a human task with the broker's playbook and exactly which identifiers to submit. A **verification loop** scans your synced inbox for the broker's confirmation email (anti-phishing gated: the link's domain must actually match the broker's) to advance a case, and a case can only reach "confirmed removed" when a fresh read-only re-scan proves your listing is gone — never from a confirmation page. Everything is opt-in and default-safe: auto-sending emails and auto-submitting forms are two separate settings toggles that both ship **off**, the engine never emits anything outside a fixed least-disclosure allowlist (`full_name, email, phone, city, state, dob, listing_url`) intersected with what each broker asks for (your SSN/passport/financial data can never reach a broker), and a CAPTCHA or bot-wall is recorded as **blocked** and never bypassed. A **human-task digest** collects every case that needs you (blocked walls, phone/fax/gov-ID channels, forms awaiting manual submit) with the prepared request attached. Nothing runs on startup; passes run only when you trigger one (`POST /api/privacy/optout`) or turn on the user-configured recheck schedule (Settings → Privacy, off by default). (`server/services/privacyOptOut.js`, `server/services/privacyRecheckScheduler.js`, `server/services/privacyScan.js`, `server/routes/privacy.js`, `server/lib/privacyValidation.js`, `data.reference/privacy/email-templates/`, `server/index.js`)- **[issue-2147] The Privacy Center org drawer now cross-links to your Digital Twin social accounts — from both sides.** Completing Phase 8 (epic #2138): the create/edit organization drawer gains a **Linked social account (Digital Twin)** picker that lets you point any org at one of your twin's social accounts. It pairs with the twin's existing "Add to org registry" / "in org registry" badge so the link is visible and editable from either surface, and a stale link to a since-deleted account is preserved rather than silently dropped. (`client/src/components/privacy/OrgDrawer.jsx`)- **[issue-2142] A new Privacy Center UI puts your encrypted PII vault and the organizations that hold it in one place.** Building on the Phase 1 encrypted vault (#2140) and Phase 2 trusted-organizations registry (#2141), a deep-linkable `/privacy/:tab` page (Identity → Privacy, `⌘K`/voice-navigable) ships three tabs: **Overview** — a doctor-style readout of whether AES-256-GCM encryption is engaged, vault record counts by type, and org counts by trust stance, with quick-jump cards into the other tabs; **Vault** — records grouped by type showing only the precomputed masked value (`•••, Portland OR` / `a•••@example.com`), with per-record "Share with Twin" / "Use for scans" optimistic toggles (hard-disabled for sensitive SSN/passport/license/financial types), a create/edit `Drawer`, and an explicit per-record **Reveal** action that decrypts plaintext only on click (never cached in list state) — plaintext never renders until you ask for it; **Organizations** — a trust/category/status chip-filtered list with per-org holdings status badges and a create/edit drawer whose holdings picker checkboxes over your vault records (masked) to record which fields each org holds. All mutations update local state directly (no full-list refetch), deletes use an inline confirm row (no `window.confirm`), and every tab is usable at 360px. Each tab path is registered in the nav manifest (`nav.identity.privacy-*`). (`client/src/pages/Privacy.jsx`, `client/src/components/privacy/`, `client/src/services/apiPrivacy.js`, `server/lib/navManifest.js`)- **[issue-2144] The Privacy Center can now find where you're exposed on people-search sites.** Phase 5 of the Privacy Center (epic #2138) adds a database of ~20 major data brokers (Spokeo, Whitepages, BeenVerified, Radaris, MyLife, and the PeopleConnect cluster — Intelius/TruthFinder/Instant Checkmate/US Search), a read-only exposure scan that searches each broker using only the identity facts you've marked as scan-eligible in the vault (never your SSN, passport, license, or financial details), and a per-broker case ledger that tracks each listing through its removal lifecycle. Scans respect a hard rule: a CAPTCHA or bot-wall is recorded as "blocked" and never bypassed, and a broker can only be marked "removed" by a fresh scan that confirms your listing is actually gone — never by a submission page saying so. Nothing runs on startup: the broker list loads on first view and you can grow it on demand from the public BADBOOL and California data-broker registries (your curated brokers are never overwritten), and scans run only when you start one or schedule them. This is the data + scan backbone for the upcoming opt-out automation (Phase 6) and Brokers UI tab.diff --git a/data.reference/privacy/email-templates/ccpa.txt b/data.reference/privacy/email-templates/ccpa.txtnew file mode 100644index 0000000000..e23e77b8fd--- /dev/null+++ b/data.reference/privacy/email-templates/ccpa.txt@@ -0,0 +1,24 @@+Subject: CCPA Request to Delete and Opt Out of Sale — {{fullName}}++To the {{brokerName}} Privacy / Data Rights team,++I am a California resident exercising my rights under the California Consumer+Privacy Act (CCPA, Cal. Civ. Code § 1798.100 et seq.). I request that you:++1. Delete all personal information you hold about me, and+2. Opt me out of any sale or sharing of my personal information, and+3. Suppress my information from your public people-search listings.++Identifying information (provided solely to locate and match my records):+{{disclosedSummary}}++{{listingSection}}+Please confirm completion in writing to this email address. Under the CCPA you+must respond within 45 days.++I am submitting this request on my own behalf. Do not use the information above+for any purpose other than fulfilling this request.++Regards,+{{fullName}}+{{requestDate}}diff --git a/data.reference/privacy/email-templates/cpra.txt b/data.reference/privacy/email-templates/cpra.txtnew file mode 100644index 0000000000..af8346a001--- /dev/null+++ b/data.reference/privacy/email-templates/cpra.txt@@ -0,0 +1,25 @@+Subject: CPRA Request to Delete, Correct, and Limit — {{fullName}}++To the {{brokerName}} Privacy / Data Rights team,++I am a California resident exercising my rights under the California Privacy+Rights Act (CPRA), which amends and expands the CCPA. I request that you:++1. Delete all personal information you hold about me,+2. Opt me out of the sale and sharing of my personal information,+3. Limit the use of any sensitive personal information, and+4. Suppress my information from your public people-search listings.++Identifying information (provided solely to locate and match my records):+{{disclosedSummary}}++{{listingSection}}+Please confirm completion in writing to this email address within the statutory+response window.++I am submitting this request on my own behalf. Do not use the information above+for any purpose other than fulfilling this request.++Regards,+{{fullName}}+{{requestDate}}diff --git a/data.reference/privacy/email-templates/gdpr.txt b/data.reference/privacy/email-templates/gdpr.txtnew file mode 100644index 0000000000..98905bc77e--- /dev/null+++ b/data.reference/privacy/email-templates/gdpr.txt@@ -0,0 +1,25 @@+Subject: GDPR Article 17 Erasure Request — {{fullName}}++To the {{brokerName}} Data Protection Officer,++I am exercising my right to erasure ("right to be forgotten") under Article 17+of the EU General Data Protection Regulation (GDPR), and my right to object to+processing under Article 21. I request that you:++1. Erase all personal data you hold about me,+2. Cease any further processing, including sale or transfer, and+3. Remove my information from your public people-search listings.++Identifying information (provided solely to locate and match my records):+{{disclosedSummary}}++{{listingSection}}+Under Article 12(3) you must respond without undue delay and within one month.+Please confirm completion in writing to this email address.++I am submitting this request on my own behalf. Do not use the information above+for any purpose other than fulfilling this request.++Regards,+{{fullName}}+{{requestDate}}diff --git a/data.reference/privacy/email-templates/generic.txt b/data.reference/privacy/email-templates/generic.txtnew file mode 100644index 0000000000..f2ba348519--- /dev/null+++ b/data.reference/privacy/email-templates/generic.txt@@ -0,0 +1,20 @@+Subject: Opt-Out and Removal Request — {{fullName}}++To the {{brokerName}} Privacy team,++I am requesting that you remove and suppress my personal information from your+people-search listings and databases, and opt me out of any sale or sharing of+my information.++Identifying information (provided solely to locate and match my records):+{{disclosedSummary}}++{{listingSection}}+Please confirm completion in writing to this email address.++I am submitting this request on my own behalf. Do not use the information above+for any purpose other than fulfilling this request.++Regards,+{{fullName}}+{{requestDate}}diff --git a/server/index.js b/server/index.jsindex b1c4333529..505f5dee7e 100644--- a/server/index.js+++ b/server/index.js@@ -171,6 +171,7 @@ import * as automationScheduler from './services/automationScheduler.js';import * as agentActionExecutor from './services/agentActionExecutor.js';import * as cos from './services/cos.js';import { startBackupScheduler } from './services/backupScheduler.js';+import { startPrivacyRecheckScheduler } from './services/privacyRecheckScheduler.js';import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';import { startImessageScheduler } from './services/imessageScheduler.js';import { startSignalScheduler } from './services/signalScheduler.js';@@ -612,6 +613,10 @@ initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: $registerPostReminderSchedule({ catchUpMissedSlot: true }).catch(err => console.error(`❌ POST reminder init failed: ${err.message}`));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));+// Initialize Privacy Center opt-out recheck scheduler — OFF by default; only+// re-runs the broker scan + opt-out pass when the user opts in via+// Settings → Privacy (sanctioned scheduled-automation exception) (#2145).+startPrivacyRecheckScheduler().catch(err => console.error(`❌ Privacy recheck scheduler init failed: ${err.message}`));// Initialize CyberCity snapshot scheduler — records periodic city-state frames// for the historical timeline scrubber (issue #877).startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.jsindex 3dc1880025..77ee7686e3 100644--- a/server/lib/privacyValidation.js+++ b/server/lib/privacyValidation.js@@ -233,3 +233,41 @@ export const privacyBrokerRefreshSchema = z.object({}).strict();export const privacyScanStartSchema = z.object({concurrency: z.number().int().min(1).max(6).optional(),}).strict();++// =============================================================================+// OPT-OUT AUTOMATION ENGINE SCHEMAS (issue #2145, epic #2138)+// =============================================================================+// Zod schemas for the opt-out run/verify actions + the user-configured recheck+// settings slice (`settings.privacy.recheck`). The engine reads its submission+// autonomy (auto-approve emails / auto-submit web forms) from that slice —+// BOTH default OFF (a fresh install never auto-sends or auto-submits anything).++// POST /api/privacy/optout — run one opt-out pass. `runVerification` (default+// true) folds the verification poll into the same pass.+export const privacyOptOutPassSchema = z.object({+ runVerification: z.boolean().optional(),+}).strict();++// POST /api/privacy/optout/verify — run only the verification pass. No body.+export const privacyOptOutVerifySchema = z.object({}).strict();++// A basic 5-field cron expression validator (minute hour dom month dow). Kept+// permissive (tokens can be `*`, numbers, ranges, lists, steps) — the scheduler+// library does the strict parse; this just rejects obvious garbage before disk.+const cronExpressionSchema = z.string().trim().min(1).max(120).regex(+ /^(\S+\s+){4}\S+$/, 'expected a 5-field cron expression',+);++// The `privacy.recheck` settings slice. Validated by PUT /api/settings when the+// `privacy` key is present (partial). Everything OFF/absent by default.+export const privacyRecheckConfigSchema = z.object({+ enabled: z.boolean().optional(),+ cronExpression: cronExpressionSchema.optional(),+ autoApproveOptOutEmails: z.boolean().optional(),+ autoSubmitWebForms: z.boolean().optional(),+}).strict();++// The `privacy` settings slice (only `recheck` for now — room to grow).+export const privacySettingsSchema = z.object({+ recheck: privacyRecheckConfigSchema.optional(),+}).strict();diff --git a/server/routes/privacy.js b/server/routes/privacy.jsindex 8f489304cd..e12e45661f 100644--- a/server/routes/privacy.js+++ b/server/routes/privacy.js@@ -28,6 +28,8 @@ import {privacyChangeDeclareSchema,privacyChangeIdParamsSchema,privacyChangeOrgParamsSchema,+ privacyOptOutPassSchema,+ privacyOptOutVerifySchema,} from '../lib/privacyValidation.js';import {createVaultRecord,@@ -55,6 +57,7 @@ import {getScanStatus,} from '../services/privacyBrokers.js';import { runScanPass } from '../services/privacyScan.js';+import { runOptOutPass, runVerificationPass, getOptOutDigest } from '../services/privacyOptOut.js';import {declareChange,listChangeEvents,@@ -212,4 +215,26 @@ router.post('/scan', asyncHandler(async (req, res) => {res.json(await runScanPass(concurrency ? { concurrency } : {}));}));+// ─── Opt-out automation engine (issue #2145) ───────────────────────────────++// User-triggered opt-out pass: submit found/indirect cases via the chosen lane+// (web-form / email), poll verifications. Submission autonomy (auto-send /+// auto-submit) is read from settings.privacy.recheck — both default OFF.+router.post('/optout', asyncHandler(async (req, res) => {+ const { runVerification } = validateRequest(privacyOptOutPassSchema, req.body ?? {});+ res.json(await runOptOutPass(runVerification === undefined ? {} : { runVerification }));+}));++// User-triggered verification-only pass (inbox confirmation scan + removal re-scan).+router.post('/optout/verify', asyncHandler(async (req, res) => {+ validateRequest(privacyOptOutVerifySchema, req.body ?? {});+ res.json(await runVerificationPass());+}));++// Human-task digest: cases that need a person (blocked walls, auto-submit-off+// forms, fax/phone/gov-ID channels) with the prepared request + playbook.+router.get('/optout/digest', asyncHandler(async (_req, res) => {+ res.json(await getOptOutDigest());+}));+export default router;diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsindex fd7311bf52..9b3596c87b 100644--- a/server/routes/privacy.test.js+++ b/server/routes/privacy.test.js@@ -42,6 +42,12 @@ vi.mock('../services/privacyScan.js', () => ({runScanPass: vi.fn(async (opts) => ({ scanned: 2, verdicts: { found: 1, not_found: 1 }, skipped: 0, brokers: 20, _opts: opts })),}));+vi.mock('../services/privacyOptOut.js', () => ({+ runOptOutPass: vi.fn(async (opts) => ({ submitted: [{ brokerId: 'spokeo', lane: 'email', outcome: 'submitted' }], skipped: 0, verification: { advanced: [], confirmed: [] }, _opts: opts })),+ runVerificationPass: vi.fn(async () => ({ advanced: [{ caseId: 'c1', brokerId: 'spokeo' }], confirmed: [] })),+ getOptOutDigest: vi.fn(async () => ({ total: 1, humanTasks: 1, blocked: 0, items: [{ caseId: 'h1', brokerId: 'wp', state: 'human_task_queued', playbook: ['call back'] }] })),+}));+vi.mock('../services/privacyChanges.js', () => ({declareChange: vi.fn(async (input) => ({ id: 'c0ffee00-0000-4000-8000-000000000003', ...input })),listChangeEvents: vi.fn(async () => [{ id: 'ev1', kind: 'address_change', progress: { pending: 1, updated: 0, removed: 0, total: 1 } }]),@@ -57,6 +63,7 @@ const orgService = await import('../services/privacyOrgs.js');const brokerService = await import('../services/privacyBrokers.js');const scanService = await import('../services/privacyScan.js');const changeService = await import('../services/privacyChanges.js');+const optOutService = await import('../services/privacyOptOut.js');const VALID_UUID = 'c0ffee00-0000-4000-8000-000000000001';@@ -376,3 +383,38 @@ describe('POST /api/privacy/scan', () => {expect((await request(makeApp()).post('/api/privacy/scan').send({ concurrency: 99 })).status).toBe(400);});});++// ─── Opt-out automation engine (issue #2145) ────────────────────────────────++describe('POST /api/privacy/optout', () => {+ it('runs an opt-out pass and returns the summary', async () => {+ const res = await request(makeApp()).post('/api/privacy/optout').send({});+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ submitted: [{ brokerId: 'spokeo', outcome: 'submitted' }] });+ expect(optOutService.runOptOutPass).toHaveBeenCalledWith({});+ });++ it('passes runVerification through and rejects an unknown key', async () => {+ await request(makeApp()).post('/api/privacy/optout').send({ runVerification: false });+ expect(optOutService.runOptOutPass).toHaveBeenCalledWith({ runVerification: false });+ expect((await request(makeApp()).post('/api/privacy/optout').send({ nope: 1 })).status).toBe(400);+ });+});++describe('POST /api/privacy/optout/verify', () => {+ it('runs a verification-only pass', async () => {+ const res = await request(makeApp()).post('/api/privacy/optout/verify').send({});+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ advanced: [{ caseId: 'c1' }] });+ expect(optOutService.runVerificationPass).toHaveBeenCalled();+ });+});++describe('GET /api/privacy/optout/digest', () => {+ it('returns the human-task digest', async () => {+ const res = await request(makeApp()).get('/api/privacy/optout/digest');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ total: 1, humanTasks: 1 });+ expect(res.body.items[0].playbook).toEqual(['call back']);+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex dfa2504e65..2258165280 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -191,6 +191,12 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.pipelineEditorialChecks !== undefined) {validateRequest(pipelineEditorialChecksSettingsSchema.partial(), req.body.pipelineEditorialChecks);}+ // Privacy Center opt-out recheck config (#2145) — validate the slice when+ // present so a malformed cron / non-boolean autonomy toggle can't reach disk+ // and break the recheck scheduler. Both autonomy toggles default OFF.+ if (req.body?.privacy !== undefined) {+ validateRequest(privacySettingsSchema.partial(), req.body.privacy);+ }// User-defined catalog types moved out of settings.json into PostgreSQL// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacydiff --git a/server/services/privacyOptOut.db.test.js b/server/services/privacyOptOut.db.test.jsnew file mode 100644index 0000000000..9a4f3f024d--- /dev/null+++ b/server/services/privacyOptOut.db.test.js@@ -0,0 +1,137 @@+/**+ * Postgres-backed round-trip for the opt-out automation engine (issue #2145).+ * Exercises the REAL case-ledger state machine (privacyBrokers.transitionCase)+ * through the lanes + verification pass, so the transitions the pure test mocks+ * are proven against the actual DB constraints. Skips cleanly when no test DB is+ * reachable. Runs via `npm run test:db` (→ portos_test) ONLY.+ *+ * Message drafts + accounts are injected (not the file-backed real ones) so the+ * suite touches only Postgres. Cleans up its own broker + cases.+ */++import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';++const originalKey = process.env.PRIVACY_VAULT_KEY;+process.env.PRIVACY_VAULT_KEY = 'e'.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_broker_cases') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'privacy_broker_cases table not present';+ }+}++if (!dbReady) console.log(`⏭️ privacyOptOut.db.test.js skipped: ${skipReason}`);++describe.skipIf(!dbReady)('privacy opt-out engine DB round-trip', () => {+ let svc; // privacyOptOut+ let brokers; // privacyBrokers+ let vault;+ const brokerId = 'test-optout-broker';+ const emailBrokerId = 'test-optout-email';+ const createdVaultIds = [];++ const account = { id: 'acct-test', type: 'gmail' };+ const injectedAccounts = async () => [account];+ const drafts = [];+ const injectedDraftCreator = async (d) => { const draft = { id: `draft-${drafts.length + 1}`, status: 'draft', ...d }; drafts.push(draft); return draft; };+ const injectedApprover = async (id) => ({ id, status: 'approved' });++ beforeAll(async () => {+ svc = await import('./privacyOptOut.js');+ brokers = await import('./privacyBrokers.js');+ vault = await import('./privacyVault.js');+ // Clean slate for cases so cross-suite ordering can't leak state in.+ await query(`DELETE FROM privacy_broker_cases`).catch(() => {});+ // A web-form broker + an email broker, inserted directly (auto source so the+ // curated seed idempotency is untouched).+ for (const [id, name, optout, antibot] of [+ [brokerId, 'Test OptOut Broker', { method: 'web_form', url: 'https://test-optout.example/optout', playbook: ['step 1'] }, false],+ [emailBrokerId, 'Test OptOut Email', { method: 'email', email: '[email protected]', url: 'https://test-optout.example' }, false],+ ]) {+ await query(+ `INSERT INTO privacy_brokers (id, name, urls, optout, tier, disclosure_fields, source, confidence, enabled, created_at, updated_at)+ VALUES ($1,$2,$3,$4,2,$5,'badbool','auto',TRUE,NOW(),NOW()) ON CONFLICT (id) DO NOTHING`,+ [id, name, JSON.stringify({ home: 'https://test-optout.example' }), JSON.stringify(optout), ['full_name', 'email', 'city', 'state', 'listing_url']],+ );+ }+ // A scan-eligible name so the disclosure payload has an identity.+ const rec = await vault.createVaultRecord({ type: 'legal_name', label: 'Legal', value: 'Jane Q Testcase', useForScans: true });+ createdVaultIds.push(rec.id);+ const addr = await vault.createVaultRecord({ type: 'address', label: 'Home', value: 'Portland, OR', useForScans: true });+ createdVaultIds.push(addr.id);+ });++ afterAll(async () => {+ for (const id of createdVaultIds) await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});+ await query(`DELETE FROM privacy_broker_cases WHERE broker_id = ANY($1)`, [[brokerId, emailBrokerId]]).catch(() => {});+ await query(`DELETE FROM privacy_brokers WHERE id = ANY($1)`, [[brokerId, emailBrokerId]]).catch(() => {});+ await close();+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;+ else process.env.PRIVACY_VAULT_KEY = originalKey;+ });++ it('emailLane drives a found case found → submitted in the ledger', async () => {+ const kase = await brokers.recordScanVerdict(emailBrokerId, 'found', { evidence: { listing_urls: ['https://test-optout.example/p/jane'] }, found: true });+ const broker = await brokers.getBroker(emailBrokerId);+ const payload = { full_name: 'Jane Q Testcase', email: '[email protected]', city: 'Portland', state: 'OR' };+ const disclosed = svc.computeDisclosedFields(broker, payload, { listingUrls: ['https://test-optout.example/p/jane'] });+ const res = await svc.emailLane(broker, kase, {+ disclosedFields: disclosed, payload, listingUrls: ['https://test-optout.example/p/jane'],+ autoApprove: false, accountsProvider: injectedAccounts, draftCreator: injectedDraftCreator, draftApprover: injectedApprover,+ });+ expect(res.outcome).toBe('submitted');+ const persisted = await brokers.getCaseForBroker(emailBrokerId);+ expect(persisted.state).toBe('submitted');+ expect(persisted.channel).toBe('email');+ expect(persisted.disclosedFields).toContain('full_name');+ });++ it('webFormLane default (auto-submit off) queues a human task in the ledger', async () => {+ const kase = await brokers.recordScanVerdict(brokerId, 'found', { evidence: {}, found: true });+ const broker = await brokers.getBroker(brokerId);+ const res = await svc.webFormLane(broker, kase, {+ disclosedFields: ['full_name'], payload: { full_name: 'Jane Q Testcase' }, listingUrls: [], autoSubmit: false,+ });+ expect(res.outcome).toBe('human_task_queued');+ const persisted = await brokers.getCaseForBroker(brokerId);+ expect(persisted.state).toBe('human_task_queued');+ });++ it('getOptOutDigest surfaces the queued human task with its playbook', async () => {+ const digest = await svc.getOptOutDigest();+ const item = digest.items.find((i) => i.brokerId === brokerId);+ expect(item).toBeTruthy();+ expect(item.playbook).toEqual(['step 1']);+ expect(item.optoutUrl).toBe('https://test-optout.example/optout');+ });++ it('verification advances submitted → verification_pending → confirmed_removed', async () => {+ // The email broker case is `submitted`. A trusted confirmation email advances it.+ const messagesProvider = async () => ({ messages: [{ id: 'm1', subject: 'Confirm your opt-out request', body: 'Click https://test-optout.example/confirm?t=1 to complete your removal.' }] });+ const advance = await svc.runVerificationPass({+ messagesProvider,+ removalProbe: async () => ({ skipped: true, reason: 'inconclusive' }),+ });+ expect(advance.advanced.some((a) => a.brokerId === emailBrokerId)).toBe(true);+ expect((await brokers.getCaseForBroker(emailBrokerId)).state).toBe('verification_pending');++ // A verifying re-scan that finds nothing → confirmed_removed (only path).+ const confirm = await svc.runVerificationPass({+ messagesProvider: async () => ({ messages: [] }),+ removalProbe: async (broker) => (broker.id === emailBrokerId ? { verdict: 'not_found' } : { skipped: true }),+ });+ expect(confirm.confirmed.some((c) => c.brokerId === emailBrokerId)).toBe(true);+ expect((await brokers.getCaseForBroker(emailBrokerId)).state).toBe('confirmed_removed');+ });+});diff --git a/server/services/privacyOptOut.js b/server/services/privacyOptOut.jsnew file mode 100644index 0000000000..add35af54e--- /dev/null+++ b/server/services/privacyOptOut.js@@ -0,0 +1,541 @@+/**+ * Data-broker opt-out AUTOMATION engine (issue #2145, epic #2138).+ *+ * Drives broker CASES (privacyBrokers.js ledger) through removal on top of the+ * Phase 5 scan/case backbone. Two submission lanes + a verification loop + a+ * human-task digest + a user-configured recheck schedule (privacyRecheckScheduler.js):+ *+ * - Web-form lane → browserService (real Chrome over CDP, SSRF-pinned nav).+ * Detects CAPTCHA / anti-bot walls and records `blocked` — NEVER defeats+ * them. Auto-submit is OFF by default; the default surfaces the prepared+ * request + playbook as a `human_task_queued` digest item.+ * - Email lane → renders a CCPA/CPRA/GDPR/generic rights-request template,+ * recipient LOCKED to the broker record's declared address, into the+ * messages drafts queue. Auto-send only behind the explicit settings toggle+ * `privacy.recheck.autoApproveOptOutEmails` (default false).+ * - Verification → scans the synced Gmail inbox for broker confirmation+ * mail, anti-phishing scores it (link domain must match the broker's own+ * domains) before advancing `submitted → verification_pending`, and a+ * verifying re-scan (not the confirmation page) is the ONLY path to+ * `confirmed_removed`.+ *+ * HARD GUARDRAILS (autonomy never overrides — mirrors unbroker):+ * - Disclosure is limited to the FIXED allowlist ∩ the broker's declared+ * disclosure_fields. The engine refuses to emit anything outside+ * {full_name,email,phone,city,state,dob,listing_url} regardless of what a+ * form asks. SSN / passport / financial values can never reach a broker+ * (they are never scan-eligible, so they never enter the payload).+ * - No CAPTCHA / anti-bot bypass. Hard challenges → `blocked` → digest.+ * - If a form demands more than planned mid-flow → the case goes to the digest,+ * the engine never decides to disclose extra PII.+ *+ * AI-PROVIDER POLICY: nothing here runs at boot. `runOptOutPass()` executes ONLY+ * from a user-triggered route or a user-created cron. No LLM calls in v1 (the+ * lanes are template + heuristic driven).+ */++import { join } from 'path';+import { readFile } from 'fs/promises';+import { PATHS } from '../lib/fileUtils.js';+import {+ listBrokers, getBroker, listBrokerCases, transitionCase,+} from './privacyBrokers.js';+import { listScanEligibleValues } from './privacyVault.js';+import { buildSearchVectors, probeBroker } from './privacyScan.js';+import { createDraft, approveDraft } from './messageDrafts.js';+import { listAccounts } from './messageAccounts.js';+import { getMessages } from './messageSync.js';+import { getSettings } from './settings.js';++// ─── Disclosure guardrail (pure) ────────────────────────────────────────────++// The FIXED least-disclosure allowlist — the engine never emits a field outside+// this set to a broker, whatever the broker's form or disclosure_fields asks.+export const DISCLOSURE_ALLOWLIST = Object.freeze([+ 'full_name', 'email', 'phone', 'city', 'state', 'dob', 'listing_url',+]);++/**+ * Build the disclosure payload from scan-eligible vault values. Only the fixed+ * allowlist keys are ever populated. Sensitive types can't appear because the+ * vault excludes them from scan-eligibility. `city`/`state` are parsed from the+ * most recent CURRENT address (falls back to any address). Pure.+ * Returns `{ full_name, email, phone, city, state, dob }` (listing_url is+ * per-case, added from the case evidence at send time).+ */+export function buildDisclosurePayload(scanValues = []) {+ const vectors = buildSearchVectors(scanValues);+ const payload = {};+ if (vectors.names[0]?.full) payload.full_name = vectors.names[0].full;+ if (vectors.emails[0]) payload.email = vectors.emails[0];+ if (vectors.phones[0]) payload.phone = vectors.phones[0];+ // Prefer a current address for city/state; fall back to the first parsed one.+ const loc = vectors.locations.find((l) => l.status === 'current') || vectors.locations[0];+ if (loc?.city) payload.city = loc.city;+ if (loc?.state) payload.state = loc.state;+ // DOB is scan-eligible only if the user opted it in; parse from the raw values.+ const dob = scanValues.find((v) => v.type === 'dob' && typeof v.value === 'string' && v.value.trim());+ if (dob) payload.dob = dob.value.trim();+ return payload;+}++/**+ * The fields this case may disclose to THIS broker: the fixed allowlist ∩ the+ * broker's declared disclosure_fields ∩ the fields we actually hold a value for.+ * `listing_url` is included only when the case has a captured listing URL. Pure.+ */+export function computeDisclosedFields(broker, payload, { listingUrls = [] } = {}) {+ const declared = Array.isArray(broker?.disclosureFields) ? broker.disclosureFields : [];+ const have = new Set(Object.keys(payload || {}));+ if (listingUrls.length) have.add('listing_url');+ return DISCLOSURE_ALLOWLIST.filter((f) => declared.includes(f) && have.has(f));+}++/** Human-readable one-line-per-field summary of the disclosed identifiers. Pure. */+export function renderDisclosedSummary(disclosedFields, payload, { listingUrls = [] } = {}) {+ const LABELS = {+ full_name: 'Full name', email: 'Email', phone: 'Phone',+ city: 'City', state: 'State', dob: 'Date of birth', listing_url: 'Listing URL',+ };+ return disclosedFields+ .filter((f) => f !== 'listing_url')+ .map((f) => `- ${LABELS[f]}: ${payload[f]}`)+ .concat(listingUrls.map((u) => `- ${LABELS.listing_url}: ${u}`))+ .join('\n');+}++// ─── Lane selection (pure) ──────────────────────────────────────────────────++/**+ * Choose the submission lane for a broker. `email` when the broker declares an+ * email channel and (its method is email OR we prefer the email lane for an+ * anti-bot-walled site with an email fallback). `web_form` when there's an+ * opt-out URL. Otherwise `human` (fax / phone / mail / gov-ID → digest). Pure.+ */+export function chooseLane(broker) {+ const optout = broker?.optout || {};+ const hasEmail = typeof optout.email === 'string' && optout.email.includes('@');+ const hasUrl = typeof optout.url === 'string' && /^https?:\/\//i.test(optout.url);+ if (optout.method === 'email') return hasEmail ? 'email' : 'human';+ // An anti-bot-walled form with an email fallback goes the email route (a web+ // submission would just hit the wall → blocked).+ if (broker?.antibot && hasEmail) return 'email';+ if (hasUrl) return 'web_form';+ if (hasEmail) return 'email';+ return 'human';+}++/**+ * Which template a broker's email lane uses. CCPA/CPRA for a CA-registry or+ * CCPA-noted broker, GDPR when the notes mention it, else generic. Pure — the+ * caller passes the disclosure payload so a CA-address subject prefers CCPA.+ */+export function chooseEmailTemplate(broker, payload = {}) {+ const notes = `${broker?.optout?.notes || ''}`.toLowerCase();+ if (notes.includes('gdpr')) return 'gdpr';+ if (notes.includes('cpra')) return 'cpra';+ if (notes.includes('ccpa') || broker?.source === 'ca_registry' || payload.state === 'CA') return 'ccpa';+ return 'generic';+}++// ─── Email template rendering ───────────────────────────────────────────────++const TEMPLATE_NAMES = Object.freeze(['ccpa', 'cpra', 'gdpr', 'generic']);+const templateCache = new Map();++async function loadTemplate(name) {+ const key = TEMPLATE_NAMES.includes(name) ? name : 'generic';+ if (templateCache.has(key)) return templateCache.get(key);+ const path = join(PATHS.root, 'data.reference', 'privacy', 'email-templates', `${key}.txt`);+ const raw = await readFile(path, 'utf8');+ templateCache.set(key, raw);+ return raw;+}++/** Fill `{{token}}` placeholders. Pure. Unknown tokens collapse to ''. */+export function fillTemplate(raw, tokens) {+ return String(raw).replace(/\{\{(\w+)\}\}/g, (_, k) => (tokens[k] ?? ''));+}++/**+ * Render an opt-out email into `{ subject, body }`. The first "Subject:" line of+ * the template becomes the subject; the remainder is the body. Recipient is NOT+ * decided here — the caller locks it to the broker's declared address.+ */+export async function renderOptOutEmail({ broker, payload, disclosedFields, listingUrls = [], now = new Date(), templateLoader = loadTemplate }) {+ const templateName = chooseEmailTemplate(broker, payload);+ const raw = await templateLoader(templateName);+ const disclosedSummary = renderDisclosedSummary(disclosedFields, payload, { listingUrls });+ const listingSection = listingUrls.length+ ? `The specific listing(s) to remove:\n${listingUrls.map((u) => ` ${u}`).join('\n')}\n`+ : '';+ const filled = fillTemplate(raw, {+ fullName: payload.full_name || 'the requesting individual',+ brokerName: broker?.name || broker?.id || 'the data broker',+ disclosedSummary,+ listingSection,+ requestDate: now.toISOString().slice(0, 10),+ });+ const lines = filled.split('\n');+ const subjectLine = lines.find((l) => l.toLowerCase().startsWith('subject:'));+ const subject = subjectLine ? subjectLine.replace(/^subject:\s*/i, '').trim() : `Opt-out request — ${broker?.name || broker?.id}`;+ const body = lines.filter((l) => l !== subjectLine).join('\n').trim();+ return { subject, body, templateName };+}++// ─── Verification anti-phishing scoring (pure) ──────────────────────────────++// Extract every http(s) link host from an email body.+function extractLinkHosts(text) {+ const hosts = new Set();+ const re = /https?:\/\/([^/\s"'>)]+)/gi;+ let m;+ // eslint-disable-next-line no-cond-assign+ while ((m = re.exec(String(text || ''))) !== null) {+ hosts.add(m[1].toLowerCase().replace(/^www\./, ''));+ }+ return [...hosts];+}++// The broker's own domains, from its urls.* + optout.url + optout.email.+export function brokerDomains(broker) {+ const domains = new Set();+ const addUrl = (u) => {+ if (typeof u !== 'string') return;+ const host = extractLinkHosts(u)[0];+ if (host) domains.add(host.replace(/^www\./, ''));+ };+ for (const u of Object.values(broker?.urls || {})) addUrl(u);+ addUrl(broker?.optout?.url);+ const email = broker?.optout?.email;+ if (typeof email === 'string' && email.includes('@')) {+ domains.add(email.split('@')[1].toLowerCase().replace(/^www\./, ''));+ }+ return [...domains];+}++// Registrable-ish suffix match: the link host equals a broker domain or is a+// subdomain of it (foo.spokeo.com matches spokeo.com).+function hostMatchesDomain(host, domain) {+ return host === domain || host.endsWith(`.${domain}`);+}++/**+ * Score a candidate inbox message as a genuine broker confirmation. A message+ * is trusted ONLY when it carries a link whose host matches one of the broker's+ * declared domains (anti-phishing) AND its text reads like a confirmation.+ * Returns `{ isConfirmation, hasVerificationLink, verificationUrl, score, reason }`.+ * Pure.+ */+export function scoreVerificationEmail(message, broker) {+ const domains = brokerDomains(broker);+ const text = `${message?.subject || ''}\n${message?.body || message?.snippet || ''}`;+ const lower = text.toLowerCase();+ const links = extractLinkHosts(text);+ const bodyForUrls = `${message?.body || message?.snippet || ''}`;+ const urlMatches = (String(bodyForUrls).match(/https?:\/\/[^\s"'>)]+/gi) || []);++ const matchingUrl = urlMatches.find((u) => {+ const host = extractLinkHosts(u)[0];+ return host && domains.some((d) => hostMatchesDomain(host, d));+ }) || null;+ const domainMatch = links.some((h) => domains.some((d) => hostMatchesDomain(h, d)));++ const confirmWords = ['confirm', 'verify', 'verification', 'opt-out', 'opt out', 'removal', 'suppress', 'unsubscribe', 'request received'];+ const looksLikeConfirmation = confirmWords.some((w) => lower.includes(w));+ const verificationWords = ['click', 'confirm your', 'verify your', 'to complete', 'confirmation link'];+ const hasVerificationLink = Boolean(matchingUrl) && verificationWords.some((w) => lower.includes(w));++ let score = 0;+ if (domainMatch) score += 0.6;+ if (looksLikeConfirmation) score += 0.3;+ if (hasVerificationLink) score += 0.1;++ return {+ isConfirmation: domainMatch && looksLikeConfirmation,+ hasVerificationLink,+ verificationUrl: hasVerificationLink ? matchingUrl : null,+ score: Math.round(score * 100) / 100,+ reason: !domainMatch ? 'no_domain_match' : (!looksLikeConfirmation ? 'not_confirmation_text' : 'ok'),+ };+}++// ─── Lane executors (side-effecting; injectable) ────────────────────────────++/**+ * WEB-FORM lane. Default-safe: prepares the request and queues it as a human+ * task with the playbook + prepared disclosure, UNLESS auto-submit is enabled.+ * When enabled, it SSRF-pin-navigates the opt-out URL, detects an anti-bot wall+ * (→ `blocked`, never defeated) and otherwise records `submitted` with screenshot+ * evidence. A form that demands more than planned mid-flow → `human_task_queued`+ * (never discloses extra PII). Deps injectable so the run loop is testable.+ */+export async function webFormLane(broker, kase, { disclosedFields, payload, listingUrls, autoSubmit = false, probe = null, now = new Date() }) {+ const optoutUrl = broker?.optout?.url;+ const evidence = {+ lane: 'web_form', optout_url: optoutUrl || null,+ playbook: broker?.optout?.playbook || [], disclosed: disclosedFields,+ };+ // Default (auto-submit off): surface as a human task — the user runs the+ // playbook with the prepared identifiers. Honest, and never touches a CAPTCHA.+ if (!autoSubmit || !optoutUrl) {+ await transitionCase(kase.id, 'human_task_queued', {+ channel: 'web_form', disclosedFields, evidence: { ...evidence, requires: 'manual_submit' },+ reason: !optoutUrl ? 'no_optout_url' : 'auto_submit_disabled', now,+ });+ return { caseId: kase.id, lane: 'web_form', outcome: 'human_task_queued' };+ }+ // Auto-submit path: probe the page (injectable — real impl drives CDP).+ const result = probe ? await probe(optoutUrl, { broker, disclosedFields, payload, listingUrls }).catch((e) => ({ outcome: 'error', error: e?.message })) : { outcome: 'unavailable' };+ if (result.outcome === 'blocked') {+ // `blocked` is only reachable from a settled SCAN verdict (found / indirect /+ // not_found). A `reappeared` case can't transition straight to blocked, so it+ // goes to the digest as a human task with the wall reason instead — same+ // net effect (a person must act), and it never trips the state machine.+ const canBlock = ['found', 'indirect_exposure', 'not_found'].includes(kase.state);+ const to = canBlock ? 'blocked' : 'human_task_queued';+ await transitionCase(kase.id, to, { channel: 'web_form', reason: 'antibot_wall', evidence: { ...evidence, ...result.evidence }, now });+ return { caseId: kase.id, lane: 'web_form', outcome: to };+ }+ if (result.outcome === 'submitted') {+ await transitionCase(kase.id, 'optout_in_progress', { channel: 'web_form', disclosedFields, evidence, now });+ const submitted = await transitionCase(kase.id, 'submitted', { channel: 'web_form', evidence: { ...evidence, screenshot: result.screenshot || null, confirmation: result.confirmation || null }, now });+ return { caseId: kase.id, lane: 'web_form', outcome: 'submitted', case: submitted };+ }+ // Unexpected extra challenge / unavailable → human digest, no extra disclosure.+ await transitionCase(kase.id, 'human_task_queued', { channel: 'web_form', disclosedFields, evidence: { ...evidence, requires: 'manual_submit', probe: result.outcome }, reason: result.outcome === 'error' ? 'probe_error' : 'needs_human', now });+ return { caseId: kase.id, lane: 'web_form', outcome: 'human_task_queued' };+}++/**+ * EMAIL lane. Renders the rights-request template, LOCKS the recipient to the+ * broker's declared address, and creates a `draft` in the messages queue.+ * Auto-approve+send only when `autoApprove` (settings toggle) is on. Transitions+ * the case `optout_in_progress → submitted`. Deps injectable.+ */+export async function emailLane(broker, kase, {+ disclosedFields, payload, listingUrls = [], autoApprove = false, now = new Date(),+ accountsProvider = listAccounts, draftCreator = createDraft, draftApprover = approveDraft, sender = null,+}) {+ const to = broker?.optout?.email;+ if (typeof to !== 'string' || !to.includes('@')) {+ await transitionCase(kase.id, 'human_task_queued', { channel: 'email', reason: 'no_broker_email', now });+ return { caseId: kase.id, lane: 'email', outcome: 'human_task_queued' };+ }+ const accounts = await accountsProvider();+ const account = accounts.find((a) => a.type === 'gmail') ?? accounts[0];+ if (!account) {+ await transitionCase(kase.id, 'human_task_queued', { channel: 'email', reason: 'no_message_account', now });+ return { caseId: kase.id, lane: 'email', outcome: 'human_task_queued' };+ }+ const { subject, body, templateName } = await renderOptOutEmail({ broker, payload, disclosedFields, listingUrls, now });+ const draft = await draftCreator({+ accountId: account.id,+ to: [to], // recipient LOCKED to the broker's declared address+ subject,+ body,+ generatedBy: 'privacy-optout',+ sendVia: account.type === 'gmail' ? 'api' : 'playwright',+ });++ await transitionCase(kase.id, 'optout_in_progress', { channel: 'email', disclosedFields, evidence: { lane: 'email', to, template: templateName, draftId: draft.id, disclosed: disclosedFields }, now });++ let sent = false;+ if (autoApprove) {+ // Standing-authorization auto-send (settings opt-in). Approve then dispatch.+ await draftApprover(draft.id);+ if (sender) {+ const res = await sender(draft.id).catch((e) => ({ success: false, error: e?.message }));+ sent = Boolean(res?.success);+ }+ }+ const submitted = await transitionCase(kase.id, 'submitted', {+ channel: 'email',+ evidence: { lane: 'email', to, template: templateName, draftId: draft.id, autoApproved: autoApprove, sent, disclosed: disclosedFields },+ now,+ });+ return { caseId: kase.id, lane: 'email', outcome: 'submitted', draftId: draft.id, autoApproved: autoApprove, sent, case: submitted };+}++// ─── Planner (pure) ─────────────────────────────────────────────────────────++// States the opt-out pass acts on for a NEW submission. `found`/`indirect_exposure`+// are the actionable exposures; a `reappeared` case (re-listed after removal) is+// re-worked too.+const SUBMITTABLE = new Set(['found', 'indirect_exposure', 'reappeared']);+// States whose verification the pass polls forward.+const VERIFY_POLL = new Set(['submitted', 'verification_pending', 'awaiting_processing']);++/**+ * Order the actionable cases: cluster PARENTS first (one suppression covers the+ * children), then `found` before `indirect_exposure`, then by broker name. Pure.+ * `casesWithBroker` is `[{ case, broker }]`.+ */+export function planOptOutActions(casesWithBroker = []) {+ const submit = casesWithBroker.filter(({ case: c }) => SUBMITTABLE.has(c.state));+ const verify = casesWithBroker.filter(({ case: c }) => VERIFY_POLL.has(c.state));+ const stateRank = { found: 0, reappeared: 0, indirect_exposure: 1 };+ submit.sort((a, b) => {+ const pa = a.broker?.clusterParent ? 1 : 0;+ const pb = b.broker?.clusterParent ? 1 : 0;+ if (pa !== pb) return pa - pb; // parents (no clusterParent) first+ const ra = stateRank[a.case.state] ?? 2;+ const rb = stateRank[b.case.state] ?? 2;+ if (ra !== rb) return ra - rb;+ return String(a.broker?.name || '').localeCompare(String(b.broker?.name || ''));+ });+ return { submit, verify };+}++// ─── Verification pass ──────────────────────────────────────────────────────++/**+ * Poll the synced inbox for a broker confirmation for each `submitted` case and+ * advance it to `verification_pending` (anti-phishing gated). Then a verifying+ * re-scan of `verification_pending`/`awaiting_processing` cases decides+ * `confirmed_removed` (not_found) — the ONLY path to that state — leaving a+ * still-listed case in place. Deps injectable (no network in tests).+ */+export async function runVerificationPass({+ now = new Date(), messagesProvider = getMessages, removalProbe = probeBroker, probeDeps = {},+} = {}) {+ const cases = await listBrokerCases();+ const advanced = [];+ const confirmed = [];+ // 1. submitted → verification_pending when a trusted confirmation email exists.+ const submitted = cases.filter((c) => c.state === 'submitted');+ if (submitted.length) {+ const inbox = await messagesProvider({ limit: 200 }).catch(() => ({ messages: [] }));+ const messages = inbox?.messages || [];+ for (const c of submitted) {+ const broker = await getBroker(c.brokerId);+ if (!broker) continue;+ const hit = messages.map((m) => ({ m, s: scoreVerificationEmail(m, broker) })).find(({ s }) => s.isConfirmation);+ if (hit) {+ await transitionCase(c.id, 'verification_pending', {+ channel: c.channel || undefined,+ evidence: { ...(c.evidence || {}), verification: { messageId: hit.m.id, url: hit.s.verificationUrl, score: hit.s.score } },+ now,+ });+ advanced.push({ caseId: c.id, brokerId: c.brokerId, verificationUrl: hit.s.verificationUrl });+ }+ }+ }+ // 2. verifying re-scan → confirmed_removed (not_found only) for verification_pending/awaiting_processing.+ const toVerify = (await listBrokerCases()).filter((c) => c.state === 'verification_pending' || c.state === 'awaiting_processing');+ if (toVerify.length) {+ const scanValues = await listScanEligibleValues();+ const vectors = buildSearchVectors(scanValues);+ for (const c of toVerify) {+ const broker = await getBroker(c.brokerId);+ if (!broker) continue;+ // READ-ONLY probe (no ledger write) — a raw scan verdict is gated out of+ // opt-out-owned states, so probeBroker classifies the CURRENT listing+ // without touching the case. `not_found` is the ONLY path to confirmed.+ const probed = await removalProbe(broker, vectors, probeDeps).catch(() => null);+ if (probed && !probed.skipped && probed.verdict === 'not_found') {+ await transitionCase(c.id, 'confirmed_removed', { viaRescan: true, evidence: { ...(c.evidence || {}), verifiedRemovedAt: now.toISOString() }, now });+ confirmed.push({ caseId: c.id, brokerId: c.brokerId });+ }+ }+ }+ console.log(`✅ Verification pass: ${advanced.length} advanced, ${confirmed.length} confirmed removed`);+ return { advanced, confirmed };+}++// ─── Main run loop ──────────────────────────────────────────────────────────++/**+ * Run one opt-out pass. USER-TRIGGERED (route) or USER-SCHEDULED (cron) ONLY.+ * Order (per design): refresh already handled by scan; here we (1) submit+ * `found` cluster-parents-first via the chosen lane, (2) email `indirect_exposure`,+ * (3) poll verifications, (4) leave `blocked`/`human_task_queued` for the digest.+ *+ * Reads submission autonomy from settings (`privacy.recheck.autoApproveOptOutEmails`,+ * `privacy.recheck.autoSubmitWebForms`, both default OFF). Deps injectable.+ */+export async function runOptOutPass({+ now = new Date(), settingsProvider = getSettings, deps = {}, runVerification = true,+} = {}) {+ const settings = await settingsProvider();+ const recheck = settings?.privacy?.recheck || {};+ const autoApprove = recheck.autoApproveOptOutEmails === true;+ const autoSubmit = recheck.autoSubmitWebForms === true;++ const scanValues = await listScanEligibleValues();+ const payload = buildDisclosurePayload(scanValues);+ if (!payload.full_name) {+ console.log('📋 Opt-out pass aborted: no scan-eligible name in the vault');+ return { submitted: [], skipped: 0, verification: null, reason: 'no_disclosure_identity' };+ }++ const [brokers, cases] = await Promise.all([listBrokers({ enabled: true }), listBrokerCases()]);+ const brokerById = new Map(brokers.map((b) => [b.id, b]));+ const casesWithBroker = cases+ .map((c) => ({ case: c, broker: brokerById.get(c.brokerId) }))+ .filter((x) => x.broker);+ const { submit } = planOptOutActions(casesWithBroker);++ const submitted = [];+ let skipped = 0;+ for (const { case: kase, broker } of submit) {+ const listingUrls = Array.isArray(kase.evidence?.listing_urls) ? kase.evidence.listing_urls : [];+ const disclosedFields = computeDisclosedFields(broker, payload, { listingUrls });+ const lane = chooseLane(broker);+ if (lane === 'human') {+ await transitionCase(kase.id, 'human_task_queued', { reason: 'human_only_channel', channel: broker.optout?.method || 'unknown', now });+ submitted.push({ caseId: kase.id, brokerId: broker.id, lane: 'human', outcome: 'human_task_queued' });+ continue;+ }+ if (disclosedFields.filter((f) => f !== 'listing_url').length === 0) {+ // Nothing safe to disclose — don't submit an empty request.+ skipped += 1;+ continue;+ }+ const result = lane === 'email'+ ? await emailLane(broker, kase, { disclosedFields, payload, listingUrls, autoApprove, now, ...(deps.email || {}) })+ : await webFormLane(broker, kase, { disclosedFields, payload, listingUrls, autoSubmit, now, ...(deps.webForm || {}) });+ submitted.push({ brokerId: broker.id, ...result });+ }++ const verification = runVerification+ ? await runVerificationPass({ now, ...(deps.verification || {}) })+ : null;++ console.log(`📋 Opt-out pass: ${submitted.length} actioned, ${skipped} skipped (autoApprove=${autoApprove}, autoSubmit=${autoSubmit})`);+ return { submitted, skipped, verification, autonomy: { autoApprove, autoSubmit } };+}++// ─── Human-task digest ──────────────────────────────────────────────────────++/**+ * Aggregate the cases that need a human: `human_task_queued` (auto-submit off,+ * fax/phone/gov-ID channels, mid-flow surprises) and `blocked` (anti-bot walls).+ * Each item carries the broker, the reason, the prepared disclosure, and the+ * playbook so the UI digest is an actionable checklist. Read-only.+ */+export async function getOptOutDigest() {+ const [human, blocked] = await Promise.all([+ listBrokerCases({ state: 'human_task_queued' }),+ listBrokerCases({ state: 'blocked' }),+ ]);+ const toItem = (c) => ({+ caseId: c.id,+ brokerId: c.brokerId,+ brokerName: c.brokerName,+ state: c.state,+ reason: c.reason || null,+ channel: c.channel || null,+ disclosedFields: c.disclosedFields || [],+ optoutUrl: c.evidence?.optout_url || null,+ playbook: c.evidence?.playbook || [],+ nextRecheckAt: c.nextRecheckAt,+ });+ const items = [...human.map(toItem), ...blocked.map(toItem)];+ return {+ total: items.length,+ humanTasks: human.length,+ blocked: blocked.length,+ items,+ };+}diff --git a/server/services/privacyOptOut.test.js b/server/services/privacyOptOut.test.jsnew file mode 100644index 0000000000..60e620272f--- /dev/null+++ b/server/services/privacyOptOut.test.js@@ -0,0 +1,319 @@+/**+ * Pure-logic + injectable-dep tests for the opt-out automation engine+ * (issue #2145): disclosure guardrail, lane selection, template rendering,+ * anti-phishing verification scoring, planner ordering, and the lane/run-loop+ * wiring. No network / DB — privacyBrokers transitions + the message/vault/scan+ * services are mocked so the orchestration is exercised without Postgres.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const transitionCase = vi.fn(async (id, to, patch) => ({ id, state: to, ...patch }));+const listBrokers = vi.fn(async () => []);+const listBrokerCases = vi.fn(async () => []);+const getBroker = vi.fn(async () => null);++vi.mock('./privacyBrokers.js', () => ({+ transitionCase,+ listBrokers,+ listBrokerCases,+ getBroker,+ getCaseForBroker: vi.fn(async () => null),+}));+vi.mock('./privacyVault.js', () => ({ listScanEligibleValues: vi.fn(async () => []) }));+vi.mock('./privacyScan.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, probeBroker: vi.fn(async () => ({ skipped: true, reason: 'inconclusive' })) };+});+const createDraft = vi.fn(async (d) => ({ id: 'draft-1', status: 'draft', ...d }));+const approveDraft = vi.fn(async () => ({ id: 'draft-1', status: 'approved' }));+vi.mock('./messageDrafts.js', () => ({ createDraft, approveDraft }));+vi.mock('./messageAccounts.js', () => ({ listAccounts: vi.fn(async () => [{ id: 'acct-1', type: 'gmail' }]) }));+vi.mock('./messageSync.js', () => ({ getMessages: vi.fn(async () => ({ messages: [] })) }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({ privacy: { recheck: {} } })) }));++const {+ DISCLOSURE_ALLOWLIST, buildDisclosurePayload, computeDisclosedFields, renderDisclosedSummary,+ chooseLane, chooseEmailTemplate, fillTemplate, renderOptOutEmail,+ brokerDomains, scoreVerificationEmail, planOptOutActions,+ emailLane, webFormLane, runOptOutPass, runVerificationPass, getOptOutDigest,+} = await import('./privacyOptOut.js');+const scan = await import('./privacyScan.js');+const settings = await import('./settings.js');++beforeEach(() => {+ vi.clearAllMocks();+ transitionCase.mockImplementation(async (id, to, patch) => ({ id, state: to, ...patch }));+ listBrokers.mockResolvedValue([]);+ listBrokerCases.mockResolvedValue([]);+ getBroker.mockResolvedValue(null);+ createDraft.mockImplementation(async (d) => ({ id: 'draft-1', status: 'draft', ...d }));+ settings.getSettings.mockResolvedValue({ privacy: { recheck: {} } });+});++const SCAN_VALUES = [+ { 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' },+];++describe('buildDisclosurePayload', () => {+ it('populates only allowlisted keys from vault scan values', () => {+ const p = buildDisclosurePayload(SCAN_VALUES);+ expect(p).toEqual({ full_name: 'Jane Q Doe', email: '[email protected]', phone: '+1 503 555 0100', city: 'Portland', state: 'OR' });+ for (const k of Object.keys(p)) expect(DISCLOSURE_ALLOWLIST).toContain(k);+ });+ it('prefers a current address for city/state', () => {+ const p = buildDisclosurePayload([+ { type: 'legal_name', value: 'A B' },+ { type: 'address', value: 'Salem, OR', status: 'previous' },+ { type: 'address', value: 'Austin, TX', status: 'current' },+ ]);+ expect(p.city).toBe('Austin');+ expect(p.state).toBe('TX');+ });+ it('includes dob only when present as a scan value', () => {+ const p = buildDisclosurePayload([...SCAN_VALUES, { type: 'dob', value: '1990-01-01' }]);+ expect(p.dob).toBe('1990-01-01');+ });+});++describe('computeDisclosedFields — allowlist ∩ broker ∩ available', () => {+ const payload = { full_name: 'Jane Q Doe', email: '[email protected]', phone: '1', city: 'Portland', state: 'OR' };+ it('intersects the fixed allowlist with the broker declared fields we hold', () => {+ const broker = { disclosureFields: ['full_name', 'city', 'state', 'email', 'listing_url'] };+ expect(computeDisclosedFields(broker, payload)).toEqual(['full_name', 'email', 'city', 'state']);+ });+ it('adds listing_url only when the case has one', () => {+ const broker = { disclosureFields: ['full_name', 'listing_url'] };+ expect(computeDisclosedFields(broker, payload)).toEqual(['full_name']);+ expect(computeDisclosedFields(broker, payload, { listingUrls: ['https://x/1'] })).toEqual(['full_name', 'listing_url']);+ });+ it('never emits a field outside the allowlist even if the broker asks', () => {+ const broker = { disclosureFields: ['full_name', 'ssn', 'passport', 'mothers_maiden'] };+ const withEvil = { ...payload, ssn: '123', passport: 'X' };+ expect(computeDisclosedFields(broker, withEvil)).toEqual(['full_name']);+ });+});++describe('chooseLane', () => {+ it('email method with an address → email', () => {+ expect(chooseLane({ optout: { method: 'email', email: '[email protected]' } })).toBe('email');+ });+ it('web_form method with a url → web_form', () => {+ expect(chooseLane({ optout: { method: 'web_form', url: 'https://b.com/optout' } })).toBe('web_form');+ });+ it('anti-bot walled form with an email fallback → email', () => {+ expect(chooseLane({ antibot: true, optout: { method: 'web_form', url: 'https://b.com/o', email: '[email protected]' } })).toBe('email');+ });+ it('no channel → human', () => {+ expect(chooseLane({ optout: { method: 'fax' } })).toBe('human');+ });+});++describe('chooseEmailTemplate', () => {+ it('CA-address subject → ccpa', () => {+ expect(chooseEmailTemplate({ optout: { notes: '' } }, { state: 'CA' })).toBe('ccpa');+ });+ it('gdpr note wins', () => {+ expect(chooseEmailTemplate({ optout: { notes: 'Use the GDPR lane' } })).toBe('gdpr');+ });+ it('default generic', () => {+ expect(chooseEmailTemplate({ optout: { notes: '' } }, { state: 'OR' })).toBe('generic');+ });+});++describe('fillTemplate + renderOptOutEmail', () => {+ it('fills tokens and collapses unknowns', () => {+ expect(fillTemplate('Hi {{a}} / {{missing}}', { a: 'X' })).toBe('Hi X / ');+ });+ it('splits subject from body and injects disclosure', async () => {+ const templateLoader = async () => 'Subject: Opt-out for {{fullName}}\n\nBody\n{{disclosedSummary}}\n';+ const out = await renderOptOutEmail({+ broker: { name: 'Spokeo', disclosureFields: ['full_name', 'email'] },+ payload: { full_name: 'Jane Q Doe', email: '[email protected]' },+ disclosedFields: ['full_name', 'email'],+ templateLoader,+ now: new Date('2026-07-08T00:00:00Z'),+ });+ expect(out.subject).toBe('Opt-out for Jane Q Doe');+ expect(out.body).toContain('Full name: Jane Q Doe');+ expect(out.body).toContain('Email: [email protected]');+ expect(out.body).not.toMatch(/^Subject:/m);+ });+});++describe('brokerDomains + scoreVerificationEmail (anti-phishing)', () => {+ const broker = { urls: { home: 'https://www.spokeo.com' }, optout: { url: 'https://www.spokeo.com/optout', email: '[email protected]' } };+ it('collects the broker domains', () => {+ expect(brokerDomains(broker)).toContain('spokeo.com');+ });+ it('trusts a confirmation email with a matching link domain', () => {+ const msg = { subject: 'Confirm your opt-out', body: 'Please click https://www.spokeo.com/confirm?t=abc to complete your removal.' };+ const s = scoreVerificationEmail(msg, broker);+ expect(s.isConfirmation).toBe(true);+ expect(s.verificationUrl).toContain('spokeo.com/confirm');+ });+ it('rejects a look-alike phishing domain', () => {+ const msg = { subject: 'Confirm your opt-out', body: 'Click https://spokeo-confirm.evil.com/x to complete.' };+ const s = scoreVerificationEmail(msg, broker);+ expect(s.isConfirmation).toBe(false);+ expect(s.reason).toBe('no_domain_match');+ });+ it('rejects a matching-domain email that is not a confirmation', () => {+ const msg = { subject: 'Your weekly newsletter', body: 'News from https://www.spokeo.com/blog' };+ expect(scoreVerificationEmail(msg, broker).isConfirmation).toBe(false);+ });+});++describe('planOptOutActions ordering', () => {+ it('cluster parents first, then found before indirect, then by name', () => {+ const cwb = [+ { case: { state: 'indirect_exposure' }, broker: { name: 'Zeta', clusterParent: null } },+ { case: { state: 'found' }, broker: { name: 'Beta', clusterParent: 'parent' } },+ { case: { state: 'found' }, broker: { name: 'Alpha', clusterParent: null } },+ ];+ const { submit } = planOptOutActions(cwb);+ expect(submit.map((s) => s.broker.name)).toEqual(['Alpha', 'Zeta', 'Beta']);+ });+ it('splits verify-poll states out', () => {+ const cwb = [+ { case: { state: 'submitted' }, broker: { name: 'A' } },+ { case: { state: 'found' }, broker: { name: 'B' } },+ ];+ const { submit, verify } = planOptOutActions(cwb);+ expect(submit).toHaveLength(1);+ expect(verify).toHaveLength(1);+ });+});++describe('emailLane', () => {+ const broker = { id: 'mylife', name: 'MyLife', optout: { method: 'email', email: '[email protected]' }, disclosureFields: ['full_name', 'email'] };+ const payload = { full_name: 'Jane Q Doe', email: '[email protected]' };+ it('creates a draft locked to the broker address and transitions to submitted', async () => {+ const res = await emailLane(broker, { id: 'c1' }, { disclosedFields: ['full_name', 'email'], payload, autoApprove: false });+ expect(res.outcome).toBe('submitted');+ expect(createDraft).toHaveBeenCalledWith(expect.objectContaining({ to: ['[email protected]'], generatedBy: 'privacy-optout' }));+ expect(approveDraft).not.toHaveBeenCalled();+ const states = transitionCase.mock.calls.map((c) => c[1]);+ expect(states).toEqual(['optout_in_progress', 'submitted']);+ });+ it('auto-approves + sends when the toggle is on', async () => {+ const sender = vi.fn(async () => ({ success: true }));+ const res = await emailLane(broker, { id: 'c1' }, { disclosedFields: ['full_name', 'email'], payload, autoApprove: true, sender });+ expect(approveDraft).toHaveBeenCalledWith('draft-1');+ expect(sender).toHaveBeenCalledWith('draft-1');+ expect(res.sent).toBe(true);+ });+ it('queues a human task when the broker has no email', async () => {+ const res = await emailLane({ id: 'x', optout: {} }, { id: 'c1' }, { disclosedFields: ['full_name'], payload });+ expect(res.outcome).toBe('human_task_queued');+ });+});++describe('webFormLane', () => {+ const broker = { id: 'spokeo', name: 'Spokeo', optout: { method: 'web_form', url: 'https://www.spokeo.com/optout', playbook: ['step 1'] }, disclosureFields: ['full_name', 'email', 'listing_url'] };+ it('default (auto-submit off) → human_task_queued with the playbook', async () => {+ const res = await webFormLane(broker, { id: 'c1' }, { disclosedFields: ['full_name'], payload: {}, listingUrls: [], autoSubmit: false });+ expect(res.outcome).toBe('human_task_queued');+ expect(transitionCase).toHaveBeenCalledWith('c1', 'human_task_queued', expect.objectContaining({ channel: 'web_form' }));+ });+ it('auto-submit + anti-bot wall → blocked (never defeated)', async () => {+ const probe = vi.fn(async () => ({ outcome: 'blocked', evidence: { wall: 'captcha' } }));+ const res = await webFormLane(broker, { id: 'c1', state: 'found' }, { disclosedFields: ['full_name'], payload: {}, listingUrls: [], autoSubmit: true, probe });+ expect(res.outcome).toBe('blocked');+ });+ it('a reappeared case that hits a wall → human_task_queued (state machine safe)', async () => {+ const probe = vi.fn(async () => ({ outcome: 'blocked' }));+ const res = await webFormLane(broker, { id: 'c1', state: 'reappeared' }, { disclosedFields: ['full_name'], payload: {}, listingUrls: [], autoSubmit: true, probe });+ expect(res.outcome).toBe('human_task_queued');+ });+ it('auto-submit success → submitted', async () => {+ const probe = vi.fn(async () => ({ outcome: 'submitted', screenshot: 's.png' }));+ const res = await webFormLane(broker, { id: 'c1' }, { disclosedFields: ['full_name'], payload: {}, listingUrls: [], autoSubmit: true, probe });+ expect(res.outcome).toBe('submitted');+ const states = transitionCase.mock.calls.map((c) => c[1]);+ expect(states).toEqual(['optout_in_progress', 'submitted']);+ });+});++describe('runOptOutPass', () => {+ it('aborts when there is no scan-eligible name', async () => {+ const vault = await import('./privacyVault.js');+ vault.listScanEligibleValues.mockResolvedValueOnce([]);+ const res = await runOptOutPass({ runVerification: false });+ expect(res.reason).toBe('no_disclosure_identity');+ });+ it('routes a found email-broker through the email lane', async () => {+ const vault = await import('./privacyVault.js');+ vault.listScanEligibleValues.mockResolvedValue(SCAN_VALUES);+ listBrokers.mockResolvedValue([{ id: 'mylife', name: 'MyLife', optout: { method: 'email', email: '[email protected]' }, disclosureFields: ['full_name', 'email'], clusterParent: null }]);+ listBrokerCases.mockResolvedValue([{ id: 'c1', brokerId: 'mylife', state: 'found', evidence: {} }]);+ const res = await runOptOutPass({ runVerification: false });+ expect(res.submitted[0].lane).toBe('email');+ expect(res.submitted[0].outcome).toBe('submitted');+ });+ it('reads autonomy toggles from settings', async () => {+ const vault = await import('./privacyVault.js');+ vault.listScanEligibleValues.mockResolvedValue(SCAN_VALUES);+ settings.getSettings.mockResolvedValue({ privacy: { recheck: { autoApproveOptOutEmails: true, autoSubmitWebForms: true } } });+ listBrokers.mockResolvedValue([]);+ listBrokerCases.mockResolvedValue([]);+ const res = await runOptOutPass({ runVerification: false });+ expect(res.autonomy).toEqual({ autoApprove: true, autoSubmit: true });+ });+});++describe('runVerificationPass', () => {+ it('advances submitted → verification_pending on a trusted confirmation', async () => {+ const broker = { id: 'spokeo', urls: { home: 'https://www.spokeo.com' }, optout: { url: 'https://www.spokeo.com/optout' } };+ getBroker.mockResolvedValue(broker);+ listBrokerCases+ .mockResolvedValueOnce([{ id: 'c1', brokerId: 'spokeo', state: 'submitted', evidence: {} }])+ .mockResolvedValueOnce([]); // no verification_pending/awaiting to re-scan+ const messagesProvider = vi.fn(async () => ({ messages: [{ id: 'm1', subject: 'Confirm your opt-out', body: 'Click https://www.spokeo.com/confirm to complete removal.' }] }));+ const res = await runVerificationPass({ messagesProvider });+ expect(res.advanced).toHaveLength(1);+ expect(transitionCase).toHaveBeenCalledWith('c1', 'verification_pending', expect.anything());+ });+ it('confirms removal only when a read-only re-scan returns not_found', async () => {+ const broker = { id: 'spokeo', urls: { search: 'https://www.spokeo.com/{firstName}-{lastName}/{state}' } };+ getBroker.mockResolvedValue(broker);+ const vault = await import('./privacyVault.js');+ vault.listScanEligibleValues.mockResolvedValue(SCAN_VALUES);+ listBrokerCases+ .mockResolvedValueOnce([]) // no submitted+ .mockResolvedValueOnce([{ id: 'c2', brokerId: 'spokeo', state: 'awaiting_processing', evidence: {} }]);+ const removalProbe = vi.fn(async () => ({ verdict: 'not_found' }));+ const res = await runVerificationPass({ removalProbe });+ expect(res.confirmed).toHaveLength(1);+ expect(transitionCase).toHaveBeenCalledWith('c2', 'confirmed_removed', expect.objectContaining({ viaRescan: true }));+ });+ it('leaves a still-listed case untouched', async () => {+ getBroker.mockResolvedValue({ id: 'spokeo', urls: { search: 'https://www.spokeo.com/{firstName}/{state}' } });+ const vault = await import('./privacyVault.js');+ vault.listScanEligibleValues.mockResolvedValue(SCAN_VALUES);+ listBrokerCases+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([{ id: 'c3', brokerId: 'spokeo', state: 'verification_pending', evidence: {} }]);+ const removalProbe = vi.fn(async () => ({ verdict: 'found', found: true }));+ const res = await runVerificationPass({ removalProbe });+ expect(res.confirmed).toHaveLength(0);+ });+});++describe('getOptOutDigest', () => {+ it('aggregates human-task + blocked cases with playbook + reason', async () => {+ listBrokerCases.mockImplementation(async ({ state } = {}) => {+ if (state === 'human_task_queued') return [{ id: 'h1', brokerId: 'wp', brokerName: 'Whitepages', state, reason: 'auto_submit_disabled', evidence: { optout_url: 'https://wp/o', playbook: ['call back'] } }];+ if (state === 'blocked') return [{ id: 'b1', brokerId: 'rad', brokerName: 'Radaris', state, reason: 'antibot_wall', evidence: {} }];+ return [];+ });+ const digest = await getOptOutDigest();+ expect(digest.total).toBe(2);+ expect(digest.humanTasks).toBe(1);+ expect(digest.blocked).toBe(1);+ expect(digest.items[0].playbook).toEqual(['call back']);+ });+});diff --git a/server/services/privacyRecheckScheduler.js b/server/services/privacyRecheckScheduler.jsnew file mode 100644index 0000000000..9c6329747e--- /dev/null+++ b/server/services/privacyRecheckScheduler.js@@ -0,0 +1,62 @@+/**+ * Privacy broker opt-out recheck scheduler (issue #2145, epic #2138).+ *+ * Registers a cron that re-runs the exposure scan + opt-out pass + verification+ * over due broker cases. OFF by default — the user turns it on from the Privacy+ * UI (settings `privacy.recheck.enabled`). This is the SANCTIONED scheduled-+ * automation exception to the no-cold-bootstrap AI-provider policy: the user+ * explicitly configured it, so it may drive the engine (and any LLM inside it)+ * on its own schedule. Mirrors backupScheduler.js.+ *+ * The cron expression is locked in at registration; enabled/autonomy toggles are+ * re-read inside the handler so a Settings save takes effect on the next run+ * without a restart.+ */++import { schedule, cancel } from './eventScheduler.js';+import { getSettings } from './settings.js';+import { getUserTimezone } from '../lib/timezone.js';+import { runScanPass } from './privacyScan.js';+import { runOptOutPass } from './privacyOptOut.js';++const EVENT_ID = 'privacy-recheck';++export async function startPrivacyRecheckScheduler() {+ const settings = await getSettings();+ const recheck = settings.privacy?.recheck || {};++ if (recheck.enabled !== true) {+ console.log('🛡️ Privacy recheck scheduler: disabled in settings — skipping');+ return;+ }++ const cronExpression = recheck.cronExpression || '0 4 * * 0'; // weekly, Sun 4am+ const timezone = await getUserTimezone();++ schedule({+ id: EVENT_ID,+ type: 'cron',+ cron: cronExpression,+ timezone,+ handler: async () => {+ const current = await getSettings();+ if (current.privacy?.recheck?.enabled !== true) {+ console.log('🛡️ Privacy recheck: disabled since registration — skipping run');+ return;+ }+ console.log('🛡️ Privacy recheck: running scheduled scan + opt-out pass');+ // Scan first (re-checks due cases + finds new exposure), then work the+ // cases. Both are read-settings-driven and safe to re-run (idempotent).+ await runScanPass();+ await runOptOutPass();+ },+ metadata: { source: 'privacyRecheckScheduler' },+ });++ console.log(`🛡️ Privacy recheck scheduler: registered at cron "${cronExpression}"`);+}++export function stopPrivacyRecheckScheduler() {+ cancel(EVENT_ID);+ console.log('🛡️ Privacy recheck scheduler: stopped');+}diff --git a/server/services/privacyScan.js b/server/services/privacyScan.jsindex b4b9a170b0..c6ee2ba4fb 100644--- a/server/services/privacyScan.js+++ b/server/services/privacyScan.js@@ -208,15 +208,15 @@ async function httpFetchLane(url, fetchImpl) {}/**- * 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.+ * READ-ONLY probe of ONE broker for exposure — fetch + classify, NO ledger+ * write. Returns `{ verdict, found, evidence, url }` or `{ skipped, reason }`.+ * Shared by scanBroker (which then records) and the opt-out verification+ * re-scan (privacyOptOut.runVerificationPass) which must classify a broker's+ * CURRENT listing WITHOUT overwriting an opt-out-owned case's ledger state.+ * `deps` injectable so tests/verification never hit the network.*/-export async function scanBroker(broker, vectors, {- fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(),+export async function probeBroker(broker, vectors, {+ fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe,} = {}) {const template = broker?.urls?.search;const name = (vectors.names || [])[0];@@ -229,7 +229,7 @@ export async function scanBroker(broker, vectors, {return { skipped: true, reason: 'unsafe_or_unfillable_url' };}- let result = await httpFetchLane(url, fetchImpl);+ const result = await httpFetchLane(url, fetchImpl);let html = result?.html ?? '';let status = result?.status ?? null;@@ -240,17 +240,34 @@ export async function scanBroker(broker, vectors, {}if (!result && !html) {- // Total network failure — inconclusive, leave case unscanned.+ // Total network failure — inconclusive.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' };+ return { skipped: true, reason: classified.evidence?.match_basis || 'inconclusive', verdict: null, evidence };}- const kase = await recordScanVerdict(broker.id, classified.verdict, {- evidence, found: classified.found ?? null, now,+ return { verdict: classified.verdict, found: classified.found ?? null, evidence, url };+}++/**+ * Scan ONE broker for exposure and record the verdict. Thin wrapper over the+ * read-only probeBroker that then writes the ledger 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 probed = await probeBroker(broker, vectors, { fetchImpl, browserFetch, urlSafe });+ if (probed.skipped) return { skipped: true, reason: probed.reason };+ const kase = await recordScanVerdict(broker.id, probed.verdict, {+ evidence: probed.evidence, found: probed.found ?? null, now,});return kase;}diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 8563660ffb..063ba8ebd3 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -16,6 +16,7 @@ export const DB_TEST_INCLUDE = ['services/privacyOrgs.db.test.js','services/privacyChanges.db.test.js','services/privacyBrokers.db.test.js',+ 'services/privacyOptOut.db.test.js','services/catalogCanonProjection.test.js','services/catalogRefResolver.test.js','services/creativeDirector/projectsDB.test.js',