release: v0.20.0

This commit is contained in:
Ralksta
2026-10-02 18:14:23 +02:00
committed by GitHub
parent 81ce886b01
commit 5f831f719a
209 changed files with 13807 additions and 803 deletions

View File

@@ -0,0 +1,279 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { NextRequest, NextResponse } from 'next/server';
import {
LAT,
asciiOf,
cameraHeic,
cameraJpeg,
chunked,
contains,
exifOf,
heicExif,
latin1,
parseTiff,
} from '@/lib/__tests__/fixtures/location';
/**
* GET /api/zoom/[album]/[id] (#467): the full-resolution file behind the
* lightbox zoom. Every refusal is the same 404; the route checks are tested
* here, the per-route zoom/password resolution in lib/__tests__/auth-zoom.
*/
vi.mock('@/lib/config', () => ({ getConfig: vi.fn() }));
vi.mock('@/lib/tokens', () => ({
decodeAssetId: vi.fn((t: string) => (t.startsWith('tok-') ? t.replace('tok-', '') : null)),
}));
vi.mock('@/lib/immich', () => ({
immich: { getAlbum: vi.fn(), streamAsset: vi.fn(), streamFullsize: vi.fn() },
ImmichUnavailableError: class ImmichUnavailableError extends Error {},
}));
vi.mock('@/lib/rate-limit', () => ({
checkRateLimit: vi.fn(() => ({ success: true, resetAt: 0 })),
getClientIp: vi.fn(() => '127.0.0.1'),
retryAfterSeconds: vi.fn(() => 60),
}));
vi.mock('@/lib/auth', () => ({
siteLockResponse: vi.fn(() => null),
isAlbumZoomReachable: vi.fn(() => true),
}));
vi.mock('@/lib/publishedAssets', () => ({ isPublishedAsset: vi.fn(async () => true) }));
vi.mock('next/headers', () => ({
cookies: vi.fn(() => Promise.resolve({ get: () => undefined })),
}));
import { GET } from '../route';
import { getConfig } from '@/lib/config';
import { immich, ImmichUnavailableError } from '@/lib/immich';
import { checkRateLimit } from '@/lib/rate-limit';
import { isAlbumZoomReachable, siteLockResponse } from '@/lib/auth';
import { isPublishedAsset } from '@/lib/publishedAssets';
const mocked = <T>(fn: T) => fn as unknown as ReturnType<typeof vi.fn>;
const asset = (id: string, originalMimeType: string, type = 'IMAGE') => ({
id,
type,
originalMimeType,
originalFileName: `${id}.bin`,
});
const ALBUM = {
id: 'album',
albumName: 'Album',
assets: [
asset('jpeg', 'image/jpeg'),
asset('avif', 'image/avif'),
asset('heic', 'image/heic'),
asset('png', 'image/png'),
asset('webp', 'image/webp'),
asset('mov', 'video/quicktime', 'VIDEO'),
{ ...asset('edited', 'image/jpeg'), isEdited: true },
{ ...asset('edited-heic', 'image/heic'), isEdited: true },
],
};
function upstream(data: Uint8Array, contentType: string) {
return { stream: chunked(data, 1000), contentType, contentLength: String(data.length) };
}
const zoom = (assetToken = 'tok-jpeg', albumToken = 'tok-album') =>
GET(new NextRequest(`http://localhost/api/zoom/${albumToken}/${assetToken}`), {
params: Promise.resolve({ album: albumToken, id: assetToken }),
});
/** A HEIF-family file branded as AVIF, as Lightroom writes one. */
function avifFile() {
const { file } = cameraHeic();
const out = file.slice();
out.set([0x61, 0x76, 0x69, 0x66], 8); // major brand → 'avif'
return out;
}
beforeEach(() => {
vi.clearAllMocks();
mocked(getConfig).mockReturnValue({ albums: ['album'] });
mocked(immich.getAlbum).mockResolvedValue(ALBUM);
});
describe('refusals', () => {
it('answers a locked site with the lock, before anything else', async () => {
mocked(siteLockResponse).mockReturnValueOnce(
NextResponse.json(
{ error: 'locked' },
{ status: 401, headers: { 'Cache-Control': 'no-store' } },
),
);
const res = await zoom();
expect(res.status).toBe(401);
expect(immich.getAlbum).not.toHaveBeenCalled();
});
it('rate-limits in its own bucket', async () => {
mocked(checkRateLimit).mockReturnValueOnce({ success: false, resetAt: Date.now() + 1000 });
const res = await zoom();
expect(res.status).toBe(429);
expect(res.headers.get('cache-control')).toBe('no-store');
expect(res.headers.get('retry-after')).toBe('60');
expect(checkRateLimit).toHaveBeenCalledWith('zoom:127.0.0.1', 20);
});
it.each([
['an undecodable album token', () => zoom('tok-jpeg', 'garbage')],
['an undecodable asset token', () => zoom('garbage')],
])('refuses %s', async (_name, call) => {
const res = await call();
expect(res.status).toBe(404);
expect(res.headers.get('cache-control')).toBe('no-store');
});
it('refuses an album that is not on the allowlist', async () => {
mocked(getConfig).mockReturnValue({ albums: ['other'] });
expect((await zoom()).status).toBe(404);
expect(isAlbumZoomReachable).not.toHaveBeenCalled();
});
it('refuses when zoom is off, or the album is locked, hidden behind an offline page …', async () => {
// isAlbumZoomReachable covers each of those (lib/__tests__/auth-zoom).
mocked(isAlbumZoomReachable).mockReturnValueOnce(false);
const res = await zoom();
expect(res.status).toBe(404);
expect(isAlbumZoomReachable).toHaveBeenCalledWith('album', expect.any(Function));
expect(immich.streamAsset).not.toHaveBeenCalled();
});
it('refuses an asset the site no longer publishes', async () => {
mocked(isPublishedAsset).mockResolvedValueOnce(false);
expect((await zoom()).status).toBe(404);
expect(immich.getAlbum).not.toHaveBeenCalled();
});
it('refuses an asset from another album', async () => {
expect((await zoom('tok-elsewhere')).status).toBe(404);
expect(immich.streamAsset).not.toHaveBeenCalled();
});
it.each(['png', 'webp', 'mov'])('never streams a %s', async (id) => {
expect((await zoom(`tok-${id}`)).status).toBe(404);
expect(immich.streamAsset).not.toHaveBeenCalled();
expect(immich.streamFullsize).not.toHaveBeenCalled();
});
it('answers 503 while Immich is down', async () => {
mocked(immich.getAlbum).mockRejectedValueOnce(new ImmichUnavailableError('down'));
const res = await zoom();
expect(res.status).toBe(503);
expect(res.headers.get('cache-control')).toBe('no-store');
});
});
describe('the JPEG original', () => {
it('goes out without GPS, inline, privately cached, length intact', async () => {
const { file } = cameraJpeg(true);
mocked(immich.streamAsset).mockResolvedValue(upstream(file, 'image/jpeg'));
const res = await zoom();
expect(res.status).toBe(200);
expect(immich.streamAsset).toHaveBeenCalledWith('jpeg', 'original');
expect(immich.streamFullsize).not.toHaveBeenCalled();
expect(res.headers.get('content-type')).toBe('image/jpeg');
expect(res.headers.get('content-disposition')).toBe('inline');
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
expect(res.headers.get('cache-control')).toBe('private, max-age=3600');
expect(res.headers.get('content-length')).toBe(String(file.length));
const body = new Uint8Array(await res.arrayBuffer());
expect(body.length).toBe(file.length);
const tiff = parseTiff(exifOf(body)!);
expect(tiff.gps).toBeNull();
expect(asciiOf(tiff.ifd0.get(0x0110))).toBe('Canon EOS R5');
expect(contains(body, LAT.value(true))).toBe(false);
expect(latin1(body)).not.toMatch(/exif:GPS/);
});
it('is refused when its metadata cannot be located', async () => {
mocked(immich.streamAsset).mockResolvedValue({
stream: chunked(new Uint8Array([0xff, 0xd8, 0xff, 0xe1, 0x40, 0x00, 0x45, 0x78]), 8),
contentType: 'image/jpeg',
contentLength: '8',
});
expect((await zoom()).status).toBe(404);
});
it('is refused when the bytes are not a JPEG at all', async () => {
// Labelled JPEG, actually a PNG: the scrubber would pass it through
// untouched, eXIf chunk and all.
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
mocked(immich.streamAsset).mockResolvedValue(upstream(png, 'image/jpeg'));
expect((await zoom()).status).toBe(404);
});
});
describe('the AVIF original', () => {
it('goes out without GPS', async () => {
const file = avifFile();
mocked(immich.streamAsset).mockResolvedValue(upstream(file, 'image/avif'));
const res = await zoom('tok-avif');
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toBe('image/avif');
const body = new Uint8Array(await res.arrayBuffer());
expect(body.length).toBe(file.length);
expect(parseTiff(heicExif(body)!).gps).toBeNull();
});
});
describe('a HEIC (not browser-displayable)', () => {
it('uses Immich’s full-size rendition, scrubbed', async () => {
const { file } = cameraJpeg(false);
mocked(immich.streamFullsize).mockResolvedValue(upstream(file, 'image/jpeg'));
const res = await zoom('tok-heic');
expect(res.status).toBe(200);
expect(immich.streamFullsize).toHaveBeenCalledWith('heic', false);
expect(immich.streamAsset).not.toHaveBeenCalled();
const body = new Uint8Array(await res.arrayBuffer());
expect(parseTiff(exifOf(body)!).gps).toBeNull();
});
it('is 404 when Immich has no rendition', async () => {
mocked(immich.streamFullsize).mockResolvedValue(null);
const res = await zoom('tok-heic');
expect(res.status).toBe(404);
expect(res.headers.get('cache-control')).toBe('no-store');
});
it('never sends the HEIC original itself', async () => {
mocked(immich.streamFullsize).mockResolvedValue(upstream(cameraHeic().file, 'image/heic'));
expect((await zoom('tok-heic')).status).toBe(404);
});
it('refuses a WebP rendition, whose metadata is not scrubbed', async () => {
const webp = new TextEncoder().encode('RIFF\x10\x00\x00\x00WEBPVP8 ');
mocked(immich.streamFullsize).mockResolvedValue(upstream(webp, 'image/webp'));
expect((await zoom('tok-heic')).status).toBe(404);
});
});
describe('a photo edited in Immich (#831)', () => {
it.each(['edited', 'edited-heic'])(
'zooms a %s into the edited full-size rendition, never the original',
async (id) => {
// Immich's edited rendition is a JPEG; given one with GPS here, the
// scrubber still has to take it out.
const { file } = cameraJpeg(true);
mocked(immich.streamFullsize).mockResolvedValue(upstream(file, 'image/jpeg'));
const res = await zoom(`tok-${id}`);
expect(res.status).toBe(200);
expect(immich.streamFullsize).toHaveBeenCalledWith(id, true);
expect(immich.streamAsset).not.toHaveBeenCalled();
const body = new Uint8Array(await res.arrayBuffer());
expect(parseTiff(exifOf(body)!).gps).toBeNull();
expect(contains(body, LAT.value(true))).toBe(false);
},
);
it('is 404 when Immich has no edited rendition', async () => {
mocked(immich.streamFullsize).mockResolvedValue(null);
const res = await zoom('tok-edited');
expect(res.status).toBe(404);
expect(res.headers.get('cache-control')).toBe('no-store');
});
});

