postgresai 0.12.0-beta.7 → 0.14.0-beta.1

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,368 @@
1
+ const test = require("node:test");
2
+ const assert = require("node:assert/strict");
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const net = require("node:net");
7
+ const { spawn, spawnSync } = require("node:child_process");
8
+
9
+ function sqlLiteral(value) {
10
+ return `'${String(value).replace(/'/g, "''")}'`;
11
+ }
12
+
13
+ function findOnPath(cmd) {
14
+ const which = spawnSync("sh", ["-lc", `command -v ${cmd}`], { encoding: "utf8" });
15
+ if (which.status === 0) return String(which.stdout || "").trim();
16
+ return null;
17
+ }
18
+
19
+ function findPgBin(cmd) {
20
+ const p = findOnPath(cmd);
21
+ if (p) return p;
22
+
23
+ // Debian/Ubuntu (GitLab CI node:*-bullseye images): binaries usually live here.
24
+ // We avoid filesystem globbing in JS and just ask the shell.
25
+ const probe = spawnSync(
26
+ "sh",
27
+ [
28
+ "-lc",
29
+ `ls -1 /usr/lib/postgresql/*/bin/${cmd} 2>/dev/null | head -n 1 || true`,
30
+ ],
31
+ { encoding: "utf8" }
32
+ );
33
+ const out = String(probe.stdout || "").trim();
34
+ if (out) return out;
35
+
36
+ return null;
37
+ }
38
+
39
+ function havePostgresBinaries() {
40
+ return !!(findPgBin("initdb") && findPgBin("postgres"));
41
+ }
42
+
43
+ async function getFreePort() {
44
+ return await new Promise((resolve, reject) => {
45
+ const srv = net.createServer();
46
+ srv.listen(0, "127.0.0.1", () => {
47
+ const addr = srv.address();
48
+ srv.close((err) => {
49
+ if (err) return reject(err);
50
+ resolve(addr.port);
51
+ });
52
+ });
53
+ srv.on("error", reject);
54
+ });
55
+ }
56
+
57
+ async function waitFor(fn, { timeoutMs = 10000, intervalMs = 100 } = {}) {
58
+ const start = Date.now();
59
+ // eslint-disable-next-line no-constant-condition
60
+ while (true) {
61
+ try {
62
+ return await fn();
63
+ } catch (e) {
64
+ if (Date.now() - start > timeoutMs) throw e;
65
+ await new Promise((r) => setTimeout(r, intervalMs));
66
+ }
67
+ }
68
+ }
69
+
70
+ async function withTempPostgres(t) {
71
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "postgresai-init-"));
72
+ const dataDir = path.join(tmpRoot, "data");
73
+ const socketDir = path.join(tmpRoot, "sock");
74
+ fs.mkdirSync(socketDir, { recursive: true });
75
+
76
+ const initdb = findPgBin("initdb");
77
+ const postgresBin = findPgBin("postgres");
78
+ assert.ok(initdb && postgresBin, "PostgreSQL binaries not found (need initdb and postgres)");
79
+
80
+ const init = spawnSync(initdb, ["-D", dataDir, "-U", "postgres", "-A", "trust"], {
81
+ encoding: "utf8",
82
+ });
83
+ assert.equal(init.status, 0, init.stderr || init.stdout);
84
+
85
+ // Configure: local socket trust, TCP scram.
86
+ const hbaPath = path.join(dataDir, "pg_hba.conf");
87
+ fs.appendFileSync(
88
+ hbaPath,
89
+ "\n# Added by postgresai init integration tests\nlocal all all trust\nhost all all 127.0.0.1/32 scram-sha-256\nhost all all ::1/128 scram-sha-256\n",
90
+ "utf8"
91
+ );
92
+
93
+ const port = await getFreePort();
94
+
95
+ const postgresProc = spawn(postgresBin, ["-D", dataDir, "-k", socketDir, "-h", "127.0.0.1", "-p", String(port)], {
96
+ stdio: ["ignore", "pipe", "pipe"],
97
+ });
98
+
99
+ // Register cleanup immediately so failures below don't leave a running postgres and hang CI.
100
+ t.after(async () => {
101
+ postgresProc.kill("SIGTERM");
102
+ try {
103
+ await waitFor(
104
+ async () => {
105
+ if (postgresProc.exitCode === null) throw new Error("still running");
106
+ },
107
+ { timeoutMs: 5000, intervalMs: 100 }
108
+ );
109
+ } catch {
110
+ postgresProc.kill("SIGKILL");
111
+ }
112
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
113
+ });
114
+
115
+ const { Client } = require("pg");
116
+
117
+ const connectLocal = async (database = "postgres") => {
118
+ // IMPORTANT: must match the port Postgres is started with; otherwise pg defaults to 5432 and the socket path won't exist.
119
+ const c = new Client({ host: socketDir, port, user: "postgres", database });
120
+ await c.connect();
121
+ return c;
122
+ };
123
+
124
+ await waitFor(async () => {
125
+ const c = await connectLocal();
126
+ await c.end();
127
+ });
128
+
129
+ const postgresPassword = "postgrespw";
130
+ {
131
+ const c = await connectLocal();
132
+ await c.query(`alter user postgres password ${sqlLiteral(postgresPassword)};`);
133
+ await c.query("create database testdb");
134
+ await c.end();
135
+ }
136
+
137
+ const adminUri = `postgresql://postgres:${postgresPassword}@127.0.0.1:${port}/testdb`;
138
+ return { port, socketDir, adminUri, postgresPassword };
139
+ }
140
+
141
+ async function runCliInit(args, env = {}) {
142
+ const node = process.execPath;
143
+ const cliPath = path.resolve(__dirname, "..", "dist", "bin", "postgres-ai.js");
144
+ const res = spawnSync(node, [cliPath, "init", ...args], {
145
+ encoding: "utf8",
146
+ env: { ...process.env, ...env },
147
+ });
148
+ return res;
149
+ }
150
+
151
+ test(
152
+ "integration: init supports URI / conninfo / psql-like connection styles",
153
+ { skip: !havePostgresBinaries() },
154
+ async (t) => {
155
+ const pg = await withTempPostgres(t);
156
+
157
+ // 1) positional URI
158
+ {
159
+ const r = await runCliInit([pg.adminUri, "--password", "monpw", "--skip-optional-permissions"]);
160
+ assert.equal(r.status, 0, r.stderr || r.stdout);
161
+ }
162
+
163
+ // 2) conninfo
164
+ {
165
+ const conninfo = `dbname=testdb host=127.0.0.1 port=${pg.port} user=postgres password=${pg.postgresPassword}`;
166
+ const r = await runCliInit([conninfo, "--password", "monpw2", "--skip-optional-permissions"]);
167
+ assert.equal(r.status, 0, r.stderr || r.stdout);
168
+ }
169
+
170
+ // 3) psql-like options (+ PGPASSWORD)
171
+ {
172
+ const r = await runCliInit(
173
+ [
174
+ "-h",
175
+ "127.0.0.1",
176
+ "-p",
177
+ String(pg.port),
178
+ "-U",
179
+ "postgres",
180
+ "-d",
181
+ "testdb",
182
+ "--password",
183
+ "monpw3",
184
+ "--skip-optional-permissions",
185
+ ],
186
+ { PGPASSWORD: pg.postgresPassword }
187
+ );
188
+ assert.equal(r.status, 0, r.stderr || r.stdout);
189
+ }
190
+ }
191
+ );
192
+
193
+ test(
194
+ "integration: init requires explicit monitoring password in non-interactive mode (unless --print-password)",
195
+ { skip: !havePostgresBinaries() },
196
+ async (t) => {
197
+ const pg = await withTempPostgres(t);
198
+
199
+ // spawnSync captures stdout/stderr (non-TTY). We should not print a generated password unless explicitly requested.
200
+ {
201
+ const r = await runCliInit([pg.adminUri, "--skip-optional-permissions"]);
202
+ assert.notEqual(r.status, 0);
203
+ assert.match(r.stderr, /not printed in non-interactive mode/i);
204
+ assert.match(r.stderr, /--print-password/);
205
+ }
206
+
207
+ // With explicit opt-in, it should succeed (and will print the generated password).
208
+ {
209
+ const r = await runCliInit([pg.adminUri, "--print-password", "--skip-optional-permissions"]);
210
+ assert.equal(r.status, 0, r.stderr || r.stdout);
211
+ assert.match(r.stdout, /Generated monitoring password for postgres_ai_mon/i);
212
+ assert.match(r.stdout, /PGAI_MON_PASSWORD=/);
213
+ }
214
+ }
215
+ );
216
+
217
+ test(
218
+ "integration: init fixes slightly-off permissions idempotently",
219
+ { skip: !havePostgresBinaries() },
220
+ async (t) => {
221
+ const pg = await withTempPostgres(t);
222
+ const { Client } = require("pg");
223
+
224
+ // Create monitoring role with wrong password, no grants.
225
+ {
226
+ const c = new Client({ connectionString: pg.adminUri });
227
+ await c.connect();
228
+ await c.query(
229
+ "do $$ begin if not exists (select 1 from pg_roles where rolname='postgres_ai_mon') then create role postgres_ai_mon login password 'wrong'; end if; end $$;"
230
+ );
231
+ await c.end();
232
+ }
233
+
234
+ // Run init (should grant everything).
235
+ {
236
+ const r = await runCliInit([pg.adminUri, "--password", "correctpw", "--skip-optional-permissions"]);
237
+ assert.equal(r.status, 0, r.stderr || r.stdout);
238
+ }
239
+
240
+ // Verify privileges.
241
+ {
242
+ const c = new Client({ connectionString: pg.adminUri });
243
+ await c.connect();
244
+ const dbOk = await c.query(
245
+ "select has_database_privilege('postgres_ai_mon', current_database(), 'CONNECT') as ok"
246
+ );
247
+ assert.equal(dbOk.rows[0].ok, true);
248
+ const roleOk = await c.query("select pg_has_role('postgres_ai_mon', 'pg_monitor', 'member') as ok");
249
+ assert.equal(roleOk.rows[0].ok, true);
250
+ const idxOk = await c.query(
251
+ "select has_table_privilege('postgres_ai_mon', 'pg_catalog.pg_index', 'SELECT') as ok"
252
+ );
253
+ assert.equal(idxOk.rows[0].ok, true);
254
+ const viewOk = await c.query(
255
+ "select has_table_privilege('postgres_ai_mon', 'public.pg_statistic', 'SELECT') as ok"
256
+ );
257
+ assert.equal(viewOk.rows[0].ok, true);
258
+ const sp = await c.query("select rolconfig from pg_roles where rolname='postgres_ai_mon'");
259
+ assert.ok(Array.isArray(sp.rows[0].rolconfig));
260
+ assert.ok(sp.rows[0].rolconfig.some((v) => String(v).includes("search_path=")));
261
+ await c.end();
262
+ }
263
+
264
+ // Run init again (idempotent).
265
+ {
266
+ const r = await runCliInit([pg.adminUri, "--password", "correctpw", "--skip-optional-permissions"]);
267
+ assert.equal(r.status, 0, r.stderr || r.stdout);
268
+ }
269
+ }
270
+ );
271
+
272
+ test("integration: init reports nicely when lacking permissions", { skip: !havePostgresBinaries() }, async (t) => {
273
+ const pg = await withTempPostgres(t);
274
+ const { Client } = require("pg");
275
+
276
+ // Create limited user that can connect but cannot create roles / grant.
277
+ const limitedPw = "limitedpw";
278
+ {
279
+ const c = new Client({ connectionString: pg.adminUri });
280
+ await c.connect();
281
+ await c.query(`do $$ begin
282
+ if not exists (select 1 from pg_roles where rolname='limited') then
283
+ begin
284
+ create role limited login password ${sqlLiteral(limitedPw)};
285
+ exception when duplicate_object then
286
+ null;
287
+ end;
288
+ end if;
289
+ end $$;`);
290
+ await c.query("grant connect on database testdb to limited");
291
+ await c.end();
292
+ }
293
+
294
+ const limitedUri = `postgresql://limited:${limitedPw}@127.0.0.1:${pg.port}/testdb`;
295
+ const r = await runCliInit([limitedUri, "--password", "monpw", "--skip-optional-permissions"]);
296
+ assert.notEqual(r.status, 0);
297
+ assert.match(r.stderr, /init failed:/);
298
+ // Should include step context and hint.
299
+ assert.match(r.stderr, /Failed at step "/);
300
+ assert.match(r.stderr, /Permission error:/i);
301
+ assert.match(r.stderr, /How to fix:/i);
302
+ assert.match(r.stderr, /Hint: connect as a superuser/i);
303
+ });
304
+
305
+ test("integration: init --verify returns 0 when ok and non-zero when missing", { skip: !havePostgresBinaries() }, async (t) => {
306
+ const pg = await withTempPostgres(t);
307
+ const { Client } = require("pg");
308
+
309
+ // Prepare: run init
310
+ {
311
+ const r = await runCliInit([pg.adminUri, "--password", "monpw", "--skip-optional-permissions"]);
312
+ assert.equal(r.status, 0, r.stderr || r.stdout);
313
+ }
314
+
315
+ // Verify should pass
316
+ {
317
+ const r = await runCliInit([pg.adminUri, "--verify", "--skip-optional-permissions"]);
318
+ assert.equal(r.status, 0, r.stderr || r.stdout);
319
+ assert.match(r.stdout, /init verify: OK/i);
320
+ }
321
+
322
+ // Break a required privilege and ensure verify fails
323
+ {
324
+ const c = new Client({ connectionString: pg.adminUri });
325
+ await c.connect();
326
+ // pg_catalog tables are often readable via PUBLIC by default; revoke from PUBLIC too so the failure is deterministic.
327
+ await c.query("revoke select on pg_catalog.pg_index from public");
328
+ await c.query("revoke select on pg_catalog.pg_index from postgres_ai_mon");
329
+ await c.end();
330
+ }
331
+ {
332
+ const r = await runCliInit([pg.adminUri, "--verify", "--skip-optional-permissions"]);
333
+ assert.notEqual(r.status, 0);
334
+ assert.match(r.stderr, /init verify failed/i);
335
+ assert.match(r.stderr, /pg_catalog\.pg_index/i);
336
+ }
337
+ });
338
+
339
+ test("integration: init --reset-password updates the monitoring role login password", { skip: !havePostgresBinaries() }, async (t) => {
340
+ const pg = await withTempPostgres(t);
341
+ const { Client } = require("pg");
342
+
343
+ // Initial setup with password pw1
344
+ {
345
+ const r = await runCliInit([pg.adminUri, "--password", "pw1", "--skip-optional-permissions"]);
346
+ assert.equal(r.status, 0, r.stderr || r.stdout);
347
+ }
348
+
349
+ // Reset to pw2
350
+ {
351
+ const r = await runCliInit([pg.adminUri, "--reset-password", "--password", "pw2", "--skip-optional-permissions"]);
352
+ assert.equal(r.status, 0, r.stderr || r.stdout);
353
+ assert.match(r.stdout, /password reset/i);
354
+ }
355
+
356
+ // Connect as monitoring user with new password should work
357
+ {
358
+ const c = new Client({
359
+ connectionString: `postgresql://postgres_ai_mon:pw2@127.0.0.1:${pg.port}/testdb`,
360
+ });
361
+ await c.connect();
362
+ const ok = await c.query("select 1 as ok");
363
+ assert.equal(ok.rows[0].ok, 1);
364
+ await c.end();
365
+ }
366
+ });
367
+
368
+
@@ -0,0 +1,154 @@
1
+ const test = require("node:test");
2
+ const assert = require("node:assert/strict");
3
+
4
+ // These tests intentionally import the compiled JS output.
5
+ // Run via: npm --prefix cli test
6
+ const init = require("../dist/lib/init.js");
7
+
8
+ function runCli(args, env = {}) {
9
+ const { spawnSync } = require("node:child_process");
10
+ const path = require("node:path");
11
+ const node = process.execPath;
12
+ const cliPath = path.resolve(__dirname, "..", "dist", "bin", "postgres-ai.js");
13
+ return spawnSync(node, [cliPath, ...args], {
14
+ encoding: "utf8",
15
+ env: { ...process.env, ...env },
16
+ });
17
+ }
18
+
19
+ test("maskConnectionString hides password when present", () => {
20
+ const masked = init.maskConnectionString("postgresql://user:secret@localhost:5432/mydb");
21
+ assert.match(masked, /postgresql:\/\/user:\*{5}@localhost:5432\/mydb/);
22
+ assert.doesNotMatch(masked, /secret/);
23
+ });
24
+
25
+ test("parseLibpqConninfo parses basic host/dbname/user/port/password", () => {
26
+ const cfg = init.parseLibpqConninfo("dbname=mydb host=localhost user=alice port=5432 password=secret");
27
+ assert.equal(cfg.database, "mydb");
28
+ assert.equal(cfg.host, "localhost");
29
+ assert.equal(cfg.user, "alice");
30
+ assert.equal(cfg.port, 5432);
31
+ assert.equal(cfg.password, "secret");
32
+ });
33
+
34
+ test("parseLibpqConninfo supports quoted values", () => {
35
+ const cfg = init.parseLibpqConninfo("dbname='my db' host='local host'");
36
+ assert.equal(cfg.database, "my db");
37
+ assert.equal(cfg.host, "local host");
38
+ });
39
+
40
+ test("buildInitPlan includes create user when role does not exist", async () => {
41
+ const plan = await init.buildInitPlan({
42
+ database: "mydb",
43
+ monitoringUser: "postgres_ai_mon",
44
+ monitoringPassword: "pw",
45
+ includeOptionalPermissions: false,
46
+ roleExists: false,
47
+ });
48
+
49
+ assert.equal(plan.database, "mydb");
50
+ const roleStep = plan.steps.find((s) => s.name === "01.role");
51
+ assert.ok(roleStep);
52
+ assert.match(roleStep.sql, /create\s+user/i);
53
+ assert.ok(!plan.steps.some((s) => s.optional));
54
+ });
55
+
56
+ test("buildInitPlan includes role step when roleExists is omitted", async () => {
57
+ const plan = await init.buildInitPlan({
58
+ database: "mydb",
59
+ monitoringUser: "postgres_ai_mon",
60
+ monitoringPassword: "pw",
61
+ includeOptionalPermissions: false,
62
+ });
63
+ const roleStep = plan.steps.find((s) => s.name === "01.role");
64
+ assert.ok(roleStep);
65
+ assert.match(roleStep.sql, /do\s+\$\$/i);
66
+ });
67
+
68
+ test("buildInitPlan inlines password safely for CREATE/ALTER ROLE grammar", async () => {
69
+ const plan = await init.buildInitPlan({
70
+ database: "mydb",
71
+ monitoringUser: "postgres_ai_mon",
72
+ monitoringPassword: "pa'ss",
73
+ includeOptionalPermissions: false,
74
+ roleExists: false,
75
+ });
76
+ const step = plan.steps.find((s) => s.name === "01.role");
77
+ assert.ok(step);
78
+ assert.match(step.sql, /password 'pa''ss'/);
79
+ assert.equal(step.params, undefined);
80
+ });
81
+
82
+ test("buildInitPlan includes alter user when role exists", async () => {
83
+ const plan = await init.buildInitPlan({
84
+ database: "mydb",
85
+ monitoringUser: "postgres_ai_mon",
86
+ monitoringPassword: "pw",
87
+ includeOptionalPermissions: true,
88
+ roleExists: true,
89
+ });
90
+
91
+ const roleStep = plan.steps.find((s) => s.name === "01.role");
92
+ assert.ok(roleStep);
93
+ assert.match(roleStep.sql, /alter\s+user/i);
94
+ assert.ok(plan.steps.some((s) => s.optional));
95
+ });
96
+
97
+ test("resolveAdminConnection accepts positional URI", () => {
98
+ const r = init.resolveAdminConnection({ conn: "postgresql://u:p@h:5432/d" });
99
+ assert.ok(r.clientConfig.connectionString);
100
+ assert.doesNotMatch(r.display, /:p@/);
101
+ });
102
+
103
+ test("resolveAdminConnection accepts positional conninfo", () => {
104
+ const r = init.resolveAdminConnection({ conn: "dbname=mydb host=localhost user=alice" });
105
+ assert.equal(r.clientConfig.database, "mydb");
106
+ assert.equal(r.clientConfig.host, "localhost");
107
+ assert.equal(r.clientConfig.user, "alice");
108
+ });
109
+
110
+ test("resolveAdminConnection rejects invalid psql-like port", () => {
111
+ assert.throws(
112
+ () => init.resolveAdminConnection({ host: "localhost", port: "abc", username: "u", dbname: "d" }),
113
+ /Invalid port value/
114
+ );
115
+ });
116
+
117
+ test("resolveAdminConnection rejects when only PGPASSWORD is provided (no connection details)", () => {
118
+ assert.throws(() => init.resolveAdminConnection({ envPassword: "pw" }), /Connection is required/);
119
+ });
120
+
121
+ test("resolveAdminConnection error message includes examples", () => {
122
+ assert.throws(() => init.resolveAdminConnection({}), /Examples:/);
123
+ });
124
+
125
+ test("cli: init with missing connection prints init help/options", () => {
126
+ const r = runCli(["init"]);
127
+ assert.notEqual(r.status, 0);
128
+ // We should show options, not just the error message.
129
+ assert.match(r.stderr, /--print-sql/);
130
+ assert.match(r.stderr, /--monitoring-user/);
131
+ });
132
+
133
+ test("print-sql redaction regex matches password literal with embedded quotes", async () => {
134
+ const plan = await init.buildInitPlan({
135
+ database: "mydb",
136
+ monitoringUser: "postgres_ai_mon",
137
+ monitoringPassword: "pa'ss",
138
+ includeOptionalPermissions: false,
139
+ roleExists: false,
140
+ });
141
+ const step = plan.steps.find((s) => s.name === "01.role");
142
+ assert.ok(step);
143
+ const redacted = step.sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
144
+ assert.match(redacted, /password '<redacted>'/i);
145
+ });
146
+
147
+ test("cli: init --print-sql works without connection (offline mode)", () => {
148
+ const r = runCli(["init", "--print-sql", "-d", "mydb", "--password", "monpw"]);
149
+ assert.equal(r.status, 0, r.stderr || r.stdout);
150
+ assert.match(r.stdout, /SQL plan \(offline; not connected\)/);
151
+ assert.match(r.stdout, /grant connect on database "mydb" to "postgres_ai_mon"/i);
152
+ });
153
+
154
+