postgresai 0.12.0-beta.6 → 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.
package/lib/init.ts ADDED
@@ -0,0 +1,565 @@
1
+ import * as readline from "readline";
2
+ import { randomBytes } from "crypto";
3
+ import { URL } from "url";
4
+ import type { Client as PgClient } from "pg";
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+
8
+ export type PgClientConfig = {
9
+ connectionString?: string;
10
+ host?: string;
11
+ port?: number;
12
+ user?: string;
13
+ password?: string;
14
+ database?: string;
15
+ ssl?: any;
16
+ };
17
+
18
+ export type AdminConnection = {
19
+ clientConfig: PgClientConfig;
20
+ display: string;
21
+ };
22
+
23
+ export type InitStep = {
24
+ name: string;
25
+ sql: string;
26
+ params?: unknown[];
27
+ optional?: boolean;
28
+ };
29
+
30
+ export type InitPlan = {
31
+ monitoringUser: string;
32
+ database: string;
33
+ steps: InitStep[];
34
+ };
35
+
36
+ function packageRootDirFromCompiled(): string {
37
+ // dist/lib/init.js -> <pkg>/dist/lib ; package root is ../..
38
+ return path.resolve(__dirname, "..", "..");
39
+ }
40
+
41
+ function sqlDir(): string {
42
+ return path.join(packageRootDirFromCompiled(), "sql");
43
+ }
44
+
45
+ function loadSqlTemplate(filename: string): string {
46
+ const p = path.join(sqlDir(), filename);
47
+ return fs.readFileSync(p, "utf8");
48
+ }
49
+
50
+ function applyTemplate(sql: string, vars: Record<string, string>): string {
51
+ return sql.replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => {
52
+ const v = vars[key];
53
+ if (v === undefined) throw new Error(`Missing SQL template var: ${key}`);
54
+ return v;
55
+ });
56
+ }
57
+
58
+ function quoteIdent(ident: string): string {
59
+ // Always quote. Escape embedded quotes by doubling.
60
+ return `"${ident.replace(/"/g, "\"\"")}"`;
61
+ }
62
+
63
+ function quoteLiteral(value: string): string {
64
+ // Single-quote and escape embedded quotes by doubling.
65
+ // This is used where Postgres grammar requires a literal (e.g., CREATE/ALTER ROLE PASSWORD).
66
+ return `'${value.replace(/'/g, "''")}'`;
67
+ }
68
+
69
+ export function maskConnectionString(dbUrl: string): string {
70
+ // Hide password if present (postgresql://user:pass@host/db).
71
+ try {
72
+ const u = new URL(dbUrl);
73
+ if (u.password) u.password = "*****";
74
+ return u.toString();
75
+ } catch {
76
+ return dbUrl.replace(/\/\/([^:/?#]+):([^@/?#]+)@/g, "//$1:*****@");
77
+ }
78
+ }
79
+
80
+ function isLikelyUri(value: string): boolean {
81
+ return /^postgres(ql)?:\/\//i.test(value.trim());
82
+ }
83
+
84
+ function tokenizeConninfo(input: string): string[] {
85
+ const s = input.trim();
86
+ const tokens: string[] = [];
87
+ let i = 0;
88
+
89
+ const isSpace = (ch: string) => ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
90
+
91
+ while (i < s.length) {
92
+ while (i < s.length && isSpace(s[i]!)) i++;
93
+ if (i >= s.length) break;
94
+
95
+ let tok = "";
96
+ let inSingle = false;
97
+ while (i < s.length) {
98
+ const ch = s[i]!;
99
+ if (!inSingle && isSpace(ch)) break;
100
+
101
+ if (ch === "'" && !inSingle) {
102
+ inSingle = true;
103
+ i++;
104
+ continue;
105
+ }
106
+ if (ch === "'" && inSingle) {
107
+ inSingle = false;
108
+ i++;
109
+ continue;
110
+ }
111
+
112
+ if (ch === "\\" && i + 1 < s.length) {
113
+ tok += s[i + 1]!;
114
+ i += 2;
115
+ continue;
116
+ }
117
+
118
+ tok += ch;
119
+ i++;
120
+ }
121
+
122
+ tokens.push(tok);
123
+ while (i < s.length && isSpace(s[i]!)) i++;
124
+ }
125
+
126
+ return tokens;
127
+ }
128
+
129
+ export function parseLibpqConninfo(input: string): PgClientConfig {
130
+ const tokens = tokenizeConninfo(input);
131
+ const cfg: PgClientConfig = {};
132
+
133
+ for (const t of tokens) {
134
+ const eq = t.indexOf("=");
135
+ if (eq <= 0) continue;
136
+ const key = t.slice(0, eq).trim();
137
+ const rawVal = t.slice(eq + 1);
138
+ const val = rawVal.trim();
139
+ if (!key) continue;
140
+
141
+ switch (key) {
142
+ case "host":
143
+ cfg.host = val;
144
+ break;
145
+ case "port": {
146
+ const p = Number(val);
147
+ if (Number.isFinite(p)) cfg.port = p;
148
+ break;
149
+ }
150
+ case "user":
151
+ cfg.user = val;
152
+ break;
153
+ case "password":
154
+ cfg.password = val;
155
+ break;
156
+ case "dbname":
157
+ case "database":
158
+ cfg.database = val;
159
+ break;
160
+ // ignore everything else (sslmode, options, application_name, etc.)
161
+ default:
162
+ break;
163
+ }
164
+ }
165
+
166
+ return cfg;
167
+ }
168
+
169
+ export function describePgConfig(cfg: PgClientConfig): string {
170
+ if (cfg.connectionString) return maskConnectionString(cfg.connectionString);
171
+ const user = cfg.user ? cfg.user : "<user>";
172
+ const host = cfg.host ? cfg.host : "<host>";
173
+ const port = cfg.port ? String(cfg.port) : "<port>";
174
+ const db = cfg.database ? cfg.database : "<db>";
175
+ // Don't include password
176
+ return `postgresql://${user}:*****@${host}:${port}/${db}`;
177
+ }
178
+
179
+ export function resolveAdminConnection(opts: {
180
+ conn?: string;
181
+ dbUrlFlag?: string;
182
+ host?: string;
183
+ port?: string | number;
184
+ username?: string;
185
+ dbname?: string;
186
+ adminPassword?: string;
187
+ envPassword?: string;
188
+ }): AdminConnection {
189
+ const conn = (opts.conn || "").trim();
190
+ const dbUrlFlag = (opts.dbUrlFlag || "").trim();
191
+
192
+ // NOTE: passwords alone (PGPASSWORD / --admin-password) do NOT constitute a connection.
193
+ // We require at least some connection addressing (host/port/user/db) if no positional arg / --db-url is provided.
194
+ const hasConnDetails = !!(opts.host || opts.port || opts.username || opts.dbname);
195
+
196
+ if (conn && dbUrlFlag) {
197
+ throw new Error("Provide either positional connection string or --db-url, not both");
198
+ }
199
+
200
+ if (conn || dbUrlFlag) {
201
+ const v = conn || dbUrlFlag;
202
+ if (isLikelyUri(v)) {
203
+ return { clientConfig: { connectionString: v }, display: maskConnectionString(v) };
204
+ }
205
+ // libpq conninfo (dbname=... host=...)
206
+ const cfg = parseLibpqConninfo(v);
207
+ if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
208
+ return { clientConfig: cfg, display: describePgConfig(cfg) };
209
+ }
210
+
211
+ if (!hasConnDetails) {
212
+ throw new Error(
213
+ [
214
+ "Connection is required.",
215
+ "",
216
+ "Examples:",
217
+ " postgresai init postgresql://admin@host:5432/dbname",
218
+ " postgresai init \"dbname=dbname host=host user=admin\"",
219
+ " postgresai init -h host -p 5432 -U admin -d dbname",
220
+ "",
221
+ "Admin password:",
222
+ " --admin-password <password> (or set PGPASSWORD)",
223
+ ].join("\n")
224
+ );
225
+ }
226
+
227
+ const cfg: PgClientConfig = {};
228
+ if (opts.host) cfg.host = opts.host;
229
+ if (opts.port !== undefined && opts.port !== "") {
230
+ const p = Number(opts.port);
231
+ if (!Number.isFinite(p) || !Number.isInteger(p) || p <= 0 || p > 65535) {
232
+ throw new Error(`Invalid port value: ${String(opts.port)}`);
233
+ }
234
+ cfg.port = p;
235
+ }
236
+ if (opts.username) cfg.user = opts.username;
237
+ if (opts.dbname) cfg.database = opts.dbname;
238
+ if (opts.adminPassword) cfg.password = opts.adminPassword;
239
+ if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
240
+ return { clientConfig: cfg, display: describePgConfig(cfg) };
241
+ }
242
+
243
+ export async function promptHidden(prompt: string): Promise<string> {
244
+ // Implement our own hidden input reader so:
245
+ // - prompt text is visible
246
+ // - only user input is masked
247
+ // - we don't rely on non-public readline internals
248
+ if (!process.stdin.isTTY) {
249
+ throw new Error("Cannot prompt for password in non-interactive mode");
250
+ }
251
+
252
+ const stdin = process.stdin;
253
+ const stdout = process.stdout as NodeJS.WriteStream;
254
+
255
+ stdout.write(prompt);
256
+
257
+ return await new Promise<string>((resolve, reject) => {
258
+ let value = "";
259
+
260
+ const cleanup = () => {
261
+ try {
262
+ stdin.setRawMode(false);
263
+ } catch {
264
+ // ignore
265
+ }
266
+ stdin.removeListener("keypress", onKeypress);
267
+ };
268
+
269
+ const onKeypress = (str: string, key: any) => {
270
+ if (key?.ctrl && key?.name === "c") {
271
+ stdout.write("\n");
272
+ cleanup();
273
+ reject(new Error("Cancelled"));
274
+ return;
275
+ }
276
+
277
+ if (key?.name === "return" || key?.name === "enter") {
278
+ stdout.write("\n");
279
+ cleanup();
280
+ resolve(value);
281
+ return;
282
+ }
283
+
284
+ if (key?.name === "backspace") {
285
+ if (value.length > 0) {
286
+ value = value.slice(0, -1);
287
+ // Erase one mask char.
288
+ stdout.write("\b \b");
289
+ }
290
+ return;
291
+ }
292
+
293
+ // Ignore other control keys.
294
+ if (key?.ctrl || key?.meta) return;
295
+
296
+ if (typeof str === "string" && str.length > 0) {
297
+ value += str;
298
+ stdout.write("*");
299
+ }
300
+ };
301
+
302
+ readline.emitKeypressEvents(stdin);
303
+ stdin.setRawMode(true);
304
+ stdin.on("keypress", onKeypress);
305
+ stdin.resume();
306
+ });
307
+ }
308
+
309
+ function generateMonitoringPassword(): string {
310
+ // URL-safe and easy to copy/paste; length ~32 chars.
311
+ return randomBytes(24).toString("base64url");
312
+ }
313
+
314
+ export async function resolveMonitoringPassword(opts: {
315
+ passwordFlag?: string;
316
+ passwordEnv?: string;
317
+ prompt?: (prompt: string) => Promise<string>;
318
+ monitoringUser: string;
319
+ }): Promise<{ password: string; generated: boolean }> {
320
+ const fromFlag = (opts.passwordFlag || "").trim();
321
+ if (fromFlag) return { password: fromFlag, generated: false };
322
+
323
+ const fromEnv = (opts.passwordEnv || "").trim();
324
+ if (fromEnv) return { password: fromEnv, generated: false };
325
+
326
+ // Default: auto-generate (safer than prompting; works in non-interactive mode).
327
+ return { password: generateMonitoringPassword(), generated: true };
328
+ }
329
+
330
+ export async function buildInitPlan(params: {
331
+ database: string;
332
+ monitoringUser?: string;
333
+ monitoringPassword: string;
334
+ includeOptionalPermissions: boolean;
335
+ roleExists?: boolean;
336
+ }): Promise<InitPlan> {
337
+ const monitoringUser = params.monitoringUser || "postgres_ai_mon";
338
+ const database = params.database;
339
+
340
+ const qRole = quoteIdent(monitoringUser);
341
+ const qDb = quoteIdent(database);
342
+ const qPw = quoteLiteral(params.monitoringPassword);
343
+ const qRoleNameLit = quoteLiteral(monitoringUser);
344
+
345
+ const steps: InitStep[] = [];
346
+
347
+ const vars = {
348
+ ROLE_IDENT: qRole,
349
+ DB_IDENT: qDb,
350
+ };
351
+
352
+ // 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
361
+ 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};
365
+ end if;
366
+ end $$;`;
367
+ }
368
+
369
+ const roleSql = applyTemplate(loadSqlTemplate("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
370
+ steps.push({ name: "01.role", sql: roleSql });
371
+
372
+ steps.push({
373
+ name: "02.permissions",
374
+ sql: applyTemplate(loadSqlTemplate("02.permissions.sql"), vars),
375
+ });
376
+
377
+ if (params.includeOptionalPermissions) {
378
+ steps.push(
379
+ {
380
+ name: "03.optional_rds",
381
+ sql: applyTemplate(loadSqlTemplate("03.optional_rds.sql"), vars),
382
+ optional: true,
383
+ },
384
+ {
385
+ name: "04.optional_self_managed",
386
+ sql: applyTemplate(loadSqlTemplate("04.optional_self_managed.sql"), vars),
387
+ optional: true,
388
+ }
389
+ );
390
+ }
391
+
392
+ return { monitoringUser, database, steps };
393
+ }
394
+
395
+ export async function applyInitPlan(params: {
396
+ client: PgClient;
397
+ plan: InitPlan;
398
+ verbose?: boolean;
399
+ }): Promise<{ applied: string[]; skippedOptional: string[] }> {
400
+ const applied: string[] = [];
401
+ const skippedOptional: string[] = [];
402
+
403
+ // Apply non-optional steps in a single transaction.
404
+ await params.client.query("begin;");
405
+ try {
406
+ for (const step of params.plan.steps.filter((s) => !s.optional)) {
407
+ try {
408
+ await params.client.query(step.sql, step.params as any);
409
+ applied.push(step.name);
410
+ } catch (e) {
411
+ const msg = e instanceof Error ? e.message : String(e);
412
+ const errAny = e as any;
413
+ 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;
417
+ }
418
+ throw wrapped;
419
+ }
420
+ }
421
+ await params.client.query("commit;");
422
+ } catch (e) {
423
+ // Rollback errors should never mask the original failure.
424
+ try {
425
+ await params.client.query("rollback;");
426
+ } catch {
427
+ // ignore
428
+ }
429
+ throw e;
430
+ }
431
+
432
+ // Apply optional steps outside of the transaction so a failure doesn't abort everything.
433
+ for (const step of params.plan.steps.filter((s) => s.optional)) {
434
+ try {
435
+ await params.client.query(step.sql, step.params as any);
436
+ applied.push(step.name);
437
+ } catch {
438
+ skippedOptional.push(step.name);
439
+ // best-effort: ignore
440
+ }
441
+ }
442
+
443
+ return { applied, skippedOptional };
444
+ }
445
+
446
+ export type VerifyInitResult = {
447
+ ok: boolean;
448
+ missingRequired: string[];
449
+ missingOptional: string[];
450
+ };
451
+
452
+ export async function verifyInitSetup(params: {
453
+ client: PgClient;
454
+ database: string;
455
+ monitoringUser: string;
456
+ includeOptionalPermissions: boolean;
457
+ }): 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
+ }
479
+
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
+ }
487
+
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
+ }
495
+
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",
502
+ [role]
503
+ );
504
+ if (!viewPrivRes.rows?.[0]?.ok) {
505
+ missingRequired.push("SELECT on view public.pg_statistic");
506
+ }
507
+ }
508
+
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
+ }
516
+
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");
527
+ }
528
+ }
529
+
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
+ );
541
+ if (!fnRes.rows?.[0]?.ok) {
542
+ missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
543
+ }
544
+ }
545
+ }
546
+
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
+ }
559
+ }
560
+ }
561
+
562
+ return { ok: missingRequired.length === 0, missingRequired, missingOptional };
563
+ }
564
+
565
+