0b3ab76405
Immich connections stay server-side with an encrypted API key, albums can be imported, and photos are only sent back when an event's push button is pressed: originals upload once, edited photos re-render, and edits hashes plus checksums skip anything already in Immich. This also lands the accompanying editor, cloud and administration work that was still uncommitted. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
2070 lines
72 KiB
JavaScript
2070 lines
72 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,
|
|
TRUST_PROXY,
|
|
} from './config.mjs';
|
|
import {
|
|
authenticate,
|
|
createSession,
|
|
hashPassword,
|
|
normalizeEmail,
|
|
publicUser,
|
|
spendPasswordCheck,
|
|
validEmail,
|
|
verifyPassword,
|
|
} from './auth.mjs';
|
|
import {
|
|
addGalleryComment,
|
|
commentsByOwner,
|
|
commentsForToken,
|
|
countPhotos,
|
|
eventByShareToken,
|
|
eventOwner,
|
|
galleryPick,
|
|
getPhoto,
|
|
invites,
|
|
kv,
|
|
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,
|
|
originalTarget,
|
|
removeAsset,
|
|
setStorageRoot,
|
|
storageBytes,
|
|
storageRoot,
|
|
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';
|
|
import {
|
|
createImmichAlbumForEvent,
|
|
disconnectImmich,
|
|
disconnectImmichAdmin,
|
|
immichAdminPing,
|
|
immichAdminStatus,
|
|
immichConfigured,
|
|
immichEventQueue,
|
|
immichJobFor,
|
|
immichLinksForOwner,
|
|
immichPendingPhotos,
|
|
immichPing,
|
|
immichStatusFor,
|
|
listImmichAlbums,
|
|
publishImmichOriginal,
|
|
pushImmichPhoto,
|
|
pushImmichPhotoMetadata,
|
|
saveImmichAdminSettings,
|
|
saveImmichUserSettings,
|
|
startImmichImport,
|
|
} from './immich.mjs';
|
|
|
|
const VERSION = '1.0.0';
|
|
const COOKIE = 'lumen_session';
|
|
|
|
/** Self-only policy; must allow the wasm engines and React inline styles. */
|
|
const CSP = [
|
|
"default-src 'self'",
|
|
"script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'",
|
|
"style-src 'self' 'unsafe-inline'",
|
|
"img-src 'self' data: blob:",
|
|
"font-src 'self' data:",
|
|
"connect-src 'self'",
|
|
"media-src 'self' blob:",
|
|
"worker-src 'self' blob:",
|
|
"object-src 'none'",
|
|
"base-uri 'self'",
|
|
"form-action 'self'",
|
|
"frame-ancestors 'self'",
|
|
].join('; ');
|
|
|
|
/* ------------------------------------------------------------------ helpers */
|
|
|
|
function json(res, status, payload, extraHeaders = {}) {
|
|
const body = Buffer.from(JSON.stringify(payload));
|
|
res.writeHead(status, {
|
|
'Content-Type': 'application/json; charset=utf-8',
|
|
'Content-Length': body.length,
|
|
'Cache-Control': 'no-store',
|
|
...extraHeaders,
|
|
});
|
|
res.end(body);
|
|
}
|
|
|
|
class PayloadTooLarge extends Error {}
|
|
|
|
function error(res, status, message, extraHeaders = {}) {
|
|
json(res, status, { error: message }, extraHeaders);
|
|
}
|
|
|
|
/** Failed sign-ins are bucketed per socket address and per account. */
|
|
const AUTH_WINDOW_MS = 15 * 60 * 1000;
|
|
const authBuckets = new Map();
|
|
|
|
function clientIp(req) {
|
|
// X-Forwarded-For is spoofable unless a proxy overwrites it, so it is only
|
|
// consulted when the operator opts in with LUMINARY_TRUST_PROXY=1.
|
|
if (TRUST_PROXY) {
|
|
const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
|
|
if (forwarded) return forwarded;
|
|
}
|
|
return String(req.socket?.remoteAddress ?? 'unknown');
|
|
}
|
|
|
|
/**
|
|
* Per-address cap. Behind a proxy without TRUST_PROXY every client shares the
|
|
* proxy address, so the cap is higher to avoid turning noise into a lock-out;
|
|
* the per-account limit is the real brute-force bound.
|
|
*/
|
|
const LOGIN_IP_LIMIT = TRUST_PROXY ? 50 : 500;
|
|
|
|
function authFailures(key) {
|
|
const bucket = authBuckets.get(key);
|
|
if (!bucket || Date.now() - bucket.start >= AUTH_WINDOW_MS) return 0;
|
|
return bucket.count;
|
|
}
|
|
|
|
function recordAuthFailure(key) {
|
|
const now = Date.now();
|
|
const bucket = authBuckets.get(key);
|
|
if (!bucket || now - bucket.start >= AUTH_WINDOW_MS) {
|
|
authBuckets.set(key, { start: now, count: 1 });
|
|
} else {
|
|
bucket.count += 1;
|
|
}
|
|
if (authBuckets.size > 10_000) {
|
|
for (const [name, value] of authBuckets) {
|
|
if (now - value.start >= AUTH_WINDOW_MS) authBuckets.delete(name);
|
|
}
|
|
}
|
|
}
|
|
|
|
function clearAuthFailures(key) {
|
|
authBuckets.delete(key);
|
|
}
|
|
|
|
/** Coarse fixed-window limiter for public gallery writes. */
|
|
const galleryBuckets = new Map();
|
|
function allowGalleryWrite(req, token) {
|
|
const key = `${clientIp(req)}:${token}`;
|
|
const now = Date.now();
|
|
const bucket = galleryBuckets.get(key);
|
|
if (!bucket || now - bucket.start >= 60_000) {
|
|
galleryBuckets.set(key, { start: now, count: 1 });
|
|
if (galleryBuckets.size > 5_000) {
|
|
for (const [name, value] of galleryBuckets) {
|
|
if (now - value.start >= 60_000) galleryBuckets.delete(name);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
bucket.count += 1;
|
|
return bucket.count <= 120;
|
|
}
|
|
|
|
const PHOTO_MIME_BY_EXT = {
|
|
jpg: 'image/jpeg',
|
|
jpeg: 'image/jpeg',
|
|
png: 'image/png',
|
|
webp: 'image/webp',
|
|
gif: 'image/gif',
|
|
avif: 'image/avif',
|
|
tif: 'image/tiff',
|
|
tiff: 'image/tiff',
|
|
};
|
|
const PHOTO_MIMES = new Set(Object.values(PHOTO_MIME_BY_EXT));
|
|
|
|
/** Only raster types the browser cannot turn into script are served inline. */
|
|
function normalizePhotoMime(value, name = '') {
|
|
const mime = String(value ?? '').split(';')[0].trim().toLowerCase();
|
|
if (PHOTO_MIMES.has(mime)) return mime;
|
|
const ext = String(name).split('.').pop()?.toLowerCase() ?? '';
|
|
return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream';
|
|
}
|
|
|
|
function parseCookies(req) {
|
|
const out = {};
|
|
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
|
const idx = part.indexOf('=');
|
|
if (idx < 0) continue;
|
|
try {
|
|
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
|
|
} catch {
|
|
/* ignore malformed percent-encoding in a cookie */
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function sessionCookie(req, token, maxAge) {
|
|
const secure = req.headers['x-forwarded-proto'] === 'https' ? '; Secure' : '';
|
|
return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* A null owner means the row does not exist yet (new records are allowed).
|
|
* An empty owner is a legacy row from before workspaces; only an admin may
|
|
* touch it. Everyone else may only reach their own rows.
|
|
*/
|
|
function ownedBy(owner, user) {
|
|
if (owner === null || owner === undefined) return true;
|
|
return owner === user.id || (owner === '' && user.role === 'admin');
|
|
}
|
|
|
|
function adminUser(row) {
|
|
return {
|
|
id: row.id,
|
|
email: row.email,
|
|
name: row.name ?? '',
|
|
role: row.role ?? 'member',
|
|
disabled: Boolean(row.disabled),
|
|
createdAt: row.created_at ?? null,
|
|
};
|
|
}
|
|
|
|
function inviteStatus(row, now = Date.now()) {
|
|
if (!row) return 'missing';
|
|
if (row.revoked_at) return 'revoked';
|
|
if (row.accepted_at) return 'accepted';
|
|
if (Number(row.expires_at) <= now) return 'expired';
|
|
return 'pending';
|
|
}
|
|
|
|
function adminInvite(row) {
|
|
return {
|
|
token: row.token,
|
|
email: row.email ?? '',
|
|
role: row.role ?? 'member',
|
|
status: inviteStatus(row),
|
|
createdAt: row.created_at ?? null,
|
|
expiresAt: row.expires_at ?? null,
|
|
acceptedAt: row.accepted_at ?? null,
|
|
acceptedBy: row.accepted_by ?? null,
|
|
revokedAt: row.revoked_at ?? null,
|
|
};
|
|
}
|
|
|
|
/** Accepts either a bare token or a copied /join/<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;
|
|
let tooLarge = false;
|
|
req.on('data', (chunk) => {
|
|
if (tooLarge) return;
|
|
size += chunk.length;
|
|
if (size > limit) {
|
|
tooLarge = true;
|
|
chunks.length = 0;
|
|
// Keep draining instead of destroying the socket so the 413 can flush.
|
|
req.resume();
|
|
reject(new PayloadTooLarge(`Request exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
req.on('error', reject);
|
|
});
|
|
}
|
|
|
|
async function readJson(req, limit = 8 * 1024 * 1024) {
|
|
const raw = await readBody(req, limit);
|
|
if (!raw.length) return {};
|
|
try {
|
|
return JSON.parse(raw.toString('utf8'));
|
|
} catch {
|
|
throw new Error('Request body is not valid JSON');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Streams an upload straight to disk. Buffering the body would let one request
|
|
* hold hundreds of megabytes of RAM.
|
|
*/
|
|
async function receiveUpload(req, target, limit) {
|
|
const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`;
|
|
let size = 0;
|
|
try {
|
|
await new Promise((resolve, reject) => {
|
|
const out = fs.createWriteStream(temp, { flags: 'wx' });
|
|
let settled = false;
|
|
const fail = (err) => {
|
|
if (settled) return;
|
|
settled = true;
|
|
req.unpipe(out);
|
|
out.destroy();
|
|
req.resume();
|
|
fs.rm(temp, { force: true }, () => reject(err));
|
|
};
|
|
req.on('data', (chunk) => {
|
|
if (settled) return;
|
|
size += chunk.length;
|
|
if (size > limit) fail(new PayloadTooLarge('Upload exceeds the size limit'));
|
|
});
|
|
req.on('error', fail);
|
|
out.on('error', fail);
|
|
out.on('finish', () => {
|
|
if (settled) return;
|
|
settled = true;
|
|
resolve();
|
|
});
|
|
req.pipe(out);
|
|
});
|
|
if (!size) {
|
|
await fsp.rm(temp, { force: true });
|
|
return 0;
|
|
}
|
|
await fsp.rename(temp, target);
|
|
return size;
|
|
} catch (err) {
|
|
await fsp.rm(temp, { force: true }).catch(() => undefined);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
function match(pathname, pattern) {
|
|
const p = pattern.split('/');
|
|
const a = pathname.split('/');
|
|
if (p.length !== a.length) return null;
|
|
const params = {};
|
|
for (let i = 0; i < p.length; i++) {
|
|
if (p[i].startsWith(':')) {
|
|
params[p[i].slice(1)] = decodeURIComponent(a[i]);
|
|
} else if (p[i] !== a[i]) {
|
|
return null;
|
|
}
|
|
}
|
|
return params;
|
|
}
|
|
|
|
function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
|
|
res.writeHead(200, {
|
|
'Content-Type': type,
|
|
'Content-Length': data.length,
|
|
'Cache-Control': cache,
|
|
'X-Content-Type-Options': 'nosniff',
|
|
});
|
|
res.end(data);
|
|
}
|
|
|
|
/** The bridge row and source id for a photo imported from the dashboard. */
|
|
function bridgeLinkForPhoto(photoId) {
|
|
const photo = getPhoto(photoId);
|
|
if (!photo?.eventId) return null;
|
|
const bridge = bridgeForEvent(photo.eventId);
|
|
if (!bridge) return null;
|
|
const sourceId = photo.bridgeSource?.sourceId ?? photoId.replace(/^br-/, '');
|
|
return { photo, bridge, sourceId };
|
|
}
|
|
|
|
async function sendFile(req, res, filePath, type, cache = 'private, max-age=86400', extraHeaders = {}) {
|
|
if (!filePath) return error(res, 404, 'Not found');
|
|
try {
|
|
const stat = await fsp.stat(filePath);
|
|
res.writeHead(200, {
|
|
'Content-Type': type,
|
|
'Content-Length': stat.size,
|
|
'Cache-Control': cache,
|
|
'X-Content-Type-Options': 'nosniff',
|
|
...extraHeaders,
|
|
});
|
|
if (req.method === 'HEAD') return res.end();
|
|
fs.createReadStream(filePath).pipe(res);
|
|
} catch {
|
|
error(res, 404, 'Not found');
|
|
}
|
|
}
|
|
|
|
function decodeDataUrl(value) {
|
|
if (typeof value !== 'string') return null;
|
|
const m = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=\s]+)$/.exec(value);
|
|
if (!m) return null;
|
|
return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') };
|
|
}
|
|
|
|
/** Health totals walk the filesystem, so cache them instead of scanning per hit. */
|
|
let healthCache = { at: 0, photos: 0, bytes: 0, root: '', custom: false };
|
|
function healthStats() {
|
|
if (Date.now() - healthCache.at < 30_000) return healthCache;
|
|
healthCache = {
|
|
at: Date.now(),
|
|
photos: countPhotos(),
|
|
bytes: storageBytes(),
|
|
root: storageRoot(),
|
|
custom: isCustomRoot(),
|
|
};
|
|
return healthCache;
|
|
}
|
|
|
|
const MAX_ARCHIVE_FILES = 400;
|
|
const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
|
|
let archiveBuilding = false;
|
|
|
|
/** Uploads accepted for an id that does not have a photo row yet. */
|
|
const recentUploads = new Map();
|
|
|
|
function pendingBytes(ownerId) {
|
|
let total = 0;
|
|
for (const upload of recentUploads.values()) {
|
|
if (upload.pending && upload.ownerId === ownerId) total += upload.bytes;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- api */
|
|
|
|
import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs';
|
|
|
|
const routes = [];
|
|
function route(method, pattern, handler) {
|
|
routes.push({ method, pattern, handler });
|
|
}
|
|
|
|
route('GET', '/api/health', async ({ req, res }) => {
|
|
const raw = await rawSupport();
|
|
const user = currentUser(req);
|
|
const stats = healthStats();
|
|
json(res, 200, {
|
|
ok: true,
|
|
app: 'luminary',
|
|
version: VERSION,
|
|
needsSetup: users.count() === 0,
|
|
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
|
photos: stats.photos,
|
|
bytes: stats.bytes,
|
|
// The absolute data path is only for signed-in team members.
|
|
...(user ? { storage: { root: stats.root, custom: stats.custom } } : {}),
|
|
raw,
|
|
});
|
|
});
|
|
|
|
route('POST', '/api/auth/register', async ({ req, res }) => {
|
|
const body = await readJson(req, 64 * 1024);
|
|
const email = normalizeEmail(body.email);
|
|
const password = typeof body.password === 'string' ? body.password : '';
|
|
const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : '';
|
|
if (!validEmail(email)) return error(res, 400, 'Enter a valid email address');
|
|
if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password');
|
|
if (users.byEmail(email)) return error(res, 409, 'That email is already registered');
|
|
|
|
const first = users.count() === 0;
|
|
const sharedCode = typeof body.invite === 'string' ? body.invite.trim() : '';
|
|
const token = inviteTokenFrom(body.inviteToken) || inviteTokenFrom(sharedCode);
|
|
let inviteRow = token ? invites.byToken(token) : null;
|
|
|
|
if (!first) {
|
|
if (inviteRow) {
|
|
const status = inviteStatus(inviteRow);
|
|
if (status === 'accepted') return error(res, 409, 'This invite has already been used');
|
|
if (status === 'revoked') return error(res, 403, 'This invite link was turned off by an admin');
|
|
if (status === 'expired') return error(res, 403, 'This invite link has expired. Ask an admin for a new one');
|
|
if (inviteRow.email && normalizeEmail(inviteRow.email) !== email) {
|
|
return error(res, 403, 'This invite was created for a different email address');
|
|
}
|
|
} else if (sharedCode && INVITE && sharedCode === INVITE) {
|
|
/* the long-lived shared code still works alongside personal links */
|
|
} else if (token) {
|
|
return error(res, 403, 'This invite link is not valid');
|
|
} else if (!INVITE) {
|
|
return error(res, 403, 'Registration is closed. Use the invite link an admin sent you.');
|
|
} else if (sharedCode !== INVITE) {
|
|
return error(res, 403, 'Invite code is not correct');
|
|
}
|
|
}
|
|
|
|
const id = crypto.randomUUID();
|
|
users.create({
|
|
id,
|
|
email,
|
|
name: name || email.split('@')[0],
|
|
passHash: await hashPassword(password),
|
|
role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member',
|
|
});
|
|
if (inviteRow && !invites.accept(token, id)) {
|
|
users.remove(id);
|
|
return error(res, 409, 'This invite has already been used');
|
|
}
|
|
const session = createSession(id);
|
|
json(
|
|
res,
|
|
201,
|
|
{ token: session, user: publicUser(users.byId(id)) },
|
|
{ 'Set-Cookie': sessionCookie(req, session, 30 * 24 * 3600) },
|
|
);
|
|
});
|
|
|
|
route('POST', '/api/auth/login', async ({ req, res }) => {
|
|
const ipKey = `login:ip:${clientIp(req)}`;
|
|
if (authFailures(ipKey) >= LOGIN_IP_LIMIT) {
|
|
return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' });
|
|
}
|
|
|
|
const body = await readJson(req, 64 * 1024);
|
|
const email = normalizeEmail(body.email);
|
|
const password = typeof body.password === 'string' ? body.password : '';
|
|
const accountKey = `login:acct:${clientIp(req)}:${email}`;
|
|
if (authFailures(accountKey) >= 8) {
|
|
return error(res, 429, 'Too many sign-in attempts for this account. Try again later.', {
|
|
'Retry-After': '900',
|
|
});
|
|
}
|
|
|
|
const row = users.byEmail(email);
|
|
if (!row) {
|
|
// Spend the same scrypt work as a real account so response timing does not
|
|
// reveal which addresses are registered.
|
|
await spendPasswordCheck(password);
|
|
recordAuthFailure(ipKey);
|
|
recordAuthFailure(accountKey);
|
|
return error(res, 401, 'Email or password is not correct');
|
|
}
|
|
|
|
const valid = await verifyPassword(password, row.pass_hash);
|
|
if (!valid) {
|
|
recordAuthFailure(ipKey);
|
|
recordAuthFailure(accountKey);
|
|
return error(res, 401, 'Email or password is not correct');
|
|
}
|
|
clearAuthFailures(accountKey);
|
|
if (row.disabled) return error(res, 403, 'This account has been disabled by an administrator');
|
|
const token = createSession(row.id);
|
|
json(
|
|
res,
|
|
200,
|
|
{ token, user: publicUser(users.byId(row.id)) },
|
|
{ 'Set-Cookie': sessionCookie(req, token, 30 * 24 * 3600) },
|
|
);
|
|
});
|
|
|
|
route('POST', '/api/auth/logout', async ({ req, res }) => {
|
|
const token = parseCookies(req)[COOKIE];
|
|
if (token) sessions.destroy(token);
|
|
json(res, 200, { ok: true }, { 'Set-Cookie': `${COOKIE}=; Path=/; HttpOnly; Max-Age=0` });
|
|
});
|
|
|
|
route('GET', '/api/auth/me', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
json(res, 200, { user });
|
|
});
|
|
|
|
/* Public invite lookup for /join/<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(),
|
|
immich: immichAdminStatus(),
|
|
});
|
|
});
|
|
|
|
route('POST', '/api/admin/users', async ({ req, res }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const body = await readJson(req, 64 * 1024);
|
|
const email = normalizeEmail(body.email);
|
|
const password = typeof body.password === 'string' ? body.password : '';
|
|
const name = typeof body.name === 'string' ? body.name.trim().slice(0, 80) : '';
|
|
const role = body.role === 'admin' ? 'admin' : 'member';
|
|
if (!validEmail(email)) return error(res, 400, 'Enter a valid email address');
|
|
if (password.length < 8) return error(res, 400, 'Use at least 8 characters for the password');
|
|
if (users.byEmail(email)) return error(res, 409, 'That email is already registered');
|
|
|
|
const id = crypto.randomUUID();
|
|
users.create({
|
|
id,
|
|
email,
|
|
name: name || email.split('@')[0],
|
|
passHash: await hashPassword(password),
|
|
role,
|
|
});
|
|
json(res, 201, { user: adminUser(users.byId(id)) });
|
|
});
|
|
|
|
route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => {
|
|
const admin = requireAdmin(req, res);
|
|
if (!admin) return;
|
|
const target = users.byId(params.id);
|
|
if (!target) return error(res, 404, 'No such account');
|
|
|
|
const body = await readJson(req, 64 * 1024);
|
|
const patch = {};
|
|
if (typeof body.name === 'string') patch.name = body.name.trim().slice(0, 80);
|
|
|
|
if (typeof body.password === 'string' && body.password) {
|
|
if (body.password.length < 8) return error(res, 400, 'Use at least 8 characters for the password');
|
|
patch.passHash = await hashPassword(body.password);
|
|
}
|
|
|
|
if (typeof body.role === 'string') {
|
|
if (body.role !== 'admin' && body.role !== 'member') {
|
|
return error(res, 400, 'Role must be admin or member');
|
|
}
|
|
if (params.id === admin.id && body.role !== 'admin') {
|
|
return error(res, 400, 'You cannot remove your own administrator access');
|
|
}
|
|
if (target.role === 'admin' && body.role !== 'admin' && users.activeAdmins() <= 1) {
|
|
return error(res, 400, 'Keep at least one active administrator');
|
|
}
|
|
patch.role = body.role;
|
|
}
|
|
|
|
if (typeof body.disabled === 'boolean') {
|
|
if (params.id === admin.id && body.disabled) {
|
|
return error(res, 400, 'You cannot disable your own account');
|
|
}
|
|
if (target.role === 'admin' && body.disabled && users.activeAdmins() <= 1) {
|
|
return error(res, 400, 'Keep at least one active administrator');
|
|
}
|
|
patch.disabled = body.disabled;
|
|
}
|
|
|
|
const updated = users.update(params.id, patch);
|
|
if (patch.disabled || patch.passHash) sessions.destroyForUser(params.id);
|
|
json(res, 200, { user: adminUser(updated) });
|
|
});
|
|
|
|
route('POST', '/api/admin/invites', async ({ req, res }) => {
|
|
const admin = requireAdmin(req, res);
|
|
if (!admin) return;
|
|
const body = await readJson(req, 64 * 1024);
|
|
const email = normalizeEmail(body.email);
|
|
if (email && !validEmail(email)) return error(res, 400, 'Enter a valid email address');
|
|
const role = body.role === 'admin' ? 'admin' : 'member';
|
|
const days = Math.min(30, Math.max(1, Number(body.days) || 7));
|
|
const token = crypto.randomBytes(24).toString('base64url');
|
|
invites.create({
|
|
token,
|
|
email,
|
|
role,
|
|
createdBy: admin.id,
|
|
expiresAt: Date.now() + days * 24 * 60 * 60 * 1000,
|
|
});
|
|
json(res, 201, { invite: adminInvite(invites.byToken(token)) });
|
|
});
|
|
|
|
route('DELETE', '/api/admin/invites/:token', async ({ req, res, params }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const row = invites.byToken(params.token);
|
|
if (!row) return error(res, 404, 'No such invite');
|
|
if (row.accepted_at) return error(res, 400, 'That invite has already been used');
|
|
invites.revoke(params.token);
|
|
json(res, 200, { ok: true });
|
|
});
|
|
|
|
route('DELETE', '/api/admin/users/:id', async ({ req, res, params }) => {
|
|
const admin = requireAdmin(req, res);
|
|
if (!admin) return;
|
|
if (params.id === admin.id) return error(res, 400, 'You cannot delete your own account');
|
|
const target = users.byId(params.id);
|
|
if (!target) return error(res, 404, 'No such account');
|
|
if (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/admin/immich', async ({ req, res }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
json(res, 200, { immich: immichAdminStatus() });
|
|
});
|
|
|
|
route('PUT', '/api/admin/immich', async ({ req, res }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
const body = await readJson(req, 16 * 1024);
|
|
try {
|
|
json(res, 200, { immich: saveImmichAdminSettings(body) });
|
|
} catch (err) {
|
|
return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection');
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/admin/immich/test', async ({ req, res }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
try {
|
|
json(res, 200, await immichAdminPing());
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
|
}
|
|
});
|
|
|
|
route('DELETE', '/api/admin/immich', async ({ req, res }) => {
|
|
if (!requireAdmin(req, res)) return;
|
|
json(res, 200, { immich: disconnectImmichAdmin() });
|
|
});
|
|
|
|
/* ------------------------------------------------------------------ immich */
|
|
|
|
route('GET', '/api/immich', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
json(res, 200, { immich: immichStatusFor(user.id) });
|
|
});
|
|
|
|
route('PUT', '/api/immich', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
const body = await readJson(req, 16 * 1024);
|
|
try {
|
|
json(res, 200, { immich: saveImmichUserSettings(user.id, body) });
|
|
} catch (err) {
|
|
return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection');
|
|
}
|
|
});
|
|
|
|
route('DELETE', '/api/immich', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
json(res, 200, { immich: disconnectImmich(user.id) });
|
|
});
|
|
|
|
route('POST', '/api/immich/test', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
try {
|
|
json(res, 200, await immichPing(user.id));
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
|
}
|
|
});
|
|
|
|
/** Albums are listed for any signed-in user; the API key still stays server-side. */
|
|
route('GET', '/api/immich/albums', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!immichConfigured(user.id)) return error(res, 503, 'Immich is not configured yet');
|
|
try {
|
|
const links = new Map(immichLinksForOwner(user.id).map((link) => [link.albumId, link]));
|
|
const albums = await listImmichAlbums(user.id);
|
|
json(res, 200, {
|
|
albums: albums.map((album) => ({
|
|
...album,
|
|
eventId: links.get(album.id)?.eventId ?? null,
|
|
lastSyncAt: links.get(album.id)?.lastSyncAt ?? null,
|
|
kind: links.get(album.id)?.kind ?? 'import',
|
|
})),
|
|
});
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich');
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/immich/albums', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
const body = await readJson(req, 16 * 1024);
|
|
if (typeof body.eventId !== 'string' || !body.eventId) {
|
|
return error(res, 400, 'Choose the event for the gallery');
|
|
}
|
|
if (!ownedBy(eventOwner(body.eventId), user)) return error(res, 404, 'No such event');
|
|
try {
|
|
json(res, 201, await createImmichAlbumForEvent({
|
|
ownerId: user.id,
|
|
eventId: body.eventId,
|
|
name: body.name,
|
|
}));
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not create the Immich gallery');
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/immich/albums/:id/import', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
try {
|
|
json(res, 202, { job: startImmichImport({ albumId: params.id, ownerId: user.id }) });
|
|
} catch (err) {
|
|
return error(res, 400, err instanceof Error ? err.message : 'Could not start the import');
|
|
}
|
|
});
|
|
|
|
route('GET', '/api/immich/jobs/:id', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
const job = immichJobFor(params.id, user);
|
|
if (!job) return error(res, 404, 'Import job not found');
|
|
json(res, 200, { job });
|
|
});
|
|
|
|
route('POST', '/api/immich/photos/:id/metadata', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
|
|
|
const body = await readJson(req, 64 * 1024);
|
|
const rating = Math.max(0, Math.min(5, Math.trunc(Number(body.rating) || 0)));
|
|
const flag = body.flag === 'pick' || body.flag === 'reject' ? body.flag : 'none';
|
|
const keywords = Array.isArray(body.keywords)
|
|
? body.keywords.filter((word) => typeof word === 'string').slice(0, 100)
|
|
: [];
|
|
try {
|
|
json(res, 200, await pushImmichPhotoMetadata({
|
|
photoId: params.id,
|
|
ownerId: user.id,
|
|
local: { rating, flag, keywords },
|
|
}));
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not sync Immich metadata');
|
|
}
|
|
});
|
|
|
|
/** Photo ids still missing from an event's gallery, for a backfill run. */
|
|
route('GET', '/api/immich/events/:id/pending', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
|
try {
|
|
json(res, 200, immichPendingPhotos({ eventId: params.id, ownerId: user.id }));
|
|
} catch (err) {
|
|
return error(res, 400, err instanceof Error ? err.message : 'Could not read the Immich queue');
|
|
}
|
|
});
|
|
|
|
/**
|
|
* The manual push plan for an event: originals Immich has never seen plus the
|
|
* edits that changed since the last push. Nothing uploads from this route.
|
|
*/
|
|
route('GET', '/api/immich/events/:id/queue', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
|
try {
|
|
json(res, 200, immichEventQueue({ eventId: params.id, ownerId: user.id }));
|
|
} catch (err) {
|
|
return error(res, 400, err instanceof Error ? err.message : 'Could not plan the Immich push');
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/immich/photos/:id/publish', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
|
try {
|
|
json(res, 200, await publishImmichOriginal({ photoId: params.id, ownerId: user.id }));
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not publish the photo');
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/immich/photos/:id/push', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
|
|
|
const body = await readJson(req, 96 * 1024 * 1024);
|
|
if (typeof body.jpeg !== 'string' || !body.jpeg) {
|
|
return error(res, 400, 'A rendered JPEG is required');
|
|
}
|
|
const jpeg = Buffer.from(body.jpeg, 'base64');
|
|
if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
|
|
return error(res, 400, 'The edited file is not a JPEG image');
|
|
}
|
|
try {
|
|
json(res, 200, await pushImmichPhoto({ photoId: params.id, ownerId: user.id, jpeg }));
|
|
} catch (err) {
|
|
return error(res, 502, err instanceof Error ? err.message : 'Could not send the edit to Immich');
|
|
}
|
|
});
|
|
|
|
route('GET', '/api/bridge/login', async ({ req, res, url }) => {
|
|
if (!bridgeConfigured()) {
|
|
return error(res, 503, 'The advanced editor bridge is not configured');
|
|
}
|
|
const token = url.searchParams.get('token') || '';
|
|
const payload = verifyBridgeToken(token);
|
|
if (!payload || payload.kind !== 'login') {
|
|
return error(res, 401, 'This advanced-editor link is invalid or has expired');
|
|
}
|
|
|
|
try {
|
|
const service = await exchangeBridgeToken(token, payload.sid);
|
|
const email = normalizeEmail(payload.email);
|
|
if (!validEmail(email)) {
|
|
return error(res, 400, 'The dashboard account has no usable email address');
|
|
}
|
|
|
|
let row = users.byEmail(email);
|
|
if (!row) {
|
|
const id = crypto.randomUUID();
|
|
users.create({
|
|
id,
|
|
email,
|
|
name: payload.name || email.split('@')[0],
|
|
passHash: await hashPassword(crypto.randomBytes(24).toString('hex')),
|
|
role: 'member',
|
|
});
|
|
row = users.byId(id);
|
|
}
|
|
|
|
purgeExpiredBridges();
|
|
const imported = await importBridgeEvent({
|
|
serviceToken: service.token,
|
|
sessionId: payload.sid,
|
|
ownerId: row.id,
|
|
});
|
|
const sessionToken = createSession(row.id);
|
|
res.writeHead(302, {
|
|
Location: `/?bridge=${encodeURIComponent(imported.eventId)}`,
|
|
'Set-Cookie': sessionCookie(req, sessionToken, 30 * 24 * 3600),
|
|
'Cache-Control': 'no-store',
|
|
});
|
|
res.end();
|
|
} catch (err) {
|
|
return error(
|
|
res,
|
|
502,
|
|
err instanceof Error ? err.message : 'Could not open the advanced editor',
|
|
);
|
|
}
|
|
});
|
|
|
|
/** Client proofing picks, rolled up per photo for the owner's library. */
|
|
function ownerProofs(ownerId) {
|
|
const proofs = new Map();
|
|
const ensure = (photoId, eventId) => {
|
|
const entry = proofs.get(photoId) ?? {
|
|
photoId,
|
|
eventId,
|
|
count: 0,
|
|
clients: [],
|
|
comments: 0,
|
|
approved: 0,
|
|
changes: 0,
|
|
};
|
|
proofs.set(photoId, entry);
|
|
return entry;
|
|
};
|
|
for (const pick of picksByOwner(ownerId)) {
|
|
if (!pick.picked) continue;
|
|
const entry = ensure(pick.photoId, pick.eventId);
|
|
entry.count += 1;
|
|
entry.clients.push(pick.clientName || 'Client');
|
|
}
|
|
for (const comment of commentsByOwner(ownerId)) {
|
|
ensure(comment.photoId, comment.eventId).comments += 1;
|
|
}
|
|
for (const review of reviewsByOwner(ownerId)) {
|
|
const entry = ensure(review.photoId, review.eventId);
|
|
if (review.status === 'approved') entry.approved += 1;
|
|
else if (review.status === 'changes') entry.changes += 1;
|
|
if (review.clientName) entry.clients.push(review.clientName);
|
|
}
|
|
return [...proofs.values()].map((entry) => ({
|
|
...entry,
|
|
clients: [...new Set(entry.clients)],
|
|
}));
|
|
}
|
|
|
|
route('GET', '/api/proofs', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
json(res, 200, { proofs: ownerProofs(user.id) });
|
|
});
|
|
|
|
route('GET', '/api/sync', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
json(res, 200, {
|
|
user,
|
|
events: listEvents(user.id),
|
|
photos: listPhotos(user.id),
|
|
presets: kv.get('presets') ?? [],
|
|
proofs: ownerProofs(user.id),
|
|
});
|
|
});
|
|
|
|
/* -------------------------------------------------------------- proofing */
|
|
|
|
/** Token-protected lookup: the photo must belong to the shared event. */
|
|
function galleryPhoto(token, photoId) {
|
|
const shared = eventByShareToken(token);
|
|
if (!shared) return null;
|
|
const photo = getPhoto(photoId);
|
|
if (!photo || photo.eventId !== shared.id || photo.deletedAt) return null;
|
|
return { shared, photo };
|
|
}
|
|
|
|
route('GET', '/api/events/:id/share', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event');
|
|
const token = shareTokenFor(params.id);
|
|
const feedback = token
|
|
? [
|
|
...commentsForToken(token).map((comment) => ({
|
|
kind: 'comment',
|
|
photoId: comment.photoId,
|
|
clientName: comment.clientName,
|
|
body: comment.body,
|
|
createdAt: comment.createdAt,
|
|
})),
|
|
...reviewsForToken(token)
|
|
.filter((review) => review.status === 'approved' || review.status === 'changes')
|
|
.map((review) => ({
|
|
kind: review.status === 'approved' ? 'approved' : 'changes',
|
|
photoId: review.photoId,
|
|
clientName: review.clientName,
|
|
createdAt: review.updatedAt,
|
|
})),
|
|
].sort((a, b) => b.createdAt - a.createdAt)
|
|
: [];
|
|
json(res, 200, {
|
|
token,
|
|
picks: token
|
|
? picksForToken(token)
|
|
.filter((p) => p.picked)
|
|
.map((p) => ({ photoId: p.photoId, clientName: p.clientName }))
|
|
: [],
|
|
feedback,
|
|
});
|
|
});
|
|
|
|
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);
|
|
if (!file) return error(res, 404, 'Not found');
|
|
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
|
return sendFile(
|
|
req,
|
|
res,
|
|
file,
|
|
mime,
|
|
'private, max-age=3600',
|
|
mime === 'application/octet-stream' ? { 'Content-Disposition': 'attachment' } : {},
|
|
);
|
|
});
|
|
|
|
/** Client download of the edited proof, named like the delivered file. */
|
|
route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => {
|
|
const hit = galleryPhoto(params.token, params.id);
|
|
if (!hit) return error(res, 404, 'Not found');
|
|
const proof = findProof(params.id);
|
|
const file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
|
const originalName = String(hit.photo.name || 'photo.jpg');
|
|
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
|
const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name);
|
|
return sendFile(req, res, file, mime, 'private, max-age=3600', {
|
|
'Content-Disposition': `attachment; filename="${safe}"`,
|
|
});
|
|
});
|
|
|
|
/** Download the client's favourites as one ZIP. */
|
|
route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, url }) => {
|
|
const 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');
|
|
if (archiveBuilding) {
|
|
return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', {
|
|
'Retry-After': '30',
|
|
});
|
|
}
|
|
|
|
archiveBuilding = true;
|
|
try {
|
|
const entries = [];
|
|
const seen = new Set();
|
|
let totalBytes = 0;
|
|
for (const pick of picks) {
|
|
if (seen.has(pick.photoId)) continue;
|
|
seen.add(pick.photoId);
|
|
const photo = getPhoto(pick.photoId);
|
|
if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue;
|
|
const proof = findProof(photo.id);
|
|
const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id);
|
|
if (!file) continue;
|
|
if (entries.length >= MAX_ARCHIVE_FILES) {
|
|
return error(res, 413, 'Too many favourites for one archive. Download in smaller batches.');
|
|
}
|
|
try {
|
|
const stat = await fsp.stat(file);
|
|
if (totalBytes + stat.size > MAX_ARCHIVE_BYTES) {
|
|
return error(
|
|
res,
|
|
413,
|
|
'This selection is too large for one archive. Download in smaller batches.',
|
|
);
|
|
}
|
|
const data = await fsp.readFile(file);
|
|
totalBytes += data.length;
|
|
const originalName = String(photo.name || 'photo.jpg');
|
|
const name = proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName;
|
|
entries.push({ name, data });
|
|
} catch {
|
|
/* skip an unreadable file rather than losing the whole archive */
|
|
}
|
|
}
|
|
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
|
|
|
|
const archive = createZip(entries);
|
|
const eventName = String(shared.event.name || 'proofing')
|
|
.replace(/[^a-z0-9._ -]+/gi, '-')
|
|
.trim() || 'proofing';
|
|
res.writeHead(200, {
|
|
'Content-Type': 'application/zip',
|
|
'Content-Length': archive.length,
|
|
'Cache-Control': 'no-store',
|
|
'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`,
|
|
});
|
|
res.end(archive);
|
|
} finally {
|
|
archiveBuilding = false;
|
|
}
|
|
});
|
|
|
|
route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => {
|
|
if (!allowGalleryWrite(req, params.token)) {
|
|
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
|
}
|
|
if (!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 (!allowGalleryWrite(req, params.token)) {
|
|
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
|
}
|
|
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 (!allowGalleryWrite(req, params.token)) {
|
|
return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' });
|
|
}
|
|
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');
|
|
const owner = photoOwner(params.id);
|
|
if (owner !== null && !ownedBy(owner, user)) return error(res, 404, 'No such photo');
|
|
|
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
const name = url.searchParams.get('name') || 'upload';
|
|
const drop = url.searchParams.get('drop') === '1';
|
|
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
|
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
|
const raw = isRawName(name) || drop;
|
|
|
|
// New ids are part of the normal import flow: the client uploads bytes first
|
|
// and PUTs the record afterwards. Until that row exists the bytes are charged
|
|
// to this user's quota, so nobody can fill the disk with unclaimed files.
|
|
const limit = owner
|
|
? MAX_UPLOAD
|
|
: Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id)));
|
|
if (limit < 1) {
|
|
return error(res, 413, 'This account has no storage quota left for a new upload');
|
|
}
|
|
const announced = Number(req.headers['content-length']);
|
|
if (Number.isFinite(announced) && announced > limit) {
|
|
return error(
|
|
res,
|
|
413,
|
|
owner
|
|
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
|
: 'This upload does not fit in the remaining storage quota',
|
|
);
|
|
}
|
|
|
|
// Reserve the announced size synchronously: otherwise two parallel uploads
|
|
// could each pass the same remaining-quota check before either writes.
|
|
if (owner === null) {
|
|
recentUploads.set(params.id, {
|
|
ownerId: user.id,
|
|
bytes: Number.isFinite(announced) && announced > 0 ? announced : limit,
|
|
at: Date.now(),
|
|
pending: true,
|
|
});
|
|
}
|
|
|
|
const target = originalTarget(params.id, ext);
|
|
const previous = findOriginal(params.id);
|
|
if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined);
|
|
|
|
let size = 0;
|
|
try {
|
|
size = await receiveUpload(req, target, limit);
|
|
} catch (err) {
|
|
if (owner === null) recentUploads.delete(params.id);
|
|
if (err instanceof PayloadTooLarge) {
|
|
return error(
|
|
res,
|
|
413,
|
|
owner
|
|
? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit`
|
|
: 'This upload does not fit in the remaining storage quota',
|
|
);
|
|
}
|
|
throw err;
|
|
}
|
|
if (!size) {
|
|
if (owner === null) recentUploads.delete(params.id);
|
|
return error(res, 400, 'Empty upload');
|
|
}
|
|
|
|
recentUploads.set(params.id, {
|
|
ownerId: user.id,
|
|
bytes: size,
|
|
at: Date.now(),
|
|
pending: owner === null,
|
|
});
|
|
|
|
if (raw) {
|
|
try {
|
|
const data = await fsp.readFile(target);
|
|
const decoded = 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) {
|
|
recentUploads.delete(params.id);
|
|
await removeAsset(params.id).catch(() => undefined);
|
|
return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file');
|
|
}
|
|
}
|
|
|
|
return json(res, 201, { raw: false, mime, size });
|
|
});
|
|
|
|
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, normalizePhotoMime(linked.photo.mime, linked.photo.name));
|
|
});
|
|
|
|
route('POST', '/api/bridge/export', async ({ req, res }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
|
|
const body = await readJson(req, 64 * 1024 * 1024);
|
|
if (typeof body.photoId !== 'string' || typeof body.jpeg !== 'string') {
|
|
return error(res, 400, 'A photo id and a rendered JPEG are required');
|
|
}
|
|
|
|
const linked = bridgeLinkForPhoto(body.photoId);
|
|
if (!linked) return error(res, 404, 'This photo is not part of an advanced edit');
|
|
if (!ownedBy(photoOwner(body.photoId), user)) return error(res, 404, 'This photo is not part of an advanced edit');
|
|
|
|
const result = await forwardBridgeRender(linked.bridge, linked.sourceId, {
|
|
jpeg: body.jpeg,
|
|
edits: body.edits ?? {},
|
|
});
|
|
if (result.status >= 400) {
|
|
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event');
|
|
}
|
|
return json(res, 200, result.body ?? { ok: true });
|
|
});
|
|
|
|
route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
|
const user = currentUser(req);
|
|
if (!user) return error(res, 401, 'Not signed in');
|
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
|
const body = await readJson(req);
|
|
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
|
|
const record = { ...body, id: params.id };
|
|
|
|
// Quota accounting uses bytes the server actually received, not the client's
|
|
// claim, for an upload that just finished.
|
|
const upload = recentUploads.get(params.id);
|
|
if (upload && upload.ownerId === user.id) {
|
|
record.size = upload.bytes;
|
|
recentUploads.delete(params.id);
|
|
}
|
|
record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name);
|
|
|
|
const thumb = decodeDataUrl(record.thumb);
|
|
if (thumb) {
|
|
await writeThumb(params.id, thumb.data);
|
|
delete record.thumb;
|
|
}
|
|
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');
|
|
recentUploads.delete(params.id);
|
|
removePhoto(params.id);
|
|
clearDenoised(params.id);
|
|
await removeAsset(params.id);
|
|
json(res, 200, { ok: true });
|
|
});
|
|
|
|
/* ---------------------------------------------------------------- static ui */
|
|
|
|
const MIME = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.json': 'application/json; charset=utf-8',
|
|
'.svg': 'image/svg+xml',
|
|
'.png': 'image/png',
|
|
'.pdf': 'application/pdf',
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.webp': 'image/webp',
|
|
'.ico': 'image/x-icon',
|
|
'.woff2': 'font/woff2',
|
|
'.map': 'application/json; charset=utf-8',
|
|
};
|
|
|
|
async function serveStatic(req, res, url) {
|
|
let pathname;
|
|
try {
|
|
pathname = decodeURIComponent(url.pathname);
|
|
} catch {
|
|
return error(res, 400, 'Bad request');
|
|
}
|
|
if (pathname.includes('\0')) return error(res, 400, 'Bad request');
|
|
// path.relative, not startsWith: a sibling such as /srv/dist-private shares
|
|
// the dist prefix and would otherwise pass a bare prefix check.
|
|
const candidate = path.resolve(path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname));
|
|
const relative = path.relative(DIST_DIR, candidate);
|
|
if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
|
|
try {
|
|
const stat = await fsp.stat(candidate);
|
|
if (stat.isFile()) {
|
|
const ext = path.extname(candidate).toLowerCase();
|
|
const immutable = pathname.startsWith('/assets/');
|
|
return sendFile(
|
|
req,
|
|
res,
|
|
candidate,
|
|
MIME[ext] ?? 'application/octet-stream',
|
|
immutable ? 'public, max-age=31536000, immutable' : 'no-cache',
|
|
);
|
|
}
|
|
} catch {
|
|
/* fall through to the SPA entry */
|
|
}
|
|
}
|
|
const index = path.join(DIST_DIR, 'index.html');
|
|
if (!fs.existsSync(index)) {
|
|
return error(
|
|
res,
|
|
503,
|
|
'The web build is missing. Run "npm run build" (or use "npm run dev" with the Vite dev server).',
|
|
);
|
|
}
|
|
return sendFile(req, res, index, MIME['.html'], 'no-cache');
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ server */
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
|
|
res.setHeader('Content-Security-Policy', CSP);
|
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
|
res.setHeader('Referrer-Policy', 'same-origin');
|
|
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');
|
|
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
|
if (String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() === 'https') {
|
|
res.setHeader('Strict-Transport-Security', 'max-age=15552000');
|
|
}
|
|
try {
|
|
if (url.pathname.startsWith('/api/')) {
|
|
for (const r of routes) {
|
|
if (r.method !== req.method) continue;
|
|
const params = match(url.pathname, r.pattern);
|
|
if (!params) continue;
|
|
return await r.handler({ req, res, params, url });
|
|
}
|
|
return error(res, 404, `No route for ${req.method} ${url.pathname}`);
|
|
}
|
|
return await serveStatic(req, res, url);
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : 'Unexpected error';
|
|
console.error(`[luminary] ${req.method} ${url.pathname} → ${message}`);
|
|
if (!res.headersSent) {
|
|
if (err instanceof PayloadTooLarge) return error(res, 413, message);
|
|
// Do not leak internals from an unexpected failure.
|
|
return error(res, 500, 'Unexpected server error');
|
|
}
|
|
res.end();
|
|
}
|
|
});
|
|
|
|
/** Drop uploads that were streamed to disk but never became a photo record. */
|
|
async function sweepStaleUploads() {
|
|
const cutoff = Date.now() - 60 * 60 * 1000;
|
|
for (const [id, upload] of recentUploads) {
|
|
if (upload.at > cutoff) continue;
|
|
recentUploads.delete(id);
|
|
if (!getPhoto(id)) await removeAsset(id).catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
/** Remove pre-upgrade orphans: originals with no catalog row, older than a day. */
|
|
async function sweepOrphanOriginals() {
|
|
const dir = path.join(storageRoot(), 'originals');
|
|
const names = await fsp.readdir(dir).catch(() => []);
|
|
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
|
for (const name of names) {
|
|
const id = name.replace(/\.[^.]+$/, '');
|
|
if (/^[A-Za-z0-9_-]{1,80}$/.test(id) && getPhoto(id)) continue;
|
|
const file = path.join(dir, name);
|
|
const stat = await fsp.stat(file).catch(() => null);
|
|
if (stat && stat.mtimeMs < cutoff) await fsp.rm(file, { force: true }).catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
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)');
|
|
});
|
|
|
|
setInterval(() => {
|
|
void sweepStaleUploads().catch((err) =>
|
|
console.error(`[luminary] upload sweep: ${err.message}`),
|
|
);
|
|
}, 10 * 60 * 1000).unref?.();
|
|
|
|
void sweepOrphanOriginals().catch((err) =>
|
|
console.error(`[luminary] orphan sweep: ${err.message}`),
|
|
);
|
|
|
|
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
process.on(signal, () => {
|
|
server.close(() => process.exit(0));
|
|
});
|
|
}
|