|
| 1 | +import fs from 'node:fs'; |
| 2 | +import type http from 'node:http'; |
| 3 | +import os from 'node:os'; |
| 4 | +import path from 'node:path'; |
| 5 | +import { serveStaticFile } from './serve-static-file.js'; |
| 6 | + |
| 7 | +const mkTempDir = () => |
| 8 | + fs.mkdtempSync(path.join(os.tmpdir(), 'serve-static-file-')); |
| 9 | + |
| 10 | +const createResponse = () => { |
| 11 | + let body = ''; |
| 12 | + const response = { |
| 13 | + statusCode: 200, |
| 14 | + setHeader: vi.fn(), |
| 15 | + end: vi.fn((chunk?: string | Buffer) => { |
| 16 | + if (chunk) body += chunk.toString(); |
| 17 | + }), |
| 18 | + } as unknown as http.ServerResponse; |
| 19 | + |
| 20 | + return { response, getBody: () => body }; |
| 21 | +}; |
| 22 | + |
| 23 | +test('serves static files with URL-encoded characters in their names', async () => { |
| 24 | + const projectDir = mkTempDir(); |
| 25 | + const staticDir = path.join(projectDir, 'emails', 'static'); |
| 26 | + const contents = 'asset contents'; |
| 27 | + const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(projectDir); |
| 28 | + const { response, getBody } = createResponse(); |
| 29 | + |
| 30 | + fs.mkdirSync(staticDir, { recursive: true }); |
| 31 | + fs.writeFileSync(path.join(staticDir, 'company logo.txt'), contents); |
| 32 | + |
| 33 | + await serveStaticFile(response, '/static/company%20logo.txt', 'emails'); |
| 34 | + |
| 35 | + expect(response.statusCode).toBe(200); |
| 36 | + expect(getBody()).toBe(contents); |
| 37 | + |
| 38 | + cwdSpy.mockRestore(); |
| 39 | + fs.rmSync(projectDir, { recursive: true }); |
| 40 | +}); |
| 41 | + |
| 42 | +test('does not serve URL-encoded paths outside the static directory', async () => { |
| 43 | + const projectDir = mkTempDir(); |
| 44 | + const staticDir = path.join(projectDir, 'emails', 'static'); |
| 45 | + const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(projectDir); |
| 46 | + const { response } = createResponse(); |
| 47 | + |
| 48 | + fs.mkdirSync(staticDir, { recursive: true }); |
| 49 | + fs.writeFileSync(path.join(projectDir, 'secret.txt'), 'secret contents'); |
| 50 | + |
| 51 | + await serveStaticFile( |
| 52 | + response, |
| 53 | + '/static/%2e%2e%2f%2e%2e%2fsecret.txt', |
| 54 | + 'emails', |
| 55 | + ); |
| 56 | + |
| 57 | + expect(response.statusCode).toBe(403); |
| 58 | + |
| 59 | + cwdSpy.mockRestore(); |
| 60 | + fs.rmSync(projectDir, { recursive: true }); |
| 61 | +}); |
| 62 | + |
| 63 | +test('returns a bad request for malformed URL encoding', async () => { |
| 64 | + const { response } = createResponse(); |
| 65 | + |
| 66 | + await serveStaticFile(response, '/static/image%E0%A4%A.png', 'emails'); |
| 67 | + |
| 68 | + expect(response.statusCode).toBe(400); |
| 69 | +}); |
0 commit comments