postgresai 0.11.0-alpha.1 → 0.11.0-alpha.11

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