Skip to content

Conversation

@ajatshatru01
Copy link

@ajatshatru01 ajatshatru01 commented Oct 25, 2025

Implemented safe message length limiting along with basic sanitization using escapeHTML, to avoid any issues like XSS when sending message

🌟 Pre-submission Checklist

  • I have starred the repository (mandatory before contributing)
  • 💬 I am a member of the Discord server: Join Here
  • 📝 I have signed up at helixque.netlify.app
  • 📢 I have checked the #pull-request channel to ensure no one else is working on this issue
  • 📝 I have mentioned this PR in the Discord #pull-request channel

Summary

Brief description of what this PR accomplishes.
Converts text to a string and trims it.

Ensures it’s no longer than 1000 characters.

Escapes HTML (<, >, &, etc.) to prevent injection attacks.

Sends the safe text to all connected clients.

Stores the safe message in history.

Type of Changes

  • 🚀 Feature addition
  • 🐛 Bug fix
  • 📚 Documentation update
  • 🔧 Refactoring
  • 🎨 UI/UX improvements
  • ⚡ Performance optimizations
  • 📱 Mobile responsiveness
  • ♿ Accessibility improvements
  • Other: _____

Testing Completed

  • ✅ I have tested these changes locally
  • 🔧 Backend functionality works properly (if applicable)
  • 🎨 Frontend functionality works properly (if applicable)
  • 🌐 WebRTC connections work properly (if applicable)
  • 📱 Tested on different screen sizes/devices
  • 🔄 Tested edge cases (disconnections, reconnections, etc.)
  • 🧪 All existing functionality remains unaffected

Development Setup Verification

  • 📦 Dependencies installed for both frontend and backend
  • 🚀 Development servers start without errors
  • 🏗️ Code builds successfully

Code Quality

  • 📏 Follows existing TypeScript and React patterns
  • 📝 Uses meaningful variable and function names
  • 💡 Added comments for complex logic
  • 🎯 Code is properly formatted
  • 🔍 Self-review of the code has been performed

Related Issues

Closes #192

Screenshots/Videos

Additional Notes

Any additional information or context about the changes.


Note: For faster PR review and approval, ensure you're active in our Discord server!

Summary by CodeRabbit

  • Bug Fixes
    • Improved chat message security by escaping HTML content to prevent potential rendering issues.
    • Enhanced input validation to ensure required message information is present before processing.
    • Added a 1000-character limit for chat messages.

Implemented safe message length limiting along with basic sanitization using escapeHTML, to avoid any issues like XSS when sending message
@coderabbitai
Copy link

coderabbitai bot commented Oct 25, 2025

Walkthrough

Added HTML escaping and enhanced input validation to chat message processing in the chat service. Text is now sanitized through trimming, truncation to 1000 characters, and HTML entity escaping before being stored and broadcast.

Changes

Cohort / File(s) Change Summary
Chat service security hardening
backend/src/chat/chat.ts
Introduced escapeHtml import and applied HTML entity escaping to chat messages. Enhanced input validation to ensure roomId, text, and from are present. Implemented multi-step text sanitization: trim, slice to 1000 chars, then escape HTML. Applied sanitized text to message payload storage and broadcasting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Single-file change with straightforward security additions
  • Input validation logic is standard and low-risk
  • HTML escaping applied consistently throughout message handling

Poem

