Forty-one commits since v0.11.0. See CHANGELOG.md for the full list and the upgrade notes.
130 lines
5.0 KiB
TypeScript
130 lines
5.0 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, ImmichUnavailableError } from '@/lib/immich';
|
|
import { resolveImageSize } from '@/lib/imageSize';
|
|
import { decodeAssetId } from '@/lib/tokens';
|
|
import { getConfig } from '@/lib/config';
|
|
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
|
|
import { siteLockResponse } from '@/lib/auth';
|
|
|
|
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 = retryAfterSeconds(resetAt);
|
|
const userAgent = request.headers.get('user-agent') || 'unknown';
|
|
console.warn(
|
|
`[Image API] ⚠️ Rate limit exceeded for IP: ${ip} (UA: ${userAgent}). Retry after ${retryAfter}s`,
|
|
);
|
|
// Without Retry-After the browser and next/image back off on their own
|
|
// schedule — a retry storm against a server that just said it was
|
|
// overloaded, and one page issues ~50 of these requests. no-store because
|
|
// the success path serves this URL as `immutable`.
|
|
return NextResponse.json(
|
|
{ error: 'Too many requests' },
|
|
{
|
|
status: 429,
|
|
headers: { 'Retry-After': String(retryAfter), 'Cache-Control': 'no-store' },
|
|
},
|
|
);
|
|
}
|
|
|
|
// The page-level gate does not cover route handlers — without this a locked
|
|
// site would still serve to anyone holding the URL.
|
|
const locked = siteLockResponse(request);
|
|
if (locked) return locked;
|
|
|
|
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 });
|
|
}
|
|
|
|
const size = resolveImageSize(
|
|
request.nextUrl.searchParams.get('size'),
|
|
request.nextUrl.searchParams.get('w'),
|
|
);
|
|
|
|
// ── Browser Cache Optimization ─────────────────────
|
|
// Use the opaque token to generate a safe ETag without leaking Immich UUIDs.
|
|
// IMAGE_CACHE_VERSION participates so that a bump is not defeated by a client
|
|
// replaying the old ETag against the new URL — the response is served
|
|
// `immutable`, so this only matters after expiry or a cache eviction, but a
|
|
// matching ETag across two different URLs would be wrong either way.
|
|
const cacheVersion = request.nextUrl.searchParams.get('v') ?? '';
|
|
const etag = `W/"${token}-${size}${cacheVersion ? `-${cacheVersion}` : ''}"`;
|
|
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),
|
|
},
|
|
});
|
|
}
|
|
|
|
let result;
|
|
try {
|
|
result = await immich.streamAsset(assetId, size);
|
|
} catch (error) {
|
|
// An outage must not look like a deleted photo. These URLs are served with
|
|
// `immutable` on success, and a bare 404 is heuristically cacheable — so
|
|
// without no-store the browser can pin a broken image for the whole session.
|
|
if (error instanceof ImmichUnavailableError) {
|
|
console.error(`[Image API] Immich unavailable for ${assetId}:`, error.message);
|
|
return NextResponse.json(
|
|
{ error: 'Immich is currently unavailable' },
|
|
{ status: 503, headers: { 'Retry-After': '30', 'Cache-Control': 'no-store' } },
|
|
);
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
if (!result) {
|
|
console.error(`[Image API] ❌ Asset not found in Immich: ${assetId} (Size: ${size})`);
|
|
return NextResponse.json(
|
|
{ error: 'Asset not found' },
|
|
{ status: 404, headers: { 'Cache-Control': 'no-store' } },
|
|
);
|
|
}
|
|
|
|
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 });
|
|
}
|