Files
immich-folio/app/api/install/route.ts
Ralksta 2f546f440d release: v0.11.0 (#459)
Ships `dev` as **v0.11.0**. `main` contains nothing that `dev` does not,
so this is a clean sync.

## Headline changes since v0.10.0

- **Journal & Journal Studio** — photo essays at `/journal`,
split-screen block editor with live preview, drafts, per-entry
passwords, cover images
- **First-run setup wizard at `/install`** — configure a fresh
deployment from the browser; credentials are verified against Immich
before anything is written, and the wizard is gated by a one-time token
- **About page editor and toggle** in the admin panel
- **Per-album photo order** independent of Immich, with a drag & drop
editor
- **Custom favicon upload**
- **Experimental portfolio features** — justified grid, `cover` hero,
unlisted subpages, per-album grid overrides, cover focal points,
external nav links
- **Security** — asset tokens length-capped before decoding (#423),
journal author markdown escaped rather than filtered, journal file paths
contained, admin session key derived with scrypt (#432), Next.js 16.3.0
for CVE-2025-13465
- **Fixed** — client proofing honours its own configuration again
(#454); journal photo rendering (#432)

Full detail in [CHANGELOG.md](CHANGELOG.md#0110--2026-08-15).

## Verified

`npx tsc --noEmit` clean · `npx vitest run` 435 tests pass · `npm run
build` succeeds · lint 0 errors · `prettier --check` clean · local
`docker build` of the release tree.

## After merge

Tag `v0.11.0` on `main` and publish the release — that triggers
`docker-publish.yml`, which pushes the image and moves `latest`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 09:09:18 +02:00

118 lines
4.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';
import { completeInstall, isInstalled, normalizeApiBase, validateSetupToken } from '@/lib/install';
import { invalidateConfigCache } from '@/lib/config';
import { DEFAULT_PRESET } from '@/lib/config/theme';
import { immich } from '@/lib/immich';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
/** Install submissions per minute per IP — only live before install. */
const INSTALL_RPM = 10;
const THEME_PRESETS = [
'studio-modern',
'studio',
'minimal',
'editorial',
'classic',
'noir',
'monograph',
];
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** POST: run the install wizard's final step — verify, then write config. */
export async function POST(request: NextRequest) {
if (isInstalled()) {
return NextResponse.json({ error: 'Setup is already complete' }, { status: 403 });
}
const token = request.nextUrl.searchParams.get('token') ?? request.headers.get('x-setup-token');
if (!validateSetupToken(token)) {
return NextResponse.json({ error: 'Invalid or missing setup token' }, { status: 403 });
}
const ip = getClientIp(request);
const rl = checkRateLimit(`install:${ip}`, INSTALL_RPM);
if (!rl.success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
},
);
}
const body = await request.json().catch(() => null);
if (!body) {
return NextResponse.json({ error: 'Missing request body' }, { status: 400 });
}
const apiUrl = typeof body.apiUrl === 'string' ? body.apiUrl.trim() : '';
const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
if (!apiUrl || !apiKey) {
return NextResponse.json({ error: 'Immich URL and API key are required' }, { status: 400 });
}
const apiBase = normalizeApiBase(apiUrl);
if (!apiBase) {
return NextResponse.json({ error: 'Invalid Immich URL' }, { status: 400 });
}
const theme = THEME_PRESETS.includes(body.theme) ? body.theme : DEFAULT_PRESET;
// Album selection is optional: an empty gallery is a valid install.
const rawAlbums: unknown[] = Array.isArray(body.albums) ? (body.albums as unknown[]) : [];
const albums: string[] = rawAlbums
.filter((id): id is string => typeof id === 'string' && UUID_REGEX.test(id.trim()))
.map((id) => id.trim());
let adminPassword = '';
if (typeof body.adminPassword === 'string' && body.adminPassword.length > 0) {
adminPassword = body.adminPassword;
if (adminPassword.length > 1024) {
return NextResponse.json({ error: 'Admin password is too long' }, { status: 400 });
}
}
// Verify the credentials against Immich before writing anything, so a typo
// does not produce an "installed" app that cannot load a single photo.
try {
const res = await fetch(`${apiBase}/server/ping`, {
headers: { 'x-api-key': apiKey, Accept: 'application/json' },
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) {
return NextResponse.json(
{ error: `Immich rejected the connection (HTTP ${res.status})` },
{ status: 502 },
);
}
} catch {
return NextResponse.json({ error: 'Could not reach Immich at this URL' }, { status: 502 });
}
try {
await completeInstall({
apiUrl,
apiKey,
siteTitle: typeof body.siteTitle === 'string' ? body.siteTitle : undefined,
siteSubtitle: typeof body.siteSubtitle === 'string' ? body.siteSubtitle : undefined,
theme,
albums,
adminPassword,
});
// The wizard wrote new YAML; the running process must not keep serving
// setup mode. The install.json mtime cache is dropped inside completeInstall.
invalidateConfigCache();
immich.invalidateAll();
revalidatePath('/', 'layout');
return NextResponse.json({ success: true });
} catch (err) {
console.error('[Install] Failed to write configuration files:', err);
return NextResponse.json({ error: 'Failed to write configuration files' }, { status: 500 });
}
}