Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2140]): encrypted PII vault — crypto, schema, service, API
Adam Eivy52d8ab6643c4
diff --git a/.env.example b/.env.exampleindex 68b84835be..07df40b321 100644--- a/.env.example+++ b/.env.example@@ -109,3 +109,9 @@ PGPASSWORD=portos# Ollama context window size passed to new model loads (default: 32768)# OLLAMA_NUM_CTX=32768++# Privacy Center PII Vault encryption key — 32 bytes, hex (64 chars) or base64.+# Auto-generated and appended to .env on the first vault write if unset. Back+# it up: losing it makes every encrypted vault value unrecoverable.+# PRIVACY_VAULT_KEY=<64 hex chars>+diff --git a/scripts/migrations/160-privacy-vault-tables.js b/scripts/migrations/160-privacy-vault-tables.jsnew file mode 100644index 0000000000..049cc55b31--- /dev/null+++ b/scripts/migrations/160-privacy-vault-tables.js@@ -0,0 +1,28 @@+/**+ * Registration stub for the Privacy Center PII Vault tables (issue #2140,+ * epic #2138).+ *+ * The actual DDL — `CREATE TABLE IF NOT EXISTS privacy_vault_records` (+ its+ * `idx_privacy_vault_records_type` index) and `privacy_consents` — is+ * idempotent and lives in `ensureSchema()` (`server/lib/db.js`) and the+ * fresh-install seed (`server/scripts/init-db.sql`), both of which run at+ * server boot AFTER the DB pool is up. The `scripts/migrations/` runner+ * executes BEFORE the pool is initialized, so a DB-table create cannot live+ * here — the same reason migrations 048–052 and 108 are boot-time ++ * stub-registered.+ *+ * This stub exists so the new-table change is *registered the standard way*:+ * it lands in `data/migrations.applied.json` so the migration ledger and+ * `git log` show when the privacy tables were introduced. Both tables are+ * additive (brand-new, machine-local db-primary stores) with no data+ * backfill — the privacyVault service populates them lazily on the first+ * vault record create (which also self-heals PRIVACY_VAULT_KEY into `.env`).+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🔐 privacy_vault_records/privacy_consents: tables created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex d3b74a68ed..d76eb42800 100644--- a/server/index.js+++ b/server/index.js@@ -111,6 +111,7 @@ import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';import musicVideoRoutes from './routes/musicVideo.js';import moodBoardRoutes from './routes/moodBoard.js';+import privacyRoutes from './routes/privacy.js';import writersRoomRoutes from './routes/writersRoom.js';import universeBuilderRoutes from './routes/universeBuilder.js';import authorsRoutes from './routes/authors.js';@@ -520,6 +521,7 @@ app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/music-video', musicVideoRoutes);app.use('/api/mood-boards', moodBoardRoutes);+app.use('/api/privacy', privacyRoutes);app.use('/api/writers-room', writersRoomRoutes);app.use('/api/universe-builder', universeBuilderRoutes);app.use('/api/authors', authorsRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 067774464a..1a682f244f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -42,6 +42,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). || `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). || `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. |+| `privacyValidation.js` | Privacy Center PII Vault schemas (issue #2140) — vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. || `socketValidation.js` | Socket event payload schemas. || `storyBuilderValidation.js` | Unified Story Builder session/step schemas. || `telegramValidation.js` | Telegram bot config + test schemas. |@@ -220,6 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. || `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. || `telegramClient.js` | Telegram bot client. |+| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into `.env` on first write, never logs the value), `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |## Model & configdiff --git a/server/lib/db.js b/server/lib/db.jsindex 531a4c081a..d5b9d2103a 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -1254,6 +1254,42 @@ async function ensureSchemaImpl() {`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: 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);+ // plaintext is NEVER stored, `masked_value` is the display form. Machine-+ // local: no federation, no tombstones (deferred, #2148) — a delete is a+ // hard DELETE. `use_for_scans` gates which facts the broker scan engine+ // may disclose (hard-false for ssn/passport/drivers_license/+ // financial_account — enforced app-side). Mirrors the privacy blocks in+ // init-db.sql.+ `CREATE TABLE IF NOT EXISTS privacy_vault_records (+ id UUID PRIMARY KEY,+ type TEXT NOT NULL,+ label TEXT NOT NULL DEFAULT '',+ value_enc TEXT NOT NULL,+ masked_value TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT 'current',+ valid_from DATE,+ valid_to DATE,+ share_with_twin BOOLEAN NOT NULL DEFAULT FALSE,+ use_for_scans BOOLEAN NOT NULL DEFAULT FALSE,+ notes TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ // 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.+ `CREATE TABLE IF NOT EXISTS privacy_consents (+ id UUID PRIMARY KEY,+ subject TEXT NOT NULL DEFAULT 'self',+ scope TEXT NOT NULL,+ method TEXT NOT NULL,+ granted_at TIMESTAMPTZ DEFAULT NOW()+ )`,+// ─── Deletion audit log (incident #1248-follow-up) ──────────────────────// Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone// (recovery), and hard-delete of user-authored records — written by a DBdiff --git a/server/lib/index.js b/server/lib/index.jsindex cef1b1ae7c..6921b16aff 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -34,6 +34,7 @@ export * as notesValidation from './notesValidation.js';export * as peerSyncValidation from './peerSyncValidation.js';export * as pipelineValidation from './pipelineValidation.js';export * as postValidation from './postValidation.js';+export * as privacyValidation from './privacyValidation.js';export * as socketValidation from './socketValidation.js';export * as storyBuilderValidation from './storyBuilderValidation.js';export * as telegramValidation from './telegramValidation.js';@@ -196,6 +197,7 @@ export * from './planIds.js';export * from './renderSlot.js';export * from './telegramClient.js';export * from './textUtils.js';+export * from './vaultCrypto.js';// === Model & config ===export * from './browserConfig.js';diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.jsnew file mode 100644index 0000000000..efcd256aa0--- /dev/null+++ b/server/lib/privacyValidation.js@@ -0,0 +1,78 @@+import { z } from 'zod';++// =============================================================================+// PRIVACY CENTER SCHEMAS (issue #2140, epic #2138)+// =============================================================================+// Zod schemas for the encrypted PII Vault. Records are db-primary Postgres+// (`privacy_vault_records` / `privacy_consents`), machine-local (federation is+// a deferred child issue). validation.js re-exports everything here so deep+// imports keep working; the lib barrel also namespace-exports this module as+// `privacyValidation`.++export const PRIVACY_VAULT_TYPES = Object.freeze([+ 'legal_name', 'address', 'phone', 'email', 'dob',+ 'ssn', 'passport', 'drivers_license', 'financial_account', 'custom',+]);++// Types that may NEVER be used for broker scans — `use_for_scans: true` is+// rejected at the API AND hard-forced false in the service (defense in depth).+// Disclosing these to a data broker's search form is never least-disclosure.+export const PRIVACY_SENSITIVE_TYPES = Object.freeze([+ 'ssn', 'passport', 'drivers_license', 'financial_account',+]);++// Types whose `use_for_scans` DEFAULTS to true (broker scans need name /+// contact facts to find listings). Everything else defaults false.+export const PRIVACY_SCAN_DEFAULT_TYPES = Object.freeze([+ 'legal_name', 'email', 'phone', 'address',+]);++export const PRIVACY_VAULT_STATUSES = Object.freeze(['current', 'previous']);++// ISO calendar date (DATE column) — nullable to clear.+const isoDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'expected YYYY-MM-DD').nullable().optional();++const rejectSensitiveScans = (val, ctx) => {+ if (val.useForScans === true && PRIVACY_SENSITIVE_TYPES.includes(val.type)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['useForScans'],+ message: `useForScans cannot be true for sensitive type "${val.type}"`,+ });+ }+};++export const privacyVaultCreateSchema = z.object({+ type: z.enum(PRIVACY_VAULT_TYPES),+ label: z.string().trim().min(1).max(200),+ value: z.string().min(1).max(10000),+ status: z.enum(PRIVACY_VAULT_STATUSES).optional(),+ validFrom: isoDateSchema,+ validTo: isoDateSchema,+ shareWithTwin: z.boolean().optional(),+ useForScans: z.boolean().optional(),+ notes: z.string().max(5000).optional(),+}).strict().superRefine(rejectSensitiveScans);++// PUT is a partial update. `type` is immutable (it drives masking + scan+// defaults; changing a record's type is a delete + re-create). The sensitive+// use_for_scans hard-false is re-enforced in the service against the STORED+// type, since the schema can't see it here.+export const privacyVaultUpdateSchema = z.object({+ label: z.string().trim().min(1).max(200).optional(),+ value: z.string().min(1).max(10000).optional(),+ status: z.enum(PRIVACY_VAULT_STATUSES).optional(),+ validFrom: isoDateSchema,+ validTo: isoDateSchema,+ shareWithTwin: z.boolean().optional(),+ useForScans: z.boolean().optional(),+ notes: z.string().max(5000).optional(),+}).strict();++export const privacyVaultListQuerySchema = z.object({+ type: z.enum(PRIVACY_VAULT_TYPES).optional(),+}).strict();++export const privacyVaultIdParamsSchema = z.object({+ id: z.string().uuid(),+}).strict();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ebd9d4690a..beb79cfb0a 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -612,6 +612,7 @@ export * from './creativeDirectorValidation.js';export * from './musicVideoValidation.js';export * from './storyBuilderValidation.js';export * from './moodBoardValidation.js';+export * from './privacyValidation.js';export * from './agentValidation.js';export * from './cosValidation.js';export * from './mediaValidation.js';diff --git a/server/lib/vaultCrypto.js b/server/lib/vaultCrypto.jsnew file mode 100644index 0000000000..c58598a63a--- /dev/null+++ b/server/lib/vaultCrypto.js@@ -0,0 +1,147 @@+/**+ * Vault Crypto — field-level AES-256-GCM for the Privacy Center PII Vault+ * (issue #2140, epic #2138). PortOS's first encrypted-at-rest layer.+ *+ * Ciphertext format (versioned for future key rotation):+ * `v1:<iv_b64>:<tag_b64>:<ct_b64>`+ * — per-value random 12-byte IV, 16-byte GCM auth tag. Any tampering with the+ * IV, tag, or ciphertext makes decryptValue throw (GCM authentication).+ *+ * Key: 32 bytes from env `PRIVACY_VAULT_KEY` (hex or base64 — see+ * `.env.example`). `ensureVaultKey()` self-heals a missing key on first write:+ * generates via randomBytes(32), appends it to `.env`, and logs ONE emoji line+ * that never contains the key value.+ *+ * Masking lives here too (pure, no DB) so list/read responses can show a+ * recognizable-but-safe value while plaintext stays encrypted at rest.+ * Plaintext PII must NEVER be logged — callers log ids/types only.+ */++import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';+import { join } from 'path';+import { PATHS, tryReadFile, atomicWrite } from './fileUtils.js';++const CIPHER = 'aes-256-gcm';+const IV_BYTES = 12;+const KEY_BYTES = 32;+const FORMAT_VERSION = 'v1';++const DEFAULT_ENV_PATH = join(PATHS.root, '.env');++/** Parse a hex- or base64-encoded 32-byte key; null when absent/invalid. */+function parseKey(raw) {+ if (typeof raw !== 'string') return null;+ const value = raw.trim();+ if (!value) return null;+ if (/^[0-9a-fA-F]{64}$/.test(value)) return Buffer.from(value, 'hex');+ if (/^[A-Za-z0-9+/=]+$/.test(value)) {+ const decoded = Buffer.from(value, 'base64');+ if (decoded.length === KEY_BYTES) return decoded;+ }+ return null;+}++function getVaultKey() {+ return parseKey(process.env.PRIVACY_VAULT_KEY);+}++/** True when PRIVACY_VAULT_KEY holds a valid 32-byte key. */+export function isVaultKeyConfigured() {+ return getVaultKey() !== null;+}++/**+ * Self-heal a missing vault key: when `PRIVACY_VAULT_KEY` is unset or invalid,+ * generate 32 random bytes, append the hex form to `.env` (created if absent),+ * and set `process.env` so the running server picks it up immediately. Reads+ * the `.env` file first so a key added after boot is adopted rather than+ * duplicated. Returns `{ generated }`. Never logs the key value.+ */+export async function ensureVaultKey({ envPath = DEFAULT_ENV_PATH } = {}) {+ if (isVaultKeyConfigured()) return { generated: false };++ const content = (await tryReadFile(envPath)) ?? '';+ const existing = content.match(/^PRIVACY_VAULT_KEY=(.*)$/m);+ if (existing && parseKey(existing[1])) {+ process.env.PRIVACY_VAULT_KEY = existing[1].trim();+ return { generated: false };+ }++ const key = randomBytes(KEY_BYTES).toString('hex');+ const separator = content && !content.endsWith('\n') ? '\n' : '';+ await atomicWrite(envPath, `${content}${separator}PRIVACY_VAULT_KEY=${key}\n`);+ process.env.PRIVACY_VAULT_KEY = key;+ console.log('🔐 Generated PRIVACY_VAULT_KEY and appended it to .env (vault encryption engaged)');+ return { generated: true };+}++/** Encrypt a plaintext string → `v1:<iv_b64>:<tag_b64>:<ct_b64>`. */+export function encryptValue(plaintext) {+ const key = getVaultKey();+ if (!key) throw new Error('PRIVACY_VAULT_KEY is not configured — call ensureVaultKey() first');+ if (typeof plaintext !== 'string') throw new Error('encryptValue requires a string');+ const iv = randomBytes(IV_BYTES);+ const cipher = createCipheriv(CIPHER, key, iv);+ const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);+ const tag = cipher.getAuthTag();+ return `${FORMAT_VERSION}:${iv.toString('base64')}:${tag.toString('base64')}:${ct.toString('base64')}`;+}++/**+ * Decrypt a `v1:` ciphertext back to plaintext. Throws on an unknown format+ * version, a malformed payload, or any tampering (GCM auth failure).+ */+export function decryptValue(ciphertext) {+ const key = getVaultKey();+ if (!key) throw new Error('PRIVACY_VAULT_KEY is not configured — call ensureVaultKey() first');+ if (typeof ciphertext !== 'string') throw new Error('decryptValue requires a string');+ const [version, ivB64, tagB64, ctB64] = ciphertext.split(':');+ if (version !== FORMAT_VERSION || !ivB64 || !tagB64 || !ctB64) {+ throw new Error(`Unsupported vault ciphertext format (expected ${FORMAT_VERSION}:iv:tag:ct)`);+ }+ const iv = Buffer.from(ivB64, 'base64');+ const tag = Buffer.from(tagB64, 'base64');+ if (iv.length !== IV_BYTES || tag.length !== 16) throw new Error('Malformed vault ciphertext');+ const decipher = createDecipheriv(CIPHER, key, iv);+ decipher.setAuthTag(tag);+ return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64')), decipher.final()]).toString('utf8');+}++// ─── Masking ─────────────────────────────────────────────────────────────────++/** `••••1234` — last 4 of the digits (or raw chars when digits are scarce). */+function maskLastFour(value) {+ const digits = value.replace(/\D/g, '');+ const tail = (digits.length >= 4 ? digits : value).slice(-4);+ return `••••${tail}`;+}++/**+ * Per-type display mask. Never returns the plaintext:+ * - ssn / phone / financial_account → last-4 (`••••1234`)+ * - email → first char + domain visible (`j•••@example.com`)+ * - address → street segment masked, city/state visible (`••• Portland, OR`)+ * - everything else → first character + `•••`+ */+export function maskValue(type, plaintext) {+ const value = typeof plaintext === 'string' ? plaintext.trim() : '';+ if (!value) return '••••';+ switch (type) {+ case 'ssn':+ case 'phone':+ case 'financial_account':+ return maskLastFour(value);+ case 'email': {+ const at = value.indexOf('@');+ if (at <= 0) return '••••';+ return `${value[0]}•••@${value.slice(at + 1)}`;+ }+ case 'address': {+ const comma = value.indexOf(',');+ if (comma === -1) return '•••';+ return `•••${value.slice(comma)}`;+ }+ default:+ return `${value[0]}•••`;+ }+}diff --git a/server/lib/vaultCrypto.test.js b/server/lib/vaultCrypto.test.jsnew file mode 100644index 0000000000..583373228e--- /dev/null+++ b/server/lib/vaultCrypto.test.js@@ -0,0 +1,168 @@+/**+ * Vault crypto unit tests (issue #2140) — pure, no DB. Round-trip, tamper+ * detection (GCM auth), key parsing (hex + base64), ensureVaultKey self-heal+ * against a temp .env, and the per-type display masking.+ */++import { describe, it, expect, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import {+ encryptValue, decryptValue, ensureVaultKey, isVaultKeyConfigured, maskValue,+} from './vaultCrypto.js';++// Fixed 32-byte test key (hex). Never a real key.+const HEX_KEY = 'a'.repeat(64);+const originalKey = process.env.PRIVACY_VAULT_KEY;++afterAll(() => {+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;+ else process.env.PRIVACY_VAULT_KEY = originalKey;+});++describe('isVaultKeyConfigured', () => {+ it('is false when unset or invalid, true for hex and base64 keys', () => {+ delete process.env.PRIVACY_VAULT_KEY;+ expect(isVaultKeyConfigured()).toBe(false);+ process.env.PRIVACY_VAULT_KEY = 'not-a-key';+ expect(isVaultKeyConfigured()).toBe(false);+ process.env.PRIVACY_VAULT_KEY = 'abcd'; // valid base64, wrong length+ expect(isVaultKeyConfigured()).toBe(false);+ process.env.PRIVACY_VAULT_KEY = HEX_KEY;+ expect(isVaultKeyConfigured()).toBe(true);+ process.env.PRIVACY_VAULT_KEY = Buffer.alloc(32, 7).toString('base64');+ expect(isVaultKeyConfigured()).toBe(true);+ });+});++describe('encryptValue / decryptValue', () => {+ beforeEach(() => { process.env.PRIVACY_VAULT_KEY = HEX_KEY; });++ it('round-trips plaintext through the v1 format', () => {+ const ct = encryptValue('123-45-6789');+ expect(ct).toMatch(/^v1:[A-Za-z0-9+/=]+:[A-Za-z0-9+/=]+:[A-Za-z0-9+/=]+$/);+ expect(ct).not.toContain('123-45-6789');+ expect(decryptValue(ct)).toBe('123-45-6789');+ });++ it('round-trips unicode and uses a fresh IV per value', () => {+ const plain = 'Å déjà vu — 東京 🏠';+ const a = encryptValue(plain);+ const b = encryptValue(plain);+ expect(a).not.toBe(b); // per-value random IV+ expect(decryptValue(a)).toBe(plain);+ expect(decryptValue(b)).toBe(plain);+ });++ it('throws on a tampered auth tag', () => {+ const [v, iv, tag, ct] = encryptValue('secret').split(':');+ const tagBuf = Buffer.from(tag, 'base64');+ tagBuf[0] ^= 0xff;+ expect(() => decryptValue(`${v}:${iv}:${tagBuf.toString('base64')}:${ct}`)).toThrow();+ });++ it('throws on tampered ciphertext', () => {+ const [v, iv, tag, ct] = encryptValue('secret').split(':');+ const ctBuf = Buffer.from(ct, 'base64');+ ctBuf[0] ^= 0xff;+ expect(() => decryptValue(`${v}:${iv}:${tag}:${ctBuf.toString('base64')}`)).toThrow();+ });++ it('throws on an unknown version or malformed payload', () => {+ const ct = encryptValue('secret');+ expect(() => decryptValue(ct.replace(/^v1:/, 'v2:'))).toThrow(/format/);+ expect(() => decryptValue('garbage')).toThrow(/format/);+ expect(() => decryptValue('v1:AAAA:BBBB:CCCC')).toThrow();+ });++ it('throws when the key is not configured', () => {+ delete process.env.PRIVACY_VAULT_KEY;+ expect(() => encryptValue('x')).toThrow(/PRIVACY_VAULT_KEY/);+ expect(() => decryptValue('v1:a:b:c')).toThrow(/PRIVACY_VAULT_KEY/);+ });+});++describe('ensureVaultKey', () => {+ let dir;+ let envPath;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'vault-crypto-'));+ envPath = join(dir, '.env');+ delete process.env.PRIVACY_VAULT_KEY;+ });++ it('is a no-op when the env key is already valid', async () => {+ process.env.PRIVACY_VAULT_KEY = HEX_KEY;+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: false });+ expect(existsSync(envPath)).toBe(false);+ });++ it('generates a key, appends it to a fresh .env, and engages encryption', async () => {+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: true });+ const content = readFileSync(envPath, 'utf8');+ expect(content).toMatch(/^PRIVACY_VAULT_KEY=[0-9a-f]{64}\n$/m);+ expect(isVaultKeyConfigured()).toBe(true);+ expect(decryptValue(encryptValue('hello'))).toBe('hello');+ });++ it('appends without clobbering existing .env content (even without trailing newline)', async () => {+ writeFileSync(envPath, 'OTHER_VAR=1');+ await ensureVaultKey({ envPath });+ const content = readFileSync(envPath, 'utf8');+ expect(content).toMatch(/^OTHER_VAR=1\nPRIVACY_VAULT_KEY=[0-9a-f]{64}\n$/);+ });++ it('adopts a valid key already present in .env instead of generating a duplicate', async () => {+ writeFileSync(envPath, `PRIVACY_VAULT_KEY=${HEX_KEY}\n`);+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: false });+ expect(process.env.PRIVACY_VAULT_KEY).toBe(HEX_KEY);+ expect(readFileSync(envPath, 'utf8').match(/PRIVACY_VAULT_KEY/g)).toHaveLength(1);+ });++ it('replaces an invalid env value with a freshly generated key', async () => {+ process.env.PRIVACY_VAULT_KEY = 'stale-garbage';+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: true });+ expect(isVaultKeyConfigured()).toBe(true);+ });++ afterEach(() => rmSync(dir, { recursive: true, force: true }));+});++describe('maskValue', () => {+ it('masks last-4 types (ssn / phone / financial_account)', () => {+ expect(maskValue('ssn', '123-45-6789')).toBe('••••6789');+ expect(maskValue('phone', '+1 (503) 555-0142')).toBe('••••0142');+ expect(maskValue('financial_account', 'DE89 3704 0044 0532 0130 00')).toBe('••••3000');+ });++ it('keeps the email domain visible', () => {+ expect(maskValue('email', '[email protected]')).toBe('j•••@example.com');+ expect(maskValue('email', 'no-at-sign')).toBe('••••');+ });++ it('masks the street segment of an address', () => {+ expect(maskValue('address', '123 Main St, Portland, OR 97201')).toBe('•••, Portland, OR 97201');+ expect(maskValue('address', '123 Main St')).toBe('•••');+ });++ it('falls back to first-char masking for other types', () => {+ expect(maskValue('legal_name', 'Adam Eivy')).toBe('A•••');+ expect(maskValue('dob', '1980-01-02')).toBe('1•••');+ expect(maskValue('custom', 'whatever')).toBe('w•••');+ });++ it('fully masks empty or non-string values', () => {+ expect(maskValue('legal_name', '')).toBe('••••');+ expect(maskValue('ssn', undefined)).toBe('••••');+ });++ it('never returns the plaintext', () => {+ for (const type of ['ssn', 'phone', 'email', 'address', 'legal_name', 'custom']) {+ const masked = maskValue(type, '[email protected]');+ expect(masked).not.toBe('[email protected]');+ expect(masked).not.toContain('sensitive-value');+ }+ });+});diff --git a/server/routes/privacy.js b/server/routes/privacy.jsnew file mode 100644index 0000000000..5b37f07fd1--- /dev/null+++ b/server/routes/privacy.js@@ -0,0 +1,67 @@+/**+ * Privacy Center Routes — encrypted PII Vault REST surface (issue #2140).+ *+ * Mounted at /api/privacy. List/read responses carry `maskedValue` only —+ * `value_enc` and plaintext never leave the service except through the ONE+ * explicit reveal endpoint.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ privacyVaultCreateSchema,+ privacyVaultUpdateSchema,+ privacyVaultListQuerySchema,+ privacyVaultIdParamsSchema,+} from '../lib/privacyValidation.js';+import {+ createVaultRecord,+ listVaultRecords,+ getVaultRecord,+ updateVaultRecord,+ deleteVaultRecord,+ revealValue,+ getVaultStatus,+} from '../services/privacyVault.js';++const router = Router();++router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await getVaultStatus());+}));++router.get('/vault', asyncHandler(async (req, res) => {+ const { type } = validateRequest(privacyVaultListQuerySchema, req.query);+ res.json(await listVaultRecords({ type }));+}));++router.post('/vault', asyncHandler(async (req, res) => {+ const data = validateRequest(privacyVaultCreateSchema, req.body);+ res.status(201).json(await createVaultRecord(data));+}));++router.get('/vault/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyVaultIdParamsSchema, req.params);+ const record = await getVaultRecord(id);+ if (!record) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });+ res.json(record);+}));++router.put('/vault/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyVaultIdParamsSchema, req.params);+ const patch = validateRequest(privacyVaultUpdateSchema, req.body);+ res.json(await updateVaultRecord(id, patch));+}));++router.delete('/vault/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyVaultIdParamsSchema, req.params);+ res.json(await deleteVaultRecord(id));+}));++router.post('/vault/:id/reveal', asyncHandler(async (req, res) => {+ const { id } = validateRequest(privacyVaultIdParamsSchema, req.params);+ res.json(await revealValue(id));+}));++export default router;diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.jsnew file mode 100644index 0000000000..90070fc85d--- /dev/null+++ b/server/routes/privacy.test.js@@ -0,0 +1,118 @@+/**+ * Privacy route tests (issue #2140) — service mocked; verifies routing, Zod+ * validation (schema-parity: POST full / PUT partial), the sensitive-type+ * useForScans rejection at the API edge, and that responses pass through the+ * masked service shape.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/privacyVault.js', () => ({+ createVaultRecord: vi.fn(async (input) => ({ id: 'c0ffee00-0000-4000-8000-000000000001', type: input.type, label: input.label, maskedValue: '••••' })),+ listVaultRecords: vi.fn(async () => [{ id: 'r1', type: 'email', maskedValue: 'a•••@b.com' }]),+ getVaultRecord: vi.fn(async () => null),+ updateVaultRecord: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteVaultRecord: vi.fn(async () => ({ ok: true })),+ revealValue: vi.fn(async (id) => ({ id, type: 'email', value: '[email protected]' })),+ getVaultStatus: vi.fn(async () => ({ keyConfigured: true, recordCounts: { email: 1 } })),+}));++const privacyRoutes = (await import('./privacy.js')).default;+const service = await import('../services/privacyVault.js');++const VALID_UUID = 'c0ffee00-0000-4000-8000-000000000001';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/privacy', privacyRoutes);+ app.use(errorMiddleware);+ return app;+}++beforeEach(() => vi.clearAllMocks());++describe('GET /api/privacy/status', () => {+ it('returns the vault status readout', async () => {+ const res = await request(makeApp()).get('/api/privacy/status');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ keyConfigured: true, recordCounts: { email: 1 } });+ });+});++describe('GET /api/privacy/vault', () => {+ it('lists records (masked shape passes through)', async () => {+ const res = await request(makeApp()).get('/api/privacy/vault');+ expect(res.status).toBe(200);+ expect(res.body).toEqual([{ id: 'r1', type: 'email', maskedValue: 'a•••@b.com' }]);+ });++ it('accepts a valid type filter and rejects an unknown one', async () => {+ expect((await request(makeApp()).get('/api/privacy/vault?type=email')).status).toBe(200);+ expect(service.listVaultRecords).toHaveBeenCalledWith({ type: 'email' });+ expect((await request(makeApp()).get('/api/privacy/vault?type=bogus')).status).toBe(400);+ });+});++describe('POST /api/privacy/vault', () => {+ it('creates a record from a valid body', async () => {+ const res = await request(makeApp()).post('/api/privacy/vault')+ .send({ type: 'email', label: 'Main', value: '[email protected]' });+ expect(res.status).toBe(201);+ expect(service.createVaultRecord).toHaveBeenCalledWith({ type: 'email', label: 'Main', value: '[email protected]' });+ });++ it('rejects a missing value, an unknown type, and unknown keys', async () => {+ expect((await request(makeApp()).post('/api/privacy/vault').send({ type: 'email', label: 'x' })).status).toBe(400);+ expect((await request(makeApp()).post('/api/privacy/vault').send({ type: 'nope', label: 'x', value: 'v' })).status).toBe(400);+ expect((await request(makeApp()).post('/api/privacy/vault').send({ type: 'email', label: 'x', value: 'v', extra: 1 })).status).toBe(400);+ });++ it('rejects useForScans=true for sensitive types at the schema edge', async () => {+ for (const type of ['ssn', 'passport', 'drivers_license', 'financial_account']) {+ const res = await request(makeApp()).post('/api/privacy/vault')+ .send({ type, label: 'doc', value: 'x', useForScans: true });+ expect(res.status).toBe(400);+ }+ expect(service.createVaultRecord).not.toHaveBeenCalled();+ });+});++describe('PUT /api/privacy/vault/:id', () => {+ it('applies a partial patch', async () => {+ const res = await request(makeApp()).put(`/api/privacy/vault/${VALID_UUID}`).send({ label: 'renamed' });+ expect(res.status).toBe(200);+ expect(service.updateVaultRecord).toHaveBeenCalledWith(VALID_UUID, { label: 'renamed' });+ });++ it('rejects a type change (immutable) and a non-uuid id', async () => {+ expect((await request(makeApp()).put(`/api/privacy/vault/${VALID_UUID}`).send({ type: 'email' })).status).toBe(400);+ expect((await request(makeApp()).put('/api/privacy/vault/not-a-uuid').send({ label: 'x' })).status).toBe(400);+ });+});++describe('DELETE /api/privacy/vault/:id', () => {+ it('deletes by id and validates the uuid', async () => {+ expect((await request(makeApp()).delete(`/api/privacy/vault/${VALID_UUID}`)).status).toBe(200);+ expect(service.deleteVaultRecord).toHaveBeenCalledWith(VALID_UUID);+ expect((await request(makeApp()).delete('/api/privacy/vault/nope')).status).toBe(400);+ });+});++describe('POST /api/privacy/vault/:id/reveal', () => {+ it('returns the decrypted value from the ONE reveal path', async () => {+ const res = await request(makeApp()).post(`/api/privacy/vault/${VALID_UUID}/reveal`);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ id: VALID_UUID, type: 'email', value: '[email protected]' });+ });+});++describe('GET /api/privacy/vault/:id', () => {+ it('404s a missing record', async () => {+ const res = await request(makeApp()).get(`/api/privacy/vault/${VALID_UUID}`);+ expect(res.status).toBe(404);+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 30ca95a9ed..79ab5b6ea7 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1040,6 +1040,41 @@ 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: 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+-- NEVER stored; `masked_value` is the display form. Machine-local — no+-- federation, no tombstones (deferred, #2148); a delete is a hard DELETE.+-- `use_for_scans` gates which facts the broker scan engine may disclose+-- (hard-false for ssn/passport/drivers_license/financial_account — enforced+-- app-side). Mirrors the privacy blocks in server/lib/db.js ensureSchema().+CREATE TABLE IF NOT EXISTS privacy_vault_records (+ id UUID PRIMARY KEY,+ type TEXT NOT NULL,+ label TEXT NOT NULL DEFAULT '',+ value_enc TEXT NOT NULL,+ masked_value TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT 'current',+ valid_from DATE,+ valid_to DATE,+ share_with_twin BOOLEAN NOT NULL DEFAULT FALSE,+ use_for_scans BOOLEAN NOT NULL DEFAULT FALSE,+ notes TEXT NOT NULL DEFAULT '',+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+-- 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.+CREATE TABLE IF NOT EXISTS privacy_consents (+ id UUID PRIMARY KEY,+ subject TEXT NOT NULL DEFAULT 'self',+ scope TEXT NOT NULL,+ method TEXT NOT NULL,+ granted_at TIMESTAMPTZ DEFAULT NOW()+);+-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of-- every tombstone / un-tombstone / hard-delete of user-authored records, written-- by a DB trigger so it captures deletions from ANY source (app, a test suite'sdiff --git a/server/services/privacyVault.db.test.js b/server/services/privacyVault.db.test.jsnew file mode 100644index 0000000000..cfb6a49bfb--- /dev/null+++ b/server/services/privacyVault.db.test.js@@ -0,0 +1,162 @@+/**+ * Postgres-backed round-trip for the privacy vault (issue #2140).+ *+ * Like moodBoard/db.test.js, this needs a live PostgreSQL with the schema+ * applied. If no DB is reachable (CI, fresh checkout) it SKIPS cleanly rather+ * than failing red. When a DB IS reachable it exercises the full CRUD ++ * reveal + status surface and asserts the encryption-at-rest acceptance+ * criterion: a raw dump of the created rows contains no plaintext. Cleans up+ * only rows it created — no global table mutation. Runs via `npm run test:db`+ * (→ portos_test) ONLY; the db.js guards refuse writes to a non-test DB.+ */++import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';++// A valid key BEFORE the service is imported/called so ensureVaultKey never+// touches the repo's real .env during the run.+const HEX_KEY = 'c'.repeat(64);+const originalKey = process.env.PRIVACY_VAULT_KEY;+process.env.PRIVACY_VAULT_KEY = HEX_KEY;++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'privacy_vault_records') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'privacy_vault_records table not present';+ }+}++if (!dbReady) console.log(`⏭️ privacyVault.db.test.js skipped: ${skipReason}`);++describe.skipIf(!dbReady)('privacy vault DB round-trip', () => {+ let vault;+ const created = [];+ let tableWasEmpty = false;+ const testStart = new Date().toISOString();++ beforeAll(async () => {+ vault = await import('./privacyVault.js');+ const { rows } = await query(`SELECT COUNT(*)::int AS n FROM privacy_vault_records`);+ tableWasEmpty = rows[0].n === 0;+ });++ afterAll(async () => {+ for (const id of created) {+ await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});+ }+ // Only consent rows this run could have created (first-record consent).+ if (tableWasEmpty) {+ await query(+ `DELETE FROM privacy_consents WHERE scope = 'pii_vault' AND granted_at >= $1`,+ [testStart],+ ).catch(() => {});+ }+ await close();+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;+ else process.env.PRIVACY_VAULT_KEY = originalKey;+ });++ it('creates a record with ciphertext + mask — raw row has NO plaintext', async () => {+ const record = await vault.createVaultRecord({+ type: 'ssn', label: 'My SSN', value: '123-45-6789',+ });+ created.push(record.id);+ expect(record.maskedValue).toBe('••••6789');+ expect(record.useForScans).toBe(false); // sensitive hard-false+ expect(record).not.toHaveProperty('value_enc');++ // Acceptance criterion: raw table dump carries no plaintext PII.+ const { rows } = await query(`SELECT * FROM privacy_vault_records WHERE id = $1`, [record.id]);+ const rawDump = JSON.stringify(rows[0]);+ expect(rawDump).not.toContain('123-45-6789');+ expect(rows[0].value_enc).toMatch(/^v1:/);+ });++ it('writes the first-record consent row', async () => {+ // createVaultRecord above ran with the pre-test emptiness we captured.+ const { rows } = await query(+ `SELECT scope, method, subject FROM privacy_consents WHERE scope = 'pii_vault' AND granted_at >= $1`,+ [testStart],+ );+ if (tableWasEmpty) {+ expect(rows.length).toBeGreaterThan(0);+ expect(rows[0]).toMatchObject({ scope: 'pii_vault', method: 'vault-record-create', subject: 'self' });+ } else {+ expect(rows.length).toBe(0); // not the first record → no new consent+ }+ });++ it('lists masked records and filters by type', async () => {+ const record = await vault.createVaultRecord({+ type: 'email', label: 'Main email', value: '[email protected]',+ });+ created.push(record.id);+ expect(record.useForScans).toBe(true); // scan-default type++ const all = await vault.listVaultRecords();+ const mine = all.find((r) => r.id === record.id);+ expect(mine.maskedValue).toBe('v•••@example.com');+ expect(JSON.stringify(all)).not.toContain('[email protected]');++ const emails = await vault.listVaultRecords({ type: 'email' });+ expect(emails.every((r) => r.type === 'email')).toBe(true);+ expect(emails.some((r) => r.id === record.id)).toBe(true);+ });++ it('reveals the decrypted plaintext through the ONE reveal path', async () => {+ const record = await vault.createVaultRecord({+ type: 'phone', label: 'Cell', value: '+1 503 555 0142',+ });+ created.push(record.id);+ const revealed = await vault.revealValue(record.id);+ expect(revealed).toEqual({ id: record.id, type: 'phone', value: '+1 503 555 0142' });+ });++ it('updates value (re-encrypt + re-mask) and metadata', async () => {+ const record = await vault.createVaultRecord({+ type: 'address', label: 'Home', value: '123 Main St, Portland, OR 97201',+ });+ created.push(record.id);+ const updated = await vault.updateVaultRecord(record.id, {+ value: '9 Oak Ave, Salem, OR 97301', label: 'New home', status: 'current',+ });+ expect(updated.label).toBe('New home');+ expect(updated.maskedValue).toBe('•••, Salem, OR 97301');+ expect((await vault.revealValue(record.id)).value).toBe('9 Oak Ave, Salem, OR 97301');+ });++ it('hard-rejects useForScans=true on a stored sensitive type', async () => {+ const record = await vault.createVaultRecord({+ type: 'passport', label: 'Passport', value: 'P123456789',+ });+ created.push(record.id);+ expect(record.useForScans).toBe(false);+ await expect(vault.updateVaultRecord(record.id, { useForScans: true }))+ .rejects.toMatchObject({ status: 400, code: 'SENSITIVE_TYPE_SCAN_FORBIDDEN' });+ });++ it('deletes a record and 404s subsequent access', async () => {+ const record = await vault.createVaultRecord({+ type: 'custom', label: 'Temp', value: 'to-delete',+ });+ expect(await vault.deleteVaultRecord(record.id)).toEqual({ ok: true });+ expect(await vault.getVaultRecord(record.id)).toBe(null);+ await expect(vault.revealValue(record.id)).rejects.toMatchObject({ status: 404 });+ await expect(vault.deleteVaultRecord(record.id)).rejects.toMatchObject({ status: 404 });+ });++ it('reports vault status with per-type counts', async () => {+ const status = await vault.getVaultStatus();+ expect(status.keyConfigured).toBe(true);+ expect(typeof status.recordCounts).toBe('object');+ });+});diff --git a/server/services/privacyVault.js b/server/services/privacyVault.jsnew file mode 100644index 0000000000..e265f7d5ca--- /dev/null+++ b/server/services/privacyVault.js@@ -0,0 +1,182 @@+/**+ * Privacy Vault — encrypted-at-rest PII records (issue #2140, epic #2138).+ *+ * db-primary Postgres per docs/STORAGE.md: one row per identity fact in+ * `privacy_vault_records` (dedicated columns — the records are relational and+ * queried by type), consent audit rows in `privacy_consents`. Machine-local:+ * NO federation, NO tombstones (deferred child issue #2148).+ *+ * Encryption contract:+ * - plaintext is NEVER stored — every write computes `value_enc` (AES-256-GCM+ * via lib/vaultCrypto.js) + a per-type `masked_value` for list/read display.+ * - plaintext is NEVER logged — log ids/types only, single-line emoji style.+ * - reads return masked values; `revealValue(id)` is the ONE decrypt path.+ *+ * The first vault record creation writes an explicit consent row (scope+ * `pii_vault`) — the audit trail the later broker opt-out engine builds on.+ */++import { randomUUID } from 'crypto';+import { query, withTransaction } from '../lib/db.js';+import { ServerError } from '../lib/errorHandler.js';+import {+ encryptValue, decryptValue, ensureVaultKey, isVaultKeyConfigured, maskValue,+} from '../lib/vaultCrypto.js';+import { PRIVACY_SENSITIVE_TYPES, PRIVACY_SCAN_DEFAULT_TYPES } from '../lib/privacyValidation.js';++// Everything EXCEPT value_enc — list/read responses never carry ciphertext.+const RECORD_COLUMNS = `id, type, label, masked_value, status, valid_from, valid_to,+ share_with_twin, use_for_scans, notes, created_at, updated_at`;++function rowToRecord(row) {+ if (!row) return null;+ return {+ id: row.id,+ type: row.type,+ label: row.label,+ maskedValue: row.masked_value,+ status: row.status,+ validFrom: row.valid_from ? new Date(row.valid_from).toISOString().slice(0, 10) : null,+ validTo: row.valid_to ? new Date(row.valid_to).toISOString().slice(0, 10) : null,+ shareWithTwin: row.share_with_twin,+ useForScans: row.use_for_scans,+ notes: row.notes,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ };+}++/**+ * Effective use_for_scans for a record: sensitive types are HARD false (the+ * schema already rejects an explicit true; this re-enforces it), otherwise the+ * caller's explicit choice wins, otherwise the per-type default (true for+ * legal_name/email/phone/address).+ */+export function resolveUseForScans(type, requested) {+ if (PRIVACY_SENSITIVE_TYPES.includes(type)) return false;+ if (typeof requested === 'boolean') return 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+ 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;+ const { rows } = await query(+ `INSERT INTO privacy_vault_records+ (id, type, label, value_enc, masked_value, status, valid_from, valid_to,+ share_with_twin, use_for_scans, notes, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW(), NOW())+ RETURNING ${RECORD_COLUMNS}`,+ [+ id, input.type, input.label,+ encryptValue(input.value), maskValue(input.type, input.value),+ input.status ?? 'current',+ input.validFrom ?? null, input.validTo ?? null,+ input.shareWithTwin === true, useForScans,+ input.notes ?? '',+ ],+ );+ if (isFirstRecord) {+ await recordConsent({ scope: 'pii_vault', method: 'vault-record-create' });+ }+ console.log(`🔐 Created vault record ${id} (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`);+ return rows.map(rowToRecord);+}++export async function getVaultRecord(id) {+ const { rows } = await query(`SELECT ${RECORD_COLUMNS} FROM privacy_vault_records WHERE id = $1`, [id]);+ return rowToRecord(rows[0]);+}++export async function updateVaultRecord(id, patch) {+ return withTransaction(async (client) => {+ // Row lock: label PATCH + value PATCH from different UI affordances can+ // race a read-modify-write; FOR UPDATE serializes writes to one record.+ const sel = await client.query(+ `SELECT id, type FROM privacy_vault_records WHERE id = $1 FOR UPDATE`, [id],+ );+ const existing = sel.rows[0];+ if (!existing) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });+ if (patch.useForScans === true && PRIVACY_SENSITIVE_TYPES.includes(existing.type)) {+ throw new ServerError(+ `useForScans cannot be true for sensitive type "${existing.type}"`,+ { status: 400, code: 'SENSITIVE_TYPE_SCAN_FORBIDDEN' },+ );+ }+ const sets = [];+ const params = [];+ const add = (column, value) => {+ params.push(value);+ sets.push(`${column} = $${params.length}`);+ };+ if (patch.value !== undefined) {+ await ensureVaultKey();+ add('value_enc', encryptValue(patch.value));+ add('masked_value', maskValue(existing.type, patch.value));+ }+ if (patch.label !== undefined) add('label', patch.label);+ if (patch.status !== undefined) add('status', patch.status);+ if (patch.validFrom !== undefined) add('valid_from', patch.validFrom);+ if (patch.validTo !== undefined) add('valid_to', patch.validTo);+ if (patch.shareWithTwin !== undefined) add('share_with_twin', patch.shareWithTwin);+ if (patch.useForScans !== undefined) add('use_for_scans', resolveUseForScans(existing.type, patch.useForScans));+ if (patch.notes !== undefined) add('notes', patch.notes);+ params.push(id);+ const { rows } = await client.query(+ `UPDATE privacy_vault_records SET ${[...sets, 'updated_at = NOW()'].join(', ')}+ WHERE id = $${params.length} RETURNING ${RECORD_COLUMNS}`,+ params,+ );+ console.log(`🔐 Updated vault record ${id} (type=${existing.type})`);+ return rowToRecord(rows[0]);+ });+}++export async function deleteVaultRecord(id) {+ const { rows } = await query(`DELETE FROM privacy_vault_records WHERE id = $1 RETURNING id, type`, [id]);+ if (!rows[0]) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });+ console.log(`🗑️ Deleted vault record ${id} (type=${rows[0].type})`);+ return { ok: true };+}++/** The ONE decrypt path — explicit reveal. Returns plaintext; logs id/type only. */+export async function revealValue(id) {+ const { rows } = await query(`SELECT id, type, value_enc FROM privacy_vault_records WHERE id = $1`, [id]);+ if (!rows[0]) throw new ServerError('Vault record not found', { status: 404, code: 'NOT_FOUND' });+ const value = decryptValue(rows[0].value_enc);+ console.log(`🔓 Revealed vault record ${id} (type=${rows[0].type})`);+ return { id: rows[0].id, type: rows[0].type, value };+}++/** Doctor-style readout: { keyConfigured, recordCounts: { <type>: n } }. */+export async function getVaultStatus() {+ const { rows } = await query(+ `SELECT type, COUNT(*)::int AS n FROM privacy_vault_records GROUP BY type ORDER BY type`,+ );+ const recordCounts = {};+ for (const row of rows) recordCounts[row.type] = row.n;+ return { keyConfigured: isVaultKeyConfigured(), recordCounts };+}diff --git a/server/services/privacyVault.test.js b/server/services/privacyVault.test.jsnew file mode 100644index 0000000000..c2ad3d2675--- /dev/null+++ b/server/services/privacyVault.test.js@@ -0,0 +1,170 @@+/**+ * Privacy vault service unit tests (issue #2140) — DB mocked; the live-DB+ * round trip lives in privacyVault.db.test.js (test:db → portos_test only).+ * Pins the encryption-at-write contract (params carry ciphertext + mask,+ * never plaintext), the first-record consent write, and the sensitive-type+ * use_for_scans hard-false rules.+ */++import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';++const { queryMock, withTransactionMock } = vi.hoisted(() => ({+ queryMock: vi.fn(),+ withTransactionMock: vi.fn(),+}));++vi.mock('../lib/db.js', () => ({+ query: queryMock,+ withTransaction: withTransactionMock,+}));++const {+ createVaultRecord, updateVaultRecord, revealValue, getVaultStatus, resolveUseForScans,+} = await import('./privacyVault.js');+const { encryptValue } = await import('../lib/vaultCrypto.js');++const HEX_KEY = 'b'.repeat(64);+const originalKey = process.env.PRIVACY_VAULT_KEY;++beforeAll(() => { process.env.PRIVACY_VAULT_KEY = HEX_KEY; });+afterAll(() => {+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;+ else process.env.PRIVACY_VAULT_KEY = originalKey;+});++beforeEach(() => {+ queryMock.mockReset();+ withTransactionMock.mockReset();+});++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],+ created_at: 'now', updated_at: 'now',+});++// queryMock playbook for createVaultRecord: COUNT probe → INSERT → (consent INSERT).+function mockCreateFlow({ existingCount = 1 } = {}) {+ queryMock.mockImplementation(async (sql, params) => {+ if (/COUNT\(\*\)/.test(sql)) return { rows: [{ n: existingCount }] };+ if (/INSERT INTO privacy_vault_records/.test(sql)) return { rows: [insertedRow(params)] };+ if (/INSERT INTO privacy_consents/.test(sql)) return { rows: [] };+ throw new Error(`unexpected query: ${sql}`);+ });+}++describe('resolveUseForScans', () => {+ it('hard-forces false for sensitive types even when requested true', () => {+ for (const type of ['ssn', 'passport', 'drivers_license', 'financial_account']) {+ expect(resolveUseForScans(type, true)).toBe(false);+ expect(resolveUseForScans(type, undefined)).toBe(false);+ }+ });++ it('defaults true for scan-default types and false otherwise', () => {+ for (const type of ['legal_name', 'email', 'phone', 'address']) {+ expect(resolveUseForScans(type, undefined)).toBe(true);+ }+ expect(resolveUseForScans('dob', undefined)).toBe(false);+ expect(resolveUseForScans('custom', undefined)).toBe(false);+ });++ it('lets an explicit choice win for non-sensitive types', () => {+ expect(resolveUseForScans('email', false)).toBe(false);+ expect(resolveUseForScans('dob', true)).toBe(true);+ });+});++describe('createVaultRecord', () => {+ it('stores ciphertext + mask — never the plaintext', async () => {+ mockCreateFlow();+ 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).not.toContain('123-45-6789');+ expect(record.maskedValue).toBe('••••6789');+ expect(record.useForScans).toBe(false); // ssn is hard-false+ expect(record).not.toHaveProperty('valueEnc');+ expect(record).not.toHaveProperty('value_enc');+ });++ it('applies the per-type use_for_scans default', async () => {+ mockCreateFlow();+ const record = await createVaultRecord({ type: 'email', label: 'Main', value: '[email protected]' });+ expect(record.useForScans).toBe(true);+ });++ it('writes a consent row on the FIRST record only', async () => {+ 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);++ queryMock.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);+ });+});++describe('updateVaultRecord', () => {+ function mockLockedRow(row) {+ const client = {+ query: vi.fn(async (sql, params) => {+ if (/FOR UPDATE/.test(sql)) return { rows: row ? [row] : [] };+ if (/UPDATE privacy_vault_records/.test(sql)) {+ return { rows: [{ ...insertedRow(['id', row.type, '', 'enc', 'mask', 'current', null, null, false, false, '']), id: row.id }] };+ }+ throw new Error(`unexpected client query: ${sql}`);+ }),+ };+ withTransactionMock.mockImplementation(async (fn) => fn(client));+ return client;+ }++ it('rejects useForScans=true against a stored sensitive type', async () => {+ mockLockedRow({ id: 'r1', type: 'passport' });+ await expect(updateVaultRecord('r1', { useForScans: true }))+ .rejects.toMatchObject({ status: 400, code: 'SENSITIVE_TYPE_SCAN_FORBIDDEN' });+ });++ it('404s an unknown record', async () => {+ mockLockedRow(null);+ await expect(updateVaultRecord('missing', { label: 'x' }))+ .rejects.toMatchObject({ status: 404 });+ });++ it('re-encrypts and re-masks when value changes', async () => {+ const client = mockLockedRow({ id: 'r1', type: 'phone' });+ await updateVaultRecord('r1', { value: '503-555-0142' });+ const update = client.query.mock.calls.find(([sql]) => /UPDATE privacy_vault_records/.test(sql));+ expect(update[1][0]).toMatch(/^v1:/);+ expect(update[1][1]).toBe('••••0142');+ expect(update[1]).not.toContain('503-555-0142');+ });+});++describe('revealValue', () => {+ it('decrypts the stored ciphertext', async () => {+ const enc = encryptValue('my secret value');+ queryMock.mockResolvedValue({ rows: [{ id: 'r1', type: 'custom', value_enc: enc }] });+ expect(await revealValue('r1')).toEqual({ id: 'r1', type: 'custom', value: 'my secret value' });+ });++ it('404s an unknown record', async () => {+ queryMock.mockResolvedValue({ rows: [] });+ await expect(revealValue('missing')).rejects.toMatchObject({ status: 404 });+ });+});++describe('getVaultStatus', () => {+ it('reports key state and per-type counts', async () => {+ queryMock.mockResolvedValue({ rows: [{ type: 'email', n: 2 }, { type: 'ssn', n: 1 }] });+ expect(await getVaultStatus()).toEqual({+ keyConfigured: true,+ recordCounts: { email: 2, ssn: 1 },+ });+ });+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 87b4d25b71..c36fd7a3af 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -11,6 +11,7 @@ export const DB_TEST_INCLUDE = ['**/db.test.js','services/catalogDB.test.js','services/catalogDB.facets.db.test.js',+ 'services/privacyVault.db.test.js','services/catalogCanonProjection.test.js','services/catalogRefResolver.test.js','services/creativeDirector/projectsDB.test.js',