file-handle 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -0
- package/README.zh-CN.md +93 -0
- package/package.json +36 -0
- package/server/bin/cli.js +3 -0
- package/server/common/adapter.js +90 -0
- package/server/common/i18n.js +109 -0
- package/server/config.js +123 -0
- package/server/fh.app.dat +0 -0
- package/server/index.js +153 -0
- package/server/middlewares/ipValidation.js +33 -0
- package/server/middlewares/security.js +172 -0
- package/server/middlewares/upload.js +57 -0
- package/server/routes/api.js +174 -0
- package/server/routes/fh.js +82 -0
- package/server/routes/res.js +18 -0
- package/server/types/d.js +1 -0
- package/server/types/index.js +83 -0
- package/server/types/response.js +20 -0
- package/server/utils/Preview/Markdown/registrie.js +8 -0
- package/server/utils/Preview/Text/registrie.js +92 -0
- package/server/utils/Preview/types.js +1 -0
- package/server/utils/logger.js +55 -0
- package/server/utils/path.js +62 -0
package/server/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import https from 'https';
|
|
3
|
+
import http from 'http';
|
|
4
|
+
import color from 'cli-color';
|
|
5
|
+
import fs from 'fs/promises';
|
|
6
|
+
import os from 'os';
|
|
7
|
+
import cookieParser from 'cookie-parser';
|
|
8
|
+
import { loadConfig } from './config.js';
|
|
9
|
+
import { createFileSystemRouter } from './routes/fh.js';
|
|
10
|
+
import { createApiRouter } from './routes/api.js';
|
|
11
|
+
import { createResourcesRouter } from './routes/res.js';
|
|
12
|
+
import { handleUploadError } from './middlewares/upload.js';
|
|
13
|
+
import { validatePassword, validateFileOperation, errorHandler, corsMiddleware } from './middlewares/security.js';
|
|
14
|
+
import { validateIpAccess } from './middlewares/ipValidation.js';
|
|
15
|
+
import { getText } from './common/i18n.js';
|
|
16
|
+
import { info, debug } from './utils/logger.js';
|
|
17
|
+
const lang = getText();
|
|
18
|
+
export async function startServer() {
|
|
19
|
+
// 加载配置
|
|
20
|
+
const config = loadConfig();
|
|
21
|
+
debug(`Server config loaded: ${JSON.stringify(config, null, 2)}`);
|
|
22
|
+
// 创建Express应用
|
|
23
|
+
const app = express();
|
|
24
|
+
// 配置中间件
|
|
25
|
+
app.use(express.json());
|
|
26
|
+
app.use(cookieParser());
|
|
27
|
+
app.use((req, res, next) => {
|
|
28
|
+
res.setHeader('Server', 'File-Handle Server');
|
|
29
|
+
next();
|
|
30
|
+
});
|
|
31
|
+
app.use(corsMiddleware);
|
|
32
|
+
app.use(validateIpAccess(config));
|
|
33
|
+
app.use(validatePassword(config));
|
|
34
|
+
app.use(validateFileOperation(config));
|
|
35
|
+
// 根路径重定向到文件系统
|
|
36
|
+
app.get('/', (req, res) => {
|
|
37
|
+
res.redirect('/fh/');
|
|
38
|
+
});
|
|
39
|
+
// 配置路由
|
|
40
|
+
app.use('/fh', createFileSystemRouter(config));
|
|
41
|
+
app.use('/api', createApiRouter(config));
|
|
42
|
+
createResourcesRouter(app, config);
|
|
43
|
+
// 错误处理
|
|
44
|
+
app.use(handleUploadError);
|
|
45
|
+
app.use(errorHandler);
|
|
46
|
+
// 启动服务器
|
|
47
|
+
let server;
|
|
48
|
+
if (config.tls) {
|
|
49
|
+
const credentials = {
|
|
50
|
+
key: await fs.readFile(config.tls.key),
|
|
51
|
+
cert: await fs.readFile(config.tls.cert)
|
|
52
|
+
};
|
|
53
|
+
server = https.createServer(credentials, app);
|
|
54
|
+
info(lang.server.startingHttps);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
server = http.createServer(app);
|
|
58
|
+
info(lang.server.startingHttp);
|
|
59
|
+
}
|
|
60
|
+
const port = await findAvailablePort(config.port);
|
|
61
|
+
const localIPs = getLocalNetworkIPs();
|
|
62
|
+
if (config.allowedIPs) {
|
|
63
|
+
// 如果指定了允许访问的IP地址,则只允许这些IP访问
|
|
64
|
+
server.listen(port, '127.0.0.1', () => {
|
|
65
|
+
info(lang.server.allowedIpsOnly);
|
|
66
|
+
info(`${lang.server.running}${port}`);
|
|
67
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
68
|
+
info(lang.server.accessibleAddresses);
|
|
69
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
70
|
+
config.allowedIPs && config.allowedIPs.forEach(ip => {
|
|
71
|
+
info(color.green(`http://${ip}:${port}/fh/`));
|
|
72
|
+
});
|
|
73
|
+
info('\n\n');
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
else if (localIPs.length > 0 && !config.allowWan) {
|
|
77
|
+
// 如果存在局域网IP且未启用公网访问,则只监听局域网IP
|
|
78
|
+
server.listen(port, '127.0.0.1', () => {
|
|
79
|
+
info(lang.server.localAndLanOnly);
|
|
80
|
+
info(`${lang.server.running}${port}`);
|
|
81
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
82
|
+
info(lang.server.accessibleAddresses);
|
|
83
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
84
|
+
localIPs.forEach(ip => {
|
|
85
|
+
info(color.green(`http://${ip}:${port}/fh/`));
|
|
86
|
+
});
|
|
87
|
+
info('\n\n');
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
// 允许所有IP访问
|
|
92
|
+
server.listen(port, '127.0.0.1', () => {
|
|
93
|
+
info(`${lang.server.running}${port}`);
|
|
94
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
95
|
+
info(lang.server.accessibleAddresses);
|
|
96
|
+
info(`http://0.0.0.0:${port}/fh/`);
|
|
97
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
98
|
+
info(`\n\n`);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
if (config.password) {
|
|
102
|
+
info(`${lang.server.loginPassword}${color.green(config.password)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function findAvailablePort(startPort, maxAttempts = 50) {
|
|
106
|
+
const app = express();
|
|
107
|
+
for (let port = startPort; port < startPort + maxAttempts; port++) {
|
|
108
|
+
try {
|
|
109
|
+
await new Promise((resolve, reject) => {
|
|
110
|
+
const server = http.createServer(app)
|
|
111
|
+
.once('error', err => {
|
|
112
|
+
info(lang.server.portInUse.replace('{port}', port.toString()));
|
|
113
|
+
reject(err);
|
|
114
|
+
})
|
|
115
|
+
.once('listening', () => {
|
|
116
|
+
server.close();
|
|
117
|
+
resolve(port);
|
|
118
|
+
})
|
|
119
|
+
.listen(port, '127.0.0.1');
|
|
120
|
+
});
|
|
121
|
+
return port;
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
throw new Error(`No available port found after ${maxAttempts} attempts`);
|
|
128
|
+
}
|
|
129
|
+
function getLocalNetworkIPs() {
|
|
130
|
+
const interfaces = os.networkInterfaces();
|
|
131
|
+
const ips = [];
|
|
132
|
+
for (const name of Object.keys(interfaces)) {
|
|
133
|
+
for (const iface of interfaces[name] || []) {
|
|
134
|
+
// 跳过内部回环地址和非IPv4地址
|
|
135
|
+
if (iface.internal || iface.family !== 'IPv4')
|
|
136
|
+
continue;
|
|
137
|
+
// 判断是否为局域网IP
|
|
138
|
+
if (iface.address.startsWith('192.168.') ||
|
|
139
|
+
iface.address.startsWith('10.') ||
|
|
140
|
+
iface.address.match(/^172\.(1[6-9]|2[0-9]|3[0-1])\./)) {
|
|
141
|
+
ips.push(iface.address);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return ips;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* File-Handle
|
|
149
|
+
*
|
|
150
|
+
* @module file-handle
|
|
151
|
+
* @license [Apache-2.0]{@link https://github.com/purplestone/file-handle}
|
|
152
|
+
* @copyright (c) 2025 gaoyuan.
|
|
153
|
+
*/
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { FileOperationError } from '../types/index.js';
|
|
2
|
+
import { error } from '../utils/logger.js';
|
|
3
|
+
// IP验证中间件
|
|
4
|
+
export function validateIpAccess(config) {
|
|
5
|
+
return (req, res, next) => {
|
|
6
|
+
// 如果没有配置IP限制,直接通过
|
|
7
|
+
if (!config.allowedIPs && !config.allowWan) {
|
|
8
|
+
return next();
|
|
9
|
+
}
|
|
10
|
+
const clientIp = req.ip || req.socket.remoteAddress || '';
|
|
11
|
+
const normalizedClientIp = clientIp.replace(/^::ffff:/, ''); // 处理IPv6格式的IPv4地址
|
|
12
|
+
// 如果配置了允许的IP列表
|
|
13
|
+
if (config.allowedIPs && config.allowedIPs.length > 0) {
|
|
14
|
+
if (normalizedClientIp !== '127.0.0.1' && !config.allowedIPs.includes(normalizedClientIp)) {
|
|
15
|
+
error(`Unauthorized access attempt from IP: ${normalizedClientIp}`);
|
|
16
|
+
throw new FileOperationError('Unauthorized: IP not allowed', 403);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// 如果禁止公网访问,只允许本地和局域网IP
|
|
20
|
+
else if (!config.allowWan) {
|
|
21
|
+
const isLocalOrPrivate = (normalizedClientIp === '127.0.0.1' ||
|
|
22
|
+
normalizedClientIp.startsWith('192.168.') ||
|
|
23
|
+
normalizedClientIp.startsWith('10.') ||
|
|
24
|
+
normalizedClientIp.match(/^172\.(1[6-9]|2[0-9]|3[0-1])\./) ||
|
|
25
|
+
normalizedClientIp === '::1');
|
|
26
|
+
if (!isLocalOrPrivate) {
|
|
27
|
+
error(`Unauthorized public access attempt from IP: ${normalizedClientIp}`);
|
|
28
|
+
throw new FileOperationError('Unauthorized: Public IP access not allowed', 403);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
next();
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { FileOperationError } from '../types/index.js';
|
|
2
|
+
import { error } from '../utils/logger.js';
|
|
3
|
+
import { getPack } from '../common/i18n.js';
|
|
4
|
+
// 验证密码中间件
|
|
5
|
+
export function validatePassword(config) {
|
|
6
|
+
return (req, res, next) => {
|
|
7
|
+
// 如果没有设置密码,直接通过
|
|
8
|
+
if (!config.password) {
|
|
9
|
+
return next();
|
|
10
|
+
}
|
|
11
|
+
// 检查cookie中的密码
|
|
12
|
+
const cookiePassword = req.cookies?.['auth-password'];
|
|
13
|
+
if (cookiePassword === config.password) {
|
|
14
|
+
return next();
|
|
15
|
+
}
|
|
16
|
+
// 密码错误或未提供密码,返回登录页面
|
|
17
|
+
res.status(401).send(loginHtml());
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
// 验证文件操作权限中间件
|
|
21
|
+
export function validateFileOperation(config) {
|
|
22
|
+
return (req, res, next) => {
|
|
23
|
+
const operation = req.path.split('/').pop();
|
|
24
|
+
// 验证删除权限
|
|
25
|
+
if (operation === 'delete' && !config.allowDelete) {
|
|
26
|
+
error('Delete operation not allowed');
|
|
27
|
+
throw new FileOperationError('Operation not allowed: Delete is disabled', 403);
|
|
28
|
+
}
|
|
29
|
+
// 验证编辑权限
|
|
30
|
+
if (operation === 'edit' && !config.allowEdit) {
|
|
31
|
+
error('Edit operation not allowed');
|
|
32
|
+
throw new FileOperationError('Operation not allowed: Edit is disabled', 403);
|
|
33
|
+
}
|
|
34
|
+
next();
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
// 错误处理中间件
|
|
38
|
+
export function errorHandler(err, req, res, next) {
|
|
39
|
+
error(err);
|
|
40
|
+
if (err instanceof FileOperationError) {
|
|
41
|
+
return res.status(err.code).json({
|
|
42
|
+
code: -err.code,
|
|
43
|
+
msg: err.message
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
res.status(500).json({
|
|
47
|
+
code: -500,
|
|
48
|
+
msg: 'Internal Server Error'
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
// CORS中间件
|
|
52
|
+
export function corsMiddleware(req, res, next) {
|
|
53
|
+
res.header('Access-Control-Allow-Origin', '*');
|
|
54
|
+
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
|
|
55
|
+
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-Auth-Password');
|
|
56
|
+
if (req.method === 'OPTIONS') {
|
|
57
|
+
return res.sendStatus(200);
|
|
58
|
+
}
|
|
59
|
+
next();
|
|
60
|
+
}
|
|
61
|
+
const i18n = getPack('ui');
|
|
62
|
+
function loginHtml() {
|
|
63
|
+
return `
|
|
64
|
+
<!DOCTYPE html>
|
|
65
|
+
<html>
|
|
66
|
+
<head>
|
|
67
|
+
<meta charset="UTF-8">
|
|
68
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
69
|
+
<title>Login</title>
|
|
70
|
+
<style>
|
|
71
|
+
body {
|
|
72
|
+
font-family: Arial, sans-serif;
|
|
73
|
+
display: flex;
|
|
74
|
+
justify-content: center;
|
|
75
|
+
align-items: center;
|
|
76
|
+
height: 100vh;
|
|
77
|
+
margin: 0;
|
|
78
|
+
background-color: #f5f5f5;
|
|
79
|
+
}
|
|
80
|
+
.login-container {
|
|
81
|
+
background: white;
|
|
82
|
+
padding: 2rem;
|
|
83
|
+
border-radius: 8px;
|
|
84
|
+
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
85
|
+
width: 100%;
|
|
86
|
+
max-width: 400px;
|
|
87
|
+
position: relative;
|
|
88
|
+
}
|
|
89
|
+
.form-group {
|
|
90
|
+
margin-bottom: 1rem;
|
|
91
|
+
}
|
|
92
|
+
input[type="password"] {
|
|
93
|
+
width: 100%;
|
|
94
|
+
padding: 0.5rem;
|
|
95
|
+
border: 1px solid #ddd;
|
|
96
|
+
border-radius: 4px;
|
|
97
|
+
font-size: 1rem;
|
|
98
|
+
}
|
|
99
|
+
button {
|
|
100
|
+
width: 100%;
|
|
101
|
+
padding: 0.75rem;
|
|
102
|
+
background-color: #007bff;
|
|
103
|
+
color: white;
|
|
104
|
+
border: none;
|
|
105
|
+
border-radius: 4px;
|
|
106
|
+
font-size: 1rem;
|
|
107
|
+
cursor: pointer;
|
|
108
|
+
}
|
|
109
|
+
button:hover {
|
|
110
|
+
background-color: #0056b3;
|
|
111
|
+
}
|
|
112
|
+
.lang-switch {
|
|
113
|
+
position: absolute;
|
|
114
|
+
top: 1rem;
|
|
115
|
+
right: 1rem;
|
|
116
|
+
background: none;
|
|
117
|
+
border: none;
|
|
118
|
+
color: #007bff;
|
|
119
|
+
cursor: pointer;
|
|
120
|
+
text-decoration: underline;
|
|
121
|
+
padding: 0;
|
|
122
|
+
width: auto;
|
|
123
|
+
}
|
|
124
|
+
.lang-switch:hover {
|
|
125
|
+
color: #0056b3;
|
|
126
|
+
background: none;
|
|
127
|
+
}
|
|
128
|
+
</style>
|
|
129
|
+
</head>
|
|
130
|
+
<body>
|
|
131
|
+
<div class="login-container">
|
|
132
|
+
<button class="lang-switch" onclick="toggleLanguage()"></button>
|
|
133
|
+
<h1 class="i18n-title"></h1>
|
|
134
|
+
<form id="loginForm" onsubmit="handleSubmit(event)">
|
|
135
|
+
<div class="form-group">
|
|
136
|
+
<input type="password" id="password" required>
|
|
137
|
+
</div>
|
|
138
|
+
<button type="submit" class="i18n-submit"></button>
|
|
139
|
+
</form>
|
|
140
|
+
</div>
|
|
141
|
+
<script>
|
|
142
|
+
let currentLang = localStorage.getItem('preferred-language') || 'zh-CN';
|
|
143
|
+
const i18n = ${JSON.stringify(i18n)};
|
|
144
|
+
|
|
145
|
+
function updateTexts() {
|
|
146
|
+
const texts = i18n[currentLang];
|
|
147
|
+
document.querySelector('.i18n-title').textContent = texts.ui.title;
|
|
148
|
+
document.getElementById('password').placeholder = texts.ui.passwordPlaceholder;
|
|
149
|
+
document.querySelector('.i18n-submit').textContent = texts.ui.submit;
|
|
150
|
+
document.querySelector('.lang-switch').textContent = texts.ui.switchLang;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function toggleLanguage() {
|
|
154
|
+
currentLang = currentLang === 'zh-CN' ? 'en-US' : 'zh-CN';
|
|
155
|
+
localStorage.setItem('preferred-language', currentLang);
|
|
156
|
+
updateTexts();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function handleSubmit(event) {
|
|
160
|
+
event.preventDefault();
|
|
161
|
+
const password = document.getElementById('password').value;
|
|
162
|
+
document.cookie = 'auth-password=' + password + '; max-age=' + 60 * 60 * 24 + '; path=/';
|
|
163
|
+
window.location.reload();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 初始化页面文本
|
|
167
|
+
updateTexts();
|
|
168
|
+
</script>
|
|
169
|
+
</body>
|
|
170
|
+
</html>
|
|
171
|
+
`;
|
|
172
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import multer from 'multer';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { validateFileName } from '../utils/path.js';
|
|
4
|
+
import { FileOperationError } from '../types/index.js';
|
|
5
|
+
import { debug, error } from '../utils/logger.js';
|
|
6
|
+
// 创建文件上传配置
|
|
7
|
+
export function createUploadMiddleware(config) {
|
|
8
|
+
const storage = multer.diskStorage({
|
|
9
|
+
destination: (req, file, cb) => {
|
|
10
|
+
// 获取上传目录
|
|
11
|
+
const uploadPath = req.query.path || '';
|
|
12
|
+
const targetDir = path.join(config.rootDir, uploadPath);
|
|
13
|
+
cb(null, targetDir);
|
|
14
|
+
},
|
|
15
|
+
filename: (req, file, cb) => {
|
|
16
|
+
const decodedName = Buffer.from(file.originalname, 'latin1').toString('utf8');
|
|
17
|
+
// 验证文件名
|
|
18
|
+
if (!validateFileName(decodedName)) {
|
|
19
|
+
return cb(new FileOperationError('Invalid filename', 400), '');
|
|
20
|
+
}
|
|
21
|
+
// 如果文件已存在,添加时间戳
|
|
22
|
+
const filename = decodedName;
|
|
23
|
+
debug(`Processing upload: ${filename}`);
|
|
24
|
+
cb(null, filename);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
// 文件过滤器
|
|
28
|
+
const fileFilter = (req, file, cb) => {
|
|
29
|
+
// 验证文件名
|
|
30
|
+
if (!validateFileName(file.originalname)) {
|
|
31
|
+
error(`Invalid filename: ${file.originalname}`);
|
|
32
|
+
cb(new FileOperationError('Invalid filename', 400));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
cb(null, true);
|
|
36
|
+
};
|
|
37
|
+
// 创建multer实例
|
|
38
|
+
return multer({
|
|
39
|
+
storage,
|
|
40
|
+
fileFilter,
|
|
41
|
+
limits: {
|
|
42
|
+
fileSize: config.uploadLimit
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// 错误处理中间件
|
|
47
|
+
export function handleUploadError(err, req, res, next) {
|
|
48
|
+
if (err instanceof multer.MulterError) {
|
|
49
|
+
if (err.code === 'LIMIT_FILE_SIZE') {
|
|
50
|
+
return res.status(413).json({
|
|
51
|
+
success: false,
|
|
52
|
+
message: 'File too large'
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
next(err);
|
|
57
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { ApiResponseBuilder } from '../types/response.js';
|
|
5
|
+
import { normalizePath, validateFileName } from '../utils/path.js';
|
|
6
|
+
import { isEditorAble, isPreviewAble, getMime } from '../types/index.js';
|
|
7
|
+
import { createUploadMiddleware } from '../middlewares/upload.js';
|
|
8
|
+
import { info } from '../utils/logger.js';
|
|
9
|
+
export function createApiRouter(config) {
|
|
10
|
+
const router = Router();
|
|
11
|
+
const upload = createUploadMiddleware(config);
|
|
12
|
+
// 配置文件上传路由
|
|
13
|
+
router.post('/upload', upload.array('files'), (req, res) => {
|
|
14
|
+
const files = req.files.map(file => ({
|
|
15
|
+
originalName: file.originalname,
|
|
16
|
+
savedPath: file.path,
|
|
17
|
+
size: file.size
|
|
18
|
+
}));
|
|
19
|
+
res.json(ApiResponseBuilder.success({
|
|
20
|
+
files
|
|
21
|
+
}, 'Files uploaded successfully'));
|
|
22
|
+
info(`Uploaded: ${files.length} files`);
|
|
23
|
+
});
|
|
24
|
+
router.post('/create', async (req, res, next) => {
|
|
25
|
+
try {
|
|
26
|
+
const { path: dirPath } = req.body;
|
|
27
|
+
if (!dirPath || !validateFileName(path.basename(dirPath))) {
|
|
28
|
+
throw new FileOperationError('Invalid directory name', 400);
|
|
29
|
+
}
|
|
30
|
+
const fullPath = normalizePath(dirPath, config.rootDir);
|
|
31
|
+
await fs.mkdir(fullPath, { recursive: true });
|
|
32
|
+
res.json(ApiResponseBuilder.success(null, 'Directory created successfully'));
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
next(err);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
// 删除文件或目录
|
|
39
|
+
router.delete('/delete', async (req, res, next) => {
|
|
40
|
+
try {
|
|
41
|
+
const { path: targetPath } = req.body;
|
|
42
|
+
const fullPath = normalizePath(targetPath, config.rootDir);
|
|
43
|
+
const stats = await fs.stat(fullPath);
|
|
44
|
+
if (stats.isDirectory()) {
|
|
45
|
+
await fs.rm(fullPath, { recursive: true });
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
await fs.unlink(fullPath);
|
|
49
|
+
}
|
|
50
|
+
res.json(ApiResponseBuilder.success(null, 'File or directory deleted successfully'));
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
next(err);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
// 编辑文件
|
|
57
|
+
router.put('/edit', async (req, res, next) => {
|
|
58
|
+
try {
|
|
59
|
+
const { path: filePath, content } = req.body;
|
|
60
|
+
const fullPath = normalizePath(filePath, config.rootDir);
|
|
61
|
+
await fs.writeFile(fullPath, content, 'utf8');
|
|
62
|
+
res.json(ApiResponseBuilder.success(null, 'File updated successfully'));
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
next(err);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
// 获取文件或目录信息
|
|
69
|
+
router.get('/get', async (req, res, next) => {
|
|
70
|
+
try {
|
|
71
|
+
const { path: targetPath = '/' } = req.query;
|
|
72
|
+
const fullPath = normalizePath(targetPath, config.rootDir);
|
|
73
|
+
const stats = await fs.stat(fullPath);
|
|
74
|
+
const self = await fs.lstat(fullPath);
|
|
75
|
+
const isDirectory = stats.isDirectory();
|
|
76
|
+
const isSymbolicLink = self.isSymbolicLink();
|
|
77
|
+
if (isDirectory) {
|
|
78
|
+
// 如果是目录,返回目录下的所有文件和子目录信息
|
|
79
|
+
const items = await fs.readdir(fullPath, { withFileTypes: true });
|
|
80
|
+
let realPath;
|
|
81
|
+
const contents = await Promise.all(items.map(async (item) => {
|
|
82
|
+
let beDir = item.isDirectory();
|
|
83
|
+
const itemPath = path.join(fullPath, item.name);
|
|
84
|
+
if (item.isSymbolicLink()) {
|
|
85
|
+
const targetStats = await fs.stat(itemPath);
|
|
86
|
+
beDir = targetStats.isDirectory();
|
|
87
|
+
// realPath = await fs.realpath(itemPath);
|
|
88
|
+
}
|
|
89
|
+
const itemStats = await fs.stat(itemPath);
|
|
90
|
+
const oItem = {
|
|
91
|
+
name: item.name,
|
|
92
|
+
path: path.relative(config.rootDir, itemPath).replace(/\\/g, '/'),
|
|
93
|
+
isDirectory: beDir,
|
|
94
|
+
isLink: item.isSymbolicLink(),
|
|
95
|
+
size: itemStats.size,
|
|
96
|
+
modifiedTime: itemStats.mtime.toISOString(),
|
|
97
|
+
mimeType: item.isDirectory() ? false : getMime(item.name),
|
|
98
|
+
isPreviewable: item.isDirectory() ? false : isPreviewAble(item.name),
|
|
99
|
+
isEditorViewable: item.isDirectory() ? false : isEditorAble(item.name)
|
|
100
|
+
};
|
|
101
|
+
if (realPath) {
|
|
102
|
+
// oItem.realPath = realPath;
|
|
103
|
+
}
|
|
104
|
+
return oItem;
|
|
105
|
+
}));
|
|
106
|
+
res.json(ApiResponseBuilder.success({
|
|
107
|
+
isDirectory: true,
|
|
108
|
+
path: path.relative(config.rootDir, fullPath).replace(/\\/g, '/'),
|
|
109
|
+
contents
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
// 如果是文件,返回文件信息
|
|
114
|
+
let fileName = path.basename(fullPath);
|
|
115
|
+
let realPath;
|
|
116
|
+
const oRes = {
|
|
117
|
+
isDirectory: false,
|
|
118
|
+
isLink: isSymbolicLink,
|
|
119
|
+
name: fileName,
|
|
120
|
+
path: path.relative(config.rootDir, fullPath).replace(/\\/g, '/'),
|
|
121
|
+
size: stats.size,
|
|
122
|
+
modifiedTime: stats.mtime.toISOString(),
|
|
123
|
+
mimeType: stats.isDirectory() ? false : getMime(fileName),
|
|
124
|
+
isPreviewable: stats.isDirectory() ? false : isPreviewAble(fileName),
|
|
125
|
+
isEditorViewable: stats.isDirectory() ? false : isEditorAble(fileName)
|
|
126
|
+
};
|
|
127
|
+
// if (stats.isSymbolicLink()) {
|
|
128
|
+
// realPath = await fs.realpath(fullPath);
|
|
129
|
+
// oRes.realPath = realPath;
|
|
130
|
+
// }
|
|
131
|
+
res.json(ApiResponseBuilder.success(oRes));
|
|
132
|
+
}
|
|
133
|
+
info(`Get : ${fullPath}`);
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
if (err.code === 'ENOENT') {
|
|
137
|
+
res.json(ApiResponseBuilder.notFound());
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
next(err);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
// 下载文件
|
|
145
|
+
router.post('/download', async (req, res, next) => {
|
|
146
|
+
try {
|
|
147
|
+
const { path: targetPath } = req.body;
|
|
148
|
+
const fullPath = normalizePath(targetPath, config.rootDir);
|
|
149
|
+
const stats = await fs.stat(fullPath);
|
|
150
|
+
if (stats.isDirectory()) {
|
|
151
|
+
throw new FileOperationError('Cannot download a directory', 400);
|
|
152
|
+
}
|
|
153
|
+
const filename = path.basename(fullPath);
|
|
154
|
+
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
|
155
|
+
res.setHeader('Content-Type', 'application/octet-stream');
|
|
156
|
+
res.setHeader('Content-Length', stats.size);
|
|
157
|
+
const fileStream = await fs.readFile(fullPath);
|
|
158
|
+
res.send(fileStream);
|
|
159
|
+
info(`Downloaded: ${fullPath}`);
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
next(err);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
return router;
|
|
166
|
+
}
|
|
167
|
+
// 文件操作错误
|
|
168
|
+
export class FileOperationError extends Error {
|
|
169
|
+
constructor(message, code = 500) {
|
|
170
|
+
super(message);
|
|
171
|
+
this.code = code;
|
|
172
|
+
this.name = 'FileOperationError';
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import { getMime } from '../types/index.js';
|
|
3
|
+
import { normalizePath } from '../utils/path.js';
|
|
4
|
+
import { sendFeReq } from "../common/adapter.js";
|
|
5
|
+
import fs from 'fs/promises';
|
|
6
|
+
import { info } from '../utils/logger.js';
|
|
7
|
+
import path from 'path';
|
|
8
|
+
import archiver from 'archiver';
|
|
9
|
+
export function createFileSystemRouter(config) {
|
|
10
|
+
const router = Router();
|
|
11
|
+
// 统一处理返回前端入口页面的函数
|
|
12
|
+
const sendClientPage = (req, res, next) => {
|
|
13
|
+
sendFeReq('index.html', req, res, next);
|
|
14
|
+
};
|
|
15
|
+
router.get('/*', async (req, res, next) => {
|
|
16
|
+
try {
|
|
17
|
+
const downloadFlag = req.query.download === 'true';
|
|
18
|
+
const viewFlag = req.query.view;
|
|
19
|
+
const editFlag = req.query.edit;
|
|
20
|
+
const requestPath = req.params[0]?.replace(/^fh\//, '') || '';
|
|
21
|
+
const fullPath = normalizePath(requestPath, config.rootDir);
|
|
22
|
+
const stats = await fs.stat(fullPath);
|
|
23
|
+
if (stats.isDirectory()) {
|
|
24
|
+
if (downloadFlag) {
|
|
25
|
+
// 创建zip压缩包
|
|
26
|
+
const archive = archiver('zip', {
|
|
27
|
+
zlib: { level: 9 } // 设置压缩级别
|
|
28
|
+
});
|
|
29
|
+
// 设置响应头
|
|
30
|
+
res.attachment(`${path.basename(fullPath)}.zip`);
|
|
31
|
+
archive.pipe(res);
|
|
32
|
+
// 将目录添加到zip,使用目录名作为根目录
|
|
33
|
+
archive.directory(fullPath, path.basename(fullPath));
|
|
34
|
+
// 完成压缩
|
|
35
|
+
await archive.finalize();
|
|
36
|
+
info(`Downloaded directory: ${fullPath}`);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
// 如果是目录请求,返回前端页
|
|
40
|
+
sendClientPage(req, res, next);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
// 处理文件
|
|
45
|
+
const fileExt = path.extname(fullPath).toLowerCase();
|
|
46
|
+
if (downloadFlag) {
|
|
47
|
+
res.download(fullPath);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
let mimeType = getMime(fullPath);
|
|
51
|
+
// 使用浏览器默认行为,否则viewable的使用text/plain,否则会触发下载
|
|
52
|
+
if (!viewFlag && !editFlag) {
|
|
53
|
+
!!mimeType && res.set('Content-Type', mimeType);
|
|
54
|
+
res.sendFile(fullPath, { dotfiles: 'allow' });
|
|
55
|
+
}
|
|
56
|
+
else if (editFlag) {
|
|
57
|
+
sendClientPage(req, res, next);
|
|
58
|
+
}
|
|
59
|
+
else if (viewFlag) {
|
|
60
|
+
sendClientPage(req, res, next);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
res.download(fullPath);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
info(`View file: ${fullPath}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
// 如果资源不存在或发生其他错误,返回前端入口页面显示404信息
|
|
71
|
+
if (err.code === 'ENOENT') {
|
|
72
|
+
// 设置404状态码,让前端知道是404错误
|
|
73
|
+
res.status(404);
|
|
74
|
+
sendClientPage(req, res, next);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
next(err);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
return router;
|
|
82
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import { buildPreviewerHtml, sendFeReq } from "../common/adapter.js";
|
|
3
|
+
export function createResourcesRouter(app, config) {
|
|
4
|
+
const routerRes = Router();
|
|
5
|
+
routerRes.get('/*', (req, res, next) => {
|
|
6
|
+
sendFeReq(null, req, res, next);
|
|
7
|
+
});
|
|
8
|
+
app.use('/res', routerRes);
|
|
9
|
+
const routerPreview = Router();
|
|
10
|
+
routerPreview.get('/*', (req, res, next) => {
|
|
11
|
+
sendFeReq({
|
|
12
|
+
'^.*': 'src/components/Preview/\\1/index.html'
|
|
13
|
+
}, req, res, next, function (content) {
|
|
14
|
+
return buildPreviewerHtml(content);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
app.use('/previewer', routerRes);
|
|
18
|
+
}
|