Release v0.18.0 — merges `dev` into `main`. ## Thanks - [@lancetm714](https://github.com/lancetm714) for the accent-contrast fix (#680 → #724). - [@RichKidsDev](https://github.com/RichKidsDev) for reporting the outdated Impressum (#697). ### Security - **Journal drafts and password-protected entries no longer render publicly as a subpage essay** ([#684](https://github.com/ralksta/immich-folio/pull/684), [GHSA-987w-cpwm-c9g9](https://github.com/ralksta/immich-folio/security/advisories/GHSA-987w-cpwm-c9g9), medium). A subpage's `essayFile` read the journal entry straight from disk, skipping the draft and password rules `/journal/<slug>` applies. It now resolves through the same rules: a draft reads as missing for visitors, and a protected entry shows its password gate, sharing the `lb_auth_journal_<slug>` cookie. - **Immich descriptions are escaped in generated subpage essays** ([#684](https://github.com/ralksta/immich-folio/pull/684), [GHSA-8ppx-39jv-q5xm](https://github.com/ralksta/immich-folio/security/advisories/GHSA-8ppx-39jv-q5xm), low). The essay built from a subpage's albums (`layout: essay` without markdown) put each asset's Immich description into the page as raw HTML. Captions are now HTML-escaped, and they go through `assetCaption()`, so `exif.caption: false` is respected there as well. Tracked in [#689](https://github.com/ralksta/immich-folio/issues/689). - **Admin drafts no longer keep a typed password, and the contact form's email check runs in linear time** ([#727](https://github.com/ralksta/immich-folio/pull/727)). The admin's session drafts wrote a password as typed to `sessionStorage`; a draft holding a plaintext password is now not kept (the unsaved-changes guard still warns). The email pattern could backtrack polynomially on a crafted domain; its labels now exclude the dot and the length is checked first. Both found by CodeQL before release. ### Added - **A built-in contact form with an inbox in the admin** ([#703](https://github.com/ralksta/immich-folio/pull/703), closes [#702](https://github.com/ralksta/immich-folio/issues/702)). `/contact` needs neither SMTP nor a form service: each message is one file in `content/messages/` (mode `0600`), read under the new _Messages_ tab, where _Reply by email_ opens the owner's mail client with the message quoted. Messages older than `contact.retentionDays` (default 90) are deleted. An optional ntfy push goes to `contact.notifyUrl` or `CONTACT_NOTIFY_URL`, and since [#709](https://github.com/ralksta/immich-folio/pull/709) it carries a fixed "new message" line and nothing about the sender — no name, no address, no text. Spam is kept out without a captcha: an off-screen honeypot, a minimum fill time, three submissions a minute per IP and a cap of 500 stored messages. With the Impressum on and no `legal.contactUrl`, the Impressum links the form as its second contact channel. A new doctor check warns when the form is on but nobody is notified. - **A privacy policy page, next to a list of what the site processes** ([#708](https://github.com/ralksta/immich-folio/pull/708)). `/privacy` renders `content/privacy.md`, edited under Settings → Legal, and the footer links it once the file has text; `privacy.enabled: false` hides it. Folio writes no legal text. Beside the editor it lists what _this_ installation does, read off the configuration — the map, statistics, contact form, password cookies, CDN — and marks every entry that involves a third party. _Insert headings_ adds the matching section headings and nothing else. The doctor warns while the Impressum is on and there is no policy. - **French, Spanish, Italian and Dutch interface translations** ([#681](https://github.com/ralksta/immich-folio/pull/681)), selected with `settings.yaml: lang` as before. The admin panel stays English. - **CDN mode for photos and videos** ([#681](https://github.com/ralksta/immich-folio/pull/681)). With `CDN_URL` set, image and video URLs point at a pull CDN whose origin is this server, so repeat views reach neither the server nor Immich. A site password switches the mode off, since a CDN would hand out cached photos without checking the unlock cookie. The CDN origin is added to the CSP, and a doctor check covers the password and `TRUSTED_PROXY_HOPS` cases. See `docs/deployment.md#cdn-mode`. - **A reworked admin panel** ([#712](https://github.com/ralksta/immich-folio/pull/712), [#713](https://github.com/ralksta/immich-folio/pull/713), [#714](https://github.com/ralksta/immich-folio/pull/714), [#716](https://github.com/ralksta/immich-folio/pull/716), [#717](https://github.com/ralksta/immich-folio/pull/717), [#718](https://github.com/ralksta/immich-folio/pull/718), [#719](https://github.com/ralksta/immich-folio/pull/719), [#721](https://github.com/ralksta/immich-folio/pull/721)): - **A sidebar instead of the header row**, grouped by task, with an unread count on Messages and a dot on Diagnostics while Immich is down. It collapses to an icon rail, with names shown on hover and focus, and remembers that per browser. - **`/admin` is an overview**: what needs attention (unread messages, doctor warnings), published pages, journal entries and recent views. - **The site's own visual language** — the preset's fonts, hairline borders, the square marker — and one page header on every screen. The accent is kept for the current place and the primary action; switches are now pills reading ON or OFF, in green rather than the accent, so Studio Modern's red no longer makes an enabled setting look like an error. - **The page builder is a structure list and a panel.** Hero, subpages and standalone albums sit in one list on the left, subpages drag-sorted in place; the selected entry is edited on the right instead of in an overlay. - **Dialogs only where a change is permanent.** Deleting a message or a journal entry, and resetting the favicon (which used to delete the file without asking), go through one confirm dialog in the admin's own look. Removals in the page builder, which only touch unsaved state, happen at once and offer _Undo_. No `window.confirm()` is left. - **Feature switches are grouped by meaning** as one-line rows under Settings → General; page transitions and scroll-to-top moved to Theme → Look & motion. No setting keys changed. ### Changed - **Fonts and the Leaflet stylesheet are served from the site itself** ([#700](https://github.com/ralksta/immich-folio/pull/700)). Every page used to link `fonts.googleapis.com`, which sends each visitor's IP address to Google. The server now fetches a theme's Google fonts once, rewrites the stylesheet and caches the files in `content/.fonts/`; custom fonts in `theme.fonts` keep working. If Google cannot be reached before a font is cached, the page falls back to the theme's system fonts. `leaflet.css` comes from the npm package instead of unpkg. The CSP drops `fonts.googleapis.com`, `fonts.gstatic.com` and `unpkg.com`. - **Email addresses are kept out of the served HTML** ([#705](https://github.com/ralksta/immich-folio/pull/705)). The Impressum and footer render the address only after hydration, from an encoded form, so harvesters reading raw HTML find nothing. Without JavaScript the Impressum shows `name [at] example [dot] de`. This defeats bulk harvesting, not a person with a browser. - **The Impressum cites § 5 DDG and links its contacts** ([#698](https://github.com/ralksta/immich-folio/pull/698), reported in [#697](https://github.com/ralksta/immich-folio/issues/697) by [@RichKidsDev](https://github.com/RichKidsDev)). The TMG was replaced by the DDG in May 2024; `legal.heading` replaces the line for other laws (e.g. § 5 ECG in Austria). `legal.contactUrl` and `legal.contactLabel` add a contact form as the second channel, so a phone number stays optional. Email, phone and contact URL are now links, and the "Created with the Impressum generator by eRecht24" line, shown on every site whether true or not, is gone. Settings → Legal gains fields for heading, contact URL, VAT ID and tax number, and a doctor check flags missing details. - **Missing pages answer `404`** ([#704](https://github.com/ralksta/immich-folio/pull/704)). Every missing page used to answer `200`, because streaming had started before `notFound()` ran. `/contact`, `/impressum`, `/map` and `/privacy` while switched off, and `/journal/<slug>` without an entry, now return a real 404 with the same not-found page. Album and subpage slugs still depend on Immich and stay soft 404s. - **Passwords set in the admin are stored as scrypt hashes** ([#706](https://github.com/ralksta/immich-folio/pull/706), closes [#690](https://github.com/ralksta/immich-folio/issues/690)). Subpage, album, journal-entry and site passwords were written as typed. The save routes now hash them; a stored hash reads _Protected_ with _Change_ and _Remove_ and is never put into an input. Visitors who unlocked a page stay signed in across unrelated saves. Existing plaintext passwords are hashed the next time their file is saved in the admin. - **One notification surface in the admin** ([#707](https://github.com/ralksta/immich-folio/pull/707)) replaces every `alert()`: errors stay until dismissed, successes clear themselves, and screen readers announce both. ### Fixed - **Map tiles load again** ([#701](https://github.com/ralksta/immich-folio/pull/701)). CARTO started answering every tile with an "API KEY REQUIRED" image, leaving `/map` and journal map blocks as a grey grid. Tiles now come from OpenStreetMap; the dark look is a CSS filter, so the map now follows the colour mode. - **The page builder no longer drops a subpage's `proofing:` flag on save** ([#711](https://github.com/ralksta/immich-folio/pull/711)). A page switched off for proofing by hand reverted after any unrelated edit. - **Unsaved edits in Settings and About survive switching admin tabs, and a backup restore is no longer overwritten by the next save** ([#687](https://github.com/ralksta/immich-folio/pull/687)). Editors that were open during a restore now reload and offer unsaved edits back as a conflict. Also: "Restore my changes" after a conflict found nothing, removing an album left its drawer showing the next album, and the journal saved (rotating a backup) without changes. - **Accent-backed buttons stay readable with a light or malformed accent** ([#724](https://github.com/ralksta/immich-folio/pull/724), supersedes [#680](https://github.com/ralksta/immich-folio/pull/680)) — contributed by [@lancetm714](https://github.com/lancetm714). A white accent made the proofing dialog's _Download selected (.zip)_ button white on white. `theme.accent` is now accepted as hex only and normalised to `#rrggbb`, anything else falls back to the preset, and the proofing dialog and filter pills use the mode-aware `--on-accent` text colour from #688. - **Every preset's accent is visible in both colour modes** ([#688](https://github.com/ralksta/immich-folio/pull/688)). Presets had one accent for both modes; minimal's dark mode drew black buttons on black. Presets now carry a light and a dark accent, and text on accent-filled buttons picks black or white for contrast. A custom accent stays the owner's choice in both modes. - **Visitor-side inconsistencies** ([#685](https://github.com/ralksta/immich-folio/pull/685)): after visiting `/impressum`, every subpage header turned centred and uppercase; back links announced "Back to Back to …"; the hero EXIF chip ignored `exif.location`/`camera`/`settings`; videos in journal entries opened as stills; the setup screen named a non-existent `.env.example`. - **An essay's lightbox walks only the photos the story shows** ([#686](https://github.com/ralksta/immich-folio/pull/686)), not every photo of the subpage's albums, and the proofing bar in essays shows the selection count instead of a filter button that did nothing. - **The page panel scrolls with the mouse wheel** ([#720](https://github.com/ralksta/immich-folio/pull/720)). - **The journal editor's top bar wraps on phones** ([#723](https://github.com/ralksta/immich-folio/pull/723), closes [#675](https://github.com/ralksta/immich-folio/issues/675)), so the title stays editable and Save stays on screen. - **Every admin form field has a name for assistive technology** ([#715](https://github.com/ralksta/immich-folio/pull/715)). Only two inputs had a linked label; 47 are linked now, and clicking a label focuses its field. ### Internal - **`SettingsEditor` and `PageBuilder` are split up** ([#710](https://github.com/ralksta/immich-folio/pull/710), [#711](https://github.com/ralksta/immich-folio/pull/711)). The 2,200-line settings editor is a shell with one file per section; the page builder's YAML handling and edits are pure functions under test. Both were checked side by side against `dev` for identical output. - **`useAdminFetch()`** ([#707](https://github.com/ralksta/immich-folio/pull/707)) gives Analytics, Messages, Backups and the journal list one loading and error pattern. - README brought up to v0.17.0 ([#678](https://github.com/ralksta/immich-folio/pull/678), [#679](https://github.com/ralksta/immich-folio/pull/679)). ### Upgrade notes **`content/` gains two directories the app writes to:** `content/.fonts/` for the cached fonts and `content/messages/` for contact-form messages. Both are created on demand, so a writable `content/` is enough, as before. **The server needs outbound HTTPS to Google once per font** to fill the font cache. Until then pages fall back to the theme's system fonts. Visitors' browsers no longer contact Google. **A custom CSP or reverse-proxy allowlist** must now allow `tile.openstreetmap.org` for images instead of `*.basemaps.cartocdn.com`, and no longer needs `fonts.googleapis.com`, `fonts.gstatic.com` or `unpkg.com`. The built-in CSP is updated. **`theme.accent` must be hex** (`#rgb`, `#rrggbb` or `#rrggbbaa`). Anything else, including a value without `#`, falls back to the preset's accent. **Plaintext passwords in `gallery.yaml`, `settings.yaml` or journal entries** are hashed the next time that file is saved in the admin; one save clears the doctor's warning. **New, optional settings:** `contact.*` (the form is off by default), `privacy.enabled`, `legal.heading`, `legal.contactUrl`, `legal.contactLabel`, and the `CDN_URL` and `CONTACT_NOTIFY_URL` environment variables. See `content/settings.yaml.example` and `.env.local.example`. In the example file, `vatId` and `taxId` had swapped sample values; check yours if you copied them. No `IMAGE_CACHE_VERSION` bump is needed this time. --------- 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>
777 lines
29 KiB
TypeScript
777 lines
29 KiB
TypeScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { env } from '../env';
|
|
import { resolveAuthSecret } from '../secret';
|
|
import { resolveSiteUrl } from '../siteUrl';
|
|
import { getInstallCredentials } from '../install';
|
|
import { loadYaml, clearYamlCache, validateUuid } from './parser';
|
|
import { resolveTheme, VALID_LAYOUTS, DEFAULT_PRESET } from './theme';
|
|
import { ALBUM_SORT_MODES, isAlbumSortMode, type AlbumSortMode } from '../albumSort';
|
|
import { LOCATION_PRECISIONS, isLocationPrecision, type LocationPrecision } from '../mapPrecision';
|
|
import {
|
|
slugify,
|
|
findAlbumSlugCollisions,
|
|
resolveExifDisplay,
|
|
resolveColorMode,
|
|
clamp,
|
|
PHOTO_GRID_COLUMNS_MIN,
|
|
PHOTO_GRID_COLUMNS_MAX,
|
|
PHOTO_GRID_GAP_MAX,
|
|
AppConfig,
|
|
AlbumEntryObject,
|
|
SubpageConfig,
|
|
SubpageSectionConfig,
|
|
SubpageObjectValue,
|
|
GalleryYaml,
|
|
SettingsYaml,
|
|
GridConfig,
|
|
LegalConfig,
|
|
ContactConfig,
|
|
CONTACT_RETENTION_DEFAULT,
|
|
CONTACT_RETENTION_MAX,
|
|
isHttpUrl,
|
|
} from './schema';
|
|
|
|
export * from './schema';
|
|
export * from './theme';
|
|
|
|
/** Invalidate the cached YAML so the next getConfig() call re-parses the files. */
|
|
export function invalidateConfigCache(): void {
|
|
clearYamlCache();
|
|
}
|
|
|
|
/**
|
|
* getConfig(), but returns null instead of throwing on a gallery.yaml that
|
|
* cannot be derived.
|
|
*
|
|
* getConfig() throws for three shapes the admin page builder is able to write:
|
|
* a gallery with neither albums nor subpages, a subpage with no name, and a
|
|
* subpage with neither albums nor sections. A throw inside a *layout* is not
|
|
* caught by app/error.tsx — that needs a global-error boundary — so the site
|
|
* and /admin would go down together, locking the user out of the only tool that
|
|
* can undo the save. That is issue #326's failure mode reached through an
|
|
* invalid config rather than a missing one.
|
|
*
|
|
* Callers should treat null exactly like `needsSetup`: show the setup screen,
|
|
* and keep /admin reachable.
|
|
*/
|
|
export function getConfigOrNull(): AppConfig | null {
|
|
try {
|
|
return getConfig();
|
|
} catch (error) {
|
|
console.error(
|
|
'[Folio] content/gallery.yaml could not be loaded — serving the setup screen. ' +
|
|
'Fix the file or restore a backup from content/.backups/:',
|
|
error,
|
|
);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
interface RawGridOverrides {
|
|
columns?: number;
|
|
gap?: number;
|
|
aspectRatio?: string;
|
|
layout?: string;
|
|
}
|
|
|
|
/**
|
|
* Converts raw YAML grid overrides into a typed partial GridConfig.
|
|
*
|
|
* `columns` and `gap` are clamped here, not left for the renderer: a subpage
|
|
* or album override reaches `--grid-columns` unclamped (app/[...path]/page.tsx),
|
|
* so `columns: -1` produced an invalid `repeat(-1, 1fr)` and collapsed the
|
|
* whole grid to one column with no error anywhere (#633). The cover grid had
|
|
* this already (buildCoverGridVars); this is the same treatment for the photo
|
|
* grid it was missing from.
|
|
*/
|
|
function parseGridOverrides(raw: RawGridOverrides): Partial<GridConfig> {
|
|
return {
|
|
...(raw.columns != null
|
|
? { columns: clamp(raw.columns, PHOTO_GRID_COLUMNS_MIN, PHOTO_GRID_COLUMNS_MAX) }
|
|
: {}),
|
|
...(raw.gap != null ? { gap: clamp(raw.gap, 0, PHOTO_GRID_GAP_MAX) } : {}),
|
|
...(raw.aspectRatio != null ? { aspectRatio: raw.aspectRatio } : {}),
|
|
...(raw.layout != null
|
|
? {
|
|
layout: (VALID_LAYOUTS.includes(raw.layout)
|
|
? raw.layout
|
|
: 'masonry') as GridConfig['layout'],
|
|
}
|
|
: {}),
|
|
};
|
|
}
|
|
|
|
/** Converts raw YAML grid overrides into a typed partial GridConfig. */
|
|
export function buildSubpageGrid(
|
|
raw?: RawGridOverrides,
|
|
): { grid: Partial<GridConfig> } | Record<string, never> {
|
|
if (!raw) return {};
|
|
return { grid: parseGridOverrides(raw) };
|
|
}
|
|
|
|
/**
|
|
* The two grids a subpage can override, as one spread-able object.
|
|
*
|
|
* `grid` sizes the photos inside its albums, `coverGrid` the album-cover tiles
|
|
* on the page itself. They were a single key until #523, where the admin field
|
|
* labelled "Album Cover Grid" turned out to retune every photo grid on the page
|
|
* as well. A gallery.yaml written before the split has no `coverGrid`, so the
|
|
* covers fall back to `grid` and such a page renders exactly as it did.
|
|
*/
|
|
function buildSubpageGrids(
|
|
grid?: RawGridOverrides,
|
|
coverGrid?: RawGridOverrides,
|
|
): { grid?: Partial<GridConfig>; coverGrid?: Partial<GridConfig> } {
|
|
const resolved = coverGrid ?? grid;
|
|
return {
|
|
...buildSubpageGrid(grid),
|
|
...(resolved ? { coverGrid: parseGridOverrides(resolved) } : {}),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Whether client proofing is on for a page.
|
|
*
|
|
* Precedence is subpage → global, the same shape `buildSubpageGrid` gives the
|
|
* grid: a subpage's own `proofing:` wins in either direction, and a page
|
|
* reached without one follows `proofing.enabled` from settings.yaml. `??`
|
|
* rather than `||` is load-bearing — `proofing: false` on a subpage has to
|
|
* override a global `true`, which `||` would discard.
|
|
*
|
|
* Photo essays deliberately do not use this: a published story is not an album
|
|
* handover, so it requires an explicit `proofing: true` and ignores the global
|
|
* default. That exception lives at its call site in app/[...path]/page.tsx.
|
|
*/
|
|
export function resolveProofing(
|
|
subpage: { proofing?: boolean } | undefined,
|
|
globalEnabled: boolean,
|
|
): boolean {
|
|
return subpage?.proofing ?? globalEnabled;
|
|
}
|
|
|
|
/**
|
|
* EXPERIMENTAL: keep only nav links that are safe to render as header <a>
|
|
* tags. Non-http(s) schemes (javascript:, data:) and incomplete entries are
|
|
* dropped with a warning rather than throwing — a bad external link should
|
|
* not take the site down.
|
|
*/
|
|
export function sanitizeNavLinks(
|
|
raw?: Array<{ label?: string; url?: string }>,
|
|
): Array<{ label: string; url: string }> {
|
|
if (!raw) return [];
|
|
const links: Array<{ label: string; url: string }> = [];
|
|
for (const entry of raw) {
|
|
const label = entry.label?.trim();
|
|
const url = entry.url?.trim();
|
|
if (!label || !url || !/^https?:\/\//i.test(url)) {
|
|
console.warn(
|
|
`[Folio] settings.yaml navLinks: dropping entry ${JSON.stringify(entry)} — ` +
|
|
'label and an http(s) url are required.',
|
|
);
|
|
continue;
|
|
}
|
|
links.push({ label, url });
|
|
}
|
|
return links;
|
|
}
|
|
|
|
/**
|
|
* The `legal:` block of settings.yaml, as the Impressum page renders it.
|
|
*
|
|
* `contactUrl` ends up in an `href`, so it gets the same rule as navLinks:
|
|
* anything that is not http(s) is dropped with a warning, which keeps a
|
|
* `javascript:` URL in hand-edited YAML off the page without taking it down.
|
|
* Empty strings become undefined so the page can test fields with `&&`.
|
|
*/
|
|
export function resolveLegal(raw?: Partial<LegalConfig>): LegalConfig {
|
|
const opt = (value?: string) => value?.trim() || undefined;
|
|
let contactUrl = opt(raw?.contactUrl);
|
|
if (contactUrl && !isHttpUrl(contactUrl)) {
|
|
console.warn(
|
|
`[Folio] settings.yaml legal.contactUrl: dropping ${JSON.stringify(contactUrl)} — ` +
|
|
'only http(s) URLs are allowed.',
|
|
);
|
|
contactUrl = undefined;
|
|
}
|
|
return {
|
|
enabled: raw?.enabled === true,
|
|
heading: opt(raw?.heading),
|
|
name: raw?.name || '',
|
|
address: raw?.address || '',
|
|
zipCity: raw?.zipCity || '',
|
|
country: raw?.country || '',
|
|
email: opt(raw?.email),
|
|
phone: opt(raw?.phone),
|
|
contactUrl,
|
|
contactLabel: opt(raw?.contactLabel),
|
|
taxId: opt(raw?.taxId),
|
|
vatId: opt(raw?.vatId),
|
|
extraInfo: opt(raw?.extraInfo),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The `contact:` block. `CONTACT_NOTIFY_URL` wins over `notifyUrl`, the same
|
|
* precedence SITE_PASSWORD has: an ntfy topic URL is as good as a password to
|
|
* anyone who wants to spam the owner's phone, so it may live outside the YAML.
|
|
* A non-http(s) URL is dropped with a warning, like `legal.contactUrl`.
|
|
*/
|
|
export function resolveContact(
|
|
raw?: SettingsYaml['contact'],
|
|
envNotifyUrl?: string,
|
|
): ContactConfig {
|
|
let notifyUrl = envNotifyUrl?.trim() || raw?.notifyUrl?.trim() || undefined;
|
|
if (notifyUrl && !isHttpUrl(notifyUrl)) {
|
|
console.warn(
|
|
`[Folio] contact.notifyUrl: dropping ${JSON.stringify(notifyUrl)} — only http(s) URLs are allowed.`,
|
|
);
|
|
notifyUrl = undefined;
|
|
}
|
|
const days = raw?.retentionDays;
|
|
return {
|
|
enabled: raw?.enabled === true,
|
|
notifyUrl,
|
|
retentionDays:
|
|
typeof days === 'number' && Number.isFinite(days)
|
|
? clamp(Math.round(days), 1, CONTACT_RETENTION_MAX)
|
|
: CONTACT_RETENTION_DEFAULT,
|
|
};
|
|
}
|
|
|
|
/** The parts of AppConfig that come from gallery.yaml. */
|
|
export interface GalleryDerivation {
|
|
albums: string[];
|
|
standaloneAlbums: string[];
|
|
subpages: SubpageConfig[];
|
|
albumOverrides: Record<string, string>;
|
|
albumDescriptions: Record<string, string>;
|
|
albumPasswords: Record<string, string>;
|
|
albumHeroImages: Record<string, string>;
|
|
albumSortModes: Record<string, AlbumSortMode>;
|
|
albumManualOrders: Record<string, string[]>;
|
|
albumGrids: Record<string, Partial<GridConfig>>;
|
|
albumCoverPositions: Record<string, string>;
|
|
albumDownloads: Record<string, boolean>;
|
|
albumLocationPrecision: Record<string, LocationPrecision>;
|
|
}
|
|
|
|
/**
|
|
* Derive the gallery half of AppConfig, throwing on a structure that cannot be
|
|
* represented: a subpage with no name, a subpage with neither albums nor
|
|
* sections. A gallery with no albums and no subpages is NOT an error — an
|
|
* empty gallery still renders (title, hero-less homepage) so the owner can
|
|
* add albums later via /admin.
|
|
*
|
|
* Extracted from getConfig() so the admin PUT can run the *real* derivation
|
|
* against a proposed gallery before writing it. Re-implementing the three
|
|
* checks in the route would guarantee drift; write-then-verify-then-roll-back
|
|
* would leave a window where other requests read the broken config.
|
|
*/
|
|
export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
|
|
const albumOverrides: Record<string, string> = {};
|
|
const albumDescriptions: Record<string, string> = {};
|
|
const albumPasswords: Record<string, string> = {};
|
|
const albumHeroImages: Record<string, string> = {};
|
|
const albumSortModes: Record<string, AlbumSortMode> = {};
|
|
const albumManualOrders: Record<string, string[]> = {};
|
|
const albumGrids: Record<string, Partial<GridConfig>> = {};
|
|
const albumCoverPositions: Record<string, string> = {};
|
|
const albumDownloads: Record<string, boolean> = {};
|
|
const albumLocationPrecision: Record<string, LocationPrecision> = {};
|
|
|
|
/** Returns null for an entry whose album ID is not a UUID; callers drop it. */
|
|
function processAlbumEntry(
|
|
entry: string | Record<string, string | AlbumEntryObject>,
|
|
context: string,
|
|
inheritedLocation?: LocationPrecision,
|
|
): string | null {
|
|
if (typeof entry === 'string') {
|
|
if (inheritedLocation) albumLocationPrecision[entry] = inheritedLocation;
|
|
return validateUuid(entry, context);
|
|
}
|
|
const [uuid, value] = Object.entries(entry)[0];
|
|
const validatedUuid = validateUuid(uuid, context);
|
|
if (!validatedUuid) return null;
|
|
// The subpage's setting applies unless the album states its own below.
|
|
if (inheritedLocation) albumLocationPrecision[validatedUuid] = inheritedLocation;
|
|
|
|
if (typeof value === 'string') {
|
|
albumOverrides[validatedUuid] = value;
|
|
} else {
|
|
if (value.title) albumOverrides[validatedUuid] = value.title;
|
|
if (value.description) albumDescriptions[validatedUuid] = value.description;
|
|
if (value.password) albumPasswords[validatedUuid] = value.password;
|
|
// The album ID (the key) is validated above; the hero asset ID is a
|
|
// separate UUID and was previously stored raw. It flows to encodeAssetId
|
|
// via app/[...path]/page.tsx, which encrypts whatever it is handed — so a
|
|
// typo here produced a well-formed URL that 404s forever, with nothing in
|
|
// the log naming the cause. Every other ID in this file goes through
|
|
// validateUuid; this one was the gap.
|
|
if (value.heroImage) {
|
|
const heroId = validateUuid(
|
|
value.heroImage,
|
|
`${context} heroImage for album ${validatedUuid}`,
|
|
);
|
|
// Dropped rather than defaulted: without one the album falls back to its
|
|
// Immich cover, which is a better answer than a request that 400s.
|
|
if (heroId) albumHeroImages[validatedUuid] = heroId;
|
|
}
|
|
|
|
// Throw rather than fall back to the default: a typo would otherwise be
|
|
// invisible — the album would just keep rendering in Immich order and the
|
|
// owner would be left wondering why the setting does nothing. Throwing
|
|
// also gives the admin PUT its 400 for free via the deriveGallery
|
|
// dry-run, and getConfigOrNull() degrades a hand-edited file to the setup
|
|
// screen rather than taking the site down. Name the album and the legal
|
|
// values so the log line is enough to fix it.
|
|
if (value.sort != null) {
|
|
if (!isAlbumSortMode(value.sort)) {
|
|
throw new Error(
|
|
`${context}: album ${validatedUuid} has an unknown sort "${value.sort}". ` +
|
|
`Valid values are: ${ALBUM_SORT_MODES.join(', ')}.`,
|
|
);
|
|
}
|
|
albumSortModes[validatedUuid] = value.sort;
|
|
}
|
|
|
|
// Kept regardless of the mode, so switching manual → newest → manual does
|
|
// not silently destroy a hand-curated order.
|
|
if (value.assetOrder?.length) {
|
|
albumManualOrders[validatedUuid] = value.assetOrder
|
|
.map((assetId, i) =>
|
|
validateUuid(assetId, `${context} assetOrder[${i}] for album ${validatedUuid}`),
|
|
)
|
|
.filter((id): id is string => id !== null);
|
|
}
|
|
|
|
// EXPERIMENTAL: per-album grid override — reuses the subpage-grid
|
|
// normalisation so unknown layouts degrade identically.
|
|
if (value.grid) {
|
|
const built = buildSubpageGrid(value.grid);
|
|
if ('grid' in built) albumGrids[validatedUuid] = built.grid;
|
|
}
|
|
|
|
// EXPERIMENTAL: coverPosition lands in a style attribute, so only a
|
|
// strict CSS position grammar is allowed. Throw like `sort` does — a
|
|
// silent fallback would leave the owner wondering why nothing moves.
|
|
if (value.coverPosition != null) {
|
|
const pos = value.coverPosition.trim();
|
|
const keyword = /^(center|top|bottom|left|right)( (center|top|bottom|left|right))?$/;
|
|
const percent = /^\d{1,3}% \d{1,3}%$/;
|
|
if (!keyword.test(pos) && !percent.test(pos)) {
|
|
throw new Error(
|
|
`${context}: album ${validatedUuid} has an invalid coverPosition "${value.coverPosition}". ` +
|
|
`Use two percentages ("50% 25%") or CSS keywords ("top", "center bottom").`,
|
|
);
|
|
}
|
|
albumCoverPositions[validatedUuid] = pos;
|
|
}
|
|
|
|
// Opt-in per album, never global: a public portfolio must not start
|
|
// handing out full-resolution originals because one client gallery
|
|
// needed to (#475).
|
|
if (value.download === true) albumDownloads[validatedUuid] = true;
|
|
const location = parseLocation(value.location, `${context}: album ${validatedUuid} location`);
|
|
if (location) albumLocationPrecision[validatedUuid] = location;
|
|
}
|
|
return validatedUuid;
|
|
}
|
|
|
|
/** Album entries, with the ones whose ID is not a UUID dropped (#517). */
|
|
function processAlbumEntries(
|
|
entries: Array<string | Record<string, string | AlbumEntryObject>>,
|
|
context: string,
|
|
inheritedLocation?: LocationPrecision,
|
|
): string[] {
|
|
return entries
|
|
.map((entry) => processAlbumEntry(entry, context, inheritedLocation))
|
|
.filter((id): id is string => id !== null);
|
|
}
|
|
|
|
/**
|
|
* Narrow a raw `location:` value, or throw. Rejected rather than defaulted
|
|
* for the same reason as `sort`: a typo in a privacy setting that silently
|
|
* fell back to `exact` would publish the position it was meant to withhold.
|
|
*/
|
|
function parseLocation(raw: string | undefined, context: string): LocationPrecision | undefined {
|
|
if (raw == null) return undefined;
|
|
if (!isLocationPrecision(raw)) {
|
|
throw new Error(
|
|
`${context}: unknown location "${raw}". ` +
|
|
`Valid values are: ${LOCATION_PRECISIONS.join(', ')}.`,
|
|
);
|
|
}
|
|
return raw;
|
|
}
|
|
|
|
const standaloneAlbumIds = processAlbumEntries(gallery.albums ?? [], 'gallery.yaml albums');
|
|
|
|
let subpages: SubpageConfig[] = [];
|
|
|
|
if (Array.isArray(gallery.subpages)) {
|
|
subpages = gallery.subpages.map((sp) => {
|
|
if (!sp.name) {
|
|
throw new Error(`Subpage "(unnamed)" must have a name`);
|
|
}
|
|
|
|
// Parse sections if present
|
|
let sections: SubpageSectionConfig[] | undefined;
|
|
let albumIds: string[];
|
|
|
|
if (sp.sections && sp.sections.length > 0) {
|
|
sections = sp.sections.map((sec) => ({
|
|
title: sec.title,
|
|
slug: slugify(sec.title),
|
|
description: sec.description,
|
|
albumIds: processAlbumEntries(
|
|
sec.albums,
|
|
`subpage "${sp.name}" section "${sec.title}"`,
|
|
parseLocation(sp.location, `subpage "${sp.name}" location`),
|
|
),
|
|
}));
|
|
// flat union of all section albums
|
|
albumIds = sections!.flatMap((sec) => sec.albumIds);
|
|
// Also include any top-level albums (outside sections)
|
|
const topLevel = processAlbumEntries(
|
|
sp.albums ?? [],
|
|
`subpage "${sp.name}"`,
|
|
parseLocation(sp.location, `subpage "${sp.name}" location`),
|
|
);
|
|
albumIds = [...topLevel, ...albumIds];
|
|
} else {
|
|
const albums = sp.albums ?? [];
|
|
if (albums.length === 0) {
|
|
throw new Error(`Subpage "${sp.name}" must have albums or sections`);
|
|
}
|
|
albumIds = processAlbumEntries(
|
|
albums,
|
|
`subpage "${sp.name}"`,
|
|
parseLocation(sp.location, `subpage "${sp.name}" location`),
|
|
);
|
|
}
|
|
|
|
return {
|
|
name: sp.name,
|
|
slug: slugify(sp.name),
|
|
title: sp.title,
|
|
subtitle: sp.subtitle,
|
|
albumIds,
|
|
sections,
|
|
password: sp.password,
|
|
proofing: sp.proofing,
|
|
essayFile: sp.essayFile,
|
|
essayText: sp.essayText,
|
|
enabled: sp.enabled !== false,
|
|
hidden: sp.hidden === true,
|
|
...buildSubpageGrids(sp.grid, sp.coverGrid),
|
|
};
|
|
});
|
|
} else if (gallery.subpages) {
|
|
subpages = Object.entries(gallery.subpages).map(([name, value]) => {
|
|
if (Array.isArray(value)) {
|
|
return {
|
|
name,
|
|
slug: slugify(name),
|
|
albumIds: processAlbumEntries(value, `subpage "${name}"`),
|
|
enabled: true,
|
|
};
|
|
}
|
|
const sp = value as SubpageObjectValue;
|
|
const albumEntries = sp.albums || [];
|
|
return {
|
|
name,
|
|
slug: slugify(name),
|
|
title: sp.title,
|
|
subtitle: sp.subtitle,
|
|
albumIds: processAlbumEntries(
|
|
albumEntries,
|
|
`subpage "${name}"`,
|
|
parseLocation(sp.location, `subpage "${name}" location`),
|
|
),
|
|
password: sp.password,
|
|
proofing: sp.proofing,
|
|
essayFile: sp.essayFile,
|
|
essayText: sp.essayText,
|
|
enabled: sp.enabled !== false,
|
|
hidden: sp.hidden === true,
|
|
...buildSubpageGrids(sp.grid, sp.coverGrid),
|
|
};
|
|
});
|
|
}
|
|
|
|
const subpageAlbumIds = new Set(subpages.flatMap((sp) => sp.albumIds));
|
|
const allAlbumIds = [...new Set([...standaloneAlbumIds, ...subpageAlbumIds])];
|
|
const standaloneAlbums = standaloneAlbumIds.filter((id) => !subpageAlbumIds.has(id));
|
|
|
|
// Every consumer that resolves a slug takes the first match — getAlbumBySlug,
|
|
// the sitemap, findPassword — so two subpages that slugify alike leave the
|
|
// second unreachable and its password / albums resolved from the first
|
|
// (#632). slugify() folds diacritics and punctuation, so distinct names
|
|
// collide easily: "Portfolio 2024" and "Portfolio-2024" both become
|
|
// "portfolio-2024".
|
|
const subpagesBySlug = new Map<string, string[]>();
|
|
for (const sp of subpages) {
|
|
const names = subpagesBySlug.get(sp.slug) ?? [];
|
|
names.push(sp.name);
|
|
subpagesBySlug.set(sp.slug, names);
|
|
}
|
|
for (const [slug, names] of subpagesBySlug) {
|
|
if (names.length > 1) {
|
|
throw new Error(
|
|
`Subpages ${names.map((n) => `"${n}"`).join(' and ')} all produce the slug "${slug}". ` +
|
|
`Rename one so their URLs do not collide.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
// Same rule applies to albums that share a route (standalone albums among
|
|
// themselves, or one subpage's albums including its sections). Only a title
|
|
// override is known here without asking Immich — an album that keeps its
|
|
// Immich name can still collide, which is what the doctor's equivalent
|
|
// check, run against the live album list, is for.
|
|
const checkAlbumOverrideCollisions = (context: string, ids: string[]) => {
|
|
const named = ids
|
|
.map((id) => ({ id, name: albumOverrides[id] }))
|
|
.filter((a): a is { id: string; name: string } => !!a.name);
|
|
for (const { slug, albums } of findAlbumSlugCollisions(named)) {
|
|
throw new Error(
|
|
`${context}: albums titled ${albums.map((a) => `"${a.name}"`).join(' and ')} all produce ` +
|
|
`the slug "${slug}". Give one a different title override.`,
|
|
);
|
|
}
|
|
};
|
|
checkAlbumOverrideCollisions('gallery.yaml albums', standaloneAlbums);
|
|
for (const sp of subpages) {
|
|
checkAlbumOverrideCollisions(`subpage "${sp.name}"`, sp.albumIds);
|
|
}
|
|
|
|
return {
|
|
albums: allAlbumIds,
|
|
standaloneAlbums,
|
|
subpages,
|
|
albumOverrides,
|
|
albumDescriptions,
|
|
albumPasswords,
|
|
albumHeroImages,
|
|
albumSortModes,
|
|
albumManualOrders,
|
|
albumGrids,
|
|
albumCoverPositions,
|
|
albumDownloads,
|
|
albumLocationPrecision,
|
|
};
|
|
}
|
|
|
|
/** Whether content/about.md exists — the About page has nothing to show without it. */
|
|
function aboutContentExists(): boolean {
|
|
try {
|
|
return fs.existsSync(path.join(process.cwd(), 'content', 'about.md'));
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export function getConfig(): AppConfig {
|
|
// No in-memory config cache: admin saves can land in a different
|
|
// worker/process than page rendering, so a per-worker cache goes stale
|
|
// until restart. Freshness comes from the mtime-checked YAML cache in
|
|
// loadYaml() — a statSync per file, negligible next to Immich API calls.
|
|
const { apiUrl, apiKey } = getInstallCredentials();
|
|
const authSecret = resolveAuthSecret();
|
|
|
|
// The API URL may already end with /api (a user-supplied env var or a
|
|
// wizard-installed value). Appending unconditionally produces a double
|
|
// suffix and breaks every Immich request.
|
|
const immichApiUrl = apiUrl.endsWith('/api') ? apiUrl : `${apiUrl}/api`;
|
|
|
|
const gallery = loadYaml<GalleryYaml>('gallery.yaml');
|
|
const settings = loadYaml<SettingsYaml>('settings.yaml') || {};
|
|
|
|
// Two separate faults, deliberately kept apart. Missing credentials mean
|
|
// nothing can reach Immich; a missing gallery.yaml only means the public site
|
|
// has nothing to list yet. Conflating them made a credentialed deployment
|
|
// without gallery.yaml report "Immich disconnected" and locked the admin
|
|
// panel out of the album pickers that would have created the file (#507).
|
|
const needsCredentials = !apiKey || !apiUrl;
|
|
const needsGallery = !gallery;
|
|
|
|
if (needsCredentials || needsGallery) {
|
|
// Return dummy config if gallery.yaml is missing
|
|
return {
|
|
immich: { apiUrl: immichApiUrl, apiKey },
|
|
authSecret,
|
|
albums: [],
|
|
standaloneAlbums: [],
|
|
subpages: [],
|
|
siteTitle: env.SITE_TITLE || 'Immich Folio',
|
|
siteSubtitle: env.SITE_SUBTITLE || 'Setup Required',
|
|
lang: 'en',
|
|
// Nothing to protect yet, and a gate here would sit in front of the
|
|
// setup screen that is trying to tell the operator what is missing.
|
|
sitePassword: '',
|
|
seo: {
|
|
title: 'Setup Required',
|
|
description: 'Please configure Immich Folio',
|
|
titleTemplate: '%s | Setup Required',
|
|
license: '',
|
|
noIndex: true,
|
|
noFollow: true,
|
|
},
|
|
heroImages: [],
|
|
siteUrl: null,
|
|
siteUrlSource: 'none',
|
|
colorMode: 'dark',
|
|
exifOnHover: true,
|
|
exif: resolveExifDisplay(),
|
|
grid: { columns: 3, gap: 12, aspectRatio: '1', layout: 'masonry' },
|
|
gridGapExplicit: false,
|
|
theme: resolveTheme(DEFAULT_PRESET),
|
|
footer: null,
|
|
legal: { enabled: false, name: '', address: '', zipCity: '', country: '' },
|
|
contact: { enabled: false, retentionDays: CONTACT_RETENTION_DEFAULT },
|
|
privacy: { enabled: false },
|
|
map: false,
|
|
transitions: false,
|
|
scrollToTop: false,
|
|
analytics: true,
|
|
proofing: { enabled: false, allowMailto: false },
|
|
aboutEnabled: true,
|
|
albumOverrides: {},
|
|
albumDescriptions: {},
|
|
albumPasswords: {},
|
|
albumHeroImages: {},
|
|
albumSortModes: {},
|
|
albumManualOrders: {},
|
|
albumGrids: {},
|
|
albumCoverPositions: {},
|
|
albumDownloads: {},
|
|
albumLocationPrecision: {},
|
|
navLinks: [],
|
|
cacheTtl: env.CACHE_TTL * 1000,
|
|
staleMaxAge: env.STALE_MAX_AGE * 1000,
|
|
immichTimeoutMs: env.IMMICH_TIMEOUT_MS,
|
|
rateLimitRpm: env.RATE_LIMIT_RPM,
|
|
trustedProxyHops: env.TRUSTED_PROXY_HOPS,
|
|
needsSetup: true,
|
|
needsCredentials,
|
|
needsGallery,
|
|
};
|
|
}
|
|
|
|
const theme = resolveTheme(settings.theme);
|
|
|
|
const {
|
|
albums: allAlbumIds,
|
|
standaloneAlbums,
|
|
subpages,
|
|
albumOverrides,
|
|
albumDescriptions,
|
|
albumPasswords,
|
|
albumHeroImages,
|
|
albumSortModes,
|
|
albumManualOrders,
|
|
albumGrids,
|
|
albumCoverPositions,
|
|
albumDownloads,
|
|
albumLocationPrecision,
|
|
} = deriveGallery(gallery);
|
|
|
|
const siteSeoTitle = settings.seo?.title || settings.title || env.SITE_TITLE || 'Gallery';
|
|
|
|
return {
|
|
immich: { apiUrl: immichApiUrl, apiKey },
|
|
authSecret,
|
|
albums: allAlbumIds,
|
|
standaloneAlbums,
|
|
subpages,
|
|
siteTitle: settings.title ?? env.SITE_TITLE,
|
|
siteSubtitle: settings.subtitle ?? env.SITE_SUBTITLE,
|
|
lang: settings.lang ?? 'en',
|
|
// Env wins, so a deployment can rotate the site password without touching
|
|
// settings.yaml — the same precedence the Immich credentials use.
|
|
sitePassword: env.SITE_PASSWORD ?? settings.sitePassword ?? '',
|
|
seo: {
|
|
title: siteSeoTitle,
|
|
description:
|
|
settings.seo?.description ||
|
|
settings.subtitle ||
|
|
env.SITE_SUBTITLE ||
|
|
'A curated photography portfolio',
|
|
titleTemplate: settings.seo?.titleTemplate || `%s | ${siteSeoTitle}`,
|
|
noIndex: settings.seo?.noIndex === true,
|
|
noFollow: settings.seo?.noFollow === true,
|
|
license: settings.seo?.license?.trim() || '',
|
|
},
|
|
heroImages: gallery.hero
|
|
? (Array.isArray(gallery.hero) ? gallery.hero : [gallery.hero])
|
|
.map((id) => validateUuid(id, 'gallery.yaml hero'))
|
|
.filter((id): id is string => id !== null)
|
|
: [],
|
|
...(() => {
|
|
const site = resolveSiteUrl(settings.url, env.SITE_URL);
|
|
return { siteUrl: site.url, siteUrlSource: site.source };
|
|
})(),
|
|
colorMode: resolveColorMode(settings.mode),
|
|
exifOnHover: settings.exifOnHover !== false,
|
|
exif: resolveExifDisplay(settings.exif, settings.exifOnHover),
|
|
grid: {
|
|
columns:
|
|
settings.grid?.columns != null
|
|
? clamp(settings.grid.columns, PHOTO_GRID_COLUMNS_MIN, PHOTO_GRID_COLUMNS_MAX)
|
|
: 3,
|
|
gap: settings.grid?.gap != null ? clamp(settings.grid.gap, 0, PHOTO_GRID_GAP_MAX) : 12,
|
|
aspectRatio: settings.grid?.aspectRatio ?? '1',
|
|
layout: (VALID_LAYOUTS.includes(settings.grid?.layout ?? '')
|
|
? settings.grid!.layout
|
|
: 'masonry') as GridConfig['layout'],
|
|
},
|
|
gridGapExplicit: settings.grid?.gap != null,
|
|
theme,
|
|
footer: settings.footer
|
|
? {
|
|
name: settings.footer.name,
|
|
instagram: settings.footer.instagram,
|
|
email: settings.footer.email,
|
|
website: settings.footer.website,
|
|
}
|
|
: null,
|
|
legal: resolveLegal(settings.legal),
|
|
contact: resolveContact(settings.contact, env.CONTACT_NOTIFY_URL),
|
|
privacy: { enabled: settings.privacy?.enabled !== false },
|
|
map: settings.map === true,
|
|
transitions: settings.transitions !== false,
|
|
scrollToTop: settings.scrollToTop !== false,
|
|
analytics: settings.analytics !== false,
|
|
proofing: {
|
|
enabled: settings.proofing?.enabled !== false,
|
|
allowMailto: settings.proofing?.allowMailto !== false,
|
|
},
|
|
protection: settings.protection,
|
|
watermark: settings.watermark,
|
|
// The setting alone is not enough: about.md does not exist until someone
|
|
// writes it, so a fresh install put a nav link in front of an empty page
|
|
// (#518). `enabled: false` still hides it even when the file is there.
|
|
aboutEnabled: settings.about?.enabled !== false && aboutContentExists(),
|
|
albumOverrides,
|
|
albumDescriptions,
|
|
albumPasswords,
|
|
albumHeroImages,
|
|
albumSortModes,
|
|
albumManualOrders,
|
|
albumGrids,
|
|
albumCoverPositions,
|
|
albumDownloads,
|
|
albumLocationPrecision,
|
|
navLinks: sanitizeNavLinks(settings.navLinks),
|
|
cacheTtl: env.CACHE_TTL * 1000,
|
|
staleMaxAge: env.STALE_MAX_AGE * 1000,
|
|
immichTimeoutMs: env.IMMICH_TIMEOUT_MS,
|
|
rateLimitRpm: env.RATE_LIMIT_RPM,
|
|
trustedProxyHops: env.TRUSTED_PROXY_HOPS,
|
|
needsSetup: false,
|
|
needsCredentials: false,
|
|
needsGallery: false,
|
|
};
|
|
}
|