import fs from 'fs'; import path from 'path'; import crypto from 'crypto'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export function loadEnvFile(filePath) { if (!fs.existsSync(filePath)) return {}; const out = {}; for (const line of fs.readFileSync(filePath, 'utf8').split(/\r?\n/)) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) continue; const i = trimmed.indexOf('='); if (i <= 0) continue; out[trimmed.slice(0, i).trim()] = trimmed.slice(i + 1).trim(); } return out; } export function loadTencentCredentials() { const root = path.join(__dirname, '..', '..'); const envPath = path.join(root, '.env.tencent'); const env = loadEnvFile(envPath); let secretId = process.env.TENCENT_SECRET_ID || env.TENCENT_SECRET_ID; let secretKey = process.env.TENCENT_SECRET_KEY || env.TENCENT_SECRET_KEY; const csvPath = path.join(root, 'SecretKey.csv'); if ((!secretId || !secretKey) && fs.existsSync(csvPath)) { const raw = fs.readFileSync(csvPath, 'utf8').trim(); const lines = raw.split(/\r?\n/); const header = lines[0].split(','); const values = lines[1].split(','); const idx = (name) => header.indexOf(name); secretId = secretId || values[idx('SecretId')]; secretKey = secretKey || values[idx('SecretKey')]; } if (!secretId || !secretKey) { throw new Error('Missing TENCENT_SECRET_ID / TENCENT_SECRET_KEY in .env.tencent'); } return { secretId, secretKey, env }; } function sha256hex(data) { return crypto.createHash('sha256').update(data, 'utf8').digest('hex'); } function hmacSha256(key, msg, encoding) { return crypto.createHmac('sha256', key).update(msg, 'utf8').digest(encoding); } export async function tc3Request({ secretId, secretKey, service, region, action, version, payload }) { const host = `${service}.tencentcloudapi.com`; const endpoint = `https://${host}`; const timestamp = Math.floor(Date.now() / 1000); const date = new Date(timestamp * 1000).toISOString().slice(0, 10); const body = JSON.stringify(payload); const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${host}\n`; const signedHeaders = 'content-type;host'; const canonicalRequest = ['POST', '/', '', canonicalHeaders, signedHeaders, sha256hex(body)].join('\n'); const credentialScope = `${date}/${service}/tc3_request`; const stringToSign = ['TC3-HMAC-SHA256', String(timestamp), credentialScope, sha256hex(canonicalRequest)].join('\n'); const secretDate = hmacSha256(`TC3${secretKey}`, date); const secretService = hmacSha256(secretDate, service); const secretSigning = hmacSha256(secretService, 'tc3_request'); const signature = hmacSha256(secretSigning, stringToSign, 'hex'); const authorization = `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; const resp = await fetch(endpoint, { method: 'POST', headers: { Authorization: authorization, 'Content-Type': 'application/json; charset=utf-8', Host: host, 'X-TC-Action': action, 'X-TC-Timestamp': String(timestamp), 'X-TC-Version': version, 'X-TC-Region': region, }, body, }); return resp.json(); } export async function runShellCommand(cred, region, instanceIds, script, timeout = 120) { const content = Buffer.from(script, 'utf8').toString('base64'); const run = await tc3Request({ ...cred, service: 'tat', region, action: 'RunCommand', version: '2020-10-28', payload: { InstanceIds: instanceIds, Content: content, CommandType: 'SHELL', Timeout: timeout, }, }); if (run.Response?.Error) { throw new Error(`RunCommand: ${run.Response.Error.Code} ${run.Response.Error.Message}`); } const invocationId = run.Response?.InvocationId; if (!invocationId) throw new Error('RunCommand: no InvocationId'); for (let i = 0; i < 60; i++) { await new Promise((r) => setTimeout(r, 2000)); const status = await tc3Request({ ...cred, service: 'tat', region, action: 'DescribeInvocations', version: '2020-10-28', payload: { InvocationIds: [invocationId] }, }); if (status.Response?.Error) { throw new Error(`DescribeInvocations: ${status.Response.Error.Code} ${status.Response.Error.Message}`); } const task = status.Response?.InvocationTaskSet?.[0]; if (!task) continue; const state = task.TaskStatus; if (state === 'SUCCESS' || state === 'FAILED' || state === 'TIMEOUT' || state === 'PARTIAL_FAILED') { const output = task.TaskResult?.Output ? Buffer.from(task.TaskResult.Output, 'base64').toString('utf8') : ''; const errOut = task.TaskResult?.ErrorInfo || ''; return { state, output, errOut, invocationId }; } } throw new Error(`Invocation ${invocationId} timed out waiting`); } export async function probeHttp(baseUrl, paths = ['/api/health']) { const results = []; for (const p of paths) { const url = `${baseUrl.replace(/\/+$/, '')}${p}`; try { const ctrl = new AbortController(); const t = setTimeout(() => ctrl.abort(), 8000); const resp = await fetch(url, { signal: ctrl.signal, redirect: 'follow' }); clearTimeout(t); const text = await resp.text(); results.push({ url, status: resp.status, ok: resp.ok, body: text.slice(0, 200) }); } catch (err) { results.push({ url, error: err.message || String(err) }); } } return results; } export async function testLogin(apiBase) { const url = `${apiBase.replace(/\/+$/, '')}/auth/token`; try { const resp = await fetch(url, { method: 'POST', redirect: 'manual', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'superadmin@meoo.local', password: 'SuperAdmin@123' }), }); const text = await resp.text(); return { url, status: resp.status, ok: resp.ok, body: text.slice(0, 300) }; } catch (err) { return { url, error: err.message || String(err) }; } }