All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m6s
408 lines
16 KiB
JavaScript
408 lines
16 KiB
JavaScript
const crypto = require('node:crypto');
|
|
const express = require('express');
|
|
const rateLimit = require('express-rate-limit');
|
|
const mongoose = require('mongoose');
|
|
const router = express.Router();
|
|
|
|
const Campaign = require('../models/Campaign');
|
|
const Actor = require('../models/Actor');
|
|
const Item = require('../models/Item');
|
|
const FoundryLinkRequest = require('../models/FoundryLinkRequest');
|
|
const { foundryActorToCharacter } = require('../services/actor-foundry');
|
|
const { foundryItemToItemData } = require('../services/item-foundry');
|
|
|
|
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
|
|
|
|
// 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;
|
|
}
|
|
|
|
async function saveFoundryActor(campaign, source, fullSync = false) {
|
|
const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120);
|
|
const fields = foundryActorToCharacter(source || {});
|
|
if (!foundryActorId || !fields.name) return null;
|
|
|
|
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;
|
|
// 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 };
|
|
}
|
|
|
|
// A snapshot carries world-level items plus the items embedded in every actor it
|
|
// sends. World items are listed first so they own a name before its copies.
|
|
function snapshotItemSources(body) {
|
|
const sources = [];
|
|
if (Array.isArray(body.items)) sources.push(...body.items);
|
|
if (Array.isArray(body.actors)) {
|
|
for (const actor of body.actors) {
|
|
if (Array.isArray(actor?.items)) sources.push(...actor.items);
|
|
}
|
|
}
|
|
return sources;
|
|
}
|
|
|
|
async function saveFoundryItem(campaign, source, fullSync = false) {
|
|
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
|
|
const fields = foundryItemToItemData(source || {});
|
|
if (!foundryItemId || !fields) return null;
|
|
|
|
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) {
|
|
// The same gear exists more than once in Foundry: once in the world
|
|
// directory and once inside each actor carrying it. Keep a single
|
|
// Dragonroll item per name so inventories do not flood the Item list.
|
|
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;
|
|
if (!fullSync || item.isNew) Object.assign(item, fields);
|
|
if (!item.foundryNames.includes(fields.name)) {
|
|
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
|
|
}
|
|
await item.save();
|
|
return { foundryItemId, itemId: item.id };
|
|
}
|
|
|
|
async function syncFoundryItems(campaign, sources, fullSync = false) {
|
|
const items = [];
|
|
for (const source of sources) {
|
|
const mapping = await saveFoundryItem(campaign, source, fullSync);
|
|
if (mapping) items.push(mapping);
|
|
}
|
|
return items;
|
|
}
|
|
|
|
function readWorld(body) {
|
|
const world = body?.world;
|
|
if (!world || typeof world.id !== 'string' || !world.id.trim()) return null;
|
|
|
|
let foundryUrl = '';
|
|
if (typeof world.url === 'string') {
|
|
try {
|
|
const url = new URL(world.url);
|
|
if (url.protocol === 'http:' || url.protocol === 'https:') foundryUrl = url.origin;
|
|
} catch {}
|
|
}
|
|
|
|
return {
|
|
worldId: world.id.trim().slice(0, 120),
|
|
worldTitle: typeof world.title === 'string' ? world.title.trim().slice(0, 200) : '',
|
|
system: typeof world.system === 'string' ? world.system.trim().slice(0, 120) : '',
|
|
foundryUrl
|
|
};
|
|
}
|
|
|
|
async function attachWorldToCampaign(campaign, world) {
|
|
const linkedElsewhere = await Campaign.findOne({
|
|
foundryWorldId: world.worldId,
|
|
_id: { $ne: campaign._id }
|
|
}).select('_id');
|
|
if (linkedElsewhere) return false;
|
|
|
|
campaign.foundryWorldId = world.worldId;
|
|
campaign.foundryWorldTitle = world.worldTitle;
|
|
campaign.foundrySystem = world.system;
|
|
if (world.foundryUrl) {
|
|
const settings = campaign.settings && typeof campaign.settings === 'object' ? campaign.settings : {};
|
|
const integrations = settings.integrations && typeof settings.integrations === 'object'
|
|
? settings.integrations
|
|
: {};
|
|
campaign.settings = {
|
|
...settings,
|
|
integrations: {
|
|
...integrations,
|
|
foundryUrl: integrations.foundryUrl || world.foundryUrl
|
|
}
|
|
};
|
|
}
|
|
await campaign.save();
|
|
return true;
|
|
}
|
|
|
|
async function expireOtherPendingLinks(campaignId, userId, requestId) {
|
|
await FoundryLinkRequest.updateMany({
|
|
source: 'dragonroll',
|
|
campaign: campaignId,
|
|
createdBy: userId,
|
|
completedAt: null,
|
|
_id: { $ne: requestId }
|
|
}, { $set: { expiresAt: new Date() } });
|
|
}
|
|
|
|
router.post('/link/complete', linkRateLimit, async (req, res) => {
|
|
try {
|
|
const world = readWorld(req.body);
|
|
if (!world || typeof req.body.code !== 'string' || !req.body.code.trim()) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const request = await FoundryLinkRequest.findOne({
|
|
codeHash: codeHash(req.body.code),
|
|
source: 'dragonroll',
|
|
expiresAt: { $gt: new Date() },
|
|
completedAt: null
|
|
});
|
|
if (!request) return res.json({ status: 'error', msg: 'foundry.errors.link-expired' });
|
|
|
|
const campaign = await Campaign.findOne({ _id: request.campaign, createdBy: request.createdBy });
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
|
|
const attached = await attachWorldToCampaign(campaign, world);
|
|
if (!attached) return res.json({ status: 'error', msg: 'foundry.errors.world-already-linked' });
|
|
|
|
const syncToken = crypto.randomBytes(32).toString('base64url');
|
|
campaign.foundrySyncTokenHash = codeHash(syncToken);
|
|
await campaign.save();
|
|
|
|
request.worldId = world.worldId;
|
|
request.worldTitle = world.worldTitle;
|
|
request.system = world.system;
|
|
request.foundryUrl = world.foundryUrl;
|
|
request.completedAt = new Date();
|
|
request.code = undefined; // Redeemed: keep only the hash from now on.
|
|
await request.save();
|
|
await expireOtherPendingLinks(campaign._id, request.createdBy, request._id);
|
|
|
|
const bridgeUrl = process.env.FOUNDRY_API_CLIENT_URL || process.env.FOUNDRY_API_URL;
|
|
const pushToken = process.env.FOUNDRY_API_PUSH_TOKEN;
|
|
res.set('Cache-Control', 'no-store');
|
|
res.json({
|
|
status: 'ok',
|
|
world: { id: world.worldId, title: world.worldTitle, system: world.system },
|
|
syncToken,
|
|
bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
if (err.code === 11000) return res.json({ status: 'error', msg: 'foundry.errors.world-already-linked' });
|
|
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;
|
|
const actors = [];
|
|
for (const source of actorSources || []) {
|
|
const mapping = await saveFoundryActor(campaign, source, fullSync);
|
|
if (mapping) actors.push(mapping);
|
|
}
|
|
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync);
|
|
|
|
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 world
|
|
// directory and every actor's copies at the same time.
|
|
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. Removing items that no
|
|
// longer exist is left to the full snapshot sent with the actors.
|
|
router.post('/sync/item-snapshot', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) });
|
|
} 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' });
|
|
}
|
|
});
|
|
|
|
router.get('/sync/characters', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const actors = await Actor.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
|
res.json({ status: 'ok', actors });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/sync/map', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const { actorId, foundryActorId, worldId } = req.body;
|
|
if (!requestMatchesWorld(campaign, worldId) || !actorId || !foundryActorId) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const actor = await Actor.findOne({ _id: actorId, campaign: campaign._id });
|
|
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
const existing = await Actor.findOne({ campaign: campaign._id, foundryActorId, _id: { $ne: actor._id } });
|
|
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.actor-already-synced' });
|
|
|
|
actor.foundryActorId = String(foundryActorId).trim().slice(0, 120);
|
|
await actor.save();
|
|
res.json({ status: 'ok', actor });
|
|
} 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' });
|
|
}
|
|
});
|
|
|
|
router.get('/sync/items', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
|
res.json({ status: 'ok', items });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/sync/map-item', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const { itemId, foundryItemId, worldId } = req.body;
|
|
if (!requestMatchesWorld(campaign, worldId) || !itemId || !foundryItemId) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const item = await Item.findOne({ _id: itemId, campaign: campaign._id });
|
|
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
const existing = await Item.findOne({ campaign: campaign._id, foundryItemId, _id: { $ne: item._id } });
|
|
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.item-already-synced' });
|
|
|
|
item.foundryItemId = String(foundryItemId).trim().slice(0, 120);
|
|
await item.save();
|
|
res.json({ status: 'ok', item });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|