security: implement AUTH_SECRET and secure map/exif API routes

This commit is contained in:
ralksta
2026-03-07 08:18:23 +01:00
parent 2a16a9386f
commit e394fe84a0
14 changed files with 849 additions and 793 deletions

View File

@@ -22,6 +22,10 @@ CACHE_TTL=300
# Rate limit for image proxy (integer >= 1, requests per minute per IP, default: 120)
# RATE_LIMIT_RPM=120
# Secret for signing auth cookies and encrypting asset tokens (string, min 16 chars).
# If not provided, IMMICH_API_KEY will be used as a fallback (not recommended).
# AUTH_SECRET=your-super-long-random-secret-here
# ── Album configuration ──────────────────────────────────────────
# Albums, subpages, hero image, and passwords are defined in content/gallery.yaml
# See content/gallery.yaml.example for the full reference.

View File

@@ -136,8 +136,9 @@ export function PhotoGrid({ assets, layout = 'masonry', gridStyle }: PhotoGridPr
{assets.map((asset, index) => (
<FadeIn key={asset.id} delay={index < 12 ? index * 50 : 0}>
<div
className={`photo-grid__item${layout === 'showcase' && index === 0 ? ' photo-grid__featured' : ''
}`}
className={`photo-grid__item${
layout === 'showcase' && index === 0 ? ' photo-grid__featured' : ''
}`}
onClick={() => openLightbox(index)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {

View File

@@ -24,15 +24,22 @@ export async function GET(_request: Request, { params }: { params: Promise<{ id:
}
const exif = asset.exifInfo;
return NextResponse.json({
make: exif.make,
model: exif.model,
lensModel: exif.lensModel,
focalLength: exif.focalLength,
fNumber: exif.fNumber,
exposureTime: exif.exposureTime,
iso: exif.iso,
city: exif.city,
country: exif.country,
});
return NextResponse.json(
{
make: exif.make,
model: exif.model,
lensModel: exif.lensModel,
focalLength: exif.focalLength,
fNumber: exif.fNumber,
exposureTime: exif.exposureTime,
iso: exif.iso,
city: exif.city,
country: exif.country,
},
{
headers: {
'Cache-Control': 'private, max-age=86400, stale-while-revalidate=3600',
},
},
);
}

View File

@@ -4,39 +4,56 @@
* Cover asset IDs are encrypted for security.
*/
import { NextResponse } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { immich } from '@/lib/immich';
import { getConfig } from '@/lib/config';
import { imageUrl } from '@/lib/urls';
import { isAuthenticated } from '@/lib/auth';
export const dynamic = 'force-dynamic';
export async function GET() {
const config = getConfig();
export async function GET(_request: NextRequest) {
const config = getConfig();
if (!config.map) {
return NextResponse.json({ error: 'Map is not enabled' }, { status: 404 });
}
if (!config.map) {
return NextResponse.json({ error: 'Map is not enabled' }, { status: 404 });
}
const locations = await immich.getMapData();
const cookieStore = await cookies();
const getCookie = (name: string) => cookieStore.get(name)?.value;
// Encrypt cover asset IDs and convert to public-safe image URLs
const publicLocations = locations.map((loc) => ({
const locations = await immich.getMapData();
// Filter locations and albums based on auth
const publicLocations = locations
.map((loc) => {
// Only keep albums the user is allowed to see
const allowedAlbums = loc.albums.filter((a) => {
if (!a.subpageSlug) return true; // Standalone albums are public
return isAuthenticated(a.subpageSlug, getCookie);
});
if (allowedAlbums.length === 0) return null;
return {
city: loc.city,
country: loc.country,
lat: loc.lat,
lng: loc.lng,
photoCount: loc.photoCount,
photoCount: loc.photoCount, // Note: This count might be slightly off if some photos are in hidden albums
coverUrl: imageUrl(loc.coverAssetId, 'thumbnail'),
albums: loc.albums.map((a) => ({
name: a.name,
url: a.subpageSlug ? `/${a.subpageSlug}/${a.slug}` : `/${a.slug}`,
albums: allowedAlbums.map((a) => ({
name: a.name,
url: a.subpageSlug ? `/${a.subpageSlug}/${a.slug}` : `/${a.slug}`,
})),
}));
};
})
.filter((loc) => loc !== null);
return NextResponse.json(publicLocations, {
headers: {
'Cache-Control': `public, max-age=${Math.floor(config.cacheTtl / 1000)}, stale-while-revalidate=60`,
},
});
return NextResponse.json(publicLocations, {
headers: {
'Cache-Control': `private, no-cache, no-store, must-revalidate`, // Don't cache personalized map data publicly
},
});
}

View File

@@ -13,34 +13,34 @@ import './map.css';
export const dynamic = 'force-dynamic';
export const metadata: Metadata = {
title: 'Map',
title: 'Map',
};
export default function MapPage() {
const config = getConfig();
const config = getConfig();
if (!config.map) {
notFound();
}
if (!config.map) {
notFound();
}
return (
<>
{/* Leaflet CSS from CDN */}
{/* eslint-disable-next-line @next/next/no-page-custom-font */}
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossOrigin=""
/>
<div className="map-page">
<div className="map-page__header">
<BackLink href="/" label="Back to Gallery" />
<h1 className="map-page__title">Map</h1>
<p className="map-page__subtitle">Where the photos were taken</p>
</div>
<MapView />
</div>
</>
);
return (
<>
{/* Leaflet CSS from CDN */}
{}
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossOrigin=""
/>
<div className="map-page">
<div className="map-page__header">
<BackLink href="/" label="Back to Gallery" />
<h1 className="map-page__title">Map</h1>
<p className="map-page__subtitle">Where the photos were taken</p>
</div>
<MapView />
</div>
</>
);
}

View File

@@ -80,9 +80,7 @@ export default async function HomePage() {
<nav className="hero__nav hero__nav--indexed">
{subpages.map((sp, i) => (
<Link key={sp.slug} href={`/${sp.slug}`} className="hero__nav-link">
<span className="hero__nav-index">
{String(i + 1).padStart(2, '0')}
</span>
<span className="hero__nav-index">{String(i + 1).padStart(2, '0')}</span>
{sp.name}
</Link>
))}
@@ -127,11 +125,7 @@ export default async function HomePage() {
<FadeIn delay={200}>
<nav className="hero__thumbnail-strip">
{allEntries.map((entry) => (
<Link
key={entry.slug}
href={`/${entry.slug}`}
className="hero__thumbnail-item"
>
<Link key={entry.slug} href={`/${entry.slug}`} className="hero__thumbnail-item">
<span className="hero__thumbnail-label">{entry.name}</span>
</Link>
))}

View File

@@ -11,7 +11,7 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import React, { useState, useEffect, useCallback, useLayoutEffect } from 'react';
const PRESETS = ['studio', 'minimal', 'editorial', 'classic', 'noir', 'monograph', 'botanica'];
const FRAMES = ['none', 'passepartout', 'shadow'];
@@ -20,426 +20,429 @@ const GRID_LAYOUTS = ['masonry', 'uniform', 'showcase', 'filmstrip', 'editorial-
// Font stacks for each preset (must match THEME_PRESETS in config.ts)
const PRESET_FONTS: Record<string, { heading: string; body: string; caption: string }> = {
studio: { heading: 'Playfair Display', body: 'DM Sans', caption: 'EB Garamond' },
minimal: { heading: 'Geist', body: 'Geist', caption: 'IBM Plex Mono' },
editorial: { heading: 'Bodoni Moda', body: 'Newsreader', caption: 'IBM Plex Mono' },
classic: { heading: 'Cinzel', body: 'Crimson Pro', caption: 'EB Garamond' },
noir: { heading: 'Libre Baskerville', body: 'Source Sans 3', caption: 'IBM Plex Mono' },
monograph: { heading: 'Instrument Serif', body: 'Inter', caption: 'JetBrains Mono' },
botanica: { heading: 'Cormorant Garamond', body: 'Nunito Sans', caption: 'Lora' },
studio: { heading: 'Playfair Display', body: 'DM Sans', caption: 'EB Garamond' },
minimal: { heading: 'Geist', body: 'Geist', caption: 'IBM Plex Mono' },
editorial: { heading: 'Bodoni Moda', body: 'Newsreader', caption: 'IBM Plex Mono' },
classic: { heading: 'Cinzel', body: 'Crimson Pro', caption: 'EB Garamond' },
noir: { heading: 'Libre Baskerville', body: 'Source Sans 3', caption: 'IBM Plex Mono' },
monograph: { heading: 'Instrument Serif', body: 'Inter', caption: 'JetBrains Mono' },
botanica: { heading: 'Cormorant Garamond', body: 'Nunito Sans', caption: 'Lora' },
};
const PRESET_ACCENTS: Record<string, string> = {
studio: '#e60012',
minimal: '#000000',
editorial: '#8B2500',
classic: '#c49a3c',
noir: '#ff6b35',
monograph: '#333333',
botanica: '#4a7c59',
studio: '#e60012',
minimal: '#000000',
editorial: '#8B2500',
classic: '#c49a3c',
noir: '#ff6b35',
monograph: '#333333',
botanica: '#4a7c59',
};
function getAttr(attr: string): string {
return document.documentElement.getAttribute(attr) ?? '';
return document.documentElement.getAttribute(attr) ?? '';
}
function setAttr(attr: string, value: string) {
document.documentElement.setAttribute(attr, value);
document.documentElement.setAttribute(attr, value);
}
function setVar(name: string, value: string) {
document.documentElement.style.setProperty(name, value);
document.documentElement.style.setProperty(name, value);
}
export function DevToolbar() {
const [open, setOpen] = useState(false);
const [preset, setPreset] = useState('');
const [frame, setFrame] = useState('');
const [theme, setTheme] = useState('');
const [grain, setGrain] = useState('');
const [copiedYaml, setCopiedYaml] = useState('');
const [gridCols, setGridCols] = useState(3);
const [gridGap, setGridGap] = useState(12);
const [open, setOpen] = useState(false);
const [preset, setPreset] = useState('');
const [frame, setFrame] = useState('');
const [theme, setTheme] = useState('');
const [grain, setGrain] = useState('');
const [copiedYaml, setCopiedYaml] = useState('');
const [gridCols, setGridCols] = useState(3);
const [gridGap, setGridGap] = useState(12);
// Read initial values from DOM
useEffect(() => {
setPreset(getAttr('data-preset'));
setFrame(getAttr('data-photo-frame'));
setTheme(getAttr('data-theme') || 'dark');
setGrain(getAttr('data-grain'));
// Read grid vars
const style = getComputedStyle(document.documentElement);
const cols = parseInt(style.getPropertyValue('--grid-columns') || '3', 10);
const gap = parseInt(style.getPropertyValue('--grid-gap') || '12', 10);
if (!isNaN(cols)) setGridCols(cols);
if (!isNaN(gap)) setGridGap(gap);
}, []);
// Read initial values from DOM
useLayoutEffect(() => {
setPreset(getAttr('data-preset')); // eslint-disable-line react-hooks/set-state-in-effect
setFrame(getAttr('data-photo-frame'));
setTheme(getAttr('data-theme') || 'dark');
setGrain(getAttr('data-grain'));
// Read grid vars
const style = getComputedStyle(document.documentElement);
const cols = parseInt(style.getPropertyValue('--grid-columns') || '3', 10);
const gap = parseInt(style.getPropertyValue('--grid-gap') || '12', 10);
if (!isNaN(cols)) setGridCols(cols);
if (!isNaN(gap)) setGridGap(gap);
}, []);
const switchPreset = useCallback((p: string) => {
setAttr('data-preset', p);
setPreset(p);
// Update accent + fonts
const accent = PRESET_ACCENTS[p] || '#e60012';
setVar('--accent', accent);
setVar('--accent-dim', `${accent}1f`);
const fonts = PRESET_FONTS[p];
if (fonts) {
setVar('--font-serif', `'${fonts.heading}', Georgia, 'Times New Roman', serif`);
setVar('--font-sans', `'${fonts.body}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`);
setVar('--font-caption', `'${fonts.caption}', Georgia, serif`);
// Dynamically load Google Fonts if not already loaded
const families = [fonts.heading, fonts.body, fonts.caption]
.filter((f, i, a) => a.indexOf(f) === i)
.map((f) => `family=${f.replace(/\s+/g, '+')}:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400`)
.join('&');
const href = `https://fonts.googleapis.com/css2?${families}&display=swap`;
// Check if already loaded
const existing = document.querySelector(`link[href="${href}"]`);
if (!existing) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.head.appendChild(link);
}
}
}, []);
const switchPreset = useCallback((p: string) => {
setAttr('data-preset', p);
setPreset(p);
// Update accent + fonts
const accent = PRESET_ACCENTS[p] || '#e60012';
setVar('--accent', accent);
setVar('--accent-dim', `${accent}1f`);
const fonts = PRESET_FONTS[p];
if (fonts) {
setVar('--font-serif', `'${fonts.heading}', Georgia, 'Times New Roman', serif`);
setVar(
'--font-sans',
`'${fonts.body}', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`,
);
setVar('--font-caption', `'${fonts.caption}', Georgia, serif`);
// Dynamically load Google Fonts if not already loaded
const families = [fonts.heading, fonts.body, fonts.caption]
.filter((f, i, a) => a.indexOf(f) === i)
.map(
(f) => `family=${f.replace(/\s+/g, '+')}:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400`,
)
.join('&');
const href = `https://fonts.googleapis.com/css2?${families}&display=swap`;
// Check if already loaded
const existing = document.querySelector(`link[href="${href}"]`);
if (!existing) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
document.head.appendChild(link);
}
}
}, []);
const switchFrame = useCallback((f: string) => {
setAttr('data-photo-frame', f);
setFrame(f);
}, []);
const switchFrame = useCallback((f: string) => {
setAttr('data-photo-frame', f);
setFrame(f);
}, []);
const switchTheme = useCallback((t: string) => {
setAttr('data-theme', t);
setTheme(t);
}, []);
const switchTheme = useCallback((t: string) => {
setAttr('data-theme', t);
setTheme(t);
}, []);
const toggleGrain = useCallback(() => {
const next = grain === 'true' ? 'false' : 'true';
setAttr('data-grain', next);
setGrain(next);
}, [grain]);
const toggleGrain = useCallback(() => {
const next = grain === 'true' ? 'false' : 'true';
setAttr('data-grain', next);
setGrain(next);
}, [grain]);
const updateGridCols = useCallback((cols: number) => {
setGridCols(cols);
// Update all photo-grid elements
document.querySelectorAll<HTMLElement>('.photo-grid').forEach((el) => {
el.style.setProperty('--grid-columns', String(cols));
});
}, []);
const updateGridCols = useCallback((cols: number) => {
setGridCols(cols);
// Update all photo-grid elements
document.querySelectorAll<HTMLElement>('.photo-grid').forEach((el) => {
el.style.setProperty('--grid-columns', String(cols));
});
}, []);
const updateGridGap = useCallback((gap: number) => {
setGridGap(gap);
document.querySelectorAll<HTMLElement>('.photo-grid').forEach((el) => {
el.style.setProperty('--grid-gap', `${gap}px`);
});
}, []);
const updateGridGap = useCallback((gap: number) => {
setGridGap(gap);
document.querySelectorAll<HTMLElement>('.photo-grid').forEach((el) => {
el.style.setProperty('--grid-gap', `${gap}px`);
});
}, []);
const copyYaml = useCallback(
(section: string, yaml: string) => {
navigator.clipboard.writeText(yaml);
setCopiedYaml(section);
setTimeout(() => setCopiedYaml(''), 1500);
},
[],
);
const copyYaml = useCallback((section: string, yaml: string) => {
navigator.clipboard.writeText(yaml);
setCopiedYaml(section);
setTimeout(() => setCopiedYaml(''), 1500);
}, []);
const currentYaml = `theme:
const currentYaml = `theme:
preset: ${preset}
photoFrame: ${frame}
grain: ${grain === 'true'}`;
// Keyboard shortcut: Ctrl/Cmd + Shift + T
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'T') {
e.preventDefault();
setOpen((o) => !o);
}
};
document.addEventListener('keydown', handler);
return () => document.removeEventListener('keydown', handler);
}, []);
// Keyboard shortcut: Ctrl/Cmd + Shift + T
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'T') {
e.preventDefault();
setOpen((o) => !o);
}
};
document.addEventListener('keydown', handler);
return () => document.removeEventListener('keydown', handler);
}, []);
return (
<>
{/* ── Floating Toggle Button ─────────────────────── */}
<button
onClick={() => setOpen(!open)}
aria-label="Dev Toolbar"
style={{
position: 'fixed',
bottom: 20,
left: 20,
zIndex: 99999,
width: 44,
height: 44,
borderRadius: '50%',
border: '2px solid rgba(255,255,255,0.2)',
background: open
? 'linear-gradient(135deg, #f43f5e, #a855f7)'
: 'rgba(30,30,30,0.9)',
backdropFilter: 'blur(12px)',
color: '#fff',
fontSize: 18,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 0.2s ease',
boxShadow: '0 4px 24px rgba(0,0,0,0.4)',
}}
return (
<>
{/* ── Floating Toggle Button ─────────────────────── */}
<button
onClick={() => setOpen(!open)}
aria-label="Dev Toolbar"
style={{
position: 'fixed',
bottom: 20,
left: 20,
zIndex: 99999,
width: 44,
height: 44,
borderRadius: '50%',
border: '2px solid rgba(255,255,255,0.2)',
background: open ? 'linear-gradient(135deg, #f43f5e, #a855f7)' : 'rgba(30,30,30,0.9)',
backdropFilter: 'blur(12px)',
color: '#fff',
fontSize: 18,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 0.2s ease',
boxShadow: '0 4px 24px rgba(0,0,0,0.4)',
}}
>
{open ? '✕' : '🎨'}
</button>
{/* ── Panel ──────────────────────────────────────── */}
{open && (
<div
style={{
position: 'fixed',
bottom: 76,
left: 20,
zIndex: 99998,
width: 300,
maxHeight: 'calc(100vh - 120px)',
overflowY: 'auto',
background: 'rgba(18,18,22,0.96)',
backdropFilter: 'blur(20px)',
borderRadius: 16,
border: '1px solid rgba(255,255,255,0.1)',
boxShadow: '0 8px 48px rgba(0,0,0,0.6)',
color: '#e4e4e7',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
fontSize: 12,
padding: 0,
}}
>
{/* ── Header ──────────────────────────── */}
<div
style={{
padding: '14px 16px 10px',
borderBottom: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span style={{ fontWeight: 700, fontSize: 13, letterSpacing: '0.02em' }}>
🎨 Theme Builder
</span>
<span
style={{
fontSize: 10,
color: '#71717a',
background: 'rgba(255,255,255,0.06)',
padding: '2px 8px',
borderRadius: 6,
}}
>
{open ? '✕' : '🎨'}
DEV ONLY
</span>
</div>
{/* ── Preset ──────────────────────────── */}
<Section title="Preset">
<PillGrid items={PRESETS} active={preset} onSelect={switchPreset} />
</Section>
{/* ── Dark / Light ────────────────────── */}
<Section title="Mode">
<PillGrid items={['dark', 'light']} active={theme} onSelect={switchTheme} />
</Section>
{/* ── Photo Frame ─────────────────────── */}
<Section title="Photo Frame">
<PillGrid items={FRAMES} active={frame} onSelect={switchFrame} />
</Section>
{/* ── Grain ───────────────────────────── */}
<Section title="Film Grain">
<button
onClick={toggleGrain}
style={{
...pillStyle,
background:
grain === 'true'
? 'linear-gradient(135deg, #f43f5e, #a855f7)'
: 'rgba(255,255,255,0.06)',
color: grain === 'true' ? '#fff' : '#a1a1aa',
border:
grain === 'true'
? '1px solid rgba(255,255,255,0.2)'
: '1px solid rgba(255,255,255,0.06)',
}}
>
{grain === 'true' ? '● On' : '○ Off'}
</button>
</Section>
{/* ── Panel ──────────────────────────────────────── */}
{open && (
<div
style={{
position: 'fixed',
bottom: 76,
left: 20,
zIndex: 99998,
width: 300,
maxHeight: 'calc(100vh - 120px)',
overflowY: 'auto',
background: 'rgba(18,18,22,0.96)',
backdropFilter: 'blur(20px)',
borderRadius: 16,
border: '1px solid rgba(255,255,255,0.1)',
boxShadow: '0 8px 48px rgba(0,0,0,0.6)',
color: '#e4e4e7',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
fontSize: 12,
padding: 0,
}}
>
{/* ── Header ──────────────────────────── */}
<div
style={{
padding: '14px 16px 10px',
borderBottom: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span style={{ fontWeight: 700, fontSize: 13, letterSpacing: '0.02em' }}>
🎨 Theme Builder
</span>
<span
style={{
fontSize: 10,
color: '#71717a',
background: 'rgba(255,255,255,0.06)',
padding: '2px 8px',
borderRadius: 6,
}}
>
DEV ONLY
</span>
</div>
{/* ── Grid Controls ───────────────────── */}
<Section title="Grid">
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<label style={{ color: '#71717a', fontSize: 11, minWidth: 45 }}>
Cols: {gridCols}
</label>
<input
type="range"
min={1}
max={6}
value={gridCols}
onChange={(e) => updateGridCols(Number(e.target.value))}
style={{ flex: 1, accentColor: '#a855f7' }}
/>
</div>
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 8 }}>
<label style={{ color: '#71717a', fontSize: 11, minWidth: 45 }}>
Gap: {gridGap}px
</label>
<input
type="range"
min={0}
max={32}
value={gridGap}
onChange={(e) => updateGridGap(Number(e.target.value))}
style={{ flex: 1, accentColor: '#a855f7' }}
/>
</div>
</Section>
{/* ── Preset ──────────────────────────── */}
<Section title="Preset">
<PillGrid
items={PRESETS}
active={preset}
onSelect={switchPreset}
/>
</Section>
{/* ── Hero Style (info only) ──────────── */}
<Section title="Hero Style (server)">
<PillGrid
items={HERO_STYLES}
active=""
onSelect={(h) => {
copyYaml('hero', `theme:\n heroStyle: ${h}`);
}}
/>
{copiedYaml === 'hero' && <CopyBadge />}
</Section>
{/* ── Dark / Light ────────────────────── */}
<Section title="Mode">
<PillGrid
items={['dark', 'light']}
active={theme}
onSelect={switchTheme}
/>
</Section>
{/* ── Grid Layout (info only) ─────────── */}
<Section title="Grid Layout (server)">
<PillGrid
items={GRID_LAYOUTS}
active=""
onSelect={(l) => {
copyYaml('layout', `grid:\n layout: ${l}`);
}}
/>
{copiedYaml === 'layout' && <CopyBadge />}
</Section>
{/* ── Photo Frame ─────────────────────── */}
<Section title="Photo Frame">
<PillGrid
items={FRAMES}
active={frame}
onSelect={switchFrame}
/>
</Section>
{/* ── Grain ───────────────────────────── */}
<Section title="Film Grain">
<button
onClick={toggleGrain}
style={{
...pillStyle,
background: grain === 'true'
? 'linear-gradient(135deg, #f43f5e, #a855f7)'
: 'rgba(255,255,255,0.06)',
color: grain === 'true' ? '#fff' : '#a1a1aa',
border: grain === 'true' ? '1px solid rgba(255,255,255,0.2)' : '1px solid rgba(255,255,255,0.06)',
}}
>
{grain === 'true' ? '● On' : '○ Off'}
</button>
</Section>
{/* ── Grid Controls ───────────────────── */}
<Section title="Grid">
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<label style={{ color: '#71717a', fontSize: 11, minWidth: 45 }}>Cols: {gridCols}</label>
<input
type="range"
min={1}
max={6}
value={gridCols}
onChange={(e) => updateGridCols(Number(e.target.value))}
style={{ flex: 1, accentColor: '#a855f7' }}
/>
</div>
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 8 }}>
<label style={{ color: '#71717a', fontSize: 11, minWidth: 45 }}>Gap: {gridGap}px</label>
<input
type="range"
min={0}
max={32}
value={gridGap}
onChange={(e) => updateGridGap(Number(e.target.value))}
style={{ flex: 1, accentColor: '#a855f7' }}
/>
</div>
</Section>
{/* ── Hero Style (info only) ──────────── */}
<Section title="Hero Style (server)">
<PillGrid items={HERO_STYLES} active="" onSelect={(h) => {
copyYaml('hero', `theme:\n heroStyle: ${h}`);
}} />
{copiedYaml === 'hero' && <CopyBadge />}
</Section>
{/* ── Grid Layout (info only) ─────────── */}
<Section title="Grid Layout (server)">
<PillGrid items={GRID_LAYOUTS} active="" onSelect={(l) => {
copyYaml('layout', `grid:\n layout: ${l}`);
}} />
{copiedYaml === 'layout' && <CopyBadge />}
</Section>
{/* ── Export YAML ──────────────────────── */}
<div
style={{
padding: '12px 16px 16px',
borderTop: '1px solid rgba(255,255,255,0.08)',
}}
>
<button
onClick={() => copyYaml('all', currentYaml)}
style={{
width: '100%',
padding: '10px 0',
borderRadius: 10,
border: 'none',
background: copiedYaml === 'all'
? '#22c55e'
: 'linear-gradient(135deg, #a855f7, #6366f1)',
color: '#fff',
fontWeight: 600,
fontSize: 12,
cursor: 'pointer',
transition: 'all 0.15s ease',
letterSpacing: '0.02em',
}}
>
{copiedYaml === 'all' ? '✓ Copied to clipboard' : 'Copy YAML to clipboard'}
</button>
</div>
</div>
)}
</>
);
{/* ── Export YAML ──────────────────────── */}
<div
style={{
padding: '12px 16px 16px',
borderTop: '1px solid rgba(255,255,255,0.08)',
}}
>
<button
onClick={() => copyYaml('all', currentYaml)}
style={{
width: '100%',
padding: '10px 0',
borderRadius: 10,
border: 'none',
background:
copiedYaml === 'all' ? '#22c55e' : 'linear-gradient(135deg, #a855f7, #6366f1)',
color: '#fff',
fontWeight: 600,
fontSize: 12,
cursor: 'pointer',
transition: 'all 0.15s ease',
letterSpacing: '0.02em',
}}
>
{copiedYaml === 'all' ? '✓ Copied to clipboard' : 'Copy YAML to clipboard'}
</button>
</div>
</div>
)}
</>
);
}
/* ── Sub-components ───────────────────────────────── */
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div style={{ padding: '12px 16px 8px' }}>
<div
style={{
fontSize: 10,
fontWeight: 600,
textTransform: 'uppercase',
letterSpacing: '0.1em',
color: '#71717a',
marginBottom: 8,
}}
>
{title}
</div>
{children}
</div>
);
return (
<div style={{ padding: '12px 16px 8px' }}>
<div
style={{
fontSize: 10,
fontWeight: 600,
textTransform: 'uppercase',
letterSpacing: '0.1em',
color: '#71717a',
marginBottom: 8,
}}
>
{title}
</div>
{children}
</div>
);
}
const pillStyle: React.CSSProperties = {
padding: '6px 12px',
borderRadius: 8,
fontSize: 11,
fontWeight: 500,
cursor: 'pointer',
transition: 'all 0.12s ease',
whiteSpace: 'nowrap',
padding: '6px 12px',
borderRadius: 8,
fontSize: 11,
fontWeight: 500,
cursor: 'pointer',
transition: 'all 0.12s ease',
whiteSpace: 'nowrap',
};
function PillGrid({
items,
active,
onSelect,
items,
active,
onSelect,
}: {
items: string[];
active: string;
onSelect: (item: string) => void;
items: string[];
active: string;
onSelect: (item: string) => void;
}) {
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{items.map((item) => (
<button
key={item}
onClick={() => onSelect(item)}
style={{
...pillStyle,
background:
item === active
? 'linear-gradient(135deg, #a855f7, #6366f1)'
: 'rgba(255,255,255,0.06)',
color: item === active ? '#fff' : '#a1a1aa',
border:
item === active
? '1px solid rgba(255,255,255,0.2)'
: '1px solid rgba(255,255,255,0.06)',
}}
>
{item}
</button>
))}
</div>
);
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{items.map((item) => (
<button
key={item}
onClick={() => onSelect(item)}
style={{
...pillStyle,
background:
item === active
? 'linear-gradient(135deg, #a855f7, #6366f1)'
: 'rgba(255,255,255,0.06)',
color: item === active ? '#fff' : '#a1a1aa',
border:
item === active
? '1px solid rgba(255,255,255,0.2)'
: '1px solid rgba(255,255,255,0.06)',
}}
>
{item}
</button>
))}
</div>
);
}
function CopyBadge() {
return (
<span
style={{
display: 'inline-block',
marginTop: 6,
fontSize: 10,
color: '#22c55e',
fontWeight: 500,
}}
>
✓ YAML copied — paste into gallery.yaml
</span>
);
return (
<span
style={{
display: 'inline-block',
marginTop: 6,
fontSize: 10,
color: '#22c55e',
fontWeight: 500,
}}
>
✓ YAML copied — paste into gallery.yaml
</span>
);
}

View File

@@ -8,79 +8,80 @@
import { useEffect, useRef, useState } from 'react';
interface MapLocationPublic {
city: string;
country: string;
lat: number;
lng: number;
photoCount: number;
coverUrl: string;
albums: { name: string; url: string }[];
city: string;
country: string;
lat: number;
lng: number;
photoCount: number;
coverUrl: string;
albums: { name: string; url: string }[];
}
export function MapView() {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<unknown>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<unknown>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
useEffect(() => {
let cancelled = false;
async function init() {
// Dynamically import Leaflet (client-only)
const L = (await import('leaflet')).default;
async function init() {
// Dynamically import Leaflet (client-only)
const L = (await import('leaflet')).default;
if (cancelled || !containerRef.current || mapRef.current) return;
if (cancelled || !containerRef.current || mapRef.current) return;
// Fetch map data
const res = await fetch('/api/map');
if (!res.ok) {
setError('Failed to load map data');
setLoading(false);
return;
}
const locations: MapLocationPublic[] = await res.json();
// Fetch map data
const res = await fetch('/api/map');
if (!res.ok) {
setError('Failed to load map data');
setLoading(false);
return;
}
const locations: MapLocationPublic[] = await res.json();
if (cancelled) return;
if (cancelled) return;
// Initialize map
const map = L.map(containerRef.current, {
zoomControl: true,
attributionControl: true,
});
mapRef.current = map;
// Initialize map
const map = L.map(containerRef.current, {
zoomControl: true,
attributionControl: true,
});
mapRef.current = map;
// Dark-themed tiles (CartoDB Dark Matter)
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19,
}).addTo(map);
// Dark-themed tiles (CartoDB Dark Matter)
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> &copy; <a href="https://carto.com/">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19,
}).addTo(map);
if (locations.length === 0) {
// No geotagged photos — show world view
map.setView([20, 0], 2);
setLoading(false);
return;
}
if (locations.length === 0) {
// No geotagged photos — show world view
map.setView([20, 0], 2);
setLoading(false);
return;
}
// Create markers with custom HTML icons
const markers: L.Marker[] = [];
// Create markers with custom HTML icons
const markers: L.Marker[] = [];
for (const loc of locations) {
const icon = L.divIcon({
className: '',
html: `<div class="map-marker">${loc.photoCount}</div>`,
iconSize: [32, 32],
iconAnchor: [16, 16],
popupAnchor: [0, -20],
});
for (const loc of locations) {
const icon = L.divIcon({
className: '',
html: `<div class="map-marker">${loc.photoCount}</div>`,
iconSize: [32, 32],
iconAnchor: [16, 16],
popupAnchor: [0, -20],
});
const albumLinks = loc.albums
.map((a) => `<a href="${a.url}" class="map-popup__album-link">${a.name} →</a>`)
.join('');
const albumLinks = loc.albums
.map((a) => `<a href="${a.url}" class="map-popup__album-link">${a.name} →</a>`)
.join('');
const popupHtml = `
const popupHtml = `
<div class="map-popup">
<img src="${loc.coverUrl}" alt="${loc.city}" class="map-popup__cover" loading="lazy" />
<div class="map-popup__body">
@@ -92,61 +93,61 @@ export function MapView() {
</div>
`;
const marker = L.marker([loc.lat, loc.lng], { icon })
.addTo(map)
.bindPopup(popupHtml, { maxWidth: 260, minWidth: 200 });
const marker = L.marker([loc.lat, loc.lng], { icon })
.addTo(map)
.bindPopup(popupHtml, { maxWidth: 260, minWidth: 200 });
markers.push(marker);
}
markers.push(marker);
}
// Fit bounds to show all markers
if (markers.length > 0) {
const group = L.featureGroup(markers);
map.fitBounds(group.getBounds().pad(0.15));
}
// Fit bounds to show all markers
if (markers.length > 0) {
const group = L.featureGroup(markers);
map.fitBounds(group.getBounds().pad(0.15));
}
// Force Leaflet to recalculate tile grid
setTimeout(() => map.invalidateSize(), 100);
// Force Leaflet to recalculate tile grid
setTimeout(() => map.invalidateSize(), 100);
setLoading(false);
}
init().catch((err) => {
console.error('[Map] Init error:', err);
if (!cancelled) {
setError('Failed to initialize map');
setLoading(false);
}
});
return () => {
cancelled = true;
if (mapRef.current) {
(mapRef.current as L.Map).remove();
mapRef.current = null;
}
};
}, []);
if (error) {
return (
<div className="map-container__loading">
<p>{error}</p>
</div>
);
setLoading(false);
}
init().catch((err) => {
console.error('[Map] Init error:', err);
if (!cancelled) {
setError('Failed to initialize map');
setLoading(false);
}
});
return () => {
cancelled = true;
if (mapRef.current) {
(mapRef.current as L.Map).remove();
mapRef.current = null;
}
};
}, []);
if (error) {
return (
<div style={{ position: 'relative' }}>
{loading && (
<div className="map-container__loading" style={{ position: 'absolute', inset: 0, zIndex: 1000 }}>
<p>Loading map…</p>
</div>
)}
<div
ref={containerRef}
className="map-container"
/>
</div>
<div className="map-container__loading">
<p>{error}</p>
</div>
);
}
return (
<div style={{ position: 'relative' }}>
{loading && (
<div
className="map-container__loading"
style={{ position: 'absolute', inset: 0, zIndex: 1000 }}
>
<p>Loading map…</p>
</div>
)}
<div ref={containerRef} className="map-container" />
</div>
);
}

View File

@@ -1,75 +1,75 @@
import { test, expect } from '@playwright/test';
test.describe('Photo Grid', () => {
// Use a known public subpage that has photos
const GRID_URL = '/deutschland/kloster-chorin-2024';
// Use a known public subpage that has photos
const GRID_URL = '/deutschland/kloster-chorin-2024';
test('renders grid items with visible images', async ({ page }) => {
await page.goto(GRID_URL);
test('renders grid items with visible images', async ({ page }) => {
await page.goto(GRID_URL);
// Grid container should exist
const grid = page.locator('.photo-grid');
await expect(grid).toBeVisible();
// Grid container should exist
const grid = page.locator('.photo-grid');
await expect(grid).toBeVisible();
// Should have grid items
const items = grid.locator('.photo-grid__item');
const count = await items.count();
expect(count).toBeGreaterThan(0);
// Should have grid items
const items = grid.locator('.photo-grid__item');
const count = await items.count();
expect(count).toBeGreaterThan(0);
// Scroll to trigger IntersectionObserver (FadeIn)
await items.first().scrollIntoViewIfNeeded();
await page.waitForTimeout(1000);
// Scroll to trigger IntersectionObserver (FadeIn)
await items.first().scrollIntoViewIfNeeded();
await page.waitForTimeout(1000);
// First grid item should have real dimensions (not collapsed)
const firstItem = items.first();
const box = await firstItem.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeGreaterThan(100);
expect(box!.height).toBeGreaterThan(50);
// First grid item should have real dimensions (not collapsed)
const firstItem = items.first();
const box = await firstItem.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeGreaterThan(100);
expect(box!.height).toBeGreaterThan(50);
// Image inside should exist and have the fill layout
const img = firstItem.locator('img');
await expect(img).toBeAttached();
// Image inside should exist and have the fill layout
const img = firstItem.locator('img');
await expect(img).toBeAttached();
});
test('grid items have overflow hidden (CSS regression)', async ({ page }) => {
// This test guards against the CSS cascade bug where a later rule
// strips `overflow: hidden` from .photo-grid__item, which breaks
// next/image fill rendering.
await page.goto(GRID_URL);
const grid = page.locator('.photo-grid');
await expect(grid).toBeVisible();
const item = grid.locator('.photo-grid__item').first();
await item.scrollIntoViewIfNeeded();
const overflow = await item.evaluate((el) => getComputedStyle(el).overflow);
expect(overflow).toBe('hidden');
});
test('images load with real content (not just blurhash)', async ({ page }) => {
await page.goto(GRID_URL);
// Scroll to trigger lazy loading
const grid = page.locator('.photo-grid');
await grid.scrollIntoViewIfNeeded();
await page.waitForTimeout(3000);
// Check that at least one image has loaded with real pixel data
const imgLoaded = await page.evaluate(() => {
const img = document.querySelector('.photo-grid__item img') as HTMLImageElement;
if (!img) return { found: false };
return {
found: true,
complete: img.complete,
naturalWidth: img.naturalWidth,
src: img.src.substring(0, 60),
};
});
test('grid items have overflow hidden (CSS regression)', async ({ page }) => {
// This test guards against the CSS cascade bug where a later rule
// strips `overflow: hidden` from .photo-grid__item, which breaks
// next/image fill rendering.
await page.goto(GRID_URL);
const grid = page.locator('.photo-grid');
await expect(grid).toBeVisible();
const item = grid.locator('.photo-grid__item').first();
await item.scrollIntoViewIfNeeded();
const overflow = await item.evaluate((el) => getComputedStyle(el).overflow);
expect(overflow).toBe('hidden');
});
test('images load with real content (not just blurhash)', async ({ page }) => {
await page.goto(GRID_URL);
// Scroll to trigger lazy loading
const grid = page.locator('.photo-grid');
await grid.scrollIntoViewIfNeeded();
await page.waitForTimeout(3000);
// Check that at least one image has loaded with real pixel data
const imgLoaded = await page.evaluate(() => {
const img = document.querySelector('.photo-grid__item img') as HTMLImageElement;
if (!img) return { found: false };
return {
found: true,
complete: img.complete,
naturalWidth: img.naturalWidth,
src: img.src.substring(0, 60),
};
});
expect(imgLoaded.found).toBe(true);
expect(imgLoaded.complete).toBe(true);
expect(imgLoaded.naturalWidth).toBeGreaterThan(0);
});
expect(imgLoaded.found).toBe(true);
expect(imgLoaded.complete).toBe(true);
expect(imgLoaded.naturalWidth).toBeGreaterThan(0);
});
});

View File

@@ -12,7 +12,7 @@ import { getConfig, SubpageConfig } from './config';
const TOKEN_EXPIRY_HOURS = 24;
function hmac(data: string): string {
return crypto.createHmac('sha256', getConfig().immich.apiKey).update(data).digest('hex');
return crypto.createHmac('sha256', getConfig().authSecret).update(data).digest('hex');
}
function authToken(slug: string, password: string): string {

View File

@@ -125,17 +125,17 @@ interface GalleryYaml {
exifOnHover?: boolean;
map?: boolean;
theme?:
| string
| {
preset?: string;
accent?: string;
fonts?: { heading?: string; body?: string; caption?: string };
radius?: number;
photoFrame?: string;
grain?: boolean;
headerDot?: boolean;
heroStyle?: string;
};
| string
| {
preset?: string;
accent?: string;
fonts?: { heading?: string; body?: string; caption?: string };
radius?: number;
photoFrame?: string;
grain?: boolean;
headerDot?: boolean;
heroStyle?: string;
};
grid?: {
columns?: number;
gap?: number;
@@ -149,18 +149,18 @@ interface GalleryYaml {
website?: string;
};
subpages?:
| Record<string, string[] | Array<string | Record<string, string>>>
| Array<{
name: string;
albums: Array<string | Record<string, string>>;
password?: string;
grid?: {
columns?: number;
gap?: number;
aspectRatio?: string;
layout?: string;
};
}>;
| Record<string, string[] | Array<string | Record<string, string>>>
| Array<{
name: string;
albums: Array<string | Record<string, string>>;
password?: string;
grid?: {
columns?: number;
gap?: number;
aspectRatio?: string;
layout?: string;
};
}>;
}
// ── YAML loading ───────────────────────────────────────────────
@@ -171,7 +171,7 @@ function loadGalleryYaml(): GalleryYaml {
if (!fs.existsSync(yamlPath)) {
throw new Error(
`Gallery config not found: ${yamlPath}\n` +
`Copy content/gallery.yaml.example to content/gallery.yaml and add your album IDs.`,
`Copy content/gallery.yaml.example to content/gallery.yaml and add your album IDs.`,
);
}
@@ -224,6 +224,8 @@ export interface GridConfig {
export interface AppConfig {
immich: { apiUrl: string; apiKey: string };
/** Secret used for signing auth cookies and encrypting asset tokens. */
authSecret: string;
albums: string[];
standaloneAlbums: string[];
subpages: SubpageConfig[];
@@ -317,6 +319,15 @@ export function getConfig(): AppConfig {
const apiUrl = env.IMMICH_API_URL;
const apiKey = env.IMMICH_API_KEY;
const authSecret = env.AUTH_SECRET || apiKey;
if (!env.AUTH_SECRET && process.env.NODE_ENV === 'production') {
console.warn(
'\n⚠️ SECURITY WARNING: AUTH_SECRET is not set. Falling back to IMMICH_API_KEY.\n' +
' Please set a long random string as AUTH_SECRET in your .env for better security.\n',
);
}
const gallery = loadGalleryYaml();
// Resolve theme: string shorthand → preset, object → merged with preset base
@@ -340,7 +351,13 @@ export function getConfig(): AppConfig {
processAlbumEntry(entry, 'gallery.yaml albums'),
);
if (standaloneAlbumIds.length === 0 && (!gallery.subpages || (Array.isArray(gallery.subpages) ? gallery.subpages.length === 0 : Object.keys(gallery.subpages).length === 0))) {
if (
standaloneAlbumIds.length === 0 &&
(!gallery.subpages ||
(Array.isArray(gallery.subpages)
? gallery.subpages.length === 0
: Object.keys(gallery.subpages).length === 0))
) {
throw new Error('gallery.yaml must define at least one album or subpage');
}
@@ -362,19 +379,19 @@ export function getConfig(): AppConfig {
password: sp.password,
...(sp.grid
? {
grid: {
...(sp.grid.columns != null ? { columns: sp.grid.columns } : {}),
...(sp.grid.gap != null ? { gap: sp.grid.gap } : {}),
...(sp.grid.aspectRatio != null ? { aspectRatio: sp.grid.aspectRatio } : {}),
...(sp.grid.layout != null
? {
layout: (VALID_LAYOUTS.includes(sp.grid.layout)
? sp.grid.layout
: 'masonry') as GridConfig['layout'],
}
: {}),
},
}
grid: {
...(sp.grid.columns != null ? { columns: sp.grid.columns } : {}),
...(sp.grid.gap != null ? { gap: sp.grid.gap } : {}),
...(sp.grid.aspectRatio != null ? { aspectRatio: sp.grid.aspectRatio } : {}),
...(sp.grid.layout != null
? {
layout: (VALID_LAYOUTS.includes(sp.grid.layout)
? sp.grid.layout
: 'masonry') as GridConfig['layout'],
}
: {}),
},
}
: {}),
};
});
@@ -400,19 +417,19 @@ export function getConfig(): AppConfig {
password: sp.password,
...(sp.grid
? {
grid: {
...(sp.grid.columns != null ? { columns: sp.grid.columns } : {}),
...(sp.grid.gap != null ? { gap: sp.grid.gap } : {}),
...(sp.grid.aspectRatio != null ? { aspectRatio: sp.grid.aspectRatio } : {}),
...(sp.grid.layout != null
? {
layout: (VALID_LAYOUTS.includes(sp.grid.layout)
? sp.grid.layout
: 'masonry') as GridConfig['layout'],
}
: {}),
},
}
grid: {
...(sp.grid.columns != null ? { columns: sp.grid.columns } : {}),
...(sp.grid.gap != null ? { gap: sp.grid.gap } : {}),
...(sp.grid.aspectRatio != null ? { aspectRatio: sp.grid.aspectRatio } : {}),
...(sp.grid.layout != null
? {
layout: (VALID_LAYOUTS.includes(sp.grid.layout)
? sp.grid.layout
: 'masonry') as GridConfig['layout'],
}
: {}),
},
}
: {}),
};
});
@@ -427,6 +444,7 @@ export function getConfig(): AppConfig {
apiUrl: `${apiUrl}/api`,
apiKey,
},
authSecret,
albums: allAlbumIds,
standaloneAlbums: standaloneAlbumIds.filter((id) => !subpageAlbumIds.has(id)),
subpages,
@@ -434,8 +452,8 @@ export function getConfig(): AppConfig {
siteSubtitle: env.SITE_SUBTITLE,
heroImages: gallery.hero
? (Array.isArray(gallery.hero) ? gallery.hero : [gallery.hero]).map((id) =>
validateUuid(id, 'gallery.yaml hero'),
)
validateUuid(id, 'gallery.yaml hero'),
)
: [],
exifOnHover: gallery.exifOnHover !== false,
grid: {
@@ -449,11 +467,11 @@ export function getConfig(): AppConfig {
theme,
footer: gallery.footer
? {
name: gallery.footer.name,
instagram: gallery.footer.instagram,
email: gallery.footer.email,
website: gallery.footer.website,
}
name: gallery.footer.name,
instagram: gallery.footer.instagram,
email: gallery.footer.email,
website: gallery.footer.website,
}
: null,
map: gallery.map === true,
albumOverrides,

View File

@@ -26,6 +26,12 @@ const envSchema = z.object({
/** Rate limit: max requests per minute per IP */
RATE_LIMIT_RPM: z.coerce.number().int().min(1).default(120),
/**
* Secret used for signing auth cookies and encrypting asset tokens.
* If not provided, IMMICH_API_KEY will be used as a fallback (not recommended for production).
*/
AUTH_SECRET: z.string().min(16, 'AUTH_SECRET should be at least 16 characters').optional(),
});
export type Env = z.infer<typeof envSchema>;

View File

@@ -13,8 +13,8 @@ let _key: Buffer | null = null;
function getKey(): Buffer {
if (!_key) {
const apiKey = getConfig().immich.apiKey;
_key = crypto.createHash('sha256').update(apiKey).digest();
const authSecret = getConfig().authSecret;
_key = crypto.createHash('sha256').update(authSecret).digest();
}
return _key;
}

View File

@@ -15,7 +15,7 @@
* docs/screenshots/theme-{preset}-{page}.png
*/
import { execSync, spawn, type ChildProcess } from 'child_process';
import { spawn, type ChildProcess } from 'child_process';
import fs from 'fs';
import path from 'path';
@@ -28,122 +28,127 @@ const VIEWPORT = { width: 1440, height: 900 };
const IMAGE_LOAD_TIMEOUT = 8000; // ms to wait for images after networkidle
async function main() {
// Ensure output directory exists
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
// Ensure output directory exists
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
// Read original gallery.yaml to restore later
const originalYaml = fs.readFileSync(GALLERY_YAML, 'utf8');
// Read original gallery.yaml to restore later
const originalYaml = fs.readFileSync(GALLERY_YAML, 'utf8');
// Dynamic import for Playwright (may not be installed globally)
const { chromium } = await import('playwright');
const browser = await chromium.launch();
// Dynamic import for Playwright (may not be installed globally)
const { chromium } = await import('playwright');
const browser = await chromium.launch();
try {
for (const theme of THEMES) {
console.log(`\n🎨 Theme: ${theme}`);
console.log('─'.repeat(50));
try {
for (const theme of THEMES) {
console.log(`\n🎨 Theme: ${theme}`);
console.log('─'.repeat(50));
// Update gallery.yaml with the theme
const yamlWithTheme = setThemeInYaml(originalYaml, theme);
fs.writeFileSync(GALLERY_YAML, yamlWithTheme);
// Update gallery.yaml with the theme
const yamlWithTheme = setThemeInYaml(originalYaml, theme);
fs.writeFileSync(GALLERY_YAML, yamlWithTheme);
// Start dev server
console.log(' ⏳ Starting dev server...');
const server = startDevServer();
await waitForServer(BASE_URL, 15000);
console.log(' ✅ Server ready');
// Start dev server
console.log(' ⏳ Starting dev server...');
const server = startDevServer();
await waitForServer(BASE_URL, 15000);
console.log(' ✅ Server ready');
const context = await browser.newContext({ viewport: VIEWPORT });
const page = await context.newPage();
const context = await browser.newContext({ viewport: VIEWPORT });
const page = await context.newPage();
// ── Homepage screenshot ──
console.log(' 📸 Capturing homepage...');
await page.goto(BASE_URL, { waitUntil: 'networkidle' });
await waitForImages(page);
await page.screenshot({
path: path.join(OUTPUT_DIR, `theme-${theme}-home.png`),
fullPage: false,
});
console.log(` ✅ theme-${theme}-home.png`);
// ── Homepage screenshot ──
console.log(' 📸 Capturing homepage...');
await page.goto(BASE_URL, { waitUntil: 'networkidle' });
await waitForImages(page);
await page.screenshot({
path: path.join(OUTPUT_DIR, `theme-${theme}-home.png`),
fullPage: false,
});
console.log(` ✅ theme-${theme}-home.png`);
// ── Grid view screenshot ──
console.log(' 📸 Capturing grid view...');
await page.goto(`${BASE_URL}${GRID_PATH}`, { waitUntil: 'networkidle' });
// Force all fade-in elements visible (don't scroll — keep album title in view)
await page.evaluate(() => {
document.querySelectorAll('.fade-in').forEach(el => el.classList.add('fade-in--visible'));
// Trigger lazy images by switching to eager loading
document.querySelectorAll('img[loading="lazy"]').forEach(img => {
(img as HTMLImageElement).loading = 'eager';
});
});
await waitForImages(page);
// Extra settle time for late-loading images in lower columns
await page.waitForTimeout(3000);
await page.screenshot({
path: path.join(OUTPUT_DIR, `theme-${theme}-grid.png`),
fullPage: false,
});
console.log(` ✅ theme-${theme}-grid.png`);
// ── Grid view screenshot ──
console.log(' 📸 Capturing grid view...');
await page.goto(`${BASE_URL}${GRID_PATH}`, { waitUntil: 'networkidle' });
// Force all fade-in elements visible (don't scroll — keep album title in view)
await page.evaluate(() => {
document.querySelectorAll('.fade-in').forEach((el) => el.classList.add('fade-in--visible'));
// Trigger lazy images by switching to eager loading
document.querySelectorAll('img[loading="lazy"]').forEach((img) => {
(img as HTMLImageElement).loading = 'eager';
});
});
await waitForImages(page);
// Extra settle time for late-loading images in lower columns
await page.waitForTimeout(3000);
await page.screenshot({
path: path.join(OUTPUT_DIR, `theme-${theme}-grid.png`),
fullPage: false,
});
console.log(` ✅ theme-${theme}-grid.png`);
await context.close();
await context.close();
// Stop dev server
server.kill('SIGTERM');
await new Promise((resolve) => server.on('close', resolve));
console.log(' 🛑 Server stopped');
}
} finally {
// Always restore original gallery.yaml
fs.writeFileSync(GALLERY_YAML, originalYaml);
console.log('\n✅ Restored original gallery.yaml');
await browser.close();
// Stop dev server
server.kill('SIGTERM');
await new Promise((resolve) => server.on('close', resolve));
console.log(' 🛑 Server stopped');
}
} finally {
// Always restore original gallery.yaml
fs.writeFileSync(GALLERY_YAML, originalYaml);
console.log('\n✅ Restored original gallery.yaml');
await browser.close();
}
console.log(`\n🎉 Done! Screenshots saved to ${OUTPUT_DIR}/`);
console.log(` ${fs.readdirSync(OUTPUT_DIR).filter(f => f.endsWith('.png')).join(', ')}`);
console.log(`\n🎉 Done! Screenshots saved to ${OUTPUT_DIR}/`);
console.log(
` ${fs
.readdirSync(OUTPUT_DIR)
.filter((f) => f.endsWith('.png'))
.join(', ')}`,
);
}
// ── Helpers ──────────────────────────────────────────────────────
function setThemeInYaml(yaml: string, theme: string): string {
// Replace existing theme line or insert after the header comment
if (/^theme:\s*.+$/m.test(yaml)) {
return yaml.replace(/^theme:\s*.+$/m, `theme: ${theme}`);
}
// Insert theme after the header comments
const marker = '# Secrets (API key, server URL) stay in .env.local.';
return yaml.replace(marker, `${marker}\n\ntheme: ${theme}`);
// Replace existing theme line or insert after the header comment
if (/^theme:\s*.+$/m.test(yaml)) {
return yaml.replace(/^theme:\s*.+$/m, `theme: ${theme}`);
}
// Insert theme after the header comments
const marker = '# Secrets (API key, server URL) stay in .env.local.';
return yaml.replace(marker, `${marker}\n\ntheme: ${theme}`);
}
function startDevServer(): ChildProcess {
const server = spawn('npm', ['run', 'dev'], {
cwd: process.cwd(),
stdio: 'pipe',
env: { ...process.env },
});
const server = spawn('npm', ['run', 'dev'], {
cwd: process.cwd(),
stdio: 'pipe',
env: { ...process.env },
});
// Suppress server output unless DEBUG is set
if (process.env.DEBUG) {
server.stdout?.pipe(process.stdout);
server.stderr?.pipe(process.stderr);
}
// Suppress server output unless DEBUG is set
if (process.env.DEBUG) {
server.stdout?.pipe(process.stdout);
server.stderr?.pipe(process.stderr);
}
return server;
return server;
}
async function waitForServer(url: string, timeoutMs: number): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
const res = await fetch(url);
if (res.ok) return;
} catch {
// Server not ready yet
}
await sleep(500);
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
const res = await fetch(url);
if (res.ok) return;
} catch {
// Server not ready yet
}
throw new Error(`Server did not start within ${timeoutMs}ms`);
await sleep(500);
}
throw new Error(`Server did not start within ${timeoutMs}ms`);
}
/**
@@ -151,50 +156,50 @@ async function waitForServer(url: string, timeoutMs: number): Promise<void> {
* This prevents capturing blurhash placeholders instead of real photos.
*/
async function waitForImages(page: import('playwright').Page): Promise<void> {
await page.waitForTimeout(1000); // Initial settle
await page.waitForTimeout(1000); // Initial settle
await page.evaluate((timeout) => {
return new Promise<void>((resolve) => {
const images = Array.from(document.querySelectorAll('img'));
let pending = images.filter((img) => !img.complete).length;
await page.evaluate((timeout) => {
return new Promise<void>((resolve) => {
const images = Array.from(document.querySelectorAll('img'));
let pending = images.filter((img) => !img.complete).length;
if (pending === 0) {
// All images already loaded, wait a bit for any CSS transitions
setTimeout(resolve, 500);
return;
}
if (pending === 0) {
// All images already loaded, wait a bit for any CSS transitions
setTimeout(resolve, 500);
return;
}
const done = () => {
pending--;
if (pending <= 0) setTimeout(resolve, 500);
};
const done = () => {
pending--;
if (pending <= 0) setTimeout(resolve, 500);
};
images.forEach((img) => {
if (!img.complete) {
img.addEventListener('load', done);
img.addEventListener('error', done);
}
});
images.forEach((img) => {
if (!img.complete) {
img.addEventListener('load', done);
img.addEventListener('error', done);
}
});
// Safety timeout
setTimeout(resolve, timeout);
});
}, IMAGE_LOAD_TIMEOUT);
// Safety timeout
setTimeout(resolve, timeout);
});
}, IMAGE_LOAD_TIMEOUT);
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ── Run ──────────────────────────────────────────────────────────
main().catch((err) => {
console.error('❌ Screenshot generation failed:', err);
// Try to restore gallery.yaml on error
try {
const original = fs.readFileSync(GALLERY_YAML + '.bak', 'utf8');
fs.writeFileSync(GALLERY_YAML, original);
} catch {
// Backup may not exist
}
process.exit(1);
console.error('❌ Screenshot generation failed:', err);
// Try to restore gallery.yaml on error
try {
const original = fs.readFileSync(GALLERY_YAML + '.bak', 'utf8');
fs.writeFileSync(GALLERY_YAML, original);
} catch {
// Backup may not exist
}
process.exit(1);
});