Skip to content

Commit

Permalink
Escape HTML in messages and usernames
Browse files Browse the repository at this point in the history
  • Loading branch information
The-Best-Codes committed Nov 24, 2024
1 parent de68141 commit ef6546c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
8 changes: 5 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
getRecentMessages,
type User,
} from "./src/db/database";
import { LIMITS, validateInput } from "./src/constants";
import { LIMITS, validateInput, escapeHtml } from "./src/constants";
import crypto from "crypto";

const port = process.env.PORT || 5177;
Expand Down Expand Up @@ -212,13 +212,15 @@ const server: any = Bun.serve({
data.content,
LIMITS.MESSAGE_MAX_LENGTH
);
const msg = await createMessage(user.id, validatedContent);
// Escape HTML in the message
const safeContent = escapeHtml(validatedContent);
const msg = await createMessage(user.id, safeContent);
server.publish(
"chat",
JSON.stringify({
type: "message",
username: user.username,
content: validatedContent,
content: safeContent,
timestamp: new Date().toISOString(),
})
);
Expand Down
9 changes: 9 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ export const LIMITS = {
MESSAGE_MAX_LENGTH: 2000,
} as const;

export function escapeHtml(unsafe: string): string {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}

export function validateInput(input: string, maxLength: number): string {
if (!input || typeof input !== "string") {
throw new Error("Invalid input");
Expand Down
5 changes: 4 additions & 1 deletion src/db/database.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Database } from "bun:sqlite";
import * as bcrypt from "bcryptjs";
import { LIMITS, validateInput } from "../constants";
import { LIMITS, validateInput, escapeHtml } from "../constants";

const DB_PATH = process.env.DB_PATH || `${process.cwd()}/chat.db`;
const SCHEMA_PATH =
Expand Down Expand Up @@ -40,6 +40,9 @@ export const createUser = async (
username = validateInput(username, LIMITS.USERNAME_MAX_LENGTH);
password = validateInput(password, LIMITS.PASSWORD_MAX_LENGTH);

// Escape HTML in username
username = escapeHtml(username);

const hashedPassword = await bcrypt.hash(password, 10);
try {
const stmt = db.prepare(
Expand Down

0 comments on commit ef6546c

Please sign in to comment.