start of the 50th remake of a file host doomed to never be finished

This commit is contained in:
creations 2025-03-02 17:36:45 -05:00
commit 46c05ca3a9
Signed by: creations
GPG key ID: 8F553AA4320FC711
33 changed files with 2155 additions and 0 deletions

50
src/helpers/auth.ts Normal file
View file

@ -0,0 +1,50 @@
import { isUUID } from "@helpers/char";
import { logger } from "@helpers/logger";
import { type ReservedSQL, sql } from "bun";
export async function authByToken(
request: ExtendedRequest,
reservation?: ReservedSQL,
): Promise<ApiUserSession | null> {
let selfReservation: boolean = false;
if (!reservation) {
reservation = await sql.reserve();
selfReservation = true;
}
const authorizationHeader: string | null =
request.headers.get("Authorization");
if (!authorizationHeader || !authorizationHeader.startsWith("Bearer "))
return null;
const authorizationToken: string = authorizationHeader.slice(7).trim();
if (!authorizationToken || !isUUID(authorizationToken)) return null;
try {
const result: UserSession[] =
await reservation`SELECT id, username, email, roles avatar, timezone, authorization_token FROM users WHERE authorization_token = ${authorizationToken};`;
if (result.length === 0) return null;
return {
id: result[0].id,
username: result[0].username,
email: result[0].email,
email_verified: result[0].email_verified,
roles: result[0].roles,
avatar: result[0].avatar,
timezone: result[0].timezone,
authorization_token: result[0].authorization_token,
is_api: true,
};
} catch (error) {
logger.error(["Could not authenticate by token:", error as Error]);
return null;
} finally {
if (selfReservation) {
reservation.release();
}
}
}

13
src/helpers/char.ts Normal file
View file

@ -0,0 +1,13 @@
export function timestampToReadable(timestamp?: number): string {
const date: Date =
timestamp && !isNaN(timestamp) ? new Date(timestamp) : new Date();
if (isNaN(date.getTime())) return "Invalid Date";
return date.toISOString().replace("T", " ").replace("Z", "");
}
export function isUUID(uuid: string): boolean {
const regex: RegExp =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
return regex.test(uuid);
}

26
src/helpers/ejs.ts Normal file
View file

@ -0,0 +1,26 @@
import { renderFile } from "ejs";
import { resolve } from "path";
export async function renderEjsTemplate(
viewName: string | string[],
data: EjsTemplateData,
headers?: Record<string, string | number | boolean>,
): Promise<Response> {
let templatePath: string;
if (Array.isArray(viewName)) {
templatePath = resolve("src", "views", ...viewName);
} else {
templatePath = resolve("src", "views", viewName);
}
if (!templatePath.endsWith(".ejs")) {
templatePath += ".ejs";
}
const html: string = await renderFile(templatePath, data);
return new Response(html, {
headers: { "Content-Type": "text/html", ...headers },
});
}

205
src/helpers/logger.ts Normal file
View file

