210 lines
8.9 KiB
JavaScript
210 lines
8.9 KiB
JavaScript
const crypto = require('node:crypto');
|
|
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
const passport = require('passport');
|
|
const rateLimit = require('express-rate-limit');
|
|
const router = express.Router();
|
|
|
|
const Campaign = require('../models/Campaign');
|
|
const DiscordGuildLink = require('../models/DiscordGuildLink');
|
|
const secret = require('../services/keys').secret;
|
|
const serviceLinks = require('../services/service-links');
|
|
|
|
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 40 });
|
|
|
|
const GUILD_ID = /^\d{5,25}$/;
|
|
|
|
// What the sign-up screen shows about the request behind a code.
|
|
function publicRequest(request) {
|
|
return {
|
|
service: request.service,
|
|
serviceName: serviceLinks.serviceName(request.service),
|
|
targetName: request.targetName,
|
|
targetUser: request.targetUser,
|
|
system: request.targetMeta?.system || '',
|
|
expiresAt: request.expiresAt
|
|
};
|
|
}
|
|
|
|
// A session for a service that keeps working once the browser which authorised
|
|
// it is gone: Obsidian gets the same kind of session signing in gives, so its
|
|
// notes keep travelling over the routes they always used.
|
|
function userSession(user) {
|
|
const payload = {
|
|
_id: user._id,
|
|
username: user.username,
|
|
name: user.name,
|
|
email: user.email,
|
|
admin: user.admin,
|
|
settings: user.settings
|
|
};
|
|
return jwt.sign(payload, secret, { expiresIn: 172800 });
|
|
}
|
|
|
|
// A Foundry world tells Dragonroll who it is when it asks for its link, so the
|
|
// user only has to say which campaign the world may work on.
|
|
async function completeFoundryLink(campaign, request) {
|
|
const linkedElsewhere = await Campaign.findOne({
|
|
foundryWorldId: request.targetId,
|
|
_id: { $ne: campaign._id }
|
|
}).select('_id');
|
|
if (linkedElsewhere) return { msg: 'foundry.errors.world-already-linked' };
|
|
|
|
campaign.foundryWorldId = request.targetId;
|
|
campaign.foundryWorldTitle = request.targetName;
|
|
campaign.foundrySystem = request.targetMeta?.system || '';
|
|
|
|
const settings = campaign.settings && typeof campaign.settings === 'object' ? campaign.settings : {};
|
|
const integrations = settings.integrations && typeof settings.integrations === 'object' ? settings.integrations : {};
|
|
const foundryUrl = request.targetMeta?.url || '';
|
|
if (foundryUrl && !integrations.foundryUrl) {
|
|
campaign.settings = { ...settings, integrations: { ...integrations, foundryUrl } };
|
|
}
|
|
|
|
const syncToken = crypto.randomBytes(32).toString('base64url');
|
|
campaign.foundrySyncTokenHash = serviceLinks.codeHash(syncToken);
|
|
await campaign.save();
|
|
|
|
const bridgeUrl = process.env.FOUNDRY_API_CLIENT_URL || process.env.FOUNDRY_API_URL;
|
|
const pushToken = process.env.FOUNDRY_API_PUSH_TOKEN;
|
|
return {
|
|
credentials: {
|
|
syncToken,
|
|
bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null
|
|
}
|
|
};
|
|
}
|
|
|
|
// The Discord account behind the request is the one the bot answers to; a new
|
|
// authorization takes the server over from whoever held it before.
|
|
async function completeDiscordLink(campaign, request, user) {
|
|
await Campaign.updateMany(
|
|
{ discordGuildId: request.targetId, createdBy: { $ne: user.id } },
|
|
{ $unset: { discordGuildId: 1 } }
|
|
);
|
|
|
|
await DiscordGuildLink.findOneAndUpdate({ guildId: request.targetId }, {
|
|
$set: {
|
|
discordUserId: request.targetMeta?.userId || request.targetId,
|
|
dragonrollUser: user.id,
|
|
connectedAt: new Date()
|
|
}
|
|
}, { new: true, upsert: true, setDefaultsOnInsert: true });
|
|
|
|
campaign.discordGuildId = request.targetId;
|
|
await campaign.save();
|
|
}
|
|
|
|
// A service asks for a sign-up link and shows it to whoever is sitting in front
|
|
// of it. Nothing is linked until a Dragonroll user opens that link, signs in and
|
|
// picks one of their campaigns.
|
|
router.post('/start', linkRateLimit, async (req, res) => {
|
|
try {
|
|
const service = String(req.body.service || '').trim();
|
|
if (!serviceLinks.isService(service)) return res.json({ status: 'error', msg: 'link.errors.unknown-service' });
|
|
|
|
// A service that can prove who it is gets its link checked: a Discord
|
|
// server is claimed by whoever runs the bot, not by whoever knows its id.
|
|
if (serviceLinks.isBotOnly(service) && !serviceLinks.isDiscordBot(req)) {
|
|
return res.status(401).json({ status: 'error', msg: 'errors.unauthorized' });
|
|
}
|
|
|
|
const target = serviceLinks.readTarget(req.body);
|
|
if (!target.targetId) return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
if (service === 'discord' && (!GUILD_ID.test(target.targetId) || !target.targetName || !target.targetUser)) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const link = await serviceLinks.startServiceLink(service, target);
|
|
res.set('Cache-Control', 'no-store');
|
|
res.json({ status: 'ok', service, code: link.code, linkUrl: link.url, expiresAt: link.expiresAt });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// What a sign-up link is about, so the screen can name the world, Discord server
|
|
// or vault that is waiting, and the person who asked.
|
|
router.post('/details', async (req, res) => {
|
|
try {
|
|
res.set('Cache-Control', 'no-store');
|
|
const request = await serviceLinks.findServiceLinkByCode(req.body.code);
|
|
if (!request || serviceLinks.linkIsExpired(request)) {
|
|
return res.json({ status: 'error', msg: 'link.errors.expired' });
|
|
}
|
|
|
|
res.json({ status: 'ok', ...publicRequest(request) });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// The user who signs in through a link owns the campaigns listed there, so
|
|
// picking one of them is the whole authorization.
|
|
router.post('/complete', passport.authenticate('jwt', { session: false }), async (req, res) => {
|
|
try {
|
|
res.set('Cache-Control', 'no-store');
|
|
const request = await serviceLinks.findServiceLinkByCode(req.body.code);
|
|
if (!request || serviceLinks.linkIsExpired(request)) {
|
|
return res.json({ status: 'error', msg: 'link.errors.expired' });
|
|
}
|
|
|
|
const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: req.user.id });
|
|
if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
if (request.service === 'discord' && campaign.discordGuildId && campaign.discordGuildId !== request.targetId) {
|
|
return res.json({ status: 'error', msg: 'discord.errors.campaign-already-linked' });
|
|
}
|
|
|
|
if (request.service === 'foundry') {
|
|
const linked = await completeFoundryLink(campaign, request);
|
|
if (linked.msg) return res.json({ status: 'error', msg: linked.msg });
|
|
await serviceLinks.completeServiceLink(request, campaign, req.user, linked.credentials);
|
|
} else if (request.service === 'discord') {
|
|
await completeDiscordLink(campaign, request, req.user);
|
|
await serviceLinks.completeServiceLink(request, campaign, req.user);
|
|
} else {
|
|
await serviceLinks.completeServiceLink(request, campaign, req.user, { token: userSession(req.user) });
|
|
}
|
|
|
|
res.json({ status: 'ok', service: request.service, campaign: { id: campaign.id, name: campaign.name } });
|
|
} 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' });
|
|
}
|
|
});
|
|
|
|
// Where a link stands, and what the service that asked for it gets out of it.
|
|
// A credential is delivered once: a service that loses it asks for a new link.
|
|
router.post('/pickup', async (req, res) => {
|
|
try {
|
|
res.set('Cache-Control', 'no-store');
|
|
const request = await serviceLinks.findServiceLinkByCode(req.body.code);
|
|
if (!request || serviceLinks.linkIsExpired(request)) {
|
|
return res.json({ status: 'ok', state: 'expired' });
|
|
}
|
|
if (request.state !== 'linked') {
|
|
return res.json({ status: 'ok', state: request.state, campaign: null });
|
|
}
|
|
|
|
const campaign = await Campaign.findOne({ _id: request.campaign }).select('_id name').lean();
|
|
const credentials = await serviceLinks.takeServiceLinkCredentials(request);
|
|
res.json({
|
|
status: 'ok',
|
|
state: 'linked',
|
|
service: request.service,
|
|
campaign: campaign ? { id: String(campaign._id), name: campaign.name } : null,
|
|
syncToken: credentials?.syncToken || '',
|
|
bridgeConfig: credentials?.bridgeConfig || null,
|
|
token: credentials?.token || ''
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|