Files
dragonroll/dragonroll-foundry/bridge/server.js
Gitea OpenCode Agent dd4c9535d3
All checks were successful
Test / test (push) Successful in 2s
Build and Deploy Nuxt / build (push) Successful in 1m7s
Fix issue #65: Item selecting icon
2026-10-15 18:08:27 +02:00

317 lines
11 KiB
JavaScript

const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const { timingSafeEqual } = require("node:crypto");
const host = process.env.DRAGONROLL_FOUNDRY_HOST || "0.0.0.0";
const port = Number(process.env.DRAGONROLL_FOUNDRY_PORT || 8787);
const readToken = process.env.DRAGONROLL_FOUNDRY_READ_TOKEN;
const pushToken = process.env.DRAGONROLL_FOUNDRY_PUSH_TOKEN;
const allowedOrigins = new Set(
(process.env.DRAGONROLL_FOUNDRY_ALLOWED_ORIGINS || "http://localhost:30000")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean),
);
const maxBodySize = 50 * 1024 * 1024;
// The Foundry Data directory, for listing the core `icons/` library. Optional:
// without it the bridge simply cannot answer icon listing requests.
const dataPath = (process.env.DRAGONROLL_FOUNDRY_DATA_PATH || "").trim();
if (!readToken || !pushToken) {
throw new Error("Set DRAGONROLL_FOUNDRY_READ_TOKEN and DRAGONROLL_FOUNDRY_PUSH_TOKEN before starting the bridge.");
}
let snapshot = null;
function sendJson(response, status, body) {
response.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
response.end(JSON.stringify(body));
}
function setCorsHeaders(request, response) {
const origin = request.headers.origin;
if (!origin) return true;
if (!allowedOrigins.has(origin)) return false;
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Vary", "Origin");
return true;
}
function hasBearerToken(request, expectedToken) {
const match = /^Bearer\s+(.+)$/i.exec(request.headers.authorization || "");
if (!match) return false;
const actual = Buffer.from(match[1]);
const expected = Buffer.from(expectedToken);
return actual.length === expected.length && timingSafeEqual(actual, expected);
}
function readJson(request) {
return new Promise((resolve, reject) => {
const chunks = [];
let bytes = 0;
let tooLarge = false;
request.on("data", (chunk) => {
bytes += chunk.length;
if (bytes > maxBodySize) {
tooLarge = true;
chunks.length = 0;
return;
}
if (!tooLarge) chunks.push(chunk);
});
request.on("end", () => {
if (tooLarge) {
reject(Object.assign(new Error("Snapshot is too large."), { status: 413 }));
return;
}
try {
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch {
reject(Object.assign(new Error("Request body must be valid JSON."), { status: 400 }));
}
});
request.on("error", reject);
});
}
function currentSnapshot(response) {
if (!snapshot) {
sendJson(response, 503, { status: "error", msg: "foundry.not-ready" });
return null;
}
return snapshot;
}
function sendData(response, data, current) {
const ageMs = Date.now() - current.syncedAtMs;
sendJson(response, 200, {
status: "ok",
data,
world: current.world,
syncedAt: new Date(current.syncedAtMs).toISOString(),
ageSeconds: Math.floor(ageMs / 1000),
stale: ageMs > 120000,
});
}
function decodePathSegment(segment) {
try {
return decodeURIComponent(segment);
} catch {
return null;
}
}
// --- Core icon library -----------------------------------------------------
// Foundry keeps the icons it ships in the `icons/` folder of its data directory:
// thousands of images over a folder tree of their own. The campaign's icon window
// browses that tree, so the bridge lists one folder per request and pages the
// icons inside it. It never reads outside `icons/`.
const iconRoot = "icons";
const iconExtensions = new Set([".svg", ".png", ".webp", ".jpg", ".jpeg", ".gif", ".avif"]);
const defaultIconPageSize = 120;
const maxIconPageSize = 500;
function normalizeIconDirectory(input) {
const raw = String(input ?? "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
if (!raw || raw === ".") return iconRoot;
const segments = raw.split("/").filter((segment) => segment && segment !== ".");
if (!segments.length || segments.includes("..") || segments[0] !== iconRoot) return null;
return segments.join("/");
}
function readIconDirectory(dir, offset, limit) {
const root = path.resolve(dataPath, iconRoot);
const target = path.resolve(dataPath, dir);
if (target !== root && !target.startsWith(root + path.sep)) return null;
const directories = [];
const files = [];
for (const entry of fs.readdirSync(target, { withFileTypes: true })) {
const entryPath = path.posix.join(dir, entry.name);
if (entry.isDirectory()) directories.push(entryPath);
else if (entry.isFile() && iconExtensions.has(path.extname(entry.name).toLowerCase())) files.push(entryPath);
}
directories.sort((a, b) => a.localeCompare(b));
files.sort((a, b) => a.localeCompare(b));
const page = files.slice(offset, offset + limit);
return {
// Subfolders always come back whole: the window needs every one of them to
// navigate, and there are never many. Paging covers the icons.
directories,
files: page,
offset,
next: offset + page.length < files.length ? offset + page.length : null,
};
}
function sendIconListing(request, response) {
if (!dataPath) return sendJson(response, 503, { status: "error", msg: "foundry.errors.icons-unavailable" });
const params = new URL(request.url, "http://localhost").searchParams;
const dir = normalizeIconDirectory(params.get("dir"));
if (!dir) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const requestedLimit = Number(params.get("limit"));
const limit = Number.isFinite(requestedLimit)
? Math.min(maxIconPageSize, Math.max(1, Math.trunc(requestedLimit)))
: defaultIconPageSize;
const requestedOffset = Number(params.get("offset"));
const offset = Number.isFinite(requestedOffset) ? Math.max(0, Math.trunc(requestedOffset)) : 0;
try {
const listing = readIconDirectory(dir, offset, limit);
if (!listing) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
sendJson(response, 200, { status: "ok", dir, ...listing });
} catch (error) {
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return;
}
console.error(`Could not list the Foundry icon folder ${dir}.`, error);
sendJson(response, 500, { status: "error", msg: "foundry.errors.icons-unavailable" });
}
}
const server = http.createServer(async (request, response) => {
if (!setCorsHeaders(request, response)) {
sendJson(response, 403, { status: "error", msg: "foundry.origin-not-allowed" });
return;
}
if (request.method === "OPTIONS") {
response.writeHead(204);
response.end();
return;
}
const pathname = new URL(request.url, "http://localhost").pathname;
if (request.method === "GET" && pathname === "/health") {
sendJson(response, 200, {
status: "ok",
ready: Boolean(snapshot),
syncedAt: snapshot ? new Date(snapshot.syncedAtMs).toISOString() : null,
});
return;
}
if (request.method === "POST" && pathname === "/internal/snapshot") {
if (!hasBearerToken(request, pushToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
try {
const body = await readJson(request);
if (!body.world?.id || !Array.isArray(body.actors) || !Array.isArray(body.items)
|| !body.actorItems || typeof body.actorItems !== "object" || Array.isArray(body.actorItems)) {
sendJson(response, 400, { status: "error", msg: "foundry.invalid-snapshot" });
return;
}
snapshot = {
world: body.world,
actors: body.actors,
items: body.items,
actorItems: body.actorItems,
syncedAtMs: Date.now(),
};
sendJson(response, 200, { status: "ok", syncedAt: new Date(snapshot.syncedAtMs).toISOString() });
} catch (error) {
sendJson(response, error.status || 400, { status: "error", msg: "foundry.invalid-snapshot" });
}
return;
}
if (request.method === "POST" && pathname === "/internal/heartbeat") {
if (!hasBearerToken(request, pushToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
try {
const body = await readJson(request);
if (!snapshot || !body.worldId || snapshot.world.id !== body.worldId) {
sendJson(response, 409, { status: "error", msg: "foundry.not-ready" });
return;
}
snapshot.syncedAtMs = Date.now();
sendJson(response, 200, { status: "ok", syncedAt: new Date(snapshot.syncedAtMs).toISOString() });
} catch (error) {
sendJson(response, error.status || 400, { status: "error", msg: "foundry.invalid-heartbeat" });
}
return;
}
if (request.method !== "GET" || !pathname.startsWith("/api/")) {
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return;
}
if (!hasBearerToken(request, readToken)) {
sendJson(response, 401, { status: "error", msg: "unauthorized" });
return;
}
// The icon library is on disk, not in the world snapshot, so it answers whether
// or not a GM client has published one yet.
if (pathname === "/api/icons") return sendIconListing(request, response);
const current = currentSnapshot(response);
if (!current) return;
if (pathname === "/api/world") return sendData(response, current.world, current);
if (pathname === "/api/actors") return sendData(response, current.actors, current);
if (pathname === "/api/characters") {
return sendData(response, current.actors.filter((actor) => actor.type === "character"), current);
}
if (pathname === "/api/items") return sendData(response, current.items, current);
const actorItemsMatch = /^\/api\/actors\/([^/]+)\/items$/.exec(pathname);
if (actorItemsMatch) {
const actorId = decodePathSegment(actorItemsMatch[1]);
if (!actorId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const actor = current.actors.find((entry) => entry._id === actorId || entry.id === actorId);
if (!actor) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, current.actorItems[actorId] || [], current);
}
const actorMatch = /^\/api\/actors\/([^/]+)$/.exec(pathname);
if (actorMatch) {
const actorId = decodePathSegment(actorMatch[1]);
if (!actorId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const actor = current.actors.find((entry) => entry._id === actorId || entry.id === actorId);
if (!actor) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, actor, current);
}
const itemMatch = /^\/api\/items\/([^/]+)$/.exec(pathname);
if (itemMatch) {
const itemId = decodePathSegment(itemMatch[1]);
if (!itemId) return sendJson(response, 400, { status: "error", msg: "errors.missing-data" });
const item = current.items.find((entry) => entry._id === itemId || entry.id === itemId);
if (!item) return sendJson(response, 404, { status: "error", msg: "errors.notfound" });
return sendData(response, item, current);
}
sendJson(response, 404, { status: "error", msg: "errors.notfound" });
});
server.listen(port, host, () => {
console.info(`Dragonroll Foundry bridge listening on ${host}:${port}`);
});