@ -0,0 +1,205 @@
import { environment } from "@config/environment";
import { timestampToReadable } from "@helpers/char";
import type { Stats } from "fs";
import {
createWriteStream,
existsSync,
mkdirSync,
statSync,
WriteStream,
} from "fs";
import { EOL } from "os";
import { basename, join } from "path";
class Logger {
private static instance: Logger;
private static log: string = join(__dirname, "../../logs");
public static getInstance(): Logger {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
private writeToLog(logMessage: string): void {
if (environment.development) return;
const date: Date = new Date();
const logDir: string = Logger.log;
const logFile: string = join(
logDir,
`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}.log`,
);
if (!existsSync(logDir)) {
mkdirSync(logDir, { recursive: true });
}
let addSeparator: boolean = false;
if (existsSync(logFile)) {
const fileStats: Stats = statSync(logFile);
if (fileStats.size > 0) {
const lastModified: Date = new Date(fileStats.mtime);
if (
lastModified.getFullYear() === date.getFullYear() &&
lastModified.getMonth() === date.getMonth() &&
lastModified.getDate() === date.getDate() &&
lastModified.getHours() !== date.getHours()
) {
addSeparator = true;
}
}
}
const stream: WriteStream = createWriteStream(logFile, { flags: "a" });
if (addSeparator) {
stream.write(`${EOL}${date.toISOString()}${EOL}`);
}
stream.write(`${logMessage}${EOL}`);
stream.close();
}
private extractFileName(stack: string): string {
const stackLines: string[] = stack.split("\n");
let callerFile: string = "";
for (let i: number = 2; i < stackLines.length; i++) {
const line: string = stackLines[i].trim();
if (line && !line.includes("Logger.") && line.includes("(")) {
callerFile = line.split("(")[1]?.split(")")[0] || "";
break;
}
}
return basename(callerFile);
}
private getCallerInfo(stack: unknown): {
filename: string;
timestamp: string;
} {
const filename: string =
typeof stack === "string" ? this.extractFileName(stack) : "unknown";
const readableTimestamp: string = timestampToReadable();
return { filename, timestamp: readableTimestamp };
}
public info(message: string | string[], breakLine: boolean = false): void {
const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack);
const joinedMessage: string = Array.isArray(message)
? message.join(" ")
: message;
const logMessageParts: ILogMessageParts = {
readableTimestamp: { value: timestamp, color: "90" },
level: { value: "[INFO]", color: "32" },
filename: { value: `(${filename})`, color: "36" },
message: { value: joinedMessage, color: "0" },
};
this.writeToLog(`${timestamp} [INFO] (${filename}) ${joinedMessage}`);
this.writeConsoleMessageColored(logMessageParts, breakLine);
}
public warn(message: string | string[], breakLine: boolean = false): void {
const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack);
const joinedMessage: string = Array.isArray(message)
? message.join(" ")
: message;
const logMessageParts: ILogMessageParts = {
readableTimestamp: { value: timestamp, color: "90" },
level: { value: "[WARN]", color: "33" },
filename: { value: `(${filename})`, color: "36" },
message: { value: joinedMessage, color: "0" },
};
this.writeToLog(`${timestamp} [WARN] (${filename}) ${joinedMessage}`);
this.writeConsoleMessageColored(logMessageParts, breakLine);
}
public error(
message: string | Error | (string | Error)[],
breakLine: boolean = false,
): void {
const stack: string = new Error().stack || "";
const { filename, timestamp } = this.getCallerInfo(stack);
const messages: (string | Error)[] = Array.isArray(message)
? message
: [message];
const joinedMessage: string = messages
.map((msg: string | Error): string =>
typeof msg === "string" ? msg : msg.message,
)
.join(" ");
const logMessageParts: ILogMessageParts = {
readableTimestamp: { value: timestamp, color: "90" },
level: { value: "[ERROR]", color: "31" },
filename: { value: `(${filename})`, color: "36" },
message: { value: joinedMessage, color: "0" },
};
this.writeToLog(`${timestamp} [ERROR] (${filename}) ${joinedMessage}`);
this.writeConsoleMessageColored(logMessageParts, breakLine);
}
public custom(
bracketMessage: string,
bracketMessage2: string,
message: string | string[],
color: string,
breakLine: boolean = false,
): void {
const stack: string = new Error().stack || "";
const { timestamp } = this.getCallerInfo(stack);
const joinedMessage: string = Array.isArray(message)
? message.join(" ")
: message;
const logMessageParts: ILogMessageParts = {
readableTimestamp: { value: timestamp, color: "90" },
level: { value: bracketMessage, color },
filename: { value: `${bracketMessage2}`, color: "36" },
message: { value: joinedMessage, color: "0" },
};
this.writeToLog(
`${timestamp} ${bracketMessage} (${bracketMessage2}) ${joinedMessage}`,
);
this.writeConsoleMessageColored(logMessageParts, breakLine);
}
public space(): void {
console.log();
}
private writeConsoleMessageColored(
logMessageParts: ILogMessageParts,
breakLine: boolean = false,
): void {
const logMessage: string = Object.keys(logMessageParts)
.map((key: string) => {
const part: ILogMessagePart = logMessageParts[key];
return `\x1b[${part.color}m${part.value}\x1b[0m`;
})
.join(" ");
console.log(logMessage + (breakLine ? EOL : ""));
}
}
const logger: Logger = Logger.getInstance();
export { logger };

204
src/helpers/redis.ts Normal file
View file

