Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
64 lines (56 loc) · 2.4 KB
/
Copy pathserver.js
File metadata and controls
64 lines (56 loc) · 2.4 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
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 3000;
const apiWindows = new Map();
app.disable('x-powered-by');
app.use((req, res, next) => {
res.set({
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()'
});
next();
});
app.use(express.json({ limit: '8kb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', (req, res, next) => {
const now = Date.now();
const key = req.ip || req.socket.remoteAddress || 'unknown';
const current = apiWindows.get(key);
const windowState = !current || now >= current.resetAt
? { count: 1, resetAt: now + 60_000 }
: { count: current.count + 1, resetAt: current.resetAt };
apiWindows.set(key, windowState);
res.setHeader('RateLimit-Limit', '30');
res.setHeader('RateLimit-Remaining', String(Math.max(0, 30 - windowState.count)));
res.setHeader('RateLimit-Reset', String(Math.ceil(windowState.resetAt / 1000)));
if (windowState.count > 30) return res.status(429).json({ error: 'Too many requests. Please wait a moment and try again.' });
if (apiWindows.size > 1000) {
for (const [storedKey, value] of apiWindows) if (now >= value.resetAt) apiWindows.delete(storedKey);
}
next();
});
// Media extraction intentionally never runs on cloud web hosting. The browser uses the
// loopback-only Savewave Helper for resolve and download operations.
app.all(['/api/resolve', '/api/prepare-download', '/api/stream'], (_req, res) => {
return res.status(410).json({
error: 'Savewave Helper is required. Media extraction runs locally on your device.'
});
});
app.use((error, req, res, next) => {
if (!error) return next();
if (error.type === 'entity.too.large') return res.status(413).json({ error: 'Request body is too large.' });
if (error instanceof SyntaxError && error.status === 400) return res.status(400).json({ error: 'Malformed JSON request.' });
return next(error);
});
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});
if (require.main === module) {
server.listen(PORT, () => console.log(`Savewave web frontend running at http://localhost:${PORT}`));
}
module.exports = app;