Land camera-native raw profiles, real ICC soft proofing and 16-bit proxies.

Camera profiles, proofing tables and the half-float sidecar all have to agree
with the pixels the editor actually grades, so they land together with the
preset filter menu that was unusable while thumbnails streamed in.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-28 03:59:55 +00:00
parent 6dfddffc14
commit 0c113e7a91
53 changed files with 9217 additions and 476 deletions
+334 -16
View File
@@ -56,16 +56,19 @@ import {
defaultRoot,
findOriginal,
findPreview,
findPreview16,
findProof,
findProofThumb,
findThumb,
isCustomRoot,
originalTarget,
removeAsset,
removePreview16,
setStorageRoot,
storageBytes,
storageRoot,
writePreview,
writePreview16,
writeProof,
writeProofThumb,
writeThumb,
@@ -238,6 +241,77 @@ function normalizePhotoMime(value, name = '') {
return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream';
}
import {
gallerySettingsFor,
saveGallerySettings,
clearGallerySettings,
noteGalleryDownload,
} from './db.mjs';
/** Passwords are hashed per link with a random salt, so a database dump is not a key. */
function hashGalleryPassword(password, salt) {
return crypto.scryptSync(password, salt, 32).toString('hex');
}
/* Unlocked galleries live in memory: a restart asks for the password again. */
const galleryUnlocks = new Map();
const GALLERY_UNLOCK_MS = 12 * 3600 * 1000;
const galleryCookie = (token) => `lumg_${token}`;
/**
* One check for every public gallery route: revoked link, expiry, password.
* A locked gallery is a 401 so the page can show the password prompt instead
* of claiming the shoot is gone.
*/
function galleryGate(req, token) {
const shared = eventByShareToken(token);
if (!shared) {
return { ok: false, status: 404, message: 'This proofing gallery is no longer available' };
}
const settings = gallerySettingsFor(token);
if (settings.expiresAt && Date.now() > settings.expiresAt) {
return { ok: false, status: 410, message: 'This proofing gallery has expired' };
}
if (settings.passwordHash) {
const cookie = parseCookies(req)[galleryCookie(token)];
const entry = galleryUnlocks.get(token);
const valid =
cookie && entry && entry.key === cookie && entry.expires > Date.now()
? true
: false;
if (!valid) {
return {
ok: false,
status: 401,
message: 'This gallery is password protected',
locked: true,
};
}
}
return { ok: true, shared, settings };
}
/** Writes the refusal and returns true when the caller must stop. */
function galleryDenied(req, res, token) {
const gate = galleryGate(req, token);
if (gate.ok) return false;
error(res, gate.status, gate.message);
return true;
}
/** Refuses a download when the link turned downloads off or used its allowance. */
function galleryDownloadDenied(res, token, settings) {
if (!settings.allowDownloads) {
error(res, 403, 'Downloads are disabled for this gallery');
return true;
}
if (settings.downloadCap > 0 && settings.downloadCount >= settings.downloadCap) {
error(res, 403, 'This gallery has reached its download limit');
return true;
}
return false;
}
function parseCookies(req) {
const out = {};
for (const part of String(req.headers.cookie ?? '').split(';')) {
@@ -1315,6 +1389,103 @@ route('GET', '/api/events/:id/share', async ({ req, res, params }) => {
.map((p) => ({ photoId: p.photoId, clientName: p.clientName }))
: [],
feedback,
settings: token
? (() => {
const saved = gallerySettingsFor(token);
return {
passwordSet: Boolean(saved.passwordHash),
expiresAt: saved.expiresAt,
watermark: saved.watermark,
allowDownloads: saved.allowDownloads,
downloadCap: saved.downloadCap,
downloadCount: saved.downloadCount,
};
})()
: null,
});
});
/** Owner-side security settings for the proofing link. */
route('PUT', '/api/events/:id/share/settings', 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);
if (!token) return error(res, 404, 'This event has no proofing link yet');
const body = await readJson(req, 64 * 1024);
const current = gallerySettingsFor(token);
let passwordHash = current.passwordHash;
let passwordSalt = current.passwordSalt;
if (typeof body.password === 'string') {
const password = body.password.trim();
if (password === '') {
passwordHash = '';
passwordSalt = '';
} else if (password.length < 4) {
return error(res, 400, 'Use at least 4 characters for the gallery password');
} else {
passwordSalt = crypto.randomBytes(12).toString('hex');
passwordHash = hashGalleryPassword(password, passwordSalt);
}
}
const saved = saveGallerySettings(token, {
passwordHash,
passwordSalt,
expiresAt:
typeof body.expiresAt === 'number' && body.expiresAt > 0 ? body.expiresAt : null,
watermark: String(body.watermark ?? '').trim().slice(0, 80),
allowDownloads: body.allowDownloads !== false,
downloadCap: Number.isFinite(Number(body.downloadCap))
? Math.max(0, Math.min(100000, Math.round(Number(body.downloadCap))))
: current.downloadCap,
});
json(res, 200, {
settings: {
passwordSet: Boolean(saved.passwordHash),
expiresAt: saved.expiresAt,
watermark: saved.watermark,
allowDownloads: saved.allowDownloads,
downloadCap: saved.downloadCap,
downloadCount: saved.downloadCount,
},
});
});
/** Public unlock: exchanges the gallery password for a cookie scoped to the link. */
route('POST', '/api/galleries/:token/unlock', async ({ req, res, params }) => {
if (!allowGalleryWrite(req, params.token)) {
return error(res, 429, 'Too many attempts. Try again shortly.', { 'Retry-After': '60' });
}
const gate = galleryGate(req, params.token);
if (!gate.ok && gate.status === 410) return error(res, 410, gate.message);
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
const settings = gallerySettingsFor(params.token);
if (!settings.passwordHash) return json(res, 200, { ok: true });
const body = await readJson(req, 16 * 1024);
const password = String(body.password ?? '');
const attempt = Buffer.from(hashGalleryPassword(password, settings.passwordSalt), 'hex');
const expected = Buffer.from(settings.passwordHash, 'hex');
const ok =
attempt.length === expected.length && crypto.timingSafeEqual(attempt, expected);
if (!ok) return error(res, 403, 'That password does not open this gallery');
const key = crypto.randomBytes(24).toString('base64url');
galleryUnlocks.set(params.token, { key, expires: Date.now() + GALLERY_UNLOCK_MS });
res.setHeader(
'Set-Cookie',
`${galleryCookie(params.token)}=${encodeURIComponent(key)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${GALLERY_UNLOCK_MS / 1000}`,
);
json(res, 200, { ok: true });
});
/** Public: is this link locked or past its expiry? Used before the gallery loads. */
route('GET', '/api/galleries/:token/status', async ({ req, res, params }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok && !gate.locked) return error(res, gate.status, gate.message);
const settings = gate.ok ? gate.settings : gallerySettingsFor(params.token);
json(res, 200, {
locked: !gate.ok,
expiresAt: settings.expiresAt,
allowDownloads: settings.allowDownloads,
});
});
@@ -1334,14 +1505,20 @@ 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');
const token = shareTokenFor(params.id);
setShareToken(params.id, null);
if (token) {
clearGallerySettings(token);
galleryUnlocks.delete(token);
}
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');
route('GET', '/api/galleries/:token', async ({ req, res, params, url }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
const shared = gate.shared;
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
const picks = picksForToken(params.token).filter((p) => p.picked);
const counts = new Map();
@@ -1395,16 +1572,26 @@ route('GET', '/api/galleries/:token', async ({ res, params, url }) => {
photographer: 'Luminary',
photos,
picks: { total: picks.length, clients: new Set(picks.map((p) => p.clientId)).size },
downloads: {
allowed: gate.settings.allowDownloads,
remaining:
gate.settings.downloadCap > 0
? Math.max(0, gate.settings.downloadCap - gate.settings.downloadCount)
: null,
},
watermark: gate.settings.watermark,
});
});
route('GET', '/api/galleries/:token/photos/:id/thumb', async ({ req, res, params }) => {
if (galleryDenied(req, res, params.token)) return;
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 }) => {
if (galleryDenied(req, res, params.token)) return;
const hit = galleryPhoto(params.token, params.id);
if (!hit) return error(res, 404, 'Not found');
const proof = findProof(params.id);
@@ -1423,6 +1610,9 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para
/** Client download of the edited proof, named like the delivered file. */
route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, params }) => {
const gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
const hit = galleryPhoto(params.token, params.id);
if (!hit) return error(res, 404, 'Not found');
const proof = findProof(params.id);
@@ -1430,6 +1620,7 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
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);
noteGalleryDownload(params.token);
return sendFile(req, res, file, mime, 'private, max-age=3600', {
'Content-Disposition': `attachment; filename="${safe}"`,
});
@@ -1437,8 +1628,10 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par
/** 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 gate = galleryGate(req, params.token);
if (!gate.ok) return error(res, gate.status, gate.message);
if (galleryDownloadDenied(res, params.token, gate.settings)) return;
const shared = gate.shared;
const clientId = String(url.searchParams.get('client') ?? '').slice(0, 64);
const picks = picksForToken(params.token).filter(
(pick) => pick.picked && (!clientId || pick.clientId === clientId),
@@ -1487,6 +1680,7 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
const archive = createZip(entries);
noteGalleryDownload(params.token);
const eventName = String(shared.event.name || 'proofing')
.replace(/[^a-z0-9._ -]+/gi, '-')
.trim() || 'proofing';
@@ -1502,13 +1696,80 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur
}
});
/* ---------------------------------------------------------------- tether */
/**
* Tethering is a drop folder, not a camera driver: the owner (or a synced
* tethering app) writes frames into one directory per event, and the open
* editor pulls and imports them. Files are removed from the folder only after
* the client confirms the import, so a dropped connection never loses a frame.
*/
const TETHER_EXT = new Set([
'jpg', 'jpeg', 'png', 'tif', 'tiff', 'webp',
'dng', 'cr2', 'cr3', 'nef', 'arw', 'orf', 'rw2', 'raf', 'pef', 'srw',
]);
function tetherFolder(eventId) {
const safe = String(eventId).replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 64) || 'event';
return { safe, dir: path.join(DATA_DIR, 'tether', safe) };
}
/** A bare file name in the drop folder; anything with a path is refused. */
function tetherFileName(raw) {
const name = path.basename(String(raw ?? ''));
if (!name || name !== String(raw ?? '')) return null;
const ext = name.split('.').pop()?.toLowerCase() ?? '';
return TETHER_EXT.has(ext) ? name : null;
}
route('GET', '/api/events/:id/tether', 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 folder = tetherFolder(params.id);
await fsp.mkdir(folder.dir, { recursive: true });
const names = await fsp.readdir(folder.dir).catch(() => []);
const files = [];
for (const name of names) {
if (!tetherFileName(name)) continue;
const stat = await fsp.stat(path.join(folder.dir, name)).catch(() => null);
if (!stat?.isFile()) continue;
files.push({ name, size: stat.size, mtime: stat.mtimeMs });
}
files.sort((a, b) => a.mtime - b.mtime);
json(res, 200, { folder: folder.dir, files });
});
route('GET', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
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 name = tetherFileName(url.searchParams.get('name'));
if (!name) return error(res, 400, 'No such file');
const file = path.join(tetherFolder(params.id).dir, name);
const stat = await fsp.stat(file).catch(() => null);
if (!stat?.isFile()) return error(res, 404, 'No such file');
const mime = normalizePhotoMime('', name);
return sendFile(req, res, file, mime, 'no-store', {
'Content-Disposition': `attachment; filename="${name}"`,
});
});
route('DELETE', '/api/events/:id/tether/file', async ({ req, res, params, url }) => {
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 name = tetherFileName(url.searchParams.get('name'));
if (!name) return error(res, 400, 'No such file');
await fsp.unlink(path.join(tetherFolder(params.id).dir, name)).catch(() => undefined);
json(res, 200, { ok: true });
});
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');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 32 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1532,9 +1793,7 @@ 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');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 16 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1555,9 +1814,7 @@ 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');
}
if (galleryDenied(req, res, params.token)) return;
const body = await readJson(req, 32 * 1024);
const hit = galleryPhoto(params.token, String(body.photoId ?? ''));
if (!hit) return error(res, 404, 'No such photo');
@@ -1683,6 +1940,8 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
const data = await fsp.readFile(target);
const decoded = await decodeRaw(data);
await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
else await removePreview16(params.id);
const info = await jpegInfo(decoded.jpeg);
return json(res, 201, {
raw: true,
@@ -1705,6 +1964,49 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
return json(res, 201, { raw: false, mime, size });
});
/**
* Re-decode a stored RAW with the current pipeline settings. The original is
* never touched; only the editable proxy, its thumbnail and the cached denoise
* renders are replaced, so existing edits keep working on fresh pixels.
*/
route('POST', '/api/photos/:id/reprocess', 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 photo = getPhoto(params.id);
if (!photo?.raw) return error(res, 400, 'Only RAW imports can be reprocessed');
const original = findOriginal(params.id);
if (!original) return error(res, 404, 'The RAW original is missing from storage');
try {
const decoded = await decodeRaw(await fsp.readFile(original));
await writePreview(params.id, decoded.jpeg, decoded.ext);
if (decoded.preview16) await writePreview16(params.id, decoded.preview16.data);
else await removePreview16(params.id);
const thumb = await makeThumb(decoded.jpeg, 560);
if (thumb) await writeThumb(params.id, thumb);
// The old denoised renders were made from the previous proxy.
clearDenoised(params.id);
const info = await jpegInfo(decoded.jpeg);
const width = info?.width || decoded.width || photo.width;
const height = info?.height || decoded.height || photo.height;
// Stamp the record so cached previews and thumbnails are fetched again.
const previewVersion = Date.now();
// Pass the owner explicitly: savePhoto defaults to '' and would orphan the row.
savePhoto({ ...photo, width, height, mime: 'image/jpeg', previewVersion }, Date.now(), user.id);
json(res, 200, {
width,
height,
engine: decoded.engine,
note: decoded.note ?? null,
previewVersion,
previewUrl: `/api/photos/${params.id}/preview?v=${previewVersion}`,
thumbUrl: `/api/photos/${params.id}/thumb?v=${previewVersion}`,
});
} catch (err) {
return error(res, 422, err instanceof Error ? err.message : 'Could not reprocess this RAW file');
}
});
route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -1784,6 +2086,18 @@ route('GET', '/api/photos/:id/preview', async ({ req, res, params }) => {
return sendFile(req, res, findOriginal(params.id), 'application/octet-stream');
});
/**
* The 16-bit half of a raw proxy. The editor inflates it and uploads it as a
* half-float source texture so a heavy grade keeps its precision; the JPEG at
* `/preview` stays the fallback when this file is absent or too large to fetch.
*/
route('GET', '/api/photos/:id/preview16', 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');
return sendFile(req, res, findPreview16(params.id), 'image/png');
});
route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => {
const user = currentUser(req);
if (!user) return error(res, 401, 'Not signed in');
@@ -1892,8 +2206,12 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
await writeThumb(params.id, thumb.data);
delete record.thumb;
}
const versionQuery =
typeof record.previewVersion === 'number' && Number.isFinite(record.previewVersion)
? `?v=${record.previewVersion}`
: '';
if (record.raw) {
record.previewUrl = `/api/photos/${params.id}/preview`;
record.previewUrl = `/api/photos/${params.id}/preview${versionQuery}`;
const preview = findPreview(params.id);
if (!preview) {
const original = findOriginal(params.id);
@@ -1905,7 +2223,7 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
}
record.thumbUrl = record.proofAt
? `/api/photos/${params.id}/thumb?proof=${record.proofAt}`
: `/api/photos/${params.id}/thumb`;
: `/api/photos/${params.id}/thumb${versionQuery}`;
savePhoto(record, Date.now(), user.id);
json(res, 200, { photo: record });
});