File size: 16,566 Bytes
9787a3e
 
 
 
 
 
 
 
 
9f46b96
9787a3e
ae656e3
 
c273984
9787a3e
 
 
 
0fdb96e
9787a3e
e05bace
 
9787a3e
 
e05bace
9787a3e
 
e05bace
 
 
 
9787a3e
e05bace
 
 
9787a3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05bace
 
9787a3e
c273984
 
 
 
 
 
 
 
e05bace
 
9787a3e
 
 
e05bace
 
 
c273984
9787a3e
e05bace
 
 
9787a3e
e05bace
 
9787a3e
 
 
e05bace
9787a3e
 
e05bace
 
 
9787a3e
e05bace
 
9787a3e
 
e05bace
78d9cf0
9787a3e
 
 
78d9cf0
 
 
 
9787a3e
78d9cf0
9787a3e
 
 
 
1fc7456
8ae982f
9787a3e
 
8ae982f
9787a3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d9cf0
 
9787a3e
 
 
e05bace
 
 
9787a3e
e05bace
 
78d9cf0
9787a3e
 
e05bace
 
 
 
 
9787a3e
e05bace
 
78d9cf0
 
9787a3e
78d9cf0
9787a3e
 
 
78d9cf0
9787a3e
78d9cf0
9787a3e
 
e05bace
 
 
9787a3e
e05bace
9787a3e
 
 
 
e05bace
c273984
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05bace
 
 
9787a3e
 
 
e05bace
 
 
9787a3e
 
e05bace
 
 
 
 
 
 
 
 
 
9787a3e
 
 
 
 
 
 
e05bace
 
 
 
 
9787a3e
 
 
e05bace
9787a3e
 
 
e05bace
 
 
 
9787a3e
 
 
 
 
 
 
 
 
 
e05bace
 
 
 
 
 
9787a3e
 
 
e05bace
9787a3e
 
 
 
 
 
 
e05bace
 
9787a3e
e05bace
 
9787a3e
e05bace
9787a3e
 
 
 
e05bace
 
 
 
9787a3e
 
 
e05bace
9787a3e
 
 
 
e05bace
 
9787a3e
 
 
e05bace
 
 
9787a3e
 
 
e05bace
 
9787a3e
 
 
e05bace
 
 
 
 
 
9787a3e
 
 
e05bace
 
 
9787a3e
 
 
e05bace
 
 
9787a3e
e05bace
9787a3e
 
 
e05bace
 
 
 
 
 
 
 
 
 
 
 
 
 
9787a3e
 
 
e05bace
 
 
9787a3e
 
 
e05bace
 
 
 
 
9787a3e
 
 
e05bace
9787a3e
 
 
e05bace
 
 
9787a3e
e05bace
9787a3e
 
e05bace
 
9787a3e
 
e05bace
 
9787a3e
e05bace
 
9787a3e
 
e05bace
 
9787a3e
 
e05bace
 
 
 
 
9787a3e
 
 
e05bace
 
 
 
9787a3e
 
e05bace
 
 
 
 
 
 
9787a3e
 
 
e05bace
 
 
9787a3e
e05bace
 
 
 
9787a3e
e05bace
c959c78
ffbb8f6
c959c78
 
 
 
 
 
 
ffbb8f6
c959c78
ffbb8f6
c959c78
 
 
 
 
 
 
 
 
 
 
 
9787a3e
 
c959c78
ae656e3
c959c78
 
 
 
 
 
 
 
 
 
 
 
 
 
9787a3e
 
 
c959c78
 
9787a3e
c959c78
 
 
 
 
9787a3e
 
c959c78
 
 
 
 
9787a3e
 
c959c78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9787a3e
c959c78
 
 
 
ae656e3
c959c78
ae656e3
c959c78
 
 
 
 
 
 
 
 
 
 
9787a3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d9cf0
e05bace
9787a3e
 
 
e05bace
 
9787a3e
 
 
 
 
e05bace
9787a3e
 
 
 
 
e05bace
9787a3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05bace
9787a3e
 
 
 
 
 
 
 
e05bace
9787a3e
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
const express = require("express");
const bodyParser = require("body-parser");
const { sha } = require("sha256quanvn");
const { PrismaClient } = require("@prisma/client");
const multer = require("multer");
const fs = require("fs");
const statusMonitor = require("express-status-monitor")({
    path: "/bee3hivestatuspagethatnoonewillrememberthisurl",
    title: "Bee3Hive API Status",
});
const cors = require("cors");
const { withAccelerate } = require("@prisma/extension-accelerate");
const { error } = require("console");
const prisma = new PrismaClient().$extends(withAccelerate())
const app = express();

