Files
poli0981andClaude Opus 5.5 a3bfe04b40 Compact catalog packs, binary cache, themed scrollbars; bump to 4.2.0 (#103) [skip-discuss]
- Catalog packs: the build emits /data/pack/manifest-v1.json plus
  content-hashed deflate-raw packs (columns + dictionaries); the site and
  the apps read them (about 264 KB on a first visit instead of about 520 KB
  of JSON). Descriptions live in their own packs and load on demand (a game
  page: its chunk; a search: all of them).
- The IndexedDB cache is stored as compressed bytes by a small binary
  persister (replaces @tanstack/query-async-storage-persister); fflate is
  the lazy fallback where the browser has no Compression Streams.
- The readable /data/*.json goes only to apps 4.0-4.1.1 (Tauri Origin);
  everyone else gets a 410 with links to the repository
  (worker/legacy-data.ts, five positive run_worker_first entries).
- /img: exact width strings only, fallback originals and missing images
  kept at the edge for a day, failed background puts are logged.
- Themed scrollbars and a "Hide scrollbars" setting (Settings and the
  display menu); chart cards no longer block their list scrollbars.
- Policies (LEGAL_VERSION 2026-10-03): data reuse goes through the
  repository. Docs, changelog and version 4.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 19:19:42 +07:00

173 lines
6.7 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* GET /img/<width>/<path on img.itch.zone> — resized game covers.
*
* Covers are stored in the catalog as full-size itch.io originals (often
* 1–3 MB, some animated GIFs) but shown at 64–320 px. This route serves a
* WebP rendered once per (image, width) by Cloudflare Image Transformations
* and kept in R2, so the monthly unique-transformation quota is spent only
* on new images. Lookup order: edge cache → R2 → transform (→ R2 + cache).
*
* Safety: the upstream host is fixed (no open proxy / SSRF), the path must
* match a thumbnail that is in the catalog (/data/urls.json), and only two
* widths exist. When a transform fails (quota error 9422, bad source) the
* original is streamed through with a short cache instead of being stored in
* R2; it and a missing upstream image are kept in the edge cache for a day, so
* repeat requests don't redo the whole chain.
*/
import { catalogUrls } from './data'
import { SECURITY_HEADERS } from './http'
const ITCH_IMG = 'https://img.itch.zone/'
// Exact spellings only: Number() would also take "0160", "160.0" or "0xa0" and
// give the same image several edge-cache keys. A Map, not an object: no
// "constructor" from the prototype.
const WIDTHS = new Map([
['160', 160],
['640', 640],
])
const SEGMENT = /^[A-Za-z0-9%+=_.-]{1,200}$/
const YEAR = 'public, max-age=31536000, immutable'
const DAY = 'public, max-age=86400'
export interface ImgDeps {
/** Static assets (reads /data/urls.json). */
assets: Pick<Fetcher, 'fetch'>
bucket: Pick<R2Bucket, 'get' | 'put'>
/** Edge cache; absent in tests / local dev. */
cache?: Pick<Cache, 'match' | 'put'>
fetch: typeof fetch
waitUntil: (p: Promise<unknown>) => void
}
export interface ParsedImgPath {
width: number
upstream: string
}
/** Validate `/img/<w>/<a>/<b>/<file>`; keeps percent-encoding verbatim. */
export function parseImgPath(pathname: string): ParsedImgPath | null {
const parts = pathname.split('/').slice(2) // ['', 'img', w, ...rest]
if (parts.length < 2) return null
const width = WIDTHS.get(parts[0])
const rest = parts.slice(1)
if (width === undefined) return null
if (rest.length < 2 || rest.length > 4) return null
if (!rest.every((s) => SEGMENT.test(s) && s !== '.' && s !== '..')) return null
return { width, upstream: ITCH_IMG + rest.join('/') }
}
export async function r2Key(width: number, upstream: string): Promise<string> {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(upstream))
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
return `w${width}/${hex}.webp`
}
// Set of catalog thumbnail URLs, derived once per loaded map.
const thumbSets = new WeakMap<Map<string, string>, Set<string>>()
function thumbnailSet(urls: Map<string, string>): Set<string> {
let set = thumbSets.get(urls)
if (!set) {
set = new Set(urls.values())
thumbSets.set(urls, set)
}
return set
}
function imageResponse(body: BodyInit | null, type: string, cacheControl: string): Response {
return new Response(body, {
headers: {
'Content-Type': type,
'Cache-Control': cacheControl,
'Content-Security-Policy': "default-src 'none'; sandbox",
...SECURITY_HEADERS,
},
})
}
function plain(status: number, cacheControl = 'public, max-age=300'): Response {
return new Response(null, { status, headers: { 'Cache-Control': cacheControl, ...SECURITY_HEADERS } })
}
/** Keeps a copy at the edge in the background; its Cache-Control decides for how long. */
function remember(deps: ImgDeps, key: Request, res: Response): void {
if (!deps.cache) return
deps.waitUntil(deps.cache.put(key, res.clone()).catch((e) => console.warn('img: edge cache put failed', e)))
}
export async function handleImg(request: Request, url: URL, deps: ImgDeps): Promise<Response> {
if (request.method !== 'GET' && request.method !== 'HEAD') return plain(405, 'no-store')
// Cheap hotlink protection: other sites can't embed our resized copies.
if (request.headers.get('sec-fetch-site') === 'cross-site') return plain(403, 'no-store')
const parsed = parseImgPath(url.pathname)
if (!parsed) return plain(400)
const { width, upstream } = parsed
let thumbnails: Set<string>
try {
const urls = await catalogUrls({ assets: deps.assets, origin: url.origin })
thumbnails = thumbnailSet(urls)
} catch {
return plain(503, 'no-store')
}
if (!thumbnails.has(upstream)) return plain(404)
const cacheKey = new Request(`${url.origin}${url.pathname}`)
const cached = await deps.cache?.match(cacheKey)
if (cached) return cached
// Upstream resets and R2 errors reject: answer with a controlled 502, not
// an uncaught exception (Cloudflare error 1101).
try {
const key = await r2Key(width, upstream)
const stored = await deps.bucket.get(key)
if (stored) {
const res = imageResponse(stored.body, 'image/webp', YEAR)
remember(deps, cacheKey, res)
return res
}
const transformed = await deps.fetch(upstream, {
cf: { image: { width, fit: 'scale-down', format: 'webp', quality: 78, anim: false } },
} as RequestInit)
if (transformed.ok && transformed.headers.get('content-type') === 'image/webp') {
const bytes = await transformed.arrayBuffer()
const res = imageResponse(bytes, 'image/webp', YEAR)
deps.waitUntil(
deps.bucket
.put(key, bytes, { httpMetadata: { contentType: 'image/webp' } })
.catch((e) => console.warn('img: R2 put failed', e)),
)
remember(deps, cacheKey, res)
return res
}
discard(transformed)
// Transformation unavailable (quota 9422, unsupported source…): stream the
// original, keep it at the edge for a day, do not store it in R2.
const original = await deps.fetch(upstream, { cf: { cacheEverything: true, cacheTtl: 86400 } } as RequestInit)
const type = original.headers.get('content-type') ?? ''
const usable = original.ok && type.startsWith('image/') && !type.includes('svg')
if (!usable || request.method === 'HEAD') discard(original)
// itch.zone answers 403 for some broken originals: treat like a missing image.
if ([403, 404, 410].includes(original.status)) {
const missing = plain(404, DAY)
remember(deps, cacheKey, missing)
return missing
}
if (!usable) return plain(502, 'no-store')
if (request.method === 'HEAD') return imageResponse(null, type, DAY)
const res = imageResponse(original.body, type, DAY)
// GET only: a HEAD answer has no body to keep.
remember(deps, cacheKey, res)
return res
} catch {
return plain(502, 'no-store')
}
}
/** Release the connection of a response whose body is not used. */
function discard(res: Response): void {
res.body?.cancel().catch(() => {})
}