cd52a2f82f
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1454 lines
51 KiB
JavaScript
1454 lines
51 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 {
|
|
addGalleryComment,
|
|
commentsByOwner,
|
|
commentsForToken,
|
|
countPhotos,
|
|
eventByShareToken,
|
|
eventOwner,
|
|
galleryPick,
|
|
getPhoto,
|
|
invites,
|
|
kv,
|
|
listEvents,
|
|
listPhotos,
|
|
livePhotoBytes,
|
|
photoOwner,
|
|
picksByOwner,
|
|
picksForToken,
|
|
removeEvent,
|
|
reviewsByOwner,
|
|
reviewsForToken,
|
|
setGalleryReview,
|
|
removePhoto,
|
|
saveEvent,
|
|
savePhoto,
|
|
sessions,
|
|
setShareToken,
|
|
shareTokenFor,
|
|
users,
|
|
} from './db.mjs';
|
|
import {
|
|
defaultRoot,
|
|
findOriginal,
|
|
findPreview,
|
|
findProof,
|
|
findProofThumb,
|
|
findThumb,
|
|
isCustomRoot,
|
|
removeAsset,
|
|
setStorageRoot,
|
|
storageBytes,
|
|
storageRoot,
|
|
writeOriginal,
|
|
writePreview,
|
|
writeProof,
|
|
writeProofThumb,
|
|
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';
|
|
import { createZip } from './zip.mjs';
|
|
import {
|
|
cancelPrune,
|
|
quotaState,
|
|
quotasForAdmin,
|
|
schedulePrune,
|
|
setUserQuota,
|
|
startQuotaWorker,
|
|
warnUser,
|
|
} from './quota.mjs';
|
|
import { mailStatus, saveMailSettings, sendTestMail } from './mail.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()) {
|
|
const user = users.byId(row.user_id);
|
|
if (user && !user.disabled) return publicUser(user);
|
|
}
|
|
}
|
|
return authenticate(req);
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/** An ownerless row predates workspaces; anyone signed in may finish it. */
|
|
function ownedBy(owner, user) {
|
|
return !owner || owner === user.id;
|
|
}
|
|
|
|
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/<token> 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;
|
|
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', 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,
|
|
...(type.startsWith('image/') ? { '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') };
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- 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 ({ res }) => {
|
|
const raw = await rawSupport();
|
|
json(res, 200, {
|
|
ok: true,
|
|
app: 'luminary',
|
|
version: VERSION,
|
|
needsSetup: users.count() === 0,
|
|
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
|
photos: countPhotos(),
|
|
bytes: storageBytes(),
|
|
storage: { root: storageRoot(), custom: isCustomRoot() },
|
|
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;
|
|
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: 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 }) => {
|
|
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');
|
|
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/<token>; 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(),
|
|
});
|
|
});
|
|
|
|
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: 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');
|
|
|
|
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 = 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 (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');
|
|
}
|
|
});
|
|
|
|
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/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,
|
|
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,
|
|
});
|
|
});
|
|
|
|
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');
|
|
setShareToken(params.id, null);
|
|
json(res, 200, { ok: true });
|
|
});
|
|
|
|
/** Public gallery payload: no session, only the shared event and its photos. */
|
|
route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
|
|
const shared = eventByShareToken(params.token);
|
|
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
|
|
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 },
|
|
});
|
|
});
|
|
|
|
route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => {
|
|
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 }) => {
|
|
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);
|
|
return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', 'private, max-age=3600');
|
|
});
|
|
|
|
/** Client download of the edited proof, named like the delivered file. */
|
|
route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => {
|
|
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, '-');
|
|
return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', '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 shared = eventByShareToken(params.token);
|
|
if (!shared) return error(res, 404, 'This proofing gallery is no longer available');
|
|
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');
|
|
|
|
const entries = [];
|
|
const seen = new Set();
|
|
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;
|
|
try {
|
|
const data = await fsp.readFile(file);
|
|
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);
|
|
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);
|
|
});
|
|
|
|
route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => {
|
|
if (!eventByShareToken(params.token)) {
|
|
return error(res, 404, 'This proofing gallery is no longer available');
|
|
}
|
|
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 (!eventByShareToken(params.token)) {
|
|
return error(res, 404, 'This proofing gallery is no longer available');
|
|
}
|
|
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 (!eventByShareToken(params.token)) {
|
|
return error(res, 404, 'This proofing gallery is no longer available');
|
|
}
|
|
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 });
|
|
});
|
|
|
|
/**
|
|
* 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');
|
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
|
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 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');
|
|
});
|
|
|
|
/**
|
|
* 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');
|
|
});
|
|
|
|
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, 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');
|
|
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 };
|
|
|
|
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 = record.proofAt
|
|
? `/api/photos/${params.id}/thumb?proof=${record.proofAt}`
|
|
: `/api/photos/${params.id}/thumb`;
|
|
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');
|
|
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',
|
|
};
|
|
|
|
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(`[luminary] ${req.method} ${url.pathname} → ${message}`);
|
|
if (!res.headersSent) return error(res, 500, message);
|
|
res.end();
|
|
}
|
|
});
|
|
|
|
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'}`,
|
|
);
|
|
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));
|
|
});
|
|
}
|