const SALT = process.env.PRIVATE_KEY;

const services = ["https://quanvndzai-ipfs-server-1.hf.space"];
const queueFileUpload = {};

const info = (message) => {
    console.log(`<${new Date()}> [INFO] - ${message}`);
};
const warn = (message) => {
    console.log(`<${new Date()}> [INFO] - ${message}`);
};

//* Sussy bigint thing
BigInt.prototype["toJSON"] = function () {
    return this.toString();
};

//* Safe Base64 Encode
const safeb64 = (str) => {
    return btoa(str).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
};


/**
 * Returns a new array with all duplicates removed.
 *
 * @param {Array} a - The array to remove duplicates from.
 * @return {Array} - A new array with all duplicates removed.
 */
function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}


/**
 * Generates a new JSON Web Token for the given user ID, and returns it as a string.
 *
 * The token is valid for 1 day, and is signed with the server's private key.
 *
 * @param {number} id - The user's ID.
 * @return {string} A new JSON Web Token, as a string.
 */
const generateJWT = async (id) => {
    const header = {
        alg: "SHA256QUANVN",
        typ: "JWT",
    };

    const payload = {
        id: id,
        exp: Date.now() + 3600000 * 24 * 7, // 7 days
    };

    await prisma.users.update({
        where: {
            id: payload.id,
        },
        data: {
            last_login: new Date(),
        },
    });

    const token =
        safeb64(JSON.stringify(header)) + "." + safeb64(JSON.stringify(payload));

    const sig = sha(token + "." + SALT);

    info("Generated new token for user: " + id);
    // console.log("New Token generated: " + token + "." + sig)

    return token + "." + safeb64(sig);
};

const generateFileID = () => {
    const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let fileID = "";
    for (let i = 0; i < 6; i++) {
        fileID += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return fileID;
};

async function checkServer() {
    // info("Checking servers...");
    for(var i = services.length - 1; i >= 0; i--) {
        try {
            const resp = await fetch(services[i] + "/availible");

            if(!resp.ok) {
                // This server is ded but can try again later lol
                info(await resp.text());
                warn("Server " + services[i] + " fail to ping");
                continue;
            }

            const data = await resp.text();
            // info(data)
            if(data != "\"Ok!\"") {
                //This server is full
                warn("Server " + services[i] + " is full");
                services.splice(i, 1);
            }
        } catch(e) {
            // This server is ded but can try again later lol
            warn("Server " + services[i] + " fail to fetch");
            // services.splice(i, 1);
        }
    }
}

setInterval(checkServer, 60 * 1000)
checkServer()

// Configure Multer storage
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "uploads/");
    },
    filename: (req, file, cb) => {
        // cb(null, generateFileID() + '-' + Date.now());
        cb(null, generateFileID() + "-" + file.originalname);
    },
});

// Set file size limit to 10GB
const upload = multer({
    storage: storage,
    limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10GB
});

// console.log(file)

const current_connections = [];

app.use(
    cors({
        origin: "*",
    })
);

app.use(bodyParser.json()); //utilizes the body-parser package
app.use(bodyParser.urlencoded({extended: true}));

app.use(statusMonitor);

app.use("/upload_queue", express.static("uploads"));

app.get(
    "/bee3hivestatuspagethatnoonewillrememberthisurl",
    statusMonitor.pageRoute
);

app.get("/bee3hive/internal/files/:node_id", async (req, res) => {
    // TODO: Make database query for services
    const node_id = req.params.node_id;
    const record = await prisma.storage.findMany({
        where: {
            handle: node_id,
        },
        cacheStrategy: {
            ttl: 60, //* 1 min
        },
    })

    if(!record) {
        res.sendStatus(404);
        return;
    }

    res.send(record);
})

// TODO: Make database query for services