@ -0,0 +1,204 @@
import { redisConfig } from "@config/environment";
import { logger } from "@helpers/logger";
import { createClient, type RedisClientType } from "redis";
class RedisJson {
private static instance: RedisJson | null = null;
private client: RedisClientType | null = null;
private constructor() {}
public static async initialize(): Promise<RedisJson> {
if (!RedisJson.instance) {
RedisJson.instance = new RedisJson();
RedisJson.instance.client = createClient({
socket: {
host: redisConfig.host,
port: redisConfig.port,
},
username: redisConfig.username || undefined,
password: redisConfig.password || undefined,
});
RedisJson.instance.client.on("error", (err: Error) => {
logger.error([
"Error connecting to Redis:",
err,
redisConfig.host,
]);
process.exit(1);
});
RedisJson.instance.client.on("connect", () => {
logger.info([
"Connected to Redis on",
`${redisConfig.host}:${redisConfig.port}`,
]);
});
await RedisJson.instance.client.connect();
}
return RedisJson.instance;
}
public static getInstance(): RedisJson {
if (!RedisJson.instance || !RedisJson.instance.client) {
throw new Error(
"Redis instance not initialized. Call initialize() first.",
);
}
return RedisJson.instance;
}
public async disconnect(): Promise<void> {
if (!this.client) {
logger.error("Redis client is not initialized.");
process.exit(1);
}
try {
await this.client.disconnect();
this.client = null;
logger.info("Redis disconnected successfully.");
} catch (error) {
logger.error("Error disconnecting Redis client:");
logger.error(error as Error);
throw error;
}
}
public async get(
type: "JSON" | "STRING",
key: string,
path?: string,
): Promise<
string | number | boolean | Record<string, unknown> | null | unknown
> {
if (!this.client) {
logger.error("Redis client is not initialized.");
throw new Error("Redis client is not initialized.");
}
try {
if (type === "JSON") {
const value: unknown = await this.client.json.get(key, {
path,
});
if (value instanceof Date) {
return value.toISOString();
}
return value;
} else if (type === "STRING") {
const value: string | null = await this.client.get(key);
return value;
} else {
throw new Error(`Invalid type: ${type}`);
}
} catch (error) {
logger.error(`Error getting value from Redis for key: ${key}`);
logger.error(error as Error);
throw error;
}
}
public async set(
type: "JSON" | "STRING",
key: string,
value: unknown,
expiresInSeconds?: number,
path?: string,
): Promise<void> {
if (!this.client) {
logger.error("Redis client is not initialized.");
throw new Error("Redis client is not initialized.");
}
try {
if (type === "JSON") {
await this.client.json.set(key, path || "$", value as string);
if (expiresInSeconds) {
await this.client.expire(key, expiresInSeconds);
}
} else if (type === "STRING") {
if (expiresInSeconds) {
await this.client.set(key, value as string, {
EX: expiresInSeconds,
});
} else {
await this.client.set(key, value as string);
}
} else {
throw new Error(`Invalid type: ${type}`);
}
} catch (error) {
logger.error(`Error setting value in Redis for key: ${key}`);
logger.error(error as Error);
throw error;
}
}
public async delete(type: "JSON" | "STRING", key: string): Promise<void> {
if (!this.client) {
logger.error("Redis client is not initialized.");
throw new Error("Redis client is not initialized.");
}
try {
if (type === "JSON") {
await this.client.json.del(key);
} else if (type === "STRING") {
await this.client.del(key);
} else {
throw new Error(`Invalid type: ${type}`);
}
} catch (error) {
logger.error(`Error deleting value from Redis for key: ${key}`);
logger.error(error as Error);
throw error;
}
}
public async expire(key: string, seconds: number): Promise<void> {
if (!this.client) {
logger.error("Redis client is not initialized.");
throw new Error("Redis client is not initialized.");
}
try {
await this.client.expire(key, seconds);
} catch (error) {
logger.error([
`Error expiring key in Redis: ${key}`,
error as Error,
]);
throw error;
}
}
public async keys(pattern: string): Promise<string[]> {
if (!this.client) {
logger.error("Redis client is not initialized.");
throw new Error("Redis client is not initialized.");
}
try {
const keys: string[] = await this.client.keys(pattern);
return keys;
} catch (error) {
logger.error([
`Error getting keys from Redis for pattern: ${pattern}`,
error as Error,
]);
throw error;
}
}
}
export const redis: {
initialize: () => Promise<RedisJson>;
getInstance: () => RedisJson;
} = {
initialize: RedisJson.initialize,
getInstance: RedisJson.getInstance,
};
export { RedisJson };

