Skip to content

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

feat: scope the Privacy Center by household subject, with an engine-enforced consent gate (#3658)

[._.]/ Adam Eivy2e0c093dc8c5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dffda3d187..d9a3f4c99e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,4 +47,6 @@
- **Peer-sync pull requests now honor the per-peer sharing settings the push direction already respected.** `GET /api/peer-sync/record` served any subscribable record by id with no notion of who was asking, so a peer configured for "universes only" — or one with sync switched off entirely — could still read every series, media collection, and writers-room record; the record/library/CoS-history/CoS-task manifests and the CoS agent-archive bytes had the same shape. Every outbound hop now identifies this install with an `X-PortOS-Instance-Id` header attached centrally in `peerFetch`, and the receiver resolves that id against its peer registry and runs the *same* `peerAllowsOutbound` + `peerHasCategory` predicates the push path uses, so the two directions can't drift apart again. Because peers upgrade independently this ships warn-first: a pull from an unidentified, unknown, or disallowed caller is still served and logs one `⚠️` per caller per restart. The new **Settings → Sharing → "Enforce per-peer sharing settings on pull requests"** toggle (`federation.strictPullAuthorization`, default off) turns those into a 403 — the default flips in a later release once peers have had time to update. Note that the instance id is *identification*, not authentication; the instance password remains the actual access control.
+- **The Privacy Center can now hold more than one person — with consent enforced by the engine, not the UI.** Everything in the suite (vault records, organizations, holdings, change-of-address events, broker cases, consent rows) is now scoped to a *household subject*, so a partner, child or parent you have permission to act for gets their own vault and their own broker opt-out ledger, worked independently of yours. Adding someone requires recording *how* their consent was captured (verbal, written, signed form, guardian, power of attorney), and the exposure-scan and opt-out engines **refuse** to scan or submit for a subject with no consent on file — a hard 403 in the service, so a scheduled recheck, a direct API call or a future agent path is refused exactly like a hidden button would be. Deleting a subject is a hard delete that removes everything of theirs, and the `self` subject can't be deleted. Existing installs are unaffected: a `self` subject is seeded, every existing row backfills to it, and every endpoint still defaults to it, so an install that never adds a second person behaves exactly as before. The Digital Twin's privacy context and the org cross-link stay scoped to `self` — a household member's data never enters a prompt. This is the multi-person half of #2148; it stays machine-local like the rest of the Privacy Center, with no federation.
+
- A `/do:review` (or `/do:scan`, `/do:plan-task`, `/do:replan`) run queued from the **CoS quick templates** is no longer failed as `idle-no-changes`. The deliverable posture each slashdo workflow declares on its catalog entry reached the Agent Operations buttons but was silently dropped by the quick-template form, which read only the three run-shape toggles off a template's settings block — so the exact clean-tree misfire that posture exists to prevent still happened from the other surface. The flag now rides the template through the form as hidden state and into the create-task payload, and the strict template-settings schema accepts it so a user can save such a template back without a 400.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 381eccc7f6..5f0aa44e79 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -38,7 +38,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine Phase 1, #2657): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record (brief / schedule / generation / feedback / capped `runs[]`) in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. **Intentionally machine-local — never federated** (a synced schedule would double-run on every peer, same rationale as `seriesAutopilotScheduler`): NO `sync_sequence` and NO `deleted`/`deleted_at` tombstone — deletes are hard deletes, mirroring `tribe`. Phase 2 will split the machine-local *schedule* from a federatable *brief/feedback* record before adding any sync hook. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
-- `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
+- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)
diff --git a/docs/decisions/2026-08-08-privacy-records-machine-local.md b/docs/decisions/2026-08-08-privacy-records-machine-local.md
index 0a4f37f0af..d7161930c3 100644
--- a/docs/decisions/2026-08-08-privacy-records-machine-local.md
+++ b/docs/decisions/2026-08-08-privacy-records-machine-local.md
@@ -15,7 +15,7 @@
The Privacy Center (epic #2138) shipped Phases 1–8: an AES-256-GCM encrypted PII
vault, a trusted-organization registry with per-field holdings, a
change-of-address inventory, and an unbroker-style data-broker opt-out engine.
-All eight tables (`privacy_vault_records`, `privacy_consents`, `privacy_orgs`,
+All nine tables (`privacy_subjects`, `privacy_vault_records`, `privacy_consents`, `privacy_orgs`,
`privacy_org_holdings`, `privacy_change_events`, `privacy_brokers`,
`privacy_broker_cases`) are `db-primary` PostgreSQL and machine-local.
diff --git a/scripts/migrations/235-privacy-household-subjects.js b/scripts/migrations/235-privacy-household-subjects.js
new file mode 100644
index 0000000000..98ec572a01
--- /dev/null
+++ b/scripts/migrations/235-privacy-household-subjects.js
@@ -0,0 +1,35 @@
+/**
+ * Registration stub for the Privacy Center household-subjects slice (issue
+ * #3658, epic #2138).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS privacy_subjects`, the seeded
+ * `self` row + its consent row, and the `subject_id` ADD COLUMN / backfill /
+ * SET DEFAULT / SET NOT NULL sweep across `privacy_vault_records`,
+ * `privacy_orgs`, `privacy_org_holdings`, `privacy_change_events`,
+ * `privacy_broker_cases`, and `privacy_consents` — is idempotent and lives in
+ * `server/lib/db/schema/privacy.js` (run by `ensureSchema()` at boot) plus the
+ * fresh-install seed `server/scripts/init-db.sql`.
+ *
+ * It cannot live here: the `scripts/migrations/` runner executes BEFORE the DB
+ * pool is initialized, which is the same reason migrations 048–052, 108,
+ * 160/161/162, 176, and 178 are boot-time + stub-registered.
+ *
+ * This stub exists so the change is *registered the standard way* — it lands in
+ * `data/migrations.applied.json` so the migration ledger and `git log` show when
+ * multi-subject scoping was introduced.
+ *
+ * Backward compatibility: every pre-existing row backfills to the seeded `self`
+ * subject and every `subject_id` column defaults to it, so an install that never
+ * adds a second household member sees no behavioral change. The one widening
+ * that is NOT purely additive is the broker-case uniqueness index, which moves
+ * from `(broker_id)` to `(broker_id, subject_id)` — the boot DDL drops the old
+ * single-column index and creates the pair index after `subject_id` exists.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('👥 privacy_subjects: table + subject_id scoping applied idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/db/schema/privacy.js b/server/lib/db/schema/privacy.js
index e95d4733f9..af77c625c3 100644
--- a/server/lib/db/schema/privacy.js
+++ b/server/lib/db/schema/privacy.js
@@ -1,7 +1,56 @@
-// Privacy-suite DDL — vault records, consents, orgs, org holdings, brokers,
-// broker cases, and change events. Extracted verbatim from ensureSchemaImpl()
-// in server/lib/db.js (#2832); idempotent, runs on every boot.
+// Privacy-suite DDL — household subjects, vault records, consents, orgs, org
+// holdings, brokers, broker cases, and change events. Extracted verbatim from
+// ensureSchemaImpl() in server/lib/db.js (#2832); idempotent, runs on every boot.
+//
+// The seeded `self` subject. A FIXED uuid (not a random one) so the DDL below,
+// server/scripts/init-db.sql, and server/lib/privacyValidation.js's
+// SELF_SUBJECT_ID all name the same row on every install without a lookup.
+// Mirrors PRIVACY_SELF_SUBJECT_ID in server/lib/privacyValidation.js — change
+// both or neither.
+const SELF_SUBJECT_ID = '00000000-0000-4000-8000-000000000001';
+
+// The privacy tables that carry a `subject_id` scope column (issue #3658).
+// Each gets: ADD COLUMN IF NOT EXISTS → backfill NULLs to `self` → SET DEFAULT
+// → SET NOT NULL. All four steps are idempotent, so an existing install picks
+// the column up at boot and a fresh install (where the CREATE TABLE body below
+// already declares it) no-ops through them.
+const SUBJECT_SCOPED_TABLES = [
+ 'privacy_vault_records',
+ 'privacy_orgs',
+ 'privacy_org_holdings',
+ 'privacy_change_events',
+ 'privacy_broker_cases',
+ 'privacy_consents',
+];
+
+const subjectScopeUpgrades = SUBJECT_SCOPED_TABLES.flatMap((table) => [
+ `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS subject_id UUID REFERENCES privacy_subjects (id) ON DELETE CASCADE`,
+ `UPDATE ${table} SET subject_id = '${SELF_SUBJECT_ID}' WHERE subject_id IS NULL`,
+ `ALTER TABLE ${table} ALTER COLUMN subject_id SET DEFAULT '${SELF_SUBJECT_ID}'`,
+ `ALTER TABLE ${table} ALTER COLUMN subject_id SET NOT NULL`,
+]);
+
export const privacyDdl = [
+ // ─── Privacy Center: household subjects (issue #3658) ────────────────────
+ // Every person the Privacy Center works on behalf of — `self` plus any
+ // consenting household member (partner, child, parent). A TABLE rather than
+ // a free-text `subject` string so renames aren't lossy and scoping stays
+ // typed. Machine-local like the rest of the suite: no federation, no
+ // tombstones, hard deletes (which CASCADE the subject's vault/org/holding/
+ // change/case/consent rows). Created FIRST so the FKs below resolve.
+ `CREATE TABLE IF NOT EXISTS privacy_subjects (
+ id UUID PRIMARY KEY,
+ display_name TEXT NOT NULL,
+ relationship TEXT NOT NULL DEFAULT 'other',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // Seed the `self` row at a fixed id. Idempotent — an install that has
+ // already renamed it keeps its own display_name.
+ `INSERT INTO privacy_subjects (id, display_name, relationship, created_at, updated_at)
+ VALUES ('${SELF_SUBJECT_ID}', 'Me', 'self', NOW(), NOW())
+ ON CONFLICT (id) DO NOTHING`,
+
// ─── Privacy Center: PII Vault (issue #2140, epic #2138) ─────────────────
// Encrypted-at-rest identity facts. `value_enc` is AES-256-GCM ciphertext
// (`v1:<iv>:<tag>:<ct>`, key from PRIVACY_VAULT_KEY — lib/vaultCrypto.js);
@@ -16,6 +65,7 @@ export const privacyDdl = [
// init-db.sql.
`CREATE TABLE IF NOT EXISTS privacy_vault_records (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
type TEXT NOT NULL,
label TEXT NOT NULL DEFAULT '',
value_enc TEXT NOT NULL,
@@ -31,13 +81,18 @@ export const privacyDdl = [
)`,
// Type is the primary list filter (all addresses, all emails, ...).
`CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_records (type)`,
- // Explicit consent audit rows (v1 subject is always 'self'); the broker
- // opt-out engine builds on this trail. Append-only.
+ // Explicit consent audit rows, one per subject; the broker opt-out engine
+ // builds on this trail and REFUSES to act for a subject with no row here
+ // (privacySubjects.assertSubjectConsent, #3658). Append-only. The legacy
+ // free-text `subject` column is kept for the historical audit trail —
+ // `subject_id` is the FK the engine and every query scope on.
`CREATE TABLE IF NOT EXISTS privacy_consents (
id UUID PRIMARY KEY,
subject TEXT NOT NULL DEFAULT 'self',
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
scope TEXT NOT NULL,
method TEXT NOT NULL,
+ note TEXT NOT NULL DEFAULT '',
granted_at TIMESTAMPTZ DEFAULT NOW()
)`,
@@ -52,6 +107,7 @@ export const privacyDdl = [
// Mirrors the privacy blocks in init-db.sql.
`CREATE TABLE IF NOT EXISTS privacy_orgs (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'other',
website TEXT NOT NULL DEFAULT '',
@@ -71,6 +127,7 @@ export const privacyDdl = [
// its holdings rows.
`CREATE TABLE IF NOT EXISTS privacy_org_holdings (
org_id UUID NOT NULL REFERENCES privacy_orgs (id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'current',
noted_at TIMESTAMPTZ DEFAULT NOW(),
@@ -121,6 +178,7 @@ export const privacyDdl = [
// cascades its cases.
`CREATE TABLE IF NOT EXISTS privacy_broker_cases (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
state TEXT NOT NULL DEFAULT 'unscanned',
found BOOLEAN,
@@ -132,9 +190,13 @@ export const privacyDdl = [
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)`,
+ // One live case per (broker, subject) — two household members are worked
+ // through the same broker independently, so the uniqueness that used to be
+ // on `broker_id` alone is now on the pair (#3658). The single-column index
+ // is dropped so an existing install can widen without a manual step; the
+ // pair index is created by subjectScopeUpgrades below, AFTER `subject_id`
+ // exists on the table.
+ `DROP INDEX IF EXISTS idx_privacy_broker_cases_broker`,
// "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)`,
@@ -150,6 +212,7 @@ export const privacyDdl = [
// Mirrors the block in init-db.sql.
`CREATE TABLE IF NOT EXISTS privacy_change_events (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
kind TEXT NOT NULL DEFAULT 'other',
@@ -159,4 +222,29 @@ export const privacyDdl = [
// "Changes touching this record" — the inventory groups by the old record.
`CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id)`,
+ // ─── Household-subject scope upgrade (issue #3658) ───────────────────────
+ // Runs LAST: the CREATE TABLE bodies above already carry `subject_id` on a
+ // fresh install, so these are no-ops there. On an existing install they add
+ // the column, backfill every pre-existing row to `self`, and lock it down.
+ // Free-text context for a consent row (who witnessed it, where the signed
+ // form lives). Added with the table's subject scope (#3658).
+ `ALTER TABLE privacy_consents ADD COLUMN IF NOT EXISTS note TEXT NOT NULL DEFAULT ''`,
+ ...subjectScopeUpgrades,
+ // `self` always consents — the install owner IS the self subject, so the
+ // engine guard must never refuse them. Written once (guarded by NOT EXISTS)
+ // so an install that predates #3658 and never created a vault record still
+ // has a consent row, and so re-running the DDL never appends duplicates.
+ `INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)
+ SELECT gen_random_uuid(), '${SELF_SUBJECT_ID}', 'pii_vault', 'self',
+ 'seeded: the install owner is the self subject', NOW()
+ WHERE NOT EXISTS (SELECT 1 FROM privacy_consents WHERE subject_id = '${SELF_SUBJECT_ID}')`,
+ // Now that `subject_id` exists on the case ledger, the per-(broker,subject)
+ // uniqueness the scan/opt-out upsert relies on.
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker_subject ON privacy_broker_cases (broker_id, subject_id)`,
+ // "Every record for subject X" — the primary list filter once a second
+ // household member exists.
+ `CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_subject ON privacy_vault_records (subject_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_subject ON privacy_orgs (subject_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_change_events_subject ON privacy_change_events (subject_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_consents_subject ON privacy_consents (subject_id)`,
];
diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.js
index 4338b90acb..00df324ec3 100644
--- a/server/lib/privacyValidation.js
+++ b/server/lib/privacyValidation.js
@@ -17,6 +17,70 @@ const SAFE_URL_MESSAGE = 'must be an http(s) URL';
// imports keep working; the lib barrel also namespace-exports this module as
// `privacyValidation`.
+// =============================================================================
+// HOUSEHOLD SUBJECTS (issue #3658)
+// =============================================================================
+// The Privacy Center works on behalf of one or more consenting people. `self`
+// is a seeded row at a FIXED uuid so the DDL (server/lib/db/schema/privacy.js),
+// the fresh-install seed (server/scripts/init-db.sql), and the services all
+// name the same row without a lookup — change all three or none.
+export const PRIVACY_SELF_SUBJECT_ID = '00000000-0000-4000-8000-000000000001';
+
+export const PRIVACY_SUBJECT_RELATIONSHIPS = Object.freeze([
+ 'self', 'partner', 'child', 'parent', 'dependent', 'other',
+]);
+
+// How a subject's consent was captured. Carried verbatim from unbroker's
+// no-consent-no-action rule: the engine refuses to scan or submit for a subject
+// without at least one consent row, so this is an audit fact, not a UI label.
+export const PRIVACY_CONSENT_METHODS = Object.freeze([
+ 'self', 'verbal', 'written', 'signed_form', 'guardian', 'power_of_attorney', 'other',
+]);
+
+// Scope of a consent row. `pii_vault` is what the v1 vault-create path already
+// writes; `broker_optout` narrows to the removal engine. The guard treats ANY
+// row for the subject as active consent (no revocation column exists — a
+// revoked subject is deleted, which hard-deletes their records).
+export const PRIVACY_CONSENT_SCOPES = Object.freeze(['pii_vault', 'broker_optout']);
+
+// A subject reference on an existing input/query. Optional everywhere — omitted
+// means `self`, so every pre-#3658 client keeps working unchanged.
+const subjectIdField = { subjectId: z.string().uuid().optional() };
+
+// The bare subject-scope query (`?subjectId=`) shared by every read endpoint
+// that carries no other filter — status readouts, the change list, the digest.
+export const privacySubjectScopeQuerySchema = z.object({
+ subjectId: z.string().uuid().optional(),
+ limit: z.string().optional(),
+ offset: z.string().optional(),
+}).strict();
+
+export const privacySubjectCreateSchema = z.object({
+ displayName: z.string().trim().min(1).max(200),
+ relationship: z.enum(PRIVACY_SUBJECT_RELATIONSHIPS).optional(),
+ // REQUIRED: a household member may not exist in the vault without a recorded
+ // consent method. The service writes the consent row in the same transaction.
+ consentMethod: z.enum(PRIVACY_CONSENT_METHODS),
+ consentNote: z.string().max(2000).optional(),
+}).strict();
+
+export const privacySubjectUpdateSchema = z.object({
+ displayName: z.string().trim().min(1).max(200).optional(),
+ relationship: z.enum(PRIVACY_SUBJECT_RELATIONSHIPS).optional(),
+}).strict();
+
+export const privacySubjectIdParamsSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
+// POST /api/privacy/subjects/:id/consents — record a further consent (e.g. the
+// subject agreed to broker opt-outs after being added for vault records only).
+export const privacySubjectConsentSchema = z.object({
+ scope: z.enum(PRIVACY_CONSENT_SCOPES).optional(),
+ method: z.enum(PRIVACY_CONSENT_METHODS),
+ note: z.string().max(2000).optional(),
+}).strict();
+
export const PRIVACY_VAULT_TYPES = Object.freeze([
'legal_name', 'address', 'phone', 'email', 'dob',
'ssn', 'passport', 'drivers_license', 'financial_account', 'custom',
@@ -72,6 +136,7 @@ export const privacyVaultCreateSchema = z.object({
shareWithTwin: z.boolean().optional(),
useForScans: z.boolean().optional(),
notes: z.string().max(5000).optional(),
+ ...subjectIdField,
}).strict().superRefine(rejectSensitiveScans);
// PUT is a partial update. `type` is immutable (it drives masking + scan
@@ -91,6 +156,7 @@ export const privacyVaultUpdateSchema = z.object({
export const privacyVaultListQuerySchema = z.object({
type: z.enum(PRIVACY_VAULT_TYPES).optional(),
+ ...subjectIdField,
...paginationQueryFields,
}).strict();
@@ -134,6 +200,7 @@ export const privacyOrgCreateSchema = z.object({
contact: privacyOrgContactSchema.optional(),
socialAccountId: z.string().max(200).nullable().optional(),
notes: z.string().max(5000).optional(),
+ ...subjectIdField,
}).strict();
// PUT is a partial update — every field optional, same shape otherwise.
@@ -152,6 +219,7 @@ export const privacyOrgListQuerySchema = z.object({
trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),
status: z.enum(PRIVACY_ORG_STATUSES).optional(),
category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),
+ ...subjectIdField,
...paginationQueryFields,
}).strict();
@@ -211,6 +279,11 @@ export const privacyChangeDeclareSchema = z.object({
{ message: 'provide either replacement or replacementRecordId, not both', path: ['replacement'] },
);
+// GET /api/privacy/changes?subjectId= — a change event inherits its subject from
+// the OLD vault record, so there is no subjectId on the DECLARE body; it only
+// filters the list.
+export const privacyChangeListQuerySchema = privacySubjectScopeQuerySchema;
+
export const privacyChangeIdParamsSchema = z.object({
id: z.string().uuid(),
}).strict();
@@ -250,6 +323,7 @@ export const privacyBrokerListQuerySchema = z.object({
// GET /api/privacy/broker-cases?state=found
export const privacyBrokerCaseListQuerySchema = z.object({
state: z.enum(PRIVACY_BROKER_CASE_STATES).optional(),
+ ...subjectIdField,
...paginationQueryFields,
}).strict();
@@ -290,6 +364,7 @@ export const privacyCaseTransitionSchema = z.object({
// POST /api/privacy/scan — optional concurrency knob.
export const privacyScanStartSchema = z.object({
concurrency: z.number().int().min(1).max(6).optional(),
+ ...subjectIdField,
}).strict();
// =============================================================================
@@ -304,10 +379,11 @@ export const privacyScanStartSchema = z.object({
// true) folds the verification poll into the same pass.
export const privacyOptOutPassSchema = z.object({
runVerification: z.boolean().optional(),
+ ...subjectIdField,
}).strict();
// POST /api/privacy/optout/verify — run only the verification pass. No body.
-export const privacyOptOutVerifySchema = z.object({}).strict();
+export const privacyOptOutVerifySchema = z.object({ ...subjectIdField }).strict();
// A basic 5-field cron expression validator (minute hour dom month dow). Kept
// permissive (tokens can be `*`, numbers, ranges, lists, steps) — the scheduler
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index 50d93e85db..a1c2eb82ef 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -2,6 +2,10 @@
* Privacy Center Routes — encrypted PII Vault + Trusted Organizations
* registry REST surface (issues #2140, #2141).
*
+ * Every record-bearing endpoint is scoped to ONE household subject via an
+ * optional `?subjectId=` (list/read) or body `subjectId` (create). Omitting it
+ * means the seeded `self` subject, so every pre-#3658 client keeps working.
+ *
* Mounted at /api/privacy. Vault list/read responses carry `maskedValue`
* only — `value_enc` and plaintext never leave the service except through
* the ONE explicit reveal endpoint. Org holdings responses join the vault's
@@ -12,6 +16,12 @@ import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';
import {
+ privacySubjectCreateSchema,
+ privacySubjectUpdateSchema,
+ privacySubjectIdParamsSchema,
+ privacySubjectConsentSchema,
+ privacyChangeListQuerySchema,
+ privacySubjectScopeQuerySchema,
privacyVaultCreateSchema,
privacyVaultUpdateSchema,
privacyVaultListQuerySchema,
@@ -36,6 +46,16 @@ import {
privacyOptOutVerifySchema,
privacyRecheckConfigSchema,
} from '../lib/privacyValidation.js';
+import {
+ listSubjects,
+ getSubject,
+ createSubject,
+ updateSubject,
+ deleteSubject,
+ listSubjectConsents,
+ recordConsent,
+ assertSubject,
+} from '../services/privacySubjects.js';
import {
createVaultRecord,
listVaultRecords,
@@ -82,13 +102,66 @@ import {
const router = Router();
-router.get('/status', asyncHandler(async (_req, res) => {
- res.json(await getVaultStatus());
+// ─── Household subjects (issue #3658) ──────────────────────────────────────
+// The people the Privacy Center works on behalf of. `self` is seeded and
+// undeletable; every other subject requires a recorded consent method at
+// creation, and the scan/opt-out engines refuse to act without one.
+
+router.get('/subjects', asyncHandler(async (_req, res) => {
+ res.json(await listSubjects());
+}));
+
+router.post('/subjects', asyncHandler(async (req, res) => {
+ const data = validateRequest(privacySubjectCreateSchema, req.body);
+ res.status(201).json(await createSubject(data));
+}));
+
+router.get('/subjects/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
+ const subject = await getSubject(id);
+ if (!subject) throw new ServerError('Privacy subject not found', { status: 404, code: 'SUBJECT_NOT_FOUND' });
+ res.json(subject);
+}));
+
+router.put('/subjects/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
+ const patch = validateRequest(privacySubjectUpdateSchema, req.body);
+ res.json(await updateSubject(id, patch));
+}));
+
+// Hard DELETE — cascades the subject's vault records, orgs, holdings, change
+// events, broker cases, and consent rows (machine-local, no tombstones).
+router.delete('/subjects/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
+ res.json(await deleteSubject(id));
+}));
+
+router.get('/subjects/:id/consents', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
+ await assertSubject(id);
+ res.json(await listSubjectConsents(id));
+}));
+
+// Append a further consent row (e.g. the subject later agreed to broker
+// opt-outs). Append-only — there is no revoke endpoint: revoking consent means
+// deleting the subject, which hard-deletes their records.
+router.post('/subjects/:id/consents', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
+ const { scope, method, note } = validateRequest(privacySubjectConsentSchema, req.body);
+ await assertSubject(id);
+ res.status(201).json(await recordConsent({
+ subjectId: id, scope: scope ?? 'pii_vault', method, note,
+ }));
+}));
+
+router.get('/status', asyncHandler(async (req, res) => {
+ const { subjectId } = validateRequest(privacySubjectScopeQuerySchema, req.query);
+ res.json(await getVaultStatus({ subjectId }));
}));
router.get('/vault', asyncHandler(async (req, res) => {
- const { type } = validateRequest(privacyVaultListQuerySchema, req.query);
- const records = await listVaultRecords({ type });
+ const { type, subjectId } = validateRequest(privacyVaultListQuerySchema, req.query);
+ const records = await listVaultRecords({ type, subjectId });
if (!isPaginationRequested(req.query)) return res.json(records);
res.json(paginateArray(records, req.query, { defaultLimit: 50, maxLimit: 500 }));
}));
@@ -175,7 +248,8 @@ router.put('/orgs/:id/holdings', asyncHandler(async (req, res) => {
// ─── Change-of-address events + inventory workflow (issue #2143) ────────────
router.get('/changes', asyncHandler(async (req, res) => {
- const events = await listChangeEvents();
+ const { subjectId } = validateRequest(privacyChangeListQuerySchema, req.query);
+ const events = await listChangeEvents({ subjectId });
if (!isPaginationRequested(req.query)) return res.json(events);
res.json(paginateArray(events, req.query, { defaultLimit: 50, maxLimit: 500 }));
}));
@@ -230,8 +304,8 @@ router.put('/brokers/:id', asyncHandler(async (req, res) => {
}));
router.get('/broker-cases', asyncHandler(async (req, res) => {
- const { state } = validateRequest(privacyBrokerCaseListQuerySchema, req.query);
- const cases = await listBrokerCases({ state });
+ const { state, subjectId } = validateRequest(privacyBrokerCaseListQuerySchema, req.query);
+ const cases = await listBrokerCases({ state, subjectId });
if (!isPaginationRequested(req.query)) return res.json(cases);
res.json(paginateArray(cases, req.query, { defaultLimit: 50, maxLimit: 500 }));
}));
@@ -251,14 +325,15 @@ router.post('/broker-cases/:id/transition', asyncHandler(async (req, res) => {
res.json(await transitionCase(id, toState, reason === undefined ? {} : { reason }));
}));
-router.get('/scan/status', asyncHandler(async (_req, res) => {
- res.json(await getScanStatus());
+router.get('/scan/status', asyncHandler(async (req, res) => {
+ const { subjectId } = validateRequest(privacySubjectScopeQuerySchema, req.query);
+ res.json(await getScanStatus({ subjectId }));
}));
// 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 } : {}));
+ const { concurrency, subjectId } = validateRequest(privacyScanStartSchema, req.body ?? {});
+ res.json(await runScanPass({ ...(concurrency ? { concurrency } : {}), subjectId }));
}));
// ─── Opt-out automation engine (issue #2145) ───────────────────────────────
@@ -267,20 +342,24 @@ router.post('/scan', asyncHandler(async (req, res) => {
// (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 }));
+ const { runVerification, subjectId } = validateRequest(privacyOptOutPassSchema, req.body ?? {});
+ res.json(await runOptOutPass({
+ ...(runVerification === undefined ? {} : { runVerification }),
+ subjectId,
+ }));
}));
// 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());
+ const { subjectId } = validateRequest(privacyOptOutVerifySchema, req.body ?? {});
+ res.json(await runVerificationPass({ subjectId }));
}));
// 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());
+router.get('/optout/digest', asyncHandler(async (req, res) => {
+ const { subjectId } = validateRequest(privacySubjectScopeQuerySchema, req.query);
+ res.json(await getOptOutDigest({ subjectId }));
}));
// Recheck-schedule status: enabled, cron, autonomy toggles, next fire time.
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index b358fd5b9f..ad591b5fdc 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -72,7 +72,21 @@ vi.mock('../services/privacyChanges.js', () => ({
draftUpdateEmail: vi.fn(async () => ({ draftId: 'draft-1', status: 'draft' })),
}));
+// Household subjects (#3658) — mocked so the route layer is exercised without a DB.
+const SELF = '00000000-0000-4000-8000-000000000001';
+vi.mock('../services/privacySubjects.js', () => ({
+ listSubjects: vi.fn(async () => [{ id: SELF, displayName: 'Me', relationship: 'self', isSelf: true, consentCount: 1, recordCount: 2 }]),
+ getSubject: vi.fn(async (id) => (id === SELF ? { id, displayName: 'Me', relationship: 'self', isSelf: true } : null)),
+ createSubject: vi.fn(async (input) => ({ id: 'c0ffee00-0000-4000-8000-0000000000a1', ...input, isSelf: false })),
+ updateSubject: vi.fn(async (id, patch) => ({ id, ...patch })),
+ deleteSubject: vi.fn(async () => ({ ok: true })),
+ listSubjectConsents: vi.fn(async () => [{ id: 'consent-1', scope: 'pii_vault', method: 'signed_form', note: '' }]),
+ recordConsent: vi.fn(async (input) => ({ id: 'consent-2', ...input })),
+ assertSubject: vi.fn(async (id) => ({ id })),
+}));
+
const privacyRoutes = (await import('./privacy.js')).default;
+const subjectService = await import('../services/privacySubjects.js');
const service = await import('../services/privacyVault.js');
const orgService = await import('../services/privacyOrgs.js');
const brokerService = await import('../services/privacyBrokers.js');
@@ -554,3 +568,79 @@ describe('privacy recheck schedule (#2146)', () => {
expect((await request(makeApp()).put('/api/privacy/optout/schedule').send({ bogus: 1 })).status).toBe(400);
});
});
+
+// ─── Household subjects (issue #3658) ──────────────────────────────────────
+
+describe('/api/privacy/subjects', () => {
+ it('lists subjects', async () => {
+ const res = await request(makeApp()).get('/api/privacy/subjects');
+ expect(res.status).toBe(200);
+ expect(res.body[0]).toMatchObject({ id: SELF, isSelf: true, consentCount: 1 });
+ });
+
+ it('creates a subject and REQUIRES a consent method', async () => {
+ const ok = await request(makeApp()).post('/api/privacy/subjects')
+ .send({ displayName: 'Alex Example', relationship: 'partner', consentMethod: 'signed_form' });
+ expect(ok.status).toBe(201);
+ expect(subjectService.createSubject).toHaveBeenCalledWith({
+ displayName: 'Alex Example', relationship: 'partner', consentMethod: 'signed_form',
+ });
+
+ const missing = await request(makeApp()).post('/api/privacy/subjects')
+ .send({ displayName: 'Alex Example', relationship: 'partner' });
+ expect(missing.status).toBe(400);
+
+ const bogus = await request(makeApp()).post('/api/privacy/subjects')
+ .send({ displayName: 'Alex Example', consentMethod: 'telepathy' });
+ expect(bogus.status).toBe(400);
+ });
+
+ it('404s an unknown subject on read', async () => {
+ const res = await request(makeApp()).get(`/api/privacy/subjects/${VALID_UUID}`);
+ expect(res.status).toBe(404);
+ });
+
+ it('updates and deletes a subject', async () => {
+ const put = await request(makeApp()).put(`/api/privacy/subjects/${VALID_UUID}`).send({ displayName: 'Renamed' });
+ expect(put.status).toBe(200);
+ expect(subjectService.updateSubject).toHaveBeenCalledWith(VALID_UUID, { displayName: 'Renamed' });
+
+ const del = await request(makeApp()).delete(`/api/privacy/subjects/${VALID_UUID}`);
+ expect(del.status).toBe(200);
+ expect(subjectService.deleteSubject).toHaveBeenCalledWith(VALID_UUID);
+ });
+
+ it('lists and appends consent rows', async () => {
+ const list = await request(makeApp()).get(`/api/privacy/subjects/${VALID_UUID}/consents`);
+ expect(list.status).toBe(200);
+ expect(list.body[0]).toMatchObject({ scope: 'pii_vault', method: 'signed_form' });
+
+ const post = await request(makeApp()).post(`/api/privacy/subjects/${VALID_UUID}/consents`)
+ .send({ scope: 'broker_optout', method: 'written', note: 'form on file' });
+ expect(post.status).toBe(201);
+ expect(subjectService.recordConsent).toHaveBeenCalledWith({
+ subjectId: VALID_UUID, scope: 'broker_optout', method: 'written', note: 'form on file',
+ });
+ });
+});
+
+describe('subject scoping on the existing endpoints (#3658)', () => {
+ it('threads ?subjectId= into the vault list', async () => {
+ const res = await request(makeApp()).get(`/api/privacy/vault?subjectId=${VALID_UUID}`);
+ expect(res.status).toBe(200);
+ expect(service.listVaultRecords).toHaveBeenCalledWith({ type: undefined, subjectId: VALID_UUID });
+ });
+
+ it('threads subjectId into the scan + opt-out passes', async () => {
+ await request(makeApp()).post('/api/privacy/scan').send({ subjectId: VALID_UUID });
+ expect(scanService.runScanPass).toHaveBeenCalledWith({ subjectId: VALID_UUID });
+
+ await request(makeApp()).post('/api/privacy/optout').send({ subjectId: VALID_UUID });
+ expect(optOutService.runOptOutPass).toHaveBeenCalledWith({ subjectId: VALID_UUID });
+ });
+
+ it('rejects a non-uuid subjectId at the API edge', async () => {
+ const res = await request(makeApp()).get('/api/privacy/vault?subjectId=not-a-uuid');
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 818ad0a275..0dc0be3ea1 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1128,6 +1128,29 @@ CREATE TABLE IF NOT EXISTS lora_training_runs (
CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status);
CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id);
+-- Privacy Center: household subjects (issue #3658). Every person the Privacy
+-- Center works on behalf of — `self` plus any consenting household member
+-- (partner, child, parent). A TABLE rather than a free-text `subject` string so
+-- renames aren't lossy and scoping stays typed. Machine-local like the rest of
+-- the suite: no federation, no tombstones, hard deletes (which CASCADE the
+-- subject's vault/org/holding/change/case/consent rows). Created FIRST so the
+-- `subject_id` FKs below resolve. Mirrors the privacy blocks in
+-- server/lib/db/schema/privacy.js.
+CREATE TABLE IF NOT EXISTS privacy_subjects (
+ id UUID PRIMARY KEY,
+ display_name TEXT NOT NULL,
+ relationship TEXT NOT NULL DEFAULT 'other',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+-- Seed the `self` row at a FIXED id (mirrored by SELF_SUBJECT_ID in
+-- server/lib/db/schema/privacy.js and PRIVACY_SELF_SUBJECT_ID in
+-- server/lib/privacyValidation.js) so every install names the same row without
+-- a lookup. Idempotent — an install that renamed it keeps its display_name.
+INSERT INTO privacy_subjects (id, display_name, relationship, created_at, updated_at)
+VALUES ('00000000-0000-4000-8000-000000000001', 'Me', 'self', NOW(), NOW())
+ON CONFLICT (id) DO NOTHING;
+
-- Privacy Center: PII Vault (issue #2140, epic #2138). Encrypted-at-rest
-- identity facts — `value_enc` is AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`,
-- key from PRIVACY_VAULT_KEY; see server/lib/vaultCrypto.js). Plaintext is
@@ -1141,6 +1164,7 @@ CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_run
-- app-side). Mirrors the privacy blocks in server/lib/db.js ensureSchema().
CREATE TABLE IF NOT EXISTS privacy_vault_records (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
type TEXT NOT NULL,
label TEXT NOT NULL DEFAULT '',
value_enc TEXT NOT NULL,
@@ -1161,8 +1185,10 @@ CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_type ON privacy_vault_recor
CREATE TABLE IF NOT EXISTS privacy_consents (
id UUID PRIMARY KEY,
subject TEXT NOT NULL DEFAULT 'self',
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
scope TEXT NOT NULL,
method TEXT NOT NULL,
+ note TEXT NOT NULL DEFAULT '',
granted_at TIMESTAMPTZ DEFAULT NOW()
);
@@ -1176,6 +1202,7 @@ CREATE TABLE IF NOT EXISTS privacy_consents (
-- the privacy blocks in server/lib/db.js ensureSchema().
CREATE TABLE IF NOT EXISTS privacy_orgs (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'other',
website TEXT NOT NULL DEFAULT '',
@@ -1195,6 +1222,7 @@ CREATE INDEX IF NOT EXISTS idx_privacy_orgs_status ON privacy_orgs (status);
-- holdings rows.
CREATE TABLE IF NOT EXISTS privacy_org_holdings (
org_id UUID NOT NULL REFERENCES privacy_orgs (id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'current',
noted_at TIMESTAMPTZ DEFAULT NOW(),
@@ -1241,6 +1269,7 @@ CREATE INDEX IF NOT EXISTS idx_privacy_brokers_cluster_parent ON privacy_brokers
-- its cases.
CREATE TABLE IF NOT EXISTS privacy_broker_cases (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
broker_id TEXT NOT NULL REFERENCES privacy_brokers (id) ON DELETE CASCADE,
state TEXT NOT NULL DEFAULT 'unscanned',
found BOOLEAN,
@@ -1252,8 +1281,9 @@ CREATE TABLE IF NOT EXISTS privacy_broker_cases (
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);
+-- One live case per (broker, subject) — two household members are worked
+-- through the same broker independently (#3658).
+CREATE UNIQUE INDEX IF NOT EXISTS idx_privacy_broker_cases_broker_subject ON privacy_broker_cases (broker_id, subject_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);
@@ -1269,6 +1299,7 @@ CREATE INDEX IF NOT EXISTS idx_privacy_broker_cases_recheck ON privacy_broker_ca
-- the block in server/lib/db.js ensureSchema().
CREATE TABLE IF NOT EXISTS privacy_change_events (
id UUID PRIMARY KEY,
+ subject_id UUID NOT NULL DEFAULT '00000000-0000-4000-8000-000000000001' REFERENCES privacy_subjects (id) ON DELETE CASCADE,
vault_record_id UUID NOT NULL REFERENCES privacy_vault_records (id) ON DELETE CASCADE,
replacement_record_id UUID REFERENCES privacy_vault_records (id) ON DELETE SET NULL,
kind TEXT NOT NULL DEFAULT 'other',
@@ -1277,6 +1308,18 @@ CREATE TABLE IF NOT EXISTS privacy_change_events (
);
-- "Changes touching this record" — the inventory view groups by the old record.
CREATE INDEX IF NOT EXISTS idx_privacy_change_events_vault_record ON privacy_change_events (vault_record_id);
+-- "Every record for subject X" — the primary list filter once a second
+-- household member exists (#3658).
+CREATE INDEX IF NOT EXISTS idx_privacy_vault_records_subject ON privacy_vault_records (subject_id);
+CREATE INDEX IF NOT EXISTS idx_privacy_orgs_subject ON privacy_orgs (subject_id);
+CREATE INDEX IF NOT EXISTS idx_privacy_change_events_subject ON privacy_change_events (subject_id);
+CREATE INDEX IF NOT EXISTS idx_privacy_consents_subject ON privacy_consents (subject_id);
+-- `self` always consents — the install owner IS the self subject, so the
+-- engine's no-consent-no-action guard must never refuse them (#3658).
+INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)
+SELECT gen_random_uuid(), '00000000-0000-4000-8000-000000000001', 'pii_vault', 'self',
+ 'seeded: the install owner is the self subject', NOW()
+WHERE NOT EXISTS (SELECT 1 FROM privacy_consents WHERE subject_id = '00000000-0000-4000-8000-000000000001');
-- Stacker News community stewardship. Credentials are isolated from account
-- configuration; untrusted snapshots and all review transitions are auditable.
diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.js
index 988c26cfae..5c09b442dc 100644
--- a/server/services/privacyBrokers.js
+++ b/server/services/privacyBrokers.js
@@ -28,6 +28,7 @@ import { query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
import { PATHS } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { resolveSubjectId } from './privacySubjects.js';
// Cap on each registry fetch so a hung broker source can't stall a
// user-triggered refresh indefinitely (both fetchers run under Promise.all).
@@ -401,13 +402,14 @@ export async function refreshBrokers({ fetchBadbool = defaultFetchBadbool, fetch
// ─── Case ledger ────────────────────────────────────────────────────────────
-const CASE_COLUMNS = `id, broker_id, state, found, evidence, disclosed_fields,
+const CASE_COLUMNS = `id, subject_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,
+ subjectId: row.subject_id,
brokerId: row.broker_id,
state: row.state,
// Server-derived legal manual moves for this state — the client action
@@ -427,13 +429,16 @@ function rowToCase(row) {
};
}
-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 ')}` : '';
+export async function listBrokerCases({ state, subjectId } = {}) {
+ // Always scoped to ONE subject (defaulting to `self`): two household members
+ // hold independent cases against the same broker, and the opt-out engine must
+ // never plan a submission for one using the other's ledger.
+ const params = [resolveSubjectId(subjectId)];
+ const clauses = ['c.subject_id = $1'];
+ if (state) { params.push(state); clauses.push(`c.state = ${params.length}`); }
+ const where = `WHERE ${clauses.join(' AND ')}`;
const { rows } = await query(
- `SELECT c.id, c.broker_id, c.state, c.found, c.evidence, c.disclosed_fields,
+ `SELECT c.id, c.subject_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
@@ -445,9 +450,10 @@ export async function listBrokerCases({ state } = {}) {
return rows.map(rowToCase);
}
-export async function getCaseForBroker(brokerId) {
+export async function getCaseForBroker(brokerId, { subjectId } = {}) {
const { rows } = await query(
- `SELECT ${CASE_COLUMNS} FROM privacy_broker_cases WHERE broker_id = $1`, [brokerId],
+ `SELECT ${CASE_COLUMNS} FROM privacy_broker_cases WHERE broker_id = $1 AND subject_id = $2`,
+ [brokerId, resolveSubjectId(subjectId)],
);
return rowToCase(rows[0]);
}
@@ -457,15 +463,19 @@ export async function getCaseForBroker(brokerId) {
* 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() } = {}) {
+export async function recordScanVerdict(brokerId, verdict, { evidence = {}, found = null, now = new Date(), subjectId } = {}) {
if (!SCAN_VERDICTS.includes(verdict)) {
throw new ServerError(`Not a scan verdict: "${verdict}"`, { status: 400, code: 'INVALID_SCAN_VERDICT' });
}
+ const resolvedSubjectId = resolveSubjectId(subjectId);
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' });
+ // Keyed on the (broker, subject) pair — the ledger's unique index moved to
+ // that pair in #3658 so each household member gets their own case row.
const existing = await client.query(
- `SELECT id, state FROM privacy_broker_cases WHERE broker_id = $1 FOR UPDATE`, [brokerId],
+ `SELECT id, state FROM privacy_broker_cases WHERE broker_id = $1 AND subject_id = $2 FOR UPDATE`,
+ [brokerId, resolvedSubjectId],
);
const nextRecheck = computeNextRecheckAt(verdict, now);
if (!existing.rows[0]) {
@@ -473,12 +483,12 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun
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())
+ (id, subject_id, broker_id, state, found, evidence, next_recheck_at, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), NOW())
RETURNING ${CASE_COLUMNS}`,
- [id, brokerId, verdict, found, JSON.stringify(evidence), nextRecheck],
+ [id, resolvedSubjectId, brokerId, verdict, found, JSON.stringify(evidence), nextRecheck],
);
- console.log(`🔎 Broker ${brokerId}: new case → ${verdict}`);
+ console.log(`🔎 Broker ${brokerId}: new case → ${verdict} (subject=${resolvedSubjectId})`);
return rowToCase(rows[0]);
}
// Re-scan of an existing case. A settled verdict flipping is a rescan.
@@ -486,10 +496,10 @@ export async function recordScanVerdict(brokerId, verdict, { evidence = {}, foun
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],
+ WHERE id = $5 RETURNING ${CASE_COLUMNS}`,
+ [verdict, found, JSON.stringify(evidence), nextRecheck, existing.rows[0].id],
);
- console.log(`🔎 Broker ${brokerId}: case ${existing.rows[0].state} → ${verdict}`);
+ console.log(`🔎 Broker ${brokerId}: case ${existing.rows[0].state} → ${verdict} (subject=${resolvedSubjectId})`);
return rowToCase(rows[0]);
});
}
@@ -555,21 +565,29 @@ export async function forceRecheckCase(caseId, { now = new Date() } = {}) {
* 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() } = {}) {
+export async function getScanStatus({ now = new Date(), subjectId } = {}) {
await ensureSeeded();
+ const resolvedSubjectId = resolveSubjectId(subjectId);
const [brokerCount, byState, due] = await Promise.all([
+ // The broker DATABASE is shared across subjects (it is a catalog, not
+ // per-person data) — only the CASE counts are subject-scoped.
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 state, COUNT(*)::int AS n FROM privacy_broker_cases
+ WHERE subject_id = $1 GROUP BY state`,
+ [resolvedSubjectId],
+ ),
query(
`SELECT COUNT(*)::int AS n FROM privacy_broker_cases
- WHERE next_recheck_at IS NULL OR next_recheck_at <= $1`,
- [now.toISOString()],
+ WHERE subject_id = $1 AND (next_recheck_at IS NULL OR next_recheck_at <= $2)`,
+ [resolvedSubjectId, now.toISOString()],
),
]);
const caseCounts = {};
for (const row of byState.rows) caseCounts[row.state] = row.n;
return {
enabledBrokers: brokerCount.rows[0].n,
+ subjectId: resolvedSubjectId,
caseCounts,
dueForRecheck: due.rows[0].n,
};
diff --git a/server/services/privacyChanges.js b/server/services/privacyChanges.js
index c33f0b4d0c..874f28461d 100644
--- a/server/services/privacyChanges.js
+++ b/server/services/privacyChanges.js
@@ -29,10 +29,11 @@ import { ServerError } from '../lib/errorHandler.js';
import { encryptValue, maskValue, ensureVaultKey } from '../lib/vaultCrypto.js';
import { resolveUseForScans, getVaultRecord, revealValue } from './privacyVault.js';
import { getOrg } from './privacyOrgs.js';
+import { resolveSubjectId } from './privacySubjects.js';
import { listAccounts } from './messageAccounts.js';
import { createDraft } from './messageDrafts.js';
-const EVENT_COLUMNS = `id, vault_record_id, replacement_record_id, kind, declared_at, note`;
+const EVENT_COLUMNS = `id, subject_id, vault_record_id, replacement_record_id, kind, declared_at, note`;
// Holdings statuses that make up the per-event inventory (a `current` holding is
// only relevant to a NEW record, not the change checklist).
@@ -65,6 +66,7 @@ function rowToEvent(row) {
if (!row) return null;
return {
id: row.id,
+ subjectId: row.subject_id,
vaultRecordId: row.vault_record_id,
replacementRecordId: row.replacement_record_id,
kind: row.kind,
@@ -104,8 +106,10 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
// so the transaction body is pure DB work (a replacement is encrypted inside).
if (replacement) await ensureVaultKey();
return withTransaction(async (client) => {
+ // The event inherits its subject from the OLD record — a change is always
+ // "this person's fact changed", so there is no subjectId on the input.
const { rows: oldRows } = await client.query(
- `SELECT id, type FROM privacy_vault_records WHERE id = $1 FOR UPDATE`, [vaultRecordId],
+ `SELECT id, type, subject_id FROM privacy_vault_records WHERE id = $1 FOR UPDATE`, [vaultRecordId],
);
const oldRecord = oldRows[0];
if (!oldRecord) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });
@@ -114,11 +118,19 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
let replacementId = null;
if (replacementRecordId) {
const { rows } = await client.query(
- `SELECT id FROM privacy_vault_records WHERE id = $1`, [replacementRecordId],
+ `SELECT id, subject_id FROM privacy_vault_records WHERE id = $1`, [replacementRecordId],
);
if (!rows[0]) {
throw new ServerError('Replacement vault record not found', { status: 400, code: 'REPLACEMENT_NOT_FOUND' });
}
+ // Retiring one person's address in favour of ANOTHER person's record is
+ // never a legitimate change — it would silently re-point their orgs.
+ if (rows[0].subject_id !== oldRecord.subject_id) {
+ throw new ServerError(
+ 'Replacement vault record belongs to a different privacy subject',
+ { status: 400, code: 'SUBJECT_MISMATCH' },
+ );
+ }
replacementId = replacementRecordId;
} else if (replacement) {
replacementId = randomUUID();
@@ -126,11 +138,11 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
const useForScans = resolveUseForScans(type, replacement.useForScans);
await client.query(
`INSERT INTO privacy_vault_records
- (id, type, label, value_enc, masked_value, status, valid_from, valid_to,
+ (id, subject_id, type, label, value_enc, masked_value, status, valid_from, valid_to,
share_with_twin, use_for_scans, notes, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, 'current', $6, NULL, $7, $8, $9, NOW(), NOW())`,
+ VALUES ($1, $2, $3, $4, $5, $6, 'current', $7, NULL, $8, $9, $10, NOW(), NOW())`,
[
- replacementId, type, replacement.label,
+ replacementId, oldRecord.subject_id, type, replacement.label,
encryptValue(replacement.value), maskValue(type, replacement.value),
replacement.validFrom ?? null,
replacement.shareWithTwin === true, useForScans, replacement.notes ?? '',
@@ -157,10 +169,10 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
if (replacementId) {
for (const row of flipped) {
await client.query(
- `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
- VALUES ($1, $2, 'current', NOW(), NOW())
+ `INSERT INTO privacy_org_holdings (org_id, subject_id, vault_record_id, status, noted_at, updated_at)
+ VALUES ($1, $2, $3, 'current', NOW(), NOW())
ON CONFLICT (org_id, vault_record_id) DO UPDATE SET status = 'current', updated_at = NOW()`,
- [row.org_id, replacementId],
+ [row.org_id, oldRecord.subject_id, replacementId],
);
}
}
@@ -168,10 +180,10 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
const eventId = randomUUID();
const resolvedKind = kind ?? kindForType(oldRecord.type);
const { rows: evRows } = await client.query(
- `INSERT INTO privacy_change_events (id, vault_record_id, replacement_record_id, kind, declared_at, note)
- VALUES ($1, $2, $3, $4, NOW(), $5)
+ `INSERT INTO privacy_change_events (id, subject_id, vault_record_id, replacement_record_id, kind, declared_at, note)
+ VALUES ($1, $2, $3, $4, $5, NOW(), $6)
RETURNING ${EVENT_COLUMNS}`,
- [eventId, vaultRecordId, replacementId, resolvedKind, note ?? ''],
+ [eventId, oldRecord.subject_id, vaultRecordId, replacementId, resolvedKind, note ?? ''],
);
console.log(`📮 Declared privacy change ${eventId} (kind=${resolvedKind}, orgs flipped=${flipped.length}, replacement=${replacementId ? 'yes' : 'none'})`);
return rowToEvent(evRows[0]);
@@ -179,9 +191,9 @@ export async function declareChange({ vaultRecordId, replacement, replacementRec
}
/** List all change events, newest first, with per-event progress counts + masked old/new values. */
-export async function listChangeEvents() {
+export async function listChangeEvents({ subjectId } = {}) {
const { rows } = await query(
- `SELECT e.id, e.vault_record_id, e.replacement_record_id, e.kind, e.declared_at, e.note,
+ `SELECT e.id, e.subject_id, e.vault_record_id, e.replacement_record_id, e.kind, e.declared_at, e.note,
ov.type AS old_type, ov.label AS old_label, ov.masked_value AS old_masked,
rv.type AS new_type, rv.label AS new_label, rv.masked_value AS new_masked,
COUNT(h.org_id) FILTER (WHERE h.status = 'update_pending')::int AS pending_count,
@@ -192,9 +204,10 @@ export async function listChangeEvents() {
LEFT JOIN privacy_vault_records rv ON rv.id = e.replacement_record_id
LEFT JOIN privacy_org_holdings h
ON h.vault_record_id = e.vault_record_id AND h.status = ANY($1::text[])
+ WHERE e.subject_id = $2
GROUP BY e.id, ov.type, ov.label, ov.masked_value, rv.type, rv.label, rv.masked_value
ORDER BY e.declared_at DESC`,
- [INVENTORY_STATUSES],
+ [INVENTORY_STATUSES, resolveSubjectId(subjectId)],
);
return rows.map((row) => ({
...rowToEvent(row),
diff --git a/server/services/privacyOptOut.js b/server/services/privacyOptOut.js
index aba66e4c29..cf2c610841 100644
--- a/server/services/privacyOptOut.js
+++ b/server/services/privacyOptOut.js
@@ -20,6 +20,12 @@
* `confirmed_removed`.
*
* HARD GUARDRAILS (autonomy never overrides — mirrors unbroker):
+ * - NO CONSENT, NO ACTION. `runOptOutPass` / `runVerificationPass` refuse to
+ * act for a subject with no recorded consent row
+ * (privacySubjects.assertSubjectConsent, #3658). Like the disclosure
+ * allowlist below, the guard lives in the SERVICE — a scheduled recheck, a
+ * direct API call, or a future agent path is refused exactly like a hidden
+ * UI button would be.
* - 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
@@ -46,6 +52,7 @@ import { createDraft, approveDraft } from './messageDrafts.js';
import { listAccounts } from './messageAccounts.js';
import { getMessages } from './messageSync.js';
import { getSettings } from './settings.js';
+import { resolveSubjectId, assertSubjectConsent } from './privacySubjects.js';
// ─── Disclosure guardrail (pure) ────────────────────────────────────────────
@@ -398,8 +405,13 @@ export function planOptOutActions(casesWithBroker = []) {
*/
export async function runVerificationPass({
now = new Date(), messagesProvider = getMessages, removalProbe = probeBroker, probeDeps = {},
+ subjectId,
} = {}) {
- const cases = await listBrokerCases();
+ // CONSENT GATE — the verification pass re-probes brokers for the subject, so
+ // it is gated exactly like the submission pass.
+ const resolvedSubjectId = resolveSubjectId(subjectId);
+ await assertSubjectConsent(resolvedSubjectId, { action: 'opt-out verification pass' });
+ const cases = await listBrokerCases({ subjectId: resolvedSubjectId });
const advanced = [];
const confirmed = [];
// 1. submitted → verification_pending when a trusted confirmation email exists.
@@ -422,9 +434,9 @@ export async function runVerificationPass({
}
}
// 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');
+ const toVerify = (await listBrokerCases({ subjectId: resolvedSubjectId })).filter((c) => c.state === 'verification_pending' || c.state === 'awaiting_processing');
if (toVerify.length) {
- const scanValues = await listScanEligibleValues();
+ const scanValues = await listScanEligibleValues({ subjectId: resolvedSubjectId });
const vectors = buildSearchVectors(scanValues);
for (const c of toVerify) {
const broker = await getBroker(c.brokerId);
@@ -455,21 +467,26 @@ export async function runVerificationPass({
* `privacy.recheck.autoSubmitWebForms`, both default OFF). Deps injectable.
*/
export async function runOptOutPass({
- now = new Date(), settingsProvider = getSettings, deps = {}, runVerification = true,
+ now = new Date(), settingsProvider = getSettings, deps = {}, runVerification = true, subjectId,
} = {}) {
+ // CONSENT GATE — BEFORE any vault read, broker fetch, or draft creation. NO
+ // CONSENT, NO ACTION: a subject without a recorded consent row is refused
+ // (403) here in the service, not merely in the UI.
+ const resolvedSubjectId = resolveSubjectId(subjectId);
+ await assertSubjectConsent(resolvedSubjectId, { action: 'broker opt-out pass' });
const settings = await settingsProvider();
const recheck = settings?.privacy?.recheck || {};
const autoApprove = recheck.autoApproveOptOutEmails === true;
const autoSubmit = recheck.autoSubmitWebForms === true;
- const scanValues = await listScanEligibleValues();
+ const scanValues = await listScanEligibleValues({ subjectId: resolvedSubjectId });
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' };
+ return { submitted: [], skipped: 0, verification: null, subjectId: resolvedSubjectId, reason: 'no_disclosure_identity' };
}
- const [brokers, cases] = await Promise.all([listBrokers({ enabled: true }), listBrokerCases()]);
+ const [brokers, cases] = await Promise.all([listBrokers({ enabled: true }), listBrokerCases({ subjectId: resolvedSubjectId })]);
const brokerById = new Map(brokers.map((b) => [b.id, b]));
const casesWithBroker = cases
.map((c) => ({ case: c, broker: brokerById.get(c.brokerId) }))
@@ -499,11 +516,11 @@ export async function runOptOutPass({
}
const verification = runVerification
- ? await runVerificationPass({ now, ...(deps.verification || {}) })
+ ? await runVerificationPass({ now, subjectId: resolvedSubjectId, ...(deps.verification || {}) })
: null;
console.log(`📋 Opt-out pass: ${submitted.length} actioned, ${skipped} skipped (autoApprove=${autoApprove}, autoSubmit=${autoSubmit})`);
- return { submitted, skipped, verification, autonomy: { autoApprove, autoSubmit } };
+ return { submitted, skipped, verification, subjectId: resolvedSubjectId, autonomy: { autoApprove, autoSubmit } };
}
// ─── Human-task digest ──────────────────────────────────────────────────────
@@ -514,10 +531,11 @@ export async function runOptOutPass({
* 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() {
+export async function getOptOutDigest({ subjectId } = {}) {
+ const resolvedSubjectId = resolveSubjectId(subjectId);
const [human, blocked] = await Promise.all([
- listBrokerCases({ state: 'human_task_queued' }),
- listBrokerCases({ state: 'blocked' }),
+ listBrokerCases({ state: 'human_task_queued', subjectId: resolvedSubjectId }),
+ listBrokerCases({ state: 'blocked', subjectId: resolvedSubjectId }),
]);
const toItem = (c) => ({
caseId: c.id,
@@ -540,6 +558,7 @@ export async function getOptOutDigest() {
const items = [...human.map(toItem), ...blocked.map(toItem)];
return {
total: items.length,
+ subjectId: resolvedSubjectId,
humanTasks: human.length,
blocked: blocked.length,
items,
diff --git a/server/services/privacyOptOut.test.js b/server/services/privacyOptOut.test.js
index 3b93e8d57d..ea502951e3 100644
--- a/server/services/privacyOptOut.test.js
+++ b/server/services/privacyOptOut.test.js
@@ -21,6 +21,16 @@ vi.mock('./privacyBrokers.js', () => ({
getCaseForBroker: vi.fn(async () => null),
}));
vi.mock('./privacyVault.js', () => ({ listScanEligibleValues: vi.fn(async () => []) }));
+// #3658 consent gate — mocked so the pass runs without a DB, and so a test can
+// flip it to the refusing behaviour to prove the guard is engine-enforced.
+const SELF = '00000000-0000-4000-8000-000000000001';
+const { assertSubjectConsentMock } = vi.hoisted(() => ({
+ assertSubjectConsentMock: vi.fn(async (id) => ({ id: id || '00000000-0000-4000-8000-000000000001' })),
+}));
+vi.mock('./privacySubjects.js', () => ({
+ resolveSubjectId: (id) => id || SELF,
+ assertSubjectConsent: assertSubjectConsentMock,
+}));
vi.mock('./privacyScan.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, probeBroker: vi.fn(async () => ({ skipped: true, reason: 'inconclusive' })) };
@@ -43,6 +53,7 @@ const settings = await import('./settings.js');
beforeEach(() => {
vi.clearAllMocks();
+ assertSubjectConsentMock.mockImplementation(async (id) => ({ id: id || SELF }));
transitionCase.mockImplementation(async (id, to, patch) => ({ id, state: to, ...patch }));
listBrokers.mockResolvedValue([]);
listBrokerCases.mockResolvedValue([]);
@@ -323,3 +334,44 @@ describe('getOptOutDigest', () => {
expect(digest.items[1].searchUrl).toBe('https://rad/p/Jane/Doe/');
});
});
+
+// ─── Consent gate (issue #3658) ─────────────────────────────────────────────
+// NO CONSENT, NO ACTION — carried verbatim from unbroker. The refusal is at the
+// SERVICE layer, so a cron / direct API / agent caller is refused exactly like a
+// hidden UI button would be. Asserted here, NOT only in a UI test.
+describe('consent gate — engine-enforced (#3658)', () => {
+ const refuse = () => {
+ assertSubjectConsentMock.mockImplementation(async () => {
+ const err = new Error('no consent');
+ err.status = 403;
+ err.code = 'SUBJECT_CONSENT_REQUIRED';
+ throw err;
+ });
+ };
+
+ it('runOptOutPass refuses a subject with no consent, before reading the vault', async () => {
+ refuse();
+ const vault = await import('./privacyVault.js');
+ await expect(runOptOutPass({ subjectId: 'subject-2' }))
+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });
+ expect(vault.listScanEligibleValues).not.toHaveBeenCalled();
+ expect(listBrokers).not.toHaveBeenCalled();
+ expect(transitionCase).not.toHaveBeenCalled();
+ expect(createDraft).not.toHaveBeenCalled();
+ });
+
+ it('runVerificationPass refuses a subject with no consent, before reading the ledger', async () => {
+ refuse();
+ await expect(runVerificationPass({ subjectId: 'subject-2' }))
+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });
+ expect(listBrokerCases).not.toHaveBeenCalled();
+ expect(transitionCase).not.toHaveBeenCalled();
+ });
+
+ it('passes the resolved subject through to the guard and the ledger reads', async () => {
+ listBrokerCases.mockResolvedValue([]);
+ await runVerificationPass({ subjectId: 'subject-2' });
+ expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { action: 'opt-out verification pass' });
+ expect(listBrokerCases).toHaveBeenCalledWith({ subjectId: 'subject-2' });
+ });
+});
diff --git a/server/services/privacyOrgs.js b/server/services/privacyOrgs.js
index 8a34fd39cc..20c112618c 100644
--- a/server/services/privacyOrgs.js
+++ b/server/services/privacyOrgs.js
@@ -21,14 +21,16 @@
import { randomUUID } from 'crypto';
import { query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
+import { resolveSubjectId, assertSubject } from './privacySubjects.js';
-const ORG_COLUMNS = `id, name, category, website, trust, status, contact,
+const ORG_COLUMNS = `id, subject_id, name, category, website, trust, status, contact,
social_account_id, notes, created_at, updated_at`;
function rowToOrg(row) {
if (!row) return null;
return {
id: row.id,
+ subjectId: row.subject_id,
name: row.name,
category: row.category,
website: row.website,
@@ -45,6 +47,7 @@ function rowToOrg(row) {
function rowToHolding(row) {
return {
orgId: row.org_id,
+ subjectId: row.subject_id,
vaultRecordId: row.vault_record_id,
status: row.status,
notedAt: row.noted_at,
@@ -58,14 +61,16 @@ function rowToHolding(row) {
}
export async function createOrg(input) {
+ // A bogus subjectId must 404 up front rather than trip a raw FK violation.
+ const subjectId = (await assertSubject(input.subjectId)).id;
const id = randomUUID();
const { rows } = await query(
`INSERT INTO privacy_orgs
- (id, name, category, website, trust, status, contact, social_account_id, notes, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW(), NOW())
+ (id, subject_id, name, category, website, trust, status, contact, social_account_id, notes, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW())
RETURNING ${ORG_COLUMNS}`,
[
- id, input.name,
+ id, subjectId, input.name,
input.category ?? 'other', input.website ?? '',
input.trust ?? 'trusted', input.status ?? 'active',
JSON.stringify(input.contact ?? {}),
@@ -76,17 +81,18 @@ export async function createOrg(input) {
// Log id/category only — the org NAME (bank, employer, medical provider, …)
// is user-entered privacy-adjacent data and follows the same never-log
// posture as the vault's plaintext values (see privacyVault.js header).
- console.log(`🏢 Created privacy org ${id} (category=${input.category ?? 'other'})`);
+ console.log(`🏢 Created privacy org ${id} (subject=${subjectId}, category=${input.category ?? 'other'})`);
return rowToOrg(rows[0]);
}
-export async function listOrgs({ trust, status, category } = {}) {
- const clauses = [];
- const params = [];
+export async function listOrgs({ trust, status, category, subjectId } = {}) {
+ // Always scoped to ONE subject (defaulting to `self`) — see listVaultRecords.
+ const params = [resolveSubjectId(subjectId)];
+ const clauses = ['subject_id = $1'];
if (trust) { params.push(trust); clauses.push(`trust = $${params.length}`); }
if (status) { params.push(status); clauses.push(`status = $${params.length}`); }
if (category) { params.push(category); clauses.push(`category = $${params.length}`); }
- const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
+ const where = `WHERE ${clauses.join(' AND ')}`;
const { rows } = await query(
`SELECT ${ORG_COLUMNS} FROM privacy_orgs ${where} ORDER BY name ASC`,
params,
@@ -138,7 +144,7 @@ export async function deleteOrg(id) {
*/
export async function getHoldingsForOrg(orgId) {
const { rows } = await query(
- `SELECT h.org_id, h.vault_record_id, h.status, h.noted_at, h.updated_at,
+ `SELECT h.org_id, h.subject_id, h.vault_record_id, h.status, h.noted_at, h.updated_at,
v.type, v.label, v.masked_value
FROM privacy_org_holdings h
JOIN privacy_vault_records v ON v.id = h.vault_record_id
@@ -152,7 +158,7 @@ export async function getHoldingsForOrg(orgId) {
/** Which orgs hold vault record `vaultRecordId` — powers the inventory view. */
export async function getOrgsHoldingRecord(vaultRecordId) {
const { rows } = await query(
- `SELECT h.org_id, h.vault_record_id, h.status, h.noted_at, h.updated_at,
+ `SELECT h.org_id, h.subject_id, h.vault_record_id, h.status, h.noted_at, h.updated_at,
o.name AS org_name
FROM privacy_org_holdings h
JOIN privacy_orgs o ON o.id = h.org_id
@@ -183,10 +189,27 @@ export async function getOrgsHoldingRecord(vaultRecordId) {
*/
export async function setOrgHoldings(orgId, holdings) {
await withTransaction(async (client) => {
- const { rows: orgRows } = await client.query(`SELECT id FROM privacy_orgs WHERE id = $1 FOR UPDATE`, [orgId]);
+ const { rows: orgRows } = await client.query(`SELECT id, subject_id FROM privacy_orgs WHERE id = $1 FOR UPDATE`, [orgId]);
if (!orgRows[0]) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ const subjectId = orgRows[0].subject_id;
const ids = holdings.map((h) => h.vaultRecordId);
+ // A holding is "org X holds subject S's fact" — so the org and the vault
+ // record must belong to the SAME subject. Without this check a stale UI id
+ // could file one household member's address under another member's org,
+ // and the per-subject views would silently disagree with each other.
+ if (ids.length) {
+ const { rows: mismatched } = await client.query(
+ `SELECT id FROM privacy_vault_records WHERE id = ANY($1::uuid[]) AND subject_id <> $2`,
+ [ids, subjectId],
+ );
+ if (mismatched[0]) {
+ throw new ServerError(
+ `Vault record ${mismatched[0].id} belongs to a different privacy subject`,
+ { status: 400, code: 'SUBJECT_MISMATCH' },
+ );
+ }
+ }
if (ids.length === 0) {
await client.query(`DELETE FROM privacy_org_holdings WHERE org_id = $1`, [orgId]);
} else {
@@ -199,11 +222,11 @@ export async function setOrgHoldings(orgId, holdings) {
// deletion) trips the FK constraint — surface it as a clean 400
// instead of a raw Postgres constraint-violation 500.
await client.query(
- `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
- VALUES ($1, $2, $3, NOW(), NOW())
+ `INSERT INTO privacy_org_holdings (org_id, subject_id, vault_record_id, status, noted_at, updated_at)
+ VALUES ($1, $2, $3, $4, NOW(), NOW())
ON CONFLICT (org_id, vault_record_id)
- DO UPDATE SET status = EXCLUDED.status, updated_at = NOW()`,
- [orgId, h.vaultRecordId, h.status ?? 'current'],
+ DO UPDATE SET status = EXCLUDED.status, subject_id = EXCLUDED.subject_id, updated_at = NOW()`,
+ [orgId, subjectId, h.vaultRecordId, h.status ?? 'current'],
).catch((err) => {
if (err?.code === '23503') {
throw new ServerError(`Vault record ${h.vaultRecordId} not found`, { status: 400, code: 'VAULT_RECORD_NOT_FOUND' });
@@ -239,17 +262,20 @@ export async function setHoldingsStatus(vaultRecordId, fromStatus, toStatus) {
* Accounts tab so it can badge "in org registry" without N per-account calls.
* Returns `[{ socialAccountId, orgId, orgName }]`.
*/
-export async function getOrgsBySocialAccounts() {
+export async function getOrgsBySocialAccounts({ subjectId } = {}) {
// Degrade gracefully to an empty index when Privacy Center isn't provisioned
// yet (fresh install pre-migration) — the twin's Accounts tab calls this on
// load, so a missing table must yield no badges rather than a 500.
const { rows: tableRows } = await query(`SELECT to_regclass('public.privacy_orgs') AS orgs`);
if (!tableRows[0]?.orgs) return [];
+ // Scoped to `self` by default: the Digital Twin models the install's owner,
+ // so a household member's orgs must not badge the twin's Accounts tab.
const { rows } = await query(
`SELECT id, name, social_account_id
FROM privacy_orgs
- WHERE social_account_id IS NOT NULL
+ WHERE social_account_id IS NOT NULL AND subject_id = $1
ORDER BY name`,
+ [resolveSubjectId(subjectId)],
);
return rows.map((row) => ({
socialAccountId: row.social_account_id,
@@ -259,21 +285,26 @@ export async function getOrgsBySocialAccounts() {
}
/** Per-org holding counts + per-vault-record org counts — powers the inventory view. */
-export async function getHoldingsSummary() {
+export async function getHoldingsSummary({ subjectId } = {}) {
+ const resolvedSubjectId = resolveSubjectId(subjectId);
const [byOrg, byRecord] = await Promise.all([
query(
`SELECT o.id AS org_id, o.name AS org_name, COUNT(h.vault_record_id)::int AS holding_count
FROM privacy_orgs o
LEFT JOIN privacy_org_holdings h ON h.org_id = o.id
+ WHERE o.subject_id = $1
GROUP BY o.id, o.name
ORDER BY o.name`,
+ [resolvedSubjectId],
),
query(
`SELECT v.id AS vault_record_id, v.type, v.label, COUNT(h.org_id)::int AS org_count
FROM privacy_vault_records v
LEFT JOIN privacy_org_holdings h ON h.vault_record_id = v.id
+ WHERE v.subject_id = $1
GROUP BY v.id, v.type, v.label
ORDER BY v.type, v.label`,
+ [resolvedSubjectId],
),
]);
return {
diff --git a/server/services/privacyOrgs.test.js b/server/services/privacyOrgs.test.js
index 84a83128c4..732a27fa5d 100644
--- a/server/services/privacyOrgs.test.js
+++ b/server/services/privacyOrgs.test.js
@@ -14,6 +14,18 @@ const { queryMock, withTransactionMock } = vi.hoisted(() => ({
vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: withTransactionMock }));
+// #3658: the subject scope resolves through privacySubjects; stubbed so these
+// DB-mocked tests keep asserting on the privacy_* SQL rather than a subject read.
+const SELF = '00000000-0000-4000-8000-000000000001';
+vi.mock('./privacySubjects.js', () => ({
+ resolveSubjectId: (id) => id || SELF,
+ assertSubject: vi.fn(async (id) => ({ id: id || SELF })),
+ assertSubjectConsent: vi.fn(async (id) => ({ id: id || SELF })),
+ recordConsent: vi.fn(async () => ({ id: 'consent-1' })),
+ listSubjects: vi.fn(async () => [{ id: SELF, consentCount: 1 }]),
+}));
+
+
const {
createOrg, listOrgs, getOrg, updateOrg, deleteOrg,
getHoldingsForOrg, getOrgsHoldingRecord, setOrgHoldings, setHoldingsStatus, getHoldingsSummary,
@@ -32,7 +44,7 @@ function mockTransaction(handler) {
}
const orgRow = (overrides = {}) => ({
- id: 'o1', name: 'Acme Bank', category: 'bank', website: 'https://acme.example',
+ id: 'o1', subject_id: SELF, name: 'Acme Bank', category: 'bank', website: 'https://acme.example',
trust: 'trusted', status: 'active', contact: {}, social_account_id: null,
notes: '', created_at: 'now', updated_at: 'now', ...overrides,
});
@@ -43,10 +55,11 @@ describe('createOrg', () => {
const org = await createOrg({ name: 'Acme Bank' });
const [sql, params] = queryMock.mock.calls[0];
expect(sql).toMatch(/INSERT INTO privacy_orgs/);
- expect(params[1]).toBe('Acme Bank');
- expect(params[2]).toBe('other'); // category default
- expect(params[4]).toBe('trusted'); // trust default
- expect(params[5]).toBe('active'); // status default
+ expect(params[1]).toBe(SELF); // subject scope defaults to `self` (#3658)
+ expect(params[2]).toBe('Acme Bank');
+ expect(params[3]).toBe('other'); // category default
+ expect(params[5]).toBe('trusted'); // trust default
+ expect(params[6]).toBe('active'); // status default
expect(org.name).toBe('Acme Bank');
});
@@ -54,7 +67,7 @@ describe('createOrg', () => {
queryMock.mockResolvedValue({ rows: [orgRow()] });
await createOrg({ name: 'Acme', contact: { email: '[email protected]' } });
const [, params] = queryMock.mock.calls[0];
- expect(params[6]).toBe(JSON.stringify({ email: '[email protected]' }));
+ expect(params[7]).toBe(JSON.stringify({ email: '[email protected]' }));
});
it('never logs the org name — it is privacy-adjacent data, like the vault plaintext', async () => {
@@ -68,23 +81,30 @@ describe('createOrg', () => {
});
describe('listOrgs', () => {
- it('lists with no filters', async () => {
+ it('lists with no filters, always scoped to a subject (#3658)', async () => {
queryMock.mockResolvedValue({ rows: [orgRow()] });
const orgs = await listOrgs();
expect(orgs).toHaveLength(1);
const [sql, params] = queryMock.mock.calls[0];
- expect(sql).not.toMatch(/WHERE/);
- expect(params).toEqual([]);
+ expect(sql).toMatch(/WHERE subject_id = \$1/);
+ expect(params).toEqual([SELF]);
});
- it('applies trust/status/category filters', async () => {
+ it('applies trust/status/category filters on top of the subject scope', async () => {
queryMock.mockResolvedValue({ rows: [] });
await listOrgs({ trust: 'unwanted', status: 'active', category: 'broker' });
const [sql, params] = queryMock.mock.calls[0];
- expect(sql).toMatch(/trust = \$1/);
- expect(sql).toMatch(/status = \$2/);
- expect(sql).toMatch(/category = \$3/);
- expect(params).toEqual(['unwanted', 'active', 'broker']);
+ expect(sql).toMatch(/subject_id = \$1/);
+ expect(sql).toMatch(/trust = \$2/);
+ expect(sql).toMatch(/status = \$3/);
+ expect(sql).toMatch(/category = \$4/);
+ expect(params).toEqual([SELF, 'unwanted', 'active', 'broker']);
+ });
+
+ it('scopes to an explicit subject when one is given', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await listOrgs({ subjectId: 'subject-2' });
+ expect(queryMock.mock.calls[0][1]).toEqual(['subject-2']);
});
});
@@ -175,6 +195,7 @@ describe('setOrgHoldings', () => {
it('deletes the complement and upserts the given set, all inside one transaction', async () => {
const client = mockTransaction(async (sql) => {
if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
+ if (/FROM privacy_vault_records WHERE id = ANY/.test(sql)) return { rows: [] };
if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
if (/INSERT INTO privacy_org_holdings/.test(sql)) return { rows: [] };
throw new Error(`unexpected client query: ${sql}`);
@@ -185,7 +206,7 @@ describe('setOrgHoldings', () => {
expect(deleteCall[1]).toEqual(['o1', ['v1', 'v2']]);
const insertCalls = client.query.mock.calls.filter(([sql]) => /INSERT INTO privacy_org_holdings/.test(sql));
expect(insertCalls).toHaveLength(2);
- expect(insertCalls[1][1]).toEqual(['o1', 'v2', 'current']); // default status applied
+ expect(insertCalls[1][1]).toEqual(['o1', SELF, 'v2', 'current']); // subject stamped + default status applied
expect(withTransactionMock).toHaveBeenCalledTimes(1);
});
@@ -205,6 +226,7 @@ describe('setOrgHoldings', () => {
const fkError = Object.assign(new Error('insert or update on table violates foreign key constraint'), { code: '23503' });
mockTransaction(async (sql) => {
if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
+ if (/FROM privacy_vault_records WHERE id = ANY/.test(sql)) return { rows: [] };
if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
if (/INSERT INTO privacy_org_holdings/.test(sql)) throw fkError;
throw new Error(`unexpected client query: ${sql}`);
diff --git a/server/services/privacyRecheckScheduler.js b/server/services/privacyRecheckScheduler.js
index a2b89ee6c3..e599e82a46 100644
--- a/server/services/privacyRecheckScheduler.js
+++ b/server/services/privacyRecheckScheduler.js
@@ -18,6 +18,7 @@ import { getSettings } from './settings.js';
import { getUserTimezone } from '../lib/timezone.js';
import { runScanPass } from './privacyScan.js';
import { runOptOutPass } from './privacyOptOut.js';
+import { listSubjects } from './privacySubjects.js';
const EVENT_ID = 'privacy-recheck';
const DEFAULT_CRON = '0 4 * * 0'; // weekly, Sun 4am
@@ -45,11 +46,25 @@ export async function startPrivacyRecheckScheduler() {
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();
+ // Run for EVERY consenting subject, not just `self` — a household member
+ // added to the Privacy Center gets the same scheduled upkeep (#3658). A
+ // subject with no consent row is skipped here (the engines would refuse
+ // them anyway); one subject's failure must not abort the others, and this
+ // handler runs OUTSIDE the request lifecycle, so the per-subject try/catch
+ // is the sanctioned exception to the no-try/catch rule.
+ const subjects = await listSubjects();
+ const consenting = subjects.filter((s) => (s.consentCount ?? 0) > 0);
+ console.log(`🛡️ Privacy recheck: running scheduled scan + opt-out pass for ${consenting.length} consenting subject(s)`);
+ for (const subject of consenting) {
+ try {
+ // Scan first (re-checks due cases + finds new exposure), then work the
+ // cases. Both are settings-driven and safe to re-run (idempotent).
+ await runScanPass({ subjectId: subject.id });
+ await runOptOutPass({ subjectId: subject.id });
+ } catch (err) {
+ console.error(`❌ Privacy recheck failed for subject ${subject.id}: ${err.message}`);
+ }
+ }
},
metadata: { source: 'privacyRecheckScheduler' },
});
diff --git a/server/services/privacyScan.js b/server/services/privacyScan.js
index 3107c496b2..66f09ad05a 100644
--- a/server/services/privacyScan.js
+++ b/server/services/privacyScan.js
@@ -12,6 +12,11 @@
* render static HTML), escalating to the SSRF-pinned real-Chrome fetch
* (`fetchUrlMainText`) only when the page needs JS. Both lanes are SSRF-vetted.
*
+ * CONSENT: `runScanPass` refuses to probe ANY broker for a subject without a
+ * recorded consent row (privacySubjects.assertSubjectConsent) — the guard lives
+ * in the service, not the UI, so a scheduled recheck or a direct API call is
+ * refused exactly like a hidden button would be (#3658).
+ *
* 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
@@ -23,6 +28,7 @@ import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.j
import { fetchUrlMainText } from './catalogIngestSources.js';
import { listScanEligibleValues } from './privacyVault.js';
import { listBrokers, listBrokerCases, recordScanVerdict } from './privacyBrokers.js';
+import { resolveSubjectId, assertSubjectConsent } from './privacySubjects.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,
@@ -297,11 +303,12 @@ export async function probeBroker(broker, vectors, {
*/
export async function scanBroker(broker, vectors, {
fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(),
+ subjectId,
} = {}) {
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,
+ evidence: probed.evidence, found: probed.found ?? null, now, subjectId,
});
return kase;
}
@@ -313,18 +320,23 @@ export async function scanBroker(broker, vectors, {
*
* 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();
+export async function runScanPass({ concurrency = 3, fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(), subjectId } = {}) {
+ // CONSENT GATE — BEFORE any vault read or broker fetch. A subject with no
+ // consent row on file is refused outright (403); the UI hiding the Scan button
+ // is not sufficient, since a cron/API/agent caller reaches this same function.
+ const resolvedSubjectId = resolveSubjectId(subjectId);
+ await assertSubjectConsent(resolvedSubjectId, { action: 'broker exposure scan' });
+ const scanValues = await listScanEligibleValues({ subjectId: resolvedSubjectId });
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' };
+ return { scanned: 0, verdicts: {}, skipped: 0, brokers: 0, subjectId: resolvedSubjectId, 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 casesByBroker = new Map((await listBrokerCases({ subjectId: resolvedSubjectId })).map((c) => [c.brokerId, c]));
const nowMs = now.getTime();
const brokers = allBrokers.filter((b) => {
const kase = casesByBroker.get(b.id);
@@ -340,12 +352,12 @@ export async function runScanPass({ concurrency = 3, fetchImpl = fetch, browserF
// 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 })));
+ const results = await Promise.all(batch.map((b) => scanBroker(b, vectors, { fetchImpl, browserFetch, urlSafe, now, subjectId: resolvedSubjectId })));
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 };
+ return { scanned, verdicts, skipped, brokers: brokers.length, subjectId: resolvedSubjectId };
}
diff --git a/server/services/privacyScan.test.js b/server/services/privacyScan.test.js
index beaa149b41..0eb921d388 100644
--- a/server/services/privacyScan.test.js
+++ b/server/services/privacyScan.test.js
@@ -13,9 +13,19 @@ vi.mock('./privacyBrokers.js', async (importOriginal) => {
});
vi.mock('./catalogIngestSources.js', () => ({ fetchUrlMainText: vi.fn(async () => null) }));
vi.mock('./privacyVault.js', () => ({ listScanEligibleValues: vi.fn(async () => []) }));
+// #3658 consent gate — mocked so the pass runs without a DB, and so a test can
+// flip it to the refusing behaviour to prove the guard is engine-enforced.
+const SELF = '00000000-0000-4000-8000-000000000001';
+const { assertSubjectConsentMock } = vi.hoisted(() => ({
+ assertSubjectConsentMock: vi.fn(async (id) => ({ id: id || '00000000-0000-4000-8000-000000000001' })),
+}));
+vi.mock('./privacySubjects.js', () => ({
+ resolveSubjectId: (id) => id || SELF,
+ assertSubjectConsent: assertSubjectConsentMock,
+}));
const {
- parseCityState, buildSearchVectors, fillSearchUrl, classifyScanResult, scanBroker,
+ parseCityState, buildSearchVectors, fillSearchUrl, classifyScanResult, scanBroker, runScanPass,
} = await import('./privacyScan.js');
const brokers = await import('./privacyBrokers.js');
@@ -197,3 +207,35 @@ describe('scanBroker — classify → record wiring', () => {
expect(brokers.recordScanVerdict).not.toHaveBeenCalled();
});
});
+
+// ─── Consent gate (issue #3658) ─────────────────────────────────────────────
+// NO CONSENT, NO ACTION. The scan pass must refuse a subject with no consent row
+// BEFORE it decrypts a single vault value or fetches a single broker page — the
+// refusal lives in the service, not in the UI that hides the Scan button.
+describe('runScanPass consent gate — engine-enforced (#3658)', () => {
+ it('refuses a subject with no consent, before reading the vault', async () => {
+ assertSubjectConsentMock.mockImplementationOnce(async () => {
+ const err = new Error('no consent');
+ err.status = 403;
+ err.code = 'SUBJECT_CONSENT_REQUIRED';
+ throw err;
+ });
+ const vault = await import('./privacyVault.js');
+ vault.listScanEligibleValues.mockClear();
+ await expect(runScanPass({ subjectId: 'subject-2' }))
+ .rejects.toMatchObject({ code: 'SUBJECT_CONSENT_REQUIRED' });
+ expect(vault.listScanEligibleValues).not.toHaveBeenCalled();
+ expect(brokers.recordScanVerdict).not.toHaveBeenCalled();
+ });
+
+ it('checks consent for the resolved subject and scopes the vault read to it', async () => {
+ const vault = await import('./privacyVault.js');
+ vault.listScanEligibleValues.mockClear();
+ vault.listScanEligibleValues.mockResolvedValue([]);
+ const result = await runScanPass({ subjectId: 'subject-2' });
+ expect(assertSubjectConsentMock).toHaveBeenCalledWith('subject-2', { action: 'broker exposure scan' });
+ expect(vault.listScanEligibleValues).toHaveBeenCalledWith({ subjectId: 'subject-2' });
+ // No name vector ⇒ the pass short-circuits without touching a broker.
+ expect(result.reason).toBe('no_scan_vectors');
+ });
+});
diff --git a/server/services/privacySubjects.js b/server/services/privacySubjects.js
new file mode 100644
index 0000000000..07b5fc99e8
--- /dev/null
+++ b/server/services/privacySubjects.js
@@ -0,0 +1,236 @@
+/**
+ * Household subjects + the consent gate (issue #3658, epic #2138).
+ *
+ * db-primary Postgres per docs/STORAGE.md: one row per person the Privacy
+ * Center works on behalf of in `privacy_subjects`, with the consent audit trail
+ * in `privacy_consents`. Every other privacy table carries a `subject_id` FK
+ * defaulted to the seeded `self` row, so an install that never adds a second
+ * subject behaves exactly as it did before this module existed.
+ *
+ * Machine-local: NO federation, NO tombstones — NEVER federated, by decision
+ * rather than deferral (ADR
+ * docs/decisions/2026-08-08-privacy-records-machine-local.md, #2148). Deleting a
+ * subject is a hard DELETE that CASCADES their vault records, orgs, holdings,
+ * change events, broker cases, and consent rows.
+ *
+ * CONSENT IS ENGINE-ENFORCED, NOT UI-ENFORCED. Carried verbatim from unbroker's
+ * no-consent-no-action rule: `assertSubjectConsent()` is called by
+ * `privacyScan.runScanPass()` and `privacyOptOut.runOptOutPass()` /
+ * `runVerificationPass()` before either touches a broker. Hiding the button in
+ * the UI is NOT sufficient — a scheduled recheck, a direct API call, or a future
+ * agent path all route through the service, which is where the refusal lives.
+ *
+ * Log lines never carry a subject's `display_name` — a household member's name
+ * is PII in exactly the way the vault's values are (see privacyVault.js's
+ * plaintext-never-logged posture); logs carry id + relationship only.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { PRIVACY_SELF_SUBJECT_ID } from '../lib/privacyValidation.js';
+
+const SUBJECT_COLUMNS = `id, display_name, relationship, created_at, updated_at`;
+
+function rowToSubject(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ displayName: row.display_name,
+ relationship: row.relationship,
+ isSelf: String(row.id).toLowerCase() === PRIVACY_SELF_SUBJECT_ID,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ // Present only on the aggregate list query.
+ ...(row.consent_count !== undefined ? { consentCount: row.consent_count } : {}),
+ ...(row.record_count !== undefined ? { recordCount: row.record_count } : {}),
+ };
+}
+
+/**
+ * Normalize an optional caller-supplied subject id to a concrete one. Absent /
+ * empty ⇒ the seeded `self` row, which is what every pre-#3658 caller means.
+ * Pure — no DB round-trip (existence is enforced by the FK / assertSubject).
+ */
+export function resolveSubjectId(subjectId) {
+ // Lower-cased: Zod's uuid() accepts an upper-case uuid, and the seeded row's
+ // id is stored lower-case — comparing the two raw would make an upper-case
+ // `self` id look like a different subject (and defeat the delete guard).
+ return subjectId ? String(subjectId).toLowerCase() : PRIVACY_SELF_SUBJECT_ID;
+}
+
+/** Write a consent row for a subject. Append-only audit trail. */
+export async function recordConsent({ subjectId, scope, method, note }) {
+ const id = randomUUID();
+ const resolved = resolveSubjectId(subjectId);
+ // The legacy free-text `subject` column keeps its DEFAULT 'self' — it is
+ // frozen historical audit data; `subject_id` is the live scope (#3658).
+ await query(
+ `INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)
+ VALUES ($1, $2, $3, $4, $5, NOW())`,
+ [id, resolved, scope, method, note ?? ''],
+ );
+ console.log(`📝 Recorded privacy consent ${id} (subject=${resolved}, scope=${scope}, method=${method})`);
+ return { id, subjectId: resolved, scope, method, note: note ?? '' };
+}
+
+// ─── Subject CRUD ───────────────────────────────────────────────────────────
+
+/**
+ * List every subject with their consent-row count and vault-record count, so
+ * the UI switcher can badge a subject that has no consent on file (and would
+ * therefore be refused by the engine).
+ */
+export async function listSubjects() {
+ const { rows } = await query(
+ `SELECT s.id, s.display_name, s.relationship, s.created_at, s.updated_at,
+ (SELECT COUNT(*)::int FROM privacy_consents c WHERE c.subject_id = s.id) AS consent_count,
+ (SELECT COUNT(*)::int FROM privacy_vault_records v WHERE v.subject_id = s.id) AS record_count
+ FROM privacy_subjects s
+ ORDER BY (s.id <> $1), s.display_name ASC`,
+ [PRIVACY_SELF_SUBJECT_ID],
+ );
+ return rows.map(rowToSubject);
+}
+
+export async function getSubject(id) {
+ const { rows } = await query(`SELECT ${SUBJECT_COLUMNS} FROM privacy_subjects WHERE id = $1`, [id]);
+ return rowToSubject(rows[0]);
+}
+
+/**
+ * Assert the subject exists, returning its row. Every subject-scoped write path
+ * calls this so a stale/bogus id surfaces as a clean 404 rather than a raw
+ * Postgres FK violation (23503) at INSERT time.
+ */
+export async function assertSubject(subjectId) {
+ const resolved = resolveSubjectId(subjectId);
+ const subject = await getSubject(resolved);
+ if (!subject) {
+ throw new ServerError(`Privacy subject ${resolved} not found`, { status: 404, code: 'SUBJECT_NOT_FOUND' });
+ }
+ return subject;
+}
+
+/**
+ * Add a household member. The consent method is REQUIRED and its row is written
+ * in the SAME transaction as the subject — there is no window in which a subject
+ * exists without recorded consent, so the engine guard can never be raced.
+ */
+export async function createSubject({ displayName, relationship, consentMethod, consentNote }) {
+ const id = randomUUID();
+ const resolvedRelationship = relationship ?? 'other';
+ const subject = await withTransaction(async (client) => {
+ const { rows } = await client.query(
+ `INSERT INTO privacy_subjects (id, display_name, relationship, created_at, updated_at)
+ VALUES ($1, $2, $3, NOW(), NOW())
+ RETURNING ${SUBJECT_COLUMNS}`,
+ [id, displayName, resolvedRelationship],
+ );
+ await client.query(
+ `INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)
+ VALUES ($1, $2, 'pii_vault', $3, $4, NOW())`,
+ [randomUUID(), id, consentMethod, consentNote ?? ''],
+ );
+ return rowToSubject(rows[0]);
+ });
+ // display_name is PII — log the id + relationship only (privacyVault.js posture).
+ console.log(`👤 Created privacy subject ${id} (relationship=${resolvedRelationship}, consent=${consentMethod})`);
+ return subject;
+}
+
+export async function updateSubject(id, patch) {
+ const sets = [];
+ const params = [];
+ const add = (column, value) => {
+ params.push(value);
+ sets.push(`${column} = $${params.length}`);
+ };
+ if (patch.displayName !== undefined) add('display_name', patch.displayName);
+ if (patch.relationship !== undefined) add('relationship', patch.relationship);
+ if (sets.length === 0) return assertSubject(id);
+ params.push(id);
+ const { rows } = await query(
+ `UPDATE privacy_subjects SET ${[...sets, 'updated_at = NOW()'].join(', ')}
+ WHERE id = $${params.length} RETURNING ${SUBJECT_COLUMNS}`,
+ params,
+ );
+ if (!rows[0]) throw new ServerError('Privacy subject not found', { status: 404, code: 'SUBJECT_NOT_FOUND' });
+ console.log(`👤 Updated privacy subject ${id}`);
+ return rowToSubject(rows[0]);
+}
+
+/**
+ * Hard-delete a subject and, by FK CASCADE, every record scoped to them (vault
+ * records, orgs, holdings, change events, broker cases, consents). Machine-local
+ * means no tombstone — the ADR's hard-delete rule applies unchanged.
+ *
+ * `self` can never be deleted: it is the default every subject-scoped column
+ * falls back to, so removing it would break every subsequent insert.
+ */
+export async function deleteSubject(id) {
+ if (resolveSubjectId(id) === PRIVACY_SELF_SUBJECT_ID) {
+ throw new ServerError(
+ 'The `self` subject cannot be deleted',
+ { status: 400, code: 'SELF_SUBJECT_UNDELETABLE' },
+ );
+ }
+ const { rows } = await query(`DELETE FROM privacy_subjects WHERE id = $1 RETURNING id`, [id]);
+ if (!rows[0]) throw new ServerError('Privacy subject not found', { status: 404, code: 'SUBJECT_NOT_FOUND' });
+ console.log(`🗑️ Deleted privacy subject ${id} (vault/orgs/holdings/changes/cases cascaded)`);
+ return { ok: true };
+}
+
+// ─── Consent gate (engine-enforced) ─────────────────────────────────────────
+
+/** The consent audit trail for one subject, newest first. */
+export async function listSubjectConsents(subjectId) {
+ const resolved = resolveSubjectId(subjectId);
+ const { rows } = await query(
+ `SELECT id, subject_id, scope, method, note, granted_at
+ FROM privacy_consents WHERE subject_id = $1 ORDER BY granted_at DESC`,
+ [resolved],
+ );
+ return rows.map((row) => ({
+ id: row.id,
+ subjectId: row.subject_id,
+ scope: row.scope,
+ method: row.method,
+ note: row.note ?? '',
+ grantedAt: row.granted_at,
+ }));
+}
+
+/**
+ * Does this subject have active consent on file? ANY consent row counts — there
+ * is no revocation column, because revoking consent means deleting the subject
+ * (which hard-deletes their records; see deleteSubject). Callers that need a
+ * hard stop use assertSubjectConsent instead.
+ */
+export async function hasActiveConsent(subjectId) {
+ const resolved = resolveSubjectId(subjectId);
+ const { rows } = await query(
+ `SELECT 1 FROM privacy_consents WHERE subject_id = $1 LIMIT 1`, [resolved],
+ );
+ return rows.length > 0;
+}
+
+/**
+ * THE consent guard. `privacyScan` and `privacyOptOut` call this before any
+ * broker work — a subject with no consent row on file gets a hard refusal, at
+ * the SERVICE layer, so a scheduled recheck / direct API call / future agent
+ * path is refused exactly like a UI click would be. Mirrors the existing
+ * disclosure-allowlist guard in privacyOptOut.js: the engine's guarantees do not
+ * live in the UI.
+ *
+ * Returns the subject row so callers can log/annotate without a second read.
+ */
+export async function assertSubjectConsent(subjectId, { action = 'this action' } = {}) {
+ const subject = await assertSubject(subjectId);
+ if (await hasActiveConsent(subject.id)) return subject;
+ console.log(`⛔ Refused ${action} for privacy subject ${subject.id}: no consent on file`);
+ throw new ServerError(
+ `Privacy subject ${subject.id} has no recorded consent — ${action} refused`,
+ { status: 403, code: 'SUBJECT_CONSENT_REQUIRED' },
+ );
+}
diff --git a/server/services/privacySubjects.test.js b/server/services/privacySubjects.test.js
new file mode 100644
index 0000000000..7554e5e399
--- /dev/null
+++ b/server/services/privacySubjects.test.js
@@ -0,0 +1,196 @@
+/**
+ * Household-subject service unit tests (issue #3658) — DB mocked.
+ *
+ * Pins the three contracts other privacy services depend on:
+ * - `self` resolution: an absent subjectId is the seeded `self` row, so every
+ * pre-#3658 caller keeps its old behaviour.
+ * - subject creation writes the consent row in the SAME transaction, so a
+ * subject can never exist without recorded consent.
+ * - `assertSubjectConsent` REFUSES (403) a subject with no consent row — the
+ * engine-enforced half of the no-consent-no-action rule.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { queryMock, withTransactionMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+ withTransactionMock: vi.fn(),
+}));
+
+vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: withTransactionMock }));
+
+const {
+ resolveSubjectId, createSubject, updateSubject, deleteSubject,
+ listSubjects, assertSubject, hasActiveConsent, assertSubjectConsent, recordConsent,
+} = await import('./privacySubjects.js');
+const { PRIVACY_SELF_SUBJECT_ID } = await import('../lib/privacyValidation.js');
+
+const subjectRow = (overrides = {}) => ({
+ id: PRIVACY_SELF_SUBJECT_ID, display_name: 'Me', relationship: 'self',
+ created_at: 'now', updated_at: 'now', ...overrides,
+});
+
+beforeEach(() => {
+ queryMock.mockReset();
+ withTransactionMock.mockReset();
+});
+
+describe('resolveSubjectId', () => {
+ it('falls back to the seeded `self` row for an absent or empty id', () => {
+ expect(resolveSubjectId()).toBe(PRIVACY_SELF_SUBJECT_ID);
+ expect(resolveSubjectId(undefined)).toBe(PRIVACY_SELF_SUBJECT_ID);
+ expect(resolveSubjectId('')).toBe(PRIVACY_SELF_SUBJECT_ID);
+ });
+
+ it('passes an explicit id through untouched', () => {
+ expect(resolveSubjectId('11111111-2222-4333-8444-555555555555')).toBe('11111111-2222-4333-8444-555555555555');
+ });
+});
+
+describe('createSubject', () => {
+ it('writes the subject AND its consent row inside ONE transaction', async () => {
+ const client = { query: vi.fn(async (sql) => (/INSERT INTO privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2', display_name: 'Alex Example', relationship: 'partner' })] }
+ : { rows: [] })) };
+ withTransactionMock.mockImplementation(async (fn) => fn(client));
+
+ const subject = await createSubject({
+ displayName: 'Alex Example', relationship: 'partner', consentMethod: 'signed_form',
+ });
+
+ expect(withTransactionMock).toHaveBeenCalledTimes(1);
+ const consentInsert = client.query.mock.calls.find(([sql]) => /INSERT INTO privacy_consents/.test(sql));
+ expect(consentInsert).toBeDefined();
+ expect(consentInsert[1][2]).toBe('signed_form'); // method
+ expect(subject).toMatchObject({ id: 's2', relationship: 'partner', isSelf: false });
+ });
+
+ it('never logs the subject display name — it is PII, like the vault plaintext', async () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const client = { query: vi.fn(async (sql) => (/INSERT INTO privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2', display_name: 'Alex Example', relationship: 'partner' })] }
+ : { rows: [] })) };
+ withTransactionMock.mockImplementation(async (fn) => fn(client));
+ await createSubject({ displayName: 'Alex Example', consentMethod: 'verbal' });
+ const logged = logSpy.mock.calls.map((args) => args.join(' ')).join('\n');
+ expect(logged).not.toContain('Alex Example');
+ logSpy.mockRestore();
+ });
+});
+
+describe('assertSubject', () => {
+ it('404s an unknown subject rather than letting a raw FK violation surface', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(assertSubject('11111111-2222-4333-8444-555555555555'))
+ .rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });
+ });
+
+ it('resolves an absent id to `self`', async () => {
+ queryMock.mockResolvedValue({ rows: [subjectRow()] });
+ const subject = await assertSubject();
+ expect(queryMock.mock.calls[0][1]).toEqual([PRIVACY_SELF_SUBJECT_ID]);
+ expect(subject.isSelf).toBe(true);
+ });
+});
+
+describe('updateSubject', () => {
+ it('builds a partial SET clause for only the provided fields', async () => {
+ queryMock.mockResolvedValue({ rows: [subjectRow({ display_name: 'Renamed' })] });
+ await updateSubject('s2', { displayName: 'Renamed' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/SET display_name = \$1, updated_at = NOW\(\)/);
+ expect(params).toEqual(['Renamed', 's2']);
+ });
+
+ it('404s an unknown subject', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(updateSubject('s2', { displayName: 'x' }))
+ .rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });
+ });
+});
+
+describe('deleteSubject', () => {
+ it('refuses to delete `self` — every subject_id column defaults to it', async () => {
+ await expect(deleteSubject(PRIVACY_SELF_SUBJECT_ID))
+ .rejects.toMatchObject({ status: 400, code: 'SELF_SUBJECT_UNDELETABLE' });
+ expect(queryMock).not.toHaveBeenCalled();
+ });
+
+ it('hard-deletes a household member (records cascade — no tombstone)', async () => {
+ queryMock.mockResolvedValue({ rows: [{ id: 's2' }] });
+ expect(await deleteSubject('s2')).toEqual({ ok: true });
+ expect(queryMock.mock.calls[0][0]).toMatch(/DELETE FROM privacy_subjects/);
+ });
+
+ it('404s an unknown subject', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(deleteSubject('s2')).rejects.toMatchObject({ status: 404 });
+ });
+});
+
+describe('listSubjects', () => {
+ it('returns `self` first and carries consent/record counts for the UI switcher', async () => {
+ queryMock.mockResolvedValue({
+ rows: [
+ { ...subjectRow(), consent_count: 1, record_count: 4 },
+ { ...subjectRow({ id: 's2', display_name: 'Alex Example', relationship: 'partner' }), consent_count: 0, record_count: 0 },
+ ],
+ });
+ const subjects = await listSubjects();
+ expect(subjects[0].isSelf).toBe(true);
+ expect(subjects[0]).toMatchObject({ consentCount: 1, recordCount: 4 });
+ expect(subjects[1]).toMatchObject({ isSelf: false, consentCount: 0 });
+ // The ORDER BY must put `self` first regardless of display name.
+ expect(queryMock.mock.calls[0][0]).toMatch(/ORDER BY \(s\.id <> \$1\)/);
+ });
+});
+
+describe('recordConsent', () => {
+ it('scopes the row by subject_id and stores the note verbatim', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ const consent = await recordConsent({
+ subjectId: 's2', scope: 'broker_optout', method: 'written', note: 'form filed 2026-01-01',
+ });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/INSERT INTO privacy_consents/);
+ expect(params[1]).toBe('s2');
+ expect(params[2]).toBe('broker_optout');
+ expect(params[3]).toBe('written');
+ expect(params[4]).toBe('form filed 2026-01-01');
+ expect(consent).toMatchObject({ subjectId: 's2', scope: 'broker_optout', method: 'written' });
+ });
+});
+
+describe('consent gate', () => {
+ it('hasActiveConsent is true when ANY consent row exists for the subject', async () => {
+ queryMock.mockResolvedValue({ rows: [{ '?column?': 1 }] });
+ expect(await hasActiveConsent('s2')).toBe(true);
+ expect(queryMock.mock.calls[0][1]).toEqual(['s2']);
+ });
+
+ it('hasActiveConsent is false when the subject has no rows', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ expect(await hasActiveConsent('s2')).toBe(false);
+ });
+
+ it('assertSubjectConsent REFUSES a consentless subject with a 403', async () => {
+ queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2', relationship: 'partner' })] }
+ : { rows: [] }));
+ await expect(assertSubjectConsent('s2', { action: 'broker opt-out pass' }))
+ .rejects.toMatchObject({ status: 403, code: 'SUBJECT_CONSENT_REQUIRED' });
+ });
+
+ it('assertSubjectConsent returns the subject when consent is on file', async () => {
+ queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2', relationship: 'partner' })] }
+ : { rows: [{ '?column?': 1 }] }));
+ await expect(assertSubjectConsent('s2')).resolves.toMatchObject({ id: 's2' });
+ });
+
+ it('assertSubjectConsent 404s before it ever checks consent for an unknown subject', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(assertSubjectConsent('s2')).rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });
+ expect(queryMock).toHaveBeenCalledTimes(1); // no consent probe
+ });
+});
diff --git a/server/services/privacyTwinContext.js b/server/services/privacyTwinContext.js
index 751710d671..7482249a3f 100644
--- a/server/services/privacyTwinContext.js
+++ b/server/services/privacyTwinContext.js
@@ -22,7 +22,7 @@
*/
import { query } from '../lib/db.js';
-import { PRIVACY_SENSITIVE_TYPES } from '../lib/privacyValidation.js';
+import { PRIVACY_SENSITIVE_TYPES, PRIVACY_SELF_SUBJECT_ID } from '../lib/privacyValidation.js';
// vaultCrypto is imported lazily (inside getPrivacyTwinContext) so merely
// importing this module — which digital-twin-context.js does at top level —
// doesn't eagerly evaluate vaultCrypto's install-root .env path resolution.
@@ -36,7 +36,9 @@ const REMOVED_BROKER_STATES = new Set(['removed', 'confirmed_removed', 'suppress
/** One-line "Organizations on file" summary (counts by trust + category span). */
async function buildOrgSummary() {
- const { rows } = await query(`SELECT trust, category FROM privacy_orgs`);
+ // Scoped to `self`: the Digital Twin models the install's OWNER, so a
+ // household member's orgs/cases/records must never enter its prompt (#3658).
+ const { rows } = await query(`SELECT trust, category FROM privacy_orgs WHERE subject_id = $1`, [PRIVACY_SELF_SUBJECT_ID]);
if (rows.length === 0) return '';
const byTrust = {};
const categories = new Set();
@@ -54,7 +56,7 @@ async function buildOrgSummary() {
/** One-line data-broker opt-out posture (only when Phase 5/6 tables exist). */
async function buildBrokerPosture() {
- const { rows } = await query(`SELECT state FROM privacy_broker_cases`);
+ const { rows } = await query(`SELECT state FROM privacy_broker_cases WHERE subject_id = $1`, [PRIVACY_SELF_SUBJECT_ID]);
if (rows.length === 0) return '';
let removed = 0;
for (const row of rows) if (REMOVED_BROKER_STATES.has(row.state)) removed += 1;
@@ -90,9 +92,10 @@ export async function getPrivacyTwinContext() {
`SELECT type, label, status, value_enc
FROM privacy_vault_records
WHERE share_with_twin = true
+ AND subject_id = $2
AND type <> ALL($1::text[])
ORDER BY type, label`,
- [PRIVACY_SENSITIVE_TYPES],
+ [PRIVACY_SENSITIVE_TYPES, PRIVACY_SELF_SUBJECT_ID],
);
if (records.length > 0) {
const { decryptValue } = await import('../lib/vaultCrypto.js');
diff --git a/server/services/privacyVault.js b/server/services/privacyVault.js
index 7d268ae532..369a954bda 100644
--- a/server/services/privacyVault.js
+++ b/server/services/privacyVault.js
@@ -26,12 +26,17 @@ import {
encryptValue, decryptValue, ensureVaultKey, isVaultKeyConfigured, maskValue,
} from '../lib/vaultCrypto.js';
import { PRIVACY_SENSITIVE_TYPES, PRIVACY_SCAN_DEFAULT_TYPES } from '../lib/privacyValidation.js';
+import { resolveSubjectId, assertSubject, recordConsent } from './privacySubjects.js';
+
+// Re-exported so the pre-#3658 deep import `privacyVault.recordConsent` keeps
+// working; the consent trail itself now lives with the subjects that own it.
+export { recordConsent };
// Everything EXCEPT value_enc — list/read responses never carry ciphertext.
// DATE columns come back via to_char as plain 'YYYY-MM-DD' strings: node-postgres
// otherwise parses DATE into a local-midnight JS Date, and re-serializing that
// through toISOString() shifts the date back a day in UTC+N timezones.
-const RECORD_COLUMNS = `id, type, label, masked_value, status,
+const RECORD_COLUMNS = `id, subject_id, type, label, masked_value, status,
to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
to_char(valid_to, 'YYYY-MM-DD') AS valid_to,
share_with_twin, use_for_scans, notes, created_at, updated_at`;
@@ -40,6 +45,7 @@ function rowToRecord(row) {
if (!row) return null;
return {
id: row.id,
+ subjectId: row.subject_id,
type: row.type,
label: row.label,
maskedValue: row.masked_value,
@@ -66,33 +72,28 @@ export function resolveUseForScans(type, requested) {
return PRIVACY_SCAN_DEFAULT_TYPES.includes(type);
}
-/** Write an explicit consent row (subject defaults to 'self' for v1). */
-export async function recordConsent({ subject = 'self', scope, method }) {
- const id = randomUUID();
- await query(
- `INSERT INTO privacy_consents (id, subject, scope, method, granted_at)
- VALUES ($1, $2, $3, $4, NOW())`,
- [id, subject, scope, method],
- );
- console.log(`📝 Recorded privacy consent ${id} (scope=${scope}, method=${method})`);
- return { id, subject, scope, method };
-}
-
export async function createVaultRecord(input) {
await ensureVaultKey(); // self-heal a missing key on first write
+ // A bogus subjectId must 404 up front rather than trip a raw FK violation.
+ const subjectId = (await assertSubject(input.subjectId)).id;
const id = randomUUID();
const useForScans = resolveUseForScans(input.type, input.useForScans);
- // First-ever record ⇒ write the consent row (audit trail for the opt-out engine).
- const { rows: countRows } = await query(`SELECT COUNT(*)::int AS n FROM privacy_vault_records`);
- const isFirstRecord = countRows[0].n === 0;
+ // First record FOR THIS SUBJECT ⇒ write the consent row (audit trail for the
+ // opt-out engine). Scoped per subject so a household member added directly
+ // through the vault still gets a consent row of their own rather than riding
+ // on `self`'s.
+ const { rows: countRows } = await query(
+ `SELECT COUNT(*)::int AS n FROM privacy_consents WHERE subject_id = $1`, [subjectId],
+ );
+ const needsConsent = countRows[0].n === 0;
const { rows } = await query(
`INSERT INTO privacy_vault_records
- (id, type, label, value_enc, masked_value, status, valid_from, valid_to,
+ (id, subject_id, type, label, value_enc, masked_value, status, valid_from, valid_to,
share_with_twin, use_for_scans, notes, created_at, updated_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW(), NOW())
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NOW(), NOW())
RETURNING ${RECORD_COLUMNS}`,
[
- id, input.type, input.label,
+ id, subjectId, input.type, input.label,
encryptValue(input.value), maskValue(input.type, input.value),
input.status ?? 'current',
input.validFrom ?? null, input.validTo ?? null,
@@ -100,17 +101,26 @@ export async function createVaultRecord(input) {
input.notes ?? '',
],
);
- if (isFirstRecord) {
- await recordConsent({ scope: 'pii_vault', method: 'vault-record-create' });
+ if (needsConsent) {
+ await recordConsent({ subjectId, scope: 'pii_vault', method: 'vault-record-create' });
}
- console.log(`🔐 Created vault record ${id} (type=${input.type})`);
+ console.log(`🔐 Created vault record ${id} (subject=${subjectId}, type=${input.type})`);
return rowToRecord(rows[0]);
}
-export async function listVaultRecords({ type } = {}) {
- const { rows } = type
- ? await query(`SELECT ${RECORD_COLUMNS} FROM privacy_vault_records WHERE type = $1 ORDER BY created_at DESC`, [type])
- : await query(`SELECT ${RECORD_COLUMNS} FROM privacy_vault_records ORDER BY created_at DESC`);
+export async function listVaultRecords({ type, subjectId } = {}) {
+ // Always scoped to ONE subject — an unscoped list would mix two household
+ // members' identity facts into one table, which is exactly what this scoping
+ // exists to prevent. Omitting subjectId means `self`, so every pre-#3658
+ // caller is unchanged.
+ const params = [resolveSubjectId(subjectId)];
+ const clauses = ['subject_id = $1'];
+ if (type) { params.push(type); clauses.push(`type = ${params.length}`); }
+ const { rows } = await query(
+ `SELECT ${RECORD_COLUMNS} FROM privacy_vault_records
+ WHERE ${clauses.join(' AND ')} ORDER BY created_at DESC`,
+ params,
+ );
return rows.map(rowToRecord);
}
@@ -189,14 +199,16 @@ export async function revealValue(id) {
* still list an old address). Plaintext is returned to the caller but never
* logged — the count is.
*/
-export async function listScanEligibleValues() {
+export async function listScanEligibleValues({ subjectId } = {}) {
+ const resolvedSubjectId = resolveSubjectId(subjectId);
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
+ WHERE use_for_scans = TRUE AND subject_id = $1
ORDER BY type, created_at`,
+ [resolvedSubjectId],
);
const values = rows.map((row) => ({
id: row.id,
@@ -206,16 +218,19 @@ export async function listScanEligibleValues() {
validFrom: row.valid_from ?? null,
validTo: row.valid_to ?? null,
}));
- console.log(`🔎 Assembled ${values.length} scan-eligible vault values`);
+ console.log(`🔎 Assembled ${values.length} scan-eligible vault values (subject=${resolvedSubjectId})`);
return values;
}
/** Doctor-style readout: { keyConfigured, recordCounts: { <type>: n } }. */
-export async function getVaultStatus() {
+export async function getVaultStatus({ subjectId } = {}) {
+ const resolvedSubjectId = resolveSubjectId(subjectId);
const { rows } = await query(
- `SELECT type, COUNT(*)::int AS n FROM privacy_vault_records GROUP BY type ORDER BY type`,
+ `SELECT type, COUNT(*)::int AS n FROM privacy_vault_records
+ WHERE subject_id = $1 GROUP BY type ORDER BY type`,
+ [resolvedSubjectId],
);
const recordCounts = {};
for (const row of rows) recordCounts[row.type] = row.n;
- return { keyConfigured: isVaultKeyConfigured(), recordCounts };
+ return { keyConfigured: isVaultKeyConfigured(), subjectId: resolvedSubjectId, recordCounts };
}
diff --git a/server/services/privacyVault.test.js b/server/services/privacyVault.test.js
index c2ad3d2675..559a90ff42 100644
--- a/server/services/privacyVault.test.js
+++ b/server/services/privacyVault.test.js
@@ -18,6 +18,16 @@ vi.mock('../lib/db.js', () => ({
withTransaction: withTransactionMock,
}));
+// #3658: the subject scope + consent trail live in privacySubjects; stubbed so
+// these DB-mocked tests keep asserting on the privacy_vault_records SQL.
+const SELF = '00000000-0000-4000-8000-000000000001';
+const { recordConsentMock } = vi.hoisted(() => ({ recordConsentMock: vi.fn(async () => ({ id: 'consent-1' })) }));
+vi.mock('./privacySubjects.js', () => ({
+ resolveSubjectId: (id) => id || SELF,
+ assertSubject: vi.fn(async (id) => ({ id: id || SELF })),
+ recordConsent: recordConsentMock,
+}));
+
const {
createVaultRecord, updateVaultRecord, revealValue, getVaultStatus, resolveUseForScans,
} = await import('./privacyVault.js');
@@ -38,13 +48,15 @@ beforeEach(() => {
});
const insertedRow = (params) => ({
- id: params[0], type: params[1], label: params[2], masked_value: params[4],
- status: params[5], valid_from: params[6], valid_to: params[7],
- share_with_twin: params[8], use_for_scans: params[9], notes: params[10],
+ id: params[0], subject_id: params[1], type: params[2], label: params[3], masked_value: params[5],
+ status: params[6], valid_from: params[7], valid_to: params[8],
+ share_with_twin: params[9], use_for_scans: params[10], notes: params[11],
created_at: 'now', updated_at: 'now',
});
-// queryMock playbook for createVaultRecord: COUNT probe → INSERT → (consent INSERT).
+// queryMock playbook for createVaultRecord: consent COUNT probe → INSERT.
+// `existingCount` is the subject's EXISTING CONSENT-row count (#3658): 0 means
+// this create also writes the subject's first consent row.
function mockCreateFlow({ existingCount = 1 } = {}) {
queryMock.mockImplementation(async (sql, params) => {
if (/COUNT\(\*\)/.test(sql)) return { rows: [{ n: existingCount }] };
@@ -82,8 +94,9 @@ describe('createVaultRecord', () => {
const record = await createVaultRecord({ type: 'ssn', label: 'My SSN', value: '123-45-6789' });
const insert = queryMock.mock.calls.find(([sql]) => /INSERT INTO privacy_vault_records/.test(sql));
const params = insert[1];
- expect(params[3]).toMatch(/^v1:/); // value_enc
- expect(params[4]).toBe('••••6789'); // masked_value
+ expect(params[1]).toBe(SELF); // subject scope defaults to `self` (#3658)
+ expect(params[4]).toMatch(/^v1:/); // value_enc
+ expect(params[5]).toBe('••••6789'); // masked_value
expect(params).not.toContain('123-45-6789');
expect(record.maskedValue).toBe('••••6789');
expect(record.useForScans).toBe(false); // ssn is hard-false
@@ -97,15 +110,24 @@ describe('createVaultRecord', () => {
expect(record.useForScans).toBe(true);
});
- it('writes a consent row on the FIRST record only', async () => {
+ it("writes a consent row on the subject's FIRST record only", async () => {
+ recordConsentMock.mockClear();
mockCreateFlow({ existingCount: 0 });
await createVaultRecord({ type: 'email', label: 'Main', value: '[email protected]' });
- expect(queryMock.mock.calls.some(([sql]) => /INSERT INTO privacy_consents/.test(sql))).toBe(true);
+ expect(recordConsentMock).toHaveBeenCalledWith({ subjectId: SELF, scope: 'pii_vault', method: 'vault-record-create' });
- queryMock.mockClear();
+ recordConsentMock.mockClear();
mockCreateFlow({ existingCount: 3 });
await createVaultRecord({ type: 'email', label: 'Alt', value: '[email protected]' });
- expect(queryMock.mock.calls.some(([sql]) => /INSERT INTO privacy_consents/.test(sql))).toBe(false);
+ expect(recordConsentMock).not.toHaveBeenCalled();
+ });
+
+ it('scopes the record to an explicit household subject when one is given (#3658)', async () => {
+ mockCreateFlow();
+ const record = await createVaultRecord({ type: 'email', label: 'Main', value: '[email protected]', subjectId: 'subject-2' });
+ const insert = queryMock.mock.calls.find(([sql]) => /INSERT INTO privacy_vault_records/.test(sql));
+ expect(insert[1][1]).toBe('subject-2');
+ expect(record.subjectId).toBe('subject-2');
});
});
@@ -164,6 +186,7 @@ describe('getVaultStatus', () => {
queryMock.mockResolvedValue({ rows: [{ type: 'email', n: 2 }, { type: 'ssn', n: 1 }] });
expect(await getVaultStatus()).toEqual({
keyConfigured: true,
+ subjectId: SELF,
recordCounts: { email: 2, ssn: 1 },
});
});
diff --git a/server/services/sharing/privacyNeverFederates.test.js b/server/services/sharing/privacyNeverFederates.test.js
index 190c985c6f..5aeac70670 100644
--- a/server/services/sharing/privacyNeverFederates.test.js
+++ b/server/services/sharing/privacyNeverFederates.test.js
@@ -53,7 +53,7 @@ describe('privacy records never federate (ADR 2026-08-08, #2148)', () => {
it('gives no privacy table a sync cursor or tombstone column', () => {
// Sanity: if the filter ever matches nothing the assertions below are
// vacuous, so pin the table count we expect to be guarding.
- expect(privacyCreateTableStatements).toHaveLength(7);
+ expect(privacyCreateTableStatements).toHaveLength(8);
for (const stmt of privacyCreateTableStatements) {
const table = stmt.match(/privacy_[a-z_]+/i)?.[0];
for (const column of FEDERATION_COLUMNS) {