import { randomInt, randomUUID } from "node:crypto"; import { rmSync } from "node:fs"; import { mkdir, unlink } from "node:fs/promises"; import { html, Html } from "@elysiajs/html"; import { jwt, type JWTPayloadSpec } from "@elysiajs/jwt"; import { staticPlugin } from "@elysiajs/static"; import { Database } from "bun:sqlite"; import { Elysia, t } from "elysia"; import sanitize from "sanitize-filename"; import { BaseHtml } from "./components/base"; import { Header } from "./components/header"; import { getAllInputs, getAllTargets, getPossibleTargets, mainConverter, } from "./converters/main"; import { normalizeFiletype, normalizeOutputFiletype, } from "./helpers/normalizeFiletype"; import "./helpers/printVersions"; mkdir("./data", { recursive: true }).catch(console.error); const db = new Database("./data/mydb.sqlite", { create: true }); const uploadsDir = "./data/uploads/"; const outputDir = "./data/output/"; const ACCOUNT_REGISTRATION = process.env.ACCOUNT_REGISTRATION?.toLowerCase() === "true" || false; const HTTP_ALLOWED = process.env.HTTP_ALLOWED?.toLowerCase() === "true" || false; const ALLOW_UNAUTHENTICATED = process.env.ALLOW_UNAUTHENTICATED?.toLowerCase() === "true" || false; const AUTO_DELETE_EVERY_N_HOURS = process.env.AUTO_DELETE_EVERY_N_HOURS ? Number(process.env.AUTO_DELETE_EVERY_N_HOURS) : 24; const HIDE_HISTORY = process.env.HIDE_HISTORY?.toLowerCase() === "true" || false; const WEBROOT = process.env.WEBROOT ?? ""; // fileNames: fileNames, // filesToConvert: fileNames.length, // convertedFiles : 0, // outputFiles: [], // init db if not exists if (!db.query("SELECT * FROM sqlite_master WHERE type='table'").get()) { db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL, password TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS file_names ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, file_name TEXT NOT NULL, output_file_name TEXT NOT NULL, status TEXT DEFAULT 'not started', FOREIGN KEY (job_id) REFERENCES jobs(id) ); CREATE TABLE IF NOT EXISTS jobs ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, date_created TEXT NOT NULL, status TEXT DEFAULT 'not started', num_files INTEGER DEFAULT 0, FOREIGN KEY (user_id) REFERENCES users(id) ); PRAGMA user_version = 1;`); } const dbVersion = ( db.query("PRAGMA user_version").get() as { user_version?: number } ).user_version; if (dbVersion === 0) { db.exec( "ALTER TABLE file_names ADD COLUMN status TEXT DEFAULT 'not started';", ); db.exec("PRAGMA user_version = 1;"); console.log("Updated database to version 1."); } let FIRST_RUN = db.query("SELECT * FROM users").get() === null || false; class User { id!: number; email!: string; password!: string; } class Filename { id!: number; job_id!: number; file_name!: string; output_file_name!: string; status!: string; } class Jobs { finished_files!: number; id!: number; user_id!: number; date_created!: string; status!: string; num_files!: number; } // enable WAL mode db.exec("PRAGMA journal_mode = WAL;"); const app = new Elysia({ serve: { maxRequestBodySize: Number.MAX_SAFE_INTEGER, }, prefix: WEBROOT, }) .use(html()) .use( jwt({ name: "jwt", schema: t.Object({ id: t.String(), }), secret: process.env.JWT_SECRET ?? randomUUID(), exp: "7d", }), ) .use( staticPlugin({ assets: "public", prefix: "", }), ) .get("/test", () => { return ( Hello World

