diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..0963a65 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,36 @@ +# Verification pipeline for git.maple-street.net (Gitea Actions / act_runner). +# +# Runs the same gates a release needs, so a broken commit cannot reach main +# unnoticed. The container is pinned to the Node major the Dockerfile ships, and +# the runner only needs Docker — no Node, Chrome or extra tools on the host. +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + verify: + runs-on: ubuntu-latest + container: node:24-bookworm + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: npm ci + + - name: Typecheck + run: npm run typecheck + + # Includes the server HTTP suite, which starts the real server against a + # temporary data directory (auth, ownership, quota, gallery, ranges). + - name: Tests + run: npm test + + - name: Production build + run: npm run build + + - name: Server syntax + run: for file in server/*.mjs; do node --check "$file"; done diff --git a/.gitignore b/.gitignore index 3ff3c9e..c1dc2f9 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ windows/launcher/webview2/obj/ # Transfer-only Windows release archives windows/releases/*.zip windows/releases/*.exe + +# Transfer-only macOS release archives +macos/releases/ diff --git a/Dockerfile b/Dockerfile index f552e44..d686a83 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,6 +13,8 @@ COPY tsconfig.json vite.config.ts index.html ./ COPY src ./src # Vite copies public/ into dist/, so the served PDF (in-app Guide link) needs it here. COPY public ./public +# The build writes the .br/.gz asset copies the server prefers to send. +COPY scripts ./scripts RUN npm run build # ------------------------------------------------------- production node_modules diff --git a/README.md b/README.md index 6cd6bdd..4ec20c3 100644 --- a/README.md +++ b/README.md @@ -277,7 +277,7 @@ directly and have no legacy alias. ```bash npm ci -npm run build # type-checks and bundles dist/ +npm run build # type-checks, bundles dist/ and writes .br/.gz copies npm start # serves dist/ and /api from one Node process ``` @@ -360,6 +360,25 @@ Two independent things to back up: `GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does not include image bytes; keep a file-level backup for those. +`npm run backup` automates item 1 without stopping the server: it writes a consistent +`VACUUM INTO` snapshot of the live catalog (WAL included) to `$LUMINARY_DATA/backups`, +re-opens it to run `PRAGMA integrity_check`, records counts in a manifest and prunes to +the last 14 snapshots. `--keep`, `--dir` and `LUMINARY_BACKUP_DIR` change that; originals +are opt-in because they dwarf the catalog: + +```bash +npm run backup # catalog only +npm run backup -- --with-originals --keep 30 + +# nightly at 02:30, keeping the copy off the data volume +30 2 * * * cd /srv/luminary && /usr/bin/npm run backup -- --with-originals --dir /mnt/backups >> /var/log/luminary-backup.log 2>&1 +``` + +To restore, stop the server, copy `catalog-*.db` back as `lumenroom.db` (delete the old +`-wal`/`-shm` files first) and copy `originals-*/` back into the storage root. Previews, +thumbnails, proofs and denoise renders are regenerable; only `originals/` and +`secret.key` must survive. + --- ## Docker @@ -971,11 +990,21 @@ positions. Camera-lens defaults require both a normalised camera and lens name t | `npm run server:dev` | Server with `node --watch` | | `npm run dev` | Vite HMR on 5173 | | `npm run typecheck` | `tsc --noEmit` | -| `npm test` | Vitest, one pass then exit | +| `npm test` | Vitest, one pass then exit: pure logic plus the server HTTP suite | +| `npm run backup` | Snapshot the catalog (originals optional) without stopping the server | +| `npm run precompress` | Write the `.br`/`.gz` asset copies by hand; `npm run build` does this | | `npm run check:render` | Headless Chrome check that the 16-bit sidecar and JPEG proxy upload in the same row order | | `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build | | `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) | +### Continuous integration + +`.gitea/workflows/ci.yml` runs on every push and pull request: `npm ci`, +`npm run typecheck`, `npm test` and `npm run build` inside a `node:24-bookworm` +container, then `node --check` on every `server/*.mjs`. It only needs Docker on the +runner, so the same gate works on the LAN Gitea instance. Release binaries are still +built and attached by hand; the workflow is what keeps `main` buildable. + Conventions worth knowing before changing code: - The server is plain ESM (`.mjs`) with no build step. Keep it framework-free and avoid @@ -1007,8 +1036,13 @@ Conventions worth knowing before changing code: | `src/lib/dcp.test.ts` | DCP tag parsing and the camera matrix recipe against LibRaw's own values | | `src/lib/softProof.test.ts` | ICC parsing (including counted lut16 tables), the printer round trip, gamut threshold, rendering-intent selection and CMYK profiles | | `src/lib/dcpLibrary.test.ts` | Per-camera DCP library: validation, replacement, forgetting and camera matching | +| `server/http.test.mjs` | Real server on a throwaway data directory: signup/invite rules, cross-owner isolation, upload quota accounting, byte ranges, unreadable files not killing the process, gallery download cap | -There are no server integration tests; the API is exercised through the UI. +`server/http.test.mjs` spawns `server/index.mjs` on a random loopback port with a +temporary `LUMINARY_DATA`, drives it with `fetch` and deletes the directory afterwards, +so it needs no fixtures and never touches a real catalog. Its permission test (an +unreadable original must answer 404 instead of crashing the process) is skipped when the +suite runs as root, because root ignores file modes. `npm run check:render` covers the one thing the unit suite cannot: what a shader does to real GPU pixels. It encodes a 16-bit sidecar with the server's own encoder, serves it diff --git a/macos/Info.plist b/macos/Info.plist new file mode 100644 index 0000000..7551b7a --- /dev/null +++ b/macos/Info.plist @@ -0,0 +1,34 @@ + + + + + CFBundleName + Luminary + CFBundleDisplayName + Luminary + CFBundleIdentifier + __BUNDLE_ID__ + CFBundleVersion + __VERSION__ + CFBundleShortVersionString + __VERSION__ + CFBundleExecutable + Luminary + CFBundleIconFile + Luminary + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleSignature + ???? + LSMinimumSystemVersion + __MIN_OS__ + LSApplicationCategoryType + public.app-category.photography + NSHighResolutionCapable + + NSHumanReadableCopyright + MIT licensed. Copyright 2026 Brian Hursey. + + diff --git a/macos/README-macos.txt b/macos/README-macos.txt new file mode 100644 index 0000000..b42523a --- /dev/null +++ b/macos/README-macos.txt @@ -0,0 +1,63 @@ +Luminary for macOS +================== + +Install + 1. Open the disk image (or unzip the archive). + 2. Drag Luminary to the Applications folder. + 3. Eject the disk image, then open Luminary from Applications. + +First launch (unsigned build) + This build is not notarized by Apple, so macOS will say it cannot verify the + app. That is expected: it means nobody paid Apple's yearly fee, not that + anything is wrong with the file. + 1. Double-click Luminary and dismiss the warning with Done. + 2. Open System Settings > Privacy & Security. + 3. Scroll to Security and click Open Anyway, then authenticate. + macOS remembers the choice, so this is a one-time step. The Open Anyway + button only appears for about an hour after the blocked attempt; if it is + missing, double-click the app again and go back. + +What it needs + - macOS 11 Big Sur or newer (the build records its own minimum in + Info.plist; 11.0 for the Node 22 build, 13.5 for the Node 24 build). + - A browser with WebAssembly and WebGL2. Chrome or Edge is used for the app + window when installed; otherwise the default browser opens a normal tab. + - Nothing else. Node.js is inside the app, so no Homebrew, no npm install + and no administrator password are needed for day-to-day use. + +Start, stop and status + Opening Luminary starts the local server and opens the editor. Opening it + again reuses the running copy instead of starting a second one. + - Stop Luminary.command (next to the app in the disk image) stops the server. + - The same commands are available from a terminal: + /Applications/Luminary.app/Contents/Resources/launcher.sh --status + /Applications/Luminary.app/Contents/Resources/launcher.sh --stop + (or run the app with --args --status: open -a Luminary --args --status) + +Where your photos live + ~/Library/Application Support/Luminary/data + That folder holds the SQLite catalog, the originals, previews and thumbnails. + Set LUMINARY_DATA before launching to keep it somewhere else, such as an + external drive. Back it up by copying the whole folder while Luminary is + stopped, including lumenroom.db, lumenroom.db-wal and lumenroom.db-shm. + +Logs + ~/Library/Application Support/Luminary/data/logs/server.out.log + ~/Library/Application Support/Luminary/data/logs/server.err.log + +Updating + Quit the server (Stop Luminary.command), drag the new Luminary.app over the + old one, and start it again. The data folder is outside the app and is not + touched. The catalog migrates itself on first start. + +Notes + - The server listens on 127.0.0.1 only. For proofing galleries that other + devices should reach, run the server yourself with HOST=0.0.0.0. + - The app window is Chrome or Edge in app mode, using its own profile in the + data folder, so it does not mix with your normal browsing. Set + LUMINARY_WINDOW=browser to open a normal tab instead. + - This build is single-user desktop mode: it signs in as a local admin + without a password and is not meant for several people sharing one Mac + account. + - The bundle is ad-hoc signed. If you rebuild it yourself with a Developer ID + certificate and notarize it, the first-launch step above disappears. diff --git a/macos/README.md b/macos/README.md new file mode 100644 index 0000000..cbbbde7 --- /dev/null +++ b/macos/README.md @@ -0,0 +1,186 @@ +# macOS app (optional) + +An additive, self-contained way to produce a double-clickable macOS app of +Luminary. The server and Docker workflow stay the source of truth: this folder +only *packages* the existing `dist/` + `server/` output, and the build writes +its artifacts **outside the checkout**. + +## Isolation guarantees + +1. **The packaging tree is additive.** There is no `package.json` script for + this, and no change to `Dockerfile`, `docker-compose.yml` or + `scripts/deploy.mjs`. Invoke it directly: `node macos/build.mjs`. The app + uses the same desktop mode the Windows launcher uses (`LUMINARY_LOCAL=1`), + which is off unless a launcher sets it. +2. **Artifacts live outside the repo** (default: `~/Library/Caches/luminary-macos`). + The script refuses an `--out` inside the checkout, because + `scripts/deploy.mjs` rsyncs the worktree to production and `docker build` + would pull the bundle into its context. +3. **The worktree must be clean outside `macos/`** before and after a build + (the untracked `logo.png` is tolerated). `--allow-dirty` overrides it. +4. **Nothing in the app changes at run time.** The bundle is the unchanged + `server/` + `dist/` + production `node_modules`, started with `PORT`, `HOST`, + `NODE_ENV` and `LUMINARY_DATA` — all variables the server already reads. + +It must run on macOS: the build needs `clang`, `codesign`, `ditto`, `hdiutil`, +`sips` and `iconutil`. The Windows bundle is the one that cross-builds from +Linux. + +## Quick start + +On a fresh checkout run `npm ci` once: the UI build uses `vite` and `tsc` from +the dev dependencies, and the script copies the production dependencies into +the app itself. + +```sh +node macos/build.mjs # host arch, Node 24, ad-hoc signature, zip + dmg +node macos/build.mjs --arch universal # arm64 + x86_64, both sharp slices +node macos/build.mjs --node v22.23.5 # minimum macOS 11.0 instead of 13.5 +node macos/build.mjs --skip-build --sign none +``` + +Outputs: + +``` +~/Library/Caches/luminary-macos/ + stage/Luminary.app + Luminary-0.5.1-mac-arm64.zip + Luminary-0.5.1-mac-arm64.dmg + cache/ # downloaded node tarballs, icon work +``` + +`--publish` copies the zip and dmg into `macos/releases/` with a +`SHA256SUMS.txt`, for transfer to a Mac. `.gitignore` keeps those archives out +of git. + +## Bundle layout + +``` +Luminary.app/Contents/ + Info.plist, PkgInfo + MacOS/Luminary native shim (main.c) -> execs the launcher + Resources/ + launcher.sh start/stop/status/verify (bash) + Luminary.icns + version.txt, README-macos.txt + runtime/node official Node for the built architecture + app/ + server/ unchanged, minus data/ and *.test.* + dist/ unchanged, including .br/.gz variants + node_modules/ production deps only (sharp for each slice) + package.json, LICENSE, THIRD_PARTY_NOTICES.md, licenses/ +``` + +The main executable is a **Mach-O shim**, not a shell script. Apple treats +scripts in `Contents/MacOS` as resources, and the notary service rejects a +bundle whose main executable is not signed native code; the shim is a few lines +of C that execs `bash launcher.sh`, so the launcher stays editable without a +rebuild and the bundle can still be signed and notarized. + +## Node and the minimum macOS version + +| Node | Bundled runtime minimum | `LSMinimumSystemVersion` | +| --- | --- | --- | +| v22.18+ | macOS 11.0 | 11.0 | +| v24+ | macOS 13.5 | 13.5 | + +Node 24's official macOS binaries are built against 13.5, so they cannot start +on Big Sur or Monterey; a macOS 11 build must bundle Node 22. Both lines run +this server: `node:sqlite` is unflagged from 22.13, type stripping (used by +`server/denoise-worker.mjs` importing a `.ts` pipeline) from 22.18, and the +HTTP integration suite passes under 22.23.5. + +`--node-bin` uses a local binary instead of downloading one; the build warns if +`otool -L` shows libraries outside `/usr/lib` and `/System` (a Homebrew node +would drag Homebrew's ICU along and fail on a stock Mac). + +## Signing and notarization + +Three modes: + +| `--sign` | What it does | Users see | +| --- | --- | --- | +| `adhoc` (default) | `codesign --sign -` on every Mach-O, then the bundle | “Apple could not verify …”, one-time Open Anyway | +| `none` | no signature | the same, and arm64 Macs may refuse to launch it | +| `developer-id` | signs each nested Mach-O with the Developer ID, hardened runtime and JIT entitlements on executables, then the bundle | no warning | + +Notarization needs a paid Apple Developer Program membership: + +```sh +xcrun notarytool store-credentials luminary \ + --apple-id you@example.com --team-id TEAMID --password APP_SPECIFIC_PASSWORD + +node macos/build.mjs --arch universal \ + --sign developer-id --identity "Developer ID Application: Brian Hursey (TEAMID)" \ + --notarize luminary --publish +``` + +The build submits the zip, staples the `.app`, rebuilds the zip, then creates the +dmg and submits and staples that too. `entitlements.plist` contains +`allow-jit`, `allow-unsigned-executable-memory` and `disable-library-validation` +— Node needs the first two under the hardened runtime, and sharp loads libvips +as a dylib, which library validation would otherwise reject. + +Without the certificate everything still works; the first-launch instructions in +`README-macos.txt` cover the Gatekeeper step. macOS 15 and 26 removed the +Control-click → Open bypass, so that text names the System Settings path. + +## Launcher behaviour + +Same rules as the Windows launcher (`windows/launcher/DESIGN.md`): + +- **No mutex.** `runtime.json` in the data folder records pid/port, and + `/api/health` is the liveness test: a healthy recorded port is reused, a stale + one is replaced. +- **Ports** 8787–8887, loopback only. The chosen port is passed as `PORT`. +- **Data** defaults to `~/Library/Application Support/Luminary/data`; an + existing `LUMINARY_DATA` wins. Logs go to `/logs/`. +- **Window**: Chrome or Edge in `--app` mode with its own profile in the data + folder; `--browser` or `LUMINARY_WINDOW=browser` opens a normal tab; neither + installed falls back to the default browser. +- **Server lifetime**: detached, so closing the browser does not stop it and + reopening the app reuses it. `--stop` (and `Stop Luminary.command` next to the + app in the dmg) terminates it; `--status` prints pid, port, health and paths; + `--verify` checks the three files a complete bundle needs. + +## Test checklist (on the Tahoe machine) + +1. `node macos/build.mjs --arch universal --dmg` → zip and dmg exist; summary + prints arch, Node version, target and hashes. +2. `codesign --verify --deep --strict --verbose=2 stage/Luminary.app` → valid. +3. Copy the app out of the dmg, open it → browser/app window opens on the + editor, no sign-in screen (desktop mode). +4. Launch again while it runs → same port is reused, no second node process; + `pgrep -fl 'Resources/runtime/node'` shows one. +5. `--stop` → process gone, `runtime.json` removed; `--stop` again says + "not running". +6. Occupy 8787 with another listener → the app starts on 8788 and opens that + URL. +7. Import a raw, apply a film look, export → proves libraw WASM, sharp (dylibs + load under the signature) and the export path. +8. Denoise a photo → proves the `.ts` worker under the bundled Node. +9. Quit the browser, reopen the app → the same catalog opens; the data folder + holds the SQLite files. +10. `--verify` with a renamed `runtime/node` → exit 3 and a dialog, not a silent + failure. +11. Path with spaces / non-ASCII in `LUMINARY_DATA` → starts and writes there. +12. Gatekeeper: download the zip through a browser (quarantine flag), then + follow README-macos.txt → one-time Open Anyway, then normal launches. +13. On an Intel Mac: the same bundle runs (universal, both sharp slices). +14. Optional: notarized build → double-click installs with no warning, + `spctl -a -vv -t exec Luminary.app` says `accepted`. + +## Known limits + +- **No Dock menu.** The launcher exits once the browser opens; stopping is + `--stop` / `Stop Luminary.command`, not a Quit menu item. +- **Ad-hoc signing is per-bundle.** Copying the app with an archiver that drops + extended attributes can make macOS call it damaged; the zip is made with + `ditto` for that reason. +- **Universal builds install sharp twice** (one `npm ci` per architecture) and + copy the second slice's `@img` packages across; this is tested for layout, not + for runtime, until both architectures are exercised. +- **Icon quality depends on the source.** `public/logo.png` is 147×160, so the + generated `.icns` is soft; pass `--icon` with a 1024×1024 PNG for a release. +- **No auto-update, no file associations, no login item.** Same phase-2 list as + Windows. diff --git a/macos/build.mjs b/macos/build.mjs new file mode 100644 index 0000000..d907601 --- /dev/null +++ b/macos/build.mjs @@ -0,0 +1,854 @@ +#!/usr/bin/env node +/** + * Build the optional self-contained macOS app for Luminary. + * + * Like windows/build.mjs this is deliberately additive: it only reads the + * repository (`dist/`, `server/`, `package.json`) and writes everything into a + * directory outside the checkout. Nothing in `src/`, `server/`, `package.json`, + * the Dockerfile or the deploy script is modified, and no npm script is added. + * Run it directly, on macOS: + * + * node macos/build.mjs # host arch, Node 24, ad-hoc signed + * node macos/build.mjs --arch universal --dmg + * node macos/build.mjs --node v22.23.5 # minimum macOS 11.0 + * node macos/build.mjs --skip-build --sign none + * + * The bundle keeps the layout the server expects (it derives `DIST_DIR` from + * the parent of `server/`), with a native shim as the app's main executable: + * + * Luminary.app/Contents/ + * Info.plist, PkgInfo + * MacOS/Luminary native shim that execs the launcher script + * Resources/ + * launcher.sh start/stop/status/verify logic (bash) + * Luminary.icns + * version.txt, README-macos.txt + * runtime/node official Node for this architecture + * app/ unchanged server/, dist/, production deps + */ +import { createHash } from 'node:crypto'; +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + renameSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, '..'); +const LAUNCHER_DIR = path.join(HERE, 'launcher'); +const RELEASES_DIR = path.join(HERE, 'releases'); +const DEFAULT_NODE = 'v24.22.2'; +const DEFAULT_BUNDLE_ID = 'net.maple-street.luminary'; +const INFO_PLIST = path.join(HERE, 'Info.plist'); +const ENTITLEMENTS = path.join(HERE, 'entitlements.plist'); + +const HELP = `Luminary macOS app + +Usage: node macos/build.mjs [options] + + --out output directory (default: ~/Library/Caches/luminary-macos). + Must be outside this repository; the app is staged in + /stage/Luminary.app and archived next to it. + --skip-build reuse the existing dist/ instead of running npm run build + --node bundled Node version (default ${DEFAULT_NODE}). + v22.18+ gives a macOS 11.0 bundle; v24+ needs macOS 13.5. + --node-bin bundle this node binary instead of downloading one + --arch host (default), arm64, x64 or universal + --target minimum macOS version (default: derived from Node; + e.g. 11.0 for Node 22, 13.5 for Node 24) + --sign adhoc (default), developer-id or none + --identity Developer ID Application identity for --sign developer-id + --notarize notarytool keychain profile; implies --sign developer-id + --dmg also write a disk image (default) + --no-dmg skip the disk image + --icon icon source (default: macos/icon-1024.png) + --bundle-id CFBundleIdentifier (default ${DEFAULT_BUNDLE_ID}) + --allow-dirty skip the check that the checkout is clean outside macos/ + --publish copy the finished zip and dmg to macos/releases + --help print this text + +Requires macOS with the Xcode command line tools (clang, codesign, ditto, +hdiutil, sips, iconutil). Nothing is written into the repository except with +--publish. +`; + +function fail(message) { + process.stderr.write(`macos: FAILED: ${message}\n`); + process.exit(1); +} + +function log(step, message) { + process.stdout.write(`macos: ${step.padEnd(9)} ${message}\n`); +} + +function warn(message) { + process.stderr.write(`macos: warning: ${message}\n`); +} + +function capture(command, args, cwd) { + return spawnSync(command, args, { cwd, encoding: 'utf8' }); +} + +function run(command, args, cwd, extraEnv) { + log('run', [command, ...args].join(' ')); + const result = spawnSync(command, args, { + cwd, + stdio: 'inherit', + env: extraEnv ? { ...process.env, ...extraEnv } : process.env, + }); + if (result.error) fail(`${command} could not start: ${result.error.message}`); + if (result.status !== 0) fail(`${command} ${args.join(' ')} exited with ${result.status}`); + return result; +} + +function defaultOutDir() { + return path.join(os.homedir(), 'Library', 'Caches', 'luminary-macos'); +} + +function parseArgs(argv) { + const options = { + out: defaultOutDir(), + node: DEFAULT_NODE, + nodeBin: '', + arch: 'host', + target: '', + sign: 'adhoc', + identity: '', + notarize: '', + dmg: true, + build: true, + icon: path.join(HERE, 'icon-1024.png'), + bundleId: DEFAULT_BUNDLE_ID, + allowDirty: false, + publish: false, + help: false, + }; + const value = (index, flag) => { + const next = argv[index + 1]; + if (!next || next.startsWith('--')) fail(`${flag} needs a value`); + return next; + }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--out') { + options.out = path.resolve(value(i, arg)); + i += 1; + } else if (arg === '--node') { + const version = value(i, arg); + options.node = version.startsWith('v') ? version : `v${version}`; + i += 1; + } else if (arg === '--node-bin') { + options.nodeBin = path.resolve(value(i, arg)); + i += 1; + } else if (arg === '--arch') { + options.arch = value(i, arg); + i += 1; + } else if (arg === '--target') { + options.target = value(i, arg); + i += 1; + } else if (arg === '--sign') { + options.sign = value(i, arg); + i += 1; + } else if (arg === '--identity') { + options.identity = value(i, arg); + i += 1; + } else if (arg === '--notarize') { + options.notarize = value(i, arg); + i += 1; + } else if (arg === '--icon') { + options.icon = path.resolve(value(i, arg)); + i += 1; + } else if (arg === '--bundle-id') { + options.bundleId = value(i, arg); + i += 1; + } else if (arg === '--skip-build') { + options.build = false; + } else if (arg === '--dmg') { + options.dmg = true; + } else if (arg === '--no-dmg') { + options.dmg = false; + } else if (arg === '--allow-dirty') { + options.allowDirty = true; + } else if (arg === '--publish') { + options.publish = true; + } else if (arg === '--help' || arg === '-h') { + options.help = true; + } else { + fail(`unknown option ${arg} (see --help)`); + } + } + if (!['host', 'arm64', 'x64', 'universal'].includes(options.arch)) { + fail(`--arch must be host, arm64, x64 or universal (got ${options.arch})`); + } + if (!['adhoc', 'developer-id', 'none'].includes(options.sign)) { + fail(`--sign must be adhoc, developer-id or none (got ${options.sign})`); + } + if (!/^v\d+\.\d+\.\d+$/.test(options.node)) { + fail(`--node must look like v24.22.2 (got ${options.node})`); + } + if (options.notarize) options.sign = 'developer-id'; + if (options.sign === 'developer-id' && !options.identity) { + fail('--sign developer-id needs --identity "Developer ID Application: ..."'); + } + if (options.nodeBin && !existsSync(options.nodeBin)) { + fail(`--node-bin not found: ${options.nodeBin}`); + } + return options; +} + +/** + * The staged app and its runtime must not land in the checkout: scripts/deploy + * rsyncs the worktree to production and docker build would pull it into the + * context. + */ +function assertOutsideRepo(outDir) { + const relative = path.relative(ROOT, outDir); + const inside = !relative.startsWith('..') && !path.isAbsolute(relative); + if (inside) { + fail( + `--out resolves inside the repository (${outDir}).\n` + + 'Pick a directory outside the checkout, or omit --out to use the cache.', + ); + } +} + +function git(args, { trim = true } = {}) { + const result = capture('git', args, ROOT); + if (result.error || result.status !== 0) return null; + return trim ? result.stdout.trim() : result.stdout; +} + +/** Only this folder and the long-standing untracked logo may be dirty. */ +function checkRepoClean(options) { + const status = git(['status', '--porcelain'], { trim: false }); + if (status === null) { + warn('git is unavailable here; skipping the worktree check'); + return; + } + const unexpected = status + .split('\n') + .filter((line) => line.length > 3) + .map((line) => line.slice(3).replace(/^"|"$/g, '').replace(/^.* -> /, '').trim()) + .filter((file) => file && !file.startsWith('macos/') && file !== 'logo.png'); + if (!unexpected.length) return; + if (options.allowDirty) { + warn(`building from a modified checkout: ${unexpected.join(', ')}`); + return; + } + fail( + `the checkout has changes outside macos/:\n ${unexpected.join('\n ')}\n` + + 'Commit or stash them, or pass --allow-dirty to build anyway.', + ); +} + +function readPackage() { + const file = path.join(ROOT, 'package.json'); + if (!existsSync(file)) fail('run this from a Luminary checkout (package.json missing)'); + return JSON.parse(readFileSync(file, 'utf8')); +} + +function sha256File(file) { + return createHash('sha256').update(readFileSync(file)).digest('hex'); +} + +async function download(url) { + const response = await fetch(url); + if (!response.ok) throw new Error(`${response.status} ${response.statusText} from ${url}`); + return Buffer.from(await response.arrayBuffer()); +} + +function fileType(file) { + const result = capture('file', ['-b', file]); + return result.status === 0 ? result.stdout.trim() : ''; +} + +function nodeMajor(version) { + return Number(version.slice(1).split('.')[0]); +} + +function minimumOS(version) { + const major = nodeMajor(version); + if (major === 22) return '11.0'; + if (major >= 24) return '13.5'; + return '11.0'; +} + +function resolveArchs(requested) { + if (requested === 'universal') return ['arm64', 'x64']; + if (requested === 'host') return [process.arch === 'arm64' ? 'arm64' : 'x64']; + return [requested]; +} + +function clangArch(arch) { + return arch === 'x64' ? 'x86_64' : 'arm64'; +} + +function ensureUi(options) { + const dist = path.join(ROOT, 'dist', 'index.html'); + if (options.build) { + log('ui', 'npm run build (typecheck + vite build + compressed variants)'); + run('npm', ['run', 'build'], ROOT); + } else { + log('ui', 'reusing the existing dist/ (--skip-build)'); + } + if (!existsSync(dist)) fail('dist/index.html is missing; drop --skip-build or run "npm run build"'); +} + +function copyServer(appDir) { + cpSync(path.join(ROOT, 'server'), path.join(appDir, 'server'), { + recursive: true, + filter: (source) => { + const relative = path.relative(path.join(ROOT, 'server'), source).split(path.sep).join('/'); + if (relative === 'data' || relative.startsWith('data/')) return false; + if (/\.test\.(mjs|ts)$/.test(relative)) return false; + return true; + }, + }); +} + +function copyLegal(appDir) { + for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) { + const source = path.join(ROOT, name); + if (existsSync(source)) cpSync(source, path.join(appDir, name)); + } + const licenses = path.join(ROOT, 'licenses'); + if (existsSync(licenses)) cpSync(licenses, path.join(appDir, 'licenses'), { recursive: true }); +} + +function installDeps(appDir, archs, outDir) { + cpSync(path.join(ROOT, 'package.json'), path.join(appDir, 'package.json')); + cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json')); + + log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`); + // sharp resolves its prebuilt binary through optionalDependencies, so npm can + // fetch the target architecture's package from any host. + run( + 'npm', + ['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'], + appDir, + ); + rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true }); + + // A universal app needs both sharp slices; npm's --cpu selects one at a time, + // so install the second architecture separately and copy its packages across. + for (const arch of archs.slice(1)) { + const side = path.join(outDir, `deps-${arch}`); + rmSync(side, { recursive: true, force: true }); + mkdirSync(side, { recursive: true }); + cpSync(path.join(ROOT, 'package.json'), path.join(side, 'package.json')); + cpSync(path.join(ROOT, 'package-lock.json'), path.join(side, 'package-lock.json')); + run( + 'npm', + ['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'], + side, + ); + for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) { + const from = path.join(side, 'node_modules', pkg); + if (!existsSync(from)) fail(`${pkg} was not installed for the ${arch} slice`); + rmSync(path.join(appDir, 'node_modules', pkg), { recursive: true, force: true }); + cpSync(from, path.join(appDir, 'node_modules', pkg), { recursive: true }); + log('deps', `added ${pkg}`); + } + rmSync(side, { recursive: true, force: true }); + } + + verifySharp(appDir, archs); +} + +function verifySharp(appDir, archs) { + for (const arch of archs) { + const dir = path.join(appDir, 'node_modules', '@img', `sharp-darwin-${arch}`); + if (!existsSync(dir)) { + warn(`@img/sharp-darwin-${arch} is missing; the server will fall back to JPEG proxies`); + continue; + } + const binaries = []; + const walk = (current) => { + for (const entry of readdirSync(current, { withFileTypes: true })) { + const absolute = path.join(current, entry.name); + if (entry.isDirectory()) walk(absolute); + else if (/\.(node|dylib)$/i.test(entry.name)) binaries.push(path.relative(dir, absolute)); + } + }; + walk(dir); + const libvips = path.join(appDir, 'node_modules', '@img', `sharp-libvips-darwin-${arch}`); + log( + 'deps', + binaries.some((file) => file.endsWith('.node')) + ? `sharp darwin-${arch} ready (${binaries.length} native file(s)${existsSync(libvips) ? ', libvips included' : ''})` + : `sharp darwin-${arch} has no .node binary`, + ); + } +} + +async function ensureNode(options, outDir, archs) { + if (options.nodeBin) { + const kind = fileType(options.nodeBin); + if (!/Mach-O/.test(kind)) fail(`--node-bin is not a Mach-O binary (${kind || 'unknown'})`); + const binaryArch = /universal/.test(kind) ? 'universal' : /arm64/.test(kind) ? 'arm64' : 'x64'; + if (binaryArch !== 'universal' && (archs.length > 1 || binaryArch !== archs[0])) { + fail( + `--node-bin is ${binaryArch} but --arch needs ${archs.join(' + ')}.\n` + + 'Use the official nodejs.org tarball, or omit --node-bin to download both slices.', + ); + } + log('node', `using ${options.nodeBin} (${binaryArch})`); + return { path: options.nodeBin, arch: binaryArch, version: options.node, hash: sha256File(options.nodeBin) }; + } + + const version = options.node; + const major = nodeMajor(version); + if (major === 23) fail('Node 23 is not an LTS line; use v22 (macOS 11) or v24 (macOS 13.5)'); + if (major < 22) fail(`Node ${version} is too old: node:sqlite needs 22.13+ (type stripping 22.18+)`); + if (major === 22 && Number(version.split('.')[1]) < 18) { + fail(`${version} cannot strip types by default; server/denoise-worker.mjs needs v22.18+`); + } + + const cache = path.join(outDir, 'cache', `node-${version}`); + mkdirSync(cache, { recursive: true }); + const sumsFile = path.join(cache, 'SHASUMS256.txt'); + if (!existsSync(sumsFile)) { + log('node', `downloading SHASUMS256.txt for ${version}`); + writeFileSync(sumsFile, await download(`https://nodejs.org/dist/${version}/SHASUMS256.txt`)); + } + const sums = new Map( + readFileSync(sumsFile, 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => { + const [hash, name] = line.trim().split(/\s+/); + return [name, hash]; + }), + ); + + const binaries = []; + for (const arch of archs) { + const name = `node-${version}-darwin-${arch}.tar.gz`; + const tarball = path.join(cache, name); + if (!existsSync(tarball)) { + log('node', `downloading ${name}`); + try { + writeFileSync(tarball, await download(`https://nodejs.org/dist/${version}/${name}`)); + } catch (error) { + fail(`could not download ${name}: ${error.message}`); + } + } + const hash = sha256File(tarball); + const expected = sums.get(name); + if (expected && expected !== hash) { + rmSync(tarball, { force: true }); + fail(`${name} failed its SHA-256 check (${hash} != ${expected}); re-run to download again`); + } + if (!expected) warn(`${name} has no published checksum; using it unverified`); + + const dir = path.join(cache, `node-${version}-darwin-${arch}`); + const binary = path.join(dir, 'bin', 'node'); + if (!existsSync(binary)) { + mkdirSync(dir, { recursive: true }); + run('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1']); + } + const kind = fileType(binary); + if (!/Mach-O/.test(kind)) fail(`extracted ${arch} node is not a Mach-O binary (${kind})`); + binaries.push(binary); + log('node', `${version} darwin-${arch} verified (sha256 ${hash.slice(0, 12)}…)`); + } + + if (binaries.length === 1) { + return { path: binaries[0], arch: archs[0], version, hash: sha256File(binaries[0]) }; + } + const universal = path.join(cache, `node-${version}-universal`); + rmSync(universal, { force: true }); + run('lipo', ['-create', ...binaries, '-output', universal]); + const kind = fileType(universal); + if (!/universal binary/.test(kind)) fail(`lipo did not produce a universal binary (${kind})`); + chmodSync(universal, 0o755); + log('node', `${version} universal (arm64 + x86_64)`); + return { path: universal, arch: 'universal', version, hash: sha256File(universal) }; +} + +function checkNodePortability(binary) { + const result = capture('otool', ['-L', binary]); + if (result.status !== 0) return; + const foreign = result.stdout + .split('\n') + .slice(1) + .map((line) => line.trim().split(' ')[0]) + .filter((lib) => lib && !lib.startsWith('/usr/lib/') && !lib.startsWith('/System/')); + if (foreign.length) { + warn( + `the bundled node links to libraries outside macOS: ${foreign.join(', ')}.\n` + + 'Use the official nodejs.org tarball so the app runs on a Mac without Homebrew.', + ); + } +} + +function compileShim(app, archs, target) { + const found = capture('xcrun', ['--find', 'clang']); + const clang = found.status === 0 ? found.stdout.trim() : ''; + if (!clang) { + fail( + 'clang is missing. Install the Xcode command line tools:\n' + + ' xcode-select --install\n' + + 'and run the build again.', + ); + } + const output = path.join(app, 'Contents', 'MacOS', 'Luminary'); + const args = ['-O2', '-Wall', '-Wextra', `-mmacosx-version-min=${target}`]; + for (const arch of archs) args.push('-arch', clangArch(arch)); + args.push('-o', output, path.join(LAUNCHER_DIR, 'main.c')); + run(clang, args); + chmodSync(output, 0o755); + log('launcher', `native shim (${archs.join(' + ')}, macOS ${target}+)`); +} + +function renderInfoPlist(app, { version, target, bundleId }) { + const text = readFileSync(INFO_PLIST, 'utf8') + .replaceAll('__VERSION__', version) + .replaceAll('__MIN_OS__', target) + .replaceAll('__BUNDLE_ID__', bundleId); + writeFileSync(path.join(app, 'Contents', 'Info.plist'), text); + writeFileSync(path.join(app, 'Contents', 'PkgInfo'), 'APPL????'); +} + +function buildIcon(app, source, outDir) { + if (!existsSync(source)) { + warn(`icon source not found: ${source}; the app will use the generic icon`); + return; + } + const sips = '/usr/bin/sips'; + const iconutil = '/usr/bin/iconutil'; + if (!existsSync(sips) || !existsSync(iconutil)) { + warn('sips/iconutil are missing; skipping the icon'); + return; + } + const probe = capture(sips, ['-g', 'pixelWidth', '-g', 'pixelHeight', source]); + const width = Number((probe.stdout.match(/pixelWidth:\s*(\d+)/) ?? [])[1] ?? 0); + const height = Number((probe.stdout.match(/pixelHeight:\s*(\d+)/) ?? [])[1] ?? 0); + if (!width || !height) { + warn(`could not read the icon size of ${source}; skipping the icon`); + return; + } + const square = Math.max(width, height); + if (square < 512) { + warn( + `the icon source is ${width}x${height}; the .icns will look soft.\n` + + 'Pass --icon with a 1024x1024 PNG for a crisp Dock icon.', + ); + } + + const work = path.join(outDir, 'cache', 'icon'); + rmSync(work, { recursive: true, force: true }); + mkdirSync(path.join(work, 'Luminary.iconset'), { recursive: true }); + const padded = path.join(work, 'square.png'); + if (width === height) { + cpSync(source, padded); + } else { + run(sips, ['-p', String(square), String(square), '--padColor', '0B0D10', source, '--out', padded]); + } + + const iconset = path.join(work, 'Luminary.iconset'); + for (const size of [16, 32, 128, 256, 512]) { + for (const scale of [1, 2]) { + const pixels = size * scale; + const name = scale === 1 ? `icon_${size}x${size}.png` : `icon_${size}x${size}@2x.png`; + run(sips, ['-z', String(pixels), String(pixels), padded, '--out', path.join(iconset, name)]); + } + } + run(iconutil, ['-c', 'icns', iconset, '-o', path.join(app, 'Contents', 'Resources', 'Luminary.icns')]); + log('icon', `Luminary.icns from ${path.relative(ROOT, source)} (${width}x${height})`); +} + +function writeVersion(resources, info) { + const commit = git(['rev-parse', '--short', 'HEAD']) ?? 'unknown'; + const lines = [ + `Luminary ${info.version}`, + `commit ${commit}`, + `built ${new Date().toISOString()}`, + `node ${info.nodeVersion} darwin-${info.nodeArch} sha256 ${info.nodeHash} size ${info.nodeSize}`, + `arch ${info.archs.join(' + ')}`, + `minimum macOS ${info.target}`, + 'launcher native shim -> launcher.sh', + ]; + writeFileSync(path.join(resources, 'version.txt'), `${lines.join('\n')}\n`); + return commit; +} + +function machOFiles(root) { + const found = []; + const walk = (current) => { + for (const entry of readdirSync(current, { withFileTypes: true })) { + const absolute = path.join(current, entry.name); + if (entry.isDirectory()) { + walk(absolute); + continue; + } + if (!entry.isFile()) continue; + // `file` per file would be hundreds of subprocesses across node_modules; + // only native modules, dylibs and executables can be Mach-O here. + const stat = statSync(absolute); + const candidate = + /\.(node|dylib|so)$/i.test(entry.name) || (stat.mode & 0o111) !== 0; + if (candidate && /Mach-O/.test(fileType(absolute))) found.push(absolute); + } + }; + walk(root); + return found; +} + +function signApp(app, options) { + if (options.sign === 'none') { + warn( + 'the app is unsigned: arm64 Macs refuse to launch it at all, and Intel\n' + + 'Macs show the Gatekeeper warning. Ship adhoc or developer-id instead.', + ); + return; + } + const nested = machOFiles(app).filter((file) => !file.endsWith('/Contents/MacOS/Luminary')); + for (const file of nested) { + if (options.sign === 'adhoc') { + run('codesign', ['--force', '--sign', '-', file]); + continue; + } + const kind = fileType(file); + const executable = /executable/.test(kind) && !/dylib|bundle/.test(kind); + const args = ['--force', '--timestamp', '--sign', options.identity]; + if (executable) args.push('--options', 'runtime', '--entitlements', ENTITLEMENTS); + args.push(file); + run('codesign', args); + } + const finalArgs = + options.sign === 'adhoc' + ? ['--force', '--sign', '-', app] + : [ + '--force', + '--timestamp', + '--options', + 'runtime', + '--entitlements', + ENTITLEMENTS, + '--sign', + options.identity, + app, + ]; + run('codesign', finalArgs); + const verify = capture('codesign', ['--verify', '--deep', '--strict', '--verbose=2', app]); + if (verify.status !== 0) fail(`codesign verification failed:\n${verify.stderr.trim()}`); + log('sign', options.sign === 'adhoc' ? 'ad-hoc signature verified' : `signed with ${options.identity}`); +} + +function zipApp(app, zipPath) { + rmSync(zipPath, { force: true }); + // ditto keeps symlinks, extended attributes and the code signature intact; + // `zip -r` corrupts bundles often enough to produce "app is damaged". + run('ditto', ['-c', '-k', '--keepParent', '--sequesterRsrc', app, zipPath]); + return statSync(zipPath).size; +} + +function makeDmg(app, dmgPath, outDir) { + const root = path.join(outDir, 'dmg'); + rmSync(root, { recursive: true, force: true }); + mkdirSync(root, { recursive: true }); + cpSync(app, path.join(root, 'Luminary.app'), { recursive: true, verbatimSymlinks: true }); + symlinkSync('Applications', path.join(root, 'Applications')); + cpSync(path.join(HERE, 'README-macos.txt'), path.join(root, 'README-macos.txt')); + const stop = path.join(LAUNCHER_DIR, 'Stop Luminary.command'); + if (existsSync(stop)) { + cpSync(stop, path.join(root, 'Stop Luminary.command')); + chmodSync(path.join(root, 'Stop Luminary.command'), 0o755); + } + rmSync(dmgPath, { force: true }); + run('hdiutil', [ + 'create', + '-volname', + 'Luminary', + '-srcfolder', + root, + '-ov', + '-format', + 'UDZO', + dmgPath, + ]); + rmSync(root, { recursive: true, force: true }); + return statSync(dmgPath).size; +} + +function notarize(artifact, profile) { + log('notarize', `submitting ${path.basename(artifact)}`); + run('xcrun', ['notarytool', 'submit', artifact, '--keychain-profile', profile, '--wait']); +} + +function staple(artifact) { + run('xcrun', ['stapler', 'staple', artifact]); + run('xcrun', ['stapler', 'validate', artifact]); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) { + process.stdout.write(HELP); + return 0; + } + if (process.platform !== 'darwin') { + fail( + 'the macOS app must be built on macOS: it needs clang, codesign, ditto and hdiutil.\n' + + 'The Windows bundle is the one that cross-builds from Linux.', + ); + } + assertOutsideRepo(options.out); + const pkg = readPackage(); + const archs = resolveArchs(options.arch); + const target = options.target || minimumOS(options.node); + const [targetMajor, targetMinor = 0] = target.split('.').map(Number); + if (nodeMajor(options.node) >= 24 && (targetMajor < 13 || (targetMajor === 13 && targetMinor < 5))) { + fail( + `Node ${options.node} needs macOS 13.5 or newer, but --target is ${target}.\n` + + 'Build with --node v22.23.5 for a macOS 11.0 bundle.', + ); + } + log('repo', `${pkg.name} ${pkg.version} at ${ROOT}`); + log('out', options.out); + checkRepoClean(options); + ensureUi(options); + + const stageRoot = path.join(options.out, 'stage'); + const workRoot = path.join(options.out, 'stage.next'); + const app = path.join(workRoot, 'Luminary.app'); + const contents = path.join(app, 'Contents'); + const resources = path.join(contents, 'Resources'); + const appDir = path.join(resources, 'app'); + rmSync(workRoot, { recursive: true, force: true }); + for (const dir of [path.join(contents, 'MacOS'), resources, appDir, path.join(resources, 'runtime')]) { + mkdirSync(dir, { recursive: true }); + } + + log('stage', 'copying dist/ and server/ (the layout the server expects)'); + cpSync(path.join(ROOT, 'dist'), path.join(appDir, 'dist'), { recursive: true }); + copyServer(appDir); + copyLegal(appDir); + installDeps(appDir, archs, options.out); + + const node = await ensureNode(options, options.out, archs); + checkNodePortability(node.path); + cpSync(node.path, path.join(resources, 'runtime', 'node')); + chmodSync(path.join(resources, 'runtime', 'node'), 0o755); + log('node', `bundled ${path.basename(node.path)} (${(statSync(node.path).size / 1024 / 1024).toFixed(1)} MB)`); + + cpSync(path.join(LAUNCHER_DIR, 'launcher.sh'), path.join(resources, 'launcher.sh')); + chmodSync(path.join(resources, 'launcher.sh'), 0o755); + cpSync(path.join(HERE, 'README-macos.txt'), path.join(resources, 'README-macos.txt')); + + renderInfoPlist(app, { version: pkg.version, target, bundleId: options.bundleId }); + compileShim(app, archs, target); + buildIcon(app, options.icon, options.out); + + const commit = writeVersion(resources, { + version: pkg.version, + nodeVersion: options.node, + nodeArch: node.arch, + nodeHash: node.hash, + nodeSize: statSync(node.path).size, + archs, + target, + }); + + signApp(app, options); + + const label = archs.length > 1 ? 'universal' : archs[0]; + const zipPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.zip`); + let zipBytes = zipApp(app, zipPath); + + if (options.notarize) { + notarize(zipPath, options.notarize); + staple(app); + zipBytes = zipApp(app, zipPath); + } else { + const assessment = capture('spctl', ['-a', '-vv', '-t', 'exec', app]); + if (assessment.status !== 0) { + log('gatekeeper', 'not notarized: users must use Privacy & Security > Open Anyway'); + } + } + + let dmgPath = ''; + let dmgBytes = 0; + if (options.dmg) { + dmgPath = path.join(options.out, `Luminary-${pkg.version}-mac-${label}.dmg`); + dmgBytes = makeDmg(app, dmgPath, options.out); + if (options.notarize) { + notarize(dmgPath, options.notarize); + staple(dmgPath); + } + log('dmg', `${path.basename(dmgPath)} (${(dmgBytes / 1024 / 1024).toFixed(1)} MB)`); + } + + // The isolation contract: nothing outside macos/ may have changed. Checked + // before --publish writes anything into the checkout. + if (!options.allowDirty) checkRepoClean(options); + + rmSync(stageRoot, { recursive: true, force: true }); + renameSync(workRoot, stageRoot); + + let published = []; + if (options.publish) { + mkdirSync(RELEASES_DIR, { recursive: true }); + const sums = []; + for (const artifact of [zipPath, ...(dmgPath ? [dmgPath] : [])]) { + const targetPath = path.join(RELEASES_DIR, path.basename(artifact)); + cpSync(artifact, targetPath); + sums.push(`${sha256File(targetPath)} ${path.basename(targetPath)}`); + log('publish', path.relative(ROOT, targetPath)); + } + writeFileSync(path.join(RELEASES_DIR, 'SHA256SUMS.txt'), `${sums.join('\n')}\n`); + published = sums; + } + + process.stdout.write( + [ + '', + 'macos build PASSED', + ` app ${path.join(stageRoot, 'Luminary.app')}`, + ` zip ${zipPath}`, + ` zip size ${(zipBytes / 1024 / 1024).toFixed(1)} MB`, + ` zip sha256 ${sha256File(zipPath)}`, + ...(dmgPath + ? [ + ` dmg ${dmgPath}`, + ` dmg size ${(dmgBytes / 1024 / 1024).toFixed(1)} MB`, + ` dmg sha256 ${sha256File(dmgPath)}`, + ] + : []), + ` arch ${label}`, + ` node ${options.node} darwin-${node.arch}`, + ` target macOS ${target}+`, + ` signature ${options.sign}${options.identity ? ` (${options.identity})` : ''}`, + ` commit ${commit}`, + ...(published.length ? ['', ...published.map((line) => ` publish ${line}`)] : []), + '', + options.notarize + ? 'Notarized and stapled: users can open it with a normal double-click.' + : 'Not notarized: first launch needs Privacy & Security > Open Anyway (see README-macos.txt).', + '', + ].join('\n'), + ); + return 0; +} + +main().then( + (code) => { + process.exitCode = code; + }, + (error) => { + fail(error instanceof Error ? error.message : String(error)); + }, +); diff --git a/macos/entitlements.plist b/macos/entitlements.plist new file mode 100644 index 0000000..18f0058 --- /dev/null +++ b/macos/entitlements.plist @@ -0,0 +1,16 @@ + + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + com.apple.security.cs.disable-library-validation + + + diff --git a/macos/icon-1024.png b/macos/icon-1024.png new file mode 100644 index 0000000..3658683 Binary files /dev/null and b/macos/icon-1024.png differ diff --git a/macos/icon-source.svg b/macos/icon-source.svg new file mode 100644 index 0000000..0b84780 --- /dev/null +++ b/macos/icon-source.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/launcher/Stop Luminary.command b/macos/launcher/Stop Luminary.command new file mode 100644 index 0000000..7664c26 --- /dev/null +++ b/macos/launcher/Stop Luminary.command @@ -0,0 +1,18 @@ +#!/bin/bash +# Stop the Luminary server started by Luminary.app. +# Double-clicking a .command file opens Terminal for as long as this runs. +set -u + +APP="/Applications/Luminary.app" +if [ ! -d "$APP" ]; then + APP="$(cd "$(dirname "$0")" && pwd)/Luminary.app" +fi + +if [ ! -d "$APP" ]; then + echo "Luminary.app was not found in /Applications. Move it there and try again." + read -r -p "Press Return to close this window." _ + exit 1 +fi + +"$APP/Contents/Resources/launcher.sh" --stop +read -r -p "Press Return to close this window." _ diff --git a/macos/launcher/launcher.sh b/macos/launcher/launcher.sh new file mode 100644 index 0000000..6bc9e36 --- /dev/null +++ b/macos/launcher/launcher.sh @@ -0,0 +1,248 @@ +#!/bin/bash +# Luminary.app launcher. +# +# Called by the native shim in Contents/MacOS/Luminary. Keeps the same rules as +# the Windows launcher: pick a loopback port, start the bundled node exactly like +# `node server/index.mjs`, wait for /api/health, then open the browser. The +# server is detached and keeps running after the app exits, so launching again +# reuses it instead of starting a second copy. +# +# launcher.sh start (or reuse) and open the window +# launcher.sh --stop stop the server recorded in runtime.json +# launcher.sh --status print pid, port, health and data directory +# launcher.sh --verify check that this is a complete bundle (exit 3 if not) +# launcher.sh --browser open a normal browser tab instead of an app window +set -u + +HERE="$(cd "$(dirname "$0")" && pwd)" +APP="$HERE/app" +NODE="$HERE/runtime/node" +DATA="${LUMINARY_DATA:-$HOME/Library/Application Support/Luminary/data}" +STATE="$DATA/runtime.json" +LOGS="$DATA/logs" +WINDOW="${LUMINARY_WINDOW:-app}" + +say() { printf 'Luminary: %s\n' "$*"; } +err() { printf 'Luminary: %s\n' "$*" >&2; } +die() { err "$*"; exit 1; } + +# A blocking dialog for launches from Finder, where stderr goes nowhere. +dialog() { + local message + message=$(printf '%s' "$1" | tr '"' "'" | tr '\n' ' ') + if command -v osascript >/dev/null 2>&1; then + osascript -e "display dialog \"$message\" with title \"Luminary\" buttons {\"OK\"} default button 1 with icon caution" >/dev/null 2>&1 || true + fi +} + +version_line() { + if [ -f "$HERE/version.txt" ]; then head -1 "$HERE/version.txt"; else echo "Luminary (version unknown)"; fi +} + +state_port() { + [ -f "$STATE" ] || return 0 + sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1 +} + +state_pid() { + [ -f "$STATE" ] || return 0 + sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$STATE" | head -1 +} + +healthy() { + curl -fs -m 2 "http://127.0.0.1:$1/api/health" >/dev/null 2>&1 +} + +# Ask node rather than nc: the bundle always has one, and nc's flags differ +# between the BSD tool macOS ships and builds found elsewhere. +port_in_use() { + "$NODE" -e 'const net=require("net");const s=net.connect(+process.argv[1],"127.0.0.1");s.on("connect",()=>{s.destroy();process.exit(0)});s.on("error",()=>process.exit(1))' "$1" >/dev/null 2>&1 +} + +tail_logs() { + [ -f "$LOGS/server.err.log" ] || return 0 + err "last lines from $LOGS/server.err.log:" + tail -n 20 "$LOGS/server.err.log" >&2 || true +} + +open_window() { + local url="$1" + if [ "$WINDOW" = "browser" ]; then + open "$url" + return + fi + if [ -d "/Applications/Google Chrome.app" ] || [ -d "$HOME/Applications/Google Chrome.app" ]; then + open -na "Google Chrome" --args \ + --app="$url" \ + --user-data-dir="$DATA/window-profile-chrome" \ + --window-size=1500,950 --no-first-run --no-default-browser-check + elif [ -d "/Applications/Microsoft Edge.app" ] || [ -d "$HOME/Applications/Microsoft Edge.app" ]; then + open -na "Microsoft Edge" --args \ + --app="$url" \ + --user-data-dir="$DATA/window-profile-edge" \ + --window-size=1500,950 --no-first-run --no-default-browser-check + else + open "$url" + fi +} + +verify() { + local status=0 file size + for file in "$NODE" "$APP/server/index.mjs" "$APP/dist/index.html"; do + if [ ! -f "$file" ]; then + err "missing: ${file#"$HERE"/}" + status=3 + elif [ ! -s "$file" ]; then + err "empty: ${file#"$HERE"/}" + status=3 + else + size=$(wc -c <"$file" | tr -d ' ') + say "ok: ${file#"$HERE"/} ($size bytes)" + fi + done + say "bundle: $HERE" + say "version: $(version_line)" + return $status +} + +start() { + [ -x "$NODE" ] || chmod +x "$NODE" 2>/dev/null || true + + if [ -f "$STATE" ]; then + local existing + existing=$(state_port) + if [ -n "$existing" ] && healthy "$existing"; then + say "already running on port $existing" + open_window "http://127.0.0.1:$existing" + exit 0 + fi + rm -f "$STATE" + fi + + if ! verify >/dev/null 2>&1; then + verify >&2 || true + dialog "This copy of Luminary is incomplete. Copy Luminary.app out of the disk image or zip and try again. If it still fails, download the app again." + exit 3 + fi + + mkdir -p "$DATA" "$LOGS" 2>/dev/null || { + dialog "Luminary cannot write to $DATA. Set LUMINARY_DATA to a folder you can write to and try again." + exit 1 + } + + local port="" + local candidate + # Brace expansion instead of seq: macOS does not ship seq. + for candidate in {8787..8887}; do + if ! port_in_use "$candidate"; then + port="$candidate" + break + fi + done + [ -n "$port" ] || { dialog "No free port between 8787 and 8887. Quit the app using one and try again."; exit 1; } + + LUMINARY_DATA="$DATA" \ + LUMINARY_LOCAL=1 \ + HOST=127.0.0.1 \ + PORT="$port" \ + NODE_ENV=production \ + nohup "$NODE" --disable-warning=ExperimentalWarning "$APP/server/index.mjs" \ + >>"$LOGS/server.out.log" 2>>"$LOGS/server.err.log" & + local pid=$! + + printf '{\n "pid": %s,\n "port": %s,\n "url": "http://127.0.0.1:%s",\n "data": "%s",\n "started": "%s"\n}\n' \ + "$pid" "$port" "$port" "$DATA" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$STATE" + + local waited=0 + while [ "$waited" -lt 240 ]; do + if healthy "$port"; then + open_window "http://127.0.0.1:$port" + exit 0 + fi + if ! kill -0 "$pid" 2>/dev/null; then + rm -f "$STATE" + tail_logs + dialog "Luminary's server stopped while starting. Log: $LOGS/server.err.log" + exit 1 + fi + sleep 0.5 + waited=$((waited + 1)) + done + + kill "$pid" 2>/dev/null || true + rm -f "$STATE" + tail_logs + dialog "Luminary did not start within 120 seconds. Log: $LOGS/server.err.log" + exit 1 +} + +stop() { + if [ ! -f "$STATE" ]; then + say "not running" + return 0 + fi + local pid + pid=$(state_pid) + if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then + kill -TERM "$pid" 2>/dev/null || true + local tick + for tick in {1..20}; do + kill -0 "$pid" 2>/dev/null || break + sleep 0.25 + done + kill -0 "$pid" 2>/dev/null && kill -KILL "$pid" 2>/dev/null || true + say "stopped (pid $pid)" + else + say "not running (removed a stale runtime.json)" + fi + rm -f "$STATE" +} + +status() { + local port pid + port=$(state_port) + pid=$(state_pid) + say "version: $(version_line)" + say "bundle: $HERE" + say "data: $DATA" + if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then + say "pid: $pid" + elif [ -n "$pid" ]; then + say "pid: $pid (not running)" + else + say "pid: -" + fi + if [ -n "$port" ] && healthy "$port"; then + say "health: ok on http://127.0.0.1:$port" + elif [ -n "$port" ]; then + say "health: no response on port $port" + else + say "health: not started" + fi +} + +case "${1:-}" in + --stop) stop ;; + --status) status ;; + --verify) verify; exit $? ;; + --browser) WINDOW=browser; start ;; + --help | -h) + cat <<'USAGE' +Luminary.app launcher + +No argument starts the app (or reuses a running copy) and opens the window. + --browser open a normal browser tab instead of a Chrome/Edge app window + --stop stop the server this bundle started + --status print version, pid, port, health and the data directory + --verify check that the bundle is complete + +Data: ~/Library/Application Support/Luminary/data (override with LUMINARY_DATA) +Logs: /logs/server.out.log and server.err.log +USAGE + ;; + "") start ;; + *) + err "unknown argument: $1 (try --help)" + exit 2 + ;; +esac diff --git a/macos/launcher/main.c b/macos/launcher/main.c new file mode 100644 index 0000000..d0771e3 --- /dev/null +++ b/macos/launcher/main.c @@ -0,0 +1,73 @@ +/* + * Luminary.app main executable. + * + * The bundle needs a Mach-O main executable so it can be code signed and, if a + * certificate is ever bought, notarized: Apple's notary service rejects a + * bundle whose CFBundleExecutable is a shell script. This shim resolves its own + * path, finds Contents/Resources/launcher.sh next to it, and execs bash on it, + * passing every argument through. All the actual launcher logic lives in that + * script, where it can be changed without recompiling anything. + */ +#include +#include +#include +#include +#include + +#ifdef __APPLE__ +#include +#endif + +/** Write this process's executable path into buf, or return -1. */ +static int executable_path(char *buf, size_t size) { +#ifdef __APPLE__ + uint32_t needed = (uint32_t)size; + if (_NSGetExecutablePath(buf, &needed) != 0) return -1; + return 0; +#else + /* Not used in the bundle; kept so the shim can be built and tested when + * packaging is exercised from a non-Apple host. */ + ssize_t length = readlink("/proc/self/exe", buf, size - 1); + if (length < 0) return -1; + buf[length] = '\0'; + return 0; +#endif +} + +int main(int argc, char **argv) { + char raw[PATH_MAX]; + char exe[PATH_MAX]; + char script[PATH_MAX]; + + if (executable_path(raw, sizeof raw) != 0) { + fprintf(stderr, "luminary: cannot resolve the application path\n"); + return 1; + } + if (realpath(raw, exe) == NULL) { + fprintf(stderr, "luminary: cannot resolve %s\n", raw); + return 1; + } + + /* exe is .../Luminary.app/Contents/MacOS/Luminary */ + char *slash = strrchr(exe, '/'); + if (slash == NULL) { + fprintf(stderr, "luminary: unexpected executable path %s\n", exe); + return 1; + } + *slash = '\0'; + + if (snprintf(script, sizeof script, "%s/../Resources/launcher.sh", exe) >= (int)sizeof script) { + fprintf(stderr, "luminary: application path is too long\n"); + return 1; + } + + char *args[argc + 2]; + args[0] = "/bin/bash"; + args[1] = script; + for (int i = 1; i < argc; i++) args[i + 1] = argv[i]; + args[argc + 1] = NULL; + + execv("/bin/bash", args); + perror("luminary: could not start the launcher"); + return 1; +} diff --git a/package.json b/package.json index 280c0f4..b372977 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ "dev": "vite", "server": "node server/index.mjs", "server:dev": "node --watch server/index.mjs", - "build": "tsc --noEmit && vite build", + "build": "tsc --noEmit && vite build && node scripts/precompress.mjs", + "precompress": "node scripts/precompress.mjs", + "backup": "node scripts/backup.mjs", "start": "node server/index.mjs", "preview": "vite preview", "typecheck": "tsc --noEmit", diff --git a/scripts/backup.mjs b/scripts/backup.mjs new file mode 100644 index 0000000..bef90aa --- /dev/null +++ b/scripts/backup.mjs @@ -0,0 +1,185 @@ +/** + * Catalog backups without stopping the server. + * + * `VACUUM INTO` writes a consistent copy of the live SQLite database (including + * everything still in the WAL), so a backup is safe while people are editing. + * Originals are large, so copying them is opt-in: previews, thumbnails and + * denoise renders are all regenerable, originals are not. + * + * npm run backup # database only, keep 14 + * npm run backup -- --with-originals # also copy originals/ (can be huge) + * npm run backup -- --keep 30 --dir /mnt/backups + * + * Restore: stop the server, put the `catalog-*.db` snapshot back as lumenroom.db + * (delete the old -wal/-shm files) and copy the originals snapshot back into the + * storage root. + */ + +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +function argValue(name, fallback) { + const index = process.argv.indexOf(`--${name}`); + if (index < 0) return fallback; + const value = process.argv[index + 1]; + return value && !value.startsWith('--') ? value : fallback; +} + +const DATA_DIR = path.resolve( + process.env.LUMINARY_DATA || process.env.LUMENROOM_DATA || path.join(ROOT, 'server', 'data'), +); +const DB_PATH = path.join(DATA_DIR, 'lumenroom.db'); +const BACKUP_DIR = path.resolve( + argValue('dir', process.env.LUMINARY_BACKUP_DIR || path.join(DATA_DIR, 'backups')), +); +const KEEP = Math.max(1, Number(argValue('keep', process.env.LUMINARY_BACKUP_KEEP || '14')) || 14); +const WITH_ORIGINALS = process.argv.includes('--with-originals'); + +const pad = (value) => String(value).padStart(2, '0'); +const now = new Date(); +const stamp = [ + now.getFullYear(), + pad(now.getMonth() + 1), + pad(now.getDate()), + '-', + pad(now.getHours()), + pad(now.getMinutes()), + pad(now.getSeconds()), +].join(''); + +const fmt = (bytes) => { + if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`; + if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`; + if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`; + return `${bytes} B`; +}; + +/** The admin may have moved image files out of DATA_DIR; the catalog knows. */ +function storageRoot() { + const db = new DatabaseSync(DB_PATH, { readOnly: true }); + try { + const row = db.prepare("SELECT value FROM kv WHERE key = 'storageRoot'").get(); + if (!row?.value) return DATA_DIR; + const parsed = JSON.parse(row.value); + return typeof parsed === 'string' && parsed.trim() ? path.resolve(parsed) : DATA_DIR; + } catch { + return DATA_DIR; + } finally { + db.close(); + } +} + +async function prune(prefix, keep) { + let names = []; + try { + names = (await fsp.readdir(BACKUP_DIR)).filter((name) => name.startsWith(prefix)); + } catch { + return 0; + } + names.sort(); + const stale = names.slice(0, Math.max(0, names.length - keep)); + for (const name of stale) { + await fsp.rm(path.join(BACKUP_DIR, name), { recursive: true, force: true }); + } + return stale.length; +} + +if (!fs.existsSync(DB_PATH)) { + console.error(`backup: no catalog at ${DB_PATH}`); + process.exit(1); +} + +await fsp.mkdir(BACKUP_DIR, { recursive: true }); + +/* --------------------------------------------------------- database snapshot */ +const snapshot = path.join(BACKUP_DIR, `catalog-${stamp}.db`); +const db = new DatabaseSync(DB_PATH); +let counts; +try { + // VACUUM INTO is a consistent point-in-time copy and also compacts it. + db.exec(`VACUUM INTO '${snapshot.replaceAll("'", "''")}'`); + counts = { + users: Number(db.prepare('SELECT COUNT(*) AS n FROM users').get()?.n ?? 0), + events: Number(db.prepare('SELECT COUNT(*) AS n FROM events').get()?.n ?? 0), + photos: Number(db.prepare('SELECT COUNT(*) AS n FROM photos').get()?.n ?? 0), + }; +} catch (err) { + console.error(`backup: could not snapshot the catalog: ${err.message}`); + process.exit(1); +} finally { + db.close(); +} + +/* Verify the copy opens and is internally consistent before trusting it. */ +const check = new DatabaseSync(snapshot, { readOnly: true }); +let integrity = 'unknown'; +try { + integrity = String(check.prepare('PRAGMA integrity_check').get()?.integrity_check ?? 'unknown'); +} finally { + check.close(); +} +if (integrity !== 'ok') { + console.error(`backup: snapshot failed its integrity check (${integrity})`); + process.exit(1); +} + +const dbBytes = (await fsp.stat(snapshot)).size; +let copiedOriginals = null; +let originalsBytes = 0; + +/* ---------------------------------------------------------------- originals */ +if (WITH_ORIGINALS) { + const source = path.join(storageRoot(), 'originals'); + const target = path.join(BACKUP_DIR, `originals-${stamp}`); + try { + await fsp.cp(source, target, { recursive: true, force: true }); + for (const name of await fsp.readdir(target)) { + const stat = await fsp.stat(path.join(target, name)).catch(() => null); + if (stat?.isFile()) originalsBytes += stat.size; + } + copiedOriginals = target; + } catch (err) { + console.error(`backup: catalog saved, but copying originals failed: ${err.message}`); + process.exitCode = 1; + } +} + +await fsp.writeFile( + path.join(BACKUP_DIR, `manifest-${stamp}.json`), + `${JSON.stringify( + { + kind: 'luminary-backup', + version: 1, + createdAt: now.toISOString(), + catalog: path.basename(snapshot), + counts, + bytes: dbBytes, + originals: copiedOriginals ? { path: path.basename(copiedOriginals), bytes: originalsBytes } : null, + storageRoot: storageRoot(), + }, + null, + 2, + )}\n`, +); + +const prunedDb = await prune('catalog-', KEEP); +const prunedOriginals = WITH_ORIGINALS ? await prune('originals-', KEEP) : 0; +const prunedManifests = await prune('manifest-', KEEP); + +console.log(`backup: ${snapshot}`); +console.log( + ` ${fmt(dbBytes)} · ${counts.users} user(s), ${counts.events} event(s), ${counts.photos} photo record(s)`, +); +if (copiedOriginals) console.log(` originals: ${copiedOriginals} (${fmt(originalsBytes)})`); +const pruned = prunedDb + prunedOriginals + prunedManifests; +if (pruned) console.log(` pruned ${pruned} old file(s), keeping ${KEEP}`); +if (!WITH_ORIGINALS) { + console.log( + ` note: original files were not copied; run with --with-originals or rsync ${path.join(storageRoot(), 'originals')}`, + ); +} diff --git a/scripts/precompress.mjs b/scripts/precompress.mjs new file mode 100644 index 0000000..b19111e --- /dev/null +++ b/scripts/precompress.mjs @@ -0,0 +1,93 @@ +/** + * Writes `.br` and `.gz` copies of the text assets next to the built files. + * + * The server serves those directly when a browser offers an encoding, so no + * request ever pays for compression: `index-*.js` is ~780 kB raw and ~240 kB + * gzipped, which is the difference between a slow and a normal first load. + * Images and fonts are already compressed and are left alone. + */ + +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const DIST = path.join(ROOT, 'dist'); +const MIN_BYTES = 1024; +const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.json', '.map', '.txt', '.xml', '.webmanifest']); + +const brotliOptions = { + params: { + [zlib.constants.BROTLI_PARAM_QUALITY]: 11, + [zlib.constants.BROTLI_PARAM_SIZE_HINT]: 0, + }, +}; + +async function* walk(dir) { + for (const entry of await fsp.readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) yield* walk(full); + else if (entry.isFile()) yield full; + } +} + +function isStale(source, target) { + try { + const out = fs.statSync(target); + return out.mtimeMs < fs.statSync(source).mtimeMs; + } catch { + return true; + } +} + +async function compressFile(file, totals) { + const ext = path.extname(file).toLowerCase(); + if (!COMPRESSIBLE.has(ext)) return 0; + const stat = await fsp.stat(file); + if (stat.size < MIN_BYTES) return 0; + + const raw = await fsp.readFile(file); + let files = 0; + + for (const variant of ['gz', 'br']) { + const target = `${file}.${variant}`; + if (!isStale(file, target)) continue; + const body = + variant === 'gz' + ? zlib.gzipSync(raw, { level: 9 }) + : zlib.brotliCompressSync(raw, { + ...brotliOptions, + params: { + ...brotliOptions.params, + [zlib.constants.BROTLI_PARAM_SIZE_HINT]: raw.length, + }, + }); + // A "compressed" file that is larger than the original is never served. + if (body.length >= raw.length) { + await fsp.rm(target, { force: true }); + continue; + } + await fsp.writeFile(target, body); + files += 1; + totals[variant] += raw.length - body.length; + } + return files; +} + +if (!fs.existsSync(DIST)) { + console.error('precompress: dist/ is missing — run "vite build" first'); + process.exit(1); +} + +const totals = { gz: 0, br: 0 }; +let files = 0; +for await (const file of walk(DIST)) { + files += await compressFile(file, totals); +} + +const kb = (bytes) => `${Math.round(bytes / 1024)} kB`; +console.log( + `precompress: wrote ${files} variant(s); a full load saves ${kb(totals.gz)} with gzip or ${kb(totals.br)} with brotli`, +); diff --git a/server/http.test.mjs b/server/http.test.mjs new file mode 100644 index 0000000..50c48b7 --- /dev/null +++ b/server/http.test.mjs @@ -0,0 +1,282 @@ +/** + * Server HTTP integration tests. + * + * The real server is started once against a throwaway data directory, so these + * exercise the routing, session, ownership, quota, gallery and file-serving + * layers that the pure-logic suite cannot reach. Nothing touches a real catalog. + */ + +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, test } from 'vitest'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const PORT = 18_000 + Math.floor(Math.random() * 20_000); +const BASE = `http://127.0.0.1:${PORT}`; + +let child = null; +let dataDir = ''; +let output = ''; + +/** One browser: keeps the cookies the server sets for this session. */ +class Client { + cookies = new Map(); + + async call(pathname, init = {}) { + const headers = { ...(init.headers ?? {}) }; + if (this.cookies.size) { + headers.cookie = [...this.cookies].map(([key, value]) => `${key}=${value}`).join('; '); + } + const res = await fetch(BASE + pathname, { ...init, headers }); + for (const raw of res.headers.getSetCookie?.() ?? []) { + const [pair] = raw.split(';'); + const at = pair.indexOf('='); + const key = pair.slice(0, at).trim(); + const value = pair.slice(at + 1).trim(); + if (!value || /Max-Age=0/i.test(raw)) this.cookies.delete(key); + else this.cookies.set(key, value); + } + return res; + } + + async json(pathname, init = {}) { + const res = await this.call(pathname, init); + const text = await res.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = { raw: text }; + } + return { res, body }; + } +} + +const postJson = (payload) => ({ + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(payload), +}); +const putJson = (payload) => ({ ...postJson(payload), method: 'PUT' }); + +const admin = new Client(); +const member = new Client(); +const guest = new Client(); + +const eventId = 'evt-http-test'; +const photoId = 'ph-http-test'; +const photoBytes = Buffer.alloc(8 * 1024, 7); + +function photoRecord(extra = {}) { + return { + id: photoId, + eventId, + name: 'audit.jpg', + width: 100, + height: 80, + size: 2, + mime: 'image/jpeg', + addedAt: Date.now(), + edits: {}, + history: [], + rating: 0, + flag: 'none', + keywords: [], + thumb: '', + ...extra, + }; +} + +beforeAll(async () => { + dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'luminary-http-')); + child = spawn(process.execPath, ['server/index.mjs'], { + cwd: ROOT, + env: { + ...process.env, + LUMINARY_DATA: dataDir, + PORT: String(PORT), + HOST: '127.0.0.1', + LUMINARY_LOCAL: '', + LUMINARY_INVITE: '', + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout.on('data', (chunk) => { + output += chunk; + }); + child.stderr.on('data', (chunk) => { + output += chunk; + }); + + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + try { + const res = await fetch(`${BASE}/api/health`); + if (res.ok) return; + } catch { + /* not listening yet */ + } + await new Promise((resolve) => setTimeout(resolve, 150)); + } + throw new Error(`server did not start\n${output}`); +}, 45_000); + +afterAll(async () => { + child?.kill('SIGKILL'); + if (dataDir) await fsp.rm(dataDir, { recursive: true, force: true }).catch(() => undefined); +}); + +describe('auth and ownership', () => { + test('the first account is the admin and gets a session', async () => { + const { res, body } = await admin.json( + '/api/auth/register', + postJson({ email: 'Admin@Example.com', password: 'password123', name: 'Admin' }), + ); + expect(res.status).toBe(201); + expect(body.user.role).toBe('admin'); + + const me = await admin.json('/api/auth/me'); + expect(me.res.status).toBe(200); + expect(me.body.user.email).toBe('admin@example.com'); + }); + + test('registration is closed once an account exists', async () => { + const { res } = await guest.json( + '/api/auth/register', + postJson({ email: 'walk-in@example.com', password: 'password123' }), + ); + expect(res.status).toBe(403); + }); + + test('an invited member cannot reach another owner\'s photo', async () => { + const invite = await admin.json( + '/api/admin/invites', + postJson({ email: 'member@example.com', role: 'member' }), + ); + expect(invite.res.status).toBe(201); + + const registered = await member.json( + '/api/auth/register', + postJson({ + email: 'member@example.com', + password: 'password123', + inviteToken: invite.body.invite.token, + }), + ); + expect(registered.res.status).toBe(201); + expect(registered.body.user.role).toBe('member'); + + const upload = await admin.call(`/api/photos/${photoId}/original?name=audit.jpg&mime=image/jpeg`, { + method: 'POST', + headers: { 'content-type': 'application/octet-stream' }, + body: photoBytes, + }); + expect(upload.status).toBe(201); + }); + + test('a saved record cannot shrink its measured size', async () => { + const saved = await admin.json(`/api/photos/${photoId}`, putJson(photoRecord())); + expect(saved.res.status).toBe(200); + + const quota = await admin.json('/api/quota'); + expect(quota.res.status).toBe(200); + expect(quota.body.used).toBe(photoBytes.length); + }); + + test('a member cannot read or overwrite the admin\'s photo', async () => { + const preview = await member.call(`/api/photos/${photoId}/preview`); + expect(preview.status).toBe(404); + + const overwrite = await member.call(`/api/photos/${photoId}`, putJson({ ...photoRecord(), name: 'stolen.jpg' })); + expect(overwrite.status).toBe(404); + }); + + test('a member cannot park a photo inside another owner\'s event', async () => { + const event = await admin.call(`/api/events/${eventId}`, putJson({ id: eventId, name: 'Audit shoot', createdAt: Date.now() })); + expect(event.status).toBe(200); + + const sneaky = await member.call('/api/photos/ph-member-1', putJson(photoRecord({ id: 'ph-member-1' }))); + expect(sneaky.status).toBe(404); + }); +}); + +describe('file serving', () => { + test('byte ranges resume a download', async () => { + const res = await admin.call(`/api/photos/${photoId}/original`, { + headers: { range: 'bytes=100-199' }, + }); + expect(res.status).toBe(206); + expect(res.headers.get('content-range')).toBe(`bytes 100-199/${photoBytes.length}`); + expect(res.headers.get('accept-ranges')).toBe('bytes'); + const body = Buffer.from(await res.arrayBuffer()); + expect(body.equals(photoBytes.subarray(100, 200))).toBe(true); + }); + + test('an impossible range is refused without touching other requests', async () => { + const res = await admin.call(`/api/photos/${photoId}/original`, { + headers: { range: `bytes=${photoBytes.length + 10}-` }, + }); + expect(res.status).toBe(416); + const health = await fetch(`${BASE}/api/health`); + expect(health.status).toBe(200); + }); + + test('an unreadable original answers 404 and leaves the server running', async () => { + if (process.getuid?.() === 0) return; // root ignores file permissions + const original = path.join(dataDir, 'originals', `${photoId}.jpg`); + fs.chmodSync(original, 0o000); + try { + const res = await admin.call(`/api/photos/${photoId}/original`); + expect(res.status).toBe(404); + const health = await fetch(`${BASE}/api/health`); + expect(health.status).toBe(200); + } finally { + fs.chmodSync(original, 0o644); + } + }); +}); + +describe('proofing gallery', () => { + test('downloads count against the cap only when a file is sent', async () => { + const share = await admin.json(`/api/events/${eventId}/share`, { method: 'POST' }); + expect(share.res.status).toBe(200); + const token = share.body.token; + + const settings = await admin.call( + `/api/events/${eventId}/share/settings`, + putJson({ allowDownloads: true, downloadCap: 2 }), + ); + expect(settings.status).toBe(200); + + const pick = await guest.call( + `/api/galleries/${token}/picks`, + postJson({ photoId, clientId: 'client-1', clientName: 'Client', picked: true }), + ); + expect(pick.status).toBe(200); + + // First download uses one of the two allowed downloads. + const first = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`); + expect(first.status).toBe(200); + await first.arrayBuffer(); + + // A missing render must not consume the remaining allowance. + const original = path.join(dataDir, 'originals', `${photoId}.jpg`); + // Outside originals/: any `.*` name inside that folder is still an original. + const parked = path.join(dataDir, `${photoId}.jpg.parked`); + await fsp.rename(original, parked); + const missing = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`); + expect(missing.status).toBe(404); + await fsp.rename(parked, original); + + const second = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`); + expect(second.status).toBe(200); + await second.arrayBuffer(); + + const third = await guest.call(`/api/galleries/${token}/photos/${photoId}/download`); + expect(third.status).toBe(403); + }); +}); diff --git a/server/index.mjs b/server/index.mjs index c0ecb85..3ad2389 100644 --- a/server/index.mjs +++ b/server/index.mjs @@ -58,6 +58,7 @@ import { import { defaultRoot, findOriginal, + findOriginals, findPreview, findPreview16, findProof, @@ -531,7 +532,13 @@ function match(pathname, pattern) { const params = {}; for (let i = 0; i < p.length; i++) { if (p[i].startsWith(':')) { - params[p[i].slice(1)] = decodeURIComponent(a[i]); + // A malformed escape such as %E0%A4%A must not throw URIError out of the + // router; it simply cannot match any record. + try { + params[p[i].slice(1)] = decodeURIComponent(a[i]); + } catch { + return null; + } } else if (p[i] !== a[i]) { return null; } @@ -539,6 +546,40 @@ function match(pathname, pattern) { return params; } +/** `bytes=start-end` / `bytes=start-` / `bytes=-suffix`, first range only. */ +function parseRange(header, size) { + if (typeof header !== 'string' || !header.startsWith('bytes=')) return null; + const spec = header.slice(6).split(',')[0].trim(); + const match = /^(\d*)-(\d*)$/.exec(spec); + if (!match) return null; + const [, rawStart, rawEnd] = match; + if (!rawStart && !rawEnd) return null; + let start; + let end; + if (!rawStart) { + const suffix = Number(rawEnd); + if (!Number.isFinite(suffix) || suffix <= 0) return { unsatisfiable: true }; + start = Math.max(0, size - suffix); + end = size - 1; + } else { + start = Number(rawStart); + end = rawEnd ? Number(rawEnd) : size - 1; + if (end >= size) end = size - 1; + } + if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) { + return { unsatisfiable: true }; + } + return { start, end }; +} + +/** The precompressed variant the client can take, if this build wrote one. */ +function acceptedEncoding(req) { + const value = String(req.headers['accept-encoding'] ?? '').toLowerCase(); + if (value.includes('br')) return 'br'; + if (value.includes('gzip')) return 'gzip'; + return null; +} + function sendBuffer(res, data, type, cache = 'private, max-age=3600') { res.writeHead(200, { 'Content-Type': type, @@ -561,19 +602,59 @@ function bridgeLinkForPhoto(photoId) { async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) { if (!filePath) return error(res, 404, 'Not found'); + // Open first, then stat the open handle. A file can vanish or lose its + // permissions between a separate stat and open, and a ReadStream error with + // no listener is an uncaught exception that takes the whole server down. + let handle; try { - const stat = await fsp.stat(filePath); - res.writeHead(200, { + handle = await fsp.open(filePath, 'r'); + } catch { + return error(res, 404, 'Not found'); + } + try { + const stat = await handle.stat(); + // Byte ranges let a 300 MB original resume after a dropped connection + // instead of starting over. The whole file is still streamed, never read + // into memory. + const range = req.method === 'GET' ? parseRange(req.headers.range, stat.size) : null; + if (range?.unsatisfiable) { + await handle.close(); + res.writeHead(416, { + 'Content-Range': `bytes */${stat.size}`, + 'Accept-Ranges': 'bytes', + 'Cache-Control': cache, + 'X-Content-Type-Options': 'nosniff', + }); + return res.end(); + } + const start = range ? range.start : 0; + const end = range ? range.end : stat.size - 1; + const length = stat.size === 0 ? 0 : end - start + 1; + const headers = { 'Content-Type': type, - 'Content-Length': stat.size, + 'Content-Length': length, 'Cache-Control': cache, 'X-Content-Type-Options': 'nosniff', + 'Accept-Ranges': 'bytes', ...extraHeaders, - }); - if (req.method === 'HEAD') return res.end(); - fs.createReadStream(filePath).pipe(res); + }; + if (range) headers['Content-Range'] = `bytes ${start}-${end}/${stat.size}`; + res.writeHead(range ? 206 : 200, headers); + if (req.method === 'HEAD' || length === 0) { + await handle.close(); + return res.end(); + } + const stream = range ? handle.createReadStream({ start, end }) : handle.createReadStream(); + // A read that fails mid-transfer (unmounted volume, I/O error) cannot be + // turned into an error page once the 200 is on the wire, but it must not + // crash the process either. + stream.on('error', () => res.destroy()); + res.on('close', () => stream.destroy()); + return stream.pipe(res); } catch { - error(res, 404, 'Not found'); + await handle.close().catch(() => undefined); + if (!res.headersSent) return error(res, 404, 'Not found'); + return res.destroy(); } } @@ -1765,9 +1846,12 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par if (!hit) return error(res, 404, 'Not found'); const proof = findProof(params.id); const file = proof ?? findPreview(params.id) ?? findOriginal(params.id); + if (!file) return error(res, 404, 'Not found'); const originalName = String(hit.photo.name || 'photo.jpg'); const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-'); const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); + // Count the download only once there is a file to send, so a missing render + // does not quietly use up the client's allowance. noteGalleryDownload(params.token); return sendFile(req, res, file, mime, 'private, max-age=3600', { 'Content-Disposition': `attachment; filename="${safe}"`, @@ -2088,18 +2172,32 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { // New ids are part of the normal import flow: the client uploads bytes first // and PUTs the record afterwards. Until that row exists the bytes are charged // to this user's quota, so nobody can fill the disk with unclaimed files. - const limit = owner - ? MAX_UPLOAD - : Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id))); + // An existing photo may still be replaced, but the replacement only has the + // room its own file frees plus what is left of the quota: an account that is + // already full can shrink an original, never grow one past its cap. + const replacing = owner !== null ? findOriginal(params.id) : null; + const replacedBytes = replacing + ? ((await fsp.stat(replacing).catch(() => null))?.size ?? 0) + : 0; + const limit = Math.min( + MAX_UPLOAD, + Math.max(0, quotaState(user.id).remaining + replacedBytes - pendingBytes(user.id)), + ); if (limit < 1) { - return error(res, 413, 'This account has no storage quota left for a new upload'); + return error( + res, + 413, + owner + ? 'This account has no storage quota left for this file' + : 'This account has no storage quota left for a new upload', + ); } const announced = Number(req.headers['content-length']); if (Number.isFinite(announced) && announced > limit) { return error( res, 413, - owner + announced > MAX_UPLOAD ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` : 'This upload does not fit in the remaining storage quota', ); @@ -2117,8 +2215,6 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { } const target = originalTarget(params.id, ext); - const previous = findOriginal(params.id); - if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined); let size = 0; try { @@ -2129,7 +2225,7 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { return error( res, 413, - owner + limit >= MAX_UPLOAD ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` : 'This upload does not fit in the remaining storage quota', ); @@ -2141,6 +2237,15 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { return error(res, 400, 'Empty upload'); } + // Replace the previous bytes only now that the new file is safely on disk: a + // failed or aborted replacement must leave the photo it was replacing + // readable. Other extensions are dropped too, so an id never keeps a stale + // copy that `findOriginal` might return instead of the new file. + for (const previous of findOriginals(params.id)) { + if (previous === target) continue; + await fsp.rm(previous, { force: true }).catch(() => undefined); + } + recentUploads.set(params.id, { ownerId: user.id, bytes: size, @@ -2458,6 +2563,13 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => { if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL'); const record = { ...body, id: params.id }; + // A photo may only join an event in the same workspace; otherwise a member + // could park rows inside someone else's event and skew its totals. + const targetEventId = typeof record.eventId === 'string' ? record.eventId : ''; + if (targetEventId && !ownedBy(eventOwner(targetEventId), user)) { + return error(res, 404, 'No such event'); + } + // Quota accounting uses bytes the server actually received, not the client's // claim, for an upload that just finished. const upload = recentUploads.get(params.id); @@ -2467,6 +2579,16 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => { } record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name); + // Library totals, quota usage and prune plans are measured from the bytes on + // disk, not from what a saved record claims. Without this a client could PUT + // size: 2 for a 20 MB original, shrink its reported usage and dodge its quota + // while the file stayed on the volume. + const storedOriginal = findOriginal(params.id); + if (storedOriginal) { + const stat = await fsp.stat(storedOriginal).catch(() => null); + if (stat) record.size = stat.size; + } + const thumb = decodeDataUrl(record.thumb); if (thumb) { await writeThumb(params.id, thumb.data); @@ -2543,13 +2665,22 @@ async function serveStatic(req, res, url) { if (stat.isFile()) { const ext = path.extname(candidate).toLowerCase(); const immutable = pathname.startsWith('/assets/'); - return sendFile( - req, - res, - candidate, - MIME[ext] ?? 'application/octet-stream', - immutable ? 'public, max-age=31536000, immutable' : 'no-cache', - ); + const cache = immutable ? 'public, max-age=31536000, immutable' : 'no-cache'; + const mime = MIME[ext] ?? 'application/octet-stream'; + // `npm run build` writes .br/.gz copies of the text assets, so the + // first request does not pay for compression and every later one is + // just a file read. + const encoding = acceptedEncoding(req); + const variants = encoding === 'br' ? ['br', 'gz'] : encoding === 'gzip' ? ['gz'] : []; + for (const variant of variants) { + const packed = `${candidate}.${variant}`; + if (!fs.existsSync(packed)) continue; + return sendFile(req, res, packed, mime, cache, { + 'Content-Encoding': variant === 'br' ? 'br' : 'gzip', + Vary: 'Accept-Encoding', + }); + } + return sendFile(req, res, candidate, mime, cache); } } catch { /* fall through to the SPA entry */ diff --git a/server/storage.mjs b/server/storage.mjs index d0a8d4f..6166cc6 100644 --- a/server/storage.mjs +++ b/server/storage.mjs @@ -88,15 +88,20 @@ export function originalTarget(id, ext = 'bin') { return originalPath(id, ext); } -export function findOriginal(id) { +export function findOriginals(id) { const safe = lookupId(id); - if (!safe) return null; + if (!safe) return []; const { originals } = dirs(); const prefix = `${safe}.`; - for (const name of listFiles(originals)) { - if (name.startsWith(prefix)) return path.join(originals, name); - } - return null; + return listFiles(originals) + // An interrupted upload leaves `..part-xxxx` behind; it is not a + // usable original, and returning it would serve a truncated image. + .filter((name) => name.startsWith(prefix) && !name.includes('.part-')) + .map((name) => path.join(originals, name)); +} + +export function findOriginal(id) { + return findOriginals(id)[0] ?? null; } export async function writePreview(id, data, ext = 'jpg') { diff --git a/src/App.tsx b/src/App.tsx index 5d8bbda..5f5282a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,21 +1,15 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import AboutModal from './components/AboutModal'; -import AdminPanel from './components/AdminPanel'; import CloudPanel from './components/CloudPanel'; import CommandPalette from './components/CommandPalette'; import ContextMenu, { type MenuEntry } from './components/ContextMenu'; import Develop from './components/Develop'; import EventSidebar from './components/EventSidebar'; import ExportModal from './components/ExportModal'; -import CompareView from './components/CompareView'; import FilterBar from './components/FilterBar'; import ImportModal from './components/ImportModal'; -import ImmichPanel from './components/ImmichPanel'; import LibraryGrid from './components/LibraryGrid'; -import MergeModal from './components/MergeModal'; import PasteSettingsModal from './components/PasteSettingsModal'; -import PrintModal from './components/PrintModal'; -import ShareModal from './components/ShareModal'; import RawReprocessModal, { type RawReprocessFailure, type RawReprocessJob, @@ -26,6 +20,15 @@ import Shortcuts from './components/Shortcuts'; import Stars, { ColorSwatches, FlagButtons } from './components/Stars'; import TopBar from './components/TopBar'; import { usePersistentState } from './lib/usePersistentState'; + +// Only mounted when the user opens them, so they are separate chunks: the grid +// and the editor are what the first paint needs. +const AdminPanel = lazy(() => import('./components/AdminPanel')); +const CompareView = lazy(() => import('./components/CompareView')); +const ImmichPanel = lazy(() => import('./components/ImmichPanel')); +const MergeModal = lazy(() => import('./components/MergeModal')); +const PrintModal = lazy(() => import('./components/PrintModal')); +const ShareModal = lazy(() => import('./components/ShareModal')); import { currentUser, deleteEventRemote, @@ -2563,32 +2566,38 @@ export default function App() { )} {compareOpen && selected.length >= 2 && selected.length <= 4 && ( - photos.find((photo) => photo.id === id)) - .filter((photo): photo is PhotoRecord => Boolean(photo)) - .slice(0, 4)} - onClose={() => setCompareOpen(false)} - onOpen={(id) => { - setCompareOpen(false); - openPhoto(id); - }} - /> + + photos.find((photo) => photo.id === id)) + .filter((photo): photo is PhotoRecord => Boolean(photo)) + .slice(0, 4)} + onClose={() => setCompareOpen(false)} + onOpen={(id) => { + setCompareOpen(false); + openPhoto(id); + }} + /> + )} {printOpen && ( - selected.includes(photo.id))} - onClose={() => setPrintOpen(false)} - /> + + selected.includes(photo.id))} + onClose={() => setPrintOpen(false)} + /> + )} {mergeOpen && ( - selected.includes(photo.id))} - onClose={() => setMergeOpen(false)} - onDone={(result) => void addMergedPhoto(result)} - /> + + selected.includes(photo.id))} + onClose={() => setMergeOpen(false)} + onDone={(result) => void addMergedPhoto(result)} + /> + )} {exportOpen && ( @@ -2638,13 +2647,15 @@ export default function App() { const shared = events.find((e) => e.id === shareEventId); if (!shared) return null; return ( - p.eventId === shared.id)} - onClose={() => setShareEventId(null)} - onToast={setToast} - onProofPublished={handleProofPublished} - /> + + p.eventId === shared.id)} + onClose={() => setShareEventId(null)} + onToast={setToast} + onProofPublished={handleProofPublished} + /> + ); })()} @@ -2681,26 +2692,30 @@ export default function App() { )} {adminOpen && cloudUser && !localMode && ( - setAdminOpen(false)} - onChanged={() => { - void getHealth().then((health) => setCloudHealth(health)); - void getImmichStatus().then(setImmichStatus).catch(() => undefined); - }} - onRestored={() => void refreshCatalogFromServer()} - /> + + setAdminOpen(false)} + onChanged={() => { + void getHealth().then((health) => setCloudHealth(health)); + void getImmichStatus().then(setImmichStatus).catch(() => undefined); + }} + onRestored={() => void refreshCatalogFromServer()} + /> + )} {immichOpen && cloudUser && ( - setImmichOpen(false)} - onChanged={() => { - void getImmichStatus().then(setImmichStatus).catch(() => undefined); - void refreshCatalogFromServer(); - }} - onToast={setToast} - /> + + setImmichOpen(false)} + onChanged={() => { + void getImmichStatus().then(setImmichStatus).catch(() => undefined); + void refreshCatalogFromServer(); + }} + onToast={setToast} + /> + )} {menu && diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..4a686e5 --- /dev/null +++ b/src/components/ErrorBoundary.tsx @@ -0,0 +1,105 @@ +import { Component, type ErrorInfo, type ReactNode } from 'react'; + +interface Props { + children: ReactNode; +} + +interface State { + error: Error | null; + componentStack: string; + version: string; + copied: boolean; +} + +/** + * Without this, one exception anywhere in the tree unmounts React and leaves a + * blank page with nothing to report. The boundary keeps a way back (reload) + * and a way to tell support what happened, and says plainly that the library + * itself is untouched. + */ +export default class ErrorBoundary extends Component { + state: State = { error: null, componentStack: '', version: '', copied: false }; + + static getDerivedStateFromError(error: Error): Partial { + return { error }; + } + + componentDidCatch(error: Error, info: ErrorInfo) { + console.error('Luminary crashed while rendering', error, info.componentStack); + this.setState({ componentStack: info.componentStack ?? '' }); + // The version is a nicety for the diagnostics; the page works without it. + fetch('/api/health', { credentials: 'same-origin' }) + .then((res) => (res.ok ? res.json() : null)) + .then((body: { version?: string } | null) => { + if (body?.version) this.setState({ version: body.version }); + }) + .catch(() => undefined); + } + + private diagnostics(): string { + const error = this.state.error; + return [ + 'Luminary crash report', + `Version: ${this.state.version || 'unknown'}`, + `When: ${new Date().toISOString()}`, + `Page: ${window.location.pathname}${window.location.search}`, + `Browser: ${navigator.userAgent}`, + `Screen: ${window.screen.width}x${window.screen.height} @${window.devicePixelRatio}x`, + '', + `Error: ${error?.name ?? 'Error'}: ${error?.message ?? 'unknown'}`, + error?.stack ?? '', + '', + 'Component stack:', + this.state.componentStack, + ].join('\n'); + } + + private async copyDiagnostics() { + try { + await navigator.clipboard.writeText(this.diagnostics()); + this.setState({ copied: true }); + window.setTimeout(() => this.setState({ copied: false }), 2500); + } catch { + // Clipboard access can be denied; the email link still carries the report. + this.setState({ copied: false }); + } + } + + render() { + const error = this.state.error; + if (!error) return this.props.children; + + const subject = encodeURIComponent('Luminary crash report'); + const body = encodeURIComponent(this.diagnostics().slice(0, 1800)); + const mailto = `mailto:bhursey@gmail.com?subject=${subject}&body=${body}`; + + return ( +
+
+

