release: v0.15.0 (#585)

Eighteen changes since v0.14.0. See CHANGELOG.md for the full list and the upgrade notes (bump IMAGE_CACHE_VERSION).
This commit is contained in:
Ralksta
2026-09-19 22:24:10 +02:00
committed by GitHub
parent e99d3f2f1b
commit c3f92ca4ec
74 changed files with 4791 additions and 2146 deletions

View File

@@ -82,6 +82,14 @@ const ROUTES: {
method: 'GET',
args: () => [new NextRequest('http://localhost/api/admin/doctor')],
},
{
// Lists album titles and raw asset UUIDs.
name: 'GET /api/admin/alt-text',
path: 'alt-text',
load: () => import('../alt-text/route'),
method: 'GET',
args: () => [],
},
{
name: 'GET /api/admin/assets',
path: 'assets',

View File

@@ -0,0 +1,83 @@
import { NextResponse } from 'next/server';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
import { getConfig } from '@/lib/config';
import { immich } from '@/lib/immich';
import {
albumPaths,
buildAltTextReport,
pickImmichWebUrl,
type AltTextAlbumInput,
} from '@/lib/admin/alt-text';
/**
* Immich's *External domain* setting, or null when unset or unreadable. A
* failure here must not cost the report — the links just fall back.
*/
async function immichExternalDomain(apiUrl: string, apiKey: string, timeoutMs: number) {
try {
const res = await fetch(`${apiUrl}/server/config`, {
headers: { 'x-api-key': apiKey, Accept: 'application/json' },
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) return null;
const body = (await res.json()) as { externalDomain?: string };
return body.externalDomain ?? null;
} catch {
return null;
}
}
/**
* Alt-text coverage of every published album, for the diagnostics page.
*
* Goes through `immich.getAlbum()`, so it shares the album cache with the
* public site: a check right after browsing the gallery costs no Immich calls.
* An album that fails to load is counted, not fatal — the rest still report.
*/
export async function GET() {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const config = getConfig();
if (config.needsCredentials) {
return NextResponse.json({ error: 'Not configured' }, { status: 503 });
}
const paths = albumPaths(config.subpages);
const inputs: AltTextAlbumInput[] = [];
let unreadable = 0;
const [albums, externalDomain] = await Promise.all([
Promise.all(config.albums.map((id) => immich.getAlbum(id).catch(() => undefined))),
immichExternalDomain(config.immich.apiUrl, config.immich.apiKey, config.immichTimeoutMs),
]);
const immichLink = pickImmichWebUrl(externalDomain, config.immich.apiUrl);
albums.forEach((album, i) => {
if (!album) {
// null is "Immich says it does not exist" — the doctor's album-ids check
// already reports that. undefined is a failed request.
if (album === undefined) unreadable++;
return;
}
inputs.push({
id: album.id,
name: album.albumName,
path: paths.get(config.albums[i]) ?? '/',
assets: album.assets,
});
});
return NextResponse.json(
{
...buildAltTextReport(inputs, config.exif.caption),
unreadable,
immichUrl: immichLink.url,
immichUrlSource: immichLink.source,
},
{ headers: { 'Cache-Control': 'no-store' } },
);
}

View File

@@ -2,18 +2,24 @@ import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
import { listBackups, restoreBackup } from '@/lib/admin/yaml-service';
import { listJournalBackups, restoreJournalBackup } from '@/lib/admin/journal-service';
import { invalidateConfigCache } from '@/lib/config';
import { immich } from '@/lib/immich';
export type BackupTarget = 'gallery' | 'settings' | 'about' | 'journal';
export interface BackupItem {
filename: string;
target: 'gallery' | 'settings';
target: BackupTarget;
timestamp: string | null;
isPreRestore: boolean;
/** Journal backups only: the entry the backup belongs to. */
slug?: string;
/** Journal backups only: the snapshot taken when the entry was deleted. */
isDeleted?: boolean;
}
function parseBackupInfo(filename: string): BackupItem {
const target = filename.startsWith('gallery.yaml') ? 'gallery' : 'settings';
function parseBackupInfo(filename: string, target: BackupTarget): BackupItem {
const isPreRestore = filename.includes('pre-restore');
// Extract timestamp from filename like filename.2026-05-31T17-30-00-000Z.bak
@@ -37,7 +43,7 @@ function parseBackupInfo(filename: string): BackupItem {
};
}
/** GET: List all available backups for gallery and settings. */
/** GET: List all available backups, grouped by the file they restore. */
export async function GET() {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
@@ -47,16 +53,26 @@ export async function GET() {
}
try {
const galleryRaw = await listBackups('gallery.yaml');
const settingsRaw = await listBackups('settings.yaml');
const gallery = galleryRaw.map(parseBackupInfo);
const settings = settingsRaw.map(parseBackupInfo);
const gallery = (await listBackups('gallery.yaml')).map((f) => parseBackupInfo(f, 'gallery'));
const settings = (await listBackups('settings.yaml')).map((f) =>
parseBackupInfo(f, 'settings'),
);
const about = (await listBackups('about.md')).map((f) => parseBackupInfo(f, 'about'));
// Newest first across all entries, so a just-deleted entry sits on top.
const journal = (await listJournalBackups())
.map((b) => ({
...parseBackupInfo(b.filename, 'journal'),
slug: b.slug,
isDeleted: b.kind === 'deleted',
}))
.sort((a, b) => (b.timestamp ?? '').localeCompare(a.timestamp ?? ''));
return NextResponse.json({
backups: {
gallery,
settings,
about,
journal,
},
});
} catch (err) {
@@ -76,7 +92,7 @@ export async function POST(req: Request) {
try {
const body = await req.json();
const { backupFilename } = body || {};
const { backupFilename, target } = body || {};
if (!backupFilename || typeof backupFilename !== 'string') {
return NextResponse.json({ error: 'backupFilename is required' }, { status: 400 });
@@ -95,7 +111,13 @@ export async function POST(req: Request) {
return NextResponse.json({ error: 'Invalid backup file extension' }, { status: 400 });
}
await restoreBackup(backupFilename);
// Journal backups live in their own directory, and `<slug>.md.<ts>.bak`
// cannot be told apart from an about.md backup by name alone.
if (target === 'journal') {
await restoreJournalBackup(backupFilename);
} else {
await restoreBackup(backupFilename);
}
// Invalidate caches & revalidate pages
invalidateConfigCache();

View File

@@ -14,6 +14,22 @@ import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
import { siteLockResponse } from '@/lib/auth';
import { blankRanges, findMetadataRanges } from '@/lib/metadataStrip';
/**
* Bumping this changes every original's ETag, so a revalidating cache fetches
* the stripped bytes instead of replaying a pre-fix copy. Browsers hold these
* URLs as `immutable` and will not revalidate at all, so a real rollout also
* needs IMAGE_CACHE_VERSION bumped — that changes the URL itself.
*/
const STRIP_VERSION = 's1';
/**
* Originals are buffered whole so their metadata can be blanked before a single
* byte reaches the client. Anything larger is not worth holding in memory; those
* fall back to the preview rendition, which Immich generates without EXIF.
*/
const MAX_STRIP_BYTES = 64 * 1024 * 1024;
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
// ── Rate limiting ──────────────────────────────────
@@ -65,7 +81,7 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
// `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}` : ''}"`;
const etag = `W/"${token}-${size}-${STRIP_VERSION}${cacheVersion ? `-${cacheVersion}` : ''}"`;
if (request.headers.get('if-none-match') === etag) {
return new NextResponse(null, {
status: 304,
@@ -113,6 +129,57 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
contentType = 'application/octet-stream';
}
// ── Metadaten aus Originalen entfernen ─────────────
// Das Asset-Token autorisiert das Bild, nicht die Groesse: ein aus dem
// oeffentlichen HTML gelesenes Thumbnail-Token plus ?size=original lieferte
// bis hierher die unveraenderte Datei — mitsamt GPS. app/api/exif haelt
// Koordinaten bewusst zurueck, und /api/map quantisiert sie; dieser Pfad ging
// an beidem vorbei. Nur die Metadaten-Bytes werden genullt, die Bilddaten
// bleiben bitgenau erhalten — deshalb kostet das keine Qualitaet.
let body: BodyInit = result.stream;
// Gesetzt, sobald wir gestrippte Bytes ausliefern — der Wert ist dann die
// maßgebliche Content-Length.
let strippedLength: number | null = null;
if (size === 'original') {
const declaredLength = result.contentLength ? parseInt(result.contentLength, 10) : NaN;
const zuGross = Number.isFinite(declaredLength) && declaredLength > MAX_STRIP_BYTES;
const raw = zuGross ? null : new Uint8Array(await new Response(result.stream).arrayBuffer());
const ranges =
raw && raw.length <= MAX_STRIP_BYTES ? findMetadataRanges(raw, contentType) : null;
if (raw && ranges) {
const blanked = blankRanges(raw, ranges);
strippedLength = blanked.byteLength;
// ArrayBuffer statt Uint8Array: nur der ist ein gueltiger BodyInit. Die
// Zusicherung ist sicher — die Bytes stammen aus Response.arrayBuffer(),
// also nie aus einem SharedArrayBuffer, den ArrayBufferLike mit einschliesst.
body = blanked.buffer.slice(
blanked.byteOffset,
blanked.byteOffset + blanked.byteLength,
) as ArrayBuffer;
} else {
// Unbekanntes Format, kaputter Container oder zu gross: lieber die
// Vorschau ausliefern als ein Original, dessen Metadaten wir nicht
// sicher finden. Stillschweigend durchreichen war genau der Fehler.
console.warn(
`[Image API] Original von ${assetId} (${contentType}) nicht strippbar — liefere Preview.`,
);
const preview = await immich.streamAsset(assetId, 'preview');
if (!preview) {
return NextResponse.json(
{ error: 'Asset not found' },
{ status: 404, headers: { 'Cache-Control': 'no-store' } },
);
}
body = preview.stream;
contentType = preview.contentType.toLowerCase().startsWith('image/')
? preview.contentType
: 'image/jpeg';
result = { ...preview, contentLength: preview.contentLength };
}
}
const headers: Record<string, string> = {
'Content-Type': contentType,
// Images are immutable once uploaded to Immich — cache aggressively
@@ -121,9 +188,13 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
'X-RateLimit-Remaining': String(remaining),
};
if (result.contentLength) {
// Das Nullen ist laengentreu, der Wert bleibt also gueltig; beim
// Preview-Fallback stammt er vom Preview-Abruf.
if (strippedLength !== null) {
headers['Content-Length'] = String(strippedLength);
} else if (result.contentLength) {
headers['Content-Length'] = result.contentLength;
}
return new NextResponse(result.stream, { headers });
return new NextResponse(body, { headers });
}