postgresai 0.11.0-alpha.1 → 0.11.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1011 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import * as pkg from "../package.json";
5
+ import * as config from "../lib/config";
6
+ import * as yaml from "js-yaml";
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ import * as os from "os";
10
+ import { spawn, spawnSync, exec, execFile } from "child_process";
11
+ import { promisify } from "util";
12
+ import * as readline from "readline";
13
+ import * as http from "https";
14
+ import { URL } from "url";
15
+
16
+ const execPromise = promisify(exec);
17
+ const execFilePromise = promisify(execFile);
18
+
19
+ /**
20
+ * CLI configuration options
21
+ */
22
+ interface CliOptions {
23
+ apiKey?: string;
24
+ apiBaseUrl?: string;
25
+ uiBaseUrl?: string;
26
+ }
27
+
28
+ /**
29
+ * Configuration result
30
+ */
31
+ interface ConfigResult {
32
+ apiKey: string;
33
+ }
34
+
35
+ /**
36
+ * Instance configuration
37
+ */
38
+ interface Instance {
39
+ name: string;
40
+ conn_str?: string;
41
+ preset_metrics?: string;
42
+ custom_metrics?: any;
43
+ is_enabled?: boolean;
44
+ group?: string;
45
+ custom_tags?: Record<string, any>;
46
+ }
47
+
48
+ /**
49
+ * Path resolution result
50
+ */
51
+ interface PathResolution {
52
+ fs: typeof fs;
53
+ path: typeof path;
54
+ projectDir: string;
55
+ composeFile: string;
56
+ instancesFile: string;
57
+ }
58
+
59
+ /**
60
+ * Health check service
61
+ */
62
+ interface HealthService {
63
+ name: string;
64
+ url: string;
65
+ }
66
+
67
+ /**
68
+ * Get configuration from various sources
69
+ * @param opts - Command line options
70
+ * @returns Configuration object
71
+ */
72
+ function getConfig(opts: CliOptions): ConfigResult {
73
+ // Priority order:
74
+ // 1. Command line option (--api-key)
75
+ // 2. Environment variable (PGAI_API_KEY)
76
+ // 3. User-level config file (~/.config/postgresai/config.json)
77
+ // 4. Legacy project-local config (.pgwatch-config)
78
+
79
+ let apiKey = opts.apiKey || process.env.PGAI_API_KEY || "";
80
+
81
+ // Try config file if not provided via CLI or env
82
+ if (!apiKey) {
83
+ const fileConfig = config.readConfig();
84
+ if (!apiKey) apiKey = fileConfig.apiKey || "";
85
+ }
86
+
87
+ return { apiKey };
88
+ }
89
+
90
+ const program = new Command();
91
+
92
+ program
93
+ .name("postgres-ai")
94
+ .description("PostgresAI CLI")
95
+ .version(pkg.version)
96
+ .option("--api-key <key>", "API key (overrides PGAI_API_KEY)")
97
+ .option(
98
+ "--api-base-url <url>",
99
+ "API base URL for backend RPC (overrides PGAI_API_BASE_URL)"
100
+ )
101
+ .option(
102
+ "--ui-base-url <url>",
103
+ "UI base URL for browser routes (overrides PGAI_UI_BASE_URL)"
104
+ );
105
+
106
+ /**
107
+ * Stub function for not implemented commands
108
+ */
109
+ const stub = (name: string) => async (): Promise<void> => {
110
+ // Temporary stubs until Node parity is implemented
111
+ console.error(`${name}: not implemented in Node CLI yet; use bash CLI for now`);
112
+ process.exitCode = 2;
113
+ };
114
+
115
+ /**
116
+ * Resolve project paths
117
+ */
118
+ function resolvePaths(): PathResolution {
119
+ const projectDir = process.cwd();
120
+ const composeFile = path.resolve(projectDir, "docker-compose.yml");
121
+ const instancesFile = path.resolve(projectDir, "instances.yml");
122
+ return { fs, path, projectDir, composeFile, instancesFile };
123
+ }
124
+
125
+ /**
126
+ * Get docker compose command
127
+ */
128
+ function getComposeCmd(): string[] | null {
129
+ const tryCmd = (cmd: string, args: string[]): boolean =>
130
+ spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
131
+ if (tryCmd("docker-compose", ["version"])) return ["docker-compose"];
132
+ if (tryCmd("docker", ["compose", "version"])) return ["docker", "compose"];
133
+ return null;
134
+ }
135
+
136
+ /**
137
+ * Run docker compose command
138
+ */
139
+ async function runCompose(args: string[]): Promise<number> {
140
+ const { composeFile } = resolvePaths();
141
+ const cmd = getComposeCmd();
142
+ if (!cmd) {
143
+ console.error("docker compose not found (need docker-compose or docker compose)");
144
+ process.exitCode = 1;
145
+ return 1;
146
+ }
147
+ return new Promise<number>((resolve) => {
148
+ const child = spawn(cmd[0], [...cmd.slice(1), "-f", composeFile, ...args], { stdio: "inherit" });
149
+ child.on("close", (code) => resolve(code || 0));
150
+ });
151
+ }
152
+
153
+ program.command("help", { isDefault: true }).description("show help").action(() => {
154
+ program.outputHelp();
155
+ });
156
+
157
+ program
158
+ .command("install")
159
+ .description("prepare project (no-op in repo checkout)")
160
+ .action(async () => {
161
+ console.log("Project files present; nothing to install.");
162
+ });
163
+
164
+ // Monitoring services management
165
+ const mon = program.command("mon").description("monitoring services management");
166
+
167
+ mon
168
+ .command("quickstart")
169
+ .description("complete setup (generate config, start monitoring services)")
170
+ .option("--demo", "demo mode", false)
171
+ .action(async () => {
172
+ const code1 = await runCompose(["run", "--rm", "sources-generator"]);
173
+ if (code1 !== 0) {
174
+ process.exitCode = code1;
175
+ return;
176
+ }
177
+ const code2 = await runCompose(["up", "-d"]);
178
+ if (code2 !== 0) process.exitCode = code2;
179
+ });
180
+
181
+ mon
182
+ .command("start")
183
+ .description("start monitoring services")
184
+ .action(async () => {
185
+ const code = await runCompose(["up", "-d"]);
186
+ if (code !== 0) process.exitCode = code;
187
+ });
188
+
189
+ mon
190
+ .command("stop")
191
+ .description("stop monitoring services")
192
+ .action(async () => {
193
+ const code = await runCompose(["down"]);
194
+ if (code !== 0) process.exitCode = code;
195
+ });
196
+
197
+ mon
198
+ .command("restart [service]")
199
+ .description("restart all monitoring services or specific service")
200
+ .action(async (service?: string) => {
201
+ const args = ["restart"];
202
+ if (service) args.push(service);
203
+ const code = await runCompose(args);
204
+ if (code !== 0) process.exitCode = code;
205
+ });
206
+
207
+ mon
208
+ .command("status")
209
+ .description("show monitoring services status")
210
+ .action(async () => {
211
+ const code = await runCompose(["ps"]);
212
+ if (code !== 0) process.exitCode = code;
213
+ });
214
+
215
+ mon
216
+ .command("logs [service]")
217
+ .option("-f, --follow", "follow logs", false)
218
+ .option("--tail <lines>", "number of lines to show from the end of logs", "all")
219
+ .description("show logs for all or specific monitoring service")
220
+ .action(async (service: string | undefined, opts: { follow: boolean; tail: string }) => {
221
+ const args: string[] = ["logs"];
222
+ if (opts.follow) args.push("-f");
223
+ if (opts.tail) args.push("--tail", opts.tail);
224
+ if (service) args.push(service);
225
+ const code = await runCompose(args);
226
+ if (code !== 0) process.exitCode = code;
227
+ });
228
+ mon
229
+ .command("health")
230
+ .description("health check for monitoring services")
231
+ .option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0)
232
+ .action(async (opts: { wait: number }) => {
233
+ const services: HealthService[] = [
234
+ { name: "Grafana", url: "http://localhost:3000/api/health" },
235
+ { name: "Prometheus", url: "http://localhost:59090/-/healthy" },
236
+ { name: "PGWatch (Postgres)", url: "http://localhost:58080/health" },
237
+ { name: "PGWatch (Prometheus)", url: "http://localhost:58089/health" },
238
+ ];
239
+
240
+ const waitTime = opts.wait || 0;
241
+ const maxAttempts = waitTime > 0 ? Math.ceil(waitTime / 5) : 1;
242
+
243
+ console.log("Checking service health...\n");
244
+
245
+ let allHealthy = false;
246
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
247
+ if (attempt > 1) {
248
+ console.log(`Retrying (attempt ${attempt}/${maxAttempts})...\n`);
249
+ await new Promise(resolve => setTimeout(resolve, 5000));
250
+ }
251
+
252
+ allHealthy = true;
253
+ for (const service of services) {
254
+ try {
255
+ const { stdout } = await execPromise(
256
+ `curl -sf -o /dev/null -w "%{http_code}" ${service.url}`,
257
+ { timeout: 5000 }
258
+ );
259
+ const code = stdout.trim();
260
+ if (code === "200") {
261
+ console.log(`✓ ${service.name}: healthy`);
262
+ } else {
263
+ console.log(`✗ ${service.name}: unhealthy (HTTP ${code})`);
264
+ allHealthy = false;
265
+ }
266
+ } catch (error) {
267
+ console.log(`✗ ${service.name}: unreachable`);
268
+ allHealthy = false;
269
+ }
270
+ }
271
+
272
+ if (allHealthy) {
273
+ break;
274
+ }
275
+ }
276
+
277
+ console.log("");
278
+ if (allHealthy) {
279
+ console.log("All services are healthy");
280
+ } else {
281
+ console.log("Some services are unhealthy");
282
+ process.exitCode = 1;
283
+ }
284
+ });
285
+ mon
286
+ .command("config")
287
+ .description("show monitoring services configuration")
288
+ .action(async () => {
289
+ const { fs, projectDir, composeFile, instancesFile } = resolvePaths();
290
+ console.log(`Project Directory: ${projectDir}`);
291
+ console.log(`Docker Compose File: ${composeFile}`);
292
+ console.log(`Instances File: ${instancesFile}`);
293
+ if (fs.existsSync(instancesFile)) {
294
+ console.log("\nInstances configuration:\n");
295
+ const text = fs.readFileSync(instancesFile, "utf8");
296
+ process.stdout.write(text);
297
+ if (!/\n$/.test(text)) console.log();
298
+ }
299
+ });
300
+ mon
301
+ .command("update-config")
302
+ .description("apply monitoring services configuration (generate sources)")
303
+ .action(async () => {
304
+ const code = await runCompose(["run", "--rm", "sources-generator"]);
305
+ if (code !== 0) process.exitCode = code;
306
+ });
307
+ mon
308
+ .command("update")
309
+ .description("update monitoring stack")
310
+ .action(async () => {
311
+ console.log("Updating PostgresAI monitoring stack...\n");
312
+
313
+ try {
314
+ // Check if we're in a git repo
315
+ const gitDir = path.resolve(process.cwd(), ".git");
316
+ if (!fs.existsSync(gitDir)) {
317
+ console.error("Not a git repository. Cannot update.");
318
+ process.exitCode = 1;
319
+ return;
320
+ }
321
+
322
+ // Fetch latest changes
323
+ console.log("Fetching latest changes...");
324
+ await execPromise("git fetch origin");
325
+
326
+ // Check current branch
327
+ const { stdout: branch } = await execPromise("git rev-parse --abbrev-ref HEAD");
328
+ const currentBranch = branch.trim();
329
+ console.log(`Current branch: ${currentBranch}`);
330
+
331
+ // Pull latest changes
332
+ console.log("Pulling latest changes...");
333
+ const { stdout: pullOut } = await execPromise("git pull origin " + currentBranch);
334
+ console.log(pullOut);
335
+
336
+ // Update Docker images
337
+ console.log("\nUpdating Docker images...");
338
+ const code = await runCompose(["pull"]);
339
+
340
+ if (code === 0) {
341
+ console.log("\n✓ Update completed successfully");
342
+ console.log("\nTo apply updates, restart monitoring services:");
343
+ console.log(" postgres-ai mon restart");
344
+ } else {
345
+ console.error("\n✗ Docker image update failed");
346
+ process.exitCode = 1;
347
+ }
348
+ } catch (error) {
349
+ const message = error instanceof Error ? error.message : String(error);
350
+ console.error(`Update failed: ${message}`);
351
+ process.exitCode = 1;
352
+ }
353
+ });
354
+ mon
355
+ .command("reset [service]")
356
+ .description("reset all or specific monitoring service")
357
+ .action(async (service?: string) => {
358
+ const rl = readline.createInterface({
359
+ input: process.stdin,
360
+ output: process.stdout,
361
+ });
362
+
363
+ const question = (prompt: string): Promise<string> =>
364
+ new Promise((resolve) => rl.question(prompt, resolve));
365
+
366
+ try {
367
+ if (service) {
368
+ // Reset specific service
369
+ console.log(`\nThis will stop '${service}', remove its volume, and restart it.`);
370
+ console.log("All data for this service will be lost!\n");
371
+
372
+ const answer = await question("Continue? (y/N): ");
373
+ if (answer.toLowerCase() !== "y") {
374
+ console.log("Cancelled");
375
+ rl.close();
376
+ return;
377
+ }
378
+
379
+ console.log(`\nStopping ${service}...`);
380
+ await runCompose(["stop", service]);
381
+
382
+ console.log(`Removing volume for ${service}...`);
383
+ await runCompose(["rm", "-f", "-v", service]);
384
+
385
+ console.log(`Restarting ${service}...`);
386
+ const code = await runCompose(["up", "-d", service]);
387
+
388
+ if (code === 0) {
389
+ console.log(`\n✓ Service '${service}' has been reset`);
390
+ } else {
391
+ console.error(`\n✗ Failed to restart '${service}'`);
392
+ process.exitCode = 1;
393
+ }
394
+ } else {
395
+ // Reset all services
396
+ console.log("\nThis will stop all services and remove all data!");
397
+ console.log("Volumes, networks, and containers will be deleted.\n");
398
+
399
+ const answer = await question("Continue? (y/N): ");
400
+ if (answer.toLowerCase() !== "y") {
401
+ console.log("Cancelled");
402
+ rl.close();
403
+ return;
404
+ }
405
+
406
+ console.log("\nStopping services and removing data...");
407
+ const downCode = await runCompose(["down", "-v"]);
408
+
409
+ if (downCode === 0) {
410
+ console.log("✓ Environment reset completed - all containers and data removed");
411
+ } else {
412
+ console.error("✗ Reset failed");
413
+ process.exitCode = 1;
414
+ }
415
+ }
416
+
417
+ rl.close();
418
+ } catch (error) {
419
+ rl.close();
420
+ const message = error instanceof Error ? error.message : String(error);
421
+ console.error(`Reset failed: ${message}`);
422
+ process.exitCode = 1;
423
+ }
424
+ });
425
+ mon
426
+ .command("clean")
427
+ .description("cleanup monitoring services artifacts")
428
+ .action(async () => {
429
+ console.log("Cleaning up Docker resources...\n");
430
+
431
+ try {
432
+ // Remove stopped containers
433
+ const { stdout: containers } = await execFilePromise("docker", ["ps", "-aq", "--filter", "status=exited"]);
434
+ if (containers.trim()) {
435
+ const containerIds = containers.trim().split('\n');
436
+ await execFilePromise("docker", ["rm", ...containerIds]);
437
+ console.log("✓ Removed stopped containers");
438
+ } else {
439
+ console.log("✓ No stopped containers to remove");
440
+ }
441
+
442
+ // Remove unused volumes
443
+ await execFilePromise("docker", ["volume", "prune", "-f"]);
444
+ console.log("✓ Removed unused volumes");
445
+
446
+ // Remove unused networks
447
+ await execFilePromise("docker", ["network", "prune", "-f"]);
448
+ console.log("✓ Removed unused networks");
449
+
450
+ // Remove dangling images
451
+ await execFilePromise("docker", ["image", "prune", "-f"]);
452
+ console.log("✓ Removed dangling images");
453
+
454
+ console.log("\nCleanup completed");
455
+ } catch (error) {
456
+ const message = error instanceof Error ? error.message : String(error);
457
+ console.error(`Error during cleanup: ${message}`);
458
+ process.exitCode = 1;
459
+ }
460
+ });
461
+ program
462
+ .command("shell <service>")
463
+ .description("open service shell")
464
+ .action(async (service: string) => {
465
+ const code = await runCompose(["exec", service, "/bin/sh"]);
466
+ if (code !== 0) process.exitCode = code;
467
+ });
468
+ mon
469
+ .command("check")
470
+ .description("monitoring services system readiness check")
471
+ .action(async () => {
472
+ const code = await runCompose(["ps"]);
473
+ if (code !== 0) process.exitCode = code;
474
+ });
475
+
476
+ // Instance management
477
+ program
478
+ .command("list-instances")
479
+ .description("list instances")
480
+ .action(async () => {
481
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
482
+ if (!fs.existsSync(instancesPath)) {
483
+ console.error(`instances.yml not found in ${process.cwd()}`);
484
+ process.exitCode = 1;
485
+ return;
486
+ }
487
+
488
+ try {
489
+ const content = fs.readFileSync(instancesPath, "utf8");
490
+ const instances = yaml.load(content) as Instance[] | null;
491
+
492
+ if (!instances || !Array.isArray(instances) || instances.length === 0) {
493
+ console.log("No instances configured");
494
+ console.log("");
495
+ console.log("To add an instance:");
496
+ console.log(" postgres-ai add-instance <connection-string> <name>");
497
+ console.log("");
498
+ console.log("Example:");
499
+ console.log(" postgres-ai add-instance 'postgresql://user:pass@host:5432/db' my-db");
500
+ return;
501
+ }
502
+
503
+ // Filter out demo placeholder
504
+ const filtered = instances.filter((inst) => inst.name && inst.name !== "target-database");
505
+
506
+ if (filtered.length === 0) {
507
+ console.log("No instances configured");
508
+ console.log("");
509
+ console.log("To add an instance:");
510
+ console.log(" postgres-ai add-instance <connection-string> <name>");
511
+ console.log("");
512
+ console.log("Example:");
513
+ console.log(" postgres-ai add-instance 'postgresql://user:pass@host:5432/db' my-db");
514
+ return;
515
+ }
516
+
517
+ for (const inst of filtered) {
518
+ console.log(`Instance: ${inst.name}`);
519
+ }
520
+ } catch (err) {
521
+ const message = err instanceof Error ? err.message : String(err);
522
+ console.error(`Error parsing instances.yml: ${message}`);
523
+ process.exitCode = 1;
524
+ }
525
+ });
526
+ program
527
+ .command("add-instance [connStr] [name]")
528
+ .description("add instance")
529
+ .action(async (connStr?: string, name?: string) => {
530
+ const file = path.resolve(process.cwd(), "instances.yml");
531
+ if (!connStr) {
532
+ console.error("Connection string required: postgresql://user:pass@host:port/db");
533
+ process.exitCode = 1;
534
+ return;
535
+ }
536
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
537
+ if (!m) {
538
+ console.error("Invalid connection string format");
539
+ process.exitCode = 1;
540
+ return;
541
+ }
542
+ const host = m[3];
543
+ const db = m[5];
544
+ const instanceName = name && name.trim() ? name.trim() : `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
545
+
546
+ // Check if instance already exists
547
+ try {
548
+ if (fs.existsSync(file)) {
549
+ const content = fs.readFileSync(file, "utf8");
550
+ const instances = yaml.load(content) as Instance[] | null || [];
551
+ if (Array.isArray(instances)) {
552
+ const exists = instances.some((inst) => inst.name === instanceName);
553
+ if (exists) {
554
+ console.error(`Instance '${instanceName}' already exists`);
555
+ process.exitCode = 1;
556
+ return;
557
+ }
558
+ }
559
+ }
560
+ } catch (err) {
561
+ // If YAML parsing fails, fall back to simple check
562
+ const content = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
563
+ if (new RegExp(`^- name: ${instanceName}$`, "m").test(content)) {
564
+ console.error(`Instance '${instanceName}' already exists`);
565
+ process.exitCode = 1;
566
+ return;
567
+ }
568
+ }
569
+
570
+ // Add new instance
571
+ const body = `- name: ${instanceName}\n conn_str: ${connStr}\n preset_metrics: full\n custom_metrics:\n is_enabled: true\n group: default\n custom_tags:\n env: production\n cluster: default\n node_name: ${instanceName}\n sink_type: ~sink_type~\n`;
572
+ const content = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
573
+ fs.appendFileSync(file, (content && !/\n$/.test(content) ? "\n" : "") + body, "utf8");
574
+ console.log(`Instance '${instanceName}' added`);
575
+ });
576
+ program
577
+ .command("remove-instance <name>")
578
+ .description("remove instance")
579
+ .action(async (name: string) => {
580
+ const file = path.resolve(process.cwd(), "instances.yml");
581
+ if (!fs.existsSync(file)) {
582
+ console.error("instances.yml not found");
583
+ process.exitCode = 1;
584
+ return;
585
+ }
586
+
587
+ try {
588
+ const content = fs.readFileSync(file, "utf8");
589
+ const instances = yaml.load(content) as Instance[] | null;
590
+
591
+ if (!instances || !Array.isArray(instances)) {
592
+ console.error("Invalid instances.yml format");
593
+ process.exitCode = 1;
594
+ return;
595
+ }
596
+
597
+ const filtered = instances.filter((inst) => inst.name !== name);
598
+
599
+ if (filtered.length === instances.length) {
600
+ console.error(`Instance '${name}' not found`);
601
+ process.exitCode = 1;
602
+ return;
603
+ }
604
+
605
+ fs.writeFileSync(file, yaml.dump(filtered), "utf8");
606
+ console.log(`Instance '${name}' removed`);
607
+ } catch (err) {
608
+ const message = err instanceof Error ? err.message : String(err);
609
+ console.error(`Error processing instances.yml: ${message}`);
610
+ process.exitCode = 1;
611
+ }
612
+ });
613
+ program
614
+ .command("test-instance <name>")
615
+ .description("test instance connectivity")
616
+ .action(async (name: string) => {
617
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
618
+ if (!fs.existsSync(instancesPath)) {
619
+ console.error("instances.yml not found");
620
+ process.exitCode = 1;
621
+ return;
622
+ }
623
+
624
+ try {
625
+ const content = fs.readFileSync(instancesPath, "utf8");
626
+ const instances = yaml.load(content) as Instance[] | null;
627
+
628
+ if (!instances || !Array.isArray(instances)) {
629
+ console.error("Invalid instances.yml format");
630
+ process.exitCode = 1;
631
+ return;
632
+ }
633
+
634
+ const instance = instances.find((inst) => inst.name === name);
635
+
636
+ if (!instance) {
637
+ console.error(`Instance '${name}' not found`);
638
+ process.exitCode = 1;
639
+ return;
640
+ }
641
+
642
+ if (!instance.conn_str) {
643
+ console.error(`Connection string not found for instance '${name}'`);
644
+ process.exitCode = 1;
645
+ return;
646
+ }
647
+
648
+ console.log(`Testing connection to '${name}'...`);
649
+
650
+ const { stdout, stderr } = await execFilePromise(
651
+ "psql",
652
+ [instance.conn_str, "-c", "SELECT version();", "--no-psqlrc"],
653
+ { timeout: 10000, env: { ...process.env, PAGER: 'cat' } }
654
+ );
655
+ console.log(`✓ Connection successful`);
656
+ console.log(stdout.trim());
657
+ } catch (error) {
658
+ const message = error instanceof Error ? error.message : String(error);
659
+ console.error(`✗ Connection failed: ${message}`);
660
+ process.exitCode = 1;
661
+ }
662
+ });
663
+
664
+ // Authentication and API key management
665
+ program
666
+ .command("auth")
667
+ .description("authenticate via browser and obtain API key")
668
+ .option("--port <port>", "local callback server port (default: random)", parseInt)
669
+ .option("--debug", "enable debug output")
670
+ .action(async (opts: { port?: number; debug?: boolean }) => {
671
+ const pkce = require("../lib/pkce");
672
+ const authServer = require("../lib/auth-server");
673
+
674
+ console.log("Starting authentication flow...\n");
675
+
676
+ // Generate PKCE parameters
677
+ const params = pkce.generatePKCEParams();
678
+
679
+ const rootOpts = program.opts<CliOptions>();
680
+
681
+ const apiBaseUrl = (rootOpts.apiBaseUrl || process.env.PGAI_API_BASE_URL || "https://postgres.ai/api/general/").replace(/\/$/, "");
682
+ const uiBaseUrl = (rootOpts.uiBaseUrl || process.env.PGAI_UI_BASE_URL || "https://console.postgres.ai").replace(/\/$/, "");
683
+
684
+ if (opts.debug) {
685
+ console.log(`Debug: Resolved API base URL: ${apiBaseUrl}`);
686
+ console.log(`Debug: Resolved UI base URL: ${uiBaseUrl}`);
687
+ }
688
+
689
+ try {
690
+ // Step 1: Start local callback server FIRST to get actual port
691
+ console.log("Starting local callback server...");
692
+ const requestedPort = opts.port || 0; // 0 = OS assigns available port
693
+ const callbackServer = authServer.createCallbackServer(requestedPort, params.state, 300000);
694
+
695
+ // Wait a bit for server to start and get port
696
+ await new Promise(resolve => setTimeout(resolve, 100));
697
+ const actualPort = callbackServer.getPort();
698
+ const redirectUri = `http://localhost:${actualPort}/callback`;
699
+
700
+ console.log(`Callback server listening on port ${actualPort}`);
701
+
702
+ // Step 2: Initialize OAuth session on backend
703
+ console.log("Initializing authentication session...");
704
+ const initData = JSON.stringify({
705
+ client_type: "cli",
706
+ state: params.state,
707
+ code_challenge: params.codeChallenge,
708
+ code_challenge_method: params.codeChallengeMethod,
709
+ redirect_uri: redirectUri,
710
+ });
711
+
712
+ // Build init URL by appending to the API base path (keep /api/general)
713
+ const initUrl = new URL(`${apiBaseUrl}/rpc/oauth_init`);
714
+
715
+ if (opts.debug) {
716
+ console.log(`Debug: Trying to POST to: ${initUrl.toString()}`);
717
+ console.log(`Debug: Request data: ${initData}`);
718
+ }
719
+
720
+ const initReq = http.request(
721
+ initUrl,
722
+ {
723
+ method: "POST",
724
+ headers: {
725
+ "Content-Type": "application/json",
726
+ "Content-Length": Buffer.byteLength(initData),
727
+ },
728
+ },
729
+ (res) => {
730
+ let data = "";
731
+ res.on("data", (chunk) => (data += chunk));
732
+ res.on("end", async () => {
733
+ if (res.statusCode !== 200) {
734
+ console.error(`Failed to initialize auth session: ${res.statusCode}`);
735
+ console.error(data);
736
+ callbackServer.server.close();
737
+ process.exitCode = 1;
738
+ return;
739
+ }
740
+
741
+ // Step 3: Open browser
742
+ const authUrl = `${uiBaseUrl}/cli/auth?state=${encodeURIComponent(params.state)}&code_challenge=${encodeURIComponent(params.codeChallenge)}&code_challenge_method=S256&redirect_uri=${encodeURIComponent(redirectUri)}`;
743
+
744
+ if (opts.debug) {
745
+ console.log(`Debug: Auth URL: ${authUrl}`);
746
+ }
747
+
748
+ console.log(`\nOpening browser for authentication...`);
749
+ console.log(`If browser does not open automatically, visit:\n${authUrl}\n`);
750
+
751
+ // Open browser (cross-platform)
752
+ const openCommand = process.platform === "darwin" ? "open" :
753
+ process.platform === "win32" ? "start" :
754
+ "xdg-open";
755
+ spawn(openCommand, [authUrl], { detached: true, stdio: "ignore" }).unref();
756
+
757
+ // Step 4: Wait for callback
758
+ console.log("Waiting for authorization...");
759
+ try {
760
+ const { code } = await callbackServer.promise;
761
+
762
+ // Step 5: Exchange code for token
763
+ console.log("\nExchanging authorization code for API token...");
764
+ const exchangeData = JSON.stringify({
765
+ authorization_code: code,
766
+ code_verifier: params.codeVerifier,
767
+ state: params.state,
768
+ });
769
+
770
+ const exchangeUrl = new URL(`${apiBaseUrl}/rpc/oauth_token_exchange`);
771
+ const exchangeReq = http.request(
772
+ exchangeUrl,
773
+ {
774
+ method: "POST",
775
+ headers: {
776
+ "Content-Type": "application/json",
777
+ "Content-Length": Buffer.byteLength(exchangeData),
778
+ },
779
+ },
780
+ (exchangeRes) => {
781
+ let exchangeData = "";
782
+ exchangeRes.on("data", (chunk) => (exchangeData += chunk));
783
+ exchangeRes.on("end", () => {
784
+ if (exchangeRes.statusCode !== 200) {
785
+ console.error(`Failed to exchange code for token: ${exchangeRes.statusCode}`);
786
+ console.error(exchangeData);
787
+ process.exitCode = 1;
788
+ return;
789
+ }
790
+
791
+ try {
792
+ const result = JSON.parse(exchangeData);
793
+ const apiToken = result.api_token;
794
+ const orgId = result.org_id;
795
+
796
+ // Step 6: Save token to config
797
+ config.writeConfig({
798
+ apiKey: apiToken,
799
+ baseUrl: apiBaseUrl,
800
+ orgId: orgId,
801
+ });
802
+
803
+ console.log("\nAuthentication successful!");
804
+ console.log(`API key saved to: ${config.getConfigPath()}`);
805
+ console.log(`Organization ID: ${orgId}`);
806
+ console.log(`\nYou can now use the CLI without specifying an API key.`);
807
+ } catch (err) {
808
+ const message = err instanceof Error ? err.message : String(err);
809
+ console.error(`Failed to parse response: ${message}`);
810
+ process.exitCode = 1;
811
+ }
812
+ });
813
+ }
814
+ );
815
+
816
+ exchangeReq.on("error", (err: Error) => {
817
+ console.error(`Exchange request failed: ${err.message}`);
818
+ process.exitCode = 1;
819
+ });
820
+
821
+ exchangeReq.write(exchangeData);
822
+ exchangeReq.end();
823
+
824
+ } catch (err) {
825
+ const message = err instanceof Error ? err.message : String(err);
826
+ console.error(`\nAuthentication failed: ${message}`);
827
+ process.exitCode = 1;
828
+ }
829
+ });
830
+ }
831
+ );
832
+
833
+ initReq.on("error", (err: Error) => {
834
+ console.error(`Failed to connect to API: ${err.message}`);
835
+ callbackServer.server.close();
836
+ process.exitCode = 1;
837
+ });
838
+
839
+ initReq.write(initData);
840
+ initReq.end();
841
+
842
+ } catch (err) {
843
+ const message = err instanceof Error ? err.message : String(err);
844
+ console.error(`Authentication error: ${message}`);
845
+ process.exitCode = 1;
846
+ }
847
+ });
848
+
849
+ program
850
+ .command("add-key <apiKey>")
851
+ .description("store API key")
852
+ .action(async (apiKey: string) => {
853
+ config.writeConfig({ apiKey });
854
+ console.log(`API key saved to ${config.getConfigPath()}`);
855
+ });
856
+
857
+ program
858
+ .command("show-key")
859
+ .description("show API key (masked)")
860
+ .action(async () => {
861
+ const cfg = config.readConfig();
862
+ if (!cfg.apiKey) {
863
+ console.log("No API key configured");
864
+ console.log(`\nTo authenticate, run: pgai auth`);
865
+ return;
866
+ }
867
+ const mask = (k: string): string => {
868
+ if (k.length <= 8) return "****";
869
+ if (k.length <= 16) return `${k.slice(0, 4)}${"*".repeat(k.length - 8)}${k.slice(-4)}`;
870
+ // For longer keys, show more of the beginning to help identify them
871
+ return `${k.slice(0, Math.min(12, k.length - 8))}${"*".repeat(Math.max(4, k.length - 16))}${k.slice(-4)}`;
872
+ };
873
+ console.log(`Current API key: ${mask(cfg.apiKey)}`);
874
+ if (cfg.orgId) {
875
+ console.log(`Organization ID: ${cfg.orgId}`);
876
+ }
877
+ console.log(`Config location: ${config.getConfigPath()}`);
878
+ });
879
+
880
+ program
881
+ .command("remove-key")
882
+ .description("remove API key")
883
+ .action(async () => {
884
+ // Check both new config and legacy config
885
+ const newConfigPath = config.getConfigPath();
886
+ const hasNewConfig = fs.existsSync(newConfigPath);
887
+ const legacyPath = path.resolve(process.cwd(), ".pgwatch-config");
888
+ const hasLegacyConfig = fs.existsSync(legacyPath) && fs.statSync(legacyPath).isFile();
889
+
890
+ if (!hasNewConfig && !hasLegacyConfig) {
891
+ console.log("No API key configured");
892
+ return;
893
+ }
894
+
895
+ // Remove from new config
896
+ if (hasNewConfig) {
897
+ config.deleteConfigKeys(["apiKey", "orgId"]);
898
+ }
899
+
900
+ // Remove from legacy config
901
+ if (hasLegacyConfig) {
902
+ try {
903
+ const content = fs.readFileSync(legacyPath, "utf8");
904
+ const filtered = content
905
+ .split(/\r?\n/)
906
+ .filter((l) => !/^api_key=/.test(l))
907
+ .join("\n")
908
+ .replace(/\n+$/g, "\n");
909
+ fs.writeFileSync(legacyPath, filtered, "utf8");
910
+ } catch (err) {
911
+ // If we can't read/write the legacy config, just skip it
912
+ console.warn(`Warning: Could not update legacy config: ${err instanceof Error ? err.message : String(err)}`);
913
+ }
914
+ }
915
+
916
+ console.log("API key removed");
917
+ console.log(`\nTo authenticate again, run: pgai auth`);
918
+ });
919
+ mon
920
+ .command("generate-grafana-password")
921
+ .description("generate Grafana password for monitoring services")
922
+ .action(async () => {
923
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
924
+
925
+ try {
926
+ // Generate secure password using openssl
927
+ const { stdout: password } = await execPromise(
928
+ "openssl rand -base64 12 | tr -d '\n'"
929
+ );
930
+ const newPassword = password.trim();
931
+
932
+ if (!newPassword) {
933
+ console.error("Failed to generate password");
934
+ process.exitCode = 1;
935
+ return;
936
+ }
937
+
938
+ // Read existing config
939
+ let configContent = "";
940
+ if (fs.existsSync(cfgPath)) {
941
+ const stats = fs.statSync(cfgPath);
942
+ if (stats.isDirectory()) {
943
+ console.error(".pgwatch-config is a directory, expected a file. Skipping read.");
944
+ } else {
945
+ configContent = fs.readFileSync(cfgPath, "utf8");
946
+ }
947
+ }
948
+
949
+ // Update or add grafana_password
950
+ const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
951
+ lines.push(`grafana_password=${newPassword}`);
952
+
953
+ // Write back
954
+ fs.writeFileSync(cfgPath, lines.filter(Boolean).join("\n") + "\n", "utf8");
955
+
956
+ console.log("✓ New Grafana password generated and saved");
957
+ console.log("\nNew credentials:");
958
+ console.log(" URL: http://localhost:3000");
959
+ console.log(" Username: monitor");
960
+ console.log(` Password: ${newPassword}`);
961
+ console.log("\nRestart Grafana to apply:");
962
+ console.log(" postgres-ai mon restart grafana");
963
+ } catch (error) {
964
+ const message = error instanceof Error ? error.message : String(error);
965
+ console.error(`Failed to generate password: ${message}`);
966
+ console.error("\nNote: This command requires 'openssl' to be installed");
967
+ process.exitCode = 1;
968
+ }
969
+ });
970
+ mon
971
+ .command("show-grafana-credentials")
972
+ .description("show Grafana credentials for monitoring services")
973
+ .action(async () => {
974
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
975
+ if (!fs.existsSync(cfgPath)) {
976
+ console.error("Configuration file not found. Run 'postgres-ai mon quickstart' first.");
977
+ process.exitCode = 1;
978
+ return;
979
+ }
980
+
981
+ const stats = fs.statSync(cfgPath);
982
+ if (stats.isDirectory()) {
983
+ console.error(".pgwatch-config is a directory, expected a file. Cannot read credentials.");
984
+ process.exitCode = 1;
985
+ return;
986
+ }
987
+
988
+ const content = fs.readFileSync(cfgPath, "utf8");
989
+ const lines = content.split(/\r?\n/);
990
+ let password = "";
991
+ for (const line of lines) {
992
+ const m = line.match(/^grafana_password=(.+)$/);
993
+ if (m) {
994
+ password = m[1].trim();
995
+ break;
996
+ }
997
+ }
998
+ if (!password) {
999
+ console.error("Grafana password not found in configuration");
1000
+ process.exitCode = 1;
1001
+ return;
1002
+ }
1003
+ console.log("\nGrafana credentials:");
1004
+ console.log(" URL: http://localhost:3000");
1005
+ console.log(" Username: monitor");
1006
+ console.log(` Password: ${password}`);
1007
+ console.log("");
1008
+ });
1009
+
1010
+ program.parseAsync(process.argv);
1011
+