Files
glenloch-media/lumenroom/server/index.mjs
T
bhursey ebe0c77f7e
CI / build (push) Has been cancelled
feat(editor): finish the quick/advanced editor handoff
Reopen advanced edits from their saved recipe, seed or take over the quick
editor from them, refresh thumbnails after a save, and add an edited-only
download. Also fixes the Lumenroom library collapsing to slivers on large
shoots and documents deploying both containers on a new host.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 06:35:24 +00:00

604 lines
19 KiB
JavaScript

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,
MAX_UPLOAD,
PORT,
RAW_PREVIEW_EDGE,
} from './config.mjs';
import {
authenticate,
createSession,
hashPassword,
normalizeEmail,
publicUser,
validEmail,
verifyPassword,
} from './auth.mjs';
import {
countPhotos,
getPhoto,
kv,
listEvents,
listPhotos,
removeEvent,
removePhoto,
saveEvent,
savePhoto,
sessions,
users,
} from './db.mjs';
import {
findOriginal,
findPreview,
findThumb,
removeAsset,
removeThumb,
storageBytes,
writeOriginal,
writePreview,
writeThumb,
} from './storage.mjs';
import { decodeRaw, isRawName, rawSupport } from './raw.mjs';
import {
bridgeConfigured,
bridgeForEvent,
exchangeBridgeToken,
fetchBridgeImage,
forwardBridgeRender,
importBridgeEvent,
purgeExpiredBridges,
verifyBridgeToken,
} from './bridge.mjs';
import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
const VERSION = '1.0.0';
const COOKIE = 'lumen_session';
/* ------------------------------------------------------------------ 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);
}
function error(res, status, message) {
json(res, status, { error: message });
}
function parseCookies(req) {
const out = {};
for (const part of String(req.headers.cookie ?? '').split(';')) {
const idx = part.indexOf('=');
if (idx < 0) continue;
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
}
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}`;
}
function currentUser(req) {
const cookieToken = parseCookies(req)[COOKIE];
if (cookieToken) {
const row = sessions.find(cookieToken);
if (row && Number(row.expires_at) > Date.now()) return publicUser(users.byId(row.user_id));
}
return authenticate(req);
}
function readBody(req, limit = MAX_UPLOAD) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > limit) {
reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
req.destroy();
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');
}
}
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,
...(type.startsWith('image/') ? { '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') {
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,
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
});
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') };
}
/* --------------------------------------------------------------------- api */
const routes = [];
function route(method, pattern, handler) {
routes.push({ method, pattern, handler });
}
route('GET', '/api/health', async ({ res }) => {
const raw = await rawSupport();
json(res, 200, {
ok: true,
app: 'lumenroom',
version: VERSION,
needsSetup: users.count() === 0,
registrationOpen: users.count() === 0 || Boolean(INVITE),
photos: countPhotos(),
bytes: storageBytes(),
raw,
});
});
route('POST', '/api/auth/register', async ({ req, res }) => {
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;
if (!first) {
if (!INVITE) return error(res, 403, 'Registration is closed. Ask an admin for an invite code.');
if (String(body.invite ?? '') !== INVITE) return error(res, 403, 'Invite code is not correct');
}
const id = crypto.randomUUID();
users.create({
id,
email,
name: name || email.split('@')[0],
passHash: hashPassword(password),
role: first ? 'admin' : 'member',
});
const token = createSession(id);
json(
res,
201,
{ token, user: publicUser(users.byId(id)) },
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
);
});
route('POST', '/api/auth/login', async ({ req, res }) => {
const body = await readJson(req, 64 * 1024);
const email = normalizeEmail(body.email);
const password = typeof body.password === 'string' ? body.password : '';
const row = users.byEmail(email);
if (!row || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct');
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 });
});
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: hashPassword(crypto.randomBytes(24).toString('hex')),
role: 'member',
});
row = users.byId(id);
}
purgeExpiredBridges();
const imported = await importBridgeEvent({
serviceToken: service.token,
sessionId: payload.sid,
returnUrl: service.returnUrl,
});
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',
);
}
});
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(),
photos: listPhotos(),
presets: kv.get('presets') ?? [],
});
});
route('PUT', '/api/events/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
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()));
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');
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 });
});
/**
* 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 url = new URL(req.url ?? '/', 'http://localhost');
const name = url.searchParams.get('name') || 'upload';
const mime = url.searchParams.get('mime') || 'application/octet-stream';
const drop = url.searchParams.get('drop') === '1';
const data = await readBody(req);
if (!data.length) return error(res, 400, 'Empty upload');
const ext = (name.split('.').pop() || 'bin').toLowerCase();
await writeOriginal(params.id, ext, data);
if (isRawName(name) || drop) {
try {
const decoded = await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext);
const info = await jpegInfo(decoded.jpeg);
return json(res, 201, {
raw: true,
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) {
return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file');
}
}
return json(res, 201, { raw: false, mime, size: data.length });
});
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
const thumb = 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');
});
route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => {
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');
});
route('GET', '/api/photos/:id/original', async ({ req, res, params }) => {
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, linked.photo.mime || 'application/octet-stream');
});
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');
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');
}
// The grid now shows the dashboard's thumbnail of this render, so drop the
// cached copy and bump the URL the browser asks for.
await removeThumb(body.photoId).catch(() => undefined);
const thumbVersion = Date.now();
const stored = getPhoto(body.photoId);
if (stored) {
stored.thumbVersion = thumbVersion;
savePhoto(stored);
}
return json(res, 200, { ...(result.body ?? { ok: true }), thumbVersion });
});
route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
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 };
const thumb = decodeDataUrl(record.thumb);
if (thumb) {
await writeThumb(params.id, thumb.data);
delete record.thumb;
}
if (record.raw) {
record.previewUrl = `/api/photos/${params.id}/preview`;
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 = `/api/photos/${params.id}/thumb`;
savePhoto(record);
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');
removePhoto(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',
};
async function serveStatic(req, res, url) {
const pathname = decodeURIComponent(url.pathname);
const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname);
if (candidate.startsWith(DIST_DIR)) {
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('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'same-origin');
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(`[lumenroom] ${req.method} ${url.pathname} → ${message}`);
if (!res.headersSent) return error(res, 500, message);
res.end();
}
});
server.listen(PORT, HOST, async () => {
const raw = await rawSupport();
console.log(`Lumenroom 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'}`,
);
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)');
});
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => {
server.close(() => process.exit(0));
});
}