feat: 初始化 Claude Code 管理平台项目

实现了基于 Web 的 Claude Code 实例管理功能:

## 功能特性
- 🔐 用户认证:JWT 登录验证
- 🚀 实例管理:创建、启动、停止、删除 Claude Code 实例
- 📊 实时监控:CPU、内存、运行时间统计
- 📝 日志管理:Winston 日志系统
- 🔌 PM2 集成:稳定的进程管理
- 🌐 Web 界面:Vue 3 + Element Plus

## 技术栈
- 后端:Node.js + Express + TypeScript + PM2
- 前端:Vue 3 + TypeScript + Vite + Element Plus
- 认证:JWT
- 存储:文件系统(JSON)

## 项目结构
- Monorepo 结构,前后端分离
- 完整的类型定义
- 模块化设计
- 详细的开发文档

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-02 22:57:33 +08:00
commit ed626e74dc
46 files changed
+11882

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
plugins: ['@typescript-eslint'],
env: {
node: true,
es6: true,
},
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'no-console': 'off',
},
};
+7
View File
@@ -0,0 +1,7 @@
node_modules/
dist/
*.log
.env
.DS_Store
*.tsbuildinfo
coverage/
+47
View File
@@ -0,0 +1,47 @@
{
"name": "cc-cloud-backend",
"version": "1.0.0",
"description": "CC Cloud 后端服务",
"main": "dist/app.js",
"scripts": {
"dev": "tsx watch src/app.ts",
"build": "tsc",
"start": "node dist/app.js",
"lint": "eslint src --ext .ts",
"lint:fix": "eslint src --ext .ts --fix",
"typecheck": "tsc --noEmit"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"jsonwebtoken": "^9.0.2",
"bcrypt": "^5.1.1",
"pm2": "^5.3.0",
"socket.io": "^4.6.1",
"ws": "^8.16.0",
"axios": "^1.6.5",
"winston": "^3.11.0",
"winston-daily-rotate-file": "^4.7.1",
"detect-port": "^2.0.0",
"uuid": "^9.0.1",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/cors": "^2.8.17",
"@types/jsonwebtoken": "^9.0.5",
"@types/bcrypt": "^5.0.2",
"@types/node": "^20.11.5",
"@types/ws": "^8.5.10",
"@types/uuid": "^9.0.7",
"@typescript-eslint/eslint-plugin": "^6.19.1",
"@typescript-eslint/parser": "^6.19.1",
"eslint": "^8.56.0",
"tsx": "^4.7.0",
"typescript": "^5.3.3"
}
}
+153
View File
@@ -0,0 +1,153 @@
import express from 'express';
import cors from 'cors';
import { createServer } from 'http';
import { Server as SocketIOServer } from 'socket.io';
import { config } from './config';
import logger from './utils/logger';
import { initStorage } from './utils/storage';
import { initDefaultUser } from './controllers/auth.controller';
import { initInstanceService } from './services/instance.service';
import { authMiddleware, optionalAuth } from './middleware/auth.middleware';
import { errorMiddleware, notFoundMiddleware } from './middleware/error.middleware';
import {
login,
verifyToken,
} from './controllers/auth.controller';
import {
createInstanceHandler,
startInstanceHandler,
stopInstanceHandler,
deleteInstanceHandler,
listInstancesHandler,
getInstanceHandler,
getInstanceStatusHandler,
createInstanceSchema,
} from './controllers/instance.controller';
import { validate } from './middleware/validate.middleware';
// 创建 Express 应用
const app = express();
const httpServer = createServer(app);
// 创建 Socket.IO 服务器
const io = new SocketIOServer(httpServer, {
cors: {
origin: config.corsOrigin,
credentials: true,
},
});
// 中间件
app.use(cors({
origin: config.corsOrigin,
credentials: true,
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 请求日志
app.use((req, res, next) => {
logger.info(`${req.method} ${req.path}`);
next();
});
// 认证路由(不需要认证)
app.post('/api/auth/login', login);
app.get('/api/auth/verify', authMiddleware, verifyToken);
// 实例路由(需要认证)
app.post('/api/instances/start', authMiddleware, validate(createInstanceSchema), createInstanceHandler);
app.get('/api/instances', authMiddleware, listInstancesHandler);
app.get('/api/instances/:instanceId', authMiddleware, getInstanceHandler);
app.post('/api/instances/:instanceId/start', authMiddleware, startInstanceHandler);
app.post('/api/instances/:instanceId/stop', authMiddleware, stopInstanceHandler);
app.delete('/api/instances/:instanceId', authMiddleware, deleteInstanceHandler);
app.get('/api/instances/:instanceId/status', authMiddleware, getInstanceStatusHandler);
// Socket.IO 认证中间件
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
return next(new Error('认证失败'));
}
try {
const jwt = require('jsonwebtoken');
const decoded = jwt.verify(token, config.jwtSecret);
socket.data.user = decoded;
next();
} catch (error) {
next(new Error('无效的认证令牌'));
}
});
// Socket.IO 连接处理
io.on('connection', (socket) => {
logger.info('WebSocket 连接已建立', { socketId: socket.id });
socket.on('join-instance', (instanceId: string) => {
socket.join(`instance:${instanceId}`);
logger.info('加入实例房间', { socketId: socket.id, instanceId });
});
socket.on('leave-instance', (instanceId: string) => {
socket.leave(`instance:${instanceId}`);
logger.info('离开实例房间', { socketId: socket.id, instanceId });
});
socket.on('disconnect', () => {
logger.info('WebSocket 连接已断开', { socketId: socket.id });
});
});
// 导出 io 实例供其他模块使用
export { io };
// 404 处理
app.use(notFoundMiddleware);
// 错误处理
app.use(errorMiddleware);
// 初始化函数
export async function initialize() {
try {
// 初始化存储
await initStorage();
logger.info('存储初始化完成');
// 初始化默认用户
await initDefaultUser();
logger.info('默认用户初始化完成');
// 初始化实例服务
await initInstanceService();
logger.info('实例服务初始化完成');
} catch (error) {
logger.error('初始化失败', error);
throw error;
}
}
// 启动服务器
export async function startServer() {
await initialize();
httpServer.listen(config.port, () => {
logger.info(`服务器已启动`, {
port: config.port,
env: config.nodeEnv,
});
});
}
// 如果直接运行此文件
if (require.main === module) {
startServer().catch((error) => {
logger.error('服务器启动失败', error);
process.exit(1);
});
}
export default app;
+38
View File
@@ -0,0 +1,38 @@
import dotenv from 'dotenv';
import path from 'path';
dotenv.config();
export const config = {
// 服务器配置
port: parseInt(process.env.PORT || '3000'),
nodeEnv: process.env.NODE_ENV || 'development',
// JWT 配置
jwtSecret: process.env.JWT_SECRET || 'your-secret-key-change-this',
jwtExpiresIn: '7d',
// 用户认证
adminUsername: process.env.ADMIN_USERNAME || 'admin',
adminPassword: process.env.ADMIN_PASSWORD || 'admin123',
// PM2 配置
pm2Home: process.env.PM2_HOME || path.join(process.env.HOME || '', '.pm2'),
// 实例配置
instancePortRangeStart: parseInt(process.env.INSTANCE_PORT_RANGE_START || '4000'),
instancePortRangeEnd: parseInt(process.env.INSTANCE_PORT_RANGE_END || '4999'),
maxInstances: parseInt(process.env.MAX_INSTANCES || '10'),
// 日志配置
logLevel: process.env.LOG_LEVEL || 'info',
logDir: process.env.LOG_DIR || path.join(process.cwd(), 'data', 'logs'),
// 数据存储
dataDir: process.env.DATA_DIR || path.join(process.cwd(), 'data'),
instanceConfigDir: process.env.INSTANCE_CONFIG_DIR ||
path.join(process.cwd(), 'data', 'instances'),
// CORS 配置
corsOrigin: process.env.CORS_ORIGIN || 'http://localhost:5173',
};
@@ -0,0 +1,77 @@
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { config } from '../config';
import type { User, LoginRequest, LoginResponse, JwtPayload } from '../types';
import logger from '../utils/logger';
// 模拟用户存储(实际项目中应该使用数据库)
const users: Map<string, User> = new Map();
// 初始化默认管理员用户
export async function initDefaultUser() {
const userId = uuidv4();
const passwordHash = await bcrypt.hash(config.adminPassword, 10);
const defaultUser: User = {
id: userId,
username: config.adminUsername,
passwordHash,
createdAt: new Date(),
};
users.set(userId, defaultUser);
logger.info('默认管理员用户已创建', { username: config.adminUsername });
}
export async function login(req: Request, res: Response) {
try {
const { username, password }: LoginRequest = req.body;
// 查找用户
const user = Array.from(users.values()).find(u => u.username === username);
if (!user) {
return res.status(401).json({ error: '用户名或密码错误' });
}
// 验证密码
const isValid = await bcrypt.compare(password, user.passwordHash);
if (!isValid) {
return res.status(401).json({ error: '用户名或密码错误' });
}
// 生成 JWT
const payload: JwtPayload = {
userId: user.id,
username: user.username,
};
const token = jwt.sign(payload, config.jwtSecret, {
expiresIn: config.jwtExpiresIn,
});
const response: LoginResponse = {
token,
user: {
id: user.id,
username: user.username,
createdAt: user.createdAt,
},
};
logger.info('用户登录成功', { username });
res.json(response);
} catch (error) {
logger.error('登录失败', error);
res.status(500).json({ error: '登录失败' });
}
}
export async function verifyToken(req: Request, res: Response) {
// 如果能到达这里,说明 token 已经被 authMiddleware 验证过
res.json({
valid: true,
user: req.user,
});
}
@@ -0,0 +1,116 @@
import { Request, Response } from 'express';
import { z } from 'zod';
import {
createInstance,
startInstance,
stopInstance,
removeInstance,
getAllInstances,
getInstance,
} from '../services/instance.service';
import logger from '../utils/logger';
// 验证 schema
const createInstanceSchema = z.object({
body: z.object({
name: z.string().min(1, '实例名称不能为空'),
config: z.object({
model: z.string().min(1, '模型不能为空'),
apiKey: z.string().optional(),
workingDir: z.string().min(1, '工作目录不能为空'),
port: z.number().int().min(1).max(65535).optional(),
maxMemory: z.number().int().positive().optional(),
env: z.record(z.string()).optional(),
}),
}),
});
export async function createInstanceHandler(req: Request, res: Response) {
try {
const instance = await createInstance(req.body);
res.status(201).json({ instance });
} catch (error: any) {
logger.error('创建实例失败', error);
res.status(400).json({ error: error.message });
}
}
export async function startInstanceHandler(req: Request, res: Response) {
try {
const { instanceId } = req.params;
await startInstance(instanceId);
res.json({ success: true, message: '实例启动成功' });
} catch (error: any) {
logger.error('启动实例失败', error);
res.status(400).json({ error: error.message });
}
}
export async function stopInstanceHandler(req: Request, res: Response) {
try {
const { instanceId } = req.params;
await stopInstance(instanceId);
res.json({ success: true, message: '实例停止成功' });
} catch (error: any) {
logger.error('停止实例失败', error);
res.status(400).json({ error: error.message });
}
}
export async function deleteInstanceHandler(req: Request, res: Response) {
try {
const { instanceId } = req.params;
await removeInstance(instanceId);
res.json({ success: true, message: '实例删除成功' });
} catch (error: any) {
logger.error('删除实例失败', error);
res.status(400).json({ error: error.message });
}
}
export async function listInstancesHandler(req: Request, res: Response) {
try {
const instances = await getAllInstances();
res.json({ instances });
} catch (error: any) {
logger.error('获取实例列表失败', error);
res.status(500).json({ error: '获取实例列表失败' });
}
}
export async function getInstanceHandler(req: Request, res: Response) {
try {
const { instanceId } = req.params;
const instance = await getInstance(instanceId);
if (!instance) {
return res.status(404).json({ error: '实例不存在' });
}
res.json({ instance });
} catch (error: any) {
logger.error('获取实例失败', error);
res.status(500).json({ error: '获取实例失败' });
}
}
export async function getInstanceStatusHandler(req: Request, res: Response) {
try {
const { instanceId } = req.params;
const instance = await getInstance(instanceId);
if (!instance) {
return res.status(404).json({ error: '实例不存在' });
}
res.json({
status: instance.status,
stats: instance.stats,
});
} catch (error: any) {
logger.error('获取实例状态失败', error);
res.status(500).json({ error: '获取实例状态失败' });
}
}
export { createInstanceSchema };
+53
View File
@@ -0,0 +1,53 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { config } from '../config';
import type { JwtPayload } from '../types';
import logger from '../utils/logger';
// 扩展 Express Request 类型
declare global {
namespace Express {
interface Request {
user?: JwtPayload;
}
}
}
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: '未提供认证令牌' });
}
const token = authHeader.replace('Bearer ', '');
try {
const decoded = jwt.verify(token, config.jwtSecret) as JwtPayload;
req.user = decoded;
next();
} catch (error: any) {
logger.error('Token 验证失败', error);
return res.status(401).json({ error: '无效的认证令牌' });
}
}
// 可选认证(不强制要求登录)
export function optionalAuth(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return next();
}
const token = authHeader.replace('Bearer ', '');
try {
const decoded = jwt.verify(token, config.jwtSecret) as JwtPayload;
req.user = decoded;
} catch (error) {
// 忽略错误,继续处理请求
}
next();
}
@@ -0,0 +1,28 @@
import { Request, Response, NextFunction } from 'express';
import logger from '../utils/logger';
export function errorMiddleware(
error: Error,
req: Request,
res: Response,
next: NextFunction
) {
logger.error('请求处理错误', {
error: error.message,
stack: error.stack,
path: req.path,
method: req.method,
});
res.status(500).json({
error: '服务器内部错误',
message: error.message,
});
}
export function notFoundMiddleware(req: Request, res: Response) {
res.status(404).json({
error: '未找到',
message: `路径 ${req.path} 不存在`,
});
}
@@ -0,0 +1,25 @@
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject, ZodError } from 'zod';
import logger from '../utils/logger';
export function validate(schema: AnyZodObject) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
});
next();
} catch (error) {
if (error instanceof ZodError) {
logger.error('验证失败', { errors: error.errors });
return res.status(400).json({
error: '请求数据验证失败',
details: error.errors,
});
}
next(error);
}
};
}
+212
View File
@@ -0,0 +1,212 @@
import { v4 as uuidv4 } from 'uuid';
import type { Instance, CreateInstanceRequest, InstanceStats } from '../types';
import { readInstance, writeInstance, deleteInstance, listInstances, instanceExists } from '../utils/storage';
import { allocatePort, releasePort, initPortAllocations } from '../utils/port-manager';
import { startProcess, stopProcess, deleteProcess, isProcessRunning, describeProcess } from './pm2.service';
import logger from '../utils/logger';
import fs from 'fs/promises';
// 初始化端口分配
export async function initInstanceService() {
const instances = await listInstances();
const ports = instances
.filter(i => i.config.port)
.map(i => i.config.port!);
initPortAllocations(ports);
logger.info('实例服务已初始化', { instanceCount: instances.length });
}
// 创建实例
export async function createInstance(data: CreateInstanceRequest): Promise<Instance> {
const { name, config } = data;
// 验证工作目录
try {
await fs.access(config.workingDir);
} catch {
throw new Error('工作目录不存在或无权访问');
}
// 分配端口
const port = config.port ? await allocatePort(config.port) : await allocatePort();
const instance: Instance = {
id: uuidv4(),
name,
status: 'stopped',
config: {
...config,
port,
},
stats: {
memory: 0,
cpu: 0,
restarts: 0,
status: 'offline',
},
createdAt: new Date(),
};
await writeInstance(instance);
logger.info('实例已创建', { instanceId: instance.id, name, port });
return instance;
}
// 启动实例
export async function startInstance(instanceId: string): Promise<void> {
const instance = await readInstance(instanceId);
if (!instance) {
throw new Error('实例不存在');
}
if (instance.status === 'running') {
throw new Error('实例已在运行中');
}
const { config, id } = instance;
try {
// PM2 启动选项
const pm2Options = {
name: id,
script: 'npx',
args: ['@anthropic-ai/claude-code', 'serve', '--port', config.port!.toString()],
cwd: config.workingDir,
env: {
...config.env,
ANTHROPIC_API_KEY: config.apiKey || process.env.ANTHROPIC_API_KEY,
PORT: config.port!.toString(),
},
error_file: `data/logs/${id}-error.log`,
out_file: `data/logs/${id}-out.log`,
max_memory_restart: config.maxMemory ? `${config.maxMemory}M` : undefined,
};
await startProcess(pm2Options);
// 更新实例状态
instance.status = 'running';
instance.lastStarted = new Date();
instance.stats.port = config.port;
await writeInstance(instance);
logger.info('实例已启动', { instanceId, port: config.port });
} catch (error) {
instance.status = 'errored';
await writeInstance(instance);
throw error;
}
}
// 停止实例
export async function stopInstance(instanceId: string): Promise<void> {
const instance = await readInstance(instanceId);
if (!instance) {
throw new Error('实例不存在');
}
if (instance.status === 'stopped') {
throw new Error('实例未运行');
}
try {
await stopProcess(instanceId);
instance.status = 'stopped';
instance.stats.pid = undefined;
instance.stats.uptime = undefined;
instance.stats.status = 'offline';
await writeInstance(instance);
logger.info('实例已停止', { instanceId });
} catch (error) {
throw error;
}
}
// 删除实例
export async function removeInstance(instanceId: string): Promise<void> {
const instance = await readInstance(instanceId);
if (!instance) {
throw new Error('实例不存在');
}
// 如果实例在运行,先停止
if (instance.status === 'running') {
await stopInstance(instanceId);
}
// 删除 PM2 进程
try {
await deleteProcess(instanceId);
} catch (error) {
// 忽略删除进程的错误
}
// 释放端口
if (instance.config.port) {
releasePort(instance.config.port);
}
// 删除实例配置
await deleteInstance(instanceId);
logger.info('实例已删除', { instanceId });
}
// 获取实例状态
export async function getInstanceStatus(instanceId: string): Promise<InstanceStats> {
const instance = await readInstance(instanceId);
if (!instance) {
throw new Error('实例不存在');
}
const process = await describeProcess(instanceId);
if (process) {
const isRunning = process.pm2_env.status === 'online';
instance.stats = {
pid: process.pid,
port: instance.config.port,
uptime: process.pm2_env.uptime,
memory: process.monit.memory,
cpu: process.monit.cpu,
restarts: process.pm2_env.restart_time,
status: isRunning ? 'online' : 'offline',
};
// 更新状态
instance.status = isRunning ? 'running' : 'stopped';
await writeInstance(instance);
} else {
instance.stats.status = 'offline';
instance.status = 'stopped';
}
return instance.stats;
}
// 获取所有实例
export async function getAllInstances(): Promise<Instance[]> {
const instances = await listInstances();
// 更新所有实例的状态
for (const instance of instances) {
try {
await getInstanceStatus(instance.id);
} catch (error) {
logger.error(`更新实例状态失败: ${instance.id}`, error);
}
}
// 重新读取最新的实例数据
return await listInstances();
}
// 获取单个实例
export async function getInstance(instanceId: string): Promise<Instance | null> {
await getInstanceStatus(instanceId);
return await readInstance(instanceId);
}
+138
View File
@@ -0,0 +1,138 @@
import pm2 from 'pm2';
import { promisify } from 'util';
import type { PM2Process } from '../types';
import logger from '../utils/logger';
// Promisify PM2 方法
const pm2Connect = promisify(pm2.connect);
const pm2Start = promisify(pm2.start);
const pm2Stop = promisify(pm2.stop);
const pm2Delete = promisify(pm2.delete);
const pm2Describe = promisify(pm2.describe);
const pm2List = promisify(pm2.list);
const pm2Restart = promisify(pm2.restart);
const pm2Disconnect = promisify(pm2.disconnect);
// PM2 连接状态
let connected = false;
// 确保 PM2 已连接
export async function ensureConnection() {
if (!connected) {
try {
await pm2Connect();
connected = true;
logger.info('PM2 已连接');
} catch (error) {
logger.error('PM2 连接失败', error);
throw error;
}
}
}
// 启动进程
export async function startProcess(options: any): Promise<void> {
await ensureConnection();
try {
await pm2Start(options);
logger.info(`PM2 进程已启动: ${options.name}`);
} catch (error) {
logger.error(`PM2 启动进程失败: ${options.name}`, error);
throw error;
}
}
// 停止进程
export async function stopProcess(processName: string): Promise<void> {
await ensureConnection();
try {
await pm2Stop(processName);
logger.info(`PM2 进程已停止: ${processName}`);
} catch (error) {
logger.error(`PM2 停止进程失败: ${processName}`, error);
throw error;
}
}
// 删除进程
export async function deleteProcess(processName: string): Promise<void> {
await ensureConnection();
try {
await pm2Delete(processName);
logger.info(`PM2 进程已删除: ${processName}`);
} catch (error) {
logger.error(`PM2 删除进程失败: ${processName}`, error);
throw error;
}
}
// 重启进程
export async function restartProcess(processName: string): Promise<void> {
await ensureConnection();
try {
await pm2Restart(processName);
logger.info(`PM2 进程已重启: ${processName}`);
} catch (error) {
logger.error(`PM2 重启进程失败: ${processName}`, error);
throw error;
}
}
// 获取进程信息
export async function describeProcess(processName: string): Promise<PM2Process | undefined> {
await ensureConnection();
try {
const processes = await pm2Describe(processName) as PM2Process[];
return processes[0];
} catch (error) {
logger.error(`PM2 获取进程信息失败: ${processName}`, error);
return undefined;
}
}
// 列出所有进程
export async function listProcesses(): Promise<PM2Process[]> {
await ensureConnection();
try {
const processes = await pm2List() as PM2Process[];
return processes;
} catch (error) {
logger.error('PM2 列出进程失败', error);
return [];
}
}
// 检查进程是否在运行
export async function isProcessRunning(processName: string): Promise<boolean> {
const process = await describeProcess(processName);
if (!process) {
return false;
}
const status = process.pm2_env.status;
return status === 'online';
}
// 断开 PM2 连接
export async function disconnect() {
if (connected) {
try {
await pm2Disconnect();
connected = false;
logger.info('PM2 已断开连接');
} catch (error) {
logger.error('PM2 断开连接失败', error);
}
}
}
// 进程退出时断开连接
process.on('exit', () => {
disconnect();
});
+73
View File
@@ -0,0 +1,73 @@
// 通用类型定义
export interface User {
id: string;
username: string;
passwordHash: string;
createdAt: Date;
}
export interface InstanceConfig {
model: string;
apiKey?: string;
workingDir: string;
port?: number;
maxMemory?: number;
env?: Record<string, string>;
}
export interface InstanceStats {
pid?: number;
port?: number;
uptime?: number;
memory: number;
cpu: number;
restarts: number;
status: 'online' | 'offline';
}
export interface Instance {
id: string;
name: string;
status: 'running' | 'stopped' | 'errored' | 'offline';
config: InstanceConfig;
stats: InstanceStats;
createdAt: Date;
lastStarted?: Date;
}
export interface CreateInstanceRequest {
name: string;
config: InstanceConfig;
}
export interface LoginRequest {
username: string;
password: string;
}
export interface LoginResponse {
token: string;
user: Omit<User, 'passwordHash'>;
}
export interface PM2Process {
name: string;
pid: number;
pm2_env: {
status: string;
uptime: number;
restart_time: number;
pm_out_log_path: string;
pm_err_log_path: string;
};
monit: {
memory: number;
cpu: number;
};
}
export interface JwtPayload {
userId: string;
username: string;
}
+62
View File
@@ -0,0 +1,62 @@
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import path from 'path';
import { config } from '../config';
const logDir = config.logDir;
// 自定义日志格式
const logFormat = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.errors({ stack: true }),
winston.format.printf(({ timestamp, level, message, stack }) => {
if (stack) {
return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack}`;
}
return `${timestamp} [${level.toUpperCase()}]: ${message}`;
})
);
// 创建日志传输器
const transports: winston.transport[] = [
// 控制台输出
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
logFormat
),
}),
];
// 文件日志(每日轮转)
if (config.nodeEnv === 'production') {
transports.push(
// 所有日志
new DailyRotateFile({
dirname: logDir,
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d',
format: logFormat,
}),
// 错误日志
new DailyRotateFile({
dirname: logDir,
filename: 'error-%DATE%.log',
datePattern: 'YYYY-MM-DD',
level: 'error',
maxSize: '20m',
maxFiles: '30d',
format: logFormat,
})
);
}
// 创建 logger
export const logger = winston.createLogger({
level: config.logLevel,
transports,
});
export default logger;
+55
View File
@@ -0,0 +1,55 @@
import detectPort from 'detect-port';
import { config } from '../config';
import logger from './logger';
// 已分配的端口缓存
const allocatedPorts = new Set<number>();
// 初始化已分配端口
export function initPortAllocations(ports: number[]) {
ports.forEach(port => allocatedPorts.add(port));
}
// 分配端口
export async function allocatePort(preferredPort?: number): Promise<number> {
// 如果指定了首选端口
if (preferredPort) {
const port = await detectPort(preferredPort);
if (port === preferredPort) {
allocatedPorts.add(port);
logger.info(`分配端口: ${port}`);
return port;
}
logger.warn(`首选端口 ${preferredPort} 已被占用,自动分配其他端口`);
}
// 自动分配可用端口
const startPort = config.instancePortRangeStart;
const endPort = config.instancePortRangeEnd;
for (let port = startPort; port <= endPort; port++) {
if (allocatedPorts.has(port)) {
continue;
}
const availablePort = await detectPort(port);
if (availablePort === port) {
allocatedPorts.add(port);
logger.info(`自动分配端口: ${port}`);
return port;
}
}
throw new Error('没有可用的端口');
}
// 释放端口
export function releasePort(port: number) {
allocatedPorts.delete(port);
logger.info(`释放端口: ${port}`);
}
// 获取所有已分配端口
export function getAllocatedPorts(): number[] {
return Array.from(allocatedPorts);
}
+108
View File
@@ -0,0 +1,108 @@
import fs from 'fs/promises';
import path from 'path';
import { config } from '../config';
import type { Instance } from '../types';
import logger from './logger';
const instancesDir = config.instanceConfigDir;
// 确保目录存在
export async function ensureDir(dir: string) {
try {
await fs.mkdir(dir, { recursive: true });
} catch (error) {
logger.error(`创建目录失败: ${dir}`, error);
throw error;
}
}
// 初始化存储
export async function initStorage() {
await ensureDir(config.dataDir);
await ensureDir(instancesDir);
await ensureDir(config.logDir);
}
// 读取实例配置
export async function readInstance(instanceId: string): Promise<Instance | null> {
try {
const filePath = path.join(instancesDir, `${instanceId}.json`);
const data = await fs.readFile(filePath, 'utf-8');
const instance = JSON.parse(data);
// 转换日期
instance.createdAt = new Date(instance.createdAt);
if (instance.lastStarted) {
instance.lastStarted = new Date(instance.lastStarted);
}
return instance;
} catch (error: any) {
if (error.code === 'ENOENT') {
return null;
}
logger.error(`读取实例配置失败: ${instanceId}`, error);
throw error;
}
}
// 写入实例配置
export async function writeInstance(instance: Instance): Promise<void> {
try {
await ensureDir(instancesDir);
const filePath = path.join(instancesDir, `${instance.id}.json`);
await fs.writeFile(filePath, JSON.stringify(instance, null, 2));
} catch (error) {
logger.error(`写入实例配置失败: ${instance.id}`, error);
throw error;
}
}
// 删除实例配置
export async function deleteInstance(instanceId: string): Promise<void> {
try {
const filePath = path.join(instancesDir, `${instanceId}.json`);
await fs.unlink(filePath);
} catch (error: any) {
if (error.code !== 'ENOENT') {
logger.error(`删除实例配置失败: ${instanceId}`, error);
throw error;
}
}
}
// 列出所有实例
export async function listInstances(): Promise<Instance[]> {
try {
await ensureDir(instancesDir);
const files = await fs.readdir(instancesDir);
const instanceFiles = files.filter(f => f.endsWith('.json'));
const instances: Instance[] = [];
for (const file of instanceFiles) {
try {
const instanceId = path.basename(file, '.json');
const instance = await readInstance(instanceId);
if (instance) {
instances.push(instance);
}
} catch (error) {
logger.error(`读取实例文件失败: ${file}`, error);
}
}
return instances;
} catch (error) {
logger.error('列出实例失败', error);
throw error;
}
}
// 检查实例是否存在
export async function instanceExists(instanceId: string): Promise<boolean> {
const filePath = path.join(instancesDir, `${instanceId}.json`);
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}