Files
Guoliang ChenandClaude Opus 5.5 4cdbd66fcf Sharper first view and smoke loader sign-off
The loader now measures throughput from whole tile batches, not just the
two probe tiles, and after a session settles inside its deadline it tops
up in the background: the needed level if the budget cut it short, then
one level above it on capable devices with a fast connection (drawn
downscaled), within time and memory caps and never under Save-Data.

The chop in the album end card and the page footer is replaced by the
LUCIO loader in smoke from lucioIP, falling back to the SVG loader
without WebGL. sync-brand.sh now copies lucio-loaders.js and defaults to
../lucioIP.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 01:47:44 -08:00

215 lines
18 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LuPhoto
LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into WebP tiles at several resolutions with libvips (at most 512 px, at least a 3 × 3 grid per level), and publishes a static site in which the browser stitches the visible tiles back together on a canvas. Covers are always open; photo tile maps are unlocked per photo by keys the daemon hands out at `/k`, with a press-and-hold check only for visitors who look automated; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md).
## Commands
```
luphoto [-config /etc/luphoto/config.toml] <command>
```
| Command | What it does |
|---|---|
| `build` | Process the albums once, publish a new build, exit. |
| `serve` | Build, watch the albums folder, rebuild after changes, and serve the site over HTTP on `server.listen`. |
| `export` | Build, watch and rebuild. Point Caddy or nginx at `<output>/current`. With `protection.gate = "server"` it also listens on `server.listen`, serving only the key endpoint `/k`, which the web server must proxy. |
| `run` | `serve` or `export`, whichever `server.mode` says. The systemd unit uses this. |
| `version` | Print the version. |
A missing config file means all defaults. `SIGHUP` re-reads the config and rebuilds (an invalid config is logged and the old one kept; a new `server.listen` restarts the listener). `SIGINT`/`SIGTERM` stop gracefully. Rebuilds never overlap; changes during a build cause one follow-up build.
## Album folders
```
/srv/luphoto/albums/
2026-10-iceland/
album.json
DSC_0001.jpg
PANO_0007.jpg
```
The folder name is the album slug (`/a/2026-10-iceland/`). Only JPEGs listed in `album.json` are processed and shown. An album whose `album.json` is broken is skipped and logged; if the previous build had it, that version stays live.
```json
{
"title": "Iceland, in October",
"subtitle": "冰岛 · 十月",
"date": "2026-10",
"order": 10,
"hidden": false,
"cover": { "photo": "PANO_0007.jpg", "crop": [0, 410, 8256, 2322] },
"collapsed_focus_y": 0.5,
"show_exif": true,
"photos": [
{ "file": "DSC_0001.jpg", "title": "Vík", "caption": "Black sand, *7 a.m.*", "alt": "A black sand beach" },
{ "file": "PANO_0007.jpg", "caption": "Two screens wide", "slides": 2 }
]
}
```
| Field | Type | Default | Meaning |
|---|---|---|---|
| `title` | string | folder name | Album title, sentence case. |
| `subtitle` | string | none | Second line, for example the Chinese title. |
| `date` | `YYYY`, `YYYY-MM` or `YYYY-MM-DD` | none | Shown as the eyebrow; sorts albums without `order`, newest first. |
| `order` | integer | none | Albums with `order` come first, ascending. |
| `hidden` | bool | `false` | Built and reachable by URL, but left off the index. |
| `cover.photo` | file name | first photo | Photo the 32:9 cover is cut from. Must be listed in `photos`. |
| `cover.crop` | `[x, y, w, h]` | none | Cover rectangle in pixels of the upright photo. |
| `cover.focus_y` | 0–1 | 0.5 | Without `crop`: a 32:9 band at full width centred at this height. |
| `collapsed_focus_y` | 0–1 | 0.5 | Which 32:6 band of the cover a closed index strip shows. |
| `show_exif` | bool | `true` | Put camera, lens, focal length, aperture, shutter, ISO and date into the manifest and caption line. GPS is never kept. |
| `photos[].file` | file name | required | A `.jpg`/`.jpeg` in the album folder. Order of the list is the viewing order. |
| `photos[].title` | string | none | Caption title. |
| `photos[].caption` | string | none | Plain text; `*emphasis*` and line breaks only. |
| `photos[].alt` | string | none | Text alternative for screen readers. |
| `photos[].slides` | integer ≥ 1 | 1 | Show a wide photo as N viewport-wide sections with a continuous pan. |
Unknown fields are errors, so typos are caught.
## Config
`/etc/luphoto/config.toml`; every key is optional. `packaging/config.toml` is the production file.
| Key | Default | Meaning |
|---|---|---|
| `server.mode` | `"export"` | What `luphoto run` does: `"serve"` or `"export"`. |
| `server.listen` | `"127.0.0.1:8080"` | Address of the built-in HTTP server. |
| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs; its host is also accepted as `Origin` on `/k`. |
| `server.trusted_proxies` | `["127.0.0.1/32", "::1/128"]` | CIDRs (or single addresses) of reverse proxies whose `client_ip_header` is believed. |
| `server.client_ip_header` | `"X-Forwarded-For"` | Header carrying the visitor's address, read only when the direct peer is in `trusted_proxies` (the right-most untrusted address wins). Behind a Cloudflare Tunnel use `"CF-Connecting-IP"`. Empty: always use the peer address. |
| `paths.albums` | `"/srv/luphoto/albums"` | Album folders. Read only. |
| `paths.output` | root or systemd: `/var/lib/luphoto/site`, else `$XDG_DATA_HOME/luphoto/site` | Builds, tiles, `current`. The site key and per-photo records go to `state/` next to it. |
| `paths.cache` | root or systemd: `/var/cache/luphoto`, else the user cache dir | Temporary vips files. |
| `images.tile_size` | `512` | Largest tile edge in pixels. Each level uses min(`tile_size`, short edge ÷ `min_grid`), at least 1 px. |
| `images.min_grid` | `3` | Minimum tile columns and rows per level (1–8). Levels whose short edge would drop below it are not made. Changing it reprocesses everything. |
| `images.overlap` | `1` | Tile overlap in pixels; 0 on levels whose tile is at most twice as wide, and always 0 while `scramble_cells` is on. |
| `images.format` | `"webp"` | `"webp"` or `"avif"` (AVIF needs a libheif AV1 encoder). |
| `images.quality` | `{ top = 90, mid = 88, low = 88 }` | Top two levels, levels above 1100 px, levels up to 1100 px. |
| `images.min_levels` | `6` | Minimum pyramid depth. |
| `images.seed_px` | `48` | Long edge of the blurred placeholder. |
| `images.tile_names` | `"hashed"` | Only `"hashed"` in v1. |
| `images.scramble_cells` | `true` | Shuffle the 64 px cells inside each tile with a per-photo key; the browser restores them when it decodes a tile. Tiles under two cells wide or high are left alone. Forces tile overlap 0. Changing it reprocesses everything. |
| `loading.budget_ms` | `3000` | Time budget per photo in the browser. |
| `loading.max_dpr` | `2.0` | Highest device pixel ratio the loader honours. |
| `loading.concurrency` | `6` | Parallel tile requests. |
| `build.watch` | `true` | Watch the albums folder in `serve` and `export`. |
| `build.debounce` | `"30s"` | Quiet time after the last change before rebuilding. |
| `build.workers` | `2` | Photos processed in parallel. vips threads per photo = CPUs ÷ workers. |
| `build.keep_builds` | `3` | Builds kept; tile folders and decoys no kept build uses are deleted. |
| `protection.block_context_menu` | `true` | Disable the context menu on photos. |
| `protection.hotlink_allow` | `["photos.luciochen.com"]` | Hosts allowed as `Referer` for `/t/*` and as `Origin` for `/k`; empty Referers on `/t/*` and the site's own host are always allowed. |
| `protection.decoys` | `4` | Decoy tiles per real tile in each photo folder (0–16); 0 turns decoys off. |
| `protection.gate` | `"server"` | `"server"`: photo keys come from the daemon's `/k`, with the risk checks below. `"off"`: every photo key is published in the album manifest and `/k` is never called (pure static hosting). The old `true`/`false` still read as `"server"`/`"off"`. |
| `protection.pow_bits` | `20` | Base proof-of-work size of a challenge (10–26); each extra bit doubles the average work. |
| `protection.photo_limit` | `400` | Photo keys one address may unlock per `window` before it is challenged again; more than 4 × this in a window is answered 429. |
| `protection.min_entropy` | `20` | Interaction score (0–100) below which a visitor counts as low-entropy. |
| `protection.landing_limit` | `5` | Low-entropy direct landings per address per `window` before every request without a pass is challenged (1–10000). |
| `protection.window` | `"10m"` | Sliding window of the per-address counters (1m–24h). |
| `protection.pass_ttl` | `"12h"` | Lifetime of the pass a solved challenge earns (1m–720h). |
The watcher ignores dotfiles (including rsync's `.name.XXXXXX` temp files), `*.part`, `*.tmp` and editor backups. vips runs at `nice +5` so processing does not starve the web server.
## Protection
Everything except the small key endpoint `/k` stays static files, so export mode, Caddy, nginx and Cloudflare caching of `/t/` keep working. What a build adds on top of hashed tile names:
- **Small tiles.** Every level of every photo and cover is cut into at least a 3 × 3 grid (`images.min_grid`), so no single file is a usable picture, not even the small levels.
- **Decoys.** Each photo folder `/t/<hash>/` also holds `protection.decoys` × as many decoy files as it has real tiles: hard links (copies if linking fails) to real tiles of other photos, from other albums first, with tile sizes as close as possible. A decoy name is an HMAC of the photo, level, slot and source tile, so a name never changes its bytes and `/t/` stays immutable. Decoys are chosen after all photos are processed; unchanged photos keep their decoys from build to build.
- **Sealed maps.** The album manifest and index carry only layout (sizes, tile grid, captions, EXIF). Which file sits where lives in one small JSON per photo and cover, `/a/<slug>/p/<hash>.<build>.json`, fetched when that photo is near: per level the shuffled pool of real and decoy ids, plus a `sealed` payload (the blurred seed, the cell-scramble seed, the grid→pool map and tile byte sizes) encrypted with a SHA-256 counter-mode keystream.
- **Keys.** Each build gets a random 32-byte secret in `builds/<id>/.secret` (mode 0600, never served). Every photo's pool is sealed with its own key, HMAC-SHA-256(secret, "photo|" + photo hash). Covers are sealed with one public cover key per build, HMAC(secret, "cover|"), published in the index JSON and every manifest, so the index and the next-album strip always draw without a check. With `gate = "off"` the manifest also lists every photo key.
- **Key endpoint.** The album page asks `POST /k` for the keys of the current photo and its neighbours, at most 8 per request: one request when the page loads, then one more only when the visitor moves past the photos it covers, never for photos far away. The first grant also returns a page token (30 minutes, bound to the address, build and album); later requests from that page send it, so one page load counts as at most one landing. The daemon answers it in serve mode and, in export mode, on `server.listen` (proxy `/k` there; it must never be cached). It accepts only requests whose `Origin` (or `Referer`) is the site's host, `server.base_url`'s host or a `hotlink_allow` host, for the current build or any kept build, and grants only hashes of the album named in the request.
- **When the prompt appears.** The main page never asks. Following a link to an album or straight to a photo (`/a/<slug>/#7`) does not ask either, as long as the address behaves. The press-and-hold card (0.9 s, while a Web Worker solves a proof of work) is shown when:
- a collection is opened from the index or the next-album card and the visitor's interaction score is below `min_entropy` and no pass is stored (the score counts mouse path, direction changes and distinct 8 px cells, touch gestures that move, scrolling and key presses, summed over the tab's session);
- an address has made `landing_limit` low-entropy landings (album page loads, a new tab or a reload each counting once, opened without a recent click from the site) within `window`, after which every request from it without a pass is challenged;
- an address has unlocked more than `photo_limit` photos since its last solved challenge within `window`.
- **Per-address limits.** IPv4 addresses are counted per /32, IPv6 per /64, in memory (per-minute counters over `window`, at most 200 000 addresses, least recently seen dropped first). A solved challenge earns a pass bound to that address for `pass_ttl`, which skips the entropy checks but not `photo_limit`; it resets the address's landing and photo counters. Each challenge solved within the window adds one bit of work (up to +6 over `pow_bits`), and more than 4 × `photo_limit` photos in a window are refused with 429 and `Retry-After` regardless of passes.
- **Cell scrambling** (`images.scramble_cells`, on by default), the hotlink rule on `/t/*`, no context menu, and `robots.txt` with `Disallow: /t/` and `Disallow: /a/*/p/`.
Limits: this raises the cost of bulk downloading; it does not prevent it. The interaction score is reported by the browser, so a bot can fake it; such a bot is bounded only by `photo_limit` per address and the escalating proof of work (about 0.25 s at 20 bits and 15 s at 26 bits in desktop V8, phones several times slower), and by the 429 cap. Many addresses multiply its budget. A determined scraper that drives a real browser, or reimplements the client, can still decrypt the maps and stitch the tiles; and decoys are byte-identical copies of other photos' tiles, so a crawler that downloads every folder can tell which files are shared. Every visitor's browser must be able to draw the photos, so it always has everything needed to do so.
## Install
### Ubuntu 22.04 / 24.04, Debian 12
```sh
sudo apt install ./luphoto_<version>_amd64.deb
sudoedit /etc/luphoto/config.toml
sudo systemctl enable --now luphoto
```
The package depends on `libvips-tools` and creates:
- user and group `luphoto`, and group `luphoto-upload`;
- `/srv/luphoto/albums` (root:luphoto-upload, mode 2775, so members of `luphoto-upload` can upload);
- `/var/lib/luphoto` and `/var/cache/luphoto` (owned by `luphoto`);
- `/etc/luphoto/config.toml` (kept on upgrade), `/usr/lib/systemd/system/luphoto.service`, and examples in `/usr/share/doc/luphoto/`.
The unit runs `luphoto run` as `luphoto` with `ProtectSystem=strict`, the albums read only, and only `/var/lib/luphoto` and `/var/cache/luphoto` writable. `systemctl reload luphoto` sends SIGHUP.
### Other distributions
Unpack `luphoto_<version>_linux_<arch>.tar.gz` and follow its `INSTALL.md`. You need libvips 8.12+ with its command-line tools.
## Uploading
Add yourself to `luphoto-upload` (`sudo usermod -aG luphoto-upload $USER`, then log in again), then:
```sh
rsync -av --chmod=Dg+rwxs,Fg+rw 2026-10-iceland/ server:/srv/luphoto/albums/2026-10-iceland/
```
rsync writes to dotted temp names and renames at the end, which the watcher ignores; the rebuild starts `build.debounce` after the last file lands. SFTP clients that upload to `*.part` work the same way.
## Web server
- **Serve mode**: LuPhoto serves `current` itself with the right headers (immutable caching for `/t/`, `/og/`, `/assets/`; one minute for HTML and JSON; CSP; hotlink 403 on `/t/*`; precompressed gzip; no directory listings; `404.html` for missing paths). Put Caddy (`packaging/Caddyfile.serve`), nginx (`packaging/nginx.serve.conf`) or a Cloudflare Tunnel in front.
- **Export mode**: serve `/var/lib/luphoto/site/current` with `packaging/Caddyfile` or `packaging/nginx.conf`, and proxy `/k` to `luphoto run` on `server.listen` (both examples do; the daemon serves nothing else there). Without that proxy, photos stay jumbled unless `protection.gate = "off"`. Each build writes `.gz` files next to HTML, JSON, JS, CSS and SVG for `precompressed gzip` / `gzip_static`. Each build also writes `robots.txt`; serve mode serves the same file.
- **Cloudflare**: `packaging/cloudflared.yml` and `packaging/cloudflare.md` (cache rules).
## Building from source
Development runs in Docker; the Windows host needs no libvips. From Git Bash or any POSIX shell:
```sh
scripts/dev.sh go build -o bin/luphoto ./cmd/luphoto
scripts/dev.sh go vet ./...
scripts/dev.sh
```
`scripts/dev.sh` builds the `luphoto-dev` image (Ubuntu 24.04, Go, libvips-tools) on first use, mounts the repository at `/src` and keeps Go caches in volumes. Extra `docker run` arguments go in `LUPHOTO_DEV_ARGS`, for example `LUPHOTO_DEV_ARGS="-v /path/to/work:/work -p 127.0.0.1:8080:8080"`.
`scripts/package.sh` builds static binaries (`CGO_ENABLED=0`, `-trimpath`, `-ldflags "-s -w -X main.version=…"`) for amd64 and arm64, the `.deb` packages (nfpm, installed into `.tools/` on first use) and the tarballs into `dist/`, all inside the dev container. Set `VERSION` to override `git describe`. The `Makefile` has `web`, `build`, `dist` and `deb` targets for hosts with make.
### Front-end
TypeScript and CSS live in `web/src`. The minified bundles, fonts, favicon and chop in `internal/site/static` are committed, so `go build` never needs Node. After changing the front-end, rebuild on a host with Node 22:
```sh
npm --prefix web ci
npm --prefix web run build
```
This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts are self-hosted from the `@fontsource` packages (latin and latin-ext only). Each site build writes the files to `/assets/` under content-hashed names.
### Brand
`scripts/sync-brand.sh` copies the tokens, `lucio-morph.js`, `lucio-loaders.js`, the favicon and the chop from `../lucioIP` (or `$LUCIO_IP_DIR`) into `web/brand/`, stripping comments. The copies are committed; rebuild the front-end afterwards.
## Output layout
```
/var/lib/luphoto/
site/
current -> builds/<id>
builds/<id>/index.html, 404.html, robots.txt, index.<id>.json, a/<slug>/index.html, a/<slug>/manifest.<id>.json,
a/<slug>/p/<hash>.<id>.json, assets/, t -> ../../t, og -> ../../og (plus .gz copies)
builds/<id>/.refs every pool id per photo folder, read by the cleanup to find stale decoys (never served)
builds/<id>/.secret the build's 32-byte key secret, mode 0600, read by /k (never served)
t/<photo-hash>/<tile-id>.webp real tiles and decoys (hard links), unordered
og/<hash>.jpg
state/
site.key
pyramids/<photo-hash>.json
```