Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/common-wings-doubt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/kit": patch
---

fix: reject malformed streamed data encoding
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/client/ndjson.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { read_stream } from './stream.js';
* @param {ReadableStreamDefaultReader<Uint8Array>} reader
*/
export async function* read_ndjson(reader) {
for await (const block of read_stream(reader, '\n')) {
for await (const block of read_stream(reader, '\n', { fatal: true })) {
const line = block.trim();
if (line) {
yield JSON.parse(line);
Expand Down
48 changes: 48 additions & 0 deletions packages/kit/src/runtime/client/ndjson.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { expect, test } from 'vitest';
import { read_ndjson } from './ndjson.js';

const encoder = new TextEncoder();

/**
* @param {Uint8Array[]} chunks
*/
function read(chunks) {
return read_ndjson(
new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(chunk);
}
controller.close();
}
}).getReader()
);
}

/**
* @param {Uint8Array[]} chunks
*/
async function collect(chunks) {
const values = [];
for await (const value of read(chunks)) {
values.push(value);
}
return values;
}

test('parses streamed data when UTF-8 code points are split across chunks', async () => {
const bytes = encoder.encode(`${JSON.stringify({ type: 'data', value: '\u00e9' })}\n`);
const chunks = Array.from(bytes, (byte) => new Uint8Array([byte]));

await expect(collect(chunks)).resolves.toEqual([{ type: 'data', value: '\u00e9' }]);
});

test('rejects malformed UTF-8 before parsing streamed data', async () => {
const chunks = [
encoder.encode('{"type":"data","nodes":[{"id":239,'),
new Uint8Array([0xff]),
encoder.encode('"url":240}]}\n')
];

await expect(collect(chunks)).rejects.toThrow(TypeError);
});
5 changes: 3 additions & 2 deletions packages/kit/src/runtime/client/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
* stream closes.
* @param {ReadableStreamDefaultReader<Uint8Array>} reader
* @param {string} delimiter
* @param {TextDecoderOptions} [options]
*/
export async function* read_stream(reader, delimiter) {
export async function* read_stream(reader, delimiter, options) {
let done = false;
let buffer = '';
const decoder = new TextDecoder();
const decoder = new TextDecoder(undefined, options);

while (true) {
let split = buffer.indexOf(delimiter);
Expand Down
Loading