-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
164 lines (133 loc) · 5.09 KB
/
Copy pathserver.js
File metadata and controls
164 lines (133 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
const express = require('express');
const cors = require('cors');
const path = require('path');
const https = require('https');
const http = require('http');
const fs = require('fs');
const WebSocket = require('ws');
require('dotenv').config();
require('./db/init');
const siliconflowRoutes = require('./routes/siliconflow');
const fileSystemRoutes = require('./routes/fileSystem');
const configRoutes = require('./routes/config');
const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.static('public'));
app.use('/media', express.static('media'));
app.use('/api/chat', siliconflowRoutes);
app.use('/api/files', fileSystemRoutes);
app.use('/api/config', configRoutes);
app.get('/remote', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'remote.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
let server;
if (process.env.HTTPS === 'true') {
const privateKey = fs.readFileSync(process.env.SSL_KEY || 'server.key', 'utf8');
const certificate = fs.readFileSync(process.env.SSL_CERT || 'server.cert', 'utf8');
const credentials = {key: privateKey, cert: certificate};
server = https.createServer(credentials, app);
console.log('HTTPS mode enabled');
} else {
server = http.createServer(app);
console.log('HTTP mode enabled');
}
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('New remote client connected');
ws.on('message', async (message) => {
try {
const data = JSON.parse(message);
if (data.type === 'file-operation') {
const result = await handleFileOperation(data);
ws.send(JSON.stringify({ type: 'file-result', id: data.id, result }));
} else if (data.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong' }));
}
} catch (error) {
ws.send(JSON.stringify({ type: 'error', error: error.message }));
}
});
ws.on('close', () => {
console.log('Remote client disconnected');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
async function handleFileOperation(data) {
const { operation, path: filePath, content } = data;
const ALLOWED_BASE_PATH = process.env.WORKSPACE_PATH || path.join(__dirname, 'workspace');
function validatePath(requestedPath) {
const resolvedPath = path.resolve(requestedPath);
const resolvedBase = path.resolve(ALLOWED_BASE_PATH);
if (!resolvedPath.startsWith(resolvedBase)) {
throw new Error('Access denied: Path outside workspace');
}
return resolvedPath;
}
switch (operation) {
case 'read':
return await readFile(filePath, validatePath);
case 'write':
return await writeFile(filePath, content, validatePath);
case 'list':
return await listDirectory(filePath, validatePath);
case 'delete':
return await deletePath(filePath, validatePath);
case 'create':
return await createPath(filePath, data.fileType, validatePath);
default:
throw new Error('Unknown operation');
}
}
async function readFile(filePath, validatePath) {
const targetPath = validatePath(path.join(ALLOWED_BASE_PATH, filePath));
const content = await fs.promises.readFile(targetPath, 'utf8');
return { success: true, content };
}
async function writeFile(filePath, content, validatePath) {
const targetPath = validatePath(path.join(ALLOWED_BASE_PATH, filePath));
await fs.promises.writeFile(targetPath, content, 'utf8');
return { success: true };
}
async function listDirectory(dir, validatePath) {
const targetPath = validatePath(path.join(ALLOWED_BASE_PATH, dir || '.'));
const items = await fs.promises.readdir(targetPath, { withFileTypes: true });
const result = items.map(item => ({
name: item.name,
path: path.join(dir || '.', item.name),
type: item.isDirectory() ? 'directory' : 'file'
}));
return { success: true, items: result };
}
async function deletePath(filePath, validatePath) {
const targetPath = validatePath(path.join(ALLOWED_BASE_PATH, filePath));
const stats = await fs.promises.stat(targetPath);
if (stats.isDirectory()) {
await fs.promises.rm(targetPath, { recursive: true, force: true });
} else {
await fs.promises.unlink(targetPath);
}
return { success: true };
}
async function createPath(filePath, fileType, validatePath) {
const targetPath = validatePath(path.join(ALLOWED_BASE_PATH, filePath));
if (fileType === 'directory') {
await fs.promises.mkdir(targetPath, { recursive: true });
} else {
await fs.promises.writeFile(targetPath, '', 'utf8');
}
return { success: true };
}
server.listen(PORT, HOST, () => {
console.log(`Locode server running at http${process.env.HTTPS === 'true' ? 's' : ''}://${HOST}:${PORT}`);
console.log(`Local access: http${process.env.HTTPS === 'true' ? 's' : ''}://localhost:${PORT}`);
console.log(`Network access: http${process.env.HTTPS === 'true' ? 's' : ''}://<your-ip-address>:${PORT}`);
console.log(`WebSocket server ready for remote connections`);
});