fix: Immich outage handling, image tiers, admin save safety (#394)

* fix: migrate deprecated middleware convention to proxy

Next.js 16 deprecated the `middleware` file convention in favour of
`proxy`. The build warned on every run, and the convention is slated for
removal in a future major — at which point Next.js would silently stop
invoking this file. That is not a cosmetic failure: proxy.ts owns the
Content-Security-Policy and the per-request nonce, so an uninvoked file
means every document response ships with no CSP at all, with nothing in
the build output to catch it.

Renames middleware.ts to proxy.ts and the exported middleware() to
proxy(), per the official migration. The config.matcher export is
unchanged, so route coverage is identical.

Adds lib/__tests__/proxy.test.ts, which pins the export name and
verifies the behaviour a silent regression would take out: a CSP is set,
the nonce in the policy matches the one forwarded to pages via x-nonce,
nonces differ per request, x-pathname still reaches the root layout, and
the matcher continues to cover /admin.

Verified: tsc 0 errors, 105 unit tests passing (98 before), production
build succeeds with 0 deprecation warnings.

* fix: stop reporting Immich outages as missing albums

lib/immich.ts request() returned null for every failure mode: a 5xx, a
rejected API key, a network error, and a non-JSON body all looked exactly
like "Immich answered and said this does not exist". Callers had no way
to tell the two apart, and app/[...path]/page.tsx calls notFound() on a
null album in five places.

The result was that while Immich was down or returning 5xx, every album
URL served a hard 404 — for albums that exist. Visitors saw "not found",
and crawlers were free to de-index real content over a transient outage.

request() now throws ImmichUnavailableError for anything that is not a
definitive answer about the resource, and reserves null for 404 and 410.
Pages let that propagate, so an outage surfaces as a 500 rather than a
404. Two callers must not propagate and are handled explicitly:

- ping() catches and returns false — it answers "is Immich reachable",
  and both callers (/api/health, /api/admin/status) render that as a
  status field.
- /api/exif and /api/map return 503 with Retry-After instead of 404 and
  an empty marker list respectively. An empty map is otherwise
  indistinguishable from a gallery with no GPS data.

Adds 10 tests: each failure mode maps to the right outcome, getAlbum and
getAlbums propagate rather than reporting empty, ping stays non-throwing,
and a failed request leaves no stale entry in the in-flight coalescing
map — which would otherwise replay the failure after Immich recovered.

Verified: tsc 0 errors, 115 unit tests passing (105 before), production
build exit 0, eslint 0 errors on all touched files.

* fix: bound how long Immich requests may hang

lib/immich.ts set no timeout on any of its three fetch call sites, so the
only ceiling was undici's built-in default, measured in minutes. Every
page is force-dynamic, which means an Immich that accepts connections but
never answers held each visitor's render open for that whole window —
and since nothing caches the failure, load kept arriving.

Adds IMMICH_TIMEOUT_MS (default 15000, floored at 1000 so a stray 0
cannot mean "no timeout"), threaded through env.ts and AppConfig like
CACHE_TTL.

The two kinds of call need different treatment:

- request() carries a whole-exchange AbortSignal.timeout(). JSON
  payloads are small, so one budget can cover headers and body.
- streamAsset()/streamVideo() use an AbortController whose timer is
  cleared in a finally the moment response headers arrive. A large
  original photo or a long video is legitimately slow to transfer; a
  whole-request timeout would truncate playback and break seeking, since
  every range request would restart the clock.

A timed-out request surfaces as ImmichUnavailableError naming the budget,
so a misconfigured value is diagnosable from the log line alone.

Adds 5 tests, including the two that pin the distinction: a stream whose
headers have arrived is not aborted an hour later, while a stream that
never sends headers still is.

Verified: tsc 0 errors, 120 unit tests passing (115 before), production
build exit 0, no new eslint errors (the one error in env.ts is
pre-existing — confirmed against a clean tree).

* fix: stop caching Immich outages as permanently missing media

f3 split "gone" from "unavailable" in request(), but streamAsset() and
streamVideo() have their own fetch calls and were left returning null for
every failure. Both proxy routes turn null into a 404.

That 404 carried no Cache-Control, and a 404 is heuristically cacheable
per RFC 9111 — on URLs the success path serves as `immutable`. So a
transient outage, or a timeout introduced in 370e668, could pin a broken
image or an unplayable video in the visitor's browser cache well after
Immich recovered.

Both stream methods now throw ImmichUnavailableError for transport
failures, timeouts, and any error status other than 404/410, and reserve
null for genuinely absent media. A 200 with no body counts as
unavailable, not as missing. The routes translate that into 503 with
Retry-After, and both error responses — the 503 and the real 404 — now
send Cache-Control: no-store.

streamVideo keeps accepting 206, so range requests and seeking are
unaffected.

Adds 7 tests covering each failure mode for both methods plus the 206
path, and updates the F4 timeout test, which asserted the old null return.

Verified: tsc 0 errors, 127 unit tests passing (120 before), production
build exit 0, eslint 0 errors on touched files.

* perf: cache "does not exist" answers from Immich

getAlbum() and getAssetInfo() cached successes but discarded a definitive
"not found", so a missing resource was re-queried upstream on every call.

Measured before: 5 sequential lookups of a missing asset produced 5
upstream fetches. After: 1.

This is not hypothetical. app/page.tsx resolves every gallery.yaml hero
ID through getAssetInfo() on each render, and the homepage is
force-dynamic — so a hero photo deleted from Immich but still listed in
gallery.yaml cost one 404 round-trip per page view, indefinitely.

Absence is stored as a frozen MISSING sentinel because the cache cannot
distinguish a miss from a stored null; both read back as null.

Only definitive 404/410 answers are cached. An outage throws
ImmichUnavailableError and is deliberately never stored — caching one
would keep the gallery broken after Immich recovered. A test pins that:
a 503 followed by a healthy response must reach Immich the second time.

Stored under the normal cacheTtl rather than a separate shorter negative
TTL, because the reason for a shorter one no longer applies: outages are
not cached at all now, and both invalidation paths (the Immich webhook
and the admin save/reload) clear the entry immediately, so a corrected
asset ID takes effect at once rather than waiting out a TTL.

Also raises the test config's cacheTtl from 0, which expired entries in
the same millisecond they were written and would have made any caching
assertion flaky. Test isolation comes from cache.clear() in beforeEach.

Verified: tsc 0 errors, 131 unit tests passing (127 before), production
build exit 0, eslint 0 errors on touched files.

* fix: add themed error and not-found pages

The app had no app/error.tsx, app/not-found.tsx or global-error.tsx, so
every failure fell through to Next.js's unstyled default page.

That gap became visible with 253ade0, which made an Immich outage produce
a 500 instead of a false 404 — correct, but what a visitor saw was a bare
framework error screen with none of the site's theming.

The two pages also carry the distinction the error split was for, and
they carry it structurally rather than by inspecting the error: notFound()
renders not-found.tsx, a throw renders error.tsx. That matters because
Next.js strips error messages in production and replaces them with a
digest — this component genuinely cannot tell an Immich outage from any
other server error, so it does not claim to. It frames the failure as
temporary and offers reset(); not-found.tsx deliberately does not, since
a real 404 is not transient.

The digest is shown so a user report can be traced to a log line. The raw
error message is never rendered — it can carry an upstream URL, a header
or a config value.

Both pages reuse .empty-state, which existed in globals.css but was
unreferenced anywhere in the app; extended with title, actions and button
elements matching the PasswordGate button, the only other action button
in the codebase.

Tested by server-rendering both components (react-dom/server, no new
dependencies) — 8 tests covering the styling hook, the retry and home
affordances, digest handling, and that a message containing an API key or
host address does not reach the markup. Note vitest.config.ts only
includes lib/__tests__/**/*.test.ts, so the test uses createElement
rather than JSX; a .tsx file there would never run.

Not verified in a browser: this worktree has no .env.local and only
.example content files, so the app boots into setup mode and neither
Playwright nor a dev server can exercise these routes here.

Verified: tsc 0 errors, 139 unit tests passing (131 before), production
build exit 0 with /_not-found registered, eslint 0 errors.

* perf: drop the unused originalUrl from every photo item

PhotoItem declared originalUrl and toPhotoItems computed it for every
asset, but a repo-wide grep found exactly two references: the field
declaration and the assignment. Nothing ever read it — the grid uses
thumbUrl, the lightbox uses previewUrl.

The cost was not the encryption. PhotoItem is a server-to-client prop, so
the dead field was serialized into the RSC payload and shipped to the
browser for every photo.

Measured: 137 bytes per asset once serialized, so 6.7 KB for a 50-photo
album and 66.9 KB for a 500-photo one — transferred and parsed on every
page view, never read.

Removed rather than wired up to a "view original" affordance. Exposing
full-size originals is a bandwidth and privacy decision for the project
to make deliberately, not something to infer from a dangling field.

No unit test: this is a deletion whose correctness is exactly "nothing
referenced it", which tsc and a repo-wide grep already establish. A test
asserting the absence of a field would restate the type checker.

Verified: tsc 0 errors, 139 unit tests passing, production build exit 0,
eslint unchanged at 4 pre-existing errors on the touched files (unused
imports, confirmed identical against a stashed clean tree).

* chore: remove four orphaned imports from the catch-all route

Link, Image, PhotoGrid and BackLink were imported by app/[...path]/page.tsx
and never used — 4 of the 6 no-unused-vars errors in the repo baseline.

Verified they are leftovers, not a dropped render path: PhotoGrid and
BackLink are both rendered by AlbumDetailView, which imports them itself,
and BackLink is also used by the impressum and map pages. Rendering was
extracted out of page.tsx into AlbumDetailView/SubpageGridView at some
point and the imports stayed behind. `type PhotoItem` is still needed by
toPhotoItems, so that import narrows to a type-only import rather than
disappearing.

No bundle win, measured: .next/static is 1084 KB across 20 JS chunks both
before and after, byte-identical. Turbopack already tree-shook them. The
backlog note that predicted unused client-component imports would hold
them in the client graph was wrong, and has been corrected there.

The value is readability and lint: repo errors drop from 54 to 50, and
page.tsx no longer reads as though it renders the grid itself.

chore: rather than fix:/perf: — nothing behaves differently and the
measurement showed no performance change, so either of those labels would
misdescribe it. CLAUDE.md lists chore: as a valid prefix.

Verified: tsc 0 errors, 139 unit tests passing, production build exit 0,
eslint 0 errors on the touched file.

* fix: make ?w= able to narrow the image tier instead of being ignored

The image proxy resolved its Immich rendition with `?size=` winning
whenever present, falling back to `?w=` otherwise. lib/urls.ts always
writes `?size=`, so for every URL this app generates the width branch was
unreachable and widthToSize() was dead code — while CLAUDE.md documented
the width mapping as the actual behaviour.

`?size=` is now a ceiling rather than an override: when both are present
the smaller tier wins, so a width can narrow the request but never widen
it. That asymmetry is the point. Letting width win outright — the obvious
reading of the docs — would have been a real regression: next/image emits
widths up to 3840 and widthToSize(1920) is 'original', so every large
display would have started downloading full-size originals in place of
previews. A test pins that specific case.

No measured change today. The only URLs carrying both parameters are
?size=preview with next/image widths, whose smallest vw-based deviceSize
is 640 — already preview either way. This is a correctness fix that makes
the documented contract true and testable, not a performance win.

Moved the logic to lib/imageSize.ts so it can be tested at all:
vitest.config.ts only collects lib/__tests__, so nothing inside a route
file is reachable from the suite. 9 tests cover the tier boundaries, both
single-parameter paths, malformed input, and the ceiling behaviour.

CLAUDE.md updated to describe the ceiling rule rather than a plain
width mapping.

Verified: tsc 0 errors, 148 unit tests passing (139 before), production
build exit 0, eslint 0 errors on touched files.

* fix: validate the per-album heroImage UUID from gallery.yaml

Every asset ID in gallery.yaml is routed through validateUuid before it
can reach encodeAssetId, which encrypts whatever it is handed. One was
not: for a per-album entry the album ID (the map key) was validated while
the heroImage value was stored raw.

A typo there produced a perfectly well-formed image URL that 404s forever,
with nothing in the log naming the cause — the failure surfaced as a
broken hero image on an album page, far from the line that caused it.

This is narrower than the finding that prompted it, which proposed
guarding encodeAssetId itself. Validation belongs at config load, where it
runs once and can name the file and the album; a guard in encodeAssetId
would run on every render and duplicate validateUuid at the wrong layer.
The heroImage path was the only unvalidated route into it.

validateUuid warns and substitutes the nil UUID rather than throwing, so a
bad ID still degrades to a missing image instead of taking the page down —
and since f511e62 that 404 is negative-cached, so it costs one upstream
request rather than one per render.

Adds 4 tests. The two that pin the wiring were mutation-checked: both fail
against the unfixed code and pass with it.

Verified: tsc 0 errors, 152 unit tests passing (148 before), production
build exit 0, eslint 0 errors on touched files.

* fix: keep /admin reachable when gallery.yaml cannot be derived

getConfig() throws on three shapes the admin page builder is able to
write: a gallery with neither albums nor subpages, a subpage with no name,
and a subpage with neither albums nor sections.

RootLayout called it unguarded, and a throw in a *layout* is not caught by
app/error.tsx — that needs a global-error boundary, which this app does
not have. /admin renders inside that same layout, so one bad save took
down the site together with the only tool that could undo it. Recovery
meant editing content/gallery.yaml on the host, or exec'ing into the
container. This is issue #326's failure mode reached through an invalid
config instead of a missing one.

Adds getConfigOrNull(), which returns null rather than throwing and logs
the underlying error plus the path to content/.backups/. The layout treats
null exactly like needsSetup: setup screen for visitors, children rendered
for admin paths so the panel still loads. generateMetadata() is guarded
too — it also calls getConfig(), and it also runs before any error
boundary.

This is the half of the finding that makes every broken config
recoverable, including ones this app never wrote: a hand-edited file, a
restored backup, a config from an older version. The other half —
validating in the admin PUT so the bad state is never written — is filed
separately; it prevents new breakage but cannot repair existing breakage,
so it was not the one to do first.

Adds 10 tests. Three pin the premise by asserting getConfig() really does
throw on each shape, so the fallback cannot quietly become dead weight.
One asserts the needsSetup path still returns a config rather than null,
since missing and invalid are different states that must not collapse.

Not verified in a browser: this worktree has no .env.local and only
.example content files, so the layout/error-boundary interaction is
reasoned from Next.js semantics and covered at the getConfig level only.

Verified: tsc 0 errors, 162 unit tests passing (152 before), production
build exit 0, eslint 0 errors on touched files.

* fix: reject an admin save the site would not be able to load

The admin PUT validated only the shape of the hero field, then wrote. None
of getConfig()'s three throw conditions was checked, so the page builder
could persist a gallery.yaml that cannot be loaded — and the user got
"Saved successfully" for it. Since 95877af that no longer locks anyone
out, but the public site still drops to the setup screen until someone
notices.

Extracts the gallery half of getConfig() into deriveGallery(), which the
route now runs against the proposed gallery before writing. Two
alternatives were rejected on purpose:

- Re-checking the three conditions in the route would put a second copy of
  the rules next to the first, and the two would drift.
- Write-then-verify-then-roll-back leaves a window in which other requests
  read the broken config.

The extraction is a pure move: no logic changed inside it, and all 162
pre-existing tests pass untouched, which is what makes that claim
checkable rather than asserted.

The 400 carries the derivation's own message, so the admin UI names the
offending subpage instead of saying "invalid gallery" — a builder with a
dozen subpages needs to know which one. A test pins that the message
identifies it.

Adds 8 tests: each rejected shape, the named-subpage message, and the
valid structures (standalone albums, subpage membership, sections,
per-album overrides and hero images) so the extraction cannot silently
lose behaviour.

Verified: tsc 0 errors, 170 unit tests passing (162 before), production
build exit 0, eslint 0 errors on touched files.

* fix: hash subpage passwords off the main thread

verifyScrypt used crypto.scryptSync, measured at 22.8ms per call — 22.8ms
during which the Node process serves nothing else, because the sync
variant runs on the main thread rather than the libuv threadpool.

The /api/auth rate limit does not contain this. It allows 10 attempts per
minute, but the bucket key is the client IP, and with the default
TRUSTED_PROXY_HOPS=0 that IP is read from x-real-ip / x-forwarded-for —
both attacker-controlled. lib/rate-limit.ts already documents that those
headers are spoofable at hops=0; what followed from it was not written
down anywhere: one attacker rotating a header gets unlimited buckets, and
each request buys 22.8ms of dead process. Roughly 44 requests per second
saturates it.

Switches verifyScrypt and generateScryptHash to the async crypto.scrypt,
which runs on the threadpool. This does not stop the spoofing — that is
inherent to hops=0 and already documented — it removes the amplification
that made spoofing worth doing.

authenticate() becomes async. It had exactly one caller
(app/api/auth/route.ts). isAuthenticated() is deliberately left
synchronous: it only computes an HMAC, and it is called from server
components.

Adds 4 tests, two of which pin the fix and were mutation-checked against
the old implementation — both fail with scryptSync and pass with scrypt.
One asserts scryptSync is never called; the other asserts a 2ms interval
still fires during a hash, which is the property that actually matters. A
slower machine lengthens the hash and yields more ticks, so that test
fails on a blocked loop rather than on a busy one.

Also adds a scrypt-hashed fixture subpage, so the suite exercises
verifyScrypt rather than only the deprecated plaintext fallback.

Verified: tsc 0 errors, 174 unit tests passing (170 before), production
build exit 0, eslint 0 errors on touched files.

* fix: warn when TRUSTED_PROXY_HOPS cannot identify a client

getClientIp falls back to a shared 'unknown' bucket whenever the
X-Forwarded-For chain is shorter than the configured hop count, or the
header is absent with hops > 1.

That fallback is correct — the alternative is trusting a spoofable entry —
but it was silent, and silence is the problem. Every unidentified request
shares one bucket per endpoint, and this is an image proxy: a single
50-photo grid issues ~50 /api/image requests, so the default
RATE_LIMIT_RPM=1500 is collectively spent by roughly 30 page loads a
minute. Someone who sets TRUSTED_PROXY_HOPS=2 for Cloudflare-plus-nginx
and then reaches nginx directly gets a site that 429s everyone, with
nothing in the log pointing at the cause.

Warns once per process, naming the configured hop count and what was
actually seen — the chain length, or which header was missing. Once, not
per request: enough to diagnose without flooding the log.

The fallback itself is unchanged. Trusting a shorter chain would hand
every client its own bucket key and defeat the limiter entirely.

No warning at hops=0, where the shared bucket is the documented
consequence of not declaring a proxy rather than a misconfiguration.

Adds 6 tests covering each fall-through path, the once-per-process
behaviour, and both silence cases. The once-per-process flag needs a test
seam to re-arm, hence the __resetProxyWarningForTests export.

Verified: tsc 0 errors, 180 unit tests passing (174 before), production
build exit 0, eslint 0 errors on touched files.

* fix: send Retry-After on every rate-limited response

/api/image, /api/video and /api/exif each computed the retry delay,
interpolated it into a console.warn, and then returned a 429 without it —
the number was calculated and thrown away. /api/og did not compute it at
all. Only /api/auth and /api/map sent the header.

This matters more for an image proxy than for a typical API: one gallery
page issues around fifty /api/image requests, so a burst that trips the
limit produces fifty rejections carrying no back-off signal. The browser
and next/image then retry on their own schedule — a retry storm against a
server that just reported it was overloaded.

Adds Retry-After and Cache-Control: no-store to all four. no-store because
the success path serves these same URLs as `immutable`.

The delay now comes from a shared retryAfterSeconds() helper rather than
an inline Math.ceil in each route, which also fixes an edge every copy
shared: a window on the point of expiring yields 0, and Retry-After: 0
tells the client to retry immediately, which is the opposite of what a 429
means. A resetAt already in the past yields a negative number, which is
not valid HTTP. The helper floors at 1.

The three routes that already sent the header (/api/auth, /api/map,
/api/admin/auth) and /api/health now use the helper too — leaving four
copies of the buggy arithmetic behind while centralising the rest would
have been worse than not centralising at all.

Adds 2 tests, one of them specifically for the zero-and-negative edge.

Verified: tsc 0 errors, 182 unit tests passing (180 before), production
build exit 0, eslint 0 errors on all ten touched files.

* fix: add an escape hatch for stale browser image caches

Image and video responses are served
`Cache-Control: public, max-age=31536000, immutable`, so a browser does
not revalidate them for a year — the ETag is not even consulted. When
Immich regenerates thumbnails after a job re-run, or a photo is rotated,
the asset ID does not change, so neither does the deterministic token or
the URL. Visitors keep the old rendition, and the webhook that clears the
server-side caches cannot reach a browser. The only existing remedy was
rotating AUTH_SECRET, which invalidates every token on the site.

Corrects the framing this started from. The finding described it as an
ETag problem, but `immutable` means the ETag is never reached in the case
that matters. The URL is the only lever a browser cache responds to, so
the buster belongs there. It is also mixed into the ETag, since a matching
ETag across two different URLs would be wrong regardless.

Adds IMAGE_CACHE_VERSION, empty by default. Unset, the generated URLs are
byte-identical to before — a test asserts exactly that, because a
cache-busting feature that changes URLs when nobody asked for it would
silently discard every visitor's cache on deploy.

The value is URL-encoded at parse time; an unescaped one could otherwise
inject query parameters into every image URL on the site.

Deliberately not done: shortening max-age or dropping `immutable`. Both
trade a large, real bandwidth win for a rare correctness case, and the
cost is not measurable from this worktree. The aggressive caching stays
the default; this only adds a way out.

Adds 6 tests: default-unchanged, whitespace treated as unset, both URL
shapes, escaping, and that a bump changes the query while leaving the
token intact.

Verified: tsc 0 errors, 188 unit tests passing (182 before), production
build exit 0, eslint unchanged (the one error in env.ts is pre-existing,
confirmed against a stashed tree).

* security: validate the backup filename before restoring from it

restoreBackup() joined its argument straight into a path and copied the
result over a content file. path.join resolves `..`, so
restoreBackup('../../../../etc/passwd') would have written any readable
file over content/settings.yaml — whose contents the admin GET endpoints
hand straight back. The destination was chosen by
backupFilename.includes('gallery.yaml'), which is substring matching on
the same attacker-supplied string, so the caller picked that too.

Not exploitable today: the function has zero callers. That is precisely
why it was worth fixing rather than leaving — it is an exported function
carrying a traversal bug, waiting for whoever wires up the restore button
the admin panel does not yet have.

Hardened rather than deleted. The status endpoint already reports backup
counts, so restore is plainly intended; removing a half-built feature is
the maintainer's call, not a side effect of a security fix.

The name must now match the pattern this service itself produces, and the
destination is derived from the matched group rather than a substring
search. The redundant basename check is kept on purpose: it preserves the
guarantee if that pattern is ever loosened.

Adds 12 tests. Nine of them fail against the unguarded version —
mutation-checked by removing the guard and confirming, rather than
assuming they would.

Verified: tsc 0 errors, 200 unit tests passing (188 before), production
build exit 0, eslint 0 errors on touched files.

* fix: give each admin save its own temp file

writeYamlFile wrote to a constant `${filePath}.tmp` before renaming. The
rename is what makes the write atomic; the temp filename was not. Two
saves of the same file in flight at once shared that path, so the second
writeFile could interleave with the first's rename — publishing one save's
bytes under the other's, or a truncated mix of both. A double-clicked Save
in the page builder is enough to reach it.

The temp name now carries the pid and a per-process counter, so concurrent
writers cannot collide either within a process or across workers.

Also wraps the write and rename so a failure unlinks the temp file instead
of leaving it in content/. The cleanup swallows its own errors: failing to
tidy up must not replace the real error with a misleading one.

Adds 7 tests, and both halves were mutation-checked independently —
reverting to the fixed temp path fails two of them, removing the cleanup
fails two others. Two of the tests exist to pin properties that are easy
to regress silently: that the rename targets the temp file just written,
and that the happy path issues no unlink.

Verified: tsc 0 errors, 207 unit tests passing (200 before), production
build exit 0, eslint 0 errors on touched files.

* fix: await the stream-timeout rejection before advancing timers

`npm run test:unit` exited 1 even though all 207 tests passed. The
timeout test started `streamAsset`, advanced the fake timers past the
15s budget, and only then attached the rejection expectation. The abort
fires *during* `advanceTimersByTimeAsync`, so for one microtask turn the
promise was rejected with no handler attached — Node reports that as an
unhandled rejection, and vitest fails the whole run on it regardless of
test outcomes. CI would have blocked on a green suite.

Attaching the assertion before advancing the timers fixes the ordering
without weakening it: the same rejection and the same `captured.aborted`
check still run, just awaited after the advance rather than created
after it.

Verified: vitest exit 0, 207/207 passing, tsc 0 errors, prettier clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ralksta
2026-08-05 12:04:01 +02:00
committed by GitHub
parent 25d936f11f
commit 300a031445
43 changed files with 2073 additions and 197 deletions

View File

@@ -19,6 +19,21 @@ SITE_SUBTITLE=A visual journal
# Cache TTL in seconds (integer >= 0, default: 300 = 5 minutes) # Cache TTL in seconds (integer >= 0, default: 300 = 5 minutes)
CACHE_TTL=300 CACHE_TTL=300
# Cache-buster for image and video URLs (any string, default: empty = off).
# Images are served with a one-year immutable cache, so browsers never
# revalidate them. If you regenerate thumbnails in Immich, or rotate/edit a
# photo, the asset ID stays the same and visitors keep seeing the old version.
# Bump this value (e.g. 1 → 2) to change every image URL at once and force a
# refetch. Leave it unset in normal operation.
# IMAGE_CACHE_VERSION=1
# How long to wait for a response from Immich, in milliseconds
# (integer, minimum 1000, default: 15000 = 15 seconds).
# Bounds the wait for a *response* only — downloading a large photo or a long
# video is not capped by this. Raise it if metadata search on very large albums
# times out; lower it to fail faster when Immich is unreachable.
# IMMICH_TIMEOUT_MS=15000
# Rate limit for image proxy (integer >= 1, requests per minute per IP, default: 120) # Rate limit for image proxy (integer >= 1, requests per minute per IP, default: 120)
# RATE_LIMIT_RPM=120 # RATE_LIMIT_RPM=120

View File

@@ -75,7 +75,9 @@ Singleton `ImmichClient` class exported as `immich`. All Immich API calls are se
| `GET /api/admin/albums` | Browse all shared Immich albums (admin-only) | | `GET /api/admin/albums` | Browse all shared Immich albums (admin-only) |
| `POST /api/admin/reload` | Invalidate config + Immich cache | | `POST /api/admin/reload` | Invalidate config + Immich cache |
The image proxy maps requested pixel widths (`?w=`) to Immich size tiers: `≤250px→thumbnail`, `≤1440px→preview`, `>1440px→original`. The image proxy maps requested pixel widths (`?w=`) to Immich size tiers: `≤250px→thumbnail`, `≤1440px→preview`, `>1440px→original` (`lib/imageSize.ts`).
`?size=` (written by `lib/urls.ts`) acts as a **ceiling**, not an override. When both parameters are present the smaller tier wins, so `?w=` can narrow the request but never widen it — `next/image` emits widths up to 3840, so letting width win outright would serve full-size originals to every large display.
### Routing (`app/[...path]/page.tsx`) ### Routing (`app/[...path]/page.tsx`)
@@ -119,10 +121,12 @@ Visual page builder and settings editor at `/admin`. Enabled by setting `ADMIN_P
After saving, `invalidateConfigCache()` is called so the next request picks up the new YAML without restart. After saving, `invalidateConfigCache()` is called so the next request picks up the new YAML without restart.
### Middleware (`middleware.ts`) ### Proxy (`proxy.ts`)
Applies CSP (with per-request nonce), HSTS, and other security headers on all non-API, non-static routes. The nonce is passed to pages via the `x-nonce` request header. Applies CSP (with per-request nonce), HSTS, and other security headers on all non-API, non-static routes. The nonce is passed to pages via the `x-nonce` request header.
Next.js 16 renamed the `middleware` file convention to `proxy`: the file is `proxy.ts` and it exports `proxy()` (not `middleware()`). The `config.matcher` export is unchanged.
## Code conventions ## Code conventions
- **TypeScript strict mode** — no untyped `any`; use `@ts-expect-error` (not `@ts-ignore`) with a comment when suppressing type errors. - **TypeScript strict mode** — no untyped `any`; use `@ts-expect-error` (not `@ts-ignore`) with a comment when suppressing type errors.

View File

@@ -96,6 +96,8 @@ IMMICH_API_KEY=your-api-key
SITE_TITLE=My Photography # default: "Gallery" SITE_TITLE=My Photography # default: "Gallery"
SITE_SUBTITLE=A visual journal # default: empty SITE_SUBTITLE=A visual journal # default: empty
CACHE_TTL=300 # seconds, default: 300 CACHE_TTL=300 # seconds, default: 300
IMMICH_TIMEOUT_MS=15000 # Immich response wait, default: 15000
IMAGE_CACHE_VERSION=1 # bump to bust browser image caches, default: off
RATE_LIMIT_RPM=1500 # requests/min/IP, default: 1500 RATE_LIMIT_RPM=1500 # requests/min/IP, default: 1500
AUTH_SECRET=long-random-string # required in production AUTH_SECRET=long-random-string # required in production
TRUSTED_PROXY_HOPS=1 # reverse proxies in front, default: 0 TRUSTED_PROXY_HOPS=1 # reverse proxies in front, default: 0

View File

@@ -18,7 +18,6 @@ export interface PhotoItem {
type: 'image' | 'video'; type: 'image' | 'video';
thumbUrl: string; thumbUrl: string;
previewUrl: string; previewUrl: string;
originalUrl: string;
videoUrl?: string; videoUrl?: string;
exifUrl: string; exifUrl: string;
blurDataURL?: string; blurDataURL?: string;

View File

@@ -10,13 +10,13 @@
* with back-link to the subpage * with back-link to the subpage
*/ */
import Link from 'next/link';
import Image from 'next/image';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { immich, type ImmichAsset } from '@/lib/immich'; import { immich, type ImmichAsset } from '@/lib/immich';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { PhotoGrid, type PhotoItem } from './PhotoGrid'; // Only the type: rendering moved to AlbumDetailView/SubpageGridView, which
// import the component themselves.
import type { PhotoItem } from './PhotoGrid';
import { import {
imageUrl, imageUrl,
exifUrl, exifUrl,
@@ -29,7 +29,6 @@ import { encodeAssetId } from '@/lib/tokens';
import { getConfig, type GridConfig } from '@/lib/config'; import { getConfig, type GridConfig } from '@/lib/config';
import { isProtected, isAuthenticated } from '@/lib/auth'; import { isProtected, isAuthenticated } from '@/lib/auth';
import PasswordGate from '@/components/PasswordGate'; import PasswordGate from '@/components/PasswordGate';
import { BackLink } from '@/components/BackLink';
import { AlbumDetailView } from './AlbumDetailView'; import { AlbumDetailView } from './AlbumDetailView';
import { SubpageGridView } from './SubpageGridView'; import { SubpageGridView } from './SubpageGridView';
@@ -103,7 +102,6 @@ function toPhotoItems(assets: ImmichAsset[], showExif: boolean): PhotoItem[] {
type: isVideo ? 'video' : 'image', type: isVideo ? 'video' : 'image',
thumbUrl: imageUrl(a.id, 'preview'), thumbUrl: imageUrl(a.id, 'preview'),
previewUrl: imageUrl(a.id, 'preview'), previewUrl: imageUrl(a.id, 'preview'),
originalUrl: imageUrl(a.id, 'original'),
...(isVideo ? { videoUrl: videoUrl(a.id) } : {}), ...(isVideo ? { videoUrl: videoUrl(a.id) } : {}),
exifUrl: exifUrl(a.id), exifUrl: exifUrl(a.id),
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}), ...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),

View File

@@ -8,7 +8,7 @@ export const metadata: Metadata = {
/** /**
* Required for the CSP nonce. The admin page is a pure client component, so * Required for the CSP nonce. The admin page is a pure client component, so
* Next.js would statically prerender it at build time — and a prerendered HTML * Next.js would statically prerender it at build time — and a prerendered HTML
* file cannot carry the per-request nonce that middleware.ts issues. Since the * file cannot carry the per-request nonce that proxy.ts issues. Since the
* CSP uses 'strict-dynamic' (which makes 'self' inert), unnonced script tags * CSP uses 'strict-dynamic' (which makes 'self' inert), unnonced script tags
* are blocked and the panel never hydrates. Rendering per request lets Next.js * are blocked and the panel never hydrates. Rendering per request lets Next.js
* stamp the nonce onto the script tags it emits. * stamp the nonce onto the script tags it emits.

View File

@@ -7,7 +7,7 @@ import {
COOKIE_NAME, COOKIE_NAME,
SESSION_DURATION_MS, SESSION_DURATION_MS,
} from '@/lib/admin/auth'; } from '@/lib/admin/auth';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
/** Admin login attempts per minute per IP — the highest-value credential in the app. */ /** Admin login attempts per minute per IP — the highest-value credential in the app. */
const ADMIN_AUTH_RPM = 5; const ADMIN_AUTH_RPM = 5;
@@ -21,7 +21,7 @@ export async function POST(request: NextRequest) {
{ error: 'Too many requests' }, { error: 'Too many requests' },
{ {
status: 429, status: 429,
headers: { 'Retry-After': String(Math.ceil((rl.resetAt - Date.now()) / 1000)) }, headers: { 'Retry-After': String(retryAfterSeconds(rl.resetAt)) },
}, },
); );
} }

View File

@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache'; import { revalidatePath } from 'next/cache';
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth'; import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
import { readGalleryYaml, writeGalleryYaml } from '@/lib/admin/yaml-service'; import { readGalleryYaml, writeGalleryYaml } from '@/lib/admin/yaml-service';
import { invalidateConfigCache } from '@/lib/config'; import { invalidateConfigCache, deriveGallery } from '@/lib/config';
import { immich } from '@/lib/immich'; import { immich } from '@/lib/immich';
import type { GalleryYaml } from '@/lib/config/schema'; import type { GalleryYaml } from '@/lib/config/schema';
@@ -39,13 +39,34 @@ export async function PUT(request: Request) {
return NextResponse.json({ error: 'Invalid hero format' }, { status: 400 }); return NextResponse.json({ error: 'Invalid hero format' }, { status: 400 });
} }
// Run the *real* derivation before writing. getConfig() throws on a gallery
// with no albums and no subpages, a subpage with no name, or a subpage with
// neither albums nor sections — all of which the page builder can produce.
// Writing one used to report "Saved successfully" and then take the public
// site down until someone noticed.
//
// Calling deriveGallery rather than re-checking those conditions here is
// deliberate: a second copy of the rules would drift from the first. So is
// validating before the write rather than rolling back after — a rollback
// leaves a window in which other requests read the broken config.
try {
deriveGallery(gallery);
} catch (err) {
const reason = err instanceof Error ? err.message : 'Invalid gallery structure';
console.warn('[Admin] Rejected an unloadable gallery.yaml:', reason);
return NextResponse.json({ error: reason }, { status: 400 });
}
try { try {
await writeGalleryYaml(gallery); await writeGalleryYaml(gallery);
invalidateConfigCache(); invalidateConfigCache();
immich.invalidateAll(); immich.invalidateAll();
// Revalidate all pages so the homepage picks up new hero images immediately // Revalidate all pages so the homepage picks up new hero images immediately
revalidatePath('/', 'layout'); revalidatePath('/', 'layout');
return NextResponse.json({ success: true, message: 'Saved successfully. Backup of previous version created.' }); return NextResponse.json({
success: true,
message: 'Saved successfully. Backup of previous version created.',
});
} catch (err) { } catch (err) {
console.error('[Admin] Failed to write gallery.yaml:', err); console.error('[Admin] Failed to write gallery.yaml:', err);
return NextResponse.json({ error: 'Failed to save gallery config' }, { status: 500 }); return NextResponse.json({ error: 'Failed to save gallery config' }, { status: 500 });

View File

@@ -5,7 +5,7 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { authenticate, isProtected } from '@/lib/auth'; import { authenticate, isProtected } from '@/lib/auth';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
/** Tight limit for auth attempts — 10 per minute per IP. */ /** Tight limit for auth attempts — 10 per minute per IP. */
const AUTH_RPM = 10; const AUTH_RPM = 10;
@@ -21,7 +21,7 @@ export async function POST(request: NextRequest) {
{ {
status: 429, status: 429,
headers: { headers: {
'Retry-After': String(Math.ceil((resetAt - Date.now()) / 1000)), 'Retry-After': String(retryAfterSeconds(resetAt)),
'X-RateLimit-Limit': String(AUTH_RPM), 'X-RateLimit-Limit': String(AUTH_RPM),
'X-RateLimit-Remaining': String(remaining), 'X-RateLimit-Remaining': String(remaining),
}, },
@@ -59,7 +59,7 @@ export async function POST(request: NextRequest) {
); );
} }
const setCookie = authenticate(slug, password, type); const setCookie = await authenticate(slug, password, type);
if (!setCookie) { if (!setCookie) {
return NextResponse.json({ error: 'Invalid password' }, { status: 401 }); return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
} }

View File

@@ -6,10 +6,10 @@
*/ */
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { immich } from '@/lib/immich'; import { immich, ImmichUnavailableError } from '@/lib/immich';
import { decodeAssetId } from '@/lib/tokens'; import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const config = getConfig(); const config = getConfig();
@@ -24,9 +24,15 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
const { success, resetAt } = checkRateLimit(`exif:${ip}`, config.rateLimitRpm); const { success, resetAt } = checkRateLimit(`exif:${ip}`, config.rateLimitRpm);
if (!success) { if (!success) {
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000); const retryAfter = retryAfterSeconds(resetAt);
console.warn(`[EXIF API] ⚠️ Rate limit exceeded for IP: ${ip}. Retry after ${retryAfter}s`); console.warn(`[EXIF API] ⚠️ Rate limit exceeded for IP: ${ip}. Retry after ${retryAfter}s`);
return NextResponse.json({ error: 'Too many requests' }, { status: 429 }); return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { 'Retry-After': String(retryAfter), 'Cache-Control': 'no-store' },
},
);
} }
const { id: token } = await params; const { id: token } = await params;
@@ -37,7 +43,22 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json({ error: 'Invalid token' }, { status: 400 }); return NextResponse.json({ error: 'Invalid token' }, { status: 400 });
} }
const asset = await immich.getAssetInfo(assetId); let asset;
try {
asset = await immich.getAssetInfo(assetId);
} catch (error) {
// Immich is down, not "this asset has no EXIF" — say so, so the lightbox
// can retry rather than caching a 404 for a photo that does have data.
if (error instanceof ImmichUnavailableError) {
console.error(`[EXIF API] Immich unavailable for ${assetId}:`, error.message);
return NextResponse.json(
{ error: 'Immich is currently unavailable' },
{ status: 503, headers: { 'Retry-After': '30', 'Cache-Control': 'no-store' } },
);
}
throw error;
}
if (!asset?.exifInfo) { if (!asset?.exifInfo) {
return NextResponse.json({ error: 'No EXIF data' }, { status: 404 }); return NextResponse.json({ error: 'No EXIF data' }, { status: 404 });
} }

View File

@@ -7,7 +7,7 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { immich } from '@/lib/immich'; import { immich } from '@/lib/immich';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
const startTime = Date.now(); const startTime = Date.now();
@@ -30,7 +30,7 @@ export async function GET(request: NextRequest) {
{ {
status: 429, status: 429,
headers: { headers: {
'Retry-After': String(Math.ceil((resetAt - Date.now()) / 1000)), 'Retry-After': String(retryAfterSeconds(resetAt)),
'X-RateLimit-Limit': String(rateLimitRpm), 'X-RateLimit-Limit': String(rateLimitRpm),
'X-RateLimit-Remaining': String(remaining), 'X-RateLimit-Remaining': String(remaining),
}, },

View File

@@ -8,21 +8,11 @@
*/ */
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { immich, ImageSize } from '@/lib/immich'; import { immich, ImmichUnavailableError } from '@/lib/immich';
import { resolveImageSize } from '@/lib/imageSize';
import { decodeAssetId } from '@/lib/tokens'; import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
const VALID_SIZES: ImageSize[] = ['thumbnail', 'preview', 'original'];
/**
* Map a requested pixel width to the best Immich size tier.
*/
function widthToSize(w: number): ImageSize {
if (w <= 250) return 'thumbnail';
if (w <= 1440) return 'preview';
return 'original';
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
// ── Rate limiting ────────────────────────────────── // ── Rate limiting ──────────────────────────────────
@@ -30,12 +20,22 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
const { success, remaining, resetAt } = checkRateLimit(`image:${ip}`, getConfig().rateLimitRpm); const { success, remaining, resetAt } = checkRateLimit(`image:${ip}`, getConfig().rateLimitRpm);
if (!success) { if (!success) {
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000); const retryAfter = retryAfterSeconds(resetAt);
const userAgent = request.headers.get('user-agent') || 'unknown'; const userAgent = request.headers.get('user-agent') || 'unknown';
console.warn( console.warn(
`[Image API] ⚠️ Rate limit exceeded for IP: ${ip} (UA: ${userAgent}). Retry after ${retryAfter}s`, `[Image API] ⚠️ Rate limit exceeded for IP: ${ip} (UA: ${userAgent}). Retry after ${retryAfter}s`,
); );
return NextResponse.json({ error: 'Too many requests' }, { status: 429 }); // Without Retry-After the browser and next/image back off on their own
// schedule — a retry storm against a server that just said it was
// overloaded, and one page issues ~50 of these requests. no-store because
// the success path serves this URL as `immutable`.
return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { 'Retry-After': String(retryAfter), 'Cache-Control': 'no-store' },
},
);
} }
const { id: token } = await params; const { id: token } = await params;
@@ -47,23 +47,19 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json({ error: 'Invalid token' }, { status: 400 }); return NextResponse.json({ error: 'Invalid token' }, { status: 400 });
} }
// Determine size: prefer explicit ?size=, then infer from ?w= const size = resolveImageSize(
const sizeParam = request.nextUrl.searchParams.get('size'); request.nextUrl.searchParams.get('size'),
const widthParam = request.nextUrl.searchParams.get('w'); request.nextUrl.searchParams.get('w'),
);
let size: ImageSize = 'preview';
if (sizeParam && VALID_SIZES.includes(sizeParam as ImageSize)) {
size = sizeParam as ImageSize;
} else if (widthParam) {
const w = parseInt(widthParam, 10);
if (!isNaN(w) && w > 0) {
size = widthToSize(w);
}
}
// ── Browser Cache Optimization ───────────────────── // ── Browser Cache Optimization ─────────────────────
// Use the opaque token to generate a safe ETag without leaking Immich UUIDs // Use the opaque token to generate a safe ETag without leaking Immich UUIDs.
const etag = `W/"${token}-${size}"`; // IMAGE_CACHE_VERSION participates so that a bump is not defeated by a client
// replaying the old ETag against the new URL — the response is served
// `immutable`, so this only matters after expiry or a cache eviction, but a
// matching ETag across two different URLs would be wrong either way.
const cacheVersion = request.nextUrl.searchParams.get('v') ?? '';
const etag = `W/"${token}-${size}${cacheVersion ? `-${cacheVersion}` : ''}"`;
if (request.headers.get('if-none-match') === etag) { if (request.headers.get('if-none-match') === etag) {
return new NextResponse(null, { return new NextResponse(null, {
status: 304, status: 304,
@@ -75,10 +71,29 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
}); });
} }
const result = await immich.streamAsset(assetId, size); let result;
try {
result = await immich.streamAsset(assetId, size);
} catch (error) {
// An outage must not look like a deleted photo. These URLs are served with
// `immutable` on success, and a bare 404 is heuristically cacheable — so
// without no-store the browser can pin a broken image for the whole session.
if (error instanceof ImmichUnavailableError) {
console.error(`[Image API] Immich unavailable for ${assetId}:`, error.message);
return NextResponse.json(
{ error: 'Immich is currently unavailable' },
{ status: 503, headers: { 'Retry-After': '30', 'Cache-Control': 'no-store' } },
);
}
throw error;
}
if (!result) { if (!result) {
console.error(`[Image API] ❌ Asset not found in Immich: ${assetId} (Size: ${size})`); console.error(`[Image API] ❌ Asset not found in Immich: ${assetId} (Size: ${size})`);
return NextResponse.json({ error: 'Asset not found' }, { status: 404 }); return NextResponse.json(
{ error: 'Asset not found' },
{ status: 404, headers: { 'Cache-Control': 'no-store' } },
);
} }
let contentType = result.contentType.toLowerCase(); let contentType = result.contentType.toLowerCase();

View File

@@ -10,7 +10,8 @@ import { getConfig } from '@/lib/config';
import { imageUrl } from '@/lib/urls'; import { imageUrl } from '@/lib/urls';
import { isAuthenticated } from '@/lib/auth'; import { isAuthenticated } from '@/lib/auth';
import { getMapData } from '@/lib/mapService'; import { getMapData } from '@/lib/mapService';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { ImmichUnavailableError } from '@/lib/immich';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -26,7 +27,7 @@ export async function GET(request: NextRequest) {
{ {
status: 429, status: 429,
headers: { headers: {
'Retry-After': String(Math.ceil((rl.resetAt - Date.now()) / 1000)), 'Retry-After': String(retryAfterSeconds(rl.resetAt)),
'X-RateLimit-Limit': '120', 'X-RateLimit-Limit': '120',
'X-RateLimit-Remaining': '0', 'X-RateLimit-Remaining': '0',
}, },
@@ -43,7 +44,21 @@ export async function GET(request: NextRequest) {
const cookieStore = await cookies(); const cookieStore = await cookies();
const getCookie = (name: string) => cookieStore.get(name)?.value; const getCookie = (name: string) => cookieStore.get(name)?.value;
const locations = await getMapData(); let locations;
try {
locations = await getMapData();
} catch (error) {
// Without this the map would render as "no photos anywhere" during an
// Immich outage, which is indistinguishable from a gallery with no GPS data.
if (error instanceof ImmichUnavailableError) {
console.error('[Map API] Immich unavailable:', error.message);
return NextResponse.json(
{ error: 'Immich is currently unavailable' },
{ status: 503, headers: { 'Retry-After': '30', 'Cache-Control': 'no-store' } },
);
}
throw error;
}
// Filter locations and albums based on auth. // Filter locations and albums based on auth.
// An album is visible only if BOTH its subpage gate (if any) and its own // An album is visible only if BOTH its subpage gate (if any) and its own

View File

@@ -9,7 +9,7 @@
import { ImageResponse } from 'next/og'; import { ImageResponse } from 'next/og';
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
/** /**
* OG image rendering runs satori + resvg per request and each unique ?title * OG image rendering runs satori + resvg per request and each unique ?title
@@ -23,9 +23,15 @@ export async function GET(request: NextRequest) {
const ip = getClientIp(request); const ip = getClientIp(request);
const { theme } = getConfig(); const { theme } = getConfig();
const { success } = checkRateLimit(`og:${ip}`, OG_RPM); const { success, resetAt } = checkRateLimit(`og:${ip}`, OG_RPM);
if (!success) { if (!success) {
return new NextResponse('Too many requests', { status: 429 }); return new NextResponse('Too many requests', {
status: 429,
headers: {
'Retry-After': String(retryAfterSeconds(resetAt)),
'Cache-Control': 'no-store',
},
});
} }
const { searchParams } = request.nextUrl; const { searchParams } = request.nextUrl;

View File

@@ -10,10 +10,10 @@
*/ */
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { immich } from '@/lib/immich'; import { immich, ImmichUnavailableError } from '@/lib/immich';
import { decodeAssetId } from '@/lib/tokens'; import { decodeAssetId } from '@/lib/tokens';
import { getConfig } from '@/lib/config'; import { getConfig } from '@/lib/config';
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
// ── Rate limiting ────────────────────────────────── // ── Rate limiting ──────────────────────────────────
@@ -21,9 +21,15 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
const { success, remaining, resetAt } = checkRateLimit(`video:${ip}`, getConfig().rateLimitRpm); const { success, remaining, resetAt } = checkRateLimit(`video:${ip}`, getConfig().rateLimitRpm);
if (!success) { if (!success) {
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000); const retryAfter = retryAfterSeconds(resetAt);
console.warn(`[Video API] ⚠️ Rate limit exceeded for IP: ${ip}. Retry after ${retryAfter}s`); console.warn(`[Video API] ⚠️ Rate limit exceeded for IP: ${ip}. Retry after ${retryAfter}s`);
return NextResponse.json({ error: 'Too many requests' }, { status: 429 }); return NextResponse.json(
{ error: 'Too many requests' },
{
status: 429,
headers: { 'Retry-After': String(retryAfter), 'Cache-Control': 'no-store' },
},
);
} }
const { id: token } = await params; const { id: token } = await params;
@@ -38,10 +44,28 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
// Forward Range header from browser (needed for <video> seeking) // Forward Range header from browser (needed for <video> seeking)
const rangeHeader = request.headers.get('range'); const rangeHeader = request.headers.get('range');
const result = await immich.streamVideo(assetId, rangeHeader); let result;
try {
result = await immich.streamVideo(assetId, rangeHeader);
} catch (error) {
// Same reasoning as the image route: an outage mid-playback must not be
// cached as a permanently missing video.
if (error instanceof ImmichUnavailableError) {
console.error(`[Video API] Immich unavailable for ${assetId}:`, error.message);
return NextResponse.json(
{ error: 'Immich is currently unavailable' },
{ status: 503, headers: { 'Retry-After': '30', 'Cache-Control': 'no-store' } },
);
}
throw error;
}
if (!result) { if (!result) {
console.error(`[Video API] ❌ Asset not found in Immich: ${assetId}`); console.error(`[Video API] ❌ Asset not found in Immich: ${assetId}`);
return NextResponse.json({ error: 'Asset not found' }, { status: 404 }); return NextResponse.json(
{ error: 'Asset not found' },
{ status: 404, headers: { 'Cache-Control': 'no-store' } },
);
} }
let contentType = result.contentType.toLowerCase(); let contentType = result.contentType.toLowerCase();

53
app/error.tsx Normal file
View File

@@ -0,0 +1,53 @@
'use client';
import { useEffect } from 'react';
import Link from 'next/link';
/**
* Rendered when a page throws — in practice almost always
* ImmichUnavailableError, since that is what the Immich client raises when the
* server cannot answer.
*
* The wording deliberately does not name Immich or claim to know the cause.
* Next.js strips error messages in production builds and replaces them with a
* digest, so this component genuinely cannot tell an Immich outage from any
* other server error — asserting one would be a guess shown to visitors. The
* distinction that matters is already made structurally: notFound() renders
* not-found.tsx, a throw renders this.
*/
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error('[Folio] Page render failed:', error);
}, [error]);
return (
<div className="empty-state">
<h1 className="empty-state__title">Something went wrong</h1>
<p className="empty-state__text">
This page could not be loaded right now. It is usually temporary — try again in a moment.
</p>
<div className="empty-state__actions">
<button type="button" onClick={reset} className="empty-state__button">
Try again
</button>
<Link href="/" className="empty-state__button empty-state__button--quiet">
Back to the gallery
</Link>
</div>
{error.digest && (
<p
className="empty-state__text"
style={{ marginTop: 24, fontSize: '0.8rem', opacity: 0.5 }}
>
Reference: {error.digest}
</p>
)}
</div>
);
}

View File

@@ -1289,6 +1289,55 @@
font-weight: 300; font-weight: 300;
} }
.empty-state__title {
font-family: var(--font-serif);
font-size: clamp(1.75rem, 4vw, 2.5rem);
font-weight: 400;
letter-spacing: -0.02em;
margin-bottom: 12px;
color: var(--text-primary);
}
.empty-state__actions {
display: flex;
gap: 12px;
justify-content: center;
flex-wrap: wrap;
margin-top: 32px;
}
/* Matches the PasswordGate button, the only other action button in the app. */
.empty-state__button {
padding: 12px 24px;
background: var(--accent);
color: var(--bg-primary);
border: none;
border-radius: var(--radius-md);
font-family: var(--font-sans);
font-size: 0.85rem;
font-weight: 500;
letter-spacing: 0.05em;
cursor: pointer;
text-decoration: none;
transition: opacity var(--transition-fast);
}
.empty-state__button:hover {
opacity: 0.9;
}
.empty-state__button--quiet {
background: transparent;
color: var(--text-secondary);
border: 1px solid var(--border-subtle);
}
.empty-state__button--quiet:hover {
color: var(--text-primary);
border-color: var(--border-hover);
opacity: 1;
}
/* ── Theme Conditionals ──────────────────────────── */ /* ── Theme Conditionals ──────────────────────────── */
/* Features toggled via data attributes on <html>, set by theme config */ /* Features toggled via data attributes on <html>, set by theme config */

View File

@@ -13,13 +13,18 @@ import { ThemeToggle } from '@/components/ThemeToggle';
import { ScrollToTop } from '@/components/ScrollToTop'; import { ScrollToTop } from '@/components/ScrollToTop';
import { Footer } from '@/components/Footer'; import { Footer } from '@/components/Footer';
import { SetupScreen } from '@/components/SetupScreen'; import { SetupScreen } from '@/components/SetupScreen';
import { getConfig, getGoogleFontsUrl, AppConfig } from '@/lib/config'; import { getConfigOrNull, getGoogleFontsUrl, AppConfig } from '@/lib/config';
import { isAdminPath } from '@/lib/admin/paths'; import { isAdminPath } from '@/lib/admin/paths';
// 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';
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata(): Promise<Metadata> {
const config = getConfig(); const config = getConfigOrNull();
if (!config) {
// Nothing to describe, and nothing that should be indexed while broken.
return { title: 'Setup Required', robots: { index: false, follow: false } };
}
const siteTitle = config.seo.title; const siteTitle = config.seo.title;
const siteDescription = config.seo.description; const siteDescription = config.seo.description;
const robots = { const robots = {
@@ -50,7 +55,22 @@ export async function generateMetadata(): Promise<Metadata> {
} }
export default async function RootLayout({ children }: { children: React.ReactNode }) { export default async function RootLayout({ children }: { children: React.ReactNode }) {
const config = getConfig(); const config = getConfigOrNull();
const pathname = (await headers()).get('x-pathname');
// gallery.yaml exists but cannot be derived — an empty gallery, a nameless
// subpage, a subpage with no albums. The admin page builder can write all
// three, and this layout is what /admin renders inside, so throwing here
// would take down the only tool that can undo the save. Render the minimum
// that keeps /admin usable and show everyone else the setup screen.
if (!config) {
return (
<html lang="en" suppressHydrationWarning>
<body>{isAdminPath(pathname) ? children : <SetupScreen />}</body>
</html>
);
}
const { theme } = config; const { theme } = config;
const fontsUrl = getGoogleFontsUrl(theme); const fontsUrl = getGoogleFontsUrl(theme);
@@ -67,7 +87,6 @@ export default async function RootLayout({ children }: { children: React.ReactNo
// /admin stays reachable during setup — it is the tool that completes the // /admin stays reachable during setup — it is the tool that completes the
// setup, so the setup screen must not lock it out (#326). // setup, so the setup screen must not lock it out (#326).
const pathname = (await headers()).get('x-pathname');
if ((config as AppConfig & { needsSetup?: boolean }).needsSetup && !isAdminPath(pathname)) { if ((config as AppConfig & { needsSetup?: boolean }).needsSetup && !isAdminPath(pathname)) {
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>

26
app/not-found.tsx Normal file
View File

@@ -0,0 +1,26 @@
import Link from 'next/link';
/**
* Rendered when a page calls notFound() — i.e. Immich answered and the album
* or asset genuinely does not exist.
*
* The counterpart is error.tsx, which handles the case where Immich could not
* answer at all. Keeping the two apart is the whole point of the
* ImmichUnavailableError split: an outage must not tell a visitor (or a
* crawler) that their content is gone.
*/
export default function NotFound() {
return (
<div className="empty-state">
<h1 className="empty-state__title">Not found</h1>
<p className="empty-state__text">
This page does not exist, or the album is no longer published.
</p>
<div className="empty-state__actions">
<Link href="/" className="empty-state__button">
Back to the gallery
</Link>
</div>
</div>
);
}

View File

@@ -1,4 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest'; import { describe, it, expect, vi, afterEach } from 'vitest';
import crypto from 'crypto';
// Mock config to provide a predictable API key and subpage config // Mock config to provide a predictable API key and subpage config
vi.mock('@/lib/config', () => ({ vi.mock('@/lib/config', () => ({
@@ -18,6 +19,15 @@ vi.mock('@/lib/config', () => ({
albumIds: ['00000000-0000-0000-0000-000000000002'], albumIds: ['00000000-0000-0000-0000-000000000002'],
// no password // no password
}, },
{
name: 'Hashed',
slug: 'hashed',
albumIds: ['00000000-0000-0000-0000-000000000003'],
// scrypt hash of 'scrypted-pass' with a fixed salt — exercises the
// verifyScrypt path rather than the deprecated plaintext fallback.
password:
'scrypt:0123456789abcdef0123456789abcdef:4850eef18a09612ef11fdcd943bf64ce98d0eca2b0f677f9c0c51d1f648b8a101cf7ea36b6f94cfc05236b2fda6fffabd0929dc7e14c07626522fba68bf26de5',
},
], ],
}), }),
})); }));
@@ -51,27 +61,64 @@ describe('isProtected', () => {
}); });
describe('authenticate', () => { describe('authenticate', () => {
it('returns a Set-Cookie string for the correct password', () => { it('returns a Set-Cookie string for the correct password', async () => {
const cookie = authenticate('private', 'secret123'); const cookie = await authenticate('private', 'secret123');
expect(cookie).toBeTruthy(); expect(cookie).toBeTruthy();
expect(cookie).toContain('lb_auth_private='); expect(cookie).toContain('lb_auth_private=');
expect(cookie).toContain('HttpOnly'); expect(cookie).toContain('HttpOnly');
expect(cookie).toContain('SameSite=Strict'); expect(cookie).toContain('SameSite=Strict');
}); });
it('returns null for the wrong password', () => { it('returns null for the wrong password', async () => {
expect(authenticate('private', 'wrongpass')).toBeNull(); await expect(authenticate('private', 'wrongpass')).resolves.toBeNull();
}); });
it('returns null for a non-protected slug', () => { it('returns null for a non-protected slug', async () => {
expect(authenticate('public', 'anything')).toBeNull(); await expect(authenticate('public', 'anything')).resolves.toBeNull();
});
it('accepts a correct scrypt-hashed password', async () => {
await expect(authenticate('hashed', 'scrypted-pass')).resolves.toContain('lb_auth_hashed=');
});
it('rejects a wrong password against a scrypt hash', async () => {
await expect(authenticate('hashed', 'wrong')).resolves.toBeNull();
});
});
/**
* scryptSync costs ~23ms of blocked main thread per call. The /api/auth limit
* is keyed on the client IP, and at the default TRUSTED_PROXY_HOPS=0 that IP
* comes from a spoofable header — so unlimited buckets, each buying 23ms of
* dead process. The async variant runs on the libuv threadpool instead.
*/
describe('password hashing does not stall the process', () => {
it('never calls the synchronous scrypt', async () => {
const sync = vi.spyOn(crypto, 'scryptSync');
await authenticate('hashed', 'scrypted-pass');
expect(sync).not.toHaveBeenCalled();
sync.mockRestore();
});
it('leaves timers free to fire while hashing', async () => {
let ticks = 0;
const interval = setInterval(() => ticks++, 2);
await authenticate('hashed', 'scrypted-pass');
clearInterval(interval);
// The synchronous variant yields to nothing for the whole hash, so a 2ms
// interval gets at most one tick after it finishes. Async leaves room for
// many. A slower machine makes the hash longer, i.e. more ticks — so this
// fails on a blocked loop, not on a busy one.
expect(ticks).toBeGreaterThan(3);
}); });
}); });
describe('isAuthenticated', () => { describe('isAuthenticated', () => {
it('returns true when a valid cookie is present', () => { it('returns true when a valid cookie is present', async () => {
// First authenticate to get the expected token // First authenticate to get the expected token
const cookie = authenticate('private', 'secret123')!; const cookie = (await authenticate('private', 'secret123'))!;
const token = cookie.split('=')[1].split(';')[0]; const token = cookie.split('=')[1].split(';')[0];
const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined); const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined);
@@ -95,16 +142,16 @@ describe('isAuthenticated', () => {
}); });
describe('token expiry', () => { describe('token expiry', () => {
function tokenFor(slug: string, password: string): string { async function tokenFor(slug: string, password: string): Promise<string> {
return authenticate(slug, password)!.split('=')[1].split(';')[0]; return (await authenticate(slug, password))!.split('=')[1].split(';')[0];
} }
afterEach(() => { afterEach(() => {
vi.useRealTimers(); vi.useRealTimers();
}); });
it('rejects a token once its embedded expiry has passed', () => { it('rejects a token once its embedded expiry has passed', async () => {
const token = tokenFor('private', 'secret123'); const token = await tokenFor('private', 'secret123');
const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined); const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined);
expect(isAuthenticated('private', getCookie)).toBe(true); expect(isAuthenticated('private', getCookie)).toBe(true);
@@ -115,8 +162,8 @@ describe('token expiry', () => {
expect(isAuthenticated('private', getCookie)).toBe(false); expect(isAuthenticated('private', getCookie)).toBe(false);
}); });
it('still accepts a token just before it expires', () => { it('still accepts a token just before it expires', async () => {
const token = tokenFor('private', 'secret123'); const token = await tokenFor('private', 'secret123');
const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined); const getCookie = (name: string) => (name === 'lb_auth_private' ? token : undefined);
vi.useFakeTimers(); vi.useFakeTimers();
@@ -124,8 +171,8 @@ describe('token expiry', () => {
expect(isAuthenticated('private', getCookie)).toBe(true); expect(isAuthenticated('private', getCookie)).toBe(true);
}); });
it('rejects a token whose expiry was tampered with', () => { it('rejects a token whose expiry was tampered with', async () => {
const token = tokenFor('private', 'secret123'); const token = await tokenFor('private', 'secret123');
const [, sig] = token.split('.'); const [, sig] = token.split('.');
const farFuture = Date.now() + 365 * 24 * 60 * 60 * 1000; const farFuture = Date.now() + 365 * 24 * 60 * 60 * 1000;
@@ -143,8 +190,8 @@ describe('token expiry', () => {
} }
}); });
it('sets a cookie Max-Age consistent with the embedded expiry', () => { it('sets a cookie Max-Age consistent with the embedded expiry', async () => {
const cookie = authenticate('private', 'secret123')!; const cookie = (await authenticate('private', 'secret123'))!;
const maxAge = Number(cookie.match(/Max-Age=(\d+)/)![1]); const maxAge = Number(cookie.match(/Max-Age=(\d+)/)![1]);
const exp = Number(cookie.split('=')[1].split(';')[0].split('.')[0]); const exp = Number(cookie.split('=')[1].split(';')[0].split('.')[0]);
expect(Math.abs(exp - (Date.now() + maxAge * 1000))).toBeLessThan(2000); expect(Math.abs(exp - (Date.now() + maxAge * 1000))).toBeLessThan(2000);

View File

@@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('fs/promises', () => ({
default: {
copyFile: vi.fn(async () => undefined),
readFile: vi.fn(),
writeFile: vi.fn(),
rename: vi.fn(),
mkdir: vi.fn(),
access: vi.fn(),
readdir: vi.fn(async () => []),
unlink: vi.fn(),
},
}));
import fs from 'fs/promises';
import { restoreBackup } from '@/lib/admin/yaml-service';
/**
* restoreBackup joins its argument into a path and copies the result over a
* content file, whose contents the admin GET endpoints then return. Before this
* guard, `path.join` resolved `..` segments, so any readable file on the host
* could be written over content/settings.yaml and read back.
*
* The function has no callers yet — this pins the guard for whoever wires up the
* restore button the admin panel does not have.
*/
describe('restoreBackup rejects anything that is not a backup it produced', () => {
beforeEach(() => vi.clearAllMocks());
const rejected = [
'../../../../etc/passwd',
'../gallery.yaml',
'.backups/../../gallery.yaml',
'/etc/passwd',
'gallery.yaml', // the live file, not a backup
'gallery.yaml.2026-05-31T17-30-00-000Z.bak.txt',
'evil-gallery.yaml.2026-05-31T17-30-00-000Z.bak',
'',
];
for (const name of rejected) {
it(`refuses ${JSON.stringify(name)}`, async () => {
await expect(restoreBackup(name)).rejects.toThrow(/unrecognised backup name/i);
expect(fs.copyFile).not.toHaveBeenCalled();
});
}
// A traversal that still ended in a plausible-looking name would have picked
// the destination too, via the old includes('gallery.yaml') check.
it('refuses a traversal that embeds a valid-looking name', async () => {
await expect(restoreBackup('../../gallery.yaml.2026-01-01T00-00-00-000Z.bak')).rejects.toThrow(
/unrecognised backup name/i,
);
expect(fs.copyFile).not.toHaveBeenCalled();
});
});
describe('restoreBackup accepts the names it writes', () => {
beforeEach(() => vi.clearAllMocks());
it('restores a normal backup', async () => {
await expect(
restoreBackup('gallery.yaml.2026-05-31T17-30-00-000Z.bak'),
).resolves.toBeUndefined();
expect(fs.copyFile).toHaveBeenCalled();
});
it('restores a pre-restore backup', async () => {
await expect(
restoreBackup('settings.yaml.2026-05-31T17-30-00-000Z.pre-restore.bak'),
).resolves.toBeUndefined();
});
it('derives the destination from the matched name, not a substring search', async () => {
await restoreBackup('settings.yaml.2026-05-31T17-30-00-000Z.bak');
// Last copyFile is backup → target; the first is the pre-restore snapshot.
const calls = vi.mocked(fs.copyFile).mock.calls;
expect(String(calls[calls.length - 1][1])).toMatch(/content\/settings\.yaml$/);
});
});

View File

@@ -0,0 +1,93 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@/lib/env', () => ({
env: {
IMMICH_API_URL: 'http://localhost:2283',
IMMICH_API_KEY: 'test-key',
SITE_TITLE: 'Test Gallery',
SITE_SUBTITLE: '',
CACHE_TTL: 300,
IMMICH_TIMEOUT_MS: 15000,
RATE_LIMIT_RPM: 120,
TRUSTED_PROXY_HOPS: 0,
},
}));
vi.mock('@/lib/secret', () => ({
resolveAuthSecret: () => 'test-auth-secret-32-chars-long-min',
}));
// Spy on validateUuid so we can assert *which* values are routed through it.
// vi.hoisted because vi.mock factories are hoisted above const declarations.
// Two-arg signature, matching the real validateUuid(id, context) — the context
// argument is what the second assertion below inspects.
const { validateUuidSpy } = vi.hoisted(() => ({
validateUuidSpy: vi.fn((id: string, _context: string) => id),
}));
vi.mock('@/lib/config/parser', () => ({
loadYaml: vi.fn(),
clearYamlCache: vi.fn(),
validateUuid: validateUuidSpy,
}));
import { getConfig, invalidateConfigCache } from '@/lib/config';
import { loadYaml } from '@/lib/config/parser';
const ALBUM_ID = '11111111-1111-1111-1111-111111111111';
const HERO_ID = '22222222-2222-2222-2222-222222222222';
/**
* Every asset ID in gallery.yaml is routed through validateUuid before it can
* reach encodeAssetId, which encrypts whatever it is handed. A per-album
* heroImage was the one that slipped through: the album ID (the map key) was
* validated, the hero asset ID (the value) was stored raw. A typo there
* produced a perfectly well-formed image URL that 404s forever, with nothing in
* the log naming the cause.
*/
describe('gallery.yaml per-album heroImage', () => {
beforeEach(() => {
validateUuidSpy.mockClear();
invalidateConfigCache();
vi.mocked(loadYaml).mockImplementation((filename: string) => {
if (filename === 'gallery.yaml') {
return { albums: [{ [ALBUM_ID]: { title: 'An Album', heroImage: HERO_ID } }] };
}
if (filename === 'settings.yaml') return {};
return null;
});
});
it('routes the hero asset ID through validateUuid, not just the album ID', () => {
getConfig();
const validated = validateUuidSpy.mock.calls.map((c) => c[0]);
expect(validated).toContain(HERO_ID);
});
it('names the album in the validation context so the warning is actionable', () => {
getConfig();
const heroCall = validateUuidSpy.mock.calls.find((c) => c[0] === HERO_ID);
expect(heroCall?.[1]).toContain(ALBUM_ID);
});
it('stores the validated value, keyed by album', () => {
expect(getConfig().albumHeroImages[ALBUM_ID]).toBe(HERO_ID);
});
// The substitution the wiring above depends on: validateUuid never throws, so
// a bad ID degrades to a 404 image rather than taking the whole page down.
it('real validateUuid warns and substitutes rather than throwing', async () => {
const actual =
await vi.importActual<typeof import('@/lib/config/parser')>('@/lib/config/parser');
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const result = actual.validateUuid('not-a-uuid', 'gallery.yaml heroImage');
expect(result).toBe('00000000-0000-0000-0000-000000000000');
expect(warn).toHaveBeenCalled();
expect(String(warn.mock.calls[0][0])).toContain('gallery.yaml heroImage');
warn.mockRestore();
});
});

View File

@@ -0,0 +1,116 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('@/lib/env', () => ({
env: {
IMMICH_API_URL: 'http://localhost:2283',
IMMICH_API_KEY: 'test-key',
SITE_TITLE: 'Test Gallery',
SITE_SUBTITLE: '',
CACHE_TTL: 300,
IMMICH_TIMEOUT_MS: 15000,
RATE_LIMIT_RPM: 120,
TRUSTED_PROXY_HOPS: 0,
},
}));
vi.mock('@/lib/secret', () => ({
resolveAuthSecret: () => 'test-auth-secret-32-chars-long-min',
}));
vi.mock('@/lib/config/parser', () => ({
loadYaml: vi.fn(),
clearYamlCache: vi.fn(),
validateUuid: (id: string) => id,
}));
import { getConfig, getConfigOrNull, invalidateConfigCache } from '@/lib/config';
import { loadYaml } from '@/lib/config/parser';
const ALBUM_ID = '11111111-1111-1111-1111-111111111111';
function withGallery(gallery: unknown) {
vi.mocked(loadYaml).mockImplementation((filename: string) => {
if (filename === 'gallery.yaml') return gallery;
if (filename === 'settings.yaml') return {};
return null;
});
}
/**
* 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
* the only tool that can undo the save.
*/
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 neither albums nor sections': {
albums: [ALBUM_ID],
subpages: [{ name: 'Empty', albums: [] }],
},
};
describe('getConfig() rejects an underivable gallery.yaml', () => {
beforeEach(() => invalidateConfigCache());
// Pins the premise the fix exists for. If these ever stop throwing, the
// fallback below is dead weight and should be revisited rather than kept.
for (const [label, gallery] of Object.entries(UNDERIVABLE)) {
it(`throws on ${label}`, () => {
withGallery(gallery);
expect(() => getConfig()).toThrow();
});
}
});
describe('getConfigOrNull()', () => {
let error: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
invalidateConfigCache();
error = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => error.mockRestore());
for (const [label, gallery] of Object.entries(UNDERIVABLE)) {
it(`returns null instead of throwing on ${label}`, () => {
withGallery(gallery);
expect(getConfigOrNull()).toBeNull();
});
}
it('logs the underlying error so the cause is diagnosable from the server log', () => {
withGallery({ albums: [] });
getConfigOrNull();
expect(error).toHaveBeenCalled();
expect(String(error.mock.calls[0][0])).toMatch(/gallery\.yaml/);
});
it('points at the backup directory, since that is the recovery path', () => {
withGallery({ albums: [] });
getConfigOrNull();
expect(String(error.mock.calls[0][0])).toContain('content/.backups/');
});
it('returns the real config untouched when the gallery is valid', () => {
withGallery({ albums: [ALBUM_ID] });
const config = getConfigOrNull();
expect(config).not.toBeNull();
expect(config?.albums).toEqual([ALBUM_ID]);
expect(error).not.toHaveBeenCalled();
});
it('does not swallow the needsSetup path, which is a different state', () => {
// Missing gallery.yaml is not an error — getConfig() returns a dummy config
// with needsSetup so the app can render SetupScreen. That must still work.
vi.mocked(loadYaml).mockReturnValue(null);
const config = getConfigOrNull();
expect(config).not.toBeNull();
expect(config?.needsSetup).toBe(true);
expect(error).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,106 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('@/lib/env', () => ({
env: {
IMMICH_API_URL: 'http://localhost:2283',
IMMICH_API_KEY: 'test-key',
SITE_TITLE: 'Test Gallery',
SITE_SUBTITLE: '',
CACHE_TTL: 300,
IMMICH_TIMEOUT_MS: 15000,
RATE_LIMIT_RPM: 120,
TRUSTED_PROXY_HOPS: 0,
},
}));
vi.mock('@/lib/config/parser', () => ({
loadYaml: vi.fn(),
clearYamlCache: vi.fn(),
validateUuid: (id: string) => id,
}));
import { deriveGallery } from '@/lib/config';
import type { GalleryYaml } from '@/lib/config/schema';
const A = '11111111-1111-1111-1111-111111111111';
const B = '22222222-2222-2222-2222-222222222222';
/**
* The admin PUT calls this before writing, so that a save the site cannot load
* is rejected with a 400 instead of reported as successful. These are the exact
* shapes the page builder can produce.
*/
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', () => {
expect(() =>
deriveGallery({ albums: [A], subpages: [{ albums: [A] }] } as unknown as GalleryYaml),
).toThrow(/must have a name/i);
});
it('rejects a subpage with neither albums nor sections', () => {
expect(() =>
deriveGallery({
albums: [A],
subpages: [{ name: 'Empty', albums: [] }],
} as unknown as GalleryYaml),
).toThrow(/Empty/);
});
// The message reaches the admin UI as the 400 body, so it has to identify
// which subpage is at fault — "invalid gallery" would be useless in a builder
// with a dozen subpages.
it('names the offending subpage so the error is actionable', () => {
expect(() =>
deriveGallery({
albums: [A],
subpages: [
{ name: 'Fine', albums: [A] },
{ name: 'Broken One', albums: [] },
],
} as unknown as GalleryYaml),
).toThrow(/Broken One/);
});
});
describe('deriveGallery accepts valid structures', () => {
it('derives standalone albums', () => {
const result = deriveGallery({ albums: [A, B] } as GalleryYaml);
expect(result.albums).toEqual([A, B]);
expect(result.standaloneAlbums).toEqual([A, B]);
expect(result.subpages).toEqual([]);
});
it('treats an album inside a subpage as no longer standalone', () => {
const result = deriveGallery({
albums: [A],
subpages: [{ name: 'Trips', albums: [B] }],
} as unknown as GalleryYaml);
expect(result.albums).toEqual([A, B]);
expect(result.standaloneAlbums).toEqual([A]);
expect(result.subpages[0].slug).toBe('trips');
});
it('accepts a subpage that has sections instead of albums', () => {
const result = deriveGallery({
subpages: [{ name: 'Work', sections: [{ title: 'Recent Work', albums: [A] }] }],
} as unknown as GalleryYaml);
expect(result.subpages[0].sections?.[0].slug).toBe('recent-work');
expect(result.albums).toEqual([A]);
});
it('collects per-album overrides and hero images', () => {
const result = deriveGallery({
albums: [{ [A]: { title: 'Renamed', description: 'A note', heroImage: B } }],
} as unknown as GalleryYaml);
expect(result.albumOverrides[A]).toBe('Renamed');
expect(result.albumDescriptions[A]).toBe('A note');
expect(result.albumHeroImages[A]).toBe(B);
});
});

View File

@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import NotFound from '@/app/not-found';
import ErrorPage from '@/app/error';
// Uses createElement rather than JSX because vitest.config.ts only includes
// lib/__tests__/**/*.test.ts — a .tsx file here would never run.
describe('not-found page', () => {
const html = () => renderToStaticMarkup(createElement(NotFound));
it('uses the themed empty-state styling rather than raw markup', () => {
expect(html()).toContain('empty-state');
});
it('offers a way back to the gallery', () => {
expect(html()).toContain('href="/"');
});
// notFound() means Immich answered and the content is genuinely gone. If this
// page hedged with "try again", a real 404 would look like a transient fault.
it('does not suggest the problem is temporary', () => {
expect(html()).not.toMatch(/try again|temporar|unavailable/i);
});
});
describe('error page', () => {
const render = (error: Error & { digest?: string }) =>
renderToStaticMarkup(createElement(ErrorPage, { error, reset: () => {} }));
it('offers a retry and a way back to the gallery', () => {
const html = render(new Error('boom'));
expect(html).toContain('Try again');
expect(html).toContain('href="/"');
});
it('surfaces the Next.js digest so a report can be traced to a log line', () => {
const html = render(Object.assign(new Error('boom'), { digest: 'abc123def' }));
expect(html).toContain('abc123def');
});
it('omits the reference line when there is no digest', () => {
expect(render(new Error('boom'))).not.toContain('Reference:');
});
// Error messages reaching this component can carry internal detail — an
// upstream URL, a header, a config value. Never echo them to a visitor.
it('does not leak the raw error message', () => {
const html = render(new Error('connect ECONNREFUSED 10.0.0.5:2283 x-api-key=hunter2'));
expect(html).not.toContain('hunter2');
expect(html).not.toContain('10.0.0.5');
expect(html).not.toContain('ECONNREFUSED');
});
// The counterpart assertion to the not-found page: this one *should* frame the
// failure as transient, because that is what an Immich outage is.
it('frames the failure as temporary', () => {
expect(render(new Error('boom'))).toMatch(/temporary/i);
});
});

View File

@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('@/lib/config', () => ({
getConfig: () => ({ authSecret: 'test-auth-secret-32-chars-long-min' }),
}));
const ASSET = '11111111-1111-1111-1111-111111111111';
/**
* Image responses are served `immutable` for a year, so the browser never
* revalidates — the ETag is not even consulted. The URL is the only thing that
* can invalidate a browser cache, which is why the buster lives there and not
* only in the ETag. Immich regenerates thumbnails when a job is re-run or a
* photo is rotated, and the asset ID does not change, so nothing else would.
*/
describe('IMAGE_CACHE_VERSION', () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllEnvs();
});
async function urls() {
const { imageUrl, videoUrl } = await import('@/lib/urls');
return { imageUrl, videoUrl };
}
it('leaves URLs byte-identical when unset — the default must not change', async () => {
const { imageUrl, videoUrl } = await urls();
expect(imageUrl(ASSET)).toMatch(/^\/api\/image\/[^?]+\?size=preview$/);
expect(imageUrl(ASSET, 'thumbnail')).toMatch(/^\/api\/image\/[^?]+\?size=thumbnail$/);
expect(videoUrl(ASSET)).toMatch(/^\/api\/video\/[^?]+$/);
});
it('treats an empty or whitespace-only value as unset', async () => {
vi.stubEnv('IMAGE_CACHE_VERSION', ' ');
const { imageUrl } = await urls();
expect(imageUrl(ASSET)).not.toContain('v=');
});
it('appends the version to image URLs when set', async () => {
vi.stubEnv('IMAGE_CACHE_VERSION', '2');
const { imageUrl } = await urls();
expect(imageUrl(ASSET)).toMatch(/\?size=preview&v=2$/);
});
it('uses a leading ? on video URLs, which carry no other parameter', async () => {
vi.stubEnv('IMAGE_CACHE_VERSION', '2');
const { videoUrl } = await urls();
const url = videoUrl(ASSET);
expect(url).toMatch(/\?v=2$/);
expect(url).not.toContain('?&');
});
it('escapes a value that would otherwise break the query string', async () => {
vi.stubEnv('IMAGE_CACHE_VERSION', 'a b&c=d');
const { imageUrl } = await urls();
const url = imageUrl(ASSET);
expect(url).toContain('v=a%20b%26c%3Dd');
// One '&' only — the separator. An unescaped value would inject parameters.
expect(url.split('&')).toHaveLength(2);
});
it('changes the URL when bumped, which is the entire point', async () => {
vi.stubEnv('IMAGE_CACHE_VERSION', '1');
const before = (await urls()).imageUrl(ASSET);
vi.resetModules();
vi.stubEnv('IMAGE_CACHE_VERSION', '2');
const after = (await urls()).imageUrl(ASSET);
expect(after).not.toBe(before);
// The token itself is unchanged: same asset, same encryption, new cache key.
expect(after.split('?')[0]).toBe(before.split('?')[0]);
});
});

View File

@@ -0,0 +1,60 @@
import { describe, it, expect } from 'vitest';
import { resolveImageSize, widthToSize } from '../imageSize';
describe('widthToSize', () => {
it('maps widths to Immich tiers at the documented boundaries', () => {
expect(widthToSize(250)).toBe('thumbnail');
expect(widthToSize(251)).toBe('preview');
expect(widthToSize(1440)).toBe('preview');
expect(widthToSize(1441)).toBe('original');
});
});
describe('resolveImageSize', () => {
it('defaults to preview when neither parameter is given', () => {
expect(resolveImageSize(null, null)).toBe('preview');
});
it('honours an explicit size on its own', () => {
expect(resolveImageSize('thumbnail', null)).toBe('thumbnail');
expect(resolveImageSize('original', null)).toBe('original');
});
it('falls back to the width-derived tier when no size is given', () => {
expect(resolveImageSize(null, '128')).toBe('thumbnail');
expect(resolveImageSize(null, '3840')).toBe('original');
});
it('ignores an unrecognised size rather than trusting it', () => {
expect(resolveImageSize('enormous', null)).toBe('preview');
});
it('ignores a non-numeric or non-positive width', () => {
expect(resolveImageSize('preview', 'abc')).toBe('preview');
expect(resolveImageSize('preview', '0')).toBe('preview');
expect(resolveImageSize('preview', '-100')).toBe('preview');
});
// The reason this function exists. ?size= is a ceiling; a width may lower the
// tier but must never raise it.
describe('when both are present, the smaller tier wins', () => {
it('lets a small width narrow the requested size', () => {
expect(resolveImageSize('preview', '128')).toBe('thumbnail');
});
// The regression this guards. next/image emits widths up to 3840 and
// widthToSize(1920) is 'original' — letting width win would ship full-size
// originals to every large display.
it('never upgrades past the requested size', () => {
expect(resolveImageSize('preview', '1920')).toBe('preview');
expect(resolveImageSize('preview', '3840')).toBe('preview');
expect(resolveImageSize('thumbnail', '3840')).toBe('thumbnail');
});
it('leaves the real grid case unchanged', () => {
// lib/urls.ts writes ?size=preview; next/image's smallest vw-based
// deviceSize is 640. This combination must stay on preview.
expect(resolveImageSize('preview', '640')).toBe('preview');
});
});
});

View File

@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
import { immich } from '../immich'; import { immich, ImmichUnavailableError } from '../immich';
import * as config from '../config'; import * as config from '../config';
import { cache } from '../cache'; import { cache } from '../cache';
@@ -16,7 +16,11 @@ vi.mock('../config', async () => {
subpages: [], subpages: [],
albumOverrides: { 'album-1': 'Override Name' }, albumOverrides: { 'album-1': 'Override Name' },
albumDescriptions: {}, albumDescriptions: {},
cacheTtl: 0, // Non-zero: a 0 TTL expires an entry in the same millisecond it is
// written, which would make any caching assertion flaky. Isolation comes
// from the cache.clear() in beforeEach, not from an unusable TTL.
cacheTtl: 60_000,
immichTimeoutMs: 15000,
}), }),
}; };
}); });
@@ -57,6 +61,294 @@ describe('ImmichClient', () => {
const result = await (immich as any).request('/test'); const result = await (immich as any).request('/test');
expect(result).toBeNull(); expect(result).toBeNull();
}); });
// A null return means "Immich answered: this does not exist" and the page
// turns it into notFound(). Every other failure must be distinguishable,
// or an outage renders a hard 404 for albums that do exist.
describe('distinguishes "gone" from "unavailable"', () => {
it('returns null for 410 Gone', async () => {
mockFetch.mockResolvedValueOnce({ ok: false, status: 410, statusText: 'Gone' });
await expect((immich as any).request('/test')).resolves.toBeNull();
});
it('throws on a 5xx instead of reporting the resource as missing', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 503,
statusText: 'Service Unavailable',
});
await expect((immich as any).request('/test')).rejects.toBeInstanceOf(
ImmichUnavailableError,
);
});
it('throws on a rejected API key rather than 404-ing every album', async () => {
mockFetch.mockResolvedValueOnce({ ok: false, status: 401, statusText: 'Unauthorized' });
await expect((immich as any).request('/test')).rejects.toBeInstanceOf(
ImmichUnavailableError,
);
});
it('throws when the network is unreachable', async () => {
mockFetch.mockRejectedValueOnce(new Error('ECONNREFUSED'));
await expect((immich as any).request('/test')).rejects.toBeInstanceOf(
ImmichUnavailableError,
);
});
it('throws when a gateway returns an HTML error page instead of JSON', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
headers: { get: () => 'text/html' },
json: async () => ({}),
});
await expect((immich as any).request('/test')).rejects.toBeInstanceOf(
ImmichUnavailableError,
);
});
it('carries the upstream status for logging', async () => {
mockFetch.mockResolvedValueOnce({ ok: false, status: 502, statusText: 'Bad Gateway' });
await expect((immich as any).request('/test')).rejects.toMatchObject({ status: 502 });
});
});
});
// Without a budget the only ceiling is undici's default, measured in minutes.
// Every page is force-dynamic, so an Immich that accepts connections but never
// answers would hold each visitor's render open for that whole window.
describe('timeouts', () => {
const timeoutError = () => {
const err = new Error('The operation was aborted due to timeout');
err.name = 'TimeoutError';
return err;
};
it('sends an abort signal with every JSON request', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
headers: { get: () => 'application/json' },
json: async () => ({}),
});
await (immich as any).request('/test');
expect(mockFetch.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
});
it('reports a timed-out request as unavailable, not as a missing resource', async () => {
mockFetch.mockRejectedValueOnce(timeoutError());
await expect((immich as any).request('/test')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('names the budget in the error so a misconfigured timeout is diagnosable', async () => {
mockFetch.mockRejectedValueOnce(timeoutError());
await expect((immich as any).request('/test')).rejects.toThrow(/15000ms/);
});
// The stream methods deliberately use a headers-only timeout. A whole-request
// timeout would truncate a large original photo or a long video mid-transfer.
it('stops the clock once stream headers arrive, so a slow body is not truncated', async () => {
vi.useFakeTimers();
try {
let captured: AbortSignal | undefined;
mockFetch.mockImplementation(async (_url: string, init: { signal?: AbortSignal }) => {
captured = init.signal;
return {
ok: true,
status: 200,
body: new ReadableStream(),
headers: { get: () => null },
};
});
const result = await immich.streamAsset('asset-1');
expect(result).not.toBeNull();
// Far beyond the 15s budget: a whole-request timeout would abort here
// and kill an in-progress download.
vi.advanceTimersByTime(60 * 60 * 1000);
expect(captured?.aborted).toBe(false);
} finally {
vi.useRealTimers();
}
});
it('still aborts a stream that never returns headers', async () => {
vi.useFakeTimers();
try {
let captured: AbortSignal | undefined;
mockFetch.mockImplementation(
(_url: string, init: { signal?: AbortSignal }) =>
new Promise((_resolve, reject) => {
captured = init.signal;
init.signal?.addEventListener('abort', () => reject(timeoutError()));
}),
);
const pending = immich.streamAsset('asset-1');
// Attach the rejection handler *before* advancing timers: the abort
// fires during advanceTimersByTimeAsync, and a promise that rejects
// with no handler yet attached is reported as an unhandled rejection,
// which fails the whole vitest run.
const rejects = expect(pending).rejects.toBeInstanceOf(ImmichUnavailableError);
await vi.advanceTimersByTimeAsync(15001);
await rejects;
expect(captured?.aborted).toBe(true);
} finally {
vi.useRealTimers();
}
});
});
// The image/video routes serve these URLs with `immutable` on success and turn
// a null into a 404. A bare 404 is heuristically cacheable, so an outage that
// looked like "missing" could pin a broken image in the browser cache.
describe('stream failures distinguish gone from unavailable', () => {
const streamRes = (status: number) => ({
ok: status >= 200 && status < 300,
status,
body: null,
headers: { get: () => null },
});
it('streamAsset returns null for a genuinely missing asset', async () => {
mockFetch.mockResolvedValueOnce(streamRes(404));
await expect(immich.streamAsset('asset-1')).resolves.toBeNull();
});
it('streamAsset throws when Immich errors rather than reporting it missing', async () => {
mockFetch.mockResolvedValueOnce(streamRes(500));
await expect(immich.streamAsset('asset-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('streamAsset throws when the network is unreachable', async () => {
mockFetch.mockRejectedValueOnce(new Error('ECONNREFUSED'));
await expect(immich.streamAsset('asset-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('streamAsset throws on a 200 with no body', async () => {
mockFetch.mockResolvedValueOnce(streamRes(200));
await expect(immich.streamAsset('asset-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('streamVideo returns null for a genuinely missing video', async () => {
mockFetch.mockResolvedValueOnce(streamRes(404));
await expect(immich.streamVideo('asset-1')).resolves.toBeNull();
});
it('streamVideo throws when Immich errors', async () => {
mockFetch.mockResolvedValueOnce(streamRes(502));
await expect(immich.streamVideo('asset-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('streamVideo still accepts a 206 partial response for seeking', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 206,
body: new ReadableStream(),
headers: { get: () => null },
});
const result = await immich.streamVideo('asset-1', 'bytes=0-1023');
expect(result?.status).toBe(206);
});
});
// Measured before the fix: 5 sequential lookups of a missing asset produced 5
// upstream fetches. The homepage resolves every gallery.yaml hero ID on each
// render and is force-dynamic, so a hero photo deleted from Immich cost one
// 404 round-trip per page view, indefinitely.
describe('negative caching', () => {
const notFound = { ok: false, status: 404, statusText: 'Not Found' };
it('queries Immich once for a repeatedly-requested missing asset', async () => {
mockFetch.mockResolvedValue(notFound);
for (let i = 0; i < 5; i++) {
await expect(immich.getAssetInfo('missing-asset')).resolves.toBeNull();
}
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('queries Immich once for a repeatedly-requested missing album', async () => {
mockFetch.mockResolvedValue(notFound);
for (let i = 0; i < 3; i++) {
await expect(immich.getAlbum('album-1')).resolves.toBeNull();
}
// One album request + one metadata-search request, from the first call only.
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it('does not cache an outage, which would outlive the recovery', async () => {
mockFetch.mockResolvedValueOnce({ ok: false, status: 503, statusText: 'Unavailable' });
await expect(immich.getAssetInfo('asset-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
// Immich recovers: the very next call must reach it, not replay the failure.
mockFetch.mockResolvedValueOnce({
ok: true,
headers: { get: () => 'application/json' },
json: async () => ({ id: 'asset-1' }),
});
await expect(immich.getAssetInfo('asset-1')).resolves.toMatchObject({ id: 'asset-1' });
});
it('a cached absence is cleared by invalidation, so a fix takes effect at once', async () => {
mockFetch.mockResolvedValue(notFound);
await expect(immich.getAssetInfo('asset-1')).resolves.toBeNull();
immich.invalidateAll();
mockFetch.mockResolvedValue({
ok: true,
headers: { get: () => 'application/json' },
json: async () => ({ id: 'asset-1' }),
});
await expect(immich.getAssetInfo('asset-1')).resolves.toMatchObject({ id: 'asset-1' });
});
});
// The regression this whole error type exists to prevent.
describe('outage handling', () => {
it('getAlbum propagates an outage instead of returning null', async () => {
// Not mockResolvedValueOnce: getAlbum fires the album and metadata-search
// requests concurrently, so both need the failing response.
mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Internal Server Error' });
await expect(immich.getAlbum('album-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('getAlbums propagates an outage instead of returning an empty list', async () => {
// Returning [] here would render the homepage as "this gallery has no
// albums" while Immich is merely down.
mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Internal Server Error' });
await expect(immich.getAlbums()).rejects.toBeInstanceOf(ImmichUnavailableError);
});
it('a failed album does not leave a stale entry in the in-flight map', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Internal Server Error' });
await expect(immich.getAlbum('album-1')).rejects.toBeInstanceOf(ImmichUnavailableError);
// A stranded pending promise would make every later call replay the
// failure forever, even after Immich recovers.
expect((immich as any).pendingAlbumPromises.has('album-1')).toBe(false);
expect((immich as any).pendingAlbumsPromise).toBeNull();
});
it('ping reports unreachable as false rather than throwing', async () => {
// /api/health and /api/admin/status render this as a status field.
mockFetch.mockRejectedValueOnce(new Error('ECONNREFUSED'));
await expect(immich.ping()).resolves.toBe(false);
});
}); });
describe('getAlbums()', () => { describe('getAlbums()', () => {

View File

@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest';
import { NextRequest } from 'next/server';
import { proxy, config } from '@/proxy';
// Next.js 16 renamed the "middleware" file convention to "proxy": the file must
// be proxy.ts and must export proxy(), not middleware(). A silent regression here
// (wrong filename, wrong export name) means Next.js never invokes this code and
// every document response ships without a CSP — with no build error to catch it.
describe('proxy', () => {
const run = (pathname = '/') => proxy(new NextRequest(`https://example.com${pathname}`));
it('is exported under the name Next.js 16 expects', () => {
expect(typeof proxy).toBe('function');
});
it('sets a Content-Security-Policy on the response', () => {
const csp = run().headers.get('Content-Security-Policy');
expect(csp).toContain("default-src 'self'");
expect(csp).toContain("frame-ancestors 'none'");
});
it('issues a per-request nonce and passes it to pages via x-nonce', () => {
const response = run();
const nonce = response.headers.get('x-middleware-request-x-nonce');
expect(nonce).toBeTruthy();
// The nonce in the CSP must be the same one the page receives, otherwise
// Next.js stamps scripts with a nonce the policy does not allow.
expect(response.headers.get('Content-Security-Policy')).toContain(`'nonce-${nonce}'`);
});
it('generates a different nonce per request', () => {
const first = run().headers.get('x-middleware-request-x-nonce');
const second = run().headers.get('x-middleware-request-x-nonce');
expect(first).not.toBe(second);
});
it('forwards the pathname so the root layout can keep /admin reachable', () => {
const response = run('/admin/settings');
expect(response.headers.get('x-middleware-request-x-pathname')).toBe('/admin/settings');
});
it('does not set unsafe-inline alongside the nonce', () => {
// CSP2-only browsers ignore 'strict-dynamic' and would honour the fallback,
// making it strictly worse than having none.
expect(run().headers.get('Content-Security-Policy')).not.toContain(
"script-src 'self' 'unsafe-inline'",
);
});
it('keeps a matcher that excludes api and static assets but covers /admin', () => {
const source = config.matcher[0].source;
expect(source).toContain('api');
expect(source).toContain('_next/static');
expect(source).not.toContain('admin');
});
});

