refacor: 重构目录架构

This commit is contained in:
2026-09-16 22:43:21 +08:00
parent b37cdb0d54
commit 2754ed1e45
2762 changed files with 0 additions and 1529 deletions
+234
View File
@@ -0,0 +1,234 @@
import { execSync } from 'child_process';
import { existsSync, mkdirSync, readFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { Client } from 'ssh2';
import { printInfo, printSuccess } from './ui/render.js';
import type { ServerConfig } from './types.js';
import { getSshKeyPath } from './config.js';
export interface SSHExecResult {
stdout: string;
stderr: string;
code: number;
}
export interface SSHConnectResult {
conn: Client;
/** 本次连接使用的认证方式 */
authMethod: 'key' | 'password';
}
export function resolveKeyPath(config: ServerConfig): string {
return config.keyPath || getSshKeyPath();
}
export function ensureKeyPair(keyPath: string = getSshKeyPath()): { publicKey: string; privateKeyPath: string } {
if (existsSync(keyPath)) {
const publicKeyPath = `${keyPath}.pub`;
const publicKey = existsSync(publicKeyPath) ? readFileSync(publicKeyPath, 'utf8').trim() : '';
return { publicKey, privateKeyPath: keyPath };
}
const dir = join(homedir(), '.ssh');
mkdirSync(dir, { recursive: true });
execSync(`ssh-keygen -t ed25519 -f "${keyPath}" -N "" -C "ecom-deploy"`, { stdio: 'pipe' });
const publicKey = readFileSync(`${keyPath}.pub`, 'utf8').trim();
printSuccess(`SSH 密钥已生成: ${keyPath}.pub`);
return { publicKey, privateKeyPath: keyPath };
}
function sshConnect(config: ServerConfig, password?: string, keyPath?: string): Promise<Client> {
return new Promise((resolve, reject) => {
const conn = new Client();
const privateKeyPath = keyPath || resolveKeyPath(config);
const opts: any = {
host: config.host,
port: config.port,
username: config.username,
readyTimeout: 15000,
keepaliveInterval: 10000,
};
if (password) {
opts.password = password;
opts.tryKeyboard = true;
} else if (existsSync(privateKeyPath)) {
opts.privateKey = readFileSync(privateKeyPath, 'utf8');
}
conn.on('ready', () => resolve(conn));
conn.on('error', (err) => reject(err));
conn.on('keyboard-interactive', (_name, _instructions, _instructionsLang, _prompts, finish) => {
finish([password || '']);
});
conn.connect(opts);
});
}
export async function connectWithRetry(
config: ServerConfig,
password?: string,
onPassword?: () => Promise<string>,
): Promise<SSHConnectResult> {
let lastError: Error | null = null;
const keyPath = resolveKeyPath(config);
// 优先尝试密钥(只要本地密钥文件存在)
if (existsSync(keyPath)) {
try {
const conn = await sshConnect(config, undefined, keyPath);
return { conn, authMethod: 'key' };
} catch (e: any) {
lastError = e;
printInfo(`密钥认证失败 (${e.message}),尝试密码...`);
}
}
if (password || config.lastPassword) {
try {
const conn = await sshConnect(config, password || config.lastPassword);
return { conn, authMethod: 'password' };
} catch (e: any) {
lastError = e;
}
}
if (onPassword) {
password = await onPassword();
try {
const conn = await sshConnect(config, password);
return { conn, authMethod: 'password' };
} catch (e: any) {
lastError = e;
throw new Error(`SSH 连接失败: ${lastError?.message || '未知错误'}`);
}
}
throw new Error(`SSH 连接失败: ${lastError?.message || '无法连接'}`);
}
/** 远程 shell 初始化:passwd home 不可用时回退到 /tmp,避免 docker 等命令 mkdir home 失败 */
export const REMOTE_SHELL_INIT = `
PASSWD_HOME=$(getent passwd "$(whoami)" | cut -d: -f6)
FALLBACK_HOME="/tmp/ecom-deploy-$(whoami)"
if [ -n "$PASSWD_HOME" ] && [ -d "$PASSWD_HOME" ] && [ -w "$PASSWD_HOME" ]; then
export HOME="$PASSWD_HOME"
elif [ -n "$PASSWD_HOME" ] && mkdir -p "$PASSWD_HOME" 2>/dev/null && [ -w "$PASSWD_HOME" ]; then
export HOME="$PASSWD_HOME"
else
mkdir -p "$FALLBACK_HOME"
export HOME="$FALLBACK_HOME"
fi
`.trim();
export function wrapRemoteCommand(command: string): string {
return `${REMOTE_SHELL_INIT}\n${command}`;
}
export async function execRemote(conn: Client, command: string): Promise<SSHExecResult> {
return new Promise((resolve, reject) => {
let stdout = '';
let stderr = '';
conn.exec(wrapRemoteCommand(command), (err, stream) => {
if (err) return reject(err);
stream.on('close', (code: number) => {
resolve({ stdout, stderr, code });
});
stream.on('data', (data: Buffer) => {
stdout += data.toString();
});
stream.stderr.on('data', (data: Buffer) => {
stderr += data.toString();
});
});
});
}
export async function uploadFile(conn: Client, localPath: string, remotePath: string): Promise<void> {
return new Promise((resolve, reject) => {
conn.sftp((err, sftp) => {
if (err) return reject(new Error(`SFTP 连接失败: ${err.message}`));
sftp.fastPut(localPath, remotePath, (err2) => {
sftp.end();
if (err2) reject(new Error(`上传失败 ${localPath} → ${remotePath}: ${err2.message}`));
else resolve();
});
});
});
}
export async function ensureRemoteDir(conn: Client, dir: string): Promise<void> {
const { code, stderr } = await execRemote(conn, `mkdir -p "${dir}"`);
if (code !== 0) throw new Error(`创建远程目录失败 ${dir}: ${stderr}`);
}
/** 将公钥写入远程 authorized_keys(必须能创建 passwd 中的 home 目录,sshd 才认密钥) */
export async function uploadPublicKey(conn: Client, publicKey: string): Promise<void> {
const keyBody = publicKey.trim().split(/\s+/)[1] || publicKey.trim().slice(0, 32);
const escapedKey = publicKey.trim().replace(/'/g, `'\\''`);
const script = `
PASSWD_HOME=$(getent passwd "$(whoami)" | cut -d: -f6)
if [ -z "$PASSWD_HOME" ]; then echo "ERR: 无法解析用户 home 目录"; exit 1; fi
if ! mkdir -p "$PASSWD_HOME/.ssh" 2>/dev/null; then
echo "ERR: 无法创建 $PASSWD_HOME/.ssh"
echo "请在服务器执行: sudo mkdir -p $PASSWD_HOME && sudo chown $(whoami):$(whoami) $PASSWD_HOME"
exit 1
fi
chmod 700 "$PASSWD_HOME/.ssh"
AUTH_FILE="$PASSWD_HOME/.ssh/authorized_keys"
touch "$AUTH_FILE" && chmod 600 "$AUTH_FILE"
if grep -Fq '${keyBody}' "$AUTH_FILE" 2>/dev/null; then
echo "公钥已存在"
else
printf '%s\\n' '${escapedKey}' >> "$AUTH_FILE"
echo "公钥已写入"
fi
`.trim();
const { code, stdout, stderr } = await execRemote(conn, script);
if (code !== 0) {
throw new Error(`上传公钥失败: ${stderr || stdout}`);
}
if (stdout.includes('公钥已存在')) {
printInfo('公钥已存在,跳过');
} else {
printSuccess('公钥已上传到服务器');
}
}
/** 密码登录成功后自动安装公钥,供后续免密连接 */
export async function installKeyAfterPasswordAuth(conn: Client, config: ServerConfig): Promise<string> {
const { publicKey, privateKeyPath } = ensureKeyPair(resolveKeyPath(config));
await uploadPublicKey(conn, publicKey);
return privateKeyPath;
}
export async function setupSSHKey(config: ServerConfig, password: string): Promise<void> {
const { conn } = await connectWithRetry(config, password);
try {
await installKeyAfterPasswordAuth(conn, config);
config.authType = 'key';
config.keyPath = resolveKeyPath(config);
config.lastPassword = undefined;
printSuccess('SSH 密钥认证已配置完成');
} finally {
conn.end();
}
}
export async function testConnection(config: ServerConfig, password?: string): Promise<boolean> {
try {
const { conn } = await connectWithRetry(config, password);
conn.end();
return true;
} catch {
return false;
}
}