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

fix: address review — bind the vault/case list filters as $N, close the scanBroker consent bypass, and default the consent scope (#3658)

[._.]/ Adam Eivy7041bda36c28
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index a1c2eb82ef..d983a447f4 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -148,10 +148,7 @@ router.get('/subjects/:id/consents', asyncHandler(async (req, res) => {
router.post('/subjects/:id/consents', asyncHandler(async (req, res) => {
const { id } = validateRequest(privacySubjectIdParamsSchema, req.params);
const { scope, method, note } = validateRequest(privacySubjectConsentSchema, req.body);
- await assertSubject(id);
- res.status(201).json(await recordConsent({
- subjectId: id, scope: scope ?? 'pii_vault', method, note,
- }));
+ res.status(201).json(await recordConsent({ subjectId: id, scope, method, note }));
}));
router.get('/status', asyncHandler(async (req, res) => {
diff --git a/server/services/privacyBrokers.js b/server/services/privacyBrokers.js
index 5c09b442dc..28d798a343 100644
--- a/server/services/privacyBrokers.js
+++ b/server/services/privacyBrokers.js
@@ -435,7 +435,7 @@ export async function listBrokerCases({ state, subjectId } = {}) {
// never plan a submission for one using the other's ledger.
const params = [resolveSubjectId(subjectId)];
const clauses = ['c.subject_id = $1'];
- if (state) { params.push(state); clauses.push(`c.state = ${params.length}`); }
+ if (state) { params.push(state); clauses.push(`c.state = $${params.length}`); }
const where = `WHERE ${clauses.join(' AND ')}`;
const { rows } = await query(
`SELECT c.id, c.subject_id, c.broker_id, c.state, c.found, c.evidence, c.disclosed_fields,
diff --git a/server/services/privacyBrokers.test.js b/server/services/privacyBrokers.test.js
index 3a96a3c8a4..7d64229826 100644
--- a/server/services/privacyBrokers.test.js
+++ b/server/services/privacyBrokers.test.js
@@ -1,11 +1,19 @@
/**
* Pure-logic tests for the broker case state machine + recheck backoff +
- * refresh parsers (issue #2144). No DB — the DB round-trip lives in
- * privacyBrokers.db.test.js.
+ * refresh parsers (issue #2144), plus the subject-scoped case-list query shape
+ * (#3658). The DB is mocked (the pure tests don't touch it); the real DB
+ * round-trip lives in privacyBrokers.db.test.js.
*/
-import { describe, it, expect } from 'vitest';
-import {
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { queryMock } = vi.hoisted(() => ({ queryMock: vi.fn() }));
+vi.mock('../lib/db.js', () => ({ query: queryMock, withTransaction: vi.fn() }));
+
+const SELF = '00000000-0000-4000-8000-000000000001';
+vi.mock('./privacySubjects.js', () => ({ resolveSubjectId: (id) => id || SELF }));
+
+const {
CASE_STATES,
SCAN_VERDICTS,
assertTransition,
@@ -13,7 +21,28 @@ import {
computeNextRecheckAt,
parseCaRegistryCsv,
parseBadboolList,
-} from './privacyBrokers.js';
+ listBrokerCases,
+} = await import('./privacyBrokers.js');
+
+beforeEach(() => queryMock.mockReset());
+
+describe('listBrokerCases — subject scoping (#3658)', () => {
+ it('always scopes to a subject and binds the state filter as $2 (not a literal)', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await listBrokerCases({ state: 'found' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/WHERE c\.subject_id = \$1 AND c\.state = \$2/);
+ expect(params).toEqual([SELF, 'found']);
+ });
+
+ it('scopes to an explicit subject with no state filter', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await listBrokerCases({ subjectId: 'subject-2' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/WHERE c\.subject_id = \$1\s/);
+ expect(params).toEqual(['subject-2']);
+ });
+});
describe('assertTransition — valid paths', () => {
it('allows every scan verdict from unscanned', () => {
diff --git a/server/services/privacyScan.js b/server/services/privacyScan.js
index 66f09ad05a..41b26f4669 100644
--- a/server/services/privacyScan.js
+++ b/server/services/privacyScan.js
@@ -294,7 +294,10 @@ export async function probeBroker(broker, vectors, {
/**
* Scan ONE broker for exposure and record the verdict. Thin wrapper over the
- * read-only probeBroker that then writes the ledger verdict. `deps` are
+ * read-only probeBroker that then writes the ledger verdict. Re-asserts the
+ * subject's consent even though runScanPass already did: this is an exported
+ * entry point, so a direct caller (route, agent, single-broker recheck) must not
+ * be able to reach a ledger write around the gate. One indexed SELECT per broker. `deps` are
* injectable so tests never hit the network/browser:
* - `fetchImpl` (default global fetch) — the HTTP lane.
* - `browserFetch` (default fetchUrlMainText) — the JS-required escalation.
@@ -305,10 +308,12 @@ export async function scanBroker(broker, vectors, {
fetchImpl = fetch, browserFetch = fetchUrlMainText, urlSafe = isScanUrlSafe, now = new Date(),
subjectId,
} = {}) {
+ const resolvedSubjectId = resolveSubjectId(subjectId);
+ await assertSubjectConsent(resolvedSubjectId, { action: `broker exposure scan (${broker?.id})` });
const probed = await probeBroker(broker, vectors, { fetchImpl, browserFetch, urlSafe });
if (probed.skipped) return { skipped: true, reason: probed.reason };
const kase = await recordScanVerdict(broker.id, probed.verdict, {
- evidence: probed.evidence, found: probed.found ?? null, now, subjectId,
+ evidence: probed.evidence, found: probed.found ?? null, now, subjectId: resolvedSubjectId,
});
return kase;
}
diff --git a/server/services/privacySubjects.js b/server/services/privacySubjects.js
index 07b5fc99e8..92304e51ae 100644
--- a/server/services/privacySubjects.js
+++ b/server/services/privacySubjects.js
@@ -59,19 +59,23 @@ export function resolveSubjectId(subjectId) {
return subjectId ? String(subjectId).toLowerCase() : PRIVACY_SELF_SUBJECT_ID;
}
-/** Write a consent row for a subject. Append-only audit trail. */
+/**
+ * Write a consent row for a subject. Append-only audit trail. Asserts the
+ * subject first so an unknown id is a clean 404 rather than a raw FK violation,
+ * and defaults `scope` (the column is NOT NULL and the API leaves it optional).
+ */
export async function recordConsent({ subjectId, scope, method, note }) {
+ const resolved = (await assertSubject(subjectId)).id;
const id = randomUUID();
- const resolved = resolveSubjectId(subjectId);
// The legacy free-text `subject` column keeps its DEFAULT 'self' — it is
// frozen historical audit data; `subject_id` is the live scope (#3658).
await query(
`INSERT INTO privacy_consents (id, subject_id, scope, method, note, granted_at)
VALUES ($1, $2, $3, $4, $5, NOW())`,
- [id, resolved, scope, method, note ?? ''],
+ [id, resolved, scope ?? 'pii_vault', method, note ?? ''],
);
- console.log(`📝 Recorded privacy consent ${id} (subject=${resolved}, scope=${scope}, method=${method})`);
- return { id, subjectId: resolved, scope, method, note: note ?? '' };
+ console.log(`📝 Recorded privacy consent ${id} (subject=${resolved}, scope=${scope ?? 'pii_vault'}, method=${method})`);
+ return { id, subjectId: resolved, scope: scope ?? 'pii_vault', method, note: note ?? '' };
}
// ─── Subject CRUD ───────────────────────────────────────────────────────────
diff --git a/server/services/privacySubjects.test.js b/server/services/privacySubjects.test.js
index 7554e5e399..5b91d2a92d 100644
--- a/server/services/privacySubjects.test.js
+++ b/server/services/privacySubjects.test.js
@@ -146,12 +146,30 @@ describe('listSubjects', () => {
});
describe('recordConsent', () => {
- it('scopes the row by subject_id and stores the note verbatim', async () => {
+ it('404s an unknown subject rather than emitting a raw FK violation', async () => {
queryMock.mockResolvedValue({ rows: [] });
+ await expect(recordConsent({ subjectId: 's2', scope: 'pii_vault', method: 'written' }))
+ .rejects.toMatchObject({ status: 404, code: 'SUBJECT_NOT_FOUND' });
+ });
+
+ it("defaults the NOT NULL scope column when the caller omits it", async () => {
+ queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2' })] }
+ : { rows: [] }));
+ const consent = await recordConsent({ subjectId: 's2', method: 'verbal' });
+ const insert = queryMock.mock.calls.find(([q]) => /INSERT INTO privacy_consents/.test(q));
+ expect(insert[1][2]).toBe('pii_vault');
+ expect(consent.scope).toBe('pii_vault');
+ });
+
+ it('scopes the row by subject_id and stores the note verbatim', async () => {
+ queryMock.mockImplementation(async (sql) => (/FROM privacy_subjects/.test(sql)
+ ? { rows: [subjectRow({ id: 's2', relationship: 'partner' })] }
+ : { rows: [] }));
const consent = await recordConsent({
subjectId: 's2', scope: 'broker_optout', method: 'written', note: 'form filed 2026-01-01',
});
- const [sql, params] = queryMock.mock.calls[0];
+ const [sql, params] = queryMock.mock.calls.find(([q]) => /INSERT INTO privacy_consents/.test(q));
expect(sql).toMatch(/INSERT INTO privacy_consents/);
expect(params[1]).toBe('s2');
expect(params[2]).toBe('broker_optout');
diff --git a/server/services/privacyVault.js b/server/services/privacyVault.js
index 369a954bda..597fb5d84c 100644
--- a/server/services/privacyVault.js
+++ b/server/services/privacyVault.js
@@ -115,7 +115,7 @@ export async function listVaultRecords({ type, subjectId } = {}) {
// caller is unchanged.
const params = [resolveSubjectId(subjectId)];
const clauses = ['subject_id = $1'];
- if (type) { params.push(type); clauses.push(`type = ${params.length}`); }
+ if (type) { params.push(type); clauses.push(`type = $${params.length}`); }
const { rows } = await query(
`SELECT ${RECORD_COLUMNS} FROM privacy_vault_records
WHERE ${clauses.join(' AND ')} ORDER BY created_at DESC`,
diff --git a/server/services/privacyVault.test.js b/server/services/privacyVault.test.js
index 559a90ff42..3d08bdcfcd 100644
--- a/server/services/privacyVault.test.js
+++ b/server/services/privacyVault.test.js
@@ -29,7 +29,7 @@ vi.mock('./privacySubjects.js', () => ({
}));
const {
- createVaultRecord, updateVaultRecord, revealValue, getVaultStatus, resolveUseForScans,
+ createVaultRecord, listVaultRecords, updateVaultRecord, revealValue, getVaultStatus, resolveUseForScans,
} = await import('./privacyVault.js');
const { encryptValue } = await import('../lib/vaultCrypto.js');
@@ -131,6 +131,24 @@ describe('createVaultRecord', () => {
});
});
+describe('listVaultRecords', () => {
+ it('scopes to the subject and binds the type filter as $2 (not a literal)', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await listVaultRecords({ type: 'email' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/WHERE subject_id = \$1 AND type = \$2/);
+ expect(params).toEqual([SELF, 'email']);
+ });
+
+ it('omits the type clause when no type is given', async () => {
+ queryMock.mockResolvedValue({ rows: [] });
+ await listVaultRecords({ subjectId: 'subject-2' });
+ const [sql, params] = queryMock.mock.calls[0];
+ expect(sql).toMatch(/WHERE subject_id = \$1 ORDER BY/);
+ expect(params).toEqual(['subject-2']);
+ });
+});
+
describe('updateVaultRecord', () => {
function mockLockedRow(row) {
const client = {