feat(editor): bridge the advanced photo editor into the event workflow
CI / build (push) Has been cancelled

Event photos can now be opened in Lumenroom, a WebGL2 develop module, from the
photo editor's Advanced button. The dashboard signs a short-lived token scoped
to one user and event; Lumenroom exchanges it, imports the event's photo list
and proxies bytes on demand, so nothing is copied and the temporary catalog
expires with the bridge session. Saving in Lumenroom renders the photo and
writes it back as the event's edited JPEG, with the advanced recipe kept in
event_photos.advanced_edit_json.

Lumenroom is vendored under lumenroom/ and built as a second compose service,
so one clone and `docker compose up -d --build` deploys both apps.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-21 01:34:20 +00:00
parent 982f9048e1
commit 0cb315ea88
89 changed files with 22087 additions and 1 deletions
@@ -0,0 +1,40 @@
import { NextRequest } from "next/server";
import { authenticateBridge } from "@/db/bridge";
import {
BRIDGE_SESSION_TTL_SECONDS,
signBridgeToken,
} from "@/lib/bridge";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
* POST /api/bridge/sessions/:sessionId/exchange
*
* The login token is deliberately short-lived because it travels in a URL.
* The editor exchanges it once for a service token it keeps server-side; that
* token authorizes the photo proxy and the save-back calls.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> },
) => {
const { sessionId } = await params;
const auth = await authenticateBridge(req, sessionId, "login");
if (!auth) return errorResponse(401, "invalid or expired bridge token");
const token = signBridgeToken({
sid: auth.session.id,
eid: auth.session.eventId,
uid: auth.user.id,
email: auth.user.email,
name: auth.user.name,
kind: "service",
exp: Math.floor(Date.now() / 1000) + BRIDGE_SESSION_TTL_SECONDS,
});
return jsonResponse({
token,
sessionId: auth.session.id,
eventId: auth.session.eventId,
expiresAt: auth.session.expiresAt,
});
};
@@ -0,0 +1,105 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge";
import {
editedStoredNameForEventPhoto,
eventPhotoPath,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
const MAX_BODY_BYTES = 64 * 1024 * 1024;
const MAX_RECIPE_BYTES = 512 * 1024;
const MAX_JPEG_BYTES = 48 * 1024 * 1024;
/**
* POST /api/bridge/sessions/:sessionId/photos/:photoId/render
* Body: { jpeg: <base64>, edits: <advanced recipe>, width, height }
*
* The advanced editor renders in the browser, so the server only has to store
* the result. The JPEG becomes the photo's edited version (used by the gallery,
* thumbnails and delivery exports) and the recipe is kept so the editor can be
* reopened with its sliders intact.
*/
export const POST = async (
req: NextRequest,
{
params,
}: {
params: Promise<{ sessionId: string; photoId: string }>;
},
) => {
const { sessionId, photoId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) {
return errorResponse(413, "the rendered image is too large");
}
const photo = await getBridgePhoto(auth.session.eventId, photoId);
if (!photo) return errorResponse(404, "unknown photo");
const body = (await req.json().catch(() => null)) as
| { jpeg?: unknown; edits?: unknown }
| null;
if (!body || typeof body.jpeg !== "string") {
return errorResponse(400, "a base64 JPEG is required");
}
let data: Buffer;
try {
data = Buffer.from(body.jpeg, "base64");
} catch {
return errorResponse(400, "the image could not be decoded");
}
if (data.byteLength < 4 || data[0] !== 0xff || data[1] !== 0xd8) {
return errorResponse(400, "the image is not a JPEG");
}
if (data.byteLength > MAX_JPEG_BYTES) {
return errorResponse(413, "the rendered image is too large");
}
const recipe = JSON.stringify(body.edits ?? {});
if (recipe.length > MAX_RECIPE_BYTES) {
return errorResponse(413, "the edit recipe is too large");
}
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const storedName = editedStoredNameForEventPhoto(
auth.session.eventId,
photo.id,
);
const target = eventPhotoPath(storage.root, storedName);
const temporary = `${target}.${randomUUID()}.tmp`;
try {
await mkdir(path.dirname(target), { recursive: true });
await writeFile(temporary, data);
await rename(temporary, target);
} catch {
await unlink(temporary).catch(() => undefined);
return errorResponse(500, "the edited image could not be saved");
}
const editedAt = await saveBridgeRender({
photoId: photo.id,
editedStoredName: storedName,
editedSizeBytes: data.byteLength,
advancedEditJson: recipe,
editedBy: auth.user.id,
});
if (!editedAt) {
await unlink(target).catch(() => undefined);
return errorResponse(404, "unknown photo");
}
return jsonResponse({
ok: true,
editedAt,
editedSizeBytes: data.byteLength,
});
};
@@ -0,0 +1,165 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import sharp from "sharp";
import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
import {
bridgeProxyStoredNameForEventPhoto,
bridgeThumbStoredNameForEventPhoto,
eventPhotoPath,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { renderPhotoJpeg } from "@/lib/photo-render";
const PROXY_MAX_EDGE = 4000;
const THUMB_MAX_EDGE = 480;
function imageResponse(data: Buffer, contentType = "image/jpeg"): Response {
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": contentType,
"content-length": String(data.byteLength),
"cache-control": "private, max-age=3600",
"x-content-type-options": "nosniff",
},
});
}
/** Reads a cached derivative or writes it atomically on first use. */
async function cached(
filePath: string,
produce: () => Promise<Buffer>,
): Promise<Buffer> {
try {
const info = await stat(filePath);
if (info.isFile() && info.size > 0) return readFile(filePath);
} catch {
// Not generated yet.
}
const data = await produce();
await mkdir(path.dirname(filePath), { recursive: true });
const temporary = `${filePath}.${randomUUID()}.tmp`;
await writeFile(temporary, data);
await rename(temporary, filePath);
return data;
}
async function thumbFor(filePath: string, kind: "raw" | "image") {
if (kind === "raw") {
const rendered = await renderPhotoJpeg({
filePath,
kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: THUMB_MAX_EDGE,
});
return rendered.data;
}
return sharp(filePath)
.resize({
width: THUMB_MAX_EDGE,
height: THUMB_MAX_EDGE,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: 82, mozjpeg: true })
.toBuffer();
}
/**
* GET /api/bridge/sessions/:sessionId/photos/:photoId/source?variant=original|proxy|thumb
*
* `original` streams the untouched bytes (the editor decodes RAW itself);
* `proxy` is a 4000 px JPEG, used when the editor only needs a browser image;
* `thumb` is a small grid preview. Derivatives are cached beside the original
* so repeated opens are free.
*/
export const GET = async (
req: NextRequest,
{
params,
}: {
params: Promise<{ sessionId: string; photoId: string }>;
},
) => {
const { sessionId, photoId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
const photo = await getBridgePhoto(auth.session.eventId, photoId);
if (!photo) return errorResponse(404, "unknown photo");
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const originalPath = eventPhotoPath(storage.root, photo.storedName);
const variant = req.nextUrl.searchParams.get("variant") ?? "original";
if (variant === "original") {
let size: number;
try {
const info = await stat(originalPath);
if (!info.isFile()) throw new Error("missing");
size = info.size;
} catch {
return errorResponse(404, "the file is missing from storage");
}
const stream = createReadStream(originalPath);
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
status: 200,
headers: {
"content-type": photo.mimeType || "application/octet-stream",
"content-length": String(size),
"content-disposition": "inline",
"cache-control": "private, max-age=3600",
"x-content-type-options": "nosniff",
},
},
);
}
if (variant === "thumb") {
try {
const thumbPath = eventPhotoPath(
storage.root,
bridgeThumbStoredNameForEventPhoto(auth.session.eventId, photo.id),
);
const data = await cached(thumbPath, () =>
thumbFor(originalPath, photo.kind),
);
return imageResponse(data);
} catch {
return errorResponse(422, "the thumbnail could not be generated");
}
}
if (variant === "proxy") {
try {
const proxyPath = eventPhotoPath(
storage.root,
bridgeProxyStoredNameForEventPhoto(auth.session.eventId, photo.id),
);
const data = await cached(proxyPath, async () => {
const rendered = await renderPhotoJpeg({
filePath: originalPath,
kind: photo.kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: PROXY_MAX_EDGE,
});
return rendered.data;
});
return imageResponse(data);
} catch {
return errorResponse(422, "the editable preview could not be generated");
}
}
return errorResponse(400, "unknown source variant");
};
@@ -0,0 +1,83 @@
import { NextRequest } from "next/server";
import {
authenticateBridge,
getBridgeEventSummary,
listBridgePhotos,
} from "@/db/bridge";
import { bridgeReturnUrl } from "@/lib/bridge";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { eventPhotoPath } from "@/lib/event-photos";
import sharp from "sharp";
/** Reads the header dimensions without decoding the whole file. */
async function imageSize(
path: string,
): Promise<{ width: number; height: number } | null> {
try {
const meta = await sharp(path).metadata();
if (!meta.width || !meta.height) return null;
return { width: meta.width, height: meta.height };
} catch {
return null;
}
}
/**
* GET /api/bridge/sessions/:sessionId
*
* Everything the advanced editor needs to mirror one event: its title, dates
* and photo list. Photo bytes are fetched separately, one at a time, so opening
* a large event does not transfer gigabytes up front.
*/
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> },
) => {
const { sessionId } = await params;
const auth = await authenticateBridge(req, sessionId);
if (!auth) return errorResponse(401, "invalid or expired bridge session");
const event = await getBridgeEventSummary(auth.session.eventId);
if (!event) return errorResponse(404, "unknown event");
const rows = await listBridgePhotos(auth.session.eventId);
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
// Dimensions are only known for browser images; RAW dimensions arrive with
// the proxy the editor builds from the original.
const sizes = new Map<string, { width: number; height: number }>();
for (const row of rows) {
if (row.kind !== "image") continue;
const size = await imageSize(
eventPhotoPath(storage.root, row.storedName),
).catch(() => null);
if (size) sizes.set(row.id, size);
}
return jsonResponse({
session: { id: auth.session.id, expiresAt: auth.session.expiresAt },
event: {
id: event.id,
title: event.title,
eventType: event.eventType,
startsAt: event.startsAt,
endsAt: event.endsAt,
location: event.location,
description: event.description,
},
photos: rows.map((row) => ({
id: row.id,
filename: row.filename,
mimeType: row.mimeType,
kind: row.kind,
sizeBytes: row.sizeBytes,
folderName: row.folderName,
width: sizes.get(row.id)?.width ?? 0,
height: sizes.get(row.id)?.height ?? 0,
takenAt: row.createdAt,
})),
editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) },
});
};
+63
View File
@@ -0,0 +1,63 @@
import { NextRequest } from "next/server";
import { gateSession } from "@/auth/api";
import { bridgeUser, createBridgeSession } from "@/db/bridge";
import { getEventAccess } from "@/db/events";
import { errorResponse, jsonResponse } from "@/lib/http";
import {
BRIDGE_LOGIN_TTL_SECONDS,
advancedEditorUrl,
bridgeConfigured,
bridgeReturnUrl,
signBridgeToken,
} from "@/lib/bridge";
/**
* POST /api/events/:id/advanced
*
* Opens a bridge session for the advanced editor and returns the one-time URL
* the browser should follow. Authorization happens here, once, with the normal
* dashboard session; the editor only ever sees the scoped token.
*/
export const POST = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!bridgeConfigured()) {
return errorResponse(
503,
"the advanced editor is not configured; set BRIDGE_SECRET and LUMENROOM_URL",
);
}
const editor = advancedEditorUrl()!;
const user = await bridgeUser(gate.id);
if (!user) return errorResponse(401, "Authentication required");
const session = await createBridgeSession({
userId: gate.id,
eventId: id,
});
const token = signBridgeToken({
sid: session.id,
eid: id,
uid: gate.id,
email: user.email,
name: user.name,
kind: "login",
exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS,
});
return jsonResponse({
url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`,
expiresAt: session.expiresAt,
returnUrl: bridgeReturnUrl(id),
});
};