const crypto = require('node:crypto'); const express = require('express'); const mongoose = require('mongoose'); const router = express.Router(); const Campaign = require('../models/Campaign'); const Actor = require('../models/Actor'); const Item = require('../models/Item'); const Folder = require('../models/Folder'); const { foundryActorToCharacter } = require('../services/actor-foundry'); const { foundryItemToItemData } = require('../services/item-foundry'); const { joinFoundryAssetUrl } = require('../services/foundry-icons'); const serviceLinks = require('../services/service-links'); // Upper bound for the Foundry names remembered per synced item (see Item model). const MAX_FOUNDRY_NAMES = 20; function codeHash(code) { return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex'); } function readSyncToken(req) { const match = /^Bearer\s+(.+)$/i.exec(req.get('authorization') || ''); return match?.[1] || ''; } async function syncCampaign(req, res) { const token = readSyncToken(req); if (!token) { res.json({ status: 'error', msg: 'unauthorized' }); return null; } const campaign = await Campaign.findOne({ foundrySyncTokenHash: codeHash(token) }); if (!campaign?.foundryWorldId) { res.json({ status: 'error', msg: 'unauthorized' }); return null; } return campaign; } function requestMatchesWorld(campaign, worldId) { return typeof worldId === 'string' && worldId === campaign.foundryWorldId; } // Foundry serves its data directory from the world's own address, which is the one the // campaign keeps under `settings.integrations.foundryUrl` — the icon window already loads // the world's icons through it. The module sends the images it publishes as absolute URLs; // the bridge's snapshot and older modules carry Foundry's relative paths, and a sheet // reading one of those against Dragonroll's upload folder finds nothing, which is how the // icons stopped loading (Syndria98/dragonroll#89). An absolute URL travels as it is, and so // does a path when the campaign has no world address to read it against. function worldAssetUrl(image, worldUrl) { const value = String(image ?? '').trim(); if (!value || /^(https?:|data:|\/\/)/i.test(value)) return value; return joinFoundryAssetUrl(worldUrl, value) || value; } // The images a world document arrives with, read against its world before they land. function resolveWorldAssets(fields, campaign) { const worldUrl = campaign?.settings?.integrations?.foundryUrl; if (typeof fields.image === 'string') fields.image = worldAssetUrl(fields.image, worldUrl); if (Array.isArray(fields.inventory)) { for (const entry of fields.inventory) entry.icon = worldAssetUrl(entry.icon, worldUrl); } if (Array.isArray(fields.features)) { for (const entry of fields.features) entry.icon = worldAssetUrl(entry.icon, worldUrl); } } async function saveFoundryActor(campaign, source, fullSync = false, replace = false) { const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120); const fields = foundryActorToCharacter(source || {}, replace); if (!foundryActorId || !fields.name) return null; resolveWorldAssets(fields, campaign); let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId }); const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId; if (!actor && mongoose.isValidObjectId(dragonrollActorId)) { actor = await Actor.findOne({ _id: dragonrollActorId, campaign: campaign._id }); } if (!actor) { const possibleMatches = await Actor.find({ campaign: campaign._id, name: fields.name, foundryActorId: { $exists: false } }).limit(2); actor = possibleMatches.length === 1 ? possibleMatches[0] : new Actor({ campaign: campaign._id }); } actor.foundryActorId = foundryActorId; // `created` says whether this row is new: whoever imports a whole world counts // the rows it made apart from the ones it only wrote over. const created = actor.isNew; // A full snapshot runs when a GM reconnects. Preserve existing Dragonroll // edits then; live Foundry change events continue to overwrite normally. if (!fullSync || actor.isNew) Object.assign(actor, fields); await actor.save(); return { foundryActorId, actorId: actor.id, created }; } // The campaign's item list mirrors the world's item directory and nothing else // (Syndria98/dragonroll#67). The items embedded in an actor are that character's own // inventory: they travel with the actor document (see services/actor-foundry.js), so a // snapshot feeds Item rows from the world directory (`body.items`) alone and gear a // character merely carries stays on its sheet instead of standing in the item list. function snapshotItemSources(body) { return Array.isArray(body.items) ? body.items : []; } async function saveFoundryItem(campaign, source, fullSync = false, folders = null) { const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120); const fields = foundryItemToItemData(source || {}); if (!foundryItemId || !fields) return null; resolveWorldAssets(fields, campaign); let item = await Item.findOne({ campaign: campaign._id, foundryItemId }); const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId; if (!item && mongoose.isValidObjectId(dragonrollItemId)) { const flagged = await Item.findOne({ _id: dragonrollItemId, campaign: campaign._id }); // Only adopt a flagged item while no other Foundry document owns its mapping. if (flagged && (!flagged.foundryItemId || flagged.foundryItemId === foundryItemId)) item = flagged; } if (!item) { // A world item can share its name with a Dragonroll row the campaign made by // hand, or with one it renamed away from. Keep a single item per name so a // piece of gear the world sends folds into that row instead of doubling it. const sameName = await Item.find({ campaign: campaign._id, $or: [{ name: fields.name }, { foundryNames: fields.name }] }).limit(4); const represented = sameName.find((candidate) => candidate.foundryItemId); if (represented) return { foundryItemId, itemId: represented.id }; const unclaimed = sameName.filter((candidate) => !candidate.foundryItemId); item = unclaimed.length === 1 ? unclaimed[0] : new Item({ campaign: campaign._id, name: fields.name }); } item.foundryItemId = foundryItemId; // `created` says whether this row is new: whoever imports a whole world counts // the rows it made apart from the ones it only wrote over. const created = item.isNew; if (!fullSync || item.isNew) Object.assign(item, fields); // Foundry's own icon is kept on every save, not only when the edits above // land: the item window offers it back after the user picked their own. if (fields.image) item.foundryImage = fields.image; if (!item.foundryNames.includes(fields.name)) { item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES); } // Which folder of the campaign's item tree the world says this item stands in. // `undefined` means the push says nothing about folders — an older module that // knows nothing about them — and the item stays where it is. The world owns the // folder of its own directory, so a move it reports lands on a full snapshot too // and wins over one a campaign made from its item list. const folder = resolveFoundryItemFolder(source, folders); if (folder !== undefined) item.folder = folder; await item.save(); return { foundryItemId, itemId: item.id, created }; } async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) { const items = []; for (const source of sources) { const mapping = await saveFoundryItem(campaign, source, fullSync, folders); if (mapping) items.push(mapping); } return items; } // --- Item folders ------------------------------------------------------------ // A Foundry world groups its item directory into folders; the campaign mirrors that // tree as Folders of target 'item' so its item list reads like the world's. Every // push from a module that knows about folders carries the whole world tree, and // names the folder each world item it sends stands in. Only the world's item // directory reaches the campaign's item list, so only its folders are mirrored; the // inventory folders an actor keeps for itself are none of the item list's business. // The colour a pushed folder carries. `undefined` means the push says nothing about // colours — an older module, which knows nothing about them — and the colour the // campaign has stays; `null` is the world leaving a folder uncoloured, which takes // the campaign's colour off along with it. Anything else is the colour to show. function foundryFolderColor(source) { if (source?.color === undefined) return undefined; const color = typeof source.color === 'string' ? source.color.trim() : ''; return color || null; } // Parents before children, so a folder is mapped before the one nested in it. // A folder whose parent is missing, or caught in a cycle, becomes a root. function orderFoundryFolderSources(sources) { const byId = new Map(); for (const source of sources) { const id = String(source?.id || '').trim().slice(0, 120); const name = String(source?.name || '').trim(); if (!id || !name) continue; byId.set(id, { id, name, parent: String(source?.parent || '').trim().slice(0, 120), color: foundryFolderColor(source) }); } const ordered = []; const placed = new Set(); const visiting = new Set(); function place(id) { if (!byId.has(id) || placed.has(id) || visiting.has(id)) return; visiting.add(id); place(byId.get(id).parent); visiting.delete(id); placed.add(id); ordered.push(byId.get(id)); } for (const id of byId.keys()) place(id); return ordered; } // The campaign folders mirroring the world's item folder tree, keyed by the Foundry // folder id so pushing the same tree again neither doubles a folder nor loses the // items filed in it. Rows the campaign made for its own items (no foundryFolderId) // are left alone: the world does not know them. async function syncFoundryItemFolders(campaign, folderSources) { const folders = new Map(); for (const folder of await Folder.find({ campaign: campaign._id, target: 'item' })) { if (folder.foundryFolderId) folders.set(String(folder.foundryFolderId), folder); } const ordered = orderFoundryFolderSources(folderSources); const inTree = new Set(ordered.map((source) => source.id)); for (const source of ordered) { let folder = folders.get(source.id); if (!folder) { folder = new Folder({ campaign: campaign._id, target: 'item', foundryFolderId: source.id, name: source.name }); } // The world owns this tree, so unlike an item's fields a rename or a move // lands whatever kind of push carried it: the whole tree arrives with each. folder.name = source.name; // The colour the world shows for the folder arrives here with the tree. if (source.color !== undefined) folder.color = source.color; const parent = inTree.has(source.parent) ? folders.get(source.parent) : null; folder.parentFolder = parent ? parent._id : null; await folder.save(); folders.set(source.id, folder); } // Folders the world no longer has go with it, and the items standing in them // move to the root instead of pointing at a folder that is not there. const staleIds = [...folders.values()] .filter((folder) => folder.foundryFolderId && !inTree.has(String(folder.foundryFolderId))) .map((folder) => folder._id); if (staleIds.length) { await Item.updateMany({ campaign: campaign._id, folder: { $in: staleIds } }, { $set: { folder: null } }); await Folder.deleteMany({ campaign: campaign._id, _id: { $in: staleIds } }); } return folders; } // The folder of a pushed item: undefined when the push says nothing about folders, // null for the root of the item directory, and the campaign folder otherwise. An // id the tree does not know puts the item at the root rather than nowhere. function resolveFoundryItemFolder(source, folders) { const foundryFolderId = source?.dragonroll?.folder; if (!folders || typeof foundryFolderId !== 'string') return undefined; return folders.get(foundryFolderId.trim())?._id || null; } // Linking a world to a campaign happens through the sign-up link every service // uses (routes/service-link.js); what stays here is the sync that world keeps up // with the campaign once that link has handed it its token. // The Foundry module shows this in its settings: the sync token alone only proves // a link was made once, so the module asks which campaign it belongs to and hears // back nothing but `unauthorized` once that campaign unlinks the world again. router.get('/sync/status', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; res.set('Cache-Control', 'no-store'); res.json({ status: 'ok', campaign: { id: campaign.id, name: campaign.name }, worldId: campaign.foundryWorldId }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); router.post('/sync/snapshot', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; const actorSources = Array.isArray(req.body.actors) ? req.body.actors : null; const itemSources = Array.isArray(req.body.items) ? req.body.items : null; if (!requestMatchesWorld(campaign, req.body.worldId) || (!actorSources && !itemSources)) { return res.json({ status: 'error', msg: 'errors.missing-data' }); } const fullSync = req.body.fullSync === true; // A forced actor sync from the module's context menu replaces the campaign's // row for the actors it sends entirely (Syndria98/dragonroll#96). It stays // clear of fullSync: it never prunes, unlike a reconnect's full snapshot. const replace = req.body.replace === true; // A module that knows nothing about item folders sends neither the tree // nor the folder of an item, and then nothing here touches the folders. const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null; const actors = []; for (const source of actorSources || []) { const mapping = await saveFoundryActor(campaign, source, fullSync, replace); if (mapping) actors.push(mapping); } const itemFolders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null; const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync, itemFolders); if (fullSync && actorSources) { const currentIds = actorSources .map((source) => String(source?._id || source?.id || '').trim()) .filter(Boolean); await Actor.deleteMany({ campaign: campaign._id, foundryActorId: { $exists: true, $nin: currentIds } }); } // Pruning needs a full snapshot: only that request sees the whole world // directory, so it alone knows which synced rows the world has let go of. if (fullSync && itemSources) { const currentIds = snapshotItemSources(req.body) .map((source) => String(source?._id || source?.id || '').trim()) .filter(Boolean); await Item.deleteMany({ campaign: campaign._id, foundryItemId: { $exists: true, $nin: currentIds } }); } res.json({ status: 'ok', actors, items }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); // Live Foundry item edits: upserts only, never prunes items. Removing items that no // longer exist is left to the full snapshot sent with the actors. Item folders are // the exception: every request carries the world's whole folder tree, so a folder // the world dropped is dropped here too, and a push may carry folders only. router.post('/sync/item-snapshot', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null; if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) { return res.json({ status: 'error', msg: 'errors.missing-data' }); } const folders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null; res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items, false, folders) }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); router.post('/sync/delete', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; const foundryActorId = String(req.body.foundryActorId || '').trim(); if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryActorId) { return res.json({ status: 'error', msg: 'errors.missing-data' }); } await Actor.deleteOne({ campaign: campaign._id, foundryActorId }); res.json({ status: 'ok' }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); // Only world-level Foundry items reach this route: an item dropped by an actor // still exists in the world, and its actor snapshot overwrites the inventory. router.post('/sync/item-delete', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; const foundryItemId = String(req.body.foundryItemId || '').trim(); if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryItemId) { return res.json({ status: 'error', msg: 'errors.missing-data' }); } await Item.deleteOne({ campaign: campaign._id, foundryItemId }); res.json({ status: 'ok' }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); // A world letting its campaign go from the module settings: the campaign forgets // the world and the token this request used stops working, so the world is free // to pair again — and the campaign's settings stop listing it as connected. router.post('/sync/unlink', async (req, res) => { try { const campaign = await syncCampaign(req, res); if (!campaign) return; if (!requestMatchesWorld(campaign, req.body.worldId)) { return res.json({ status: 'error', msg: 'errors.missing-data' }); } await serviceLinks.unlinkFoundryWorld(campaign); res.json({ status: 'ok' }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); } }); module.exports = router; // The writers every Foundry document goes through: the sync pushes above, and the // force import a campaign asks for from its sidebar (routes/foundry.js). One set of // rules decides which campaign row a world document owns, so pulling a world over // twice updates its rows instead of doubling them. module.exports.saveFoundryActor = saveFoundryActor; module.exports.saveFoundryItem = saveFoundryItem;