postgresai 0.14.0-dev.14 → 0.14.0-dev.15

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.
package/lib/init.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import * as readline from "readline";
2
2
  import { randomBytes } from "crypto";
3
3
  import { URL } from "url";
4
+ import type { ConnectionOptions as TlsConnectionOptions } from "tls";
4
5
  import type { Client as PgClient } from "pg";
5
6
  import * as fs from "fs";
6
7
  import * as path from "path";
7
8
 
9
+ export const DEFAULT_MONITORING_USER = "postgres_ai_mon";
10
+
8
11
  export type PgClientConfig = {
9
12
  connectionString?: string;
10
13
  host?: string;
@@ -12,7 +15,7 @@ export type PgClientConfig = {
12
15
  user?: string;
13
16
  password?: string;
14
17
  database?: string;
15
- ssl?: any;
18
+ ssl?: boolean | TlsConnectionOptions;
16
19
  };
17
20
 
18
21
  export type AdminConnection = {
@@ -57,15 +60,26 @@ function applyTemplate(sql: string, vars: Record<string, string>): string {
57
60
 
58
61
  function quoteIdent(ident: string): string {
59
62
  // Always quote. Escape embedded quotes by doubling.
63
+ if (ident.includes("\0")) {
64
+ throw new Error("Identifier cannot contain null bytes");
65
+ }
60
66
  return `"${ident.replace(/"/g, "\"\"")}"`;
61
67
  }
62
68
 
63
69
  function quoteLiteral(value: string): string {
64
70
  // Single-quote and escape embedded quotes by doubling.
65
71
  // This is used where Postgres grammar requires a literal (e.g., CREATE/ALTER ROLE PASSWORD).
72
+ if (value.includes("\0")) {
73
+ throw new Error("Literal cannot contain null bytes");
74
+ }
66
75
  return `'${value.replace(/'/g, "''")}'`;
67
76
  }
68
77
 
78
+ export function redactPasswordsInSql(sql: string): string {
79
+ // Replace PASSWORD '<literal>' (handles doubled quotes inside).
80
+ return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
81
+ }
82
+
69
83
  export function maskConnectionString(dbUrl: string): string {
70
84
  // Hide password if present (postgresql://user:pass@host/db).
71
85
  try {
@@ -307,8 +321,13 @@ export async function promptHidden(prompt: string): Promise<string> {
307
321
  }
308
322
 
309
323
  function generateMonitoringPassword(): string {
310
- // URL-safe and easy to copy/paste; length ~32 chars.
311
- return randomBytes(24).toString("base64url");
324
+ // URL-safe and easy to copy/paste; 24 bytes => 32 base64url chars (no padding).
325
+ // Note: randomBytes() throws on failure; we add a tiny sanity check for unexpected output.
326
+ const password = randomBytes(24).toString("base64url");
327
+ if (password.length < 30) {
328
+ throw new Error("Password generation failed: unexpected output length");
329
+ }
330
+ return password;
312
331
  }
313
332
 
314
333
  export async function resolveMonitoringPassword(opts: {
@@ -332,9 +351,8 @@ export async function buildInitPlan(params: {
332
351
  monitoringUser?: string;
333
352
  monitoringPassword: string;
334
353
  includeOptionalPermissions: boolean;
335
- roleExists?: boolean;
336
354
  }): Promise<InitPlan> {
337
- const monitoringUser = params.monitoringUser || "postgres_ai_mon";
355
+ const monitoringUser = params.monitoringUser || DEFAULT_MONITORING_USER;
338
356
  const database = params.database;
339
357
 
340
358
  const qRole = quoteIdent(monitoringUser);
@@ -350,21 +368,20 @@ export async function buildInitPlan(params: {
350
368
  };
351
369
 
352
370
  // Role creation/update is done in one template file.
353
- // If roleExists is unknown, use a single DO block to create-or-alter safely.
354
- let roleStmt: string | null = null;
355
- if (params.roleExists === false) {
356
- roleStmt = `create user ${qRole} with password ${qPw};`;
357
- } else if (params.roleExists === true) {
358
- roleStmt = `alter user ${qRole} with password ${qPw};`;
359
- } else {
360
- roleStmt = `do $$ begin
371
+ // Always use a single DO block to avoid race conditions between "role exists?" checks and CREATE USER.
372
+ // We:
373
+ // - create role if missing (and handle duplicate_object in case another session created it concurrently),
374
+ // - then ALTER ROLE to ensure the password is set to the desired value.
375
+ const roleStmt = `do $$ begin
361
376
  if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
362
- create user ${qRole} with password ${qPw};
363
- else
364
- alter user ${qRole} with password ${qPw};
377
+ begin
378
+ create user ${qRole} with password ${qPw};
379
+ exception when duplicate_object then
380
+ null;
381
+ end;
365
382
  end if;
383
+ alter user ${qRole} with password ${qPw};
366
384
  end $$;`;
367
- }
368
385
 
369
386
  const roleSql = applyTemplate(loadSqlTemplate("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
370
387
  steps.push({ name: "01.role", sql: roleSql });
@@ -411,9 +428,31 @@ export async function applyInitPlan(params: {
411
428
  const msg = e instanceof Error ? e.message : String(e);
412
429
  const errAny = e as any;
413
430
  const wrapped: any = new Error(`Failed at step "${step.name}": ${msg}`);
414
- // Preserve Postgres error code so callers can provide better hints (e.g., 42501 insufficient_privilege).
415
- if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
416
- wrapped.code = errAny.code;
431
+ // Preserve useful Postgres error fields so callers can provide better hints / diagnostics.
432
+ const pgErrorFields = [
433
+ "code",
434
+ "detail",
435
+ "hint",
436
+ "position",
437
+ "internalPosition",
438
+ "internalQuery",
439
+ "where",
440
+ "schema",
441
+ "table",
442
+ "column",
443
+ "dataType",
444
+ "constraint",
445
+ "file",
446
+ "line",
447
+ "routine",
448
+ ] as const;
449
+ if (errAny && typeof errAny === "object") {
450
+ for (const field of pgErrorFields) {
451
+ if (errAny[field] !== undefined) wrapped[field] = errAny[field];
452
+ }
453
+ }
454
+ if (e instanceof Error && e.stack) {
455
+ wrapped.stack = e.stack;
417
456
  }
418
457
  throw wrapped;
419
458
  }
@@ -432,11 +471,24 @@ export async function applyInitPlan(params: {
432
471
  // Apply optional steps outside of the transaction so a failure doesn't abort everything.
433
472
  for (const step of params.plan.steps.filter((s) => s.optional)) {
434
473
  try {
435
- await params.client.query(step.sql, step.params as any);
436
- applied.push(step.name);
474
+ // Run each optional step in its own mini-transaction to avoid partial application.
475
+ await params.client.query("begin;");
476
+ try {
477
+ await params.client.query(step.sql, step.params as any);
478
+ await params.client.query("commit;");
479
+ applied.push(step.name);
480
+ } catch {
481
+ try {
482
+ await params.client.query("rollback;");
483
+ } catch {
484
+ // ignore rollback errors
485
+ }
486
+ skippedOptional.push(step.name);
487
+ // best-effort: ignore
488
+ }
437
489
  } catch {
490
+ // If we can't even begin/commit, treat as skipped.
438
491
  skippedOptional.push(step.name);
439
- // best-effort: ignore
440
492
  }
441
493
  }
442
494
 
@@ -455,111 +507,122 @@ export async function verifyInitSetup(params: {
455
507
  monitoringUser: string;
456
508
  includeOptionalPermissions: boolean;
457
509
  }): Promise<VerifyInitResult> {
458
- const missingRequired: string[] = [];
459
- const missingOptional: string[] = [];
460
-
461
- const role = params.monitoringUser;
462
- const db = params.database;
463
-
464
- const roleRes = await params.client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [role]);
465
- const roleExists = (roleRes.rowCount ?? 0) > 0;
466
- if (!roleExists) {
467
- missingRequired.push(`role "${role}" does not exist`);
468
- // If role is missing, other checks will error or be meaningless.
469
- return { ok: false, missingRequired, missingOptional };
470
- }
471
-
472
- const connectRes = await params.client.query(
473
- "select has_database_privilege($1, $2, 'CONNECT') as ok",
474
- [role, db]
475
- );
476
- if (!connectRes.rows?.[0]?.ok) {
477
- missingRequired.push(`CONNECT on database "${db}"`);
478
- }
510
+ // Use a repeatable-read snapshot so all checks see a consistent view.
511
+ await params.client.query("begin isolation level repeatable read;");
512
+ try {
513
+ const missingRequired: string[] = [];
514
+ const missingOptional: string[] = [];
515
+
516
+ const role = params.monitoringUser;
517
+ const db = params.database;
518
+
519
+ const roleRes = await params.client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [role]);
520
+ const roleExists = (roleRes.rowCount ?? 0) > 0;
521
+ if (!roleExists) {
522
+ missingRequired.push(`role "${role}" does not exist`);
523
+ // If role is missing, other checks will error or be meaningless.
524
+ return { ok: false, missingRequired, missingOptional };
525
+ }
479
526
 
480
- const pgMonitorRes = await params.client.query(
481
- "select pg_has_role($1, 'pg_monitor', 'member') as ok",
482
- [role]
483
- );
484
- if (!pgMonitorRes.rows?.[0]?.ok) {
485
- missingRequired.push("membership in role pg_monitor");
486
- }
527
+ const connectRes = await params.client.query(
528
+ "select has_database_privilege($1, $2, 'CONNECT') as ok",
529
+ [role, db]
530
+ );
531
+ if (!connectRes.rows?.[0]?.ok) {
532
+ missingRequired.push(`CONNECT on database "${db}"`);
533
+ }
487
534
 
488
- const pgIndexRes = await params.client.query(
489
- "select has_table_privilege($1, 'pg_catalog.pg_index', 'SELECT') as ok",
490
- [role]
491
- );
492
- if (!pgIndexRes.rows?.[0]?.ok) {
493
- missingRequired.push("SELECT on pg_catalog.pg_index");
494
- }
535
+ const pgMonitorRes = await params.client.query(
536
+ "select pg_has_role($1, 'pg_monitor', 'member') as ok",
537
+ [role]
538
+ );
539
+ if (!pgMonitorRes.rows?.[0]?.ok) {
540
+ missingRequired.push("membership in role pg_monitor");
541
+ }
495
542
 
496
- const viewExistsRes = await params.client.query("select to_regclass('public.pg_statistic') is not null as ok");
497
- if (!viewExistsRes.rows?.[0]?.ok) {
498
- missingRequired.push("view public.pg_statistic exists");
499
- } else {
500
- const viewPrivRes = await params.client.query(
501
- "select has_table_privilege($1, 'public.pg_statistic', 'SELECT') as ok",
543
+ const pgIndexRes = await params.client.query(
544
+ "select has_table_privilege($1, 'pg_catalog.pg_index', 'SELECT') as ok",
502
545
  [role]
503
546
  );
504
- if (!viewPrivRes.rows?.[0]?.ok) {
505
- missingRequired.push("SELECT on view public.pg_statistic");
547
+ if (!pgIndexRes.rows?.[0]?.ok) {
548
+ missingRequired.push("SELECT on pg_catalog.pg_index");
506
549
  }
507
- }
508
550
 
509
- const schemaUsageRes = await params.client.query(
510
- "select has_schema_privilege($1, 'public', 'USAGE') as ok",
511
- [role]
512
- );
513
- if (!schemaUsageRes.rows?.[0]?.ok) {
514
- missingRequired.push("USAGE on schema public");
515
- }
551
+ const viewExistsRes = await params.client.query("select to_regclass('public.pg_statistic') is not null as ok");
552
+ if (!viewExistsRes.rows?.[0]?.ok) {
553
+ missingRequired.push("view public.pg_statistic exists");
554
+ } else {
555
+ const viewPrivRes = await params.client.query(
556
+ "select has_table_privilege($1, 'public.pg_statistic', 'SELECT') as ok",
557
+ [role]
558
+ );
559
+ if (!viewPrivRes.rows?.[0]?.ok) {
560
+ missingRequired.push("SELECT on view public.pg_statistic");
561
+ }
562
+ }
516
563
 
517
- const rolcfgRes = await params.client.query("select rolconfig from pg_catalog.pg_roles where rolname = $1", [role]);
518
- const rolconfig = rolcfgRes.rows?.[0]?.rolconfig;
519
- const spLine = Array.isArray(rolconfig) ? rolconfig.find((v: any) => String(v).startsWith("search_path=")) : undefined;
520
- if (typeof spLine !== "string" || !spLine) {
521
- missingRequired.push("role search_path is set");
522
- } else {
523
- // We accept any ordering as long as public and pg_catalog are included.
524
- const sp = spLine.toLowerCase();
525
- if (!sp.includes("public") || !sp.includes("pg_catalog")) {
526
- missingRequired.push("role search_path includes public and pg_catalog");
564
+ const schemaUsageRes = await params.client.query(
565
+ "select has_schema_privilege($1, 'public', 'USAGE') as ok",
566
+ [role]
567
+ );
568
+ if (!schemaUsageRes.rows?.[0]?.ok) {
569
+ missingRequired.push("USAGE on schema public");
527
570
  }
528
- }
529
571
 
530
- if (params.includeOptionalPermissions) {
531
- // Optional RDS/Aurora extras
532
- {
533
- const extRes = await params.client.query("select 1 from pg_extension where extname = 'rds_tools'");
534
- if ((extRes.rowCount ?? 0) === 0) {
535
- missingOptional.push("extension rds_tools");
536
- } else {
537
- const fnRes = await params.client.query(
538
- "select has_function_privilege($1, 'rds_tools.pg_ls_multixactdir()', 'EXECUTE') as ok",
539
- [role]
540
- );
572
+ const rolcfgRes = await params.client.query("select rolconfig from pg_catalog.pg_roles where rolname = $1", [role]);
573
+ const rolconfig = rolcfgRes.rows?.[0]?.rolconfig;
574
+ const spLine = Array.isArray(rolconfig) ? rolconfig.find((v: any) => String(v).startsWith("search_path=")) : undefined;
575
+ if (typeof spLine !== "string" || !spLine) {
576
+ missingRequired.push("role search_path is set");
577
+ } else {
578
+ // We accept any ordering as long as public and pg_catalog are included.
579
+ const sp = spLine.toLowerCase();
580
+ if (!sp.includes("public") || !sp.includes("pg_catalog")) {
581
+ missingRequired.push("role search_path includes public and pg_catalog");
582
+ }
583
+ }
584
+
585
+ if (params.includeOptionalPermissions) {
586
+ // Optional RDS/Aurora extras
587
+ {
588
+ const extRes = await params.client.query("select 1 from pg_extension where extname = 'rds_tools'");
589
+ if ((extRes.rowCount ?? 0) === 0) {
590
+ missingOptional.push("extension rds_tools");
591
+ } else {
592
+ const fnRes = await params.client.query(
593
+ "select has_function_privilege($1, 'rds_tools.pg_ls_multixactdir()', 'EXECUTE') as ok",
594
+ [role]
595
+ );
596
+ if (!fnRes.rows?.[0]?.ok) {
597
+ missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
598
+ }
599
+ }
600
+ }
601
+
602
+ // Optional self-managed extras
603
+ const optionalFns = [
604
+ "pg_catalog.pg_stat_file(text)",
605
+ "pg_catalog.pg_stat_file(text, boolean)",
606
+ "pg_catalog.pg_ls_dir(text)",
607
+ "pg_catalog.pg_ls_dir(text, boolean, boolean)",
608
+ ];
609
+ for (const fn of optionalFns) {
610
+ const fnRes = await params.client.query("select has_function_privilege($1, $2, 'EXECUTE') as ok", [role, fn]);
541
611
  if (!fnRes.rows?.[0]?.ok) {
542
- missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
612
+ missingOptional.push(`EXECUTE on ${fn}`);
543
613
  }
544
614
  }
545
615
  }
546
616
 
547
- // Optional self-managed extras
548
- const optionalFns = [
549
- "pg_catalog.pg_stat_file(text)",
550
- "pg_catalog.pg_stat_file(text, boolean)",
551
- "pg_catalog.pg_ls_dir(text)",
552
- "pg_catalog.pg_ls_dir(text, boolean, boolean)",
553
- ];
554
- for (const fn of optionalFns) {
555
- const fnRes = await params.client.query("select has_function_privilege($1, $2, 'EXECUTE') as ok", [role, fn]);
556
- if (!fnRes.rows?.[0]?.ok) {
557
- missingOptional.push(`EXECUTE on ${fn}`);
558
- }
617
+ return { ok: missingRequired.length === 0, missingRequired, missingOptional };
618
+ } finally {
619
+ // Read-only: rollback to release snapshot; do not mask original errors.
620
+ try {
621
+ await params.client.query("rollback;");
622
+ } catch {
623
+ // ignore
559
624
  }
560
625
  }
561
-
562
- return { ok: missingRequired.length === 0, missingRequired, missingOptional };
563
626
  }
564
627
 
565
628
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.14.0-dev.14",
3
+ "version": "0.14.0-dev.15",
4
4
  "description": "postgres_ai CLI (Node.js)",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
@@ -92,25 +92,41 @@ async function withTempPostgres(t) {
92
92
 
93
93
  const port = await getFreePort();
94
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");
95
+ let postgresProc;
96
+ try {
97
+ postgresProc = spawn(
98
+ postgresBin,
99
+ ["-D", dataDir, "-k", socketDir, "-h", "127.0.0.1", "-p", String(port)],
100
+ {
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ }
103
+ );
104
+
105
+ // Register cleanup immediately so failures below don't leave a running postgres and hang CI.
106
+ t.after(async () => {
107
+ postgresProc.kill("SIGTERM");
108
+ try {
109
+ await waitFor(
110
+ async () => {
111
+ if (postgresProc.exitCode === null) throw new Error("still running");
112
+ },
113
+ { timeoutMs: 5000, intervalMs: 100 }
114
+ );
115
+ } catch {
116
+ postgresProc.kill("SIGKILL");
117
+ }
118
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
119
+ });
120
+ } catch (e) {
121
+ // If anything goes wrong before cleanup is registered, ensure we don't leak a running postgres.
102
122
  try {
103
- await waitFor(
104
- async () => {
105
- if (postgresProc.exitCode === null) throw new Error("still running");
106
- },
107
- { timeoutMs: 5000, intervalMs: 100 }
108
- );
123
+ if (postgresProc) postgresProc.kill("SIGKILL");
109
124
  } catch {
110
- postgresProc.kill("SIGKILL");
125
+ // ignore
111
126
  }
112
127
  fs.rmSync(tmpRoot, { recursive: true, force: true });
113
- });
128
+ throw e;
129
+ }
114
130
 
115
131
  const { Client } = require("pg");
116
132
 
@@ -208,8 +224,8 @@ test(
208
224
  {
209
225
  const r = await runCliInit([pg.adminUri, "--print-password", "--skip-optional-permissions"]);
210
226
  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=/);
227
+ assert.match(r.stderr, /Generated monitoring password for postgres_ai_mon/i);
228
+ assert.match(r.stderr, /PGAI_MON_PASSWORD='/);
213
229
  }
214
230
  }
215
231
  );
@@ -294,12 +310,10 @@ test("integration: init reports nicely when lacking permissions", { skip: !haveP
294
310
  const limitedUri = `postgresql://limited:${limitedPw}@127.0.0.1:${pg.port}/testdb`;
295
311
  const r = await runCliInit([limitedUri, "--password", "monpw", "--skip-optional-permissions"]);
296
312
  assert.notEqual(r.status, 0);
297
- assert.match(r.stderr, /init failed:/);
313
+ assert.match(r.stderr, /Error: init failed:/);
298
314
  // Should include step context and hint.
299
315
  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);
316
+ assert.match(r.stderr, /Fix: connect as a superuser/i);
303
317
  });
304
318
 
305
319
  test("integration: init --verify returns 0 when ok and non-zero when missing", { skip: !havePostgresBinaries() }, async (t) => {