security: implement secure IP retrieval with TRUSTED_PROXIES support (closes #139)

This commit is contained in:
ralksta
2026-04-24 22:14:53 +02:00
parent 3c5715e0b0
commit 771cee517a
6 changed files with 64 additions and 7 deletions

View File

@@ -1,3 +1,4 @@
import crypto from 'crypto';
import { env } from '../env';
import { loadYaml, validateUuid } from './parser';
import { resolveTheme, VALID_LAYOUTS } from './theme';
@@ -16,6 +17,7 @@ export * from './schema';
export * from './theme';
let _config: AppConfig | null = null;
let _fallbackSecret: string | null = null;
/** Converts raw YAML grid overrides into a typed partial GridConfig. */
export function buildSubpageGrid(raw?: {
@@ -54,10 +56,13 @@ export function getConfig(): AppConfig {
'SECURITY ERROR: AUTH_SECRET is not set in production. Please set a long random string as AUTH_SECRET in your .env.',
);
}
if (!_fallbackSecret) {
_fallbackSecret = crypto.randomBytes(32).toString('hex');
}
console.warn(
'\n⚠️ SECURITY WARNING: AUTH_SECRET is not set. Falling back to IMMICH_API_KEY.\n Please set a long random string as AUTH_SECRET in your .env for better security.\n',
'\n⚠️ SECURITY WARNING: AUTH_SECRET is not set. Generating a temporary random secret for this session.\n Please set a long random string as AUTH_SECRET in your .env for better security.\n',
);
AUTH_SECRET = apiKey;
AUTH_SECRET = _fallbackSecret;
}
const authSecret = AUTH_SECRET;
@@ -93,6 +98,7 @@ export function getConfig(): AppConfig {
albumPasswords: {},
cacheTtl: env.CACHE_TTL * 1000,
rateLimitRpm: env.RATE_LIMIT_RPM,
trustedProxies: env.TRUSTED_PROXIES,
needsSetup: true,
};
return _config;
@@ -268,6 +274,7 @@ export function getConfig(): AppConfig {
albumPasswords,
cacheTtl: env.CACHE_TTL * 1000,
rateLimitRpm: env.RATE_LIMIT_RPM,
trustedProxies: env.TRUSTED_PROXIES,
needsSetup: false,
};
return _config;

View File

@@ -94,6 +94,7 @@ export interface AppConfig {
albumPasswords: Record<string, string>;
cacheTtl: number;
rateLimitRpm: number;
trustedProxies: string[];
needsSetup?: boolean;
}

View File

@@ -11,6 +11,7 @@ export interface Env {
CACHE_TTL: number;
RATE_LIMIT_RPM: number;
AUTH_SECRET?: string;
TRUSTED_PROXIES: string[];
}
function parseEnv(): Env {
@@ -44,6 +45,10 @@ function parseEnv(): Env {
CACHE_TTL: Math.max(0, cacheTtl),
RATE_LIMIT_RPM: Math.max(1, rateLimit),
AUTH_SECRET: process.env.AUTH_SECRET,
TRUSTED_PROXIES: (process.env.TRUSTED_PROXIES || '')
.split(',')
.map((ip) => ip.trim())
.filter((ip) => ip !== ''),
};
}

View File

@@ -10,15 +10,32 @@
*/
import { NextRequest } from 'next/server';
import { getConfig } from './config';
export function getClientIp(request: NextRequest): string {
// @ts-expect-error - Next.js 15 removed request.ip but hosting platforms like Vercel still populate it
const ip = request.ip as string | undefined;
const config = getConfig();
const directIp = request.ip; // Populated by Next.js if on Vercel/Netlify
const xForwardedFor = request.headers.get('x-forwarded-for');
const xRealIp = request.headers.get('x-real-ip');
// If trusted proxies are configured, only trust headers if the request
// comes from one of those proxies.
if (config.trustedProxies.length > 0) {
if (directIp && config.trustedProxies.includes(directIp)) {
return xRealIp ?? xForwardedFor?.split(',')[0].trim() ?? directIp;
}
// If we have trusted proxies but the direct IP is unknown or untrusted,
// we return the direct IP (if any) and ignore potentially spoofed headers.
return directIp ?? 'unknown';
}
// Fallback for self-hosted environments without explicit trusted proxies:
// We have to trust headers as a best-effort, but this is vulnerable to spoofing.
return (
ip ??
request.headers.get('x-real-ip') ??
request.headers.get('x-forwarded-for')?.split(',')[0].trim() ??
directIp ??
xRealIp ??
xForwardedFor?.split(',')[0].trim() ??
'unknown'
);
}