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
13 changes: 12 additions & 1 deletion src/files/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ export async function downloadFile(
throw new CLIError(`Download failed: HTTP ${res.status}`, ExitCode.GENERAL);
}

const contentLength = Number(res.headers.get('content-length') || 0);
// fetch transparently decodes compressed responses, so Content-Length
// only describes the readable body when no Content-Encoding is present.
const contentLength = res.headers.get('content-encoding')
? 0
: Number(res.headers.get('content-length') || 0);
const reader = res.body?.getReader();
if (!reader) throw new CLIError('No response body', ExitCode.GENERAL);

Expand Down Expand Up @@ -69,6 +73,13 @@ export async function downloadFile(
received += value.byteLength;
progress?.update(received);
}

if (contentLength > 0 && received !== contentLength) {
throw new CLIError(
`Download truncated: expected ${contentLength} bytes, received ${received}.`,
ExitCode.NETWORK,
);
}
readComplete = true;
} finally {
reader.releaseLock();
Expand Down
37 changes: 37 additions & 0 deletions test/files/download.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,41 @@ describe('downloadFile', () => {
expect(existsSync(destPath)).toBe(true);
expect(readdirSync(dir)).toEqual(['video.mp4']);
});

it('rejects a cleanly ended response whose body is shorter than Content-Length', async () => {
const dir = makeTempDir();
const destPath = join(dir, 'video.mp4');
writeFileSync(destPath, 'original');

globalThis.fetch = (async () => new Response(new TextEncoder().encode('new'), {
status: 200,
headers: { 'content-length': '10' },
})) as unknown as typeof fetch;

await expect(
downloadFile('https://example.com/video.mp4', destPath, { quiet: true, retries: 0 }),
).rejects.toThrow('Download truncated: expected 10 bytes, received 3');

expect(readFileSync(destPath, 'utf-8')).toBe('original');
expect(readdirSync(dir)).toEqual(['video.mp4']);
});

it('does not compare decoded response bytes with compressed Content-Length', async () => {
const dir = makeTempDir();
const destPath = join(dir, 'video.mp4');

globalThis.fetch = (async () => new Response(new TextEncoder().encode('new'), {
status: 200,
headers: {
'content-encoding': 'gzip',
'content-length': '10',
},
})) as unknown as typeof fetch;

await expect(
downloadFile('https://example.com/video.mp4', destPath, { quiet: true, retries: 0 }),
).resolves.toEqual({ size: 3 });

expect(readFileSync(destPath, 'utf-8')).toBe('new');
});
});
Loading