View File

@@ -0,0 +1,181 @@
/**
* The full-resolution image behind the lightbox zoom (#467).
*
* Shaped like the download route, and for the same reason: this hands out a
* file at full resolution, so it re-checks everything instead of treating the
* asset token as the capability the image proxy does.
*
* - the album must be on the allowlist,
* - the visitor must be able to reach it by a route on which zoom resolves
* on — album, then subpage, then `zoom` in settings.yaml — with every
* password gate on that route satisfied,
* - the asset must currently be published and belong to that album, and
* - it must have a zoomable source (lib/zoomSource.ts).
*
* What it sends:
*
* - JPEG and AVIF originals as they are stored, minus their location: GPS and
* sub-city place names are removed in place on the way through
* (lib/locationScrub.ts), so the length still holds.
* - For formats a browser cannot show (HEIC, RAW, TIFF, …), Immich's
* full-size JPEG rendition, through the same scrubber. When Immich has
* none — full-size previews switched off, or the asset not yet processed —
* the answer is 404 and the lightbox stays on the preview.
* - For a photo edited in Immich, whatever its format, the edited full-size
* rendition (#831), through the same scrubber, so the zoom shows the crop
* and rotation the preview shows.
*
* Whatever the source, only a file the scrubber recognised and cleaned goes
* out, and only as JPEG or AVIF. A format it passes through untouched (a PNG
* labelled as JPEG, a WebP rendition) is refused rather than sent with
* whatever metadata it carries.
*/
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { immich, ImmichUnavailableError } from '@/lib/immich';
import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
import { isAlbumZoomReachable, siteLockResponse } from '@/lib/auth';
import { isPublishedAsset } from '@/lib/publishedAssets';
import { scrubLocationStream } from '@/lib/locationScrub';
import { ZOOM_CONTENT_TYPES, zoomSourceFor } from '@/lib/zoomSource';
export const dynamic = 'force-dynamic';
/**
* Per client IP and minute. A zoom is one deliberate gesture per photo, and
* each answer is a full-resolution file off the Immich server — 7 MB for a
* 60 MP JPEG. Twenty a minute is a zoom every three seconds, sustained, which
* a visitor checking focus does not reach; a script pulling originals does.
* Below the download route's 30: a download is rarer still, but zooming is
* offered on whole albums that never opted into downloads.
*/
const ZOOM_RPM = 20;
const NO_STORE = { 'Cache-Control': 'no-store' };
/** One 404 for every refusal, so the response never says which check failed. */
const notFound = () =>
NextResponse.json({ error: 'Not found' }, { status: 404, headers: NO_STORE });
const unavailable = () =>
NextResponse.json(
{ error: 'Immich is currently unavailable' },
{ status: 503, headers: { ...NO_STORE, 'Retry-After': '30' } },
);
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ album: string; id: string }> },
) {
const ip = getClientIp(request);
const rl = checkRateLimit(`zoom:${ip}`, ZOOM_RPM);
if (!rl.success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { ...NO_STORE, 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
},
);
}
const locked = siteLockResponse(request);
if (locked) return locked;
const { album: albumToken, id: assetToken } = await params;
const albumId = decodeAssetId(albumToken);
const assetId = decodeAssetId(assetToken);
if (!albumId || !assetId) return notFound();
const config = getConfig();
if (!config.albums.includes(albumId)) return notFound();
// Zoom on, and a route to the album the visitor could have taken. A route
// handler is reached without passing through the page, so the page's gates
// are asked again here.
const cookieStore = await cookies();
const getCookie = (name: string) => cookieStore.get(name)?.value;
if (!isAlbumZoomReachable(albumId, getCookie)) return notFound();
// Same membership test as the image proxy: an album taken offline or an
// asset removed from it stops being served at once, not after the cache.
if (!(await isPublishedAsset(assetId))) return notFound();
let album;
try {
album = await immich.getAlbum(albumId);
} catch (error) {
if (error instanceof ImmichUnavailableError) return unavailable();
throw error;
}
if (!album) return notFound();
// The asset has to be in the album that authorised the zoom.
const asset = album.assets.find((candidate) => candidate.id === assetId);
if (!asset) return notFound();
const source = zoomSourceFor(asset);
if (!source) return notFound();
let result;
try {
// An edited photo (#831) is zoomed into Immich's edited full-size
// rendition, never its original, which is the unedited file. Redirects
// are not followed here either: should Immich send one, it would be to a
// smaller rendition, which must not pass for full resolution.
result =
source === 'original'
? await immich.streamAsset(assetId, 'original')
: await immich.streamFullsize(assetId, source === 'edited');
} catch (error) {
if (error instanceof ImmichUnavailableError) return unavailable();
throw error;
}
// For `fullsize` this is the common "Immich has no rendition" case.
if (!result) return notFound();
const contentType = result.contentType.toLowerCase().split(';')[0].trim();
if (!ZOOM_CONTENT_TYPES.has(contentType)) {
await (result.stream as ReadableStream).cancel().catch(() => {});
console.warn(`[Zoom] Refused ${assetId}: Immich sent ${contentType || 'no type'}.`);
return notFound();
}
let scrubbed;
try {
scrubbed = await scrubLocationStream(result.stream as ReadableStream<Uint8Array>);
} catch (error) {
console.error(`[Zoom] Reading ${source} ${assetId} failed:`, error);
return unavailable();
}
if (!scrubbed.ok) {
console.warn(
`[Zoom] Refused ${assetId}: its location metadata could not be removed (${scrubbed.reason}).`,
);
return notFound();
}
if (scrubbed.format === 'passthrough') {
// Labelled JPEG/AVIF, but not a file the scrubber knows how to clean.
await scrubbed.stream.cancel().catch(() => {});
console.warn(`[Zoom] Refused ${assetId}: not a JPEG or HEIF-family file.`);
return notFound();
}
const headers: Record<string, string> = {
'Content-Type': contentType,
// Shown in the page, never saved by a click.
'Content-Disposition': 'inline',
// Private: the answer depends on this visitor's cookies, so a shared cache
// (a CDN, a proxy) must not hand it to the next one. An hour in the
// visitor's own cache makes a second zoom into the same photo free.
'Cache-Control': 'private, max-age=3600',
'X-Content-Type-Options': 'nosniff',
};
// Scrubbing overwrites in place, so the upstream length still holds.
if (result.contentLength) headers['Content-Length'] = result.contentLength;
return new NextResponse(scrubbed.stream, { headers });
}