162
src/helpers/sessions.ts Normal file
View file

@ -0,0 +1,162 @@
import { jwt } from "@config/environment";
import { environment } from "@config/environment";
import { redis } from "@helpers/redis";
import { createDecoder, createSigner, createVerifier } from "fast-jwt";
type Signer = (payload: UserSession, options?: UserSession) => string;
type Verifier = (token: string, options?: UserSession) => UserSession;
type Decoder = (token: string, options?: UserSession) => UserSession;
class SessionManager {
private signer: Signer;
private verifier: Verifier;
private decoder: Decoder;
constructor() {
this.signer = createSigner({
key: jwt.secret,
expiresIn: jwt.expiresIn,
});
this.verifier = createVerifier({ key: jwt.secret });
this.decoder = createDecoder();
}
public async createSession(
payload: UserSession,
userAgent: string,
): Promise<string> {
const token: string = this.signer(payload);
const sessionKey: string = `session:${payload.id}:${token}`;
await redis
.getInstance()
.set(
"JSON",
sessionKey,
{ ...payload, userAgent },
this.getExpirationInSeconds(),
);
const cookie: string = this.generateCookie(token);
return cookie;
}
public async getSession(request: Request): Promise<UserSession | null> {
const cookie: string | null = request.headers.get("Cookie");
if (!cookie) return null;
const token: string | null =
cookie.match(/session=([^;]+)/)?.[1] || null;
if (!token) return null;
const userSessions: string[] = await redis
.getInstance()
.keys("session:*:" + token);
if (!userSessions.length) return null;
const sessionData: unknown = await redis
.getInstance()
.get("JSON", userSessions[0]);
if (!sessionData) return null;
const payload: UserSession & { userAgent: string } =
sessionData as UserSession & { userAgent: string };
return payload;
}
public async verifySession(token: string): Promise<UserSession> {
const userSessions: string[] = await redis
.getInstance()
.keys("session:*:" + token);
if (!userSessions.length)
throw new Error("Session not found or expired");
const sessionData: unknown = await redis
.getInstance()
.get("JSON", userSessions[0]);
if (!sessionData) throw new Error("Session not found or expired");
const payload: UserSession = this.verifier(token);
return payload;
}
public async decodeSession(token: string): Promise<UserSession> {
const payload: UserSession = this.decoder(token);
return payload;
}
public async invalidateSession(request: Request): Promise<void> {
const cookie: string | null = request.headers.get("Cookie");
if (!cookie) return;
const token: string | null =
cookie.match(/session=([^;]+)/)?.[1] || null;
if (!token) return;
const userSessions: string[] = await redis
.getInstance()
.keys("session:*:" + token);
if (!userSessions.length) return;
await redis.getInstance().delete("JSON", userSessions[0]);
}
private generateCookie(
token: string,
maxAge: number = this.getExpirationInSeconds(),
options?: {
secure?: boolean;
httpOnly?: boolean;
sameSite?: "Strict" | "Lax" | "None";
path?: string;
domain?: string;
},
): string {
const {
secure = !environment.development,
httpOnly = true,
sameSite = environment.development ? "Lax" : "None",
path = "/",
domain,
} = options || {};
let cookie: string = `session=${encodeURIComponent(token)}; Path=${path}; Max-Age=${maxAge}`;
if (httpOnly) cookie += "; HttpOnly";
if (secure) cookie += "; Secure";
if (sameSite) cookie += `; SameSite=${sameSite}`;
if (domain) cookie += `; Domain=${domain}`;
return cookie;
}
private getExpirationInSeconds(): number {
const match: RegExpMatchArray | null =
jwt.expiresIn.match(/^(\d+)([smhd])$/);
if (!match) {
throw new Error("Invalid expiresIn format in jwt config");
}
const [, value, unit] = match;
const num: number = parseInt(value, 10);
switch (unit) {
case "s":
return num;
case "m":
return num * 60;
case "h":
return num * 3600;
case "d":
return num * 86400;
default:
throw new Error("Invalid time unit in expiresIn");
}
}
}
const sessionManager: SessionManager = new SessionManager();
export { sessionManager };

