From 0a8452b3c84deb577a68c92537814bdfeaedf757 Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Wed, 14 Oct 2026 14:07:52 +0000 Subject: [PATCH 1/3] Fix issue #19: Add unified campaign sync --- backend/src/index.js | 24 +- backend/src/models/DiscordLinkRequest.js | 20 - backend/src/models/FoundryLinkRequest.js | 24 -- backend/src/models/ServiceLinkRequest.js | 44 ++ backend/src/routes/campaign.js | 121 ++---- backend/src/routes/discord.js | 142 ++----- backend/src/routes/foundry-link.js | 114 +---- backend/src/routes/service-link.js | 209 +++++++++ backend/src/services/service-links.js | 254 +++++++++++ discord-bot/src/dragonroll-api.js | 16 +- dragonroll-foundry/scripts/api.js | 220 ++++++---- frontend/app/app.vue | 16 +- .../app/components/views/DiscordAuthorize.vue | 260 ------------ .../components/views/ServiceLinkAuthorize.vue | 395 ++++++++++++++++++ .../windows/CampaignSettingsWindow.vue | 197 ++++----- frontend/i18n/locales/ca/campaigns.json | 31 +- frontend/i18n/locales/ca/link.json | 35 ++ frontend/i18n/locales/en/campaigns.json | 31 +- frontend/i18n/locales/en/link.json | 35 ++ frontend/i18n/locales/es/campaigns.json | 31 +- frontend/i18n/locales/es/link.json | 35 ++ tests/foundry-pairing-status.test.js | 136 +++--- 22 files changed, 1469 insertions(+), 921 deletions(-) delete mode 100644 backend/src/models/DiscordLinkRequest.js delete mode 100644 backend/src/models/FoundryLinkRequest.js create mode 100644 backend/src/models/ServiceLinkRequest.js create mode 100644 backend/src/routes/service-link.js create mode 100644 backend/src/services/service-links.js delete mode 100644 frontend/app/components/views/DiscordAuthorize.vue create mode 100644 frontend/app/components/views/ServiceLinkAuthorize.vue create mode 100644 frontend/i18n/locales/ca/link.json create mode 100644 frontend/i18n/locales/en/link.json create mode 100644 frontend/i18n/locales/es/link.json diff --git a/backend/src/index.js b/backend/src/index.js index b6258b6e..9e1c103a 100644 --- a/backend/src/index.js +++ b/backend/src/index.js @@ -40,19 +40,22 @@ require('./services/passport')(passport); // CORS app.use(cookieParser()); -const foundryCorsPaths = [ - '/api/foundry/link/complete', '/foundry/link/complete', +// Services talk to Dragonroll from their own application (a Foundry world, an +// Obsidian vault, the Discord bot), so their link routes cannot be limited to +// one origin. What they may do is decided by the link code each of them holds. +const openCorsPaths = [ '/api/foundry/sync', '/foundry/sync', + '/api/link/start', '/link/start', + '/api/link/pickup', '/link/pickup', ]; -const foundryCors = cors({ +const openCors = cors({ origin: true, methods: ['GET', 'POST', 'OPTIONS'], - allowedHeaders: ['Authorization', 'Content-Type'], + allowedHeaders: ['Authorization', 'Content-Type', 'X-Dragonroll-Discord-Bot-Secret'], }); -app.use('/api/foundry/link/complete', foundryCors); -app.use('/foundry/link/complete', foundryCors); -app.use('/api/foundry/sync', foundryCors); -app.use('/foundry/sync', foundryCors); +for (const path of openCorsPaths) { + app.use(path, openCors); +} const appCors = cors({ origin: 'http://localhost:3000', @@ -66,6 +69,11 @@ app.use((req, res, next) => { // ROUTES (NO AUTH) app.use('/api/user', require('./routes/user')); app.use('/api/discord', require('./routes/discord')); +// The one way every service (Foundry, Discord, Obsidian) links itself to a +// campaign: it asks for a sign-up link, a user opens it and picks the campaign. +// Each service authenticates with its own proof: the Discord bot with its +// secret, Foundry and Obsidian with the link code they were handed. +app.use('/api/link', require('./routes/service-link')); app.use('/api/foundry', require('./routes/foundry-link')); app.use('/foundry', require('./routes/foundry-link')); diff --git a/backend/src/models/DiscordLinkRequest.js b/backend/src/models/DiscordLinkRequest.js deleted file mode 100644 index 0a239a11..00000000 --- a/backend/src/models/DiscordLinkRequest.js +++ /dev/null @@ -1,20 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -const DiscordLinkRequestSchema = new Schema({ - codeHash: { type: String, required: true, unique: true }, - guildId: { type: String, required: true }, - guildName: { type: String, required: true }, - discordUserId: { type: String, required: true }, - discordUserName: { type: String, required: true }, - dragonrollUser: { type: Schema.Types.ObjectId, ref: 'User' }, - createdAt: { type: Date, default: Date.now }, - expiresAt: { type: Date, required: true }, - completedAt: { type: Date }, - // Quan el bot ja ha confirmat a Discord que aquesta autoritzacio s'ha fet. - notifiedAt: { type: Date } -}); - -DiscordLinkRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); - -module.exports = mongoose.model('DiscordLinkRequest', DiscordLinkRequestSchema); diff --git a/backend/src/models/FoundryLinkRequest.js b/backend/src/models/FoundryLinkRequest.js deleted file mode 100644 index 3f02327d..00000000 --- a/backend/src/models/FoundryLinkRequest.js +++ /dev/null @@ -1,24 +0,0 @@ -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -const FoundryLinkRequestSchema = new Schema({ - codeHash: { type: String, required: true, unique: true }, - // Kept in clear text so the campaign settings screen can re-display a pending - // pairing code after a reload or a backend restart. It is only ever returned - // to the user who created the request and is cleared once the link completes. - code: { type: String }, - source: { type: String, enum: ['dragonroll'], required: true }, - campaign: { type: Schema.Types.ObjectId, ref: 'Campaign' }, - createdBy: { type: Schema.Types.ObjectId, ref: 'User' }, - worldId: { type: String }, - worldTitle: { type: String }, - system: { type: String }, - foundryUrl: { type: String }, - createdAt: { type: Date, default: Date.now }, - expiresAt: { type: Date, required: true }, - completedAt: { type: Date } -}); - -FoundryLinkRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); - -module.exports = mongoose.model('FoundryLinkRequest', FoundryLinkRequestSchema); diff --git a/backend/src/models/ServiceLinkRequest.js b/backend/src/models/ServiceLinkRequest.js new file mode 100644 index 00000000..6e2f1a13 --- /dev/null +++ b/backend/src/models/ServiceLinkRequest.js @@ -0,0 +1,44 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +// One row per service installation that wants to use a campaign: a Foundry +// world, a Discord server, an Obsidian vault. Asking for a link resets the row +// to a fresh pending request, so a service always has one row and that row is +// also the record of the link that is active right now. +// +// The service starts the request and shows the sign-up link it gets back; a +// Dragonroll user then signs in through that link and picks the campaign. The +// service picks its credential up with the same code it was given. +const ServiceLinkRequestSchema = new Schema({ + service: { type: String, enum: ['foundry', 'discord', 'obsidian'], required: true }, + // Who is asking, in its own terms: Foundry world id, Discord guild id, vault id. + targetId: { type: String }, + targetName: { type: String }, + // The person who asked, as far as the service knows: GM name, Discord user... + targetUser: { type: String }, + // Whatever else the service describes itself with (Foundry system and URL). + targetMeta: { type: Object }, + codeHash: { type: String, required: true, unique: true }, + campaign: { type: Schema.Types.ObjectId, ref: 'Campaign' }, + dragonrollUser: { type: Schema.Types.ObjectId, ref: 'User' }, + // 'pending' until a Dragonroll user picks a campaign through the sign-up + // link, 'linked' while that choice stands, 'revoked' once the campaign + // unlinked the service again. + state: { type: String, enum: ['pending', 'linked', 'revoked'], default: 'pending' }, + // What the service gets when it picks the link up: the Foundry sync token, + // the Obsidian session. Dropped as soon as it has been delivered. + credentials: { type: Object, select: false }, + createdAt: { type: Date, default: Date.now }, + // Only a request nobody answers expires: an empty value keeps the link. + expiresAt: { type: Date }, + linkedAt: { type: Date }, + pickedUpAt: { type: Date }, + // The Discord bot has confirmed this authorization in Discord. + notifiedAt: { type: Date } +}); + +ServiceLinkRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); +ServiceLinkRequestSchema.index({ service: 1, targetId: 1 }); +ServiceLinkRequestSchema.index({ campaign: 1, service: 1, state: 1 }); + +module.exports = mongoose.model('ServiceLinkRequest', ServiceLinkRequestSchema); diff --git a/backend/src/routes/campaign.js b/backend/src/routes/campaign.js index c2b366d8..c90b4c09 100644 --- a/backend/src/routes/campaign.js +++ b/backend/src/routes/campaign.js @@ -1,24 +1,28 @@ const express = require('express') const router = express.Router(); -const crypto = require('node:crypto'); const Campaign = require("../models/Campaign"); -const FoundryLinkRequest = require('../models/FoundryLinkRequest'); +const User = require('../models/User'); +const serviceLinks = require('../services/service-links'); -const FOUNDRY_LINK_TTL_MS = 10 * 60 * 1000; +// Every service links to a campaign through the same sign-up link +// (routes/service-link.js); a campaign only drops one of them again. +async function unlinkService(campaign, service) { + if (service === 'foundry') { + campaign.foundryWorldId = undefined; + campaign.foundryWorldTitle = undefined; + campaign.foundrySystem = undefined; + campaign.set('foundrySyncTokenHash', undefined); + } else if (service === 'discord') { + // The Discord account the bot answers to stays: the server is simply + // left without a campaign until somebody picks one again. + campaign.discordGuildId = undefined; + } -function foundryCodeHash(code) { - return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex'); -} - -async function expirePendingFoundryLinks(campaignId, userId) { - const filter = { - source: 'dragonroll', - campaign: campaignId, - createdBy: userId, - completedAt: null - }; - await FoundryLinkRequest.updateMany(filter, { $set: { expiresAt: new Date() } }); + await campaign.save(); + // A link a service still holds becomes invalid, and it finds that out the + // next time it asks where its link stands. + await serviceLinks.revokeServiceLink(service, campaign._id); } router.post('/create', async (req, res) => { @@ -74,73 +78,26 @@ router.post('/update', async (req, res) => { } }); -router.post('/foundry-link/start', async (req, res) => { - try { - const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: req.user.id }); - if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' }); - - await expirePendingFoundryLinks(campaign._id, req.user.id); - const code = crypto.randomBytes(24).toString('base64url'); - const expiresAt = new Date(Date.now() + FOUNDRY_LINK_TTL_MS); - const request = await FoundryLinkRequest.create({ - codeHash: foundryCodeHash(code), - code, - source: 'dragonroll', - campaign: campaign._id, - createdBy: req.user.id, - expiresAt - }); - - res.set('Cache-Control', 'no-store'); - res.json({ status: 'ok', code, requestId: request.id, expiresAt }); - } catch (err) { - console.error(err); - res.json({ status: 'error', msg: 'errors.internal' }); - } -}); - -router.get('/foundry-link/status/:requestId', async (req, res) => { - try { - const request = await FoundryLinkRequest.findOne({ - _id: req.params.requestId, - source: 'dragonroll', - createdBy: req.user.id - }); - if (!request) return res.json({ status: 'ok', state: 'expired' }); - if (!request.completedAt && request.expiresAt <= new Date()) { - return res.json({ status: 'ok', state: 'expired' }); - } - if (!request.completedAt) return res.json({ status: 'ok', state: 'pending' }); - - const campaign = await Campaign.findOne({ _id: request.campaign, createdBy: req.user.id }); - if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' }); - res.json({ status: 'ok', state: 'complete', campaign }); - } catch (err) { - console.error(err); - res.json({ status: 'error', msg: 'errors.internal' }); - } -}); - -// Returns the still-valid pending pairing request for a campaign, so the -// settings window can restore its pairing code across reloads and restarts. -router.get('/foundry-link/pending', async (req, res) => { +// Which services a campaign has connected, and the account each of them was +// authorized with. +router.get('/services', async (req, res) => { try { const campaign = await Campaign.findOne({ _id: req.query.campaignId, createdBy: req.user.id }); if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' }); - const request = await FoundryLinkRequest.findOne({ - source: 'dragonroll', - campaign: campaign._id, - createdBy: req.user.id, - completedAt: null, - expiresAt: { $gt: new Date() } - }).sort({ createdAt: -1 }); - if (!request) return res.json({ status: 'ok', request: null }); + const links = await serviceLinks.listLinkedServices(campaign._id); + const userIds = [...new Set(links.map((link) => String(link.dragonrollUser ?? '')).filter(Boolean))]; + const users = userIds.length + ? await User.find({ _id: { $in: userIds } }).select('username name').lean() + : []; + const names = new Map(users.map((user) => [String(user._id), user.username || user.name])); - res.set('Cache-Control', 'no-store'); res.json({ status: 'ok', - request: { requestId: request.id, code: request.code, expiresAt: request.expiresAt } + services: links.map((link) => ({ + ...link, + dragonrollUserName: names.get(String(link.dragonrollUser ?? '')) || null + })) }); } catch (err) { console.error(err); @@ -148,18 +105,16 @@ router.get('/foundry-link/pending', async (req, res) => { } }); -router.post('/foundry-unlink', async (req, res) => { +router.post('/service-unlink', async (req, res) => { try { + const service = String(req.body.service || '').trim(); + if (!serviceLinks.isService(service)) return res.json({ status: 'error', msg: 'errors.missing-data' }); + const campaign = await Campaign.findOne({ _id: req.body.campaignId, createdBy: req.user.id }); if (!campaign) return res.json({ status: 'error', msg: 'errors.notfound' }); - campaign.foundryWorldId = undefined; - campaign.foundryWorldTitle = undefined; - campaign.foundrySystem = undefined; - campaign.set('foundrySyncTokenHash', undefined); - await campaign.save(); - await expirePendingFoundryLinks(campaign._id, req.user.id); - res.json({ status: 'ok', campaign }); + await unlinkService(campaign, service); + res.json({ status: 'ok', campaign, services: await serviceLinks.listLinkedServices(campaign._id) }); } catch (err) { console.error(err); res.json({ status: 'error', msg: 'errors.internal' }); diff --git a/backend/src/routes/discord.js b/backend/src/routes/discord.js index 00612213..66e96766 100644 --- a/backend/src/routes/discord.js +++ b/backend/src/routes/discord.js @@ -1,124 +1,25 @@ -const crypto = require('node:crypto'); const express = require('express'); -const passport = require('passport'); const router = express.Router(); const Actor = require('../models/Actor'); const Campaign = require('../models/Campaign'); const DiscordGuildLink = require('../models/DiscordGuildLink'); -const DiscordLinkRequest = require('../models/DiscordLinkRequest'); +const ServiceLinkRequest = require('../models/ServiceLinkRequest'); const User = require('../models/User'); +const serviceLinks = require('../services/service-links'); -const LINK_TTL_MS = 10 * 60 * 1000; -const NOTIFICATION_WINDOW_MS = 15 * 60 * 1000; const NOTIFICATION_LIMIT = 10; +const requireBot = serviceLinks.requireDiscordBot; + function validGuildId(value) { return /^\d{5,25}$/.test(String(value ?? '')); } -function codeHash(code) { - return crypto.createHash('sha256').update(String(code ?? '')).digest('hex'); -} - -function requireBot(req, res, next) { - 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); - - if (!expected.length || expected.length !== supplied.length || !crypto.timingSafeEqual(expected, supplied)) { - return res.status(401).json({ status: 'error', msg: 'errors.unauthorized' }); - } - return next(); -} - -function frontendAuthorizeUrl() { - const frontendUrl = (process.env.DRAGONROLL_FRONTEND_URL || 'http://localhost:3000').trim().replace(/\/+$/, ''); - return `${frontendUrl}/discord/authorize`; -} - -// La pantalla d'autorització l'serveix el frontend. El codi viatja al fragment de la URL i el -// navegador no l'envia mai al servidor, així que els enllaços antics del bot arriben a la -// pantalla sense codi i demanen de tornar a executar /dragonroll connect. -router.get('/authorize', (req, res) => { - res.set('Cache-Control', 'no-store'); - res.set('Referrer-Policy', 'no-referrer'); - res.set('X-Content-Type-Options', 'nosniff'); - res.redirect(302, frontendAuthorizeUrl()); -}); - -router.post('/link/start', requireBot, async (req, res) => { - try { - const { guildId, guildName, discordUserId, discordUserName } = req.body; - if (!validGuildId(guildId) || !/^\d{5,25}$/.test(String(discordUserId ?? '')) || !guildName || !discordUserName) { - return res.json({ status: 'error', msg: 'errors.missing-data' }); - } - - const code = crypto.randomBytes(32).toString('base64url'); - await DiscordLinkRequest.create({ - codeHash: codeHash(code), - guildId: String(guildId), - guildName: String(guildName).slice(0, 100), - discordUserId: String(discordUserId), - discordUserName: String(discordUserName).slice(0, 100), - expiresAt: new Date(Date.now() + LINK_TTL_MS) - }); - - res.json({ status: 'ok', code, expiresAt: new Date(Date.now() + LINK_TTL_MS) }); - } catch (err) { - console.error(err); - res.json({ status: 'error', msg: 'errors.internal' }); - } -}); - -router.post('/link/details', async (req, res) => { - try { - res.set('Cache-Control', 'no-store'); - const request = await DiscordLinkRequest.findOne({ - codeHash: codeHash(req.body.code), - expiresAt: { $gt: new Date() }, - completedAt: null - }).lean(); - if (!request) return res.json({ status: 'error', msg: 'discord.errors.link-expired' }); - - res.json({ status: 'ok', guildName: request.guildName, discordUserName: request.discordUserName }); - } catch (err) { - console.error(err); - res.json({ status: 'error', msg: 'errors.internal' }); - } -}); - -router.post('/link/complete', passport.authenticate('jwt', { session: false }), async (req, res) => { - try { - const request = await DiscordLinkRequest.findOneAndUpdate({ - codeHash: codeHash(req.body.code), - expiresAt: { $gt: new Date() }, - completedAt: null - }, { - $set: { completedAt: new Date(), dragonrollUser: req.user.id } - }, { new: true }); - if (!request) return res.json({ status: 'error', msg: 'discord.errors.link-expired' }); - - await Campaign.updateMany( - { discordGuildId: request.guildId, createdBy: { $ne: req.user.id } }, - { $unset: { discordGuildId: 1 } } - ); - - await DiscordGuildLink.findOneAndUpdate({ guildId: request.guildId }, { - $set: { - discordUserId: request.discordUserId, - dragonrollUser: req.user.id, - connectedAt: new Date() - } - }, { new: true, upsert: true, setDefaultsOnInsert: true }); - - res.json({ status: 'ok', guildName: request.guildName }); - } catch (err) { - console.error(err); - res.json({ status: 'error', msg: 'errors.internal' }); - } -}); +// Connecting a Discord server is the service link of issue: the bot asks +// /api/link/start for a sign-up link, and whoever opens it signs in and picks the +// campaign this server may read. What is left here is what the bot needs once +// that link exists: confirming it in Discord and working with its campaign. async function dragonrollUserNames(requests) { const userIds = [...new Set(requests.map((request) => String(request.dragonrollUser ?? '')).filter(Boolean))]; @@ -132,16 +33,18 @@ async function dragonrollUserNames(requests) { // mateix evita que dos processos del bot confirmïn la mateixa vegada. router.post('/bot/link-requests/notifications', requireBot, async (req, res) => { try { - const pending = await DiscordLinkRequest.find({ - completedAt: { $gte: new Date(Date.now() - NOTIFICATION_WINDOW_MS) }, + const pending = await ServiceLinkRequest.find({ + service: 'discord', + state: 'linked', + linkedAt: { $gte: new Date(Date.now() - serviceLinks.NOTIFICATION_WINDOW_MS) }, notifiedAt: null - }).select('_id guildId guildName discordUserId discordUserName dragonrollUser') + }).select('_id targetId targetName targetUser targetMeta dragonrollUser campaign') .limit(NOTIFICATION_LIMIT) .lean(); const claimed = []; for (const request of pending) { - const taken = await DiscordLinkRequest.findOneAndUpdate( + const taken = await ServiceLinkRequest.findOneAndUpdate( { _id: request._id, notifiedAt: null }, { $set: { notifiedAt: new Date() } }, { new: true } @@ -150,15 +53,22 @@ router.post('/bot/link-requests/notifications', requireBot, async (req, res) => } const names = await dragonrollUserNames(claimed); + const campaignIds = [...new Set(claimed.map((request) => String(request.campaign ?? '')).filter(Boolean))]; + const campaigns = campaignIds.length + ? await Campaign.find({ _id: { $in: campaignIds } }).select('_id name').lean() + : []; + const campaignNames = new Map(campaigns.map((campaign) => [String(campaign._id), campaign.name])); + res.json({ status: 'ok', notifications: claimed.map((request) => ({ id: String(request._id), - guildId: request.guildId, - guildName: request.guildName, - discordUserId: request.discordUserId, - discordUserName: request.discordUserName, - dragonrollUserName: names.get(String(request.dragonrollUser ?? '')) || null + guildId: request.targetId, + guildName: request.targetName, + discordUserId: request.targetMeta?.userId || '', + discordUserName: request.targetUser, + dragonrollUserName: names.get(String(request.dragonrollUser ?? '')) || null, + campaignName: campaignNames.get(String(request.campaign ?? '')) || null })) }); } catch (err) { diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index e7aa9c73..33062571 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -1,18 +1,14 @@ 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; @@ -129,113 +125,9 @@ async function syncFoundryItems(campaign, sources, fullSync = false) { 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', - campaign: { id: campaign.id, name: campaign.name }, - 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' }); - } -}); +// 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 diff --git a/backend/src/routes/service-link.js b/backend/src/routes/service-link.js new file mode 100644 index 00000000..7020a14f --- /dev/null +++ b/backend/src/routes/service-link.js @@ -0,0 +1,209 @@ +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; diff --git a/backend/src/services/service-links.js b/backend/src/services/service-links.js new file mode 100644 index 00000000..e99ee8e9 --- /dev/null +++ b/backend/src/services/service-links.js @@ -0,0 +1,254 @@ +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 +}; diff --git a/discord-bot/src/dragonroll-api.js b/discord-bot/src/dragonroll-api.js index 0b995285..6c60a6c1 100644 --- a/discord-bot/src/dragonroll-api.js +++ b/discord-bot/src/dragonroll-api.js @@ -47,11 +47,23 @@ function createDragonrollApi(config) { return payload; } + // The backend hands out the sign-up link the person opens to pick a campaign, + // so the bot never builds one itself: every service shows the same link. async function startAuthorization(guildId, guildName, discordUserId, discordUserName) { - return request('/discord/link/start', { + const payload = await request('/link/start', { method: 'POST', - body: JSON.stringify({ guildId, guildName, discordUserId, discordUserName }) + body: JSON.stringify({ + service: 'discord', + target: { + id: String(guildId), + name: guildName, + user: discordUserName, + meta: { userId: String(discordUserId) } + } + }) }); + if (!payload.linkUrl) throw new Error('Dragonroll did not provide a sign-up link. Update the Dragonroll backend.'); + return payload; } async function claimLinkNotifications() { diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index 9618bb0f..a309e2eb 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -4,25 +4,24 @@ const SETTING_PUSH_TOKEN = "pushToken"; const SETTING_BRIDGE_CONFIG = "bridgeConfig"; const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl"; const SETTING_LINK_CODE = "linkCode"; +const SETTING_LINK_URL = "linkUrl"; const SETTING_PAIRING_STATUS = "pairingStatus"; const SETTING_SYNC_TOKEN = "syncToken"; const SETTING_AUTO_SYNC = "autoSync"; +// How often a world asks Dragonroll whether its sign-up link has been answered. +const LINK_POLL_MS = 5000; let syncTimeout; let syncInProgress = false; let syncRequested = false; -let handlingLinkCode = false; -let updatingLinkCodeSetting = false; -let linkRetriesDisabled = false; -const FATAL_LINK_ERRORS = new Set([ - "foundry.errors.link-expired", - "foundry.errors.world-already-linked", -]); +let askingForLink = false; +let checkingLink = false; +let updatingLinkSetting = false; // Marks a pairing Dragonroll honoured once and no longer accepts: the campaign // unlinked this world, so the token this client holds is dead. const PAIRING_REVOKED = "revoked"; let updatingPairingStatus = false; let linkedCampaignName = ""; -let pairingProblem = ""; +let linkProblem = ""; let actorSyncTimeout; let characterSyncRunning = false; let actorSyncErrorLogged = false; @@ -138,18 +137,24 @@ Hooks.once("init", () => { }); game.settings.register(MODULE_ID, SETTING_LINK_CODE, { - name: "Dragonroll Campaign Pairing Code", - hint: "Paste a pairing code created in Dragonroll campaign settings.", + name: "Dragonroll Connection Link Code", scope: "client", - config: true, + config: false, + type: String, + default: "", + }); + + game.settings.register(MODULE_ID, SETTING_LINK_URL, { + name: "Dragonroll Connection Link", + scope: "client", + config: false, type: String, default: "", - onChange: handleLinkCodeChange, }); game.settings.register(MODULE_ID, SETTING_PAIRING_STATUS, { name: "Dragonroll Pairing Status", - hint: "Whether this world is connected to a Dragonroll campaign. The module keeps this text up to date and the pairing lives in the browser of whoever linked the world: there is nothing to set here.", + hint: "Whether this world is connected to a Dragonroll campaign. The module keeps this text up to date: it asks Dragonroll for a sign-up link, and whoever opens that link picks the campaign. There is nothing to set here.", scope: "client", config: true, type: String, @@ -218,90 +223,113 @@ async function getDragonroll(path, token) { return result; } -function linkErrorMessage(error) { - const messages = { - "foundry.errors.link-expired": "The pairing code is invalid, expired, or already used.", - "foundry.errors.world-already-linked": "This Foundry world is already linked to another campaign.", +// --- Connecting a world ---------------------------------------------------- +// A world does not paste a code into its settings any more: it asks Dragonroll +// for the same sign-up link every service gets, the GM opens it and picks the +// campaign this world may work on. That link then hands the world its token. + +function worldLinkRequest() { + const world = api.getWorld(); + return { + service: "foundry", + target: { + id: world.id, + name: world.title, + user: game.user?.name || "", + meta: { system: world.system, url: world.url }, + }, }; - return messages[error.message] || error.message; } -async function setLinkCode(value) { - updatingLinkCodeSetting = true; +async function setLink(code, url) { + updatingLinkSetting = true; try { - await game.settings.set(MODULE_ID, SETTING_LINK_CODE, value); + await game.settings.set(MODULE_ID, SETTING_LINK_CODE, code); + await game.settings.set(MODULE_ID, SETTING_LINK_URL, url); } finally { - updatingLinkCodeSetting = false; + updatingLinkSetting = false; } } -function handleLinkCodeChange(value) { - if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return; - linkRetriesDisabled = false; - // A code typed by hand supersedes whatever went wrong with the last one. - pairingProblem = ""; - setPairingStatus(pairingStatusText()); - completeDragonrollCampaignLink(value.trim()); +async function requestDragonrollLink() { + if (askingForLink || !game.user?.isGM || !game.world) return; + askingForLink = true; + try { + const result = await postDragonroll("link/start", worldLinkRequest()); + linkProblem = ""; + await setLink(String(result.code || ""), String(result.linkUrl || "")); + ui.notifications?.info(`Open this link to pick the Dragonroll campaign for this world: ${result.linkUrl}`); + } catch (error) { + console.error(`${MODULE_ID} | Could not get a Dragonroll connection link.`, error); + linkProblem = error.message; + } finally { + askingForLink = false; + await setPairingStatus(pairingStatusText()); + } } -async function completeDragonrollCampaignLink(code, options = {}) { - if (handlingLinkCode) return; - handlingLinkCode = true; - const notifyOnError = options.notifyOnError !== false; - try { - if (!game.user?.isGM || !game.world) throw new Error("Open the world as a GM to link it."); - const result = await postDragonroll("foundry/link/complete", { code, world: api.getWorld() }); - let syncTokenStored = false; - if (result.syncToken) { - try { - await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, result.syncToken); - syncTokenStored = true; - } catch (error) { - console.error(`${MODULE_ID} | Could not save the character sync token.`, error); - } +// What a link leaves this client with once a campaign has been picked: the token +// its sync runs on, and the bridge settings that came with it. +async function applyDragonrollLink(result) { + let syncTokenStored = false; + if (result.syncToken) { + try { + await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, result.syncToken); + syncTokenStored = true; + } catch (error) { + console.error(`${MODULE_ID} | Could not save the character sync token.`, error); } - if (result.bridgeConfig?.url && result.bridgeConfig?.pushToken) { - try { - await game.settings.set(MODULE_ID, SETTING_BRIDGE_CONFIG, result.bridgeConfig); - } catch (error) { - console.error(`${MODULE_ID} | Could not save the bridge configuration.`, error); - ui.notifications?.warn("The world was linked, but its bridge settings could not be saved on this client."); - } - } - // Keep an unprocessed pairing code in the setting when its sync token could - // not be saved, so the retry below can complete the link again. - if (syncTokenStored || !result.syncToken) await setLinkCode(""); - if (!syncTokenStored) { - ui.notifications?.warn("The world was linked, but character sync is unavailable. Update Dragonroll and link the world again."); + } + if (result.bridgeConfig?.url && result.bridgeConfig?.pushToken) { + try { + await game.settings.set(MODULE_ID, SETTING_BRIDGE_CONFIG, result.bridgeConfig); + } catch (error) { + console.error(`${MODULE_ID} | Could not save the bridge configuration.`, error); + ui.notifications?.warn("This world was linked, but its bridge settings could not be saved on this client."); } + } + + linkedCampaignName = String(result.campaign?.name || "").trim(); + await setLink("", ""); + if (syncTokenStored) { + ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); scheduleSnapshotSync(0); setTimeout(initializeCharacterSync, 0); setTimeout(reconcileDragonrollItems, 2000); - linkedCampaignName = String(result.campaign?.name || "").trim(); - ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); - await setPairingStatus(pairingStatusText()); - } catch (error) { - console.error(`${MODULE_ID} | Could not complete the campaign link.`, error); - // Expired or already-used codes will never redeem, so stop the background - // retry; any error keeps retrying (the Dragonroll server may be restarting). - linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message); - // Only a code that can never be redeemed belongs in the status: while the - // retry is still running, waiting for Dragonroll is the honest text. - if (linkRetriesDisabled) pairingProblem = linkErrorMessage(error); - if (notifyOnError) ui.notifications?.error(linkErrorMessage(error)); - await setPairingStatus(pairingStatusText()); - } finally { - handlingLinkCode = false; + } else { + // Without a token this client cannot sync, and only a fresh link gives one. + linkProblem = "this client could not save the token it was given"; + ui.notifications?.warn("This world is linked to a Dragonroll campaign, but character sync is unavailable. Update Dragonroll and link the world again."); } } -// A pairing code entered while the Dragonroll server was unreachable (or just -// before Foundry restarted) stays in the setting; redeem it on world start so -// the connection survives restarts without typing the code in again. -async function resumePendingDragonrollLink(options = {}) { - if (handlingLinkCode || !game.user?.isGM || !game.world) return; +// Where the sign-up link stands: still waiting for the GM to pick a campaign, +// finished and handing its token over, or gone, in which case there is a new +// link to show instead of a world that quietly stops trying. +async function advanceDragonrollLink() { + if (askingForLink || checkingLink || !game.user?.isGM || !game.world || getSyncToken()) return; const code = game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim(); - if (code) await completeDragonrollCampaignLink(code, options); + if (!code) return requestDragonrollLink(); + + checkingLink = true; + try { + const result = await postDragonroll("link/pickup", { code }); + if (result.state === "pending") return; + if (result.state === "linked") await applyDragonrollLink(result); + else if (result.state === "revoked") { + linkProblem = PAIRING_REVOKED; + await setLink("", ""); + } else { + await setLink("", ""); + await requestDragonrollLink(); + } + } catch (error) { + // Dragonroll may be restarting: the next check asks again. + console.warn(`${MODULE_ID} | Could not check the Dragonroll connection link.`, error); + } finally { + checkingLink = false; + await setPairingStatus(pairingStatusText()); + } } // --- Pairing status -------------------------------------------------------- @@ -310,19 +338,22 @@ async function resumePendingDragonrollLink(options = {}) { // reads correctly from the first frame and is corrected by refreshPairingStatus. function pairingStatusText() { - if (pairingProblem === PAIRING_REVOKED) { - return "Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Create a new pairing code there to link it again."; + const link = game.settings.get(MODULE_ID, SETTING_LINK_URL)?.trim(); + if (linkProblem === PAIRING_REVOKED) { + return link + ? `Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Open ${link} to pick a campaign again.` + : "Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Its settings will show a link to pick one again."; } if (getSyncToken()) { return linkedCampaignName ? `Connected to the Dragonroll campaign "${linkedCampaignName}".` : "Connected to a Dragonroll campaign."; } - if (pairingProblem) return `Not connected: Dragonroll did not accept that pairing code (${pairingProblem})`; - if (game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim()) { - return "Not connected yet: waiting for Dragonroll to accept this pairing code."; + if (linkProblem) return `Not connected: Dragonroll did not answer this world's link (${linkProblem})`; + if (link) { + return `Not connected yet: open ${link} in a browser, sign in and pick the campaign for this world.`; } - return "Not connected to a Dragonroll campaign. Paste a pairing code from that campaign's settings to link this world."; + return "Not connected to a Dragonroll campaign. Set the Dragonroll Endpoint in these settings, then reload this world to get a sign-up link."; } async function setPairingStatus(text) { @@ -357,12 +388,19 @@ async function refreshPairingStatus() { try { const result = await getDragonroll("foundry/sync/status", token); linkedCampaignName = String(result.campaign?.name || "").trim(); - if (pairingProblem === PAIRING_REVOKED) pairingProblem = ""; + if (linkProblem === PAIRING_REVOKED) linkProblem = ""; } catch (error) { // An unauthorized token is a campaign that unlinked this world. Any other // failure (an unreachable Dragonroll, or one old enough to have no status // route) says nothing about the pairing, so keep showing what we know. - if (error.message === "unauthorized") pairingProblem = PAIRING_REVOKED; + if (error.message === "unauthorized") { + linkProblem = PAIRING_REVOKED; + linkedCampaignName = ""; + // The dead token is dropped so the world stops pushing to a campaign that + // no longer wants it, and its link check asks for a sign-up link again. + await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, ""); + ui.notifications?.warn("This world is no longer linked to its Dragonroll campaign. Its settings show the link to pick one again."); + } } await setPairingStatus(pairingStatusText()); } @@ -1140,11 +1178,13 @@ async function publishHeartbeat() { } Hooks.once("ready", () => { - resumePendingDragonrollLink().then(refreshPairingStatus); + advanceDragonrollLink().then(refreshPairingStatus); + // While this world has no campaign, its sign-up link is what the GM has to + // work with: keep showing it and keep asking whether it has been answered. setInterval(() => { - if (linkRetriesDisabled) return; - resumePendingDragonrollLink({ notifyOnError: false }); - }, 60000); + if (getSyncToken()) return; + advanceDragonrollLink(); + }, LINK_POLL_MS); setInterval(refreshPairingStatus, 60000); scheduleSnapshotSync(0); setInterval(publishHeartbeat, 60000); diff --git a/frontend/app/app.vue b/frontend/app/app.vue index 1ed6331e..09b7ca8c 100644 --- a/frontend/app/app.vue +++ b/frontend/app/app.vue @@ -2,7 +2,7 @@ import ContentManager from './components/managers/ContentManager.vue'; import ToastManager from './components/managers/ToastManager.vue'; import WindowManager from './components/managers/WindowManager.vue'; -import DiscordAuthorize from './components/views/DiscordAuthorize.vue'; +import ServiceLinkAuthorize from './components/views/ServiceLinkAuthorize.vue'; import { CreateWindow } from '@/services/Windows' import { GetUser, HasAdmin } from './services/User'; @@ -12,10 +12,14 @@ import { useCampaignService } from './services/Campaign'; const { RestoreCampaign } = useCampaignService(); -// El bot de Discord enllaça amb aquesta pantalla; no és part de l'aplicació i no ha d'arrencar -// les finestres normals. +// Els serveis (Discord, Foundry, Obsidian) enllacen amb aquesta pantalla única; no són part +// de l'aplicació i no han d'arrencar les finestres normals. La ruta antiga de Discord també +// hi porta, perquè els enllaços que ja corren per Discord no queden morts. const requestUrl = useRequestURL(); -const isDiscordAuthorize = computed(() => requestUrl.pathname.replace(/\/+$/, '') === '/discord/authorize'); +const isServiceLink = computed(() => { + const path = requestUrl.pathname.replace(/\/+$/, ''); + return path === '/link/authorize' || path === '/discord/authorize'; +}); async function start(){ if(GetUser()){ @@ -46,14 +50,14 @@ useHead({ onMounted(() => { setupTheme(); setTheme('dark'); - if(!isDiscordAuthorize.value){ + if(!isServiceLink.value){ start(); } })