Initial commit: Luminary photo catalog and RAW editor

Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-23 15:19:25 +00:00
commit cd52a2f82f
121 changed files with 101872 additions and 0 deletions
+265
View File
@@ -0,0 +1,265 @@
/**
* Bridge to the Media Team Hub dashboard.
*
* The dashboard signs a short-lived token scoped to one event; this module
* verifies it, exchanges it for a service token, mirrors the event's photo list
* into the local catalog, and proxies bytes/save-backs for as long as the
* bridge session lives. Nothing here is reachable without a valid token.
*/
import crypto from 'node:crypto';
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
import { removeAsset } from './storage.mjs';
const VERSION = 'g1';
/* ------------------------------------------------------------------- tokens */
export function bridgeConfigured() {
return Boolean(BRIDGE_SECRET && GLENLOCH_URL);
}
export function verifyBridgeToken(token, now = Date.now()) {
if (!BRIDGE_SECRET || typeof token !== 'string') return null;
const parts = token.split('.');
if (parts.length !== 3 || parts[0] !== VERSION) return null;
const [, body, signature] = parts;
const expected = crypto.createHmac('sha256', BRIDGE_SECRET).update(body).digest();
let supplied;
try {
supplied = Buffer.from(signature.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
} catch {
return null;
}
if (
supplied.length !== expected.length ||
!crypto.timingSafeEqual(supplied, expected)
) {
return null;
}
let payload;
try {
payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
} catch {
return null;
}
if (
!payload ||
typeof payload.sid !== 'string' ||
typeof payload.eid !== 'string' ||
typeof payload.uid !== 'string' ||
typeof payload.email !== 'string' ||
(payload.kind !== 'login' && payload.kind !== 'service') ||
typeof payload.exp !== 'number' ||
payload.exp * 1000 <= now
) {
return null;
}
return payload;
}
async function dashboardJson(url, token, init = {}) {
const res = await fetch(url, {
...init,
headers: {
...(init.headers ?? {}),
authorization: `Bearer ${token}`,
},
});
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
if (!res.ok) {
throw new Error(body?.error || `Dashboard request failed (${res.status})`);
}
return body;
}
/** Swap the one browser-hop login token for a longer server-side token. */
export async function exchangeBridgeToken(loginToken, sessionId) {
return dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}/exchange`,
loginToken,
{ method: 'POST' },
);
}
/* ------------------------------------------------------------------ storage */
const bridgeInsert = db.prepare(`
INSERT INTO bridge_events (event_id, session_id, token, glenloch_url, source_event_id, return_url, expires_at, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(event_id) DO UPDATE SET
session_id = excluded.session_id,
token = excluded.token,
glenloch_url = excluded.glenloch_url,
source_event_id = excluded.source_event_id,
return_url = excluded.return_url,
expires_at = excluded.expires_at,
created_at = excluded.created_at
`);
const bridgeGet = db.prepare('SELECT * FROM bridge_events WHERE event_id = ?');
const bridgeExpired = db.prepare('SELECT event_id FROM bridge_events WHERE expires_at < ?');
const bridgeDelete = db.prepare('DELETE FROM bridge_events WHERE event_id = ?');
const photosForEvent = db.prepare('SELECT id FROM photos WHERE event_id = ?');
export function bridgeEventId(sourceEventId) {
return `br-${sourceEventId}`;
}
export function bridgePhotoId(sourcePhotoId) {
return `br-${sourcePhotoId}`;
}
export function bridgeForEvent(eventId) {
return bridgeGet.get(eventId) ?? null;
}
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
function dropBridgeEvent(eventId) {
for (const row of photosForEvent.all(eventId)) {
removePhoto(row.id);
removeAsset(row.id).catch(() => undefined);
}
removeEvent(eventId);
bridgeDelete.run(eventId);
}
/** Removes events whose bridge session has expired. Safe to call often. */
export function purgeExpiredBridges(now = Date.now()) {
for (const row of bridgeExpired.all(now)) {
dropBridgeEvent(row.event_id);
}
}
function eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt) {
const source = listing.event;
return {
id: eventId,
name: source.title || 'Advanced edit',
date: source.startsAt ? Date.parse(source.startsAt) : Date.now(),
createdAt: Date.now(),
notes: source.description ?? undefined,
bridge: {
sessionId,
sourceEventId: source.id,
dashboardUrl: returnUrl ?? `${GLENLOCH_URL}/events/${source.id}`,
expiresAt,
},
};
}
function photoRecordFrom(photo, eventId, sessionId, index) {
const id = bridgePhotoId(photo.id);
const raw = photo.kind === 'raw';
return {
id,
eventId,
order: index,
name: photo.filename,
width: photo.width || 0,
height: photo.height || 0,
size: photo.sizeBytes || 0,
mime: photo.mimeType || 'application/octet-stream',
addedAt: Date.now(),
takenAt: photo.takenAt ? Date.parse(photo.takenAt) : undefined,
meta: {},
thumb: '',
thumbUrl: `/api/photos/${id}/thumb`,
rating: 0,
flag: 'none',
color: '',
keywords: [],
edits: {},
history: [],
raw,
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
bridgeSource: { sessionId, sourceId: photo.id },
};
}
/**
* Mirrors one event into the local catalog. The photo bytes stay on the
* dashboard; only metadata, previews and thumbnails are temporary here.
*/
export async function importBridgeEvent({ serviceToken, sessionId, ownerId = '' }) {
const expiresAt =
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
const listing = await dashboardJson(
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}`,
serviceToken,
);
const eventId = bridgeEventId(listing.event.id);
dropBridgeEvent(eventId);
const returnUrl = listing.editor?.returnUrl ?? null;
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0, ownerId);
listing.photos.forEach((photo, index) => {
savePhoto(photoRecordFrom(photo, eventId, sessionId, index), Date.now(), ownerId);
});
bridgeInsert.run(
eventId,
sessionId,
serviceToken,
GLENLOCH_URL,
listing.event.id,
returnUrl,
expiresAt,
Date.now(),
);
return {
eventId,
photoCount: listing.photos.length,
sessionId,
expiresAt,
};
}
/* ----------------------------------------------------------------- proxying */
export function bridgeSourceUrl(row, sourcePhotoId, variant) {
const params = new URLSearchParams({ variant });
return `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/source?${params}`;
}
export async function fetchBridgeImage(row, sourcePhotoId, variant) {
return fetch(bridgeSourceUrl(row, sourcePhotoId, variant), {
headers: { authorization: `Bearer ${row.token}` },
});
}
/** Forwards a browser-rendered JPEG and recipe to the dashboard. */
export async function forwardBridgeRender(row, sourcePhotoId, payload) {
const res = await fetch(
`${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
row.session_id,
)}/photos/${encodeURIComponent(sourcePhotoId)}/render`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${row.token}`,
},
body: JSON.stringify(payload),
},
);
const text = await res.text();
let body = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
body = null;
}
return { status: res.status, body };
}