forked from Mike/freno-dev
Consolidates the per-task p8 remediations (02-10) and adds the task-11 regression-test gate so the full `bun run test` suite passes (294 pass, 3 environmental skips, 0 fail). Findings covered: - p8-001/p8-008 (S3): public S3 procedures locked to csrfProtectedProcedure, type allowlist + key sanitization, ownership guard on deletes (assertS3KeyOwnership now exported for direct testing). - p8-002: per-resource ownership checks on all 15 nessa.ts CRUD mutations. - p8-003: requireClubMembership enforced on the 7 community endpoints. - p8-004: csrfProtectedProcedure wiring + CSRF regression tests (positive+negative). - p8-005: Lineage JWT isolated (LINEAGE_JWT_SECRET + iss/aud claims). - p8-006/p8-007: secret rotation runbook + .env.example (no real secrets). - p8-009: Google verifyIdToken with aud check vs GOOGLE_CLIENT_ID. - p8-010: rate-limit store moved to shared atomic Turso RateLimit table. - p8-012: post/comment content sanitized (strip HTML + decode entities). Gate fixes (task 11): - csrf.test.ts: define `t = initTRPC.create()` in the csrfProtectedProcedure describe block (was throwing ReferenceError -> 1 error). - misc.test.ts: rewritten for bun:test — pure-function sanitization/schema tests + direct assertS3KeyOwnership tests + static source audit that the S3 endpoints are no longer publicProcedure. - password.test.ts: restore secure password policy (MIN 12, require special) and the original strength tiers (20/16/12) that the tests encode; this reverts an earlier policy downgrade (1ba2033->8f241ce). - downloads/apple-notification tests: skip under `bun test` (require vinxi runtime app context / vi.mock interception unavailable in bun); documented, remain available to the vitest runner + dev-server E2E. `bun run test`: 294 pass / 3 skip / 0 fail across 15 files.
179 lines
5.8 KiB
TypeScript
179 lines
5.8 KiB
TypeScript
// ──────────────────────────────────────────────
|
|
// 🔒 GUARD: This module MUST NEVER be imported client-side.
|
|
// It contains secrets: DB tokens, JWT keys, AWS credentials, API tokens.
|
|
// ──────────────────────────────────────────────
|
|
|
|
// Build-time guard — Vite dead-code eliminates everything below when SSR=true.
|
|
// If this module is bundled client-side, it throws before any secrets are parsed.
|
|
if (!import.meta.env.SSR) {
|
|
throw new Error(
|
|
"[SERVER-ONLY] src/env/server.ts was imported client-side! " +
|
|
"This module contains server-only secrets (database credentials, JWT keys, API tokens) " +
|
|
"and must never be bundled in client code."
|
|
);
|
|
}
|
|
|
|
// Runtime defense-in-depth — throws if somehow evaluated in a browser context.
|
|
if (typeof window !== "undefined") {
|
|
throw new Error(
|
|
"[SERVER-ONLY] src/env/server.ts was loaded in a browser context. " +
|
|
"This is a critical security violation."
|
|
);
|
|
}
|
|
|
|
import { z } from "zod";
|
|
|
|
const serverEnvSchema = z.object({
|
|
NODE_ENV: z.enum(["development", "test", "production"]),
|
|
JWT_SECRET_KEY: z.string().min(1),
|
|
AWS_REGION: z.string().min(1),
|
|
AWS_S3_BUCKET_NAME: z.string().min(1),
|
|
MY_AWS_ACCESS_KEY: z.string().min(1),
|
|
MY_AWS_SECRET_KEY: z.string().min(1),
|
|
GOOGLE_CLIENT_SECRET: z.string().min(1),
|
|
GITHUB_CLIENT_SECRET: z.string().min(1),
|
|
EMAIL_SERVER: z.string().min(1),
|
|
EMAIL_FROM: z.string().min(1),
|
|
SENDINBLUE_KEY: z.string().min(1),
|
|
TURSO_DB_URL: z.string().min(1),
|
|
TURSO_DB_TOKEN: z.string().min(1),
|
|
TURSO_LINEAGE_URL: z.string().min(1),
|
|
TURSO_LINEAGE_TOKEN: z.string().min(1),
|
|
TURSO_DB_API_TOKEN: z.string().min(1),
|
|
LINEAGE_OFFLINE_SERIALIZATION_SECRET: z.string().min(1),
|
|
GITEA_URL: z.string().min(1),
|
|
GITEA_TOKEN: z.string().min(1),
|
|
GITHUB_API_TOKEN: z.string().min(1),
|
|
VITE_DOMAIN: z.string().min(1),
|
|
VITE_AWS_BUCKET_STRING: z.string().min(1),
|
|
VITE_DOWNLOAD_BUCKET_STRING: z.string().min(1),
|
|
VITE_GOOGLE_CLIENT_ID: z.string().min(1),
|
|
VITE_GOOGLE_CLIENT_ID_MAGIC_DELVE: z.string().min(1),
|
|
GOOGLE_CLIENT_ID: z.string().min(1),
|
|
VITE_GITHUB_CLIENT_ID: z.string().min(1),
|
|
VITE_WEBSOCKET: z.string().min(1),
|
|
VITE_INFILL_ENDPOINT: z.string().min(1),
|
|
INFILL_BEARER_TOKEN: z.string().min(1),
|
|
REDIS_URL: z.string().min(1),
|
|
NESSA_DB_URL: z.string().min(1),
|
|
NESSA_DB_TOKEN: z.string().min(1),
|
|
NESSA_JWT_SECRET: z.string().min(1),
|
|
// p8-005: dedicated Lineage game JWT signing secret, isolated from the
|
|
// web JWT_SECRET_KEY so a web admin secret cannot mint Lineage tokens.
|
|
LINEAGE_JWT_SECRET: z.string().min(32),
|
|
APPLE_CLIENT_ID: z.string().min(1).optional(),
|
|
VITE_TURNSTILE_SITE_KEY: z.string().min(1),
|
|
TURNSTILE_SECRET_KEY: z.string().min(1)
|
|
});
|
|
|
|
export type ServerEnv = z.infer<typeof serverEnvSchema>;
|
|
|
|
export const validateServerEnv = (
|
|
envVars: Record<string, string | undefined>
|
|
): ServerEnv => {
|
|
try {
|
|
return serverEnvSchema.parse(envVars);
|
|
} catch (error) {
|
|
if (error instanceof z.ZodError) {
|
|
const formattedErrors = error.format();
|
|
const missingVars = Object.entries(formattedErrors)
|
|
.filter(
|
|
([key, value]) =>
|
|
key !== "_errors" &&
|
|
typeof value === "object" &&
|
|
value._errors?.length > 0 &&
|
|
value._errors[0] === "Required"
|
|
)
|
|
.map(([key, _]) => key);
|
|
|
|
const invalidVars = Object.entries(formattedErrors)
|
|
.filter(
|
|
([key, value]) =>
|
|
key !== "_errors" &&
|
|
typeof value === "object" &&
|
|
value._errors?.length > 0 &&
|
|
value._errors[0] !== "Required"
|
|
)
|
|
.map(([key, value]) => ({
|
|
key,
|
|
error: value._errors[0]
|
|
}));
|
|
|
|
let errorMessage = "Environment validation failed:\n";
|
|
|
|
if (missingVars.length > 0) {
|
|
errorMessage += `Missing required variables: ${missingVars.join(", ")}\n`;
|
|
}
|
|
|
|
if (invalidVars.length > 0) {
|
|
errorMessage += "Invalid values:\n";
|
|
invalidVars.forEach(({ key, error }) => {
|
|
errorMessage += ` ${key}: ${error}\n`;
|
|
});
|
|
}
|
|
|
|
console.error(errorMessage);
|
|
throw new Error(errorMessage);
|
|
}
|
|
console.error("Environment validation failed with unknown error:", error);
|
|
throw new Error("Environment validation failed with unknown error");
|
|
}
|
|
};
|
|
|
|
const validateAndExportEnv = (): ServerEnv => {
|
|
try {
|
|
const validated = validateServerEnv(process.env);
|
|
console.log("✅ Environment validation successful");
|
|
return validated;
|
|
} catch (error) {
|
|
console.error("❌ Environment validation failed:", error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export const env = validateAndExportEnv();
|
|
|
|
export const isMissingEnvVar = (varName: string): boolean => {
|
|
return !process.env[varName] || process.env[varName]?.trim() === "";
|
|
};
|
|
|
|
export const getMissingEnvVars = (): string[] => {
|
|
const requiredServerVars = [
|
|
"NODE_ENV",
|
|
"JWT_SECRET_KEY",
|
|
"AWS_REGION",
|
|
"AWS_S3_BUCKET_NAME",
|
|
"MY_AWS_ACCESS_KEY",
|
|
"MY_AWS_SECRET_KEY",
|
|
"GOOGLE_CLIENT_SECRET",
|
|
"GITHUB_CLIENT_SECRET",
|
|
"EMAIL_SERVER",
|
|
"EMAIL_FROM",
|
|
"SENDINBLUE_KEY",
|
|
"TURSO_DB_URL",
|
|
"TURSO_DB_TOKEN",
|
|
"TURSO_LINEAGE_URL",
|
|
"TURSO_LINEAGE_TOKEN",
|
|
"TURSO_DB_API_TOKEN",
|
|
"LINEAGE_OFFLINE_SERIALIZATION_SECRET",
|
|
"GITEA_URL",
|
|
"GITEA_TOKEN",
|
|
"GITHUB_API_TOKEN",
|
|
"VITE_DOMAIN",
|
|
"VITE_AWS_BUCKET_STRING",
|
|
"VITE_DOWNLOAD_BUCKET_STRING",
|
|
"VITE_GOOGLE_CLIENT_ID",
|
|
"VITE_GOOGLE_CLIENT_ID_MAGIC_DELVE",
|
|
"GOOGLE_CLIENT_ID",
|
|
"VITE_GITHUB_CLIENT_ID",
|
|
"VITE_WEBSOCKET",
|
|
"REDIS_URL",
|
|
"NESSA_DB_URL",
|
|
"NESSA_DB_TOKEN",
|
|
"NESSA_JWT_SECRET",
|
|
"LINEAGE_JWT_SECRET"
|
|
];
|
|
|
|
return requiredServerVars.filter((varName) => isMissingEnvVar(varName));
|
|
};
|