postgresai 0.14.0-dev.7 → 0.14.0-dev.71

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.
Files changed (83) hide show
  1. package/README.md +161 -61
  2. package/bin/postgres-ai.ts +1982 -404
  3. package/bun.lock +258 -0
  4. package/bunfig.toml +20 -0
  5. package/dist/bin/postgres-ai.js +29395 -1576
  6. package/dist/sql/01.role.sql +16 -0
  7. package/dist/sql/02.permissions.sql +37 -0
  8. package/dist/sql/03.optional_rds.sql +6 -0
  9. package/dist/sql/04.optional_self_managed.sql +8 -0
  10. package/dist/sql/05.helpers.sql +439 -0
  11. package/dist/sql/sql/01.role.sql +16 -0
  12. package/dist/sql/sql/02.permissions.sql +37 -0
  13. package/dist/sql/sql/03.optional_rds.sql +6 -0
  14. package/dist/sql/sql/04.optional_self_managed.sql +8 -0
  15. package/dist/sql/sql/05.helpers.sql +439 -0
  16. package/lib/auth-server.ts +124 -106
  17. package/lib/checkup-api.ts +386 -0
  18. package/lib/checkup.ts +1396 -0
  19. package/lib/config.ts +6 -3
  20. package/lib/init.ts +568 -155
  21. package/lib/issues.ts +400 -191
  22. package/lib/mcp-server.ts +213 -90
  23. package/lib/metrics-embedded.ts +79 -0
  24. package/lib/metrics-loader.ts +127 -0
  25. package/lib/supabase.ts +769 -0
  26. package/lib/util.ts +61 -0
  27. package/package.json +20 -10
  28. package/packages/postgres-ai/README.md +26 -0
  29. package/packages/postgres-ai/bin/postgres-ai.js +27 -0
  30. package/packages/postgres-ai/package.json +27 -0
  31. package/scripts/embed-metrics.ts +154 -0
  32. package/sql/01.role.sql +16 -0
  33. package/sql/02.permissions.sql +37 -0
  34. package/sql/03.optional_rds.sql +6 -0
  35. package/sql/04.optional_self_managed.sql +8 -0
  36. package/sql/05.helpers.sql +439 -0
  37. package/test/auth.test.ts +258 -0
  38. package/test/checkup.integration.test.ts +321 -0
  39. package/test/checkup.test.ts +1117 -0
  40. package/test/config-consistency.test.ts +36 -0
  41. package/test/init.integration.test.ts +500 -0
  42. package/test/init.test.ts +682 -0
  43. package/test/issues.cli.test.ts +314 -0
  44. package/test/issues.test.ts +456 -0
  45. package/test/mcp-server.test.ts +988 -0
  46. package/test/schema-validation.test.ts +81 -0
  47. package/test/supabase.test.ts +568 -0
  48. package/test/test-utils.ts +128 -0
  49. package/tsconfig.json +12 -20
  50. package/dist/bin/postgres-ai.d.ts +0 -3
  51. package/dist/bin/postgres-ai.d.ts.map +0 -1
  52. package/dist/bin/postgres-ai.js.map +0 -1
  53. package/dist/lib/auth-server.d.ts +0 -31
  54. package/dist/lib/auth-server.d.ts.map +0 -1
  55. package/dist/lib/auth-server.js +0 -263
  56. package/dist/lib/auth-server.js.map +0 -1
  57. package/dist/lib/config.d.ts +0 -45
  58. package/dist/lib/config.d.ts.map +0 -1
  59. package/dist/lib/config.js +0 -181
  60. package/dist/lib/config.js.map +0 -1
  61. package/dist/lib/init.d.ts +0 -61
  62. package/dist/lib/init.d.ts.map +0 -1
  63. package/dist/lib/init.js +0 -359
  64. package/dist/lib/init.js.map +0 -1
  65. package/dist/lib/issues.d.ts +0 -75
  66. package/dist/lib/issues.d.ts.map +0 -1
  67. package/dist/lib/issues.js +0 -336
  68. package/dist/lib/issues.js.map +0 -1
  69. package/dist/lib/mcp-server.d.ts +0 -9
  70. package/dist/lib/mcp-server.d.ts.map +0 -1
  71. package/dist/lib/mcp-server.js +0 -168
  72. package/dist/lib/mcp-server.js.map +0 -1
  73. package/dist/lib/pkce.d.ts +0 -32
  74. package/dist/lib/pkce.d.ts.map +0 -1
  75. package/dist/lib/pkce.js +0 -101
  76. package/dist/lib/pkce.js.map +0 -1
  77. package/dist/lib/util.d.ts +0 -27
  78. package/dist/lib/util.d.ts.map +0 -1
  79. package/dist/lib/util.js +0 -46
  80. package/dist/lib/util.js.map +0 -1
  81. package/dist/package.json +0 -46
  82. package/test/init.integration.test.cjs +0 -269
  83. package/test/init.test.cjs +0 -69
