import { EC2Client, RunInstancesCommand, DescribeInstancesCommand, CreateTagsCommand, StopInstancesCommand, StartInstancesCommand, RebootInstancesCommand, TerminateInstancesCommand, } from '@aws-sdk/client-ec2'; import { getDb } from '../db'; import { generateUserData, generateWindowsPassword } from './userdata'; import { encrypt } from '../utils/crypto'; import { terminateSessionsByInstance, deleteSessionsByInstance } from './connection-manager'; /** Shape returned from aws_config table */ interface AwsConfig { access_key: string; secret_key_encrypted: string; region: string; ami_id: string; instance_type: string | null; key_pair_name: string | null; security_group_id: string | null; subnet_id: string | null; } /** Shape of an instance row from the DB */ export interface InstanceRecord { id: number; user_id: number; ec2_instance_id: string; machine_guid: string; status: string; public_ip: string | null; rdp_username: string | null; rdp_password_encrypted: string | null; started_at: number | null; expires_at: number | null; created_at: number; } /** Result returned after launching an instance */ export interface LaunchResult { instanceId: number; ec2InstanceId: string; machineGuid: string; status: string; } // --------------------------------------------------------------------------- // Internal helpers // --------------------------------------------------------------------------- /** Build an EC2Client from the stored AWS configuration. */ function buildEc2Client(config: AwsConfig, decryptFn: (s: string) => string): EC2Client { const secretKey = decryptFn(config.secret_key_encrypted); return new EC2Client({ region: config.region, credentials: { accessKeyId: config.access_key, secretAccessKey: secretKey, }, }); } /** Write an instance action log entry. */ function logInstanceAction( userId: number, username: string, ec2InstanceId: string | null, action: string, durationSeconds?: number, ): void { try { const db = getDb(); db.prepare( 'INSERT INTO instance_logs (user_id, username, ec2_instance_id, action, duration_seconds) VALUES (?, ?, ?, ?, ?)' ).run(userId, username, ec2InstanceId, action, durationSeconds ?? null); } catch (err: any) { console.error('[InstanceLog] 写入日志失败:', err.message); } } /** Load the single AWS config row. Throws if not configured. */ export function loadAwsConfig(): AwsConfig { const db = getDb(); const config = db .prepare( 'SELECT access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id FROM aws_config ORDER BY id DESC LIMIT 1', ) .get() as AwsConfig | undefined; if (!config || !config.access_key || !config.secret_key_encrypted || !config.region || !config.ami_id) { throw new Error('请先配置 AWS 参数'); } return config; } /** Read max_instance_lifetime_minutes from system_settings (default 1440 = 24h). */ export function getMaxLifetimeMinutes(): number { const db = getDb(); const row = db .prepare("SELECT value FROM system_settings WHERE key = 'max_instance_lifetime_minutes'") .get() as { value: string } | undefined; if (row && row.value) { const parsed = Number(row.value); if (!isNaN(parsed) && parsed > 0) return parsed; } return 1440; } /** * Poll DescribeInstances until the instance reaches the desired state or * the timeout is exceeded. */ async function waitForState( ec2: EC2Client, ec2InstanceId: string, desiredState: string, timeoutMs = 300_000, intervalMs = 5_000, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { const desc = await ec2.send( new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }), ); const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name; if (state === desiredState) return; } catch (err: any) { // AWS eventual consistency: instance ID may not be visible yet const code = err.Code ?? err.name ?? ''; if ( code === 'InvalidInstanceID.NotFound' || err.message?.includes('does not exist') ) { console.warn( `[waitForState] 实例 ${ec2InstanceId} 尚未可见,等待重试...`, ); } else { throw err; } } await new Promise((r) => setTimeout(r, intervalMs)); } throw new Error(`实例 ${ec2InstanceId} 未在超时时间内进入 ${desiredState} 状态`); } // --------------------------------------------------------------------------- // Public API // --------------------------------------------------------------------------- /** * Launch a new EC2 instance for the given user with the specified MachineGuid. * * Steps: * 1. Read AWS config from DB * 2. Call RunInstances with UserData script * 3. Wait for "running" state * 4. Retrieve public IP via DescribeInstances * 5. Retrieve Windows password via GetPasswordData * 6. Encrypt RDP password and persist instance record * 7. Return full instance info including RDP credentials */ export async function launchInstance( userId: number, machineGuid: string, username: string, /** Injected decrypt function – defaults to the crypto util */ decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): Promise { const config = loadAwsConfig(); const ec2 = buildEc2Client(config, decryptFn); // Generate admin password const adminPassword = generateWindowsPassword(); // 1. Build RunInstances params const userData = generateUserData(machineGuid, adminPassword); const runParams: any = { ImageId: config.ami_id, InstanceType: config.instance_type || 't3.medium', MinCount: 1, MaxCount: 1, UserData: userData, BlockDeviceMappings: [ { DeviceName: '/dev/sda1', Ebs: { VolumeType: 'gp3', DeleteOnTermination: true, }, }, ], NetworkInterfaces: [ { DeviceIndex: 0, AssociatePublicIpAddress: true, Ipv6AddressCount: 1, SubnetId: config.subnet_id || undefined, Groups: config.security_group_id ? [config.security_group_id] : undefined, }, ], MetadataOptions: { HttpTokens: 'required', HttpEndpoint: 'enabled', }, }; if (config.key_pair_name) runParams.KeyName = config.key_pair_name; // 2. Launch let ec2InstanceId: string; try { const runResult = await ec2.send(new RunInstancesCommand(runParams)); ec2InstanceId = runResult.Instances?.[0]?.InstanceId ?? ''; if (!ec2InstanceId) { throw new Error('RunInstances 未返回实例 ID'); } } catch (err: any) { throw new Error(`EC2 实例启动失败: ${err.message}`); } // Insert a pending record immediately with password const db = getDb(); const now = Math.floor(Date.now() / 1000); const encryptedPassword = encrypt(adminPassword); const insertResult = db .prepare( `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, rdp_username, rdp_password_encrypted, created_at) VALUES (?, ?, ?, 'pending', 'Administrator', ?, ?)`, ) .run(userId, ec2InstanceId, machineGuid, encryptedPassword, now); const instanceId = Number(insertResult.lastInsertRowid); // Tag the instance with Name const nameTag = `BIFA-${username}-${now}-${userId}`; ec2.send(new CreateTagsCommand({ Resources: [ec2InstanceId], Tags: [{ Key: 'Name', Value: nameTag }], })).catch((err) => { console.error(`[LaunchInstance] 打 Name Tag 失败:`, err.message); }); logInstanceAction(userId, username, ec2InstanceId, 'launch'); // 3. Async: wait for running, get IP, update record finalizeInstance(instanceId, ec2InstanceId, ec2).catch((err) => { console.error(`[LaunchInstance] 异步完成实例 ${instanceId} 失败:`, err.message); const db2 = getDb(); db2.prepare("UPDATE instances SET status = 'terminated' WHERE id = ?").run(instanceId); }); return { instanceId, ec2InstanceId, machineGuid, status: 'pending', }; } /** * Async background work after RunInstances: wait for running, get IP/password, set expires_at. */ async function finalizeInstance( instanceId: number, ec2InstanceId: string, ec2: EC2Client, ): Promise { // Wait for running await waitForState(ec2, ec2InstanceId, 'running'); // Get public IP const descResult = await ec2.send( new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }), ); const publicIp = descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? ''; // Compute expires_at from NOW (when instance is actually running) const runningNow = Math.floor(Date.now() / 1000); const maxLifetimeMinutes = getMaxLifetimeMinutes(); const expiresAt = runningNow + maxLifetimeMinutes * 60; const db = getDb(); db.prepare( `UPDATE instances SET status = 'running', public_ip = ?, started_at = ?, expires_at = ? WHERE id = ?`, ).run(publicIp, runningNow, expiresAt, instanceId); console.log(`[LaunchInstance] 实例 ${instanceId} (${ec2InstanceId}) 已就绪`); } /** * Stop (shut down) a running EC2 instance. */ export async function stopInstance( instanceId: number, decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): Promise { const db = getDb(); const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as | (Pick) | undefined; if (!row) throw new Error('实例不存在'); if (row.status !== 'running') throw new Error('只能关机运行中的实例'); const config = loadAwsConfig(); const ec2 = buildEc2Client(config, decryptFn); await ec2.send(new StopInstancesCommand({ InstanceIds: [row.ec2_instance_id] })); // Clean up all active RDP sessions for this instance terminateSessionsByInstance(row.ec2_instance_id); db.prepare("UPDATE instances SET status = 'stopped', public_ip = NULL WHERE id = ?").run(instanceId); const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined; const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined; logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'stop', duration); } /** * Start a previously stopped EC2 instance. */ export async function startInstance( instanceId: number, decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): Promise { const db = getDb(); const row = db.prepare('SELECT ec2_instance_id, status, user_id FROM instances WHERE id = ?').get(instanceId) as | Pick | undefined; if (!row) throw new Error('实例不存在'); if (row.status !== 'stopped') throw new Error('只能启动已停止的实例'); const config = loadAwsConfig(); const ec2 = buildEc2Client(config, decryptFn); await ec2.send(new StartInstancesCommand({ InstanceIds: [row.ec2_instance_id] })); db.prepare("UPDATE instances SET status = 'running' WHERE id = ?").run(instanceId); const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined; logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'start'); // Async: wait for running and re-fetch public IP (async () => { try { await waitForState(ec2, row.ec2_instance_id, 'running'); const descResult = await ec2.send( new DescribeInstancesCommand({ InstanceIds: [row.ec2_instance_id] }), ); const publicIp = descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? ''; db.prepare('UPDATE instances SET public_ip = ? WHERE id = ?').run(publicIp || null, instanceId); console.log(`[StartInstance] 实例 ${instanceId} 新公网 IP: ${publicIp}`); } catch (err: any) { console.error(`[StartInstance] 获取实例 ${instanceId} 公网 IP 失败:`, err.message); } })(); } /** * Reboot a running EC2 instance. */ export async function rebootInstance( instanceId: number, decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): Promise { const db = getDb(); const row = db.prepare('SELECT ec2_instance_id, status FROM instances WHERE id = ?').get(instanceId) as | Pick | undefined; if (!row) throw new Error('实例不存在'); if (row.status !== 'running') throw new Error('只能重启运行中的实例'); const config = loadAwsConfig(); const ec2 = buildEc2Client(config, decryptFn); await ec2.send(new RebootInstancesCommand({ InstanceIds: [row.ec2_instance_id] })); // Status stays 'running' after reboot } /** * Terminate (destroy) an EC2 instance. */ export async function terminateInstance( instanceId: number, decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): Promise { const db = getDb(); const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as | (Pick) | undefined; if (!row) throw new Error('实例不存在'); if (row.status === 'terminated') throw new Error('实例已终止'); const config = loadAwsConfig(); const ec2 = buildEc2Client(config, decryptFn); await ec2.send(new TerminateInstancesCommand({ InstanceIds: [row.ec2_instance_id] })); // Clean up all active RDP sessions for this instance terminateSessionsByInstance(row.ec2_instance_id); const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined; const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined; logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'terminate', duration); // Delete session records before deleting instance to avoid FK constraint violation deleteSessionsByInstance(row.ec2_instance_id); db.prepare('DELETE FROM instances WHERE id = ?').run(instanceId); } /** * Get RDP connection info for an instance. */ export function getInstanceRdpInfo( instanceId: number, decryptFn: (s: string) => string = require('../utils/crypto').decrypt, ): { publicIp: string; rdpUsername: string; rdpPassword: string } { const db = getDb(); const row = db .prepare('SELECT public_ip, rdp_username, rdp_password_encrypted FROM instances WHERE id = ?') .get(instanceId) as Pick | undefined; if (!row) throw new Error('实例不存在'); let rdpPassword = ''; if (row.rdp_password_encrypted) { rdpPassword = decryptFn(row.rdp_password_encrypted); } return { publicIp: row.public_ip ?? '', rdpUsername: row.rdp_username ?? '', rdpPassword, }; }