release: v0.19.0
Release v0.19.0. See the `## [0.19.0] — 2026-09-29` section of [CHANGELOG.md](https://github.com/ralksta/immich-folio/blob/dev/CHANGELOG.md) for the full list. Highlights: client proofing links (#683), custom content pages (#738), asset picker search (#740), concurrent-edit detection (#742), env-locked settings (#739), an accessibility baseline (#741), three security fixes with advisories (#737, #755, #759), and a pre-release quality pass (#780–#797). --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: ralksta <ralksta@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Ralf <rohlenbo79@gmail.com> Co-authored-by: Paul Thies <110185070+ImScheinox@users.noreply.github.com> Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com> Co-authored-by: Lance Martin <lancetaylor95@gmail.com>
This commit is contained in:
152
app/api/webhook/__tests__/route.test.ts
Normal file
152
app/api/webhook/__tests__/route.test.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { createHmac } from 'crypto';
|
||||
|
||||
/**
|
||||
* The webhook is reachable by anyone, and the body has to be read before its
|
||||
* HMAC can be checked. The read is therefore capped: a declared length over
|
||||
* the cap is refused without touching the stream, and a body that turns out
|
||||
* longer than declared (or declares nothing, as a chunked one does) is cut off
|
||||
* at the cap. The signature must be exactly the hex digest of the raw bytes.
|
||||
*/
|
||||
|
||||
const SECRET = 'test-webhook-secret';
|
||||
|
||||
const env = vi.hoisted(() => ({ WEBHOOK_SECRET: '' as string | undefined }));
|
||||
vi.mock('@/lib/env', () => ({ env }));
|
||||
vi.mock('@/lib/immich', () => ({
|
||||
immich: { invalidateAlbum: vi.fn(), invalidateAll: vi.fn() },
|
||||
}));
|
||||
vi.mock('@/lib/rate-limit', () => ({
|
||||
checkRateLimit: vi.fn(() => ({ success: true, resetAt: 0 })),
|
||||
getClientIp: vi.fn(() => '127.0.0.1'),
|
||||
}));
|
||||
|
||||
import { POST } from '../route';
|
||||
import { immich } from '@/lib/immich';
|
||||
|
||||
const URL = 'http://localhost/api/webhook';
|
||||
const CAP = 64 * 1024;
|
||||
|
||||
function sign(body: string | Uint8Array): string {
|
||||
return createHmac('sha256', SECRET).update(body).digest('hex');
|
||||
}
|
||||
|
||||
function post(body: string, headers: Record<string, string> = {}): NextRequest {
|
||||
return new NextRequest(URL, {
|
||||
method: 'POST',
|
||||
body,
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A request whose body is a lazily produced stream of `chunks` chunks of
|
||||
* `size` bytes each. `pulls()` reports how many chunks the route asked for.
|
||||
*/
|
||||
function streamed(chunks: number, size: number, headers: Record<string, string> = {}) {
|
||||
let pulled = 0;
|
||||
const chunk = new Uint8Array(size).fill(0x20); // spaces: valid JSON whitespace
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (pulled >= chunks) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
pulled++;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
const request = new NextRequest(URL, {
|
||||
method: 'POST',
|
||||
body,
|
||||
headers,
|
||||
duplex: 'half', // undici requires it for a stream body
|
||||
});
|
||||
return { request, pulls: () => pulled };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
env.WEBHOOK_SECRET = SECRET;
|
||||
});
|
||||
|
||||
describe('POST /api/webhook', () => {
|
||||
it('answers 501 when WEBHOOK_SECRET is unset, before looking at the size', async () => {
|
||||
env.WEBHOOK_SECRET = undefined;
|
||||
const { request } = streamed(1, 16, { 'content-length': String(CAP * 10) });
|
||||
const res = await POST(request);
|
||||
expect(res.status).toBe(501);
|
||||
expect(request.bodyUsed).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses an oversized Content-Length with 413 without reading the body', async () => {
|
||||
const { request } = streamed(1, 16, {
|
||||
'content-length': String(CAP + 1),
|
||||
'x-immich-signature': 'a'.repeat(64),
|
||||
});
|
||||
const res = await POST(request);
|
||||
expect(res.status).toBe(413);
|
||||
expect(request.bodyUsed).toBe(false);
|
||||
});
|
||||
|
||||
it('cuts off a chunked body over the cap, even with a valid signature', async () => {
|
||||
// 100 chunks of 1 KiB = 100 KiB; the whole body is signed correctly, so
|
||||
// only the size cap can turn it away.
|
||||
const size = 1024;
|
||||
const chunks = 100;
|
||||
const full = ' '.repeat(size * chunks);
|
||||
const { request, pulls } = streamed(chunks, size, { 'x-immich-signature': sign(full) });
|
||||
expect(request.headers.get('content-length')).toBeNull();
|
||||
|
||||
const res = await POST(request);
|
||||
expect(res.status).toBe(413);
|
||||
expect(pulls()).toBeLessThan(chunks);
|
||||
expect(immich.invalidateAll).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('accepts a correctly signed payload under the cap', async () => {
|
||||
const body = JSON.stringify({ event: 'album.updated', albumId: 'album-1' });
|
||||
const res = await POST(post(body, { 'x-immich-signature': sign(body) }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true, invalidated: 'album-1' });
|
||||
expect(immich.invalidateAlbum).toHaveBeenCalledWith('album-1');
|
||||
});
|
||||
|
||||
it('verifies the signature over the raw bytes, byte-order mark included', async () => {
|
||||
const json = JSON.stringify({ event: 'album.updated', albumId: 'album-1' });
|
||||
const raw = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(json)]);
|
||||
const res = await POST(
|
||||
new NextRequest(URL, {
|
||||
method: 'POST',
|
||||
body: raw,
|
||||
headers: { 'x-immich-signature': sign(raw) },
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('answers 401 for a wrong signature', async () => {
|
||||
const body = JSON.stringify({ event: 'album.updated', albumId: 'album-1' });
|
||||
const res = await POST(post(body, { 'x-immich-signature': sign('something else') }));
|
||||
expect(res.status).toBe(401);
|
||||
expect(immich.invalidateAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers 401 for a missing signature', async () => {
|
||||
const res = await POST(post('{"event":"x"}'));
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['trailing non-hex characters', (sig: string) => `${sig}zz`],
|
||||
['a trailing odd nibble', (sig: string) => `${sig}0`],
|
||||
['an over-long digest', (sig: string) => sig.repeat(4)],
|
||||
['non-hex characters', () => 'z'.repeat(64)],
|
||||
])('answers 401 for a signature with %s', async (_label, mangle) => {
|
||||
const body = JSON.stringify({ event: 'album.updated', albumId: 'album-1' });
|
||||
const res = await POST(post(body, { 'x-immich-signature': mangle(sign(body)) }));
|
||||
expect(res.status).toBe(401);
|
||||
expect(immich.invalidateAlbum).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,8 @@
|
||||
*
|
||||
* HMAC-SHA256(WEBHOOK_SECRET, raw request body)
|
||||
*
|
||||
* If WEBHOOK_SECRET is not set, the endpoint returns 501.
|
||||
* If WEBHOOK_SECRET is not set, the endpoint returns 501. Bodies over
|
||||
* MAX_BODY_BYTES are refused with 413 before the signature is checked.
|
||||
*
|
||||
* Supported Immich event types:
|
||||
* - album.updated → invalidates the specific album
|
||||
@@ -23,10 +24,23 @@ import { createHmac, timingSafeEqual } from 'crypto';
|
||||
import { immich } from '@/lib/immich';
|
||||
import { env } from '@/lib/env';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
import { readBytesCapped } from '@/lib/requestBody';
|
||||
|
||||
// Tight rate limit — webhooks should come from one trusted source only
|
||||
const WEBHOOK_RPM = 60;
|
||||
|
||||
/**
|
||||
* Largest body the route reads before the signature is checked. The payload
|
||||
* is a small JSON object (`{ "event": "album.updated", "albumId": "<uuid>" }`,
|
||||
* well under 1 KiB), so 64 KiB leaves ample headroom for extra fields while
|
||||
* keeping an unauthenticated sender from making the server buffer and hash
|
||||
* an arbitrarily large body.
|
||||
*/
|
||||
const MAX_BODY_BYTES = 64 * 1024;
|
||||
|
||||
/** An HMAC-SHA256 hex digest: exactly 64 hex characters. */
|
||||
const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/i;
|
||||
|
||||
/** Album-scoped Immich webhook events. */
|
||||
const ALBUM_EVENTS = new Set(['album.updated', 'album.assetAdded', 'album.assetRemoved']);
|
||||
|
||||
@@ -46,13 +60,24 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
|
||||
}
|
||||
|
||||
// ── Body size ──────────────────────────────────────
|
||||
// The declared length is refused before a byte is read; the capped reader
|
||||
// covers a missing or understated Content-Length and chunked bodies.
|
||||
const declared = Number(request.headers.get('content-length') ?? '');
|
||||
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
|
||||
return NextResponse.json({ error: 'Payload too large' }, { status: 413 });
|
||||
}
|
||||
|
||||
// ── Read body (needed for HMAC verification) ───────
|
||||
let rawBody: string;
|
||||
let rawBody: Buffer | null;
|
||||
try {
|
||||
rawBody = await request.text();
|
||||
rawBody = await readBytesCapped(request, MAX_BODY_BYTES);
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Failed to read request body' }, { status: 400 });
|
||||
}
|
||||
if (rawBody === null) {
|
||||
return NextResponse.json({ error: 'Payload too large' }, { status: 413 });
|
||||
}
|
||||
|
||||
// ── Signature verification ─────────────────────────
|
||||
const signature = request.headers.get('x-immich-signature');
|
||||
@@ -63,13 +88,11 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const expected = createHmac('sha256', env.WEBHOOK_SECRET).update(rawBody).digest('hex');
|
||||
|
||||
let signatureValid = false;
|
||||
try {
|
||||
signatureValid = timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'));
|
||||
} catch {
|
||||
// Buffer lengths differ → invalid hex or wrong length
|
||||
signatureValid = false;
|
||||
}
|
||||
// Anything but a 64-character hex digest is refused before decoding, so a
|
||||
// malformed or over-long header gets the same answer as a wrong one.
|
||||
const signatureValid =
|
||||
SIGNATURE_PATTERN.test(signature) &&
|
||||
timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'));
|
||||
|
||||
if (!signatureValid) {
|
||||
console.warn(`[Webhook] ⚠️ Invalid signature from ${ip}`);
|
||||
@@ -79,7 +102,7 @@ export async function POST(request: NextRequest) {
|
||||
// ── Parse payload ──────────────────────────────────
|
||||
let payload: { event?: string; albumId?: string } = {};
|
||||
try {
|
||||
payload = JSON.parse(rawBody);
|
||||
payload = JSON.parse(new TextDecoder().decode(rawBody));
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user