postgresai 0.14.0-beta.1 → 0.14.0-beta.2

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,9 @@ 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
+ // NOTE: kept async for API stability / potential future async template loading.
356
+ const monitoringUser = params.monitoringUser || DEFAULT_MONITORING_USER;
338
357
  const database = params.database;
339
358
 
340
359
  const qRole = quoteIdent(monitoringUser);
@@ -344,27 +363,26 @@ export async function buildInitPlan(params: {
344
363
 
345
364
  const steps: InitStep[] = [];
346
365
 
347
- const vars = {
366
+ const vars: Record<string, string> = {
348
367
  ROLE_IDENT: qRole,
349
368
  DB_IDENT: qDb,
350
369
  };
351
370
 
352
371
  // 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
372
+ // Always use a single DO block to avoid race conditions between "role exists?" checks and CREATE USER.
373
+ // We:
374
+ // - create role if missing (and handle duplicate_object in case another session created it concurrently),
375
+ // - then ALTER ROLE to ensure the password is set to the desired value.
376
+ const roleStmt = `do $$ begin
361
377
  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};
378
+ begin
379
+ create user ${qRole} with password ${qPw};
380
+ exception when duplicate_object then
381
+ null;
382
+ end;
365
383
  end if;
384
+ alter user ${qRole} with password ${qPw};
366
385
  end $$;`;
367
- }
368
386
 
369
387
  const roleSql = applyTemplate(loadSqlTemplate("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
370
388
  steps.push({ name: "01.role", sql: roleSql });
@@ -411,9 +429,31 @@ export async function applyInitPlan(params: {
411
429
  const msg = e instanceof Error ? e.message : String(e);
412
430
  const errAny = e as any;
413
431
  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;
432
+ // Preserve useful Postgres error fields so callers can provide better hints / diagnostics.
433
+ const pgErrorFields = [
434
+ "code",
435
+ "detail",
436
+ "hint",
437
+ "position",
438
+ "internalPosition",
439
+ "internalQuery",
440
+ "where",
441
+ "schema",
442
+ "table",
443
+ "column",
444
+ "dataType",
445
+ "constraint",
446
+ "file",
447
+ "line",
448
+ "routine",
449
+ ] as const;
450
+ if (errAny && typeof errAny === "object") {
451
+ for (const field of pgErrorFields) {
452
+ if (errAny[field] !== undefined) wrapped[field] = errAny[field];
453
+ }
454
+ }
455
+ if (e instanceof Error && e.stack) {
456
+ wrapped.stack = e.stack;
417
457
  }
418
458
  throw wrapped;
419
459
  }
@@ -432,11 +472,24 @@ export async function applyInitPlan(params: {
432
472
  // Apply optional steps outside of the transaction so a failure doesn't abort everything.
433
473
  for (const step of params.plan.steps.filter((s) => s.optional)) {
434
474
  try {
435
- await params.client.query(step.sql, step.params as any);
436
- applied.push(step.name);
475
+ // Run each optional step in its own mini-transaction to avoid partial application.
476
+ await params.client.query("begin;");
477
+ try {
478
+ await params.client.query(step.sql, step.params as any);
479
+ await params.client.query("commit;");
480
+ applied.push(step.name);
481
+ } catch {
482
+ try {
483
+ await params.client.query("rollback;");
484
+ } catch {
485
+ // ignore rollback errors
486
+ }
487
+ skippedOptional.push(step.name);
488
+ // best-effort: ignore
489
+ }
437
490
  } catch {
491
+ // If we can't even begin/commit, treat as skipped.
438
492
  skippedOptional.push(step.name);
439
- // best-effort: ignore
440
493
  }
441
494
  }
442
495
 
@@ -455,111 +508,122 @@ export async function verifyInitSetup(params: {
455
508
  monitoringUser: string;
456
509
  includeOptionalPermissions: boolean;
457
510
  }): 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
- }
511
+ // Use a repeatable-read snapshot so all checks see a consistent view.
512
+ await params.client.query("begin isolation level repeatable read;");
513
+ try {
514
+ const missingRequired: string[] = [];
515
+ const missingOptional: string[] = [];
516
+
517
+ const role = params.monitoringUser;
518
+ const db = params.database;
519
+
520
+ const roleRes = await params.client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [role]);
521
+ const roleExists = (roleRes.rowCount ?? 0) > 0;
522
+ if (!roleExists) {
523
+ missingRequired.push(`role "${role}" does not exist`);
524
+ // If role is missing, other checks will error or be meaningless.
525
+ return { ok: false, missingRequired, missingOptional };
526
+ }
479
527
 
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
- }
528
+ const connectRes = await params.client.query(
529
+ "select has_database_privilege($1, $2, 'CONNECT') as ok",
530
+ [role, db]
531
+ );
532
+ if (!connectRes.rows?.[0]?.ok) {
533
+ missingRequired.push(`CONNECT on database "${db}"`);
534
+ }
487
535
 
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
- }
536
+ const pgMonitorRes = await params.client.query(
537
+ "select pg_has_role($1, 'pg_monitor', 'member') as ok",
538
+ [role]
539
+ );
540
+ if (!pgMonitorRes.rows?.[0]?.ok) {
541
+ missingRequired.push("membership in role pg_monitor");
542
+ }
495
543
 
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",
544
+ const pgIndexRes = await params.client.query(
545
+ "select has_table_privilege($1, 'pg_catalog.pg_index', 'SELECT') as ok",
502
546
  [role]
503
547
  );
504
- if (!viewPrivRes.rows?.[0]?.ok) {
505
- missingRequired.push("SELECT on view public.pg_statistic");
548
+ if (!pgIndexRes.rows?.[0]?.ok) {
549
+ missingRequired.push("SELECT on pg_catalog.pg_index");
506
550
  }
507
- }
508
551
 
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
- }
552
+ const viewExistsRes = await params.client.query("select to_regclass('public.pg_statistic') is not null as ok");
553
+ if (!viewExistsRes.rows?.[0]?.ok) {
554
+ missingRequired.push("view public.pg_statistic exists");
555
+ } else {
556
+ const viewPrivRes = await params.client.query(
557
+ "select has_table_privilege($1, 'public.pg_statistic', 'SELECT') as ok",
558
+ [role]
559
+ );
560
+ if (!viewPrivRes.rows?.[0]?.ok) {
561
+ missingRequired.push("SELECT on view public.pg_statistic");
562
+ }
563
+ }
516
564
 
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");
565
+ const schemaUsageRes = await params.client.query(
566
+ "select has_schema_privilege($1, 'public', 'USAGE') as ok",
567
+ [role]
568
+ );
569
+ if (!schemaUsageRes.rows?.[0]?.ok) {
570
+ missingRequired.push("USAGE on schema public");
527
571
  }
528
- }
529
572
 
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
- );
573
+ const rolcfgRes = await params.client.query("select rolconfig from pg_catalog.pg_roles where rolname = $1", [role]);
574
+ const rolconfig = rolcfgRes.rows?.[0]?.rolconfig;
575
+ const spLine = Array.isArray(rolconfig) ? rolconfig.find((v: any) => String(v).startsWith("search_path=")) : undefined;
576
+ if (typeof spLine !== "string" || !spLine) {
577
+ missingRequired.push("role search_path is set");
578
+ } else {
579
+ // We accept any ordering as long as public and pg_catalog are included.
580
+ const sp = spLine.toLowerCase();
581
+ if (!sp.includes("public") || !sp.includes("pg_catalog")) {
582
+ missingRequired.push("role search_path includes public and pg_catalog");
583
+ }
584
+ }
585
+
586
+ if (params.includeOptionalPermissions) {
587
+ // Optional RDS/Aurora extras
588
+ {
589
+ const extRes = await params.client.query("select 1 from pg_extension where extname = 'rds_tools'");
590
+ if ((extRes.rowCount ?? 0) === 0) {
591
+ missingOptional.push("extension rds_tools");
592
+ } else {
593
+ const fnRes = await params.client.query(
594
+ "select has_function_privilege($1, 'rds_tools.pg_ls_multixactdir()', 'EXECUTE') as ok",
595
+ [role]
596
+ );
597
+ if (!fnRes.rows?.[0]?.ok) {
598
+ missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
599
+ }
600
+ }
601
+ }
602
+
603
+ // Optional self-managed extras
604
+ const optionalFns = [
605
+ "pg_catalog.pg_stat_file(text)",
606
+ "pg_catalog.pg_stat_file(text, boolean)",
607
+ "pg_catalog.pg_ls_dir(text)",
608
+ "pg_catalog.pg_ls_dir(text, boolean, boolean)",
609
+ ];
610
+ for (const fn of optionalFns) {
611
+ const fnRes = await params.client.query("select has_function_privilege($1, $2, 'EXECUTE') as ok", [role, fn]);
541
612
  if (!fnRes.rows?.[0]?.ok) {
542
- missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
613
+ missingOptional.push(`EXECUTE on ${fn}`);
543
614
  }
544
615
  }
545
616
  }
546
617
 
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
- }
618
+ return { ok: missingRequired.length === 0, missingRequired, missingOptional };
619
+ } finally {
620
+ // Read-only: rollback to release snapshot; do not mask original errors.
621
+ try {
622
+ await params.client.query("rollback;");
623
+ } catch {
624
+ // ignore
559
625
  }
560
626
  }
