feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled

Event photos can now be opened in Lumenroom, a WebGL2 develop module, from the
photo editor's Advanced button. The dashboard signs a short-lived token scoped
to one user and event; Lumenroom exchanges it, imports the event's photo list
and proxies bytes on demand, so nothing is copied and the temporary catalog
expires with the bridge session. Saving in Lumenroom renders the photo and
writes it back as the event's edited JPEG, with the advanced recipe kept in
event_photos.advanced_edit_json.

Lumenroom is vendored under lumenroom/ and built as a second compose service,
so one clone and `docker compose up -d --build` deploys both apps.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-21 01:34:20 +00:00
parent 982f9048e1
commit 0cb315ea88
89 changed files with 22087 additions and 1 deletions
+58
View File
@@ -0,0 +1,58 @@
import crypto from 'node:crypto';
import { SESSION_DAYS } from './config.mjs';
import { sessions, users } from './db.mjs';
const KEYLEN = 64;
export function hashPassword(password) {
const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync(password, salt, KEYLEN);
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
}
export function verifyPassword(password, stored) {
const [scheme, saltHex, hashHex] = String(stored).split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, 'hex');
const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
export function createSession(userId) {
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
sessions.purge();
sessions.create(token, userId, expiresAt);
return token;
}
export function publicUser(row) {
if (!row) return null;
return {
id: row.id,
email: row.email,
name: row.name ?? '',
role: row.role ?? 'member',
};
}
export function authenticate(req) {
const header = String(req.headers.authorization ?? '');
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
if (!token) return null;
const session = sessions.find(token);
if (!session) return null;
if (Number(session.expires_at) < Date.now()) {
sessions.destroy(token);
return null;
}
return publicUser(users.byId(session.user_id));
}
export function normalizeEmail(value) {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}
export function validEmail(email) {
return /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email);
}
+265
View File
@@ -0,0 +1,265 @@
/**
* Bridge to the Media Team Hub dashboard.
*
* The dashboard signs a short-lived token scoped to one event; this module
* verifies it, exchanges it for a service token, mirrors the event's photo list
* into the local catalog, and proxies bytes/save-backs for as long as the
* bridge session lives. Nothing here is reachable without a valid token.
*/
import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { removeAsset } from './storage.mjs';
const VERSION = 'g1';
/* ------------------------------------------------------------------- tokens */
export function bridgeConfigured() {
return Boolean(BRIDGE_SECRET && GLENLOCH_URL);
}
export function verifyBridgeToken(token, now = Date.now()) {
if (!BRIDGE_SECRET || typeof token !== 'string') return null;
const parts = token.split('.');
if (parts.length !== 3 || parts[0] !== VERSION) return null;
const [, body, signature] = parts;
const expected = crypto.createHmac('sha256', BRIDGE_SECRET).update(body).digest();
let supplied;
try {
supplied = Buffer.from(signature.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
} catch {
return null;
}
if (
supplied.length !== expected.length ||
!crypto.timingSafeEqual(supplied, expected)
) {
return null;
}
let payload;
try {
payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
} catch {
return null;
}
if (
!payload ||
typeof payload.sid !== 'string' ||
typeof payload.eid !== 'string' ||
typeof payload.uid !== 'string' ||
typeof payload.email !== 'string' ||
(payload.kind !== 'login' && payload.kind !== 'service') ||
typeof payload.exp !== 'number' ||
payload.exp * 1000 <= now
) {
return null;
}
return payload;
}
async function dashboardJson(url, token, init = {}) {
const res = await fetch(url, {
...init,
headers: {
...(init.headers ?? {}),
authorization: `Bearer ${token}`,
},
});
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
if (!res.ok) {
throw new Error(body?.error || `Dashboard request failed (${res.status})`);
}
return body;
}
/** Swap the one browser-hop login token for a longer server-side token. */
export async function exchangeBridgeToken(loginToken, sessionId) {
return dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}/exchange`,
loginToken,
{ method: 'POST' },
);
}
/* ------------------------------------------------------------------ storage */
const bridgeInsert = db.prepare(`
INSERT INTO bridge_events (event_id, session_id, token, glenloch_url, source_event_id, return_url, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(event_id) DO UPDATE SET
session_id = excluded.session_id,
token = excluded.token,
glenloch_url = excluded.glenloch_url,
source_event_id = excluded.source_event_id,
return_url = excluded.return_url,
expires_at = excluded.expires_at,
created_at = excluded.created_at
`);
const bridgeGet = db.prepare('SELECT * FROM bridge_events WHERE event_id = ?');
const bridgeExpired = db.prepare('SELECT event_id FROM bridge_events WHERE expires_at < ?');
const bridgeDelete = db.prepare('DELETE FROM bridge_events WHERE event_id = ?');
const photosForEvent = db.prepare('SELECT id FROM photos WHERE event_id = ?');
export function bridgeEventId(sourceEventId) {
return `br-${sourceEventId}`;
}
export function bridgePhotoId(sourcePhotoId) {
return `br-${sourcePhotoId}`;
}
export function bridgeForEvent(eventId) {
return bridgeGet.get(eventId) ?? null;
}
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
function dropBridgeEvent(eventId) {
for (const row of photosForEvent.all(eventId)) {
removePhoto(row.id);
removeAsset(row.id).catch(() => undefined);
}
removeEvent(eventId);
bridgeDelete.run(eventId);
}
/** Removes events whose bridge session has expired. Safe to call often. */
export function purgeExpiredBridges(now = Date.now()) {
for (const row of bridgeExpired.all(now)) {
dropBridgeEvent(row.event_id);
}
}
function eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt) {
const source = listing.event;
return {
id: eventId,
name: source.title || 'Advanced edit',
date: source.startsAt ? Date.parse(source.startsAt) : Date.now(),
createdAt: Date.now(),
notes: source.description ?? undefined,
bridge: {
sessionId,
sourceEventId: source.id,
dashboardUrl: returnUrl ?? `${GLENLOCH_URL}/events/${source.id}`,
expiresAt,
},
};
}
function photoRecordFrom(photo, eventId, sessionId, index) {
const id = bridgePhotoId(photo.id);
const raw = photo.kind === 'raw';
return {
id,
eventId,
order: index,
name: photo.filename,
width: photo.width || 0,
height: photo.height || 0,
size: photo.sizeBytes || 0,
mime: photo.mimeType || 'application/octet-stream',
addedAt: Date.now(),
takenAt: photo.takenAt ? Date.parse(photo.takenAt) : undefined,
meta: {},
thumb: '',
thumbUrl: `/api/photos/${id}/thumb`,
rating: 0,
flag: 'none',
color: '',
keywords: [],
edits: {},
history: [],
raw,
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
bridgeSource: { sessionId, sourceId: photo.id },
};
}
/**
* Mirrors one event into the local catalog. The photo bytes stay on the
* dashboard; only metadata, previews and thumbnails are temporary here.
*/
export async function importBridgeEvent({ serviceToken, sessionId }) {
const expiresAt =
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
const listing = await dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}`,
serviceToken,
);
const eventId = bridgeEventId(listing.event.id);
dropBridgeEvent(eventId);
const returnUrl = listing.editor?.returnUrl ?? null;
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0);
listing.photos.forEach((photo, index) => {
savePhoto(photoRecordFrom(photo, eventId, sessionId, index));
});
bridgeInsert.run(
eventId,
sessionId,
serviceToken,
GLENLOCH_URL,
listing.event.id,
returnUrl,
expiresAt,
Date.now(),
);
return {
eventId,
photoCount: listing.photos.length,
sessionId,
expiresAt,
};
}
/* ----------------------------------------------------------------- proxying */
export function bridgeSourceUrl(row, sourcePhotoId, variant) {
const params = new URLSearchParams({ variant });
return `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/source?${params}`;
}
export async function fetchBridgeImage(row, sourcePhotoId, variant) {
return fetch(bridgeSourceUrl(row, sourcePhotoId, variant), {
headers: { authorization: `Bearer ${row.token}` },
});
}
/** Forwards a browser-rendered JPEG and recipe to the dashboard. */
export async function forwardBridgeRender(row, sourcePhotoId, payload) {
const res = await fetch(
`${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/render`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${row.token}`,
},
body: JSON.stringify(payload),
},
);
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
return { status: res.status, body };
}
+51
View File
@@ -0,0 +1,51 @@
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
export const ROOT = path.resolve(here, '..');
export const DATA_DIR = process.env.LUMENROOM_DATA
? path.resolve(process.env.LUMENROOM_DATA)
: path.join(here, 'data');
export const ORIGINAL_DIR = path.join(DATA_DIR, 'originals');
export const PREVIEW_DIR = path.join(DATA_DIR, 'previews');
export const THUMB_DIR = path.join(DATA_DIR, 'thumbs');
export const DB_PATH = path.join(DATA_DIR, 'lumenroom.db');
export const DIST_DIR = path.join(ROOT, 'dist');
export const PORT = Number(process.env.PORT || 8787);
export const HOST = process.env.HOST || '0.0.0.0';
/** Shared invite code required to register after the first account exists. */
export const INVITE = process.env.LUMENROOM_INVITE || '';
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
/** How long an imported bridge event survives without being reopened. */
export const BRIDGE_TTL_HOURS = Number(process.env.LUMENROOM_BRIDGE_TTL_HOURS || 12);
/** Upload ceiling in bytes (300 MB default, bigger than any consumer raw). */
export const MAX_UPLOAD = Number(process.env.LUMENROOM_MAX_UPLOAD || 300 * 1024 * 1024);
/** Long edge used for the editable proxy of raw files. */
export const RAW_PREVIEW_EDGE = Number(process.env.LUMENROOM_RAW_EDGE || 6000);
export const SESSION_DAYS = 30;
/** How many raws decode at once. One core is left for the HTTP server. */
export const RAW_WORKERS = Math.max(
1,
Number(
process.env.LUMENROOM_RAW_WORKERS ||
Math.min(4, Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1)),
),
);
/** Idle decoder workers are disposed after this long to release memory. */
export const RAW_IDLE_MS = Number(process.env.LUMENROOM_RAW_IDLE_MS || 90_000);
+177
View File
@@ -0,0 +1,177 @@
import fs from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
import { DATA_DIR, DB_PATH } from './config.mjs';
fs.mkdirSync(DATA_DIR, { recursive: true });
export const db = new DatabaseSync(DB_PATH);
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL DEFAULT '',
pass_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member',
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
sort_index REAL NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
data TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS photos (
id TEXT PRIMARY KEY,
event_id TEXT NOT NULL DEFAULT '',
sort_index REAL NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL,
raw INTEGER NOT NULL DEFAULT 0,
data TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS photos_event ON photos(event_id);
CREATE INDEX IF NOT EXISTS photos_updated ON photos(updated_at);
CREATE TABLE IF NOT EXISTS kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS bridge_events (
event_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
token TEXT NOT NULL,
glenloch_url TEXT NOT NULL,
source_event_id TEXT NOT NULL,
return_url TEXT,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
`);
const q = {
upsertEvent: db.prepare(`
INSERT INTO events (id, sort_index, created_at, data) VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET sort_index = excluded.sort_index, data = excluded.data
`),
deleteEvent: db.prepare('DELETE FROM events WHERE id = ?'),
allEvents: db.prepare('SELECT data FROM events ORDER BY sort_index ASC, created_at ASC'),
upsertPhoto: db.prepare(`
INSERT INTO photos (id, event_id, sort_index, updated_at, raw, data) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
event_id = excluded.event_id,
sort_index = excluded.sort_index,
updated_at = excluded.updated_at,
raw = excluded.raw,
data = excluded.data
`),
deletePhoto: db.prepare('DELETE FROM photos WHERE id = ?'),
allPhotos: db.prepare('SELECT data FROM photos ORDER BY sort_index ASC, updated_at ASC'),
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
insertUser: db.prepare(
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
),
userCount: db.prepare('SELECT COUNT(*) AS n FROM users'),
findUserById: db.prepare('SELECT id, email, name, role, created_at FROM users WHERE id = ?'),
insertSession: db.prepare(
'INSERT INTO sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)',
),
findSession: db.prepare('SELECT * FROM sessions WHERE token = ?'),
deleteSession: db.prepare('DELETE FROM sessions WHERE token = ?'),
purgeSessions: db.prepare('DELETE FROM sessions WHERE expires_at < ?'),
kvGet: db.prepare('SELECT value FROM kv WHERE key = ?'),
kvSet: db.prepare(
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
),
};
function parse(json) {
if (!json) return null;
try {
return JSON.parse(json);
} catch {
return null;
}
}
export function listEvents() {
return q.allEvents.all().map((r) => parse(r.data)).filter((r) => r !== null);
}
export function saveEvent(record, sortIndex = 0) {
q.upsertEvent.run(record.id, sortIndex, record.createdAt ?? Date.now(), JSON.stringify(record));
}
export function removeEvent(id) {
q.deleteEvent.run(id);
}
export function listPhotos() {
return q.allPhotos.all().map((r) => parse(r.data)).filter((r) => r !== null);
}
export function getPhoto(id) {
const row = q.photo.get(id);
return row ? parse(row.data) : null;
}
export function savePhoto(record, updatedAt = Date.now()) {
q.upsertPhoto.run(
record.id,
record.eventId ?? '',
typeof record.order === 'number' ? record.order : 0,
updatedAt,
record.raw ? 1 : 0,
JSON.stringify(record),
);
}
export function removePhoto(id) {
q.deletePhoto.run(id);
}
export function countPhotos() {
return Number(q.photoCount.get()?.n ?? 0);
}
export const users = {
count: () => Number(q.userCount.get()?.n ?? 0),
byEmail: (email) => q.findUserByEmail.get(String(email).toLowerCase()),
byId: (id) => q.findUserById.get(id),
create: (user) =>
q.insertUser.run(user.id, user.email.toLowerCase(), user.name, user.passHash, user.role, Date.now()),
};
export const sessions = {
create: (token, userId, expiresAt) => q.insertSession.run(token, userId, Date.now(), expiresAt),
find: (token) => q.findSession.get(token),
destroy: (token) => q.deleteSession.run(token),
purge: () => q.purgeSessions.run(Date.now()),
};
export const kv = {
get: (key) => {
const row = q.kvGet.get(key);
return row ? parse(row.value) : null;
},
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
};
+129
View File
@@ -0,0 +1,129 @@
import zlib from 'node:zlib';
import { RAW_PREVIEW_EDGE } from './config.mjs';
let sharpModule = null;
let sharpFailed = false;
/** sharp gives us JPEG encoding and resizing; without it we fall back to PNG. */
export async function loadSharp() {
if (sharpModule) return sharpModule;
if (sharpFailed) return null;
try {
const mod = await import('sharp');
sharpModule = mod.default;
return sharpModule;
} catch {
sharpFailed = true;
return null;
}
}
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c;
}
return table;
})();
function crc32(buf) {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type, data) {
const out = Buffer.alloc(8 + data.length + 4);
out.writeUInt32BE(data.length, 0);
out.write(type, 4, 'ascii');
data.copy(out, 8);
out.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 8 + data.length);
return out;
}
/** Minimal dependency-free 8-bit RGB PNG encoder (used only when sharp is absent). */
export function encodePng(rgb, width, height) {
const stride = width * 3;
const raw = Buffer.alloc((stride + 1) * height);
for (let y = 0; y < height; y++) {
raw[y * (stride + 1)] = 0;
Buffer.from(rgb.buffer, rgb.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1);
}
const idat = zlib.deflateSync(raw, { level: 6 });
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8;
ihdr[9] = 2;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', idat),
chunk('IEND', Buffer.alloc(0)),
]);
}
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
const sharp = await loadSharp();
if (!sharp) {
return { data: encodePng(rgb, width, height), ext: 'png', width, height };
}
let img = sharp(Buffer.from(rgb.buffer, rgb.byteOffset, rgb.byteLength), {
raw: { width, height, channels: 3 },
});
if (maxEdge > 0 && Math.max(width, height) > maxEdge) img = img.resize({ width: width >= height ? maxEdge : null, height: height > width ? maxEdge : null, fit: 'inside' });
const data = await img.jpeg({ quality, chromaSubsampling: '4:4:4' }).toBuffer();
const meta = await sharp(data).metadata();
return { data, ext: 'jpg', width: Number(meta.width ?? width), height: Number(meta.height ?? height) };
}
export async function jpegInfo(buffer) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
const meta = await sharp(buffer).metadata();
return { width: Number(meta.width ?? 0), height: Number(meta.height ?? 0), format: meta.format };
} catch {
return null;
}
}
/** Re-encode any decodable image to a normalised JPEG proxy. */
export async function toJpegProxy(buffer, maxEdge = RAW_PREVIEW_EDGE) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
let img = sharp(buffer, { failOn: 'none' }).rotate();
const meta = await img.metadata();
const w = Number(meta.width ?? 0);
const h = Number(meta.height ?? 0);
if (!w || !h) return null;
if (maxEdge > 0 && Math.max(w, h) > maxEdge) img = img.resize({ width: maxEdge, height: maxEdge, fit: 'inside' });
const data = await img.jpeg({ quality: 92, chromaSubsampling: '4:4:4' }).toBuffer();
const outMeta = await sharp(data).metadata();
return { data, width: Number(outMeta.width ?? w), height: Number(outMeta.height ?? h), ext: 'jpg' };
} catch {
return null;
}
}
export async function makeThumb(buffer, edge = 512) {
const sharp = await loadSharp();
if (!sharp) return null;
try {
const data = await sharp(buffer, { failOn: 'none' })
.rotate()
.resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true })
.jpeg({ quality: 82 })
.toBuffer();
return data;
} catch {
return null;
}
}
+591
View File
@@ -0,0 +1,591 @@
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,
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,
});
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');
}
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');
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));
});
}
+120
View File
@@ -0,0 +1,120 @@
import { RAW_IDLE_MS, RAW_WORKERS } from './config.mjs';
import { installLibrawRuntime } from './libraw-runtime.mjs';
let ctorPromise = null;
/** Load the decoder class once; installs the Node worker shim on first use. */
export function loadLibRaw() {
if (!ctorPromise) {
ctorPromise = (async () => {
await installLibrawRuntime();
const mod = await import('libraw-wasm');
const ctor = mod.default?.default ?? mod.default;
if (typeof ctor !== 'function') throw new Error('libraw-wasm did not export a constructor');
return ctor;
})();
}
return ctorPromise;
}
/**
* Bounded pool of decoder instances. Each instance owns one worker thread, so
* this caps how much demosaicing runs at the same time; extra jobs queue.
* Idle instances are disposed after RAW_IDLE_MS to give the memory back.
*/
class LibRawPool {
constructor(size = RAW_WORKERS) {
this.size = Math.max(1, Math.floor(size));
this.free = [];
this.total = 0;
this.waiters = [];
this.closed = false;
}
async acquire() {
const entry = this.free.pop();
if (entry) {
if (entry.timer) clearTimeout(entry.timer);
return entry.lib;
}
if (this.total < this.size) {
this.total++;
try {
const Ctor = await loadLibRaw();
return new Ctor();
} catch (err) {
this.total--;
throw err;
}
}
return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
}
release(lib, healthy = true) {
if (this.closed || !healthy) {
this.discard(lib);
return;
}
const waiter = this.waiters.shift();
if (waiter) {
waiter.resolve(lib);
return;
}
const entry = { lib, timer: null };
entry.timer = setTimeout(() => {
const idx = this.free.indexOf(entry);
if (idx >= 0) {
this.free.splice(idx, 1);
this.discard(lib);
}
}, RAW_IDLE_MS);
entry.timer.unref?.();
this.free.push(entry);
}
discard(lib) {
try {
lib.dispose();
} catch {
/* worker already gone */
}
this.total = Math.max(0, this.total - 1);
const waiter = this.waiters.shift();
if (waiter) {
this.total++;
loadLibRaw()
.then((Ctor) => new Ctor())
.then(waiter.resolve, waiter.reject);
}
}
/** Run `fn` with a decoder instance; the instance returns to the pool after. */
async use(fn) {
const lib = await this.acquire();
let healthy = true;
try {
return await fn(lib);
} catch (err) {
// A dead worker keeps failing, so recycle it instead of handing it back.
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
throw err;
} finally {
this.release(lib, healthy);
}
}
get stats() {
return {
size: this.size,
busy: this.total - this.free.length,
idle: this.free.length,
queued: this.waiters.length,
};
}
}
export const rawPool = new LibRawPool();
export function poolSupport() {
return { size: rawPool.size, workers: RAW_WORKERS };
}
+34
View File
@@ -0,0 +1,34 @@
/**
* libraw-wasm is browser-first: the wrapper spawns a Web Worker and the
* Emscripten build loads libraw.wasm with fetch(). Node has neither a global
* Worker nor file:// support in fetch, so the decoder runs in a worker_thread
* with a tiny browser-globals shim (see libraw-worker.mjs).
*
* This is a no-op in the browser, where the real Worker already exists.
*/
let installed = false;
export async function installLibrawRuntime() {
if (installed) return;
installed = true;
if (typeof globalThis.Worker === 'function') return;
const { Worker: NodeWorker } = await import('node:worker_threads');
const entry = new URL('./libraw-worker.mjs', import.meta.url);
class BrowserWorker {
constructor() {
this._worker = new NodeWorker(entry);
this._worker.on('message', (data) => this.onmessage?.({ data }));
this._worker.on('error', (err) => this.onerror?.(err));
}
postMessage(message, transfer) {
this._worker.postMessage(message, transfer);
}
terminate() {
return this._worker.terminate();
}
}
globalThis.Worker = BrowserWorker;
}
+31
View File
@@ -0,0 +1,31 @@
import { parentPort } from 'node:worker_threads';
import fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
// libraw-wasm targets browsers: emulate the worker globals its build expects.
globalThis.self = globalThis;
globalThis.WorkerGlobalScope = globalThis;
globalThis.postMessage = (msg, transfer) => parentPort.postMessage(msg, transfer);
globalThis.addEventListener = () => {};
// Emscripten loads libraw.wasm through fetch(); Node's fetch rejects file:// URLs.
const realFetch = globalThis.fetch;
globalThis.fetch = async (url, init) => {
const href = typeof url === 'string' ? url : url instanceof URL ? url.href : String(url);
if (href.startsWith('file:')) {
const buf = await fs.readFile(fileURLToPath(href));
return new Response(buf, { status: 200, headers: { 'content-type': 'application/wasm' } });
}
return realFetch(url, init);
};
// Buffer anything that arrives before the module registers `onmessage`.
const queue = [];
parentPort.on('message', (data) => {
if (typeof globalThis.onmessage === 'function') globalThis.onmessage({ data });
else queue.push(data);
});
await import('libraw-wasm/dist/worker.js');
for (const data of queue.splice(0)) globalThis.onmessage({ data });
+214
View File
@@ -0,0 +1,214 @@
import { RAW_PREVIEW_EDGE } from './config.mjs';
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
/** Every raw container the pipeline will attempt, grouped by vendor family. */
export const RAW_EXTENSIONS = new Set([
// Canon
'cr2', 'cr3', 'crw',
// Nikon
'nef', 'nrw',
// Sony
'arw', 'srf', 'sr2',
// Olympus / OM System
'orf',
// Panasonic / Leica
'rw2', 'raw', 'rwl',
// Fujifilm
'raf',
// Pentax / Ricoh
'pef', 'dng',
// Samsung, Hasselblad, Leaf, Phase One, Sigma, Epson, Kodak, Minolta
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
]);
export function isRawName(name = '') {
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return RAW_EXTENSIONS.has(ext);
}
/** True when the buffer starts with a container signature LibRaw can open. */
export function looksLikeRaw(buffer) {
if (!buffer || buffer.length < 64) return false;
const hex4 = buffer.subarray(0, 4).toString('hex');
const ascii = buffer.subarray(0, 16).toString('latin1');
if (hex4 === '49492a00' || hex4 === '4d4d002a') return true; // TIFF family
if (hex4 === '4949524f' || hex4 === '4d4d4f52') return true; // ORF
if (hex4 === '49495500') return true; // RW2
if (hex4 === '49494949') return true; // Phase One IIQ
if (ascii.startsWith('FUJIFILMCCD-RAW')) return true; // RAF
if (ascii.startsWith('FOVb')) return true; // X3F
if (buffer.subarray(4, 8).toString('latin1') === 'ftyp') return true; // CR3
return false;
}
let engineState = 'unloaded';
export async function rawEngine() {
if (engineState === 'unloaded') {
try {
await loadLibRaw();
engineState = 'ready';
} catch {
engineState = 'missing';
}
}
return engineState;
}
const DECODE_SETTINGS = {
outputBps: 8,
useCameraWb: true,
outputColor: 1, // sRGB
userQual: 3,
highlight: 0,
noAutoBright: false,
// Use the orientation stored in the raw container: phone and DSLR files often
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
// sideways proxy that no later step can fix without losing the original axes.
userFlip: -1,
useFujiRotate: -1,
};
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
function toRgb(img) {
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
const width = Number(img.width);
const height = Number(img.height);
const colors = Number(img.colors ?? 3);
const bits = Number(img.bits ?? 8);
const src = img.data;
const pixelCount = width * height;
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
if (src.length < needed) {
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
}
const rgb = Buffer.alloc(pixelCount * 3);
if (bits > 8) {
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
for (let i = 0; i < pixelCount; i++) {
const s = i * colors;
rgb[i * 3] = view[s] >> 8;
rgb[i * 3 + 1] = view[s + 1] >> 8;
rgb[i * 3 + 2] = view[s + 2] >> 8;
}
} else {
for (let i = 0; i < pixelCount; i++) {
const s = i * colors;
rgb[i * 3] = src[s];
rgb[i * 3 + 1] = src[s + 1];
rgb[i * 3 + 2] = src[s + 2];
}
}
return { rgb, width, height };
}
/**
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
*/
async function demosaic(buffer) {
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
return rawPool.use(async (lib) => {
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
// a copy so the caller's bytes survive for the embedded-preview fallback.
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
return toRgb(await lib.imageData());
});
}
const SOI = Buffer.from([0xff, 0xd8, 0xff]);
const EOI = Buffer.from([0xff, 0xd9]);
/** Pull the largest embedded JPEG straight out of a raw container. */
export function extractEmbeddedJpeg(buffer) {
let best = null;
let from = 0;
while (from < buffer.length - 3) {
const start = buffer.indexOf(SOI, from);
if (start < 0) break;
const end = buffer.indexOf(EOI, start + 3);
if (end < 0) break;
const length = end + 2 - start;
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
from = end + 2;
}
return best;
}
/** Camera preview, preferably the one LibRaw knows the offset and length of. */
async function embeddedPreview(buffer) {
if ((await rawEngine()) === 'ready') {
try {
const thumb = await rawPool.use(async (lib) => {
await lib.open(Buffer.from(buffer), { useCameraWb: true });
return lib.thumbnailData();
});
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
return Buffer.from(thumb.data);
}
} catch {
/* fall through to the byte scan */
}
}
return extractEmbeddedJpeg(buffer);
}
/**
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
* falls back to the camera's own embedded preview when it cannot.
*/
export async function decodeRaw(buffer) {
let librawError = null;
if (looksLikeRaw(buffer)) {
try {
const { rgb, width, height } = await demosaic(buffer);
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
return {
jpeg: encoded.data,
width: encoded.width,
height: encoded.height,
engine: 'libraw',
ext: encoded.ext,
};
} catch (err) {
librawError = err instanceof Error ? err.message : String(err);
}
} else {
librawError = 'not a recognised raw container';
}
const embedded = await embeddedPreview(buffer);
if (embedded) {
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
if (proxy) {
const size = await jpegInfo(proxy.data);
return {
jpeg: proxy.data,
width: size?.width || proxy.width,
height: size?.height || proxy.height,
engine: 'embedded',
ext: proxy.ext,
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
};
}
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined };
}
throw new Error(
`Could not decode this raw file. ${librawError ? `LibRaw said: ${librawError}.` : 'LibRaw is not installed.'}`,
);
}
export async function rawSupport() {
const engine = await rawEngine();
const sharp = await loadSharp();
return {
libraw: engine === 'ready',
sharp: Boolean(sharp),
workers: rawPool.size,
busy: rawPool.stats.busy,
formats: [...RAW_EXTENSIONS].sort(),
};
}
+90
View File
@@ -0,0 +1,90 @@
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR } from './config.mjs';
for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) fs.mkdirSync(dir, { recursive: true });
const SAFE = /^[A-Za-z0-9_-]{1,80}$/;
function safeId(id) {
if (!SAFE.test(id)) throw new Error('Invalid asset id');
return id;
}
/** Original files keep their real extension so a raw can be recovered later. */
function originalPath(id, ext = 'bin') {
return path.join(ORIGINAL_DIR, `${safeId(id)}.${ext.replace(/[^a-z0-9]/gi, '') || 'bin'}`);
}
export async function writeOriginal(id, ext, data) {
const target = originalPath(id, ext);
await fsp.writeFile(target, data);
return target;
}
/**
* Reads are lookups: a malformed id simply has no file, so it must not throw a
* 500 out of the request handler. Writers keep the strict check.
*/
function lookupId(id) {
return typeof id === 'string' && SAFE.test(id) ? id : null;
}
export function findOriginal(id) {
const safe = lookupId(id);
if (!safe) return null;
const prefix = `${safe}.`;
for (const name of fs.readdirSync(ORIGINAL_DIR)) {
if (name.startsWith(prefix)) return path.join(ORIGINAL_DIR, name);
}
return null;
}
export async function writePreview(id, data, ext = 'jpg') {
const target = path.join(PREVIEW_DIR, `${safeId(id)}.${ext}`);
await fsp.writeFile(target, data);
return target;
}
export function findPreview(id) {
const safe = lookupId(id);
if (!safe) return null;
for (const ext of ['jpg', 'png']) {
const p = path.join(PREVIEW_DIR, `${safe}.${ext}`);
if (fs.existsSync(p)) return p;
}
return null;
}
export async function writeThumb(id, data) {
const target = path.join(THUMB_DIR, `${safeId(id)}.jpg`);
await fsp.writeFile(target, data);
return target;
}
export function findThumb(id) {
const safe = lookupId(id);
if (!safe) return null;
const p = path.join(THUMB_DIR, `${safe}.jpg`);
return fs.existsSync(p) ? p : null;
}
export async function removeAsset(id) {
const files = [findOriginal(id), findPreview(id), findThumb(id)];
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
}
export function storageBytes() {
let total = 0;
for (const dir of [ORIGINAL_DIR, PREVIEW_DIR, THUMB_DIR]) {
for (const name of fs.readdirSync(dir)) {
try {
total += fs.statSync(path.join(dir, name)).size;
} catch {
/* file vanished mid-scan */
}
}
}
return total;
}