forked from RaminNietzsche/CVE-Radar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecrets.ts
More file actions
43 lines (36 loc) · 1.42 KB
/
Copy pathsecrets.ts
File metadata and controls
43 lines (36 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { readFileSync } from "node:fs";
/** Env pairs: direct value or `*_FILE` path (Docker/K8s secret mounts). */
export const SECRET_ENV_PAIRS = [
["NVD_API_KEY", "NVD_API_KEY_FILE"],
["GITHUB_TOKEN", "GITHUB_TOKEN_FILE"],
["DEEPL_API_KEY", "DEEPL_API_KEY_FILE"],
["ALERT_WEBHOOK_URL", "ALERT_WEBHOOK_URL_FILE"],
["API_SECRET", "API_SECRET_FILE"],
] as const;
export type SecretEnvKey = (typeof SECRET_ENV_PAIRS)[number][0];
export function readSecret(envKey: string, fileKey: string): string | undefined {
const filePath = process.env[fileKey]?.trim();
if (filePath) {
return readFileSync(filePath, "utf8").trim() || undefined;
}
const direct = process.env[envKey]?.trim();
return direct || undefined;
}
/** Load secrets from mounted files into `process.env` before the app reads them. */
export function hydrateSecretsFromFiles(): void {
for (const [envKey, fileKey] of SECRET_ENV_PAIRS) {
const filePath = process.env[fileKey]?.trim();
if (!filePath) continue;
let value: string;
try {
value = readFileSync(filePath, "utf8").trim();
} catch (err) {
const message = err instanceof Error ? err.message : "read failed";
throw new Error(`Cannot read ${fileKey} (${filePath}): ${message}`, { cause: err });
}
if (value) process.env[envKey] = value;
}
}
export function hasSecret(envKey: SecretEnvKey): boolean {
return Boolean(readSecret(envKey, `${envKey}_FILE`));
}