import http from 'node:http'; import fs from 'node:fs'; import fsp from 'node:fs/promises'; import path from 'node:path'; import crypto from 'node:crypto'; import { DATA_DIR, DIST_DIR, HOST, INVITE, LOCAL_EMAIL, LOCAL_MODE, MAX_UPLOAD, PORT, RAW_PREVIEW_EDGE, TRUST_PROXY, } from './config.mjs'; import { authenticate, createSession, hashPassword, normalizeEmail, publicUser, spendPasswordCheck, validEmail, verifyPassword, } from './auth.mjs'; import { addGalleryComment, commentsByOwner, commentsForToken, countPhotos, eventByShareToken, eventOwner, galleryPick, getPhoto, invites, kv, lensProfiles, listEvents, listPhotos, livePhotoBytes, photoOwner, picksByOwner, picksForToken, removeEvent, reviewsByOwner, reviewsForToken, setGalleryReview, removePhoto, saveEvent, savePhoto, sessions, setShareToken, shareTokenFor, users, } from './db.mjs'; import { defaultRoot, findOriginal, findPreview, findPreview16, findProof, findProofThumb, findThumb, findThumb16, isCustomRoot, originalTarget, removeAsset, removePreview16, removeThumb16, setStorageRoot, storageBytes, storageRoot, writePreview, writePreview16, writeProof, writeProofThumb, writeThumb, writeThumb16, } from './storage.mjs'; import { previewRebuildTargets, startPreviewRebuild } from './previewRebuild.mjs'; import { decodeRaw, decodeStill, isRawName, isStillName, rawSupport } from './raw.mjs'; import { bridgeConfigured, bridgeForEvent, exchangeBridgeToken, fetchBridgeImage, forwardBridgeRender, importBridgeEvent, purgeExpiredBridges, verifyBridgeToken, } from './bridge.mjs'; import { cameraThumb16, jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; import { createZip } from './zip.mjs'; import { parseCalibration } from './lensCalibration.mjs'; import { cancelPrune, quotaState, quotasForAdmin, schedulePrune, setUserQuota, startQuotaWorker, warnUser, } from './quota.mjs'; import { mailStatus, saveMailSettings, sendTestMail } from './mail.mjs'; import { createImmichAlbumForEvent, disconnectImmich, disconnectImmichAdmin, immichAdminPing, immichAdminStatus, immichConfigured, immichEventQueue, immichJobFor, immichLinksForOwner, immichPendingPhotos, immichPing, immichStatusFor, listImmichAlbums, publishImmichOriginal, pushImmichPhoto, pushImmichPhotoMetadata, saveImmichAdminSettings, saveImmichUserSettings, startImmichImport, } from './immich.mjs'; const VERSION = '1.0.0'; const COOKIE = 'lumen_session'; /** Self-only policy; must allow the wasm engines and React inline styles. */ const CSP = [ "default-src 'self'", "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:", "font-src 'self' data:", "connect-src 'self'", "media-src 'self' blob:", "worker-src 'self' blob:", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'self'", ].join('; '); /* ------------------------------------------------------------------ helpers */ function json(res, status, payload, extraHeaders = {}) { const body = Buffer.from(JSON.stringify(payload)); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': body.length, 'Cache-Control': 'no-store', ...extraHeaders, }); res.end(body); } class PayloadTooLarge extends Error {} function error(res, status, message, extraHeaders = {}) { json(res, status, { error: message }, extraHeaders); } /** Failed sign-ins are bucketed per socket address and per account. */ const AUTH_WINDOW_MS = 15 * 60 * 1000; const authBuckets = new Map(); function clientIp(req) { // X-Forwarded-For is spoofable unless a proxy overwrites it, so it is only // consulted when the operator opts in with LUMINARY_TRUST_PROXY=1. if (TRUST_PROXY) { const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim(); if (forwarded) return forwarded; } return String(req.socket?.remoteAddress ?? 'unknown'); } /** * Per-address cap. Behind a proxy without TRUST_PROXY every client shares the * proxy address, so the cap is higher to avoid turning noise into a lock-out; * the per-account limit is the real brute-force bound. */ const LOGIN_IP_LIMIT = TRUST_PROXY ? 50 : 500; function authFailures(key) { const bucket = authBuckets.get(key); if (!bucket || Date.now() - bucket.start >= AUTH_WINDOW_MS) return 0; return bucket.count; } function recordAuthFailure(key) { const now = Date.now(); const bucket = authBuckets.get(key); if (!bucket || now - bucket.start >= AUTH_WINDOW_MS) { authBuckets.set(key, { start: now, count: 1 }); } else { bucket.count += 1; } if (authBuckets.size > 10_000) { for (const [name, value] of authBuckets) { if (now - value.start >= AUTH_WINDOW_MS) authBuckets.delete(name); } } } function clearAuthFailures(key) { authBuckets.delete(key); } /** Coarse fixed-window limiter for public gallery writes. */ const galleryBuckets = new Map(); function allowGalleryWrite(req, token) { const key = `${clientIp(req)}:${token}`; const now = Date.now(); const bucket = galleryBuckets.get(key); if (!bucket || now - bucket.start >= 60_000) { galleryBuckets.set(key, { start: now, count: 1 }); if (galleryBuckets.size > 5_000) { for (const [name, value] of galleryBuckets) { if (now - value.start >= 60_000) galleryBuckets.delete(name); } } return true; } bucket.count += 1; return bucket.count <= 120; } const PHOTO_MIME_BY_EXT = { jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif', tif: 'image/tiff', tiff: 'image/tiff', }; const PHOTO_MIMES = new Set(Object.values(PHOTO_MIME_BY_EXT)); /** Only raster types the browser cannot turn into script are served inline. */ function normalizePhotoMime(value, name = '') { const mime = String(value ?? '').split(';')[0].trim().toLowerCase(); if (PHOTO_MIMES.has(mime)) return mime; const ext = String(name).split('.').pop()?.toLowerCase() ?? ''; return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream'; } import { gallerySettingsFor, saveGallerySettings, clearGallerySettings, noteGalleryDownload, } from './db.mjs'; /** Passwords are hashed per link with a random salt, so a database dump is not a key. */ function hashGalleryPassword(password, salt) { return crypto.scryptSync(password, salt, 32).toString('hex'); } /* Unlocked galleries live in memory: a restart asks for the password again. */ const galleryUnlocks = new Map(); const GALLERY_UNLOCK_MS = 12 * 3600 * 1000; const galleryCookie = (token) => `lumg_${token}`; /** * One check for every public gallery route: revoked link, expiry, password. * A locked gallery is a 401 so the page can show the password prompt instead * of claiming the shoot is gone. */ function galleryGate(req, token) { const shared = eventByShareToken(token); if (!shared) { return { ok: false, status: 404, message: 'This proofing gallery is no longer available' }; } const settings = gallerySettingsFor(token); if (settings.expiresAt && Date.now() > settings.expiresAt) { return { ok: false, status: 410, message: 'This proofing gallery has expired' }; } if (settings.passwordHash) { const cookie = parseCookies(req)[galleryCookie(token)]; const entry = galleryUnlocks.get(token); const valid = cookie && entry && entry.key === cookie && entry.expires > Date.now() ? true : false; if (!valid) { return { ok: false, status: 401, message: 'This gallery is password protected', locked: true, }; } } return { ok: true, shared, settings }; } /** Writes the refusal and returns true when the caller must stop. */ function galleryDenied(req, res, token) { const gate = galleryGate(req, token); if (gate.ok) return false; error(res, gate.status, gate.message); return true; } /** Refuses a download when the link turned downloads off or used its allowance. */ function galleryDownloadDenied(res, token, settings) { if (!settings.allowDownloads) { error(res, 403, 'Downloads are disabled for this gallery'); return true; } if (settings.downloadCap > 0 && settings.downloadCount >= settings.downloadCap) { error(res, 403, 'This gallery has reached its download limit'); return true; } return false; } function parseCookies(req) { const out = {}; for (const part of String(req.headers.cookie ?? '').split(';')) { const idx = part.indexOf('='); if (idx < 0) continue; try { out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim()); } catch { /* ignore malformed percent-encoding in a cookie */ } } return out; } function sessionCookie(req, token, maxAge) { const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : ''; return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`; } /** * LUMINARY_LOCAL=1 (the Windows desktop bundle): one admin account, no signup, * no sign-in, and an unauthenticated request is the local owner. The password * is random and never shown, so the account cannot be signed into over a * network; the launcher also binds loopback only. */ let localOwner = null; async function prepareLocalOwner() { if (!LOCAL_MODE) return; const existing = users.byEmail(LOCAL_EMAIL); if (existing) { localOwner = publicUser(existing); return; } const id = crypto.randomUUID(); users.create({ id, email: LOCAL_EMAIL, name: 'Local', passHash: await hashPassword(crypto.randomBytes(32).toString('hex')), role: 'admin', }); localOwner = publicUser(users.byId(id)); } function currentUser(req) { const cookieToken = parseCookies(req)[COOKIE]; if (cookieToken) { const row = sessions.find(cookieToken); if (row && Number(row.expires_at) > Date.now()) { const user = users.byId(row.user_id); if (user && !user.disabled) return publicUser(user); } } const authenticated = authenticate(req); if (authenticated) return authenticated; // A personal, loopback-only install has one owner: no credentials needed. return LOCAL_MODE ? localOwner : null; } function requireAdmin(req, res) { const user = currentUser(req); if (!user) { error(res, 401, 'Not signed in'); return null; } if (user.role !== 'admin') { error(res, 403, 'Administrator access is required'); return null; } return user; } /** * A null owner means the row does not exist yet (new records are allowed). * An empty owner is a legacy row from before workspaces; only an admin may * touch it. Everyone else may only reach their own rows. */ function ownedBy(owner, user) { if (owner === null || owner === undefined) return true; return owner === user.id || (owner === '' && user.role === 'admin'); } function adminUser(row) { return { id: row.id, email: row.email, name: row.name ?? '', role: row.role ?? 'member', disabled: Boolean(row.disabled), createdAt: row.created_at ?? null, }; } function inviteStatus(row, now = Date.now()) { if (!row) return 'missing'; if (row.revoked_at) return 'revoked'; if (row.accepted_at) return 'accepted'; if (Number(row.expires_at) <= now) return 'expired'; return 'pending'; } function adminInvite(row) { return { token: row.token, email: row.email ?? '', role: row.role ?? 'member', status: inviteStatus(row), createdAt: row.created_at ?? null, expiresAt: row.expires_at ?? null, acceptedAt: row.accepted_at ?? null, acceptedBy: row.accepted_by ?? null, revokedAt: row.revoked_at ?? null, }; } /** Accepts either a bare token or a copied /join/ link. */ function inviteTokenFrom(value) { if (typeof value !== 'string') return ''; const raw = value.trim(); if (!raw) return ''; const match = /\/join\/([A-Za-z0-9_-]+)\/?/.exec(raw); if (match) return match[1]; return /^[A-Za-z0-9_-]{16,64}$/.test(raw) ? raw : ''; } function readBody(req, limit = MAX_UPLOAD) { return new Promise((resolve, reject) => { const chunks = []; let size = 0; let tooLarge = false; req.on('data', (chunk) => { if (tooLarge) return; size += chunk.length; if (size > limit) { tooLarge = true; chunks.length = 0; // Keep draining instead of destroying the socket so the 413 can flush. req.resume(); reject(new PayloadTooLarge(`Request exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`)); return; } chunks.push(chunk); }); req.on('end', () => resolve(Buffer.concat(chunks))); req.on('error', reject); }); } async function readJson(req, limit = 8 * 1024 * 1024) { const raw = await readBody(req, limit); if (!raw.length) return {}; try { return JSON.parse(raw.toString('utf8')); } catch { throw new Error('Request body is not valid JSON'); } } /** * Streams an upload straight to disk. Buffering the body would let one request * hold hundreds of megabytes of RAM. */ async function receiveUpload(req, target, limit) { const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`; let size = 0; try { await new Promise((resolve, reject) => { const out = fs.createWriteStream(temp, { flags: 'wx' }); let settled = false; const fail = (err) => { if (settled) return; settled = true; req.unpipe(out); out.destroy(); req.resume(); fs.rm(temp, { force: true }, () => reject(err)); }; req.on('data', (chunk) => { if (settled) return; size += chunk.length; if (size > limit) fail(new PayloadTooLarge('Upload exceeds the size limit')); }); req.on('error', fail); out.on('error', fail); out.on('finish', () => { if (settled) return; settled = true; resolve(); }); req.pipe(out); }); if (!size) { await fsp.rm(temp, { force: true }); return 0; } await fsp.rename(temp, target); return size; } catch (err) { await fsp.rm(temp, { force: true }).catch(() => undefined); throw err; } } function match(pathname, pattern) { const p = pattern.split('/'); const a = pathname.split('/'); if (p.length !== a.length) return null; const params = {}; for (let i = 0; i < p.length; i++) { if (p[i].startsWith(':')) { params[p[i].slice(1)] = decodeURIComponent(a[i]); } else if (p[i] !== a[i]) { return null; } } return params; } function sendBuffer(res, data, type, cache = 'private, max-age=3600') { res.writeHead(200, { 'Content-Type': type, 'Content-Length': data.length, 'Cache-Control': cache, 'X-Content-Type-Options': 'nosniff', }); res.end(data); } /** The bridge row and source id for a photo imported from the dashboard. */ function bridgeLinkForPhoto(photoId) { const photo = getPhoto(photoId); if (!photo?.eventId) return null; const bridge = bridgeForEvent(photo.eventId); if (!bridge) return null; const sourceId = photo.bridgeSource?.sourceId ?? photoId.replace(/^br-/, ''); return { photo, bridge, sourceId }; } async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) { if (!filePath) return error(res, 404, 'Not found'); try { const stat = await fsp.stat(filePath); res.writeHead(200, { 'Content-Type': type, 'Content-Length': stat.size, 'Cache-Control': cache, 'X-Content-Type-Options': 'nosniff', ...extraHeaders, }); if (req.method === 'HEAD') return res.end(); fs.createReadStream(filePath).pipe(res); } catch { error(res, 404, 'Not found'); } } function decodeDataUrl(value) { if (typeof value !== 'string') return null; const m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=\s]+)$/.exec(value); if (!m) return null; return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') }; } /** Health totals walk the filesystem, so cache them instead of scanning per hit. */ let healthCache = { at: 0, photos: 0, bytes: 0, root: '', custom: false }; function healthStats() { if (Date.now() - healthCache.at < 30_000) return healthCache; healthCache = { at: Date.now(), photos: countPhotos(), bytes: storageBytes(), root: storageRoot(), custom: isCustomRoot(), }; return healthCache; } const MAX_ARCHIVE_FILES = 400; const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; let archiveBuilding = false; /** Uploads accepted for an id that does not have a photo row yet. */ const recentUploads = new Map(); function pendingBytes(ownerId) { let total = 0; for (const upload of recentUploads.values()) { if (upload.pending && upload.ownerId === ownerId) total += upload.bytes; } return total; } /* --------------------------------------------------------------------- api */ import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs'; const routes = []; function route(method, pattern, handler) { routes.push({ method, pattern, handler }); } route('GET', '/api/health', async ({ req, res }) => { const raw = await rawSupport(); const user = currentUser(req); const stats = healthStats(); json(res, 200, { ok: true, app: 'luminary', version: VERSION, needsSetup: !LOCAL_MODE && users.count() === 0, registrationOpen: !LOCAL_MODE && (users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0), local: LOCAL_MODE, photos: stats.photos, bytes: stats.bytes, // The absolute data path is only for signed-in team members. ...(user ? { storage: { root: stats.root, custom: stats.custom } } : {}), raw, }); }); route('POST', '/api/auth/register', async ({ req, res }) => { if (LOCAL_MODE) { return error(res, 403, 'This is a single-user desktop install; accounts are not used'); } const body = await readJson(req, 64 * 1024); const email = normalizeEmail(body.email); const password = typeof body.password === 'string' ? body.password : ''; const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : ''; if (!validEmail(email)) return error(res, 400, 'Enter a valid email address'); if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password'); if (users.byEmail(email)) return error(res, 409, 'That email is already registered'); const first = users.count() === 0; const sharedCode = typeof body.invite === 'string' ? body.invite.trim() : ''; const token = inviteTokenFrom(body.inviteToken) || inviteTokenFrom(sharedCode); let inviteRow = token ? invites.byToken(token) : null; if (!first) { if (inviteRow) { const status = inviteStatus(inviteRow); if (status === 'accepted') return error(res, 409, 'This invite has already been used'); if (status === 'revoked') return error(res, 403, 'This invite link was turned off by an admin'); if (status === 'expired') return error(res, 403, 'This invite link has expired. Ask an admin for a new one'); if (inviteRow.email && normalizeEmail(inviteRow.email) !== email) { return error(res, 403, 'This invite was created for a different email address'); } } else if (sharedCode && INVITE && sharedCode === INVITE) { /* the long-lived shared code still works alongside personal links */ } else if (token) { return error(res, 403, 'This invite link is not valid'); } else if (!INVITE) { return error(res, 403, 'Registration is closed. Use the invite link an admin sent you.'); } else if (sharedCode !== INVITE) { return error(res, 403, 'Invite code is not correct'); } } const id = crypto.randomUUID(); users.create({ id, email, name: name || email.split('@')[0], passHash: await hashPassword(password), role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member', }); if (inviteRow && !invites.accept(token, id)) { users.remove(id); return error(res, 409, 'This invite has already been used'); } const session = createSession(id); json( res, 201, { token: session, user: publicUser(users.byId(id)) }, { 'Set-Cookie': sessionCookie(req, session, 30 * 24 * 3600) }, ); }); route('POST', '/api/auth/login', async ({ req, res }) => { // Desktop mode has no password; hand out the local session so a stale login // form or bookmark cannot strand the user on a sign-in screen. if (LOCAL_MODE && localOwner) { const token = createSession(localOwner.id); return json( res, 200, { token, user: localOwner }, { 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) }, ); } const ipKey = `login:ip:${clientIp(req)}`; if (authFailures(ipKey) >= LOGIN_IP_LIMIT) { return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' }); } const body = await readJson(req, 64 * 1024); const email = normalizeEmail(body.email); const password = typeof body.password === 'string' ? body.password : ''; const accountKey = `login:acct:${clientIp(req)}:${email}`; if (authFailures(accountKey) >= 8) { return error(res, 429, 'Too many sign-in attempts for this account. Try again later.', { 'Retry-After': '900', }); } const row = users.byEmail(email); if (!row) { // Spend the same scrypt work as a real account so response timing does not // reveal which addresses are registered. await spendPasswordCheck(password); recordAuthFailure(ipKey); recordAuthFailure(accountKey); return error(res, 401, 'Email or password is not correct'); } const valid = await verifyPassword(password, row.pass_hash); if (!valid) { recordAuthFailure(ipKey); recordAuthFailure(accountKey); return error(res, 401, 'Email or password is not correct'); } clearAuthFailures(accountKey); if (row.disabled) return error(res, 403, 'This account has been disabled by an administrator'); const token = createSession(row.id); json( res, 200, { token, user: publicUser(users.byId(row.id)) }, { 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) }, ); }); route('POST', '/api/auth/logout', async ({ req, res }) => { const token = parseCookies(req)[COOKIE]; if (token) sessions.destroy(token); json(res, 200, { ok: true }, { 'Set-Cookie': `${COOKIE}=; Path=/; HttpOnly; Max-Age=0` }); }); route('GET', '/api/auth/me', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { user }); }); /* Public invite lookup for /join/; reveals only what the page needs. */ route('GET', '/api/invites/:token', async ({ res, params }) => { const row = invites.byToken(params.token); if (!row) return error(res, 404, 'This invite link is not valid'); json(res, 200, { status: inviteStatus(row), email: row.email ?? '', role: row.role ?? 'member', expiresAt: row.expires_at ?? null, }); }); /* ------------------------------------------------------------------- admin */ route('GET', '/api/admin/overview', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const totalsByEvent = new Map(users.eventTotals().map((row) => [row.event_id, row])); const owners = new Map(users.list().map((row) => [row.id, row.email])); json(res, 200, { users: users.list().map(adminUser), events: listEvents() .map((event) => { const totals = totalsByEvent.get(event.id); const ownerId = eventOwner(event.id) ?? ''; return { id: event.id, name: event.name ?? 'Untitled event', createdAt: event.createdAt ?? null, photos: Number(totals?.n ?? 0), bytes: Number(totals?.bytes ?? 0), ownerId, ownerEmail: owners.get(ownerId) ?? '', }; }) .sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0)), invites: invites.all().map(adminInvite), totals: { users: users.count(), photos: countPhotos(), bytes: livePhotoBytes(), pendingInvites: invites.pendingCount(), }, storage: { root: storageRoot(), defaultRoot: defaultRoot(), custom: isCustomRoot(), diskBytes: storageBytes(), }, quotas: quotasForAdmin(), mail: mailStatus(), immich: immichAdminStatus(), }); }); route('POST', '/api/admin/users', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const body = await readJson(req, 64 * 1024); const email = normalizeEmail(body.email); const password = typeof body.password === 'string' ? body.password : ''; const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : ''; const role = body.role === 'admin' ? 'admin' : 'member'; if (!validEmail(email)) return error(res, 400, 'Enter a valid email address'); if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password'); if (users.byEmail(email)) return error(res, 409, 'That email is already registered'); const id = crypto.randomUUID(); users.create({ id, email, name: name || email.split('@')[0], passHash: await hashPassword(password), role, }); json(res, 201, { user: adminUser(users.byId(id)) }); }); route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => { const admin = requireAdmin(req, res); if (!admin) return; const target = users.byId(params.id); if (!target) return error(res, 404, 'No such account'); if (LOCAL_MODE && localOwner && target.id === localOwner.id) { return error(res, 403, 'The local account is managed by the desktop launcher'); } const body = await readJson(req, 64 * 1024); const patch = {}; if (typeof body.name === 'string') patch.name = body.name.trim().slice(0, 80); if (typeof body.password === 'string' && body.password) { if (body.password.length < 8) return error(res, 400, 'Use at least 8 characters for the password'); patch.passHash = await hashPassword(body.password); } if (typeof body.role === 'string') { if (body.role !== 'admin' && body.role !== 'member') { return error(res, 400, 'Role must be admin or member'); } if (params.id === admin.id && body.role !== 'admin') { return error(res, 400, 'You cannot remove your own administrator access'); } if (target.role === 'admin' && body.role !== 'admin' && users.activeAdmins() <= 1) { return error(res, 400, 'Keep at least one active administrator'); } patch.role = body.role; } if (typeof body.disabled === 'boolean') { if (params.id === admin.id && body.disabled) { return error(res, 400, 'You cannot disable your own account'); } if (target.role === 'admin' && body.disabled && users.activeAdmins() <= 1) { return error(res, 400, 'Keep at least one active administrator'); } patch.disabled = body.disabled; } const updated = users.update(params.id, patch); if (patch.disabled || patch.passHash) sessions.destroyForUser(params.id); json(res, 200, { user: adminUser(updated) }); }); route('POST', '/api/admin/invites', async ({ req, res }) => { const admin = requireAdmin(req, res); if (!admin) return; const body = await readJson(req, 64 * 1024); const email = normalizeEmail(body.email); if (email && !validEmail(email)) return error(res, 400, 'Enter a valid email address'); const role = body.role === 'admin' ? 'admin' : 'member'; const days = Math.min(30, Math.max(1, Number(body.days) || 7)); const token = crypto.randomBytes(24).toString('base64url'); invites.create({ token, email, role, createdBy: admin.id, expiresAt: Date.now() + days * 24 * 60 * 60 * 1000, }); json(res, 201, { invite: adminInvite(invites.byToken(token)) }); }); route('DELETE', '/api/admin/invites/:token', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; const row = invites.byToken(params.token); if (!row) return error(res, 404, 'No such invite'); if (row.accepted_at) return error(res, 400, 'That invite has already been used'); invites.revoke(params.token); json(res, 200, { ok: true }); }); route('DELETE', '/api/admin/users/:id', async ({ req, res, params }) => { const admin = requireAdmin(req, res); if (!admin) return; if (params.id === admin.id) return error(res, 400, 'You cannot delete your own account'); const target = users.byId(params.id); if (!target) return error(res, 404, 'No such account'); if (LOCAL_MODE && localOwner && target.id === localOwner.id) { return error(res, 403, 'The local account is managed by the desktop launcher'); } if (target.role === 'admin' && users.activeAdmins() <= 1) { return error(res, 400, 'Keep at least one active administrator'); } sessions.destroyForUser(params.id); users.remove(params.id); json(res, 200, { ok: true }); }); route('PUT', '/api/admin/events/:id', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; const existing = listEvents().find((event) => event.id === params.id); if (!existing) return error(res, 404, 'No such event'); const body = await readJson(req, 64 * 1024); const name = typeof body.name === 'string' ? body.name.trim().slice(0, 120) : ''; if (!name) return error(res, 400, 'Enter an event name'); const record = { ...existing, name }; saveEvent(record, typeof existing.order === 'number' ? existing.order : (existing.createdAt ?? Date.now())); json(res, 200, { event: record }); }); route('DELETE', '/api/admin/events/:id', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; if (!listEvents().some((event) => event.id === params.id)) return error(res, 404, 'No such event'); const ids = users.photoIdsByEvent(params.id); ids.forEach(removePhoto); // The denoise renders are not part of the catalog, so `removePhoto` cannot // know about them; without this they would outlive the event on the volume. ids.forEach(clearDenoised); await Promise.all(ids.map((id) => removeAsset(id))); removeEvent(params.id); json(res, 200, { ok: true, photos: ids.length }); }); route('GET', '/api/admin/catalog', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const backup = { // Stable file-format identifier so backups from before the rebrand still restore. kind: 'lumenroom-catalog', version: 1, generatedAt: Date.now(), events: listEvents(), photos: listPhotos(), kv: { customPresets: kv.get('customPresets') ?? [], metadataPresets: kv.get('metadataPresets') ?? [], smartCollections: kv.get('smartCollections') ?? [], exportRecipes: kv.get('exportRecipes') ?? [], }, }; json(res, 200, backup, { 'Content-Disposition': `attachment; filename="luminary-catalog-${new Date().toISOString().slice(0, 10)}.json"`, }); }); route('POST', '/api/admin/catalog', async ({ req, res }) => { const admin = requireAdmin(req, res); if (!admin) return; const body = await readJson(req, 128 * 1024 * 1024); if (body?.kind !== 'lumenroom-catalog' || !Array.isArray(body.events) || !Array.isArray(body.photos)) { return error(res, 400, 'This is not a Luminary catalog backup'); } const events = body.events.filter((event) => event && typeof event.id === 'string' && event.id); const photos = body.photos.filter((photo) => photo && typeof photo.id === 'string' && photo.id); for (const [index, event] of events.entries()) { saveEvent(event, typeof event.order === 'number' ? event.order : index, admin.id); } for (const photo of photos) { savePhoto(photo, Date.now(), admin.id); } const allowedKv = ['customPresets', 'metadataPresets', 'smartCollections', 'exportRecipes']; for (const key of allowedKv) { if (body.kv && typeof body.kv === 'object' && key in body.kv) kv.set(key, body.kv[key]); } json(res, 200, { ok: true, events: events.length, photos: photos.length }); }); route('GET', '/api/admin/storage', async ({ req, res }) => { if (!requireAdmin(req, res)) return; json(res, 200, { root: storageRoot(), defaultRoot: defaultRoot(), custom: isCustomRoot(), photos: countPhotos(), bytes: storageBytes(), }); }); route('PUT', '/api/admin/storage', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const body = await readJson(req, 64 * 1024); try { const result = await setStorageRoot(body.root); json(res, 200, { ...result, photos: countPhotos(), bytes: storageBytes() }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not use that folder'); } }); /* --------------------------------------------------------- preview rebuild */ let previewRebuild = null; /** Progress file, so a restart resumes a run instead of starting it over. */ function previewRebuildFile() { return path.join(storageRoot(), 'preview-rebuild.json'); } function savePreviewRebuild(state) { try { fs.writeFileSync(previewRebuildFile(), JSON.stringify(state)); } catch { /* Progress is a convenience; a read-only storage root must not stop a run. */ } } /** * Runs the job and mirrors its progress to disk after every photo. The proxy * rebuild takes hours on a full library, so losing it to a deploy means * starting from the first photo again. */ function beginPreviewRebuild(targets) { const job = startPreviewRebuild({ targets, regenerate: (photo) => regenerateRawPreview(photo.id, photo, photoOwner(photo.id) ?? ''), onProgress: (snapshot, pending) => savePreviewRebuild({ ...snapshot, pending: pending.map((photo) => photo.id) }), }); savePreviewRebuild({ ...job.snapshot(), pending: targets.map((photo) => photo.id) }); void job.finished.then(() => savePreviewRebuild({ ...job.snapshot(), pending: [] })); previewRebuild = job; return job; } /** Restarts a run that a restart interrupted, skipping finished photos. */ function resumePreviewRebuild() { let saved = null; try { saved = JSON.parse(fs.readFileSync(previewRebuildFile(), 'utf8')); } catch { return; } if (saved?.state !== 'running' || !Array.isArray(saved.pending) || saved.pending.length === 0) { return; } const byId = new Map(listPhotos().map((photo) => [photo.id, photo])); const targets = saved.pending.map((id) => byId.get(id)).filter(Boolean); if (targets.length === 0) return; console.log(` previews: resuming rebuild, ${targets.length} photo(s) left`); beginPreviewRebuild(targets); } function previewRebuildStatus() { return ( previewRebuild?.snapshot() ?? { state: 'idle', total: 0, done: 0, failed: 0, sidecars: 0, startedAt: null, finishedAt: null, errors: [], } ); } route('GET', '/api/admin/previews/rebuild', async ({ req, res }) => { if (!requireAdmin(req, res)) return; json(res, 200, { rebuild: previewRebuildStatus() }); }); /** * Regenerate every raw proxy from its original, which is what a library * imported by an older pipeline needs after the decode changes. The loop is CPU * bound and can run for an hour, so the request only starts it and the panel * polls the status route. */ route('POST', '/api/admin/previews/rebuild', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const current = previewRebuildStatus(); if (current.state === 'running') return json(res, 202, { rebuild: current }); const targets = previewRebuildTargets(listPhotos()); const rebuild = beginPreviewRebuild(targets); json(res, 202, { rebuild: rebuild.snapshot() }); }); route('GET', '/api/quota', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, quotaState(user.id)); }); route('PATCH', '/api/admin/quotas/:id', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; const body = await readJson(req, 64 * 1024); try { const bytes = body.bytes ?? Number(body.gigabytes) * 1024 ** 3; json(res, 200, { quota: setUserQuota(params.id, bytes) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not change the quota'); } }); route('POST', '/api/admin/quotas/:id/prune', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; try { const result = await schedulePrune(params.id); json(res, 200, result); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not schedule the prune'); } }); route('DELETE', '/api/admin/quotas/:id/prune', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; try { json(res, 200, { quota: cancelPrune(params.id) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not cancel the prune'); } }); route('POST', '/api/admin/quotas/:id/warn', async ({ req, res, params }) => { if (!requireAdmin(req, res)) return; try { json(res, 200, { quota: await warnUser(params.id) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not send the warning'); } }); route('GET', '/api/admin/mail', async ({ req, res }) => { if (!requireAdmin(req, res)) return; json(res, 200, { mail: mailStatus() }); }); route('PUT', '/api/admin/mail', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const body = await readJson(req, 64 * 1024); try { json(res, 200, { mail: saveMailSettings(body) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not save email settings'); } }); route('POST', '/api/admin/mail/test', async ({ req, res }) => { const admin = requireAdmin(req, res); if (!admin) return; const body = await readJson(req, 64 * 1024); const to = typeof body.to === 'string' && body.to.trim() ? body.to.trim() : admin.email; try { await sendTestMail(to); json(res, 200, { ok: true, to }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not send the test email'); } }); route('GET', '/api/admin/immich', async ({ req, res }) => { if (!requireAdmin(req, res)) return; json(res, 200, { immich: immichAdminStatus() }); }); route('PUT', '/api/admin/immich', async ({ req, res }) => { if (!requireAdmin(req, res)) return; const body = await readJson(req, 16 * 1024); try { json(res, 200, { immich: saveImmichAdminSettings(body) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection'); } }); route('POST', '/api/admin/immich/test', async ({ req, res }) => { if (!requireAdmin(req, res)) return; try { json(res, 200, await immichAdminPing()); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); } }); route('DELETE', '/api/admin/immich', async ({ req, res }) => { if (!requireAdmin(req, res)) return; json(res, 200, { immich: disconnectImmichAdmin() }); }); /* ------------------------------------------------------------------ immich */ route('GET', '/api/immich', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { immich: immichStatusFor(user.id) }); }); route('PUT', '/api/immich', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const body = await readJson(req, 16 * 1024); try { json(res, 200, { immich: saveImmichUserSettings(user.id, body) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection'); } }); route('DELETE', '/api/immich', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { immich: disconnectImmich(user.id) }); }); route('POST', '/api/immich/test', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); try { json(res, 200, await immichPing(user.id)); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); } }); /** Albums are listed for any signed-in user; the API key still stays server-side. */ route('GET', '/api/immich/albums', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!immichConfigured(user.id)) return error(res, 503, 'Immich is not configured yet'); try { const links = new Map(immichLinksForOwner(user.id).map((link) => [link.albumId, link])); const albums = await listImmichAlbums(user.id); json(res, 200, { albums: albums.map((album) => ({ ...album, eventId: links.get(album.id)?.eventId ?? null, lastSyncAt: links.get(album.id)?.lastSyncAt ?? null, kind: links.get(album.id)?.kind ?? 'import', })), }); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); } }); route('POST', '/api/immich/albums', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const body = await readJson(req, 16 * 1024); if (typeof body.eventId !== 'string' || !body.eventId) { return error(res, 400, 'Choose the event for the gallery'); } if (!ownedBy(eventOwner(body.eventId), user)) return error(res, 404, 'No such event'); try { json(res, 201, await createImmichAlbumForEvent({ ownerId: user.id, eventId: body.eventId, name: body.name, })); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not create the Immich gallery'); } }); route('POST', '/api/immich/albums/:id/import', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); try { json(res, 202, { job: startImmichImport({ albumId: params.id, ownerId: user.id }) }); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not start the import'); } }); route('GET', '/api/immich/jobs/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const job = immichJobFor(params.id, user); if (!job) return error(res, 404, 'Import job not found'); json(res, 200, { job }); }); route('POST', '/api/immich/photos/:id/metadata', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); const body = await readJson(req, 64 * 1024); const rating = Math.max(0, Math.min(5, Math.trunc(Number(body.rating) || 0))); const flag = body.flag === 'pick' || body.flag === 'reject' ? body.flag : 'none'; const keywords = Array.isArray(body.keywords) ? body.keywords.filter((word) => typeof word === 'string').slice(0, 100) : []; try { json(res, 200, await pushImmichPhotoMetadata({ photoId: params.id, ownerId: user.id, local: { rating, flag, keywords }, })); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not sync Immich metadata'); } }); /** Photo ids still missing from an event's gallery, for a backfill run. */ route('GET', '/api/immich/events/:id/pending', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); try { json(res, 200, immichPendingPhotos({ eventId: params.id, ownerId: user.id })); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not read the Immich queue'); } }); /** * The manual push plan for an event: originals Immich has never seen plus the * edits that changed since the last push. Nothing uploads from this route. */ route('GET', '/api/immich/events/:id/queue', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); try { json(res, 200, immichEventQueue({ eventId: params.id, ownerId: user.id })); } catch (err) { return error(res, 400, err instanceof Error ? err.message : 'Could not plan the Immich push'); } }); route('POST', '/api/immich/photos/:id/publish', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); try { json(res, 200, await publishImmichOriginal({ photoId: params.id, ownerId: user.id })); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not publish the photo'); } }); route('POST', '/api/immich/photos/:id/push', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); const body = await readJson(req, 96 * 1024 * 1024); if (typeof body.jpeg !== 'string' || !body.jpeg) { return error(res, 400, 'A rendered JPEG is required'); } const jpeg = Buffer.from(body.jpeg, 'base64'); if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) { return error(res, 400, 'The edited file is not a JPEG image'); } try { json(res, 200, await pushImmichPhoto({ photoId: params.id, ownerId: user.id, jpeg })); } catch (err) { return error(res, 502, err instanceof Error ? err.message : 'Could not send the edit to Immich'); } }); route('GET', '/api/bridge/login', async ({ req, res, url }) => { if (!bridgeConfigured()) { return error(res, 503, 'The advanced editor bridge is not configured'); } const token = url.searchParams.get('token') || ''; const payload = verifyBridgeToken(token); if (!payload || payload.kind !== 'login') { return error(res, 401, 'This advanced-editor link is invalid or has expired'); } try { const service = await exchangeBridgeToken(token, payload.sid); const email = normalizeEmail(payload.email); if (!validEmail(email)) { return error(res, 400, 'The dashboard account has no usable email address'); } let row = users.byEmail(email); if (!row) { const id = crypto.randomUUID(); users.create({ id, email, name: payload.name || email.split('@')[0], passHash: await hashPassword(crypto.randomBytes(24).toString('hex')), role: 'member', }); row = users.byId(id); } purgeExpiredBridges(); const imported = await importBridgeEvent({ serviceToken: service.token, sessionId: payload.sid, ownerId: row.id, }); const sessionToken = createSession(row.id); res.writeHead(302, { Location: `/?bridge=${encodeURIComponent(imported.eventId)}`, 'Set-Cookie': sessionCookie(req, sessionToken, 30 * 24 * 3600), 'Cache-Control': 'no-store', }); res.end(); } catch (err) { return error( res, 502, err instanceof Error ? err.message : 'Could not open the advanced editor', ); } }); /** Client proofing picks, rolled up per photo for the owner's library. */ function ownerProofs(ownerId) { const proofs = new Map(); const ensure = (photoId, eventId) => { const entry = proofs.get(photoId) ?? { photoId, eventId, count: 0, clients: [], comments: 0, approved: 0, changes: 0, }; proofs.set(photoId, entry); return entry; }; for (const pick of picksByOwner(ownerId)) { if (!pick.picked) continue; const entry = ensure(pick.photoId, pick.eventId); entry.count += 1; entry.clients.push(pick.clientName || 'Client'); } for (const comment of commentsByOwner(ownerId)) { ensure(comment.photoId, comment.eventId).comments += 1; } for (const review of reviewsByOwner(ownerId)) { const entry = ensure(review.photoId, review.eventId); if (review.status === 'approved') entry.approved += 1; else if (review.status === 'changes') entry.changes += 1; if (review.clientName) entry.clients.push(review.clientName); } return [...proofs.values()].map((entry) => ({ ...entry, clients: [...new Set(entry.clients)], })); } route('GET', '/api/proofs', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { proofs: ownerProofs(user.id) }); }); route('GET', '/api/sync', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { user, events: listEvents(user.id), photos: listPhotos(user.id), presets: kv.get('presets') ?? [], proofs: ownerProofs(user.id), }); }); /* -------------------------------------------------------------- proofing */ /** Token-protected lookup: the photo must belong to the shared event. */ function galleryPhoto(token, photoId) { const shared = eventByShareToken(token); if (!shared) return null; const photo = getPhoto(photoId); if (!photo || photo.eventId !== shared.id || photo.deletedAt) return null; return { shared, photo }; } route('GET', '/api/events/:id/share', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const token = shareTokenFor(params.id); const feedback = token ? [ ...commentsForToken(token).map((comment) => ({ kind: 'comment', photoId: comment.photoId, clientName: comment.clientName, body: comment.body, createdAt: comment.createdAt, })), ...reviewsForToken(token) .filter((review) => review.status === 'approved' || review.status === 'changes') .map((review) => ({ kind: review.status === 'approved' ? 'approved' : 'changes', photoId: review.photoId, clientName: review.clientName, createdAt: review.updatedAt, })), ].sort((a, b) => b.createdAt - a.createdAt) : []; json(res, 200, { token, picks: token ? picksForToken(token) .filter((p) => p.picked) .map((p) => ({ photoId: p.photoId, clientName: p.clientName })) : [], feedback, settings: token ? (() => { const saved = gallerySettingsFor(token); return { passwordSet: Boolean(saved.passwordHash), expiresAt: saved.expiresAt, watermark: saved.watermark, allowDownloads: saved.allowDownloads, downloadCap: saved.downloadCap, downloadCount: saved.downloadCount, }; })() : null, }); }); /** Owner-side security settings for the proofing link. */ route('PUT', '/api/events/:id/share/settings', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const token = shareTokenFor(params.id); if (!token) return error(res, 404, 'This event has no proofing link yet'); const body = await readJson(req, 64 * 1024); const current = gallerySettingsFor(token); let passwordHash = current.passwordHash; let passwordSalt = current.passwordSalt; if (typeof body.password === 'string') { const password = body.password.trim(); if (password === '') { passwordHash = ''; passwordSalt = ''; } else if (password.length < 4) { return error(res, 400, 'Use at least 4 characters for the gallery password'); } else { passwordSalt = crypto.randomBytes(12).toString('hex'); passwordHash = hashGalleryPassword(password, passwordSalt); } } const saved = saveGallerySettings(token, { passwordHash, passwordSalt, expiresAt: typeof body.expiresAt === 'number' && body.expiresAt > 0 ? body.expiresAt : null, watermark: String(body.watermark ?? '').trim().slice(0, 80), allowDownloads: body.allowDownloads !== false, downloadCap: Number.isFinite(Number(body.downloadCap)) ? Math.max(0, Math.min(100000, Math.round(Number(body.downloadCap)))) : current.downloadCap, }); json(res, 200, { settings: { passwordSet: Boolean(saved.passwordHash), expiresAt: saved.expiresAt, watermark: saved.watermark, allowDownloads: saved.allowDownloads, downloadCap: saved.downloadCap, downloadCount: saved.downloadCount, }, }); }); /** Public unlock: exchanges the gallery password for a cookie scoped to the link. */ route('POST', '/api/galleries/:token/unlock', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many attempts. Try again shortly.', { 'Retry-After': '60' }); } const gate = galleryGate(req, params.token); if (!gate.ok && gate.status === 410) return error(res, 410, gate.message); if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message); const settings = gallerySettingsFor(params.token); if (!settings.passwordHash) return json(res, 200, { ok: true }); const body = await readJson(req, 16 * 1024); const password = String(body.password ?? ''); const attempt = Buffer.from(hashGalleryPassword(password, settings.passwordSalt), 'hex'); const expected = Buffer.from(settings.passwordHash, 'hex'); const ok = attempt.length === expected.length && crypto.timingSafeEqual(attempt, expected); if (!ok) return error(res, 403, 'That password does not open this gallery'); const key = crypto.randomBytes(24).toString('base64url'); galleryUnlocks.set(params.token, { key, expires: Date.now() + GALLERY_UNLOCK_MS }); res.setHeader( 'Set-Cookie', `${galleryCookie(params.token)}=${encodeURIComponent(key)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${GALLERY_UNLOCK_MS / 1000}`, ); json(res, 200, { ok: true }); }); /** Public: is this link locked or past its expiry? Used before the gallery loads. */ route('GET', '/api/galleries/:token/status', async ({ req, res, params }) => { const gate = galleryGate(req, params.token); if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message); const settings = gate.ok ? gate.settings : gallerySettingsFor(params.token); json(res, 200, { locked: !gate.ok, expiresAt: settings.expiresAt, allowDownloads: settings.allowDownloads, }); }); route('POST', '/api/events/:id/share', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); let token = shareTokenFor(params.id); if (!token) { token = crypto.randomBytes(18).toString('base64url'); setShareToken(params.id, token); } json(res, 200, { token }); }); route('DELETE', '/api/events/:id/share', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const token = shareTokenFor(params.id); setShareToken(params.id, null); if (token) { clearGallerySettings(token); galleryUnlocks.delete(token); } json(res, 200, { ok: true }); }); /** Public gallery payload: no session, only the shared event and its photos. */ route('GET', '/api/galleries/:token', async ({ req, res, params, url }) => { const gate = galleryGate(req, params.token); if (!gate.ok) return error(res, gate.status, gate.message); const shared = gate.shared; const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64); const picks = picksForToken(params.token).filter((p) => p.picked); const counts = new Map(); const mine = new Set(); for (const pick of picks) { counts.set(pick.photoId, (counts.get(pick.photoId) ?? 0) + 1); if (clientId && pick.clientId === clientId) mine.add(pick.photoId); } const comments = new Map(); for (const comment of commentsForToken(params.token)) { const list = comments.get(comment.photoId) ?? []; list.push({ id: comment.id, clientName: comment.clientName || 'Client', body: comment.body, createdAt: comment.createdAt, }); comments.set(comment.photoId, list); } const reviews = new Map(); for (const review of reviewsForToken(params.token)) { if (clientId && review.clientId !== clientId) continue; reviews.set(review.photoId, review.status); } const photos = listPhotos(shared.ownerId) .filter((photo) => photo.eventId === shared.id && !photo.deletedAt) .sort( (a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a.takenAt ?? a.addedAt) - (b.takenAt ?? b.addedAt), ) .map((photo) => ({ id: photo.id, name: photo.name, width: photo.width, height: photo.height, takenAt: photo.takenAt ?? null, thumbUrl: `/api/galleries/${params.token}/photos/${photo.id}/thumb${photo.proofAt ? `?proof=${photo.proofAt}` : ''}`, previewUrl: `/api/galleries/${params.token}/photos/${photo.id}/preview${photo.proofAt ? `?proof=${photo.proofAt}` : ''}`, pickCount: counts.get(photo.id) ?? 0, mine: mine.has(photo.id), comments: comments.get(photo.id) ?? [], reviewStatus: reviews.get(photo.id) ?? null, })); json(res, 200, { event: { name: shared.event.name ?? 'Proofing gallery', date: shared.event.date ?? shared.event.createdAt ?? null, notes: shared.event.notes ?? '', }, photographer: 'Luminary', photos, picks: { total: picks.length, clients: new Set(picks.map((p) => p.clientId)).size }, downloads: { allowed: gate.settings.allowDownloads, remaining: gate.settings.downloadCap > 0 ? Math.max(0, gate.settings.downloadCap - gate.settings.downloadCount) : null, }, watermark: gate.settings.watermark, }); }); route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => { if (galleryDenied(req, res, params.token)) return; if (!galleryPhoto(params.token, params.id)) return error(res, 404, 'Not found'); const file = findProofThumb(params.id) ?? (await findThumb(params.id)); return sendFile(req, res, file, 'image/jpeg', 'private, max-age=3600'); }); route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, params }) => { if (galleryDenied(req, res, params.token)) return; const hit = galleryPhoto(params.token, params.id); 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 mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); return sendFile( req, res, file, mime, 'private, max-age=3600', mime === 'application/octet-stream' ? { 'Content-Disposition': 'attachment' } : {}, ); }); /** Client download of the edited proof, named like the delivered file. */ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => { const gate = galleryGate(req, params.token); if (!gate.ok) return error(res, gate.status, gate.message); if (galleryDownloadDenied(res, params.token, gate.settings)) return; const hit = galleryPhoto(params.token, params.id); if (!hit) return error(res, 404, 'Not found'); const proof = findProof(params.id); const file = proof ?? findPreview(params.id) ?? findOriginal(params.id); 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); noteGalleryDownload(params.token); return sendFile(req, res, file, mime, 'private, max-age=3600', { 'Content-Disposition': `attachment; filename="${safe}"`, }); }); /** Download the client's favourites as one ZIP. */ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, url }) => { const gate = galleryGate(req, params.token); if (!gate.ok) return error(res, gate.status, gate.message); if (galleryDownloadDenied(res, params.token, gate.settings)) return; const shared = gate.shared; const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64); const picks = picksForToken(params.token).filter( (pick) => pick.picked && (!clientId || pick.clientId === clientId), ); if (!picks.length) return error(res, 404, 'There are no favourites to download yet'); if (archiveBuilding) { return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', { 'Retry-After': '30', }); } archiveBuilding = true; try { const entries = []; const seen = new Set(); let totalBytes = 0; for (const pick of picks) { if (seen.has(pick.photoId)) continue; seen.add(pick.photoId); const photo = getPhoto(pick.photoId); if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue; const proof = findProof(photo.id); const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id); if (!file) continue; if (entries.length >= MAX_ARCHIVE_FILES) { return error(res, 413, 'Too many favourites for one archive. Download in smaller batches.'); } try { const stat = await fsp.stat(file); if (totalBytes + stat.size > MAX_ARCHIVE_BYTES) { return error( res, 413, 'This selection is too large for one archive. Download in smaller batches.', ); } const data = await fsp.readFile(file); totalBytes += data.length; const originalName = String(photo.name || 'photo.jpg'); const name = proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName; entries.push({ name, data }); } catch { /* skip an unreadable file rather than losing the whole archive */ } } if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet'); const archive = createZip(entries); noteGalleryDownload(params.token); const eventName = String(shared.event.name || 'proofing') .replace(/[^a-z0-9._ -]+/gi, '-') .trim() || 'proofing'; res.writeHead(200, { 'Content-Type': 'application/zip', 'Content-Length': archive.length, 'Cache-Control': 'no-store', 'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`, }); res.end(archive); } finally { archiveBuilding = false; } }); /* ---------------------------------------------------------------- tether */ /** * Tethering is a drop folder, not a camera driver: the owner (or a synced * tethering app) writes frames into one directory per event, and the open * editor pulls and imports them. Files are removed from the folder only after * the client confirms the import, so a dropped connection never loses a frame. */ const TETHER_EXT = new Set([ 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'webp', 'dng', 'cr2', 'cr3', 'nef', 'arw', 'orf', 'rw2', 'raf', 'pef', 'srw', ]); function tetherFolder(eventId) { const safe = String(eventId).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'event'; return { safe, dir: path.join(DATA_DIR, 'tether', safe) }; } /** A bare file name in the drop folder; anything with a path is refused. */ function tetherFileName(raw) { const name = path.basename(String(raw ?? '')); if (!name || name !== String(raw ?? '')) return null; const ext = name.split('.').pop()?.toLowerCase() ?? ''; return TETHER_EXT.has(ext) ? name : null; } route('GET', '/api/events/:id/tether', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const folder = tetherFolder(params.id); await fsp.mkdir(folder.dir, { recursive: true }); const names = await fsp.readdir(folder.dir).catch(() => []); const files = []; for (const name of names) { if (!tetherFileName(name)) continue; const stat = await fsp.stat(path.join(folder.dir, name)).catch(() => null); if (!stat?.isFile()) continue; files.push({ name, size: stat.size, mtime: stat.mtimeMs }); } files.sort((a, b) => a.mtime - b.mtime); json(res, 200, { folder: folder.dir, files }); }); route('GET', '/api/events/:id/tether/file', async ({ req, res, params, url }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const name = tetherFileName(url.searchParams.get('name')); if (!name) return error(res, 400, 'No such file'); const file = path.join(tetherFolder(params.id).dir, name); const stat = await fsp.stat(file).catch(() => null); if (!stat?.isFile()) return error(res, 404, 'No such file'); const mime = normalizePhotoMime('', name); return sendFile(req, res, file, mime, 'no-store', { 'Content-Disposition': `attachment; filename="${name}"`, }); }); route('DELETE', '/api/events/:id/tether/file', async ({ req, res, params, url }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const name = tetherFileName(url.searchParams.get('name')); if (!name) return error(res, 400, 'No such file'); await fsp.unlink(path.join(tetherFolder(params.id).dir, name)).catch(() => undefined); json(res, 200, { ok: true }); }); route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 32 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); const clientId = String(body.clientId ?? '').trim().slice(0, 64); const text = String(body.body ?? '').trim().slice(0, 1200); if (!clientId || !text) return error(res, 400, 'A comment needs a client and text'); const clientName = String(body.clientName ?? '').trim().slice(0, 60); const comment = { id: crypto.randomUUID(), token: params.token, photoId: hit.photo.id, clientId, clientName, body: text, }; addGalleryComment(comment); json(res, 200, { comment: { ...comment, createdAt: Date.now() } }); }); route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 16 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); const clientId = String(body.clientId ?? '').trim().slice(0, 64); const status = body.status === 'approved' || body.status === 'changes' ? body.status : 'none'; if (!clientId) return error(res, 400, 'Missing client id'); setGalleryReview({ token: params.token, photoId: hit.photo.id, clientId, clientName: String(body.clientName ?? '').trim().slice(0, 60), status, }); json(res, 200, { ok: true, status }); }); route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => { if (!allowGalleryWrite(req, params.token)) { return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); } if (galleryDenied(req, res, params.token)) return; const body = await readJson(req, 32 * 1024); const hit = galleryPhoto(params.token, String(body.photoId ?? '')); if (!hit) return error(res, 404, 'No such photo'); const clientId = String(body.clientId ?? '').trim().slice(0, 64); if (!clientId) return error(res, 400, 'Missing client id'); const clientName = String(body.clientName ?? '').trim().slice(0, 60); galleryPick(params.token, hit.photo.id, clientId, clientName, body.picked !== false); json(res, 200, { ok: true }); }); route('PUT', '/api/events/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); const body = await readJson(req, 256 * 1024); const record = { ...body, id: params.id }; saveEvent( record, typeof body.order === 'number' ? body.order : Number(body.createdAt ?? Date.now()), user.id, ); json(res, 200, { event: record }); }); route('DELETE', '/api/events/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); removeEvent(params.id); json(res, 200, { ok: true }); }); route('PUT', '/api/presets', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const body = await readJson(req, 512 * 1024); kv.set('presets', Array.isArray(body.presets) ? body.presets : []); json(res, 200, { ok: true }); }); /* ---------------------------------------------------- team lens calibrations */ route('GET', '/api/lens-profiles', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); json(res, 200, { profiles: lensProfiles.list() }); }); route('POST', '/api/lens-profiles', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const body = await readJson(req, 256 * 1024); const parsed = parseCalibration(body); if (parsed.error) return error(res, 400, parsed.error); const now = Date.now(); const profile = lensProfiles.save({ ...parsed.value, id: crypto.randomUUID(), createdBy: user.id, createdAt: now, updatedAt: now, }); json(res, 201, { profile }); }); /** Any member can read the team's calibrations; the author or an admin edits them. */ function editableProfile(id, user) { const profile = lensProfiles.get(id); if (!profile) return { status: 404, message: 'No such lens profile' }; if (profile.createdBy !== user.id && user.role !== 'admin') { return { status: 403, message: 'Only the member who added this profile or an admin can change it' }; } return { profile }; } route('PUT', '/api/lens-profiles/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const found = editableProfile(params.id, user); if (found.status) return error(res, found.status, found.message); const body = await readJson(req, 256 * 1024); const parsed = parseCalibration(body); if (parsed.error) return error(res, 400, parsed.error); const profile = lensProfiles.save({ ...parsed.value, id: found.profile.id, createdBy: found.profile.createdBy, createdAt: found.profile.createdAt, updatedAt: Date.now(), }); json(res, 200, { profile }); }); route('DELETE', '/api/lens-profiles/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const found = editableProfile(params.id, user); if (found.status) return error(res, found.status, found.message); lensProfiles.remove(found.profile.id); json(res, 200, { ok: true }); }); /** * Store the original file. Raw files are demosaiced here so every browser can * edit them; ordinary images are kept byte-for-byte and previewed client-side. */ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const owner = photoOwner(params.id); if (owner !== null && !ownedBy(owner, user)) return error(res, 404, 'No such photo'); const url = new URL(req.url ?? '/', 'http://localhost'); const name = url.searchParams.get('name') || 'upload'; const drop = url.searchParams.get('drop') === '1'; const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name); const ext = (name.split('.').pop() || 'bin').toLowerCase(); // TIFF is not a raw container, but browsers cannot decode it either. It takes // the same upload path and is turned into a JPEG proxy here with sharp. const still = isStillName(name); const raw = isRawName(name) || drop || still; // 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))); if (limit < 1) { return error(res, 413, '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 ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` : 'This upload does not fit in the remaining storage quota', ); } // Reserve the announced size synchronously: otherwise two parallel uploads // could each pass the same remaining-quota check before either writes. if (owner === null) { recentUploads.set(params.id, { ownerId: user.id, bytes: Number.isFinite(announced) && announced > 0 ? announced : limit, at: Date.now(), pending: true, }); } 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 { size = await receiveUpload(req, target, limit); } catch (err) { if (owner === null) recentUploads.delete(params.id); if (err instanceof PayloadTooLarge) { return error( res, 413, owner ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` : 'This upload does not fit in the remaining storage quota', ); } throw err; } if (!size) { if (owner === null) recentUploads.delete(params.id); return error(res, 400, 'Empty upload'); } recentUploads.set(params.id, { ownerId: user.id, bytes: size, at: Date.now(), pending: owner === null, }); if (raw) { try { const data = await fsp.readFile(target); const decoded = still ? await decodeStill(data) : await decodeRaw(data); await writePreview(params.id, decoded.jpeg, decoded.ext); if (decoded.preview16) { await writePreview16(params.id, decoded.preview16.data); // The thumbnail may not exist yet; drop any camera-native tile so the // first grid view rebuilds it from the new pixels. await removeThumb16(params.id); } else { await removePreview16(params.id); await removeThumb16(params.id); } const info = await jpegInfo(decoded.jpeg); return json(res, 201, { raw: isRawName(name) || drop, serverDecoded: still, engine: decoded.engine, width: info?.width || decoded.width, height: info?.height || decoded.height, mime: 'image/jpeg', previewUrl: `/api/photos/${params.id}/preview`, thumbUrl: `/api/photos/${params.id}/thumb`, note: decoded.note ?? null, maxEdge: RAW_PREVIEW_EDGE, }); } catch (err) { recentUploads.delete(params.id); await removeAsset(params.id).catch(() => undefined); return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file'); } } return json(res, 201, { raw: false, mime, size }); }); /** * Re-decode one stored RAW and replace everything derived from it. Shared by the * single-photo route and the admin rebuild so the two cannot drift apart. * * The original is never touched; only the editable proxy, its thumbnail, the * 16-bit sidecar and the cached denoise renders are replaced, so existing edits * keep working on fresh pixels. */ async function regenerateRawPreview(id, photo, ownerId) { const original = findOriginal(id); if (!original) throw new Error('The RAW original is missing from storage'); const decoded = await decodeRaw(await fsp.readFile(original)); await writePreview(id, decoded.jpeg, decoded.ext); if (decoded.preview16) { await writePreview16(id, decoded.preview16.data); // The thumbnail may not exist yet; drop any camera-native tile so the grid // rebuilds it from the new pixels. await removeThumb16(id); } else { await removePreview16(id); await removeThumb16(id); } const thumb = await makeThumb(decoded.jpeg, 560); if (thumb) await writeThumb(id, thumb); // The old denoised renders were made from the previous proxy. clearDenoised(id); const info = await jpegInfo(decoded.jpeg); const width = info?.width || decoded.width || photo.width; const height = info?.height || decoded.height || photo.height; // Stamp the record so cached previews and thumbnails are fetched again. const previewVersion = Date.now(); // Pass the owner explicitly: savePhoto defaults to '' and would orphan the row. savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), ownerId); return { width, height, engine: decoded.engine, note: decoded.note ?? null, previewVersion, sidecar: Boolean(decoded.preview16), }; } route('POST', '/api/photos/:id/reprocess', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); const photo = getPhoto(params.id); if (!photo?.raw) return error(res, 400, 'Only RAW imports can be reprocessed'); const original = findOriginal(params.id); if (!original) return error(res, 404, 'The RAW original is missing from storage'); try { const result = await regenerateRawPreview(params.id, photo, user.id); json(res, 200, { ...result, previewUrl: `/api/photos/${params.id}/preview?v=${result.previewVersion}`, thumbUrl: `/api/photos/${params.id}/thumb?v=${result.previewVersion}`, }); } catch (err) { return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file'); } }); route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); const thumb = findProofThumb(params.id) ?? findThumb(params.id); if (thumb) return sendFile(req, res, thumb, 'image/jpeg'); const linked = bridgeLinkForPhoto(params.id); if (!linked) return error(res, 404, 'Not found'); const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'thumb'); if (!upstream.ok) return error(res, 404, 'Thumbnail unavailable'); const data = Buffer.from(await upstream.arrayBuffer()); await writeThumb(params.id, data); return sendBuffer(res, data, 'image/jpeg'); }); /** * Camera-native version of the grid thumbnail, built on first request from the * 16-bit sidecar and the JPEG thumbnail so the two have identical dimensions. * Without this the grid can only show the camera profile's effect in Develop. */ route('GET', '/api/photos/:id/thumb16', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); let file = findThumb16(params.id); if (!file) { const sidecar = findPreview16(params.id); const thumb = findThumb(params.id); if (sidecar && thumb) { const info = await jpegInfo(await fsp.readFile(thumb)); if (info?.width && info?.height) { const png = await cameraThumb16(await fsp.readFile(sidecar), info.width, info.height); if (png) file = await writeThumb16(params.id, png); } } } return sendFile(req, res, file, 'image/png'); }); /** * Store a rendered proof for an edited photo. The editable proxy and original * stay untouched; galleries read this copy so clients see the developed image. */ route('POST', '/api/photos/:id/proof', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); const body = await readJson(req, 16 * 1024 * 1024); if (typeof body.jpeg !== 'string' || !body.jpeg) return error(res, 400, 'A JPEG proof is required'); const jpeg = Buffer.from(body.jpeg, 'base64'); if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) { return error(res, 400, 'The proof is not a JPEG image'); } await writeProof(params.id, jpeg); const thumb = await makeThumb(jpeg, 560); if (thumb) await writeProofThumb(params.id, thumb); const existing = getPhoto(params.id); const proofAt = Date.now(); if (existing) { savePhoto( { ...existing, proofAt, thumbUrl: `/api/photos/${params.id}/thumb?proof=${proofAt}`, }, proofAt, user.id, ); } const info = await jpegInfo(jpeg); json(res, 200, { ok: true, proofAt, width: info?.width ?? null, height: info?.height ?? null, thumbUrl: `/api/photos/${params.id}/thumb?proof=${proofAt}`, }); }); route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); const preview = findPreview(params.id); if (preview) return sendFile(req, res, preview, preview.endsWith('.png') ? 'image/png' : 'image/jpeg'); const linked = bridgeLinkForPhoto(params.id); if (linked) { const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'proxy'); if (!upstream.ok) return error(res, 404, 'Preview unavailable'); const data = Buffer.from(await upstream.arrayBuffer()); await writePreview(params.id, data); const info = await jpegInfo(data); if (info?.width && info?.height) { savePhoto({ ...linked.photo, width: info.width, height: info.height, mime: 'image/jpeg', size: data.length }); } return sendBuffer(res, data, 'image/jpeg'); } return sendFile(req, res, findOriginal(params.id), 'application/octet-stream'); }); /** * The 16-bit half of a raw proxy. The editor inflates it and uploads it as a * half-float source texture so a heavy grade keeps its precision; the JPEG at * `/preview` stays the fallback when this file is absent or too large to fetch. */ route('GET', '/api/photos/:id/preview16', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); return sendFile(req, res, findPreview16(params.id), 'image/png'); }); route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); // Denoise the proxy the editor actually shows, not the raw: the result has to // line up pixel for pixel with the canvas and with the client's export path. // The Amount slider is the client's: the render is always full strength. const source = findPreview(params.id) ?? findOriginal(params.id); if (!source) return error(res, 404, 'Nothing to denoise'); const job = startDenoise({ photoId: params.id, sourcePath: source }); return json(res, 202, { jobId: job.id, state: job.state }); }); route('GET', '/api/denoise/jobs/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const job = getDenoiseJob(params.id); if (!job) return error(res, 404, 'Job not found'); if (!ownedBy(photoOwner(job.photoId), user)) return error(res, 404, 'Not found'); return json(res, 200, { id: job.id, key: job.key, state: job.state, ms: job.ms ?? null, error: job.error ?? null, url: job.url ?? null, stats: job.stats ?? null, }); }); route('GET', '/api/photos/:id/denoised', async ({ req, res, params, url }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); const file = findDenoisedFor(params.id, url.searchParams.get('v') ?? undefined); if (!file) return error(res, 404, 'No denoised version'); return sendFile(req, res, file, 'image/jpeg', 'private, max-age=31536000, immutable'); }); /** Drop the rendered denoise files for a photo, e.g. when the edit is cleared. */ route('DELETE', '/api/photos/:id/denoised', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); clearDenoised(params.id); json(res, 200, { ok: true }); }); route('GET', '/api/photos/:id/original', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); const original = findOriginal(params.id); if (original) return sendFile(req, res, original, 'application/octet-stream', 'private, max-age=3600'); const linked = bridgeLinkForPhoto(params.id); if (!linked) return error(res, 404, 'Not found'); const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original'); if (!upstream.ok) return error(res, 404, 'Original unavailable'); const data = Buffer.from(await upstream.arrayBuffer()); return sendBuffer(res, data, normalizePhotoMime(linked.photo.mime, linked.photo.name)); }); route('POST', '/api/bridge/export', async ({ req, res }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); const body = await readJson(req, 64 * 1024 * 1024); if (typeof body.photoId !== 'string' || typeof body.jpeg !== 'string') { return error(res, 400, 'A photo id and a rendered JPEG are required'); } const linked = bridgeLinkForPhoto(body.photoId); if (!linked) return error(res, 404, 'This photo is not part of an advanced edit'); if (!ownedBy(photoOwner(body.photoId), user)) return error(res, 404, 'This photo is not part of an advanced edit'); const result = await forwardBridgeRender(linked.bridge, linked.sourceId, { jpeg: body.jpeg, edits: body.edits ?? {}, }); if (result.status >= 400) { return error(res, result.status, result.body?.error || 'The edit could not be saved to the event'); } return json(res, 200, result.body ?? { ok: true }); }); route('PUT', '/api/photos/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); const body = await readJson(req); if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL'); const record = { ...body, id: params.id }; // 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); if (upload && upload.ownerId === user.id) { record.size = upload.bytes; recentUploads.delete(params.id); } record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name); const thumb = decodeDataUrl(record.thumb); if (thumb) { await writeThumb(params.id, thumb.data); delete record.thumb; } const versionQuery = typeof record.previewVersion === 'number' && Number.isFinite(record.previewVersion) ? `?v=${record.previewVersion}` : ''; if (record.raw) { record.previewUrl = `/api/photos/${params.id}/preview${versionQuery}`; const preview = findPreview(params.id); if (!preview) { const original = findOriginal(params.id); if (original) { const proxy = await toJpegProxy(await fsp.readFile(original)); if (proxy) await writePreview(params.id, proxy.data, proxy.ext); } } } record.thumbUrl = record.proofAt ? `/api/photos/${params.id}/thumb?proof=${record.proofAt}` : `/api/photos/${params.id}/thumb${versionQuery}`; savePhoto(record, Date.now(), user.id); json(res, 200, { photo: record }); }); route('DELETE', '/api/photos/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); recentUploads.delete(params.id); removePhoto(params.id); clearDenoised(params.id); await removeAsset(params.id); json(res, 200, { ok: true }); }); /* ---------------------------------------------------------------- static ui */ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.pdf': 'application/pdf', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.map': 'application/json; charset=utf-8', // Served for any WebAssembly asset that ends up in the build output. '.wasm': 'application/wasm', }; async function serveStatic(req, res, url) { let pathname; try { pathname = decodeURIComponent(url.pathname); } catch { return error(res, 400, 'Bad request'); } if (pathname.includes('\0')) return error(res, 400, 'Bad request'); // path.relative, not startsWith: a sibling such as /srv/dist-private shares // the dist prefix and would otherwise pass a bare prefix check. const candidate = path.resolve(path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname)); const relative = path.relative(DIST_DIR, candidate); if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) { try { const stat = await fsp.stat(candidate); 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', ); } } catch { /* fall through to the SPA entry */ } } const index = path.join(DIST_DIR, 'index.html'); if (!fs.existsSync(index)) { return error( res, 503, 'The web build is missing. Run "npm run build" (or use "npm run dev" with the Vite dev server).', ); } return sendFile(req, res, index, MIME['.html'], 'no-cache'); } /* ------------------------------------------------------------------ server */ const server = http.createServer(async (req, res) => { const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`); res.setHeader('Content-Security-Policy', CSP); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('Referrer-Policy', 'same-origin'); res.setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); if (String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() === 'https') { res.setHeader('Strict-Transport-Security', 'max-age=15552000'); } try { if (url.pathname.startsWith('/api/')) { for (const r of routes) { if (r.method !== req.method) continue; const params = match(url.pathname, r.pattern); if (!params) continue; return await r.handler({ req, res, params, url }); } return error(res, 404, `No route for ${req.method} ${url.pathname}`); } return await serveStatic(req, res, url); } catch (err) { const message = err instanceof Error ? err.message : 'Unexpected error'; console.error(`[luminary] ${req.method} ${url.pathname} โ†’ ${message}`); if (!res.headersSent) { if (err instanceof PayloadTooLarge) return error(res, 413, message); // Do not leak internals from an unexpected failure. return error(res, 500, 'Unexpected server error'); } res.end(); } }); /** Drop uploads that were streamed to disk but never became a photo record. */ async function sweepStaleUploads() { const cutoff = Date.now() - 60 * 60 * 1000; for (const [id, upload] of recentUploads) { if (upload.at > cutoff) continue; recentUploads.delete(id); if (!getPhoto(id)) await removeAsset(id).catch(() => undefined); } } /** Remove pre-upgrade orphans: originals with no catalog row, older than a day. */ async function sweepOrphanOriginals() { const dir = path.join(storageRoot(), 'originals'); const names = await fsp.readdir(dir).catch(() => []); const cutoff = Date.now() - 24 * 60 * 60 * 1000; for (const name of names) { const id = name.replace(/\.[^.]+$/, ''); if (/^[A-Za-z0-9_-]{1,80}$/.test(id) && getPhoto(id)) continue; const file = path.join(dir, name); const stat = await fsp.stat(file).catch(() => null); if (stat && stat.mtimeMs < cutoff) await fsp.rm(file, { force: true }).catch(() => undefined); } } await prepareLocalOwner(); if (LOCAL_MODE && !['127.0.0.1', 'localhost', '::1'].includes(HOST)) { console.warn( ` local: LUMINARY_LOCAL=1 with HOST=${HOST}; every client is treated as the local admin`, ); } server.listen(PORT, HOST, async () => { startQuotaWorker(); const raw = await rawSupport(); console.log(`Luminary server listening on http://localhost:${PORT}`); console.log(` data: ${DATA_DIR}`); console.log( ` raw: libraw ${raw.libraw ? `ready (${raw.workers} parallel worker${raw.workers === 1 ? '' : 's'})` : 'missing'} ยท jpeg ${raw.sharp ? 'sharp' : 'png fallback'}`, ); if (LOCAL_MODE) { console.log(` local: ${LOCAL_EMAIL} โ€” sign-in disabled (LUMINARY_LOCAL=1)`); } else { console.log(` users: ${users.count()} account(s)${users.count() === 0 ? ' โ€” first signup becomes admin' : ''}`); } if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)'); resumePreviewRebuild(); }); setInterval(() => { void sweepStaleUploads().catch((err) => console.error(`[luminary] upload sweep: ${err.message}`), ); }, 10 * 60 * 1000).unref?.(); void sweepOrphanOriginals().catch((err) => console.error(`[luminary] orphan sweep: ${err.message}`), ); for (const signal of ['SIGINT', 'SIGTERM']) { process.on(signal, () => { server.close(() => process.exit(0)); }); }