const crypto = require('node:crypto'); const jwt = require('jsonwebtoken'); const ServiceLinkRequest = require('../models/ServiceLinkRequest'); const Campaign = require('../models/Campaign'); const keys = require('./keys'); // How long a sign-up link waits for somebody to open it. const LINK_TTL_MS = 10 * 60 * 1000; // How long the Discord bot can still confirm an authorization it was away for. const NOTIFICATION_WINDOW_MS = 15 * 60 * 1000; // The token the Obsidian plugin gets back is its long-lived credential: a plugin cannot ask // somebody to open the sign-up link again every 48 hours. It carries the id of the link so that // revoking the link works right away — see services/passport.js. const OBSIDIAN_TOKEN_TTL = '365d'; // Every service that connects to a campaign does it the same way: it asks the // backend for a sign-up link, shows it to the person sitting in front of it, // and picks its credential up once a Dragonroll user has signed in through that // link and chosen a campaign. `botOnly` services are the ones that can prove // who they are to the backend; the others can only be trusted with their own // link, which is why what they get from a link is decided by the user. const SERVICES = { foundry: { name: 'Foundry VTT' }, discord: { name: 'Discord', botOnly: true }, obsidian: { name: 'Obsidian' }, }; function isService(value) { return Object.prototype.hasOwnProperty.call(SERVICES, value); } function serviceName(service) { return SERVICES[service]?.name || service; } function isBotOnly(service) { return SERVICES[service]?.botOnly === true; } function codeHash(code) { return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex'); } function newLinkCode() { return crypto.randomBytes(32).toString('base64url'); } function frontendBaseUrl() { return (process.env.DRAGONROLL_FRONTEND_URL || 'http://localhost:3000').trim().replace(/\/+$/, ''); } // The sign-up link a service shows: it opens the Dragonroll page where somebody // signs in and picks the campaign. The code travels in the fragment, so the // browser never sends it to the server. function signUpLinkUrl(service, code) { return `${frontendBaseUrl()}/link/authorize?service=${encodeURIComponent(service)}#code=${encodeURIComponent(code)}`; } // The bot talks to the backend with a shared secret instead of a login, so a // Discord server cannot be claimed by somebody who merely knows its id. function isDiscordBot(req) { const configuredSecret = process.env.DRAGONROLL_DISCORD_BOT_SECRET?.trim() || ''; const suppliedSecret = req.get('x-dragonroll-discord-bot-secret') || ''; const expected = Buffer.from(configuredSecret); const supplied = Buffer.from(suppliedSecret); return !!expected.length && expected.length === supplied.length && crypto.timingSafeEqual(expected, supplied); } function requireDiscordBot(req, res, next) { if (!isDiscordBot(req)) { return res.status(401).json({ status: 'error', msg: 'errors.unauthorized' }); } return next(); } function readText(value, max) { return typeof value === 'string' ? value.trim().slice(0, max) : ''; } // Whatever else a service says about itself: the Foundry system it runs, the // Discord user id behind the person who asked... Values are kept short and // plain, because they come from a service and end up shown to a user. function readMeta(source) { const meta = {}; for (const [key, value] of Object.entries(source).slice(0, MAX_META_ENTRIES)) { if (value === null || value === undefined || typeof value === 'boolean') { if (typeof value === 'boolean') meta[key] = value; continue; } if (typeof value !== 'string' && typeof value !== 'number') continue; meta[key] = String(value).trim().slice(0, MAX_META_VALUE_LENGTH); } return meta; } // How a service describes itself: which world/server/vault is asking, on whose // behalf, and the little that goes with it. function readTarget(body) { const source = body?.target && typeof body.target === 'object' ? body.target : {}; const target = { targetId: readText(source.id, 120), targetName: readText(source.name, 200), targetUser: readText(source.user, 120), targetMeta: source.meta && typeof source.meta === 'object' && !Array.isArray(source.meta) ? readMeta(source.meta) : {} }; if (typeof target.targetMeta.url === 'string') { try { const url = new URL(target.targetMeta.url); target.targetMeta.url = url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : ''; } catch { target.targetMeta.url = ''; } } return target; } function linkIsExpired(request) { return request?.state === 'pending' && (!request.expiresAt || request.expiresAt <= new Date()); } // A service asking again reuses its own row: one world, one Discord server and // one vault each have a single link, and asking for it replaces the last one. async function startServiceLink(service, target) { const code = newLinkCode(); const expiresAt = new Date(Date.now() + LINK_TTL_MS); const request = await ServiceLinkRequest.findOneAndUpdate( { service: service, targetId: target.targetId }, { $set: { service: service, targetId: target.targetId, targetName: target.targetName, targetUser: target.targetUser, targetMeta: target.targetMeta, codeHash: codeHash(code), state: 'pending', expiresAt: expiresAt }, $unset: { campaign: 1, dragonrollUser: 1, credentials: 1, linkedAt: 1, pickedUpAt: 1, notifiedAt: 1 } }, { new: true, upsert: true, setDefaultsOnInsert: true } ); return { request, code, url: signUpLinkUrl(service, code), expiresAt }; } async function findServiceLinkByCode(code) { if (!code) return null; return ServiceLinkRequest.findOne({ codeHash: codeHash(code) }).select('+credentials').lean(); } // The credential that belongs to a link is handed over once and then dropped: // whoever loses it starts the link again from the service, which is where they // got the link from in the first place. async function takeServiceLinkCredentials(request) { const credentials = request?.credentials || null; if (!credentials) return null; await ServiceLinkRequest.updateOne( { _id: request._id }, { $set: { pickedUpAt: new Date() }, $unset: { credentials: 1 } } ); return credentials; } // The user who owns the campaign picked it for this link. async function completeServiceLink(request, campaign, user, credentials = null) { request.campaign = campaign._id; request.dragonrollUser = user.id; request.state = 'linked'; request.linkedAt = new Date(); request.pickedUpAt = null; request.notifiedAt = null; request.credentials = credentials || undefined; // An answered link is the record of a live connection: it stays until the // service re-links or the campaign unlinks it. request.expiresAt = null; await request.save(); return request; } // A campaign dropping a service: the link stops being valid, and the service // finds that out the next time it asks. async function revokeServiceLink(service, campaignId) { const result = await ServiceLinkRequest.updateMany( { service: service, campaign: campaignId, state: 'linked' }, { $set: { state: 'revoked', campaign: null }, $unset: { credentials: 1, linkedAt: 1 } } ); return result.matchedCount; } // What a campaign has connected to it, newest link first and one row per // service, so the campaign settings can list its services together. async function listLinkedServices(campaignId) { const links = await ServiceLinkRequest.find({ campaign: campaignId, state: 'linked' }) .sort({ linkedAt: -1 }) .lean(); const seen = new Set(); const services = []; for (const link of links) { if (seen.has(link.service)) continue; seen.add(link.service); services.push({ service: link.service, name: serviceName(link.service), targetId: link.targetId || '', targetName: link.targetName || '', targetUser: link.targetUser || '', dragonrollUser: link.dragonrollUser || null, linkedAt: link.linkedAt }); } return services; } module.exports = { LINK_TTL_MS, NOTIFICATION_WINDOW_MS, SERVICES, codeHash, completeServiceLink, findServiceLinkByCode, isBotOnly, isDiscordBot, isService, linkIsExpired, listLinkedServices, readTarget, requireDiscordBot, revokeServiceLink, serviceName, signUpLinkUrl, startServiceLink, takeServiceLinkCredentials };