-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
277 lines (230 loc) · 8.71 KB
/
server.js
File metadata and controls
277 lines (230 loc) · 8.71 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const url = require('url');
const { fileURLToPath } = require('url');
const path = require('path');
const https = require('https');
const fs = require('fs');
const app = express();
const MAX_DOWNLOAD_SIZE_KB = parseInt(process.env.SERVER_MAX_DOWNLOAD_SIZE_KB, 10) || 2 * 1024;
// Enable CORS and increase payload limit
app.use(cors());
app.use(express.json({
limit: process.env.SERVER_JSON_LIMIT || '2mb'
}));
app.use(express.urlencoded({
extended: true,
limit: process.env.SERVER_URLENCODED_LIMIT || '2mb'
}));
// Custom axios instance with extended timeout and SSL handling
const client = axios.create({
timeout: 60000,
maxBodyLength: Infinity,
maxContentLength: Infinity,
httpsAgent: new https.Agent({
rejectUnauthorized: false,
keepAlive: true
}),
// Important for Google Drive: follow redirects
maxRedirects: 5
});
// Headers builder function
const buildHeaders = (fileUrl) => {
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Connection': 'keep-alive'
};
return headers;
};
app.get('/', (req, res) => {
const indexPath = path.join(__dirname, 'index.html');
fs.readFile(indexPath, 'utf8', (err, data) => {
if (err) {
console.error("File read error:", err);
return res.status(500).send('Error loading index.html');
}
res.setHeader('Content-Type', 'text/html');
res.send(data);
});
});
app.use(express.static(__dirname));
const ALLOWED_DOMAINS_FOR_DOWNLOAD = new Set(
(process.env.SERVER_ALLOWED_DOMAINS_FOR_DOWNLOAD || '').split(',')
);
const ALLOWED_LOCAL_ROOTS = (process.env.SERVER_ALLOWED_LOCAL_ROOTS || __dirname)
.split(',')
.map(entry => entry.trim())
.filter(Boolean)
.map(entry => path.resolve(entry));
function isAllowedDomain(fileUrl) {
try {
const parsedUrl = new URL(fileUrl);
const domain = parsedUrl.hostname;
if (ALLOWED_DOMAINS_FOR_DOWNLOAD.has('*')) {
return true;
}
return ALLOWED_DOMAINS_FOR_DOWNLOAD.has(domain);
} catch {
return false;
}
}
function isAllowedLocalPath(filePath) {
const resolvedPath = path.resolve(filePath);
return ALLOWED_LOCAL_ROOTS.some(root => {
const relative = path.relative(root, resolvedPath);
return !relative.startsWith('..') && !path.isAbsolute(relative);
});
}
// Download endpoint
app.get('/download', async (req, res) => {
const { url: fileUrl } = req.query;
if (!fileUrl) {
return res.status(400).json({ error: 'URL parameter is required' });
}
try {
console.log(`Attempting to download: ${fileUrl}`);
const parsedUrl = new URL(fileUrl);
if (parsedUrl.protocol === 'file:') {
const localPath = fileURLToPath(fileUrl);
if (!isAllowedLocalPath(localPath)) {
console.error(`Local path not allowed: ${localPath}`);
return res.status(403).json({ error: 'Local path not allowed' });
}
const stats = await fs.promises.stat(localPath);
if (!stats.isFile()) {
return res.status(400).json({ error: 'Requested path is not a file' });
}
const fileSizeKB = stats.size / 1024;
if (fileSizeKB > MAX_DOWNLOAD_SIZE_KB) {
console.error(`Local file exceeds max size: ${fileSizeKB.toFixed(2)} KB`);
return res.status(413).json({
error: 'File too large',
details: `Maximum allowed size is ${MAX_DOWNLOAD_SIZE_KB} KB`
});
}
const fileName = path.basename(localPath);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Length', stats.size);
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.setHeader('Last-Modified', stats.mtime.toUTCString());
const readStream = fs.createReadStream(localPath);
readStream.on('error', (error) => {
console.error('Local file stream error:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Unable to read local file', details: error.message });
} else {
res.end();
}
});
readStream.pipe(res);
readStream.on('end', () => {
console.log(`Successfully served local file: ${localPath}, Total size: ${fileSizeKB.toFixed(2)} KB`);
});
return;
}
if (!isAllowedDomain(fileUrl)) {
return res.status(403).json({ error: 'Domain not allowed' });
}
// Invia richiesta remota
let response = await client({
method: 'GET',
url: fileUrl,
responseType: 'stream',
headers: buildHeaders(fileUrl)
});
// Imposta il nome del file
let fileName = path.basename(url.parse(fileUrl).pathname);
const contentDispositionHeader = response.headers['content-disposition'];
if (contentDispositionHeader) {
const match = contentDispositionHeader.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match) {
fileName = match[1].replace(/['"]/g, '');
}
}
// Imposta intestazioni di risposta
res.setHeader('Content-Type', response.headers['content-type'] || 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
// Copia intestazioni opzionali
['last-modified', 'etag'].forEach(header => {
if (response.headers[header]) {
res.setHeader(header, response.headers[header]);
}
});
// Misura la dimensione durante il download
let downloadedSizeBytes = 0;
response.data.on('data', (chunk) => {
downloadedSizeBytes += chunk.length;
// Converti i byte in KB
const downloadedSizeKB = downloadedSizeBytes / 1024;
// Interrompi il download se supera la dimensione massima
if (downloadedSizeKB > MAX_DOWNLOAD_SIZE_KB) {
console.error(`File exceeds max size during download: ${downloadedSizeKB.toFixed(2)} KB`);
res.status(413).json({
error: 'File too large',
details: `Maximum allowed size is ${MAX_DOWNLOAD_SIZE_KB} KB`
});
// Interrompi lo streaming
response.data.destroy();
}
});
// Gestisci gli errori durante lo streaming
response.data.on('error', (error) => {
console.error('Stream error:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Stream error', details: error.message });
}
});
// Stream il file al client
response.data.pipe(res).on('error', (error) => {
console.error('Pipe error:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Pipe error', details: error.message });
}
});
response.data.on('end', () => {
console.log(`Successfully downloaded: ${fileUrl}, Total size: ${(downloadedSizeBytes / 1024).toFixed(2)} KB`);
});
} catch (error) {
console.error('Download error:', error);
const statusCode = error.response?.status || 500;
res.status(statusCode).json({
error: 'Download failed',
details: error.message,
status: statusCode
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Server error:', err);
res.status(500).json({
error: 'Internal server error',
details: err.message
});
});
// Start server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Access the application at http://localhost:${PORT}`);
});
// Handle process termination
process.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing HTTP server');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGINT signal received: closing HTTP server');
process.exit(0);
});