Skip to content
45 changes: 45 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,49 @@ export function addDevEnvVariables() {
} catch (error) {
// Ignore errors if the .env file doesn't exist
}

// Validate the loaded environment variables
validateDevEnvVariables();
}

/**
* Validate and sanitize the DEV_USER_EXTENSIONS_PATH environment variable.
* Removes invalid paths from the environment with logged errors.
*/
function validateDevEnvVariables() {
// Validate DEV_USER_EXTENSIONS_PATH if it was loaded
if (process.env.DEV_USER_EXTENSIONS_PATH) {
let devPath = process.env.DEV_USER_EXTENSIONS_PATH;

// Trim whitespace and resolve the path to an absolute path
devPath = path.resolve(devPath.trim());

// Check if the path exists and is a directory
try {
const stats = fs.statSync(devPath);
if (!stats.isDirectory()) {
logger.error(`DEV_USER_EXTENSIONS_PATH is not a directory: ${devPath}. Removing from environment.`);
delete process.env.DEV_USER_EXTENSIONS_PATH;
} else {
// Update the environment variable with the sanitized (trimmed and resolved) path
process.env.DEV_USER_EXTENSIONS_PATH = devPath;
}
} catch (error) {
const nodeError = error as NodeJS.ErrnoException;
const errorCode = nodeError.code || "UNKNOWN";

// Provide specific error messages based on the error code
let errorMessage: string;
if (errorCode === "ENOENT") {
errorMessage = `DEV_USER_EXTENSIONS_PATH does not exist: ${devPath}. Removing from environment.`;
} else if (errorCode === "EACCES") {
errorMessage = `Permission denied accessing DEV_USER_EXTENSIONS_PATH: ${devPath}. Removing from environment.`;
} else {
errorMessage = `Error accessing DEV_USER_EXTENSIONS_PATH: ${devPath} (${errorCode}). Removing from environment.`;
}

logger.error(errorMessage, error as Error);
delete process.env.DEV_USER_EXTENSIONS_PATH;
}
}
}