54
src/index.ts Normal file
View file

@ -0,0 +1,54 @@
import { logger } from "@helpers/logger";
import { type ReservedSQL, sql } from "bun";
import { readdir } from "fs/promises";
import { resolve } from "path";
import { serverHandler } from "@/server";
import { redis } from "./helpers/redis";
async function initializeDatabase(): Promise<void> {
const sqlDir: string = resolve("config", "sql");
const files: string[] = await readdir(sqlDir);
const reservation: ReservedSQL = await sql.reserve();
for (const file of files) {
if (file.endsWith(".ts")) {
const { createTable } = await import(resolve(sqlDir, file));
await createTable(reservation);
}
}
reservation.release();
}
async function main(): Promise<void> {
try {
try {
await sql`SELECT 1;`;
logger.info([
"Connected to PostgreSQL on",
`${process.env.PGHOST}:${process.env.PGPORT}`,
]);
} catch (error) {
logger.error([
"Could not establish a connection to PostgreSQL:",
error as Error,
]);
process.exit(1);
}
await redis.initialize();
serverHandler.initialize();
await initializeDatabase();
} catch (error) {
throw error;
}
}
main().catch((error: Error) => {
logger.error(["Error initializing the server:", error]);
process.exit(1);
});

View file

@ -0,0 +1,161 @@
import {
isValidEmail,
isValidPassword,
isValidUsername,
} from "@config/sql/users";
import { password as bunPassword, type ReservedSQL, sql } from "bun";
import { logger } from "@/helpers/logger";
import { sessionManager } from "@/helpers/sessions";
const routeDef: RouteDef = {
method: "POST",
accepts: "application/json",
returns: "application/json",
needsBody: "json",
};
async function handler(
request: ExtendedRequest,
requestBody: unknown,
): Promise<Response> {
if (request.session) {
if ((request.session as ApiUserSession).is_api) {
return Response.json(
{
success: false,
code: 403,
error: "You cannot log in while using an authorization token",
},
{ status: 403 },
);
}
return Response.json(
{
success: false,
code: 403,
error: "Already logged in",
},
{ status: 403 },
);
}
const { username, email, password } = requestBody as {
username: string;
email: string;
password: string;
};
if (!password || (!username && !email)) {
return Response.json(
{
success: false,
code: 400,
error: "Expected username or email, and password",
},
{ status: 400 },
);
}
const errors: string[] = [];
const validations: UserValidation[] = [
{ check: isValidUsername(username), field: "Username" },
{ check: isValidEmail(email), field: "Email" },
{ check: isValidPassword(password), field: "Password" },
];
validations.forEach(({ check }: UserValidation): void => {
if (!check.valid && check.error) {
errors.push(check.error);
}
});
if (errors.length > 0) {
return Response.json(
{
success: false,
code: 400,
errors,
},
{ status: 400 },
);
}
const reservation: ReservedSQL = await sql.reserve();
let user: User | null = null;
try {
user = await reservation`
SELECT * FROM users
WHERE (username = ${username} OR email = ${email})
LIMIT 1;
`.then((rows: User[]): User | null => rows[0]);
if (!user) {
await bunPassword.verify("fake", await bunPassword.hash("fake"));
return Response.json(
{
success: false,
code: 401,
error: "Invalid username, email, or password",
},
{ status: 401 },
);
}
const passwordMatch: boolean = await bunPassword.verify(
password,
user.password,
);
if (!passwordMatch) {
return Response.json(
{
success: false,
code: 401,
error: "Invalid username, email, or password",
},
{ status: 401 },
);
}
} catch (error) {
logger.error(["Error logging in", error as Error]);
return Response.json(
{
success: false,
code: 500,
error: "An error occurred while logging in",
},
{ status: 500 },
);
} finally {
if (reservation) reservation.release();
}
const sessionCookie: string = await sessionManager.createSession(
{
id: user.id,
username: user.username,
email: user.email,
email_verified: user.email_verified,
roles: user.roles,
avatar: user.avatar,
timezone: user.timezone,
authorization_token: user.authorization_token,
},
request.headers.get("User-Agent") || "",
);
return Response.json(
{
success: true,
code: 200,
},
{ status: 200, headers: { "Set-Cookie": sessionCookie } },
);
}
export { handler, routeDef };

