* Escapes a CSV value to prevent formula injection and handle special characters. * * Protection against CSV injection attacks: * - Values starting with =, +, -, @, tab, or carriage return are prefixed with single quote * - This prevents execution of formulas like =HYPERLINK() or =CMD|'/C calc'!
(value: string | number | null | undefined)
| 44 | * - Internal double quotes are escaped by doubling them |
| 45 | */ |
| 46 | function escapeCsvValue(value: string | number | null | undefined): string { |
| 47 | if (value === null || value === undefined) return ''; |
| 48 | let str = String(value); |
| 49 | |
| 50 | // Prevent CSV formula injection |
| 51 | // Characters that can trigger formula execution in Excel/Google Sheets |
| 52 | if (/^[=+\-@\t\r]/.test(str)) { |
| 53 | str = `'${str}`; // Prefix with single quote to treat as text |
| 54 | } |
| 55 | |
| 56 | // Standard CSV escaping |
| 57 | if (str.includes(',') || str.includes('"') || str.includes('\n')) { |
| 58 | return `"${str.replace(/"/g, '""')}"`; |
| 59 | } |
| 60 | return str; |
| 61 | } |
| 62 | |
| 63 | function toDownloadFilenameToken(value: string): string { |
| 64 | return value.replace(/[^a-zA-Z0-9_-]+/g, '-'); |
no test coverage detected