diff --git a/AGENTS.md b/AGENTS.md
index a7ae6c2d..dbaf0321 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -116,7 +116,7 @@ rest, expire after 10 min, and Obsidian gets a long-lived (365 d) token back.
Foundry then syncs with that token on `/api/foundry/sync/*` (`routes/foundry-link.js`, mounted before
the JWT guard; CORS opened for it): `snapshot` (actors + world items, `fullSync` also prunes),
`item-snapshot`, `item-delete`, `scenes` (the world's scenes as the campaign's maps, `fullSync` also
-prunes), `scene-delete`, `characters`, `items`, `notes` / `map-note`, `status`,
+prunes), `scene-delete`, `characters`, `items`, `notes` / `map-note`, `status`, `unlink`,
`map` / `map-item`, `delete`. Rules:
- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index); a Foundry document carrying the `dragonroll-foundry.actorId` / `.itemId` flag adopts the matching Dragonroll row.
diff --git a/backend/src/routes/campaign.js b/backend/src/routes/campaign.js
index c90b4c09..1db8941e 100644
--- a/backend/src/routes/campaign.js
+++ b/backend/src/routes/campaign.js
@@ -8,12 +8,11 @@ const serviceLinks = require('../services/service-links');
// 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') {
+ // A Foundry world can also let the campaign go from the module itself
+ // (routes/foundry-link.js), so both go through the same helper.
+ if (service === 'foundry') return serviceLinks.unlinkFoundryWorld(campaign);
+
+ 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;
diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js
index 580944d1..f6e90eef 100644
--- a/backend/src/routes/foundry-link.js
+++ b/backend/src/routes/foundry-link.js
@@ -14,6 +14,7 @@ const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { foundrySceneToMapData } = require('../services/map-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
+const serviceLinks = require('../services/service-links');
// Upper bound for the Foundry names remembered per synced item (see Item model).
const MAX_FOUNDRY_NAMES = 20;
@@ -698,6 +699,25 @@ router.post('/sync/map-note', async (req, res) => {
}
});
+// A world letting its campaign go from the module settings: the campaign forgets
+// the world and the token this request used stops working, so the world is free
+// to pair again — and the campaign's settings stop listing it as connected.
+router.post('/sync/unlink', async (req, res) => {
+ try {
+ const campaign = await syncCampaign(req, res);
+ if (!campaign) return;
+ if (!requestMatchesWorld(campaign, req.body.worldId)) {
+ return res.json({ status: 'error', msg: 'errors.missing-data' });
+ }
+
+ await serviceLinks.unlinkFoundryWorld(campaign);
+ res.json({ status: 'ok' });
+ } catch (err) {
+ console.error(err);
+ res.json({ status: 'error', msg: 'errors.internal' });
+ }
+});
+
module.exports = router;
// The writers every Foundry document goes through: the sync pushes above, and the
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of
diff --git a/backend/src/services/service-links.js b/backend/src/services/service-links.js
index c1775322..b2b870b9 100644
--- a/backend/src/services/service-links.js
+++ b/backend/src/services/service-links.js
@@ -165,7 +165,9 @@ async function startServiceLink(service, target) {
async function findServiceLinkByCode(code) {
if (!code) return null;
- return ServiceLinkRequest.findOne({ codeHash: codeHash(code) }).select('+credentials').lean();
+ // Not `.lean()`: the link answered by /complete is saved back with its new
+ // state, and a plain object has no document behind it to save.
+ return ServiceLinkRequest.findOne({ codeHash: codeHash(code) }).select('+credentials');
}
// The credential that belongs to a link is handed over once and then dropped:
@@ -211,6 +213,18 @@ async function revokeServiceLink(service, campaignId) {
return result.matchedCount;
}
+// A campaign letting a Foundry world go: it forgets the world, which frees the
+// world to pair with a campaign again, and the token the world still holds stops
+// working the next time it asks.
+async function unlinkFoundryWorld(campaign) {
+ campaign.foundryWorldId = undefined;
+ campaign.foundryWorldTitle = undefined;
+ campaign.foundrySystem = undefined;
+ campaign.set('foundrySyncTokenHash', undefined);
+ await campaign.save();
+ await revokeServiceLink('foundry', campaign._id);
+}
+
// 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) {
@@ -254,5 +268,6 @@ module.exports = {
serviceName,
signUpLinkUrl,
startServiceLink,
- takeServiceLinkCredentials
+ takeServiceLinkCredentials,
+ unlinkFoundryWorld
};
diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md
index 0c6d392b..4de55b0f 100644
--- a/dragonroll-foundry/README.md
+++ b/dragonroll-foundry/README.md
@@ -54,6 +54,13 @@ gives the reason when a pairing code can never be redeemed, and says the world i
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.
+**Dragonroll Connection** in the module settings opens the same state with the two actions a GM needs:
+**Copy link** puts the sign-up link on the clipboard to hand to whoever will pick the campaign, and
+**Unlink campaign** lets the world go. Unlinking drops the token on this client and on the campaign
+(`POST /api/foundry/sync/unlink`), so the campaign's settings stop listing the world and it can be
+paired again. If Dragonroll cannot be reached the token is kept and the failure is reported instead —
+dropping it alone would leave the campaign still believing the world is connected.
+
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.
@@ -182,6 +189,7 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `GET /api/foundry/sync/notes/revision` | A hash of the campaign's notes and folder paths, for the module's change check |
| `POST /api/foundry/sync/map-note` | Store a note's journal page id after creating that page |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
+| `POST /api/foundry/sync/unlink` | The module unlinks the world; the campaign forgets it and the token is revoked |
| `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 aec7e750..457d205a 100644
--- a/dragonroll-foundry/scripts/api.js
+++ b/dragonroll-foundry/scripts/api.js
@@ -180,6 +180,8 @@ Hooks.once("init", () => {
onChange: handleAutoSyncChange,
});
+ registerPairingMenu();
+
const module = game.modules.get(MODULE_ID);
if (!module) {
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
@@ -427,6 +429,135 @@ async function refreshPairingStatus() {
await setPairingStatus(pairingStatusText());
}
+// --- Connection actions ----------------------------------------------------
+// The module settings open a small window for the two things a GM does about a
+// pairing: hand its sign-up link to somebody, and let the campaign go again.
+
+// The sign-up link lives in a client setting, so copying it is how it reaches
+// the browser the user will open it in.
+async function copyPairingLink() {
+ if (getSyncToken()) {
+ ui.notifications?.info("This world is already linked to a Dragonroll campaign; there is no sign-up link to copy.");
+ return;
+ }
+ if (!game.settings.get(MODULE_ID, SETTING_LINK_URL)?.trim()) await requestDragonrollLink();
+
+ const link = game.settings.get(MODULE_ID, SETTING_LINK_URL)?.trim();
+ if (!link) {
+ ui.notifications?.warn("Dragonroll does not have a sign-up link for this world right now. Check the Dragonroll Endpoint setting.");
+ return;
+ }
+ try {
+ await navigator.clipboard.writeText(link);
+ ui.notifications?.info("Dragonroll sign-up link copied to the clipboard.");
+ } catch (error) {
+ // A browser can refuse the clipboard; the link is still the GM's to copy.
+ console.warn(`${MODULE_ID} | Could not copy the Dragonroll sign-up link.`, error);
+ ui.notifications?.warn(`Copy the Dragonroll sign-up link yourself: ${link}`);
+ }
+}
+
+// Letting the campaign go from this side: Dragonroll forgets the world and drops
+// the token, so this world can pair with a campaign again. An unreachable
+// Dragonroll keeps the token — dropping it here would leave the campaign still
+// listing a world that can no longer reach it.
+async function unlinkDragonrollCampaign() {
+ if (!game.user?.isGM || !game.world) return;
+ const token = getSyncToken();
+ try {
+ if (token) await postDragonroll("foundry/sync/unlink", { worldId: game.world.id }, token);
+ } catch (error) {
+ if (error.message !== "unauthorized") {
+ console.error(`${MODULE_ID} | Could not unlink this world from Dragonroll.`, error);
+ ui.notifications?.warn(`Dragonroll could not unlink this world: ${error.message}`);
+ return;
+ }
+ }
+
+ await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, "");
+ linkedCampaignName = "";
+ linkProblem = "";
+ await setLink("", "");
+ await setPairingStatus(pairingStatusText());
+ ui.notifications?.info("This Foundry world is no longer linked to its Dragonroll campaign.");
+ await requestDragonrollLink();
+}
+
+function registerPairingMenu() {
+ const ApplicationV2 = globalThis.foundry?.applications?.api?.ApplicationV2;
+ // The module is loaded without Foundry's settings UI in its tests, and no
+ // Foundry this module runs on lacks ApplicationV2.
+ if (typeof game.settings.registerMenu !== "function" || !ApplicationV2) return;
+
+ class DragonrollPairingMenu extends ApplicationV2 {
+ static DEFAULT_OPTIONS = {
+ id: "dragonroll-pairing-menu",
+ classes: [MODULE_ID],
+ window: { title: "Dragonroll Connection", icon: "fa-solid fa-link" },
+ position: { width: 560 },
+ actions: {
+ copyLink() {
+ return copyPairingLink().then(() => this.render());
+ },
+ unlink() {
+ return unlinkDragonrollCampaign().then(() => this.render());
+ },
+ },
+ };
+
+ async _renderHTML() {
+ const link = game.settings.get(MODULE_ID, SETTING_LINK_URL)?.trim();
+ const root = document.createElement("div");
+ root.className = "dragonroll-pairing-menu";
+
+ const status = document.createElement("p");
+ status.textContent = pairingStatusText();
+ root.append(status);
+
+ if (link) {
+ const field = document.createElement("input");
+ field.type = "text";
+ field.readOnly = true;
+ field.value = link;
+ field.addEventListener("focus", () => field.select());
+ root.append(field);
+ }
+
+ const actions = document.createElement("div");
+ actions.className = "dragonroll-pairing-actions";
+
+ const copy = document.createElement("button");
+ copy.type = "button";
+ copy.dataset.action = "copyLink";
+ copy.innerHTML = ' Copy link';
+ copy.disabled = Boolean(getSyncToken());
+
+ const unlink = document.createElement("button");
+ unlink.type = "button";
+ unlink.dataset.action = "unlink";
+ unlink.innerHTML = ' Unlink campaign';
+ unlink.disabled = !getSyncToken();
+
+ actions.append(copy, unlink);
+ root.append(actions);
+ return root;
+ }
+
+ _replaceHTML(result, content) {
+ content.replaceChildren(result);
+ }
+ }
+
+ game.settings.registerMenu(MODULE_ID, "pairingMenu", {
+ name: "Dragonroll Connection",
+ label: "Copy link / Unlink",
+ hint: "Copy this world's sign-up link, or unlink the Dragonroll campaign it was paired with.",
+ icon: "fa-solid fa-link",
+ type: DragonrollPairingMenu,
+ restricted: true,
+ });
+}
+
function scheduleSnapshotSync(delay = 500) {
clearTimeout(syncTimeout);
syncTimeout = setTimeout(publishSnapshot, delay);
diff --git a/dragonroll-foundry/styles/dragonroll.css b/dragonroll-foundry/styles/dragonroll.css
index 4589eaa7..44712d87 100644
--- a/dragonroll-foundry/styles/dragonroll.css
+++ b/dragonroll-foundry/styles/dragonroll.css
@@ -25,3 +25,19 @@
text-decoration: underline dashed;
cursor: help;
}
+
+/* The connection window the module settings open: the sign-up link and its actions. */
+.dragonroll-pairing-menu {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.dragonroll-pairing-menu input[readonly] {
+ width: 100%;
+}
+
+.dragonroll-pairing-actions {
+ display: flex;
+ gap: 8px;
+}
diff --git a/tests/character-sheet-traits-items.test.js b/tests/character-sheet-traits-items.test.js
index 4c3ae787..8a2bd662 100644
--- a/tests/character-sheet-traits-items.test.js
+++ b/tests/character-sheet-traits-items.test.js
@@ -148,6 +148,7 @@ function loadFoundryWriters({ seed = {}, settings } = {}) {
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
+ if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
diff --git a/tests/foundry-force-import.test.js b/tests/foundry-force-import.test.js
index 9fe0536d..723c28e9 100644
--- a/tests/foundry-force-import.test.js
+++ b/tests/foundry-force-import.test.js
@@ -284,6 +284,7 @@ function loadFoundryWriters({ seed = {} } = {}) {
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
+ if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
diff --git a/tests/foundry-note-journal.test.js b/tests/foundry-note-journal.test.js
index 0b507b81..aa2cebc5 100644
--- a/tests/foundry-note-journal.test.js
+++ b/tests/foundry-note-journal.test.js
@@ -133,6 +133,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
+ if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
diff --git a/tests/foundry-pairing-status.test.js b/tests/foundry-pairing-status.test.js
index 27eb2ce8..0ea82627 100644
--- a/tests/foundry-pairing-status.test.js
+++ b/tests/foundry-pairing-status.test.js
@@ -40,8 +40,10 @@ function makeStubWorld({
const state = {
hooks: new Map(),
registered: new Map(),
+ menus: new Map(),
requests: [],
notifications: [],
+ copied: [],
};
const settingsStore = {
@@ -57,6 +59,10 @@ function makeStubWorld({
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
+ // The module registers a menu for its connection actions: the window needs
+ // ApplicationV2 to exist, not to render.
+ foundry: { applications: { api: { ApplicationV2: class { render() {} } } } },
+ navigator: { clipboard: { writeText: async (text) => state.copied.push(text) } },
ui: {
notifications: {
info: (text) => state.notifications.push(["info", text]),
@@ -110,6 +116,7 @@ function makeStubWorld({
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
+ registerMenu(module, key, definition) { state.menus.set(key, definition); },
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
@@ -267,6 +274,43 @@ test("an expired link is replaced by one the GM can still open", async () => {
assert.match(world.status(), /link-code-2/, "and shows the new one");
});
+test("the connection window copies the sign-up link", async () => {
+ const world = await makeStubWorld({
+ syncToken: "",
+ linkCode: "link-code-1",
+ linkUrl: SIGN_UP_LINK,
+ answers: { "link/pickup": { status: "ok", state: "pending" } },
+ }).start();
+
+ const menu = world.menus.get("pairingMenu");
+ assert.ok(menu, "the module settings open the connection window");
+ await menu.type.DEFAULT_OPTIONS.actions.copyLink.call(new menu.type());
+
+ assert.deepEqual(world.copied, [SIGN_UP_LINK], "the link waiting for its GM reaches the clipboard");
+});
+
+test("the connection window unlinks the campaign and asks for a fresh link", async () => {
+ const world = await makeStubWorld({
+ answers: {
+ "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" },
+ "foundry/sync/unlink": { status: "ok" },
+ "link/start": { status: "ok", code: "link-code-2", linkUrl: SIGN_UP_LINK },
+ },
+ }).start();
+ assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
+
+ const menu = world.menus.get("pairingMenu");
+ await menu.type.DEFAULT_OPTIONS.actions.unlink.call(new menu.type());
+
+ const unlink = world.requests.find((request) => request.href.includes("foundry/sync/unlink"));
+ assert.ok(unlink, "Dragonroll is told to forget this world");
+ assert.equal(unlink.body.worldId, "world-1");
+ assert.equal(unlink.authorization, "Bearer sync-token-1", "the world unlinks with the token it holds");
+ assert.equal(world.setting("syncToken"), "", "the token is dropped on this client too");
+ assert.equal(world.setting("linkCode"), "link-code-2", "a fresh link is kept ready to pair again");
+ assert.match(world.status(), /^Not connected yet/);
+});
+
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" } },
diff --git a/tests/item-folder-sync.test.js b/tests/item-folder-sync.test.js
index cb5d8b56..e7e592d5 100644
--- a/tests/item-folder-sync.test.js
+++ b/tests/item-folder-sync.test.js
@@ -145,6 +145,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
if (id === "../services/item-foundry") return repoRequire(path.join("backend", "src", "services", "item-foundry.js"));
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
+ if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
diff --git a/tests/map-foundry-sync.test.js b/tests/map-foundry-sync.test.js
index 4f0dc238..eafccdfc 100644
--- a/tests/map-foundry-sync.test.js
+++ b/tests/map-foundry-sync.test.js
@@ -125,6 +125,7 @@ function loadSyncRoute({ seed = {}, worldId = "world-1", settings } = {}) {
if (id === "../services/item-foundry") return { foundryItemToItemData: () => null };
if (id === "../services/foundry-icons") return repoRequire(path.join("backend", "src", "services", "foundry-icons.js"));
if (id === "../services/map-foundry") return repoRequire(path.join("backend", "src", "services", "map-foundry.js"));
+ if (id === "../services/service-links") return { unlinkFoundryWorld: async () => {} };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
diff --git a/tests/service-link-target.test.js b/tests/service-link-target.test.js
index eeecf51d..58c9f445 100644
--- a/tests/service-link-target.test.js
+++ b/tests/service-link-target.test.js
@@ -6,6 +6,58 @@ const { test } = require("node:test");
const assert = require("node:assert/strict");
const serviceLinks = require("../backend/src/services/service-links");
+const ServiceLinkRequest = require("../backend/src/models/ServiceLinkRequest");
+
+test("a link found by its code can be answered and saved", async () => {
+ const original = ServiceLinkRequest.findOne;
+ const document = { _id: "link-1", state: "pending", save: async () => {} };
+ const query = {
+ select: () => query,
+ lean: () => Promise.resolve({ _id: "link-1", state: "pending" }),
+ then: (resolve, reject) => Promise.resolve(document).then(resolve, reject),
+ };
+ ServiceLinkRequest.findOne = () => query;
+ try {
+ const request = await serviceLinks.findServiceLinkByCode("code-1");
+ assert.equal(typeof request?.save, "function",
+ "the complete route saves the answered link, so it cannot be a plain lean object");
+ } finally {
+ ServiceLinkRequest.findOne = original;
+ }
+});
+
+test("unlinking a Foundry world forgets it and revokes its link", async () => {
+ const original = ServiceLinkRequest.updateMany;
+ const revocations = [];
+ ServiceLinkRequest.updateMany = async (filter, update) => {
+ revocations.push({ filter, update });
+ return { matchedCount: 1 };
+ };
+ try {
+ const campaign = {
+ _id: "campaign-1",
+ foundryWorldId: "world-1",
+ foundryWorldTitle: "Test World",
+ foundrySystem: "dnd5e",
+ foundrySyncTokenHash: "hash",
+ set(key, value) { this[key] = value; },
+ async save() { campaign.saved = true; },
+ };
+
+ await serviceLinks.unlinkFoundryWorld(campaign);
+
+ assert.equal(campaign.saved, true);
+ assert.equal(campaign.foundryWorldId, undefined);
+ assert.equal(campaign.foundryWorldTitle, undefined);
+ assert.equal(campaign.foundrySystem, undefined);
+ assert.equal(campaign.foundrySyncTokenHash, undefined);
+ assert.equal(revocations[0].filter.service, "foundry");
+ assert.equal(revocations[0].filter.campaign, "campaign-1");
+ assert.equal(revocations[0].update.$set.state, "revoked");
+ } finally {
+ ServiceLinkRequest.updateMany = original;
+ }
+});
test("a link request keeps the service metadata short and plain", () => {
const target = serviceLinks.readTarget({