| | | 1 | | /** |
| | | 2 | | * Which strings are usable as environment variable names, per the map-file |
| | | 3 | | * naming constraint in ADR-0008: an accepted name must survive a `.env` |
| | | 4 | | * round-trip as itself and nothing else. Anything outside `^[A-Za-z0-9_./-]+$` |
| | | 5 | | * is either read back as a different assignment (`=`, CR, LF, U+2028, U+2029) |
| | | 6 | | * or silently lost (a space, `#`, a tab, a non-Latin letter). `/` stays |
| | | 7 | | * valid: it is the hierarchy separator map files have always used |
| | | 8 | | * (`Database/Password`). |
| | | 9 | | * |
| | | 10 | | * `__proto__` is inside the allowlist but every reader that accumulates pairs |
| | | 11 | | * into a plain object drops it, so it is rejected as well. |
| | | 12 | | */ |
| | 4 | 13 | | const READABLE_NAME = /^[A-Za-z0-9_./-]+$/; |
| | | 14 | | |
| | 4 | 15 | | const UNSUPPORTED_NAMES = new Set(['__proto__']); |
| | | 16 | | |
| | | 17 | | export function isValidEnvironmentVariableName(name: string): boolean { |
| | 65 | 18 | | return READABLE_NAME.test(name) && !UNSUPPORTED_NAMES.has(name); |
| | | 19 | | } |
| | | 20 | | |
| | | 21 | | /** |
| | | 22 | | * Builds the rejection message. The name is untrusted input, so it is quoted |
| | | 23 | | * rather than interpolated: a name carrying line terminators cannot break the |
| | | 24 | | * message across lines. Only the name is echoed, never the mapped value. |
| | | 25 | | */ |
| | | 26 | | export function invalidEnvironmentVariableNameMessage(name: string): string { |
| | 35 | 27 | | if (name.trim() === '') { |
| | 4 | 28 | | return 'Environment variable name cannot be empty'; |
| | | 29 | | } |
| | | 30 | | |
| | 31 | 31 | | if (UNSUPPORTED_NAMES.has(name)) { |
| | 2 | 32 | | return ( |
| | | 33 | | `Unsupported environment variable name ${quoteName(name)}: ` + |
| | | 34 | | 'a .env parser cannot read this name back, so it would be written ' + |
| | | 35 | | 'but never resolved' |
| | | 36 | | ); |
| | | 37 | | } |
| | | 38 | | |
| | 29 | 39 | | return ( |
| | | 40 | | `Invalid environment variable name ${quoteName(name)}: names may only ` + |
| | | 41 | | 'contain letters, digits, underscore, dot, hyphen and slash, so that ' + |
| | | 42 | | 'they can be read back from a .env file' |
| | | 43 | | ); |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | function quoteName(name: string): string { |
| | | 47 | | // JSON.stringify escapes CR, LF and the other control characters, but leaves |
| | | 48 | | // U+2028/U+2029 literal even though they terminate a line in JavaScript. |
| | 31 | 49 | | return JSON.stringify(name) |
| | | 50 | | .replace(/\u{2028}/gu, '\\u2028') |
| | | 51 | | .replace(/\u{2029}/gu, '\\u2029'); |
| | | 52 | | } |