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:
lucioandClaude Opus 5.5 committed 2026-11-04 22:45:50 -08:00
1 parent f5152fb709
commit c87aad0254
31 files changed
+2021 -414

No files matched your search

+24 -10
View File
@@ -1,6 +1,6 @@
# 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. A one-time robot check unlocks the tile maps; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md).
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
@@ -12,7 +12,7 @@ luphoto [-config /etc/luphoto/config.toml] <command>
|---|---|
| `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; no HTTP. Point Caddy or nginx at `<output>/current`. |
| `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. |
@@ -75,7 +75,9 @@ Unknown fields are errors, so typos are caught.
|---|---|---|
| `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. |
| `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. |
@@ -96,24 +98,35 @@ Unknown fields are errors, so typos are caught.
| `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/*`; empty Referers and the site's own host are always allowed. |
| `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` | `true` | Show the press-and-hold robot check before photos unlock. `false` publishes the key in the clear and shows no check. |
| `protection.pow_bits` | `20` | Proof-of-work size for the robot check (10–26); each extra bit doubles the average work. |
| `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 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:
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.
- **Robot check.** Each build picks a random salt and a random `n` below 2^`pow_bits`. The key is SHA-256("luphoto-key" | salt | n); only a 16-byte check value is published. On the first visit a small card asks the visitor to press and hold for 0.9 s while a Web Worker finds `n` (at 20 bits about 0.1–0.25 s in desktop V8; phones are several times slower). The pass is kept in `localStorage` for that build. Until it is unlocked, each photo shows a jumble of tiles drawn from its pool.
- **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. A determined scraper that drives a real browser, or reimplements the client, can solve the check in a fraction of a second, 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.
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
@@ -151,7 +164,7 @@ rsync writes to dotted temp names and renames at the end, which the watcher igno
## 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`. 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.
- **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
@@ -192,6 +205,7 @@ This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts ar
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/
+43 -16
View File
@@ -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
+69 -5
View File
@@ -3,6 +3,8 @@ package app
import (
"context"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"sync"
@@ -12,7 +14,10 @@ import (
"github.com/luciochen233/luphoto/internal/build"
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/keys"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/server"
"github.com/luciochen233/luphoto/internal/site"
"github.com/luciochen233/luphoto/internal/watch"
)
@@ -24,7 +29,9 @@ type daemon struct {
logger *log.Logger
cfg atomic.Pointer[config.Config]
builds chan string
keys *keys.Service
handler *server.Handler
root http.Handler
server *server.Server
watchCancel context.CancelFunc
watchDone chan struct{}
@@ -36,6 +43,17 @@ type daemon struct {
func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logger *log.Logger) error {
d := &daemon{mode: mode, configPath: configPath, logger: logger, builds: make(chan string, 1)}
d.cfg.Store(cfg)
siteKey, err := process.SiteKey(cfg.State)
if err != nil {
return err
}
d.keys = keys.New(siteKey, keySettings(cfg))
if mode == "serve" {
d.handler = server.NewHandler(handlerSettings(cfg), d.keys)
d.root = d.handler
} else {
d.root = keys.Only(d.keys)
}
var builder sync.WaitGroup
builder.Add(1)
@@ -45,13 +63,15 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge
}()
d.requestBuild("startup")
if mode == "serve" {
d.handler = server.NewHandler(handlerSettings(cfg))
srv, err := server.Start(cfg.Server.Listen, d.handler, logger)
if d.listens(cfg) {
srv, err := server.Start(cfg.Server.Listen, d.root, logger)
if err != nil {
return err
}
d.server = srv
if mode != "serve" {
logger.Printf("export: serving only %s on %s", site.KeyPath, cfg.Server.Listen)
}
}
d.syncWatcher(ctx, cfg)
@@ -76,10 +96,35 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge
}
}
func (d *daemon) listens(cfg *config.Config) bool {
return d.mode == "serve" || string(cfg.Protection.Gate) == site.GateServer
}
func handlerSettings(cfg *config.Config) server.Settings {
return server.Settings{Output: cfg.Paths.Output, HotlinkAllow: cfg.Protection.HotlinkAllow}
}
func keySettings(cfg *config.Config) keys.Settings {
trusted, _ := config.ParsePrefixes(cfg.Server.TrustedProxies)
hosts := append([]string(nil), cfg.Protection.HotlinkAllow...)
if u, err := url.Parse(cfg.Server.BaseURL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
p := cfg.Protection
return keys.Settings{
Output: cfg.Paths.Output,
Gate: string(p.Gate),
Hosts: hosts,
Trusted: trusted,
IPHeader: cfg.Server.ClientIPHeader,
PowBits: p.PowBits,
PhotoLimit: p.PhotoLimit,
MinEntropy: p.MinEntropy,
LandingLimit: p.LandingLimit,
Window: p.Window.Duration,
PassTTL: p.PassTTL.Duration,
}
}
func (d *daemon) requestBuild(reason string) {
select {
case d.builds <- reason:
@@ -104,6 +149,7 @@ func (d *daemon) buildLoop(ctx context.Context) {
d.logger.Printf("build failed: %v; previous build stays live", err)
continue
}
d.keys.Reload()
d.logger.Print(summary.String())
}
}
@@ -166,8 +212,25 @@ func (d *daemon) reload(ctx context.Context) {
if next.Server.Mode != previous.Server.Mode {
d.logger.Printf("reload: server.mode changed to %q; restart the service to switch modes", next.Server.Mode)
}
if d.server != nil && next.Server.Listen != previous.Server.Listen {
srv, err := server.Start(next.Server.Listen, d.handler, d.logger)
want := d.listens(next)
switch {
case !want && d.server != nil:
old := d.server
d.server = nil
go func() {
if err := old.Shutdown(shutdownTimeout); err != nil {
d.logger.Printf("reload: closing listener: %v", err)
}
}()
case want && d.server == nil:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s: %v", next.Server.Listen, err)
} else {
d.server = srv
}
case want && next.Server.Listen != previous.Server.Listen:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s, keeping %s: %v", next.Server.Listen, previous.Server.Listen, err)
next.Server.Listen = previous.Server.Listen
@@ -185,6 +248,7 @@ func (d *daemon) reload(ctx context.Context) {
if d.handler != nil {
d.handler.Update(handlerSettings(next))
}
d.keys.Update(keySettings(next))
d.syncWatcher(ctx, next)
d.logger.Printf("reload: config %s applied", d.configPath)
d.requestBuild("SIGHUP")
+64 -13
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
@@ -246,7 +247,7 @@ func (b *builder) run(ctx context.Context) (*Summary, error) {
}
sum.Cached = len(records) - sum.Processed
id, err := newBuildID()
id, err := b.newBuildID()
if err != nil {
return nil, err
}
@@ -298,19 +299,33 @@ func (b *builder) run(ctx context.Context) (*Summary, error) {
}
sum.Albums = len(manifests)
gate, err := protect.NewGate(b.cfg.Protection.PowBits, b.cfg.Protection.Gate)
secret, err := protect.NewSecret()
if err != nil {
return nil, err
}
keyer := protect.NewKeyer(secret)
coverKey := keyer.Cover()
covers := make(map[string]bool, len(manifests))
for _, m := range manifests {
covers[m.Cover.Hash] = true
}
keys := make(map[string][32]byte, len(lives))
for _, l := range lives {
if covers[l.rec.Hash] {
keys[l.rec.Hash] = coverKey
} else {
keys[l.rec.Hash] = keyer.Photo(l.rec.Hash)
}
}
poolStart := time.Now()
pools, linked, err := b.pools(lives, gate)
pools, linked, err := b.pools(lives, keys)
if err != nil {
return nil, fmt.Errorf("decoys: %w", err)
}
sum.DecoysLinked = linked
b.log.Printf("protect: %d pools sealed, %d decoys linked in %s", len(pools), linked, round(time.Since(poolStart)))
if err := b.writeBuild(id, manifests, gate, lives, pools); err != nil {
if err := b.writeBuild(id, manifests, secret, keys, coverKey, lives, pools); err != nil {
return nil, err
}
if err := fsutil.SymlinkAtomic(filepath.Join("builds", id), b.current); err != nil {
@@ -461,15 +476,43 @@ func (b *builder) carryOver(previous, slug, id string) (*site.Manifest, []*proce
return &m, records
}
func newBuildID() (string, error) {
func buildStamp(t time.Time) string {
return t.Format("20060102-150405") + fmt.Sprintf("-%06d", t.Nanosecond()/1000)
}
func (b *builder) newBuildID() (string, error) {
var suffix [3]byte
if _, err := rand.Read(suffix[:]); err != nil {
return "", err
}
return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil
t := time.Now().UTC().Truncate(time.Microsecond)
if entries, err := os.ReadDir(b.builds); err == nil {
for _, entry := range entries {
if last, ok := parseStamp(entry.Name()); ok && !t.After(last) {
t = last.Add(time.Microsecond)
}
}
}
return buildStamp(t) + "-" + hex.EncodeToString(suffix[:]), nil
}
func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protect.Gate, lives []*live, pools map[string]*pool) error {
func parseStamp(name string) (time.Time, bool) {
if len(name) < 15 {
return time.Time{}, false
}
t, err := time.Parse("20060102-150405", name[:15])
if err != nil {
return time.Time{}, false
}
if len(name) >= 23 && name[15] == '-' && name[22] == '-' {
if micro, err := strconv.Atoi(name[16:22]); err == nil {
return t.Add(time.Duration(micro) * time.Microsecond), true
}
}
return t.Add(time.Second - time.Microsecond), true
}
func (b *builder) writeBuild(id string, manifests []*site.Manifest, secret []byte, keys map[string][32]byte, coverKey [32]byte, lives []*live, pools map[string]*pool) error {
stage := fsutil.TempName(filepath.Join(b.builds, id))
if err := os.MkdirAll(filepath.Join(stage, "a"), 0o755); err != nil {
return err
@@ -495,15 +538,14 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protec
MaxDPR: b.cfg.Loading.MaxDPR,
Concurrency: b.cfg.Loading.Concurrency,
BlockContextMenu: b.cfg.Protection.BlockContextMenu,
Gate: gate.Enabled,
Gate: string(b.cfg.Protection.Gate),
MinEntropy: b.cfg.Protection.MinEntropy,
BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"),
}
public := &site.Gate{Build: id}
if gate.Enabled {
public.Salt, public.Bits, public.Check = gate.SaltHex(), gate.Bits, gate.CheckHex()
} else {
public.Key = gate.KeyHex()
public := &site.Gate{Build: id, Mode: page.Gate, Cover: hex.EncodeToString(coverKey[:]), MinEntropy: page.MinEntropy}
if err := fsutil.WriteFileAtomic(filepath.Join(stage, protect.SecretName), secret, 0o600); err != nil {
return err
}
if err := fsutil.WriteFileAtomic(filepath.Join(stage, "robots.txt"), []byte(site.Robots), 0o644); err != nil {
return err
@@ -515,6 +557,15 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protec
index := &site.Index{Build: id, Tiles: b.tiles(), Gate: public, Albums: []site.IndexAlbum{}}
for _, m := range manifests {
m.Gate = public
if public.Mode == site.GateOff {
open := *public
open.Keys = make(map[string]string, len(m.Photos))
for _, p := range m.Photos {
k := keys[p.Hash]
open.Keys[p.Hash] = hex.EncodeToString(k[:])
}
m.Gate = &open
}
if m.Hidden {
continue
}
+4 -4
View File
@@ -142,7 +142,7 @@ func (idx *decoyIndex) pick(owner int32, size int) (*bucket, tier, int) {
return nil, nil, 0
}
func (b *builder) pools(lives []*live, gate *protect.Gate) (map[string]*pool, int, error) {
func (b *builder) pools(lives []*live, keys map[string][32]byte) (map[string]*pool, int, error) {
idx := newDecoyIndex(lives)
out := make([]*pool, len(lives))
errs := make([]error, len(lives))
@@ -159,7 +159,7 @@ func (b *builder) pools(lives []*live, gate *protect.Gate) (map[string]*pool, in
if i >= len(lives) {
return
}
p, n, err := b.pool(idx, int32(i), keyed, gate)
p, n, err := b.pool(idx, int32(i), keyed, keys[lives[i].rec.Hash])
out[i], errs[i] = p, err
linked.Add(int64(n))
}
@@ -181,7 +181,7 @@ type link struct {
source string
}
func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, gate *protect.Gate) (*pool, int, error) {
func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, key [32]byte) (*pool, int, error) {
rec := idx.lives[owner].rec
hash := rec.Hash
decoys := b.cfg.Protection.Decoys
@@ -254,7 +254,7 @@ func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, gate
if err != nil {
return nil, made, err
}
public.Sealed, err = protect.Seal(gate.Key, plain)
public.Sealed, err = protect.Seal(key, plain)
if err != nil {
return nil, made, err
}
+96 -9
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/fs"
"net/netip"
"os"
"path/filepath"
"sort"
@@ -28,9 +29,11 @@ type Config struct {
}
type Server struct {
Mode string `toml:"mode"`
Listen string `toml:"listen"`
BaseURL string `toml:"base_url"`
Mode string `toml:"mode"`
Listen string `toml:"listen"`
BaseURL string `toml:"base_url"`
TrustedProxies []string `toml:"trusted_proxies"`
ClientIPHeader string `toml:"client_ip_header"`
}
type Paths struct {
@@ -74,8 +77,31 @@ type Protection struct {
BlockContextMenu bool `toml:"block_context_menu"`
HotlinkAllow []string `toml:"hotlink_allow"`
Decoys int `toml:"decoys"`
Gate bool `toml:"gate"`
Gate GateMode `toml:"gate"`
PowBits int `toml:"pow_bits"`
PhotoLimit int `toml:"photo_limit"`
MinEntropy int `toml:"min_entropy"`
LandingLimit int `toml:"landing_limit"`
Window Duration `toml:"window"`
PassTTL Duration `toml:"pass_ttl"`
}
type GateMode string
func (g *GateMode) UnmarshalTOML(value any) error {
switch v := value.(type) {
case string:
*g = GateMode(strings.TrimSpace(v))
case bool:
if v {
*g = "server"
} else {
*g = "off"
}
default:
return fmt.Errorf("protection.gate must be \"server\" or \"off\"")
}
return nil
}
type Duration struct {
@@ -98,9 +124,11 @@ func (d Duration) MarshalText() ([]byte, error) {
func Defaults() Config {
return Config{
Server: Server{
Mode: "export",
Listen: "127.0.0.1:8080",
BaseURL: "https://photos.luciochen.com",
Mode: "export",
Listen: "127.0.0.1:8080",
BaseURL: "https://photos.luciochen.com",
TrustedProxies: []string{"127.0.0.1/32", "::1/128"},
ClientIPHeader: "X-Forwarded-For",
},
Paths: Paths{
Albums: "/srv/luphoto/albums",
@@ -131,8 +159,13 @@ func Defaults() Config {
BlockContextMenu: true,
HotlinkAllow: []string{"photos.luciochen.com"},
Decoys: 4,
Gate: true,
Gate: "server",
PowBits: 20,
PhotoLimit: 400,
MinEntropy: 20,
LandingLimit: 5,
Window: Duration{10 * time.Minute},
PassTTL: Duration{12 * time.Hour},
},
}
}
@@ -288,9 +321,38 @@ func (c *Config) Validate() error {
if c.Protection.Decoys < 0 || c.Protection.Decoys > 16 {
add("protection.decoys must be between 0 and 16")
}
if c.Protection.PowBits < 10 || c.Protection.PowBits > 26 {
p := c.Protection
switch p.Gate {
case "server", "off":
default:
add("protection.gate must be \"server\" or \"off\", got %q", p.Gate)
}
if p.PowBits < 10 || p.PowBits > 26 {
add("protection.pow_bits must be between 10 and 26")
}
if p.PhotoLimit < 1 || p.PhotoLimit > 1000000 {
add("protection.photo_limit must be between 1 and 1000000")
}
if p.MinEntropy < 0 || p.MinEntropy > 100 {
add("protection.min_entropy must be between 0 and 100")
}
if p.LandingLimit < 1 || p.LandingLimit > 10000 {
add("protection.landing_limit must be between 1 and 10000")
}
if p.Window.Duration < time.Minute || p.Window.Duration > 24*time.Hour {
add("protection.window must be between 1m and 24h")
}
if p.PassTTL.Duration < time.Minute || p.PassTTL.Duration > 30*24*time.Hour {
add("protection.pass_ttl must be between 1m and 720h")
}
if _, err := ParsePrefixes(c.Server.TrustedProxies); err != nil {
add("server.trusted_proxies: %v", err)
}
if h := c.Server.ClientIPHeader; h != "" && strings.IndexFunc(h, func(r rune) bool {
return !(r == '-' || r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z')
}) >= 0 {
add("server.client_ip_header %q is not a header name", h)
}
for _, host := range c.Protection.HotlinkAllow {
if host == "" || strings.ContainsAny(host, "/ ") {
add("protection.hotlink_allow entry %q is not a host name", host)
@@ -302,6 +364,31 @@ func (c *Config) Validate() error {
return nil
}
func ParsePrefixes(values []string) ([]netip.Prefix, error) {
out := make([]netip.Prefix, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if strings.Contains(value, "/") {
prefix, err := netip.ParsePrefix(value)
if err != nil {
return nil, fmt.Errorf("%q is not a CIDR", value)
}
if prefix.Addr().Is4In6() {
prefix = netip.PrefixFrom(prefix.Addr().Unmap(), max(0, prefix.Bits()-96))
}
out = append(out, prefix.Masked())
continue
}
addr, err := netip.ParseAddr(value)
if err != nil {
return nil, fmt.Errorf("%q is not an address or CIDR", value)
}
addr = addr.Unmap()
out = append(out, netip.PrefixFrom(addr, addr.BitLen()))
}
return out, nil
}
func within(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
if err != nil {
+127
View File
@@ -0,0 +1,127 @@
package keys
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/luciochen233/luphoto/internal/fsutil"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const (
rescanEvery = 2 * time.Second
albumCache = 4096
)
type album map[string]struct{}
type buildInfo struct {
id string
dir string
secret []byte
mu sync.Mutex
albums map[string]album
}
type builds struct {
mu sync.RWMutex
root string
byID map[string]*buildInfo
scanned time.Time
}
func validID(id string) bool {
if id == "" || len(id) > 64 {
return false
}
for i := 0; i < len(id); i++ {
c := id[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c == '-') {
return false
}
}
return true
}
func validSlug(slug string) bool {
return slug != "" && len(slug) <= 255 && !strings.HasPrefix(slug, ".") && !strings.ContainsAny(slug, "/\\\x00")
}
func (b *builds) reload(root string) {
next := map[string]*buildInfo{}
b.mu.RLock()
old := b.byID
same := b.root == root
b.mu.RUnlock()
dir := filepath.Join(root, "builds")
entries, _ := os.ReadDir(dir)
for _, entry := range entries {
id := entry.Name()
if !entry.IsDir() || !validID(id) {
continue
}
if info, ok := old[id]; ok && same {
next[id] = info
continue
}
secret, err := protect.ReadSecret(filepath.Join(dir, id))
if err != nil {
continue
}
next[id] = &buildInfo{id: id, dir: filepath.Join(dir, id), secret: secret, albums: map[string]album{}}
}
b.mu.Lock()
b.root = root
b.byID = next
b.scanned = time.Now()
b.mu.Unlock()
}
func (b *builds) get(root, id string) *buildInfo {
if !validID(id) {
return nil
}
b.mu.RLock()
info := b.byID[id]
fresh := time.Since(b.scanned) < rescanEvery && b.root == root
b.mu.RUnlock()
if info != nil || fresh {
return info
}
b.reload(root)
b.mu.RLock()
info = b.byID[id]
b.mu.RUnlock()
return info
}
func (info *buildInfo) album(slug string) album {
if !validSlug(slug) {
return nil
}
info.mu.Lock()
defer info.mu.Unlock()
if a, ok := info.albums[slug]; ok {
return a
}
var m struct {
Photos []struct {
Hash string `json:"hash"`
} `json:"photos"`
}
var a album
if err := fsutil.ReadJSON(filepath.Join(info.dir, "a", slug, site.ManifestName(info.id)), &m); err == nil {
a = make(album, len(m.Photos))
for _, p := range m.Photos {
a[p.Hash] = struct{}{}
}
}
if a != nil || len(info.albums) < albumCache {
info.albums[slug] = a
}
return a
}
+448
View File
@@ -0,0 +1,448 @@
package keys
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"hash"
"net"
"net/http"
"net/netip"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const (
bodyLimit = 4 << 10
maxPhotos = 8
tokenRaw = 24
tokenLen = 32
macLen = tokenRaw - 5
challengeTTL = 5 * time.Minute
clockSkew = 30 * time.Second
usedCapacity = 1 << 15
maxNonce = 1 << 53
contextNav = "nav"
contextLand = "land"
challengeKind = 'c'
passKind = 'p'
pageKind = 'g'
pageTTL = 30 * time.Minute
)
type Settings struct {
Output string
Gate string
Hosts []string
Trusted []netip.Prefix
IPHeader string
PowBits int
PhotoLimit int
MinEntropy int
LandingLimit int
Window time.Duration
PassTTL time.Duration
}
type Service struct {
settings atomic.Pointer[Settings]
table atomic.Pointer[table]
macs sync.Pool
builds builds
used used
}
type used struct {
mu sync.Mutex
seen map[[macLen]byte]struct{}
ring [][macLen]byte
next int
}
func (u *used) add(mac [macLen]byte) bool {
u.mu.Lock()
defer u.mu.Unlock()
if _, ok := u.seen[mac]; ok {
return false
}
if len(u.ring) < usedCapacity {
u.ring = append(u.ring, mac)
} else {
delete(u.seen, u.ring[u.next])
u.ring[u.next] = mac
u.next = (u.next + 1) % usedCapacity
}
u.seen[mac] = struct{}{}
return true
}
func New(siteKey []byte, settings Settings) *Service {
s := &Service{}
key := append([]byte(nil), siteKey...)
s.macs.New = func() any { return hmac.New(sha256.New, key) }
s.used.seen = make(map[[macLen]byte]struct{})
s.Update(settings)
return s
}
func (s *Service) Update(settings Settings) {
hosts := make([]string, 0, len(settings.Hosts))
for _, h := range settings.Hosts {
if h = strings.ToLower(strings.TrimSpace(h)); h != "" {
hosts = append(hosts, h)
}
}
settings.Hosts = hosts
previous := s.settings.Swap(&settings)
if previous == nil || previous.Window != settings.Window || s.table.Load() == nil {
s.table.Store(newTable(settings.Window))
}
if previous == nil || previous.Output != settings.Output {
s.builds.reload(settings.Output)
}
}
func (s *Service) Reload() {
if set := s.settings.Load(); set != nil {
s.builds.reload(set.Output)
}
}
func (s *Service) sign(kind byte, bucket [16]byte, head []byte, scope ...string) [32]byte {
mac := s.macs.Get().(hash.Hash)
mac.Reset()
var buf [1 + 16 + 5]byte
buf[0] = kind
copy(buf[1:], bucket[:])
copy(buf[17:], head)
mac.Write(buf[:])
for _, part := range scope {
mac.Write([]byte{0})
mac.Write([]byte(part))
}
var out [32]byte
mac.Sum(out[:0])
s.macs.Put(mac)
return out
}
func (s *Service) token(kind byte, bucket [16]byte, stamp uint32, extra byte, scope ...string) string {
var raw [tokenRaw]byte
binary.BigEndian.PutUint32(raw[:4], stamp)
raw[4] = extra
sum := s.sign(kind, bucket, raw[:5], scope...)
copy(raw[5:], sum[:macLen])
return base64.RawURLEncoding.EncodeToString(raw[:])
}
func (s *Service) open(kind byte, bucket [16]byte, text string, scope ...string) (uint32, byte, [macLen]byte, bool) {
var raw [tokenRaw]byte
var mac [macLen]byte
if len(text) != tokenLen {
return 0, 0, mac, false
}
if n, err := base64.RawURLEncoding.Decode(raw[:], []byte(text)); err != nil || n != tokenRaw {
return 0, 0, mac, false
}
sum := s.sign(kind, bucket, raw[:5], scope...)
if !hmac.Equal(sum[:macLen], raw[5:]) {
return 0, 0, mac, false
}
copy(mac[:], raw[5:])
return binary.BigEndian.Uint32(raw[:4]), raw[4], mac, true
}
func (s *Service) passValid(bucket [16]byte, text string, now time.Time, ttl time.Duration) bool {
expiry, _, _, ok := s.open(passKind, bucket, text)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= ttl+clockSkew
}
func (s *Service) pageValid(bucket [16]byte, text, build, album string, now time.Time) bool {
if text == "" {
return false
}
expiry, _, _, ok := s.open(pageKind, bucket, text, build, album)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= pageTTL+clockSkew
}
func (s *Service) solved(bucket [16]byte, c *challengeAnswer, now time.Time) bool {
if c == nil || c.Nonce > maxNonce {
return false
}
issued, bits, mac, ok := s.open(challengeKind, bucket, c.Token)
if !ok || bits < 1 || bits > 32 {
return false
}
at := time.Unix(int64(issued), 0)
if now.Sub(at) > challengeTTL || at.Sub(now) > clockSkew {
return false
}
var msg [tokenLen + 8]byte
copy(msg[:], c.Token)
binary.BigEndian.PutUint64(msg[tokenLen:], c.Nonce)
sum := sha256.Sum256(msg[:])
if binary.BigEndian.Uint32(sum[:4])>>(32-uint(bits)) != 0 {
return false
}
return s.used.add(mac)
}
type challengeAnswer struct {
Token string `json:"token"`
Nonce uint64 `json:"nonce"`
}
type request struct {
Build string `json:"build"`
Album string `json:"album"`
Photos []string `json:"photos"`
Context string `json:"context"`
Entropy float64 `json:"entropy"`
Pass string `json:"pass"`
Page string `json:"page"`
Challenge *challengeAnswer `json:"challenge"`
}
type granted struct {
Keys map[string]string `json:"keys"`
Pass string `json:"pass,omitempty"`
Page string `json:"page,omitempty"`
Stale bool `json:"stale,omitempty"`
}
type puzzle struct {
Token string `json:"token"`
Bits int `json:"bits"`
}
type challenged struct {
Challenge puzzle `json:"challenge"`
Stale bool `json:"stale,omitempty"`
}
type failure struct {
Error string `json:"error"`
}
func reply(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(body)
}
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("Cache-Control", "no-store")
set := s.settings.Load()
if set.Gate != site.GateServer {
reply(w, http.StatusNotFound, failure{"off"})
return
}
if r.Method != http.MethodPost {
header.Set("Allow", "POST")
reply(w, http.StatusMethodNotAllowed, failure{"method"})
return
}
if !allowedOrigin(r, set.Hosts) {
reply(w, http.StatusForbidden, failure{"origin"})
return
}
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
var req request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
reply(w, http.StatusBadRequest, failure{"body"})
return
}
if len(req.Photos) > maxPhotos || (req.Context != contextNav && req.Context != contextLand) || !(req.Entropy >= 0 && req.Entropy <= 100) {
reply(w, http.StatusBadRequest, failure{"request"})
return
}
info := s.builds.get(set.Output, req.Build)
if info == nil {
reply(w, http.StatusBadRequest, failure{"build"})
return
}
members := info.album(req.Album)
if members == nil {
reply(w, http.StatusBadRequest, failure{"album"})
return
}
photos := req.Photos[:0]
for _, h := range req.Photos {
if _, ok := members[h]; !ok {
continue
}
dup := false
for _, seen := range photos {
if seen == h {
dup = true
break
}
}
if !dup {
photos = append(photos, h)
}
}
now := time.Now()
bucket := bucketOf(clientIP(r, set))
pass := req.Pass != "" && s.passValid(bucket, req.Pass, now, set.PassTTL)
stale := req.Pass != "" && !pass
page := s.pageValid(bucket, req.Page, req.Build, req.Album, now)
solved := s.solved(bucket, req.Challenge, now)
out := s.table.Load().decide(bucket, now, input{
nav: req.Context == contextNav,
low: req.Entropy < float64(set.MinEntropy),
pass: pass,
page: page,
solved: solved,
photos: len(photos),
photoLimit: set.PhotoLimit,
landings: set.LandingLimit,
powBits: set.PowBits,
})
switch out.verdict {
case limited:
header.Set("Retry-After", strconv.Itoa(max(1, int((out.retry+time.Second-1)/time.Second))))
reply(w, http.StatusTooManyRequests, failure{"limit"})
case challenge:
reply(w, http.StatusOK, challenged{Challenge: puzzle{Token: s.token(challengeKind, bucket, uint32(now.Unix()), byte(out.bits)), Bits: out.bits}, Stale: stale})
default:
body := granted{Keys: make(map[string]string, len(photos)), Stale: stale && !solved}
keyer := protect.NewKeyer(info.secret)
for _, h := range photos {
k := keyer.Photo(h)
body.Keys[h] = hex.EncodeToString(k[:])
}
if solved {
body.Pass = s.token(passKind, bucket, uint32(now.Add(set.PassTTL).Unix()), 1)
}
if !page {
body.Page = s.token(pageKind, bucket, uint32(now.Add(pageTTL).Unix()), 1, req.Build, req.Album)
}
reply(w, http.StatusOK, body)
}
}
func Only(keys http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path != site.KeyPath {
header.Set("Cache-Control", "no-store")
http.NotFound(w, r)
return
}
keys.ServeHTTP(w, r)
})
}
func hostOf(hostport string) string {
if h, _, err := net.SplitHostPort(hostport); err == nil {
return strings.ToLower(h)
}
return strings.ToLower(strings.Trim(hostport, "[]"))
}
func allowedOrigin(r *http.Request, hosts []string) bool {
source := r.Header.Get("Origin")
if source == "" {
source = r.Header.Get("Referer")
}
if source == "" || source == "null" {
return false
}
u, err := url.Parse(source)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return false
}
host := strings.ToLower(u.Hostname())
if host == hostOf(r.Host) {
return true
}
for _, allowed := range hosts {
if host == allowed {
return true
}
}
return false
}
func trusted(addr netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
if p.Contains(addr) {
return true
}
}
return false
}
func clientIP(r *http.Request, set *Settings) netip.Addr {
var peer netip.Addr
if ap, err := netip.ParseAddrPort(r.RemoteAddr); err == nil {
peer = ap.Addr().Unmap()
} else if a, err := netip.ParseAddr(r.RemoteAddr); err == nil {
peer = a.Unmap()
}
if set.IPHeader == "" || !peer.IsValid() || !trusted(peer, set.Trusted) {
return peer
}
values := r.Header.Values(set.IPHeader)
var leftmost netip.Addr
for i := len(values) - 1; i >= 0; i-- {
rest := values[i]
for rest != "" {
part := rest
if at := strings.LastIndexByte(rest, ','); at >= 0 {
part, rest = rest[at+1:], rest[:at]
} else {
rest = ""
}
addr, err := netip.ParseAddr(strings.TrimSpace(part))
if err != nil {
if ap, err := netip.ParseAddrPort(strings.TrimSpace(part)); err == nil {
addr = ap.Addr()
} else {
return peer
}
}
addr = addr.Unmap()
if !trusted(addr, set.Trusted) {
return addr
}
leftmost = addr
}
}
if leftmost.IsValid() {
return leftmost
}
return peer
}
func bucketOf(addr netip.Addr) [16]byte {
key := addr.As16()
if addr.Is6() {
clear(key[8:])
}
return key
}
+219
View File
@@ -0,0 +1,219 @@
package keys
import (
"math"
"sync"
"time"
)
const (
slotCount = 16
shardCount = 16
maxBuckets = 200000
)
type slot struct {
photos uint32
low uint16
solved uint16
}
type bucket struct {
key [16]byte
at int64
solveAt int64
solveBase uint32
prev int32
next int32
slots [slotCount]slot
}
type shard struct {
mu sync.Mutex
index map[[16]byte]int32
items []bucket
head int32
tail int32
}
type table struct {
width int64
span int64
limit int
shards [shardCount]shard
}
func newTable(window time.Duration) *table {
width := max(int64(time.Minute), (int64(window)+slotCount-1)/slotCount)
width = (width + int64(time.Minute) - 1) / int64(time.Minute) * int64(time.Minute)
span := min(int64(slotCount), (int64(window)+width-1)/width)
t := &table{width: width, span: span, limit: maxBuckets / shardCount}
for i := range t.shards {
t.shards[i].index = make(map[[16]byte]int32)
t.shards[i].head = -1
t.shards[i].tail = -1
}
return t
}
func (s *shard) unlink(i int32) {
b := &s.items[i]
if b.prev >= 0 {
s.items[b.prev].next = b.next
} else {
s.head = b.next
}
if b.next >= 0 {
s.items[b.next].prev = b.prev
} else {
s.tail = b.prev
}
b.prev, b.next = -1, -1
}
func (s *shard) front(i int32) {
b := &s.items[i]
b.prev = -1
b.next = s.head
if s.head >= 0 {
s.items[s.head].prev = i
}
s.head = i
if s.tail < 0 {
s.tail = i
}
}
func (s *shard) get(key [16]byte, limit int, now int64) *bucket {
if i, ok := s.index[key]; ok {
if s.head != i {
s.unlink(i)
s.front(i)
}
return &s.items[i]
}
var i int32
if len(s.items) < limit {
s.items = append(s.items, bucket{})
i = int32(len(s.items) - 1)
} else {
i = s.tail
s.unlink(i)
delete(s.index, s.items[i].key)
}
s.items[i] = bucket{key: key, at: now, solveAt: math.MinInt64 / 2, prev: -1, next: -1}
s.index[key] = i
s.front(i)
return &s.items[i]
}
func (b *bucket) advance(now int64) {
if now <= b.at {
return
}
if now-b.at >= slotCount {
b.slots = [slotCount]slot{}
} else {
for at := b.at + 1; at <= now; at++ {
b.slots[at%slotCount] = slot{}
}
}
b.at = now
}
type input struct {
nav bool
low bool
pass bool
page bool
solved bool
photos int
photoLimit int
landings int
powBits int
}
type verdict int
const (
grant verdict = iota
challenge
limited
)
type outcome struct {
verdict verdict
bits int
retry time.Duration
}
func shardOf(key [16]byte) int {
h := uint32(2166136261)
for _, c := range key {
h = (h ^ uint32(c)) * 16777619
}
return int(h % shardCount)
}
func (t *table) decide(key [16]byte, now time.Time, in input) outcome {
s := &t.shards[shardOf(key)]
s.mu.Lock()
defer s.mu.Unlock()
cur := now.UnixNano() / t.width
b := s.get(key, t.limit, cur)
b.advance(cur)
var photos, since, low, solved uint64
for i := int64(0); i < t.span; i++ {
at := cur - i
sl := &b.slots[at%slotCount]
photos += uint64(sl.photos)
low += uint64(sl.low)
solved += uint64(sl.solved)
if at >= b.solveAt {
since += uint64(sl.photos)
}
}
if b.solveAt > cur-t.span {
since -= min(since, uint64(b.solveBase))
} else {
since = photos
}
limit := uint64(in.photoLimit)
if photos > 4*limit {
return outcome{verdict: limited, retry: t.retry(b, cur, now, photos-4*limit)}
}
here := &b.slots[cur%slotCount]
if in.solved {
for i := range b.slots {
b.slots[i].low = 0
}
if here.solved < math.MaxUint16 {
here.solved++
}
b.solveAt = cur
b.solveBase = here.photos
here.photos += uint32(in.photos)
return outcome{verdict: grant}
}
admitted := in.pass || in.page
if since > limit || (!admitted && in.nav && in.low) || (!admitted && low >= uint64(in.landings)) {
return outcome{verdict: challenge, bits: min(32, in.powBits+int(min(6, solved)))}
}
here.photos += uint32(in.photos)
if !admitted && !in.nav && in.low && here.low < math.MaxUint16 {
here.low++
}
return outcome{verdict: grant}
}
func (t *table) retry(b *bucket, cur int64, now time.Time, excess uint64) time.Duration {
var dropped uint64
for i := t.span - 1; i >= 0; i-- {
at := cur - i
dropped += uint64(b.slots[at%slotCount].photos)
if dropped >= excess {
return time.Duration((at+t.span)*t.width - now.UnixNano())
}
}
return time.Duration(t.width)
}
+6 -2
View File
@@ -96,7 +96,7 @@ func New(ctx context.Context, cfg *config.Config) (*Processor, error) {
return nil, err
}
}
key, err := loadOrCreateKey(filepath.Join(cfg.State, "site.key"))
key, err := SiteKey(cfg.State)
if err != nil {
return nil, err
}
@@ -150,7 +150,11 @@ func (p *Processor) VipsVersion() string {
return p.vips.Version
}
func loadOrCreateKey(path string) ([]byte, error) {
func SiteKey(state string) ([]byte, error) {
path := filepath.Join(state, "site.key")
if err := os.MkdirAll(state, 0o755); err != nil {
return nil, err
}
key, err := os.ReadFile(path)
if err == nil {
if len(key) != 32 {
+45 -36
View File
@@ -1,63 +1,72 @@
package protect
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"os"
"path/filepath"
)
const (
SealMagic = "luphoto-sealed-1"
NonceSize = 12
keyLabel = "luphoto-key"
chkLabel = "luphoto-check"
SealMagic = "luphoto-sealed-1"
NonceSize = 12
SecretName = ".secret"
SecretSize = 32
)
type Gate struct {
Salt [16]byte
N uint32
Bits int
Key [32]byte
Check [16]byte
Enabled bool
}
func NewGate(bits int, enabled bool) (*Gate, error) {
g := &Gate{Bits: bits, Enabled: enabled}
var raw [4]byte
if _, err := rand.Read(g.Salt[:]); err != nil {
func NewSecret() ([]byte, error) {
secret := make([]byte, SecretSize)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
if _, err := rand.Read(raw[:]); err != nil {
return secret, nil
}
func ReadSecret(buildDir string) ([]byte, error) {
secret, err := os.ReadFile(filepath.Join(buildDir, SecretName))
if err != nil {
return nil, err
}
g.N = binary.BigEndian.Uint32(raw[:]) & (uint32(1)<<bits - 1)
g.Key = Derive(keyLabel, g.Salt[:], g.N)
check := Derive(chkLabel, g.Salt[:], g.N)
copy(g.Check[:], check[:16])
return g, nil
if len(secret) != SecretSize {
return nil, fmt.Errorf("build secret %s: expected %d bytes, found %d", buildDir, SecretSize, len(secret))
}
return secret, nil
}
func Derive(label string, salt []byte, n uint32) [32]byte {
buf := make([]byte, 0, len(label)+len(salt)+4)
buf = append(buf, label...)
buf = append(buf, salt...)
buf = binary.BigEndian.AppendUint32(buf, n)
return sha256.Sum256(buf)
type Keyer struct {
mac hash.Hash
buf []byte
sum []byte
}
func (g *Gate) SaltHex() string {
return hex.EncodeToString(g.Salt[:])
func NewKeyer(secret []byte) *Keyer {
return &Keyer{mac: hmac.New(sha256.New, secret), buf: make([]byte, 0, 64), sum: make([]byte, 0, sha256.Size)}
}
func (g *Gate) CheckHex() string {
return hex.EncodeToString(g.Check[:])
func (k *Keyer) derive(label, hash string) [32]byte {
b := append(k.buf[:0], label...)
b = append(b, '|')
b = append(b, hash...)
k.buf = b
k.mac.Reset()
k.mac.Write(b)
k.sum = k.mac.Sum(k.sum[:0])
var out [32]byte
copy(out[:], k.sum)
return out
}
func (g *Gate) KeyHex() string {
return hex.EncodeToString(g.Key[:])
func (k *Keyer) Photo(hash string) [32]byte {
return k.derive("photo", hash)
}
func (k *Keyer) Cover() [32]byte {
return k.derive("cover", "")
}
func Seal(key [32]byte, plain []byte) (string, error) {
+7 -2
View File
@@ -50,10 +50,11 @@ type Settings struct {
type Handler struct {
settings atomic.Pointer[Settings]
keys http.Handler
}
func NewHandler(settings Settings) *Handler {
h := &Handler{}
func NewHandler(settings Settings, keys http.Handler) *Handler {
h := &Handler{keys: keys}
h.Update(settings)
return h
}
@@ -72,6 +73,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header.Set("Content-Security-Policy", contentSecurityPolicy)
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path == "/k" && h.keys != nil {
h.keys.ServeHTTP(w, r)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
header.Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+13 -6
View File
@@ -61,12 +61,18 @@ func Layout(p *process.Pyramid) *Pyramid {
return out
}
const (
GateServer = "server"
GateOff = "off"
KeyPath = "/k"
)
type Gate struct {
Build string `json:"build"`
Salt string `json:"salt,omitempty"`
Bits int `json:"bits,omitempty"`
Check string `json:"check,omitempty"`
Key string `json:"key,omitempty"`
Build string `json:"build"`
Mode string `json:"mode"`
Cover string `json:"cover"`
MinEntropy int `json:"min_entropy"`
Keys map[string]string `json:"keys,omitempty"`
}
type Pool struct {
@@ -171,7 +177,8 @@ type Page struct {
MaxDPR float64
Concurrency int
BlockContextMenu bool
Gate bool
Gate string
MinEntropy int
BaseURL string
}
+1 -1
View File
@@ -1 +1 @@
"use strict";(()=>{(function(n){let t={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},e="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(u,g)=>{let d=document.createElementNS(i,u);for(let v in g)d.setAttribute(v,g[v]);return d},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=u=>Math.max(0,Math.min(1,u)),a=u=>u*u*(3-2*u),h=.5;function l(u,g){let d=0,v=0,f=null,M=0;function S(L){let w=(L-M)/g;M=L,d=d<v?Math.min(v,d+w):Math.max(v,d-w),u(d),f=d===v?null:requestAnimationFrame(S)}function p(L){if(v=L,r()){d=L,u(d);return}f===null&&(M=performance.now(),f=requestAnimationFrame(S))}return{play:()=>p(1),reverse:()=>p(0),toggle:()=>p(v?0:1),set:L=>{cancelAnimationFrame(f),f=null,v=d=L,u(d)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return d}}}function c(u,g,d,v){let f=o(v)*g;if(u.style.visibility=f<.05?"hidden":"visible",d==="both"){let M=f/2;u.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,g-2*M).toFixed(2)+" "+M.toFixed(2)),u.setAttribute("stroke-dashoffset","0")}else d==="end"?(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset",(-(g-f)).toFixed(2))):(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset","0"))}function b(u,g={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},g),v=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});v.style.display="block",v.style.width="100%",v.style.height="auto";let f=sLine truncated
"use strict";(()=>{(function(n){let t={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},e="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(u,y)=>{let d=document.createElementNS(i,u);for(let v in y)d.setAttribute(v,y[v]);return d},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=u=>Math.max(0,Math.min(1,u)),a=u=>u*u*(3-2*u),h=.5;function l(u,y){let d=0,v=0,f=null,M=0;function A(L){let x=(L-M)/y;M=L,d=d<v?Math.min(v,d+x):Math.max(v,d-x),u(d),f=d===v?null:requestAnimationFrame(A)}function p(L){if(v=L,r()){d=L,u(d);return}f===null&&(M=performance.now(),f=requestAnimationFrame(A))}return{play:()=>p(1),reverse:()=>p(0),toggle:()=>p(v?0:1),set:L=>{cancelAnimationFrame(f),f=null,v=d=L,u(d)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return d}}}function c(u,y,d,v){let f=o(v)*y;if(u.style.visibility=f<.05?"hidden":"visible",d==="both"){let M=f/2;u.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,y-2*M).toFixed(2)+" "+M.toFixed(2)),u.setAttribute("stroke-dashoffset","0")}else d==="end"?(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*y+20).toFixed(2)),u.setAttribute("stroke-dashoffset",(-(y-f)).toFixed(2))):(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*y+20).toFixed(2)),u.setAttribute("stroke-dashoffset","0"))}function g(u,y={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},y),v=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});v.style.display="block",v.style.width="100%",v.style.height="auto";let f=sLine truncated
+1 -1
View File
@@ -1 +1 @@
"use strict";(()=>{function v(t){let a=t.seed+"|"+t.level+"|"+t.x+"|"+t.y,o=2166136261;for(let r=0;r<a.length;r++)o=Math.imul(o^a.charCodeAt(r),16777619)>>>0;return o}function M(t,a){let o=new Array(t);for(let e=0;e<t;e++)o[e]=e;let r=a|0,n=()=>{r=r+1831565813|0;let e=Math.imul(r^r>>>15,1|r);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};for(let e=t-1;e>0;e--){let s=Math.floor(n()*(e+1)),i=o[e];o[e]=o[s],o[s]=i}return o}function A(t,a,o,r,n){t.drawImage(a,0,0);let e=n.cell,s=Math.floor(o/e),i=Math.floor(r/e);if(s<2||i<2)return;let c=s*i,f=M(c,v(n));for(let l=0;l<c;l++){let b=f[l];if(b===l)continue;let u=l%s*e,d=Math.floor(l/s)*e,h=b%s*e,I=Math.floor(b/s)*e;t.drawImage(a,u,d,e,e,h,I,e,e)}}var U=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),m=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function S(t,a){for(let o=a;o<64;o++){let r=t[o-15],n=t[o-2],e=(r>>>7|r<<25)^(r>>>18|r<<14)^r>>>3,s=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10;t[o]=t[o-16]+e+t[o-7]+s|0}}function k(t,a,o,r){let n=t[0],e=t[1],s=t[2],i=t[3],c=t[4],f=t[5],l=t[6],b=t[7];for(let u=o;u<r;u++){let d=b+((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&l)+U[u]+a[u]|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&e^n&s^e&s)|0;b=l,l=f,f=c,c=i+d|0,i=s,s=e,e=n,n=d+h|0}t[0]=n,t[1]=e,t[2]=s,t[3]=i,t[4]=c,t[5]=f,t[6]=l,t[7]=b}var H=new Int32Array(64),j=new Int32Array(8),F=new Int32Array(8);var C=new TextEncoder;function B(t,a,o){let r=C.encode(t),n=new Uint8Array(r.length+a.length+4);n.set(r),n.set(a,r.length);let e=r.length+a.length;return n[e]=o>>>24,n[e+1]=o>>>16&255,n[e+2]=o>>>8&255,n[e+3]=o&255,n}var y=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);this.target=new Int32Array(4);let r=new Uint8Array(64);r.set(B("luphoto-check",a,0)),r[33]=128,r[62]=33*8>>>8,r[63]=33*8&255;let n=this.w;for(let e=0;e<16;e++)n[e]=r[e*4]<<24|r[e*4+1]<<16|r[e*4+2]<<8|r[e*4+3];this.saltTail=r[28]<<24;for(let e=16;e<22;e++){let s=n[e-15],i=n[e-2],c=(s>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,f=(i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10;n[e]=n[e-16]+c+n[e-7]+f|0}this.mid.set(m),k(this.mid,n,0,7);for(let e=0;e<4;e++)this.target[e]=o[e*4]<<24|o[e*4+1]<<16|o[e*4+2]<<8|o[e*4+3]}run(a,o){let r=this.w,n=this.s,e=this.mid,s=this.target[0],i=this.saltTail;for(let c=a;c<o;c++)if(r[7]=i|c>>>8,r[8]=(c&255)<<24|8388608,S(r,22),n.set(e),k(n,r,7,64),(m[0]+n[0]|0)===s&&(m[1]+n[1]|0)===this.target[1]&&(m[2]+n[2]|0)===this.target[2]&&(m[3]+n[3]|0)===this.target[3])return c;return-1}};function p(t){let a=new Uint8Array(t.length>>>1);for(let o=0;o<a.length;o++)a[o]=parseInt(t.substr(o*2,2),16);return a}var x=self,g=new Map,O=typeof createImageBitmap=="function",w=self.OffscreenCanvas;x.onmessage=t=>{let a=t.data;if(a.type==="pow"){let o=new y(p(a.salt),p(a.check));x.postMessage({pow:o.run(0,2**a.bits)});return}if(a.type==="abort"){g.get(a.key)?.abort(),g.delete(a.key);return}E(a)};function T(t,a){if(!w)throw new Error("unsupported-offscreen");let o=new w(t.width,t.height),r=o.getContext("2d");if(!r)throw new Error("unsupported-offscreen");return A(r,t,t.width,t.height,a),t.close(),o.transferToImageBitmap()}async function E(t){if(!O){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(t.scramble&&!w){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;g.set(t.key,a);let o=performance.now();try{let r=await fetch(t.url,{signal:a.signal,credentials:"same-origin"});if(!r.ok)throw new Error("HTTP "+r.status);let n=await r.blob(),e=performance.now()-o,s=await createImageBitmap(n);if(t.scramble&&(s=T(s,t.scramble)),a.signal.aborted)throw s.close(),new Error("aborted");x.postMessage({key:t.key,ok:!0,bitmap:s,bytes:n.size,ms:e},[s])}catch(r){let n=r instanceof Error?r.message:String(r);x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:n})}finally{g.delete(t.key)}}})();
"use strict";(()=>{function M(e){let a=e.seed+"|"+e.level+"|"+e.x+"|"+e.y,o=2166136261;for(let n=0;n<a.length;n++)o=Math.imul(o^a.charCodeAt(n),16777619)>>>0;return o}function v(e,a){let o=new Array(e);for(let t=0;t<e;t++)o[t]=t;let n=a|0,r=()=>{n=n+1831565813|0;let t=Math.imul(n^n>>>15,1|n);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};for(let t=e-1;t>0;t--){let c=Math.floor(r()*(t+1)),l=o[t];o[t]=o[c],o[c]=l}return o}function w(e,a,o,n,r){e.drawImage(a,0,0);let t=r.cell,c=Math.floor(o/t),l=Math.floor(n/t);if(c<2||l<2)return;let s=c*l,i=v(s,M(r));for(let f=0;f<s;f++){let b=i[f];if(b===f)continue;let x=f%c*t,m=Math.floor(f/c)*t,h=b%c*t,I=Math.floor(b/c)*t;e.drawImage(a,x,m,t,t,h,I,t,t)}}var C=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),A=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function S(e,a){for(let o=a;o<64;o++){let n=e[o-15],r=e[o-2],t=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,c=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[o]=e[o-16]+t+e[o-7]+c|0}}function k(e,a,o,n){let r=e[0],t=e[1],c=e[2],l=e[3],s=e[4],i=e[5],f=e[6],b=e[7];for(let x=o;x<n;x++){let m=b+((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&i^~s&f)+C[x]+a[x]|0,h=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&t^r&c^t&c)|0;b=f,f=i,i=s,s=l+m|0,l=c,c=t,t=r,r=m+h|0}e[0]=r,e[1]=t,e[2]=c,e[3]=l,e[4]=s,e[5]=i,e[6]=f,e[7]=b}var E=new Int32Array(64),T=new Int32Array(8),j=new Int32Array(8);var p=4294967296,d=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);let n=this.w;for(let r=0;r<8;r++)n[r]=a.charCodeAt(r*4)<<24|a.charCodeAt(r*4+1)<<16|a.charCodeAt(r*4+2)<<8|a.charCodeAt(r*4+3);n[10]=-2147483648,n[15]=320,this.mid.set(A),k(this.mid,n,0,8),this.shift=32-Math.max(1,Math.min(32,o))}run(a,o,n){let r=this.w,t=this.s,c=this.mid,l=this.shift,s=A[0];r[8]=a|0;for(let i=o;i<n;i++)if(r[9]=i|0,S(r,16),t.set(c),k(t,r,8,64),!(s+t[0]>>>l))return i;return-1}};var u=self,y=new Map,U=typeof createImageBitmap=="function",g=self.OffscreenCanvas;u.onmessage=e=>{let a=e.data;if(a.type==="pow"){let o=new d(a.token,a.bits);for(let n=0;n<2097152;n++){let r=o.run(n,0,p);if(r>=0){u.postMessage({pow:n*p+r});return}}u.postMessage({pow:-1});return}if(a.type==="abort"){y.get(a.key)?.abort(),y.delete(a.key);return}O(a)};function B(e,a){if(!g)throw new Error("unsupported-offscreen");let o=new g(e.width,e.height),n=o.getContext("2d");if(!n)throw new Error("unsupported-offscreen");return w(n,e,e.width,e.height,a),e.close(),o.transferToImageBitmap()}async function O(e){if(!U){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(e.scramble&&!g){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;y.set(e.key,a);let o=performance.now();try{let n=await fetch(e.url,{signal:a.signal,credentials:"same-origin"});if(!n.ok)throw new Error("HTTP "+n.status);let r=await n.blob(),t=performance.now()-o,c=await createImageBitmap(r);if(e.scramble&&(c=B(c,e.scramble)),a.signal.aborted)throw c.close(),new Error("aborted");u.postMessage({key:e.key,ok:!0,bitmap:c,bytes:r.size,ms:t},[c])}catch(n){let r=n instanceof Error?n.message:String(n);u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:r})}finally{y.delete(e.key)}}})();
+1 -1
View File
@@ -24,7 +24,7 @@
<link rel="stylesheet" href="{{.Assets.CSS.URL}}">
<script src="{{.Assets.JS.URL}}" defer></script>
{{- end}}
{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}" data-gate="{{.Gate}}"{{end}}
{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}" data-gate="{{.Gate}}" data-min-entropy="{{.MinEntropy}}"{{end}}
{{define "footer"}}<footer class="site-footer">
<p class="footer-line">Guoliang Chen · <span lang="zh">陈国梁</span> · Lucio</p>
<span class="chop">{{.Assets.Chop}}</span>
+9 -2
View File
@@ -14,7 +14,7 @@ photos.luciochen.com {
@immutable path /t/* /og/* /assets/*
header @immutable Cache-Control "public, max-age=31536000, immutable"
@short not path /t/* /og/* /assets/*
@short not path /t/* /og/* /assets/* /k
header @short Cache-Control "public, max-age=60"
header {
@@ -24,7 +24,14 @@ photos.luciochen.com {
-Server
}
@methods not method GET HEAD
handle /k {
reverse_proxy 127.0.0.1:8080
}
@methods {
not method GET HEAD
not path /k
}
respond @methods 405
file_server {
+20 -5
View File
@@ -1,10 +1,25 @@
# Cloudflare
Run the site behind a Cloudflare Tunnel (`cloudflared.yml` in this folder). In serve mode the tunnel points at LuPhoto on `127.0.0.1:8080`. In export mode it points at Caddy or nginx; give that web server a plain HTTP listener on `127.0.0.1:8080` for the tunnel, for example `http://photos.luciochen.com:8080` in the Caddyfile, or `listen 127.0.0.1:8080;` in nginx.
Run the site behind a Cloudflare Tunnel (`cloudflared.yml` in this folder). In serve mode the tunnel points at LuPhoto on `127.0.0.1:8080`. In export mode it points at Caddy or nginx, and LuPhoto itself listens on `server.listen` (`127.0.0.1:8080` by default) for the key endpoint `/k`, so give the web server a different plain HTTP listener for the tunnel, for example `http://photos.luciochen.com:8081` in the Caddyfile, or `listen 127.0.0.1:8081;` in nginx, and point the tunnel there.
Cache rules (Caching → Cache Rules), in this order:
## Client addresses
1. Tiles, OG images and assets: when the URI path starts with `/t/`, `/og/` or `/assets/`, set *Eligible for cache*, Edge TTL 1 month (or "use cache-control header"), Browser TTL "respect origin". Their names are content-hashed, so they never change.
2. Everything else (HTML, `/a/*` including the per-photo pool files under `/a/<slug>/p/`, `index.<build>.json`, `robots.txt`): Edge TTL 1 minute or "respect origin" (`max-age=60`). Manifests and pool files are named after the build, so a new build needs no purge. Decoy tiles under `/t/` never change their bytes either, so rule 1 holds for them.
LuPhoto limits photo keys per visitor address, so it must see the real one. Through the tunnel every request reaches the origin from `cloudflared` on loopback, and Cloudflare puts the visitor's address in `CF-Connecting-IP`. In `/etc/luphoto/config.toml`:
Keep "Cache by device type" and query-string variations off. Hotlink protection is done by LuPhoto, Caddy or nginx on `/t/*`; Cloudflare's own Hotlink Protection can stay off, or be enabled for the same hostname.
```toml
[server]
trusted_proxies = ["127.0.0.1/32", "::1/128"]
client_ip_header = "CF-Connecting-IP"
```
`trusted_proxies` must list the address the request comes from when it reaches LuPhoto: loopback for `cloudflared`, Caddy or nginx on the same machine (they pass `CF-Connecting-IP` through unchanged). If `cloudflared` runs on another host, add that host's address. Never trust a range the public can connect from directly, or anyone can choose their own address. Without the tunnel, behind Caddy or nginx only, keep the default `"X-Forwarded-For"`.
## Cache rules
Caching → Cache Rules, in this order:
1. Key endpoint: when the URI path equals `/k`, *Bypass cache*. It is a per-visitor `POST` answered with `Cache-Control: no-store`; it must never be cached or served from the edge.
2. Tiles, OG images and assets: when the URI path starts with `/t/`, `/og/` or `/assets/`, set *Eligible for cache*, Edge TTL 1 month (or "use cache-control header"), Browser TTL "respect origin". Their names are content-hashed, so they never change.
3. Everything else (HTML, `/a/*` including the per-photo pool files under `/a/<slug>/p/`, `index.<build>.json`, `robots.txt`): Edge TTL 1 minute or "respect origin" (`max-age=60`). Manifests and pool files are named after the build, so a new build needs no purge. Decoy tiles under `/t/` never change their bytes either, so rule 2 holds for them.
Keep "Cache by device type" and query-string variations off. Hotlink protection is done by LuPhoto, Caddy or nginx on `/t/*`, and `/k` checks `Origin`; Cloudflare's own Hotlink Protection can stay off, or be enabled for the same hostname. Bot Fight Mode and similar challenges must not be applied to `/k`, because they would answer the browser's `fetch` with an HTML page.
+11 -4
View File
@@ -1,7 +1,9 @@
[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"
@@ -34,5 +36,10 @@ 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"
+16 -1
View File
@@ -4,6 +4,12 @@ map $http_referer $luphoto_hotlink {
"~^https?://photos\.luciochen\.com(:[0-9]+)?(/|$)" 0;
}
map "$request_method $uri" $luphoto_bad_method {
default 1;
"~^(GET|HEAD) " 0;
"POST /k" 0;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
@@ -21,7 +27,7 @@ server {
server_tokens off;
error_page 404 /404.html;
if ($request_method !~ ^(GET|HEAD)$) {
if ($luphoto_bad_method) {
return 405;
}
@@ -29,6 +35,15 @@ server {
return 404;
}
location = /k {
client_max_body_size 4k;
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
}
location = /404.html {
internal;
add_header Cache-Control "public, max-age=60" always;
+1
View File
@@ -12,6 +12,7 @@ server {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_buffering on;
}
+40 -24
View File
@@ -1,7 +1,9 @@
import { mountWordmark } from "./brand";
import { TileCache, cacheBudget } from "./cache";
import { Gate } from "./gate";
import { entropyScore, startEntropy } from "./entropy";
import { guardLink, takeNav, type GuardOptions } from "./gate";
import { IndexPage } from "./index";
import { AlbumKeys, fixedKeys } from "./keys";
import { Scheduler } from "./scheduler";
import { readSettings, type Manifest, type Settings, type SiteIndex } from "./types";
import { Viewer } from "./viewer";
@@ -18,27 +20,37 @@ function shared(settings: Settings): { scheduler: Scheduler; cache: TileCache }
return { scheduler: new Scheduler(settings.concurrency, settings.workerUrl), cache: new TileCache(cacheBudget()) };
}
async function startAlbum(stage: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
const manifest = await fetchJSON<Manifest>(settings.manifestUrl);
if (manifest.photos.length === 0) {
gate.abandon();
return;
function guardOptions(settings: Settings, minEntropy: () => number): GuardOptions | null {
if (settings.gate === "off") {
return null;
}
gate.configure(manifest.gate);
const { scheduler, cache } = shared(settings);
document.documentElement.classList.add("has-viewer");
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, gate, tiles: manifest.tiles }));
return { build: settings.build, workerUrl: settings.workerUrl, minEntropy, score: entropyScore };
}
async function startIndex(root: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
if (index.albums.length === 0) {
gate.abandon();
async function startAlbum(stage: HTMLElement, settings: Settings, nav: boolean): Promise<void> {
const manifest = await fetchJSON<Manifest>(settings.manifestUrl);
if (manifest.photos.length === 0) {
return;
}
gate.configure(index.gate);
const keys = new AlbumKeys(manifest.gate, manifest.slug, nav ? "nav" : "land", settings.workerUrl);
const { scheduler, cache } = shared(settings);
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, gate, tiles: index.tiles }));
document.documentElement.classList.add("has-viewer");
const minEntropy = manifest.gate.min_entropy ?? settings.minEntropy;
lifecycle(
new Viewer(stage, manifest, settings, { scheduler, cache, settings, keys, tiles: manifest.tiles }, keys, guardOptions(settings, () => minEntropy)),
);
}
async function startIndex(root: HTMLElement, settings: Settings, minEntropy: (value: number) => void): Promise<void> {
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
if (typeof index.gate.min_entropy === "number") {
minEntropy(index.gate.min_entropy);
}
if (index.albums.length === 0) {
return;
}
const { scheduler, cache } = shared(settings);
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, keys: fixedKeys(index.gate.cover), tiles: index.tiles }));
}
interface Suspendable {
@@ -68,15 +80,12 @@ function showLoadError(): void {
}
function boot(): void {
startEntropy();
const settings = readSettings(document.body);
if (settings.page === "album") {
const stage = document.getElementById("stage");
if (stage) {
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
startAlbum(stage, settings, gate).catch(() => {
gate.abandon();
showLoadError();
});
startAlbum(stage, settings, takeNav(settings.slug)).catch(showLoadError);
}
} else if (settings.page === "notfound") {
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
@@ -86,9 +95,16 @@ function boot(): void {
} else if (settings.page === "index") {
const root = document.getElementById("strips");
if (root) {
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
startIndex(root, settings, gate).catch(() => {
gate.abandon();
let minEntropy = settings.minEntropy;
const options = guardOptions(settings, () => minEntropy);
if (options) {
for (const anchor of Array.from(root.querySelectorAll<HTMLAnchorElement>("a.strip"))) {
guardLink(anchor, () => anchor.dataset.slug ?? "", options);
}
}
startIndex(root, settings, (value) => {
minEntropy = value;
}).catch(() => {
document.documentElement.classList.remove("has-strips");
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
if (header && !header.classList.contains("has-svg")) {
+203
View File
@@ -0,0 +1,203 @@
const storageKey = "luphoto.entropy";
const segment = 8;
const turnCos = Math.cos(Math.PI / 6);
const scrollGapMs = 100;
const touchSlop = 10;
interface Saved {
p: number;
t: number;
c: number;
g: number;
s: number;
k: number;
}
class Tracker {
private path = 0;
private turns = 0;
private cells = 0;
private gestures = 0;
private scrolls = 0;
private keys = 0;
private readonly seen = new Uint32Array(128);
private lastX = 0;
private lastY = 0;
private hasLast = false;
private segX = 0;
private segY = 0;
private prevX = 0;
private prevY = 0;
private hasPrev = false;
private touchId = -1;
private touchX = 0;
private touchY = 0;
private touchMoved = false;
private lastScroll = -Infinity;
private memory: Saved | null = null;
constructor() {
this.load();
const options: AddEventListenerOptions = { passive: true, capture: true };
addEventListener("pointermove", (e) => this.onMove(e), options);
addEventListener("pointerdown", (e) => this.onDown(e), options);
addEventListener("pointerup", (e) => this.onUp(e), options);
addEventListener("pointercancel", (e) => this.onCancel(e), options);
addEventListener("wheel", (e) => this.onScroll(e), options);
addEventListener("scroll", (e) => this.onScroll(e), options);
addEventListener("keydown", (e) => this.onKey(e), options);
addEventListener("pagehide", () => this.save());
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
this.save();
}
});
}
private onMove(e: PointerEvent): void {
if (!e.isTrusted) {
return;
}
const x = e.clientX;
const y = e.clientY;
if (e.pointerType !== "mouse") {
if (e.pointerId === this.touchId && !this.touchMoved && Math.abs(x - this.touchX) + Math.abs(y - this.touchY) > touchSlop) {
this.touchMoved = true;
}
return;
}
const h = (((x >> 3) * 73856093) ^ ((y >> 3) * 19349663)) & 4095;
const bit = 1 << (h & 31);
if ((this.seen[h >>> 5] & bit) === 0) {
this.seen[h >>> 5] |= bit;
this.cells++;
}
if (!this.hasLast) {
this.lastX = x;
this.lastY = y;
this.hasLast = true;
return;
}
const dx = x - this.lastX;
const dy = y - this.lastY;
this.lastX = x;
this.lastY = y;
if (dx === 0 && dy === 0) {
return;
}
this.path += Math.sqrt(dx * dx + dy * dy);
this.segX += dx;
this.segY += dy;
const length = Math.sqrt(this.segX * this.segX + this.segY * this.segY);
if (length < segment) {
return;
}
if (this.hasPrev) {
const previous = Math.sqrt(this.prevX * this.prevX + this.prevY * this.prevY);
if ((this.segX * this.prevX + this.segY * this.prevY) / (length * previous) < turnCos) {
this.turns++;
}
}
this.prevX = this.segX;
this.prevY = this.segY;
this.hasPrev = true;
this.segX = 0;
this.segY = 0;
}
private onDown(e: PointerEvent): void {
if (!e.isTrusted || e.pointerType === "mouse") {
return;
}
this.touchId = e.pointerId;
this.touchX = e.clientX;
this.touchY = e.clientY;
this.touchMoved = false;
}
private onUp(e: PointerEvent): void {
if (e.pointerId !== this.touchId) {
return;
}
if (this.touchMoved) {
this.gestures++;
}
this.touchId = -1;
}
private onCancel(e: PointerEvent): void {
if (e.pointerId !== this.touchId) {
return;
}
this.gestures++;
this.touchId = -1;
}
private onScroll(e: Event): void {
if (e.isTrusted && e.timeStamp - this.lastScroll >= scrollGapMs) {
this.lastScroll = e.timeStamp;
this.scrolls++;
}
}
private onKey(e: KeyboardEvent): void {
if (e.isTrusted && !e.repeat) {
this.keys++;
}
}
score(): number {
const mouse = Math.min(25, this.path / 120) + Math.min(35, this.turns * 2.5) + Math.min(20, this.cells / 6);
const total = mouse + Math.min(45, this.gestures * 8) + Math.min(15, this.scrolls * 1.5) + Math.min(20, this.keys * 2);
this.save();
return Math.min(100, Math.round(total));
}
private load(): void {
let saved: Saved | null = null;
try {
const raw = sessionStorage.getItem(storageKey);
saved = raw ? (JSON.parse(raw) as Saved) : null;
} catch {
saved = this.memory;
}
if (!saved) {
return;
}
const n = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
this.path = n(saved.p);
this.turns = n(saved.t);
this.cells = n(saved.c);
this.gestures = n(saved.g);
this.scrolls = n(saved.s);
this.keys = n(saved.k);
}
save(): void {
const saved: Saved = {
p: Math.round(this.path),
t: this.turns,
c: this.cells,
g: this.gestures,
s: this.scrolls,
k: this.keys,
};
this.memory = saved;
try {
sessionStorage.setItem(storageKey, JSON.stringify(saved));
} catch {
return;
}
}
}
let tracker: Tracker | null = null;
export function startEntropy(): void {
tracker ??= new Tracker();
}
export function entropyScore(): number {
startEntropy();
return tracker ? tracker.score() : 0;
}
+250 -167
View File
@@ -1,214 +1,276 @@
import { PowSearch, deriveKey, fromHex, toHex } from "./sha256";
import type { GateInfo } from "./types";
import { PowSearch, nonceSpan } from "./sha256";
const storageKey = "luphoto.pass";
const passKey = "luphoto.pass";
const navKey = "luphoto.nav";
const navTtlMs = 30000;
const holdMs = 900;
const sliceSize = 1 << 14;
const svgNS = "http://www.w3.org/2000/svg";
const line = "Press and hold to see the photos";
const passPattern = /^[A-Za-z0-9_-]{32}$/;
let memoryPass: string | null = null;
let memoryNav: string | null = null;
interface Pass {
build: string;
s: string;
export type KeyContext = "nav" | "land";
export interface Answer {
token: string;
nonce: number;
}
function readPass(): Pass | null {
export interface Puzzle {
token: string;
bits: number;
}
export interface KeyRequest {
build: string;
album: string;
photos: string[];
context: KeyContext;
entropy: number;
pass?: string;
page?: string;
challenge?: Answer;
}
export interface KeyReply {
keys?: Record<string, string>;
pass?: string;
page?: string;
stale?: boolean;
challenge?: Puzzle;
}
export class KeyError extends Error {
constructor(
readonly status: number,
readonly retryAfter: number,
) {
super("keys " + status);
}
}
export function readPass(): string {
let raw = memoryPass;
try {
raw = localStorage.getItem(storageKey) ?? raw;
raw = localStorage.getItem(passKey) ?? raw;
} catch {
raw = memoryPass;
}
if (!raw) {
return null;
}
try {
const pass = JSON.parse(raw) as Partial<Pass>;
if (typeof pass.build === "string" && typeof pass.s === "string" && /^[0-9a-f]{64}$/.test(pass.s)) {
return { build: pass.build, s: pass.s };
}
} catch {
return null;
}
return null;
return raw && passPattern.test(raw) ? raw : "";
}
function writePass(pass: Pass | null): void {
memoryPass = pass ? JSON.stringify(pass) : null;
export function writePass(pass: string | null): void {
memoryPass = pass;
try {
if (memoryPass) {
localStorage.setItem(storageKey, memoryPass);
if (pass) {
localStorage.setItem(passKey, pass);
} else {
localStorage.removeItem(storageKey);
localStorage.removeItem(passKey);
}
} catch {
return;
}
}
export class Gate {
key: Uint8Array | null = null;
private stored = false;
private found: Uint8Array | null = null;
private held = false;
private info: GateInfo | null = null;
private card: GateCard | null = null;
private worker: Worker | null = null;
private readonly listeners: Array<() => void> = [];
constructor(
private readonly build: string,
private readonly enabled: boolean,
private readonly workerUrl: string,
) {
if (!enabled) {
return;
}
const pass = readPass();
if (pass && pass.build === build) {
this.key = fromHex(pass.s);
this.stored = true;
return;
}
this.card = new GateCard(() => this.onHeld());
export function markNav(slug: string): void {
memoryNav = JSON.stringify({ slug, at: Date.now() });
try {
sessionStorage.setItem(navKey, memoryNav);
} catch {
return;
}
}
onUnlock(listener: () => void): void {
this.listeners.push(listener);
export function takeNav(slug: string): boolean {
let raw = memoryNav;
try {
raw = sessionStorage.getItem(navKey) ?? raw;
sessionStorage.removeItem(navKey);
} catch {
raw = memoryNav;
}
configure(info: GateInfo): void {
if (this.info) {
return;
}
this.info = info;
if (info.key) {
this.found = fromHex(info.key);
this.unlock(false);
return;
}
if (this.key && info.build !== this.build) {
this.reset();
return;
}
if (!this.key) {
this.search();
}
memoryNav = null;
if (!raw) {
return false;
}
reject(key: Uint8Array): void {
if (key !== this.key || !this.stored || !this.info || this.info.key) {
return;
}
this.reset();
try {
const nav = JSON.parse(raw) as { slug?: unknown; at?: unknown };
const age = Date.now() - Number(nav.at);
return nav.slug === slug && age >= 0 && age <= navTtlMs;
} catch {
return false;
}
}
abandon(): void {
this.card?.dismiss();
this.card = null;
this.worker?.terminate();
this.worker = null;
export async function requestKeys(body: KeyRequest): Promise<KeyReply> {
const response = await fetch("/k", {
method: "POST",
credentials: "same-origin",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!response.ok) {
throw new KeyError(response.status, Number(response.headers.get("Retry-After")) || 0);
}
return (await response.json()) as KeyReply;
}
private reset(): void {
writePass(null);
this.key = null;
this.stored = false;
this.held = false;
this.found = null;
if (!this.card) {
this.card = new GateCard(() => this.onHeld());
}
this.search();
}
private search(): void {
const info = this.info;
if (!info || !info.salt || !info.check || !info.bits || this.worker) {
return;
}
const salt = fromHex(info.salt);
const done = (n: number) => {
this.worker?.terminate();
this.worker = null;
if (n < 0) {
this.card?.fail();
return;
}
this.found = deriveKey(salt, n);
if (this.held) {
this.unlock(true);
}
};
const fallback = () => this.searchHere(salt, fromHex(info.check ?? ""), info.bits ?? 0, done);
if (typeof Worker === "undefined" || !this.workerUrl) {
fallback();
return;
}
try {
const worker = new Worker(this.workerUrl);
this.worker = worker;
worker.onmessage = (event: MessageEvent<{ pow?: number }>) => {
if (typeof event.data.pow === "number" && this.worker === worker) {
done(event.data.pow);
}
};
worker.onerror = () => {
if (this.worker === worker) {
worker.terminate();
this.worker = null;
fallback();
}
};
worker.postMessage({ type: "pow", salt: info.salt, check: info.check, bits: info.bits });
} catch {
this.worker = null;
fallback();
}
}
private searchHere(salt: Uint8Array, check: Uint8Array, bits: number, done: (n: number) => void): void {
const search = new PowSearch(salt, check);
const end = 2 ** bits;
function solveHere(puzzle: Puzzle): Promise<number> {
return new Promise((resolve) => {
const search = new PowSearch(puzzle.token, puzzle.bits);
let hi = 0;
let from = 0;
const step = () => {
const to = Math.min(end, from + sliceSize);
const n = search.run(from, to);
from = to;
if (n >= 0 || from >= end) {
done(n);
const to = Math.min(nonceSpan, from + sliceSize);
const lo = search.run(hi, from, to);
if (lo >= 0) {
resolve(hi * nonceSpan + lo);
return;
}
from = to;
if (from >= nonceSpan) {
hi++;
from = 0;
}
setTimeout(step, 0);
};
setTimeout(step, 0);
}
});
}
private onHeld(): void {
this.held = true;
if (this.found) {
this.unlock(true);
} else {
this.card?.wait();
}
export function solve(puzzle: Puzzle, workerUrl: string): Promise<number> {
if (puzzle.token.length !== 32 || !(puzzle.bits >= 1 && puzzle.bits <= 32)) {
return Promise.reject(new Error("puzzle"));
}
private unlock(remember: boolean): void {
if (!this.found) {
if (typeof Worker === "undefined" || !workerUrl) {
return solveHere(puzzle);
}
return new Promise((resolve, reject) => {
let worker: Worker;
try {
worker = new Worker(workerUrl);
} catch {
resolve(solveHere(puzzle));
return;
}
this.key = this.found;
this.stored = false;
if (remember && this.enabled) {
writePass({ build: this.info?.build ?? this.build, s: toHex(this.key) });
worker.onmessage = (event: MessageEvent<{ pow?: number }>) => {
const nonce = event.data.pow;
if (typeof nonce !== "number") {
return;
}
worker.terminate();
if (nonce < 0) {
reject(new Error("puzzle"));
} else {
resolve(nonce);
}
};
worker.onerror = () => {
worker.terminate();
resolve(solveHere(puzzle));
};
worker.postMessage({ type: "pow", token: puzzle.token, bits: puzzle.bits });
});
}
let active: Promise<KeyReply | null> | null = null;
export function challenge(
first: Promise<KeyReply>,
answer: (solution: Answer) => Promise<KeyReply>,
workerUrl: string,
cancellable: boolean,
): Promise<KeyReply | null> {
if (active) {
return active.then(() => null);
}
const run = new Promise<KeyReply | null>((resolve) => {
let held: () => void = () => undefined;
const holding = new Promise<void>((done) => {
held = done;
});
const card = new GateCard(
() => {
held();
card.wait();
},
cancellable ? () => resolve(null) : null,
);
const flow = async (): Promise<KeyReply> => {
let reply = await first;
while (reply.challenge) {
const puzzle = reply.challenge;
const nonce = solve(puzzle, workerUrl);
await holding;
reply = await answer({ token: puzzle.token, nonce: await nonce });
}
return reply;
};
flow().then(
(reply) => {
card.dismiss();
resolve(reply);
},
() => {
card.fail();
resolve(null);
},
);
});
active = run;
void run.then(() => {
active = null;
});
return run;
}
export interface GuardOptions {
build: string;
workerUrl: string;
minEntropy: () => number;
score: () => number;
}
export function guardLink(anchor: HTMLAnchorElement, slugOf: () => string, options: GuardOptions): void {
anchor.addEventListener("click", (e) => {
const slug = slugOf();
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !slug) {
return;
}
this.card?.dismiss();
this.card = null;
for (const listener of this.listeners) {
listener();
if (options.score() >= options.minEntropy() || readPass()) {
markNav(slug);
return;
}
e.preventDefault();
const href = anchor.href;
const base = (): KeyRequest => ({ build: options.build, album: slug, photos: [], context: "nav", entropy: options.score() });
void challenge(
requestKeys(base()),
(solution) => requestKeys({ ...base(), challenge: solution }),
options.workerUrl,
true,
).then((reply) => {
if (!reply) {
return;
}
if (reply.pass) {
writePass(reply.pass);
}
markNav(slug);
location.assign(href);
});
});
}
function capture(element: Element, pointerId: number): void {
try {
element.setPointerCapture(pointerId);
} catch {
return;
}
}
@@ -224,8 +286,12 @@ class GateCard {
private frame = 0;
private holding = false;
private finished = false;
private gone = false;
constructor(private readonly onHeld: () => void) {
constructor(
private readonly onHeld: () => void,
private readonly onCancel: (() => void) | null,
) {
this.restore = document.activeElement;
const root = document.createElement("div");
root.className = "gate";
@@ -292,7 +358,7 @@ class GateCard {
return;
}
e.preventDefault();
button.setPointerCapture(e.pointerId);
capture(button, e.pointerId);
this.press();
});
for (const type of ["pointerup", "pointercancel", "lostpointercapture"]) {
@@ -320,8 +386,20 @@ class GateCard {
this.root.remove();
}
});
if (this.onCancel) {
document.addEventListener("keydown", this.onEscape, true);
}
}
private readonly onEscape = (e: KeyboardEvent): void => {
if (e.key === "Escape" && !this.gone) {
e.preventDefault();
e.stopPropagation();
this.dismiss();
this.onCancel?.();
}
};
private setProgress(fraction: number): void {
this.ring.style.setProperty("stroke-dashoffset", String(100 - Math.max(0, Math.min(1, fraction)) * 100));
}
@@ -381,6 +459,11 @@ class GateCard {
}
dismiss(): void {
if (this.gone) {
return;
}
this.gone = true;
document.removeEventListener("keydown", this.onEscape, true);
cancelAnimationFrame(this.frame);
const hadFocus = this.root.contains(document.activeElement);
for (const element of this.inert) {
-11
View File
@@ -56,17 +56,6 @@ export class IndexPage {
this.measure();
this.observe();
this.bind();
env.gate.onUnlock(() => {
if (this.suspended) {
return;
}
for (const strip of this.strips) {
if (strip.isNear) {
strip.startSession();
}
strip.requestDraw();
}
});
}
suspend(hidden: boolean): void {
+203
View File
@@ -0,0 +1,203 @@
import { entropyScore } from "./entropy";
import { KeyError, challenge, readPass, requestKeys, writePass, type KeyContext, type KeyReply, type KeyRequest } from "./gate";
import { fromHex } from "./sha256";
import type { GateInfo } from "./types";
export interface KeySource {
key(hash: string): Uint8Array | null;
settle(hash: string, signal: AbortSignal): Promise<void>;
}
export function fixedKeys(hex: string): KeySource {
const key = /^[0-9a-f]{64}$/.test(hex) ? fromHex(hex) : null;
return { key: () => key, settle: () => Promise.resolve() };
}
const batchSize = 8;
const settleMs = 400;
const retryMs = 2000;
const keyPattern = /^[0-9a-f]{64}$/;
export class AlbumKeys implements KeySource {
private readonly keys = new Map<string, Uint8Array>();
private readonly inflight = new Set<string>();
private readonly waiters = new Set<() => void>();
private readonly listeners: Array<(fresh: string[]) => void> = [];
private queue: string[] = [];
private busy = false;
private blocked = false;
private failed = false;
private pausedUntil = 0;
private page = "";
private readonly server: boolean;
constructor(
private readonly gate: GateInfo,
private readonly slug: string,
private readonly context: KeyContext,
private readonly workerUrl: string,
) {
this.server = gate.mode !== "off";
if (!this.server) {
for (const [hash, hex] of Object.entries(gate.keys ?? {})) {
if (keyPattern.test(hex)) {
this.keys.set(hash, fromHex(hex));
}
}
}
}
onKeys(listener: (fresh: string[]) => void): void {
this.listeners.push(listener);
}
key(hash: string): Uint8Array | null {
return this.keys.get(hash) ?? null;
}
has(hash: string): boolean {
return this.keys.has(hash);
}
want(near: string[], ahead: string[]): void {
if (!this.server || near.every((hash) => this.keys.has(hash) || this.inflight.has(hash))) {
return;
}
const missing = (hash: string) => !this.keys.has(hash) && !this.inflight.has(hash);
this.queue = Array.from(new Set(near.concat(ahead))).filter(missing);
this.pump();
}
settle(hash: string, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (this.keys.has(hash) || this.blocked || this.failed || signal.aborted) {
resolve();
return;
}
const done = () => {
clearTimeout(timer);
this.waiters.delete(check);
signal.removeEventListener("abort", done);
resolve();
};
const check = () => {
if (this.keys.has(hash) || this.blocked || this.failed) {
done();
}
};
const timer = window.setTimeout(done, settleMs);
this.waiters.add(check);
signal.addEventListener("abort", done, { once: true });
});
}
private wake(): void {
for (const check of Array.from(this.waiters)) {
check();
}
}
private body(photos: string[], pass: string): KeyRequest {
const body: KeyRequest = { build: this.gate.build, album: this.slug, photos, context: this.context, entropy: entropyScore() };
if (pass) {
body.pass = pass;
}
if (this.page) {
body.page = this.page;
}
return body;
}
private pump(): void {
if (this.busy || this.blocked || this.failed || this.queue.length === 0 || performance.now() < this.pausedUntil) {
return;
}
const photos = this.queue.slice(0, batchSize);
this.queue = [];
void this.send(photos);
}
private pause(ms: number, photos: string[]): void {
this.pausedUntil = performance.now() + ms;
window.setTimeout(() => {
this.queue = Array.from(new Set(photos.concat(this.queue))).filter((hash) => !this.keys.has(hash) && !this.inflight.has(hash));
this.pump();
}, ms);
}
private async send(photos: string[]): Promise<void> {
this.busy = true;
for (const hash of photos) {
this.inflight.add(hash);
}
let pending: string[] = [];
let delay = 0;
try {
const pass = readPass();
const reply = await requestKeys(this.body(photos, pass));
this.absorb(reply, pass);
if (reply.challenge) {
this.blocked = true;
this.wake();
const solved = await challenge(
Promise.resolve(reply),
(solution) => requestKeys({ ...this.body(photos, ""), challenge: solution }),
this.workerUrl,
false,
);
this.blocked = false;
if (solved) {
this.absorb(solved, "");
} else {
this.failed = true;
}
}
} catch (error) {
if (error instanceof KeyError && error.status === 429) {
delay = Math.max(1, error.retryAfter) * 1000;
pending = photos;
} else if (error instanceof KeyError && error.status >= 400 && error.status < 500) {
this.failed = true;
} else {
delay = retryMs;
pending = photos;
}
} finally {
for (const hash of photos) {
this.inflight.delete(hash);
}
this.busy = false;
this.wake();
}
if (delay > 0) {
this.pause(delay, pending.filter((hash) => !this.keys.has(hash)));
} else {
this.pump();
}
}
private absorb(reply: KeyReply, sent: string): void {
if (reply.stale && sent && readPass() === sent) {
writePass(null);
}
if (reply.pass) {
writePass(reply.pass);
}
if (reply.page) {
this.page = reply.page;
}
const fresh: string[] = [];
for (const [hash, hex] of Object.entries(reply.keys ?? {})) {
if (keyPattern.test(hex) && !this.keys.has(hash)) {
this.keys.set(hash, fromHex(hex));
fresh.push(hash);
}
}
if (fresh.length > 0) {
this.wake();
for (const listener of this.listeners) {
listener(fresh);
}
}
}
}
+17 -11
View File
@@ -1,5 +1,5 @@
import type { TileCache } from "./cache";
import type { Gate } from "./gate";
import type { KeySource } from "./keys";
import { cellRect, drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
import { AbortError, PRIORITY_CURRENT, PRIORITY_PREFETCH, decodeBlob, releaseImage, type Scheduler, type TileResult } from "./scheduler";
import type { ScrambleSpec } from "./scramble";
@@ -12,7 +12,7 @@ export interface LoaderEnv {
cache: TileCache;
settings: Settings;
tiles: Tiles;
gate: Gate;
keys: KeySource;
requestDraw: () => void;
onStatus?: (loader: PhotoLoader) => void;
}
@@ -92,6 +92,7 @@ export class PhotoLoader {
private triedKey: Uint8Array | null = null;
private jumbleLevel = -1;
private jumble: string[] = [];
private settling = false;
private session: AbortController | null = null;
private prefetchController: AbortController | null = null;
finalLevel = -1;
@@ -104,6 +105,10 @@ export class PhotoLoader {
private readonly env: LoaderEnv,
) {}
get stalled(): boolean {
return !this.opened && !this.settling;
}
private tileUrl(id: string): string {
const tiles = this.env.tiles;
return tiles.path + this.pyramid.hash + "/" + id + "." + tiles.format;
@@ -144,7 +149,7 @@ export class PhotoLoader {
if (this.opened) {
return true;
}
const key = this.env.gate.key;
const key = this.env.keys.key(this.pyramid.hash);
const pool = this.pool;
if (!key || !pool || key === this.triedKey) {
return false;
@@ -161,7 +166,6 @@ export class PhotoLoader {
}
const levels = this.pyramid.levels;
if (!sealed || !Array.isArray(sealed.levels) || sealed.levels.length !== levels.length) {
this.env.gate.reject(key);
return false;
}
const ids: string[][] = [];
@@ -371,6 +375,14 @@ export class PhotoLoader {
if (signal.aborted) {
return;
}
if (ready && !this.open()) {
this.settling = true;
await this.env.keys.settle(this.pyramid.hash, signal);
this.settling = false;
if (signal.aborted) {
return;
}
}
if (!ready || !this.open()) {
const ids = this.chooseJumble(view, dpr);
await this.track(
@@ -444,13 +456,7 @@ export class PhotoLoader {
const controller = this.resetPrefetch();
const signal = controller.signal;
void this.ensurePool().then(async (ready) => {
if (signal.aborted || !ready) {
return;
}
if (!this.open()) {
for (const id of this.chooseJumble(view, dpr)) {
void this.fetchJumble(id, PRIORITY_PREFETCH, signal).catch(() => undefined);
}
if (signal.aborted || !ready || !this.open()) {
return;
}
await this.ensureSeed();
+23 -61
View File
@@ -94,82 +94,44 @@ export function sha256(message: Uint8Array, out: Uint8Array = new Uint8Array(32)
return out;
}
const encoder = new TextEncoder();
function labelled(label: string, salt: Uint8Array, n: number): Uint8Array {
const prefix = encoder.encode(label);
const message = new Uint8Array(prefix.length + salt.length + 4);
message.set(prefix);
message.set(salt, prefix.length);
const at = prefix.length + salt.length;
message[at] = n >>> 24;
message[at + 1] = (n >>> 16) & 255;
message[at + 2] = (n >>> 8) & 255;
message[at + 3] = n & 255;
return message;
}
export function deriveKey(salt: Uint8Array, n: number): Uint8Array {
return sha256(labelled("luphoto-key", salt, n));
}
export function checkFor(salt: Uint8Array, n: number): Uint8Array {
return sha256(labelled("luphoto-check", salt, n)).subarray(0, 16);
}
export const nonceSpan = 4294967296;
export class PowSearch {
private readonly w = new Int32Array(64);
private readonly mid = new Int32Array(8);
private readonly s = new Int32Array(8);
private readonly target = new Int32Array(4);
private readonly saltTail: number;
private readonly shift: number;
constructor(salt: Uint8Array, check: Uint8Array) {
const block = new Uint8Array(64);
block.set(labelled("luphoto-check", salt, 0));
block[33] = 0x80;
block[62] = (33 * 8) >>> 8;
block[63] = (33 * 8) & 255;
constructor(token: string, bits: number) {
const w = this.w;
for (let i = 0; i < 16; i++) {
w[i] = (block[i * 4] << 24) | (block[i * 4 + 1] << 16) | (block[i * 4 + 2] << 8) | block[i * 4 + 3];
}
this.saltTail = block[28] << 24;
for (let i = 16; i < 22; i++) {
const x = w[i - 15];
const y = w[i - 2];
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
for (let i = 0; i < 8; i++) {
w[i] =
(token.charCodeAt(i * 4) << 24) |
(token.charCodeAt(i * 4 + 1) << 16) |
(token.charCodeAt(i * 4 + 2) << 8) |
token.charCodeAt(i * 4 + 3);
}
w[10] = 0x80000000 | 0;
w[15] = 320;
this.mid.set(IV);
rounds(this.mid, w, 0, 7);
for (let i = 0; i < 4; i++) {
this.target[i] = (check[i * 4] << 24) | (check[i * 4 + 1] << 16) | (check[i * 4 + 2] << 8) | check[i * 4 + 3];
}
rounds(this.mid, w, 0, 8);
this.shift = 32 - Math.max(1, Math.min(32, bits));
}
run(from: number, to: number): number {
run(hi: number, from: number, to: number): number {
const w = this.w;
const s = this.s;
const mid = this.mid;
const t0 = this.target[0];
const tail = this.saltTail;
for (let n = from; n < to; n++) {
w[7] = tail | (n >>> 8);
w[8] = ((n & 255) << 24) | 0x800000;
expand(w, 22);
const shift = this.shift;
const h0 = IV[0];
w[8] = hi | 0;
for (let lo = from; lo < to; lo++) {
w[9] = lo | 0;
expand(w, 16);
s.set(mid);
rounds(s, w, 7, 64);
if (((IV[0] + s[0]) | 0) !== t0) {
continue;
}
if (
((IV[1] + s[1]) | 0) === this.target[1] &&
((IV[2] + s[2]) | 0) === this.target[2] &&
((IV[3] + s[3]) | 0) === this.target[3]
) {
return n;
rounds(s, w, 8, 64);
if ((h0 + s[0]) >>> shift === 0) {
return lo;
}
}
return -1;
+8 -6
View File
@@ -16,10 +16,10 @@ export interface Pyramid {
export interface GateInfo {
build: string;
salt?: string;
bits?: number;
check?: string;
key?: string;
mode: string;
cover: string;
min_entropy: number;
keys?: Record<string, string>;
}
export interface PoolFile {
@@ -109,7 +109,8 @@ export interface Settings {
maxDpr: number;
concurrency: number;
blockContextMenu: boolean;
gate: boolean;
gate: string;
minEntropy: number;
}
export function readSettings(body: HTMLElement): Settings {
@@ -129,7 +130,8 @@ export function readSettings(body: HTMLElement): Settings {
maxDpr: num(data.maxDpr, 2),
concurrency: Math.max(1, Math.round(num(data.concurrency, 6))),
blockContextMenu: data.blockContextMenu !== "false",
gate: data.gate !== "false",
gate: data.gate === "off" ? "off" : "server",
minEntropy: data.minEntropy && Number.isFinite(Number(data.minEntropy)) ? Number(data.minEntropy) : 20,
};
}
+41 -11
View File
@@ -1,7 +1,9 @@
import { cloneChop, mountWordmark } from "./brand";
import { CaptionPanel, setLang } from "./caption";
import type { View } from "./geometry";
import { guardLink, type GuardOptions } from "./gate";
import { BusyIndicator, ProgressLine } from "./indicator";
import { fixedKeys, type AlbumKeys } from "./keys";
import { PhotoLoader, type LoaderEnv } from "./loader";
import { Strip } from "./strip";
import { poolUrl, type Manifest, type Settings, type SiteIndex } from "./types";
@@ -109,6 +111,7 @@ export class Viewer {
private readonly progress: ProgressLine;
private readonly homeMark: HTMLElement | null;
private nextStrip: Strip | null = null;
private nextSlug = "";
private idleTimer = 0;
private announceTimer = 0;
private suspended = false;
@@ -161,6 +164,8 @@ export class Viewer {
private readonly manifest: Manifest,
private readonly settings: Settings,
private readonly env: Omit<LoaderEnv, "requestDraw" | "onStatus">,
private readonly keys: AlbumKeys,
guard: GuardOptions | null,
) {
this.canvas = document.createElement("canvas");
this.canvas.className = "stage-canvas";
@@ -197,12 +202,15 @@ export class Viewer {
this.measure();
this.current = this.stopForHash();
this.camera = this.stops[this.current].camera;
keys.onKeys((fresh) => this.onKeys(fresh));
if (guard) {
guardLink(this.nextLink, () => this.nextSlug, guard);
}
this.bind();
this.activate(-1);
this.requestDraw();
this.wake();
this.loadNextAlbum();
env.gate.onUnlock(() => this.onUnlock());
}
private buildEndCard(): HTMLElement {
@@ -869,6 +877,9 @@ export class Viewer {
if ((previousStop >= 0 || location.hash !== "") && location.hash !== "#" + (stop.photo + 1)) {
history.replaceState(history.state, "", "#" + (stop.photo + 1));
}
}
this.wantKeys();
if (stop.photo >= 0) {
this.startSession();
}
this.syncNextStrip();
@@ -930,20 +941,38 @@ export class Viewer {
this.requestDraw();
}
private onUnlock(): void {
private wantKeys(): void {
const photos = this.manifest.photos;
const stop = this.stops[this.current];
const at = stop.photo < 0 ? photos.length - 1 : stop.photo;
const pick = (offsets: number[]): string[] => {
const out: string[] = [];
for (const offset of offsets) {
const i = at + offset;
if (i >= 0 && i < photos.length) {
out.push(photos[i].hash);
}
}
return out;
};
this.keys.want(pick([0, 1, -1, 2, 3]), pick([4, 5, 6, 7, -2, 8, 9]));
}
private onKeys(fresh: string[]): void {
if (this.suspended) {
return;
}
const photos = this.manifest.photos;
const got = (i: number) => i >= 0 && i < photos.length && fresh.includes(photos[i].hash);
const stop = this.stops[this.current];
if (this.zoomPhoto >= 0) {
this.startZoomSession();
} else {
this.startSession();
}
if (this.nextStrip) {
if (this.nextStrip.isNear) {
this.nextStrip.startSession();
if (got(this.zoomPhoto) && this.loader(this.zoomPhoto).stalled) {
this.startZoomSession();
}
this.nextStrip.requestDraw();
} else if (stop.photo >= 0 && got(stop.photo) && this.loader(stop.photo).stalled) {
this.startSession();
} else if (stop.photo >= 0 && got(stop.photo + 1) && !this.loader(stop.photo).status.active) {
this.prefetchAround(this.current);
}
this.requestDraw();
}
@@ -1058,6 +1087,7 @@ export class Viewer {
return;
}
this.nextLink.href = "/a/" + encodeURIComponent(next.slug) + "/";
this.nextSlug = next.slug;
const eyebrow = this.nextLink.querySelector(".next-eyebrow");
const title = this.nextLink.querySelector(".next-title");
if (eyebrow) {
@@ -1073,7 +1103,7 @@ export class Viewer {
next.cover,
next.collapsed_focus_y ?? 0.5,
poolUrl(index.build, next.slug, next.cover.hash),
{ ...this.env, tiles: index.tiles },
{ ...this.env, keys: fixedKeys(index.gate.cover), tiles: index.tiles },
() => undefined,
);
this.nextLink.classList.add("has-strip");
+11 -5
View File
@@ -1,5 +1,5 @@
import { unscramble, type ScrambleSpec } from "./scramble";
import { PowSearch, fromHex } from "./sha256";
import { PowSearch, nonceSpan } from "./sha256";
interface FetchMessage {
type: "fetch";
@@ -15,8 +15,7 @@ interface AbortMessage {
interface PowMessage {
type: "pow";
salt: string;
check: string;
token: string;
bits: number;
}
@@ -55,8 +54,15 @@ const Offscreen = (self as unknown as { OffscreenCanvas?: OffscreenConstructor }
scope.onmessage = (event) => {
const message = event.data;
if (message.type === "pow") {
const search = new PowSearch(fromHex(message.salt), fromHex(message.check));
scope.postMessage({ pow: search.run(0, 2 ** message.bits) });
const search = new PowSearch(message.token, message.bits);
for (let hi = 0; hi < 2097152; hi++) {
const lo = search.run(hi, 0, nonceSpan);
if (lo >= 0) {
scope.postMessage({ pow: hi * nonceSpan + lo });
return;
}
}
scope.postMessage({ pow: -1 });
return;
}
if (message.type === "abort") {