-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (67 loc) · 2.46 KB
/
Copy pathserver.js
File metadata and controls
90 lines (67 loc) · 2.46 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
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const crypto = require("crypto");
const rateLimit = require("express-rate-limit");
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const fileLinks = new Map();
const LINK_EXPIRY_TIME = 1 * 60 * 1000;
const limiter = rateLimit({
windowMs: 1 * 60 * 1000,
max: 10,
message: "Too many requests, please try again later.",
});
app.use(express.static("public"));
app.use("/share", limiter);
function generateShortID() {
return crypto.randomBytes(3).toString("hex");
}
function isValidMagnet(magnet) {
return /^magnet:\?xt=urn:[a-z0-9]+:[a-zA-Z0-9]{20,}/.test(magnet);
}
// WebSocket connection
wss.on("connection", (ws) => {
console.log("Client connected");
ws.on("message", (message) => {
try {
const data = JSON.parse(message);
if (data.type === "share") {
if (!isValidMagnet(data.magnet)) {
ws.send(JSON.stringify({ type: "error", message: "Invalid magnet link" }));
return;
}
const shortID = generateShortID();
fileLinks.set(shortID, {
magnet: data.magnet,
expiresAt: Date.now() + LINK_EXPIRY_TIME
});
ws.send(JSON.stringify({ type: "shortURL", url: `https://magnetdrop.onrender.com/share/${shortID}` }));
//ws.send(JSON.stringify({ type: "shortURL", url: `http://localhost:3000/share/${shortID}` }));
setTimeout(() => {
fileLinks.delete(shortID);
console.log(`Deleted expired link: ${shortID}`);
}, LINK_EXPIRY_TIME);
}
} catch (error) {
ws.send(JSON.stringify({ type: "error", message: "Invalid request format" }));
}
});
ws.on("close", () => {
console.log("Client disconnected");
});
});
app.get("/share/:id", (req, res) => {
const shortID = req.params.id;
const linkData = fileLinks.get(shortID);
if (linkData && Date.now() < linkData.expiresAt) {
res.redirect(`/?magnet=${encodeURIComponent(linkData.magnet)}`);
} else {
res.status(404).send("File not found or expired");
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});