@optima-chat/dev-skills 0.7.32 → 0.7.33

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.
@@ -70,12 +70,48 @@ export function parseDatabaseUrl(url: string): { user: string; password: string;
70
70
  }
71
71
 
72
72
  // ─── SSH tunnel ─────────────────────────────────────────────────────────────
73
+ // 端口被占不等于 tunnel 还能转发:AWS bastion idle 断连后,本地 ssh 进程还活着、
74
+ // 端口还 LISTEN,但流量过不去,所有后续查询会 hang 到客户端 timeout。
75
+ // 用 pg_isready 真去 ping postgres,超时就当 zombie,杀掉重建。
76
+ function isTunnelHealthy(localPort: number): boolean {
77
+ try {
78
+ execSync(`pg_isready -h localhost -p ${localPort} -t 3 -q`, { stdio: 'ignore' });
79
+ return true;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ function killOrphanTunnel(localPort: number): void {
86
+ try {
87
+ const pids = execSync(`lsof -ti:${localPort}`, { encoding: 'utf-8' }).trim();
88
+ if (pids) execSync(`kill -9 ${pids.split(/\s+/).join(' ')}`, { stdio: 'ignore' });
89
+ } catch { /* nothing to kill */ }
90
+ }
91
+
73
92
  export function setupSSHTunnel(dbHost: string, localPort: number): void {
74
- try { execSync(`lsof -ti:${localPort}`, { stdio: 'ignore' }); return; } catch { /* need tunnel */ }
93
+ let portInUse = false;
94
+ try { execSync(`lsof -ti:${localPort}`, { stdio: 'ignore' }); portInUse = true; } catch { /* free */ }
95
+
96
+ if (portInUse) {
97
+ if (isTunnelHealthy(localPort)) return;
98
+ console.log(`! SSH tunnel on port ${localPort} not responding (zombie), replacing...`);
99
+ killOrphanTunnel(localPort);
100
+ }
101
+
75
102
  const sshKeyPath = `${process.env.HOME}/.ssh/optima-ec2-key`;
76
103
  if (!fs.existsSync(sshKeyPath)) throw new Error(`SSH key not found: ${sshKeyPath}. Please obtain optima-ec2-key from xbfool.`);
77
104
  console.log(`Creating SSH tunnel: localhost:${localPort} -> ${EC2_HOST} -> ${dbHost}:5432`);
78
- execSync(`ssh -i ${sshKeyPath} -f -N -o StrictHostKeyChecking=no -L ${localPort}:${dbHost}:5432 ec2-user@${EC2_HOST}`, { stdio: 'inherit' });
105
+ // ServerAliveInterval/CountMax: 服务端 30s 没回应就让 ssh 自己退出(不留 zombie)
106
+ // ExitOnForwardFailure: 端口绑定失败立刻退出(不会黑悄悄继续跑)
107
+ // ConnectTimeout: 10s 不通就放弃(业界 ssh 默认 120s 太宽)
108
+ execSync(
109
+ `ssh -i ${sshKeyPath} -f -N -o StrictHostKeyChecking=no ` +
110
+ `-o ServerAliveInterval=30 -o ServerAliveCountMax=3 ` +
111
+ `-o ExitOnForwardFailure=yes -o ConnectTimeout=10 ` +
112
+ `-L ${localPort}:${dbHost}:5432 ec2-user@${EC2_HOST}`,
113
+ { stdio: 'inherit' }
114
+ );
79
115
  }
80
116
 
81
117
  // ─── psql ───────────────────────────────────────────────────────────────────
@@ -92,17 +92,50 @@ function parseDatabaseUrl(url) {
92
92
  return { user: decodeURIComponent(match[1]), password: decodeURIComponent(match[2]), host: match[3], port: parseInt(match[4], 10), database: match[5] };
93
93
  }
94
94
  // ─── SSH tunnel ─────────────────────────────────────────────────────────────
95
+ // 端口被占不等于 tunnel 还能转发:AWS bastion idle 断连后,本地 ssh 进程还活着、
96
+ // 端口还 LISTEN,但流量过不去,所有后续查询会 hang 到客户端 timeout。
97
+ // 用 pg_isready 真去 ping postgres,超时就当 zombie,杀掉重建。
98
+ function isTunnelHealthy(localPort) {
99
+ try {
100
+ (0, child_process_1.execSync)(`pg_isready -h localhost -p ${localPort} -t 3 -q`, { stdio: 'ignore' });
101
+ return true;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ function killOrphanTunnel(localPort) {
108
+ try {
109
+ const pids = (0, child_process_1.execSync)(`lsof -ti:${localPort}`, { encoding: 'utf-8' }).trim();
110
+ if (pids)
111
+ (0, child_process_1.execSync)(`kill -9 ${pids.split(/\s+/).join(' ')}`, { stdio: 'ignore' });
112
+ }
113
+ catch { /* nothing to kill */ }
114
+ }
95
115
  function setupSSHTunnel(dbHost, localPort) {
116
+ let portInUse = false;
96
117
  try {
97
118
  (0, child_process_1.execSync)(`lsof -ti:${localPort}`, { stdio: 'ignore' });
98
- return;
119
+ portInUse = true;
120
+ }
121
+ catch { /* free */ }
122
+ if (portInUse) {
123
+ if (isTunnelHealthy(localPort))
124
+ return;
125
+ console.log(`! SSH tunnel on port ${localPort} not responding (zombie), replacing...`);
126
+ killOrphanTunnel(localPort);
99
127
  }
100
- catch { /* need tunnel */ }
101
128
  const sshKeyPath = `${process.env.HOME}/.ssh/optima-ec2-key`;
102
129
  if (!fs.existsSync(sshKeyPath))
103
130
  throw new Error(`SSH key not found: ${sshKeyPath}. Please obtain optima-ec2-key from xbfool.`);
104
131
  console.log(`Creating SSH tunnel: localhost:${localPort} -> ${EC2_HOST} -> ${dbHost}:5432`);
105
- (0, child_process_1.execSync)(`ssh -i ${sshKeyPath} -f -N -o StrictHostKeyChecking=no -L ${localPort}:${dbHost}:5432 ec2-user@${EC2_HOST}`, { stdio: 'inherit' });
132
+ // ServerAliveInterval/CountMax: 服务端 30s 没回应就让 ssh 自己退出(不留 zombie)
133
+ // ExitOnForwardFailure: 端口绑定失败立刻退出(不会黑悄悄继续跑)
134
+ // ConnectTimeout: 10s 不通就放弃(业界 ssh 默认 120s 太宽)
135
+ (0, child_process_1.execSync)(`ssh -i ${sshKeyPath} -f -N -o StrictHostKeyChecking=no ` +
136
+ `-o ServerAliveInterval=30 -o ServerAliveCountMax=3 ` +
137
+ `-o ExitOnForwardFailure=yes -o ConnectTimeout=10 ` +
138
+ `-L ${localPort}:${dbHost}:5432 ec2-user@${EC2_HOST}`, { stdio: 'inherit' });
106
139
  }
107
140
  // ─── psql ───────────────────────────────────────────────────────────────────
108
141
  function findPsqlPath() {
File without changes
File without changes
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const db_utils_1 = require("./db-utils");
5
+ function parseArgs(args) {
6
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
7
+ console.log(`Usage: optima-grant-credits <email> --amount <n> [options]
8
+
9
+ Options:
10
+ --amount <n> Credits to grant (required)
11
+ --type <type> Credit type: bonus, referral (default: bonus)
12
+ --description <text> Description (optional)
13
+ --env <env> Environment: stage, prod (default: stage)
14
+ -h, --help Show this help`);
15
+ process.exit(0);
16
+ }
17
+ const email = args[0];
18
+ let amount = 0;
19
+ let type = 'bonus';
20
+ let description = null;
21
+ let env = 'stage';
22
+ for (let i = 1; i < args.length; i++) {
23
+ if (args[i] === '--amount' && args[i + 1]) {
24
+ amount = parseInt(args[++i], 10);
25
+ }
26
+ else if (args[i] === '--type' && args[i + 1]) {
27
+ type = args[++i];
28
+ }
29
+ else if (args[i] === '--description' && args[i + 1]) {
30
+ description = args[++i];
31
+ }
32
+ else if (args[i] === '--env' && args[i + 1]) {
33
+ env = args[++i];
34
+ }
35
+ }
36
+ if (amount < 1) {
37
+ console.error('--amount is required and must be >= 1');
38
+ process.exit(1);
39
+ }
40
+ if (!['bonus', 'referral'].includes(type)) {
41
+ console.error(`Unknown type: ${type}. Available: bonus, referral`);
42
+ process.exit(1);
43
+ }
44
+ if (!['stage', 'prod'].includes(env)) {
45
+ console.error('Env must be stage or prod (billing DB not available in CI)');
46
+ process.exit(1);
47
+ }
48
+ return { email, amount, type, description, env };
49
+ }
50
+ async function main() {
51
+ const { email, amount, type, description, env } = parseArgs(process.argv.slice(2));
52
+ const infisicalConfig = (0, db_utils_1.getInfisicalConfig)();
53
+ const token = (0, db_utils_1.getInfisicalToken)(infisicalConfig);
54
+ console.log(`\n🎁 Granting ${amount} ${type} credits to ${email} [${env.toUpperCase()}]\n`);
55
+ const userId = await (0, db_utils_1.resolveUserId)(email, env, infisicalConfig, token);
56
+ const billing = await (0, db_utils_1.connectBillingDB)(env, infisicalConfig, token);
57
+ const bq = billing.query;
58
+ const now = new Date().toISOString();
59
+ const safeUserId = (0, db_utils_1.escapeSQL)(userId);
60
+ const safeType = (0, db_utils_1.escapeSQL)(type);
61
+ const safeDesc = (0, db_utils_1.escapeSQL)(description || `Admin ${type} credit grant`);
62
+ console.log(`Inserting ${amount} ${type} credits...`);
63
+ const ledgerId = bq(`INSERT INTO credit_ledger (id, user_id, type, description, initial_amount, remaining, created_at) VALUES (concat('crd_${safeType}_', substr(md5(random()::text), 1, 16)), '${safeUserId}', '${safeType}', '${safeDesc}', ${amount}, ${amount}, '${now}') RETURNING id`);
64
+ console.log(`✓ Credits granted (ledger ID: ${ledgerId})`);
65
+ const balance = bq(`SELECT COALESCE(SUM(remaining), 0) FROM credit_ledger WHERE user_id='${safeUserId}' AND remaining > 0 AND (expires_at IS NULL OR expires_at > NOW())`);
66
+ console.log(`\n✅ Done! ${email} now has ${balance} total credits\n`);
67
+ }
68
+ main().catch(error => {
69
+ console.error('\n❌ Error:', error.message);
70
+ process.exit(1);
71
+ });
File without changes
File without changes
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optima-chat/dev-skills",
3
- "version": "0.7.32",
3
+ "version": "0.7.33",
4
4
  "description": "Claude Code Skills for Optima development team - cross-environment collaboration tools",
5
5
  "main": "index.js",
6
6
  "bin": {