app.post("/auth/email/register", async (req, res) => {
    let { username, email, password } = req.body;

    if (!username || !email || !password) {
        info("Missing required fields registration");
        res.sendStatus(400);
        return;
    }

    if (username.length < 6) {
        info("Username: " + username + " is too short!");
        res.sendStatus(400);
        return;
    }

    username = username.trim();
    password = password.trim();
    email = email.trim();

    // console.log(username, email, password)

    if (
        ["admin", "administrator", "root", "user", "anonymous", "guest"].includes(
            username
        )
    ) {
        warn("Username not allowed: " + username);
        res.sendStatus(401);
        return;
    }

    const record = await prisma.users.findUnique({
        where: {
            email: email,
        },
    });

    if (record) {
        info("User already exists: " + username);
        res.status(400).send({ error: "Username already exists" });
        return;
    }

    try {
        info(
            "Creating user: " +
            email +
            " username: " +
            username +
            " password: " +
            sha(password) +
            " " +
            new Date()
        );

        const created = await prisma.users.create({
            data: {
                username: username,
                email: email,
                password_hash: sha(password),
                last_login: new Date(),
            },
        });

        info("User created: " + email + " username: " + username);
        res.send({ token: await generateJWT(created.id) });
        return;
    } catch (e) {
        warn("Error on creating users");
        console.log(e);
        res.sendStatus(500);
        return;
    }
});

app.post("/auth/email/login", async (req, res) => {
    const { email, password } = req.body;

    if (!email || !password) {
        info("Missing required fields login");
        res.sendStatus(400);
        return;
    }

    const record = await prisma.users.findUnique({
        where: {
            email: email,
        },
    });

    if (!record) {
        info("User not found: " + email);
        res.sendStatus(401);
        return;
    }

    if (record.password_hash != sha(password)) {
        warn("Wrong password attempt: " + email);
        res.sendStatus(401);
        return;
    }

    info("User logged in: " + email);
    res.send({ token: await generateJWT(record.id) });
});

app.use(async (req, res, next) => {
    if (!req.headers.authorization) {
        info("Authorization header not found");
        res.sendStatus(401);
        return;
    }

    let token;
    try {
        token = req.headers.authorization.slice(7); // Bearer token
    } catch (e) {
        warn("Parsing token fail");
        console.log(e);
        return;
    }

    if (!token) {
        info("Token not found");
        res.sendStatus(401);
        return;
    }

    const [tokenHeader, tokenPayload, tokenSig] = token.split(".");

    if (!tokenHeader || !tokenPayload || !tokenSig) {
        info("Invalid token");
        res.sendStatus(401);
        return;
    }

    // console.log(tokenHeader, tokenPayload, tokenSig)

    try {
        // console.lo
        const header = JSON.parse(Buffer.from(tokenHeader, "base64").toString());
        const payload = JSON.parse(Buffer.from(tokenPayload, "base64").toString());
        const token_sig = Buffer.from(tokenSig, "base64").toString();
        const sig = sha(tokenHeader + "." + tokenPayload + "." + SALT);

        // console.log(header, payload, token_sig, sig)

        if (sig !== token_sig) {
            warn("Invalid signature");
            res.sendStatus(401);
            return;
        }

        if (Date.now() > payload.exp) {
            warn("Token expired");
            res.sendStatus(401);
            return;
        }

        const record = await prisma.users.findUnique({
            where: {
                id: payload.id,
            },
        });

        if (!record) {
            warn("Record not found");
            res.sendStatus(500); // How?
            return;
        }

        info("Authorized: " + record.id);

        req.user = record;
        next();
        return;
    } catch (e) {
        console.log(e);
        res.sendStatus(401);
        return;
    }
});

app.post("/auth/me", async (req, res) => {
    if (!Array.isArray(queueFileUpload[req.user.username])) {
        queueFileUpload[req.user.username] = [];
    }
    // User already authorize
    res.send(req.user);
});

app.post("/auth/delete", async (req, res) => {
    // User already authorize
    const { password } = req.body;

    if (!password) {
        info("Missing password when deleting user");
        res.sendStatus(400);
        return;
    }

    // Check password
    if (sha(password) != req.user.password_hash) {
        res.sendStatus(401);
        return;
    }

    // Delete User
    try {
        await prisma.users.delete({
            where: {
                id: req.user.id,
            },
        });
        res.sendStatus(200);
        return;
    } catch (e) {
        warn("Error on deleting user");
        console.log(e);
        res.sendStatus(500);
        return;
    }
});