🐰 A whisker-twitching fix so fine,
HTML gremlins? They won't cross the line!
With trim and escape, the messages shine,
No XSS tricks—just chat so divine! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title Check ❓ Inconclusive The PR title "Update chat.ts" is extremely vague and non-descriptive. It fails to convey any meaningful information about the actual changes being made—specifically that the PR introduces HTML escaping for XSS prevention, message length limiting to 1000 characters, and text sanitization. The title uses generic phrasing that could apply to almost any modification to this file, making it difficult for a teammate reviewing commit history to quickly understand the primary purpose of the change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed The PR description follows the required template structure and includes all mandatory sections: a pre-submission checklist (fully completed), a summary describing the HTML escaping and message length limiting changes, type of changes selection (Feature addition and Performance optimizations), comprehensive testing completion checkboxes (all marked done), development setup verification (all marked done), and code quality verification (all marked done). The summary accurately reflects the implementation described in the raw changes, detailing the sanitization steps (trimming, truncating to 1000 characters, HTML escaping) and their purposes. While the summary could be slightly more descriptive upfront, it sufficiently communicates what the PR accomplishes and includes a related issue reference (#192).
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
backend/src/chat/chat.ts (1)

78-78: Consider extracting the character limit to a named constant.

The 1000-character limit is hardcoded here. Extracting it to a named constant (e.g., MAX_MESSAGE_LENGTH) at the top of the file alongside MAX_HISTORY would improve maintainability and make the limit easier to adjust in the future.

Apply this diff to extract the constant:

 const MAX_HISTORY = 300;
+const MAX_MESSAGE_LENGTH = 1000;
 const roomHistories = new Map<string, HistItem[]>();

Then update line 78:

-    safeText = safeText.slice(0, 1000);
+    safeText = safeText.slice(0, MAX_MESSAGE_LENGTH);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b9fad5d and 5847d45.

📒 Files selected for processing (1)
  • backend/src/chat/chat.ts (3 hunks)
🔇 Additional comments (1)
backend/src/chat/chat.ts (1)

77-79: Excellent security improvements for XSS prevention.

The three-step sanitization process (trim → truncate → escape) effectively prevents XSS attacks and limits message size. Using the escape-html library is the standard approach for HTML entity escaping, and the defensive toString() call handles edge cases where non-string values might be passed.

// server/chat.ts
import type { Server, Socket } from "socket.io";

import escapeHtml from "escape-html"; // npm install escape-html
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify that the escape-html dependency is installed.

Ensure that escape-html has been added to package.json dependencies. Without it, the application will fail at runtime with a module not found error.

Run the following script to verify the dependency exists:


🏁 Script executed:

#!/bin/bash
# Description: Check if escape-html is listed in package.json dependencies

cat package.json | jq '.dependencies["escape-html"], .devDependencies["escape-html"]'

Length of output: 44


🏁 Script executed:

#!/bin/bash
# Find package.json files and check escape-html dependency

# Locate all package.json files
echo "=== Locating package.json files ==="
fd -type f -name "package.json"

echo ""
echo "=== Checking backend/package.json for escape-html ==="
if [ -f "backend/package.json" ]; then
  cat backend/package.json | jq '.dependencies["escape-html"], .devDependencies["escape-html"]'
else
  echo "backend/package.json not found"
fi

Length of output: 271


🏁 Script executed:

#!/bin/bash
# Display backend/package.json to confirm escape-html is missing

echo "=== Contents of backend/package.json ==="
cat backend/package.json | jq '.' | head -30

Length of output: 756


Add escape-html to backend/package.json dependencies.

The import statement on line 3 references the escape-html package, but it is not listed in backend/package.json dependencies. This will cause a module not found error at runtime. Add "escape-html": "^1.4.2" (or appropriate version) to the dependencies section in backend/package.json.

🤖 Prompt for AI Agents
In backend/src/chat/chat.ts around line 3, the code imports "escape-html" but
backend/package.json does not list it as a dependency; add "escape-html":
"^1.4.2" (or an appropriate version) to the "dependencies" section of
backend/package.json, run npm install (or yarn) to update package-lock.json (or
yarn.lock), and commit the updated package.json and lockfile so the module is
available at runtime.

Comment on lines +76 to +79
if (!roomId || !text || !from) return;
let safeText = text.toString().trim();
safeText = safeText.slice(0, 1000);
safeText = escapeHtml(safeText);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Validate text after trimming to prevent empty messages.

The current validation checks !text before trimming (line 76), but trimming happens afterward (line 77). This allows messages containing only whitespace (e.g., " ") to pass validation, resulting in empty messages being broadcast and stored after trimming.

Apply this diff to fix the validation order:

-     
-    if (!roomId || !text || !from) return;
-    let safeText = text.toString().trim();
+    if (!roomId || !from) return;
+    let safeText = text?.toString().trim();
+    if (!safeText) return;
     safeText = safeText.slice(0, 1000);
     safeText = escapeHtml(safeText);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In backend/src/chat/chat.ts around lines 76 to 79, the code validates `text`
before trimming which lets whitespace-only messages pass; change the order so
you convert to string and trim first, then validate the trimmed result (return
if empty), then apply the 1000-char slice and escapeHtml. Ensure the validation
checks the trimmed string (e.g., `if (!roomId || !from || safeText.length === 0)
return`) so messages that are only whitespace are rejected.

@javatcoding1
Copy link
Collaborator

@ajatshatru01 the issue isn’t mentioned. Please make sure you’ve starred both repositories, joined our Discord server, and read the CONTRIBUTING.md before raising a PR.

@ajatshatru01
Copy link
Author

@ajatshatru01 the issue isn’t mentioned. Please make sure you’ve starred both repositories, joined our Discord server, and read the CONTRIBUTING.md before raising a PR.

ok i will do it right now

@javatcoding1
Copy link
Collaborator

@ajatshatru01 in frontend there is no limit number please do update that as well

@ajatshatru01
Copy link
Author

@ajatshatru01 in frontend there is no limit number please do update that as well

i am not able to understand this, can you properly refer to what i am supposed to fix

@javatcoding1
Copy link
Collaborator

@ajatshatru01 like mention that we have the limit of 200 words in frontend something like that

@ajatshatru01
Copy link
Author

@ajatshatru01 like mention that we have the limit of 200 words in frontend something like that

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Implementing safe message length limiting along with basic sanitization using escapeHTML, to avoid any issues like XSS

2 participants