View file

@ -0,0 +1,50 @@
import { sessionManager } from "@/helpers/sessions";
const routeDef: RouteDef = {
method: "POST",
accepts: "*/*",
returns: "application/json",
};
async function handler(request: ExtendedRequest): Promise<Response> {
if (!request.session) {
return Response.json(
{
success: false,
code: 403,
error: "You are not logged in",
},
{ status: 403 },
);
}
if ((request.session as ApiUserSession).is_api) {
return Response.json(
{
success: false,
code: 403,
error: "You cannot logout while using an authorization token",
},
{ status: 403 },
);
}
sessionManager.invalidateSession(request);
return Response.json(
{
success: true,
code: 200,
message: "Successfully logged out",
},
{
status: 200,
headers: {
"Set-Cookie":
"session=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Strict",
},
},
);
}
export { handler, routeDef };

View file

@ -0,0 +1,197 @@
import { getSetting } from "@config/sql/settings";
import {
isValidEmail,
isValidInvite,
isValidPassword,
isValidUsername,
} from "@config/sql/users";
import { password as bunPassword, type ReservedSQL, sql } from "bun";
import type { UUID } from "crypto";
import { logger } from "@/helpers/logger";
import { sessionManager } from "@/helpers/sessions";
const routeDef: RouteDef = {
method: "POST",
accepts: "application/json",
returns: "application/json",
needsBody: "json",
};
async function handler(
request: ExtendedRequest,
requestBody: unknown,
): Promise<Response> {
const { username, email, password, invite } = requestBody as {
username: string;
email: string;
password: string;
invite?: string;
};
if (!username || !email || !password) {
return Response.json(
{
success: false,
code: 400,
error: "Expected username, email, and password",
},
{ status: 400 },
);
}
const errors: string[] = [];
const validations: UserValidation[] = [
{ check: isValidUsername(username), field: "Username" },
{ check: isValidEmail(email), field: "Email" },
{ check: isValidPassword(password), field: "Password" },
];
validations.forEach(({ check }: UserValidation): void => {
if (!check.valid && check.error) {
errors.push(check.error);
}
});
const reservation: ReservedSQL = await sql.reserve();
let firstUser: boolean = false;
let invitedBy: UUID | null = null;
let roles: string[] = [];
try {
const registrationEnabled: boolean =
(await getSetting("registrationEnabled", reservation)) === "true";
const invitationsEnabled: boolean =
(await getSetting("invitationsEnabled", reservation)) === "true";
firstUser =
Number(
(await reservation`SELECT COUNT(*) AS count FROM users;`)[0]
?.count,
) === 0;
if (!firstUser && invite) {
const inviteValidation: { valid: boolean; error?: string } =
isValidInvite(invite);
if (!inviteValidation.valid && inviteValidation.error) {
errors.push(inviteValidation.error);
}
}
if (
(!firstUser && !registrationEnabled && !invite) ||
(!firstUser && invite && !invitationsEnabled)
) {
errors.push("Registration is disabled");
}
roles.push("user");
if (firstUser) {
roles.push("admin");
}
const { usernameExists, emailExists } = await reservation`
SELECT
EXISTS(SELECT 1 FROM users WHERE LOWER(username) = LOWER(${username})) AS usernameExists,
EXISTS(SELECT 1 FROM users WHERE LOWER(email) = LOWER(${email})) AS emailExists;
`;
if (usernameExists) errors.push("Username already exists");
if (emailExists) errors.push("Email already exists");
if (invite) {
invitedBy = (
await reservation`SELECT user_id FROM invites WHERE invite = ${invite};`
)[0]?.id;
if (!invitedBy) errors.push("Invalid invite code");
}
} catch (error) {
errors.push("An error occurred while checking for existing users");
logger.error(["Error checking for existing users:", error as Error]);
}
if (errors.length > 0) {
return Response.json(
{
success: false,
code: 400,
errors,
},
{ status: 400 },
);
}
let user: User | null = null;
const hashedPassword: string = await bunPassword.hash(password, {
algorithm: "argon2id",
});
const defaultTimezone: string =
(await getSetting("default_timezone", reservation)) || "UTC";
try {
user = (
await reservation`
INSERT INTO users (username, email, password, invited_by, roles, timezone)
VALUES (${username}, ${email}, ${hashedPassword}, ${invitedBy}, ARRAY[${roles.join(",")}]::TEXT[], ${defaultTimezone})
RETURNING *;
`
)[0];
if (!user) {
logger.error("User was not created");
return Response.json(
{
success: false,
code: 500,
error: "An error occurred with the user registration",
},
{ status: 500 },
);
}
if (invitedBy) {
await reservation`DELETE FROM invites WHERE invite = ${invite};`;
}
} catch (error) {
logger.error([
"Error inserting user into the database:",
error as Error,
]);
return Response.json(
{
success: false,
code: 500,
error: "An error occurred while creating the user",
},
{ status: 500 },
);
} finally {
reservation.release();
}
const sessionCookie: string = await sessionManager.createSession(
{
id: user.id,
username: user.username,
email: user.email,
email_verified: user.email_verified,
roles: user.roles,
avatar: user.avatar,
timezone: user.timezone,
authorization_token: user.authorization_token,
},
request.headers.get("User-Agent") || "",
);
return Response.json(
{
success: true,
code: 201,
message: "User Registered",
id: user.id,
},
{ status: 201, headers: { "Set-Cookie": sessionCookie } },
);
}
export { handler, routeDef };