Hello

); }) .get("/setup", ({ redirect }) => { if (!FIRST_RUN) { return redirect(`${WEBROOT}/login`, 302); } return (

Welcome to ConvertX!

Create your account
); }) .get("/register", ({ redirect }) => { if (!ACCOUNT_REGISTRATION) { return redirect(`${WEBROOT}/login`, 302); } return ( <>
); }) .post( "/register", async ({ body, set, redirect, jwt, cookie: { auth } }) => { if (!ACCOUNT_REGISTRATION && !FIRST_RUN) { return redirect(`${WEBROOT}/login`, 302); } if (FIRST_RUN) { FIRST_RUN = false; } const existingUser = await db .query("SELECT * FROM users WHERE email = ?") .get(body.email); if (existingUser) { set.status = 400; return { message: "Email already in use.", }; } const savedPassword = await Bun.password.hash(body.password); db.query("INSERT INTO users (email, password) VALUES (?, ?)").run( body.email, savedPassword, ); const user = db .query("SELECT * FROM users WHERE email = ?") .as(User) .get(body.email); if (!user) { set.status = 500; return { message: "Failed to create user.", }; } const accessToken = await jwt.sign({ id: String(user.id), }); if (!auth) { set.status = 500; return { message: "No auth cookie, perhaps your browser is blocking cookies.", }; } // set cookie auth.set({ value: accessToken, httpOnly: true, secure: !HTTP_ALLOWED, maxAge: 60 * 60 * 24 * 7, sameSite: "strict", }); return redirect(`${WEBROOT}/`, 302); }, { body: t.Object({ email: t.String(), password: t.String() }) }, ) .get("/login", async ({ jwt, redirect, cookie: { auth } }) => { if (FIRST_RUN) { return redirect(`${WEBROOT}/setup`, 302); } // if already logged in, redirect to home if (auth?.value) { const user = await jwt.verify(auth.value); if (user) { return redirect(`${WEBROOT}/`, 302); } auth.remove(); } return ( <>
); }) .post( "/login", async function handler({ body, set, redirect, jwt, cookie: { auth } }) { const existingUser = db .query("SELECT * FROM users WHERE email = ?") .as(User) .get(body.email); if (!existingUser) { set.status = 403; return { message: "Invalid credentials.", }; } const validPassword = await Bun.password.verify( body.password, existingUser.password, ); if (!validPassword) { set.status = 403; return { message: "Invalid credentials.", }; } const accessToken = await jwt.sign({ id: String(existingUser.id), }); if (!auth) { set.status = 500; return { message: "No auth cookie, perhaps your browser is blocking cookies.", }; } // set cookie auth.set({ value: accessToken, httpOnly: true, secure: !HTTP_ALLOWED, maxAge: 60 * 60 * 24 * 7, sameSite: "strict", }); return redirect(`${WEBROOT}/`, 302); }, { body: t.Object({ email: t.String(), password: t.String() }) }, ) .get("/logoff", ({ redirect, cookie: { auth } }) => { if (auth?.value) { auth.remove(); } return redirect(`${WEBROOT}/login`, 302); }) .post("/logoff", ({ redirect, cookie: { auth } }) => { if (auth?.value) { auth.remove(); } return redirect(`${WEBROOT}/login`, 302); }) .get("/account", async ({ jwt, redirect, cookie: { auth } }) => { if (!auth?.value) { return redirect(`${WEBROOT}/`); } const user = await jwt.verify(auth.value); if (!user) { return redirect(`${WEBROOT}/`, 302); } const userData = db .query("SELECT * FROM users WHERE id = ?") .as(User) .get(user.id); if (!userData) { return redirect(`${WEBROOT}/`, 302); } return ( <>
); }) .post( "/account", async function handler({ body, set, redirect, jwt, cookie: { auth } }) { if (!auth?.value) { return redirect(`${WEBROOT}/login`, 302); } const user = await jwt.verify(auth.value); if (!user) { return redirect(`${WEBROOT}/login`, 302); } const existingUser = db .query("SELECT * FROM users WHERE id = ?") .as(User) .get(user.id); if (!existingUser) { if (auth?.value) { auth.remove(); } return redirect(`${WEBROOT}/login`, 302); } const validPassword = await Bun.password.verify( body.password, existingUser.password, ); if (!validPassword) { set.status = 403; return { message: "Invalid credentials.", }; } const fields = []; const values = []; if (body.email) { const existingUser = await db .query("SELECT id FROM users WHERE email = ?") .as(User) .get(body.email); if (existingUser && existingUser.id.toString() !== user.id) { set.status = 409; return { message: "Email already in use." }; } fields.push("email"); values.push(body.email); } if (body.newPassword) { fields.push("password"); values.push(await Bun.password.hash(body.newPassword)); } if (fields.length > 0) { db.query( `UPDATE users SET ${fields.map((field) => `${field}=?`).join(", ")} WHERE id=?`, ).run(...values, user.id); } return redirect(`${WEBROOT}/`, 302); }, { body: t.Object({ email: t.MaybeEmpty(t.String()), newPassword: t.MaybeEmpty(t.String()), password: t.String(), }), }, ) .get("/", async ({ jwt, redirect, cookie: { auth, jobId } }) => { if (!ALLOW_UNAUTHENTICATED) { if (FIRST_RUN) { return redirect(`${WEBROOT}/setup`, 302); } if (!auth?.value) { return redirect(`${WEBROOT}/login`, 302); } } // validate jwt let user: ({ id: string } & JWTPayloadSpec) | false = false; if (ALLOW_UNAUTHENTICATED) { const newUserId = String( randomInt( 2 ** 24, Math.min(2 ** 48 + 2 ** 24 - 1, Number.MAX_SAFE_INTEGER), ), ); const accessToken = await jwt.sign({ id: newUserId, }); user = { id: newUserId }; if (!auth) { return { message: "No auth cookie, perhaps your browser is blocking cookies.", }; } // set cookie auth.set({ value: accessToken, httpOnly: true, secure: !HTTP_ALLOWED, maxAge: 24 * 60 * 60, sameSite: "strict", }); } else if (auth?.value) { user = await jwt.verify(auth.value); if (user !== false && user.id) { if (Number.parseInt(user.id) < 2 ** 24 || !ALLOW_UNAUTHENTICATED) { // make sure user exists in db const existingUser = db .query("SELECT * FROM users WHERE id = ?") .as(User) .get(user.id); if (!existingUser) { if (auth?.value) { auth.remove(); } return redirect(`${WEBROOT}/login`, 302); } } } } if (!user) { return redirect(`${WEBROOT}/login`, 302); } // create a new job db.query("INSERT INTO jobs (user_id, date_created) VALUES (?, ?)").run( user.id, new Date().toISOString(), ); const id = ( db .query("SELECT id FROM jobs WHERE user_id = ? ORDER BY id DESC") .get(user.id) as { id: number } ).id; if (!jobId) { return { message: "Cookies should be enabled to use this app." }; } jobId.set({ value: id, httpOnly: true, secure: !HTTP_ALLOWED, maxAge: 24 * 60 * 60, sameSite: "strict", }); console.log("jobId set to:", id); return ( <>

Convert

Choose a file or drag it here
{/* Hidden element which determines the format to convert the file too and the converter to use */}