Foundry and discord bot
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s

This commit is contained in:
2026-10-11 22:26:29 +02:00
parent a2b512699a
commit 1402045001
65 changed files with 5962 additions and 144 deletions

View File

@@ -0,0 +1,258 @@
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 FoundryLinkRequest = require('../models/FoundryLinkRequest');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 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 };
}
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;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.actors)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const actors = [];
for (const source of req.body.actors) {
const mapping = await saveFoundryActor(campaign, source, req.body.fullSync === true);
if (mapping) actors.push(mapping);
}
if (req.body.fullSync === true) {
const currentIds = req.body.actors
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await Actor.deleteMany({
campaign: campaign._id,
foundryActorId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', actors });
} 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' });
}
});
module.exports = router;