Files
nanoclaw/src/env.ts
T
root 0f01fe2c07 fix(env): prevent crash on single-character .env values
A value like `X=a` would pass the startsWith/endsWith quote check
(both `"` and `'` are single chars), then slice(1, -1) would produce
an empty string, silently dropping the value. Add length >= 2 guard
before checking for surrounding quotes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 19:01:17 -03:00

44 lines
1.3 KiB
TypeScript

import fs from 'fs';
import path from 'path';
import { logger } from './logger.js';
/**
* Parse the .env file and return values for the requested keys.
* Does NOT load anything into process.env — callers decide what to
* do with the values. This keeps secrets out of the process environment
* so they don't leak to child processes.
*/
export function readEnvFile(keys: string[]): Record<string, string> {
const envFile = path.join(process.cwd(), '.env');
let content: string;
try {
content = fs.readFileSync(envFile, 'utf-8');
} catch (err) {
logger.debug({ err }, '.env file not found, using defaults');
return {};
}
const result: Record<string, string> = {};
const wanted = new Set(keys);
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx === -1) continue;
const key = trimmed.slice(0, eqIdx).trim();
if (!wanted.has(key)) continue;
let value = trimmed.slice(eqIdx + 1).trim();
if (
value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")))
) {
value = value.slice(1, -1);
}
if (value) result[key] = value;
}
return result;
}