release: v0.11.0 — journal fixes, admin URLs, design system cleanup (#432)

* fix(screenshots): sharp-Typen fuer 0.34 und 0.35 gleichzeitig (#410)

sharp 0.35 ist von `export =` auf ESM umgestellt: der Modul-Namespace
ist nicht mehr aufrufbar, die Factory sitzt unter .default. Der
Type-Check brach damit in scripts/screenshots.ts weg, sobald der
Next-Bump (#402) sharp von 0.34.5 auf 0.35.3 mitzieht -- sharp ist hier
keine deklarierte Dependency, sondern kommt ueber Next mit.

Die Form wird jetzt aus dem installierten Paket abgeleitet statt
festgeschrieben, zur Laufzeit wie im Typ. Geprueft mit beiden
Versionen: tsc laeuft mit 0.34.5 und mit 0.35.3 fehlerfrei durch.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(deps): bump the nextjs group across 1 directory with 2 updates (#402)

Bumps the nextjs group with 2 updates in the / directory: [next](https://github.com/vercel/next.js) and [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next).


Updates `next` from 16.2.12 to 16.3.0
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.2.12...v16.3.0)

Updates `eslint-config-next` from 16.2.12 to 16.3.0
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.0/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.3.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: nextjs
- dependency-name: next
  dependency-version: 16.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: nextjs
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump prettier from 3.8.3 to 3.9.6 (#405)

Bumps [prettier](https://github.com/prettier/prettier) from 3.8.3 to 3.9.6.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.9.6)

---
updated-dependencies:
- dependency-name: prettier
  dependency-version: 3.9.6
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* docs(changelog): Unreleased-Sektion fuer die Bumps nach v0.10.0 (#413)

Die Dependency-PRs sind nach dem Release auf dev gelandet, teils auch
auf main. Ohne Eintrag waeren sie beim naechsten Release unsichtbar --
inklusive Next 16.3.0, das CVE-2025-13465 mitbringt.

Ausserdem im 0.10.0-Abschnitt nachgetragen, dass der Trivy-Scan bis
#409 nie gelaufen ist. Der Fix steckt im Tag v0.10.0, fehlte aber in der
Aufzaehlung -- und "Images werden bei jedem Publish gescannt" stand im
Changelog, waehrend der Job im Action-Setup abbrach.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(gallery): per-album sort order, independent of Immich (#408) (#414)

Album order was dictated entirely by Immich: getAlbum() sorted by the
album's own asc/desc flag, so a Folio album always mirrored the archive.
A curated series has a narrative order that has nothing to do with
capture time, and changing the Immich album's sort to fit the website
changes it for the archive too.

Adds an optional per-album `sort` in gallery.yaml, editable in /admin,
defaulting to today's behaviour so every existing config is unchanged:

  immich (default) | newest | oldest | filename | manual

`manual` is a pinned *prefix*: `assetOrder` lists only the photos placed
by hand, everything else follows in the album's Immich order. A full
permutation of a 2,000-photo album would be ~80 KB of UUIDs in a file
that is rewritten and copied to content/.backups/ on every admin save.
It also makes drift fall out for free — photos removed in Immich never
match, new ones land in the tail rather than being hidden.

Sorting is applied after the cache read, not before the cache write, so
the LRU keeps one canonical Immich-ordered copy per album. That avoids
putting the mode in the cache key, lets a config change take effect
without depending on invalidation, and keeps the stale-serving path
correct. cache.get() returns the stored object by reference, so
withSort() returns a shallow clone with a new array — sorting in place
would reorder the shared entry, and under request coalescing every
concurrent caller would be sorting the same array.

Also fixes a prerequisite bug: /api/admin/albums/[albumId]/assets read
album.assets from GET /albums/:id, which Immich 3.x no longer populates
(lib/immich.ts:507). The hero picker's "This Album" tab returned nothing
and threw outright when the key was absent. It now goes through the
client's paginated metadata search, with ?types=all to opt videos in for
the reorder editor.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>

* refactor(admin): drop decorative emoji from the sort select labels (#415)

An <option> cannot contain markup, so the SVG set in Icons is not
reachable there — but a decorative emoji is not a substitute for it.
Plain text instead; the album card badge already uses a real icon.

The remaining emoji in the admin panel (asset picker tabs, section
headings, layout picker options) predate this branch and are left for a
separate cleanup.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>

* refactor(admin): replace emoji icons with the shared SVG icon set (#416)

The admin panel mixed two icon conventions: inline SVGs from
`Icons.tsx` in most components, and decorative emoji in the asset
picker and a few PageBuilder labels. Emoji render inconsistently
across platforms, ignore the accent colour, and cannot inherit the
`.svg-icon` sizing rules.

- Icons.tsx: add `IconStar` (filled — it marks a state, not an
  action) and `IconImage`.
- AssetPicker: the three tab labels and the favourite tile badge now
  use IconFolder / IconStar / IconImage.
- PageBuilder: the "Standalone Albums" and "Subpages" headings use
  the icon set instead of an emoji.
- PageBuilder: the layout picker drops its emoji for plain text. An
  <option> cannot contain markup, so an SVG is impossible there and a
  decorative glyph is not a substitute.
- admin.css: align icon and label in the picker tabs, and swap the
  favourite badge's text-shadow for drop-shadow, which is what
  applies to an inline SVG.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>

* refactor(admin): fold PageBuilder's local icons into the shared Icons module (#418)

* refactor(admin): fold PageBuilder's local icons into the shared module

PageBuilder.tsx carried its own `Icons` object duplicating most of the
glyphs already exported by Icons.tsx, with hardcoded sizes and slightly
divergent paths. Migrate all 32 call sites to the shared module and
delete the local object.

Five glyphs had no counterpart and are added to Icons.tsx as 1:1 ports
of the local paths: IconX, IconPlus, IconHome, IconCopy, IconImage.
The local ExternalLink and Check are dropped rather than ported — both
had zero call sites.

Two glyphs change shape slightly, which is the point of consolidating:
the shared IconCamera includes the viewfinder bump the local copy
omitted, and drag handles now use IconGripVertical.

IconGripVertical uses the module's square 24x24 viewBox, so `.svg-drag`
goes from 12x18 to 18x18 — the old non-square box would letterbox the
glyph down to 12x12 and shrink the handle.

* fix(admin): resolve icon-module integration after #416

Merging dev brought in #416, which added a second IconImage to Icons.tsx
and two <Icons.Camera>/<Icons.Folder> section headers that reference the
local Icons object this PR removes. Git merged both cleanly but the result
did not type-check.

- drop the duplicate IconImage (both copies were byte-identical)
- point the two section headers at the imported IconCamera/IconFolder
- refresh the SORT_LABELS comment: the icon set is imported now, not
  declared below

---------

Co-authored-by: ralksta <ralksta@users.noreply.github.com>

* fix(config): allow an empty gallery, guard against a double /api suffix (#421)

An empty gallery is now a valid, rendered state instead of a throw: deriveGallery() no longer requires at least one album or subpage, so a deployment with no albums yet renders a bare homepage the owner can fill in via /admin.

getConfig() also stops appending /api to an Immich URL that already ends in it, which previously produced .../api/api and broke every upstream request.

Includes a restore of the per-album sort test cases, which the branch had lost by being cut before #408/#414.

* feat(admin): favicon upload, served from the content volume (#422)

Adds a bundled default favicon, an upload widget in admin Settings > General, and a route that serves the icon from the writable content/ volume with a fallback to the bundled default. Raster uploads (PNG/ICO/JPEG) are wrapped in an SVG container; the response carries its own CSP so an uploaded SVG cannot execute script on the origin.

The GET route revalidates with an ETag instead of caching immutably, so a newly uploaded icon shows up immediately. Uploads are written via temp file + rename, and a Reset button restores the bundled default.

* ci: flag unformatted files in a PR, without blocking it (#424)

Prettier is configured as an error rule in eslint.config.mjs but has never run in CI, so part of the tree predates it. A final CI step now diffs against the PR base, runs prettier --list-different over the changed files, and emits a warning annotation per offender plus a job summary.

Advisory by design: it never fails the job. Blocking would turn a PR red for merely touching a file that was already unformatted, and normalising the tree in one commit would wreck git blame and conflict with the PRs in flight.

Requires fetch-depth: 0, since diffing against the base needs its history.

* feat(install): first-run wizard gated by a one-time setup token (#419)

Adds /install, a four-step first-run wizard: connect to Immich, optionally pick albums, name the site, finish. It verifies the credentials against the Immich server before writing anything, then writes gallery.yaml, settings.yaml and a content/install.json carrying the Immich credentials and a generated site secret.

install.json exists because a running process cannot pick up new env vars — the wizard has to write configuration that takes effect without a restart. getInstallCredentials() merges it under the real environment, so env vars always win and rotation stays a matter of setting one.

Both the page and the API routes are gated by a one-time setup token printed to the server log, so a deployment that is reachable before gallery.yaml exists cannot be configured by whoever finds it first. The token is stored in content/.setup-token (0600) rather than a module variable: Next.js bundles the page and each route handler separately, so a module-level token left the page and the API disagreeing inside one process and the wizard stuck on step 1. It is removed once the install completes.

The admin password is stored as an scrypt hash using the scheme lib/auth.ts already applies to album passwords; a plaintext ADMIN_PASSWORD env var keeps working.

* docs: document the setup wizard, fix the read-only content mount (#425)

Quick Start now leads with the /install wizard, with the hand-written YAML route kept alongside it, and a First-Run Setup section covers the setup token, the files the wizard writes, and env-var precedence.

Two corrections: both Docker examples mounted content/ as :ro, which silently breaks the wizard, the admin panel and the backup rotation alike — docs/admin-panel.md already said so and the README contradicted it. And nothing documented that content/install.json holds the Immich API key, so a backup of content/ is a backup of credentials.

Also adds a Contributors section crediting the people whose work is in the project.

* feat(admin): floating save bar pinned to the bottom of the viewport (#426)

The save bar was the first, static element inside .admin-main. Since the
document itself scrolls, it left the viewport as soon as you scrolled down
— editing a subpage section or a settings block far below gave no visible
dirty hint and no reachable save button.

Replace it with a bottom-pinned floating bar shared by both editors. It
only mounts while there is something to act on (unsaved changes, an
in-flight save, or a result message), so it never covers content while
idle. The success message clears after 5s, which hides the bar again.

- new SaveBar component, replacing the duplicated markup in PageBuilder
  and SettingsEditor
- adopt the previously unused .floating-save-bar CSS: slide-in keyframes
  (carrying translateX(-50%)), dirty border, wrap/gap, mobile variant and
  a prefers-reduced-motion opt-out; z-index 900 keeps it below modals
- .admin-main gains bottom padding so the bar never covers page content
- drop the now-unreachable idle hints: the ⌘S hint becomes a button title,
  the Live Sync note becomes a static line above the settings layout
- header "Site" link now bypasses the cache (/?fresh=1), so the preview
  stays reachable when the bar is hidden

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(admin): themed listbox for the album sort control (#427)

The per-album "Photo order" control was a native <select>. Because an
<option> cannot contain markup, its choices could not use the admin
panel's currentColor SVG set — the reason #415 had to fall back to plain
text after dropping the emoji labels.

Adds a Listbox component implementing the ARIA combobox/listbox pattern,
so options can render a glyph beside their label:

- DOM focus stays on the trigger button; the active option is announced
  through aria-activedescendant, keeping focus management to one element
- Keyboard: arrows (clamped at the ends, like a native select),
  Home/End, Enter/Space to commit, Escape to cancel, Tab commits and
  moves on, and prefix type-ahead with a repeat-key cycle
- Outside dismissal on pointerdown, so a press starting outside closes
  the popup before the click retargets

The sort options now carry an icon each: calendar, arrow-down, arrow-up,
an A→Z marker, and the drag glyph for manual — matching the badge the
album card already shows. SORT_LABELS stays plain text because the badge
feeds it to a title attribute.

Closes #417

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(git): ignore generated design handoff folders

* fix(admin): stop the album sort dropdown clipping, and simplify the panel (#428)

* fix(admin): render listbox popup in a portal so it escapes modal clipping

The sort control's popup was position:absolute inside three clipping ancestors
(.album-drawer overflow:hidden > .album-drawer-body overflow-y:auto >
.modal-right-column overflow-y:auto), so it was cut off at the bottom of the
Edit Album Details modal. z-index could not help: clipping happens before
stacking. It also always hung below the trigger, with no flip.

Portal the popup to document.body and position it from the trigger's viewport
rect, flipping above when there is more room there and capping max-height to the
space available so it scrolls internally rather than overflowing. It is
dismissed on scroll and resize, since the anchor is only measured on open.

The outside-pointerdown handler now also treats the popup as inside; without
that the portalled list counts as outside, and a click on an option would close
it before the selection commits.

* refactor(admin): single-column album details panel

The left column spent 1.2fr on a cover thumbnail and three stat rows, two of
which (Status, Custom Hero) only restated the form fields opposite them, while
the form itself was squeezed into 1.8fr behind a second nested scroller.

Stack the drawer in one column instead: cover as a banner, then the form at full
width, with the UUID moved into the footer. The body is now the only scroll
container, which also removes one of the ancestors that was clipping the sort
popup.

---------

Co-authored-by: ralksta <ralksta@users.noreply.github.com>

* fix(admin): give the portalled listbox its theme back, lock the page behind modals (#429)

Two defects in the album editor.

The sort listbox popup painted transparent. Every --admin-* variable is
scoped to .admin-layout, and since the popup moved into document.body it
sits outside that subtree, so background/border/text all resolved to
nothing. It now carries its own copy of the palette in both colour
schemes, plus the font it no longer inherits.

Scrolling inside a modal also moved the page behind it. No admin modal
ever locked body scroll: the overlay covers the page but does not absorb
wheel events, so a scroll starting on the backdrop — or continuing past
the end of the modal's own scroller — reaches the document.
overscroll-behavior cannot cover that case on its own, because it only
applies to scroll containers and the backdrop is not one.

useScrollLock freezes body while a modal is open and compensates for the
width the scrollbar gives up, so nothing shifts underneath. Each lock
restores the inline value it found, which makes nesting work without a
counter — a picker opened from the drawer restores the drawer's hidden
state instead of clearing it. Applied to both drawers and all four
picker modals, which share the defect. overscroll-behavior: contain on
the scrollers stops the chaining they can handle themselves.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* fix(security): allow unsafe-eval in CSP script-src during dev mode

* feat(journal): add Journal Studio with split-screen editor, live preview and dedicated routes

* fix(build): separate client parser from server journal-service and fix build type errors

* fix(journal): Fotos rendern, Layout und Lightbox-Steuerung korrigieren

Fünf unabhängige Fehler in der öffentlichen Journal- und Essay-Ansicht:

* Foto-Blöcke wurden nie angezeigt. EssayView löst ein Foto über
  PhotoItem.id auf, und das sind verschlüsselte Tokens — die Blöcke aus
  dem Markdown tragen aber rohe Asset-UUIDs. Jede Zuordnung lief ins
  Leere, und nicht auflösbare Blöcke werden still verworfen. Die IDs
  werden jetzt serverseitig übersetzt; damit verschwinden nebenbei die
  rohen UUIDs aus dem Client-Payload, die dort laut Projektregel nie
  auftauchen dürfen. Nicht auflösbare Referenzen werden geloggt.

* Überschriften standen weiter links als der Fließtext. Jeder Block
  hatte einzeln `max-width: 68ch`, und `ch` ist relativ zur Schrift des
  Elements — die Serif-Überschrift ergab eine breitere Spalte. Ersetzt
  durch eine gemeinsame, font-unabhängige `--essay-measure`.

* Fullbleed-Fotos bluteten nur nach links aus: `.essay-figure` ist
  `width: 100%`, wodurch die Box überbestimmt ist und der negative
  rechte Margin verworfen wird.

* Foto-Paare stellten beide Bilder gleich breit dar, wodurch ein
  Hochformat neben einem Querformat doppelt so hoch wurde. Jetzt eine
  Justified-Reihe: Breite proportional zum Seitenverhältnis, dadurch
  exakt gleiche Höhen ohne Beschnitt.

* Die Lightbox hatte im Journal keine Tastatursteuerung und keine
  Scroll-Sperre — beides lag in PhotoGrid, also nur im Album-Raster.
  Verlagert in die Lightbox selbst, der doppelte Handler in PhotoGrid
  entfernt (sonst wäre pro Pfeildruck zwei Bilder weitergesprungen).

Zusätzlich sind Proofing-Herzen und das EXIF-Panel im redaktionellen
Modus abschaltbar und im Journal aus: Client-Proofing ist ein
Übergabe-Workflow für Alben, keine Funktion einer Reportage. Auf der
Übersicht wurde der Untertitel doppelt gerendert, weil extractExcerpt()
auf ihn zurückfällt.

* feat(admin): eigene URLs für alle Bereiche und überarbeiteter Journal Studio

Das Panel war eine einzige Client-Komponente, die ihre Tabs über
useState umschaltet: keine Route pro Bereich, kein Deep-Link, kein
Zurück-Button, und nach jedem Reload landete man wieder auf "Pages".
Auch der Journal-Editor hatte keine eigene URL.

Jetzt sieben echte Routen (/admin, /admin/pages, /admin/journal,
/admin/journal/<slug>, /admin/settings, /admin/settings/<section>,
/admin/analytics). Die Shell mit Auth-Prüfung und Kopfzeile sitzt im
Layout und umschließt children — so bleibt die Session-Prüfung über
Routenwechsel montiert, statt bei jedem Tab-Wechsel neu zu laufen und
den Spinner aufblitzen zu lassen. Unbekannte Settings-Sections fallen
auf General zurück.

Im selben Zug der Journal Studio, der die Routing-Änderung ohnehin
berührt:

* Alle Eingabefelder nutzten die Klasse `admin-input`, die in keinem
  CSS definiert war — sie fielen auf Browser-Defaults zurück. Jetzt
  gestylt, gescoped, damit der generische Name nicht ins übrige Panel
  leckt.
* Der Split View ist per Divider verschiebbar (Maus, Tastatur,
  Doppelklick zum Zurücksetzen), Breite in localStorage.
* Das Studio bricht aus der 1120px-Spalte aus, die Preview hat Platz.
* Die Preview zeigte für jedes Foto fest 3:2 und log damit über das
  Layout der veröffentlichten Seite; die echten Verhältnisse werden
  jetzt an den Thumbnails gemessen.
* Blöcke mit alten positionsbasierten Foto-Referenzen werden markiert —
  die lassen sich auf einer eigenständigen Journal-Seite nicht auflösen
  und verschwanden bisher stillschweigend.
* Blocktyp-Chips als gemeinsame Komponente, monochrom und per Icon
  unterschieden statt in einer eigenen Blau/Lila/Orange-Palette, die
  sonst nirgends im Panel vorkommt.
* Emojis raus, SVG-Icons rein.

* fix(admin): Designsystem-Lücken im Panel schließen

Eine systematische Suche nach Klassen, die im TSX benutzt, aber in
keinem CSS definiert sind, hat vier Stellen mit demselben Muster
gefunden:

* `admin-btn-secondary` und `admin-btn-danger` existierten nicht.
  Sämtliche Löschen-Buttons sahen aus wie normale Buttons — keine
  Warnwirkung. Als `.admin-btn.admin-btn-danger` geschrieben, weil die
  Varianten mit den Größenklassen kombiniert werden, die weiter unten
  ihren eigenen Hintergrund setzen.
* `page-progress-fill` fehlte: die Balken im Analytics-Panel waren
  leere Rinnen, der Wert unsichtbar. Ebenso `analytics-empty` und
  `admin-loading-container`.
* `subpage-drawer-section`, `subpage-drawer-title-group` und
  `input-with-icon` im PageBuilder waren wirkungslos und teils mit
  Inline-Styles notdürftig kompensiert.
* `grid-card-preview` fehlte, wodurch alle Layout-Vorschauen auf Höhe
  null kollabierten. Nur "Showcase" war sichtbar — und das aus Versehen,
  weil sein Tile `hero-tile` hieß und damit die `aspect-ratio` einer
  fremden PageBuilder-Klasse erbte. Umbenannt.

Dazu die Theme-Vorschauen, die praktisch identisch aussahen: alle
sieben zeigten dieselben drei quadratischen Kacheln, einziger
Unterschied war die Hintergrundfarbe. Sie spiegeln jetzt die echten
Preset-Daten aus lib/config/theme.ts — Schriftcharakter, Eckradius,
Rasterdichte, Passepartout bzw. Schatten.

Die Kopfzeile richtet sich an einer gemeinsamen Steuerhöhe aus. Der
"Site"-Link war höher als die Buttons daneben: `.admin-btn` hatte keine
explizite line-height, und <button> bekommt box-sizing: border-box vom
Browser, <a> nicht. Die Statusanzeige setzte weder Schriftfamilie noch
-größe und fiel auf den Browser-Default zurück — sie war nie Teil des
Designsystems. Jetzt gleiche Höhe und Typografie, Pillenform als
Zustandsanzeige, Trenner zur Aktionsgruppe. Das dauerhafte Pulsieren
des grünen Punkts entfällt; Animation bleibt den Zuständen vorbehalten,
die Aufmerksamkeit brauchen.

Restliche Emojis durch SVG-Icons ersetzt.

* feat(admin): add scroll-to-top toggle and SVG arrow

The back-to-top button was always on and drew its arrow with the ↑ text
character. Add a `scrollToTop` setting (General section in the admin
panel, defaults to on so existing sites are unaffected) and replace the
glyph with a stroked SVG that inherits currentColor across all presets.

Scroll handling is now rAF-throttled, and prefers-reduced-motion turns
off both the hover lift and the smooth scroll.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* security(journal): escape author HTML instead of filtering it

CodeQL flags 26 high-severity alerts on the release PR; the bulk of them
point at sanitizeHtml(), a denylist of three regexes whose output goes
into dangerouslySetInnerHTML. I reproduced the bypasses before changing
anything — all four pass the old filter:

  <img src=x onerror=alert(1)>        unquoted handler, regex wants quotes
  <img src=x onerror='alert(1)'>      single quotes, same reason
  <svg onload=alert(1)>               not a <script> tag
  javasjavascript:cript:alert(1)      one-pass replace, the rest recombines

Plus an attribute breakout in the link renderer, which interpolated the
URL into href="${url}" unescaped:

  [x](" onmouseover=alert(1) x=")  ->  <a href="" onmouseover=alert(1" ...>

Replaced with escaping. Every `&<>"'` in author text becomes an entity
before any markdown rule runs, so the only tags in the output are the
ones renderInlineMarkdown builds itself and a URL cannot leave its
attribute. Link schemes are now an allowlist (http, https, mailto, tel,
relative, anchor); anything else renders as plain text.

The serializer needed decodeHtmlEntities to match: without it a save
would write `&lt;` into the Markdown file and the next parse would
escape the `&` again, corrupting the text further on every round trip.
A test covers parse -> serialize -> parse stability.

Two existing tests asserted the old behaviour and were rewritten rather
than deleted: one expected the script tag to be *removed* from the
output, the other expected the substring "onerror" to be absent. Both
now assert the property that matters — that no tag can form — because
`onerror` surviving as inert text is fine.

Exploitation required admin access either way: journal and essay text
comes from the studio or from content/*.md. This removes the weakness,
it does not close an open door.

* fix(journal): contain file paths, fix frontmatter escaping, defuse two regexes

Follow-up to the CodeQL findings on release PR #432. I went through all 23
alerts individually; this addresses the ones that are worth addressing and
documents the ones that are not.

Path containment (12 alerts, all false positives). Every path built from a
slug goes through isValidSlug(), a strict `/^[a-zA-Z0-9_-]+$/` allowlist —
verified against `../../etc/passwd`, `foo/../../bar`, `a/b`, `..` and
friends, all rejected. CodeQL cannot see it because the check lives in
another module. Added a containedPath() helper that resolves the path and
refuses anything landing outside the content directory: a second lock on a
door that was already locked, and a barrier the analysis can follow. Also
removed the dead `slug.endsWith('.md')` branches — isValidSlug rejects
dots, so they could never be taken.

Frontmatter escaping (1 alert, a real bug). The serializer escaped `"` but
not `\`, and the parser never unescaped anything. A title containing either
character gained a backslash on every save/load cycle:

  Path C:\Users "quoted"  ->  Path C:\\Users \"quoted\"  ->  ...

Escaping now covers the backslash first and the parser undoes both. A round
trip test covers quotes, backslashes, colons and apostrophes.

Two of three ReDoS regexes (2 alerts). The heading pattern had `\s+` next to
`(.+)`, which overlap, so the engine tried every split of the whitespace run
before failing; it is `[ \t]+` and `(\S.*)` now. The quote author pattern
wrapped a lazy group around an optional group — the quadratic case — and is
an index split on the first separator now.

The third regex, the bold/italic pass, is deliberately left alone. Rewriting
it with a negated class removes the backtracking but breaks nesting:
`**bold *and italic* here**` renders as `*<em>bold </em>and italic<em> here</em>*`.
The input is Markdown from an authenticated admin, never a visitor, so the
worst case is an author slowing down their own page. The comment in the code
says so.

Not addressed: 5 js/insufficient-password-hash alerts. They ask for a slow
KDF where the code uses SHA-256/HMAC — correct in general, but the admin
password comes from an environment variable and is never stored, so a
stronger KDF protects nothing that is not already in plaintext in the
environment.

399 unit tests pass (18 new), build and tsc clean.

* fix(journal): split the quote author by scanning, not by pattern

Cleaning up after myself. #439 replaced the quote author regex
`/^(.*?)(?:\s+--\s+(.+))?$/` — a lazy group around an optional one, the
quadratic case — with `/\s+--\s+/`, and CodeQL promptly flagged the
replacement for the same reason. One reported pattern traded for another.

splitQuoteAuthor() scans for the first `--` that has whitespace on both
sides. Linear, and it needs no reasoning about the regex engine at all.

Behaviour is identical to the original regex, checked case by case
against it: separator, no separator, several separators, tabs, wide gaps,
`a--b` without spaces, leading and trailing separators, empty string. All
nine are covered by tests, plus one asserting it stays fast on a 50k
whitespace run.

* security(admin): derive the session signing key with scrypt

getSigningKey() ran the admin password through a single SHA-256 digest.
It is key derivation rather than password storage, so it was never a
stored-hash problem — but if the derived key ever leaked, one fast hash
makes recovering the password by brute force cheap. CodeQL flags it as
js/insufficient-password-hash and, for this particular alert, has a
point.

scrypt now. Two details that matter:

The salt has to be stable. A random salt would produce a different key on
every call and invalidate every session; it is derived from AUTH_SECRET,
which is deployment-specific. Verified across separate processes: same
inputs produce a verifying token, so a restart or redeploy does not log
everyone out.

The result is cached for the process lifetime. scrypt is deliberately
slow and getSigningKey() runs on every admin request — deriving per call
would add ~24ms to each one. The cache key is a digest of secret plus
password, so a rotation misses the cache and derives again, and no extra
plaintext copy of the password is kept around.

Measured: first derivation 24ms, subsequent calls 0.12ms. Password
change and secret change both invalidate an existing token, checked in
separate processes.

Note the one-time effect: existing admin sessions are invalidated by the
change in derivation, so everyone logs in once more.

* security(admin): key the signing-key cache on its inputs, not a digest

#441 removed the SHA-256 digest of the admin password from the key
derivation and introduced a new one three lines above it, as the cache
key. Same rule, same file: CodeQL reported it immediately.

The comment justifying it was wrong too. It claimed no second plaintext
copy of the password was retained, while building the digest input
allocates exactly that in order to hash it.

The cache now holds the two input strings and compares them directly.
They are the same objects the env and install caches already hold, so
nothing extra is retained, and no fast hash of the password exists in
memory for the life of the process.

Re-verified after the change, in separate processes: a token from one
process verifies in another with the same inputs, a changed password or
secret rejects it, first derivation 24ms, cached calls 0.001ms.

That leaves scrypt as the only place the password is hashed here. The
two HMACs further down operate on the derived key and on token data, not
on the password; the constant-time comparison in verifyAdminPassword is
the previously dismissed one.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com>
This commit is contained in:
Ralksta
2026-08-14 16:55:07 +02:00
committed by GitHub
parent d4d8c8b42f
commit 2fe1157a5d
79 changed files with 7878 additions and 987 deletions

View File

@@ -22,6 +22,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
with:
# The formatting step diffs against the PR's base, which needs the
# base branch's history — the default shallow clone has none of it.
fetch-depth: 0
- name: Set up Node.js - name: Set up Node.js
uses: actions/setup-node@v7 uses: actions/setup-node@v7
@@ -45,3 +49,42 @@ jobs:
IMMICH_API_URL: http://localhost:2283 IMMICH_API_URL: http://localhost:2283
IMMICH_API_KEY: placeholder-key-for-ci IMMICH_API_KEY: placeholder-key-for-ci
AUTH_SECRET: placeholder-secret-for-ci-builds-must-be-32-chars-long AUTH_SECRET: placeholder-secret-for-ci-builds-must-be-32-chars-long
# Advisory only — this step never fails the job.
#
# Prettier is configured as an eslint error but has never been run in CI,
# so a chunk of the tree predates it. Blocking on that would make a PR red
# for merely touching an old file, and reformatting the tree wholesale
# would bury every future diff in unrelated churn. Annotating the files a
# PR already changes puts the information in front of the author without
# putting a gate in the way. Runs last so real failures surface first.
- name: Formatting – changed files (advisory)
if: github.event_name == 'pull_request'
continue-on-error: true
run: |
files=$(git diff --name-only --diff-filter=d \
"${{ github.event.pull_request.base.sha }}...HEAD" \
-- '*.ts' '*.tsx' '*.js' '*.mjs' '*.css' '*.json' '*.md' '*.yml' '*.yaml')
if [ -z "$files" ]; then
echo "No formattable files changed."
exit 0
fi
# --list-different prints only the offenders and exits non-zero when
# there are any; `|| true` keeps that from ending the step.
unformatted=$(echo "$files" | xargs -d '\n' npx prettier --list-different || true)
if [ -z "$unformatted" ]; then
echo "All changed files match Prettier's style."
exit 0
fi
count=$(echo "$unformatted" | wc -l)
echo "### Prettier: $count changed file(s) not formatted" >> "$GITHUB_STEP_SUMMARY"
echo '' >> "$GITHUB_STEP_SUMMARY"
while IFS= read -r f; do
echo "::warning file=$f::Not formatted. Run: npx prettier --write $f"
echo "- \`$f\`" >> "$GITHUB_STEP_SUMMARY"
done <<< "$unformatted"
echo '' >> "$GITHUB_STEP_SUMMARY"
echo 'Advisory only — this does not block the merge.' >> "$GITHUB_STEP_SUMMARY"

7
.gitignore vendored
View File

@@ -68,7 +68,12 @@ content/about.md
content/.backups/ content/.backups/
content/analytics.json content/analytics.json
content/*.screenshot-bak content/*.screenshot-bak
# Credentials written by the /install wizard (never committed)
content/install.json
# One-time setup token, written on first access and removed once install completes
content/.setup-token
# ── Internal Dev Docs ──────────────────────────────── # ── Internal Dev Docs ────────────────────────────────
docs/dev/ docs/dev/
docs/ideas.md docs/ideas.md
/design_handoff_*/

View File

@@ -9,6 +9,44 @@ Releases up to and including v0.9.2 are documented in the
## [Unreleased] ## [Unreleased]
### Added
- **First-run setup wizard at `/install`**
([#419](https://github.com/ralksta/immich-folio/pull/419)). A fresh deployment
can now be configured from the browser: connect to Immich, optionally pick
albums, name the site. Credentials are verified against the Immich server
before anything is written, so a typo cannot produce an "installed" site that
loads no photos. The wizard is gated by a one-time token printed to the server
log — a deployment is reachable before it has any configuration, and without
the gate whoever found the URL first could configure it. Credentials land in
`content/install.json` (mode `0600`, admin password stored as an scrypt hash);
environment variables continue to take precedence, so rotation still works by
setting a variable. Configuring everything by hand remains fully supported.
- **Custom favicon upload** in admin Settings › General
([#422](https://github.com/ralksta/immich-folio/pull/422)). SVG, PNG, ICO or
JPEG, stored in the writable `content/` volume and served through
`/api/favicon` with a policy that stops an uploaded SVG executing script. A
Reset button restores the bundled default.
### Changed
- **A gallery with no albums is now a valid, rendered state**
([#421](https://github.com/ralksta/immich-folio/pull/421)) instead of an error
— the setup wizard can finish without picking one, and albums can be added
later in `/admin`.
- **The Immich URL may end in `/api`** without breaking every request
([#421](https://github.com/ralksta/immich-folio/pull/421)). The suffix was
appended unconditionally, producing `.../api/api`.
### Documentation
- **README documents the setup wizard**, what it writes, and that
`content/install.json` holds credentials — so a backup of `content/` is
understood to include your Immich API key. The Docker examples no longer mount
`content/` read-only: the wizard, the admin panel and the backup rotation all
write into it, and `:ro` silently breaks all three.
- **Contributors are credited in the README.**
### Security ### Security
- **Next.js 16.3.0** — picks up the fix for CVE-2025-13465 in Next's vendored - **Next.js 16.3.0** — picks up the fix for CVE-2025-13465 in Next's vendored
@@ -18,6 +56,13 @@ Releases up to and including v0.9.2 are documented in the
Nothing user-facing; recorded so the next release notes are complete. Nothing user-facing; recorded so the next release notes are complete.
- **CI annotates unformatted files in a PR without blocking it**
([#424](https://github.com/ralksta/immich-folio/pull/424)). Prettier is
configured as an eslint error but had never run in CI, so part of the tree
predates it. Failing on that would make a PR red for merely touching an old
file; reformatting the tree in one commit would bury every future diff in
churn. The check runs over the files a PR changes and warns.
- **Dependency PRs now target `dev`**, and CI runs on pull requests to `dev` as - **Dependency PRs now target `dev`**, and CI runs on pull requests to `dev` as
well ([#411](https://github.com/ralksta/immich-folio/pull/411)). The workflow well ([#411](https://github.com/ralksta/immich-folio/pull/411)). The workflow
previously triggered on `main` only, so a PR against `dev` carried no checks previously triggered on `main` only, so a PR against `dev` carried no checks

103
README.md
View File

@@ -128,22 +128,85 @@ Full history in the [GitHub releases](https://github.com/ralksta/immich-folio/re
## Quick Start ## Quick Start
```bash ```bash
# Clone and install
git clone https://github.com/ralksta/immich-folio.git git clone https://github.com/ralksta/immich-folio.git
cd immich-folio cd immich-folio
npm install npm install
npm run dev
```
# Configure Then open `http://localhost:3000/install` and let the setup wizard connect you to
Immich — see [First-Run Setup](#first-run-setup) below. It needs a token from the
server log, which is printed on first access.
<details>
<summary><strong>Prefer to configure by hand?</strong></summary>
The wizard writes the same files you would write yourself, so the manual route
remains fully supported:
```bash
cp .env.local.example .env.local cp .env.local.example .env.local
# Edit .env.local with your Immich server URL and API key # Edit .env.local with your Immich server URL and API key
cp content/gallery.yaml.example content/gallery.yaml cp content/gallery.yaml.example content/gallery.yaml
# Edit gallery.yaml with your album UUIDs # Edit gallery.yaml with your album UUIDs
# Run
npm run dev npm run dev
``` ```
</details>
## First-Run Setup
A deployment with no `gallery.yaml` and no Immich credentials serves a setup
screen. The wizard at **`/install`** fills both in from the browser: it connects
to Immich, lets you pick albums (optional — you can add them later in `/admin`),
and names the site. Nothing is written until your credentials have been verified
against your Immich server, so a typo cannot leave you with an "installed" site
that loads no photos.
**The wizard is gated by a one-time token** printed to the server log on first
access, because a fresh deployment is reachable before it has any configuration —
and without the gate, whoever finds the URL first could configure it:
```
══════════════════════════════════════════════════════
Immich Folio — First-run setup token
══════════════════════════════════════════════════════
Token: PTmUKFIdce2DwuqBG71RAExH7tVxceXX
```
Read it from your container logs (`docker compose logs immich-folio`) and append
it to the URL:
```
http://your-site/install?token=PTmUKFIdce2DwuqBG71RAExH7tVxceXX
```
The token is stored in `content/.setup-token` (mode `0600`) so it survives a
restart, and is deleted once setup completes. From then on `/install` redirects
to the gallery and its API routes refuse to run again.
### What the wizard writes
| File | Contents |
| ----------------------- | -------------------------------------------------------------------- |
| `content/gallery.yaml` | The albums you picked |
| `content/settings.yaml` | Site title, subtitle, theme — only if it does not exist yet |
| `content/install.json` | Immich URL and API key, a generated site secret, admin password hash |
> **`content/install.json` holds credentials.** It is written with mode `0600`,
> and it is the reason a backup of your `content/` directory is now a backup of
> your Immich API key as well — treat it accordingly. The admin password is
> stored as an scrypt hash, not as you typed it; the API key and site secret have
> to stay readable to be usable.
**Environment variables always win.** `IMMICH_API_URL`, `IMMICH_API_KEY`,
`AUTH_SECRET` and `ADMIN_PASSWORD` override anything in `install.json`, so you
can rotate any of them by setting the variable — no need to touch the file. Set
all of them up front and the wizard never appears, which is the usual choice for
an infrastructure-as-code deployment.
## Configuration ## Configuration
### Environment Variables (`.env.local`) ### Environment Variables (`.env.local`)
@@ -213,7 +276,7 @@ services:
env_file: env_file:
- .env.local - .env.local
volumes: volumes:
- ./content:/app/content:ro - ./content:/app/content
``` ```
Run with: Run with:
@@ -239,11 +302,14 @@ docker run -d \
--restart unless-stopped \ --restart unless-stopped \
-p 7211:7211 \ -p 7211:7211 \
--env-file .env.local \ --env-file .env.local \
-v ./content:/app/content:ro \ -v ./content:/app/content \
immich-folio immich-folio
``` ```
> **Note:** The `content/` volume mount lets you update `gallery.yaml` and `about.md` without rebuilding the image. > **Note:** The `content/` volume mount lets you update `gallery.yaml` and
> `about.md` without rebuilding the image. It must be **read-write**: the setup
> wizard, the admin panel and the backup rotation all write into it. A `:ro`
> mount leaves the wizard unable to complete and the admin panel unable to save.
### Health Check ### Health Check
@@ -285,6 +351,10 @@ A built-in visual editor at `/admin` lets you manage your gallery without editin
ADMIN_PASSWORD=your-secure-admin-password ADMIN_PASSWORD=your-secure-admin-password
``` ```
Or set the password in the [setup wizard](#first-run-setup), which stores it as
an scrypt hash rather than in your environment. An `ADMIN_PASSWORD` variable
takes precedence over the stored one if both are present.
Then navigate to `http://your-site/admin` and log in. The panel is protected by its Then navigate to `http://your-site/admin` and log in. The panel is protected by its
own password, separate from any album passwords, and writes straight to own password, separate from any album passwords, and writes straight to
`gallery.yaml` / `settings.yaml` with automatic backups. `gallery.yaml` / `settings.yaml` with automatic backups.
@@ -308,6 +378,27 @@ own password, separate from any album passwords, and writes straight to
- **TypeScript** - **TypeScript**
- **Vanilla CSS** (no framework) - **Vanilla CSS** (no framework)
## Contributors
Immich Folio is maintained by [@ralksta](https://github.com/ralksta) and made
better by the people below. Thank you — every one of these made the project
easier to live with.
- **[@lancetm714](https://github.com/lancetm714)** — built the setup wizard that
turns a fresh install into a few clicks in the browser instead of hand-written
config files. Also added custom favicons, so your portfolio gets its own icon
in the browser tab, and made a gallery with no albums yet a perfectly valid
starting point rather than an error.
- **[Jules](https://jules.google.com)** — an automated reviewer that has been
quietly hardening the project in the background: better screen-reader support
in the photo grid, and a series of fixes keeping the public endpoints from
being overwhelmed by traffic.
- **[Dependabot](https://github.com/dependabot)** — keeps every dependency
current, which is most of the reason security fixes land here quickly.
Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md) to get
started. Pull requests target the `dev` branch.
## License ## License
MIT License — free to use and modify for the Immich community. MIT License — free to use and modify for the Immich community.

View File

@@ -16,9 +16,22 @@ interface EssayViewProps {
title?: string; title?: string;
subtitle?: string; subtitle?: string;
watermark?: LightboxWatermark; watermark?: LightboxWatermark;
/**
* Client proofing — favorite hearts, the selection bar and the send-off modal.
* Off by default: proofing is a delivery workflow for album handovers, and a
* published story is not one. Album views opt in.
*/
proofing?: boolean;
} }
function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayViewProps) { function EssayViewContent({
essay,
assets,
title,
subtitle,
watermark,
proofing: proofingEnabled = false,
}: EssayViewProps) {
const proofing = useProofing(); const proofing = useProofing();
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null); const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
@@ -54,11 +67,7 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
case 'paragraph': case 'paragraph':
return ( return (
<div <div key={idx} className="essay-prose" dangerouslySetInnerHTML={{ __html: block.html }} />
key={idx}
className="essay-prose"
dangerouslySetInnerHTML={{ __html: block.html }}
/>
); );
case 'quote': case 'quote':
@@ -94,8 +103,8 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
block.layout === 'fullbleed' block.layout === 'fullbleed'
? '100vw' ? '100vw'
: block.layout === 'wide' : block.layout === 'wide'
? '(max-width: 1100px) 100vw, 1100px' ? '(max-width: 1100px) 100vw, 1100px'
: '(max-width: 768px) 100vw, 680px' : '(max-width: 768px) 100vw, 680px'
} }
loading={idx < 4 ? 'eager' : 'lazy'} loading={idx < 4 ? 'eager' : 'lazy'}
{...(item.blurDataURL {...(item.blurDataURL
@@ -129,7 +138,14 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))', filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))',
}} }}
> >
<svg viewBox="0 0 24 24" width="24" height="24" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2"> <svg
viewBox="0 0 24 24"
width="24"
height="24"
fill={isFav ? 'currentColor' : 'none'}
stroke="currentColor"
strokeWidth="2"
>
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" /> <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</svg> </svg>
</button> </button>
@@ -164,7 +180,9 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
onClick={() => setLightboxIndex(index)} onClick={() => setLightboxIndex(index)}
style={{ style={{
...(item.dominantColor ? { backgroundColor: item.dominantColor } : {}), ...(item.dominantColor ? { backgroundColor: item.dominantColor } : {}),
...(item.aspectRatio ? { aspectRatio: `${item.aspectRatio}` } : {}), // Width proportional to the ratio — see .essay-pair-grid.
flexGrow: item.aspectRatio ?? 1.5,
aspectRatio: `${item.aspectRatio ?? 1.5}`,
}} }}
> >
<Image <Image
@@ -203,7 +221,14 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))', filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.6))',
}} }}
> >
<svg viewBox="0 0 24 24" width="24" height="24" fill={isFav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2"> <svg
viewBox="0 0 24 24"
width="24"
height="24"
fill={isFav ? 'currentColor' : 'none'}
stroke="currentColor"
strokeWidth="2"
>
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" /> <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
</svg> </svg>
</button> </button>
@@ -294,7 +319,9 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
type="button" type="button"
onClick={() => proofing.setIsFilterActive((prev) => !prev)} onClick={() => proofing.setIsFilterActive((prev) => !prev)}
style={{ style={{
background: proofing.isFilterActive ? 'var(--accent, #e60012)' : 'rgba(255,255,255,0.15)', background: proofing.isFilterActive
? 'var(--accent, #e60012)'
: 'rgba(255,255,255,0.15)',
color: '#fff', color: '#fff',
border: 'none', border: 'none',
padding: '6px 14px', padding: '6px 14px',
@@ -324,16 +351,23 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
</div> </div>
)} )}
<ProofingModal /> {proofingEnabled && <ProofingModal />}
{lightboxIndex !== null && ( {lightboxIndex !== null && (
<Lightbox <Lightbox
assets={assets} assets={assets}
currentIndex={lightboxIndex} currentIndex={lightboxIndex}
onClose={() => setLightboxIndex(null)} onClose={() => setLightboxIndex(null)}
onNext={() => setLightboxIndex((prev) => (prev !== null ? (prev + 1) % assets.length : null))} onNext={() =>
onPrev={() => setLightboxIndex((prev) => (prev !== null ? (prev - 1 + assets.length) % assets.length : null))} setLightboxIndex((prev) => (prev !== null ? (prev + 1) % assets.length : null))
}
onPrev={() =>
setLightboxIndex((prev) =>
prev !== null ? (prev - 1 + assets.length) % assets.length : null,
)
}
watermark={watermark} watermark={watermark}
showExifToggle={false}
/> />
)} )}
</div> </div>
@@ -343,6 +377,12 @@ function EssayViewContent({ essay, assets, title, subtitle, watermark }: EssayVi
export function EssayView(props: EssayViewProps) { export function EssayView(props: EssayViewProps) {
const albumTokens = useMemo(() => props.assets.map((a) => a.id), [props.assets]); const albumTokens = useMemo(() => props.assets.map((a) => a.id), [props.assets]);
// Without the provider useProofing() returns null, and every proofing control
// (hearts in the grid and in the lightbox, selection bar) drops out on its own.
if (!props.proofing) {
return <EssayViewContent {...props} />;
}
return ( return (
<ProofingProvider albumTokens={albumTokens}> <ProofingProvider albumTokens={albumTokens}>
<EssayViewContent {...props} /> <EssayViewContent {...props} />

View File

@@ -116,32 +116,7 @@ function PhotoGridInner({ assets, layout = 'masonry', gridStyle, watermark }: Ph
setLightboxIndex((prev) => (prev !== null ? (prev - 1 + displayedAssets.length) % displayedAssets.length : null)); setLightboxIndex((prev) => (prev !== null ? (prev - 1 + displayedAssets.length) % displayedAssets.length : null));
}, [displayedAssets.length]); }, [displayedAssets.length]);
// Keyboard navigation // Keyboard navigation and the scroll lock live in <Lightbox/>.
useEffect(() => {
if (lightboxIndex === null) return;
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'Escape':
closeLightbox();
break;
case 'ArrowRight':
goNext();
break;
case 'ArrowLeft':
goPrev();
break;
}
};
document.addEventListener('keydown', handleKeyDown);
document.body.style.overflow = 'hidden';
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = '';
};
}, [lightboxIndex, closeLightbox, goNext, goPrev]);
const gridItems = useMemo(() => { const gridItems = useMemo(() => {
return displayedAssets.map((asset, index) => { return displayedAssets.map((asset, index) => {

View File

@@ -1,6 +1,23 @@
/* Photo Essay & Storytelling Mode Styles */ /* Photo Essay & Storytelling Mode Styles */
.essay-container { .essay-container {
/*
* One shared measure for every block, so headings, prose and figures line up
* on the same left edge. Deliberately in rem, not the `68ch` this replaces:
* `ch` is relative to each element's own font, so a serif heading resolved to
* a wider column than the body text and started further left. 40rem matches
* what 68ch produced for the body font. Custom properties are substituted as
* raw tokens, so a `ch` value here would be re-resolved per element and bring
* the bug straight back — keep this font-independent.
*
* `--essay-bleed` / `--essay-wide` are viewport-based by default and get
* overridden where the essay renders inside a narrower box (e.g. the admin
* Journal Studio preview pane).
*/
--essay-measure: 40rem;
--essay-wide: 1100px;
--essay-bleed: 100vw;
width: 100%; width: 100%;
max-width: 100%; max-width: 100%;
margin: 0 auto; margin: 0 auto;
@@ -9,7 +26,7 @@
/* Header & Cover */ /* Header & Cover */
.essay-header { .essay-header {
max-width: 68ch; max-width: var(--essay-measure);
margin: 0 auto 3.5rem auto; margin: 0 auto 3.5rem auto;
text-align: center; text-align: center;
} }
@@ -41,7 +58,7 @@
/* Reading column */ /* Reading column */
.essay-prose { .essay-prose {
max-width: 68ch; max-width: var(--essay-measure);
margin: 0 auto 2.5rem auto; margin: 0 auto 2.5rem auto;
font-family: var(--font-body, sans-serif); font-family: var(--font-body, sans-serif);
font-size: clamp(1.05rem, 2vw, 1.2rem); font-size: clamp(1.05rem, 2vw, 1.2rem);
@@ -55,19 +72,25 @@
.essay-heading { .essay-heading {
font-family: var(--font-heading, serif); font-family: var(--font-heading, serif);
max-width: 68ch; max-width: var(--essay-measure);
margin: 3.5rem auto 1.5rem auto; margin: 3.5rem auto 1.5rem auto;
font-weight: 600; font-weight: 600;
line-height: 1.25; line-height: 1.25;
} }
.essay-heading--1 { font-size: clamp(1.8rem, 3.5vw, 2.5rem); } .essay-heading--1 {
.essay-heading--2 { font-size: clamp(1.5rem, 3vw, 2rem); } font-size: clamp(1.8rem, 3.5vw, 2.5rem);
.essay-heading--3 { font-size: clamp(1.25rem, 2.5vw, 1.6rem); } }
.essay-heading--2 {
font-size: clamp(1.5rem, 3vw, 2rem);
}
.essay-heading--3 {
font-size: clamp(1.25rem, 2.5vw, 1.6rem);
}
/* Pullquote */ /* Pullquote */
.essay-quote { .essay-quote {
max-width: 68ch; max-width: var(--essay-measure);
margin: 3.5rem auto; margin: 3.5rem auto;
padding: 1.5rem 2rem; padding: 1.5rem 2rem;
border-left: 3px solid var(--accent, #e60012); border-left: 3px solid var(--accent, #e60012);
@@ -96,17 +119,23 @@
} }
.essay-figure--contained { .essay-figure--contained {
max-width: 68ch; max-width: var(--essay-measure);
} }
.essay-figure--wide { .essay-figure--wide {
max-width: 1100px; max-width: var(--essay-wide);
} }
/*
* `width` has to be set too, not just max-width: .essay-figure is width: 100%,
* which over-constrains the box so the negative right margin is dropped and only
* the left side bleeds.
*/
.essay-figure--fullbleed { .essay-figure--fullbleed {
max-width: 100vw; width: var(--essay-bleed);
margin-left: calc(-50vw + 50%); max-width: var(--essay-bleed);
margin-right: calc(-50vw + 50%); margin-left: calc(-0.5 * var(--essay-bleed) + 50%);
margin-right: calc(-0.5 * var(--essay-bleed) + 50%);
} }
.essay-image-wrapper { .essay-image-wrapper {
@@ -131,7 +160,7 @@
} }
.essay-figcaption { .essay-figcaption {
max-width: 68ch; max-width: var(--essay-measure);
margin: 0.75rem auto 0 auto; margin: 0.75rem auto 0 auto;
text-align: center; text-align: center;
font-family: var(--font-caption, monospace); font-family: var(--font-caption, monospace);
@@ -140,18 +169,34 @@
} }
/* Side by side photo pair */ /* Side by side photo pair */
/*
* Justified row: each photo keeps its own aspect ratio, and its width is given
* by `flex-grow: <aspect ratio>` (set inline from the asset). Since width ∝ ratio
* and height = width / ratio, both photos end up exactly the same height without
* a single pixel being cropped — a shared baseline instead of one portrait
* towering over a landscape.
*/
.essay-pair-grid { .essay-pair-grid {
display: grid; display: flex;
grid-template-columns: 1fr 1fr;
gap: 1.5rem; gap: 1.5rem;
width: 100%; width: 100%;
max-width: 1100px; max-width: var(--essay-wide);
margin: 3.5rem auto; margin: 3.5rem auto;
} }
.essay-pair-grid > .essay-image-wrapper {
flex-basis: 0;
min-width: 0;
}
@media (max-width: 640px) { @media (max-width: 640px) {
/* Stacked: full width each, height from the photo's own ratio. */
.essay-pair-grid { .essay-pair-grid {
grid-template-columns: 1fr; flex-direction: column;
gap: 1.5rem; gap: 1.5rem;
} }
.essay-pair-grid > .essay-image-wrapper {
flex: none;
}
} }

View File

@@ -32,7 +32,8 @@ import { AdminDiagnosticBanner } from '@/components/AdminDiagnosticBanner';
import { AlbumDetailView } from './AlbumDetailView'; import { AlbumDetailView } from './AlbumDetailView';
import { SubpageGridView } from './SubpageGridView'; import { SubpageGridView } from './SubpageGridView';
import { EssayView } from './EssayView'; import { EssayView } from './EssayView';
import { parseEssayMarkdown, loadEssayFromFile } from '@/lib/essay'; import { parseEssayMarkdown } from '@/lib/essay';
import { loadEssayFromFile } from '@/lib/admin/journal-service';
// Render at request time — requires live Immich connection // Render at request time — requires live Immich connection
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';

58
app/admin/AdminShell.tsx Normal file
View File

@@ -0,0 +1,58 @@
'use client';
import { useState, useEffect, type ReactNode } from 'react';
import AdminLogin from './components/AdminLogin';
import AdminDashboard from './components/AdminDashboard';
import './admin.css';
/**
* Auth gate and panel chrome for every /admin route. Lives in the admin layout
* rather than in each page, so navigating between tabs keeps the session check
* and the header mounted instead of re-running them per route.
*/
export default function AdminShell({ children }: { children: ReactNode }) {
const [authenticated, setAuthenticated] = useState<boolean | null>(null);
const [enabled, setEnabled] = useState(true);
useEffect(() => {
async function checkAuth() {
try {
const res = await fetch('/api/admin/auth');
const data = await res.json();
setAuthenticated(data.authenticated);
setEnabled(data.enabled);
} catch {
setAuthenticated(false);
}
}
checkAuth();
}, []);
if (authenticated === null) {
return (
<div className="admin-loading">
<div className="admin-spinner" />
</div>
);
}
if (!enabled) {
return (
<div className="admin-disabled">
<div className="admin-disabled-card">
<h1>Admin Panel</h1>
<p>
The admin panel is not enabled. Set <code>ADMIN_PASSWORD</code> in your environment
variables to activate it.
</p>
</div>
</div>
);
}
if (!authenticated) {
return <AdminLogin onSuccess={() => setAuthenticated(true)} />;
}
return <AdminDashboard onLogout={() => setAuthenticated(false)}>{children}</AdminDashboard>;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
import AnalyticsView from '../components/AnalyticsView';
export default function AdminAnalyticsPage() {
return <AnalyticsView />;
}

View File

@@ -1,20 +1,26 @@
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect, type ReactNode } from 'react';
import PageBuilder from './PageBuilder'; import Link from 'next/link';
import SettingsEditor from './SettingsEditor'; import { usePathname } from 'next/navigation';
import AnalyticsView from './AnalyticsView';
import BackupManagerModal from './BackupManagerModal'; import BackupManagerModal from './BackupManagerModal';
import * as Icons from './Icons'; import * as Icons from './Icons';
interface Props { interface Props {
onLogout: () => void; onLogout: () => void;
/** The active route's panel — Pages, Journal Studio, Settings or Analytics. */
children: ReactNode;
} }
type Tab = 'pages' | 'settings' | 'analytics'; const TABS = [
{ label: 'Pages', href: '/admin/pages', match: /^\/admin(\/pages)?$/ },
{ label: 'Journal', href: '/admin/journal', match: /^\/admin\/journal/ },
{ label: 'Settings', href: '/admin/settings', match: /^\/admin\/settings/ },
{ label: 'Analytics', href: '/admin/analytics', match: /^\/admin\/analytics/ },
];
export default function AdminDashboard({ onLogout }: Props) { export default function AdminDashboard({ onLogout, children }: Props) {
const [activeTab, setActiveTab] = useState<Tab>('pages'); const pathname = usePathname();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
// Diagnostics & Backup state // Diagnostics & Backup state
@@ -91,24 +97,15 @@ export default function AdminDashboard({ onLogout }: Props) {
<div className="admin-header-left"> <div className="admin-header-left">
<h1>Immich Folio</h1> <h1>Immich Folio</h1>
<nav className="admin-tabs"> <nav className="admin-tabs">
<button {TABS.map((t) => (
className={`admin-tab ${activeTab === 'pages' ? 'active' : ''}`} <Link
onClick={() => setActiveTab('pages')} key={t.href}
> href={t.href}
Pages className={`admin-tab ${t.match.test(pathname) ? 'active' : ''}`}
</button> >
<button {t.label}
className={`admin-tab ${activeTab === 'settings' ? 'active' : ''}`} </Link>
onClick={() => setActiveTab('settings')} ))}
>
Settings
</button>
<button
className={`admin-tab ${activeTab === 'analytics' ? 'active' : ''}`}
onClick={() => setActiveTab('analytics')}
>
Analytics
</button>
</nav> </nav>
</div> </div>
<div className="admin-header-right"> <div className="admin-header-right">
@@ -195,12 +192,14 @@ export default function AdminDashboard({ onLogout }: Props) {
)} )}
</div> </div>
<span className="admin-header-divider" aria-hidden="true" />
<a <a
href="/" href="/?fresh=1"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="admin-btn admin-btn-ghost" className="admin-btn admin-btn-ghost"
title="Open site in new tab" title="Open site in new tab (bypassing cache)"
> >
<Icons.IconLink size={14} /> Site <Icons.IconLink size={14} /> Site
</a> </a>
@@ -225,11 +224,7 @@ export default function AdminDashboard({ onLogout }: Props) {
</div> </div>
</header> </header>
<main className="admin-main"> <main className="admin-main">{children}</main>
{activeTab === 'pages' && <PageBuilder />}
{activeTab === 'settings' && <SettingsEditor />}
{activeTab === 'analytics' && <AnalyticsView />}
</main>
<BackupManagerModal <BackupManagerModal
isOpen={showBackupModal} isOpen={showBackupModal}

View File

@@ -1,6 +1,8 @@
'use client'; 'use client';
import { useState, useMemo } from 'react'; import { useState, useMemo } from 'react';
import { useScrollLock } from './useScrollLock';
import { IconFolder } from './Icons';
interface ImmichAlbumInfo { interface ImmichAlbumInfo {
id: string; id: string;
@@ -19,6 +21,7 @@ interface Props {
} }
export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }: Props) { export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }: Props) {
useScrollLock(true);
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const filtered = useMemo(() => { const filtered = useMemo(() => {
@@ -75,7 +78,9 @@ export default function AlbumPicker({ albums, onSelect, onClose, usedAlbumIds }:
loading="lazy" loading="lazy"
/> />
) : ( ) : (
<div className="picker-thumb-placeholder">📁</div> <div className="picker-thumb-placeholder">
<IconFolder size={20} />
</div>
)} )}
</div> </div>
<div className="picker-item-info"> <div className="picker-item-info">

View File

@@ -18,6 +18,7 @@ import {
rectSortingStrategy, rectSortingStrategy,
} from '@dnd-kit/sortable'; } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities'; import { CSS } from '@dnd-kit/utilities';
import { useScrollLock } from './useScrollLock';
interface AssetInfo { interface AssetInfo {
id: string; id: string;
@@ -92,6 +93,7 @@ export default function AssetOrderEditor({
onSave, onSave,
onClose, onClose,
}: Props) { }: Props) {
useScrollLock(true);
const [assets, setAssets] = useState<AssetInfo[]>([]); const [assets, setAssets] = useState<AssetInfo[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(''); const [error, setError] = useState('');

View File

@@ -1,7 +1,8 @@
'use client'; 'use client';
import { useState, useEffect, useCallback, useRef } from 'react'; import { useState, useEffect, useCallback, useRef } from 'react';
import { IconFolder, IconImage, IconStar } from './Icons'; import { IconCheck, IconFolder, IconImage, IconStar } from './Icons';
import { useScrollLock } from './useScrollLock';
interface AssetInfo { interface AssetInfo {
id: string; id: string;
@@ -27,6 +28,7 @@ export default function AssetPicker({
albumId, albumId,
title, title,
}: Props) { }: Props) {
useScrollLock(true);
const [tab, setTab] = useState<Tab>(albumId ? 'album' : 'favorites'); const [tab, setTab] = useState<Tab>(albumId ? 'album' : 'favorites');
const [assets, setAssets] = useState<AssetInfo[]>([]); const [assets, setAssets] = useState<AssetInfo[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -175,7 +177,11 @@ export default function AssetPicker({
alt={asset.originalFileName} alt={asset.originalFileName}
loading="lazy" loading="lazy"
/> />
{isUsed && <div className="asset-picker-used-badge">✓</div>} {isUsed && (
<div className="asset-picker-used-badge">
<IconCheck size={11} />
</div>
)}
{asset.isFavorite && !isUsed && ( {asset.isFavorite && !isUsed && (
<div className="asset-picker-fav-badge" title="Favorite in Immich"> <div className="asset-picker-fav-badge" title="Favorite in Immich">
<IconStar size={14} /> <IconStar size={14} />

View File

@@ -3,6 +3,7 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import type { BackupItem } from '@/app/api/admin/backups/route'; import type { BackupItem } from '@/app/api/admin/backups/route';
import * as Icons from './Icons'; import * as Icons from './Icons';
import { useScrollLock } from './useScrollLock';
interface Props { interface Props {
isOpen: boolean; isOpen: boolean;
@@ -49,6 +50,8 @@ export default function BackupManagerModal({ isOpen, onClose, onRestoreSuccess }
} }
}, [isOpen, fetchBackups]); }, [isOpen, fetchBackups]);
useScrollLock(isOpen);
if (!isOpen) return null; if (!isOpen) return null;
async function handleRestore(filename: string) { async function handleRestore(filename: string) {
@@ -96,7 +99,7 @@ export default function BackupManagerModal({ isOpen, onClose, onRestoreSuccess }
</p> </p>
</div> </div>
<button className="backup-modal-close-btn" onClick={onClose} aria-label="Close"> <button className="backup-modal-close-btn" onClick={onClose} aria-label="Close">
✕ <Icons.IconX size={16} />
</button> </button>
</div> </div>

View File

@@ -0,0 +1,42 @@
'use client';
import type { JournalBlock } from '@/lib/journal';
import { IconFileText, IconSparkles, IconQuote, IconCamera, IconArrowLeftRight } from './Icons';
type BlockType = JournalBlock['type'];
/**
* Block type chips for the Journal Studio and the Pages essay builder.
*
* Deliberately monochrome: the panel's colour language is neutral surfaces plus
* a single accent, and these chips label a block rather than reporting a state,
* so they carry no colour of their own. The block type is told apart by its
* icon — the same icon the "Add Block" toolbar uses for it.
*/
const BLOCK_META: Record<BlockType, { label: string; Icon: typeof IconFileText }> = {
paragraph: { label: 'Text', Icon: IconFileText },
heading: { label: 'Heading', Icon: IconSparkles },
quote: { label: 'Quote', Icon: IconQuote },
photo: { label: 'Photo', Icon: IconCamera },
'photo-pair': { label: 'Photo Pair', Icon: IconArrowLeftRight },
};
interface BlockBadgeProps {
type: BlockType;
/** Optional position prefix, e.g. "3" renders as "3 · Quote". */
index?: number;
}
export function BlockBadge({ type, index }: BlockBadgeProps) {
const meta = BLOCK_META[type];
if (!meta) return <span className="essay-block-badge">{type}</span>;
const { label, Icon } = meta;
return (
<span className="essay-block-badge">
<Icon size={11} />
{index != null && <span className="essay-block-badge-index">{index}</span>}
{label}
</span>
);
}

View File

@@ -18,6 +18,7 @@ import {
IconSparkles, IconSparkles,
IconArrowLeftRight, IconArrowLeftRight,
} from './Icons'; } from './Icons';
import { BlockBadge } from './BlockBadge';
interface EssayBlockEditorProps { interface EssayBlockEditorProps {
markdown: string; markdown: string;
@@ -119,7 +120,7 @@ export function EssayBlockEditor({ markdown, onChange, onSelectPhoto }: EssayBlo
<div className="essay-block-editor"> <div className="essay-block-editor">
{/* Sticky Dark Glass Toolbar */} {/* Sticky Dark Glass Toolbar */}
<div className="essay-toolbar-sticky"> <div className="essay-toolbar-sticky">
<span className="essay-toolbar-label">✨ Add Story Block:</span> <span className="essay-toolbar-label">Add Story Block:</span>
<button <button
type="button" type="button"
className="admin-btn admin-btn-xs" className="admin-btn admin-btn-xs"
@@ -171,19 +172,7 @@ export function EssayBlockEditor({ markdown, onChange, onSelectPhoto }: EssayBlo
<div className="essay-block-card-header"> <div className="essay-block-card-header">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<IconGripVertical size={14} style={{ color: 'var(--admin-text-muted)', cursor: 'grab' }} /> <IconGripVertical size={14} style={{ color: 'var(--admin-text-muted)', cursor: 'grab' }} />
<span <BlockBadge type={block.type} index={idx + 1} />
className={`essay-block-badge ${
block.type === 'photo' || block.type === 'photo-pair'
? 'badge-photo'
: block.type === 'heading'
? 'badge-heading'
: block.type === 'quote'
? 'badge-quote'
: ''
}`}
>
Block {idx + 1}: {block.type}
</span>
</div> </div>
<div className="essay-block-actions"> <div className="essay-block-actions">

View File

@@ -360,3 +360,123 @@ export function IconArrowLeftRight({ size = 16, className = 'svg-icon', strokeWi
); );
} }
export function IconCalendar({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
<rect width="18" height="18" x="3" y="4" rx="2" />
<path d="M8 2v4M16 2v4M3 10h18" />
</svg>
);
}
export function IconArrowDown({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
<path d="M12 5v14M19 12l-7 7-7-7" />
</svg>
);
}
export function IconArrowUp({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
<path d="M12 19V5M5 12l7-7 7 7" />
</svg>
);
}
/** An "A→Z" marker for alphabetical / filename ordering. */
export function IconSortAlpha({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
<path d="M4 10 7 3l3 7M4.9 8.2h4.2" />
<path d="M14 3h6l-6 7h6" />
<path d="M17 14v7M14 18l3 3 3-3" />
</svg>
);
}
export function IconCheck({ size = 16, className = 'svg-icon', strokeWidth = 2, ...props }: IconProps) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className} {...props}>
<path d="M20 6 9 17l-5-5" />
</svg>
);
}
/** Open book — journal entries and photo essays. */
export function IconBook({
size = 16,
className = 'svg-icon',
strokeWidth = 2,
...props
}: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
{...props}
>
<path d="M12 7v14" />
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
</svg>
);
}
export function IconEye({
size = 16,
className = 'svg-icon',
strokeWidth = 2,
...props
}: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
{...props}
>
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" />
<circle cx="12" cy="12" r="3" />
</svg>
);
}
/** Clock — reading time. */
export function IconClock({
size = 16,
className = 'svg-icon',
strokeWidth = 2,
...props
}: IconProps) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
strokeLinejoin="round"
className={className}
{...props}
>
<circle cx="12" cy="12" r="9" />
<path d="M12 7v5l3 2" />
</svg>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,345 @@
'use client';
import React from 'react';
import { createPortal } from 'react-dom';
import { IconCheck, IconChevronDown } from './Icons';
/**
* A single choice in a {@link Listbox}.
*
* `label` stays plain text so the same option table can feed a `title`
* attribute or an aria-label; `icon` is the themed glyph shown beside it.
*/
export interface ListboxOption<T extends string> {
value: T;
label: string;
icon?: React.ReactNode;
}
export interface ListboxProps<T extends string> {
value: T;
options: readonly ListboxOption<T>[];
onChange: (value: T) => void;
/** Accessible name. Prefer `labelledBy` when a visible <label> exists. */
ariaLabel?: string;
/** id of the visible label element. */
labelledBy?: string;
disabled?: boolean;
className?: string;
/** Width of the trigger; the popup always matches it. */
style?: React.CSSProperties;
}
/** How long a type-ahead buffer keeps collecting characters. */
const TYPEAHEAD_RESET_MS = 600;
/** Gap between the trigger and the popup. */
const POPUP_GAP = 4;
/** Space kept clear of the viewport edge. */
const VIEWPORT_MARGIN = 8;
/** Tallest the popup ever gets; beyond this it scrolls internally. */
const POPUP_MAX_HEIGHT = 260;
/** Below this the flipped side is not worth using. */
const POPUP_MIN_HEIGHT = 96;
/** Viewport coordinates for the popup, measured from the trigger. */
interface Placement {
left: number;
width: number;
/** Set when the popup hangs below the trigger. */
top?: number;
/** Set when the popup is flipped above it. */
bottom?: number;
maxHeight: number;
}
/**
* A select replacement that can show markup in its options.
*
* The native `<option>` element strips markup, so the admin panel's
* `currentColor` SVG set cannot be used inside a real `<select>`. This
* implements the ARIA combobox/listbox pattern instead: DOM focus never leaves
* the trigger button, and the active option is announced through
* `aria-activedescendant`. Options are plain `<li>`s — not focusable — which
* keeps focus management to a single element.
*
* The popup is portalled to `document.body` and positioned from the trigger's
* viewport rect. An absolutely positioned popup is clipped by any ancestor with
* a non-visible overflow — and z-index cannot rescue it, because clipping
* happens before stacking — so inside a scrolling modal the list would be cut
* off. Escaping to the body also lets it flip above the trigger when there is
* more room there.
*/
export function Listbox<T extends string>({
value,
options,
onChange,
ariaLabel,
labelledBy,
disabled = false,
className = '',
style,
}: ListboxProps<T>) {
const [open, setOpen] = React.useState(false);
const selectedIndex = Math.max(
0,
options.findIndex((o) => o.value === value),
);
const [activeIndex, setActiveIndex] = React.useState(selectedIndex);
const [placement, setPlacement] = React.useState<Placement | null>(null);
const wrapperRef = React.useRef<HTMLDivElement>(null);
const buttonRef = React.useRef<HTMLButtonElement>(null);
const listRef = React.useRef<HTMLUListElement>(null);
const typeahead = React.useRef({ buffer: '', at: 0 });
const baseId = React.useId();
const listId = `${baseId}-list`;
const optionId = (index: number) => `${baseId}-opt-${index}`;
const selected = options[selectedIndex];
const openList = React.useCallback(
(index = selectedIndex) => {
if (disabled) return;
setActiveIndex(index);
setOpen(true);
},
[disabled, selectedIndex],
);
const close = React.useCallback(() => {
setOpen(false);
setPlacement(null);
typeahead.current = { buffer: '', at: 0 };
}, []);
const commit = React.useCallback(
(index: number) => {
const option = options[index];
if (option) onChange(option.value);
close();
// Focus never left the trigger, but a pointer selection can blur it.
buttonRef.current?.focus();
},
[close, onChange, options],
);
// Dismiss on outside pointer press. pointerdown (not click) so a press that
// starts outside closes the popup before it can retarget the click. The popup
// is portalled, so it is not inside the wrapper — without the second test a
// press on an option would count as "outside" and close before it commits.
React.useEffect(() => {
if (!open) return;
const onPointerDown = (event: PointerEvent) => {
const target = event.target as Node;
if (!wrapperRef.current?.contains(target) && !listRef.current?.contains(target)) close();
};
document.addEventListener('pointerdown', onPointerDown);
return () => document.removeEventListener('pointerdown', onPointerDown);
}, [open, close]);
// Measure once the popup is in the DOM but before paint, so it never shows at
// a stale position. Until then it renders hidden purely to be measurable.
React.useLayoutEffect(() => {
if (!open) return;
const trigger = buttonRef.current;
const list = listRef.current;
if (!trigger || !list) return;
const rect = trigger.getBoundingClientRect();
// scrollHeight ignores our own max-height, so this is the natural height.
const wanted = Math.min(POPUP_MAX_HEIGHT, list.scrollHeight + 2);
const below = window.innerHeight - rect.bottom - POPUP_GAP - VIEWPORT_MARGIN;
const above = rect.top - POPUP_GAP - VIEWPORT_MARGIN;
const flip = wanted > below && above > below;
const room = flip ? above : below;
setPlacement({
left: rect.left,
width: rect.width,
top: flip ? undefined : rect.bottom + POPUP_GAP,
bottom: flip ? window.innerHeight - rect.top + POPUP_GAP : undefined,
maxHeight: Math.max(POPUP_MIN_HEIGHT, Math.min(POPUP_MAX_HEIGHT, room)),
});
}, [open]);
// The popup is anchored in viewport coordinates, so anything that moves the
// trigger invalidates it. Dismiss rather than re-measure — that is what a
// native select does, and the measurement above only runs on open. Capture
// phase, because the scroll usually happens on an ancestor container.
React.useEffect(() => {
if (!open) return;
window.addEventListener('scroll', close, true);
window.addEventListener('resize', close);
return () => {
window.removeEventListener('scroll', close, true);
window.removeEventListener('resize', close);
};
}, [open, close]);
// Keep the active option visible while arrowing or typing through a long list.
React.useEffect(() => {
if (!open) return;
listRef.current
?.querySelector(`#${CSS.escape(optionId(activeIndex))}`)
?.scrollIntoView({ block: 'nearest' });
// optionId is derived from baseId, which is stable for the component's life.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, activeIndex, baseId]);
/** Jump to the next option whose label starts with the accumulated buffer. */
const runTypeahead = (char: string) => {
const now = Date.now();
const buffer =
now - typeahead.current.at > TYPEAHEAD_RESET_MS ? char : typeahead.current.buffer + char;
typeahead.current = { buffer, at: now };
// A repeated single character cycles through matches instead of sticking.
const repeat = buffer.length > 1 && buffer.split('').every((c) => c === buffer[0]);
const needle = repeat ? buffer[0] : buffer;
const from = repeat || buffer.length === 1 ? activeIndex + 1 : activeIndex;
for (let i = 0; i < options.length; i++) {
const index = (from + i) % options.length;
if (options[index].label.toLowerCase().startsWith(needle.toLowerCase())) {
setActiveIndex(index);
return index;
}
}
return null;
};
const onKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
if (disabled) return;
const last = options.length - 1;
switch (event.key) {
case 'ArrowDown':
case 'ArrowUp': {
event.preventDefault();
const step = event.key === 'ArrowDown' ? 1 : -1;
if (!open) {
openList(Math.min(last, Math.max(0, selectedIndex + step)));
} else {
setActiveIndex((i) => Math.min(last, Math.max(0, i + step)));
}
return;
}
case 'Home':
case 'End': {
event.preventDefault();
const index = event.key === 'Home' ? 0 : last;
if (open) setActiveIndex(index);
else openList(index);
return;
}
case 'Enter':
case ' ':
event.preventDefault();
if (open) commit(activeIndex);
else openList();
return;
case 'Escape':
if (open) {
event.preventDefault();
close();
}
return;
case 'Tab':
// Let focus move on, but commit what the user was looking at.
if (open) commit(activeIndex);
return;
default:
break;
}
// Type-ahead: a single printable character, no modifiers.
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault();
if (!open) {
setOpen(true);
const match = runTypeahead(event.key);
if (match === null) setActiveIndex(selectedIndex);
return;
}
runTypeahead(event.key);
}
};
return (
<div ref={wrapperRef} className={`admin-listbox ${className}`.trim()} style={style}>
<button
ref={buttonRef}
type="button"
role="combobox"
aria-controls={listId}
aria-expanded={open}
aria-haspopup="listbox"
aria-activedescendant={open ? optionId(activeIndex) : undefined}
aria-label={ariaLabel}
aria-labelledby={labelledBy}
disabled={disabled}
className="admin-listbox-trigger"
onClick={() => (open ? close() : openList())}
onKeyDown={onKeyDown}
>
<span className="admin-listbox-value">
{selected?.icon}
<span>{selected?.label ?? ''}</span>
</span>
<IconChevronDown size={14} className="svg-icon admin-listbox-caret" aria-hidden="true" />
</button>
{open &&
createPortal(
<ul
ref={listRef}
id={listId}
role="listbox"
className="admin-listbox-popup"
tabIndex={-1}
style={
placement
? {
left: placement.left,
width: placement.width,
top: placement.top,
bottom: placement.bottom,
maxHeight: placement.maxHeight,
}
: // First pass: laid out but invisible, only so it can be measured.
{ left: 0, top: 0, visibility: 'hidden' }
}
>
{options.map((option, index) => (
<li
key={option.value}
id={optionId(index)}
role="option"
aria-selected={option.value === value}
className={`admin-listbox-option${index === activeIndex ? ' is-active' : ''}${
option.value === value ? ' is-selected' : ''
}`}
// pointerdown would fire before the outside-press handler can run;
// click is enough because that handler treats the popup as inside.
onClick={() => commit(index)}
onMouseEnter={() => setActiveIndex(index)}
>
{option.icon}
<span className="admin-listbox-option-label">{option.label}</span>
{option.value === value && (
<IconCheck
size={14}
className="svg-icon admin-listbox-check"
aria-hidden="true"
/>
)}
</li>
))}
</ul>,
document.body,
)}
</div>
);
}

View File

@@ -1,6 +1,6 @@
'use client'; 'use client';
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback, type ReactNode } from 'react';
import { import {
DndContext, DndContext,
closestCenter, closestCenter,
@@ -23,6 +23,8 @@ import AlbumPicker from './AlbumPicker';
import AssetPicker from './AssetPicker'; import AssetPicker from './AssetPicker';
import AssetOrderEditor from './AssetOrderEditor'; import AssetOrderEditor from './AssetOrderEditor';
import { EssayBlockEditor } from './EssayBlockEditor'; import { EssayBlockEditor } from './EssayBlockEditor';
import SaveBar from './SaveBar';
import { useScrollLock } from './useScrollLock';
import { import {
ALBUM_SORT_MODES, ALBUM_SORT_MODES,
DEFAULT_ALBUM_SORT, DEFAULT_ALBUM_SORT,
@@ -31,6 +33,10 @@ import {
} from '@/lib/albumSort'; } from '@/lib/albumSort';
import type { AlbumEntryObject } from '@/lib/config/schema'; import type { AlbumEntryObject } from '@/lib/config/schema';
import { import {
IconArrowDown,
IconArrowUp,
IconBook,
IconCalendar,
IconCamera, IconCamera,
IconCopy, IconCopy,
IconFolder, IconFolder,
@@ -41,16 +47,17 @@ import {
IconPencil, IconPencil,
IconPlus, IconPlus,
IconSearch, IconSearch,
IconSortAlpha,
IconTrash, IconTrash,
IconX, IconX,
} from './Icons'; } from './Icons';
import { Listbox, type ListboxOption } from './Listbox';
/** /**
* Labels for the per-album sort select. Order matches ALBUM_SORT_MODES. * Labels for the per-album sort control.
* *
* Plain text, no emoji: an <option> cannot contain markup, so the SVG set from * Kept as plain text on their own because they also feed the `title` attribute
* `./Icons` is not available here — and a decorative emoji is not a substitute * on the album card's sort badge, where markup is not an option.
* for it. The badge on the album card uses a real icon instead.
*/ */
const SORT_LABELS: Record<AlbumSortMode, string> = { const SORT_LABELS: Record<AlbumSortMode, string> = {
immich: 'Immich order (default)', immich: 'Immich order (default)',
@@ -60,6 +67,21 @@ const SORT_LABELS: Record<AlbumSortMode, string> = {
manual: 'Manual', manual: 'Manual',
}; };
/** Manual reuses the drag glyph so the control matches the card's badge. */
const SORT_ICONS: Record<AlbumSortMode, ReactNode> = {
immich: <IconCalendar />,
newest: <IconArrowDown />,
oldest: <IconArrowUp />,
filename: <IconSortAlpha />,
manual: <IconGripVertical />,
};
const SORT_OPTIONS: readonly ListboxOption<AlbumSortMode>[] = ALBUM_SORT_MODES.map((mode) => ({
value: mode,
label: SORT_LABELS[mode],
icon: SORT_ICONS[mode],
}));
// ── Types ────────────────────────────────────────────────────── // ── Types ──────────────────────────────────────────────────────
interface AlbumEntry { interface AlbumEntry {
id: string; id: string;
@@ -366,6 +388,11 @@ export default function PageBuilder() {
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [editingAlbumAddress, setEditingAlbumAddress] = useState<ActiveEditAlbumAddress | null>(null); const [editingAlbumAddress, setEditingAlbumAddress] = useState<ActiveEditAlbumAddress | null>(null);
// Keep the builder still behind either drawer. One combined lock rather than
// one per drawer: the album drawer opens from inside the subpage drawer, and
// a single condition avoids two locks racing over the same inline style.
useScrollLock(editingAlbumAddress !== null || expandedSubpage !== null);
// DnD sensors // DnD sensors
const sensors = useSensors( const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
@@ -860,38 +887,14 @@ export default function PageBuilder() {
return ( return (
<div className="page-builder"> <div className="page-builder">
{/* Save Bar */} <SaveBar
<div className={`save-bar ${dirty ? 'dirty' : ''}`}> dirty={dirty}
<div className="save-bar-left"> saving={saving}
{dirty && <span className="unsaved-badge">Unsaved changes</span>} saveMessage={saveMessage}
{saveMessage && ( onSave={handleSave}
<span label="Save Changes"
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`} showPreview
> />
{saveMessage}
</span>
)}
{!dirty && !saveMessage && <span className="save-hint">⌘S to save</span>}
</div>
<div className="save-bar-right">
<a
href="/?fresh=1"
target="_blank"
rel="noopener noreferrer"
className="admin-btn admin-btn-ghost admin-btn-preview"
title="Open site in new tab (bypassing cache)"
>
↗ Preview Site
</a>
<button
className="admin-btn admin-btn-primary"
onClick={handleSave}
disabled={!dirty || saving}
>
{saving ? 'Saving...' : 'Save Changes'}
</button>
</div>
</div>
{/* Search Bar */} {/* Search Bar */}
<div className="builder-search-container"> <div className="builder-search-container">
@@ -1106,7 +1109,7 @@ export default function PageBuilder() {
onClick={() => setExpandedSubpage(null)} onClick={() => setExpandedSubpage(null)}
title="Close drawer" title="Close drawer"
> >
✕ <IconX size={14} />
</button> </button>
</div> </div>
</div> </div>
@@ -1237,7 +1240,13 @@ export default function PageBuilder() {
> >
<div className="toggle-card-info" style={{ textAlign: 'left' }}> <div className="toggle-card-info" style={{ textAlign: 'left' }}>
<span className="toggle-card-title" style={{ fontWeight: 600 }}> <span className="toggle-card-title" style={{ fontWeight: 600 }}>
{sp.enabled !== false ? '🟢 Page Active (Published)' : '🔴 Page Disabled (Hidden)'} <span
className={`page-status-dot ${sp.enabled !== false ? 'is-on' : 'is-off'}`}
aria-hidden="true"
/>
{sp.enabled !== false
? 'Page Active (Published)'
: 'Page Disabled (Hidden)'}
</span> </span>
<span className="toggle-card-desc" style={{ fontSize: '0.8rem', display: 'block', opacity: 0.75 }}> <span className="toggle-card-desc" style={{ fontSize: '0.8rem', display: 'block', opacity: 0.75 }}>
{sp.enabled !== false {sp.enabled !== false
@@ -1279,23 +1288,20 @@ export default function PageBuilder() {
{/* Visual Photo Essay Builder (if layout === 'essay') */} {/* Visual Photo Essay Builder (if layout === 'essay') */}
{(sp.grid?.layout === 'essay' || sp.essayText != null) && ( {(sp.grid?.layout === 'essay' || sp.essayText != null) && (
<div className="subpage-drawer-section" style={{ background: 'var(--admin-surface, rgba(255,255,255,0.02))', padding: '1rem', borderRadius: '8px', border: '1px solid var(--admin-border, rgba(255,255,255,0.1))' }}> <div className="subpage-drawer-section">
<div style={{ marginBottom: '1rem' }}> <div className="drawer-section-heading">
<h4 style={{ margin: 0, fontSize: '1rem', display: 'flex', alignItems: 'center', gap: '8px' }}> <h4>
<span>📖 Storytelling &amp; Photo Essay Builder</span> <IconBook size={16} /> Storytelling &amp; Photo Essay Builder
</h4> </h4>
<p style={{ margin: '4px 0 0 0', fontSize: '0.8rem', opacity: 0.75 }}> <p>Compose text, quotes, and fullbleed/wide photos visually.</p>
Compose text, quotes, and fullbleed/wide photos visually.
</p>
</div> </div>
<EssayBlockEditor <EssayBlockEditor
markdown={sp.essayText || ''} markdown={sp.essayText || ''}
onChange={(newMarkdown) => updateSubpage(spIndex, { essayText: newMarkdown })} onChange={(newMarkdown) => updateSubpage(spIndex, { essayText: newMarkdown })}
onSelectPhoto={(callback) => { onSelectPhoto={(callback) => {
const firstAlbumId = sp.albums[0]?.id;
setHeroPickerTarget({ setHeroPickerTarget({
albumId: firstAlbumId, albumId: undefined,
title: 'Select Photo for Photo Essay', title: 'Select Photo for Photo Essay',
onSelect: (assetId) => { onSelect: (assetId) => {
callback(assetId); callback(assetId);
@@ -1493,182 +1499,133 @@ export default function PageBuilder() {
<IconX size={14} /> <IconX size={14} />
</button> </button>
</div> </div>
{/* One scrolling column: cover banner, then the form. Anything the
form already shows (password state, custom hero) is not
repeated as a read-only stat. */}
<div className="album-drawer-body"> <div className="album-drawer-body">
{/* Left Column - Visual Info & Stats */} <div className="modal-cover-container">
<div className="modal-left-column"> {heroThumb ? (
<div className="modal-cover-container"> <img src={`/api/admin/thumbnail/${heroThumb}`} alt="" loading="lazy" />
{heroThumb ? ( ) : (
<img src={`/api/admin/thumbnail/${heroThumb}`} alt="" loading="lazy" /> <div className="modal-cover-placeholder">
) : ( <IconCamera />
<div className="modal-cover-placeholder">
<IconCamera />
</div>
)}
</div>
<div className="modal-meta-box">
<span className="modal-album-title">{album.title || name}</span>
<span className="modal-album-subtitle">Original: {name}</span>
</div>
<div className="modal-info-list">
<div className="modal-info-item">
<span className="modal-info-label">Photo Count:</span>
<span className="modal-info-value">{count} photos</span>
</div> </div>
<div className="modal-info-item"> )}
<span className="modal-info-label">Status:</span> </div>
<span className="modal-info-value"> <div className="modal-meta-box">
{album.password ? 'Password Protected' : 'Public Access'} <span className="modal-album-title">{album.title || name}</span>
</span> <span className="modal-album-subtitle">
</div> {count} {count === 1 ? 'photo' : 'photos'}
<div className="modal-info-item"> {album.title ? ` · Original: ${name}` : ''}
<span className="modal-info-label">Custom Hero:</span> </span>
<span className="modal-info-value"> </div>
{album.heroImage ? 'Yes' : 'No'}
</span>
</div>
</div>
{/* Technical UUID */} <div className="admin-field">
<div className="drawer-uuid-section"> <label>Title override</label>
<label className="admin-field-label">IMMICH ALBUM UUID</label> <input
<div className="uuid-copy-box"> value={album.title || ''}
<code>{album.id}</code> onChange={(e) => onUpdate({ title: e.target.value || undefined })}
<button placeholder={name}
className="uuid-copy-btn" />
onClick={() => { </div>
navigator.clipboard.writeText(album.id);
}} <div className="admin-field">
title="Copy UUID" <label>Description</label>
> <textarea
<IconCopy size={12} /> value={album.description || ''}
</button> onChange={(e) => onUpdate({ description: e.target.value || undefined })}
</div> placeholder="Optional description for visitors"
rows={4}
/>
</div>
<div className="admin-field">
<label>Password protection</label>
<div className="input-with-icon">
<input
type="password"
value={album.password || ''}
onChange={(e) => onUpdate({ password: e.target.value || undefined })}
placeholder="Leave empty for public access"
/>
</div> </div>
</div> </div>
{/* Right Column - Form Fields */} {/* Hero Image Selection */}
<div className="modal-right-column"> <div className="admin-field">
<div className="admin-field"> <label>Custom Hero Image</label>
<label>Title override</label> <div className="album-hero-field">
<input {album.heroImage ? (
value={album.title || ''} <div className="album-hero-preview">
onChange={(e) => onUpdate({ title: e.target.value || undefined })} <img src={`/api/admin/thumbnail/${album.heroImage}`} alt="Hero" />
placeholder={name} <button
/> className="album-hero-remove"
onClick={() => onUpdate({ heroImage: undefined })}
title="Remove custom hero image"
>
<IconX size={14} />
</button>
</div>
) : (
<span className="album-hero-empty">Using default album cover</span>
)}
<button
className="admin-btn admin-btn-sm"
onClick={() =>
setHeroPickerTarget({
albumId: album.id,
onSelect: (assetId) => {
onUpdate({ heroImage: assetId });
setHeroPickerTarget(null);
},
currentAssetIds: album.heroImage ? [album.heroImage] : [],
title: `Pick Hero Image for ${name}`,
})
}
>
<IconImage size={12} /> {album.heroImage ? 'Change Image' : 'Pick Hero Image'}
</button>
</div> </div>
</div>
<div className="admin-field"> {/* Photo order */}
<label>Description</label> <div className="admin-field">
<textarea <label id="album-sort-label">Photo order</label>
value={album.description || ''} <Listbox
onChange={(e) => onUpdate({ description: e.target.value || undefined })} labelledBy="album-sort-label"
placeholder="Optional description for visitors" value={album.sort || DEFAULT_ALBUM_SORT}
rows={4} options={SORT_OPTIONS}
/> onChange={(mode) => onUpdate({ sort: mode })}
</div> />
<span className="admin-field-hint">
{album.sort === 'manual'
? 'Pinned photos come first, in the order you set. Everything else follows in the album’s Immich order.'
: 'Immich order follows the album’s own sort setting in Immich.'}
</span>
<div className="admin-field"> {album.sort === 'manual' && (
<label>Password protection</label> <div style={{ marginTop: '0.75rem' }}>
<div className="input-with-icon">
<input
type="password"
value={album.password || ''}
onChange={(e) => onUpdate({ password: e.target.value || undefined })}
placeholder="Leave empty for public access"
/>
</div>
</div>
{/* Hero Image Selection */}
<div className="admin-field">
<label>Custom Hero Image</label>
<div className="album-hero-field">
{album.heroImage ? (
<div className="album-hero-preview">
<img src={`/api/admin/thumbnail/${album.heroImage}`} alt="Hero" />
<button
className="album-hero-remove"
onClick={() => onUpdate({ heroImage: undefined })}
title="Remove custom hero image"
>
<IconX size={14} />
</button>
</div>
) : (
<span className="album-hero-empty">Using default album cover</span>
)}
<button <button
className="admin-btn admin-btn-sm" className="admin-btn admin-btn-sm"
onClick={() => onClick={() =>
setHeroPickerTarget({ setOrderEditorTarget({
albumId: album.id, albumId: album.id,
onSelect: (assetId) => { albumName: album.title || name,
onUpdate({ heroImage: assetId }); assetOrder: album.assetOrder || [],
setHeroPickerTarget(null); onSave: (assetOrder) => {
onUpdate({ assetOrder });
setOrderEditorTarget(null);
}, },
currentAssetIds: album.heroImage ? [album.heroImage] : [],
title: `Pick Hero Image for ${name}`,
}) })
} }
> >
<IconImage size={12} /> {album.heroImage ? 'Change Image' : 'Pick Hero Image'} <IconGripVertical size={18} className="svg-icon svg-drag" />{' '}
{album.assetOrder?.length
? `Reorder photos (${album.assetOrder.length} pinned)`
: 'Reorder photos'}
</button> </button>
</div> </div>
</div> )}
{/* Photo order */}
<div className="admin-field">
<label>Photo order</label>
<select
value={album.sort || DEFAULT_ALBUM_SORT}
onChange={(e) =>
onUpdate({
sort: isAlbumSortMode(e.target.value) ? e.target.value : undefined,
})
}
style={{
padding: '8px 12px',
borderRadius: '6px',
width: '100%',
fontSize: '0.9rem',
}}
>
{ALBUM_SORT_MODES.map((mode) => (
<option key={mode} value={mode}>
{SORT_LABELS[mode]}
</option>
))}
</select>
<span className="admin-field-hint">
{album.sort === 'manual'
? 'Pinned photos come first, in the order you set. Everything else follows in the album’s Immich order.'
: 'Immich order follows the album’s own sort setting in Immich.'}
</span>
{album.sort === 'manual' && (
<div style={{ marginTop: '0.75rem' }}>
<button
className="admin-btn admin-btn-sm"
onClick={() =>
setOrderEditorTarget({
albumId: album.id,
albumName: album.title || name,
assetOrder: album.assetOrder || [],
onSave: (assetOrder) => {
onUpdate({ assetOrder });
setOrderEditorTarget(null);
},
})
}
>
<IconGripVertical size={18} className="svg-icon svg-drag" />{' '}
{album.assetOrder?.length
? `Reorder photos (${album.assetOrder.length} pinned)`
: 'Reorder photos'}
</button>
</div>
)}
</div>
</div> </div>
</div> </div>
<div className="album-drawer-footer"> <div className="album-drawer-footer">
@@ -1679,6 +1636,19 @@ export default function PageBuilder() {
> >
<IconTrash size={14} /> Remove Album <IconTrash size={14} /> Remove Album
</button> </button>
<div className="uuid-copy-box" title="Immich album UUID">
<code>{album.id}</code>
<button
className="uuid-copy-btn"
onClick={() => {
navigator.clipboard.writeText(album.id);
}}
title="Copy UUID"
aria-label="Copy Immich album UUID"
>
<IconCopy size={12} />
</button>
</div>
<button <button
className="admin-btn admin-btn-primary" className="admin-btn admin-btn-primary"
onClick={() => setEditingAlbumAddress(null)} onClick={() => setEditingAlbumAddress(null)}

View File

@@ -0,0 +1,68 @@
'use client';
interface SaveBarProps {
dirty: boolean;
saving: boolean;
saveMessage: string;
onSave: () => void;
label: string;
/** Show the cache-bypassing preview link (page builder only). */
showPreview?: boolean;
}
/**
* Floating save bar pinned to the bottom of the viewport.
*
* It only mounts while there is something to act on (unsaved changes, an
* in-flight save, or a result message) so it never covers content otherwise.
* The success message is cleared by the caller after a few seconds, which
* makes the bar disappear on its own.
*/
export default function SaveBar({
dirty,
saving,
saveMessage,
onSave,
label,
showPreview = false,
}: SaveBarProps) {
if (!dirty && !saving && !saveMessage) return null;
return (
<div className={`floating-save-bar ${dirty ? 'dirty' : ''}`} role="status">
<div className="save-bar-left">
{saveMessage ? (
<span className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`}>
{saveMessage}
</span>
) : (
<span className="unsaved-badge">
<span className="badge-pulse-dot" aria-hidden="true" />
Unsaved changes
</span>
)}
</div>
<div className="save-bar-right">
{showPreview && (
<a
href="/?fresh=1"
target="_blank"
rel="noopener noreferrer"
className="admin-btn admin-btn-ghost admin-btn-preview"
title="Open site in new tab (bypassing cache)"
>
↗ Preview Site
</a>
)}
<button
className="admin-btn admin-btn-primary"
onClick={onSave}
disabled={!dirty || saving}
title="⌘S / Ctrl+S"
>
{saving ? 'Saving...' : label}
</button>
</div>
</div>
);
}

View File

@@ -2,7 +2,9 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link';
import * as Icons from './Icons'; import * as Icons from './Icons';
import SaveBar from './SaveBar';
interface Settings { interface Settings {
title?: string; title?: string;
@@ -11,6 +13,7 @@ interface Settings {
exifOnHover?: boolean; exifOnHover?: boolean;
map?: boolean; map?: boolean;
transitions?: boolean; transitions?: boolean;
scrollToTop?: boolean;
analytics?: boolean; analytics?: boolean;
theme?: { theme?: {
preset?: string; preset?: string;
@@ -73,13 +76,37 @@ const PHOTO_FRAMES = ['none', 'passepartout', 'shadow'];
const HERO_STYLES = ['split', 'fullbleed', 'minimal', 'stacked', 'typographic', 'mosaic']; const HERO_STYLES = ['split', 'fullbleed', 'minimal', 'stacked', 'typographic', 'mosaic'];
const ASPECT_RATIOS = ['1', '3/2', '2/3', '16/9', 'auto']; const ASPECT_RATIOS = ['1', '3/2', '2/3', '16/9', 'auto'];
const THEME_INFO: Record<string, { desc: string; label: string; accent: string; bg: string; tile: string }> = { /**
* Card metadata for the theme picker. `font`, `radius` and `frame` mirror the
* real preset definitions in lib/config/theme.ts so the mini mockups show what
* the preset actually does; `gap` is the visual density of its gallery grid.
*/
const THEME_INFO: Record<
string,
{
desc: string;
label: string;
accent: string;
bg: string;
tile: string;
font: string;
type: 'serif' | 'sans' | 'mono';
radius: number;
frame: 'none' | 'passepartout' | 'shadow';
gap: number;
}
> = {
studio: { studio: {
label: 'Studio', label: 'Studio',
desc: 'Clean, high-contrast grid with sans-serif type.', desc: 'Clean, high-contrast grid with sans-serif type.',
bg: '#141414', bg: '#141414',
tile: '#242424', tile: '#242424',
accent: '#e60012', accent: '#e60012',
font: 'Playfair Display',
type: 'serif',
radius: 0,
frame: 'passepartout',
gap: 4,
}, },
'studio-modern': { 'studio-modern': {
label: 'Studio Modern', label: 'Studio Modern',
@@ -87,6 +114,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#121212', bg: '#121212',
tile: '#191919', tile: '#191919',
accent: '#e60012', accent: '#e60012',
font: 'Archivo',
type: 'sans',
radius: 0,
frame: 'none',
gap: 3,
}, },
minimal: { minimal: {
label: 'Minimal', label: 'Minimal',
@@ -94,6 +126,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#ffffff', bg: '#ffffff',
tile: '#f3f3f3', tile: '#f3f3f3',
accent: '#111111', accent: '#111111',
font: 'Geist',
type: 'sans',
radius: 0,
frame: 'none',
gap: 2,
}, },
editorial: { editorial: {
label: 'Editorial', label: 'Editorial',
@@ -101,6 +138,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#fbf9f4', bg: '#fbf9f4',
tile: '#e5dfd4', tile: '#e5dfd4',
accent: '#b89053', accent: '#b89053',
font: 'Bodoni Moda',
type: 'serif',
radius: 0,
frame: 'shadow',
gap: 8,
}, },
classic: { classic: {
label: 'Classic', label: 'Classic',
@@ -108,6 +150,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#f7f7f7', bg: '#f7f7f7',
tile: '#ffffff', tile: '#ffffff',
accent: '#444444', accent: '#444444',
font: 'Cinzel',
type: 'serif',
radius: 12,
frame: 'passepartout',
gap: 7,
}, },
noir: { noir: {
label: 'Noir', label: 'Noir',
@@ -115,6 +162,11 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#000000', bg: '#000000',
tile: '#151515', tile: '#151515',
accent: '#ffffff', accent: '#ffffff',
font: 'Libre Baskerville',
type: 'serif',
radius: 0,
frame: 'passepartout',
gap: 6,
}, },
monograph: { monograph: {
label: 'Monograph', label: 'Monograph',
@@ -122,18 +174,44 @@ const THEME_INFO: Record<string, { desc: string; label: string; accent: string;
bg: '#f4f4f6', bg: '#f4f4f6',
tile: '#ffffff', tile: '#ffffff',
accent: '#555555', accent: '#555555',
font: 'Instrument Serif',
type: 'mono',
radius: 0,
frame: 'none',
gap: 5,
}, },
}; };
export default function SettingsEditor() { const SETTINGS_SECTIONS = [
{ id: 'general', label: 'General' },
{ id: 'theme', label: 'Theme' },
{ id: 'grid', label: 'Grid' },
{ id: 'footer', label: 'Footer' },
{ id: 'legal', label: 'Legal' },
{ id: 'seo', label: 'SEO' },
{ id: 'security', label: 'Security & Protection' },
];
interface SettingsEditorProps {
/** Sub-section to show, taken from the /admin/settings/[section] route. */
section?: string;
}
export default function SettingsEditor({ section }: SettingsEditorProps) {
const router = useRouter(); const router = useRouter();
// An unknown section in the URL falls back to General instead of an empty panel.
const activeSection = SETTINGS_SECTIONS.some((sec) => sec.id === section)
? (section as string)
: 'general';
const [settings, setSettings] = useState<Settings>({}); const [settings, setSettings] = useState<Settings>({});
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const [saveMessage, setSaveMessage] = useState(''); const [saveMessage, setSaveMessage] = useState('');
const [activeSection, setActiveSection] = useState('general');
const [currentMode, setCurrentMode] = useState<'dark' | 'light'>('dark'); const [currentMode, setCurrentMode] = useState<'dark' | 'light'>('dark');
const [faviconUploading, setFaviconUploading] = useState(false);
const [faviconMessage, setFaviconMessage] = useState('');
useEffect(() => { useEffect(() => {
loadSettings(); loadSettings();
@@ -275,54 +353,31 @@ export default function SettingsEditor() {
); );
} }
const sections = [
{ id: 'general', label: 'General' },
{ id: 'theme', label: 'Theme' },
{ id: 'grid', label: 'Grid' },
{ id: 'footer', label: 'Footer' },
{ id: 'legal', label: 'Legal' },
{ id: 'seo', label: 'SEO' },
{ id: 'security', label: 'Security & Protection' },
];
return ( return (
<div className="settings-editor"> <div className="settings-editor">
{/* Save Bar */} <SaveBar
<div className={`save-bar ${dirty ? 'dirty' : ''}`}> dirty={dirty}
<div className="save-bar-left"> saving={saving}
{dirty && <span className="unsaved-badge">Unsaved changes</span>} saveMessage={saveMessage}
{saveMessage ? ( onSave={handleSave}
<span label="Save Settings"
className={`save-message ${saveMessage.startsWith('Error') ? 'error' : 'success'}`} />
>
{saveMessage} <p className="settings-live-sync-note">
</span> <Icons.IconRefresh size={13} /> Live Sync (No Docker restart required)
) : ( </p>
<span style={{ fontSize: '0.75rem', color: 'var(--admin-text-muted)', display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}>
⚡ Live Sync (No Docker restart required)
</span>
)}
</div>
<button
className="admin-btn admin-btn-primary"
onClick={handleSave}
disabled={!dirty || saving}
>
{saving ? 'Saving...' : 'Save Settings'}
</button>
</div>
<div className="settings-layout"> <div className="settings-layout">
{/* Sidebar */} {/* Sidebar */}
<nav className="settings-nav"> <nav className="settings-nav">
{sections.map((sec) => ( {SETTINGS_SECTIONS.map((sec) => (
<button <Link
key={sec.id} key={sec.id}
href={`/admin/settings/${sec.id}`}
className={`settings-nav-item ${activeSection === sec.id ? 'active' : ''}`} className={`settings-nav-item ${activeSection === sec.id ? 'active' : ''}`}
onClick={() => setActiveSection(sec.id)}
> >
{sec.label} {sec.label}
</button> </Link>
))} ))}
</nav> </nav>
@@ -415,6 +470,20 @@ export default function SettingsEditor() {
</div> </div>
</button> </button>
<button
type="button"
className={`admin-toggle-card ${settings.scrollToTop !== false ? 'active' : ''}`}
onClick={() => update('scrollToTop', settings.scrollToTop === false)}
>
<div className="toggle-card-info">
<span className="toggle-card-title"><Icons.IconArrowUp size={16} /> Scroll-to-Top Button</span>
<span className="toggle-card-desc">Show a floating arrow that returns visitors to the top of long pages</span>
</div>
<div className={`switch-toggle ${settings.scrollToTop !== false ? 'on' : ''}`}>
<span className="switch-slider" />
</div>
</button>
<button <button
type="button" type="button"
className={`admin-toggle-card ${settings.analytics !== false ? 'active' : ''}`} className={`admin-toggle-card ${settings.analytics !== false ? 'active' : ''}`}
@@ -443,6 +512,65 @@ export default function SettingsEditor() {
</div> </div>
</button> </button>
</div> </div>
<div className="admin-field favicon-field">
<label>Favicon</label>
<div className="favicon-row">
<input
type="file"
accept=".svg,.png,.ico,.jpg,.jpeg"
disabled={faviconUploading}
onChange={async (e) => {
const file = e.target.files?.[0];
if (!file) return;
setFaviconMessage('');
setFaviconUploading(true);
const form = new FormData();
form.append('file', file);
try {
const res = await fetch('/api/admin/favicon', { method: 'PUT', body: form });
const data = await res.json();
setFaviconMessage(res.ok ? data.message : `Error: ${data.error}`);
} catch {
setFaviconMessage('Error: Upload failed');
} finally {
setFaviconUploading(false);
e.target.value = '';
}
}}
/>
<button
type="button"
className="admin-btn"
disabled={faviconUploading}
onClick={async () => {
setFaviconMessage('');
setFaviconUploading(true);
try {
const res = await fetch('/api/admin/favicon', { method: 'DELETE' });
const data = await res.json();
setFaviconMessage(res.ok ? data.message : `Error: ${data.error}`);
} catch {
setFaviconMessage('Error: Reset failed');
} finally {
setFaviconUploading(false);
}
}}
>
Reset
</button>
{faviconUploading && <div className="admin-spinner" />}
</div>
{faviconMessage && (
<p className={`save-message ${faviconMessage.startsWith('Error') ? 'error' : 'success'}`}>
{faviconMessage}
</p>
)}
<span className="admin-field-hint">
SVG, PNG, ICO, or JPEG — max 512 kB. Stored in the content volume. Reset restores
the bundled default.
</span>
</div>
</div> </div>
)} )}
@@ -457,30 +585,52 @@ export default function SettingsEditor() {
<label>Preset</label> <label>Preset</label>
<div className="preset-card-grid"> <div className="preset-card-grid">
{PRESETS.map((p) => { {PRESETS.map((p) => {
const info = THEME_INFO[p] || { label: p, desc: '', bg: '#fff', tile: '#eee', accent: '#333' }; const info = THEME_INFO[p] || {
label: p,
desc: '',
bg: '#fff',
tile: '#eee',
accent: '#333',
font: 'System',
type: 'sans' as const,
radius: 0,
frame: 'none' as const,
gap: 4,
};
const isActive = (settings.theme?.preset || 'studio') === p; const isActive = (settings.theme?.preset || 'studio') === p;
return ( return (
<button <button
key={p} key={p}
type="button" type="button"
className={`preset-card ${isActive ? 'active' : ''}`} className={`preset-card theme-preset-card ${isActive ? 'active' : ''}`}
onClick={() => update('theme.preset', p)} onClick={() => update('theme.preset', p)}
style={{ '--preset-accent': info.accent } as React.CSSProperties} style={
{
'--preset-accent': info.accent,
'--preset-bg': info.bg,
'--preset-tile': info.tile,
'--preset-radius': `${info.radius}px`,
'--preset-gap': `${info.gap}px`,
} as React.CSSProperties
}
> >
<div className="preset-card-preview" style={{ backgroundColor: info.bg }}> <div className="preset-card-preview" data-frame={info.frame}>
<div className="mini-header"> <div className="mini-header">
<span className="mini-dot" style={{ backgroundColor: info.accent }}></span> <span className={`mini-specimen type-${info.type}`}>Aa</span>
<span className="mini-line" style={{ backgroundColor: isActive ? info.accent : 'var(--admin-border)' }}></span> <span className="mini-line" />
</div> </div>
<div className="mini-grid"> <div className="mini-grid">
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div> <div className="mini-tile" />
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div> <div className="mini-tile" />
<div className="mini-tile" style={{ backgroundColor: info.tile }}></div> <div className="mini-tile" />
</div> </div>
</div> </div>
<div className="preset-card-info"> <div className="preset-card-info">
<span className="preset-card-name">{info.label}</span> <span className="preset-card-name">{info.label}</span>
<span className="preset-card-desc">{info.desc}</span> <span className="preset-card-desc">{info.desc}</span>
<span className="preset-card-specs">
{info.font} &middot; radius {info.radius} &middot; {info.frame}
</span>
</div> </div>
</button> </button>
); );
@@ -765,7 +915,7 @@ export default function SettingsEditor() {
)} )}
{l === 'showcase' && ( {l === 'showcase' && (
<div className="demo-showcase-grid"> <div className="demo-showcase-grid">
<div className="demo-tile hero-tile" /> <div className="demo-tile demo-hero" />
<div className="demo-col"><div className="demo-tile" /><div className="demo-tile" /></div> <div className="demo-col"><div className="demo-tile" /><div className="demo-tile" /></div>
</div> </div>
)} )}

View File

@@ -0,0 +1,485 @@
/* ── Journal Studio & Editor CSS ──────────────────────────────────── */
/*
* The studio is a full-width workspace: it breaks out of the 1120px
* `.admin-main` column so the split view has room for editor *and* preview.
*/
.admin-main:has(> .journal-studio),
.admin-main:has(> .journal-editor-container) {
max-width: none;
padding: 0;
}
/* ── Form controls ─────────────────────────────────────────────────
* Local field styling for the studio. Scoped so the generic class name
* cannot leak into the rest of the admin panel.
*/
.journal-studio .admin-input,
.journal-editor-container .admin-input,
.journal-modal-card .admin-input {
display: block;
width: 100%;
padding: 0.55rem 0.7rem;
background: var(--admin-bg-input, #161616);
border: 1px solid var(--admin-border, #2e2e2e);
border-radius: 8px;
color: var(--admin-text, #f0f0f0);
font-family: inherit;
font-size: 0.875rem;
line-height: 1.5;
transition:
border-color 0.15s ease,
background 0.15s ease;
}
.journal-studio .admin-input:hover,
.journal-editor-container .admin-input:hover,
.journal-modal-card .admin-input:hover {
border-color: var(--admin-border-hover, #444);
}
.journal-studio .admin-input:focus,
.journal-editor-container .admin-input:focus,
.journal-modal-card .admin-input:focus {
outline: none;
border-color: var(--admin-border-focus, #6366f1);
}
.journal-studio .admin-input::placeholder,
.journal-editor-container .admin-input::placeholder,
.journal-modal-card .admin-input::placeholder {
color: var(--admin-text-secondary, #a0a0a0);
opacity: 0.7;
}
.journal-editor-container textarea.admin-input,
.journal-modal-card textarea.admin-input {
resize: vertical;
min-height: 88px;
}
.journal-editor-container select.admin-input {
cursor: pointer;
appearance: none;
padding-right: 2rem;
background-image:
linear-gradient(45deg, transparent 50%, currentColor 50%),
linear-gradient(135deg, currentColor 50%, transparent 50%);
background-position:
calc(100% - 16px) calc(50% + 1px),
calc(100% - 11px) calc(50% + 1px);
background-size: 5px 5px;
background-repeat: no-repeat;
}
.journal-level-select {
width: 5.5rem;
flex-shrink: 0;
}
.journal-studio {
display: flex;
flex-direction: column;
height: 100%;
min-height: calc(100vh - 70px);
}
.journal-studio-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2rem;
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
}
.journal-studio-header h2 {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
display: flex;
align-items: center;
gap: 10px;
}
.journal-list-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
.journal-admin-card {
background: var(--admin-surface, rgba(255, 255, 255, 0.03));
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
border-radius: 10px;
overflow: hidden;
display: flex;
flex-direction: column;
transition:
border-color 0.2s ease,
transform 0.2s ease;
}
.journal-admin-card:hover {
border-color: var(--admin-accent, #6366f1);
transform: translateY(-2px);
}
.journal-admin-card-cover {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
background: rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.journal-admin-card-cover img {
width: 100%;
height: 100%;
object-fit: cover;
}
.journal-admin-card-body {
padding: 1.25rem;
display: flex;
flex-direction: column;
flex-grow: 1;
}
.journal-admin-card-title {
font-size: 1.15rem;
font-weight: 600;
margin: 0 0 0.4rem;
}
.journal-admin-card-slug {
font-size: 0.75rem;
font-family: monospace;
opacity: 0.6;
margin-bottom: 0.75rem;
}
.journal-admin-card-meta {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.75rem;
opacity: 0.7;
margin-bottom: 1rem;
flex-wrap: wrap;
}
.journal-admin-card-actions {
display: flex;
align-items: center;
gap: 8px;
margin-top: auto;
padding-top: 1rem;
border-top: 1px solid var(--admin-border, rgba(255, 255, 255, 0.06));
}
/* ── Split-Screen Studio Editor ────────────────────────────────────── */
.journal-editor-container {
display: flex;
flex-direction: column;
height: calc(100vh - 65px);
overflow: hidden;
}
.journal-editor-topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1.5rem;
background: var(--admin-surface, #18181b);
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
gap: 1rem;
z-index: 10;
}
.journal-editor-topbar-left {
display: flex;
align-items: center;
gap: 1rem;
flex-grow: 1;
}
.journal-editor-title-input {
font-size: 1.1rem;
font-weight: 600;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
color: inherit;
padding: 4px 8px;
max-width: 400px;
width: 100%;
}
.journal-editor-title-input:focus {
border-color: var(--admin-accent, #6366f1);
background: rgba(255, 255, 255, 0.05);
}
.journal-editor-topbar-right {
display: flex;
align-items: center;
gap: 0.75rem;
}
.journal-editor-split {
display: grid;
/* Left width is driven by the draggable divider; the preview takes the rest. */
grid-template-columns: var(--journal-split-left, 46%) 7px minmax(0, 1fr);
flex-grow: 1;
overflow: hidden;
height: 100%;
}
/* Kill text selection and pointer flicker while the divider is being dragged. */
.journal-editor-split.is-dragging {
user-select: none;
cursor: col-resize;
}
.journal-editor-split.is-dragging .journal-editor-pane-right {
pointer-events: none;
}
.journal-editor-resizer {
position: relative;
cursor: col-resize;
background: var(--admin-border, rgba(255, 255, 255, 0.08));
transition: background 0.15s ease;
touch-action: none;
}
.journal-editor-resizer:hover,
.journal-editor-resizer:focus-visible,
.journal-editor-split.is-dragging .journal-editor-resizer {
background: var(--admin-accent, #6366f1);
outline: none;
}
/* Grip dots, and a widened invisible hit area so the divider is easy to grab. */
.journal-editor-resizer-grip {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 15px;
height: 44px;
border-radius: 4px;
background: repeating-linear-gradient(to bottom, currentColor 0 2px, transparent 2px 5px);
color: rgba(255, 255, 255, 0.35);
background-clip: content-box;
padding: 0 6px;
}
.journal-editor-resizer:hover .journal-editor-resizer-grip {
color: #fff;
}
.journal-editor-pane-left {
display: flex;
flex-direction: column;
overflow-y: auto;
padding: 1.5rem 2rem 4rem;
background: var(--admin-bg, #09090b);
}
.journal-editor-pane-right {
display: flex;
flex-direction: column;
overflow-y: auto;
background: var(--surface, #111);
position: relative;
}
.journal-preview-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 1rem;
background: rgba(0, 0, 0, 0.4);
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
font-size: 0.75rem;
position: sticky;
top: 0;
z-index: 5;
backdrop-filter: blur(8px);
}
.journal-preview-frame {
padding: 2.5rem 2rem;
max-width: 1080px;
margin: 0 auto;
width: 100%;
transition: max-width 0.3s ease;
}
/*
* The essay's full-bleed and wide figures are sized against the viewport on the
* live site. Inside the preview pane that overshoots — the photo would bleed out
* of the pane and drift as the split is dragged — so they are re-anchored to the
* frame. 100% is the container's content box, so reaching the pane edges means
* adding back both horizontal paddings: 4rem for this frame plus 3rem for
* .essay-container. Keep in sync if either padding changes.
*/
.journal-preview-frame .essay-container {
--essay-bleed: calc(100% + 7rem);
--essay-wide: 100%;
}
.journal-preview-frame.mobile {
max-width: 380px;
border-left: 1px solid rgba(255, 255, 255, 0.1);
border-right: 1px solid rgba(255, 255, 255, 0.1);
min-height: 100%;
background: var(--background, #000);
}
.journal-raw-markdown-editor {
width: 100%;
height: 100%;
min-height: 500px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.9rem;
line-height: 1.6;
background: rgba(0, 0, 0, 0.3);
color: #f4f4f5;
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.1));
border-radius: 8px;
padding: 1.25rem;
resize: none;
}
.journal-raw-markdown-editor:focus {
outline: none;
border-color: var(--admin-accent, #6366f1);
}
/* Modal styling for Entry creation / Metadata */
.journal-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.75);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
backdrop-filter: blur(4px);
}
.journal-modal-card {
background: var(--admin-surface, #18181b);
border: 1px solid var(--admin-border, rgba(255, 255, 255, 0.1));
border-radius: 12px;
width: 90%;
max-width: 620px;
max-height: 88vh;
overflow-y: auto;
padding: 1.75rem;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
}
/* ── Card meta & status ───────────────────────────────────────────── */
.journal-admin-card-meta span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.journal-card-cover-placeholder {
opacity: 0.25;
}
.journal-status-pill {
padding: 0.15rem 0.5rem;
border-radius: 9999px;
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
opacity: 1;
}
.journal-status-pill.is-draft {
background: rgba(234, 179, 8, 0.15);
color: #eab308;
border: 1px solid rgba(234, 179, 8, 0.3);
}
.journal-status-pill.is-published {
background: rgba(34, 197, 94, 0.15);
color: #22c55e;
border: 1px solid rgba(34, 197, 94, 0.3);
}
.journal-preview-bar-label {
display: inline-flex;
align-items: center;
gap: 6px;
}
/* ── Block field rows ─────────────────────────────────────────────
* The generic `.admin-input { width: 100% }` would blow these rows apart,
* so the fixed-width controls are pinned here (higher specificity wins).
*/
.journal-heading-row,
.journal-photo-layout-row {
display: flex;
align-items: center;
gap: 8px;
}
.journal-editor-container .journal-heading-row .journal-level-select {
flex: 0 0 5.5rem;
width: 5.5rem;
}
.journal-editor-container .journal-heading-row input {
flex: 1 1 auto;
min-width: 0;
}
.journal-editor-container .journal-photo-layout-row select {
flex: 1 1 auto;
min-width: 0;
}
.journal-photo-layout-row .admin-btn {
flex-shrink: 0;
}
/* Stack the split view on narrow screens instead of squeezing both panes. */
@media (max-width: 1100px) {
.journal-editor-split {
grid-template-columns: 1fr;
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
}
.journal-editor-resizer {
display: none;
}
.journal-editor-pane-left {
border-bottom: 1px solid var(--admin-border, rgba(255, 255, 255, 0.08));
}
}
/* An unresolvable photo reference — shown in the block editor, not to visitors. */
.journal-block-warning {
margin: 0 0 0.75rem;
padding: 0.55rem 0.7rem;
border-radius: 8px;
font-size: 0.78rem;
line-height: 1.45;
color: #fca5a5;
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
}

View File

@@ -0,0 +1,41 @@
'use client';
import { useEffect } from 'react';
/**
* Freezes the page behind a modal for as long as `active` is true.
*
* An overlay covers the page but does not absorb wheel events: a scroll that
* starts over the backdrop — or one that continues past the end of the modal's
* own scroll container — reaches the document and moves the page underneath.
* `overscroll-behavior` alone cannot fix that, because it only applies to
* scroll containers, and the backdrop is not one.
*
* Nesting works without a counter: each lock captures whatever inline value it
* found and restores exactly that, so a picker opened from the album drawer
* restores the drawer's `hidden` rather than clearing it.
*/
export function useScrollLock(active: boolean) {
useEffect(() => {
if (!active) return;
const { body } = document;
const previousOverflow = body.style.overflow;
const previousPaddingRight = body.style.paddingRight;
// Hiding the scrollbar widens the viewport and shifts the page under the
// overlay. Pad by exactly the width it gave up so nothing moves. Overlay
// scrollbars (most touch devices) measure 0 and need no compensation.
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
if (scrollbarWidth > 0) {
const current = parseFloat(getComputedStyle(body).paddingRight) || 0;
body.style.paddingRight = `${current + scrollbarWidth}px`;
}
body.style.overflow = 'hidden';
return () => {
body.style.overflow = previousOverflow;
body.style.paddingRight = previousPaddingRight;
};
}, [active]);
}

View File

@@ -0,0 +1,10 @@
import { JournalStudio } from '../../components/JournalStudio';
export default async function AdminJournalEntryPage({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
return <JournalStudio slug={slug} />;
}

View File

@@ -0,0 +1,5 @@
import { JournalStudio } from '../components/JournalStudio';
export default function AdminJournalPage() {
return <JournalStudio />;
}

View File

@@ -1,4 +1,5 @@
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import AdminShell from './AdminShell';
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Immich Folio Admin', title: 'Immich Folio Admin',
@@ -16,5 +17,9 @@ export const metadata: Metadata = {
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
export default function AdminLayout({ children }: { children: React.ReactNode }) { export default function AdminLayout({ children }: { children: React.ReactNode }) {
return <div className="admin-layout">{children}</div>; return (
<div className="admin-layout">
<AdminShell>{children}</AdminShell>
</div>
);
} }

View File

@@ -1,54 +1,5 @@
'use client'; import PageBuilder from './components/PageBuilder';
import { useState, useEffect } from 'react'; export default function AdminHomePage() {
import AdminLogin from './components/AdminLogin'; return <PageBuilder />;
import AdminDashboard from './components/AdminDashboard';
import './admin.css';
export default function AdminPage() {
const [authenticated, setAuthenticated] = useState<boolean | null>(null);
const [enabled, setEnabled] = useState(true);
useEffect(() => {
checkAuth();
}, []);
async function checkAuth() {
try {
const res = await fetch('/api/admin/auth');
const data = await res.json();
setAuthenticated(data.authenticated);
setEnabled(data.enabled);
} catch {
setAuthenticated(false);
}
}
if (authenticated === null) {
return (
<div className="admin-loading">
<div className="admin-spinner" />
</div>
);
}
if (!enabled) {
return (
<div className="admin-disabled">
<div className="admin-disabled-card">
<h1>Admin Panel</h1>
<p>
The admin panel is not enabled. Set <code>ADMIN_PASSWORD</code> in your environment
variables to activate it.
</p>
</div>
</div>
);
}
if (!authenticated) {
return <AdminLogin onSuccess={() => setAuthenticated(true)} />;
}
return <AdminDashboard onLogout={() => setAuthenticated(false)} />;
} }

5
app/admin/pages/page.tsx Normal file
View File

@@ -0,0 +1,5 @@
import PageBuilder from '../components/PageBuilder';
export default function AdminPagesPage() {
return <PageBuilder />;
}

View File

@@ -0,0 +1,10 @@
import SettingsEditor from '../../components/SettingsEditor';
export default async function AdminSettingsSectionPage({
params,
}: {
params: Promise<{ section: string }>;
}) {
const { section } = await params;
return <SettingsEditor section={section} />;
}

View File

@@ -0,0 +1,5 @@
import SettingsEditor from '../components/SettingsEditor';
export default function AdminSettingsPage() {
return <SettingsEditor />;
}

View File

@@ -121,6 +121,64 @@ const ROUTES: {
method: 'POST', method: 'POST',
args: () => [new Request('http://localhost/api/admin/backups', { method: 'POST', body: '{}' })], args: () => [new Request('http://localhost/api/admin/backups', { method: 'POST', body: '{}' })],
}, },
{
name: 'PUT /api/admin/favicon',
path: 'favicon',
load: () => import('../favicon/route'),
method: 'PUT',
args: () => [new Request('http://localhost/api/admin/favicon', { method: 'PUT' })],
},
{
name: 'DELETE /api/admin/favicon',
path: 'favicon',
load: () => import('../favicon/route'),
method: 'DELETE',
args: () => [],
},
{
name: 'GET /api/admin/journal',
path: 'journal',
load: () => import('../journal/route'),
method: 'GET',
args: () => [],
},
{
name: 'POST /api/admin/journal',
path: 'journal',
load: () => import('../journal/route'),
method: 'POST',
args: () => [new Request('http://localhost/api/admin/journal', { method: 'POST', body: '{}' })],
},
{
name: 'GET /api/admin/journal/[slug]',
path: 'journal/[slug]',
load: () => import('../journal/[slug]/route'),
method: 'GET',
args: () => [
new Request('http://localhost/api/admin/journal/test-slug'),
{ params: Promise.resolve({ slug: 'test-slug' }) },
],
},
{
name: 'PUT /api/admin/journal/[slug]',
path: 'journal/[slug]',
load: () => import('../journal/[slug]/route'),
method: 'PUT',
args: () => [
new Request('http://localhost/api/admin/journal/test-slug', { method: 'PUT', body: '{}' }),
{ params: Promise.resolve({ slug: 'test-slug' }) },
],
},
{
name: 'DELETE /api/admin/journal/[slug]',
path: 'journal/[slug]',
load: () => import('../journal/[slug]/route'),
method: 'DELETE',
args: () => [
new Request('http://localhost/api/admin/journal/test-slug', { method: 'DELETE' }),
{ params: Promise.resolve({ slug: 'test-slug' }) },
],
},
]; ];
describe('admin route guards', () => { describe('admin route guards', () => {
@@ -165,7 +223,7 @@ describe('admin route guards', () => {
if (entry.name === '__tests__') continue; if (entry.name === '__tests__') continue;
walk(full); walk(full);
} else if (entry.name === 'route.ts') { } else if (entry.name === 'route.ts') {
found.push(path.relative(adminDir, path.dirname(full))); found.push(path.relative(adminDir, path.dirname(full)).replace(/\\/g, '/'));
} }
} }
}; };

View File

@@ -44,7 +44,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Password is too long' }, { status: 400 }); return NextResponse.json({ error: 'Password is too long' }, { status: 400 });
} }
if (!verifyAdminPassword(body.password)) { if (!(await verifyAdminPassword(body.password))) {
return NextResponse.json({ error: 'Invalid password' }, { status: 401 }); return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
} }

View File

@@ -0,0 +1,111 @@
import { NextResponse } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
const CONTENT_DIR = path.resolve(process.cwd(), 'content');
const DEST = 'favicon.svg';
const MAX_SIZE = 512 * 1024; // 512 kB
/**
* Write via temp file + rename, the same pattern yaml-service uses: GET
* /api/favicon reads this path on every request, so a plain writeFile would
* let a concurrent read see a half-written icon.
*/
async function writeFavicon(content: Buffer | string): Promise<void> {
await fs.mkdir(CONTENT_DIR, { recursive: true });
const dest = path.join(CONTENT_DIR, DEST);
const tmpPath = `${dest}.${process.pid}.${Date.now()}.tmp`;
try {
await fs.writeFile(tmpPath, content);
await fs.rename(tmpPath, dest);
} catch (err) {
await fs.unlink(tmpPath).catch(() => {});
throw err;
}
}
export async function PUT(request: Request) {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
let body: FormData;
try {
body = await request.formData();
} catch {
return NextResponse.json({ error: 'Invalid form data' }, { status: 400 });
}
// A plain text field named "file" also satisfies `body.get('file')`, and the
// .size/.arrayBuffer() calls below would then throw a 500 on what is really
// a malformed request.
const file = body.get('file');
if (!(file instanceof File)) {
return NextResponse.json({ error: 'Missing file' }, { status: 400 });
}
if (file.size > MAX_SIZE) {
return NextResponse.json({ error: 'File must be under 512 kB' }, { status: 400 });
}
const buf = Buffer.from(await file.arrayBuffer());
// SVG passes through directly — CSP on the GET route protects the origin.
if (file.type === 'image/svg+xml') {
const text = buf.toString('utf-8');
if (!text.includes('<svg')) {
return NextResponse.json({ error: 'Invalid SVG file' }, { status: 400 });
}
await writeFavicon(buf);
return NextResponse.json({ success: true, message: 'Favicon updated.' });
}
// Raster formats (PNG, ICO, JPEG) — wrap in an SVG container so the favicon
// reference and CSP apply uniformly regardless of the uploaded format.
const mime = file.type || 'image/png';
if (
mime !== 'image/png' &&
mime !== 'image/x-icon' &&
mime !== 'image/vnd.microsoft.icon' &&
mime !== 'image/jpeg'
) {
return NextResponse.json(
{ error: `Unsupported file type: ${mime}. Use SVG, PNG, ICO, or JPEG.` },
{ status: 400 },
);
}
const b64 = buf.toString('base64');
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<image href="data:${mime};base64,${b64}" width="32" height="32"/>
</svg>
`;
await writeFavicon(svg);
return NextResponse.json({ success: true, message: 'Favicon updated.' });
}
/** Clean up stale favicon files left by a previous upload of a different format. */
export async function DELETE() {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
await fs.unlink(path.join(CONTENT_DIR, DEST));
return NextResponse.json({
success: true,
message: 'Custom favicon removed. Default restored.',
});
} catch {
return NextResponse.json({ error: 'No custom favicon to remove' }, { status: 404 });
}
}

View File

@@ -0,0 +1,119 @@
import { NextResponse } from 'next/server';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
import {
isValidSlug,
sanitizeSlug,
parseJournalMarkdown,
} from '@/lib/journal';
import {
readJournalEntry,
writeJournalEntry,
deleteJournalEntry,
} from '@/lib/admin/journal-service';
interface RouteContext {
params: Promise<{ slug: string }>;
}
export async function GET(request: Request, context: RouteContext) {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { slug } = await context.params;
if (!isValidSlug(slug)) {
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
}
try {
const entry = await readJournalEntry(slug);
if (!entry) {
return NextResponse.json({ error: 'Journal entry not found' }, { status: 404 });
}
return NextResponse.json({ entry });
} catch (err) {
console.error(`[Admin API] Failed to get journal entry "${slug}":`, err);
return NextResponse.json({ error: 'Failed to read journal entry' }, { status: 500 });
}
}
export async function PUT(request: Request, context: RouteContext) {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { slug } = await context.params;
if (!isValidSlug(slug)) {
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
}
try {
const body = await request.json();
const rawMarkdown = body.rawMarkdown ?? body.content;
if (typeof rawMarkdown !== 'string') {
return NextResponse.json({ error: 'Missing rawMarkdown content' }, { status: 400 });
}
// Verify markdown can be parsed safely
parseJournalMarkdown(rawMarkdown);
const targetSlug =
typeof body.newSlug === 'string' && body.newSlug
? sanitizeSlug(body.newSlug)
: slug;
if (!isValidSlug(targetSlug)) {
return NextResponse.json({ error: 'Invalid target slug' }, { status: 400 });
}
// If renaming, ensure target doesn't already exist
if (targetSlug !== slug) {
const existing = await readJournalEntry(targetSlug);
if (existing) {
return NextResponse.json({ error: 'Target slug already exists' }, { status: 409 });
}
await writeJournalEntry(targetSlug, rawMarkdown);
await deleteJournalEntry(slug);
} else {
await writeJournalEntry(slug, rawMarkdown);
}
const updated = await readJournalEntry(targetSlug);
return NextResponse.json({ success: true, entry: updated });
} catch (err) {
console.error(`[Admin API] Failed to update journal entry "${slug}":`, err);
return NextResponse.json({ error: 'Failed to update journal entry' }, { status: 500 });
}
}
export async function DELETE(request: Request, context: RouteContext) {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { slug } = await context.params;
if (!isValidSlug(slug)) {
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
}
try {
const deleted = await deleteJournalEntry(slug);
if (!deleted) {
return NextResponse.json({ error: 'Journal entry not found' }, { status: 404 });
}
return NextResponse.json({ success: true, deletedSlug: slug });
} catch (err) {
console.error(`[Admin API] Failed to delete journal entry "${slug}":`, err);
return NextResponse.json({ error: 'Failed to delete journal entry' }, { status: 500 });
}
}

View File

@@ -0,0 +1,75 @@
import { NextResponse } from 'next/server';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
import {
sanitizeSlug,
isValidSlug,
type JournalFrontmatter,
} from '@/lib/journal';
import {
listJournalEntries,
writeJournalEntry,
readJournalEntry,
} from '@/lib/admin/journal-service';
export async function GET() {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const entries = await listJournalEntries();
return NextResponse.json({ entries });
} catch (err) {
console.error('[Admin API] Failed to list journal entries:', err);
return NextResponse.json({ error: 'Failed to list journal entries' }, { status: 500 });
}
}
export async function POST(request: Request) {
if (!isAdminEnabled()) {
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
}
if (!(await isAdminAuthenticated())) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const body = await request.json();
const rawTitle = typeof body.title === 'string' ? body.title.trim() : 'Untitled';
const slug = sanitizeSlug(typeof body.slug === 'string' && body.slug ? body.slug : rawTitle);
if (!isValidSlug(slug)) {
return NextResponse.json({ error: 'Invalid slug' }, { status: 400 });
}
const existing = await readJournalEntry(slug);
if (existing) {
return NextResponse.json({ error: 'A journal entry with this slug already exists' }, { status: 409 });
}
const frontmatter: JournalFrontmatter = {
title: rawTitle,
date: new Date().toISOString().slice(0, 10),
draft: true,
...(typeof body.subtitle === 'string' && body.subtitle ? { subtitle: body.subtitle } : {}),
...(typeof body.author === 'string' && body.author ? { author: body.author } : {}),
...(typeof body.coverAssetId === 'string' && body.coverAssetId ? { coverAssetId: body.coverAssetId } : {}),
};
let initialMarkdown = body.content;
if (typeof initialMarkdown !== 'string' || !initialMarkdown) {
initialMarkdown = `---\ntitle: "${frontmatter.title}"\ndate: "${frontmatter.date}"\ndraft: true\n---\n\nWrite your story here...`;
}
await writeJournalEntry(slug, initialMarkdown);
const created = await readJournalEntry(slug);
return NextResponse.json({ success: true, entry: created }, { status: 201 });
} catch (err) {
console.error('[Admin API] Failed to create journal entry:', err);
return NextResponse.json({ error: 'Failed to create journal entry' }, { status: 500 });
}
}

View File

@@ -46,14 +46,15 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Invalid password format or length' }, { status: 400 }); return NextResponse.json({ error: 'Invalid password format or length' }, { status: 400 });
} }
if (type !== 'subpage' && type !== 'album') { if (type !== 'subpage' && type !== 'album' && type !== 'journal') {
return NextResponse.json({ error: 'Invalid type' }, { status: 400 }); return NextResponse.json({ error: 'Invalid type' }, { status: 400 });
} }
if (!isProtected(slug, type)) { if (!isProtected(slug, type)) {
const typeLabel = type === 'journal' ? 'Journal entry' : type === 'subpage' ? 'Subpage' : 'Album';
return NextResponse.json( return NextResponse.json(
{ {
error: `${type === 'subpage' ? 'Subpage' : 'Album'} is not password-protected`, error: `${typeLabel} is not password-protected`,
}, },
{ status: 400 }, { status: 400 },
); );

48
app/api/favicon/route.ts Normal file
View File

@@ -0,0 +1,48 @@
import { NextResponse } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';
const PUBLIC_DIR = path.resolve(process.cwd(), 'public');
const CONTENT_DIR = path.resolve(process.cwd(), 'content');
export const dynamic = 'force-dynamic';
export async function GET(request: Request) {
// Prefer the uploaded favicon in content/ (writable, mounted volume).
// Fall back to the bundled default in public/.
let filePath = path.join(CONTENT_DIR, 'favicon.svg');
let stat;
try {
stat = await fs.stat(filePath);
} catch {
filePath = path.join(PUBLIC_DIR, 'favicon.svg');
try {
stat = await fs.stat(filePath);
} catch {
return new NextResponse(null, { status: 404 });
}
}
// The URL is fixed but its content is not — an upload replaces the file in
// place. A far-future `immutable` would hide the new icon for as long as the
// browser kept the old one, so revalidate every time and answer with a 304
// when nothing changed. The ETag is derived from the file itself, so it moves
// the moment the admin uploads a new one.
const etag = `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"`;
const headers = {
'Content-Type': 'image/svg+xml',
'Cache-Control': 'public, max-age=0, must-revalidate',
ETag: etag,
// /api routes are excluded from the CSP nonce in proxy.ts, so the
// response must carry its own policy. An uploaded SVG must not be
// allowed to execute script on the origin.
'Content-Security-Policy': "default-src 'none'; sandbox",
};
if (request.headers.get('if-none-match') === etag) {
return new NextResponse(null, { status: 304, headers });
}
const buf = await fs.readFile(filePath);
return new NextResponse(new Uint8Array(buf), { status: 200, headers });
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { isInstalled, normalizeApiBase, validateSetupToken } from '@/lib/install';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
/** Album discovery attempts per minute per IP — only live before install. */
const INSTALL_ALBUMS_RPM = 30;
interface AlbumSummary {
id: string;
albumName: string;
description: string;
assetCount: number;
}
/**
* POST: list shared Immich albums for the wizard's picker, using the
* credentials the user just typed. The configured Immich client cannot be used
* here — it reads getConfig(), which is still in setup mode.
*/
export async function POST(request: NextRequest) {
if (isInstalled()) {
return NextResponse.json({ error: 'Setup is already complete' }, { status: 403 });
}
const token = request.nextUrl.searchParams.get('token') ?? request.headers.get('x-setup-token');
if (!validateSetupToken(token)) {
return NextResponse.json({ error: 'Invalid or missing setup token' }, { status: 403 });
}
const ip = getClientIp(request);
const rl = checkRateLimit(`install-albums:${ip}`, INSTALL_ALBUMS_RPM);
if (!rl.success) {
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
},
);
}
const body = await request.json().catch(() => null);
const apiUrl = typeof body?.apiUrl === 'string' ? body.apiUrl.trim() : '';
const apiKey = typeof body?.apiKey === 'string' ? body.apiKey.trim() : '';
if (!apiUrl || !apiKey) {
return NextResponse.json({ error: 'Immich URL and API key are required' }, { status: 400 });
}
const apiBase = normalizeApiBase(apiUrl);
if (!apiBase) {
return NextResponse.json({ error: 'Invalid Immich URL' }, { status: 400 });
}
try {
const res = await fetch(`${apiBase}/albums?shared=true`, {
headers: {
'x-api-key': apiKey,
Accept: 'application/json',
},
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) {
return NextResponse.json(
{ error: `Immich returned HTTP ${res.status} — check the URL and API key` },
{ status: 502 },
);
}
const contentType = res.headers.get('Content-Type') || '';
if (!contentType.includes('application/json')) {
return NextResponse.json(
{ error: 'Immich returned a non-JSON response — is the URL a server base URL?' },
{ status: 502 },
);
}
const albums = (await res.json()) as AlbumSummary[];
return NextResponse.json({
albums: albums.map((album) => ({
id: album.id,
albumName: album.albumName,
assetCount: album.assetCount,
description: album.description || '',
})),
});
} catch {
return NextResponse.json({ error: 'Could not reach Immich at this URL' }, { status: 502 });
}
}

116
app/api/install/route.ts Normal file
View File

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

View File

@@ -1210,8 +1210,7 @@
border: 1px solid var(--border-subtle); border: 1px solid var(--border-subtle);
background: var(--bg-card); background: var(--bg-card);
color: var(--text-secondary); color: var(--text-secondary);
font-size: 1.1rem; padding: 0;
font-weight: 300;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -1227,6 +1226,26 @@
color var(--transition-fast); color var(--transition-fast);
} }
.scroll-to-top__icon {
width: 18px;
height: 18px;
transition: transform var(--transition-fast);
}
.scroll-to-top:hover .scroll-to-top__icon {
transform: translateY(-2px);
}
@media (prefers-reduced-motion: reduce) {
.scroll-to-top__icon {
transition: none;
}
.scroll-to-top:hover .scroll-to-top__icon {
transform: none;
}
}
.scroll-to-top--visible { .scroll-to-top--visible {
opacity: 1; opacity: 1;
pointer-events: auto; pointer-events: auto;

View File

@@ -0,0 +1,458 @@
'use client';
import Link from 'next/link';
import { useMemo, useState } from 'react';
import '../admin/admin.css';
import './install.css';
interface Album {
id: string;
albumName: string;
assetCount: number;
description: string;
}
interface Props {
initialApiUrl: string;
setupToken: string;
}
const STEPS = ['Connect', 'Albums', 'Site', 'Finish'] as const;
const THEME_OPTIONS = [
{ value: 'studio', label: 'Studio', description: 'Classic portfolio, red accent' },
{ value: 'studio-modern', label: 'Studio Modern', description: 'Clean with soft corners' },
{ value: 'minimal', label: 'Minimal', description: 'Bare-bones, monochrome' },
{ value: 'editorial', label: 'Editorial', description: 'Magazine-style serif' },
{ value: 'classic', label: 'Classic', description: 'Warm gold, traditional' },
{ value: 'noir', label: 'Noir', description: 'Dark, high-contrast' },
{ value: 'monograph', label: 'Monograph', description: 'Typographic, text-first' },
];
export function InstallWizard({ initialApiUrl, setupToken }: Props) {
const [step, setStep] = useState(0);
// Step 1 — connection
const [apiUrl, setApiUrl] = useState(initialApiUrl);
const [apiKey, setApiKey] = useState('');
const [testing, setTesting] = useState(false);
const [testError, setTestError] = useState('');
// Step 2 — album selection (optional)
const [albums, setAlbums] = useState<Album[]>([]);
const [selected, setSelected] = useState<Record<string, boolean>>({});
const [search, setSearch] = useState('');
const [loaded, setLoaded] = useState(false);
// Step 3 — site settings
const [siteTitle, setSiteTitle] = useState('');
const [siteSubtitle, setSiteSubtitle] = useState('');
const [theme, setTheme] = useState('studio');
const [adminPassword, setAdminPassword] = useState('');
const [adminConfirm, setAdminConfirm] = useState('');
const [passwordError, setPasswordError] = useState('');
// Step 4 — finish
const [installing, setInstalling] = useState(false);
const [installError, setInstallError] = useState('');
const [done, setDone] = useState(false);
const selectedCount = Object.values(selected).filter(Boolean).length;
const filteredAlbums = useMemo(() => {
const q = search.trim().toLowerCase();
if (!q) return albums;
return albums.filter((a) => a.albumName.toLowerCase().includes(q));
}, [albums, search]);
async function testConnection() {
setTesting(true);
setTestError('');
try {
const res = await fetch('/api/install/albums', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-setup-token': setupToken },
body: JSON.stringify({ apiUrl: apiUrl.trim(), apiKey: apiKey.trim() }),
});
const data = await res.json();
if (!res.ok) {
setTestError(data.error || 'Could not connect to Immich');
return;
}
setAlbums(data.albums || []);
setLoaded(true);
setStep(1);
} catch {
setTestError('Could not reach the install service');
} finally {
setTesting(false);
}
}
function toggleAlbum(id: string) {
setSelected((prev) => ({ ...prev, [id]: !prev[id] }));
}
function validateSiteStep(): boolean {
if (adminPassword && adminPassword !== adminConfirm) {
setPasswordError('Passwords do not match');
return false;
}
setPasswordError('');
return true;
}
async function runInstall() {
setInstalling(true);
setInstallError('');
try {
const res = await fetch('/api/install', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-setup-token': setupToken },
body: JSON.stringify({
apiUrl: apiUrl.trim(),
apiKey: apiKey.trim(),
siteTitle,
siteSubtitle,
theme,
albums: Object.keys(selected).filter((id) => selected[id]),
...(adminPassword ? { adminPassword } : {}),
}),
});
const data = await res.json();
if (!res.ok) {
setInstallError(data.error || 'Install failed');
return;
}
setDone(true);
} catch {
setInstallError('Could not reach the install service');
} finally {
setInstalling(false);
}
}
if (done) {
return (
<div className="admin-layout">
<div className="install-page">
<div className="install-card">
<div className="install-card__header">
<span className="install-card__kicker">Immich Folio</span>
<h1>Install complete</h1>
<p>Your portfolio is ready. Add or rearrange albums any time from the admin panel.</p>
</div>
{/* install-body carries the card's padding — every other step
renders inside it, and skipping it here left the buttons
flush against the bottom edge. */}
<div className="install-body">
<div className="install-actions">
<Link className="admin-btn admin-btn-primary" href="/">
Visit your gallery
</Link>
{adminPassword && (
<Link className="admin-btn" href="/admin">
Open admin panel
</Link>
)}
</div>
</div>
</div>
</div>
</div>
);
}
return (
<div className="admin-layout">
<div className="install-page">
<div className="install-card">
<div className="install-card__header">
<span className="install-card__kicker">Immich Folio</span>
<h1>Install wizard</h1>
<p>Connect your Immich server, choose what to show, and publish your portfolio.</p>
</div>
<ol className="install-steps" aria-label="Install steps">
{STEPS.map((label, i) => (
<li key={label} className={i < step ? 'is-done' : i === step ? 'is-active' : ''}>
<span className="install-steps__dot">{i < step ? '✓' : i + 1}</span>
<span className="install-steps__label">{label}</span>
</li>
))}
</ol>
<div className="install-body">
{step === 0 && (
<form
className="install-form"
onSubmit={(e) => {
e.preventDefault();
testConnection();
}}
>
<div className="admin-field">
<label htmlFor="install-url">Immich server URL</label>
<input
id="install-url"
type="url"
value={apiUrl}
onChange={(e) => setApiUrl(e.target.value)}
placeholder="https://photos.example.com"
required
autoFocus
disabled={testing}
/>
<p className="admin-hint">
The base URL of your Immich instance (no /api). Example:{' '}
<code>https://photos.example.com</code>
</p>
</div>
<div className="admin-field">
<label htmlFor="install-key">Immich API key</label>
<input
id="install-key"
type="password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="Your Immich API key"
required
disabled={testing}
/>
<p className="admin-hint">
Create one in Immich under Admin Settings → API Keys.
</p>
</div>
{testError && <div className="admin-error">{testError}</div>}
<div className="install-actions">
<button
type="submit"
className="admin-btn admin-btn-primary"
disabled={testing || !apiUrl || !apiKey}
>
{testing ? 'Testing connection…' : 'Test connection & continue'}
</button>
</div>
</form>
)}
{step === 1 && (
<div className="install-albums">
<p className="admin-hint">
Pick albums to publish. This step is <strong>optional</strong> — you can add
albums later from the admin panel.
</p>
{albums.length === 0 ? (
<div className="install-empty">
<p>
{loaded
? 'No shared albums found on this Immich server.'
: 'Albums could not be loaded.'}
</p>
<p className="admin-hint">
Immich only lists albums that have been shared. You can still continue and add
them later.
</p>
</div>
) : (
<>
<div className="admin-field">
<input
type="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search albums…"
aria-label="Search albums"
/>
</div>
<ul className="install-albums__list">
{filteredAlbums.map((album) => (
<li key={album.id}>
<label className="install-albums__item">
<input
type="checkbox"
checked={!!selected[album.id]}
onChange={() => toggleAlbum(album.id)}
/>
<span className="install-albums__name">{album.albumName}</span>
<span className="install-albums__meta">
{album.assetCount} photo{album.assetCount === 1 ? '' : 's'}
</span>
</label>
</li>
))}
{filteredAlbums.length === 0 && (
<li className="install-empty">No albums match “{search}”.</li>
)}
</ul>
</>
)}
<div className="install-actions">
<button className="admin-btn" onClick={() => setStep(0)} disabled={installing}>
Back
</button>
<button
className="admin-btn admin-btn-primary"
onClick={() => setStep(2)}
disabled={installing}
>
{selectedCount > 0
? `Continue with ${selectedCount} album${selectedCount === 1 ? '' : 's'}`
: 'Skip — continue with no albums'}
</button>
</div>
</div>
)}
{step === 2 && (
<form
className="install-form"
onSubmit={(e) => {
e.preventDefault();
if (validateSiteStep()) setStep(3);
}}
>
<div className="admin-field">
<label htmlFor="install-title">Site title</label>
<input
id="install-title"
type="text"
value={siteTitle}
onChange={(e) => setSiteTitle(e.target.value)}
placeholder="My Photography"
autoFocus
/>
</div>
<div className="admin-field">
<label htmlFor="install-subtitle">Subtitle</label>
<input
id="install-subtitle"
type="text"
value={siteSubtitle}
onChange={(e) => setSiteSubtitle(e.target.value)}
placeholder="A visual journal"
/>
</div>
<div className="admin-field">
<label htmlFor="install-theme">Theme</label>
<select
id="install-theme"
value={theme}
onChange={(e) => setTheme(e.target.value)}
>
{THEME_OPTIONS.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</select>
<p className="admin-hint">
{THEME_OPTIONS.find((t) => t.value === theme)?.description}
</p>
</div>
<div className="install-divider">
<span>Optional — admin panel</span>
</div>
<div className="admin-field">
<label htmlFor="install-admin-password">Admin password</label>
<input
id="install-admin-password"
type="password"
value={adminPassword}
onChange={(e) => setAdminPassword(e.target.value)}
placeholder="Leave empty to disable the admin panel"
/>
</div>
{adminPassword && (
<div className="admin-field">
<label htmlFor="install-admin-confirm">Repeat admin password</label>
<input
id="install-admin-confirm"
type="password"
value={adminConfirm}
onChange={(e) => setAdminConfirm(e.target.value)}
placeholder="Repeat the password"
/>
</div>
)}
{passwordError && <div className="admin-error">{passwordError}</div>}
<div className="install-actions">
<button
type="button"
className="admin-btn"
onClick={() => setStep(1)}
disabled={installing}
>
Back
</button>
<button type="submit" className="admin-btn admin-btn-primary">
Review install
</button>
</div>
</form>
)}
{step === 3 && (
<div className="install-review">
<dl className="install-review__list">
<div>
<dt>Immich server</dt>
<dd>{apiUrl}</dd>
</div>
<div>
<dt>Albums</dt>
<dd>
{selectedCount > 0
? `${selectedCount} selected`
: 'None — you can add them later'}
</dd>
</div>
<div>
<dt>Site title</dt>
<dd>{siteTitle || 'Gallery'}</dd>
</div>
<div>
<dt>Theme</dt>
<dd>{THEME_OPTIONS.find((t) => t.value === theme)?.label}</dd>
</div>
<div>
<dt>Admin panel</dt>
<dd>{adminPassword ? 'Enabled' : 'Disabled'}</dd>
</div>
</dl>
{installError && <div className="admin-error">{installError}</div>}
<div className="install-actions">
<button className="admin-btn" onClick={() => setStep(2)} disabled={installing}>
Back
</button>
<button
className="admin-btn admin-btn-primary"
onClick={runInstall}
disabled={installing}
>
{installing ? 'Installing…' : 'Install'}
</button>
</div>
</div>
)}
</div>
</div>
</div>
</div>
);
}

280
app/install/install.css Normal file
View File

@@ -0,0 +1,280 @@
/* ── Install Wizard Styles ───────────────────────────────────── */
/* Sits on top of the admin theme variables (.admin-layout scope). */
.install-page {
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem 1rem;
}
.install-card {
width: 100%;
max-width: 560px;
background: var(--admin-bg-raised);
border: 1px solid var(--admin-border);
border-radius: 10px;
overflow: hidden;
}
.install-card__header {
padding: 1.75rem 2rem 1.25rem;
border-bottom: 1px solid var(--admin-border);
}
.install-card__kicker {
display: block;
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--admin-accent);
margin-bottom: 0.4rem;
}
.install-card__header h1 {
margin: 0 0 0.4rem;
font-size: 1.5rem;
letter-spacing: -0.01em;
}
.install-card__header p {
margin: 0;
font-size: 0.875rem;
color: var(--admin-text-secondary);
line-height: 1.5;
}
/* ── Step indicator ──────────────────────────────────────────── */
.install-steps {
list-style: none;
margin: 0;
padding: 1rem 2rem;
display: flex;
gap: 1.5rem;
border-bottom: 1px solid var(--admin-border);
}
.install-steps li {
display: flex;
align-items: center;
gap: 0.4rem;
color: var(--admin-text-muted);
font-size: 0.75rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.install-steps__dot {
width: 20px;
height: 20px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.7rem;
border: 1px solid var(--admin-border);
background: var(--admin-bg-input);
}
.install-steps li.is-active {
color: var(--admin-text);
}
.install-steps li.is-active .install-steps__dot {
border-color: var(--admin-accent);
color: var(--admin-accent);
}
.install-steps li.is-done .install-steps__dot {
background: var(--admin-accent);
border-color: var(--admin-accent);
color: #ffffff;
}
/* ── Body ────────────────────────────────────────────────────── */
.install-body {
padding: 1.5rem 2rem 2rem;
}
.install-form {
display: flex;
flex-direction: column;
}
.install-form .admin-field {
margin-bottom: 1rem;
}
.admin-hint {
font-size: 0.78rem;
color: var(--admin-text-muted);
margin: 0.35rem 0 0;
line-height: 1.5;
}
.admin-hint code {
background: var(--admin-bg-elevated);
padding: 0.1em 0.35em;
border-radius: 4px;
color: var(--admin-text-secondary);
}
.install-actions {
display: flex;
justify-content: flex-end;
gap: 0.6rem;
margin-top: 1.5rem;
}
.install-actions .admin-btn {
text-decoration: none;
}
/* ── Albums ──────────────────────────────────────────────────── */
.install-albums__list {
list-style: none;
margin: 0.75rem 0 0;
padding: 0;
max-height: 320px;
overflow-y: auto;
border: 1px solid var(--admin-border);
border-radius: 6px;
}
.install-albums__list li + li {
border-top: 1px solid var(--admin-border);
}
.install-albums__item {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 0.75rem;
cursor: pointer;
font-size: 0.875rem;
}
.install-albums__item:hover {
background: var(--admin-bg-elevated);
}
.install-albums__item input[type='checkbox'] {
width: 16px;
height: 16px;
accent-color: var(--admin-btn-primary-bg);
flex-shrink: 0;
}
.install-albums__name {
flex: 1;
color: var(--admin-text);
}
.install-albums__meta {
font-size: 0.75rem;
color: var(--admin-text-muted);
}
.install-empty {
padding: 0.75rem 0.5rem;
color: var(--admin-text-muted);
font-size: 0.875rem;
line-height: 1.5;
}
.install-empty p {
margin: 0 0 0.35rem;
}
.install-empty .admin-hint {
margin: 0;
}
/* ── Divider ─────────────────────────────────────────────────── */
.install-divider {
display: flex;
align-items: center;
gap: 0.75rem;
margin: 0.75rem 0 1rem;
color: var(--admin-text-muted);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.install-divider::before,
.install-divider::after {
content: '';
flex: 1;
height: 1px;
background: var(--admin-border);
}
/* ── Review ──────────────────────────────────────────────────── */
.install-review__list {
margin: 0;
border: 1px solid var(--admin-border);
border-radius: 6px;
overflow: hidden;
}
.install-review__list > div {
display: flex;
gap: 1rem;
padding: 0.65rem 0.9rem;
}
.install-review__list > div + div {
border-top: 1px solid var(--admin-border);
}
.install-review__list dt {
flex: 0 0 120px;
font-size: 0.75rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--admin-text-secondary);
padding-top: 0.1rem;
}
.install-review__list dd {
margin: 0;
font-size: 0.875rem;
color: var(--admin-text);
word-break: break-word;
}
/* ── Responsive ──────────────────────────────────────────────── */
@media (max-width: 480px) {
.install-steps {
padding: 0.85rem 1rem;
gap: 1rem;
}
.install-steps__label {
display: none;
}
.install-body {
padding: 1.25rem 1rem 1.5rem;
}
.install-review__list > div {
flex-direction: column;
gap: 0.2rem;
}
.install-review__list dt {
flex: none;
}
}

70
app/install/page.tsx Normal file
View File

@@ -0,0 +1,70 @@
import type { Metadata } from 'next';
import { redirect } from 'next/navigation';
import {
isInstalled,
getInstallCredentials,
getSetupToken,
validateSetupToken,
} from '@/lib/install';
import { InstallWizard } from './InstallWizard';
export const metadata: Metadata = {
title: 'Install Immich Folio',
robots: { index: false, follow: false },
};
/**
* Rendered per request so the CSP nonce issued by proxy.ts lands on the script
* tags — same reason /admin is force-dynamic. Also what lets the redirect once
* setup is complete take effect on the next navigation, not a future build.
*/
export const dynamic = 'force-dynamic';
export default async function InstallPage({
searchParams,
}: {
searchParams: Promise<{ token?: string }>;
}) {
if (isInstalled()) {
redirect('/');
}
const { token } = await searchParams;
if (!validateSetupToken(token ?? null)) {
// Force evaluation of the token so it is logged.
getSetupToken();
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
minHeight: '60dvh',
padding: '2rem',
fontFamily: 'system-ui, sans-serif',
}}
>
<div style={{ maxWidth: '600px', width: '100%', textAlign: 'center' }}>
<h1
style={{
fontSize: 'clamp(2rem, 5vw, 3rem)',
fontWeight: 500,
marginBottom: '0.5rem',
letterSpacing: '-0.02em',
}}
>
Setup Token Required
</h1>
<p style={{ fontSize: '1.125rem', opacity: 0.7, lineHeight: 1.5 }}>
Check your server logs for the one-time setup token and append <code>?token=</code> to
this URL.
</p>
</div>
</div>
);
}
const creds = getInstallCredentials();
return <InstallWizard initialApiUrl={creds.apiUrl} setupToken={token!} />;
}

203
app/journal/[slug]/page.tsx Normal file
View File

@@ -0,0 +1,203 @@
import { notFound } from 'next/navigation';
import { cookies } from 'next/headers';
import type { Metadata } from 'next';
import { readJournalEntry } from '@/lib/admin/journal-service';
import type { ParsedJournal } from '@/lib/journal';
import { isAdminAuthenticated } from '@/lib/admin/auth';
import { getConfig } from '@/lib/config';
import { immich } from '@/lib/immich';
import {
imageUrl,
exifUrl,
assetPlaceholder,
assetAspectRatio,
assetExifSummary,
} from '@/lib/urls';
import { encodeAssetId } from '@/lib/tokens';
import { EssayView } from '@/app/[...path]/EssayView';
import type { PhotoItem } from '@/app/[...path]/PhotoGrid';
import type { ImmichAsset } from '@/lib/immich';
import PasswordGate from '@/components/PasswordGate';
import { BackLink } from '@/components/BackLink';
import { verifyScrypt, isScryptHash } from '@/lib/password';
import crypto from 'crypto';
export const dynamic = 'force-dynamic';
interface JournalDetailPageProps {
params: Promise<{ slug: string }>;
}
export async function generateMetadata({ params }: JournalDetailPageProps): Promise<Metadata> {
const { slug } = await params;
const entry = await readJournalEntry(slug);
if (!entry) return { title: 'Not Found' };
const { frontmatter } = entry.parsed;
const title = frontmatter.title || slug;
const description = frontmatter.subtitle || 'Journal entry on Immich Folio';
const ogImages = frontmatter.coverAssetId
? [{ url: imageUrl(frontmatter.coverAssetId, 'preview') }]
: [];
return {
title,
description,
openGraph: {
title,
description,
images: ogImages,
},
};
}
/** Check if journal entry password cookie is valid */
function isJournalAuthenticated(
slug: string,
storedPassword?: string,
cookieVal?: string,
): boolean {
if (!storedPassword) return true;
if (!cookieVal) return false;
const sep = cookieVal.indexOf('.');
if (sep === -1) return false;
const expiresAt = Number(cookieVal.slice(0, sep));
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return false;
const hmac = crypto
.createHmac('sha256', getConfig().authSecret)
.update(`${slug}:${storedPassword}:${expiresAt}`)
.digest('hex');
const expected = `${expiresAt}.${hmac}`;
try {
const a = Buffer.from(cookieVal, 'utf8');
const b = Buffer.from(expected, 'utf8');
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
} catch {
return false;
}
}
export default async function JournalDetailPage({ params }: JournalDetailPageProps) {
const { slug } = await params;
const entry = await readJournalEntry(slug);
if (!entry) {
notFound();
}
const { frontmatter, blocks, referencedAssetIds } = entry.parsed;
const isAuthedAdmin = await isAdminAuthenticated();
// If draft, only visible to authenticated admin
if (frontmatter.draft && !isAuthedAdmin) {
notFound();
}
// Password protection check
if (frontmatter.password) {
const cookieStore = await cookies();
const cookieVal = cookieStore.get(`lb_auth_journal_${slug}`)?.value;
if (!isJournalAuthenticated(slug, frontmatter.password, cookieVal)) {
return <PasswordGate slug={slug} title={frontmatter.title || slug} type="journal" />;
}
}
const config = getConfig();
// Fetch all referenced assets from Immich
const assetPromises = referencedAssetIds.map(async (assetId) => {
try {
const asset = await immich.getAssetInfo(assetId);
return asset;
} catch {
return null;
}
});
const rawAssets = (await Promise.all(assetPromises)).filter((a): a is ImmichAsset => a !== null);
// EssayView drops photo blocks it cannot resolve, which is right for visitors
// but leaves no trace of *why* a photo vanished. Legacy positional references
// ("1", "2") are the usual cause: they only resolved against a subpage album,
// and a standalone journal entry has none.
if (rawAssets.length < referencedAssetIds.length) {
const resolved = new Set(rawAssets.map((a) => a.id));
const missing = referencedAssetIds.filter((id) => !resolved.has(id));
// eslint-disable-next-line no-console
console.warn(
`[journal] ${slug}: ${missing.length} photo reference(s) could not be resolved and will not render: ${missing.join(', ')}`,
);
}
/*
* EssayView resolves a block's photo through PhotoItem.id, and those ids are
* encrypted tokens — while the blocks coming out of the Markdown carry raw
* asset UUIDs. Without this translation every photo block fails its lookup and
* is dropped, so a correctly authored entry renders text only. Doing it here
* also keeps raw UUIDs out of the client payload, per the project rule that
* they must never reach the browser. Unresolvable references collapse to an
* empty string, which EssayView skips.
*/
const tokenByAssetId = new Map(rawAssets.map((a) => [a.id, encodeAssetId(a.id)]));
const toToken = (assetId: string) => tokenByAssetId.get(assetId) ?? '';
const essayForClient: ParsedJournal = {
frontmatter: {
...frontmatter,
coverAssetId: frontmatter.coverAssetId ? toToken(frontmatter.coverAssetId) : undefined,
},
blocks: blocks.map((block) => {
if (block.type === 'photo') {
return { ...block, assetId: toToken(block.assetId) };
}
if (block.type === 'photo-pair') {
return {
...block,
assetIds: [toToken(block.assetIds[0]), toToken(block.assetIds[1])] as [string, string],
};
}
return block;
}),
referencedAssetIds: rawAssets.map((a) => encodeAssetId(a.id)),
};
const images: PhotoItem[] = rawAssets
.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO')
.map((a) => {
const ph = assetPlaceholder(a);
const exif = config.exifOnHover && a.type === 'IMAGE' ? assetExifSummary(a) : undefined;
const isVideo = a.type === 'VIDEO';
return {
id: encodeAssetId(a.id),
type: isVideo ? 'video' : 'image',
thumbUrl: imageUrl(a.id, 'preview'),
previewUrl: imageUrl(a.id, 'preview'),
exifUrl: exifUrl(a.id),
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),
...(exif ?? {}),
aspectRatio: assetAspectRatio(a),
};
});
return (
<div style={{ paddingTop: '2rem' }}>
<div style={{ maxWidth: '1100px', margin: '0 auto', padding: '0 1.5rem 1rem' }}>
<BackLink href="/journal" label="Back to Journal" />
</div>
<EssayView
essay={essayForClient}
assets={images}
title={frontmatter.title}
subtitle={frontmatter.subtitle}
watermark={config.watermark}
/>
</div>
);
}

176
app/journal/journal.css Normal file
View File

@@ -0,0 +1,176 @@
/* ── Journal Index & Reader Styling ───────────────────────────── */
.journal-index-container {
max-width: 1200px;
margin: 0 auto;
padding: 3rem 1.5rem 6rem;
}
.journal-index-header {
margin-bottom: 3.5rem;
text-align: left;
}
.journal-index-header__kicker {
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.15em;
opacity: 0.6;
margin-bottom: 0.5rem;
}
.journal-index-header__title {
font-size: clamp(2.2rem, 4.5vw, 3.5rem);
font-weight: 700;
line-height: 1.1;
letter-spacing: -0.02em;
margin: 0 0 0.75rem;
}
.journal-index-header__subtitle {
font-size: 1.1rem;
opacity: 0.75;
margin: 0;
max-width: 600px;
line-height: 1.5;
}
.journal-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
gap: 2.5rem;
}
.journal-card {
display: flex;
flex-direction: column;
text-decoration: none;
color: inherit;
background: var(--surface, rgba(255, 255, 255, 0.03));
border: 1px solid var(--border, rgba(255, 255, 255, 0.08));
border-radius: 12px;
overflow: hidden;
transition: transform 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease;
}
.journal-card:hover {
transform: translateY(-4px);
border-color: var(--border-hover, rgba(255, 255, 255, 0.2));
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
}
.journal-card__cover {
position: relative;
width: 100%;
aspect-ratio: 16 / 10;
background: var(--surface-subtle, rgba(255, 255, 255, 0.02));
overflow: hidden;
}
.journal-card__cover img {
object-fit: cover;
transition: transform 0.4s ease;
}
.journal-card:hover .journal-card__cover img {
transform: scale(1.03);
}
.journal-card__cover-empty {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
opacity: 0.3;
font-size: 2rem;
}
.journal-card__content {
padding: 1.75rem;
display: flex;
flex-direction: column;
flex-grow: 1;
}
.journal-card__meta {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.08em;
opacity: 0.6;
margin-bottom: 0.75rem;
}
.journal-card__title {
font-size: 1.35rem;
font-weight: 700;
line-height: 1.25;
margin: 0 0 0.5rem;
letter-spacing: -0.01em;
}
.journal-card__subtitle {
font-size: 0.95rem;
line-height: 1.45;
opacity: 0.8;
margin: 0 0 1rem;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.journal-card__excerpt {
font-size: 0.85rem;
line-height: 1.5;
opacity: 0.65;
margin: 0 0 1.25rem;
flex-grow: 1;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.journal-card__footer {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 1rem;
border-top: 1px solid var(--border, rgba(255, 255, 255, 0.06));
font-size: 0.8rem;
font-weight: 500;
}
.journal-card__read-more {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--accent, #6366f1);
transition: gap 0.2s ease;
}
.journal-card:hover .journal-card__read-more {
gap: 8px;
}
.journal-card__draft-badge {
display: inline-block;
padding: 2px 8px;
background: rgba(234, 179, 8, 0.15);
color: #eab308;
border-radius: 4px;
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
}
.journal-empty-state {
text-align: center;
padding: 5rem 1rem;
opacity: 0.7;
}

147
app/journal/page.tsx Normal file
View File

@@ -0,0 +1,147 @@
import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import { type JournalEntrySummary } from '@/lib/journal';
import { listJournalEntries } from '@/lib/admin/journal-service';
import { isAdminAuthenticated } from '@/lib/admin/auth';
import { immich } from '@/lib/immich';
import { imageUrl, assetPlaceholder } from '@/lib/urls';
import { BackLink } from '@/components/BackLink';
import './journal.css';
export const dynamic = 'force-dynamic';
export const metadata: Metadata = {
title: 'Journal',
description: 'Photo essays, travel stories, and behind-the-scenes journals.',
};
interface EnrichedJournalEntry extends JournalEntrySummary {
coverUrl?: string;
blurDataURL?: string;
dominantColor?: string;
}
export default async function JournalIndexPage() {
const isAuthedAdmin = await isAdminAuthenticated();
const allEntries = await listJournalEntries();
// Non-admins only see published entries
const visibleEntries = isAuthedAdmin
? allEntries
: allEntries.filter((e) => !e.frontmatter.draft);
// Fetch cover image placeholders and URLs
const enrichedEntries: EnrichedJournalEntry[] = await Promise.all(
visibleEntries.map(async (entry) => {
if (!entry.frontmatter.coverAssetId) {
return entry;
}
try {
const asset = await immich.getAssetInfo(entry.frontmatter.coverAssetId);
const ph = asset ? assetPlaceholder(asset) : null;
return {
...entry,
coverUrl: imageUrl(entry.frontmatter.coverAssetId, 'preview'),
blurDataURL: ph?.blurDataURL,
dominantColor: ph?.dominantColor,
};
} catch {
return {
...entry,
coverUrl: imageUrl(entry.frontmatter.coverAssetId, 'preview'),
};
}
}),
);
return (
<div className="journal-index-container">
<div className="journal-index-header">
<BackLink href="/" label="Back to Gallery" />
<p className="journal-index-header__kicker" aria-hidden="true">
Stories &amp; Essays
</p>
<h1 className="journal-index-header__title">Journal</h1>
<p className="journal-index-header__subtitle">
Photo essays, visual stories, and field notes.
</p>
</div>
{enrichedEntries.length === 0 ? (
<div className="journal-empty-state">
<p>No journal entries published yet.</p>
</div>
) : (
<div className="journal-grid">
{enrichedEntries.map((entry) => {
const dateStr = entry.frontmatter.date
? new Date(entry.frontmatter.date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
: null;
return (
<Link key={entry.slug} href={`/journal/${entry.slug}`} className="journal-card">
<div
className="journal-card__cover"
style={{
...(entry.dominantColor ? { backgroundColor: entry.dominantColor } : {}),
}}
>
{entry.coverUrl ? (
<Image
src={entry.coverUrl}
alt={entry.frontmatter.title || entry.slug}
fill
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 380px"
placeholder={entry.blurDataURL ? 'blur' : 'empty'}
blurDataURL={entry.blurDataURL}
/>
) : (
<div className="journal-card__cover-empty">📖</div>
)}
</div>
<div className="journal-card__content">
<div className="journal-card__meta">
{dateStr && <span>{dateStr}</span>}
{dateStr && entry.readingTimeMinutes && <span>•</span>}
{entry.readingTimeMinutes && <span>{entry.readingTimeMinutes} min read</span>}
{entry.frontmatter.draft && (
<span className="journal-card__draft-badge">Draft</span>
)}
</div>
<h2 className="journal-card__title">{entry.frontmatter.title || entry.slug}</h2>
{entry.frontmatter.subtitle && (
<p className="journal-card__subtitle">{entry.frontmatter.subtitle}</p>
)}
{/*
extractExcerpt() falls back to the subtitle when there is
one, so rendering both printed the same sentence twice.
*/}
{entry.excerpt && entry.excerpt !== entry.frontmatter.subtitle && (
<p className="journal-card__excerpt">{entry.excerpt}</p>
)}
<div className="journal-card__footer">
<span className="journal-card__read-more">Read Story →</span>
{entry.frontmatter.author && (
<span style={{ opacity: 0.65 }}>by {entry.frontmatter.author}</span>
)}
</div>
</div>
</Link>
);
})}
</div>
)}
</div>
);
}

View File

@@ -15,6 +15,7 @@ import { Footer } from '@/components/Footer';
import { SetupScreen } from '@/components/SetupScreen'; import { SetupScreen } from '@/components/SetupScreen';
import { getConfigOrNull, getGoogleFontsUrl, AppConfig } from '@/lib/config'; import { getConfigOrNull, getGoogleFontsUrl, AppConfig } from '@/lib/config';
import { isAdminPath } from '@/lib/admin/paths'; import { isAdminPath } from '@/lib/admin/paths';
import { isInstallPath } from '@/lib/install';
// DevToolbarLoader is a Client Component (ssr: false is only allowed there) // DevToolbarLoader is a Client Component (ssr: false is only allowed there)
import { DevToolbarLoader } from '@/components/DevToolbarLoader'; import { DevToolbarLoader } from '@/components/DevToolbarLoader';
import AssetProtection from '@/components/AssetProtection'; import AssetProtection from '@/components/AssetProtection';
@@ -24,7 +25,11 @@ export async function generateMetadata(): Promise<Metadata> {
const config = getConfigOrNull(); const config = getConfigOrNull();
if (!config) { if (!config) {
// Nothing to describe, and nothing that should be indexed while broken. // Nothing to describe, and nothing that should be indexed while broken.
return { title: 'Setup Required', robots: { index: false, follow: false } }; return {
title: 'Setup Required',
robots: { index: false, follow: false },
icons: { icon: '/api/favicon' },
};
} }
const siteTitle = config.seo.title; const siteTitle = config.seo.title;
@@ -42,6 +47,7 @@ export async function generateMetadata(): Promise<Metadata> {
description: siteDescription, description: siteDescription,
robots, robots,
icons: { icons: {
icon: '/api/favicon',
apple: '/apple-touch-icon.png', apple: '/apple-touch-icon.png',
}, },
openGraph: { openGraph: {
@@ -71,7 +77,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
if (!config) { if (!config) {
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body>{isAdminPath(pathname) ? children : <SetupScreen />}</body> <body>{isAdminPath(pathname) || isInstallPath(pathname) ? children : <SetupScreen />}</body>
</html> </html>
); );
} }
@@ -90,9 +96,14 @@ export default async function RootLayout({ children }: { children: React.ReactNo
'--radius-lg': `${theme.radius * 2}px`, '--radius-lg': `${theme.radius * 2}px`,
}; };
// /admin stays reachable during setup — it is the tool that completes the // /admin and /install stay reachable during setup — /admin is the tool that
// setup, so the setup screen must not lock it out (#326). // completes an existing setup, /install is the wizard that performs the first
if ((config as AppConfig & { needsSetup?: boolean }).needsSetup && !isAdminPath(pathname)) { // one, so the setup screen must not lock either of them out (#326).
if (
(config as AppConfig & { needsSetup?: boolean }).needsSetup &&
!isAdminPath(pathname) &&
!isInstallPath(pathname)
) {
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body> <body>
@@ -153,7 +164,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
{children} {children}
</main> </main>
<Footer /> <Footer />
<ScrollToTop /> {config.scrollToTop && <ScrollToTop />}
<AssetProtection <AssetProtection
disableRightClick={config.protection?.disableRightClick} disableRightClick={config.protection?.disableRightClick}
disableImageDrag={config.protection?.disableImageDrag} disableImageDrag={config.protection?.disableImageDrag}

View File

@@ -33,9 +33,22 @@ interface LightboxProps {
onNext: () => void; onNext: () => void;
onPrev: () => void; onPrev: () => void;
watermark?: LightboxWatermark; watermark?: LightboxWatermark;
/**
* Show the EXIF ("Info") toggle. Off for editorial contexts such as journal
* entries, where a technical data panel interrupts the story.
*/
showExifToggle?: boolean;
} }
export function Lightbox({ assets, currentIndex, onClose, onNext, onPrev, watermark }: LightboxProps) { export function Lightbox({
assets,
currentIndex,
onClose,
onNext,
onPrev,
watermark,
showExifToggle = true,
}: LightboxProps) {
const [showExif, setShowExif] = useState(false); const [showExif, setShowExif] = useState(false);
const { exifData, exifLoading, fetchExif, clearExif } = useExif(); const { exifData, exifLoading, fetchExif, clearExif } = useExif();
const [imageLoaded, setImageLoaded] = useState(false); const [imageLoaded, setImageLoaded] = useState(false);
@@ -95,16 +108,39 @@ export function Lightbox({ assets, currentIndex, onClose, onNext, onPrev, waterm
onSwipeRight: onPrev, onSwipeRight: onPrev,
}); });
// Listen for 'i' key to toggle EXIF /*
* Keyboard control and the scroll lock belong to the lightbox, not to whoever
* opens it: PhotoGrid used to install the arrow keys itself, so every other
* caller (EssayView, i.e. journal entries and photo essays) silently had no
* keyboard navigation at all.
*/
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'i' || e.key === 'I') { switch (e.key) {
handleExifToggle(); case 'Escape':
onClose();
break;
case 'ArrowRight':
onNext();
break;
case 'ArrowLeft':
onPrev();
break;
case 'i':
case 'I':
if (showExifToggle) handleExifToggle();
break;
} }
}; };
document.addEventListener('keydown', handleKeyDown); document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown); document.body.style.overflow = 'hidden';
}, [handleExifToggle]);
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = '';
};
}, [handleExifToggle, onClose, onNext, onPrev, showExifToggle]);
// Click on overlay background → close // Click on overlay background → close
const handleOverlayClick = useCallback( const handleOverlayClick = useCallback(
@@ -211,8 +247,8 @@ export function Lightbox({ assets, currentIndex, onClose, onNext, onPrev, waterm
watermark.position === 'bottom-left' watermark.position === 'bottom-left'
? styles.watermark_bottom_left ? styles.watermark_bottom_left
: watermark.position === 'center' : watermark.position === 'center'
? styles.watermark_center ? styles.watermark_center
: styles.watermark_bottom_right : styles.watermark_bottom_right
}`} }`}
style={{ opacity: (watermark.opacity ?? 50) / 100 }} style={{ opacity: (watermark.opacity ?? 50) / 100 }}
> >
@@ -268,16 +304,18 @@ export function Lightbox({ assets, currentIndex, onClose, onNext, onPrev, waterm
)} )}
{/* EXIF toggle */} {/* EXIF toggle */}
<button {showExifToggle && (
className={styles.infoToggle} <button
onClick={handleExifToggle} className={styles.infoToggle}
aria-expanded={showExif} onClick={handleExifToggle}
aria-controls="exif-panel" aria-expanded={showExif}
aria-label="Toggle photo info" aria-controls="exif-panel"
title="Toggle photo info (i)" aria-label="Toggle photo info"
> title="Toggle photo info (i)"
{showExif ? 'Hide Info' : 'Info'} >
</button> {showExif ? 'Hide Info' : 'Info'}
</button>
)}
{/* EXIF panel */} {/* EXIF panel */}
{showExif && ( {showExif && (

View File

@@ -11,7 +11,7 @@ import styles from './PasswordGate.module.css';
interface PasswordGateProps { interface PasswordGateProps {
slug: string; slug: string;
title: string; title: string;
type?: 'subpage' | 'album'; type?: 'subpage' | 'album' | 'journal';
} }
export default function PasswordGate({ slug, title, type = 'subpage' }: PasswordGateProps) { export default function PasswordGate({ slug, title, type = 'subpage' }: PasswordGateProps) {

View File

@@ -1,27 +1,40 @@
/** /**
* ScrollToTop — fixed ↑ button that appears after scrolling down. * ScrollToTop — fixed back-to-top button that fades in after scrolling down.
* Smooth-scrolls back to the top when clicked. * Toggled site-wide via `scrollToTop` in settings.yaml.
*/ */
'use client'; 'use client';
import { useState, useEffect } from 'react'; import { useState, useEffect, useRef } from 'react';
const SHOW_THRESHOLD = 300; const SHOW_THRESHOLD = 300;
export function ScrollToTop() { export function ScrollToTop() {
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const frame = useRef<number | null>(null);
useEffect(() => { useEffect(() => {
const onScroll = () => { const measure = () => {
frame.current = null;
setVisible(window.scrollY > SHOW_THRESHOLD); setVisible(window.scrollY > SHOW_THRESHOLD);
}; };
// rAF-throttled: one state update per frame, not one per scroll event.
const onScroll = () => {
if (frame.current === null) frame.current = requestAnimationFrame(measure);
};
measure();
window.addEventListener('scroll', onScroll, { passive: true }); window.addEventListener('scroll', onScroll, { passive: true });
return () => window.removeEventListener('scroll', onScroll); return () => {
window.removeEventListener('scroll', onScroll);
if (frame.current !== null) cancelAnimationFrame(frame.current);
};
}, []); }, []);
const scrollToTop = () => { const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: 'smooth' }); const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
window.scrollTo({ top: 0, behavior: reduced ? 'auto' : 'smooth' });
}; };
return ( return (
@@ -34,7 +47,20 @@ export function ScrollToTop() {
tabIndex={visible ? 0 : -1} tabIndex={visible ? 0 : -1}
aria-hidden={!visible} aria-hidden={!visible}
> >
↑ <svg
className="scroll-to-top__icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
<path d="M12 18.75V6.25" />
<path d="m6.5 11.75 5.5-5.5 5.5 5.5" />
</svg>
</button> </button>
); );
} }

View File

@@ -5,13 +5,17 @@
import Link from 'next/link'; import Link from 'next/link';
import { immich } from '@/lib/immich'; import { immich } from '@/lib/immich';
import { listJournalEntries } from '@/lib/admin/journal-service';
export async function SubpageNav() { export async function SubpageNav() {
const [subpages, standaloneAlbums] = await Promise.all([ const [subpages, standaloneAlbums, journalEntries] = await Promise.all([
immich.getSubpages(), immich.getSubpages(),
immich.getStandaloneAlbums(), immich.getStandaloneAlbums(),
listJournalEntries().catch(() => []),
]); ]);
const hasPublicJournal = journalEntries.some((e) => !e.frontmatter.draft);
return ( return (
<> <>
{subpages.map((sp) => ( {subpages.map((sp) => (
@@ -19,6 +23,11 @@ export async function SubpageNav() {
{sp.name} {sp.name}
</Link> </Link>
))} ))}
{hasPublicJournal && (
<Link href="/journal" className="header__nav-link">
Journal
</Link>
)}
{standaloneAlbums.map((album) => ( {standaloneAlbums.map((album) => (
<Link key={album.id} href={`/${album.slug}`} className="header__nav-link"> <Link key={album.id} href={`/${album.slug}`} className="header__nav-link">
{album.albumName} {album.albumName}

View File

@@ -24,6 +24,9 @@ map: true
# Enable smooth page transitions between routes # Enable smooth page transitions between routes
transitions: true transitions: true
# Show the floating back-to-top arrow on long pages
scrollToTop: true
# Client proofing & favorite photo selections # Client proofing & favorite photo selections
# proofing: # proofing:
# enabled: true # enabled: true

View File

@@ -66,7 +66,7 @@ The **Settings** tab lets you configure global site behavior:
| Section | Controls | | Section | Controls |
| --------- | ---------------------------------------------------------------- | | --------- | ---------------------------------------------------------------- |
| General | Site title, subtitle, language, EXIF on hover, map, transitions | | General | Site title, subtitle, language, EXIF on hover, map, transitions, scroll-to-top |
| Theme | Preset, accent color, photo frame, hero style, grain, header dot | | Theme | Preset, accent color, photo frame, hero style, grain, header dot |
| Grid | Layout mode, columns, gap, aspect ratio | | Grid | Layout mode, columns, gap, aspect ratio |
| Footer | Name, Instagram, email, website | | Footer | Name, Instagram, email, website |

View File

@@ -0,0 +1,116 @@
# Design-Spezifikation: Journal Studio (Foto-Essays & Stories)
_Status: Entwurf genehmigt (Brainstorming abgeschlossen) · Datum: 2026-08-14_
---
## 1. Understanding Summary
- **Ziel & Vision:** Bereitstellung eines intuitiven, erstklassigen **Journal Studios** für Fotografen, um Bild-Text-Reportagen, Reisetagebücher und Ausstellungsberichte (im Stil von Leica Journal / National Geographic) zu verfassen und zu veröffentlichen.
- **Zielgruppe:**
- **Besucher:** Immersives, typografisch elegantes Leseerlebnis mit progressiv ladenden Bildern (ThumbHash), responsiven Layouts und Lightbox-Interaktion.
- **Fotograf:** Mühelose Redaktion im Admin-Panel mit Live-Split-Screen-Vorschau und universeller Immich-Bildauswahl.
- **Konzept:** Reines Markdown mit Frontmatter im Content-Volume (`content/journal/*.md`), verwaltet über eine dedizierte Admin-UI und ausgeliefert über saubere Next.js Server Components.
- **Kern-Vorteile:**
- Trennung von Galerie-Konfiguration (`gallery.yaml`) und redaktionellen Inhalten.
- Volle Git- & Backup-Kompatibilität durch Standard-Markdown.
- Schnelle Erstellung ohne manuelle UUID-Eingabe.
---
## 2. Annahmen (Assumptions)
1. **Storage-Pfad:** Journal-Einträge werden standardmäßig unter `content/journal/[slug].md` gespeichert.
2. **Bild-Referenzierung:** Bilder verweisen über `![Alt Text](asset:IMMICH_UUID)` auf Immich-Assets und werden über den internen Image-Proxy mit Cache und ThumbHash ausgeliefert.
3. **Theming:** Die Leseansicht (`/journal/[slug]`) bindet sich nahtlos an das global konfigurierte Design-Theme an (CSS-Variablen, Fonts, Margins).
4. **Resilienz:** Nicht auffindbare Bilder führen nicht zu einem Seitenabsturz, sondern werden durch neutrale Platzhalter ersetzt.
---
## 3. Decision Log
| # | Entscheidung | Alternativen | Begründung |
|---|---|---|---|
| 1 | **Nomenklatur "Journal"** | Stories, Photo Essays, Magazin | "Stories" wirkt wie flüchtige Social-Media-Inhalte. "Journal" spiegelt zeitlose, fotografische Wertigkeit (wie Leica Journal) wider. |
| 2 | **Architektur-Ansatz 1 (Eigenständiges Studio)** | Subpage-Drawer, Quick-Fix | Maximale Schreib- und Layout-Ergonomie durch echten Split-Screen und Entkopplung von `gallery.yaml`. |
| 3 | **Persistenz als `.md`-Dateien** | Strings in `gallery.yaml`, SQLite/DB | Behält das dateibasierte, zustandsarme Self-Hosting-Paradigma bei; einfache Versionierung via Git. |
| 4 | **Bidirektionaler Editor (Blöcke ↔ Markdown)** | Nur WYSIWYG, Nur Markdown | Fotografen können visuell Blöcke anordnen oder direkt mit Markdown-Code arbeiten, ohne Datenverlust. |
| 5 | **Sicherheit via Slug-Sanitisierung** | Ungeprüfte Dateinamen | Verhindert Path Traversal (`../`) im Docker-Container/Dateisystem. |
---
## 4. Technische Architektur & Komponenten
### A. Dateisystem & Datenmodell
Jeder Eintrag ist eine `.md`-Datei mit folgendem Schema:
```markdown
---
title: "Expedition Nordkap"
subtitle: "Mit dem Bulli durch die Fjorde"
date: "2026-08-14"
author: "Ralf"
coverAssetId: "b8c2d111-0000-4000-8000-000000000000"
password: "" # Optionaler Passwortschutz (scrypt)
draft: false # Entwurf oder öffentlich
---
Hier beginnt der Text der Reportage...
![Fjord im Abendlicht](asset:93f812ab-1111-4000-8000-000000000000)
```
Unterstützte Block-Typen:
- **Heading:** `# H1`, `## H2`, `### H3`
- **Paragraph:** Fliesstext mit Inline-Markdown (`**fett**`, `*kursiv*`, `[Link](url)`)
- **Pullquote:** `> Zitattext` mit optionalem `— Autor`
- **Photo (Fullbleed / Wide / Contained):** `![Caption](asset:UUID)`
- **Photo-Pair (2-Spaltig):** Zwei aufeinanderfolgende `asset:`-Bilder
---
### B. Admin API Endpunkte (`/api/admin/journal`)
- **`GET /api/admin/journal`**: Liefert Liste aller Einträge (geparstes Frontmatter, Slug, Cover-Thumbnail, Word Count / Read Time).
- **`GET /api/admin/journal/[slug]`**: Liefert vollen Inhalt & Metadaten eines spezifischen Eintrags.
- **`PUT /api/admin/journal/[slug]`**: Speichert den Eintrag atomar (Write to `.tmp` ➔ Rename), legt `.bak`-Sicherungen an und validiert den Markdown-Baum.
- **`DELETE /api/admin/journal/[slug]`**: Löscht die `.md`-Datei nach Bestätigung.
---
### C. UI: Das Journal Studio (`/admin` ➔ Tab "Journal")
1. **Journal Dashboard:**
- Übersicht aller Einträge als Karten mit Thumbnail, Status (*Draft*, *Live*, *Protected*), Erstellungsdatum.
- Button `+ New Journal Entry`.
2. **Studio Split-Screen Editor:**
- **Top Navigation:** Titel-Eingabe, Slug, Status-Schalter, Metadaten-Modal (Autor, Datum, Passwort, Cover-Foto) und Save-Button (`Cmd+S`).
- **Linker Bereich (Authoring):**
- Umschaltbar zwischen **[Visual Blocks]** (Karten mit Drag & Drop Griffleisten) und **[Raw Markdown]**.
- Universeller Asset-Picker für Fotos aus allen Immich-Alben.
- **Rechter Bereich (Live Preview):**
- 1:1 Rendering via `EssayView` mit den CSS-Variablen des aktiven Themes.
- Viewport-Umschalter (Desktop / Mobile).
---
### D. Frontend Routing & Rendering
- **`/journal`**: Übersicht aller veröffentlichten Journal-Einträge mit Cover-Bildern und Exzerpten.
- **`/journal/[slug]`**: Detailansicht der Reportage mit Passwort-Gate (`PasswordGate`) bei geschützten Einträgen.
- **Subpage-Integration:** Kompatibilität mit `gallery.yaml` (`essayFile: "nordkap.md"`) bleibt vollständig erhalten.
---
## 5. Test- & Absicherungsstrategie
1. **Unit-Tests (`lib/__tests__/journal.test.ts`):**
- Frontmatter-Parsing & -Serialisierung.
- XSS-Sanitisierung bei bösartigem Markdown-HTML.
- Block-Transformation (Fullbleed, Pairs, Quotes).
2. **API-Tests (`app/api/admin/journal/__tests__/route.test.ts`):**
- Auth-Schutz (401/403 bei nicht-angemeldeten Requests).
- Path-Traversal-Abwehr (Rejection von `../`, `%2e%2e%2f`).
- Atomare Speicherung und Fehlerbehandlung bei Disk-Fehlern.
3. **E2E / Integration:**
- Aufruf von `/journal/[slug]` im Browser und Verifikation des Lightbox-Klicks auf eingebettete Fotos.

View File

@@ -9,6 +9,15 @@ const AUTH_SECRET = 'test-auth-secret-32-chars-long-min';
vi.mock('../env', () => ({ vi.mock('../env', () => ({
env: { env: {
IMMICH_API_URL: '',
IMMICH_API_KEY: '',
SITE_TITLE: 'Test',
SITE_SUBTITLE: '',
CACHE_TTL: 300,
IMAGE_CACHE_VERSION: '',
IMMICH_TIMEOUT_MS: 15000,
RATE_LIMIT_RPM: 1500,
TRUSTED_PROXY_HOPS: 0,
get AUTH_SECRET() { get AUTH_SECRET() {
return process.env.__TEST_AUTH_SECRET; return process.env.__TEST_AUTH_SECRET;
}, },
@@ -18,6 +27,21 @@ vi.mock('../env', () => ({
}, },
})); }));
vi.mock('../install', () => ({
getInstallCredentials() {
return {
apiUrl: '',
apiKey: '',
authSecret: process.env.__TEST_AUTH_SECRET || '',
adminPassword: process.env.__TEST_ADMIN_PASSWORD || '',
};
},
isInstalled: () => false,
isInstallPath: () => false,
normalizeApiBase: (): string => '',
completeInstall: () => {},
}));
/** Import fresh so module-level state cannot leak between cases. */ /** Import fresh so module-level state cannot leak between cases. */
async function loadAuth() { async function loadAuth() {
vi.resetModules(); vi.resetModules();
@@ -73,9 +97,14 @@ describe('admin session tokens', () => {
it('throws rather than signing with a guessable secret when AUTH_SECRET is unset in production', async () => { it('throws rather than signing with a guessable secret when AUTH_SECRET is unset in production', async () => {
delete process.env.__TEST_AUTH_SECRET; delete process.env.__TEST_AUTH_SECRET;
vi.stubEnv('NODE_ENV', 'production'); const prevNodeEnv = process.env.NODE_ENV;
const { createAdminToken } = await loadAuth(); (process.env as Record<string, string | undefined>).NODE_ENV = 'production';
expect(() => createAdminToken()).toThrow(/AUTH_SECRET/); try {
const { createAdminToken } = await loadAuth();
expect(() => createAdminToken()).toThrow(/AUTH_SECRET/);
} finally {
(process.env as Record<string, string | undefined>).NODE_ENV = prevNodeEnv;
}
}); });
it('returns false (not throw) for a malformed cookie with a short signature', async () => { it('returns false (not throw) for a malformed cookie with a short signature', async () => {
@@ -121,18 +150,18 @@ describe('admin session tokens', () => {
describe('verifyAdminPassword', () => { describe('verifyAdminPassword', () => {
it('accepts the configured password and rejects others', async () => { it('accepts the configured password and rejects others', async () => {
const { verifyAdminPassword } = await loadAuth(); const { verifyAdminPassword } = await loadAuth();
expect(verifyAdminPassword(ADMIN_PASSWORD)).toBe(true); expect(await verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
expect(verifyAdminPassword('wrong')).toBe(false); expect(await verifyAdminPassword('wrong')).toBe(false);
expect(verifyAdminPassword(`${ADMIN_PASSWORD}x`)).toBe(false); expect(await verifyAdminPassword(`${ADMIN_PASSWORD}x`)).toBe(false);
expect(verifyAdminPassword('')).toBe(false); expect(await verifyAdminPassword('')).toBe(false);
}); });
it('rejects everything when no ADMIN_PASSWORD is configured', async () => { it('rejects everything when no ADMIN_PASSWORD is configured', async () => {
delete process.env.__TEST_ADMIN_PASSWORD; delete process.env.__TEST_ADMIN_PASSWORD;
const { verifyAdminPassword, isAdminEnabled } = await loadAuth(); const { verifyAdminPassword, isAdminEnabled } = await loadAuth();
expect(isAdminEnabled()).toBe(false); expect(isAdminEnabled()).toBe(false);
expect(verifyAdminPassword('')).toBe(false); expect(await verifyAdminPassword('')).toBe(false);
expect(verifyAdminPassword('anything')).toBe(false); expect(await verifyAdminPassword('anything')).toBe(false);
}); });
// The comparison used to run on the raw strings, so a length mismatch // The comparison used to run on the raw strings, so a length mismatch
@@ -144,18 +173,53 @@ describe('verifyAdminPassword', () => {
const sameLength = 'x'.repeat(ADMIN_PASSWORD.length); const sameLength = 'x'.repeat(ADMIN_PASSWORD.length);
expect(sameLength).toHaveLength(ADMIN_PASSWORD.length); expect(sameLength).toHaveLength(ADMIN_PASSWORD.length);
expect(sameLength).not.toBe(ADMIN_PASSWORD); expect(sameLength).not.toBe(ADMIN_PASSWORD);
expect(verifyAdminPassword(sameLength)).toBe(false); expect(await verifyAdminPassword(sameLength)).toBe(false);
}); });
it('rejects an oversized attempt without hashing it', async () => { it('rejects an oversized attempt without hashing it', async () => {
const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth(); const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth();
expect(verifyAdminPassword('x'.repeat(MAX_PASSWORD_LENGTH + 1))).toBe(false); expect(await verifyAdminPassword('x'.repeat(MAX_PASSWORD_LENGTH + 1))).toBe(false);
}); });
// A cap that a real passphrase could hit would be a lockout, not a fix. // A cap that a real passphrase could hit would be a lockout, not a fix.
it('still accepts the configured password when it is long', async () => { it('still accepts the configured password when it is long', async () => {
const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth(); const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth();
expect(ADMIN_PASSWORD.length).toBeLessThanOrEqual(MAX_PASSWORD_LENGTH); expect(ADMIN_PASSWORD.length).toBeLessThanOrEqual(MAX_PASSWORD_LENGTH);
expect(verifyAdminPassword(ADMIN_PASSWORD)).toBe(true); expect(await verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
});
// The wizard writes an scrypt hash; ADMIN_PASSWORD as an env var stays
// plaintext, because that is what every existing deployment has set. Getting
// either wrong locks the owner out of the panel that fixes it.
describe('accepts both stored formats', () => {
it('verifies against a wizard-written scrypt hash', async () => {
const { generateScryptHash } = await import('@/lib/password');
process.env.__TEST_ADMIN_PASSWORD = await generateScryptHash(ADMIN_PASSWORD);
const { verifyAdminPassword, isAdminEnabled } = await loadAuth();
expect(isAdminEnabled()).toBe(true);
expect(await verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
expect(await verifyAdminPassword('wrong')).toBe(false);
expect(await verifyAdminPassword('')).toBe(false);
});
// Someone who set ADMIN_PASSWORD in docker-compose must keep working after
// an upgrade — the hash support is additive, not a migration.
it('still verifies against a plaintext env password', async () => {
process.env.__TEST_ADMIN_PASSWORD = ADMIN_PASSWORD;
const { verifyAdminPassword } = await loadAuth();
expect(await verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
expect(await verifyAdminPassword('wrong')).toBe(false);
});
// The stored hash is never the password, so it must not be accepted as one.
it('does not accept the hash itself as the password', async () => {
const { generateScryptHash } = await import('@/lib/password');
const hash = await generateScryptHash(ADMIN_PASSWORD);
process.env.__TEST_ADMIN_PASSWORD = hash;
const { verifyAdminPassword } = await loadAuth();
expect(await verifyAdminPassword(hash)).toBe(false);
});
}); });
}); });

View File

@@ -39,10 +39,11 @@ function withGallery(gallery: unknown) {
/** /**
* The admin page builder can write each of these, and the root layout renders * The admin page builder can write each of these, and the root layout renders
* /admin inside itself — so a throw here would take down the site together with * /admin inside itself — so a throw here would take down the site together with
* the only tool that can undo the save. * the only tool that can undo the save. An empty gallery is deliberately NOT in
* this list: the install wizard can finish without selecting an album, so an
* empty gallery is now a valid, rendered state (see derive-gallery.test.ts).
*/ */
const UNDERIVABLE = { const UNDERIVABLE = {
'a gallery with neither albums nor subpages': { albums: [] },
'a subpage with no name': { albums: [ALBUM_ID], subpages: [{ albums: [ALBUM_ID] }] }, 'a subpage with no name': { albums: [ALBUM_ID], subpages: [{ albums: [ALBUM_ID] }] },
'a subpage with neither albums nor sections': { 'a subpage with neither albums nor sections': {
albums: [ALBUM_ID], albums: [ALBUM_ID],
@@ -61,6 +62,17 @@ describe('getConfig() rejects an underivable gallery.yaml', () => {
expect(() => getConfig()).toThrow(); expect(() => getConfig()).toThrow();
}); });
} }
it('accepts an empty gallery — a valid post-install state', () => {
// The install wizard may finish without selecting an album, so an empty
// gallery must render (title-only homepage) rather than take down the site.
withGallery({ albums: [] });
const config = getConfig();
expect(config.albums).toEqual([]);
expect(config.standaloneAlbums).toEqual([]);
expect(config.subpages).toEqual([]);
expect(config.needsSetup).toBe(false);
});
}); });
describe('getConfigOrNull()', () => { describe('getConfigOrNull()', () => {
@@ -81,7 +93,9 @@ describe('getConfigOrNull()', () => {
} }
it('logs the underlying error so the cause is diagnosable from the server log', () => { it('logs the underlying error so the cause is diagnosable from the server log', () => {
withGallery({ albums: [] }); // A nameless subpage is still underivable — an empty gallery is not (the
// install wizard can finish without an album, so that shape is now valid).
withGallery({ albums: [ALBUM_ID], subpages: [{ albums: [ALBUM_ID] }] });
getConfigOrNull(); getConfigOrNull();
expect(error).toHaveBeenCalled(); expect(error).toHaveBeenCalled();
@@ -89,7 +103,7 @@ describe('getConfigOrNull()', () => {
}); });
it('points at the backup directory, since that is the recovery path', () => { it('points at the backup directory, since that is the recovery path', () => {
withGallery({ albums: [] }); withGallery({ albums: [ALBUM_ID], subpages: [{ albums: [ALBUM_ID] }] });
getConfigOrNull(); getConfigOrNull();
expect(String(error.mock.calls[0][0])).toContain('content/.backups/'); expect(String(error.mock.calls[0][0])).toContain('content/.backups/');
}); });

View File

@@ -31,10 +31,6 @@ const B = '22222222-2222-2222-2222-222222222222';
* shapes the page builder can produce. * shapes the page builder can produce.
*/ */
describe('deriveGallery rejects what the site cannot load', () => { describe('deriveGallery rejects what the site cannot load', () => {
it('rejects a gallery with neither albums nor subpages', () => {
expect(() => deriveGallery({ albums: [] } as GalleryYaml)).toThrow(/at least one album/i);
});
it('rejects a subpage with no name', () => { it('rejects a subpage with no name', () => {
expect(() => expect(() =>
deriveGallery({ albums: [A], subpages: [{ albums: [A] }] } as unknown as GalleryYaml), deriveGallery({ albums: [A], subpages: [{ albums: [A] }] } as unknown as GalleryYaml),
@@ -67,6 +63,15 @@ describe('deriveGallery rejects what the site cannot load', () => {
}); });
describe('deriveGallery accepts valid structures', () => { describe('deriveGallery accepts valid structures', () => {
it('derives an empty gallery (no albums or subpages)', () => {
// The install wizard can finish without selecting an album, so an empty
// gallery must be a valid, rendered state rather than an error.
const result = deriveGallery({ albums: [] } as GalleryYaml);
expect(result.albums).toEqual([]);
expect(result.standaloneAlbums).toEqual([]);
expect(result.subpages).toEqual([]);
});
it('derives standalone albums', () => { it('derives standalone albums', () => {
const result = deriveGallery({ albums: [A, B] } as GalleryYaml); const result = deriveGallery({ albums: [A, B] } as GalleryYaml);
expect(result.albums).toEqual([A, B]); expect(result.albums).toEqual([A, B]);

View File

@@ -4,7 +4,15 @@ import { parseEssayMarkdown, parseFrontmatter, sanitizeHtml, renderInlineMarkdow
describe('Essay Parser', () => { describe('Essay Parser', () => {
it('sanitizes script tags to prevent XSS', () => { it('sanitizes script tags to prevent XSS', () => {
const input = 'Hello <script>alert("XSS")</script> World'; const input = 'Hello <script>alert("XSS")</script> World';
expect(sanitizeHtml(input)).toBe('Hello World'); // sanitizeHtml escapes rather than strips: the tag stays visible as the
// author's literal text but can no longer be parsed as markup. Asserting
// the old removed-substring output would assert the denylist that this
// replaced.
const out = sanitizeHtml(input);
expect(out).not.toContain('<');
expect(out).not.toContain('>');
expect(out).toContain('Hello');
expect(out).toContain('World');
}); });
it('renders inline markdown formatting correctly', () => { it('renders inline markdown formatting correctly', () => {

View File

@@ -0,0 +1,297 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
// Readable env getters, like admin-auth.test.ts, so tests can toggle which
// values come from the environment vs. the wizard file.
vi.mock('@/lib/env', () => ({
env: {
get IMMICH_API_URL() {
return process.env.__T_INSTALL_URL || '';
},
get IMMICH_API_KEY() {
return process.env.__T_INSTALL_KEY || '';
},
get AUTH_SECRET() {
return process.env.__T_INSTALL_SECRET || '';
},
get ADMIN_PASSWORD() {
return process.env.__T_INSTALL_ADMIN || '';
},
get INSTALL_CONTENT_DIR() {
return process.env.INSTALL_CONTENT_DIR || '';
},
},
}));
/** Import fresh so the module-level install-file cache cannot leak between cases. */
async function loadInstall() {
vi.resetModules();
return import('@/lib/install');
}
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'install-test-'));
vi.stubEnv('INSTALL_CONTENT_DIR', dir);
});
afterEach(() => {
vi.unstubAllEnvs();
delete process.env.__T_INSTALL_URL;
delete process.env.__T_INSTALL_KEY;
delete process.env.__T_INSTALL_SECRET;
delete process.env.__T_INSTALL_ADMIN;
fs.rmSync(dir, { recursive: true, force: true });
});
const ALBUM_ID = '11111111-1111-1111-1111-111111111111';
describe('getInstallCredentials', () => {
it('returns the file values when the environment is empty', async () => {
const { getInstallCredentials } = await loadInstall();
fs.writeFileSync(
path.join(dir, 'install.json'),
JSON.stringify({
apiUrl: 'https://file-immich:2283',
apiKey: 'file-key',
authSecret: 'file-secret',
adminPassword: 'file-admin',
}),
);
expect(getInstallCredentials()).toEqual({
apiUrl: 'https://file-immich:2283',
apiKey: 'file-key',
authSecret: 'file-secret',
adminPassword: 'file-admin',
});
});
it('lets environment variables win over the file', async () => {
const { getInstallCredentials } = await loadInstall();
process.env.__T_INSTALL_URL = 'https://env-immich:2283';
process.env.__T_INSTALL_KEY = 'env-key';
process.env.__T_INSTALL_SECRET = 'env-secret';
process.env.__T_INSTALL_ADMIN = 'env-admin';
fs.writeFileSync(
path.join(dir, 'install.json'),
JSON.stringify({
apiUrl: 'https://file-immich:2283',
apiKey: 'file-key',
authSecret: 'file-secret',
adminPassword: 'file-admin',
}),
);
expect(getInstallCredentials()).toEqual({
apiUrl: 'https://env-immich:2283',
apiKey: 'env-key',
authSecret: 'env-secret',
adminPassword: 'env-admin',
});
});
it('returns empty strings when neither source has values', async () => {
const { getInstallCredentials } = await loadInstall();
expect(getInstallCredentials()).toEqual({
apiUrl: '',
apiKey: '',
authSecret: '',
adminPassword: '',
});
});
});
describe('isInstalled', () => {
it('is false while gallery.yaml is missing', async () => {
const { isInstalled } = await loadInstall();
process.env.__T_INSTALL_URL = 'https://immich:2283';
process.env.__T_INSTALL_KEY = 'key';
expect(isInstalled()).toBe(false);
});
it('is false when credentials are missing even if gallery.yaml exists', async () => {
const { isInstalled } = await loadInstall();
fs.writeFileSync(path.join(dir, 'gallery.yaml'), 'albums: []\n');
expect(isInstalled()).toBe(false);
});
it('is true once gallery.yaml exists and credentials resolve', async () => {
const { isInstalled } = await loadInstall();
fs.writeFileSync(path.join(dir, 'gallery.yaml'), 'albums: []\n');
process.env.__T_INSTALL_URL = 'https://immich:2283';
process.env.__T_INSTALL_KEY = 'key';
expect(isInstalled()).toBe(true);
});
});
describe('completeInstall', () => {
it('writes gallery.yaml, settings.yaml and install.json', async () => {
const { completeInstall, getInstallCredentials } = await loadInstall();
await completeInstall({
apiUrl: 'https://immich.example',
apiKey: 'api-key-123',
siteTitle: 'My Portfolio',
siteSubtitle: 'A visual journal',
theme: 'noir',
albums: [ALBUM_ID],
adminPassword: 'hunter2',
});
const gallery = fs.readFileSync(path.join(dir, 'gallery.yaml'), 'utf8');
expect(gallery).toContain('albums');
expect(gallery).toContain(ALBUM_ID);
const settings = fs.readFileSync(path.join(dir, 'settings.yaml'), 'utf8');
expect(settings).toContain('My Portfolio');
expect(settings).toContain('noir');
const creds = JSON.parse(fs.readFileSync(path.join(dir, 'install.json'), 'utf8'));
expect(creds.apiUrl).toBe('https://immich.example');
expect(creds.apiKey).toBe('api-key-123');
// Stored as a hash, never as typed — an admin password is the one
// credential here a person picked and may have reused elsewhere.
expect(creds.adminPassword).not.toBe('hunter2');
expect(creds.adminPassword).toMatch(/^scrypt:[0-9a-f]+:[0-9a-f]+$/);
const { verifyScrypt } = await import('@/lib/password');
expect(await verifyScrypt('hunter2', creds.adminPassword)).toBe(true);
expect(await verifyScrypt('wrong', creds.adminPassword)).toBe(false);
// A fresh, unguessable site secret is generated.
expect(creds.authSecret).toBeTruthy();
expect(creds.authSecret.length).toBeGreaterThanOrEqual(32);
// The generated secret resolves through getInstallCredentials.
expect(getInstallCredentials().authSecret).toBe(creds.authSecret);
});
it('writes an empty albums list when no albums are selected', async () => {
const { completeInstall } = await loadInstall();
await completeInstall({
apiUrl: 'https://immich.example',
apiKey: 'api-key-123',
albums: [],
});
const gallery = fs.readFileSync(path.join(dir, 'gallery.yaml'), 'utf8');
expect(gallery).toContain('albums: []');
});
it('does not set an admin password when none is given', async () => {
const { completeInstall } = await loadInstall();
await completeInstall({
apiUrl: 'https://immich.example',
apiKey: 'api-key-123',
});
const creds = JSON.parse(fs.readFileSync(path.join(dir, 'install.json'), 'utf8'));
expect(creds.adminPassword).toBeUndefined();
});
it('makes isInstalled() true immediately — no restart required', async () => {
const { completeInstall, isInstalled } = await loadInstall();
expect(isInstalled()).toBe(false);
await completeInstall({
apiUrl: 'https://immich.example',
apiKey: 'api-key-123',
});
expect(isInstalled()).toBe(true);
});
});
describe('normalizeApiBase', () => {
it('appends /api to a base URL', async () => {
const { normalizeApiBase } = await loadInstall();
expect(normalizeApiBase('https://photos.example.com')).toBe('https://photos.example.com/api');
});
it('strips a trailing slash', async () => {
const { normalizeApiBase } = await loadInstall();
expect(normalizeApiBase('https://photos.example.com/')).toBe('https://photos.example.com/api');
});
it('does not double-append /api', async () => {
const { normalizeApiBase } = await loadInstall();
expect(normalizeApiBase('https://photos.example.com/api')).toBe(
'https://photos.example.com/api',
);
});
it('rejects non-http(s) schemes and garbage', async () => {
const { normalizeApiBase } = await loadInstall();
expect(normalizeApiBase('ftp://photos.example.com')).toBeNull();
expect(normalizeApiBase('not a url')).toBeNull();
expect(normalizeApiBase('')).toBeNull();
});
});
describe('isInstallPath', () => {
it('matches the wizard route only', async () => {
const { isInstallPath } = await loadInstall();
expect(isInstallPath('/install')).toBe(true);
expect(isInstallPath('/install/')).toBe(true);
expect(isInstallPath('/api/install')).toBe(false);
expect(isInstallPath('/admin')).toBe(false);
expect(isInstallPath('/')).toBe(false);
expect(isInstallPath(null)).toBe(false);
});
});
describe('setup token', () => {
/**
* The reason this is a file and not a module variable: Next.js bundles the
* install page and the install route handlers separately, so each gets its
* own instance of lib/install.ts. A module-level token made /install render
* the wizard and /api/install reject that same token, inside one process —
* the wizard could not get past step 1. Two freshly imported module
* instances reproduce exactly that split.
*/
it('agrees across separate module instances', async () => {
const pageSide = await loadInstall();
const token = pageSide.getSetupToken();
const apiSide = await loadInstall(); // fresh instance, as a second bundle would be
expect(apiSide.validateSetupToken(token)).toBe(true);
});
it('persists across a restart, so the operator keeps the logged token', async () => {
const first = await loadInstall();
const token = first.getSetupToken();
const afterRestart = await loadInstall();
expect(afterRestart.getSetupToken()).toBe(token);
});
it('writes the token 0600 — it is a credential, not a config value', async () => {
const { getSetupToken } = await loadInstall();
getSetupToken();
const mode = fs.statSync(path.join(dir, '.setup-token')).mode & 0o777;
expect(mode).toBe(0o600);
});
it('rejects a wrong or missing token', async () => {
const { getSetupToken, validateSetupToken } = await loadInstall();
getSetupToken();
expect(validateSetupToken('nope')).toBe(false);
expect(validateSetupToken('')).toBe(false);
expect(validateSetupToken(null)).toBe(false);
});
// Once install is done every install route answers 403, so the token guards
// nothing — leaving it on disk would just be a stray credential.
it('is removed once the install completes', async () => {
const { getSetupToken, completeInstall } = await loadInstall();
getSetupToken();
expect(fs.existsSync(path.join(dir, '.setup-token'))).toBe(true);
await completeInstall({ apiUrl: 'http://immich.local', apiKey: 'k', albums: [] });
expect(fs.existsSync(path.join(dir, '.setup-token'))).toBe(false);
});
});

View File

@@ -0,0 +1,96 @@
import { describe, it, expect } from 'vitest';
import {
sanitizeHtml,
decodeHtmlEntities,
renderInlineMarkdown,
parseJournalMarkdown,
serializeJournalMarkdown,
} from '../journal';
/**
* The previous sanitizer was a denylist: strip `<script>`, strip `on*="..."`,
* strip the literal `javascript:`. Every case below passed straight through it
* and into `dangerouslySetInnerHTML`. They are kept as regression tests rather
* than as a list of things to filter — the implementation escapes instead, so
* none of them is special.
*/
describe('sanitizeHtml', () => {
const bypasses: [string, string][] = [
['unquoted event handler', '<img src=x onerror=alert(1)>'],
['single-quoted event handler', "<img src=x onerror='alert(1)'>"],
['non-script tag', '<svg onload=alert(1)>'],
['recombining scheme', 'javasjavascript:cript:alert(1)'],
['uppercase tag', '<IMG SRC=x ONERROR=alert(1)>'],
];
it.each(bypasses)('neutralises %s', (_name, input) => {
const out = sanitizeHtml(input);
expect(out).not.toContain('<');
expect(out).not.toContain('>');
});
it('leaves plain text readable', () => {
expect(sanitizeHtml('5 > 3 && 2 < 4')).toBe('5 &gt; 3 &amp;&amp; 2 &lt; 4');
});
});
describe('renderInlineMarkdown', () => {
it('still renders bold, italic and safe links', () => {
const html = renderInlineMarkdown('**bold** and *italic* and [link](https://example.com)');
expect(html).toContain('<strong>bold</strong>');
expect(html).toContain('<em>italic</em>');
expect(html).toContain(
'<a href="https://example.com" target="_blank" rel="noopener noreferrer">link</a>',
);
});
it.each([
['relative', '/albums/iceland'],
['anchor', '#section'],
['mailto', 'mailto:hi@example.com'],
])('allows %s links', (_name, url) => {
expect(renderInlineMarkdown(`[x](${url})`)).toContain(`href="${url}"`);
});
it.each([
['javascript', 'javascript:alert(1)'],
['recombining javascript', 'javasjavascript:cript:alert(1)'],
['whitespace-obfuscated javascript', 'java\tscript:alert(1)'],
['data url', 'data:text/html,<script>alert(1)</script>'],
])('renders %s links as plain text instead of an anchor', (_name, url) => {
const html = renderInlineMarkdown(`[click me](${url})`);
// The label survives, the URL does not become a link. A stray `)` may be
// left over because the link pattern stops at the first closing paren —
// pre-existing behaviour, and harmless as text.
expect(html).toContain('click me');
expect(html).not.toContain('<a');
expect(html).not.toContain('href');
});
it('does not let a url break out of the href attribute', () => {
const html = renderInlineMarkdown('[x](" onmouseover=alert(1) x=")');
expect(html).not.toContain('onmouseover=alert(1)');
});
it('does not let a label inject markup', () => {
const html = renderInlineMarkdown('[<img src=x onerror=alert(1)>](https://example.com)');
expect(html).not.toContain('<img');
});
});
describe('markdown round trip', () => {
it('does not accumulate entities when parsing and serializing repeatedly', () => {
const source = '---\ntitle: "T"\n---\n\nAngle < bracket & ampersand "quoted"\n';
const once = serializeJournalMarkdown(parseJournalMarkdown(source));
const twice = serializeJournalMarkdown(parseJournalMarkdown(once));
expect(once).toContain('Angle < bracket & ampersand "quoted"');
expect(twice).toBe(once);
});
it('decodes exactly what sanitizeHtml encodes', () => {
const raw = `<a href="x">5 & 6 don't</a>`;
expect(decodeHtmlEntities(sanitizeHtml(raw))).toBe(raw);
});
});

View File

@@ -0,0 +1,108 @@
import { describe, it, expect } from 'vitest';
import path from 'path';
import { resolveJournalFilePath } from '../admin/journal-service';
import { parseJournalMarkdown, serializeJournalMarkdown, splitQuoteAuthor } from '../journal';
describe('resolveJournalFilePath', () => {
it.each(['../../etc/passwd', 'foo/../../bar', '..', 'a/b', 'foo.md', '', '.'])(
'refuses %j',
(slug) => {
expect(resolveJournalFilePath(slug)).toBeNull();
},
);
it('keeps a valid slug inside content/', () => {
const resolved = resolveJournalFilePath('my-entry');
expect(resolved).not.toBeNull();
expect(resolved!.startsWith(path.join(process.cwd(), 'content') + path.sep)).toBe(true);
expect(path.basename(resolved!)).toBe('my-entry.md');
});
});
describe('frontmatter escaping', () => {
const roundTrip = (title: string) => {
const once = serializeJournalMarkdown({
frontmatter: { title },
blocks: [],
referencedAssetIds: [],
});
const parsedOnce = parseJournalMarkdown(once);
const twice = serializeJournalMarkdown(parsedOnce);
return { first: parsedOnce.frontmatter.title, stable: once === twice };
};
it.each([
['plain', 'A normal title'],
['quotes', 'A "quoted" title'],
['backslash', String.raw`Path C:\Users`],
['both', String.raw`C:\Users "quoted"`],
['colon', 'Title: with a colon'],
['apostrophe', "Author's title"],
])('survives a title with %s', (_name, title) => {
const { first, stable } = roundTrip(title);
expect(first).toBe(title);
expect(stable).toBe(true);
});
});
describe('parser behaviour is unchanged by the regex rework', () => {
const parse = (body: string) => parseJournalMarkdown(`---\ntitle: "T"\n---\n\n${body}\n`).blocks;
it('parses headings at every level', () => {
expect(parse('### Third level')[0]).toEqual({
type: 'heading',
level: 3,
text: 'Third level',
});
});
it('splits a quote from its author on the first separator', () => {
expect(parse('> Something quotable -- Some Author')[0]).toEqual({
type: 'quote',
text: 'Something quotable',
author: 'Some Author',
});
});
it('leaves a quote without a separator whole', () => {
expect(parse('> Just a quote')[0]).toEqual({
type: 'quote',
text: 'Just a quote',
author: undefined,
});
});
it('still nests italic inside bold', () => {
expect(parse('Text with **bold *and italic* inside**.')[0]).toEqual({
type: 'paragraph',
html: 'Text with <strong>bold <em>and italic</em> inside</strong>.',
});
});
});
describe('splitQuoteAuthor', () => {
it.each([
['separator', 'Quote -- Author', { body: 'Quote', author: 'Author' }],
['no separator', 'Just a quote', { body: 'Just a quote', author: undefined }],
[
'first of several',
'Quote -- Author -- Second',
{ body: 'Quote', author: 'Author -- Second' },
],
['tabs', 'Quote\t--\tAuthor', { body: 'Quote', author: 'Author' }],
['wide gap', 'Quote -- Author', { body: 'Quote', author: 'Author' }],
// Whitespace on both sides is required, so these are not separators.
['no surrounding space', 'no--separator', { body: 'no--separator', author: undefined }],
['leading', '-- author only', { body: '-- author only', author: undefined }],
['trailing', 'Quote --', { body: 'Quote --', author: undefined }],
['empty', '', { body: '', author: undefined }],
])('handles %s', (_name, input, expected) => {
expect(splitQuoteAuthor(input as string)).toEqual(expected);
});
it('stays linear on a long run of whitespace with no separator', () => {
const started = performance.now();
splitQuoteAuthor(' '.repeat(50_000) + 'x');
expect(performance.now() - started).toBeLessThan(100);
});
});

View File

@@ -0,0 +1,174 @@
import { describe, it, expect, afterEach } from 'vitest';
import {
parseJournalMarkdown,
serializeJournalMarkdown,
sanitizeHtml,
renderInlineMarkdown,
calculateReadingTime,
extractExcerpt,
isValidSlug,
sanitizeSlug,
} from '../journal';
import {
writeJournalEntry,
readJournalEntry,
deleteJournalEntry,
listJournalEntries,
} from '../admin/journal-service';
describe('Journal Service & Parser', () => {
const testSlug = 'test-journey-nordkap';
afterEach(async () => {
try {
await deleteJournalEntry(testSlug);
} catch {}
});
describe('slug validation and sanitization', () => {
it('validates safe alphanumeric and hyphenated slugs', () => {
expect(isValidSlug('my-story-2026')).toBe(true);
expect(isValidSlug('nordkap_journey')).toBe(true);
expect(isValidSlug('story')).toBe(true);
});
it('rejects path traversal and illegal characters', () => {
expect(isValidSlug('../etc/passwd')).toBe(false);
expect(isValidSlug('..\\secret')).toBe(false);
expect(isValidSlug('story/sub')).toBe(false);
expect(isValidSlug('story?query=1')).toBe(false);
});
it('sanitizes titles to clean slugs', () => {
expect(sanitizeSlug('Mein Trip nach Island & Co.!')).toBe('mein-trip-nach-island-co');
expect(sanitizeSlug(' Nordkap 2026 -- Part 1 ')).toBe('nordkap-2026-part-1');
});
});
describe('sanitizeHtml & inline markdown', () => {
it('makes script tags and inline events inert', () => {
const malicious = 'Hello <script>alert(1)</script><img src="x" onerror="alert(2)">';
const clean = sanitizeHtml(malicious);
// The word "onerror" may well survive as text — what matters is that no
// tag can form around it, so it is never an attribute. Testing for the
// absence of the substring tested the old denylist, not the property.
expect(clean).not.toContain('<');
expect(clean).not.toContain('>');
expect(clean).not.toContain('"');
});
it('formats bold, italic, and safe links', () => {
const md = 'This is **bold** and *italic* and a [link](https://example.com).';
const html = renderInlineMarkdown(md);
expect(html).toContain('<strong>bold</strong>');
expect(html).toContain('<em>italic</em>');
expect(html).toContain('<a href="https://example.com"');
});
});
describe('parseJournalMarkdown and serializeJournalMarkdown', () => {
it('parses frontmatter and structured blocks', () => {
const markdown = `---
title: "Nordkap Tour"
subtitle: "Auf den Spuren des Nordlichts"
date: "2026-08-14"
author: "Ralf"
coverAssetId: "cover-uuid-1"
draft: true
---
# Kapitel 1: Die Reise beginnt
Es war ein stürmischer Tag am Fjord.
> Das Licht im Norden ist unvergleichlich. -- Ralf
![asset-uuid-2:fullbleed](Blick über den Fjord)
![pair-1, pair-2](Zwei Perspektiven)`;
const parsed = parseJournalMarkdown(markdown);
expect(parsed.frontmatter.title).toBe('Nordkap Tour');
expect(parsed.frontmatter.subtitle).toBe('Auf den Spuren des Nordlichts');
expect(parsed.frontmatter.draft).toBe(true);
expect(parsed.frontmatter.coverAssetId).toBe('cover-uuid-1');
expect(parsed.blocks).toHaveLength(5);
expect(parsed.blocks[0]).toEqual({ type: 'heading', level: 1, text: 'Kapitel 1: Die Reise beginnt' });
expect(parsed.blocks[1]).toEqual({ type: 'paragraph', html: 'Es war ein stürmischer Tag am Fjord.' });
expect(parsed.blocks[2]).toEqual({
type: 'quote',
text: 'Das Licht im Norden ist unvergleichlich.',
author: 'Ralf',
});
expect(parsed.blocks[3]).toEqual({
type: 'photo',
assetId: 'asset-uuid-2',
caption: 'Blick über den Fjord',
layout: 'fullbleed',
});
expect(parsed.blocks[4]).toEqual({
type: 'photo-pair',
assetIds: ['pair-1', 'pair-2'],
caption: 'Zwei Perspektiven',
});
expect(parsed.referencedAssetIds).toContain('cover-uuid-1');
expect(parsed.referencedAssetIds).toContain('asset-uuid-2');
expect(parsed.referencedAssetIds).toContain('pair-1');
expect(parsed.referencedAssetIds).toContain('pair-2');
});
it('serializes parsed journal back to markdown', () => {
const markdown = `---
title: "Nordkap"
draft: true
---
# Title
A paragraph of text.
![photo-uuid:wide](Caption)`;
const parsed = parseJournalMarkdown(markdown);
const serialized = serializeJournalMarkdown(parsed);
expect(serialized).toContain('title: "Nordkap"');
expect(serialized).toContain('draft: true');
expect(serialized).toContain('# Title');
expect(serialized).toContain('A paragraph of text.');
expect(serialized).toContain('![photo-uuid:wide](Caption)');
});
});
describe('filesystem CRUD operations', () => {
it('writes, reads, lists and deletes journal files safely', async () => {
const testContent = `---
title: "Vitest Journey"
date: "2026-08-14"
draft: false
---
Testing the journal filesystem operations.`;
await writeJournalEntry(testSlug, testContent);
const entry = await readJournalEntry(testSlug);
expect(entry).not.toBeNull();
expect(entry?.parsed.frontmatter.title).toBe('Vitest Journey');
const all = await listJournalEntries();
const found = all.find((e) => e.slug === testSlug);
expect(found).toBeDefined();
expect(found?.frontmatter.title).toBe('Vitest Journey');
const deleted = await deleteJournalEntry(testSlug);
expect(deleted).toBe(true);
const checkAfter = await readJournalEntry(testSlug);
expect(checkAfter).toBeNull();
});
});
});

View File

@@ -47,6 +47,21 @@ describe('proxy', () => {
); );
}); });
it('adds unsafe-eval to script-src in development mode for React dev tools and Fast Refresh', () => {
const envObj = process.env as Record<string, string | undefined>;
const origEnv = envObj.NODE_ENV;
try {
envObj.NODE_ENV = 'development';
expect(run().headers.get('Content-Security-Policy')).toContain("'unsafe-eval'");
} finally {
envObj.NODE_ENV = origEnv;
}
});
it('omits unsafe-eval in production/test environments', () => {
expect(run().headers.get('Content-Security-Policy')).not.toContain("'unsafe-eval'");
});
it('keeps a matcher that excludes api and static assets but covers /admin', () => { it('keeps a matcher that excludes api and static assets but covers /admin', () => {
const source = config.matcher[0].source; const source = config.matcher[0].source;
expect(source).toContain('api'); expect(source).toContain('api');

View File

@@ -4,8 +4,9 @@
*/ */
import crypto from 'crypto'; import crypto from 'crypto';
import { env } from '../env'; import { getInstallCredentials } from '../install';
import { resolveAuthSecret } from '../secret'; import { resolveAuthSecret } from '../secret';
import { isScryptHash, verifyScrypt } from '../password';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
const COOKIE_NAME = 'folio_admin_session'; const COOKIE_NAME = 'folio_admin_session';
@@ -20,14 +21,48 @@ const SESSION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours
*/ */
export const MAX_PASSWORD_LENGTH = 1024; export const MAX_PASSWORD_LENGTH = 1024;
/** Admin password as configured — env wins, wizard-installed value as fallback. */
function getAdminPassword(): string {
return getInstallCredentials().adminPassword;
}
/**
* Derived session signing key, kept for the process lifetime.
*
* scrypt is deliberately slow, and getSigningKey() runs on every admin request
* — deriving per call would put ~24ms in front of each one. The cache holds the
* inputs it was derived from, so a rotated password or secret misses the cache
* and derives again.
*
* Those inputs are compared directly rather than through a digest of them: a
* digest here would be a fast hash of the admin password sitting in memory for
* the life of the process, which is the very thing scrypt was introduced below
* to avoid. Holding the strings costs nothing extra — they are the same objects
* the env and install caches already hold, whereas building a digest input
* allocates a fresh copy of the password.
*/
let cachedSigningKey: { secret: string; password: string; key: Buffer } | null = null;
function getSigningKey(): Buffer { function getSigningKey(): Buffer {
// Bind the key to ADMIN_PASSWORD as well, so rotating the password // Bind the key to ADMIN_PASSWORD as well, so rotating the password
// immediately invalidates every outstanding session token. // immediately invalidates every outstanding session token.
const secret = resolveAuthSecret(); const secret = resolveAuthSecret();
return crypto const password = getAdminPassword();
.createHash('sha256')
.update(`admin:${secret}:${env.ADMIN_PASSWORD ?? ''}`) if (cachedSigningKey?.secret === secret && cachedSigningKey.password === password) {
.digest(); return cachedSigningKey.key;
}
/*
* scrypt rather than a plain SHA-256 digest: the admin password is an input
* here, and a single fast hash would make it cheap to recover by brute force
* if the derived key ever leaked. The salt has to be stable — a random one
* would change the key on every call and invalidate every session — so it is
* derived from AUTH_SECRET, which is deployment-specific.
*/
const key = crypto.scryptSync(password, `folio-admin-session:${secret}`, 32);
cachedSigningKey = { secret, password, key };
return key;
} }
/** Create a signed session token. */ /** Create a signed session token. */
@@ -83,11 +118,18 @@ export function verifyAdminToken(token: string): boolean {
* compares subpage passwords: the intermediate values are then useless to * compares subpage passwords: the intermediate values are then useless to
* anyone who cannot also read the secret. * anyone who cannot also read the secret.
*/ */
export function verifyAdminPassword(password: string): boolean { export async function verifyAdminPassword(password: string): Promise<boolean> {
const adminPw = env.ADMIN_PASSWORD; const adminPw = getAdminPassword();
if (!adminPw) return false; if (!adminPw) return false;
if (password.length > MAX_PASSWORD_LENGTH) return false; if (password.length > MAX_PASSWORD_LENGTH) return false;
// The wizard stores a hash; ADMIN_PASSWORD as an env var stays plaintext,
// because that is what every existing deployment has set. Both must work,
// or an upgrade locks the owner out of their own admin panel.
if (isScryptHash(adminPw)) {
return verifyScrypt(password, adminPw);
}
const secret = resolveAuthSecret(); const secret = resolveAuthSecret();
const attemptHash = crypto.createHmac('sha256', secret).update(password).digest(); const attemptHash = crypto.createHmac('sha256', secret).update(password).digest();
const expectedHash = crypto.createHmac('sha256', secret).update(adminPw).digest(); const expectedHash = crypto.createHmac('sha256', secret).update(adminPw).digest();
@@ -105,7 +147,7 @@ export async function isAdminAuthenticated(): Promise<boolean> {
/** Check if admin panel is enabled (password is set). */ /** Check if admin panel is enabled (password is set). */
export function isAdminEnabled(): boolean { export function isAdminEnabled(): boolean {
return !!env.ADMIN_PASSWORD; return !!getAdminPassword();
} }
export { COOKIE_NAME, SESSION_DURATION_MS }; export { COOKIE_NAME, SESSION_DURATION_MS };

View File

@@ -0,0 +1,216 @@
/**
* Server-side Journal File & Storage Service.
* Handles reading, listing, atomic writing, backups, and deletion of journal markdown files.
*/
import fs from 'fs/promises';
import nodeFs from 'fs';
import path from 'path';
import {
parseJournalMarkdown,
calculateReadingTime,
extractExcerpt,
isValidSlug,
type JournalEntrySummary,
type ParsedJournal,
} from '../journal';
const JOURNAL_DIR = path.join(process.cwd(), 'content', 'journal');
const LEGACY_ESSAYS_DIR = path.join(process.cwd(), 'content', 'essays');
const MAX_BACKUPS = 10;
let tmpCounter = 0;
/**
* Join a filename onto a content directory, or return null if the result would
* escape it.
*
* isValidSlug() already rejects dots and separators, so nothing should ever get
* this far — this is the second lock on the door. It also gives the taint
* analysis in CI a barrier it can see: the slug check lives in another module,
* which CodeQL does not follow, so every path built from a slug was reported as
* path injection.
*/
function containedPath(dir: string, filename: string): string | null {
const base = path.resolve(dir);
const resolved = path.resolve(base, filename);
if (resolved !== base && !resolved.startsWith(base + path.sep)) return null;
return resolved;
}
/** Resolve file path for a journal slug (checks content/journal/ then content/essays/) */
export function resolveJournalFilePath(slug: string): string | null {
if (!isValidSlug(slug)) return null;
// Not `slug.endsWith('.md') ? slug : ...`: isValidSlug rejects dots, so that
// branch could never be taken.
const filename = `${slug}.md`;
const primaryPath = containedPath(JOURNAL_DIR, filename);
if (!primaryPath) return null;
if (nodeFs.existsSync(primaryPath)) return primaryPath;
const legacyPath = containedPath(LEGACY_ESSAYS_DIR, filename);
if (legacyPath && nodeFs.existsSync(legacyPath)) return legacyPath;
return primaryPath; // Target path for new writes
}
/** Load and parse an essay file from content/essays/ or content/journal/ */
export function loadEssayFromFile(filename: string): ParsedJournal | null {
try {
const filePath = resolveJournalFilePath(filename);
if (!filePath || !nodeFs.existsSync(filePath)) {
console.warn(`[Essay] File not found: ${filename}`);
return null;
}
const content = nodeFs.readFileSync(filePath, 'utf-8');
return parseJournalMarkdown(content);
} catch (error) {
console.error(`[Essay] Failed to load essay file "${filename}":`, error);
return null;
}
}
/** List all journal entries */
export async function listJournalEntries(): Promise<JournalEntrySummary[]> {
const entries: JournalEntrySummary[] = [];
const seenSlugs = new Set<string>();
const scanDir = async (dir: string) => {
try {
await fs.access(dir);
} catch {
return;
}
try {
const files = await fs.readdir(dir);
for (const file of files) {
if (!file.endsWith('.md')) continue;
const slug = file.replace(/\.md$/, '');
if (seenSlugs.has(slug)) continue;
seenSlugs.add(slug);
try {
const content = await fs.readFile(path.join(dir, file), 'utf8');
const parsed = parseJournalMarkdown(content);
const { words, minutes } = calculateReadingTime(content);
const excerpt = extractExcerpt(parsed);
entries.push({
slug,
filename: file,
frontmatter: parsed.frontmatter,
excerpt,
wordCount: words,
readingTimeMinutes: minutes,
});
} catch (err) {
console.error(`[Journal] Failed to parse ${file}:`, err);
}
}
} catch (err) {
console.error(`[Journal] Failed to read directory ${dir}:`, err);
}
};
await scanDir(JOURNAL_DIR);
await scanDir(LEGACY_ESSAYS_DIR);
// Sort: descending by date, fallback to title/slug
return entries.sort((a, b) => {
const dateA = a.frontmatter.date || '';
const dateB = b.frontmatter.date || '';
if (dateA && dateB) return dateB.localeCompare(dateA);
if (dateA) return -1;
if (dateB) return 1;
return (a.frontmatter.title || a.slug).localeCompare(b.frontmatter.title || b.slug);
});
}
/** Read a single journal entry by slug */
export async function readJournalEntry(slug: string): Promise<{
slug: string;
rawMarkdown: string;
parsed: ParsedJournal;
} | null> {
const filePath = resolveJournalFilePath(slug);
if (!filePath) return null;
try {
const rawMarkdown = await fs.readFile(filePath, 'utf8');
const parsed = parseJournalMarkdown(rawMarkdown);
return { slug, rawMarkdown, parsed };
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
throw err;
}
}
/** Atomically write/save a journal entry with backup rotation */
export async function writeJournalEntry(slug: string, rawMarkdown: string): Promise<void> {
if (!isValidSlug(slug)) {
throw new Error(`Invalid journal slug: "${slug}"`);
}
await fs.mkdir(JOURNAL_DIR, { recursive: true });
const filename = `${slug}.md`;
const filePath = containedPath(JOURNAL_DIR, filename);
if (!filePath) {
throw new Error(`Invalid journal slug: "${slug}"`);
}
// Create rolling backup if file already exists
try {
await fs.access(filePath);
const backupDir = path.join(JOURNAL_DIR, '.backups');
await fs.mkdir(backupDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const backupName = `${filename}.${timestamp}.bak`;
await fs.copyFile(filePath, path.join(backupDir, backupName));
// Prune backups
const backups = (await fs.readdir(backupDir))
.filter((f) => f.startsWith(`${filename}.`) && f.endsWith('.bak'))
.sort();
if (backups.length > MAX_BACKUPS) {
for (const old of backups.slice(0, backups.length - MAX_BACKUPS)) {
await fs.unlink(path.join(backupDir, old)).catch(() => {});
}
}
} catch {
// New file, no backup needed
}
// Atomic write via unique temp file
const tmpPath = `${filePath}.${process.pid}.${++tmpCounter}.tmp`;
try {
await fs.writeFile(tmpPath, rawMarkdown, 'utf8');
await fs.rename(tmpPath, filePath);
} catch (err) {
await fs.unlink(tmpPath).catch(() => {});
throw err;
}
console.log(`[Journal] ✅ Saved ${filename}`);
}
/** Safely delete a journal entry */
export async function deleteJournalEntry(slug: string): Promise<boolean> {
if (!isValidSlug(slug)) {
throw new Error(`Invalid journal slug: "${slug}"`);
}
const filePath = resolveJournalFilePath(slug);
if (!filePath) return false;
try {
await fs.unlink(filePath);
console.log(`[Journal] 🗑️ Deleted ${slug}.md`);
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw err;
}
}

View File

@@ -8,6 +8,7 @@
import crypto from 'crypto'; import crypto from 'crypto';
import { getConfig, SubpageConfig } from './config'; import { getConfig, SubpageConfig } from './config';
import { verifyScrypt, generateScryptHash, isScryptHash } from './password';
const TOKEN_EXPIRY_HOURS = 24; const TOKEN_EXPIRY_HOURS = 24;
@@ -18,52 +19,6 @@ function isBcryptHash(str: string): boolean {
return str.startsWith('$2a$') || str.startsWith('$2b$') || str.startsWith('$2y$'); return str.startsWith('$2a$') || str.startsWith('$2b$') || str.startsWith('$2y$');
} }
/**
* scrypt on the libuv threadpool rather than the main thread.
*
* scryptSync costs ~23ms per call, and that is 23ms during which the process
* serves nothing else. The /api/auth rate limit (10/min) is keyed on the client
* IP, but with the default TRUSTED_PROXY_HOPS=0 that IP comes from a spoofable
* header (see lib/rate-limit.ts), so an attacker rotating the header gets
* effectively unlimited buckets — each request buying 23ms of dead process.
* Running async does not stop the spoofing, but it removes the amplification
* that made it worth doing.
*/
function scryptAsync(password: string, salt: string, keylen: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
crypto.scrypt(password, salt, keylen, (err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
});
});
}
/**
* Native SCrypt verify (format: 'scrypt:salt:hash_hex')
*/
async function verifyScrypt(password: string, stored: string): Promise<boolean> {
if (!stored.startsWith('scrypt:')) return false;
try {
const [, salt, hashHex] = stored.split(':');
const key = await scryptAsync(password, salt, 64);
const expectedKey = Buffer.from(hashHex, 'hex');
if (key.length !== expectedKey.length) return false;
return crypto.timingSafeEqual(key, expectedKey);
} catch {
return false;
}
}
/**
* Helper to generate an scrypt string to print in logs.
*/
async function generateScryptHash(password: string): Promise<string> {
const salt = crypto.randomBytes(16).toString('hex');
const hash = (await scryptAsync(password, salt, 64)).toString('hex');
return `scrypt:${salt}:${hash}`;
}
function hmac(data: string): string { function hmac(data: string): string {
return crypto.createHmac('sha256', getConfig().authSecret).update(data).digest('hex'); return crypto.createHmac('sha256', getConfig().authSecret).update(data).digest('hex');
} }
@@ -81,8 +36,14 @@ function authToken(key: string, passwordSecret: string, expiresAt: number): stri
return `${expiresAt}.${hmac(`${key}:${passwordSecret}:${expiresAt}`)}`; return `${expiresAt}.${hmac(`${key}:${passwordSecret}:${expiresAt}`)}`;
} }
function cookieName(key: string, type: 'subpage' | 'album'): string { import nodeFs from 'fs';
return type === 'subpage' ? `lb_auth_${key}` : `lb_auth_album_${key}`; import { parseFrontmatter } from './journal';
import { resolveJournalFilePath } from './admin/journal-service';
function cookieName(key: string, type: 'subpage' | 'album' | 'journal'): string {
if (type === 'subpage') return `lb_auth_${key}`;
if (type === 'journal') return `lb_auth_journal_${key}`;
return `lb_auth_album_${key}`;
} }
/** /**
@@ -93,20 +54,33 @@ export function findSubpageBySlug(slug: string): SubpageConfig | undefined {
} }
/** /**
* Find the password secret for a given subpage slug or album ID. * Find the password secret for a given subpage slug, album ID, or journal entry.
*/ */
function findPassword(key: string, type: 'subpage' | 'album'): string | undefined { function findPassword(key: string, type: 'subpage' | 'album' | 'journal'): string | undefined {
const config = getConfig(); const config = getConfig();
if (type === 'subpage') { if (type === 'subpage') {
return config.subpages.find((sp) => sp.slug === key)?.password; return config.subpages.find((sp) => sp.slug === key)?.password;
} }
return config.albumPasswords[key]; if (type === 'album') {
return config.albumPasswords[key];
}
if (type === 'journal') {
try {
const filePath = resolveJournalFilePath(key);
if (filePath && nodeFs.existsSync(filePath)) {
const raw = nodeFs.readFileSync(filePath, 'utf8');
return parseFrontmatter(raw).frontmatter.password;
}
} catch {}
return undefined;
}
return undefined;
} }
/** /**
* Check if a subpage slug or album ID is password-protected. * Check if a subpage slug, album ID, or journal entry is password-protected.
*/ */
export function isProtected(key: string, type: 'subpage' | 'album' = 'subpage'): boolean { export function isProtected(key: string, type: 'subpage' | 'album' | 'journal' = 'subpage'): boolean {
return !!findPassword(key, type); return !!findPassword(key, type);
} }
@@ -117,7 +91,7 @@ export function isProtected(key: string, type: 'subpage' | 'album' = 'subpage'):
export async function authenticate( export async function authenticate(
key: string, key: string,
password: string, password: string,
type: 'subpage' | 'album' = 'subpage', type: 'subpage' | 'album' | 'journal' = 'subpage',
): Promise<string | null> { ): Promise<string | null> {
const storedPassword = findPassword(key, type); const storedPassword = findPassword(key, type);
if (!storedPassword) return null; if (!storedPassword) return null;
@@ -134,7 +108,7 @@ export async function authenticate(
return null; return null;
} }
if (storedPassword.startsWith('scrypt:')) { if (isScryptHash(storedPassword)) {
isValid = await verifyScrypt(password, storedPassword); isValid = await verifyScrypt(password, storedPassword);
} else { } else {
// Plaintext fallback (deprecated) // Plaintext fallback (deprecated)
@@ -174,7 +148,7 @@ export async function authenticate(
export function isAuthenticated( export function isAuthenticated(
key: string, key: string,
getCookie: (name: string) => string | undefined, getCookie: (name: string) => string | undefined,
type: 'subpage' | 'album' = 'subpage', type: 'subpage' | 'album' | 'journal' = 'subpage',
): boolean { ): boolean {
const storedPassword = findPassword(key, type); const storedPassword = findPassword(key, type);
if (!storedPassword) return true; // not protected if (!storedPassword) return true; // not protected

View File

@@ -1,5 +1,6 @@
import { env } from '../env'; import { env } from '../env';
import { resolveAuthSecret } from '../secret'; import { resolveAuthSecret } from '../secret';
import { getInstallCredentials } from '../install';
import { loadYaml, clearYamlCache, validateUuid } from './parser'; import { loadYaml, clearYamlCache, validateUuid } from './parser';
import { resolveTheme, VALID_LAYOUTS } from './theme'; import { resolveTheme, VALID_LAYOUTS } from './theme';
import { ALBUM_SORT_MODES, isAlbumSortMode, type AlbumSortMode } from '../albumSort'; import { ALBUM_SORT_MODES, isAlbumSortMode, type AlbumSortMode } from '../albumSort';
@@ -90,8 +91,10 @@ export interface GalleryDerivation {
/** /**
* Derive the gallery half of AppConfig, throwing on a structure that cannot be * Derive the gallery half of AppConfig, throwing on a structure that cannot be
* represented: no albums and no subpages, a subpage with no name, a subpage * represented: a subpage with no name, a subpage with neither albums nor
* with neither albums nor sections. * 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 * Extracted from getConfig() so the admin PUT can run the *real* derivation
* against a proposed gallery before writing it. Re-implementing the three * against a proposed gallery before writing it. Re-implementing the three
@@ -166,15 +169,6 @@ export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
const standaloneAlbumIds = (gallery.albums ?? []).map((entry) => const standaloneAlbumIds = (gallery.albums ?? []).map((entry) =>
processAlbumEntry(entry, 'gallery.yaml albums'), 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))
) {
throw new Error('gallery.yaml must define at least one album or subpage');
}
let subpages: SubpageConfig[] = []; let subpages: SubpageConfig[] = [];
@@ -276,17 +270,21 @@ export function getConfig(): AppConfig {
// worker/process than page rendering, so a per-worker cache goes stale // worker/process than page rendering, so a per-worker cache goes stale
// until restart. Freshness comes from the mtime-checked YAML cache in // until restart. Freshness comes from the mtime-checked YAML cache in
// loadYaml() — a statSync per file, negligible next to Immich API calls. // loadYaml() — a statSync per file, negligible next to Immich API calls.
const apiUrl = env.IMMICH_API_URL; const { apiUrl, apiKey } = getInstallCredentials();
const apiKey = env.IMMICH_API_KEY;
const authSecret = resolveAuthSecret(); 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 gallery = loadYaml<GalleryYaml>('gallery.yaml');
const settings = loadYaml<SettingsYaml>('settings.yaml') || {}; const settings = loadYaml<SettingsYaml>('settings.yaml') || {};
if (!gallery || !apiKey || !apiUrl) { if (!gallery || !apiKey || !apiUrl) {
// Return dummy config if gallery.yaml is missing // Return dummy config if gallery.yaml is missing
return { return {
immich: { apiUrl: `${apiUrl}/api`, apiKey }, immich: { apiUrl: immichApiUrl, apiKey },
authSecret, authSecret,
albums: [], albums: [],
standaloneAlbums: [], standaloneAlbums: [],
@@ -309,6 +307,7 @@ export function getConfig(): AppConfig {
legal: { enabled: false, name: '', address: '', zipCity: '', country: '' }, legal: { enabled: false, name: '', address: '', zipCity: '', country: '' },
map: false, map: false,
transitions: false, transitions: false,
scrollToTop: false,
analytics: true, analytics: true,
proofing: { enabled: false, allowMailto: false }, proofing: { enabled: false, allowMailto: false },
albumOverrides: {}, albumOverrides: {},
@@ -343,7 +342,7 @@ export function getConfig(): AppConfig {
const siteSeoTitle = settings.seo?.title || settings.title || env.SITE_TITLE || 'Gallery'; const siteSeoTitle = settings.seo?.title || settings.title || env.SITE_TITLE || 'Gallery';
return { return {
immich: { apiUrl: `${apiUrl}/api`, apiKey }, immich: { apiUrl: immichApiUrl, apiKey },
authSecret, authSecret,
albums: allAlbumIds, albums: allAlbumIds,
standaloneAlbums, standaloneAlbums,
@@ -399,6 +398,7 @@ export function getConfig(): AppConfig {
}, },
map: settings.map === true, map: settings.map === true,
transitions: settings.transitions !== false, transitions: settings.transitions !== false,
scrollToTop: settings.scrollToTop !== false,
analytics: settings.analytics !== false, analytics: settings.analytics !== false,
proofing: { proofing: {
enabled: settings.proofing?.enabled !== false, enabled: settings.proofing?.enabled !== false,

View File

@@ -104,6 +104,8 @@ export interface AppConfig {
legal: LegalConfig; legal: LegalConfig;
map: boolean; map: boolean;
transitions: boolean; transitions: boolean;
/** Floating back-to-top arrow in the frontend. */
scrollToTop: boolean;
analytics: boolean; analytics: boolean;
proofing: { proofing: {
enabled: boolean; enabled: boolean;
@@ -195,6 +197,7 @@ export interface SettingsYaml {
exifOnHover?: boolean; exifOnHover?: boolean;
map?: boolean; map?: boolean;
transitions?: boolean; transitions?: boolean;
scrollToTop?: boolean;
analytics?: boolean; analytics?: boolean;
proofing?: { proofing?: {
enabled?: boolean; enabled?: boolean;

View File

@@ -17,6 +17,7 @@ export interface Env {
TRUSTED_PROXY_HOPS: number; TRUSTED_PROXY_HOPS: number;
WEBHOOK_SECRET?: string; WEBHOOK_SECRET?: string;
ADMIN_PASSWORD?: string; ADMIN_PASSWORD?: string;
INSTALL_CONTENT_DIR?: string;
} }
function parseEnv(): Env { function parseEnv(): Env {
@@ -109,6 +110,7 @@ function parseEnv(): Env {
TRUSTED_PROXY_HOPS: trustedProxyHops, TRUSTED_PROXY_HOPS: trustedProxyHops,
WEBHOOK_SECRET: process.env.WEBHOOK_SECRET || undefined, WEBHOOK_SECRET: process.env.WEBHOOK_SECRET || undefined,
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD || undefined, ADMIN_PASSWORD: process.env.ADMIN_PASSWORD || undefined,
INSTALL_CONTENT_DIR: process.env.INSTALL_CONTENT_DIR || undefined,
}; };
} }

View File

@@ -1,273 +1,15 @@
export interface EssayFrontmatter { /**
title?: string; * Essay module (re-exports from lib/journal for full backwards compatibility).
subtitle?: string; * Client-safe pure module.
date?: string; */
author?: string;
coverAssetId?: string;
layout?: string;
}
export type EssayBlock = export {
| { type: 'heading'; level: number; text: string } type JournalFrontmatter as EssayFrontmatter,
| { type: 'paragraph'; html: string } type JournalBlock as EssayBlock,
| { type: 'quote'; text: string; author?: string } type ParsedJournal as ParsedEssay,
| { type: 'photo'; assetId: string; caption?: string; layout: 'fullbleed' | 'wide' | 'contained' } sanitizeHtml,
| { type: 'photo-pair'; assetIds: [string, string]; caption?: string }; renderInlineMarkdown,
parseFrontmatter,
export interface ParsedEssay { parseJournalMarkdown as parseEssayMarkdown,
frontmatter: EssayFrontmatter; serializeJournalMarkdown as serializeEssayMarkdown,
blocks: EssayBlock[]; } from './journal';
referencedAssetIds: string[];
}
/** Sanitize inline HTML strings to prevent XSS attacks in essay blocks */
export function sanitizeHtml(input: string): string {
return input
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
.replace(/on\w+="[^"]*"/gi, '')
.replace(/javascript:/gi, '');
}
/** Simple Markdown inline formatting (bold, italic, links, code) */
export function renderInlineMarkdown(text: string): string {
let html = sanitizeHtml(text);
// Bold: **text** or __text__
html = html.replace(/(\*\*|__)(.*?)\1/g, '<strong>$2</strong>');
// Italic: *text* or _text_
html = html.replace(/(\*|_)(.*?)\1/g, '<em>$2</em>');
// Links: [label](url)
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => {
const safeUrl = url.trim().replace(/^javascript:/i, '');
return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer">${label}</a>`;
});
return html;
}
/** Parse frontmatter (YAML block delimited by ---) */
export function parseFrontmatter(content: string): { frontmatter: EssayFrontmatter; body: string } {
const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
if (!frontmatterMatch) {
return { frontmatter: {}, body: content };
}
const rawYaml = frontmatterMatch[1];
const body = content.slice(frontmatterMatch[0].length);
const frontmatter: EssayFrontmatter = {};
for (const line of rawYaml.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) continue;
const key = trimmed.slice(0, colonIdx).trim();
let val = trimmed.slice(colonIdx + 1).trim();
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.slice(1, -1);
}
if (key === 'title') frontmatter.title = val;
else if (key === 'subtitle') frontmatter.subtitle = val;
else if (key === 'date') frontmatter.date = val;
else if (key === 'author') frontmatter.author = val;
else if (key === 'coverAssetId') frontmatter.coverAssetId = val;
else if (key === 'layout') frontmatter.layout = val;
}
return { frontmatter, body };
}
/** Parse Essay Markdown content into structured blocks */
export function parseEssayMarkdown(rawContent: string): ParsedEssay {
const { frontmatter, body } = parseFrontmatter(rawContent);
const blocks: EssayBlock[] = [];
const referencedAssetIds = new Set<string>();
if (frontmatter.coverAssetId) {
referencedAssetIds.add(frontmatter.coverAssetId);
}
// Split body into paragraph chunks separated by blank lines
const chunks = body
.split(/\r?\n\s*\r?\n/)
.map((c) => c.trim())
.filter(Boolean);
for (const chunk of chunks) {
// 1. Headings (# H1, ## H2, ### H3)
const headingMatch = chunk.match(/^(#{1,6})\s+(.+)$/);
if (headingMatch) {
blocks.push({
type: 'heading',
level: headingMatch[1].length,
text: headingMatch[2].trim(),
});
continue;
}
// 2. Blockquote (> Quote text)
if (chunk.startsWith('>')) {
const quoteText = chunk
.split('\n')
.map((l) => l.replace(/^>\s?/, ''))
.join(' ')
.trim();
// Check for quote author (-- Author Name)
const authorMatch = quoteText.match(/^(.*?)(?:\s+--\s+(.+))?$/);
if (authorMatch) {
blocks.push({
type: 'quote',
text: renderInlineMarkdown(authorMatch[1]),
author: authorMatch[2] ? authorMatch[2].trim() : undefined,
});
}
continue;
}
// 3. Image syntax: ![assetId:layout](Caption) or ![assetId1, assetId2](Caption)
const imgMatch = chunk.match(/^!\[([^\]]+)\]\(([^)]*)\)$/);
if (imgMatch) {
const rawTarget = imgMatch[1].trim();
const caption = imgMatch[2].trim() ? renderInlineMarkdown(imgMatch[2].trim()) : undefined;
// Side-by-side pair: ![asset1, asset2](Caption)
if (rawTarget.includes(',')) {
const parts = rawTarget.split(',').map((s) => s.trim());
if (parts.length >= 2) {
const id1 = parts[0];
const id2 = parts[1];
referencedAssetIds.add(id1);
referencedAssetIds.add(id2);
blocks.push({
type: 'photo-pair',
assetIds: [id1, id2],
caption,
});
continue;
}
}
// Single photo: ![assetId:layout](Caption)
let assetId = rawTarget;
let layout: 'fullbleed' | 'wide' | 'contained' = 'contained';
if (rawTarget.includes(':')) {
const [id, l] = rawTarget.split(':');
assetId = id.trim();
const normLayout = l.trim().toLowerCase();
if (normLayout === 'fullbleed') layout = 'fullbleed';
else if (normLayout === 'wide') layout = 'wide';
}
referencedAssetIds.add(assetId);
blocks.push({
type: 'photo',
assetId,
caption,
layout,
});
continue;
}
// 4. Standard Text Paragraph
blocks.push({
type: 'paragraph',
html: renderInlineMarkdown(chunk.replace(/\r?\n/g, ' ')),
});
}
return {
frontmatter,
blocks,
referencedAssetIds: Array.from(referencedAssetIds),
};
}
/** Load and parse an essay file from content/essays/ */
export function loadEssayFromFile(filename: string): ParsedEssay | null {
if (typeof window !== 'undefined') return null;
try {
// Dynamic require for Node.js modules so client bundler doesn't fail
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeFs = require('fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodePath = require('path');
const filePath = nodePath.isAbsolute(filename)
? filename
: nodePath.join(process.cwd(), 'content', 'essays', filename);
if (!nodeFs.existsSync(filePath)) {
console.warn(`[Essay] File not found: ${filePath}`);
return null;
}
const content = nodeFs.readFileSync(filePath, 'utf-8');
return parseEssayMarkdown(content);
} catch (error) {
console.error(`[Essay] Failed to load essay file "${filename}":`, error);
return null;
}
}
/** Converts a ParsedEssay structure back into clean Markdown syntax */
export function serializeEssayMarkdown(essay: ParsedEssay): string {
const lines: string[] = [];
// Frontmatter
const fmKeys = Object.keys(essay.frontmatter) as Array<keyof EssayFrontmatter>;
if (fmKeys.length > 0 && fmKeys.some((k) => essay.frontmatter[k])) {
lines.push('---');
for (const key of fmKeys) {
const val = essay.frontmatter[key];
if (val) {
lines.push(`${key}: "${val.replace(/"/g, '\\"')}"`);
}
}
lines.push('---');
lines.push('');
}
// Blocks
for (const block of essay.blocks) {
switch (block.type) {
case 'heading': {
const hashes = '#'.repeat(Math.min(Math.max(block.level, 1), 6));
lines.push(`${hashes} ${block.text}`);
break;
}
case 'paragraph': {
const text = block.html.replace(/<[^>]+>/g, (tag) => {
if (tag.startsWith('<strong>') || tag.startsWith('<b>')) return '**';
if (tag.startsWith('</strong>') || tag.startsWith('</b>')) return '**';
if (tag.startsWith('<em>') || tag.startsWith('<i>')) return '*';
if (tag.startsWith('</em>') || tag.startsWith('</i>')) return '*';
return '';
});
lines.push(text);
break;
}
case 'quote': {
const authorSuffix = block.author ? ` -- ${block.author}` : '';
const text = block.text.replace(/[\r\n]+/g, ' ');
lines.push(`> ${text}${authorSuffix}`);
break;
}
case 'photo': {
const layoutSuffix = block.layout !== 'contained' ? `:${block.layout}` : '';
const caption = block.caption ? block.caption.replace(/[\r\n]+/g, ' ') : '';
lines.push(`![${block.assetId}${layoutSuffix}](${caption})`);
break;
}
case 'photo-pair': {
const caption = block.caption ? block.caption.replace(/[\r\n]+/g, ' ') : '';
lines.push(`![${block.assetIds[0]}, ${block.assetIds[1]}](${caption})`);
break;
}
}
lines.push('');
}
return lines.join('\n').trim();
}

303
lib/install.ts Normal file
View File

@@ -0,0 +1,303 @@
/**
* Install wizard support.
*
* The wizard is the first-run path: /install walks a fresh deployment through
* connecting to Immich, picking albums (optional), and naming the site, then
* writes content/gallery.yaml, content/settings.yaml and a small
* content/install.json carrying the Immich credentials, the generated site
* secret and an optional admin password.
*
* content/install.json exists because a running process cannot pick up new
* process.env values — the wizard has to write configuration that takes effect
* without a restart. getInstallCredentials() merges it *under* the real
* environment, so env vars (Docker, .env.local) always win and rotating a
* credential is a matter of setting the corresponding env var.
*
* Once gallery.yaml exists and the credentials resolve, isInstalled() is true
* and /install — the page and both API routes — refuses to run again.
*/
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import yaml from 'js-yaml';
import { env } from './env';
import { generateScryptHash } from './password';
import type { GalleryYaml, SettingsYaml } from './config/schema';
/** The directory user content is written into. Overridable for tests. */
function installContentDir(): string {
return env.INSTALL_CONTENT_DIR || path.join(process.cwd(), 'content');
}
const INSTALL_FILENAME = 'install.json';
// ── One-time setup token —─────────────────────────────────────
const SETUP_TOKEN_FILENAME = '.setup-token';
/**
* A random token that gates the install page and the install API routes. It is
* printed to the server log on first access; the operator reads it from the
* container / process logs and supplies it as a query parameter or an
* `x-setup-token` header.
*
* Without this token the install endpoints are reachable by anyone who knows
* the URL — which is the whole internet if the app is deployed before
* `gallery.yaml` exists.
*
* It lives in a file rather than a module variable because Next.js bundles the
* page and each route handler separately: a module-level token gives
* /install one value and /api/install another, inside the same process. The
* page would render the wizard and the API would then reject the very token it
* had just printed, leaving the wizard stuck on step 1 with no way forward.
* The file is the only state both bundles agree on — and it survives a restart,
* so the operator does not have to hunt through the logs again.
*/
function generateSetupToken(): string {
const dir = installContentDir();
const tokenPath = path.join(dir, SETUP_TOKEN_FILENAME);
try {
const existing = fs.readFileSync(tokenPath, 'utf8').trim();
if (existing) return existing;
} catch {
// Not created yet — fall through and mint one.
}
const token = crypto.randomBytes(24).toString('base64url');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(tokenPath, `${token}\n`, { mode: 0o600 });
return token;
}
let _tokenLogged = false;
export function getSetupToken(): string {
const token = generateSetupToken();
if (!_tokenLogged) {
_tokenLogged = true;
console.log('\n══════════════════════════════════════════════════════');
console.log(' Immich Folio — First-run setup token');
console.log('══════════════════════════════════════════════════════');
console.log(` Token: ${token}`);
console.log('');
console.log(' Append ?token= to the /install URL (or include it as');
console.log(' an X-Setup-Token header on API requests) to access');
console.log(' the install wizard.');
console.log('══════════════════════════════════════════════════════\n');
}
return token;
}
export function validateSetupToken(token: string | null): boolean {
if (!token) return false;
const expected = generateSetupToken();
try {
const a = Buffer.from(token, 'utf8');
const b = Buffer.from(expected, 'utf8');
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
} catch {
return false;
}
}
// ── Credential management —────────────────────────────────━━━━
/** Credentials the running app should use, env vars taking precedence. */
export interface InstallCredentials {
apiUrl: string;
apiKey: string;
authSecret: string;
adminPassword: string;
}
/** Raw contents of content/install.json. */
interface InstallFileData {
apiUrl?: string;
apiKey?: string;
authSecret?: string;
adminPassword?: string;
}
let cachedInstallFile: { path: string; mtimeMs: number; data: InstallFileData } | null = null;
function readInstallFile(): InstallFileData {
const installPath = path.join(installContentDir(), INSTALL_FILENAME);
let mtimeMs = 0;
try {
mtimeMs = fs.statSync(installPath).mtimeMs;
} catch {
// File does not exist — no wizard-installed credentials.
cachedInstallFile = null;
return {};
}
if (
cachedInstallFile &&
cachedInstallFile.path === installPath &&
cachedInstallFile.mtimeMs === mtimeMs
) {
return cachedInstallFile.data;
}
let data: InstallFileData = {};
try {
data = JSON.parse(fs.readFileSync(installPath, 'utf8')) as InstallFileData;
} catch (err) {
console.warn('[Install] content/install.json is not valid JSON — ignoring it.', err);
}
cachedInstallFile = { path: installPath, mtimeMs, data };
return data;
}
/**
* Merge wizard-installed credentials with the real environment.
*
* Env wins: someone who sets IMMICH_API_URL/IMMICH_API_KEY/AUTH_SECRET/
* ADMIN_PASSWORD after installing keeps the env value, which is how rotation
* works without touching the wizard files.
*/
export function getInstallCredentials(): InstallCredentials {
const file = readInstallFile();
return {
apiUrl: env.IMMICH_API_URL || file.apiUrl || '',
apiKey: env.IMMICH_API_KEY || file.apiKey || '',
authSecret: env.AUTH_SECRET || file.authSecret || '',
adminPassword: env.ADMIN_PASSWORD || file.adminPassword || '',
};
}
/**
* Whether a first-run install is complete.
*
* Mirrors the `needsSetup` definition in getConfig(): a gallery.yaml exists AND
* Immich credentials resolve. The wizard writes all three at once, so this flips
* to true the moment the install finishes — no restart required.
*/
export function isInstalled(): boolean {
const creds = getInstallCredentials();
if (!creds.apiUrl || !creds.apiKey) return false;
return fs.existsSync(path.join(installContentDir(), 'gallery.yaml'));
}
/** Whether a request pathname belongs to the install wizard. */
export function isInstallPath(pathname: string | null): boolean {
return pathname === '/install' || pathname?.startsWith('/install/') === true;
}
/**
* Normalize a user-supplied Immich base URL into the API base the client calls.
*
* The app stores the base URL (no /api) — see lib/env.ts — and appends /api at
* call time. Users sometimes paste a URL that already ends in /api, so accept
* both rather than double-appending. Returns null when the input is not a
* valid http(s) URL.
*/
export function normalizeApiBase(raw: string): string | null {
let url: URL;
try {
url = new URL(raw);
} catch {
return null;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
const base = url.toString().replace(/\/+$/, '');
return base.endsWith('/api') ? base : `${base}/api`;
}
/** What the wizard collects on its final step. */
export interface InstallInput {
apiUrl: string;
apiKey: string;
siteTitle?: string;
siteSubtitle?: string;
theme?: string;
albums?: string[];
adminPassword?: string;
}
/** Write a file atomically: unique temp file, then rename. */
async function atomicWrite(filePath: string, content: string): Promise<void> {
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
try {
await fs.promises.writeFile(tmpPath, content, 'utf8');
await fs.promises.rename(tmpPath, filePath);
} catch (err) {
await fs.promises.unlink(tmpPath).catch(() => {});
throw err;
}
}
/**
* Persist everything the install wizard collected.
*
* Writes gallery.yaml (albums optional — an empty gallery is a valid portfolio
* the owner can fill in later via /admin), settings.yaml, and install.json.
* Runs before caches are invalidated, so the caller owns that step.
*/
export async function completeInstall(input: InstallInput): Promise<void> {
const dir = installContentDir();
await fs.promises.mkdir(dir, { recursive: true });
const gallery: GalleryYaml = {
hero: [],
albums: (input.albums ?? []).filter((id) => typeof id === 'string'),
};
const settings: SettingsYaml = {
title: input.siteTitle?.trim() || 'Gallery',
subtitle: input.siteSubtitle?.trim() || '',
theme: { preset: input.theme || 'studio' },
};
const data: InstallFileData = {
apiUrl: input.apiUrl.trim(),
apiKey: input.apiKey.trim(),
authSecret: crypto.randomBytes(32).toString('hex'),
// Hashed, not stored as typed: the API key and the site secret have to be
// recoverable to be useful, but an admin password does not — and it is the
// one credential here a person picked and may well have reused elsewhere.
...(input.adminPassword
? { adminPassword: await generateScryptHash(input.adminPassword) }
: {}),
};
const header = (name: string) =>
`# ── ${name} (created by the Immich Folio install wizard) ──────────\n`;
const dumpOptions = { lineWidth: 120, quotingType: '"' as const, noRefs: true, sortKeys: false };
const galleryPath = path.join(dir, 'gallery.yaml');
const settingsPath = path.join(dir, 'settings.yaml');
await atomicWrite(galleryPath, header('Gallery Structure') + yaml.dump(gallery, dumpOptions));
// Only create settings.yaml if it does not already exist — a deployment that
// brings its own customised settings.yaml (but is missing gallery.yaml) must
// not have it silently replaced with the three-key skeleton the wizard writes.
if (!fs.existsSync(settingsPath)) {
await atomicWrite(settingsPath, header('Site Settings') + yaml.dump(settings, dumpOptions));
}
await atomicWrite(path.join(dir, INSTALL_FILENAME), `${JSON.stringify(data, null, 2)}\n`);
try {
await fs.promises.chmod(path.join(dir, INSTALL_FILENAME), 0o600);
} catch {
// chmod is a no-op on Windows; on Linux it prevents world-readable secrets.
}
// The token exists to gate a setup that has not happened yet. Leaving it on
// disk would keep a valid credential lying around for a door that is now
// closed anyway (isInstalled() makes every install route answer 403).
try {
fs.unlinkSync(path.join(dir, SETUP_TOKEN_FILENAME));
} catch {
// Never created, or already removed.
}
// Drop the in-process cache so the next isInstalled()/getInstallCredentials()
// call reads the freshly written file.
cachedInstallFile = null;
}

405
lib/journal.ts Normal file
View File

@@ -0,0 +1,405 @@
/**
* Journal & Storytelling Types, Parser and Serializer.
* Client-safe pure TypeScript module (no Node.js fs dependencies).
*/
export interface JournalFrontmatter {
title?: string;
subtitle?: string;
date?: string;
author?: string;
coverAssetId?: string;
layout?: string;
password?: string;
draft?: boolean;
}
export type JournalBlock =
| { type: 'heading'; level: number; text: string }
| { type: 'paragraph'; html: string }
| { type: 'quote'; text: string; author?: string }
| { type: 'photo'; assetId: string; caption?: string; layout: 'fullbleed' | 'wide' | 'contained' }
| { type: 'photo-pair'; assetIds: [string, string]; caption?: string };
export interface ParsedJournal {
frontmatter: JournalFrontmatter;
blocks: JournalBlock[];
referencedAssetIds: string[];
}
export interface JournalEntrySummary {
slug: string;
filename: string;
frontmatter: JournalFrontmatter;
excerpt: string;
wordCount: number;
readingTimeMinutes: number;
}
const HTML_ESCAPES: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
};
/**
* Make an author's text inert as HTML.
*
* This escapes rather than filters. The previous implementation stripped
* `<script>` tags, `on*="..."` handlers and the literal string `javascript:`,
* which is a denylist and was trivially bypassable: `<img src=x onerror=alert(1)>`
* (unquoted handler), `onerror='...'` (single quotes), `<svg onload=...>` (not a
* script tag) and `javasjavascript:cript:` (the replacement recombines) all
* passed through into `dangerouslySetInnerHTML`.
*
* With escaping there is nothing to enumerate: the only tags in the output are
* the ones renderInlineMarkdown emits itself.
*/
export function sanitizeHtml(input: string): string {
return input.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char]);
}
/**
* Reverse of sanitizeHtml, for turning rendered block HTML back into Markdown.
* Without this a save would write `&lt;` into the file and the next parse would
* escape the `&` again, corrupting the text a little more on every round trip.
*/
export function decodeHtmlEntities(input: string): string {
return input
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, '&');
}
/**
* Schemes an author may link to. Everything else — `javascript:`, `data:`,
* `vbscript:` — renders as plain text instead of an anchor.
*/
const SAFE_URL = /^(?:https?:\/\/|mailto:|tel:|[./#])/i;
function isSafeUrl(url: string): boolean {
// Browsers ignore control characters and whitespace inside a scheme, so
// `java\tscript:` would run. Strip them before deciding.
return SAFE_URL.test(url.replace(/[\u0000-\u0020]/g, ''));
}
/** Sanitize a slug to only allow safe URL and filesystem characters */
export function isValidSlug(slug: string): boolean {
return /^[a-zA-Z0-9_-]+$/.test(slug) && !slug.includes('..');
}
export function sanitizeSlug(input: string): string {
return (
input
.toLowerCase()
.trim()
.replace(/[^a-z0-9_-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '') || 'untitled'
);
}
/** Simple Markdown inline formatting (bold, italic, links) */
export function renderInlineMarkdown(text: string): string {
// Escape first: from here on every `<` and `"` in the string is the author's
// literal text, so the markdown rules below can only ever add the tags they
// build themselves, and a URL cannot break out of its href attribute.
let html = sanitizeHtml(text);
// Bold: **text** or __text__
//
// CodeQL flags the lazy group here as polynomial backtracking. It is left as
// is on purpose: rewriting it with a negated class (`\*\*([^*]+)\*\*`) removes
// the backtracking but also breaks nesting — `**bold *and italic* here**`
// then renders as `*<em>bold </em>and italic<em> here</em>*`. The input is
// Markdown written by an authenticated admin, never visitor input, so the
// worst case is an author slowing down their own page.
html = html.replace(/(\*\*|__)(.*?)\1/g, '<strong>$2</strong>');
// Italic: *text* or _text_
html = html.replace(/(\*|_)(.*?)\1/g, '<em>$2</em>');
// Links: [label](url)
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => {
const trimmed = url.trim();
if (!isSafeUrl(trimmed)) return label;
return `<a href="${trimmed}" target="_blank" rel="noopener noreferrer">${label}</a>`;
});
return html;
}
const isWhitespace = (char: string) => char.trim() === '';
/**
* Split `Quote -- Author` at the first separator surrounded by whitespace.
*
* A plain scan rather than a pattern. The original `/^(.*?)(?:\s+--\s+(.+))?$/`
* wrapped a lazy group around an optional one — the quadratic case — and its
* first replacement, `/\s+--\s+/`, was reported as polynomial backtracking in
* turn. This is linear and needs no reasoning about the engine at all.
*/
export function splitQuoteAuthor(text: string): { body: string; author?: string } {
for (
let hyphens = text.indexOf('--');
hyphens !== -1;
hyphens = text.indexOf('--', hyphens + 2)
) {
let start = hyphens;
while (start > 0 && isWhitespace(text[start - 1])) start--;
let end = hyphens + 2;
while (end < text.length && isWhitespace(text[end])) end++;
// Whitespace is required on both sides, so `a--b` is not a separator.
if (start === hyphens || end === hyphens + 2) continue;
return { body: text.slice(0, start), author: text.slice(end).trim() || undefined };
}
return { body: text };
}
/** Parse frontmatter (YAML block delimited by ---) */
export function parseFrontmatter(content: string): {
frontmatter: JournalFrontmatter;
body: string;
} {
const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
if (!frontmatterMatch) {
return { frontmatter: {}, body: content };
}
const rawYaml = frontmatterMatch[1];
const body = content.slice(frontmatterMatch[0].length);
const frontmatter: JournalFrontmatter = {};
for (const line of rawYaml.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) continue;
const key = trimmed.slice(0, colonIdx).trim();
let val = trimmed.slice(colonIdx + 1).trim();
if (val.length >= 2 && val.startsWith('"') && val.endsWith('"')) {
// Undo the escaping serializeJournalMarkdown applies. Without this a title
// containing a quote or a backslash gained one more backslash on every
// save/load cycle.
val = val.slice(1, -1).replace(/\\([\\"])/g, '$1');
} else if (val.length >= 2 && val.startsWith("'") && val.endsWith("'")) {
val = val.slice(1, -1);
}
if (key === 'title') frontmatter.title = val;
else if (key === 'subtitle') frontmatter.subtitle = val;
else if (key === 'date') frontmatter.date = val;
else if (key === 'author') frontmatter.author = val;
else if (key === 'coverAssetId') frontmatter.coverAssetId = val;
else if (key === 'layout') frontmatter.layout = val;
else if (key === 'password') frontmatter.password = val;
else if (key === 'draft') frontmatter.draft = val === 'true' || val === '1';
}
return { frontmatter, body };
}
/** Parse Journal Markdown content into structured blocks */
export function parseJournalMarkdown(rawContent: string): ParsedJournal {
const { frontmatter, body } = parseFrontmatter(rawContent);
const blocks: JournalBlock[] = [];
const referencedAssetIds = new Set<string>();
if (frontmatter.coverAssetId) {
referencedAssetIds.add(frontmatter.coverAssetId);
}
// Split body into paragraph chunks separated by blank lines
const chunks = body
.split(/\r?\n\s*\r?\n/)
.map((c) => c.trim())
.filter(Boolean);
for (const chunk of chunks) {
// 1. Headings (# H1, ## H2, ### H3)
// `[ \t]+` rather than `\s+`: next to `(.+)` the two overlap, and the
// engine has to try every split of the whitespace run before failing.
const headingMatch = chunk.match(/^(#{1,6})[ \t]+(\S.*)$/);
if (headingMatch) {
blocks.push({
type: 'heading',
level: headingMatch[1].length,
text: headingMatch[2].trim(),
});
continue;
}
// 2. Blockquote (> Quote text)
if (chunk.startsWith('>')) {
const quoteText = chunk
.split('\n')
.map((l) => l.replace(/^>\s?/, ''))
.join(' ')
.trim();
const { body: quoteBody, author: quoteAuthor } = splitQuoteAuthor(quoteText);
blocks.push({
type: 'quote',
text: renderInlineMarkdown(quoteBody),
author: quoteAuthor,
});
continue;
}
// 3. Image syntax: ![assetId:layout](Caption) or ![assetId1, assetId2](Caption)
const imgMatch = chunk.match(/^!\[([^\]]+)\]\(([^)]*)\)$/);
if (imgMatch) {
const rawTarget = imgMatch[1].trim();
const caption = imgMatch[2].trim() ? renderInlineMarkdown(imgMatch[2].trim()) : undefined;
// Side-by-side pair: ![asset1, asset2](Caption)
if (rawTarget.includes(',')) {
const parts = rawTarget.split(',').map((s) => s.trim());
if (parts.length >= 2) {
const id1 = parts[0];
const id2 = parts[1];
referencedAssetIds.add(id1);
referencedAssetIds.add(id2);
blocks.push({
type: 'photo-pair',
assetIds: [id1, id2],
caption,
});
continue;
}
}
// Single photo: ![assetId:layout](Caption)
let assetId = rawTarget;
let layout: 'fullbleed' | 'wide' | 'contained' = 'contained';
if (rawTarget.includes(':')) {
const [id, l] = rawTarget.split(':');
assetId = id.trim();
const normLayout = l.trim().toLowerCase();
if (normLayout === 'fullbleed') layout = 'fullbleed';
else if (normLayout === 'wide') layout = 'wide';
}
referencedAssetIds.add(assetId);
blocks.push({
type: 'photo',
assetId,
caption,
layout,
});
continue;
}
// 4. Standard Text Paragraph
blocks.push({
type: 'paragraph',
html: renderInlineMarkdown(chunk.replace(/\r?\n/g, ' ')),
});
}
return {
frontmatter,
blocks,
referencedAssetIds: Array.from(referencedAssetIds),
};
}
/** Converts a ParsedJournal structure back into clean Markdown syntax */
export function serializeJournalMarkdown(journal: ParsedJournal): string {
const lines: string[] = [];
// Frontmatter
const fmKeys = Object.keys(journal.frontmatter) as Array<keyof JournalFrontmatter>;
if (
fmKeys.length > 0 &&
fmKeys.some((k) => journal.frontmatter[k] !== undefined && journal.frontmatter[k] !== '')
) {
lines.push('---');
for (const key of fmKeys) {
const val = journal.frontmatter[key];
if (val !== undefined && val !== '') {
if (typeof val === 'boolean') {
lines.push(`${key}: ${val}`);
} else {
const escaped = String(val).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
lines.push(`${key}: "${escaped}"`);
}
}
}
lines.push('---');
lines.push('');
}
// Blocks
for (const block of journal.blocks) {
switch (block.type) {
case 'heading': {
const hashes = '#'.repeat(Math.min(Math.max(block.level, 1), 6));
lines.push(`${hashes} ${block.text}`);
break;
}
case 'paragraph': {
const text = block.html.replace(/<[^>]+>/g, (tag) => {
if (tag.startsWith('<strong>') || tag.startsWith('<b>')) return '**';
if (tag.startsWith('</strong>') || tag.startsWith('</b>')) return '**';
if (tag.startsWith('<em>') || tag.startsWith('<i>')) return '*';
if (tag.startsWith('</em>') || tag.startsWith('</i>')) return '*';
return '';
});
lines.push(decodeHtmlEntities(text));
break;
}
case 'quote': {
const authorSuffix = block.author ? ` -- ${block.author}` : '';
const text = decodeHtmlEntities(block.text.replace(/[\r\n]+/g, ' '));
lines.push(`> ${text}${authorSuffix}`);
break;
}
case 'photo': {
const layoutSuffix = block.layout !== 'contained' ? `:${block.layout}` : '';
const caption = block.caption
? decodeHtmlEntities(block.caption.replace(/[\r\n]+/g, ' '))
: '';
lines.push(`![${block.assetId}${layoutSuffix}](${caption})`);
break;
}
case 'photo-pair': {
const caption = block.caption ? block.caption.replace(/[\r\n]+/g, ' ') : '';
lines.push(`![${block.assetIds[0]}, ${block.assetIds[1]}](${caption})`);
break;
}
}
lines.push('');
}
return lines.join('\n').trim();
}
/** Calculate approximate word count and reading time */
export function calculateReadingTime(text: string): { words: number; minutes: number } {
const plainText = text.replace(/<[^>]+>/g, ' ').replace(/!\[.*?\]\(.*?\)/g, ' ');
const words = plainText.trim().split(/\s+/).filter(Boolean).length;
const minutes = Math.max(1, Math.round(words / 200));
return { words, minutes };
}
/** Extract a brief plain-text excerpt from journal blocks */
export function extractExcerpt(parsed: ParsedJournal, maxLength = 160): string {
if (parsed.frontmatter.subtitle) return parsed.frontmatter.subtitle;
for (const block of parsed.blocks) {
if (block.type === 'paragraph') {
const text = block.html.replace(/<[^>]+>/g, '').trim();
if (text) {
return text.length > maxLength ? `${text.slice(0, maxLength).trim()}...` : text;
}
}
}
return '';
}

57
lib/password.ts Normal file
View File

@@ -0,0 +1,57 @@
/**
* scrypt password hashing, shared by the album/subpage gate (lib/auth.ts) and
* the admin panel (lib/admin/auth.ts).
*
* Stored format: `scrypt:<salt-hex>:<hash-hex>`.
*/
import crypto from 'crypto';
const SCRYPT_PREFIX = 'scrypt:';
/**
* scrypt on the libuv threadpool rather than the main thread.
*
* scryptSync costs ~23ms per call, and that is 23ms during which the process
* serves nothing else. The /api/auth rate limit (10/min) is keyed on the client
* IP, but with the default TRUSTED_PROXY_HOPS=0 that IP comes from a spoofable
* header (see lib/rate-limit.ts), so an attacker rotating the header gets
* effectively unlimited buckets — each request buying 23ms of dead process.
* Running async does not stop the spoofing, but it removes the amplification
* that made it worth doing.
*/
export function scryptAsync(password: string, salt: string, keylen: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
crypto.scrypt(password, salt, keylen, (err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
});
});
}
/** Whether a stored value is an scrypt hash rather than a plaintext password. */
export function isScryptHash(stored: string): boolean {
return stored.startsWith(SCRYPT_PREFIX);
}
/** Verify a password against the `scrypt:salt:hash_hex` format. */
export async function verifyScrypt(password: string, stored: string): Promise<boolean> {
if (!isScryptHash(stored)) return false;
try {
const [, salt, hashHex] = stored.split(':');
const key = await scryptAsync(password, salt, 64);
const expectedKey = Buffer.from(hashHex, 'hex');
if (key.length !== expectedKey.length) return false;
return crypto.timingSafeEqual(key, expectedKey);
} catch {
return false;
}
}
/** Produce a storable `scrypt:salt:hash_hex` string. */
export async function generateScryptHash(password: string): Promise<string> {
const salt = crypto.randomBytes(16).toString('hex');
const hash = (await scryptAsync(password, salt, 64)).toString('hex');
return `${SCRYPT_PREFIX}${salt}:${hash}`;
}

View File

@@ -8,12 +8,13 @@
import crypto from 'crypto'; import crypto from 'crypto';
import { env } from './env'; import { env } from './env';
import { getInstallCredentials } from './install';
let _fallbackSecret: string | null = null; let _fallbackSecret: string | null = null;
let _warned = false; let _warned = false;
export function resolveAuthSecret(): string { export function resolveAuthSecret(): string {
const secret = env.AUTH_SECRET; const secret = env.AUTH_SECRET || getInstallCredentials().authSecret;
if (secret) return secret; if (secret) return secret;
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {

View File

@@ -4,6 +4,8 @@ import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) { export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64'); const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const isDev = process.env.NODE_ENV === 'development';
// Define CSP directives // Define CSP directives
const cspDirectives = [ const cspDirectives = [
"default-src 'self'", "default-src 'self'",
@@ -11,7 +13,9 @@ export function proxy(request: NextRequest) {
// CSP2-only browsers ignore 'strict-dynamic' and would honour it — making // CSP2-only browsers ignore 'strict-dynamic' and would honour it — making
// the fallback strictly worse than having none. There are no inline // the fallback strictly worse than having none. There are no inline
// <script> tags in the app; Next.js nonces the ones it injects itself. // <script> tags in the app; Next.js nonces the ones it injects itself.
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`, // In development mode, Next.js / React dev tools require 'unsafe-eval' for Fast Refresh
// and stack trace reconstruction. Omitted in production.
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${isDev ? " 'unsafe-eval'" : ''}`,
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://unpkg.com", "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://unpkg.com",
"font-src 'self' https://fonts.gstatic.com", "font-src 'self' https://fonts.gstatic.com",
"img-src 'self' data: blob: https://*.basemaps.cartocdn.com https://*.tile.openstreetmap.org https://unpkg.com", "img-src 'self' data: blob: https://*.basemaps.cartocdn.com https://*.tile.openstreetmap.org https://unpkg.com",

6
public/favicon.svg Normal file
View File

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
<rect width="32" height="32" rx="6" fill="#111"/>
<circle cx="16" cy="16" r="5" stroke="#fff" stroke-width="2"/>
<circle cx="16" cy="16" r="2" fill="#fff"/>
<path d="M8 10h3l1.5-2h7l1.5 2h3a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V12a2 2 0 0 1 2-2z" stroke="#fff" stroke-width="2" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 401 B