Luminary hit an unexpected error

+

+ Your photos, edits and catalog are safe on disk — nothing was deleted. Reloading + usually clears it. If it keeps happening, send the diagnostics below so it can be + fixed. +

+

{error.message || 'Unknown error'}

+
+ + + + Email support + +
+
+ Technical details +
{this.diagnostics()}
+
+
+
+ ); + } +} diff --git a/src/main.tsx b/src/main.tsx index 75f3b1b..772370e 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -1,9 +1,15 @@ +import { lazy, Suspense } from 'react'; import { createRoot } from 'react-dom/client'; import App from './App'; -import ProofingGallery from './components/ProofingGallery'; -import JoinPage from './components/JoinPage'; +import ErrorBoundary from './components/ErrorBoundary'; import './styles.css'; +// Proofing galleries and invite pages are public and self-contained: loading +// them lazily keeps the editor out of the chunk a client downloads to view a +// shoot, and keeps the invite page tiny. +const ProofingGallery = lazy(() => import('./components/ProofingGallery')); +const JoinPage = lazy(() => import('./components/JoinPage')); + const root = document.getElementById('root'); if (!root) throw new Error('root element missing'); @@ -14,11 +20,15 @@ const galleryMatch = /^\/g\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname) const joinMatch = /^\/join\/([A-Za-z0-9_-]+)\/?$/.exec(window.location.pathname); createRoot(root).render( - galleryMatch ? ( - - ) : joinMatch ? ( - - ) : ( - - ), + + + {galleryMatch ? ( + + ) : joinMatch ? ( + + ) : ( + + )} + + , ); diff --git a/src/styles.css b/src/styles.css index e827f13..908d042 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6066,3 +6066,78 @@ figcaption { line-height: 1.7; font-size: 12px; } + +/* ---------------------------------------------------------- crash boundary */ +/* Shown instead of a blank page when rendering throws. Kept light on purpose: + it must not depend on any component that could itself be broken. */ +.crash-screen { + min-height: 100vh; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + background: var(--bg); + color: var(--text); +} + +.crash-card { + width: min(560px, 100%); + padding: 26px 28px; + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + box-shadow: 0 18px 60px rgba(0, 0, 0, 0.45); +} + +.crash-card h1 { + margin: 0 0 10px; + font-size: 18px; + font-weight: 600; +} + +.crash-card p { + margin: 0 0 12px; + color: var(--muted); + line-height: 1.6; + font-size: 13px; +} + +.crash-card .crash-message { + padding: 10px 12px; + border-left: 3px solid var(--danger); + background: rgba(224, 93, 93, 0.08); + color: var(--text); + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + word-break: break-word; +} + +.crash-details { + margin-top: 16px; + color: var(--muted); + font-size: 12px; +} + +.crash-details summary { + cursor: pointer; + margin-bottom: 8px; +} + +.crash-details pre { + max-height: 240px; + overflow: auto; + padding: 10px 12px; + background: var(--bg); + border: 1px solid var(--line); + border-radius: var(--radius); + white-space: pre-wrap; + word-break: break-word; + font-size: 11px; + line-height: 1.5; +} + +.crash-card a.btn { + text-decoration: none; + display: inline-flex; + align-items: center; +}