|
2 | 2 | # ============================================================================ |
3 | 3 | # Dream Server — Safe environment loading (no eval) |
4 | 4 | # ============================================================================ |
5 | | -# Parses KEY="value" lines (with \" and \\ escapes) from stdin and exports |
6 | | -# them in the current shell. Use instead of eval for output from |
7 | | -# build-capability-profile.sh, preflight-engine.sh, resolve-compose-stack.sh, |
8 | | -# load-backend-contract.sh, etc. |
| 5 | +# Scripts that need to load .env should use load_env_file from this script. |
| 6 | +# Do not use eval or "export $(grep ... .env | xargs)" — they allow injection. |
| 7 | +# |
| 8 | +# - load_env_file <path> — parse a .env file and export vars (safe keys, no eval) |
| 9 | +# - load_env_from_output — parse KEY="value" lines from stdin (for script output) |
9 | 10 | # ============================================================================ |
10 | 11 |
|
| 12 | +# Load a .env file safely: comments and empty lines skipped; key names must be |
| 13 | +# valid identifiers; values may be unquoted or quoted; no eval or word-splitting. |
| 14 | +load_env_file() { |
| 15 | + local path="$1" |
| 16 | + [[ -f "$path" ]] || return 0 |
| 17 | + local key value |
| 18 | + while IFS='=' read -r key value; do |
| 19 | + [[ "$key" =~ ^[[:space:]]*# ]] && continue |
| 20 | + key="${key#"${key%%[![:space:]]*}"}" |
| 21 | + key="${key%"${key##*[![:space:]]}"}" |
| 22 | + [[ -z "$key" ]] && continue |
| 23 | + [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue |
| 24 | + value="${value# }" |
| 25 | + value="${value%\"}" |
| 26 | + value="${value#\"}" |
| 27 | + value="${value%\'}" |
| 28 | + value="${value#\'}" |
| 29 | + export "$key=$value" |
| 30 | + done < "$path" |
| 31 | +} |
| 32 | + |
11 | 33 | load_env_from_output() { |
12 | 34 | local line key value |
13 | 35 | while IFS= read -r line; do |
|
0 commit comments