postgresai 0.11.0-alpha.7 → 0.11.0-alpha.9

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