app.post("/file/upload", upload.single("file"), async (req, res) => {

    try {
        const tests = fs.readdirSync("uploads");
        console.log(tests)
        console.log(req.file)
        const upload_path = req.file.path;
        const file_path = req.body.filePath;
        const full_file_path = req.user.username + (file_path ? "/" + file_path : "");

        // Upload the file to another backend

        if(services.length == 0) {
            res.status(500).send("Service unavailable");
            return;
        }

        const server = services[Math.floor(Math.random() * services.length)];

        const body = {
            filename: file_path,
            directory: full_file_path,
            username: req.user.username,
            fileURI: req.file.filename,
        }

        // console.log(body)

        // Upload the file
        try {
            info("Uploading file to " + server);
            const resp = await fetch(server + "/fetch", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(body),
            });

            if(!resp.ok) {
                warn(await resp.text());
                res.sendStatus(500);
                return;
            }

            const json = await resp.json();
            console.log(json)

            if(await prisma.storage.findUnique({ where: { dir: full_file_path } })) {
                // File already exists and same content
                warn("File already exists. No override: " + full_file_path);
                res.sendStatus(200);
                return;
            }

            if(await prisma.storage.findUnique({ where: { dir: full_file_path } })) {
                warn("File already exists. Override: " + full_file_path);
                await prisma.storage.update({
                    where:{
                        dir: full_file_path
                    },

                    data: {
                        handle: server,
                        username: req.user.username,
                        CID: json[0].Hash,
                        size: +json[0].Size,
                        dir: full_file_path,
                    }
                })
            } else {
                info("Adding record: " + full_file_path);
                //* Add record
                await prisma.storage.create({
                    data: {
                        handle: server,
                        username: req.user.username,
                        CID: json[0].Hash,
                        size: +json[0].Size,
                        dir: full_file_path,
                    }
                })
            }
        } catch (e) {
            warn("Error on uploading file");
            console.log(e);
            res.sendStatus(500);
            fs.unlinkSync(upload_path);
            return;
        }

        fs.unlinkSync(upload_path);

        info("File uploaded successfully: " + full_file_path);
        res.send("File uploaded successfully.");
    } catch (error) {
        // Fail to upload
        warn("File upload failed");
        console.log(error);
        res.status(500).send("File upload failed.");
    }
});

app.get("/file/list", async (req, res) => {
    const filePath = req.query.filePath;
    const recursive = req.query.recursive == "true";
    const files = []

    const setsDirectory = []

    try{
        const record = await prisma.storage.findMany({
            where: {
                username: req.user.username,
            }
        })

        for (const r of record) {
            const path = r.dir ? r.dir.split("/") : [];
            // remove first element too
            if(path.length > 1) {
                path.shift();
                path.pop();
            } else {
                path = [];
            }
            // console.log(path)
            let dir = "";
            for (const p of path) {
                dir += p;
                setsDirectory.push({
                    type:"directory",
                    dir
                });
            }

            r.type = "file";

            files.push(r)
        }
    } catch (e) {
        info("No file found")
        console.log(e)
    }
    res.send(files.concat(uniq(setsDirectory)));
})

app.post("/file/delete", async (req, res) => {
    const filePath = req.body.filePath;
    const full_file_path = req.user.username + (filePath ? "/" + filePath : "");


    const record = await prisma.storage.findUnique({
        where: {
            dir: full_file_path,
        }
    })

    if(!record) {
        warn("File not found: " + (full_file_path ? (full_file_path + "/") : ""))
        res.status(404).send("File not found.");
        return;
    }

    try {
        // Tell the server to unpin the file
        const resp = await fetch(record.handle + "/delete", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                CID: record.CID
            }),
        })

        if(!resp.ok) {
            throw "Respone not ok";
        }

        console.log(await resp.json())

        await prisma.storage.delete({
            where: {
                CID: record.CID
            }
        })
    } catch (e) {
        console.log(e);
        res.sendStatus(500);
        return;
    }

    info("File deleted: " + (filePath ? (filePath + "/") : ""))
    res.send("File deleted successfully.");
})

app.post("/file/getdownloadurl", async (req, res) => {
    const filePath = req.body.filePath;
    const full_file_path = req.user.username + (filePath ? "/" + filePath : "");


    info("Get download url: " + full_file_path)

    const record = await prisma.storage.findUnique({
        where: {
            dir: full_file_path
        }
    })

    if(!record) {
        res.status(404).send("File not found")
        return;
    }

    try {
        const IPFS_GATEWAY = "https://ipfs.io/ipfs/";
        res.send(IPFS_GATEWAY + record.CID);
    } catch(e) {
        console.log(e);
        res.sendStatus(500)
    }
})

app.listen(7860, () => info("Server started on port 7860"));