index.ts
| 1 | import { Elysia, StatusMap, t } from "elysia" |
| 2 | import { Database } from "bun:sqlite" |
| 3 | import { randomUUIDv7 } from "bun" |
| 4 | import staticPlugin from "@elysiajs/static" |
| 5 | import { html } from '@elysiajs/html' |
| 6 | import crypto from 'crypto' |
| 7 | import { DecryptFile, filetypes, Index, NotFound, SetCookie, ShowFile, WrongPassword } from "./components" |
| 8 | import cron from "@elysiajs/cron" |
| 9 | |
| 10 | |
| 11 | //TODO: add deletion timer |
| 12 | |
| 13 | const db = new Database("./db.sqlite") |
| 14 | db.exec("PRAGMA foreign_keys = ON") |
| 15 | db.exec("PRAGMA journal_mode = WAL2") |
| 16 | db.exec("CREATE TABLE IF NOT EXISTS files (uuid TEXT PRIMARY KEY, filename TEXT NOT NULL, content BLOB NOT NULL, filetype TEXT NOT NULL, encrypted INTEGER NOT NULL, delete_at INTEGER) STRICT") |
| 17 | db.exec("PRAGMA optimize") |
| 18 | |
| 19 | |
| 20 | function encrypt(content: Uint8Array, password: string): Buffer<ArrayBuffer> { |
| 21 | let iv = crypto.randomBytes(16) |
| 22 | const salt = crypto.randomBytes(16) |
| 23 | const key = crypto.pbkdf2Sync(password, salt, 100000, 32, "sha512") |
| 24 | let cipher = crypto.createCipheriv('aes-256-cbc', key, iv) |
| 25 | let encrypted_content = Buffer.concat([salt, iv, cipher.update(content), cipher.final()]) |
| 26 | return encrypted_content |
| 27 | } |
| 28 | |
| 29 | function decrypt(encrypted_content: Uint8Array, password: string): Buffer { |
| 30 | const salt = encrypted_content.slice(0, 16) |
| 31 | const iv = encrypted_content.slice(16, 32) |
| 32 | const key = crypto.pbkdf2Sync(password, salt, 100000, 32, "sha512") |
| 33 | let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv) |
| 34 | let content = Buffer.concat([decipher.update(encrypted_content.slice(32)), decipher.final()]) |
| 35 | return content |
| 36 | } |
| 37 | |
| 38 | function stringArrayToEnum<T extends string>( |
| 39 | arr: readonly T[] |
| 40 | ): { [K in T]: K } { |
| 41 | return arr.reduce((acc, key) => { |
| 42 | acc[key] = key; |
| 43 | return acc; |
| 44 | }, Object.create(null)); |
| 45 | } |
| 46 | |
| 47 | const app = new Elysia({ |
| 48 | serve: { |
| 49 | maxRequestBodySize: 1024 * 1024 * 1024 // 1GB |
| 50 | } |
| 51 | }) |
| 52 | .use(staticPlugin({ assets: "./assets", prefix: "/" })) |
| 53 | .use(html()) |
| 54 | .use(cron({ |
| 55 | name: "delete", |
| 56 | pattern: "*/5 * * * * *", |
| 57 | run() { |
| 58 | db.exec("DELETE FROM files WHERE delete_at < strftime('%s', 'now')") |
| 59 | } |
| 60 | })) |
| 61 | .get("/", ({ server }) => Index(server?.url.toString()!, false)) |
| 62 | .get("/js", ({ server }) => Index(server?.url.toString()!, true)) |
| 63 | .post("/upload", async ({ set, body, query }) => { |
| 64 | |
| 65 | const uuid = randomUUIDv7() |
| 66 | let content = Buffer.from(await body.file.bytes()) |
| 67 | let encrypted = false; |
| 68 | let delete_at: number | null = null |
| 69 | if (body.delete_in_minutes) { |
| 70 | delete_at = Math.floor(Date.now() / 1000) + Number(body.delete_in_minutes) * 60 |
| 71 | } |
| 72 | if (body.encrypted === "on") { |
| 73 | encrypted = true |
| 74 | } else if (body.password) { |
| 75 | content = encrypt(content, body.password) |
| 76 | encrypted = true |
| 77 | } |
| 78 | db.exec("INSERT INTO files (uuid, filename, content, filetype, encrypted, delete_at) VALUES (?, ?, ?, ?, ?, ?)", |
| 79 | [uuid, body.filename || body.file.name, content, body.filetype, encrypted, delete_at]) |
| 80 | set.status = StatusMap["See Other"] |
| 81 | if (query.withJs) { |
| 82 | set.headers["location"] = `/show-js/${uuid}` |
| 83 | } else { |
| 84 | set.headers["location"] = `/show/${uuid}` |
| 85 | } |
| 86 | return `Created with id: ${uuid}` |
| 87 | |
| 88 | }, { |
| 89 | body: t.Object({ |
| 90 | file: t.File(), |
| 91 | filename: t.Optional(t.String()), |
| 92 | //filetype: t.String()/*todo:verifiy via t.Enum*/, |
| 93 | filetype: t.Enum(stringArrayToEnum(filetypes)), |
| 94 | password: t.Optional(t.String()), |
| 95 | encrypted: t.Optional(t.String()), |
| 96 | delete_in_minutes: t.String({ format: "regex", pattern: "(^$|^[0-9]+$)" }) |
| 97 | }), |
| 98 | query: t.Object({ withJs: t.Optional(t.Boolean()) }) |
| 99 | }) |
| 100 | .get("/show/:uuid", async ({ set, params, cookie }) => { |
| 101 | |
| 102 | const result = db.prepare("SELECT filename, content, filetype, encrypted, delete_at FROM files WHERE uuid = ?").get(params.uuid) as |
| 103 | { filename: string, content: Uint8Array, filetype: string, encrypted: boolean, delete_at: number | null } || null |
| 104 | if (!result) { |
| 105 | set.status = StatusMap["Not Found"] |
| 106 | return NotFound() |
| 107 | } |
| 108 | if (result.encrypted) { |
| 109 | const password = cookie.password.value |
| 110 | if (!password) { |
| 111 | return DecryptFile(result.filename, params.uuid) |
| 112 | } else { |
| 113 | try { |
| 114 | result.content = decrypt(result.content, password) |
| 115 | } catch (e) { |
| 116 | set.status = StatusMap["Forbidden"] |
| 117 | set.headers["set-cookie"] = [ |
| 118 | `password=; Path=/show/${params.uuid}; SameSite=lax; HttpOnly; Expires=Thu, 01 Jan 1970 00:00:00 GMT`, |
| 119 | `password=; Path=/raw/${params.uuid}; SameSite=lax; HttpOnly; Expires=Thu, 01 Jan 1970 00:00:00 GMT` |
| 120 | ] |
| 121 | return WrongPassword() |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | return ShowFile(result.filename, params.uuid, result.content, result.filetype, result.delete_at) |
| 126 | |
| 127 | }, { params: t.Object({ uuid: t.String() }) }) |
| 128 | .get("/show-js/:uuid", async ({ set, params, cookie }) => { |
| 129 | |
| 130 | const result = db.prepare("SELECT filename, content, filetype, encrypted, delete_at FROM files WHERE uuid = ?").get(params.uuid) as |
| 131 | { filename: string, content: Uint8Array, filetype: string, encrypted: boolean, delete_at: number | null } || null |
| 132 | if (!result) { |
| 133 | set.status = StatusMap["Not Found"] |
| 134 | return NotFound() |
| 135 | } |
| 136 | return ShowFile(result.filename, params.uuid, null, result.filetype, result.delete_at) |
| 137 | |
| 138 | }, { params: t.Object({ uuid: t.String() }) }) |
| 139 | .post("/set-cookie/:uuid", ({ set, body, params }) => { |
| 140 | |
| 141 | set.headers["set-cookie"] = [ |
| 142 | `password=${body.password}; Path=/show/${params.uuid}; SameSite=lax; HttpOnly`, |
| 143 | `password=${body.password}; Path=/raw/${params.uuid}; SameSite=lax; HttpOnly` |
| 144 | ] |
| 145 | set.headers["location"] = `/show/${params.uuid}` |
| 146 | set.status = StatusMap["See Other"] |
| 147 | return SetCookie(params.uuid) |
| 148 | |
| 149 | }, { body: t.Object({ password: t.String() }), params: t.Object({ uuid: t.String() }) }) |
| 150 | .get("/raw/:uuid", ({ set, params, cookie, query }) => { |
| 151 | const result = db.prepare("SELECT content, filename, encrypted, filetype FROM files WHERE uuid = ?").get(params.uuid) as { content: Uint8Array, filename: string, encrypted: boolean, filetype: string } || null |
| 152 | if (!result) { |
| 153 | set.status = StatusMap["Not Found"] |
| 154 | return "File not found" |
| 155 | } |
| 156 | if (result.encrypted && query.ignore_password !== "true") { |
| 157 | if (!cookie.password.value) { |
| 158 | set.status = StatusMap["Unauthorized"] |
| 159 | return "This file is encrypted, set the cookie \"password\" with the correct password to allow the server to decrypt it" |
| 160 | } |
| 161 | try { |
| 162 | result.content = decrypt(result.content, cookie.password.value) |
| 163 | } catch (e) { |
| 164 | set.status = StatusMap["Forbidden"] |
| 165 | return "Incorrect password" |
| 166 | } |
| 167 | } |
| 168 | set.headers["encrypted"] = result.encrypted ? "true" : "false" |
| 169 | set.headers["filetype"] = result.filetype |
| 170 | set.headers["filename"] = result.filename |
| 171 | set.headers["content-disposition"] = `inline; filename=${result.filename}` |
| 172 | return result.content |
| 173 | |
| 174 | }, { params: t.Object({ uuid: t.String() }), cookie: t.Object({ password: t.Optional(t.String()) }), query: t.Object({ ignore_password: t.Optional(t.String()) }) }) |
| 175 | .listen(3000) |
| 176 | |
| 177 | console.log(`⚡ Zigbin is running at ${app.server?.hostname}:${app.server?.port} ⚡`) |