Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion common/src/util/__tests__/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'bun:test'

import { pluralize } from '../string'
import { escapeHtml, escapeString, pluralize } from '../string'

describe('pluralize', () => {
it('should handle singular and plural cases correctly', () => {
Expand Down Expand Up @@ -237,3 +237,38 @@ describe('pluralize', () => {
})
})



describe('escapeString', () => {
it('should escape JSON special characters', () => {
expect(escapeString('hello "world"')).toBe('hello \\"world\\"')
expect(escapeString('back\\slash')).toBe('back\\\\slash')
expect(escapeString('line\nbreak')).toBe('line\\nbreak')
})

it('should NOT escape HTML-unsafe characters (use escapeHtml for that)', () => {
// escapeString is for generic string escaping, not HTML contexts
expect(escapeString('<script>')).toBe('<script>')
expect(escapeString('a & b')).toBe('a & b')
})
})

describe('escapeHtml', () => {
it('should escape HTML-unsafe characters to prevent XSS', () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
'\\u003cscript\\u003ealert(\\"xss\\")\\u003c/script\\u003e',
)
expect(escapeHtml('a & b')).toBe('a \\u0026 b')
expect(escapeHtml("it's")).toBe('it\\u0027s')
expect(escapeHtml('5 > 3')).toBe('5 \\u003e 3')
})

it('should handle empty strings', () => {
expect(escapeHtml('')).toBe('')
})

it('should preserve regular characters', () => {
expect(escapeHtml('hello world')).toBe('hello world')
expect(escapeHtml('123')).toBe('123')
})
})
14 changes: 14 additions & 0 deletions common/src/util/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,17 @@ export function suffixPrefixOverlap(source: string, next: string): string {
export const escapeString = (str: string) => {
return JSON.stringify(str).slice(1, -1)
}

/**
* Escape characters that have special meaning in HTML/XML contexts to prevent
* XSS attacks and HTML injection. Use this when embedding user-controlled
* strings into HTML output, not for general string escaping (use escapeString).
*/
export const escapeHtml = (str: string): string => {
return JSON.stringify(str)
.slice(1, -1)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026')
.replace(/'/g, '\\u0027')
}
Loading