Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(self-hosting): validate DATABASE_ENCRYPTION_KEY at startup

Noah52414653b26e
diff --git a/apps/web/__tests__/unit/database-encryption-key-env.test.ts b/apps/web/__tests__/unit/database-encryption-key-env.test.ts
new file mode 100644
index 000000000..e12121ff4
--- /dev/null
+++ b/apps/web/__tests__/unit/database-encryption-key-env.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const loadServerEnv = async () => {
+ vi.resetModules();
+ const { serverEnv } = await import("@cap/env");
+ return serverEnv();
+};
+
+describe("DATABASE_ENCRYPTION_KEY validation", () => {
+ beforeEach(() => {
+ vi.stubEnv("DATABASE_URL", "mysql://localhost/cap");
+ vi.stubEnv("WEB_URL", "http://localhost:3000");
+ vi.stubEnv("NEXTAUTH_SECRET", "test");
+ vi.stubEnv("NEXTAUTH_URL", "http://localhost:3000");
+ vi.stubEnv("CAP_AWS_BUCKET", "cap");
+ vi.stubEnv("CAP_AWS_REGION", "us-east-1");
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ "ab".repeat(32),
+ "ab".repeat(16),
+ `${"ab".repeat(32)}\n`,
+ "",
+ undefined,
+ ])("accepts %j", async (key) => {
+ vi.stubEnv("DATABASE_ENCRYPTION_KEY", key);
+ expect((await loadServerEnv()).DATABASE_ENCRYPTION_KEY).toBe(key);
+ });
+
+ it.each(["x".repeat(32), "ab".repeat(24)])("rejects %j", async (key) => {
+ vi.stubEnv("DATABASE_ENCRYPTION_KEY", key);
+ await expect(loadServerEnv()).rejects.toThrow();
+ expect(console.error).toHaveBeenCalledWith(expect.any(String), [
+ expect.objectContaining({ path: ["DATABASE_ENCRYPTION_KEY"] }),
+ ]);
+ });
+});
diff --git a/apps/web/instrumentation.node.ts b/apps/web/instrumentation.node.ts
index ce13ac04e..5b4382028 100644
--- a/apps/web/instrumentation.node.ts
+++ b/apps/web/instrumentation.node.ts
@@ -14,6 +14,14 @@ import { buildEnv, serverEnv } from "@cap/env";
export async function register() {
if (process.env.NEXT_PUBLIC_IS_CAP) return;
+ // Exit, not throw: Next.js catches a throwing register() and serves 500s.
+ try {
+ serverEnv();
+ } catch {
+ console.error("🚨 Environment validation failed, exiting");
+ process.exit(1);
+ }
+
console.log("Waiting 5 seconds to run migrations");
// Function to trigger migrations with retry logic
const triggerMigrations = async (retryCount = 0, maxRetries = 3) => {
diff --git a/packages/env/server.ts b/packages/env/server.ts
index 78d649a44..a44b990ee 100644
--- a/packages/env/server.ts
+++ b/packages/env/server.ts
@@ -22,6 +22,10 @@ function createServerEnv() {
DATABASE_ENCRYPTION_KEY: z
.string()
.optional()
+ .refine(
+ (key) => !key || [16, 32].includes(Buffer.from(key, "hex").length),
+ "Must be 32 or 64 hex characters, e.g. from `openssl rand -hex 32`",
+ )
.describe(
"32 byte hex string for encrypting values like AWS access keys",
),