Files
immich-folio/app/api/image/[id]/route.ts
Ralksta 37f7f62157 security: fix pre-auth bypasses and restore Immich 3.x compatibility (#378)
Seven security issues from an audit, plus album pages and the map coming
up empty against Immich 3.x. Verified against a real Immich 3.0.3
instance in a production build.

Security:
- Admin session forgery via a hardcoded 'dev-fallback-secret' signing key
  that bypassed the production AUTH_SECRET guard
- /api/map ignored album passwords and returned working asset tokens;
  rewriting ?size=thumbnail to ?size=original downloaded full-resolution
  originals from protected albums
- Admin login had no rate limit, and the client IP came from a spoofable
  header, so rotating it bypassed every limit in the app
- Raw Immich asset UUIDs were serialized into the RSC payload
- Album tokens never expired server-side; a captured token replayed forever
- Path traversal into the Immich API via an unvalidated album id
- /admin ran with no enforced CSP (only Report-Only reached it)

TRUSTED_PROXIES is replaced by TRUSTED_PROXY_HOPS. The old variable
matched proxy IPs against the socket peer address, which self-hosted
Next.js never exposes, so the check could never pass: unset, the limiter
read a spoofable header; set, every request shared one bucket and a single
client could rate-limit the whole site. Migrates automatically.

Immich 3.x: GET /albums/:id no longer embeds assets. Assets now come from
POST /search/metadata with withExif: true — without that flag EXIF is
omitted and grid aspect ratios, the lightbox panel and map markers stay
empty. Drops support for Immich below 3.0, which now logs a warning.

Upgrade: requires Immich 3.0+; set TRUSTED_PROXY_HOPS (nginx = 1);
visitors of protected areas and admin sessions must log in once more.

91 unit tests (25 new); the new admin-auth and rate-limit cases were
confirmed to fail against the pre-fix code.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 18:57:57 +02:00

109 lines
3.8 KiB
TypeScript

/**
* Image proxy route — serves Immich assets to the browser
* without exposing the Immich server or API key.
*
* Usage: GET /api/image/:token?size=thumbnail|preview|original
* GET /api/image/:token?w=640&q=75 (for next/image loader)
* The :token is an encoded asset ID (not a raw UUID).
*/
import { NextRequest, NextResponse } from 'next/server';
import { immich, ImageSize } from '@/lib/immich';
import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
const VALID_SIZES: ImageSize[] = ['thumbnail', 'preview', 'original'];
/**
* Map a requested pixel width to the best Immich size tier.
*/
function widthToSize(w: number): ImageSize {
if (w <= 250) return 'thumbnail';
if (w <= 1440) return 'preview';
return 'original';
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
// ── Rate limiting ──────────────────────────────────
const ip = getClientIp(request);
const { success, remaining, resetAt } = checkRateLimit(`image:${ip}`, getConfig().rateLimitRpm);
if (!success) {
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
const userAgent = request.headers.get('user-agent') || 'unknown';
console.warn(
`[Image API] ⚠️ Rate limit exceeded for IP: ${ip} (UA: ${userAgent}). Retry after ${retryAfter}s`,
);
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
const { id: token } = await params;
// Decode the opaque token back to an Immich asset ID
const assetId = decodeAssetId(token);
if (!assetId) {
console.error(`[Image API] ❌ Invalid token: ${token.substring(0, 10)}...`);
return NextResponse.json({ error: 'Invalid token' }, { status: 400 });
}
// Determine size: prefer explicit ?size=, then infer from ?w=
const sizeParam = request.nextUrl.searchParams.get('size');
const widthParam = request.nextUrl.searchParams.get('w');
let size: ImageSize = 'preview';
if (sizeParam && VALID_SIZES.includes(sizeParam as ImageSize)) {
size = sizeParam as ImageSize;
} else if (widthParam) {
const w = parseInt(widthParam, 10);
if (!isNaN(w) && w > 0) {
size = widthToSize(w);
}
}
// ── Browser Cache Optimization ─────────────────────
// Use the opaque token to generate a safe ETag without leaking Immich UUIDs
const etag = `W/"${token}-${size}"`;
if (request.headers.get('if-none-match') === etag) {
return new NextResponse(null, {
status: 304,
headers: {
ETag: etag,
'Cache-Control': 'public, max-age=31536000, immutable',
'X-RateLimit-Remaining': String(remaining),
},
});
}
const result = await immich.streamAsset(assetId, size);
if (!result) {
console.error(`[Image API] ❌ Asset not found in Immich: ${assetId} (Size: ${size})`);
return NextResponse.json({ error: 'Asset not found' }, { status: 404 });
}
let contentType = result.contentType.toLowerCase();
if (contentType.includes('application/octet-stream')) {
contentType = 'image/jpeg';
} else if (
!contentType.startsWith('image/') ||
contentType.includes('svg') ||
contentType.includes('xml')
) {
contentType = 'application/octet-stream';
}
const headers: Record<string, string> = {
'Content-Type': contentType,
// Images are immutable once uploaded to Immich — cache aggressively
'Cache-Control': 'public, max-age=31536000, immutable',
ETag: etag,
'X-RateLimit-Remaining': String(remaining),
};
if (result.contentLength) {
headers['Content-Length'] = result.contentLength;
}
return new NextResponse(result.stream, { headers });
}