Skip to content

Commit 9ac5f0b

Browse files
committed
更新增强代码稳定性
1 parent 9ef205a commit 9ac5f0b

File tree

12 files changed

+307
-213
lines changed

12 files changed

+307
-213
lines changed

CodeRunner/Dockerfile

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
FROM ubuntu:22.04
2+
3+
# 避免交互式提示
4+
ENV DEBIAN_FRONTEND=noninteractive
5+
6+
# 设置时区
7+
ENV TZ=Asia/Shanghai
8+
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
9+
10+
# 安装基础工具和依赖
11+
RUN apt-get update && apt-get install -y \
12+
sudo \
13+
curl \
14+
wget \
15+
git \
16+
vim \
17+
bash \
18+
build-essential \
19+
software-properties-common \
20+
apt-transport-https \
21+
ca-certificates \
22+
gnupg \
23+
lsb-release \
24+
zsh \
25+
tmux \
26+
htop \
27+
tree \
28+
jq \
29+
unzip \
30+
openssh-client \
31+
postgresql-client \
32+
redis-tools \
33+
make \
34+
gcc \
35+
g++ \
36+
libssl-dev \
37+
zlib1g-dev \
38+
libbz2-dev \
39+
libreadline-dev \
40+
libsqlite3-dev \
41+
libncursesw5-dev \
42+
xz-utils \
43+
tk-dev \
44+
libxml2-dev \
45+
libxmlsec1-dev \
46+
libffi-dev \
47+
liblzma-dev \
48+
# Ruby 依赖
49+
libyaml-dev \
50+
libgmp-dev \
51+
&& rm -rf /var/lib/apt/lists/*
52+
53+
# 创建非root用户
54+
RUN useradd -m -s /bin/bash zerocat \
55+
&& echo "zerocat ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/zerocat \
56+
&& chmod 0440 /etc/sudoers.d/zerocat
57+
58+
# 设置工作目录
59+
WORKDIR /home/zerocat
60+
61+
# 安装 asdf 版本管理器
62+
USER zerocat
63+
RUN git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.13.1
64+
65+
# 配置 asdf
66+
RUN echo '. "$HOME/.asdf/asdf.sh"' >> ~/.bashrc && \
67+
echo '. "$HOME/.asdf/completions/asdf.bash"' >> ~/.bashrc
68+
69+
# 使用 asdf 安装编程语言
70+
SHELL ["/bin/bash", "-l", "-c"]
71+
72+
# 添加 asdf 插件
73+
RUN . "$HOME/.asdf/asdf.sh" && \
74+
asdf plugin add python && \
75+
asdf plugin add nodejs && \
76+
asdf plugin add ruby && \
77+
asdf plugin add golang && \
78+
asdf plugin add rust && \
79+
asdf plugin add java
80+
81+
# 安装 Python
82+
RUN . "$HOME/.asdf/asdf.sh" && \
83+
asdf install python latest:2.7 && \
84+
asdf install python latest:3.11 && \
85+
asdf install python latest:3.12 && \
86+
asdf install python latest:3.13 && \
87+
asdf global python latest:3.11
88+
89+
# 安装 Node.js
90+
RUN . "$HOME/.asdf/asdf.sh" && \
91+
asdf install nodejs latest:18 && \
92+
asdf install nodejs latest:20 && \
93+
asdf install nodejs latest:22 && \
94+
asdf install nodejs latest:24 && \
95+
asdf global nodejs latest:24
96+
97+
# 安装 TypeScript 和 ts-node
98+
RUN . "$HOME/.asdf/asdf.sh" && \
99+
npm install -g typescript ts-node
100+
101+
# 安装 Ruby
102+
RUN . "$HOME/.asdf/asdf.sh" && \
103+
asdf install ruby latest:3.4 && \
104+
asdf global ruby latest:3.4
105+
106+
# 安装 Golang
107+
RUN . "$HOME/.asdf/asdf.sh" && \
108+
asdf install golang latest:1.24 && \
109+
asdf global golang latest:1.24
110+
111+
# 安装 Rust
112+
RUN . "$HOME/.asdf/asdf.sh" && \
113+
asdf install rust latest:1.88 && \
114+
asdf global rust latest:1.88
115+
116+
# 安装 Java
117+
RUN . "$HOME/.asdf/asdf.sh" && \
118+
asdf install java openjdk-17 && \
119+
asdf install java openjdk-21 && \
120+
asdf install java openjdk-24 && \
121+
asdf global java openjdk-24
122+
123+
# 安装 Python 包
124+
RUN . "$HOME/.asdf/asdf.sh" && \
125+
pip install --upgrade pip && \
126+
pip install ipython poetry virtualenv black flake8 mypy pytest requests
127+
128+
# 设置权限
129+
USER root
130+
RUN chown -R zerocat:zerocat /home/zerocat
131+
132+
# 切换到非root用户
133+
USER zerocat
134+
135+
# 设置SHELL环境变量
136+
ENV SHELL=/bin/bash
137+
138+
# 配置终端
139+
RUN echo 'export PS1="\[\e[01;32m\]\u@\h\[\e[0m\]:\[\e[01;34m\]\w\[\e[0m\]\$ "' >> ~/.bashrc
140+
141+
# 设置容器启动命令
142+
CMD ["/bin/bash", "-l"]

Dockerfile

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM node:18-slim
1+
FROM node:22-slim
22

33
# 设置工作目录
44
WORKDIR /app
@@ -10,13 +10,10 @@ RUN apt-get update && apt-get install -y \
1010

1111
# 复制package文件
1212
COPY package*.json ./
13-
COPY pnpm-lock.yaml ./
1413

15-
# 安装pnpm
16-
RUN npm install -g pnpm
1714

1815
# 安装依赖
19-
RUN pnpm install
16+
RUN npm install
2017

2118
# 复制应用代码
2219
COPY . .
@@ -25,4 +22,4 @@ COPY . .
2522
EXPOSE 3000
2623

2724
# 启动命令
28-
CMD ["pnpm", "start"]
25+
CMD ["npm", "start"]

app.js

Lines changed: 37 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -3,103 +3,67 @@ const path = require('path');
33
const cookieParser = require('cookie-parser');
44
const logger = require('morgan');
55
const WebSocket = require('ws');
6-
const { terminalService } = require('./services/terminal');
7-
const adminService = require('./services/admin');
8-
const { validateToken } = require('./middleware/auth');
9-
const jwt = require('jsonwebtoken');
10-
const config = require('./config');
11-
const bodyParser = require('body-parser');
6+
const http = require('http');
127

138
const indexRouter = require('./routes/index');
14-
const usersRouter = require('./routes/users');
15-
const terminalRouter = require('./routes/terminal');
16-
const adminRouter = require('./routes/admin');
9+
const authService = require('./services/auth');
10+
const { terminalService } = require('./services/terminal');
1711

1812
const app = express();
1913

20-
// view engine setup
14+
// 视图引擎设置
2115
app.set('views', path.join(__dirname, 'views'));
2216
app.set('view engine', 'ejs');
2317

24-
// middleware setup
25-
app.use(logger(config.logging.format));
18+
// 中间件
19+
app.use(logger('dev'));
2620
app.use(express.json());
2721
app.use(express.urlencoded({ extended: false }));
2822
app.use(cookieParser());
2923
app.use(express.static(path.join(__dirname, 'public')));
30-
app.use(bodyParser.urlencoded({ limit: "100mb", extended: false }));
31-
app.use(bodyParser.json({ limit: "100mb" }));
32-
app.use(bodyParser.text({ limit: "100mb" }));
33-
app.use(bodyParser.raw({ limit: "100mb" }));
3424

35-
// Security headers
36-
app.use((req, res, next) => {
37-
res.set({
38-
'X-Content-Type-Options': 'nosniff',
39-
'X-Frame-Options': 'DENY',
40-
'X-XSS-Protection': '1; mode=block'
41-
});
42-
next();
43-
});
25+
// 认证中间件
26+
app.use(authService.validateToken.bind(authService));
4427

45-
// Routes
28+
// 路由
4629
app.use('/', indexRouter);
47-
app.use('/users', usersRouter);
48-
app.use('/terminal', terminalRouter);
49-
app.use('/admin', adminRouter);
5030

51-
// WebSocket server setup
52-
const wss = new WebSocket.Server({ noServer: true });
31+
// 错误处理
32+
app.use(function(err, req, res, next) {
33+
console.error(err.stack);
34+
res.status(err.status || 500);
35+
res.render('error', {
36+
message: err.message,
37+
error: req.app.get('env') === 'development' ? err : {}
38+
});
39+
});
40+
41+
// WebSocket服务器设置
42+
const server = http.createServer(app);
43+
const wss = new WebSocket.Server({ server });
5344

54-
// WebSocket authentication middleware
55-
async function authenticateWebSocket(request, socket, head) {
45+
wss.on('connection', async (ws, req) => {
5646
try {
57-
// 从URL参数中获取token
58-
const url = new URL(request.url, `http://${request.headers.host}`);
47+
// 解析token
48+
const url = new URL(req.url, `http://${req.headers.host}`);
5949
const token = url.searchParams.get('token');
6050

61-
if (!token) {
62-
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
63-
socket.destroy();
64-
return;
65-
}
66-
67-
// 验证token并解码用户信息
68-
const decoded = jwt.verify(token, config.jwt.secret);
69-
request.user = {
70-
userid: decoded.userid,
71-
fingerprint: decoded.fingerprint
72-
};
73-
74-
// 升级连接
75-
wss.handleUpgrade(request, socket, head, (ws) => {
76-
wss.emit('connection', ws, request);
51+
// 验证token
52+
req.headers.authorization = `Bearer ${token}`;
53+
await new Promise((resolve, reject) => {
54+
authService.validateToken(
55+
req,
56+
{ status: () => ({ json: (data) => reject(new Error(data.error)) }) },
57+
resolve
58+
);
7759
});
78-
} catch (error) {
79-
console.error('WebSocket authentication failed:', error);
80-
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
81-
socket.destroy();
82-
}
83-
}
8460

85-
// Handle WebSocket connections
86-
wss.on('connection', (ws, request) => {
87-
try {
88-
terminalService.handleConnection(ws, request);
61+
// 处理终端连接
62+
await terminalService.handleConnection(ws, req);
8963
} catch (error) {
90-
console.error('Failed to handle WebSocket connection:', error);
64+
console.error('WebSocket连接错误:', error);
9165
ws.close(1008, 'Authentication failed');
9266
}
9367
});
9468

95-
// Error handler
96-
app.use(function(err, req, res, next) {
97-
console.error(err.stack);
98-
res.status(err.status || 500);
99-
res.render('error', {
100-
message: err.message,
101-
error: req.app.get('env') === 'development' ? err : {}
102-
});
103-
});
104-
105-
module.exports = { app, authenticateWebSocket };
69+
module.exports = { app, server };

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
"delay": 2500
1010
},
1111
"scripts": {
12-
"start": "node ./bin/www",
13-
"dev": "nodemon ./bin/www"
12+
"start": "node server.js",
13+
"dev": "nodemon server.js"
1414
},
1515
"dependencies": {
1616
"axios": "^1.6.7",

routes/admin.js

Lines changed: 0 additions & 52 deletions
This file was deleted.

0 commit comments

Comments
 (0)