The security review of 39d874a (FRE-369) found the address fix recorded
the wrong thing twice. Both are fixed here; the branch is the same one
under review, this commit does not rewrite it.
Q1 — the first x-forwarded-for hop is attacker-chosen text. In
client → Cloudflare → same-host proxy → app, both proxies *append*, so
the header arrives as `<client spoof…>, <true client>, <CF edge>` and
`split(",")[0]` took the sender's own invention — the loopback-peer gate
was sound, the hop selection defeated it. Preference is now
`cf-connecting-ip` (Cloudflare overwrites it, so a client value never
survives the edge), then x-forwarded-for counted from the right with one
trusted hop discounted, then the direct peer. Every candidate must parse
as an address. h3's `getRequestIP(…, { xForwardedFor: true })` has the
same leftmost flaw and is documented as not a fix.
Q4 — the table held full client addresses indefinitely. Every analytics
entry now passes through `truncateIpAddress` in `enrichAnalyticsEntry`
(IPv4 /24, IPv6 /56, unparseable dropped), so no writer can persist a
full address by accident. Retention got the schedule it never had:
`/api/analytics/retention` on a daily Vercel cron, Bearer-authenticated
and fail-closed, with the window parameterised (the old
`cleanupOldAnalytics` spliced the number into the SQL). Default 365 days
rather than the review's 90 so enabling the cron is not itself a
destructive event — the tighter window is an operational decision, named
on the task.
Also from the review: the module doc now forbids feeding this helper into
any security decision; `isLoopbackAddress` parses instead of
string-matching (`::ffff:127.9.9.9`, `0:0:0:0:0:0:0:1`); and `host` is
normalised (lowercased, port stripped) so `nook.freno.me:443` cannot
silently miss the `host = ?` scope. The weekly loopback caveat matches
the truncated shapes writers produce now, and says plainly that "unique
visitors" counts prefixes.
186 lines
6.5 KiB
TypeScript
186 lines
6.5 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),
|
|
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),
|
|
LINEAGE_JWT_SECRET: z.string().min(32),
|
|
APPLE_CLIENT_ID_LINEAGE: z.string().min(1).optional(),
|
|
VITE_TURNSTILE_SITE_KEY: z.string().min(1),
|
|
TURNSTILE_SECRET_KEY: z.string().min(1),
|
|
NOOK_DB_URL: z.string().min(1),
|
|
NOOK_DB_TOKEN: z.string().min(1),
|
|
NOOK_LICENSE_PRIVATE_KEY: z.string().min(1),
|
|
NOOK_STRIPE_SK: z.string().min(1),
|
|
NOOK_STRIPE_WEBHOOK_SECRET: z.string().min(1),
|
|
NOOK_STRIPE_PRICE_ID: z.string().min(1),
|
|
// Brevo list the trial-start emails land in (the lifecycle mail's
|
|
// audience). Optional: capture still stores the address when unset.
|
|
NOOK_TRIAL_LIST_ID: z.coerce.number().int().positive().optional(),
|
|
// Bearer secret for the daily lifecycle-email cron. Falls back to
|
|
// Vercel's CRON_SECRET; unset + no CRON_SECRET = the endpoint denies all.
|
|
NOOK_LIFECYCLE_SECRET: z.string().min(1).optional(),
|
|
// Daily VisitorAnalytics retention cron (/api/analytics-retention). Same
|
|
// shape: falls back to CRON_SECRET, and unset denies every request.
|
|
ANALYTICS_RETENTION_SECRET: z.string().min(1).optional(),
|
|
// How long a VisitorAnalytics row lives. Unset (or unusable) = 365 days;
|
|
// see src/server/analytics-retention.ts before shortening it.
|
|
ANALYTICS_RETENTION_DAYS: z.string().optional(),
|
|
CRON_SECRET: z.string().min(1).optional()
|
|
});
|
|
|
|
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",
|
|
"VITE_GITHUB_CLIENT_ID",
|
|
"VITE_WEBSOCKET",
|
|
"LINEAGE_JWT_SECRET"
|
|
];
|
|
|
|
return requiredServerVars.filter((varName) => isMissingEnvVar(varName));
|
|
};
|