Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/config/src/env-examples.test.ts
T
2026-07-08 16:15:37 +02:00

162 lines
7.0 KiB
TypeScript

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, test } from "vitest";
import { envVariableDefinitions, getEnvVariableDefinition } from "./index.js";
import type { EnvVariableDefinition } from "./types.js";
const examplePaths = [".env.example", ".env.local.example", ".env.production.example", ".env.test"] as const;
const safeEnvFixturePaths = [".env.example", ".env.local.example", ".env.production.example", ".env.test"] as const;
const rootPath = (...segments: string[]) => resolve(process.cwd(), ...segments);
const readProjectFile = (path: string) => readFileSync(rootPath(path), "utf8");
function parseEnvExampleKeys(contents: string) {
return contents
.split(/\r?\n/)
.map((line) => line.trim())
.map((line) => line.replace(/^#\s*/, ""))
.map((line) => line.replace(/\\$/, "").trim())
.map((line) => {
const match = /^(?:[A-Za-z_][A-Za-z0-9_]*\s+)*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
return match?.[1];
})
.filter((key): key is string => Boolean(key));
}
function parseUncommentedEnvExampleKeys(contents: string) {
return contents
.split(/\r?\n/)
.filter((line) => !line.trimStart().startsWith("#"))
.map((line) => line.trim().replace(/\\$/, "").trim())
.map((line) => /^(?:[A-Za-z_][A-Za-z0-9_]*\s+)*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1])
.filter((key): key is string => Boolean(key));
}
function parseEnvAssignments(contents: string) {
return contents
.split(/\r?\n/)
.filter((line) => !line.trimStart().startsWith("#"))
.map((line) => line.trim().replace(/\\$/, "").trim())
.map((line) => {
const match = /^(?:[A-Za-z_][A-Za-z0-9_]*\s+)*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
if (!match) {
return undefined;
}
return [match[1], match[2].trim().replace(/^(["'])(.*)\1$/, "$2")] as const;
})
.filter((assignment): assignment is readonly [string, string] => Boolean(assignment));
}
const catalogNames = new Set<string>(envVariableDefinitions.map((definition) => definition.name));
// Pre-existing example keys that are documented in .env.example but not yet promoted into the
// typed env catalog. Kept as an explicit baseline so future drift still trips the contract.
const exampleOnlyBaseline = new Set<string>([
"FORM_WIDGET_CDN_URL",
"AI_OVERAGE_SUBMISSION_ENABLED",
]);
const catalogedOrDynamicSiteKey = (key: string) =>
Boolean(getEnvVariableDefinition(key as EnvVariableDefinition["name"])) || key.startsWith("SITE_KEY_") || exampleOnlyBaseline.has(key);
const secretLikeKeyPattern = /(?:SECRET|TOKEN|KEY|PASSWORD|WEBHOOK_SIGNING_SECRET|ACCESS_TOKEN|JWT)/i;
const safePlaceholderValuePattern = /^(?:|test[-\w.:@/?=&]+|replace-with[-\w.]+|<[-\w]+>|\{[A-Z_]+\}|YOUR_[A-Z_]+|https:\/\/\.\.\.ngrok-free\.app|https:\/\/your-project\.supabase\.co|https:\/\/formspree\.io\/f\/example|G-XXXXXXXXXX)$/;
describe("env example drift contract", () => {
test.each(examplePaths)("catalogs every example key in %s", (path) => {
const keys = parseEnvExampleKeys(readProjectFile(path));
const unknownKeys = keys.filter((key) => !catalogedOrDynamicSiteKey(key));
expect(unknownKeys, `${path} contains uncataloged env keys: ${unknownKeys.join(", ")}`).toEqual([]);
});
test("keeps only explicit safe env fixtures versionable", () => {
const gitignore = readProjectFile(".gitignore");
expect(gitignore).toMatch(/^\.env$/m);
expect(gitignore).toMatch(/^\.env\.\*$/m);
expect(gitignore).toMatch(/^!\.env\.test$/m);
expect(gitignore).not.toMatch(/^!\.env$/m);
expect(gitignore).not.toMatch(/^!\.env\.\*$/m);
for (const path of safeEnvFixturePaths) {
expect(gitignore, `${path} must be explicitly allowlisted`).toMatch(new RegExp(`^!${path.replace(/\./g, "\\.")}$`, "m"));
}
});
test("keeps .env.test non-secret and cataloged without exposing values", () => {
const path = ".env.test";
const contents = readProjectFile(path);
const assignments = parseEnvAssignments(contents);
const keys = assignments.map(([key]) => key);
const unknownKeys = keys.filter((key) => !catalogedOrDynamicSiteKey(key));
const suspiciousKeys = assignments
.filter(([key, value]) => secretLikeKeyPattern.test(key) && !safePlaceholderValuePattern.test(value))
.map(([key]) => key);
expect(unknownKeys, `${path} contains uncataloged env keys: ${unknownKeys.join(", ")}`).toEqual([]);
expect(suspiciousKeys, `${path} contains secret-looking fixture values for keys: ${suspiciousKeys.join(", ")}`).toEqual([]);
expect(keys).toEqual(expect.arrayContaining(["APP_NAME", "DATABASE_URL", "SESSION_SECRET", "CRYPTO_SECRET", "API_ACCESS_TOKEN", "JWT_SECRET", "WORKER_ENABLED", "BULLMQ_REDIS_URL"]));
});
test("keeps platform and runtime keys explicitly cataloged", () => {
for (const key of ["NODE_ENV", "PORT", "HOST", "WORKER_ENABLED", "BULLMQ_REDIS_URL", "REDIS_URL", "BROWSER_RUNTIME_URL", "BROWSER_RUNTIME_API_KEY", "BROWSER_SESSION_TIMEOUT_MS"]) {
expect(catalogNames.has(key), `${key} must be an explicit catalog entry, not an example-only exemption`).toBe(true);
}
});
test("keeps the shared example aligned with core, worker, and browser runtime keys", () => {
const contents = readProjectFile(".env.example");
const keys = parseEnvExampleKeys(contents);
expect(keys).toEqual(
expect.arrayContaining([
"APP_NAME",
"DATABASE_URL",
"SESSION_SECRET",
"CRYPTO_SECRET",
"APP_BASE_DOMAIN",
"WEB_APP_HOST",
"ADMIN_APP_HOST",
"API_HOST",
"API_ACCESS_TOKEN",
"JWT_SECRET",
"MAILJET_API_KEY",
"MAILJET_SECRET_KEY",
"MAILJET_FROM_EMAIL",
"WORKER_ENABLED",
"WORKER_QUEUE_GROUP",
"WORKER_CONCURRENCY_PLUGIN",
"BULLMQ_REDIS_URL",
"BROWSER_RUNTIME_URL",
"BROWSER_RUNTIME_API_KEY",
"BROWSER_SESSION_TIMEOUT_MS",
])
);
expect(keys).not.toEqual(expect.arrayContaining(["CRISP_CHAT_WEBSITE_ID"]));
expect(contents).not.toContain("CRISP_CHAT_WEBSITE_ID");
});
test("documents worker runtime keys in .env.production.example without required REDIS_URL", () => {
const path = ".env.production.example";
const contents = readProjectFile(path);
const keys = parseEnvExampleKeys(contents);
const requiredKeys = parseUncommentedEnvExampleKeys(contents);
expect(keys).toEqual(
expect.arrayContaining([
"BULLMQ_REDIS_URL",
])
);
expect(requiredKeys, `${path} must not make REDIS_URL an uncommented required key`).not.toContain("REDIS_URL");
expect(keys).toContain("WORKER_ENABLED");
});
test("documents REDIS_URL as a fallback and keeps S05/S06 inventory owners visible", () => {
const inventory = readProjectFile("docs/env-access-inventory.md");
expect(inventory).toMatch(/`REDIS_URL`[^\n]*fallback only when `BULLMQ_REDIS_URL` is absent/i);
expect(inventory).toMatch(/\|[^\n]*\|[^\n]*\|[^\n]*\|[^\n]*\|[^\n]*S05 docs[^\n]*\|/);
expect(inventory).toMatch(/\|[^\n]*\|[^\n]*\|[^\n]*\|[^\n]*\|[^\n]*S06 enforcement[^\n]*\|/);
});
});