package/lib/init.ts CHANGED
@@ -1,6 +1,37 @@
1
- import * as readline from "readline";
2
- import { URL } from "url";
1
+ import { randomBytes } from "crypto";
2
+ import { URL, fileURLToPath } from "url";
3
+ import type { ConnectionOptions as TlsConnectionOptions } from "tls";
3
4
  import type { Client as PgClient } from "pg";
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+
8
+ export const DEFAULT_MONITORING_USER = "postgres_ai_mon";
9
+
10
+ /**
11
+ * Database provider type. Affects which prepare-db steps are executed.
12
+ * Known providers have specific behavior adjustments; unknown providers use default behavior.
13
+ * TODO: Consider auto-detecting provider from connection string or server version string.
14
+ * TODO: Consider making this more flexible via a config that specifies which steps/checks to skip.
15
+ */
16
+ export type DbProvider = string;
17
+
18
+ /** Known providers with special handling. Unknown providers are treated as self-managed. */
19
+ export const KNOWN_PROVIDERS = ["self-managed", "supabase"] as const;
20
+
21
+ /** Providers where we skip role creation (users managed externally). */
22
+ const SKIP_ROLE_CREATION_PROVIDERS = ["supabase"];
23
+
24
+ /** Providers where we skip ALTER USER statements (restricted by provider). */
25
+ const SKIP_ALTER_USER_PROVIDERS = ["supabase"];
26
+
27
+ /** Providers where we skip search_path verification (not set via ALTER USER). */
28
+ const SKIP_SEARCH_PATH_CHECK_PROVIDERS = ["supabase"];
29
+
30
+ /** Check if a provider is known and return a warning message if not. */
31
+ export function validateProvider(provider: string | undefined): string | null {
32
+ if (!provider || KNOWN_PROVIDERS.includes(provider as any)) return null;
33
+ return `Unknown provider "${provider}". Known providers: ${KNOWN_PROVIDERS.join(", ")}. Treating as self-managed.`;
34
+ }
4
35
 
