|
| 1 | +import path from 'node:path'; |
| 2 | +import { mkdir, writeFile } from 'node:fs/promises'; |
| 3 | +import type { TidewaveConfig } from '../../core'; |
| 4 | +import type { TidewaveHandler, TidewaveNext, TidewaveRequest, TidewaveResponse } from '../types'; |
| 5 | +import { magicByteType } from '../magic-bytes'; |
| 6 | +import { checkOrigin } from '../security'; |
| 7 | + |
| 8 | +const MAX_UPLOAD_SIZE = 200_000_000; |
| 9 | +const ALLOWED_UPLOAD_CONTENT_TYPES = ['image/png', 'image/jpeg', 'video/webm'] as const; |
| 10 | +const ALLOWED_UPLOAD_TYPES = ['screenshot', 'recording'] as const; |
| 11 | +const ALLOWED_UPLOAD_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webm'] as const; |
| 12 | +const INVALID_UPLOAD = 'Bad Request: missing or invalid file parameter'; |
| 13 | + |
| 14 | +class InvalidUploadError extends Error {} |
| 15 | + |
| 16 | +interface UploadedFile { |
| 17 | + readonly name: string; |
| 18 | + readonly type: string; |
| 19 | + arrayBuffer(): Promise<ArrayBuffer>; |
| 20 | +} |
| 21 | + |
| 22 | +interface UploadFormData { |
| 23 | + get(name: string): unknown; |
| 24 | +} |
| 25 | + |
| 26 | +export function createHandleUpload(config: TidewaveConfig): TidewaveHandler { |
| 27 | + return async function handleUpload( |
| 28 | + req: TidewaveRequest, |
| 29 | + res: TidewaveResponse, |
| 30 | + next: TidewaveNext, |
| 31 | + ): Promise<void> { |
| 32 | + try { |
| 33 | + if (req.method !== 'POST') { |
| 34 | + notFound(res); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + if (!checkOrigin(req, res, config)) return; |
| 39 | + if (uploadTooLarge(req)) { |
| 40 | + badRequest(res); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const formData = await parseFormData(req); |
| 45 | + const type = formData.get('type'); |
| 46 | + const file = formData.get('file'); |
| 47 | + |
| 48 | + if (!isAllowedUploadType(type) || !isUploadedFile(file)) { |
| 49 | + badRequest(res); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + const buffer = Buffer.from(await file.arrayBuffer()); |
| 54 | + |
| 55 | + if (!isAllowedUpload(file, buffer)) { |
| 56 | + badRequest(res); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + const destination = uploadPath(config, type, file.name); |
| 61 | + if (!destination) { |
| 62 | + badRequest(res); |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + await mkdir(uploadDir(config, type), { recursive: true }); |
| 67 | + await writeFile(destination, buffer); |
| 68 | + |
| 69 | + res.statusCode = 200; |
| 70 | + res.setHeader('Content-Type', 'application/json'); |
| 71 | + res.end(JSON.stringify({ status: 'ok', path: destination })); |
| 72 | + } catch (err) { |
| 73 | + if (err instanceof InvalidUploadError) { |
| 74 | + badRequest(res); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + console.error(`[Tidewave] Failed to handle upload: ${err}`); |
| 79 | + |
| 80 | + if (!res.headersSent) { |
| 81 | + res.statusCode = 500; |
| 82 | + res.end('Internal server error'); |
| 83 | + } |
| 84 | + |
| 85 | + next(err); |
| 86 | + } |
| 87 | + }; |
| 88 | +} |
| 89 | + |
| 90 | +function uploadTooLarge(req: TidewaveRequest): boolean { |
| 91 | + const contentLength = firstHeaderValue(req.headers['content-length']); |
| 92 | + if (!contentLength) return false; |
| 93 | + |
| 94 | + const size = Number(contentLength); |
| 95 | + return Number.isFinite(size) && size > MAX_UPLOAD_SIZE; |
| 96 | +} |
| 97 | + |
| 98 | +async function parseFormData(req: TidewaveRequest): Promise<UploadFormData> { |
| 99 | + const body = await readRequestBody(req); |
| 100 | + const request = new Request(requestUrl(req), { |
| 101 | + method: req.method, |
| 102 | + headers: requestHeaders(req), |
| 103 | + body: toArrayBuffer(body), |
| 104 | + }); |
| 105 | + |
| 106 | + try { |
| 107 | + return await request.formData(); |
| 108 | + } catch { |
| 109 | + throw new InvalidUploadError(INVALID_UPLOAD); |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +async function readRequestBody(req: TidewaveRequest): Promise<Buffer> { |
| 114 | + const chunks: Buffer[] = []; |
| 115 | + let size = 0; |
| 116 | + |
| 117 | + for await (const chunk of req) { |
| 118 | + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); |
| 119 | + size += buffer.length; |
| 120 | + |
| 121 | + if (size > MAX_UPLOAD_SIZE) { |
| 122 | + throw new InvalidUploadError(INVALID_UPLOAD); |
| 123 | + } |
| 124 | + |
| 125 | + chunks.push(buffer); |
| 126 | + } |
| 127 | + |
| 128 | + return Buffer.concat(chunks); |
| 129 | +} |
| 130 | + |
| 131 | +function toArrayBuffer(buffer: Buffer): ArrayBuffer { |
| 132 | + const arrayBuffer = new ArrayBuffer(buffer.byteLength); |
| 133 | + new Uint8Array(arrayBuffer).set(buffer); |
| 134 | + return arrayBuffer; |
| 135 | +} |
| 136 | + |
| 137 | +function requestUrl(req: TidewaveRequest): string { |
| 138 | + const host = firstHeaderValue(req.headers.host) || 'localhost'; |
| 139 | + return `http://${host}${req.url || '/'}`; |
| 140 | +} |
| 141 | + |
| 142 | +function requestHeaders(req: TidewaveRequest): Headers { |
| 143 | + const headers = new Headers(); |
| 144 | + |
| 145 | + for (const [name, value] of Object.entries(req.headers)) { |
| 146 | + if (Array.isArray(value)) { |
| 147 | + for (const item of value) headers.append(name, item); |
| 148 | + } else if (value !== undefined) { |
| 149 | + headers.set(name, value); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return headers; |
| 154 | +} |
| 155 | + |
| 156 | +function firstHeaderValue(value: string | string[] | undefined): string | undefined { |
| 157 | + if (Array.isArray(value)) return value[0]; |
| 158 | + return value; |
| 159 | +} |
| 160 | + |
| 161 | +function isAllowedUploadType(type: unknown): type is (typeof ALLOWED_UPLOAD_TYPES)[number] { |
| 162 | + return typeof type === 'string' && isOneOf(ALLOWED_UPLOAD_TYPES, type); |
| 163 | +} |
| 164 | + |
| 165 | +function isUploadedFile(file: unknown): file is UploadedFile { |
| 166 | + if (typeof file !== 'object' || file === null) return false; |
| 167 | + |
| 168 | + const candidate = file as Partial<UploadedFile>; |
| 169 | + return ( |
| 170 | + typeof candidate.name === 'string' && |
| 171 | + typeof candidate.type === 'string' && |
| 172 | + typeof candidate.arrayBuffer === 'function' |
| 173 | + ); |
| 174 | +} |
| 175 | + |
| 176 | +function isAllowedUpload(file: UploadedFile, buffer: Buffer): boolean { |
| 177 | + const [contentType] = file.type.split(';'); |
| 178 | + |
| 179 | + return ( |
| 180 | + isOneOf(ALLOWED_UPLOAD_CONTENT_TYPES, contentType || '') && |
| 181 | + magicByteType(buffer.subarray(0, 128)) !== 'unknown' |
| 182 | + ); |
| 183 | +} |
| 184 | + |
| 185 | +function uploadDir(config: TidewaveConfig, type: (typeof ALLOWED_UPLOAD_TYPES)[number]): string { |
| 186 | + return path.join(tmpDir(config), 'tidewave', folderForType(type)); |
| 187 | +} |
| 188 | + |
| 189 | +function uploadPath( |
| 190 | + config: TidewaveConfig, |
| 191 | + type: (typeof ALLOWED_UPLOAD_TYPES)[number], |
| 192 | + filename: string, |
| 193 | +): string | null { |
| 194 | + if (!/^[A-Za-z0-9_.-]+$/.test(filename)) return null; |
| 195 | + |
| 196 | + const ext = path.extname(filename).toLowerCase(); |
| 197 | + if (!isOneOf(ALLOWED_UPLOAD_EXTENSIONS, ext)) return null; |
| 198 | + |
| 199 | + return path.join(uploadDir(config, type), filename); |
| 200 | +} |
| 201 | + |
| 202 | +function isOneOf<const T extends readonly string[]>(values: T, value: string): value is T[number] { |
| 203 | + return values.includes(value); |
| 204 | +} |
| 205 | + |
| 206 | +function tmpDir(config: TidewaveConfig): string { |
| 207 | + return config.tmpDir || 'tmp'; |
| 208 | +} |
| 209 | + |
| 210 | +function folderForType(type: (typeof ALLOWED_UPLOAD_TYPES)[number]): string { |
| 211 | + switch (type) { |
| 212 | + case 'screenshot': |
| 213 | + return 'screenshots'; |
| 214 | + case 'recording': |
| 215 | + return 'recordings'; |
| 216 | + } |
| 217 | +} |
| 218 | + |
| 219 | +function badRequest(res: TidewaveResponse): void { |
| 220 | + res.statusCode = 400; |
| 221 | + res.end(INVALID_UPLOAD); |
| 222 | +} |
| 223 | + |
| 224 | +function notFound(res: TidewaveResponse): void { |
| 225 | + res.statusCode = 404; |
| 226 | + res.end('Not Found'); |
| 227 | +} |
0 commit comments