View File

@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { NextRequest } from 'next/server'; import { NextRequest } from 'next/server';
let mockHops = 0; let mockHops = 0;
@@ -6,7 +6,12 @@ vi.mock('@/lib/config', () => ({
getConfig: () => ({ trustedProxyHops: mockHops }), getConfig: () => ({ trustedProxyHops: mockHops }),
})); }));
import { checkRateLimit, getClientIp } from '@/lib/rate-limit'; import {
checkRateLimit,
getClientIp,
retryAfterSeconds,
__resetProxyWarningForTests,
} from '@/lib/rate-limit';
function req(headers: Record<string, string>, ip?: string): NextRequest { function req(headers: Record<string, string>, ip?: string): NextRequest {
return { ...(ip ? { ip } : {}), headers: new Headers(headers) } as unknown as NextRequest; return { ...(ip ? { ip } : {}), headers: new Headers(headers) } as unknown as NextRequest;
@@ -85,6 +90,86 @@ describe('getClientIp behind two trusted proxies (TRUSTED_PROXY_HOPS=2)', () =>
}); });
}); });
/**
* Falling back to the shared 'unknown' bucket is correct — trusting a spoofable
* header would be worse — but silent. Every unidentified request shares one
* bucket per endpoint, and a 50-photo grid issues ~50 /api/image requests, so
* the default 1500 rpm is collectively spent by ~30 page loads a minute.
* Visitors get 429s with nothing in the log naming the cause.
*/
describe('diagnosing an unidentifiable client', () => {
let warn: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
__resetProxyWarningForTests();
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
// Without this the spies stack on console.warn across tests and call counts
// accumulate, which silently turns every assertion below into a false pass
// or a confusing failure.
afterEach(() => warn.mockRestore());
it('warns when the forwarded chain is shorter than the configured hops', () => {
mockHops = 2;
expect(getClientIp(req({ 'x-forwarded-for': '203.0.113.9' }))).toBe('unknown');
expect(warn).toHaveBeenCalledOnce();
const message = String(warn.mock.calls[0][0]);
expect(message).toContain('TRUSTED_PROXY_HOPS is 2');
expect(message).toContain('1 entry');
});
it('warns when neither forwarding header is present', () => {
mockHops = 1;
expect(getClientIp(req({}))).toBe('unknown');
expect(String(warn.mock.calls[0][0])).toContain('neither X-Forwarded-For nor X-Real-IP');
});
it('explains why X-Real-IP was not trusted at more than one hop', () => {
mockHops = 2;
expect(getClientIp(req({ 'x-real-ip': '203.0.113.9' }))).toBe('unknown');
expect(String(warn.mock.calls[0][0])).toContain('single hop');
});
it('warns once per process, not once per request', () => {
mockHops = 2;
for (let i = 0; i < 50; i++) getClientIp(req({}));
expect(warn).toHaveBeenCalledOnce();
});
it('stays silent while clients are being identified correctly', () => {
mockHops = 1;
expect(getClientIp(req({ 'x-forwarded-for': '203.0.113.9' }))).toBe('203.0.113.9');
expect(getClientIp(req({ 'x-real-ip': '203.0.113.9' }))).toBe('203.0.113.9');
expect(warn).not.toHaveBeenCalled();
});
it('stays silent at hops=0, where the shared bucket is expected, not a misconfiguration', () => {
mockHops = 0;
expect(getClientIp(req({}))).toBe('unknown');
expect(warn).not.toHaveBeenCalled();
});
});
describe('retryAfterSeconds', () => {
it('rounds up, so a client never retries before the window closes', () => {
expect(retryAfterSeconds(Date.now() + 1500)).toBe(2);
expect(retryAfterSeconds(Date.now() + 30_000)).toBe(30);
});
// The reason this is a function rather than an inline Math.ceil. Every route
// had its own copy, and each shared this edge: a window on the point of
// expiring gives 0, and `Retry-After: 0` tells the client to retry at once —
// the opposite of what a 429 means. A past resetAt gives a negative number,
// which is not valid HTTP at all.
it('never returns zero or a negative value', () => {
expect(retryAfterSeconds(Date.now())).toBe(1);
expect(retryAfterSeconds(Date.now() + 10)).toBe(1);
expect(retryAfterSeconds(Date.now() - 60_000)).toBe(1);
});
});
describe('checkRateLimit', () => { describe('checkRateLimit', () => {
// Use unique IP prefixes per test to avoid cross-contamination // Use unique IP prefixes per test to avoid cross-contamination
let testIp: string; let testIp: string;

View File

@@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('fs/promises', () => ({
default: {
mkdir: vi.fn(async () => undefined),
access: vi.fn(async () => {
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
}),
copyFile: vi.fn(async () => undefined),
readdir: vi.fn(async () => []),
unlink: vi.fn(async () => undefined),
writeFile: vi.fn(async () => undefined),
rename: vi.fn(async () => undefined),
readFile: vi.fn(),
},
}));
import fs from 'fs/promises';
import { writeGalleryYaml } from '@/lib/admin/yaml-service';
const gallery = { albums: ['11111111-1111-1111-1111-111111111111'] };
const tmpPaths = () => vi.mocked(fs.writeFile).mock.calls.map((c) => String(c[0]));
/**
* The rename is what makes the write atomic; the temp filename is what did not
* used to be. With a constant `gallery.yaml.tmp`, two saves in flight at once
* shared it, so the second writeFile could interleave with the first's rename.
*/
describe('writeYamlFile temp file handling', () => {
beforeEach(() => vi.clearAllMocks());
it('never writes to the bare .tmp path two callers would collide on', async () => {
await writeGalleryYaml(gallery);
expect(tmpPaths()[0]).not.toMatch(/gallery\.yaml\.tmp$/);
});
it('uses a distinct temp path for every write', async () => {
await writeGalleryYaml(gallery);
await writeGalleryYaml(gallery);
await writeGalleryYaml(gallery);
const paths = tmpPaths();
expect(paths).toHaveLength(3);
expect(new Set(paths).size).toBe(3);
});
it('renames the temp file it just wrote, not some other one', async () => {
await writeGalleryYaml(gallery);
const [written] = tmpPaths();
const [from, to] = vi.mocked(fs.rename).mock.calls[0].map(String);
expect(from).toBe(written);
expect(to).toMatch(/content\/gallery\.yaml$/);
});
it('cleans up the temp file when the write fails', async () => {
vi.mocked(fs.writeFile).mockRejectedValueOnce(new Error('ENOSPC'));
await expect(writeGalleryYaml(gallery)).rejects.toThrow('ENOSPC');
expect(String(vi.mocked(fs.unlink).mock.calls[0][0])).toBe(tmpPaths()[0]);
});
it('cleans up when the rename fails', async () => {
vi.mocked(fs.rename).mockRejectedValueOnce(new Error('EXDEV'));
await expect(writeGalleryYaml(gallery)).rejects.toThrow('EXDEV');
expect(fs.unlink).toHaveBeenCalledOnce();
});
it('does not let a cleanup failure mask the real error', async () => {
vi.mocked(fs.writeFile).mockRejectedValueOnce(new Error('ENOSPC'));
vi.mocked(fs.unlink).mockRejectedValueOnce(new Error('EACCES'));
await expect(writeGalleryYaml(gallery)).rejects.toThrow('ENOSPC');
});
it('does not unlink on the happy path', async () => {
await writeGalleryYaml(gallery);
expect(fs.unlink).not.toHaveBeenCalled();
});
});

View File

@@ -4,7 +4,7 @@
* Used by the root layout to keep /admin reachable while the app is in * Used by the root layout to keep /admin reachable while the app is in
* setup mode: the setup screen must not lock out the very tool that fixes * setup mode: the setup screen must not lock out the very tool that fixes
* an incomplete configuration (#326). A null pathname (header missing, * an incomplete configuration (#326). A null pathname (header missing,
* e.g. a route not covered by the middleware matcher) counts as non-admin * e.g. a route not covered by the proxy matcher) counts as non-admin
* so the setup screen remains the safe default. * so the setup screen remains the safe default.
*/ */
export function isAdminPath(pathname: string | null): boolean { export function isAdminPath(pathname: string | null): boolean {

View File

@@ -11,6 +11,9 @@ import type { GalleryYaml, SettingsYaml } from '../config/schema';
const CONTENT_DIR = path.join(process.cwd(), 'content'); const CONTENT_DIR = path.join(process.cwd(), 'content');
const MAX_BACKUPS = 10; // Keep last 10 backups per file const MAX_BACKUPS = 10; // Keep last 10 backups per file
/** Disambiguates temp files within one process; the pid covers across them. */
let tmpCounter = 0;
/** Read gallery.yaml and return parsed content. */ /** Read gallery.yaml and return parsed content. */
export async function readGalleryYaml(): Promise<GalleryYaml | null> { export async function readGalleryYaml(): Promise<GalleryYaml | null> {
try { try {
@@ -71,10 +74,23 @@ async function writeYamlFile(filename: string, data: unknown): Promise<void> {
sortKeys: false, sortKeys: false,
}); });
// Atomic write: write to temp file, then rename // Atomic write: write to a *unique* temp file, then rename.
const tmpPath = `${filePath}.tmp`; //
await fs.writeFile(tmpPath, content, 'utf8'); // The rename is what makes this atomic; the temp filename is what did not.
await fs.rename(tmpPath, filePath); // With a constant `${filePath}.tmp`, two saves of the same file in flight at
// once shared it — the second writeFile could interleave with the first's
// rename, leaving one save's bytes published under the other's, or a
// truncated mix. A double-clicked Save in the page builder is enough.
const tmpPath = `${filePath}.${process.pid}.${++tmpCounter}.tmp`;
try {
await fs.writeFile(tmpPath, content, 'utf8');
await fs.rename(tmpPath, filePath);
} catch (err) {
// Do not leave litter in content/ behind a failed save. Cleanup failure is
// not worth masking the real error with.
await fs.unlink(tmpPath).catch(() => {});
throw err;
}
console.log(`[Admin] ✅ Saved ${filename}`); console.log(`[Admin] ✅ Saved ${filename}`);
} }
@@ -103,16 +119,32 @@ export async function listBackups(filename: string): Promise<string[]> {
} }
} }
/**
* Names this service actually produces, and the only ones it will restore from.
*
* `[\w-]` matches neither `/` nor `.`, and the anchors leave no room for a
* prefix, so a `..` segment cannot match. Without this, `path.join` happily
* resolves `../../../../etc/passwd` and the copy below writes an arbitrary
* readable file over content/settings.yaml — which the admin GET endpoints then
* hand straight back.
*/
const BACKUP_FILENAME = /^(gallery|settings)\.yaml\.[\w-]+\.(pre-restore\.)?bak$/;
/** Restore a specific backup. */ /** Restore a specific backup. */
export async function restoreBackup(backupFilename: string): Promise<void> { export async function restoreBackup(backupFilename: string): Promise<void> {
const match = BACKUP_FILENAME.exec(backupFilename);
// The basename check is redundant against the regex above, and kept
// deliberately: it keeps the guarantee if that pattern is ever loosened.
if (!match || path.basename(backupFilename) !== backupFilename) {
throw new Error(`Refusing to restore from an unrecognised backup name: "${backupFilename}"`);
}
const backupDir = path.join(CONTENT_DIR, '.backups'); const backupDir = path.join(CONTENT_DIR, '.backups');
const backupPath = path.join(backupDir, backupFilename); const backupPath = path.join(backupDir, backupFilename);
// Determine the original filename // Derived from the matched group, never from a substring search on the input:
const originalFilename = backupFilename.includes('gallery.yaml') // `includes('gallery.yaml')` would let the caller pick the destination.
? 'gallery.yaml' const originalFilename = `${match[1]}.yaml`;
: 'settings.yaml';
const targetPath = path.join(CONTENT_DIR, originalFilename); const targetPath = path.join(CONTENT_DIR, originalFilename);
// Create a backup of current state first // Create a backup of current state first

View File

@@ -18,15 +18,35 @@ 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') * Native SCrypt verify (format: 'scrypt:salt:hash_hex')
*/ */
function verifyScrypt(password: string, stored: string): boolean { async function verifyScrypt(password: string, stored: string): Promise<boolean> {
if (!stored.startsWith('scrypt:')) return false; if (!stored.startsWith('scrypt:')) return false;
try { try {
const [, salt, hashHex] = stored.split(':'); const [, salt, hashHex] = stored.split(':');
const key = crypto.scryptSync(password, salt, 64); const key = await scryptAsync(password, salt, 64);
const expectedKey = Buffer.from(hashHex, 'hex'); const expectedKey = Buffer.from(hashHex, 'hex');
if (key.length !== expectedKey.length) return false; if (key.length !== expectedKey.length) return false;
return crypto.timingSafeEqual(key, expectedKey); return crypto.timingSafeEqual(key, expectedKey);
@@ -38,9 +58,9 @@ function verifyScrypt(password: string, stored: string): boolean {
/** /**
* Helper to generate an scrypt string to print in logs. * Helper to generate an scrypt string to print in logs.
*/ */
function generateScryptHash(password: string): string { async function generateScryptHash(password: string): Promise<string> {
const salt = crypto.randomBytes(16).toString('hex'); const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync(password, salt, 64).toString('hex'); const hash = (await scryptAsync(password, salt, 64)).toString('hex');
return `scrypt:${salt}:${hash}`; return `scrypt:${salt}:${hash}`;
} }
@@ -94,11 +114,11 @@ export function isProtected(key: string, type: 'subpage' | 'album' = 'subpage'):
* Validate a password attempt and return a Set-Cookie header value on success. * Validate a password attempt and return a Set-Cookie header value on success.
* Returns null if the password is wrong. * Returns null if the password is wrong.
*/ */
export function authenticate( export async function authenticate(
key: string, key: string,
password: string, password: string,
type: 'subpage' | 'album' = 'subpage', type: 'subpage' | 'album' = 'subpage',
): string | null { ): Promise<string | null> {
const storedPassword = findPassword(key, type); const storedPassword = findPassword(key, type);
if (!storedPassword) return null; if (!storedPassword) return null;
@@ -115,7 +135,7 @@ export function authenticate(
} }
if (storedPassword.startsWith('scrypt:')) { if (storedPassword.startsWith('scrypt:')) {
isValid = verifyScrypt(password, storedPassword); isValid = await verifyScrypt(password, storedPassword);
} else { } else {
// Plaintext fallback (deprecated) // Plaintext fallback (deprecated)
// Hash both to a fixed length before constant-time comparison to prevent timing and length attacks // Hash both to a fixed length before constant-time comparison to prevent timing and length attacks
@@ -130,7 +150,7 @@ export function authenticate(
isValid = crypto.timingSafeEqual(attemptHash, storedHash); isValid = crypto.timingSafeEqual(attemptHash, storedHash);
if (isValid) { if (isValid) {
const recommendedHash = generateScryptHash(storedPassword); const recommendedHash = await generateScryptHash(storedPassword);
console.warn( console.warn(
`\n⚠️ SECURITY WARNING: ${type === 'subpage' ? 'Subpage' : 'Album'} "${key}" is using a plaintext password in gallery.yaml.\n` + `\n⚠️ SECURITY WARNING: ${type === 'subpage' ? 'Subpage' : 'Album'} "${key}" is using a plaintext password in gallery.yaml.\n` +
` Please replace it with this native secure hash:\n\n ${recommendedHash}\n`, ` Please replace it with this native secure hash:\n\n ${recommendedHash}\n`,

View File

@@ -21,6 +21,34 @@ export function invalidateConfigCache(): void {
clearYamlCache(); clearYamlCache();
} }
/**
* getConfig(), but returns null instead of throwing on a gallery.yaml that
* cannot be derived.
*
* getConfig() throws for three shapes the admin page builder is able to write:
* a gallery with neither albums nor subpages, a subpage with no name, and a
* subpage with neither albums nor sections. A throw inside a *layout* is not
* caught by app/error.tsx — that needs a global-error boundary — so the site
* and /admin would go down together, locking the user out of the only tool that
* can undo the save. That is issue #326's failure mode reached through an
* invalid config rather than a missing one.
*
* Callers should treat null exactly like `needsSetup`: show the setup screen,
* and keep /admin reachable.
*/
export function getConfigOrNull(): AppConfig | null {
try {
return getConfig();
} catch (error) {
console.error(
'[Folio] content/gallery.yaml could not be loaded — serving the setup screen. ' +
'Fix the file or restore a backup from content/.backups/:',
error,
);
return null;
}
}
/** Converts raw YAML grid overrides into a typed partial GridConfig. */ /** Converts raw YAML grid overrides into a typed partial GridConfig. */
export function buildSubpageGrid(raw?: { export function buildSubpageGrid(raw?: {
columns?: number; columns?: number;
@@ -45,56 +73,28 @@ export function buildSubpageGrid(raw?: {
}; };
} }
export function getConfig(): AppConfig { /** The parts of AppConfig that come from gallery.yaml. */
// No in-memory config cache: admin saves can land in a different export interface GalleryDerivation {
// worker/process than page rendering, so a per-worker cache goes stale albums: string[];
// until restart. Freshness comes from the mtime-checked YAML cache in standaloneAlbums: string[];
// loadYaml() — a statSync per file, negligible next to Immich API calls. subpages: SubpageConfig[];
const apiUrl = env.IMMICH_API_URL; albumOverrides: Record<string, string>;
const apiKey = env.IMMICH_API_KEY; albumDescriptions: Record<string, string>;
const authSecret = resolveAuthSecret(); albumPasswords: Record<string, string>;
albumHeroImages: Record<string, string>;
const gallery = loadYaml<GalleryYaml>('gallery.yaml'); }
const settings = loadYaml<SettingsYaml>('settings.yaml') || {};
if (!gallery || !apiKey || !apiUrl) {
// Return dummy config if gallery.yaml is missing
return {
immich: { apiUrl: `${apiUrl}/api`, apiKey },
authSecret,
albums: [],
standaloneAlbums: [],
subpages: [],
siteTitle: env.SITE_TITLE || 'Immich Folio',
siteSubtitle: env.SITE_SUBTITLE || 'Setup Required',
lang: 'en',
seo: {
title: 'Setup Required',
description: 'Please configure Immich Folio',
noIndex: true,
noFollow: true,
},
heroImages: [],
exifOnHover: true,
grid: { columns: 3, gap: 12, aspectRatio: '1', layout: 'masonry' },
theme: resolveTheme('studio'),
footer: null,
legal: { enabled: false, name: '', address: '', zipCity: '', country: '' },
map: false,
transitions: false,
albumOverrides: {},
albumDescriptions: {},
albumPasswords: {},
albumHeroImages: {},
cacheTtl: env.CACHE_TTL * 1000,
rateLimitRpm: env.RATE_LIMIT_RPM,
trustedProxyHops: env.TRUSTED_PROXY_HOPS,
needsSetup: true,
};
}
const theme = resolveTheme(settings.theme);
/**
* 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
* with neither albums nor sections.
*
* Extracted from getConfig() so the admin PUT can run the *real* derivation
* against a proposed gallery before writing it. Re-implementing the three
* checks in the route would guarantee drift; write-then-verify-then-roll-back
* would leave a window where other requests read the broken config.
*/
export function deriveGallery(gallery: GalleryYaml): GalleryDerivation {
const albumOverrides: Record<string, string> = {}; const albumOverrides: Record<string, string> = {};
const albumDescriptions: Record<string, string> = {}; const albumDescriptions: Record<string, string> = {};
const albumPasswords: Record<string, string> = {}; const albumPasswords: Record<string, string> = {};
@@ -103,7 +103,10 @@ export function getConfig(): AppConfig {
function processAlbumEntry( function processAlbumEntry(
entry: entry:
| string | string
| Record<string, string | { title: string; description?: string; password?: string; heroImage?: string }>, | Record<
string,
string | { title: string; description?: string; password?: string; heroImage?: string }
>,
context: string, context: string,
): string { ): string {
if (typeof entry === 'string') { if (typeof entry === 'string') {
@@ -118,7 +121,18 @@ export function getConfig(): AppConfig {
if (value.title) albumOverrides[validatedUuid] = value.title; if (value.title) albumOverrides[validatedUuid] = value.title;
if (value.description) albumDescriptions[validatedUuid] = value.description; if (value.description) albumDescriptions[validatedUuid] = value.description;
if (value.password) albumPasswords[validatedUuid] = value.password; if (value.password) albumPasswords[validatedUuid] = value.password;
if (value.heroImage) albumHeroImages[validatedUuid] = value.heroImage; // The album ID (the key) is validated above; the hero asset ID is a
// separate UUID and was previously stored raw. It flows to encodeAssetId
// via app/[...path]/page.tsx, which encrypts whatever it is handed — so a
// typo here produced a well-formed URL that 404s forever, with nothing in
// the log naming the cause. Every other ID in this file goes through
// validateUuid; this one was the gap.
if (value.heroImage) {
albumHeroImages[validatedUuid] = validateUuid(
value.heroImage,
`${context} heroImage for album ${validatedUuid}`,
);
}
} }
return validatedUuid; return validatedUuid;
} }
@@ -209,11 +223,83 @@ export function getConfig(): AppConfig {
const subpageAlbumIds = new Set(subpages.flatMap((sp) => sp.albumIds)); const subpageAlbumIds = new Set(subpages.flatMap((sp) => sp.albumIds));
const allAlbumIds = [...new Set([...standaloneAlbumIds, ...subpageAlbumIds])]; const allAlbumIds = [...new Set([...standaloneAlbumIds, ...subpageAlbumIds])];
return {
albums: allAlbumIds,
standaloneAlbums: standaloneAlbumIds.filter((id) => !subpageAlbumIds.has(id)),
subpages,
albumOverrides,
albumDescriptions,
albumPasswords,
albumHeroImages,
};
}
export function getConfig(): AppConfig {
// No in-memory config cache: admin saves can land in a different
// worker/process than page rendering, so a per-worker cache goes stale
// until restart. Freshness comes from the mtime-checked YAML cache in
// loadYaml() — a statSync per file, negligible next to Immich API calls.
const apiUrl = env.IMMICH_API_URL;
const apiKey = env.IMMICH_API_KEY;
const authSecret = resolveAuthSecret();
const gallery = loadYaml<GalleryYaml>('gallery.yaml');
const settings = loadYaml<SettingsYaml>('settings.yaml') || {};
if (!gallery || !apiKey || !apiUrl) {
// Return dummy config if gallery.yaml is missing
return {
immich: { apiUrl: `${apiUrl}/api`, apiKey },
authSecret,
albums: [],
standaloneAlbums: [],
subpages: [],
siteTitle: env.SITE_TITLE || 'Immich Folio',
siteSubtitle: env.SITE_SUBTITLE || 'Setup Required',
lang: 'en',
seo: {
title: 'Setup Required',
description: 'Please configure Immich Folio',
noIndex: true,
noFollow: true,
},
heroImages: [],
exifOnHover: true,
grid: { columns: 3, gap: 12, aspectRatio: '1', layout: 'masonry' },
theme: resolveTheme('studio'),
footer: null,
legal: { enabled: false, name: '', address: '', zipCity: '', country: '' },
map: false,
transitions: false,
albumOverrides: {},
albumDescriptions: {},
albumPasswords: {},
albumHeroImages: {},
cacheTtl: env.CACHE_TTL * 1000,
immichTimeoutMs: env.IMMICH_TIMEOUT_MS,
rateLimitRpm: env.RATE_LIMIT_RPM,
trustedProxyHops: env.TRUSTED_PROXY_HOPS,
needsSetup: true,
};
}
const theme = resolveTheme(settings.theme);
const {
albums: allAlbumIds,
standaloneAlbums,
subpages,
albumOverrides,
albumDescriptions,
albumPasswords,
albumHeroImages,
} = deriveGallery(gallery);
return { return {
immich: { apiUrl: `${apiUrl}/api`, apiKey }, immich: { apiUrl: `${apiUrl}/api`, apiKey },
authSecret, authSecret,
albums: allAlbumIds, albums: allAlbumIds,
standaloneAlbums: standaloneAlbumIds.filter((id) => !subpageAlbumIds.has(id)), standaloneAlbums,
subpages, subpages,
siteTitle: settings.title ?? env.SITE_TITLE, siteTitle: settings.title ?? env.SITE_TITLE,
siteSubtitle: settings.subtitle ?? env.SITE_SUBTITLE, siteSubtitle: settings.subtitle ?? env.SITE_SUBTITLE,
@@ -270,6 +356,7 @@ export function getConfig(): AppConfig {
albumPasswords, albumPasswords,
albumHeroImages, albumHeroImages,
cacheTtl: env.CACHE_TTL * 1000, cacheTtl: env.CACHE_TTL * 1000,
immichTimeoutMs: env.IMMICH_TIMEOUT_MS,
rateLimitRpm: env.RATE_LIMIT_RPM, rateLimitRpm: env.RATE_LIMIT_RPM,
trustedProxyHops: env.TRUSTED_PROXY_HOPS, trustedProxyHops: env.TRUSTED_PROXY_HOPS,
needsSetup: false, needsSetup: false,

View File

@@ -99,6 +99,8 @@ export interface AppConfig {
albumPasswords: Record<string, string>; albumPasswords: Record<string, string>;
albumHeroImages: Record<string, string>; albumHeroImages: Record<string, string>;
cacheTtl: number; cacheTtl: number;
/** Response-wait budget for Immich API calls. Does not cap image/video body transfer. */
immichTimeoutMs: number;
rateLimitRpm: number; rateLimitRpm: number;
trustedProxyHops: number; trustedProxyHops: number;
needsSetup?: boolean; needsSetup?: boolean;

View File

@@ -9,6 +9,8 @@ export interface Env {
SITE_TITLE: string; SITE_TITLE: string;
SITE_SUBTITLE: string; SITE_SUBTITLE: string;
CACHE_TTL: number; CACHE_TTL: number;
IMAGE_CACHE_VERSION: string;
IMMICH_TIMEOUT_MS: number;
RATE_LIMIT_RPM: number; RATE_LIMIT_RPM: number;
AUTH_SECRET?: string; AUTH_SECRET?: string;
TRUSTED_PROXY_HOPS: number; TRUSTED_PROXY_HOPS: number;
@@ -35,6 +37,30 @@ function parseEnv(): Env {
const cacheTtl = const cacheTtl =
cacheTtlStr && !isNaN(parseInt(cacheTtlStr, 10)) ? parseInt(cacheTtlStr, 10) : 300; cacheTtlStr && !isNaN(parseInt(cacheTtlStr, 10)) ? parseInt(cacheTtlStr, 10) : 300;
// How long to wait on Immich before giving up. Without an explicit budget the
// only ceiling is undici's built-in default (minutes), and since every page is
// force-dynamic an Immich that accepts connections but never answers would
// hold each visitor's render open for that entire window.
//
// This bounds the wait for a *response*, not the transfer of an image or video
// body — those are legitimately slow and are not capped by this value.
const timeoutStr = process.env.IMMICH_TIMEOUT_MS;
const timeoutMs =
timeoutStr && !isNaN(parseInt(timeoutStr, 10)) ? parseInt(timeoutStr, 10) : 15000;
// Manual cache-buster for image and video URLs. Empty by default, so normal
// operation is untouched.
//
// Image responses are served `immutable` for a year, which means the browser
// does not revalidate at all — not even the ETag is consulted. That is the
// right default (these URLs are content-addressed by an encrypted asset ID),
// but it leaves no way to push a changed rendition: Immich regenerates
// thumbnails and previews when a job is re-run or a photo is rotated, and the
// asset ID — hence the token, hence the URL — stays the same. Bumping this
// value changes every image URL at once and is the only escape hatch short of
// rotating AUTH_SECRET.
const imageCacheVersion = (process.env.IMAGE_CACHE_VERSION || '').trim();
const rateLimitStr = process.env.RATE_LIMIT_RPM; const rateLimitStr = process.env.RATE_LIMIT_RPM;
const rateLimit = const rateLimit =
rateLimitStr && !isNaN(parseInt(rateLimitStr, 10)) ? parseInt(rateLimitStr, 10) : 1500; rateLimitStr && !isNaN(parseInt(rateLimitStr, 10)) ? parseInt(rateLimitStr, 10) : 1500;
@@ -65,6 +91,10 @@ function parseEnv(): Env {
SITE_TITLE: process.env.SITE_TITLE || 'Gallery', SITE_TITLE: process.env.SITE_TITLE || 'Gallery',
SITE_SUBTITLE: process.env.SITE_SUBTITLE || '', SITE_SUBTITLE: process.env.SITE_SUBTITLE || '',
CACHE_TTL: Math.max(0, cacheTtl), CACHE_TTL: Math.max(0, cacheTtl),
// Kept URL-safe: this value is appended to every image and video URL.
IMAGE_CACHE_VERSION: encodeURIComponent(imageCacheVersion),
// A sub-second budget would abort healthy requests; 0 must not mean "no timeout".
IMMICH_TIMEOUT_MS: Math.max(1000, timeoutMs),
RATE_LIMIT_RPM: Math.max(1, rateLimit), RATE_LIMIT_RPM: Math.max(1, rateLimit),
AUTH_SECRET: process.env.AUTH_SECRET, AUTH_SECRET: process.env.AUTH_SECRET,
TRUSTED_PROXY_HOPS: trustedProxyHops, TRUSTED_PROXY_HOPS: trustedProxyHops,

50
lib/imageSize.ts Normal file
View File

@@ -0,0 +1,50 @@
/**
* Resolves which Immich rendition the image proxy should fetch.
*
* Two query parameters can influence it:
* ?size= written by lib/urls.ts — the ceiling the server intends
* ?w= appended by lib/immichLoader.ts — the width next/image will display
*
* Lives here rather than in the route so it can be unit-tested: vitest.config.ts
* only collects lib/__tests__.
*/
import type { ImageSize } from './immich';
export const VALID_SIZES: ImageSize[] = ['thumbnail', 'preview', 'original'];
/** Smallest to largest — index order is the comparison. */
const SIZE_ORDER: ImageSize[] = ['thumbnail', 'preview', 'original'];
/** Map a requested pixel width to the best Immich size tier. */
export function widthToSize(w: number): ImageSize {
if (w <= 250) return 'thumbnail';
if (w <= 1440) return 'preview';
return 'original';
}
function smaller(a: ImageSize, b: ImageSize): ImageSize {
return SIZE_ORDER.indexOf(a) <= SIZE_ORDER.indexOf(b) ? a : b;
}
/**
* When both parameters are present, take the **smaller** tier.
*
* `?size=` is a ceiling, not a demand: a width may lower the tier but must never
* raise it. Letting width win outright would be actively harmful — next/image
* emits widths up to 3840, and widthToSize(1920) is 'original', so every large
* display would download full-size originals instead of previews.
*
* Previously `?size=` won unconditionally, which made this function unreachable
* for any URL the app generates, since lib/urls.ts always writes `?size=`.
*/
export function resolveImageSize(sizeParam: string | null, widthParam: string | null): ImageSize {
const explicit =
sizeParam && VALID_SIZES.includes(sizeParam as ImageSize) ? (sizeParam as ImageSize) : null;
const w = widthParam ? parseInt(widthParam, 10) : NaN;
const fromWidth = !isNaN(w) && w > 0 ? widthToSize(w) : null;
if (explicit && fromWidth) return smaller(explicit, fromWidth);
return explicit ?? fromWidth ?? 'preview';
}

View File

@@ -57,6 +57,53 @@ export interface ImmichExifInfo {
export type ImageSize = 'thumbnail' | 'preview' | 'original'; export type ImageSize = 'thumbnail' | 'preview' | 'original';
/**
* Thrown when Immich could not answer: transport failure, an error status, or
* a non-JSON body where JSON was requested.
*
* This is deliberately distinct from a `null` return, which means Immich *did*
* answer and said the resource does not exist. Conflating the two made every
* album URL render a hard 404 while Immich was down — including albums that
* exist — because the page calls `notFound()` on a null album. Only 404/410
* are treated as "gone"; everything else is an outage and must surface as one.
*/
/**
* Cache sentinel for "Immich answered, and the resource does not exist".
*
* The cache cannot tell a miss from a stored null — both read back as null — so
* absence is recorded as a distinct object identity instead.
*
* Only definitive 404/410 answers are stored. An outage throws
* `ImmichUnavailableError` and is never cached: pinning one would keep the
* gallery broken long after Immich recovered.
*
* Stored under the normal `cacheTtl` rather than a shorter negative TTL. A 404
* from Immich is as authoritative as a 200, and both invalidation paths
* (the Immich webhook and the admin panel's save/reload) clear it immediately —
* so a corrected asset ID takes effect at once rather than waiting out a TTL.
*/
const MISSING = Object.freeze({ __immichMissing: true });
type Missing = typeof MISSING;
/**
* `AbortSignal.timeout()` rejects with a `TimeoutError`; an explicit
* `controller.abort()` rejects with an `AbortError`. Both mean we gave up
* waiting, and both arrive as a plain DOMException.
*/
function isTimeout(error: unknown): boolean {
return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');
}
export class ImmichUnavailableError extends Error {
readonly status?: number;
constructor(message: string, status?: number) {
super(message);
this.name = 'ImmichUnavailableError';
this.status = status;
}
}
/** Enriched subpage with album metadata (for rendering cards). */ /** Enriched subpage with album metadata (for rendering cards). */
export interface SubpageSummary { export interface SubpageSummary {
name: string; name: string;
@@ -84,8 +131,10 @@ class ImmichClient {
if (this.config.needsSetup) return null; if (this.config.needsSetup) return null;
const url = `${this.config.immich.apiUrl}${endpoint}`; const url = `${this.config.immich.apiUrl}${endpoint}`;
let res: Response;
try { try {
const res = await fetch(url, { res = await fetch(url, {
method: body === undefined ? 'GET' : 'POST', method: body === undefined ? 'GET' : 'POST',
headers: { headers: {
'x-api-key': this.config.immich.apiKey, 'x-api-key': this.config.immich.apiKey,
@@ -93,22 +142,55 @@ class ImmichClient {
...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
}, },
...(body === undefined ? {} : { body: JSON.stringify(body) }), ...(body === undefined ? {} : { body: JSON.stringify(body) }),
// JSON payloads are small, so one budget can cover the whole exchange.
// Without it the only ceiling is undici's default, measured in minutes.
signal: AbortSignal.timeout(this.config.immichTimeoutMs),
}); });
if (!res.ok) {
console.error(`[Immich] ${res.status} ${res.statusText} for ${endpoint}`);
return null;
}
const contentType = res.headers.get('Content-Type') || '';
if (contentType.includes('application/json')) {
return (await res.json()) as T;
}
return null;
} catch (error) { } catch (error) {
console.error(`[Immich] Failed to reach ${url}:`, error); console.error(`[Immich] Failed to reach ${url}:`, error);
throw new ImmichUnavailableError(
isTimeout(error)
? `Immich did not respond within ${this.config.immichTimeoutMs}ms for ${endpoint}`
: `Cannot reach Immich for ${endpoint}`,
);
}
if (!res.ok) {
console.error(`[Immich] ${res.status} ${res.statusText} for ${endpoint}`);
// Only "gone" means gone. A 5xx, a rate limit, or a rejected API key all
// mean Immich cannot serve us right now — rendering those as a missing
// album would tell visitors and crawlers the content no longer exists.
if (res.status !== 404 && res.status !== 410) {
throw new ImmichUnavailableError(
`Immich returned ${res.status} ${res.statusText} for ${endpoint}`,
res.status,
);
}
return null; return null;
} }
const contentType = res.headers.get('Content-Type') || '';
if (!contentType.includes('application/json')) {
// We always send Accept: application/json. Anything else is a gateway or
// proxy error page, not a valid answer about the resource.
throw new ImmichUnavailableError(
`Immich returned non-JSON (${contentType || 'no Content-Type'}) for ${endpoint}`,
);
}
try {
return (await res.json()) as T;
} catch (error) {
// The timeout also covers the body read, so an abort can surface here.
if (isTimeout(error)) {
console.error(`[Immich] Timed out reading ${url}`);
throw new ImmichUnavailableError(
`Immich did not respond within ${this.config.immichTimeoutMs}ms for ${endpoint}`,
);
}
console.error(`[Immich] Malformed JSON from ${url}:`, error);
throw new ImmichUnavailableError(`Immich returned malformed JSON for ${endpoint}`);
}
} }
/** /**
@@ -129,6 +211,14 @@ class ImmichClient {
const endpoint = `/assets/${encodeURIComponent(assetId)}/video/playback`; const endpoint = `/assets/${encodeURIComponent(assetId)}/video/playback`;
const url = `${this.config.immich.apiUrl}${endpoint}`; const url = `${this.config.immich.apiUrl}${endpoint}`;
// Bound the wait for response *headers* only. The `finally` clears the timer
// the moment they arrive, so the body may then stream for as long as it
// needs — a whole-request timeout would truncate playback mid-video and
// break seeking, since every range request would restart the clock.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.config.immichTimeoutMs);
try { try {
const headers: Record<string, string> = { const headers: Record<string, string> = {
'x-api-key': this.config.immich.apiKey, 'x-api-key': this.config.immich.apiKey,
@@ -137,13 +227,23 @@ class ImmichClient {
headers['Range'] = rangeHeader; headers['Range'] = rangeHeader;
} }
const res = await fetch(url, { headers }); const res = await fetch(url, { headers, signal: controller.signal });
if ((!res.ok && res.status !== 206) || !res.body) { if (!res.ok && res.status !== 206) {
console.error(`[Immich] Failed to stream video ${assetId}: ${res.status}`); console.error(`[Immich] Failed to stream video ${assetId}: ${res.status}`);
if (res.status !== 404 && res.status !== 410) {
throw new ImmichUnavailableError(
`Immich returned ${res.status} streaming video ${assetId}`,
res.status,
);
}
return null; return null;
} }
if (!res.body) {
throw new ImmichUnavailableError(`Immich returned an empty body for video ${assetId}`);
}
return { return {
stream: res.body, stream: res.body,
contentType: res.headers.get('Content-Type') || 'video/mp4', contentType: res.headers.get('Content-Type') || 'video/mp4',
@@ -152,8 +252,20 @@ class ImmichClient {
status: res.status === 206 ? 206 : 200, status: res.status === 206 ? 206 : 200,
}; };
} catch (error) { } catch (error) {
console.error(`[Immich] Video stream error for ${assetId}:`, error); if (error instanceof ImmichUnavailableError) throw error;
return null; console.error(
isTimeout(error)
? `[Immich] Video ${assetId} did not respond within ${this.config.immichTimeoutMs}ms`
: `[Immich] Video stream error for ${assetId}:`,
error,
);
throw new ImmichUnavailableError(
isTimeout(error)
? `Immich did not respond within ${this.config.immichTimeoutMs}ms for video ${assetId}`
: `Cannot reach Immich to stream video ${assetId}`,
);
} finally {
clearTimeout(timer);
} }
} }
@@ -172,26 +284,55 @@ class ImmichClient {
: `/assets/${encodeURIComponent(assetId)}/thumbnail?size=${size}`; : `/assets/${encodeURIComponent(assetId)}/thumbnail?size=${size}`;
const url = `${this.config.immich.apiUrl}${endpoint}`; const url = `${this.config.immich.apiUrl}${endpoint}`;
// Headers-only timeout, same reasoning as streamVideo: an original-size
// photo is legitimately slow to transfer and must not be capped.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.config.immichTimeoutMs);
try { try {
const res = await fetch(url, { const res = await fetch(url, {
headers: { headers: {
'x-api-key': this.config.immich.apiKey, 'x-api-key': this.config.immich.apiKey,
}, },
signal: controller.signal,
}); });
if (!res.ok || !res.body) { if (!res.ok) {
console.error(`[Immich] Failed to stream ${assetId}: ${res.status}`); console.error(`[Immich] Failed to stream ${assetId}: ${res.status}`);
if (res.status !== 404 && res.status !== 410) {
throw new ImmichUnavailableError(
`Immich returned ${res.status} streaming asset ${assetId}`,
res.status,
);
}
return null; return null;
} }
if (!res.body) {
throw new ImmichUnavailableError(`Immich returned an empty body for asset ${assetId}`);
}
return { return {
stream: res.body, stream: res.body,
contentType: res.headers.get('Content-Type') || 'application/octet-stream', contentType: res.headers.get('Content-Type') || 'application/octet-stream',
contentLength: res.headers.get('Content-Length'), contentLength: res.headers.get('Content-Length'),
}; };
} catch (error) { } catch (error) {
console.error(`[Immich] Stream error for ${assetId}:`, error); if (error instanceof ImmichUnavailableError) throw error;
return null; console.error(
isTimeout(error)
? `[Immich] Asset ${assetId} did not respond within ${this.config.immichTimeoutMs}ms`
: `[Immich] Stream error for ${assetId}:`,
error,
);
throw new ImmichUnavailableError(
isTimeout(error)
? `Immich did not respond within ${this.config.immichTimeoutMs}ms for asset ${assetId}`
: `Cannot reach Immich to stream asset ${assetId}`,
);
} finally {
clearTimeout(timer);
} }
} }
@@ -377,8 +518,8 @@ class ImmichClient {
} }
const cacheKey = `album-${albumId}`; const cacheKey = `album-${albumId}`;
const cached = cache.get<ImmichAlbum>(cacheKey); const cached = cache.get<ImmichAlbum | Missing>(cacheKey);
if (cached) return cached; if (cached) return cached === MISSING ? null : (cached as ImmichAlbum);
if (this.pendingAlbumPromises.has(albumId)) { if (this.pendingAlbumPromises.has(albumId)) {
return this.pendingAlbumPromises.get(albumId)!; return this.pendingAlbumPromises.get(albumId)!;
@@ -392,7 +533,10 @@ class ImmichClient {
this.request<ImmichAlbum>(`/albums/${encodeURIComponent(albumId)}`), this.request<ImmichAlbum>(`/albums/${encodeURIComponent(albumId)}`),
this.fetchAlbumAssets(albumId), this.fetchAlbumAssets(albumId),
]); ]);
if (!album) return null; if (!album) {
cache.set(cacheKey, MISSING, this.config.cacheTtl);
return null;
}
// An album that Immich says has photos but returns none is almost // An album that Immich says has photos but returns none is almost
// always a server older than 3.0, where metadata search behaves // always a server older than 3.0, where metadata search behaves
@@ -464,8 +608,8 @@ class ImmichClient {
*/ */
async getAssetInfo(assetId: string): Promise<ImmichAsset | null> { async getAssetInfo(assetId: string): Promise<ImmichAsset | null> {
const cacheKey = `asset-${assetId}`; const cacheKey = `asset-${assetId}`;
const cached = cache.get<ImmichAsset>(cacheKey); const cached = cache.get<ImmichAsset | Missing>(cacheKey);
if (cached) return cached; if (cached) return cached === MISSING ? null : (cached as ImmichAsset);
// ⚡ Bolt: Deduplicate concurrent requests for the same asset ID. // ⚡ Bolt: Deduplicate concurrent requests for the same asset ID.
// If a request for this asset is already in flight (e.g. from Promise.all in a grid), // If a request for this asset is already in flight (e.g. from Promise.all in a grid),
@@ -477,7 +621,13 @@ class ImmichClient {
const promise = (async () => { const promise = (async () => {
try { try {
const asset = await this.request<ImmichAsset>(`/assets/${encodeURIComponent(assetId)}`); const asset = await this.request<ImmichAsset>(`/assets/${encodeURIComponent(assetId)}`);
if (!asset) return null; if (!asset) {
// The homepage looks up every gallery.yaml hero ID on each render
// (app/page.tsx), and those pages are force-dynamic — so a hero photo
// deleted from Immich otherwise costs an upstream 404 every time.
cache.set(cacheKey, MISSING, this.config.cacheTtl);
return null;
}
cache.set(cacheKey, asset, this.config.cacheTtl); cache.set(cacheKey, asset, this.config.cacheTtl);
return asset; return asset;
@@ -514,8 +664,14 @@ class ImmichClient {
* Check if the Immich server is reachable. * Check if the Immich server is reachable.
*/ */
async ping(): Promise<boolean> { async ping(): Promise<boolean> {
const res = await this.request<{ res: string }>('/server/ping'); try {
return !!res; const res = await this.request<{ res: string }>('/server/ping');
return !!res;
} catch {
// "Is Immich reachable?" — unreachable is the answer, not an exception.
// Both callers (/api/health, /api/admin/status) render this as a status.
return false;
}
} }
} }

View File

@@ -15,6 +15,39 @@ import { getConfig } from './config';
/** Bucket key used when the client cannot be identified with any confidence. */ /** Bucket key used when the client cannot be identified with any confidence. */
const UNIDENTIFIED = 'unknown'; const UNIDENTIFIED = 'unknown';
let warnedUnidentified = false;
/**
* Falling back to the shared bucket is the *correct* behaviour — the
* alternative is trusting a spoofable header — but it is silent, and silence is
* the problem. Every unidentified request shares one bucket per endpoint, and
* this is an image proxy: a single 50-photo grid issues ~50 `/api/image`
* requests, so the default 1500 rpm is collectively spent by roughly 30 page
* loads a minute. Visitors then see 429s with nothing in the log pointing at
* the proxy configuration that caused it.
*
* Warn once per process: enough to diagnose, not enough to flood the log.
*/
function unidentified(hops: number, detail: string): string {
if (!warnedUnidentified) {
warnedUnidentified = true;
console.warn(
`\n⚠️ Rate limiting cannot identify clients: ${detail}\n` +
` TRUSTED_PROXY_HOPS is ${hops}, so the client IP is read ${hops} entr${hops === 1 ? 'y' : 'ies'} from the\n` +
` right of X-Forwarded-For. Unidentified requests all share ONE bucket per\n` +
` endpoint, which an image proxy exhausts quickly — expect 429s for everyone.\n` +
` Set TRUSTED_PROXY_HOPS to the number of proxies actually in front of the app\n` +
` (nginx/Traefik/Caddy = 1; add 1 for each additional layer, e.g. Cloudflare = 2).\n`,
);
}
return UNIDENTIFIED;
}
/** Test seam: the warning is once-per-process, which tests need to re-arm. */
export function __resetProxyWarningForTests(): void {
warnedUnidentified = false;
}
/** /**
* Resolve the client IP to use as a rate-limit bucket key. * Resolve the client IP to use as a rate-limit bucket key.
* *
@@ -52,13 +85,26 @@ export function getClientIp(request: NextRequest): string {
.filter(Boolean); .filter(Boolean);
// Chain shorter than the configured hop count means the request did not // Chain shorter than the configured hop count means the request did not
// traverse the full proxy chain — do not fall back to a spoofable entry. // traverse the full proxy chain — do not fall back to a spoofable entry.
return chain[chain.length - hops] ?? UNIDENTIFIED; const ip = chain[chain.length - hops];
if (ip) return ip;
return unidentified(
hops,
`X-Forwarded-For carries ${chain.length} entr${chain.length === 1 ? 'y' : 'ies'}, ` +
`fewer than the ${hops} configured hop${hops === 1 ? '' : 's'}`,
);
} }
// nginx's `proxy_set_header X-Real-IP $remote_addr` overwrites rather than // nginx's `proxy_set_header X-Real-IP $remote_addr` overwrites rather than
// appends, so it is trustworthy — but only for a single hop, since an outer // appends, so it is trustworthy — but only for a single hop, since an outer
// proxy would leave an inner proxy's value in place. // proxy would leave an inner proxy's value in place.
if (xRealIp && hops === 1) return xRealIp; if (xRealIp && hops === 1) return xRealIp;
return UNIDENTIFIED;
return unidentified(
hops,
xRealIp
? 'no X-Forwarded-For header, and X-Real-IP is only trustworthy at a single hop'
: 'neither X-Forwarded-For nor X-Real-IP was present',
);
} }
// No proxy declared: headers are best-effort only. This still separates // No proxy declared: headers are best-effort only. This still separates
@@ -67,6 +113,18 @@ export function getClientIp(request: NextRequest): string {
return xRealIp ?? xForwardedFor?.split(',')[0].trim() ?? UNIDENTIFIED; return xRealIp ?? xForwardedFor?.split(',')[0].trim() ?? UNIDENTIFIED;
} }
/**
* Seconds a client should wait before retrying, for the `Retry-After` header.
*
* Floored at 1. The obvious `Math.ceil((resetAt - Date.now()) / 1000)` yields 0
* — or a negative number — when the window is on the point of expiring, and
* `Retry-After: 0` tells the client to retry immediately, which is the opposite
* of what a 429 is for. A negative value is not valid HTTP at all.
*/
export function retryAfterSeconds(resetAt: number): number {
return Math.max(1, Math.ceil((resetAt - Date.now()) / 1000));
}
interface RateLimitEntry { interface RateLimitEntry {
count: number; count: number;
expiresAt: number; expiresAt: number;

View File

@@ -4,9 +4,23 @@
*/ */
import { encodeAssetId } from './tokens'; import { encodeAssetId } from './tokens';
import { env } from './env';
import { thumbHashToBlurDataUrl, thumbHashToDominantHex } from './thumbhash'; import { thumbHashToBlurDataUrl, thumbHashToDominantHex } from './thumbhash';
import type { ImmichAsset } from './immich'; import type { ImmichAsset } from './immich';
/**
* Optional cache-buster, appended to every image and video URL.
*
* These responses are served `immutable` for a year, so the browser never
* revalidates and the ETag is never consulted — the URL is the only thing that
* can invalidate a browser cache. Setting IMAGE_CACHE_VERSION changes all of
* them at once, which is what you want after Immich regenerates thumbnails or a
* photo is rotated: the asset ID does not change, so nothing else would.
*
* Empty by default — the returned URLs are then byte-identical to before.
*/
const cacheBuster = env.IMAGE_CACHE_VERSION ? `&v=${env.IMAGE_CACHE_VERSION}` : '';
/** /**
* Generate a public image proxy URL for an asset. * Generate a public image proxy URL for an asset.
*/ */
@@ -14,7 +28,7 @@ export function imageUrl(
assetId: string, assetId: string,
size: 'thumbnail' | 'preview' | 'original' = 'preview', size: 'thumbnail' | 'preview' | 'original' = 'preview',
): string { ): string {
return `/api/image/${encodeAssetId(assetId)}?size=${size}`; return `/api/image/${encodeAssetId(assetId)}?size=${size}${cacheBuster}`;
} }
/** /**
@@ -28,7 +42,9 @@ export function exifUrl(assetId: string): string {
* Generate a public video proxy URL for an asset. * Generate a public video proxy URL for an asset.
*/ */
export function videoUrl(assetId: string): string { export function videoUrl(assetId: string): string {
return `/api/video/${encodeAssetId(assetId)}`; // No `size` here, so the buster is the only query parameter.
const v = cacheBuster ? `?${cacheBuster.slice(1)}` : '';
return `/api/video/${encodeAssetId(assetId)}${v}`;
} }
/** /**

View File

@@ -2,10 +2,10 @@ import type { NextConfig } from 'next';
/** /**
* Static security headers, applied to every response including /api and static * Static security headers, applied to every response including /api and static
* assets, which middleware does not cover. * assets, which the proxy does not cover.
* *
* The Content-Security-Policy is deliberately NOT set here: it needs a * The Content-Security-Policy is deliberately NOT set here: it needs a
* per-request nonce and is owned exclusively by middleware.ts. Keeping the two * per-request nonce and is owned exclusively by proxy.ts. Keeping the two
* layers disjoint avoids emitting the same header twice with conflicting * layers disjoint avoids emitting the same header twice with conflicting
* values, which browsers may resolve by ignoring the header altogether. * values, which browsers may resolve by ignoring the header altogether.
*/ */

View File

@@ -1,7 +1,7 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server'; import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64'); const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
// Define CSP directives // Define CSP directives