Add the optional Immich integration and manual gallery push

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>
This commit is contained in:
2026-11-25 17:43:05 +00:00
parent e0c76ba965
commit 0b3ab76405
26 changed files with 4323 additions and 144 deletions
+683 -67
View File
@@ -11,6 +11,7 @@ import {
MAX_UPLOAD,
PORT,
RAW_PREVIEW_EDGE,
TRUST_PROXY,
} from './config.mjs';
import {
authenticate,
@@ -18,6 +19,7 @@ import {
hashPassword,
normalizeEmail,
publicUser,
spendPasswordCheck,
validEmail,
verifyPassword,
} from './auth.mjs';
@@ -58,11 +60,11 @@ import {
findProofThumb,
findThumb,
isCustomRoot,
originalTarget,
removeAsset,
setStorageRoot,
storageBytes,
storageRoot,
writeOriginal,
writePreview,
writeProof,
writeProofThumb,
@@ -91,10 +93,47 @@ import {
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 = {}) {
@@ -108,8 +147,95 @@ function json(res, status, payload, extraHeaders = {}) {
res.end(body);
}
function error(res, status, message) {
json(res, status, { error: message });
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) {
@@ -117,7 +243,11 @@ function parseCookies(req) {
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());
try {
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
} catch {
/* ignore malformed percent-encoding in a cookie */
}
}
return out;
}
@@ -152,9 +282,14 @@ function requireAdmin(req, res) {
return user;
}
/** An ownerless row predates workspaces; anyone signed in may finish it. */
/**
* 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) {
return !owner || owner === user.id;
if (owner === null || owner === undefined) return true;
return owner === user.id || (owner === '' && user.role === 'admin');
}
function adminUser(row) {
@@ -204,11 +339,16 @@ 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) {
reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
req.destroy();
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);
@@ -228,6 +368,51 @@ async function readJson(req, limit = 8 * 1024 * 1024) {
}
}
/**
* 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('/');
@@ -248,7 +433,7 @@ function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
'Content-Type': type,
'Content-Length': data.length,
'Cache-Control': cache,
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
'X-Content-Type-Options': 'nosniff',
});
res.end(data);
}
@@ -271,7 +456,7 @@ async function sendFile(req, res, filePath, type, cache = 'private, max-age=8640
'Content-Type': type,
'Content-Length': stat.size,
'Cache-Control': cache,
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
'X-Content-Type-Options': 'nosniff',
...extraHeaders,
});
if (req.method === 'HEAD') return res.end();
@@ -288,6 +473,35 @@ function decodeDataUrl(value) {
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';
@@ -297,17 +511,20 @@ function route(method, pattern, handler) {
routes.push({ method, pattern, handler });
}
route('GET', '/api/health', async ({ res }) => {
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: countPhotos(),
bytes: storageBytes(),
storage: { root: storageRoot(), custom: isCustomRoot() },
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,
});
});
@@ -351,7 +568,7 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
id,
email,
name: name || email.split('@')[0],
passHash: hashPassword(password),
passHash: await hashPassword(password),
role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member',
});
if (inviteRow && !invites.accept(token, id)) {
@@ -368,11 +585,38 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
});
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 || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct');
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(
@@ -445,6 +689,7 @@ route('GET', '/api/admin/overview', async ({ req, res }) => {
},
quotas: quotasForAdmin(),
mail: mailStatus(),
immich: immichAdminStatus(),
});
});
@@ -464,7 +709,7 @@ route('POST', '/api/admin/users', async ({ req, res }) => {
id,
email,
name: name || email.split('@')[0],
passHash: hashPassword(password),
passHash: await hashPassword(password),
role,
});
json(res, 201, { user: adminUser(users.byId(id)) });
@@ -482,7 +727,7 @@ route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => {
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);
patch.passHash = await hashPassword(body.password);
}
if (typeof body.role === 'string') {
@@ -718,6 +963,208 @@ route('POST', '/api/admin/mail/test', async ({ req, res }) => {
}
});
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');
@@ -742,7 +1189,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => {
id,
email,
name: payload.name || email.split('@')[0],
passHash: hashPassword(crypto.randomBytes(24).toString('hex')),
passHash: await hashPassword(crypto.randomBytes(24).toString('hex')),
role: 'member',
});
row = users.byId(id);
@@ -962,7 +1409,16 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para
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');
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. */
@@ -973,7 +1429,8 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
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', {
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}"`,
});
});
@@ -987,44 +1444,68 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
(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 (archiveBuilding) {
return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', {
'Retry-After': '30',
});
}
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);
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');
}
@@ -1048,6 +1529,9 @@ route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) =>
});
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');
}
@@ -1068,6 +1552,9 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => {
});
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');
}
@@ -1118,19 +1605,82 @@ route('PUT', '/api/presets', async ({ req, res }) => {
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 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 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 mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
const ext = (name.split('.').pop() || 'bin').toLowerCase();
await writeOriginal(params.id, ext, data);
const raw = isRawName(name) || drop;
if (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);
@@ -1146,11 +1696,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
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: data.length });
return json(res, 201, { raw: false, mime, size });
});
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
@@ -1292,7 +1844,7 @@ route('GET', '/api/photos/:id/original', async ({ req, res, params }) => {
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');
return sendBuffer(res, data, normalizePhotoMime(linked.photo.mime, linked.photo.name));
});
route('POST', '/api/bridge/export', async ({ req, res }) => {
@@ -1326,6 +1878,15 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
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);
@@ -1353,6 +1914,7 @@ 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);
@@ -1378,9 +1940,18 @@ const MIME = {
};
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)) {
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()) {
@@ -1413,8 +1984,15 @@ async function serveStatic(req, res, url) {
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) {
@@ -1429,11 +2007,39 @@ const server = http.createServer(async (req, res) => {
} 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);
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();
@@ -1446,6 +2052,16 @@ server.listen(PORT, HOST, async () => {
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));