From ed0b9af00b3587f474d3fe758cbe3ccaea0eeee7 Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Wed, 14 Oct 2026 12:59:26 +0000 Subject: [PATCH] Fix issue #17: Foundry Module: Show pairing status --- AGENTS.md | 4 + backend/src/routes/foundry-link.js | 21 +++ dragonroll-foundry/README.md | 9 ++ dragonroll-foundry/scripts/api.js | 92 ++++++++++- tests/foundry-pairing-status.test.js | 230 +++++++++++++++++++++++++++ tests/foundry-sync-toggle.test.js | 5 +- 6 files changed, 359 insertions(+), 2 deletions(-) create mode 100644 tests/foundry-pairing-status.test.js diff --git a/AGENTS.md b/AGENTS.md index 54ddca98..79200fd4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -239,6 +239,7 @@ not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is | `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted | | `GET /sync/characters` | Actors the module applies back into Foundry | | `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) | +| `GET /sync/status` | The campaign a sync token belongs to; the module shows it in its **Dragonroll Pairing Status** setting and treats `unauthorized` as the campaign having unlinked the world | | `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document | | `POST /sync/delete` | `{worldId, foundryActorId}` | @@ -258,6 +259,9 @@ Rules worth knowing before editing this: module queues no CRUD push, runs no periodic reconcile and sends no startup snapshot; the actor directory's `Dragonroll: Force Sync` entry still pushes the selected actors as an upsert (`fullSync:false`, so it never prunes). The read-only bridge snapshot is not gated by it. +- **`pairingStatus` is a setting the module writes, not the GM**: the module settings sentence about + whether this world is connected comes from the stored sync token plus the answer from + `/sync/status` (checked at world start and every minute), and anything typed into it is replaced. - `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`. - `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only bridge, only useful when `FOUNDRY_API_URL` is configured. diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index 77d5fea0..e7aa9c73 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -225,6 +225,7 @@ router.post('/link/complete', linkRateLimit, async (req, res) => { 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 @@ -236,6 +237,26 @@ router.post('/link/complete', linkRateLimit, async (req, res) => { } }); +// 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 +// back nothing but `unauthorized` once that campaign unlinks the world again. +router.get('/sync/status', async (req, res) => { + try { + const campaign = await syncCampaign(req, res); + if (!campaign) return; + + res.set('Cache-Control', 'no-store'); + res.json({ + status: 'ok', + campaign: { id: campaign.id, name: campaign.name }, + worldId: campaign.foundryWorldId + }); + } catch (err) { + console.error(err); + res.json({ status: 'error', msg: 'errors.internal' }); + } +}); + router.post('/sync/snapshot', async (req, res) => { try { const campaign = await syncCampaign(req, res); diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md index 940dc1a5..ff027261 100644 --- a/dragonroll-foundry/README.md +++ b/dragonroll-foundry/README.md @@ -41,6 +41,14 @@ For a local backend, use `http://localhost:5000`; the module omits `/api` and th the local pairing route at its root. Character synchronization works without the optional snapshot bridge. Configure that bridge only if you also need the read-only world snapshot API described below. +**Dragonroll Pairing Status** in the module settings always says whether this browser holds a pairing +and, once Dragonroll has answered `GET /api/foundry/sync/status`, which campaign the world is +connected to. It is written by the module, not by the GM: it appears as not connected until the world +is paired, names the campaign after a pairing or a check on world start and every minute afterwards, +gives the reason when a pairing code can never be redeemed, and says the world is no longer linked +once the campaign unlinks it. Because both the pairing code and the sync token are client settings, +another browser of the same world reads as not paired. + The campaign settings show the linked world's title and system. A Foundry world can be linked to only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry client and uses the one-time code instead of a Dragonroll login token. @@ -103,6 +111,7 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon | `POST /api/foundry/sync/item-delete` | A world item was deleted | | `GET /api/foundry/sync/characters` | Characters to apply back in Foundry | | `GET /api/foundry/sync/items` | Items to apply back in Foundry | +| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status | | `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document | | `POST /api/foundry/sync/delete` | An actor was deleted | diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index cd1f0f0c..9618bb0f 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -4,6 +4,7 @@ const SETTING_PUSH_TOKEN = "pushToken"; const SETTING_BRIDGE_CONFIG = "bridgeConfig"; const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl"; const SETTING_LINK_CODE = "linkCode"; +const SETTING_PAIRING_STATUS = "pairingStatus"; const SETTING_SYNC_TOKEN = "syncToken"; const SETTING_AUTO_SYNC = "autoSync"; let syncTimeout; @@ -16,6 +17,12 @@ const FATAL_LINK_ERRORS = new Set([ "foundry.errors.link-expired", "foundry.errors.world-already-linked", ]); +// 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 actorSyncTimeout; let characterSyncRunning = false; let actorSyncErrorLogged = false; @@ -140,6 +147,16 @@ Hooks.once("init", () => { 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.", + scope: "client", + config: true, + type: String, + default: "", + onChange: handlePairingStatusChange, + }); + game.settings.register(MODULE_ID, SETTING_AUTO_SYNC, { name: "Dragonroll Auto-sync", hint: "Keep the linked Dragonroll campaign in step with this world as its actors and items change. Turn this off to stop synchronizing; the actor directory's Dragonroll: Force Sync entry then sends an actor over only when you ask for it.", @@ -221,6 +238,9 @@ async function setLinkCode(value) { 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()); } @@ -257,13 +277,19 @@ async function completeDragonrollCampaignLink(code, options = {}) { 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; } @@ -278,6 +304,69 @@ async function resumePendingDragonrollLink(options = {}) { if (code) await completeDragonrollCampaignLink(code, options); } +// --- Pairing status -------------------------------------------------------- +// The pairing status is the sentence the module settings show. Everything in it +// comes from this client plus what Dragonroll last said about its token, so it +// 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."; + } + 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."; + } + return "Not connected to a Dragonroll campaign. Paste a pairing code from that campaign's settings to link this world."; +} + +async function setPairingStatus(text) { + if (game.settings.get(MODULE_ID, SETTING_PAIRING_STATUS) === text) return; + updatingPairingStatus = true; + try { + await game.settings.set(MODULE_ID, SETTING_PAIRING_STATUS, text); + } catch (error) { + console.warn(`${MODULE_ID} | Could not store the Dragonroll pairing status.`, error); + } finally { + updatingPairingStatus = false; + } +} + +// Nothing is configured here: anything typed into the status is replaced by the +// status the module actually has. +function handlePairingStatusChange() { + if (updatingPairingStatus) return; + setPairingStatus(pairingStatusText()); +} + +// A token in this client only proves the world was paired once. Ask Dragonroll +// which campaign that token belongs to, and hear back when the campaign has +// unlinked this world again in the meantime. +async function refreshPairingStatus() { + const token = getSyncToken(); + if (!token) { + linkedCampaignName = ""; + await setPairingStatus(pairingStatusText()); + return; + } + try { + const result = await getDragonroll("foundry/sync/status", token); + linkedCampaignName = String(result.campaign?.name || "").trim(); + if (pairingProblem === PAIRING_REVOKED) pairingProblem = ""; + } 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; + } + await setPairingStatus(pairingStatusText()); +} + function scheduleSnapshotSync(delay = 500) { clearTimeout(syncTimeout); syncTimeout = setTimeout(publishSnapshot, delay); @@ -1051,11 +1140,12 @@ async function publishHeartbeat() { } Hooks.once("ready", () => { - resumePendingDragonrollLink(); + resumePendingDragonrollLink().then(refreshPairingStatus); setInterval(() => { if (linkRetriesDisabled) return; resumePendingDragonrollLink({ notifyOnError: false }); }, 60000); + setInterval(refreshPairingStatus, 60000); scheduleSnapshotSync(0); setInterval(publishHeartbeat, 60000); setTimeout(initializeCharacterSync, 1000); diff --git a/tests/foundry-pairing-status.test.js b/tests/foundry-pairing-status.test.js new file mode 100644 index 00000000..904ca3de --- /dev/null +++ b/tests/foundry-pairing-status.test.js @@ -0,0 +1,230 @@ +// Tests for the pairing status the Dragonroll Foundry module shows in its +// settings (Syndria98/dragonroll#17). Like foundry-sync-toggle.test.js, the module +// script runs inside a `node:vm` context of stubbed Foundry globals; here each +// test also decides what Dragonroll answers, because the status is that answer +// plus what this client holds (its sync token and any pairing code). +// +// Run with `npm test` from the repository root, or `node --test tests/`. + +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); + +const MODULE_ID = "dragonroll-foundry"; +const MODULE_SOURCE = fs.readFileSync( + path.join(__dirname, "..", "dragonroll-foundry", "scripts", "api.js"), + "utf8", +); + +const LINKED_CAMPAIGN = { id: "campaign-1", name: "Curse of Strahd" }; + +// The stub starts as a world that finished pairing (`syncToken: ""` is one that +// never did). `answers` maps a route fragment to the JSON Dragonroll replies +// with; a route that is not listed answers `{status:"ok"}`, and one mapped to +// null answers HTML, like a Dragonroll old enough not to have that route at all. +function makeStubWorld({ syncToken = "sync-token-1", linkCode = "", answers = {} } = {}) { + const state = { + hooks: new Map(), + registered: new Map(), + requests: [], + notifications: [], + }; + + const settingsStore = { + autoSync: true, + syncToken, + linkCode, + dragonrollApiUrl: "http://backend.test:5000", + }; + + const sandbox = { + console: { log() {}, info() {}, warn() {}, error() {} }, + URL, + CONFIG: {}, + window: { location: { origin: "http://vtt.test" } }, + ui: { + notifications: { + info: (text) => state.notifications.push(["info", text]), + warn: (text) => state.notifications.push(["warn", text]), + error: (text) => state.notifications.push(["error", text]), + }, + }, + Hooks: { + once(name, fn) { state.hooks.set(name, [fn]); }, + on(name, fn) { + const handlers = state.hooks.get(name) || []; + handlers.push(fn); + state.hooks.set(name, handlers); + }, + }, + // The pairing status never waits on a timer: it is written when the world is + // ready and whenever a pairing attempt answers, so dropping these keeps the + // snapshot and reconcile loops out of these tests. + setTimeout: () => 0, + clearTimeout: () => {}, + setInterval: () => 0, + clearInterval: () => {}, + fetch: async (url, options = {}) => { + const href = String(url); + state.requests.push({ + href, + method: options.method, + authorization: options.headers?.Authorization || "", + }); + const route = Object.keys(answers).find((fragment) => href.includes(fragment)); + const payload = route ? answers[route] : { status: "ok" }; + if (payload === null) { + return { ok: false, status: 404, json: async () => { throw new SyntaxError("Unexpected token < in JSON."); } }; + } + return { ok: true, status: 200, json: async () => payload }; + }, + Actor: { async create() { return null; } }, + Item: { async create() { return null; } }, + }; + + sandbox.game = { + user: { isGM: true }, + world: { id: "world-1", title: "Test World" }, + system: { id: "dnd5e" }, + modules: { get: () => ({}) }, + actors: { contents: [], get: () => null }, + items: { contents: [], get: () => null }, + settings: { + register(module, key, definition) { + state.registered.set(key, definition); + if (!(key in settingsStore)) settingsStore[key] = definition.default; + }, + get(module, key) { return settingsStore[key]; }, + async set(module, key, value) { + settingsStore[key] = value; + await state.registered.get(key)?.onChange?.(value); + }, + }, + }; + + vm.createContext(sandbox); + vm.runInContext(MODULE_SOURCE, sandbox); + + state.game = sandbox.game; + state.status = () => settingsStore.pairingStatus; + state.statusRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/status")); + + // The module's own awaits run in the vm's promise intrinsics, so a few turns of + // the event loop are what it takes for a written status to be observable. + state.settle = async () => { + for (let round = 0; round < 10; round += 1) await new Promise((resolve) => setImmediate(resolve)); + }; + + state.fire = async (name, ...args) => { + for (const handler of state.hooks.get(name) || []) await handler(...args); + await state.settle(); + }; + + state.configure = async (key, value) => { + await sandbox.game.settings.set(MODULE_ID, key, value); + await state.settle(); + }; + + state.start = async () => { + await state.fire("init"); + await state.fire("ready"); + return state; + }; + + return state; +} + +test("the pairing status is a setting the module configures", async () => { + const world = await makeStubWorld().start(); + + const setting = world.registered.get("pairingStatus"); + assert.equal(setting.config, true, "the pairing status appears in the module settings"); + assert.equal(setting.type.name, "String", "the pairing status is a sentence"); + assert.equal(setting.scope, "client", "the pairing status belongs to this client, like the token it comes from"); +}); + +test("a world that was never paired says it is not connected", async () => { + const world = await makeStubWorld({ syncToken: "" }).start(); + + assert.match(world.status(), /^Not connected/, "an unpaired world says so plainly"); + assert.match(world.status(), /Dragonroll campaign/, "and names what it is not connected to"); + assert.deepEqual(world.statusRequests(), [], "there is nothing to verify without a sync token"); +}); + +test("a paired world names the Dragonroll campaign it is connected to", async () => { + const world = await makeStubWorld({ + answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } }, + }).start(); + + assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`); + assert.equal(world.statusRequests()[0].authorization, "Bearer sync-token-1", "the campaign is asked with the sync token"); +}); + +test("a campaign that unlinked this world stops being reported as connected", async () => { + const world = await makeStubWorld({ + answers: { "foundry/sync/status": { status: "error", msg: "unauthorized" } }, + }).start(); + + assert.match(world.status(), /^Not connected/); + assert.match(world.status(), /no longer linked/); +}); + +test("an unreachable Dragonroll keeps the pairing this client already knows", async () => { + const world = await makeStubWorld({ answers: { "foundry/sync/status": null } }).start(); + + assert.equal(world.status(), "Connected to a Dragonroll campaign.", + "a Dragonroll without the status route says nothing, so the token speaks"); +}); + +test("a code that cannot be redeemed explains why the world is not connected", async () => { + const world = await makeStubWorld({ + syncToken: "", + answers: { "foundry/link/complete": { status: "error", msg: "foundry.errors.link-expired" } }, + }); + await world.start(); + + await world.configure("linkCode", "AN-EXPIRED-CODE"); + + assert.match(world.status(), /^Not connected/); + assert.match(world.status(), /pairing code is invalid, expired, or already used/); +}); + +test("a code still waiting on Dragonroll says the pairing is not finished", async () => { + const world = await makeStubWorld({ + syncToken: "", + answers: { "foundry/link/complete": { status: "error", msg: "errors.internal" } }, + }); + await world.start(); + + await world.configure("linkCode", "A-CODE-TO-RETRY"); + + assert.equal(world.status(), "Not connected yet: waiting for Dragonroll to accept this pairing code."); +}); + +test("redeeming a pairing code connects the world to its campaign", async () => { + const world = await makeStubWorld({ + syncToken: "", + answers: { + "foundry/link/complete": { status: "ok", campaign: LINKED_CAMPAIGN, syncToken: "sync-token-2" }, + }, + }); + await world.start(); + + await world.configure("linkCode", "A-FRESH-CODE"); + + assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`); + assert.equal(world.game.settings.get(MODULE_ID, "linkCode"), "", "a redeemed code is not kept"); +}); + +test("whatever is typed into the status is replaced by the real one", async () => { + const world = await makeStubWorld({ + answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } }, + }); + await world.start(); + + await world.configure("pairingStatus", "My own status text"); + + assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`); +}); diff --git a/tests/foundry-sync-toggle.test.js b/tests/foundry-sync-toggle.test.js index 78b59a56..87c4c3d7 100644 --- a/tests/foundry-sync-toggle.test.js +++ b/tests/foundry-sync-toggle.test.js @@ -144,7 +144,10 @@ function makeStubWorld({ autoSync = true } = {}) { state.game = sandbox.game; state.actor = (id) => actors.find((document) => document.id === id); - state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")); + // Sync pushes only: the pairing status read lives under the same prefix, and it + // tells nothing about what the world sent. + state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync") + && !request.href.includes("foundry/sync/status")); state.fire = async (name, ...args) => { for (const handler of state.hooks.get(name) || []) await handler(...args); -- 2.39.5