Risk-based robot check with server-issued photo keys
The main page and direct photo links open without a prompt. Each photo's pool is sealed with its own key, handed out by POST /k (served by the daemon in serve and export mode). The hold-and-solve card appears only for low-entropy clicks into a collection, too many low-entropy landings from one IP, or more than photo_limit photos per window, with escalating proof-of-work and a 429 cap. Build ids now sort chronologically within the same second. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
f5152fb709
commit
c87aad0254
31 files changed
+2021
-414
No files matched your search
+43
-16
@@ -2,7 +2,7 @@
|
||||
|
||||
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders from disk, cuts every photo into tiles of at most 512 px (at least 3 × 3 per level) at several resolutions, and publishes a fully static, Lucio-branded site that a browser stitches back together on a canvas. No editing, comments, likes, themes, templating or camera RAW support.
|
||||
|
||||
Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling on by default, decoy tiles and a sealed tile map behind a one-time robot check, JPEGs not listed in album.json are hidden.
|
||||
Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling on by default, decoy tiles and per-photo sealed tile maps whose keys a risk-based key endpoint hands out (covers always open, a press-and-hold check only for visitors who look automated), JPEGs not listed in album.json are hidden.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -11,7 +11,7 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor (
|
||||
-> serve mode (built-in HTTP) or export mode (folder for Caddy/nginx) -> Cloudflare Tunnel + cache -> browser canvas stitches visible tiles
|
||||
```
|
||||
|
||||
- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build.
|
||||
- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching, and with `gate = "server"` listens on `server.listen` for `/k` only; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build.
|
||||
- Tiling with libvips CLI (`vips`), installed by `apt install libvips-tools`. Support libvips 8.12 (Ubuntu 22.04) and 8.15 (Ubuntu 24.04): metadata stripping is `strip` on 8.12 and `keep=none` on 8.15+.
|
||||
- Front-end: plain TypeScript, no framework, bundled with esbuild, embedded in the binary with `go:embed`. Fixed Lucio brand.
|
||||
- Speed and memory matter: photos are processed in parallel by a bounded worker pool; hashing, EXIF reading and tile renaming run concurrently; the browser fetches tiles concurrently and decodes off the main thread.
|
||||
@@ -58,23 +58,39 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor (
|
||||
5. Seed: a 48 px (long edge) WebP, kept in the per-photo record and published only inside the sealed payload.
|
||||
6. No resolution cap: the full-resolution level is stored; the loader never fetches beyond screen size × max_dpr.
|
||||
7. Tile paths: `/t/<photo-hash>/<tile-id>.webp`. photo-hash = first 16 hex of SHA-256 over the original bytes + a processing-settings fingerprint (which includes `min_grid` and `scramble_cells`). tile-id = first 16 hex of HMAC-SHA-256(site key, photo-hash|level|x|y). The site key is generated once and kept in the state folder. Each folder also holds decoys (below), so on disk and in developer tools a folder is an unordered pile of patches from many photos.
|
||||
8. Album manifest `/a/<slug>/manifest.<build>.json`: layout only. Per photo width, height, per level width, height, tile size, cols, rows (and overlap when not 0), caption, title, alt, EXIF, slides, plus the build's `gate` record. Covers are pyramids too and are described in `/index.<build>.json`. Tile ids, byte sizes, the seed and the scramble seed are not in it.
|
||||
8. Album manifest `/a/<slug>/manifest.<build>.json`: layout only. Per photo width, height, per level width, height, tile size, cols, rows (and overlap when not 0), caption, title, alt, EXIF, slides, plus the build's `gate` record `{build, mode, cover, min_entropy}` (and `keys` when the gate is off). Covers are pyramids too and are described in `/index.<build>.json`. Tile ids, byte sizes, the seed and the scramble seed are not in it.
|
||||
|
||||
Incremental: a photo is reprocessed only when its photo-hash is new. Each build writes `builds/<id>/` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references, and inside live folders delete files no kept build's `.refs` lists. Write everything to temporary names and rename, so readers never see partial files (pool files are written straight into the unpublished stage folder).
|
||||
Incremental: a photo is reprocessed only when its photo-hash is new. Build ids are `YYYYMMDD-HHMMSS-micro-random` and always sort after every existing build, even within one second (keep_builds and the key endpoint rely on it). Each build writes `builds/<id>/` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, `.secret`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references, and inside live folders delete files no kept build's `.refs` lists. Write everything to temporary names and rename, so readers never see partial files (pool files are written straight into the unpublished stage folder).
|
||||
|
||||
Storage: about 1.33× the top level, roughly 6–10 MB of tiles per Z8 photo. Decoys are hard links and cost directory entries, not bytes; small low-level tiles cost some filesystem block overhead.
|
||||
|
||||
## Protection step (per build, after all photos are processed)
|
||||
|
||||
1. Gate: random 16-byte salt and random n < 2^`pow_bits`. Key s = SHA-256("luphoto-key" | salt | n as 4 bytes big-endian). Published in the index and every manifest: `{build, salt, bits, check}` with check = first 16 bytes of SHA-256("luphoto-check" | salt | n). With `gate = false`: `{build, key}` and no robot check, same code path.
|
||||
1. Keys: a random 32-byte build secret, written to `builds/<id>/.secret` (0600; dotfiles are never served). Photo key = HMAC-SHA-256(secret, "photo|" + photo-hash); cover key = HMAC-SHA-256(secret, "cover|"), one per build, public. The index and every manifest carry `{build, mode, cover, min_entropy}`; with `gate = "off"` each manifest also carries `keys: {hash: hex}` for its photos, so a purely static host works with the same code path.
|
||||
2. Decoys: all live pyramids (photos and covers of every published album, carried albums included) are indexed by tile size; each pyramid's primary album is the first album, in index order, that uses it. For each level with R real tiles, `decoys` × R slots are filled from the bucket whose tile size is closest to the level's, taking candidates from other albums first, then other photos of the same album, then (single-pyramid site only) the photo itself. A slot's source is the next tile on a ring ordered by tile id after a target drawn from a PRNG keyed by HMAC(site key, "pick"|hash|level), skipping ineligible or already used tiles, so selections are stable while the site does not change. Decoy name = first 16 hex of HMAC-SHA-256(site key, "decoy"|photo-hash|level|slot|source tile id). The file is a hard link to the source tile (a copy if linking fails); names already present in the folder are reused (one `ReadDir` per folder).
|
||||
3. Pool: per level the real ids and decoy names, shuffled with a PRNG keyed by HMAC(site key, "pool"|hash|level), written as one string of 16-hex ids.
|
||||
4. Seal: plaintext = "luphoto-sealed-1" (16 bytes) + JSON `{seed, scramble, levels: [{map, bytes}]}` where `map` turns a row-major grid index into a pool index. Ciphertext = plaintext XOR keystream, block i = SHA-256(s | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64.
|
||||
4. Seal: plaintext = "luphoto-sealed-1" (16 bytes) + JSON `{seed, scramble, levels: [{map, bytes}]}` where `map` turns a row-major grid index into a pool index. Ciphertext = plaintext XOR keystream, block i = SHA-256(key | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64; key = the photo key, or the cover key for covers.
|
||||
5. `/a/<slug>/p/<hash>.<build>.json` = `{levels: [pool strings], sealed}` for every photo and the cover of each album; build-named like the manifests, so a new build never pairs with a cached pool. `builds/<id>/.refs` lists every pool id per folder (8-byte binary) for the cleanup.
|
||||
|
||||
## Key endpoint `POST /k`
|
||||
|
||||
Served by the daemon in serve mode, and in export mode on `server.listen` (nothing else is served there; the web server proxies `/k`). `Cache-Control: no-store`, JSON, body at most 4 KB, POST only. Rejected with 403 unless `Origin` (or `Referer` when `Origin` is absent) names the request's host, `base_url`'s host or a `hotlink_allow` host. 404 when the gate is off.
|
||||
|
||||
- Request: `{build, album, photos: [≤ 8 photo hashes], context: "nav" | "land", entropy: 0..100, pass?, page?, challenge?: {token, nonce}}`. Unknown or GC'd build, unknown album, a bad context or entropy: 400. Hashes not in that album of that build are dropped. Builds are found by their `.secret`, cached in memory, re-read after every build the daemon runs and at most every 2 s on a miss (so builds made by a separate `luphoto build` are found too); album membership is read from the build's manifest once per album.
|
||||
- Responses: `{keys: {hash: hex}, pass?, page?, stale?}`; `{challenge: {token, bits}, stale?}`; 429 `{error}` with `Retry-After`. `stale: true` means the pass sent is not valid for this address and should be dropped.
|
||||
- Client address: the TCP peer, unless the peer is in `trusted_proxies`, then the right-most address in `client_ip_header` that is not itself a trusted proxy. Bucket: IPv4 /32, IPv6 /64.
|
||||
- State per bucket, in memory: 16 slots of `{photos, low-entropy landings, challenges solved}` over `window` (one slot per minute up to 16 minutes, wider beyond), plus the slot and count at the last solve. 16 shards, each a map into a slice with an intrusive LRU list, 200 000 buckets in all; the oldest bucket is reused when full. No allocation per request beyond a new bucket.
|
||||
- Tokens: 24 bytes, base64url (32 characters): 4-byte time, 1 byte, 19 bytes of HMAC-SHA-256 over kind | bucket | the first 5 bytes, keyed by the site key. Challenge token: issue time and bits; valid 5 minutes, once (a ring of the last 32 768 solved tokens). Pass: expiry and version. Page token: expiry 30 minutes ahead, the MAC also covering build and album; returned with every grant that did not carry a valid one for the same album.
|
||||
- Proof of work: SHA-256(token as 32 ASCII bytes | nonce as 8 bytes big-endian) has at least `bits` leading zero bits. One 64-byte block, so the browser precomputes the state after the 8 constant words.
|
||||
- Decision, in order:
|
||||
1. More than 4 × `photo_limit` photos unlocked in the window: 429.
|
||||
2. A valid, unused, solved challenge: reset the bucket's landing count and restart its photo count, count one solve, grant, and issue a pass for `pass_ttl`.
|
||||
3. Challenge, with `pow_bits` + min(6, solves in the window) bits, when photos unlocked since the last solve in the window exceed `photo_limit`; or, without a valid pass or page token for this album, when the context is `nav` and entropy < `min_entropy`, or when the window holds `landing_limit` low-entropy landings.
|
||||
4. Grant keys for the requested photos and count them; a `land` request without a pass or page token and with entropy < `min_entropy` counts as a low-entropy landing, so each page load counts once.
|
||||
|
||||
## Loading in the browser
|
||||
|
||||
0. Gate: if the gate is on and `localStorage` has no pass for this build, the robot-check card is shown at once and a Web Worker (the tile worker script, a separate instance) brute-forces n with an allocation-free SHA-256 (midstate of the first 7 rounds and the constant schedule words precomputed). Each photo's pool file is fetched when the photo or cover is near. Until unlocked, or when a pool cannot be opened, the photo shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). After unlocking, pools are decrypted lazily on the main thread (a few hundred SHA-256 blocks per photo), the seed fades in over the jumble, and the real tiles follow as below.
|
||||
0. Keys. Covers open with the public cover key at once. On an album page the viewer asks `/k` for the current photo and its neighbours (`context` "nav" when the page was opened by a guarded click within the last 30 s, else "land"; the session's interaction score; the stored pass) in one request of up to 8 (one behind to six ahead), and waits for it; it asks again, with one more batch of up to 8 looking at most nine ahead, only when a photo within one behind or three ahead of the current one has no key. At most one request is in flight and nothing is queued beyond the latest batch. The page token from the first grant is kept in memory and sent with every later request; a returned pass goes to `localStorage`; a `stale` one is dropped. If the answer is a challenge, the hold card is shown over the album while a Web Worker (the tile worker script, a separate instance) solves it with an allocation-free SHA-256; after the hold and the solution the request is repeated with the answer. Each photo's pool file is fetched when the photo is near. While its key is on the way the photo draws nothing for up to 400 ms; after that, or while a challenge is up, it shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). When the key arrives, the pool is decrypted on the main thread (a few hundred SHA-256 blocks), the seed fades in over the jumble, and the real tiles follow as below. With the gate off the keys come from the manifest and `/k` is never called.
|
||||
1. Seed: draw the seed scaled and blurred.
|
||||
2. Needed level: smallest level whose width ≥ displayed width × min(devicePixelRatio, max_dpr).
|
||||
3. Probe: fetch 1–2 tiles of the level about 1/8 of the needed one; measure throughput; blend with earlier measurements kept in sessionStorage.
|
||||
@@ -96,19 +112,25 @@ Lucio brand (source of truth: ../LUCIO_ip): graphite #111114 ground, paper #F3F1
|
||||
|
||||
## Discouraging saves
|
||||
|
||||
No `<img>` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names, at least 3 × 3 tiles per level, decoys and sealed maps behind the robot check (above). `scramble_cells` (on by default): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tiles under two cells wide or high are left alone; tile overlap is 0 when on); the scramble seed travels only inside the sealed payload, and the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed. `robots.txt` disallows `/t/` and `/a/*/p/`.
|
||||
No `<img>` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names, at least 3 × 3 tiles per level, decoys and per-photo sealed maps whose keys come from `/k` (above). `scramble_cells` (on by default): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tiles under two cells wide or high are left alone; tile overlap is 0 when on); the scramble seed travels only inside the sealed payload, and the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed. `robots.txt` disallows `/t/` and `/a/*/p/`.
|
||||
|
||||
Robot check card (index and album pages, only without a pass for the current build): graphite-2 card, mono eyebrow "Photos · Lucio", the line "Press and hold to see the photos" in Bricolage Grotesque, and an 88 px round button with a beam progress ring. Holding for 900 ms (pointer, or Space/Enter while focused) completes it; releasing early resets the ring. If the worker is still searching, the ring turns indeterminate until it finishes. The rest of the page is `inert` while the card is up; focus starts on the button and returns to the page afterwards. The pass `{build, s}` is kept in `localStorage` (memory if storage is blocked); a pass that fails to open a pool is dropped and the card comes back. Reduced motion: no spin, no fade.
|
||||
Interaction score: passive listeners on every page count mouse path length, direction changes over 30° between 8 px segments, distinct 8 px cells (a 4096-bit hashed set), touch gestures that move (or that the browser turns into a pan), wheel and scroll events (at most one per 100 ms) and key presses, trusted events only, with no allocation per event. Score = min(25, path ÷ 120) + min(35, 2.5 × turns) + min(20, cells ÷ 6) + min(45, 8 × gestures) + min(15, 1.5 × scrolls) + min(20, 2 × keys), capped at 100, kept for the tab's session in `sessionStorage` (memory if blocked).
|
||||
|
||||
Limits: this raises the cost of bulk downloading; it cannot stop a scraper that drives a real browser or reimplements the client, and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared.
|
||||
Guarded links: the index strips and the album end card's next-album link. A plain click with a score ≥ `min_entropy`, or with a stored pass, navigates normally and leaves a "nav" flag (slug and time) in `sessionStorage`. Otherwise the click is held back, the card is shown on the current page, a challenge for that album is requested at once (`photos: []`, context "nav") and solved while the visitor holds; then the pass is stored and the page navigates with the flag. Esc closes the card on these pages. Modified clicks (new tab) are not guarded; the new tab lands as "land".
|
||||
|
||||
Hold card: graphite-2 card, mono eyebrow "Photos · Lucio", the line "Press and hold to see the photos" in Bricolage Grotesque, and an 88 px round button with a beam progress ring. Holding for 900 ms (pointer, or Space/Enter while focused) completes it; releasing early resets the ring. Then the ring turns indeterminate until the worker has a solution and the server has answered. A pointer that cannot be captured still works. The rest of the page is `inert` while the card is up; focus starts on the button and returns to the page afterwards. The pass is kept in `localStorage` (memory if storage is blocked). It is never shown on load of the index. Reduced motion: no spin, no fade.
|
||||
|
||||
Limits: this raises the cost of bulk downloading; it cannot stop a scraper that drives a real browser or reimplements the client. The score is self-reported, so a bot that fakes it is bounded only by `photo_limit` per address, the escalating proof of work and the 429 cap; and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared.
|
||||
|
||||
## Config `/etc/luphoto/config.toml`
|
||||
|
||||
```toml
|
||||
[server]
|
||||
mode = "export"
|
||||
listen = "127.0.0.1:8080"
|
||||
base_url = "https://photos.luciochen.com"
|
||||
mode = "export"
|
||||
listen = "127.0.0.1:8080"
|
||||
base_url = "https://photos.luciochen.com"
|
||||
trusted_proxies = ["127.0.0.1/32", "::1/128"]
|
||||
client_ip_header = "X-Forwarded-For"
|
||||
|
||||
[paths]
|
||||
albums = "/srv/luphoto/albums"
|
||||
@@ -141,8 +163,13 @@ keep_builds = 3
|
||||
block_context_menu = true
|
||||
hotlink_allow = ["photos.luciochen.com"]
|
||||
decoys = 4
|
||||
gate = true
|
||||
gate = "server"
|
||||
pow_bits = 20
|
||||
photo_limit = 400
|
||||
min_entropy = 20
|
||||
landing_limit = 5
|
||||
window = "10m"
|
||||
pass_ttl = "12h"
|
||||
```
|
||||
|
||||
Defaults when a path is missing: running as root or under systemd uses `/var/lib/luphoto/site` and `/var/cache/luphoto`; otherwise `$XDG_DATA_HOME/luphoto/site` and `$XDG_CACHE_HOME/luphoto` (Go `os.UserCacheDir` equivalents). The site key and the per-photo processing records live in the state folder (`state/`) next to the output. SIGHUP re-reads the config and rebuilds. The watcher ignores `.part`, `.tmp`, dotfiles and rsync temp names.
|
||||
@@ -151,8 +178,8 @@ Defaults when a path is missing: running as root or under systemd uses `/var/lib
|
||||
|
||||
- `.deb` via nfpm: binary, `/etc/luphoto/config.toml`, systemd unit, `luphoto` user, `/srv/luphoto/albums`. Depends on `libvips-tools`. Ubuntu 22.04/24.04, Debian 12; other distros: tarball + unit file.
|
||||
- systemd: read-only albums, read-write output and cache only, NoNewPrivileges, ProtectSystem=strict.
|
||||
- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging.
|
||||
- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided.
|
||||
- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging; `/k` bypasses the cache. Set `client_ip_header = "CF-Connecting-IP"` and keep the tunnel's source (loopback) in `trusted_proxies`.
|
||||
- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only, except `/k`, which is proxied to the daemon on `server.listen` with the client address in `X-Forwarded-For`. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided.
|
||||
|
||||
## Milestones
|
||||
|
||||
|
||||
Reference in new issue
Block a user