const http = require("node:http"); 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; 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; } } 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; } 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}`); });