pgserve 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Tests for src/audit.js — JSONL writer with rotation + syslog target.
3
+ *
4
+ * Tests use temp dirs under /tmp; nothing touches the user's real
5
+ * `~/.pgserve/audit.log`. The syslog test stubs `logger` via PATH so we
6
+ * don't depend on (or pollute) the host's syslog daemon.
7
+ */
8
+
9
+ import { test, expect, beforeEach, afterEach } from 'bun:test';
10
+ import fs from 'fs';
11
+ import os from 'os';
12
+ import path from 'path';
13
+ import {
14
+ audit,
15
+ configureAudit,
16
+ readAuditTarget,
17
+ AUDIT_EVENTS,
18
+ _internals,
19
+ } from '../src/audit.js';
20
+
21
+ let scratchDir;
22
+
23
+ beforeEach(() => {
24
+ scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pgserve-audit-test-'));
25
+ configureAudit({
26
+ logFile: path.join(scratchDir, 'audit.log'),
27
+ target: 'file',
28
+ });
29
+ });
30
+
31
+ afterEach(() => {
32
+ try {
33
+ fs.rmSync(scratchDir, { recursive: true, force: true });
34
+ } catch { /* noop */ }
35
+ });
36
+
37
+ test('audit() appends a JSON line per event', () => {
38
+ audit(AUDIT_EVENTS.DB_CREATED, { fingerprint: 'abc123def456', db: 'app_demo_abc123def456' });
39
+ audit(AUDIT_EVENTS.CONNECTION_ROUTED, { fingerprint: 'abc123def456', peer_pid: 1234 });
40
+
41
+ const logFile = path.join(scratchDir, 'audit.log');
42
+ const lines = fs.readFileSync(logFile, 'utf8').trim().split('\n');
43
+ expect(lines.length).toBe(2);
44
+ const r1 = JSON.parse(lines[0]);
45
+ expect(r1.event).toBe('db_created');
46
+ expect(r1.fingerprint).toBe('abc123def456');
47
+ expect(typeof r1.ts).toBe('string');
48
+ expect(new Date(r1.ts).toString()).not.toBe('Invalid Date');
49
+
50
+ const r2 = JSON.parse(lines[1]);
51
+ expect(r2.event).toBe('connection_routed');
52
+ expect(r2.peer_pid).toBe(1234);
53
+ });
54
+
55
+ test('audit() refuses unknown events', () => {
56
+ expect(() => audit('definitely_not_a_real_event', {})).toThrow(/unknown event/);
57
+ });
58
+
59
+ test('audit() creates the parent directory if missing', () => {
60
+ const nested = path.join(scratchDir, 'nested', 'sub', 'audit.log');
61
+ audit(AUDIT_EVENTS.DB_CREATED, { fingerprint: 'a'.repeat(12) }, { logFile: nested });
62
+ expect(fs.existsSync(nested)).toBe(true);
63
+ });
64
+
65
+ test('all v2.0 event names are exported (incl. Group 6 tcp_*)', () => {
66
+ expect(Object.values(AUDIT_EVENTS).sort()).toEqual([
67
+ 'connection_denied_fingerprint_mismatch',
68
+ 'connection_routed',
69
+ 'db_created',
70
+ 'db_persist_honored',
71
+ 'db_reaped_liveness',
72
+ 'db_reaped_ttl',
73
+ 'enforcement_kill_switch_used',
74
+ 'tcp_token_denied',
75
+ 'tcp_token_issued',
76
+ 'tcp_token_used',
77
+ ]);
78
+ });
79
+
80
+ test('rotation kicks in once existing file crosses 50 MB', () => {
81
+ const logFile = path.join(scratchDir, 'audit.log');
82
+ // Use a sparse file to simulate a 50 MB log without writing 50 MB.
83
+ const fd = fs.openSync(logFile, 'w');
84
+ fs.ftruncateSync(fd, _internals.ROTATE_THRESHOLD_BYTES);
85
+ fs.closeSync(fd);
86
+
87
+ audit(AUDIT_EVENTS.DB_CREATED, { fingerprint: 'r'.repeat(12) });
88
+
89
+ // Original file rotated to .1, fresh file holds the new line.
90
+ expect(fs.existsSync(`${logFile}.1`)).toBe(true);
91
+ const fresh = fs.readFileSync(logFile, 'utf8');
92
+ expect(fresh.trim().split('\n').length).toBe(1);
93
+ expect(JSON.parse(fresh.trim()).event).toBe('db_created');
94
+
95
+ // The rotated file is the original 50 MB sparse file.
96
+ expect(fs.statSync(`${logFile}.1`).size).toBe(_internals.ROTATE_THRESHOLD_BYTES);
97
+ });
98
+
99
+ test('rotation cascades up to KEEP files and drops the eldest', () => {
100
+ const logFile = path.join(scratchDir, 'audit.log');
101
+ // Pre-populate audit.log.1 ... audit.log.5 with distinct markers.
102
+ for (let i = 1; i <= _internals.ROTATE_KEEP; i++) {
103
+ fs.writeFileSync(`${logFile}.${i}`, `slot-${i}\n`);
104
+ }
105
+ // And the live audit.log just under threshold.
106
+ const fd = fs.openSync(logFile, 'w');
107
+ fs.ftruncateSync(fd, _internals.ROTATE_THRESHOLD_BYTES);
108
+ fs.closeSync(fd);
109
+
110
+ audit(AUDIT_EVENTS.DB_CREATED, { fingerprint: 'q'.repeat(12) });
111
+
112
+ // .5 (was "slot-5") dropped; .4 → .5; .3 → .4; .2 → .3; .1 → .2; live → .1.
113
+ expect(fs.readFileSync(`${logFile}.5`, 'utf8').trim()).toBe('slot-4');
114
+ expect(fs.readFileSync(`${logFile}.4`, 'utf8').trim()).toBe('slot-3');
115
+ expect(fs.readFileSync(`${logFile}.3`, 'utf8').trim()).toBe('slot-2');
116
+ expect(fs.readFileSync(`${logFile}.2`, 'utf8').trim()).toBe('slot-1');
117
+ expect(fs.statSync(`${logFile}.1`).size).toBe(_internals.ROTATE_THRESHOLD_BYTES);
118
+ });
119
+
120
+ test('audit({target:"syslog"}) spawns logger -t pgserve-audit', async () => {
121
+ // Stub `logger` by prepending a temp shim to PATH.
122
+ const shimDir = path.join(scratchDir, 'shim');
123
+ fs.mkdirSync(shimDir, { recursive: true });
124
+ const marker = path.join(scratchDir, 'logger-calls.txt');
125
+ const shimPath = path.join(shimDir, 'logger');
126
+ fs.writeFileSync(
127
+ shimPath,
128
+ `#!/usr/bin/env bash
129
+ # Capture argv to a marker file so the test can verify the spawn.
130
+ printf '%s\\n' "$*" >> "${marker}"
131
+ `,
132
+ { mode: 0o755 },
133
+ );
134
+
135
+ const oldPath = process.env.PATH;
136
+ process.env.PATH = `${shimDir}:${oldPath}`;
137
+ try {
138
+ audit(
139
+ AUDIT_EVENTS.CONNECTION_ROUTED,
140
+ { fingerprint: 's'.repeat(12) },
141
+ { target: 'syslog' },
142
+ );
143
+ // logger is spawned async; poll briefly for the marker.
144
+ const deadline = Date.now() + 2000;
145
+ while (!fs.existsSync(marker) && Date.now() < deadline) {
146
+ await new Promise(r => setTimeout(r, 25));
147
+ }
148
+ expect(fs.existsSync(marker)).toBe(true);
149
+ const contents = fs.readFileSync(marker, 'utf8');
150
+ expect(contents).toContain('-t pgserve-audit');
151
+ expect(contents).toContain('"event":"connection_routed"');
152
+ } finally {
153
+ process.env.PATH = oldPath;
154
+ }
155
+ });
156
+
157
+ test('audit({target:"syslog"}) swallows missing logger binary', () => {
158
+ // Point PATH at an empty dir → `logger` cannot be found → no throw.
159
+ const empty = path.join(scratchDir, 'empty');
160
+ fs.mkdirSync(empty);
161
+ const oldPath = process.env.PATH;
162
+ process.env.PATH = empty;
163
+ try {
164
+ expect(() =>
165
+ audit(
166
+ AUDIT_EVENTS.CONNECTION_ROUTED,
167
+ { fingerprint: 'z'.repeat(12) },
168
+ { target: 'syslog' },
169
+ ),
170
+ ).not.toThrow();
171
+ } finally {
172
+ process.env.PATH = oldPath;
173
+ }
174
+ });
175
+
176
+ test('readAuditTarget reads pgserve.audit.target from package.json', () => {
177
+ const pkgFile = path.join(scratchDir, 'package.json');
178
+ fs.writeFileSync(
179
+ pkgFile,
180
+ JSON.stringify({ name: 'demo', pgserve: { audit: { target: 'syslog' } } }),
181
+ );
182
+ expect(readAuditTarget(pkgFile)).toBe('syslog');
183
+
184
+ fs.writeFileSync(pkgFile, JSON.stringify({ name: 'demo' }));
185
+ expect(readAuditTarget(pkgFile)).toBe('file');
186
+
187
+ // Missing file → file (default).
188
+ expect(readAuditTarget(path.join(scratchDir, 'missing.json'))).toBe('file');
189
+ });
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Tests for src/control-db.js — pgserve_meta schema + accessors.
3
+ *
4
+ * Boots an ephemeral pgserve router (memory mode), connects via node-pg
5
+ * to the default `postgres` database, and exercises every exported function.
6
+ */
7
+
8
+ import { test, expect, beforeAll, afterAll } from 'bun:test';
9
+ import fs from 'fs';
10
+ import pg from 'pg';
11
+ import { startMultiTenantServer } from '../src/index.js';
12
+ import {
13
+ ensureMetaSchema,
14
+ recordDbCreated,
15
+ touchLastConnection,
16
+ markPersist,
17
+ forEachReapable,
18
+ deleteMetaRow,
19
+ addAllowedToken,
20
+ revokeAllowedToken,
21
+ verifyToken,
22
+ findRowByFingerprint,
23
+ } from '../src/control-db.js';
24
+
25
+ const { Client } = pg;
26
+
27
+ const TEST_DATA_DIR = './test-data-control-db';
28
+ const PORT = 15561;
29
+
30
+ let router;
31
+ let client;
32
+
33
+ function cleanupDataDir() {
34
+ if (fs.existsSync(TEST_DATA_DIR)) {
35
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
36
+ }
37
+ }
38
+
39
+ beforeAll(async () => {
40
+ cleanupDataDir();
41
+ router = await startMultiTenantServer({
42
+ port: PORT,
43
+ baseDir: TEST_DATA_DIR,
44
+ logLevel: 'warn',
45
+ });
46
+
47
+ client = new Client({
48
+ host: '127.0.0.1',
49
+ port: PORT,
50
+ database: 'postgres',
51
+ user: 'postgres',
52
+ password: 'postgres',
53
+ });
54
+ await client.connect();
55
+ await client.query('DROP TABLE IF EXISTS pgserve_meta');
56
+ });
57
+
58
+ afterAll(async () => {
59
+ try { await client.end(); } catch { /* noop */ }
60
+ try { await router.stop(); } catch { /* noop */ }
61
+ cleanupDataDir();
62
+ });
63
+
64
+ test('ensureMetaSchema creates table on first call', async () => {
65
+ await ensureMetaSchema(client);
66
+ const r = await client.query(`
67
+ SELECT column_name FROM information_schema.columns
68
+ WHERE table_name = 'pgserve_meta'
69
+ ORDER BY ordinal_position
70
+ `);
71
+ const columns = r.rows.map(row => row.column_name);
72
+ expect(columns).toEqual([
73
+ 'database_name',
74
+ 'fingerprint',
75
+ 'peer_uid',
76
+ 'package_realpath',
77
+ 'created_at',
78
+ 'last_connection_at',
79
+ 'liveness_pid',
80
+ 'persist',
81
+ 'allowed_tokens',
82
+ ]);
83
+ });
84
+
85
+ test('ensureMetaSchema is idempotent', async () => {
86
+ await ensureMetaSchema(client);
87
+ await ensureMetaSchema(client);
88
+ // No throw — schema unchanged.
89
+ const r = await client.query(`SELECT count(*)::int AS n FROM pgserve_meta`);
90
+ expect(r.rows[0].n).toBe(0);
91
+ });
92
+
93
+ test('recordDbCreated inserts a row + select round-trip', async () => {
94
+ await client.query('TRUNCATE pgserve_meta');
95
+ await recordDbCreated(client, {
96
+ databaseName: 'app_demo_abc123def456',
97
+ fingerprint: 'abc123def456',
98
+ peerUid: 1000,
99
+ packageRealpath: '/home/me/proj/package.json',
100
+ livenessPid: 4242,
101
+ persist: false,
102
+ });
103
+ const r = await client.query(`SELECT * FROM pgserve_meta WHERE database_name = $1`, [
104
+ 'app_demo_abc123def456',
105
+ ]);
106
+ expect(r.rows.length).toBe(1);
107
+ const row = r.rows[0];
108
+ expect(row.fingerprint).toBe('abc123def456');
109
+ expect(row.peer_uid).toBe(1000);
110
+ expect(row.package_realpath).toBe('/home/me/proj/package.json');
111
+ expect(row.liveness_pid).toBe(4242);
112
+ expect(row.persist).toBe(false);
113
+ expect(row.created_at).toBeInstanceOf(Date);
114
+ expect(row.last_connection_at).toBeInstanceOf(Date);
115
+ });
116
+
117
+ test('recordDbCreated upserts on conflict (database_name PK)', async () => {
118
+ await client.query('TRUNCATE pgserve_meta');
119
+ await recordDbCreated(client, {
120
+ databaseName: 'app_demo_abc123def456',
121
+ fingerprint: 'abc123def456',
122
+ peerUid: 1000,
123
+ packageRealpath: '/home/me/proj/package.json',
124
+ livenessPid: 4242,
125
+ });
126
+ // Re-insert with new peerUid + livenessPid → must upsert.
127
+ await recordDbCreated(client, {
128
+ databaseName: 'app_demo_abc123def456',
129
+ fingerprint: 'abc123def456',
130
+ peerUid: 1001,
131
+ packageRealpath: '/home/me/proj/package.json',
132
+ livenessPid: 9999,
133
+ persist: true,
134
+ });
135
+ const r = await client.query(`SELECT peer_uid, liveness_pid, persist FROM pgserve_meta`);
136
+ expect(r.rows.length).toBe(1);
137
+ expect(r.rows[0].peer_uid).toBe(1001);
138
+ expect(r.rows[0].liveness_pid).toBe(9999);
139
+ expect(r.rows[0].persist).toBe(true);
140
+ });
141
+
142
+ test('touchLastConnection bumps last_connection_at and liveness_pid', async () => {
143
+ await client.query('TRUNCATE pgserve_meta');
144
+ await recordDbCreated(client, {
145
+ databaseName: 'app_x_111111111111',
146
+ fingerprint: '111111111111',
147
+ peerUid: 1000,
148
+ livenessPid: 100,
149
+ });
150
+ const before = await client.query(
151
+ `SELECT last_connection_at, liveness_pid FROM pgserve_meta WHERE database_name = $1`,
152
+ ['app_x_111111111111'],
153
+ );
154
+ // Sleep briefly so now() advances visibly.
155
+ await new Promise(r => setTimeout(r, 50));
156
+
157
+ await touchLastConnection(client, {
158
+ databaseName: 'app_x_111111111111',
159
+ livenessPid: 200,
160
+ });
161
+ const after = await client.query(
162
+ `SELECT last_connection_at, liveness_pid FROM pgserve_meta WHERE database_name = $1`,
163
+ ['app_x_111111111111'],
164
+ );
165
+ expect(after.rows[0].liveness_pid).toBe(200);
166
+ expect(after.rows[0].last_connection_at.getTime()).toBeGreaterThan(
167
+ before.rows[0].last_connection_at.getTime(),
168
+ );
169
+ });
170
+
171
+ test('markPersist toggles persist flag', async () => {
172
+ await client.query('TRUNCATE pgserve_meta');
173
+ await recordDbCreated(client, {
174
+ databaseName: 'app_p_222222222222',
175
+ fingerprint: '222222222222',
176
+ peerUid: 1000,
177
+ });
178
+ await markPersist(client, 'app_p_222222222222', true);
179
+ let r = await client.query(`SELECT persist FROM pgserve_meta WHERE database_name = $1`, [
180
+ 'app_p_222222222222',
181
+ ]);
182
+ expect(r.rows[0].persist).toBe(true);
183
+
184
+ await markPersist(client, 'app_p_222222222222', false);
185
+ r = await client.query(`SELECT persist FROM pgserve_meta WHERE database_name = $1`, [
186
+ 'app_p_222222222222',
187
+ ]);
188
+ expect(r.rows[0].persist).toBe(false);
189
+ });
190
+
191
+ test('forEachReapable yields only persist=false rows in last_connection_at order', async () => {
192
+ await client.query('TRUNCATE pgserve_meta');
193
+ // Older row first, newer row second; persistent row separately.
194
+ await client.query(
195
+ `INSERT INTO pgserve_meta (database_name, fingerprint, peer_uid, last_connection_at, persist)
196
+ VALUES
197
+ ('app_a_aaaaaaaaaaaa', 'aaaaaaaaaaaa', 1000, now() - interval '2 hours', false),
198
+ ('app_b_bbbbbbbbbbbb', 'bbbbbbbbbbbb', 1000, now() - interval '1 hour', false),
199
+ ('app_c_cccccccccccc', 'cccccccccccc', 1000, now(), true)`,
200
+ );
201
+
202
+ const seen = [];
203
+ for await (const row of forEachReapable(client, { now: new Date() })) {
204
+ seen.push(row.databaseName);
205
+ }
206
+ expect(seen).toEqual(['app_a_aaaaaaaaaaaa', 'app_b_bbbbbbbbbbbb']);
207
+ });
208
+
209
+ test('deleteMetaRow removes the row', async () => {
210
+ await client.query('TRUNCATE pgserve_meta');
211
+ await recordDbCreated(client, {
212
+ databaseName: 'app_del_333333333333',
213
+ fingerprint: '333333333333',
214
+ peerUid: 1000,
215
+ });
216
+ await deleteMetaRow(client, 'app_del_333333333333');
217
+ const r = await client.query(`SELECT count(*)::int AS n FROM pgserve_meta`);
218
+ expect(r.rows[0].n).toBe(0);
219
+ });
220
+
221
+ test('recordDbCreated rejects bad input', async () => {
222
+ await expect(recordDbCreated(client, { fingerprint: 'x', peerUid: 1 })).rejects.toThrow(
223
+ /databaseName required/,
224
+ );
225
+ await expect(recordDbCreated(client, { databaseName: 'd', peerUid: 1 })).rejects.toThrow(
226
+ /fingerprint required/,
227
+ );
228
+ await expect(
229
+ recordDbCreated(client, { databaseName: 'd', fingerprint: 'f', peerUid: 'nope' }),
230
+ ).rejects.toThrow(/peerUid must be number/);
231
+ });
232
+
233
+ test('addAllowedToken refuses unknown fingerprint', async () => {
234
+ await client.query('TRUNCATE pgserve_meta');
235
+ await expect(
236
+ addAllowedToken(client, { fingerprint: 'deadbeef0000', tokenId: 'tk1', tokenHash: 'h1' }),
237
+ ).rejects.toThrow(/no pgserve_meta row/);
238
+ });
239
+
240
+ test('addAllowedToken appends, verifyToken finds it, revokeAllowedToken removes it', async () => {
241
+ await client.query('TRUNCATE pgserve_meta');
242
+ await recordDbCreated(client, {
243
+ databaseName: 'app_demo_4444aabbccdd',
244
+ fingerprint: '4444aabbccdd',
245
+ peerUid: 1000,
246
+ });
247
+ await addAllowedToken(client, {
248
+ fingerprint: '4444aabbccdd',
249
+ tokenId: 'aaaa1111',
250
+ tokenHash: 'hash-1',
251
+ });
252
+ await addAllowedToken(client, {
253
+ fingerprint: '4444aabbccdd',
254
+ tokenId: 'bbbb2222',
255
+ tokenHash: 'hash-2',
256
+ });
257
+
258
+ const row = await findRowByFingerprint(client, '4444aabbccdd');
259
+ expect(row).not.toBeNull();
260
+ expect(row.allowedTokens.length).toBe(2);
261
+ expect(row.allowedTokens.map(t => t.id).sort()).toEqual(['aaaa1111', 'bbbb2222']);
262
+
263
+ const ok = await verifyToken(client, { fingerprint: '4444aabbccdd', tokenHash: 'hash-2' });
264
+ expect(ok).toEqual({ tokenId: 'bbbb2222', databaseName: 'app_demo_4444aabbccdd' });
265
+
266
+ const miss = await verifyToken(client, { fingerprint: '4444aabbccdd', tokenHash: 'no-such' });
267
+ expect(miss).toBeNull();
268
+
269
+ const affected = await revokeAllowedToken(client, 'aaaa1111');
270
+ expect(affected).toBe(1);
271
+
272
+ const after = await findRowByFingerprint(client, '4444aabbccdd');
273
+ expect(after.allowedTokens.map(t => t.id)).toEqual(['bbbb2222']);
274
+ });
275
+
276
+ test('revokeAllowedToken returns 0 for unknown id', async () => {
277
+ await client.query('TRUNCATE pgserve_meta');
278
+ await recordDbCreated(client, {
279
+ databaseName: 'app_x_5555aabbccdd',
280
+ fingerprint: '5555aabbccdd',
281
+ peerUid: 1000,
282
+ });
283
+ const affected = await revokeAllowedToken(client, 'nonexistent');
284
+ expect(affected).toBe(0);
285
+ });
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Daemon × fingerprint integration test (Group 3, deliverable 2).
3
+ *
4
+ * Verifies that PgserveDaemon.handleSocketOpen calls handleControlAccept on
5
+ * every accept, producing a `connection_routed` audit entry whose fingerprint
6
+ * is the documented 12-hex blob.
7
+ *
8
+ * Boots a real daemon (with isolated controlSocketDir + auditLogFile), dials
9
+ * the control socket via Bun.connect, and tails the audit log.
10
+ */
11
+
12
+ import { describe, test, expect } from 'bun:test';
13
+ import fs from 'fs';
14
+ import os from 'os';
15
+ import path from 'path';
16
+
17
+ import {
18
+ PgserveDaemon,
19
+ resolveControlSocketPath,
20
+ resolvePidLockPath,
21
+ } from '../src/daemon.js';
22
+ import { createLogger } from '../src/logger.js';
23
+ import { AUDIT_EVENTS, configureAudit } from '../src/audit.js';
24
+
25
+ function silentLogger() {
26
+ return createLogger({ level: 'warn' });
27
+ }
28
+
29
+ function makeIsolated(tag) {
30
+ const dir = path.join(os.tmpdir(), `pgserve-daemon-fp-${tag}-${process.pid}-${Date.now()}`);
31
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
32
+ return dir;
33
+ }
34
+
35
+ function readAuditLines(logFile) {
36
+ if (!fs.existsSync(logFile)) return [];
37
+ return fs.readFileSync(logFile, 'utf8')
38
+ .split('\n')
39
+ .filter(Boolean)
40
+ .map((l) => JSON.parse(l));
41
+ }
42
+
43
+ describe('Group 3 — daemon emits connection_routed on accept', () => {
44
+ test('handleSocketOpen derives fingerprint and audits connection_routed', async () => {
45
+ const dir = makeIsolated('routed');
46
+ const auditLogFile = path.join(dir, 'audit.log');
47
+
48
+ const daemon = new PgserveDaemon({
49
+ controlSocketDir: dir,
50
+ controlSocketPath: resolveControlSocketPath(dir),
51
+ pidLockPath: resolvePidLockPath(dir),
52
+ pgPort: 16100,
53
+ auditLogFile,
54
+ auditTarget: 'file',
55
+ logger: silentLogger(),
56
+ });
57
+ await daemon.start();
58
+
59
+ try {
60
+ // Dial the control socket. We don't need to push a real PG startup
61
+ // message — the accept hook fires the moment the connection opens,
62
+ // before any handshake bytes are needed.
63
+ const acceptedFingerprint = await new Promise((resolve, reject) => {
64
+ const timer = setTimeout(() => reject(new Error('timeout waiting for accept')), 2000);
65
+ daemon.once('accept', ({ fingerprint }) => {
66
+ clearTimeout(timer);
67
+ resolve(fingerprint);
68
+ });
69
+ Bun.connect({
70
+ unix: daemon.controlSocketPath,
71
+ socket: {
72
+ open(s) { s.end(); },
73
+ data() {},
74
+ close() {},
75
+ error(_s, err) { clearTimeout(timer); reject(err); },
76
+ },
77
+ }).catch((err) => { clearTimeout(timer); reject(err); });
78
+ });
79
+
80
+ expect(acceptedFingerprint).toBeDefined();
81
+ expect(acceptedFingerprint.fingerprint).toMatch(/^[0-9a-f]{12}$/);
82
+
83
+ // Allow the audit appendFileSync to flush. Poll briefly.
84
+ const deadline = Date.now() + 1000;
85
+ let entries = [];
86
+ while (Date.now() < deadline) {
87
+ entries = readAuditLines(auditLogFile);
88
+ if (entries.length > 0) break;
89
+ await new Promise((r) => setTimeout(r, 25));
90
+ }
91
+ expect(entries.length).toBeGreaterThan(0);
92
+ const routed = entries.find((e) => e.event === AUDIT_EVENTS.CONNECTION_ROUTED);
93
+ expect(routed).toBeDefined();
94
+ expect(routed.fingerprint).toMatch(/^[0-9a-f]{12}$/);
95
+ expect(routed.fingerprint).toBe(acceptedFingerprint.fingerprint);
96
+ expect(routed.peer_uid).toBe(process.getuid());
97
+ expect(typeof routed.peer_pid).toBe('number');
98
+ expect(['package', 'script']).toContain(routed.mode);
99
+ } finally {
100
+ await daemon.stop();
101
+ // Reset audit module's mutable defaults so other tests aren't affected.
102
+ configureAudit({
103
+ logFile: path.join(os.homedir(), '.pgserve', 'audit.log'),
104
+ target: process.env.PGSERVE_AUDIT_TARGET || 'file',
105
+ });
106
+ fs.rmSync(dir, { recursive: true, force: true });
107
+ }
108
+ });
109
+ });