561
-
562
- return { ok: missingRequired.length === 0, missingRequired, missingOptional };
563
627
  }
564
628
 
565
629
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postgresai",
3
- "version": "0.14.0-beta.1",
3
+ "version": "0.14.0-beta.2",
4
4
  "description": "postgres_ai CLI (Node.js)",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
package/sql/01.role.sql CHANGED
@@ -1,14 +1,15 @@
1
1
  -- Role creation / password update (template-filled by cli/lib/init.ts)
2
2
  --
3
- -- Example expansions (for readability/review):
4
- -- create user "postgres_ai_mon" with password '...';
5
- -- alter user "postgres_ai_mon" with password '...';
3
+ -- Always uses a race-safe pattern (create if missing, then always alter to set the password):
6
4
  -- do $$ begin
7
- -- if not exists (select 1 from pg_catalog.pg_roles where rolname = 'postgres_ai_mon') then
8
- -- create user "postgres_ai_mon" with password '...';
9
- -- else
10
- -- alter user "postgres_ai_mon" with password '...';
5
+ -- if not exists (select 1 from pg_catalog.pg_roles where rolname = '...') then
6
+ -- begin
7
+ -- create user "..." with password '...';
8
+ -- exception when duplicate_object then
9
+ -- null;
10
+ -- end;
11
11
  -- end if;
12
+ -- alter user "..." with password '...';
12
13
  -- end $$;
13
14
  {{ROLE_STMT}}
14
15
 
@@ -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:/);
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) => {