5
36
  export type PgClientConfig = {
6
37
  connectionString?: string;
@@ -9,14 +40,138 @@ export type PgClientConfig = {
9
40
  user?: string;
10
41
  password?: string;
11
42
  database?: string;
12
- ssl?: any;
43
+ ssl?: boolean | TlsConnectionOptions;
13
44
  };
14
45
 
46
+ /**
47
+ * Convert PostgreSQL sslmode to node-postgres ssl config.
48
+ */
49
+ function sslModeToConfig(mode: string): boolean | TlsConnectionOptions {
50
+ if (mode.toLowerCase() === "disable") return false;
51
+ if (mode.toLowerCase() === "verify-full" || mode.toLowerCase() === "verify-ca") return true;
52
+ // For require/prefer/allow: encrypt without certificate verification
53
+ return { rejectUnauthorized: false };
54
+ }
55
+
56
+ /** Extract sslmode from a PostgreSQL connection URI. */
57
+ function extractSslModeFromUri(uri: string): string | undefined {
58
+ try {
59
+ return new URL(uri).searchParams.get("sslmode") ?? undefined;
60
+ } catch {
61
+ return uri.match(/[?&]sslmode=([^&]+)/i)?.[1];
62
+ }
63
+ }
64
+
65
+ /** Remove sslmode parameter from a PostgreSQL connection URI. */
66
+ function stripSslModeFromUri(uri: string): string {
67
+ try {
68
+ const u = new URL(uri);
69
+ u.searchParams.delete("sslmode");
70
+ return u.toString();
71
+ } catch {
72
+ // Fallback regex for malformed URIs
73
+ return uri
74
+ .replace(/[?&]sslmode=[^&]*/gi, "")
75
+ .replace(/\?&/, "?")
76
+ .replace(/\?$/, "");
77
+ }
78
+ }
79
+
15
80
  export type AdminConnection = {
16
81
  clientConfig: PgClientConfig;
17
82
  display: string;
83
+ /** True if SSL fallback is enabled (try SSL first, fall back to non-SSL on failure). */
84
+ sslFallbackEnabled?: boolean;
18
85
  };
19
86
 
87
+ /**
88
+ * Check if an error indicates SSL negotiation failed and fallback to non-SSL should be attempted.
89
+ * This mimics libpq's sslmode=prefer behavior.
90
+ *
91
+ * IMPORTANT: This should NOT match certificate errors (expired, invalid, self-signed)
92
+ * as those are real errors the user needs to fix, not negotiation failures.
93
+ */
94
+ function isSslNegotiationError(err: unknown): boolean {
95
+ if (!err || typeof err !== "object") return false;
96
+ const e = err as any;
97
+ const msg = typeof e.message === "string" ? e.message.toLowerCase() : "";
98
+ const code = typeof e.code === "string" ? e.code : "";
99
+
100
+ // Specific patterns that indicate server doesn't support SSL (should fallback)
101
+ const fallbackPatterns = [
102
+ "the server does not support ssl",
103
+ "ssl off",
104
+ "server does not support ssl connections",
105
+ ];
106
+
107
+ for (const pattern of fallbackPatterns) {
108
+ if (msg.includes(pattern)) return true;
109
+ }
110
+
111
+ // PostgreSQL error code 08P01 (protocol violation) during initial connection
112
+ // often indicates SSL negotiation mismatch, but only if the message suggests it
113
+ if (code === "08P01" && (msg.includes("ssl") || msg.includes("unsupported"))) {
114
+ return true;
115
+ }
116
+
117
+ return false;
118
+ }
119
+
120
+ /**
121
+ * Connect to PostgreSQL with sslmode=prefer-like behavior.
122
+ * If sslFallbackEnabled is true, tries SSL first, then falls back to non-SSL on failure.
123
+ */
124
+ export async function connectWithSslFallback(
125
+ ClientClass: new (config: PgClientConfig) => PgClient,
126
+ adminConn: AdminConnection,
127
+ verbose?: boolean
128
+ ): Promise<{ client: PgClient; usedSsl: boolean }> {
129
+ const tryConnect = async (config: PgClientConfig): Promise<PgClient> => {
130
+ const client = new ClientClass(config);
131
+ await client.connect();
132
+ return client;
133
+ };
134
+
135
+ // If SSL was explicitly set or no SSL configured, just try once
136
+ if (!adminConn.sslFallbackEnabled) {
137
+ const client = await tryConnect(adminConn.clientConfig);
138
+ return { client, usedSsl: !!adminConn.clientConfig.ssl };
139
+ }
140
+
141
+ // sslmode=prefer behavior: try SSL first, fallback to non-SSL
142
+ try {
143
+ const client = await tryConnect(adminConn.clientConfig);
144
+ return { client, usedSsl: true };
145
+ } catch (sslErr) {
146
+ if (!isSslNegotiationError(sslErr)) {
147
+ // Not an SSL error, don't retry
148
+ throw sslErr;
149
+ }
150
+
151
+ if (verbose) {
152
+ console.log("SSL connection failed, retrying without SSL...");
153
+ }
154
+
155
+ // Retry without SSL
156
+ const noSslConfig: PgClientConfig = { ...adminConn.clientConfig, ssl: false };
157
+ try {
158
+ const client = await tryConnect(noSslConfig);
159
+ return { client, usedSsl: false };
160
+ } catch (noSslErr) {
161
+ // If non-SSL also fails, check if it's "SSL required" - throw that instead
162
+ if (isSslNegotiationError(noSslErr)) {
163
+ const msg = (noSslErr as any)?.message || "";
164
+ if (msg.toLowerCase().includes("ssl") && msg.toLowerCase().includes("required")) {
165
+ // Server requires SSL but SSL attempt failed - throw original SSL error
166
+ throw sslErr;
167
+ }
168
+ }
169
+ // Throw the non-SSL error (it's more relevant since SSL attempt also failed)
170
+ throw noSslErr;
171
+ }
172
+ }
173
+ }
174
+
20
175
  export type InitStep = {
21
176
  name: string;
22
177
  sql: string;
@@ -30,11 +185,64 @@ export type InitPlan = {
30
185
  steps: InitStep[];
31
186
  };
32
187
 
188
+ function sqlDir(): string {
189
+ // Handle both development and production paths
190
+ // Development: lib/init.ts -> ../sql
191
+ // Production (bundled): dist/bin/postgres-ai.js -> ../sql (copied during build)
192
+ //
193
+ // IMPORTANT: Use import.meta.url instead of __dirname because bundlers (bun/esbuild)
194
+ // bake in __dirname at build time, while import.meta.url resolves at runtime.
195
+ const currentFile = fileURLToPath(import.meta.url);
196
+ const currentDir = path.dirname(currentFile);
197
+
198
+ const candidates = [
199
+ path.resolve(currentDir, "..", "sql"), // bundled: dist/bin -> dist/sql
200
+ path.resolve(currentDir, "..", "..", "sql"), // dev from lib: lib -> ../sql
201
+ ];
202
+
203
+ for (const candidate of candidates) {
204
+ if (fs.existsSync(candidate)) {
205
+ return candidate;
206
+ }
207
+ }
208
+ throw new Error(`SQL directory not found. Searched: ${candidates.join(", ")}`);
209
+ }
210
+
211
+ function loadSqlTemplate(filename: string): string {
212
+ const p = path.join(sqlDir(), filename);
213
+ return fs.readFileSync(p, "utf8");
214
+ }
215
+
216
+ function applyTemplate(sql: string, vars: Record<string, string>): string {
217
+ return sql.replace(/\{\{([A-Z0-9_]+)\}\}/g, (_, key) => {
218
+ const v = vars[key];
219
+ if (v === undefined) throw new Error(`Missing SQL template var: ${key}`);
220
+ return v;
221
+ });
222
+ }
223
+
33
224
  function quoteIdent(ident: string): string {
34
225
  // Always quote. Escape embedded quotes by doubling.
226
+ if (ident.includes("\0")) {
227
+ throw new Error("Identifier cannot contain null bytes");
228
+ }
35
229
  return `"${ident.replace(/"/g, "\"\"")}"`;
36
230
  }
37
231
 
232
+ function quoteLiteral(value: string): string {
233
+ // Single-quote and escape embedded quotes by doubling.
234
+ // This is used where Postgres grammar requires a literal (e.g., CREATE/ALTER ROLE PASSWORD).
235
+ if (value.includes("\0")) {
236
+ throw new Error("Literal cannot contain null bytes");
237
+ }
238
+ return `'${value.replace(/'/g, "''")}'`;
239
+ }
240
+
241
+ export function redactPasswordsInSql(sql: string): string {
242
+ // Replace PASSWORD '<literal>' (handles doubled quotes inside).
243
+ return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
244
+ }
245
+
38
246
  export function maskConnectionString(dbUrl: string): string {
39
247
  // Hide password if present (postgresql://user:pass@host/db).
40
248
  try {
@@ -98,6 +306,7 @@ function tokenizeConninfo(input: string): string[] {
98
306
  export function parseLibpqConninfo(input: string): PgClientConfig {
99
307
  const tokens = tokenizeConninfo(input);
100
308
  const cfg: PgClientConfig = {};
309
+ let sslmode: string | undefined;
101
310
 
102
311
  for (const t of tokens) {
103
312
  const eq = t.indexOf("=");
@@ -126,12 +335,20 @@ export function parseLibpqConninfo(input: string): PgClientConfig {
126
335
  case "database":
127
336
  cfg.database = val;
128
337
  break;
129
- // ignore everything else (sslmode, options, application_name, etc.)
338
+ case "sslmode":
339
+ sslmode = val;
340
+ break;
341
+ // ignore everything else (options, application_name, etc.)
130
342
  default:
131
343
  break;
132
344
  }
133
345
  }
134
346
 
347
+ // Apply SSL configuration based on sslmode
348
+ if (sslmode) {
349
+ cfg.ssl = sslModeToConfig(sslmode);
350
+ }
351
+
135
352
  return cfg;
136
353
  }
137
354
 
@@ -158,8 +375,12 @@ export function resolveAdminConnection(opts: {
158
375
  const conn = (opts.conn || "").trim();
159
376
  const dbUrlFlag = (opts.dbUrlFlag || "").trim();
160
377
 
161
- const hasPsqlParts =
162
- !!(opts.host || opts.port || opts.username || opts.dbname || opts.adminPassword || opts.envPassword);
378
+ // Resolve explicit SSL setting from environment (undefined = auto-detect)
379
+ const explicitSsl = process.env.PGSSLMODE;
380
+
381
+ // NOTE: passwords alone (PGPASSWORD / --admin-password) do NOT constitute a connection.
382
+ // We require at least some connection addressing (host/port/user/db) if no positional arg / --db-url is provided.
383
+ const hasConnDetails = !!(opts.host || opts.port || opts.username || opts.dbname);
163
384
 
164
385
  if (conn && dbUrlFlag) {
165
386
  throw new Error("Provide either positional connection string or --db-url, not both");
@@ -168,84 +389,94 @@ export function resolveAdminConnection(opts: {
168
389
  if (conn || dbUrlFlag) {
169
390
  const v = conn || dbUrlFlag;
170
391
  if (isLikelyUri(v)) {
171
- return { clientConfig: { connectionString: v }, display: maskConnectionString(v) };
392
+ const urlSslMode = extractSslModeFromUri(v);
393
+ const effectiveSslMode = explicitSsl || urlSslMode;
394
+ // SSL priority: PGSSLMODE env > URL param > auto (sslmode=prefer behavior)
395
+ const sslConfig = effectiveSslMode
396
+ ? sslModeToConfig(effectiveSslMode)
397
+ : { rejectUnauthorized: false }; // Default: try SSL (with fallback)
398
+ // Enable fallback for: no explicit mode OR explicit "prefer"/"allow"
399
+ const shouldFallback = !effectiveSslMode ||
400
+ effectiveSslMode.toLowerCase() === "prefer" ||
401
+ effectiveSslMode.toLowerCase() === "allow";
402
+ // Strip sslmode from URI so pg uses our ssl config object instead
403
+ const cleanUri = stripSslModeFromUri(v);
404
+ return {
405
+ clientConfig: { connectionString: cleanUri, ssl: sslConfig },
406
+ display: maskConnectionString(v),
407
+ sslFallbackEnabled: shouldFallback,
408
+ };
172
409
  }
173
410
  // libpq conninfo (dbname=... host=...)
174
411
  const cfg = parseLibpqConninfo(v);
175
412
  if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
176
- return { clientConfig: cfg, display: describePgConfig(cfg) };
413
+ const cfgHadSsl = cfg.ssl !== undefined;
414
+ if (cfg.ssl === undefined) {
415
+ if (explicitSsl) cfg.ssl = sslModeToConfig(explicitSsl);
416
+ else cfg.ssl = { rejectUnauthorized: false }; // Default: try SSL (with fallback)
417
+ }
418
+ // Enable fallback for: no explicit mode OR explicit "prefer"/"allow"
419
+ const shouldFallback = (!explicitSsl && !cfgHadSsl) ||
420
+ (!!explicitSsl && (explicitSsl.toLowerCase() === "prefer" || explicitSsl.toLowerCase() === "allow"));
421
+ return {
422
+ clientConfig: cfg,
423
+ display: describePgConfig(cfg),
424
+ sslFallbackEnabled: shouldFallback,
425
+ };
177
426
  }
178
427
 
179
- if (!hasPsqlParts) {
180
- throw new Error(
181
- "Connection is required. Provide a connection string/conninfo as a positional arg, or use --db-url, or use -h/-p/-U/-d."
182
- );
428
+ if (!hasConnDetails) {
429
+ // Keep this message short: the CLI prints full help (including examples) on this error.
430
+ throw new Error("Connection is required.");
183
431
  }
184
432
 
185
433
  const cfg: PgClientConfig = {};
186
434
  if (opts.host) cfg.host = opts.host;
187
- if (opts.port !== undefined && opts.port !== "") cfg.port = Number(opts.port);
435
+ if (opts.port !== undefined && opts.port !== "") {
436
+ const p = Number(opts.port);
437
+ if (!Number.isFinite(p) || !Number.isInteger(p) || p <= 0 || p > 65535) {
438
+ throw new Error(`Invalid port value: ${String(opts.port)}`);
439
+ }
440
+ cfg.port = p;
441
+ }
188
442
  if (opts.username) cfg.user = opts.username;
189
443
  if (opts.dbname) cfg.database = opts.dbname;
190
444
  if (opts.adminPassword) cfg.password = opts.adminPassword;
191
445
  if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
192
- return { clientConfig: cfg, display: describePgConfig(cfg) };
446
+ if (explicitSsl) {
447
+ cfg.ssl = sslModeToConfig(explicitSsl);
448
+ // Enable fallback for explicit "prefer"/"allow"
449
+ const shouldFallback = explicitSsl.toLowerCase() === "prefer" || explicitSsl.toLowerCase() === "allow";
450
+ return { clientConfig: cfg, display: describePgConfig(cfg), sslFallbackEnabled: shouldFallback };
451
+ }
452
+ // Default: try SSL with fallback (sslmode=prefer behavior)
453
+ cfg.ssl = { rejectUnauthorized: false };
454
+ return { clientConfig: cfg, display: describePgConfig(cfg), sslFallbackEnabled: true };
193
455
  }
194
456
 
195
- export async function promptHidden(prompt: string): Promise<string> {
196
- const rl = readline.createInterface({
197
- input: process.stdin,
198
- output: process.stdout,
199
- terminal: true,
200
- });
201
-
202
- // Mask input by overriding internal write method.
203
- const anyRl = rl as any;
204
- const out = process.stdout as NodeJS.WriteStream;
205
- anyRl._writeToOutput = (str: string) => {
206
- // Keep newlines and carriage returns; mask everything else.
207
- if (str === "\n" || str === "\r\n") {
208
- out.write(str);
209
- } else {
210
- out.write("*");
211
- }
212
- };
213
-
214
- try {
215
- const answer = await new Promise<string>((resolve) => rl.question(prompt, resolve));
216
- // Ensure we end the masked line cleanly.
217
- process.stdout.write("\n");
218
- return answer;
219
- } finally {
220
- rl.close();
457
+ function generateMonitoringPassword(): string {
458
+ // URL-safe and easy to copy/paste; 24 bytes => 32 base64url chars (no padding).
459
+ // Note: randomBytes() throws on failure; we add a tiny sanity check for unexpected output.
460
+ const password = randomBytes(24).toString("base64url");
461
+ if (password.length < 30) {
462
+ throw new Error("Password generation failed: unexpected output length");
221
463
  }
464
+ return password;
222
465
  }
223
466
 
224
467
  export async function resolveMonitoringPassword(opts: {
225
468
  passwordFlag?: string;
226
469
  passwordEnv?: string;
227
- prompt?: (prompt: string) => Promise<string>;
228
470
  monitoringUser: string;
229
- }): Promise<string> {
471
+ }): Promise<{ password: string; generated: boolean }> {
230
472
  const fromFlag = (opts.passwordFlag || "").trim();
231
- if (fromFlag) return fromFlag;
473
+ if (fromFlag) return { password: fromFlag, generated: false };
232
474
 
233
475
  const fromEnv = (opts.passwordEnv || "").trim();
234
- if (fromEnv) return fromEnv;
235
-
236
- if (!process.stdin.isTTY) {
237
- throw new Error(
238
- "Monitoring user password is required in non-interactive mode (use --password or PGAI_MON_PASSWORD)"
239
- );
240
- }
476
+ if (fromEnv) return { password: fromEnv, generated: false };
241
477
 
242
- const prompter = opts.prompt || promptHidden;
243
- while (true) {
244
- const pw = (await prompter(`Enter password for monitoring user ${opts.monitoringUser}: `)).trim();
245
- if (pw) return pw;
246
- // eslint-disable-next-line no-console
247
- console.error("Password cannot be empty");
248
- }
478
+ // Default: auto-generate (safer than prompting; works in non-interactive mode).
479
+ return { password: generateMonitoringPassword(), generated: true };
249
480
  }
250
481
 
251
482
  export async function buildInitPlan(params: {
@@ -253,106 +484,87 @@ export async function buildInitPlan(params: {
253
484
  monitoringUser?: string;
254
485
  monitoringPassword: string;
255
486
  includeOptionalPermissions: boolean;
256
- roleExists?: boolean;
487
+ /** Provider type. Affects which steps are included. Defaults to "self-managed". */
488
+ provider?: DbProvider;
257
489
  }): Promise<InitPlan> {
258
- const monitoringUser = params.monitoringUser || "postgres_ai_mon";
490
+ // NOTE: kept async for API stability / potential future async template loading.
491
+ const monitoringUser = params.monitoringUser || DEFAULT_MONITORING_USER;
259
492
  const database = params.database;
493
+ const provider = params.provider ?? "self-managed";
260
494
 
261
495
  const qRole = quoteIdent(monitoringUser);
262
496
  const qDb = quoteIdent(database);
497
+ const qPw = quoteLiteral(params.monitoringPassword);
498
+ const qRoleNameLit = quoteLiteral(monitoringUser);
263
499
 
264
500
  const steps: InitStep[] = [];
265
501
 
266
- // Role creation/update is done in two alternative steps. Caller decides by checking role existence.
267
- if (params.roleExists === false) {
268
- steps.push({
269
- name: "create monitoring user",
270
- sql: `create user ${qRole} with password $1;`,
271
- params: [params.monitoringPassword],
272
- });
273
- } else if (params.roleExists === true) {
274
- steps.push({
275
- name: "update monitoring user password",
276
- sql: `alter user ${qRole} with password $1;`,
277
- params: [params.monitoringPassword],
278
- });
279
- } else {
280
- // Unknown: caller will rebuild after probing role existence.
502
+ const vars: Record<string, string> = {
503
+ ROLE_IDENT: qRole,
504
+ DB_IDENT: qDb,
505
+ };
506
+
507
+ // Some providers (e.g., Supabase) manage users externally - skip role creation.
508
+ // TODO: Make this more flexible by allowing users to specify which steps to skip via config.
509
+ if (!SKIP_ROLE_CREATION_PROVIDERS.includes(provider)) {
510
+ // Role creation/update is done in one template file.
511
+ // Always use a single DO block to avoid race conditions between "role exists?" checks and CREATE USER.
512
+ // We:
513
+ // - create role if missing (and handle duplicate_object in case another session created it concurrently),
514
+ // - then ALTER ROLE to ensure the password is set to the desired value.
515
+ const roleStmt = `do $$ begin
516
+ if not exists (select 1 from pg_catalog.pg_roles where rolname = ${qRoleNameLit}) then
517
+ begin
518
+ create user ${qRole} with password ${qPw};
519
+ exception when duplicate_object then
520
+ null;
521
+ end;
522
+ end if;
523
+ alter user ${qRole} with password ${qPw};
524
+ end $$;`;
525
+
526
+ const roleSql = applyTemplate(loadSqlTemplate("01.role.sql"), { ...vars, ROLE_STMT: roleStmt });
527
+ steps.push({ name: "01.role", sql: roleSql });
281
528
  }
282
529
 
283
- steps.push(
284
- {
285
- name: "grant connect on database",
286
- sql: `grant connect on database ${qDb} to ${qRole};`,
287
- },
288
- {
289
- name: "grant pg_monitor",
290
- sql: `grant pg_monitor to ${qRole};`,
291
- },
292
- {
293
- name: "grant select on pg_index",
294
- sql: `grant select on pg_catalog.pg_index to ${qRole};`,
295
- },
296
- {
297
- name: "create or replace public.pg_statistic view",
298
- sql: `create or replace view public.pg_statistic as
299
- select
300
- n.nspname as schemaname,
301
- c.relname as tablename,
302
- a.attname,
303
- s.stanullfrac as null_frac,
304
- s.stawidth as avg_width,
305
- false as inherited
306
- from pg_catalog.pg_statistic s
307
- join pg_catalog.pg_class c on c.oid = s.starelid
308
- join pg_catalog.pg_namespace n on n.oid = c.relnamespace
309
- join pg_catalog.pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
310
- where a.attnum > 0 and not a.attisdropped;`,
311
- },
312
- {
313
- name: "grant select on public.pg_statistic",
314
- sql: `grant select on public.pg_statistic to ${qRole};`,
315
- },
316
- {
317
- name: "ensure access to public schema (for hardened clusters)",
318
- sql: `grant usage on schema public to ${qRole};`,
319
- },
320
- {
321
- name: "set monitoring user search_path",
322
- sql: `alter user ${qRole} set search_path = "$user", public, pg_catalog;`,
323
- }
324
- );
530
+ let permissionsSql = applyTemplate(loadSqlTemplate("02.permissions.sql"), vars);
531
+
532
+ // Some providers restrict ALTER USER - remove those statements.
533
+ // TODO: Make this more flexible by allowing users to specify which statements to skip via config.
534
+ if (SKIP_ALTER_USER_PROVIDERS.includes(provider)) {
535
+ permissionsSql = permissionsSql
536
+ .split("\n")
537
+ .filter((line) => {
538
+ const trimmed = line.trim();
539
+ // Keep comments and empty lines
540
+ if (trimmed.startsWith("--") || trimmed === "") return true;
541
+ // Filter out ALTER USER statements (case-insensitive, flexible whitespace)
542
+ return !/^\s*alter\s+user\s+/i.test(line);
543
+ })
544
+ .join("\n");
545
+ }
546
+
547
+ steps.push({
548
+ name: "02.permissions",
549
+ sql: permissionsSql,
550
+ });
551
+
552
+ // Helper functions (SECURITY DEFINER) for plan analysis and table info
553
+ steps.push({
554
+ name: "05.helpers",
555
+ sql: applyTemplate(loadSqlTemplate("05.helpers.sql"), vars),
556
+ });
325
557
 
326
558
  if (params.includeOptionalPermissions) {
327
559
  steps.push(
328
560
  {
329
- name: "create rds_tools extension (optional)",
330
- sql: "create extension if not exists rds_tools;",
331
- optional: true,
332
- },
333
- {
334
- name: "grant rds_tools.pg_ls_multixactdir() (optional)",
335
- sql: `grant execute on function rds_tools.pg_ls_multixactdir() to ${qRole};`,
336
- optional: true,
337
- },
338
- {
339
- name: "grant pg_stat_file(text) (optional)",
340
- sql: `grant execute on function pg_catalog.pg_stat_file(text) to ${qRole};`,
341
- optional: true,
342
- },
343
- {
344
- name: "grant pg_stat_file(text, boolean) (optional)",
345
- sql: `grant execute on function pg_catalog.pg_stat_file(text, boolean) to ${qRole};`,
346
- optional: true,
347
- },
348
- {
349
- name: "grant pg_ls_dir(text) (optional)",
350
- sql: `grant execute on function pg_catalog.pg_ls_dir(text) to ${qRole};`,
561
+ name: "03.optional_rds",
562
+ sql: applyTemplate(loadSqlTemplate("03.optional_rds.sql"), vars),
351
563
  optional: true,
352
564
  },
353
565
  {
354
- name: "grant pg_ls_dir(text, boolean, boolean) (optional)",
355
- sql: `grant execute on function pg_catalog.pg_ls_dir(text, boolean, boolean) to ${qRole};`,
566
+ name: "04.optional_self_managed",
567
+ sql: applyTemplate(loadSqlTemplate("04.optional_self_managed.sql"), vars),
356
568
  optional: true,
357
569
  }
358
570
  );
@@ -369,28 +581,66 @@ export async function applyInitPlan(params: {
369
581
  const applied: string[] = [];
370
582
  const skippedOptional: string[] = [];
371
583
 
372
- // Apply non-optional steps in a single transaction.
373
- await params.client.query("begin;");
374
- try {
375
- for (const step of params.plan.steps.filter((s) => !s.optional)) {
584
+ // Helper to wrap a step execution in begin/commit
585
+ const executeStep = async (step: InitStep): Promise<void> => {
586
+ await params.client.query("begin;");
587
+ try {
588
+ await params.client.query(step.sql, step.params as any);
589
+ await params.client.query("commit;");
590
+ } catch (e) {
591
+ // Rollback errors should never mask the original failure.
376
592
  try {
377
- await params.client.query(step.sql, step.params as any);
378
- applied.push(step.name);
379
- } catch (e) {
380
- const msg = e instanceof Error ? e.message : String(e);
381
- throw new Error(`Failed at step "${step.name}": ${msg}`);
593
+ await params.client.query("rollback;");
594
+ } catch {
595
+ // ignore
382
596
  }
597
+ throw e;
598
+ }
599
+ };
600
+
601
+ // Apply non-optional steps, each in its own transaction
602
+ for (const step of params.plan.steps.filter((s) => !s.optional)) {
603
+ try {
604
+ await executeStep(step);
605
+ applied.push(step.name);
606
+ } catch (e) {
607
+ const msg = e instanceof Error ? e.message : String(e);
608
+ const errAny = e as any;
609
+ const wrapped: any = new Error(`Failed at step "${step.name}": ${msg}`);
610
+ // Preserve useful Postgres error fields so callers can provide better hints / diagnostics.
611
+ const pgErrorFields = [
612
+ "code",
613
+ "detail",
614
+ "hint",
615
+ "position",
616
+ "internalPosition",
617
+ "internalQuery",
618
+ "where",
619
+ "schema",
620
+ "table",
621
+ "column",
622
+ "dataType",
623
+ "constraint",
624
+ "file",
625
+ "line",
626
+ "routine",
627
+ ] as const;
628
+ if (errAny && typeof errAny === "object") {
629
+ for (const field of pgErrorFields) {
630
+ if (errAny[field] !== undefined) wrapped[field] = errAny[field];
631
+ }
632
+ }
633
+ if (e instanceof Error && e.stack) {
634
+ wrapped.stack = e.stack;
635
+ }
636
+ throw wrapped;
383
637
  }
384
- await params.client.query("commit;");
385
- } catch (e) {
386
- await params.client.query("rollback;");
387
- throw e;
388
638
  }
389
639
 
390
- // Apply optional steps outside of the transaction so a failure doesn't abort everything.
640
+ // Apply optional steps, each in its own transaction (failure doesn't abort)
391
641
  for (const step of params.plan.steps.filter((s) => s.optional)) {
392
642
  try {
393
- await params.client.query(step.sql, step.params as any);
643
+ await executeStep(step);
394
644
  applied.push(step.name);
395
645
  } catch {
396
646
  skippedOptional.push(step.name);
@@ -401,4 +651,167 @@ export async function applyInitPlan(params: {
401
651
  return { applied, skippedOptional };
402
652
  }
403
653
 
654
+ export type VerifyInitResult = {
655
+ ok: boolean;
656
+ missingRequired: string[];
657
+ missingOptional: string[];
658
+ };
659
+
660
+ export async function verifyInitSetup(params: {
661
+ client: PgClient;
662
+ database: string;
663
+ monitoringUser: string;
664
+ includeOptionalPermissions: boolean;
665
+ /** Provider type. Affects which checks are performed. */
666
+ provider?: DbProvider;
667
+ }): Promise<VerifyInitResult> {
668
+ // Use a repeatable-read snapshot so all checks see a consistent view.
669
+ await params.client.query("begin isolation level repeatable read;");
670
+ try {
671
+ const missingRequired: string[] = [];
672
+ const missingOptional: string[] = [];
673
+
674
+ const role = params.monitoringUser;
675
+ const db = params.database;
676
+ const provider = params.provider ?? "self-managed";
677
+
678
+ const roleRes = await params.client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [role]);
679
+ const roleExists = (roleRes.rowCount ?? 0) > 0;
680
+ if (!roleExists) {
681
+ missingRequired.push(`role "${role}" does not exist`);
682
+ // If role is missing, other checks will error or be meaningless.
683
+ return { ok: false, missingRequired, missingOptional };
684
+ }
685
+
686
+ const connectRes = await params.client.query(
687
+ "select has_database_privilege($1, $2, 'CONNECT') as ok",
688
+ [role, db]
689
+ );
690
+ if (!connectRes.rows?.[0]?.ok) {
691
+ missingRequired.push(`CONNECT on database "${db}"`);
692
+ }
693
+
694
+ const pgMonitorRes = await params.client.query(
695
+ "select pg_has_role($1, 'pg_monitor', 'member') as ok",
696
+ [role]
697
+ );
698
+ if (!pgMonitorRes.rows?.[0]?.ok) {
699
+ missingRequired.push("membership in role pg_monitor");
700
+ }
701
+
702
+ const pgIndexRes = await params.client.query(
703
+ "select has_table_privilege($1, 'pg_catalog.pg_index', 'SELECT') as ok",
704
+ [role]
705
+ );
706
+ if (!pgIndexRes.rows?.[0]?.ok) {
707
+ missingRequired.push("SELECT on pg_catalog.pg_index");
708
+ }
709
+
710
+ // Check postgres_ai schema exists and is usable
711
+ const schemaExistsRes = await params.client.query(
712
+ "select has_schema_privilege($1, 'postgres_ai', 'USAGE') as ok",
713
+ [role]
714
+ );
715
+ if (!schemaExistsRes.rows?.[0]?.ok) {
716
+ missingRequired.push("USAGE on schema postgres_ai");
717
+ }
718
+
719
+ const viewExistsRes = await params.client.query("select to_regclass('postgres_ai.pg_statistic') is not null as ok");
720
+ if (!viewExistsRes.rows?.[0]?.ok) {
721
+ missingRequired.push("view postgres_ai.pg_statistic exists");
722
+ } else {
723
+ const viewPrivRes = await params.client.query(
724
+ "select has_table_privilege($1, 'postgres_ai.pg_statistic', 'SELECT') as ok",
725
+ [role]
726
+ );
727
+ if (!viewPrivRes.rows?.[0]?.ok) {
728
+ missingRequired.push("SELECT on view postgres_ai.pg_statistic");
729
+ }
730
+ }
731
+
732
+ const schemaUsageRes = await params.client.query(
733
+ "select has_schema_privilege($1, 'public', 'USAGE') as ok",
734
+ [role]
735
+ );
736
+ if (!schemaUsageRes.rows?.[0]?.ok) {
737
+ missingRequired.push("USAGE on schema public");
738
+ }
739
+
740
+ // Some providers don't allow setting search_path via ALTER USER - skip this check.
741
+ // TODO: Make this more flexible by allowing users to specify which checks to skip via config.
742
+ if (!SKIP_SEARCH_PATH_CHECK_PROVIDERS.includes(provider)) {
743
+ const rolcfgRes = await params.client.query("select rolconfig from pg_catalog.pg_roles where rolname = $1", [role]);
744
+ const rolconfig = rolcfgRes.rows?.[0]?.rolconfig;
745
+ const spLine = Array.isArray(rolconfig) ? rolconfig.find((v: any) => String(v).startsWith("search_path=")) : undefined;
746
+ if (typeof spLine !== "string" || !spLine) {
747
+ missingRequired.push("role search_path is set");
748
+ } else {
749
+ // We accept any ordering as long as postgres_ai, public, and pg_catalog are included.
750
+ const sp = spLine.toLowerCase();
751
+ if (!sp.includes("postgres_ai") || !sp.includes("public") || !sp.includes("pg_catalog")) {
752
+ missingRequired.push("role search_path includes postgres_ai, public and pg_catalog");
753
+ }
754
+ }
755
+ }
756
+
757
+ // Check for helper functions
758
+ const explainFnRes = await params.client.query(
759
+ "select has_function_privilege($1, 'postgres_ai.explain_generic(text, text, text)', 'EXECUTE') as ok",
760
+ [role]
761
+ );
762
+ if (!explainFnRes.rows?.[0]?.ok) {
763
+ missingRequired.push("EXECUTE on postgres_ai.explain_generic(text, text, text)");
764
+ }
765
+
766
+ const tableDescribeFnRes = await params.client.query(
767
+ "select has_function_privilege($1, 'postgres_ai.table_describe(text)', 'EXECUTE') as ok",
768
+ [role]
769
+ );
770
+ if (!tableDescribeFnRes.rows?.[0]?.ok) {
771
+ missingRequired.push("EXECUTE on postgres_ai.table_describe(text)");
772
+ }
773
+
774
+ if (params.includeOptionalPermissions) {
775
+ // Optional RDS/Aurora extras
776
+ {
777
+ const extRes = await params.client.query("select 1 from pg_extension where extname = 'rds_tools'");
778
+ if ((extRes.rowCount ?? 0) === 0) {
779
+ missingOptional.push("extension rds_tools");
780
+ } else {
781
+ const fnRes = await params.client.query(
782
+ "select has_function_privilege($1, 'rds_tools.pg_ls_multixactdir()', 'EXECUTE') as ok",
783
+ [role]
784
+ );
785
+ if (!fnRes.rows?.[0]?.ok) {
786
+ missingOptional.push("EXECUTE on rds_tools.pg_ls_multixactdir()");
787
+ }
788
+ }
789
+ }
790
+
791
+ // Optional self-managed extras
792
+ const optionalFns = [
793
+ "pg_catalog.pg_stat_file(text)",
794
+ "pg_catalog.pg_stat_file(text, boolean)",
795
+ "pg_catalog.pg_ls_dir(text)",
796
+ "pg_catalog.pg_ls_dir(text, boolean, boolean)",
797
+ ];
798
+ for (const fn of optionalFns) {
799
+ const fnRes = await params.client.query("select has_function_privilege($1, $2, 'EXECUTE') as ok", [role, fn]);
800
+ if (!fnRes.rows?.[0]?.ok) {
801
+ missingOptional.push(`EXECUTE on ${fn}`);
802
+ }
803
+ }
804
+ }
805
+
806
+ return { ok: missingRequired.length === 0, missingRequired, missingOptional };
807
+ } finally {
808
+ // Read-only: rollback to release snapshot; do not mask original errors.
809
+ try {
810
+ await params.client.query("rollback;");
811
+ } catch {
812
+ // ignore
813
+ }
814
+ }
815
+ }
816
+
404
817