-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (63 loc) · 2.66 KB
/
index.js
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
import {Database} from "bun:sqlite";
const db = new Database("links.db");
function createRedirect(body){
let code = body.requestedCode;
if(code){
console.log("Creating: ", body.requestedCode)
db.query("INSERT INTO links (code, link) VALUES (?1, ?2)").run(body.requestedCode, body.link);
}
else{
do{
code = ""
for(let i = 0; i < 3; i++)
code += String.fromCharCode(Math.floor(Math.random() * 26)+65)
}while(db.query("SELECT link FROM links WHERE code=?").get(code) || Bun.file('/'+code).size || Bun.file('/'+code+'/index.html').size)
db.query("INSERT INTO links (code, link) VALUES (?1, ?2)").run(code, body.link);
}
return new Response(code, {status: 200});
}
const server = Bun.serve({
port: process.env.SHORTLINKS_PORT || 80,
async fetch(req) {
switch(req.method){
case "GET":
let filepath = "public" + new URL(req.url).pathname;
if(filepath.slice(-1) == "/")
filepath += "index.html";
const file = Bun.file(filepath);
if(file.size) // Invalid paths create a file with size 0
return new Response(file);
else{
const sqlResult = db.query("SELECT link FROM links WHERE code=?").get(new URL(req.url).pathname.slice(1));
if(sqlResult && sqlResult.link)
return new Response(null, {headers: {Location: sqlResult.link}, status: 302});
else
return new Response(null, {status: 404});
}
break;
case "POST":
let data;
try{
data = await req.json();
} catch(err){
return new Response("Error parsing JSON body", {status: 400});
}
if(!data.link)
return new Response("Missing destination link", {status: 400});
if(data.requestedCode){
console.log("Recieved request for : ", data.requestedCode)
if(!data.requestedCode.match(/^([0-9]|[a-z])+([0-9a-z]+)$/i))
return new Response("Requested path denied. Either non alphanumeric characters were used or the length was less than 2.", {status: 409})
const checkFolder = Bun.file("public/" + data.requestedCode + "index.html");
const checkFile = Bun.file("public/" + data.requestedCode);
const checkSQL = db.query("SELECT link FROM links WHERE code=?").get(data.requestedCode);
if(checkFolder.size || checkFile.size || checkSQL)
return new Response("Requested path denied. Path exists.", {status: 409})
}
return createRedirect(data);
break;
}
},
});
db.query("CREATE TABLE IF NOT EXISTS links (code TEXT PRIMARY KEY, link TEXT)").run();
console.log(`Server running on port ${server.port}`);