Download routes/command.js from hijnu/exec: direct link, hf CLI and curl.
- Browser
- Download file 2.67 kB
-
https://huggingface.co/spaces/hijnu/exec/resolve/main/routes/command.js
- Command line
-
hf download hf://spaces/hijnu/exec/routes/command.js
-
curl -L -o command.js https://huggingface.co/spaces/hijnu/exec/resolve/main/routes/command.js
2.67 kB
| const express = require('express'); | |
| const { execFile } = require('child_process'); | |
| const fs = require('fs').promises; | |
| const path = require('path'); | |
| const router = express.Router(); | |
| const logger = require('../utils/logger'); | |
| // 命令白名单 | |
| const allowedCommands = ['ls', 'pwd', 'whoami', 'date', 'echo', 'cat']; | |
| // 历史命令文件路径 | |
| const historyFilePath = path.join(__dirname, '..', 'data', 'command_history.json'); | |
| router.get('/command-history', async (req, res) => { | |
| try { | |
| let history = []; | |
| try { | |
| const historyData = await fs.readFile(historyFilePath, 'utf-8'); | |
| history = JSON.parse(historyData); | |
| } catch (readError) { | |
| logger.warn('读取命令历史失败,使用空数组:', readError); | |
| } | |
| res.json(history); | |
| } catch (error) { | |
| logger.error('处理命令历史请求失败:', error); | |
| res.status(500).json({ error: '无法读取命令历史' }); | |
| } | |
| }); | |
| router.post('/execute', async (req, res) => { | |
| const { command } = req.body; | |
| const baseCommand = command.split(' ')[0]; | |
| // 白名单检查的部分 | |
| // if (!allowedCommands.includes(baseCommand)) { | |
| // logger.warn(`用户 ${req.user.username} 未授权的命令: ${command}`); | |
| // return res.status(403).json({ error: '未授权命令' }); | |
| // } | |
| execFile(baseCommand, command.split(' ').slice(1), { timeout: 5000 }, async (error, stdout, stderr) => { | |
| if (error) { | |
| logger.error(`命令执行错误: ${error.message}`); | |
| return res.status(500).json({ error: error.message }); | |
| } | |
| // 记录命令历史 | |
| try { | |
| let history = []; | |
| try { | |
| const historyData = await fs.readFile(historyFilePath, 'utf-8'); | |
| history = JSON.parse(historyData); | |
| } catch (readError) { | |
| // 如果文件不存在或为空,使用空数组 | |
| } | |
| history.push({ command, timestamp: new Date().toISOString(), user: req.user.username }); | |
| if (history.length > 100) history.shift(); // 保留最近100条命令 | |
| await fs.writeFile(historyFilePath, JSON.stringify(history, null, 2)); | |
| } catch (writeError) { | |
| logger.error('写入命令历史失败:', writeError); | |
| return res.status(500).json({ error: '写入命令历史失败' }); | |
| } | |
| logger.info(`用户 ${req.user.username} 成功执行命令: ${command}`); | |
| res.json({ output: stdout, error: stderr }); | |
| }); | |
| }); | |
| module.exports = router; |