|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | + |
| 3 | +import { htmlSafeJson } from '../htmlSafeJson'; |
| 4 | + |
| 5 | +describe('htmlSafeJson', () => { |
| 6 | + it('escapes </script> breakout sequences so they cannot terminate a script element', () => { |
| 7 | + const payload = { bio: '</script><script>alert(1)</script>' }; |
| 8 | + const out = htmlSafeJson(payload); |
| 9 | + |
| 10 | + expect(out).not.toContain('</'); |
| 11 | + expect(out).not.toContain('<'); |
| 12 | + expect(out).not.toContain('>'); |
| 13 | + expect(out).not.toContain('/'); |
| 14 | + expect(JSON.parse(out)).toEqual(payload); |
| 15 | + }); |
| 16 | + |
| 17 | + it('escapes U+2028 and U+2029 line terminators', () => { |
| 18 | + const payload = { sep: '
' }; |
| 19 | + const out = htmlSafeJson(payload); |
| 20 | + |
| 21 | + expect(out).toContain('\\u2028'); |
| 22 | + expect(out).toContain('\\u2029'); |
| 23 | + expect(out).not.toContain('
'); |
| 24 | + expect(out).not.toContain('
'); |
| 25 | + expect(JSON.parse(out)).toEqual(payload); |
| 26 | + }); |
| 27 | + |
| 28 | + it('round-trips arbitrary nested values', () => { |
| 29 | + const payload = { a: 1, b: 'plain', c: { d: ['x', '</script>', null] }, e: true }; |
| 30 | + expect(JSON.parse(htmlSafeJson(payload))).toEqual(payload); |
| 31 | + }); |
| 32 | + |
| 33 | + it('returns "undefined" when JSON.stringify yields undefined', () => { |
| 34 | + expect(htmlSafeJson(undefined)).toBe('undefined'); |
| 35 | + expect(htmlSafeJson(() => {})).toBe('undefined'); |
| 36 | + }); |
| 37 | +}); |
0 commit comments