15
src/routes/api/index.ts Normal file
View file

@ -0,0 +1,15 @@
const routeDef: RouteDef = {
method: "GET",
accepts: "*/*",
returns: "application/json",
};
async function handler(): Promise<Response> {
// TODO: Put something useful here
return Response.json({
message: "Hello, World!",
});
}
export { handler, routeDef };

17
src/routes/index.ts Normal file
View file

@ -0,0 +1,17 @@
import { renderEjsTemplate } from "@helpers/ejs";
const routeDef: RouteDef = {
method: "GET",
accepts: "*/*",
returns: "text/html",
};
async function handler(): Promise<Response> {
const ejsTemplateData: EjsTemplateData = {
title: "Hello, World!",
};
return await renderEjsTemplate("index", ejsTemplateData);
}
export { handler, routeDef };

247
src/server.ts Normal file
View file

@ -0,0 +1,247 @@
import { environment } from "@config/environment";
import { logger } from "@helpers/logger";
import {
type BunFile,
FileSystemRouter,
type MatchedRoute,
type Serve,
} from "bun";
import { resolve } from "path";
import { webSocketHandler } from "@/websocket";
import { authByToken } from "./helpers/auth";
import { sessionManager } from "./helpers/sessions";
class ServerHandler {
private router: FileSystemRouter;
constructor(
private port: number,
private host: string,
) {
this.router = new FileSystemRouter({
style: "nextjs",
dir: "./src/routes",
origin: `http://${this.host}:${this.port}`,
});
}
public initialize(): void {
const server: Serve = Bun.serve({
port: this.port,
hostname: this.host,
fetch: this.handleRequest.bind(this),
websocket: {
open: webSocketHandler.handleOpen.bind(webSocketHandler),
message: webSocketHandler.handleMessage.bind(webSocketHandler),
close: webSocketHandler.handleClose.bind(webSocketHandler),
},
});
logger.info(
`Server running at http://${server.hostname}:${server.port}`,
true,
);
this.logRoutes();
}
private logRoutes(): void {
logger.info("Available routes:");
const sortedRoutes: [string, string][] = Object.entries(
this.router.routes,
).sort(([pathA]: [string, string], [pathB]: [string, string]) =>
pathA.localeCompare(pathB),
);
for (const [path, filePath] of sortedRoutes) {
logger.info(`Route: ${path}, File: ${filePath}`);
}
}
private async serveStaticFile(pathname: string): Promise<Response> {
try {
let filePath: string;
if (pathname === "/favicon.ico") {
filePath = resolve("public", "assets", "favicon.ico");
} else {
filePath = resolve(`.${pathname}`);
}
const file: BunFile = Bun.file(filePath);
if (await file.exists()) {
const fileContent: ArrayBuffer = await file.arrayBuffer();
const contentType: string =
file.type || "application/octet-stream";
return new Response(fileContent, {
headers: { "Content-Type": contentType },
});
} else {
logger.warn(`File not found: ${filePath}`);
return new Response("Not Found", { status: 404 });
}
} catch (error) {
logger.error([
`Error serving static file: ${pathname}`,
error as Error,
]);
return new Response("Internal Server Error", { status: 500 });
}
}
private async handleRequest(
request: ExtendedRequest,
server: BunServer,
): Promise<Response> {
request.startPerf = performance.now();
const pathname: string = new URL(request.url).pathname;
if (pathname.startsWith("/public") || pathname === "/favicon.ico") {
return await this.serveStaticFile(pathname);
}
const match: MatchedRoute | null = this.router.match(request);
let requestBody: unknown = {};
let response: Response;
if (match) {
const { filePath, params, query } = match;
try {
const routeModule: RouteModule = await import(filePath);
const contentType: string | null =
request.headers.get("Content-Type");
const actualContentType: string | null = contentType
? contentType.split(";")[0].trim()
: null;
if (
routeModule.routeDef.needsBody === "json" &&
actualContentType === "application/json"
) {
try {
requestBody = await request.json();
} catch {
requestBody = {};
}
} else if (
routeModule.routeDef.needsBody === "multipart" &&
actualContentType === "multipart/form-data"
) {
try {
requestBody = await request.formData();
} catch {
requestBody = {};
}
}
if (routeModule.routeDef.method !== request.method) {
response = Response.json(
{
success: false,
code: 405,
error: `Method ${request.method} Not Allowed, expected ${routeModule.routeDef.method}`,
},
{ status: 405 },
);
} else {
const expectedContentType: string | null =
routeModule.routeDef.accepts;
const matchesAccepts: boolean =
expectedContentType === "*/*" ||
actualContentType === expectedContentType;
if (!matchesAccepts) {
response = Response.json(
{
success: false,
code: 406,
error: `Content-Type ${contentType} Not Acceptable, expected ${expectedContentType}`,
},
{ status: 406 },
);
} else {
request.params = params;
request.query = query;
request.session =
(await sessionManager.getSession(request)) ||
(await authByToken(request));
response = await routeModule.handler(
request,
requestBody,
server,
);
if (routeModule.routeDef.returns !== "*/*") {
response.headers.set(
"Content-Type",
routeModule.routeDef.returns,
);
}
}
}
} catch (error: unknown) {
logger.error([
`Error handling route ${request.url}:`,
error as Error,
]);
response = Response.json(
{
success: false,
code: 500,
error: "Internal Server Error",
},
{ status: 500 },
);
}
} else {
response = Response.json(
{
success: false,
code: 404,
error: "Not Found",
},
{ status: 404 },
);
}
const headers: Headers = response.headers;
let ip: string | null = server.requestIP(request)?.address || null;
if (!ip) {
ip =
headers.get("CF-Connecting-IP") ||
headers.get("X-Real-IP") ||
headers.get("X-Forwarded-For") ||
null;
}
logger.custom(
`[${request.method}]`,
`(${response.status})`,
[
request.url,
`${(performance.now() - request.startPerf).toFixed(2)}ms`,
ip || "unknown",
],
"90",
);
return response;
}
}
const serverHandler: ServerHandler = new ServerHandler(
environment.port,
environment.host,
);
export { serverHandler };

8
src/views/index.ejs Normal file
View file

@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1> hello </h1>
</body>
</html>

34
src/websocket.ts Normal file
View file

@ -0,0 +1,34 @@
import { logger } from "@helpers/logger";
import { type ServerWebSocket } from "bun";
class WebSocketHandler {
public handleMessage(ws: ServerWebSocket, message: string): void {
logger.info(`WebSocket received: ${message}`);
try {
ws.send(`You said: ${message}`);
} catch (error) {
logger.error(["WebSocket send error", error as Error]);
}
}
public handleOpen(ws: ServerWebSocket): void {
logger.info("WebSocket connection opened.");
try {
ws.send("Welcome to the WebSocket server!");
} catch (error) {
logger.error(["WebSocket send error", error as Error]);
}
}
public handleClose(
ws: ServerWebSocket,
code: number,
reason: string,
): void {
logger.warn(`WebSocket closed with code ${code}, reason: ${reason}`);
}
}
const webSocketHandler: WebSocketHandler = new WebSocketHandler();
export { webSocketHandler };