Skip to content

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

feat([issue-2141]): trusted-organizations registry + per-field holdings

Adam Eivyb369c889f541
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0a8773e9ed..b9d2368f4c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,6 +7,7 @@
## Privacy Center
- **[issue-2140] Encrypted PII Vault** — PortOS can now store your identity facts (legal name, addresses, phones, emails, DOB, ID documents, financial-account stubs) in an encrypted-at-rest vault: values are AES-256-GCM encrypted with a key auto-provisioned into your `.env` on first use, the API only ever shows masked values (like `••••6789` or `j•••@example.com`) unless you explicitly reveal one, and sensitive document types can never be marked for use in the upcoming data-broker scans. This is Phase 1 of the Privacy Center (epic #2138) — the UI arrives in Phase 3.
+- **[issue-2141] Trusted Organizations registry** — the Privacy Center now has a place to track every organization that has (or had) your PII — banks, utilities, government, employers, subscriptions, medical, insurers, platforms — each with a trust stance (trusted/tolerated/unwanted) and per-org holdings linking to the exact vault records they hold. Holdings always show masked values, never plaintext, and deleting an organization or a vault record automatically cleans up its holdings. This is Phase 2 of the Privacy Center (epic #2138) — it's the data backbone for the upcoming change-of-address inventory and "who has my PII" view; the UI still arrives in Phase 3.
## Songs
diff --git a/scripts/migrations/162-privacy-orgs-tables.js b/scripts/migrations/162-privacy-orgs-tables.js
new file mode 100644
index 0000000000..ab9d21c277
--- /dev/null
+++ b/scripts/migrations/162-privacy-orgs-tables.js
@@ -0,0 +1,27 @@
+/**
+ * Registration stub for the Privacy Center Trusted Organizations registry
+ * (issue #2141, epic #2138).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS privacy_orgs` and
+ * `privacy_org_holdings` (+ their indexes) — is idempotent and lives in
+ * `ensureSchema()` (`server/lib/db.js`) and the fresh-install seed
+ * (`server/scripts/init-db.sql`), both of which run at server boot AFTER the
+ * DB pool is up. The `scripts/migrations/` runner executes BEFORE the pool is
+ * initialized, so a DB-table create cannot live here — the same reason
+ * migrations 048–052, 108, and 160/161 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 trusted-organizations tables were introduced. Both
+ * tables are additive (brand-new, machine-local db-primary stores) with no
+ * data backfill — the privacyOrgs service populates them lazily as the user
+ * adds organizations and holdings.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('🏢 privacy_orgs/privacy_org_holdings: tables created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index 01032a800c..b11e0a1d70 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -42,7 +42,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). |
| `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. |
-| `privacyValidation.js` | Privacy Center 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. |
+| `privacyValidation.js` | Privacy Center schemas — PII Vault (issue #2140): vault record create/update (partial PUT), list query, UUID params; the vault type/status vocabularies + the sensitive-type (`ssn`/`passport`/`drivers_license`/`financial_account`) `useForScans` hard-false rule and per-type scan defaults. Trusted Organizations registry (issue #2141): org create/update (partial PUT), list query, UUID params, and the replace-set holdings schema. |
| `socketValidation.js` | Socket event payload schemas. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 5681c9f5a4..a061edd774 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -1313,6 +1313,44 @@ async function ensureSchemaImpl() {
granted_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ // ─── Privacy Center: Trusted Organizations registry (issue #2141, epic
+ // #2138) ──────────────────────────────────────────────────────────────
+ // Every organization that has (or had) the user's PII, with a trust
+ // stance and per-org holdings linking to the exact vault records each org
+ // holds. Data backbone for the change-of-address inventory (Phase 4) and
+ // the "who has my PII" view. Machine-local: no federation, no tombstones
+ // (same deferred scope as the vault, #2148). Mirrors the privacy blocks
+ // in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS privacy_orgs (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ category TEXT NOT NULL DEFAULT 'other',
+ website TEXT NOT NULL DEFAULT '',
+ trust TEXT NOT NULL DEFAULT 'trusted',
+ status TEXT NOT NULL DEFAULT 'active',
+ contact JSONB NOT NULL DEFAULT '{}'::jsonb,
+ social_account_id TEXT,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_trust ON privacy_orgs (trust)`,
+ `CREATE INDEX IF NOT EXISTS idx_privacy_orgs_status ON privacy_orgs (status)`,
+ // Which vault records each org holds. Composite PK (no surrogate id) — an
+ // org either holds a given vault record or it doesn't, so the pair IS the
+ // identity. Cascade both ways: deleting the org or the vault record drops
+ // its holdings rows.
+ `CREATE TABLE IF NOT EXISTS privacy_org_holdings (
+ org_id UUID NOT NULL REFERENCES privacy_orgs (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(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (org_id, vault_record_id)
+ )`,
+ // Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
+ `CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id)`,
+
// ─── Deletion audit log (incident #1248-follow-up) ──────────────────────
// Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone
// (recovery), and hard-delete of user-authored records — written by a DB
diff --git a/server/lib/privacyValidation.js b/server/lib/privacyValidation.js
index efcd256aa0..17da9720dd 100644
--- a/server/lib/privacyValidation.js
+++ b/server/lib/privacyValidation.js
@@ -76,3 +76,72 @@ export const privacyVaultListQuerySchema = z.object({
export const privacyVaultIdParamsSchema = z.object({
id: z.string().uuid(),
}).strict();
+
+// =============================================================================
+// TRUSTED ORGANIZATIONS REGISTRY SCHEMAS (issue #2141, epic #2138)
+// =============================================================================
+// Zod schemas for `privacy_orgs` / `privacy_org_holdings` — db-primary Postgres,
+// machine-local (same federation-deferred scope as the vault, #2148).
+
+export const PRIVACY_ORG_CATEGORIES = Object.freeze([
+ 'bank', 'utility', 'government', 'employer', 'subscription',
+ 'medical', 'insurance', 'platform', 'broker', 'other',
+]);
+
+export const PRIVACY_ORG_TRUST_LEVELS = Object.freeze(['trusted', 'tolerated', 'unwanted']);
+
+export const PRIVACY_ORG_STATUSES = Object.freeze(['active', 'closed', 'opted_out']);
+
+export const PRIVACY_ORG_HOLDING_STATUSES = Object.freeze([
+ 'current', 'update_pending', 'updated', 'removed', 'unknown',
+]);
+
+const privacyOrgContactSchema = z.object({
+ email: z.string().max(320).optional(),
+ phone: z.string().max(64).optional(),
+ portalUrl: z.string().max(2000).optional(),
+ mailingAddress: z.string().max(2000).optional(),
+}).strict();
+
+export const privacyOrgCreateSchema = z.object({
+ name: z.string().trim().min(1).max(200),
+ category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),
+ website: z.string().max(2000).optional(),
+ trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),
+ status: z.enum(PRIVACY_ORG_STATUSES).optional(),
+ contact: privacyOrgContactSchema.optional(),
+ socialAccountId: z.string().max(200).nullable().optional(),
+ notes: z.string().max(5000).optional(),
+}).strict();
+
+// PUT is a partial update — every field optional, same shape otherwise.
+export const privacyOrgUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(200).optional(),
+ category: z.enum(PRIVACY_ORG_CATEGORIES).optional(),
+ website: z.string().max(2000).optional(),
+ trust: z.enum(PRIVACY_ORG_TRUST_LEVELS).optional(),
+ status: z.enum(PRIVACY_ORG_STATUSES).optional(),
+ contact: privacyOrgContactSchema.optional(),
+ socialAccountId: z.string().max(200).nullable().optional(),
+ notes: z.string().max(5000).optional(),
+}).strict();
+
+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(),
+}).strict();
+
+export const privacyOrgIdParamsSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
+// PUT /api/privacy/orgs/:id/holdings — replace-set semantics: body is the
+// full list of vault record ids (+ optional status) this org holds. An empty
+// array clears all holdings for the org.
+export const privacyOrgHoldingsSetSchema = z.object({
+ holdings: z.array(z.object({
+ vaultRecordId: z.string().uuid(),
+ status: z.enum(PRIVACY_ORG_HOLDING_STATUSES).optional(),
+ }).strict()).max(500),
+}).strict();
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index 5b37f07fd1..7d5259ac0a 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -1,9 +1,11 @@
/**
- * Privacy Center Routes — encrypted PII Vault REST surface (issue #2140).
+ * Privacy Center Routes — encrypted PII Vault + Trusted Organizations
+ * registry REST surface (issues #2140, #2141).
*
- * 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.
+ * 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
+ * masked fields only — never plaintext.
*/
import { Router } from 'express';
@@ -14,6 +16,11 @@ import {
privacyVaultUpdateSchema,
privacyVaultListQuerySchema,
privacyVaultIdParamsSchema,
+ privacyOrgCreateSchema,
+ privacyOrgUpdateSchema,
+ privacyOrgListQuerySchema,
+ privacyOrgIdParamsSchema,
+ privacyOrgHoldingsSetSchema,
} from '../lib/privacyValidation.js';
import {
createVaultRecord,
@@ -24,6 +31,15 @@ import {
revealValue,
getVaultStatus,
} from '../services/privacyVault.js';
+import {
+ createOrg,
+ listOrgs,
+ getOrg,
+ updateOrg,
+ deleteOrg,
+ setOrgHoldings,
+ getHoldingsForOrg,
+} from '../services/privacyOrgs.js';
const router = Router();
@@ -64,4 +80,45 @@ router.post('/vault/:id/reveal', asyncHandler(async (req, res) => {
res.json(await revealValue(id));
}));
+// ─── Trusted Organizations registry (issue #2141) ──────────────────────────
+
+router.get('/orgs', asyncHandler(async (req, res) => {
+ const filters = validateRequest(privacyOrgListQuerySchema, req.query);
+ res.json(await listOrgs(filters));
+}));
+
+router.post('/orgs', asyncHandler(async (req, res) => {
+ const data = validateRequest(privacyOrgCreateSchema, req.body);
+ res.status(201).json(await createOrg(data));
+}));
+
+router.get('/orgs/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ const org = await getOrg(id);
+ if (!org) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(org);
+}));
+
+router.put('/orgs/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ const patch = validateRequest(privacyOrgUpdateSchema, req.body);
+ res.json(await updateOrg(id, patch));
+}));
+
+router.delete('/orgs/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ res.json(await deleteOrg(id));
+}));
+
+router.get('/orgs/:id/holdings', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ res.json(await getHoldingsForOrg(id));
+}));
+
+router.put('/orgs/:id/holdings', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
+ const { holdings } = validateRequest(privacyOrgHoldingsSetSchema, req.body);
+ res.json(await setOrgHoldings(id, holdings));
+}));
+
export default router;
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index 90070fc85d..252fe54070 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -20,8 +20,19 @@ vi.mock('../services/privacyVault.js', () => ({
getVaultStatus: vi.fn(async () => ({ keyConfigured: true, recordCounts: { email: 1 } })),
}));
+vi.mock('../services/privacyOrgs.js', () => ({
+ createOrg: vi.fn(async (input) => ({ id: 'c0ffee00-0000-4000-8000-000000000002', name: input.name, trust: input.trust ?? 'trusted' })),
+ listOrgs: vi.fn(async () => [{ id: 'o1', name: 'Acme Bank', trust: 'trusted' }]),
+ getOrg: vi.fn(async () => null),
+ updateOrg: vi.fn(async (id, patch) => ({ id, ...patch })),
+ deleteOrg: vi.fn(async () => ({ ok: true })),
+ setOrgHoldings: vi.fn(async (id, holdings) => holdings.map((h) => ({ orgId: id, ...h }))),
+ getHoldingsForOrg: vi.fn(async () => [{ orgId: 'o1', vaultRecordId: 'v1', vaultMaskedValue: 'a•••@b.com' }]),
+}));
+
const privacyRoutes = (await import('./privacy.js')).default;
const service = await import('../services/privacyVault.js');
+const orgService = await import('../services/privacyOrgs.js');
const VALID_UUID = 'c0ffee00-0000-4000-8000-000000000001';
@@ -116,3 +127,83 @@ describe('GET /api/privacy/vault/:id', () => {
expect(res.status).toBe(404);
});
});
+
+describe('GET /api/privacy/orgs', () => {
+ it('lists orgs and accepts trust/status/category filters', async () => {
+ const res = await request(makeApp()).get('/api/privacy/orgs');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ id: 'o1', name: 'Acme Bank', trust: 'trusted' }]);
+
+ expect((await request(makeApp()).get('/api/privacy/orgs?trust=unwanted')).status).toBe(200);
+ expect(orgService.listOrgs).toHaveBeenCalledWith({ trust: 'unwanted' });
+ expect((await request(makeApp()).get('/api/privacy/orgs?trust=bogus')).status).toBe(400);
+ });
+});
+
+describe('POST /api/privacy/orgs', () => {
+ it('creates an org from a valid body', async () => {
+ const res = await request(makeApp()).post('/api/privacy/orgs').send({ name: 'Acme Bank', category: 'bank' });
+ expect(res.status).toBe(201);
+ expect(orgService.createOrg).toHaveBeenCalledWith({ name: 'Acme Bank', category: 'bank' });
+ });
+
+ it('rejects a missing name, an unknown category/trust, and unknown keys', async () => {
+ expect((await request(makeApp()).post('/api/privacy/orgs').send({})).status).toBe(400);
+ expect((await request(makeApp()).post('/api/privacy/orgs').send({ name: 'X', category: 'nope' })).status).toBe(400);
+ expect((await request(makeApp()).post('/api/privacy/orgs').send({ name: 'X', trust: 'nope' })).status).toBe(400);
+ expect((await request(makeApp()).post('/api/privacy/orgs').send({ name: 'X', extra: 1 })).status).toBe(400);
+ });
+});
+
+describe('GET /api/privacy/orgs/:id', () => {
+ it('404s a missing org', async () => {
+ const res = await request(makeApp()).get(`/api/privacy/orgs/${VALID_UUID}`);
+ expect(res.status).toBe(404);
+ });
+});
+
+describe('PUT /api/privacy/orgs/:id', () => {
+ it('applies a partial patch', async () => {
+ const res = await request(makeApp()).put(`/api/privacy/orgs/${VALID_UUID}`).send({ trust: 'unwanted' });
+ expect(res.status).toBe(200);
+ expect(orgService.updateOrg).toHaveBeenCalledWith(VALID_UUID, { trust: 'unwanted' });
+ });
+
+ it('rejects a non-uuid id and an unknown enum value', async () => {
+ expect((await request(makeApp()).put('/api/privacy/orgs/not-a-uuid').send({ name: 'x' })).status).toBe(400);
+ expect((await request(makeApp()).put(`/api/privacy/orgs/${VALID_UUID}`).send({ status: 'nope' })).status).toBe(400);
+ });
+});
+
+describe('DELETE /api/privacy/orgs/:id', () => {
+ it('deletes by id and validates the uuid', async () => {
+ expect((await request(makeApp()).delete(`/api/privacy/orgs/${VALID_UUID}`)).status).toBe(200);
+ expect(orgService.deleteOrg).toHaveBeenCalledWith(VALID_UUID);
+ expect((await request(makeApp()).delete('/api/privacy/orgs/nope')).status).toBe(400);
+ });
+});
+
+describe('GET /api/privacy/orgs/:id/holdings', () => {
+ it('returns the joined masked holdings for the org', async () => {
+ const res = await request(makeApp()).get(`/api/privacy/orgs/${VALID_UUID}/holdings`);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ orgId: 'o1', vaultRecordId: 'v1', vaultMaskedValue: 'a•••@b.com' }]);
+ });
+});
+
+describe('PUT /api/privacy/orgs/:id/holdings', () => {
+ it('replace-sets holdings from a valid body', async () => {
+ const res = await request(makeApp()).put(`/api/privacy/orgs/${VALID_UUID}/holdings`)
+ .send({ holdings: [{ vaultRecordId: VALID_UUID, status: 'current' }] });
+ expect(res.status).toBe(200);
+ expect(orgService.setOrgHoldings).toHaveBeenCalledWith(
+ VALID_UUID, [{ vaultRecordId: VALID_UUID, status: 'current' }],
+ );
+ });
+
+ it('accepts an empty list (clears all holdings) and rejects an unknown status', async () => {
+ expect((await request(makeApp()).put(`/api/privacy/orgs/${VALID_UUID}/holdings`).send({ holdings: [] })).status).toBe(200);
+ expect((await request(makeApp()).put(`/api/privacy/orgs/${VALID_UUID}/holdings`)
+ .send({ holdings: [{ vaultRecordId: VALID_UUID, status: 'nope' }] })).status).toBe(400);
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index a1f40db901..2150bb29b2 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1098,6 +1098,43 @@ CREATE TABLE IF NOT EXISTS privacy_consents (
granted_at TIMESTAMPTZ DEFAULT NOW()
);
+-- Privacy Center: Trusted Organizations registry (issue #2141, epic #2138).
+-- Every organization that has (or had) the user's PII, with a trust stance
+-- and per-org holdings linking to the exact vault records each org holds.
+-- Data backbone for the change-of-address inventory (Phase 4) and the "who
+-- has my PII" view. Machine-local — no federation, no tombstones (same
+-- deferred scope as the vault, #2148). Mirrors the privacy blocks in
+-- server/lib/db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS privacy_orgs (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ category TEXT NOT NULL DEFAULT 'other',
+ website TEXT NOT NULL DEFAULT '',
+ trust TEXT NOT NULL DEFAULT 'trusted',
+ status TEXT NOT NULL DEFAULT 'active',
+ contact JSONB NOT NULL DEFAULT '{}'::jsonb,
+ social_account_id TEXT,
+ notes TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_privacy_orgs_trust ON privacy_orgs (trust);
+CREATE INDEX IF NOT EXISTS idx_privacy_orgs_status ON privacy_orgs (status);
+-- Which vault records each org holds. Composite PK (no surrogate id) — an org
+-- either holds a given vault record or it doesn't, so the pair IS the
+-- identity. Cascade both ways: deleting the org or the vault record drops its
+-- holdings rows.
+CREATE TABLE IF NOT EXISTS privacy_org_holdings (
+ org_id UUID NOT NULL REFERENCES privacy_orgs (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(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (org_id, vault_record_id)
+);
+-- Reverse lookup: "which orgs hold vault record X" (getOrgsHoldingRecord).
+CREATE INDEX IF NOT EXISTS idx_privacy_org_holdings_vault_record ON privacy_org_holdings (vault_record_id);
+
-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of
-- every tombstone / un-tombstone / hard-delete of user-authored records, written
-- by a DB trigger so it captures deletions from ANY source (app, a test suite's
diff --git a/server/services/privacyOrgs.db.test.js b/server/services/privacyOrgs.db.test.js
new file mode 100644
index 0000000000..703c56cb61
--- /dev/null
+++ b/server/services/privacyOrgs.db.test.js
@@ -0,0 +1,150 @@
+/**
+ * Postgres-backed round-trip for the Trusted Organizations registry
+ * (issue #2141). Like privacyVault.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. Exercises org CRUD, cascade deletes
+ * (org delete and vault-record delete both clean up holdings), the
+ * getOrgsHoldingRecord join, and the batch status flip. 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';
+
+const HEX_KEY = 'd'.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_orgs') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'privacy_orgs table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ privacyOrgs.db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('privacy orgs DB round-trip', () => {
+ let orgs;
+ let vault;
+ const createdOrgs = [];
+ const createdVaultRecords = [];
+
+ beforeAll(async () => {
+ orgs = await import('./privacyOrgs.js');
+ vault = await import('./privacyVault.js');
+ });
+
+ afterAll(async () => {
+ for (const id of createdOrgs) {
+ await query(`DELETE FROM privacy_orgs WHERE id = $1`, [id]).catch(() => {});
+ }
+ for (const id of createdVaultRecords) {
+ await query(`DELETE FROM privacy_vault_records WHERE id = $1`, [id]).catch(() => {});
+ }
+ await close();
+ if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;
+ else process.env.PRIVACY_VAULT_KEY = originalKey;
+ });
+
+ it('creates an org, attaches vault holdings, and queries both directions', async () => {
+ const record = await vault.createVaultRecord({ type: 'email', label: 'Work email', value: '[email protected]' });
+ createdVaultRecords.push(record.id);
+
+ const org = await orgs.createOrg({ name: 'Acme Bank', category: 'bank', trust: 'trusted' });
+ createdOrgs.push(org.id);
+ expect(org.category).toBe('bank');
+
+ const holdings = await orgs.setOrgHoldings(org.id, [{ vaultRecordId: record.id, status: 'current' }]);
+ expect(holdings).toHaveLength(1);
+ expect(holdings[0]).toMatchObject({ vaultRecordId: record.id, vaultType: 'email', vaultMaskedValue: 'm•••@work.example' });
+ expect(JSON.stringify(holdings)).not.toContain('[email protected]');
+
+ const forOrg = await orgs.getHoldingsForOrg(org.id);
+ expect(forOrg).toHaveLength(1);
+
+ const holdingOrgs = await orgs.getOrgsHoldingRecord(record.id);
+ expect(holdingOrgs).toHaveLength(1);
+ expect(holdingOrgs[0]).toMatchObject({ orgId: org.id, orgName: 'Acme Bank' });
+ });
+
+ it('replace-set semantics: re-calling setOrgHoldings drops anything not listed', async () => {
+ const r1 = await vault.createVaultRecord({ type: 'phone', label: 'Cell', value: '+1 503 555 0100' });
+ const r2 = await vault.createVaultRecord({ type: 'address', label: 'Home', value: '1 Main St' });
+ createdVaultRecords.push(r1.id, r2.id);
+
+ const org = await orgs.createOrg({ name: 'Utility Co' });
+ createdOrgs.push(org.id);
+
+ await orgs.setOrgHoldings(org.id, [
+ { vaultRecordId: r1.id }, { vaultRecordId: r2.id },
+ ]);
+ expect(await orgs.getHoldingsForOrg(org.id)).toHaveLength(2);
+
+ await orgs.setOrgHoldings(org.id, [{ vaultRecordId: r1.id, status: 'update_pending' }]);
+ const after = await orgs.getHoldingsForOrg(org.id);
+ expect(after).toHaveLength(1);
+ expect(after[0]).toMatchObject({ vaultRecordId: r1.id, status: 'update_pending' });
+ });
+
+ it('cascades: deleting the org drops its holdings', async () => {
+ const record = await vault.createVaultRecord({ type: 'custom', label: 'Misc', value: 'x' });
+ createdVaultRecords.push(record.id);
+ const org = await orgs.createOrg({ name: 'Temp Org' });
+ await orgs.setOrgHoldings(org.id, [{ vaultRecordId: record.id }]);
+
+ await orgs.deleteOrg(org.id);
+ const { rows } = await query(`SELECT * FROM privacy_org_holdings WHERE org_id = $1`, [org.id]);
+ expect(rows).toHaveLength(0);
+ expect(await orgs.getOrg(org.id)).toBe(null);
+ });
+
+ it('cascades: deleting the vault record drops its holdings', async () => {
+ const record = await vault.createVaultRecord({ type: 'custom', label: 'Misc2', value: 'y' });
+ const org = await orgs.createOrg({ name: 'Another Org' });
+ createdOrgs.push(org.id);
+ await orgs.setOrgHoldings(org.id, [{ vaultRecordId: record.id }]);
+
+ await vault.deleteVaultRecord(record.id);
+ const { rows } = await query(`SELECT * FROM privacy_org_holdings WHERE vault_record_id = $1`, [record.id]);
+ expect(rows).toHaveLength(0);
+ });
+
+ it('batch-flips holdings status across all orgs holding a record', async () => {
+ const record = await vault.createVaultRecord({ type: 'address', label: 'Old address', value: '9 Old Rd' });
+ createdVaultRecords.push(record.id);
+ const orgA = await orgs.createOrg({ name: 'Bank A' });
+ const orgB = await orgs.createOrg({ name: 'Bank B' });
+ createdOrgs.push(orgA.id, orgB.id);
+ await orgs.setOrgHoldings(orgA.id, [{ vaultRecordId: record.id, status: 'current' }]);
+ await orgs.setOrgHoldings(orgB.id, [{ vaultRecordId: record.id, status: 'current' }]);
+
+ const result = await orgs.setHoldingsStatus(record.id, 'current', 'update_pending');
+ expect(result.updated).toBe(2);
+ const holdingOrgs = await orgs.getOrgsHoldingRecord(record.id);
+ expect(holdingOrgs.every((h) => h.status === 'update_pending')).toBe(true);
+ });
+
+ it('validation rejects unknown enum values at the service boundary via the schema layer', async () => {
+ const { privacyOrgCreateSchema } = await import('../lib/privacyValidation.js');
+ expect(() => privacyOrgCreateSchema.parse({ name: 'X', trust: 'bogus' })).toThrow();
+ expect(() => privacyOrgCreateSchema.parse({ name: 'X', category: 'bogus' })).toThrow();
+ expect(() => privacyOrgCreateSchema.parse({ name: 'X', status: 'bogus' })).toThrow();
+ });
+
+ it('reports a holdings summary across orgs and vault records', async () => {
+ const summary = await orgs.getHoldingsSummary();
+ expect(Array.isArray(summary.byOrg)).toBe(true);
+ expect(Array.isArray(summary.byVaultRecord)).toBe(true);
+ });
+});
diff --git a/server/services/privacyOrgs.js b/server/services/privacyOrgs.js
new file mode 100644
index 0000000000..3c9329d58d
--- /dev/null
+++ b/server/services/privacyOrgs.js
@@ -0,0 +1,230 @@
+/**
+ * Trusted Organizations registry (issue #2141, epic #2138).
+ *
+ * db-primary Postgres per docs/STORAGE.md: `privacy_orgs` (one row per
+ * organization that has or had the user's PII) and `privacy_org_holdings`
+ * (which vault records each org holds, with a per-holding status). Machine-
+ * local: NO federation, NO tombstones (same deferred scope as the vault,
+ * #2148) — deletes are hard DELETEs with cascading holdings cleanup.
+ *
+ * Holdings responses join masked vault values ONLY — never plaintext. The
+ * one decrypt path stays `revealValue()` in privacyVault.js; this service
+ * never touches `value_enc`.
+ */
+
+import { randomUUID } from 'crypto';
+import { query } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+const ORG_COLUMNS = `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,
+ name: row.name,
+ category: row.category,
+ website: row.website,
+ trust: row.trust,
+ status: row.status,
+ contact: row.contact ?? {},
+ socialAccountId: row.social_account_id,
+ notes: row.notes,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+function rowToHolding(row) {
+ return {
+ orgId: row.org_id,
+ vaultRecordId: row.vault_record_id,
+ status: row.status,
+ notedAt: row.noted_at,
+ updatedAt: row.updated_at,
+ // Present only on joined queries that select these columns.
+ ...(row.type !== undefined ? { vaultType: row.type } : {}),
+ ...(row.label !== undefined ? { vaultLabel: row.label } : {}),
+ ...(row.masked_value !== undefined ? { vaultMaskedValue: row.masked_value } : {}),
+ ...(row.org_name !== undefined ? { orgName: row.org_name } : {}),
+ };
+}
+
+export async function createOrg(input) {
+ 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())
+ RETURNING ${ORG_COLUMNS}`,
+ [
+ id, input.name,
+ input.category ?? 'other', input.website ?? '',
+ input.trust ?? 'trusted', input.status ?? 'active',
+ JSON.stringify(input.contact ?? {}),
+ input.socialAccountId ?? null,
+ input.notes ?? '',
+ ],
+ );
+ console.log(`🏢 Created privacy org ${id} (name=${input.name})`);
+ return rowToOrg(rows[0]);
+}
+
+export async function listOrgs({ trust, status, category } = {}) {
+ const clauses = [];
+ const params = [];
+ 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 { rows } = await query(
+ `SELECT ${ORG_COLUMNS} FROM privacy_orgs ${where} ORDER BY name ASC`,
+ params,
+ );
+ return rows.map(rowToOrg);
+}
+
+export async function getOrg(id) {
+ const { rows } = await query(`SELECT ${ORG_COLUMNS} FROM privacy_orgs WHERE id = $1`, [id]);
+ return rowToOrg(rows[0]);
+}
+
+export async function updateOrg(id, patch) {
+ const sets = [];
+ const params = [];
+ const add = (column, value) => {
+ params.push(value);
+ sets.push(`${column} = $${params.length}`);
+ };
+ if (patch.name !== undefined) add('name', patch.name);
+ if (patch.category !== undefined) add('category', patch.category);
+ if (patch.website !== undefined) add('website', patch.website);
+ if (patch.trust !== undefined) add('trust', patch.trust);
+ if (patch.status !== undefined) add('status', patch.status);
+ if (patch.contact !== undefined) add('contact', JSON.stringify(patch.contact));
+ if (patch.socialAccountId !== undefined) add('social_account_id', patch.socialAccountId);
+ if (patch.notes !== undefined) add('notes', patch.notes);
+ params.push(id);
+ const { rows } = await query(
+ `UPDATE privacy_orgs SET ${[...sets, 'updated_at = NOW()'].join(', ')}
+ WHERE id = $${params.length} RETURNING ${ORG_COLUMNS}`,
+ params,
+ );
+ if (!rows[0]) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ console.log(`🏢 Updated privacy org ${id}`);
+ return rowToOrg(rows[0]);
+}
+
+export async function deleteOrg(id) {
+ const { rows } = await query(`DELETE FROM privacy_orgs WHERE id = $1 RETURNING id`, [id]);
+ if (!rows[0]) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+ console.log(`🗑️ Deleted privacy org ${id} (holdings cascaded)`);
+ return { ok: true };
+}
+
+/**
+ * Which vault records does org `orgId` hold — joined with masked vault
+ * fields for display. Never selects `value_enc`.
+ */
+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,
+ v.type, v.label, v.masked_value
+ FROM privacy_org_holdings h
+ JOIN privacy_vault_records v ON v.id = h.vault_record_id
+ WHERE h.org_id = $1
+ ORDER BY v.type, v.label`,
+ [orgId],
+ );
+ return rows.map(rowToHolding);
+}
+
+/** 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,
+ o.name AS org_name
+ FROM privacy_org_holdings h
+ JOIN privacy_orgs o ON o.id = h.org_id
+ WHERE h.vault_record_id = $1
+ ORDER BY o.name`,
+ [vaultRecordId],
+ );
+ return rows.map(rowToHolding);
+}
+
+/**
+ * Replace-set the holdings for an org: the body's list of
+ * `{ vaultRecordId, status }` becomes the full holdings set for the org —
+ * anything not listed is removed. Runs as one statement per side (delete the
+ * complement, upsert the rest) rather than a delete-all + reinsert, so an
+ * unrelated concurrent read never sees a momentarily-empty holdings set.
+ */
+export async function setOrgHoldings(orgId, holdings) {
+ const org = await getOrg(orgId);
+ if (!org) throw new ServerError('Organization not found', { status: 404, code: 'NOT_FOUND' });
+
+ const ids = holdings.map((h) => h.vaultRecordId);
+ if (ids.length === 0) {
+ await query(`DELETE FROM privacy_org_holdings WHERE org_id = $1`, [orgId]);
+ } else {
+ await query(
+ `DELETE FROM privacy_org_holdings WHERE org_id = $1 AND vault_record_id != ALL($2::uuid[])`,
+ [orgId, ids],
+ );
+ for (const h of holdings) {
+ await query(
+ `INSERT INTO privacy_org_holdings (org_id, vault_record_id, status, noted_at, updated_at)
+ VALUES ($1, $2, $3, NOW(), NOW())
+ ON CONFLICT (org_id, vault_record_id)
+ DO UPDATE SET status = EXCLUDED.status, updated_at = NOW()`,
+ [orgId, h.vaultRecordId, h.status ?? 'current'],
+ );
+ }
+ }
+ console.log(`🔗 Set ${ids.length} holdings for privacy org ${orgId}`);
+ return getHoldingsForOrg(orgId);
+}
+
+/**
+ * Batch status flip across ALL orgs holding a given vault record — used by
+ * the Phase 4 change-of-address workflow ("mark every org holding my old
+ * address as update_pending"). Only rows currently in `fromStatus` flip.
+ */
+export async function setHoldingsStatus(vaultRecordId, fromStatus, toStatus) {
+ const { rows } = await query(
+ `UPDATE privacy_org_holdings SET status = $1, updated_at = NOW()
+ WHERE vault_record_id = $2 AND status = $3
+ RETURNING org_id, vault_record_id`,
+ [toStatus, vaultRecordId, fromStatus],
+ );
+ console.log(`🔁 Flipped ${rows.length} holdings for vault record ${vaultRecordId} (${fromStatus} → ${toStatus})`);
+ return { updated: rows.length };
+}
+
+/** Per-org holding counts + per-vault-record org counts — powers the inventory view. */
+export async function getHoldingsSummary() {
+ 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
+ GROUP BY o.id, o.name
+ ORDER BY o.name`,
+ ),
+ 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
+ GROUP BY v.id, v.type, v.label
+ ORDER BY v.type, v.label`,
+ ),
+ ]);
+ return {
+ byOrg: byOrg.rows.map((r) => ({ orgId: r.org_id, orgName: r.org_name, holdingCount: r.holding_count })),
+ byVaultRecord: byRecord.rows.map((r) => ({
+ vaultRecordId: r.vault_record_id, type: r.type, label: r.label, orgCount: r.org_count,
+ })),
+ };
+}
diff --git a/server/services/privacyOrgs.test.js b/server/services/privacyOrgs.test.js
new file mode 100644
index 0000000000..e5cc6e4ab7
--- /dev/null
+++ b/server/services/privacyOrgs.test.js
@@ -0,0 +1,187 @@
+/**
+ * Trusted Organizations registry service unit tests (issue #2141) — DB
+ * mocked; the live-DB round trip lives in privacyOrgs.db.test.js (test:db →
+ * portos_test only). Pins CRUD param shapes, the replace-set holdings
+ * semantics, the batch status-flip query, and the 404 paths.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { queryMock } = vi.hoisted(() => ({ queryMock: vi.fn() }));
+
+vi.mock('../lib/db.js', () => ({ query: queryMock }));
+
+const {
+ createOrg, listOrgs, getOrg, updateOrg, deleteOrg,
+ getHoldingsForOrg, getOrgsHoldingRecord, setOrgHoldings, setHoldingsStatus, getHoldingsSummary,
+} = await import('./privacyOrgs.js');
+
+beforeEach(() => { queryMock.mockReset(); });
+
+const orgRow = (overrides = {}) => ({
+ id: 'o1', 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,
+});
+
+describe('createOrg', () => {
+ it('inserts with defaults for optional fields', async () => {
+ queryMock.mockResolvedValue({ rows: [orgRow()] });
+ 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(org.name).toBe('Acme Bank');
+ });
+
+ it('serializes contact as JSON', async () => {
+ 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]' }));
+ });
+});
+
+describe('listOrgs', () => {
+ it('lists with no filters', 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([]);
+ });
+
+ it('applies trust/status/category filters', 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']);
+ });
+});
+
+describe('getOrg', () => {
+ it('returns null for a missing org', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ expect(await getOrg('missing')).toBe(null);
+ });
+});
+
+describe('updateOrg', () => {
+ it('builds a partial SET clause for only the provided fields', async () => {
+ queryMock.mockResolvedValue({ rows: [orgRow({ name: 'Renamed' })] });
+ const updated = await updateOrg('o1', { name: 'Renamed' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/SET name = \$1, updated_at = NOW\(\)/);
+ expect(params).toEqual(['Renamed', 'o1']);
+ expect(updated.name).toBe('Renamed');
+ });
+
+ it('404s an unknown org', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(updateOrg('missing', { name: 'x' })).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+});
+
+describe('deleteOrg', () => {
+ it('404s an unknown org', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await expect(deleteOrg('missing')).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('deletes and returns ok', async () => {
+ queryMock.mockResolvedValue({ rows: [{ id: 'o1' }] });
+ expect(await deleteOrg('o1')).toEqual({ ok: true });
+ });
+});
+
+describe('getHoldingsForOrg / getOrgsHoldingRecord', () => {
+ it('joins masked vault fields only — never value_enc', async () => {
+ queryMock.mockResolvedValue({
+ rows: [{
+ org_id: 'o1', vault_record_id: 'v1', status: 'current', noted_at: 'now', updated_at: 'now',
+ type: 'email', label: 'Main', masked_value: 'a•••@b.com',
+ }],
+ });
+ const holdings = await getHoldingsForOrg('o1');
+ expect(holdings[0]).toEqual({
+ orgId: 'o1', vaultRecordId: 'v1', status: 'current', notedAt: 'now', updatedAt: 'now',
+ vaultType: 'email', vaultLabel: 'Main', vaultMaskedValue: 'a•••@b.com',
+ });
+ expect(JSON.stringify(holdings)).not.toMatch(/value_enc/);
+ });
+
+ it('getOrgsHoldingRecord joins org name', async () => {
+ queryMock.mockResolvedValue({
+ rows: [{ org_id: 'o1', vault_record_id: 'v1', status: 'current', noted_at: 'now', updated_at: 'now', org_name: 'Acme Bank' }],
+ });
+ const orgs = await getOrgsHoldingRecord('v1');
+ expect(orgs[0]).toMatchObject({ orgId: 'o1', orgName: 'Acme Bank' });
+ });
+});
+
+describe('setOrgHoldings', () => {
+ it('404s an unknown org before writing anything', async () => {
+ queryMock.mockResolvedValueOnce({ rows: [] }); // getOrg
+ await expect(setOrgHoldings('missing', [{ vaultRecordId: 'v1' }]))
+ .rejects.toMatchObject({ status: 404 });
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('deletes the complement and upserts the given set', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
+ if (/DELETE FROM privacy_org_holdings/.test(sql)) return { rows: [] };
+ if (/INSERT INTO privacy_org_holdings/.test(sql)) return { rows: [] };
+ if (/SELECT h\.org_id/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ await setOrgHoldings('o1', [{ vaultRecordId: 'v1', status: 'current' }, { vaultRecordId: 'v2' }]);
+ const deleteCall = queryMock.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
+ expect(deleteCall[1]).toEqual(['o1', ['v1', 'v2']]);
+ const insertCalls = queryMock.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
+ });
+
+ it('clears all holdings when given an empty list', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_orgs WHERE id/.test(sql)) return { rows: [orgRow()] };
+ if (/DELETE FROM privacy_org_holdings WHERE org_id = \$1$/.test(sql)) return { rows: [] };
+ if (/SELECT h\.org_id/.test(sql)) return { rows: [] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ await setOrgHoldings('o1', []);
+ const deleteCall = queryMock.mock.calls.find(([sql]) => /DELETE FROM privacy_org_holdings/.test(sql));
+ expect(deleteCall[1]).toEqual(['o1']);
+ });
+});
+
+describe('setHoldingsStatus', () => {
+ it('flips only rows matching fromStatus and reports the count', async () => {
+ queryMock.mockResolvedValue({ rows: [{ org_id: 'o1', vault_record_id: 'v1' }, { org_id: 'o2', vault_record_id: 'v1' }] });
+ const result = await setHoldingsStatus('v1', 'current', 'update_pending');
+ expect(result).toEqual({ updated: 2 });
+ const [, params] = queryMock.mock.calls[0];
+ expect(params).toEqual(['update_pending', 'v1', 'current']);
+ });
+});
+
+describe('getHoldingsSummary', () => {
+ it('returns per-org and per-vault-record counts', async () => {
+ queryMock.mockImplementation(async (sql) => {
+ if (/FROM privacy_orgs o/.test(sql)) return { rows: [{ org_id: 'o1', org_name: 'Acme', holding_count: 2 }] };
+ if (/FROM privacy_vault_records v/.test(sql)) return { rows: [{ vault_record_id: 'v1', type: 'email', label: 'Main', org_count: 1 }] };
+ throw new Error(`unexpected query: ${sql}`);
+ });
+ const summary = await getHoldingsSummary();
+ expect(summary.byOrg).toEqual([{ orgId: 'o1', orgName: 'Acme', holdingCount: 2 }]);
+ expect(summary.byVaultRecord).toEqual([{ vaultRecordId: 'v1', type: 'email', label: 'Main', orgCount: 1 }]);
+ });
+});
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index d89e3ed83b..dcd60051b8 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -13,6 +13,7 @@ export const DB_TEST_INCLUDE = [
'services/catalogDB.facets.db.test.js',
'services/humanActivity.db.test.js',
'services/privacyVault.db.test.js',
+ 'services/privacyOrgs.db.test.js',
'services/catalogCanonProjection.test.js',
'services/catalogRefResolver.test.js',
'services/creativeDirector/projectsDB.test.js',