diff --git a/.gitignore b/.gitignore index 74f9b21..f173017 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ /dist/ *.tmp-* /web/node_modules/ +/.tools/ diff --git a/Makefile b/Makefile index 498f184..ef8c3e3 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,23 @@ -GO ?= go -BIN := bin/luphoto +GO ?= go +VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) +LDFLAGS := -s -w -X main.version=$(VERSION) +BIN := bin/luphoto -.PHONY: build deb clean +.PHONY: web build dist deb clean + +web: + npm --prefix web ci + npm --prefix web run build build: - $(GO) build -trimpath -o $(BIN) ./cmd/luphoto + $(GO) build -trimpath -ldflags "$(LDFLAGS)" -o $(BIN) ./cmd/luphoto + +dist: + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build -trimpath -ldflags "$(LDFLAGS)" -o dist/linux_amd64/luphoto ./cmd/luphoto + CGO_ENABLED=0 GOOS=linux GOARCH=arm64 $(GO) build -trimpath -ldflags "$(LDFLAGS)" -o dist/linux_arm64/luphoto ./cmd/luphoto deb: - @echo "deb packaging arrives in milestone M6" >&2 - @exit 1 + scripts/package.sh clean: - rm -rf bin + rm -rf bin dist diff --git a/README.md b/README.md index 3a97807..bb14168 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,146 @@ # LuPhoto -LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into 512 px tiles at several resolutions with libvips, and publishes a static site that the browser stitches back together on a canvas. See [docs/DESIGN.md](docs/DESIGN.md). +LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into 512 px WebP tiles at several resolutions with libvips, and publishes a static site in which the browser stitches the visible tiles back together on a canvas. Design: [docs/DESIGN.md](docs/DESIGN.md). -Status: milestone M1, the processor CLI. `luphoto build` scans the albums, builds tile pyramids, writes manifests and switches the `current` build. `serve` and `export` run one build and exit until M6. +## Commands -## Develop +``` +luphoto [-config /etc/luphoto/config.toml] +``` -All builds and runs happen in Docker (Ubuntu 24.04 with Go and libvips-tools); the Windows host has no libvips. From Git Bash or any POSIX shell: +| Command | What it does | +|---|---| +| `build` | Process the albums once, publish a new build, exit. | +| `serve` | Build, watch the albums folder, rebuild after changes, and serve the site over HTTP on `server.listen`. | +| `export` | Build, watch and rebuild; no HTTP. Point Caddy or nginx at `/current`. | +| `run` | `serve` or `export`, whichever `server.mode` says. The systemd unit uses this. | +| `version` | Print the version. | + +A missing config file means all defaults. `SIGHUP` re-reads the config and rebuilds (an invalid config is logged and the old one kept; a new `server.listen` restarts the listener). `SIGINT`/`SIGTERM` stop gracefully. Rebuilds never overlap; changes during a build cause one follow-up build. + +## Album folders + +``` +/srv/luphoto/albums/ + 2026-10-iceland/ + album.json + DSC_0001.jpg + PANO_0007.jpg +``` + +The folder name is the album slug (`/a/2026-10-iceland/`). Only JPEGs listed in `album.json` are processed and shown. An album whose `album.json` is broken is skipped and logged; if the previous build had it, that version stays live. + +```json +{ + "title": "Iceland, in October", + "subtitle": "冰岛 · 十月", + "date": "2026-10", + "order": 10, + "hidden": false, + "cover": { "photo": "PANO_0007.jpg", "crop": [0, 410, 8256, 2322] }, + "collapsed_focus_y": 0.5, + "show_exif": true, + "photos": [ + { "file": "DSC_0001.jpg", "title": "Vík", "caption": "Black sand, *7 a.m.*", "alt": "A black sand beach" }, + { "file": "PANO_0007.jpg", "caption": "Two screens wide", "slides": 2 } + ] +} +``` + +| Field | Type | Default | Meaning | +|---|---|---|---| +| `title` | string | folder name | Album title, sentence case. | +| `subtitle` | string | none | Second line, for example the Chinese title. | +| `date` | `YYYY`, `YYYY-MM` or `YYYY-MM-DD` | none | Shown as the eyebrow; sorts albums without `order`, newest first. | +| `order` | integer | none | Albums with `order` come first, ascending. | +| `hidden` | bool | `false` | Built and reachable by URL, but left off the index. | +| `cover.photo` | file name | first photo | Photo the 32:9 cover is cut from. Must be listed in `photos`. | +| `cover.crop` | `[x, y, w, h]` | none | Cover rectangle in pixels of the upright photo. | +| `cover.focus_y` | 0–1 | 0.5 | Without `crop`: a 32:9 band at full width centred at this height. | +| `collapsed_focus_y` | 0–1 | 0.5 | Which 32:6 band of the cover a closed index strip shows. | +| `show_exif` | bool | `true` | Put camera, lens, focal length, aperture, shutter, ISO and date into the manifest and caption line. GPS is never kept. | +| `photos[].file` | file name | required | A `.jpg`/`.jpeg` in the album folder. Order of the list is the viewing order. | +| `photos[].title` | string | none | Caption title. | +| `photos[].caption` | string | none | Plain text; `*emphasis*` and line breaks only. | +| `photos[].alt` | string | none | Text alternative for screen readers. | +| `photos[].slides` | integer ≥ 1 | 1 | Show a wide photo as N viewport-wide sections with a continuous pan. | + +Unknown fields are errors, so typos are caught. + +## Config + +`/etc/luphoto/config.toml`; every key is optional. `packaging/config.toml` is the production file. + +| Key | Default | Meaning | +|---|---|---| +| `server.mode` | `"export"` | What `luphoto run` does: `"serve"` or `"export"`. | +| `server.listen` | `"127.0.0.1:8080"` | Address of the built-in HTTP server. | +| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs. | +| `paths.albums` | `"/srv/luphoto/albums"` | Album folders. Read only. | +| `paths.output` | root or systemd: `/var/lib/luphoto/site`, else `$XDG_DATA_HOME/luphoto/site` | Builds, tiles, `current`. The site key and per-photo records go to `state/` next to it. | +| `paths.cache` | root or systemd: `/var/cache/luphoto`, else the user cache dir | Temporary vips files. | +| `images.tile_size` | `512` | Tile edge in pixels. | +| `images.overlap` | `1` | Tile overlap in pixels. | +| `images.format` | `"webp"` | `"webp"` or `"avif"` (AVIF needs a libheif AV1 encoder). | +| `images.quality` | `{ top = 82, mid = 85, low = 88 }` | Top two levels, levels above 1100 px, levels up to 1100 px. | +| `images.min_levels` | `6` | Minimum pyramid depth. | +| `images.seed_px` | `48` | Long edge of the blurred placeholder. | +| `images.tile_names` | `"hashed"` | Only `"hashed"` in v1. | +| `images.scramble_cells` | `false` | Reserved for M7. | +| `loading.budget_ms` | `3000` | Time budget per photo in the browser. | +| `loading.max_dpr` | `2.0` | Highest device pixel ratio the loader honours. | +| `loading.concurrency` | `6` | Parallel tile requests. | +| `build.watch` | `true` | Watch the albums folder in `serve` and `export`. | +| `build.debounce` | `"30s"` | Quiet time after the last change before rebuilding. | +| `build.workers` | `2` | Photos processed in parallel. vips threads per photo = CPUs ÷ workers. | +| `build.keep_builds` | `3` | Builds kept; tiles 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. | + +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. + +## Install + +### Ubuntu 22.04 / 24.04, Debian 12 + +```sh +sudo apt install ./luphoto__amd64.deb +sudoedit /etc/luphoto/config.toml +sudo systemctl enable --now luphoto +``` + +The package depends on `libvips-tools` and creates: + +- user and group `luphoto`, and group `luphoto-upload`; +- `/srv/luphoto/albums` (root:luphoto-upload, mode 2775, so members of `luphoto-upload` can upload); +- `/var/lib/luphoto` and `/var/cache/luphoto` (owned by `luphoto`); +- `/etc/luphoto/config.toml` (kept on upgrade), `/usr/lib/systemd/system/luphoto.service`, and examples in `/usr/share/doc/luphoto/`. + +The unit runs `luphoto run` as `luphoto` with `ProtectSystem=strict`, the albums read only, and only `/var/lib/luphoto` and `/var/cache/luphoto` writable. `systemctl reload luphoto` sends SIGHUP. + +### Other distributions + +Unpack `luphoto__linux_.tar.gz` and follow its `INSTALL.md`. You need libvips 8.12+ with its command-line tools. + +## Uploading + +Add yourself to `luphoto-upload` (`sudo usermod -aG luphoto-upload $USER`, then log in again), then: + +```sh +rsync -av --chmod=Dg+rwxs,Fg+rw 2026-10-iceland/ server:/srv/luphoto/albums/2026-10-iceland/ +``` + +rsync writes to dotted temp names and renames at the end, which the watcher ignores; the rebuild starts `build.debounce` after the last file lands. SFTP clients that upload to `*.part` work the same way. + +## Web server + +- **Serve mode**: LuPhoto serves `current` itself with the right headers (immutable caching for `/t/`, `/og/`, `/assets/`; one minute for HTML and JSON; CSP; hotlink 403 on `/t/*`; precompressed gzip; no directory listings). 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`. +- **Cloudflare**: `packaging/cloudflared.yml` and `packaging/cloudflare.md` (cache rules). + +## Building from source + +Development runs in Docker; the Windows host needs no libvips. From Git Bash or any POSIX shell: ```sh scripts/dev.sh go build -o bin/luphoto ./cmd/luphoto @@ -14,44 +148,35 @@ scripts/dev.sh go vet ./... scripts/dev.sh ``` -The image has no make; the `Makefile` is for hosts that have Go and make. The first call builds the `luphoto-dev` image. The repository is mounted at `/src`; Go module and build caches live in the `luphoto-gomod` and `luphoto-gocache` volumes. Extra `docker run` arguments, such as a mount for sample albums, go in `LUPHOTO_DEV_ARGS`: +`scripts/dev.sh` builds the `luphoto-dev` image (Ubuntu 24.04, Go, libvips-tools) on first use, mounts the repository at `/src` and keeps Go caches in volumes. Extra `docker run` arguments go in `LUPHOTO_DEV_ARGS`, for example `LUPHOTO_DEV_ARGS="-v /path/to/work:/work -p 127.0.0.1:8080:8080"`. -```sh -LUPHOTO_DEV_ARGS="-v /path/to/work:/work" scripts/dev.sh bin/luphoto -config /work/config.toml build -``` +`scripts/package.sh` builds static binaries (`CGO_ENABLED=0`, `-trimpath`, `-ldflags "-s -w -X main.version=…"`) for amd64 and arm64, the `.deb` packages (nfpm, installed into `.tools/` on first use) and the tarballs into `dist/`, all inside the dev container. Set `VERSION` to override `git describe`. The `Makefile` has `web`, `build`, `dist` and `deb` targets for hosts with make. -`LUPHOTO_DEV_REBUILD=1` rebuilds the image. +### Front-end -## Run - -```sh -luphoto [-config /etc/luphoto/config.toml] build -``` - -A missing config file means all defaults. Paths default to `/srv/luphoto/albums`, `/var/lib/luphoto/site` and `/var/cache/luphoto` when running as root or under systemd, otherwise to the XDG data and cache folders. The site key and per-photo records live in `state/` next to the output folder. - -Output layout: - -``` -site/ - current -> builds/ - builds//index.html, index..json, a//index.html, a//manifest..json, t -> ../../t - t//.webp - og/.jpg -state/ - site.key - pyramids/.json -``` - -## Front-end - -TypeScript and CSS live in `web/src`; the minified bundles in `internal/site/static` are committed, so `go build` never needs Node. After changing the front-end, rebuild on the host with Node 22: +TypeScript and CSS live in `web/src`. The minified bundles, fonts, favicon and chop in `internal/site/static` are committed, so `go build` never needs Node. After changing the front-end, rebuild on a host with Node 22: ```sh npm --prefix web ci npm --prefix web run build ``` -`build` type-checks with `tsc --noEmit` (strict) and bundles `app.js`, `app.css`, `worker.js`, the favicon, the chop and the self-hosted woff2 fonts (latin and latin-ext of Bricolage Grotesque, IBM Plex Sans and IBM Plex Mono, from the `@fontsource` packages) with esbuild. Each site build copies them to `/assets/` under content-hashed names. +This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts are self-hosted from the `@fontsource` packages (latin and latin-ext only). Each site build writes the files to `/assets/` under content-hashed names. -Brand files come from the Lucio brand repository. `scripts/sync-brand.sh` copies the tokens, `lucio-morph.js`, the favicon and the chop from `../LUCIO_ip` (or `$LUCIO_IP_DIR`) into `web/brand/`, stripping comments; the copies are committed. +### Brand + +`scripts/sync-brand.sh` copies the tokens, `lucio-morph.js`, the favicon and the chop from `../LUCIO_ip` (or `$LUCIO_IP_DIR`) into `web/brand/`, stripping comments. The copies are committed; rebuild the front-end afterwards. + +## Output layout + +``` +/var/lib/luphoto/ + site/ + current -> builds/ + builds//index.html, index..json, a//index.html, a//manifest..json, assets/, t -> ../../t, og -> ../../og + t//.webp + og/.jpg + state/ + site.key + pyramids/.json +``` diff --git a/cmd/luphoto/main.go b/cmd/luphoto/main.go index 23086f5..41ec717 100644 --- a/cmd/luphoto/main.go +++ b/cmd/luphoto/main.go @@ -10,19 +10,28 @@ import ( "os/signal" "syscall" + "github.com/luciochen233/luphoto/internal/app" "github.com/luciochen233/luphoto/internal/build" "github.com/luciochen233/luphoto/internal/config" ) +var version = "dev" + const usage = `usage: luphoto [-config path] commands: build process albums once and publish a new build - serve build, watch and serve over HTTP + serve build, watch and serve over HTTP on server.listen export build into the output folder and keep watching + run serve or export, as server.mode says + version print the version flags: -config path config file (default /etc/luphoto/config.toml; a missing file means all defaults) + +signals: + SIGHUP re-read the config and rebuild + SIGINT/SIGTERM stop gracefully ` func main() { @@ -62,7 +71,10 @@ func run(args []string) int { return 2 } switch command { - case "build", "serve", "export": + case "version": + fmt.Println("luphoto " + version) + return 0 + case "build", "serve", "export", "run": default: fmt.Fprintf(os.Stderr, "luphoto: unknown command %q\n\n%s", command, usage) return 2 @@ -80,15 +92,23 @@ func run(args []string) int { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() - summary, err := build.Run(ctx, cfg, logger) - if err != nil { - logger.Printf("luphoto: build failed: %v", err) - return 1 + if command == "build" { + summary, err := build.Run(ctx, cfg, logger) + if err != nil { + logger.Printf("luphoto: build failed: %v", err) + return 1 + } + logger.Print(summary.String()) + return 0 } - logger.Print(summary.String()) - if command != "build" { - logger.Printf("luphoto %s: not implemented yet (arrives in milestone M6); built once, exiting", command) + mode := command + if mode == "run" { + mode = cfg.Server.Mode + } + logger.Printf("luphoto %s: %s mode, config %s", version, mode, *configPath) + if err := app.Run(ctx, mode, *configPath, cfg, logger); err != nil { + logger.Printf("luphoto: %v", err) return 1 } return 0 diff --git a/go.mod b/go.mod index dcb2cbf..6905a12 100644 --- a/go.mod +++ b/go.mod @@ -4,5 +4,8 @@ go 1.22 require ( github.com/BurntSushi/toml v1.4.0 + github.com/fsnotify/fsnotify v1.7.0 github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd ) + +require golang.org/x/sys v0.4.0 // indirect diff --git a/go.sum b/go.sum index ec3623d..a76bb67 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,8 @@ github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc= github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk= +golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= +golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..f7905d3 --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,191 @@ +package app + +import ( + "context" + "log" + "os" + "os/signal" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/luciochen233/luphoto/internal/build" + "github.com/luciochen233/luphoto/internal/config" + "github.com/luciochen233/luphoto/internal/server" + "github.com/luciochen233/luphoto/internal/watch" +) + +const shutdownTimeout = 10 * time.Second + +type daemon struct { + mode string + configPath string + logger *log.Logger + cfg atomic.Pointer[config.Config] + builds chan string + handler *server.Handler + server *server.Server + watchCancel context.CancelFunc + watchDone chan struct{} + watchedRoot string + watchedDelay time.Duration + watching bool +} + +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) + + var builder sync.WaitGroup + builder.Add(1) + go func() { + defer builder.Done() + d.buildLoop(ctx) + }() + d.requestBuild("startup") + + if mode == "serve" { + d.handler = server.NewHandler(handlerSettings(cfg)) + srv, err := server.Start(cfg.Server.Listen, d.handler, logger) + if err != nil { + return err + } + d.server = srv + } + d.syncWatcher(ctx, cfg) + + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + defer signal.Stop(hup) + + for { + select { + case <-ctx.Done(): + logger.Printf("%s: shutting down", mode) + d.stopWatcher() + var err error + if d.server != nil { + err = d.server.Shutdown(shutdownTimeout) + } + builder.Wait() + return err + case <-hup: + d.reload(ctx) + } + } +} + +func handlerSettings(cfg *config.Config) server.Settings { + return server.Settings{Output: cfg.Paths.Output, HotlinkAllow: cfg.Protection.HotlinkAllow} +} + +func (d *daemon) requestBuild(reason string) { + select { + case d.builds <- reason: + default: + d.logger.Printf("rebuild queued (%s)", reason) + } +} + +func (d *daemon) buildLoop(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case reason := <-d.builds: + cfg := d.cfg.Load() + d.logger.Printf("build started (%s)", reason) + summary, err := build.Run(ctx, cfg, d.logger) + if err != nil { + if ctx.Err() != nil { + return + } + d.logger.Printf("build failed: %v; previous build stays live", err) + continue + } + d.logger.Print(summary.String()) + } + } +} + +func (d *daemon) syncWatcher(ctx context.Context, cfg *config.Config) { + want := cfg.Build.Watch + delay := cfg.Build.Debounce.Duration + if want == d.watching && cfg.Paths.Albums == d.watchedRoot && delay == d.watchedDelay { + return + } + d.stopWatcher() + d.watching = want + d.watchedRoot = cfg.Paths.Albums + d.watchedDelay = delay + if !want { + d.logger.Printf("watch: disabled by build.watch") + return + } + watchCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + d.watchCancel = cancel + d.watchDone = done + root := cfg.Paths.Albums + go func() { + defer close(done) + for { + err := watch.Run(watchCtx, root, delay, func(name string) { + d.requestBuild("change in " + name) + }, d.logger) + if watchCtx.Err() != nil { + return + } + d.logger.Printf("watch: %v; restarting in 5s", err) + select { + case <-watchCtx.Done(): + return + case <-time.After(5 * time.Second): + } + } + }() +} + +func (d *daemon) stopWatcher() { + if d.watchCancel != nil { + d.watchCancel() + <-d.watchDone + d.watchCancel = nil + d.watchDone = nil + } +} + +func (d *daemon) reload(ctx context.Context) { + next, err := config.Load(d.configPath) + if err != nil { + d.logger.Printf("reload: keeping the current config: %v", err) + return + } + previous := d.cfg.Load() + 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) + 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 + } else { + old := d.server + d.server = srv + go func() { + if err := old.Shutdown(shutdownTimeout); err != nil { + d.logger.Printf("reload: closing old listener: %v", err) + } + }() + } + } + d.cfg.Store(next) + if d.handler != nil { + d.handler.Update(handlerSettings(next)) + } + d.syncWatcher(ctx, next) + d.logger.Printf("reload: config %s applied", d.configPath) + d.requestBuild("SIGHUP") +} diff --git a/internal/build/build.go b/internal/build/build.go index ef69c1b..af3935f 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -477,25 +477,37 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error { errs[i] = err return } - if err := fsutil.WriteJSONAtomic(filepath.Join(dir, site.ManifestName(id)), m); err != nil { + data, err := fsutil.EncodeJSON(m) + if err == nil { + err = fsutil.WritePublicAtomic(filepath.Join(dir, site.ManifestName(id)), data) + } + if err != nil { errs[i] = err return } - errs[i] = fsutil.WriteAtomic(filepath.Join(dir, "index.html"), 0o644, func(w io.Writer) error { - return site.RenderAlbum(w, m, page) - }) + html, err := fsutil.Render(func(w io.Writer) error { return site.RenderAlbum(w, m, page) }) + if err == nil { + err = fsutil.WritePublicAtomic(filepath.Join(dir, "index.html"), html) + } + errs[i] = err }(i, m) } wg.Add(1) go func() { defer wg.Done() - if err := fsutil.WriteJSONAtomic(filepath.Join(stage, site.IndexName(id)), index); err != nil { + data, err := fsutil.EncodeJSON(index) + if err == nil { + err = fsutil.WritePublicAtomic(filepath.Join(stage, site.IndexName(id)), data) + } + if err != nil { errs[len(manifests)] = err return } - errs[len(manifests)] = fsutil.WriteAtomic(filepath.Join(stage, "index.html"), 0o644, func(w io.Writer) error { - return site.RenderIndex(w, index, page) - }) + html, err := fsutil.Render(func(w io.Writer) error { return site.RenderIndex(w, index, page) }) + if err == nil { + err = fsutil.WritePublicAtomic(filepath.Join(stage, "index.html"), html) + } + errs[len(manifests)] = err }() wg.Wait() if err := errors.Join(errs...); err != nil { diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go index e87bcaa..e09ad2b 100644 --- a/internal/fsutil/fsutil.go +++ b/internal/fsutil/fsutil.go @@ -2,6 +2,8 @@ package fsutil import ( "bufio" + "bytes" + "compress/gzip" "crypto/rand" "encoding/hex" "encoding/json" @@ -81,3 +83,37 @@ func SymlinkAtomic(target, link string) error { } return nil } + +func EncodeJSON(value any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(value); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func Render(write func(io.Writer) error) ([]byte, error) { + var buf bytes.Buffer + if err := write(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func WritePublicAtomic(path string, data []byte) error { + if err := WriteFileAtomic(path, data, 0o644); err != nil { + return err + } + return WriteAtomic(path+".gz", 0o644, func(w io.Writer) error { + zw, err := gzip.NewWriterLevel(w, gzip.BestCompression) + if err != nil { + return err + } + if _, err := zw.Write(data); err != nil { + return err + } + return zw.Close() + }) +} diff --git a/internal/process/pyramid.go b/internal/process/pyramid.go index 3db4268..b7ad99b 100644 --- a/internal/process/pyramid.go +++ b/internal/process/pyramid.go @@ -314,6 +314,30 @@ func (p *Processor) seed(ctx context.Context, src, work string) (string, error) return base64.StdEncoding.EncodeToString(data), nil } +func levelDir(files string) (string, error) { + entries, err := os.ReadDir(files) + if err != nil { + return "", err + } + found := "" + for _, entry := range entries { + if !entry.IsDir() { + continue + } + if _, err := strconv.Atoi(entry.Name()); err != nil { + continue + } + if found != "" { + return "", fmt.Errorf("dzsave wrote more than one level in %s", files) + } + found = filepath.Join(files, entry.Name()) + } + if found == "" { + return "", fmt.Errorf("dzsave wrote no level in %s", files) + } + return found, nil +} + type tileFile struct { name string x, y int @@ -331,7 +355,10 @@ func (p *Processor) cutLevel(ctx context.Context, hash, src, stage string, level "--suffix", ext+p.vips.SaveOptions(quality)); err != nil { return Level{}, err } - dir := filepath.Join(base+"_files", "0") + dir, err := levelDir(base + "_files") + if err != nil { + return Level{}, err + } entries, err := os.ReadDir(dir) if err != nil { return Level{}, err diff --git a/internal/process/vips.go b/internal/process/vips.go index f24af03..916c9f5 100644 --- a/internal/process/vips.go +++ b/internal/process/vips.go @@ -20,8 +20,11 @@ type Vips struct { Minor int Strip string env []string + nice string } +const niceIncrement = "5" + var versionPattern = regexp.MustCompile(`vips-(\d+)\.(\d+)(\.\d+)?`) func DetectVips(ctx context.Context, env []string) (*Vips, error) { @@ -42,6 +45,9 @@ func DetectVips(ctx context.Context, env []string) (*Vips, error) { major, _ := strconv.Atoi(m[1]) minor, _ := strconv.Atoi(m[2]) v := &Vips{Version: strings.TrimPrefix(m[0], "vips-"), Major: major, Minor: minor, env: env} + if nice, err := exec.LookPath("nice"); err == nil { + v.nice = nice + } if major > 8 || (major == 8 && minor >= 15) { v.Strip = "keep=none" } else { @@ -70,7 +76,12 @@ func (l *limitedBuffer) Write(p []byte) (int, error) { } func (v *Vips) Run(ctx context.Context, args ...string) error { - cmd := exec.CommandContext(ctx, "vips", args...) + var cmd *exec.Cmd + if v.nice != "" { + cmd = exec.CommandContext(ctx, v.nice, append([]string{"-n", niceIncrement, "vips"}, args...)...) + } else { + cmd = exec.CommandContext(ctx, "vips", args...) + } cmd.Env = v.env stderr := &limitedBuffer{limit: 4096} cmd.Stderr = stderr diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..16dd07d --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,283 @@ +package server + +import ( + "context" + "errors" + "fmt" + "io/fs" + "log" + "mime" + "net" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "time" +) + +const ( + contentSecurityPolicy = "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'" + cacheImmutable = "public, max-age=31536000, immutable" + cacheShort = "public, max-age=60" +) + +var contentTypes = map[string]string{ + ".html": "text/html; charset=utf-8", + ".json": "application/json", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".svg": "image/svg+xml", + ".webp": "image/webp", + ".avif": "image/avif", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".woff2": "font/woff2", + ".ico": "image/x-icon", + ".txt": "text/plain; charset=utf-8", +} + +var compressible = map[string]bool{".html": true, ".json": true, ".js": true, ".css": true, ".svg": true} + +type Settings struct { + Output string + HotlinkAllow []string +} + +type Handler struct { + settings atomic.Pointer[Settings] +} + +func NewHandler(settings Settings) *Handler { + h := &Handler{} + h.Update(settings) + return h +} + +func (h *Handler) Update(settings Settings) { + allow := make([]string, 0, len(settings.HotlinkAllow)) + for _, host := range settings.HotlinkAllow { + allow = append(allow, strings.ToLower(strings.TrimSpace(host))) + } + settings.HotlinkAllow = allow + h.settings.Store(&settings) +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("Content-Security-Policy", contentSecurityPolicy) + header.Set("X-Content-Type-Options", "nosniff") + header.Set("Referrer-Policy", "strict-origin-when-cross-origin") + if r.Method != http.MethodGet && r.Method != http.MethodHead { + header.Set("Allow", "GET, HEAD") + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + settings := h.settings.Load() + clean := path.Clean("/" + r.URL.Path) + if !visible(clean) { + http.NotFound(w, r) + return + } + if strings.HasPrefix(clean, "/t/") && hotlinked(r, settings.HotlinkAllow) { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + root, err := currentRoot(settings.Output) + if err != nil { + http.Error(w, "no build published yet", http.StatusServiceUnavailable) + return + } + name := filepath.Join(root, filepath.FromSlash(clean)) + info, err := os.Stat(name) + if err != nil { + http.NotFound(w, r) + return + } + if info.IsDir() { + index := filepath.Join(name, "index.html") + indexInfo, err := os.Stat(index) + if err != nil || !indexInfo.Mode().IsRegular() { + http.NotFound(w, r) + return + } + if !strings.HasSuffix(r.URL.Path, "/") { + target := clean + "/" + if clean == "/" { + target = "/" + } + if r.URL.RawQuery != "" { + target += "?" + r.URL.RawQuery + } + http.Redirect(w, r, target, http.StatusMovedPermanently) + return + } + name, info, clean = index, indexInfo, path.Join(clean, "index.html") + } + if !info.Mode().IsRegular() { + http.NotFound(w, r) + return + } + serveFile(w, r, clean, name, info) +} + +func visible(clean string) bool { + for _, part := range strings.Split(clean, "/") { + if strings.HasPrefix(part, ".") { + return false + } + } + return !strings.HasSuffix(clean, ".gz") +} + +func hotlinked(r *http.Request, allow []string) bool { + referer := r.Header.Get("Referer") + if referer == "" { + return false + } + u, err := url.Parse(referer) + if err != nil || u.Host == "" { + return true + } + host := strings.ToLower(u.Hostname()) + own := r.Host + if split, _, err := net.SplitHostPort(r.Host); err == nil { + own = split + } + if strings.EqualFold(own, host) { + return false + } + for _, allowed := range allow { + if host == allowed { + return false + } + } + return true +} + +func currentRoot(output string) (string, error) { + link := filepath.Join(output, "current") + target, err := os.Readlink(link) + if err != nil { + return "", err + } + if !filepath.IsAbs(target) { + target = filepath.Join(output, target) + } + info, err := os.Stat(target) + if err != nil { + return "", err + } + if !info.IsDir() { + return "", fs.ErrNotExist + } + return target, nil +} + +func cacheControl(clean string) string { + for _, prefix := range []string{"/t/", "/og/", "/assets/"} { + if strings.HasPrefix(clean, prefix) { + return cacheImmutable + } + } + return cacheShort +} + +func acceptsGzip(r *http.Request) bool { + for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") { + coding, params, _ := strings.Cut(strings.TrimSpace(part), ";") + coding = strings.ToLower(strings.TrimSpace(coding)) + if coding != "gzip" && coding != "*" { + continue + } + params = strings.ReplaceAll(strings.TrimSpace(params), " ", "") + if q, ok := strings.CutPrefix(params, "q="); ok { + if value, err := strconv.ParseFloat(q, 64); err == nil && value <= 0 { + continue + } + } + return true + } + return false +} + +func serveFile(w http.ResponseWriter, r *http.Request, clean, name string, info fs.FileInfo) { + header := w.Header() + ext := strings.ToLower(path.Ext(clean)) + contentType, ok := contentTypes[ext] + if !ok { + contentType = mime.TypeByExtension(ext) + } + if contentType == "" { + contentType = "application/octet-stream" + } + header.Set("Content-Type", contentType) + header.Set("Cache-Control", cacheControl(clean)) + variant := "" + if compressible[ext] { + header.Add("Vary", "Accept-Encoding") + if acceptsGzip(r) { + if gzInfo, err := os.Stat(name + ".gz"); err == nil && gzInfo.Mode().IsRegular() && gzInfo.ModTime().After(info.ModTime().Add(-time.Second)) { + name, info, variant = name+".gz", gzInfo, "-gz" + header.Set("Content-Encoding", "gzip") + } + } + } + f, err := os.Open(name) + if err != nil { + header.Del("Content-Encoding") + http.NotFound(w, r) + return + } + defer f.Close() + header.Set("ETag", fmt.Sprintf("\"%x-%x%s\"", info.ModTime().UnixNano(), info.Size(), variant)) + http.ServeContent(w, r, "", info.ModTime(), f) +} + +type Server struct { + http *http.Server + done chan error +} + +func Start(listen string, handler http.Handler, logger *log.Logger) (*Server, error) { + listener, err := net.Listen("tcp", listen) + if err != nil { + return nil, err + } + srv := &http.Server{ + Handler: handler, + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 2 * time.Minute, + IdleTimeout: 2 * time.Minute, + MaxHeaderBytes: 64 << 10, + ErrorLog: logger, + } + s := &Server{http: srv, done: make(chan error, 1)} + go func() { + err := srv.Serve(listener) + if errors.Is(err, http.ErrServerClosed) { + err = nil + } + s.done <- err + }() + logger.Printf("serve: listening on http://%s", listener.Addr()) + return s, nil +} + +func (s *Server) Shutdown(timeout time.Duration) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + err := s.http.Shutdown(ctx) + if errors.Is(err, context.DeadlineExceeded) { + err = s.http.Close() + } + if serveErr := <-s.done; serveErr != nil && err == nil { + err = serveErr + } + return err +} diff --git a/internal/site/assets.go b/internal/site/assets.go index 50ebf0c..bd3c63d 100644 --- a/internal/site/assets.go +++ b/internal/site/assets.go @@ -9,7 +9,6 @@ import ( "os" "path" "path/filepath" - "sort" "strings" "sync" @@ -19,8 +18,6 @@ import ( //go:embed static var staticFiles embed.FS -var preloadFonts = []string{"bricolage-grotesque-latin-wght-normal.", "ibm-plex-sans-latin-400-normal."} - type Asset struct { Name string URL string @@ -33,7 +30,6 @@ type Assets struct { Worker Asset Favicon Asset Fonts []Asset - Preload []Asset Chop template.HTML } @@ -56,13 +52,7 @@ var loadAssets = sync.OnceValue(func() Assets { } font := Asset{Name: name, URL: "/assets/" + name, data: mustRead("static/" + name)} assets.Fonts = append(assets.Fonts, font) - for _, prefix := range preloadFonts { - if strings.HasPrefix(name, prefix) { - assets.Preload = append(assets.Preload, font) - } - } } - sort.Slice(assets.Preload, func(i, j int) bool { return assets.Preload[i].Name < assets.Preload[j].Name }) return assets }) @@ -99,7 +89,12 @@ func (a Assets) Write(buildDir string) error { wg.Add(1) go func(asset Asset) { defer wg.Done() - errs <- fsutil.WriteFileAtomic(filepath.Join(dir, asset.Name), asset.data, 0o644) + target := filepath.Join(dir, asset.Name) + if path.Ext(asset.Name) == ".woff2" { + errs <- fsutil.WriteFileAtomic(target, asset.data, 0o644) + return + } + errs <- fsutil.WritePublicAtomic(target, asset.data) }(asset) } wg.Wait() diff --git a/internal/site/templates/head.html b/internal/site/templates/head.html index c7f42b4..4a3c12c 100644 --- a/internal/site/templates/head.html +++ b/internal/site/templates/head.html @@ -21,9 +21,6 @@ {{- end}} -{{- range .Assets.Preload}} - -{{- end}} {{- end}} diff --git a/internal/watch/watch.go b/internal/watch/watch.go new file mode 100644 index 0000000..96f9e54 --- /dev/null +++ b/internal/watch/watch.go @@ -0,0 +1,130 @@ +package watch + +import ( + "context" + "errors" + "io/fs" + "log" + "os" + "path/filepath" + "strings" + "time" + + "github.com/fsnotify/fsnotify" +) + +const retryMissing = 5 * time.Second + +func Ignored(name string) bool { + base := filepath.Base(name) + if base == "" || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "~") || strings.HasSuffix(base, "~") { + return true + } + lower := strings.ToLower(base) + for _, suffix := range []string{".part", ".tmp", ".partial", ".crdownload", ".swp"} { + if strings.HasSuffix(lower, suffix) { + return true + } + } + return false +} + +func Run(ctx context.Context, root string, debounce time.Duration, changed func(string), logger *log.Logger) error { + for { + info, err := os.Stat(root) + if err == nil && info.IsDir() { + break + } + logger.Printf("watch: %s is not a folder yet, retrying", root) + select { + case <-ctx.Done(): + return nil + case <-time.After(retryMissing): + } + } + watcher, err := fsnotify.NewWatcher() + if err != nil { + return err + } + defer watcher.Close() + count, err := addTree(watcher, root) + if err != nil { + return err + } + logger.Printf("watch: %d folders under %s, debounce %s", count, root, debounce) + + timer := time.NewTimer(time.Hour) + if !timer.Stop() { + <-timer.C + } + pending := "" + for { + select { + case <-ctx.Done(): + timer.Stop() + return nil + case event, ok := <-watcher.Events: + if !ok { + return errors.New("watch: event channel closed") + } + if Ignored(event.Name) { + continue + } + if event.Has(fsnotify.Create) { + if info, err := os.Stat(event.Name); err == nil && info.IsDir() { + if _, err := addTree(watcher, event.Name); err != nil { + logger.Printf("watch: %v", err) + } + } + } + if event.Has(fsnotify.Chmod) && !event.Has(fsnotify.Write) { + continue + } + if pending == "" { + pending = event.Name + } + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + timer.Reset(debounce) + case <-timer.C: + if pending != "" { + reason := pending + pending = "" + changed(reason) + } + case err, ok := <-watcher.Errors: + if !ok { + return errors.New("watch: error channel closed") + } + logger.Printf("watch: %v", err) + } + } +} + +func addTree(watcher *fsnotify.Watcher, root string) (int, error) { + count := 0 + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + if path == root { + return err + } + return nil + } + if !entry.IsDir() { + return nil + } + if path != root && Ignored(path) { + return filepath.SkipDir + } + if err := watcher.Add(path); err != nil { + return err + } + count++ + return nil + }) + return count, err +} diff --git a/packaging/Caddyfile b/packaging/Caddyfile new file mode 100644 index 0000000..ba34cb8 --- /dev/null +++ b/packaging/Caddyfile @@ -0,0 +1,33 @@ +photos.luciochen.com { + root * /var/lib/luphoto/site/current + + @hotlink { + path /t/* + header Referer * + not header_regexp Referer ^https?://photos\.luciochen\.com(:[0-9]+)?(/|$) + } + respond @hotlink 403 + + @hidden path */.* *.gz + respond @hidden 404 + + @immutable path /t/* /og/* /assets/* + header @immutable Cache-Control "public, max-age=31536000, immutable" + + @short not path /t/* /og/* /assets/* + header @short Cache-Control "public, max-age=60" + + header { + Content-Security-Policy "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'" + X-Content-Type-Options nosniff + Referrer-Policy strict-origin-when-cross-origin + -Server + } + + @methods not method GET HEAD + respond @methods 405 + + file_server { + precompressed gzip + } +} diff --git a/packaging/Caddyfile.serve b/packaging/Caddyfile.serve new file mode 100644 index 0000000..d5215a1 --- /dev/null +++ b/packaging/Caddyfile.serve @@ -0,0 +1,3 @@ +photos.luciochen.com { + reverse_proxy 127.0.0.1:8080 +} diff --git a/packaging/INSTALL.md b/packaging/INSTALL.md new file mode 100644 index 0000000..a1a36ec --- /dev/null +++ b/packaging/INSTALL.md @@ -0,0 +1,23 @@ +# Installing LuPhoto from the tarball + +For distributions without the `.deb`. You need libvips 8.12 or newer with its command-line tools (`vips`, `vipsheader`), for example `dnf install vips-tools` or `pacman -S libvips`. + +```sh +tar xzf luphoto__linux_.tar.gz +cd luphoto__linux_ +sudo install -m 0755 luphoto /usr/bin/luphoto +sudo install -d /etc/luphoto +sudo install -m 0644 config.toml /etc/luphoto/config.toml +sudo install -m 0644 luphoto.service /etc/systemd/system/luphoto.service + +sudo groupadd --system luphoto +sudo useradd --system --gid luphoto --home-dir /var/lib/luphoto --no-create-home --shell /usr/sbin/nologin luphoto +sudo groupadd --system luphoto-upload +sudo install -d -m 2775 -o root -g luphoto-upload /srv/luphoto/albums +sudo install -d -m 0755 -o luphoto -g luphoto /var/lib/luphoto /var/cache/luphoto + +sudo systemctl daemon-reload +sudo systemctl enable --now luphoto +``` + +Add uploaders to the `luphoto-upload` group. Edit `/etc/luphoto/config.toml`, then `sudo systemctl reload luphoto`. Web server examples are in `examples/`. diff --git a/packaging/cloudflare.md b/packaging/cloudflare.md new file mode 100644 index 0000000..48b7045 --- /dev/null +++ b/packaging/cloudflare.md @@ -0,0 +1,10 @@ +# 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. + +Cache rules (Caching → Cache Rules), in this order: + +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/*`, `index..json`): Edge TTL 1 minute or "respect origin" (`max-age=60`). Manifests are named after the build, so a new build needs no purge. + +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. diff --git a/packaging/cloudflared.yml b/packaging/cloudflared.yml new file mode 100644 index 0000000..8f74dd9 --- /dev/null +++ b/packaging/cloudflared.yml @@ -0,0 +1,8 @@ +tunnel: luphoto +credentials-file: /etc/cloudflared/luphoto.json +ingress: + - hostname: photos.luciochen.com + service: http://127.0.0.1:8080 + originRequest: + httpHostHeader: photos.luciochen.com + - service: http_status:404 diff --git a/packaging/config.toml b/packaging/config.toml new file mode 100644 index 0000000..2a66986 --- /dev/null +++ b/packaging/config.toml @@ -0,0 +1,34 @@ +[server] +mode = "export" +listen = "127.0.0.1:8080" +base_url = "https://photos.luciochen.com" + +[paths] +albums = "/srv/luphoto/albums" +output = "/var/lib/luphoto/site" +cache = "/var/cache/luphoto" + +[images] +tile_size = 512 +overlap = 1 +format = "webp" +quality = { top = 82, mid = 85, low = 88 } +min_levels = 6 +seed_px = 48 +tile_names = "hashed" +scramble_cells = false + +[loading] +budget_ms = 3000 +max_dpr = 2.0 +concurrency = 6 + +[build] +watch = true +debounce = "30s" +workers = 2 +keep_builds = 3 + +[protection] +block_context_menu = true +hotlink_allow = ["photos.luciochen.com"] diff --git a/packaging/luphoto.service b/packaging/luphoto.service new file mode 100644 index 0000000..c238793 --- /dev/null +++ b/packaging/luphoto.service @@ -0,0 +1,41 @@ +[Unit] +Description=LuPhoto photo site (photos.luciochen.com) +Documentation=https://github.com/luciochen233/luphoto +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=luphoto +Group=luphoto +ExecStart=/usr/bin/luphoto -config /etc/luphoto/config.toml run +ExecReload=/bin/kill -HUP $MAINPID +Restart=on-failure +RestartSec=5 +TimeoutStopSec=30 +Nice=5 +UMask=0022 +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +NoNewPrivileges=true +ReadOnlyPaths=/srv/luphoto/albums +ReadWritePaths=/var/lib/luphoto /var/cache/luphoto +CapabilityBoundingSet= +AmbientCapabilities= +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +RestrictNamespaces=true +RestrictRealtime=true +RestrictSUIDSGID=true +LockPersonality=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +ProtectClock=true +ProtectHostname=true +SystemCallArchitectures=native + +[Install] +WantedBy=multi-user.target diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml new file mode 100644 index 0000000..8a1140e --- /dev/null +++ b/packaging/nfpm.yaml @@ -0,0 +1,48 @@ +name: luphoto +arch: ${GOARCH} +platform: linux +version: ${VERSION} +version_schema: none +section: web +priority: optional +maintainer: Guoliang Chen +description: | + Static, tiled photo site for photos.luciochen.com. + Reads album folders, cuts photos into 512 px tiles with libvips and + publishes a static site that a browser stitches back together. +homepage: https://photos.luciochen.com +depends: + - libvips-tools + - passwd +contents: + - src: dist/package/luphoto + dst: /usr/bin/luphoto + file_info: + mode: 0755 + - src: packaging/config.toml + dst: /etc/luphoto/config.toml + type: config|noreplace + file_info: + mode: 0644 + - src: packaging/luphoto.service + dst: /usr/lib/systemd/system/luphoto.service + file_info: + mode: 0644 + - src: packaging/Caddyfile + dst: /usr/share/doc/luphoto/examples/Caddyfile + - src: packaging/Caddyfile.serve + dst: /usr/share/doc/luphoto/examples/Caddyfile.serve + - src: packaging/nginx.conf + dst: /usr/share/doc/luphoto/examples/nginx.conf + - src: packaging/nginx.serve.conf + dst: /usr/share/doc/luphoto/examples/nginx.serve.conf + - src: packaging/cloudflared.yml + dst: /usr/share/doc/luphoto/examples/cloudflared.yml + - src: packaging/cloudflare.md + dst: /usr/share/doc/luphoto/cloudflare.md + - src: README.md + dst: /usr/share/doc/luphoto/README.md +scripts: + postinstall: packaging/scripts/postinstall.sh + preremove: packaging/scripts/preremove.sh + postremove: packaging/scripts/postremove.sh diff --git a/packaging/nginx.conf b/packaging/nginx.conf new file mode 100644 index 0000000..b687dbf --- /dev/null +++ b/packaging/nginx.conf @@ -0,0 +1,57 @@ +map $http_referer $luphoto_hotlink { + default 1; + "" 0; + "~^https?://photos\.luciochen\.com(:[0-9]+)?(/|$)" 0; +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name photos.luciochen.com; + + ssl_certificate /etc/letsencrypt/live/photos.luciochen.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/photos.luciochen.com/privkey.pem; + + root /var/lib/luphoto/site/current; + index index.html; + autoindex off; + disable_symlinks off; + gzip_static on; + server_tokens off; + + if ($request_method !~ ^(GET|HEAD)$) { + return 405; + } + + location ~ (/\.|\.gz$) { + return 404; + } + + location /t/ { + if ($luphoto_hotlink) { + return 403; + } + add_header Cache-Control "public, max-age=31536000, immutable" always; + add_header Content-Security-Policy "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy strict-origin-when-cross-origin always; + try_files $uri =404; + } + + location ~ ^/(og|assets)/ { + add_header Cache-Control "public, max-age=31536000, immutable" always; + add_header Content-Security-Policy "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy strict-origin-when-cross-origin always; + try_files $uri =404; + } + + location / { + add_header Cache-Control "public, max-age=60" always; + add_header Content-Security-Policy "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy strict-origin-when-cross-origin always; + try_files $uri $uri/index.html =404; + } +} diff --git a/packaging/nginx.serve.conf b/packaging/nginx.serve.conf new file mode 100644 index 0000000..efe965e --- /dev/null +++ b/packaging/nginx.serve.conf @@ -0,0 +1,18 @@ +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name photos.luciochen.com; + + ssl_certificate /etc/letsencrypt/live/photos.luciochen.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/photos.luciochen.com/privkey.pem; + server_tokens off; + + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_buffering on; + } +} diff --git a/packaging/scripts/postinstall.sh b/packaging/scripts/postinstall.sh new file mode 100644 index 0000000..574e20d --- /dev/null +++ b/packaging/scripts/postinstall.sh @@ -0,0 +1,27 @@ +#!/bin/sh +set -e + +if ! getent group luphoto >/dev/null; then + groupadd --system luphoto +fi +if ! getent passwd luphoto >/dev/null; then + useradd --system --gid luphoto --home-dir /var/lib/luphoto --no-create-home --shell /usr/sbin/nologin --comment "LuPhoto" luphoto +fi +if ! getent group luphoto-upload >/dev/null; then + groupadd --system luphoto-upload +fi +usermod -a -G luphoto-upload luphoto + +if [ ! -d /srv/luphoto/albums ]; then + install -d -m 0755 -o root -g root /srv/luphoto + install -d -m 2775 -o root -g luphoto-upload /srv/luphoto/albums +fi +install -d -m 0755 -o luphoto -g luphoto /var/lib/luphoto /var/cache/luphoto + +if [ -d /run/systemd/system ]; then + systemctl daemon-reload >/dev/null 2>&1 || true + if systemctl is-active --quiet luphoto.service; then + systemctl try-restart luphoto.service >/dev/null 2>&1 || true + fi +fi +exit 0 diff --git a/packaging/scripts/postremove.sh b/packaging/scripts/postremove.sh new file mode 100644 index 0000000..5431eaf --- /dev/null +++ b/packaging/scripts/postremove.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -e + +if [ -d /run/systemd/system ]; then + systemctl daemon-reload >/dev/null 2>&1 || true +fi +if [ "$1" = "purge" ]; then + rm -rf /var/cache/luphoto +fi +exit 0 diff --git a/packaging/scripts/preremove.sh b/packaging/scripts/preremove.sh new file mode 100644 index 0000000..1dfb8a4 --- /dev/null +++ b/packaging/scripts/preremove.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -e + +if [ -d /run/systemd/system ] && [ "$1" = "remove" ]; then + systemctl stop luphoto.service >/dev/null 2>&1 || true + systemctl disable luphoto.service >/dev/null 2>&1 || true +fi +exit 0 diff --git a/scripts/package.sh b/scripts/package.sh new file mode 100644 index 0000000..08227d4 --- /dev/null +++ b/scripts/package.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +scripts_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo_dir="$(dirname "$scripts_dir")" + +if [ "${LUPHOTO_IN_CONTAINER:-0}" != "1" ]; then + exec "$scripts_dir/dev.sh" env LUPHOTO_IN_CONTAINER=1 VERSION="${VERSION:-}" ARCHES="${ARCHES:-}" bash scripts/package.sh "$@" +fi + +cd "$repo_dir" +git config --global --add safe.directory "$repo_dir" >/dev/null 2>&1 || true + +nfpm_version="v2.35.3" +arches="${ARCHES:-amd64 arm64}" +version="${VERSION:-}" +if [ -z "$version" ]; then + described="$(git describe --tags --always --dirty 2>/dev/null || echo unknown)" + case "$described" in + v[0-9]*) version="${described#v}" ;; + *) version="0.0.0+git.${described}" ;; + esac +fi + +tools_dir="$repo_dir/.tools" +if [ ! -x "$tools_dir/nfpm" ]; then + echo "package: installing nfpm $nfpm_version" + GOBIN="$tools_dir" GOTOOLCHAIN=local go install "github.com/goreleaser/nfpm/v2/cmd/nfpm@$nfpm_version" +fi + +rm -rf dist +mkdir -p dist +for arch in $arches; do + out="dist/linux_$arch" + mkdir -p "$out" + echo "package: luphoto $version linux/$arch" + CGO_ENABLED=0 GOOS=linux GOARCH="$arch" go build -trimpath -ldflags "-s -w -X main.version=$version" -o "$out/luphoto" ./cmd/luphoto + + rm -rf dist/package + mkdir -p dist/package + cp "$out/luphoto" dist/package/luphoto + VERSION="$version" GOARCH="$arch" "$tools_dir/nfpm" package --config packaging/nfpm.yaml --packager deb --target dist/ + rm -rf dist/package + + name="luphoto_${version}_linux_${arch}" + stage="dist/$name" + mkdir -p "$stage/examples" + cp "$out/luphoto" "$stage/luphoto" + cp packaging/luphoto.service packaging/config.toml packaging/INSTALL.md README.md "$stage/" + cp packaging/Caddyfile packaging/Caddyfile.serve packaging/nginx.conf packaging/nginx.serve.conf packaging/cloudflared.yml packaging/cloudflare.md "$stage/examples/" + tar -C dist -czf "dist/$name.tar.gz" "$name" + rm -rf "$stage" +done + +ls -l dist/*.deb dist/*.tar.gz