// Integration tests exercising the real Express app + a real Postgres // database through Prisma. These need DATABASE_URL pointed at a reachable, // migrated database (see /README.md) — they are skipped automatically if the // DB isn't reachable so `npm test` still passes in an environment with no DB. const request = require('supertest'); const crypto = require('crypto'); const prisma = require('../db'); const { createApp } = require('../app'); // Each test registers several users (bcrypt) and walks whole flows against a // real database, which doesn't reliably fit Jest's 5 second default. jest.setTimeout(30000); const app = createApp(); app.set('io', { to: () => ({ emit: () => {} }) }); // stub Socket.io for tests let dbAvailable = true; const cleanupCampaignIds = []; const cleanupUserIds = []; beforeAll(async () => { try { await prisma.$connect(); } catch { dbAvailable = false; } }); afterAll(async () => { if (dbAvailable) { for (const id of cleanupCampaignIds) { await prisma.campaign.delete({ where: { id } }).catch(() => {}); } for (const id of cleanupUserIds) { await prisma.user.delete({ where: { id } }).catch(() => {}); } } await prisma.$disconnect(); }); function uniqueEmail(prefix) { return `${prefix}-${crypto.randomUUID()}@test.local`; } // Valid picks for the three story steps that sit between skills and equipment. const STORY_PICKS = { talents: ['ALERT', 'KEEN_EYE'], background: { upbringing: ['SOLDIER'], home: ['VILLAGE'], turningPoint: ['BETRAYED'], personality: ['BRAVE', 'CURIOUS'], flaw: ['GREEDY'] }, appearance: { build: ['MUSCULAR'], height: ['TALL'], hair: ['RED'], eyes: ['GREEN'], complexion: ['WEATHERED'], features: ['SCAR'], style: ['CLOAK'] }, }; // Walks a character from the special-abilities step through to equipment. async function storySteps(characterId, auth) { const choose = (body) => request(app).post(`/characters/${characterId}/build/choose`).set(auth).send(body); await choose({ talents: STORY_PICKS.talents }); await choose({ picks: STORY_PICKS.background }); return choose({ picks: STORY_PICKS.appearance }); } function itIfDb(name, fn) { test(name, async () => { if (!dbAvailable) { console.warn(`Skipping "${name}" — no reachable database (set DATABASE_URL and run migrations).`); return; } await fn(); }); } describe('auth', () => { itIfDb('registers, logs in, and reads the current user', async () => { const email = uniqueEmail('dm'); const registerRes = await request(app) .post('/auth/register') .send({ email, password: 'password123', displayName: 'Test DM' }); expect(registerRes.status).toBe(201); expect(registerRes.body.token).toBeTruthy(); cleanupUserIds.push(registerRes.body.user.id); const loginRes = await request(app).post('/auth/login').send({ email, password: 'password123' }); expect(loginRes.status).toBe(200); const meRes = await request(app).get('/auth/me').set('Authorization', `Bearer ${loginRes.body.token}`); expect(meRes.status).toBe(200); expect(meRes.body.user.email).toBe(email); }); itIfDb('rejects a bad password', async () => { const email = uniqueEmail('baduser'); const registerRes = await request(app) .post('/auth/register') .send({ email, password: 'password123', displayName: 'Bad Login' }); cleanupUserIds.push(registerRes.body.user.id); const loginRes = await request(app).post('/auth/login').send({ email, password: 'wrong-password' }); expect(loginRes.status).toBe(401); }); }); describe('campaigns + characters + build flow', () => { itIfDb('DM creates a campaign, player joins, DM builds a character end-to-end', async () => { const dmEmail = uniqueEmail('dm2'); const playerEmail = uniqueEmail('player2'); const dmRegister = await request(app) .post('/auth/register') .send({ email: dmEmail, password: 'password123', displayName: 'DM Two' }); const dmToken = dmRegister.body.token; cleanupUserIds.push(dmRegister.body.user.id); const playerRegister = await request(app) .post('/auth/register') .send({ email: playerEmail, password: 'password123', displayName: 'Player Two' }); cleanupUserIds.push(playerRegister.body.user.id); const campaignRes = await request(app) .post('/campaigns') .set('Authorization', `Bearer ${dmToken}`) .send({ name: 'Integration Test Campaign', startingItemCount: 1, startingSpellCount: 0, skipMotivationRoll: true }); expect(campaignRes.status).toBe(201); const campaign = campaignRes.body.campaign; cleanupCampaignIds.push(campaign.id); const joinRes = await request(app) .post(`/campaigns/join/${campaign.inviteCode}`) .set('Authorization', `Bearer ${playerRegister.body.token}`); expect(joinRes.status).toBe(201); // DM adds a homebrew weapon to the pool so the equipment step has something to pick. const weaponRes = await request(app) .post(`/campaigns/${campaign.id}/weapons`) .set('Authorization', `Bearer ${dmToken}`) .send({ name: 'Test Dagger', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [], isStartingOption: true }); expect(weaponRes.status).toBe(201); const weaponId = weaponRes.body.weapon.id; const characterRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set('Authorization', `Bearer ${dmToken}`) .send({ name: 'Integration Hero' }); expect(characterRes.status).toBe(201); const characterId = characterRes.body.character.id; const auth = { Authorization: `Bearer ${dmToken}` }; // Step 1: species let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); expect(rollRes.status).toBe(200); let speciesChoices = rollRes.body.buildState.speciesChoices; const species = speciesChoices.options[0]; let chooseRes = await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species }); expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('ROLLING_CLASS'); // Step 2: class (skip any reroll results deterministically) rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); while (rollRes.body.buildState.classChoices.type === 'reroll') { rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); } const characterClass = rollRes.body.buildState.classChoices.options[0]; chooseRes = await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ characterClass }); expect(chooseRes.status).toBe(200); // skipMotivationRoll was true, so motivation is skipped entirely. expect(chooseRes.body.buildStage).toBe('ASSIGNING_SCORES'); // Step 4: ability scores rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); expect(rollRes.body.buildState.abilityRolls).toHaveLength(6); chooseRes = await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('ASSIGNING_PROFICIENCIES'); // Step 5: skills chooseRes = await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send({ skillProficiencies: [{ skill: 'ATHLETICS', proficient: true, expertise: false }] }); expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('CHOOSING_ABILITIES'); // Special abilities, background, appearance chooseRes = await storySteps(characterId, auth); expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('CHOOSING_EQUIPMENT'); // Step 6: equipment chooseRes = await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send({ weaponIds: [weaponId], spellIds: [] }); expect(chooseRes.status).toBe(200); expect(chooseRes.body.buildStage).toBe('CHOOSING_EQUIPMENT'); // stays here until finalize // Step 7: finalize const finalizeRes = await request(app).post(`/characters/${characterId}/build/finalize`).set(auth); expect(finalizeRes.status).toBe(200); const character = finalizeRes.body.character; expect(character.buildStage).toBe('COMPLETE'); expect(character.sheet).not.toBeNull(); expect(character.currentHp).toBe(character.sheet.hp.max); expect(character.weapons).toHaveLength(1); // Quick stats should now work. const quickStatsRes = await request(app).get(`/characters/${characterId}/quick-stats`).set(auth); expect(quickStatsRes.status).toBe(200); expect(quickStatsRes.body.quickStats.weapons).toHaveLength(1); // A non-member cannot read the character. const outsiderRegister = await request(app) .post('/auth/register') .send({ email: uniqueEmail('outsider'), password: 'password123', displayName: 'Outsider' }); cleanupUserIds.push(outsiderRegister.body.user.id); const forbiddenRes = await request(app) .get(`/characters/${characterId}`) .set('Authorization', `Bearer ${outsiderRegister.body.token}`); expect(forbiddenRes.status).toBe(403); }); }); async function setupCampaign(namePrefix) { const dmRegister = await request(app) .post('/auth/register') .send({ email: uniqueEmail(`${namePrefix}-dm`), password: 'password123', displayName: 'DM' }); const dmToken = dmRegister.body.token; cleanupUserIds.push(dmRegister.body.user.id); const playerRegister = await request(app) .post('/auth/register') .send({ email: uniqueEmail(`${namePrefix}-player`), password: 'password123', displayName: 'Player' }); const playerToken = playerRegister.body.token; cleanupUserIds.push(playerRegister.body.user.id); const campaignRes = await request(app) .post('/campaigns') .set('Authorization', `Bearer ${dmToken}`) .send({ name: `${namePrefix} Campaign`, startingItemCount: 0, startingSpellCount: 0, skipMotivationRoll: true }); const campaign = campaignRes.body.campaign; cleanupCampaignIds.push(campaign.id); await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set('Authorization', `Bearer ${playerToken}`); return { dmAuth: { Authorization: `Bearer ${dmToken}` }, playerAuth: { Authorization: `Bearer ${playerToken}` }, campaign, }; } // Walks the build flow to COMPLETE with whatever the dice give (or stops at the // equipment step, for tests that exercise it). async function buildCharacter(campaignId, auth, name, { stopBeforeEquipment = false } = {}) { const characterRes = await request(app).post(`/campaigns/${campaignId}/characters`).set(auth).send({ name }); const characterId = characterRes.body.character.id; let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); const species = rollRes.body.buildState.speciesChoices.options[0]; await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species }); rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); while (rollRes.body.buildState.classChoices.type === 'reroll') { rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth); } const characterClass = rollRes.body.buildState.classChoices.options[0]; await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ characterClass }); await request(app).post(`/characters/${characterId}/build/roll`).set(auth); await request(app) .post(`/characters/${characterId}/build/choose`) .set(auth) .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({}); await storySteps(characterId, auth); if (stopBeforeEquipment) return characterId; await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ weaponIds: [], spellIds: [] }); await request(app).post(`/characters/${characterId}/build/finalize`).set(auth); return characterId; } describe('copy character to another campaign', () => { itIfDb('copies stats, gear and spells into the target campaign and leaves the original alone', async () => { const source = await setupCampaign('copysource'); const target = await setupCampaign('copytarget'); const { playerAuth } = source; await request(app).post(`/campaigns/join/${target.campaign.inviteCode}`).set(playerAuth); const dagger = await request(app).post(`/campaigns/${source.campaign.id}/weapons/from-library`).set(source.dmAuth).send({ key: 'dagger' }); const longsword = await request(app).post(`/campaigns/${source.campaign.id}/weapons/from-library`).set(source.dmAuth).send({ key: 'longsword' }); const spell = await request(app) .post(`/campaigns/${source.campaign.id}/spells`) .set(source.dmAuth) .send({ name: 'Test Bolt', level: 1 }); // The target already has a Dagger (different case) — it must be reused, not duplicated. const targetDagger = await request(app) .post(`/campaigns/${target.campaign.id}/weapons`) .set(target.dmAuth) .send({ name: 'DAGGER', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [] }); const rope = await request(app) .post(`/campaigns/${source.campaign.id}/items`) .set(source.dmAuth) .send({ name: 'Rope', description: '50 ft of hemp', isStartingOption: true }); const characterId = await buildCharacter(source.campaign.id, playerAuth, 'Traveller'); await request(app).post(`/characters/${characterId}/weapons`).set(source.dmAuth).send({ weaponId: dagger.body.weapon.id }); await request(app).patch(`/characters/${characterId}/weapons/${dagger.body.weapon.id}`).set(playerAuth).send({ equipped: true }); await request(app).post(`/characters/${characterId}/weapons`).set(source.dmAuth).send({ weaponId: longsword.body.weapon.id, level: 2 }); await request(app).post(`/characters/${characterId}/spells`).set(source.dmAuth).send({ spellId: spell.body.spell.id }); await request(app).post(`/characters/${characterId}/inventory`).set(source.dmAuth).send({ itemId: rope.body.item.id, quantity: 2 }); await request(app).post(`/characters/${characterId}/gold`).set(playerAuth).send({ amount: 42, reason: 'Savings' }); await request(app).patch(`/characters/${characterId}`).set(source.dmAuth).send({ level: 3 }); const original = ( await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ currentHp: 1, privateNotes: 'secret' }) ).body.character; const copyRes = await request(app).post(`/characters/${characterId}/copy`).set(playerAuth).send({ targetCampaignId: target.campaign.id }); expect(copyRes.status).toBe(201); const copy = copyRes.body.character; expect(copy.id).not.toBe(characterId); expect(copy.campaignId).toBe(target.campaign.id); expect(copy.userId).toBe(original.userId); expect(copy.buildStage).toBe('COMPLETE'); expect(copy.level).toBe(3); expect(copy.gold).toBe(42); expect(copy.privateNotes).toBe('secret'); expect(copy.species).toBe(original.species); expect(copy.characterClass).toBe(original.characterClass); expect(copy.rolledScores).toEqual(original.rolledScores); expect(copy.sheet.skills).toEqual(original.sheet.skills); expect(copy.sheet.saves).toEqual(original.sheet.saves); expect(copy.currentHp).toBe(copy.sheet.hp.max); // arrives at full HP expect(copy.inventoryItems.map((i) => [i.item.name, i.item.description, i.quantity])).toEqual([['Rope', '50 ft of hemp', 2]]); expect(copy.inventoryItems[0].item.campaignId).toBe(target.campaign.id); // Pool entries created by a copy are never starting options in the target. expect(copy.inventoryItems[0].item.isStartingOption).toBe(false); const copyLedger = await request(app).get(`/characters/${copy.id}/gold`).set(playerAuth); expect(copyLedger.body.transactions.map((t) => [t.amount, t.balanceAfter])).toEqual([[42, 42]]); expect(copy.spells.map((s) => s.spell.name)).toEqual(['Test Bolt']); const copiedDagger = copy.weapons.find((w) => w.weapon.name.toLowerCase() === 'dagger'); expect(copiedDagger.weaponId).toBe(targetDagger.body.weapon.id); expect(copiedDagger.equipped).toBe(true); expect(copy.weapons.find((w) => w.weapon.name === 'Longsword')).toMatchObject({ level: 2, scaledDamageDice: '1d10' }); expect(copy.weapons.every((w) => w.weapon.campaignId === target.campaign.id)).toBe(true); expect(copy.spells.every((s) => s.spell.campaignId === target.campaign.id)).toBe(true); const targetWeapons = await request(app).get(`/campaigns/${target.campaign.id}/weapons`).set(playerAuth); expect(targetWeapons.body.weapons.map((w) => w.name).sort()).toEqual(['DAGGER', 'Longsword']); const originalAfter = await request(app).get(`/characters/${characterId}`).set(playerAuth); expect(originalAfter.body.character.campaignId).toBe(source.campaign.id); expect(originalAfter.body.character.currentHp).toBe(1); expect(originalAfter.body.character.weapons).toHaveLength(2); }); itIfDb('enforces membership, ownership, build state and privacy', async () => { const source = await setupCampaign('copyrules'); const other = await setupCampaign('copyrules-other'); const characterId = await buildCharacter(source.campaign.id, source.playerAuth, 'Homebody'); await request(app).patch(`/characters/${characterId}`).set(source.playerAuth).send({ privateNotes: 'secret' }); // Owner isn't a member of the other campaign. let res = await request(app).post(`/characters/${characterId}/copy`).set(source.playerAuth).send({ targetCampaignId: other.campaign.id }); expect(res.status).toBe(403); // Same campaign is not "another campaign". res = await request(app).post(`/characters/${characterId}/copy`).set(source.playerAuth).send({ targetCampaignId: source.campaign.id }); expect(res.status).toBe(400); // A fellow player in both campaigns can't copy someone else's character. await request(app).post(`/campaigns/join/${source.campaign.inviteCode}`).set(other.playerAuth); res = await request(app).post(`/characters/${characterId}/copy`).set(other.playerAuth).send({ targetCampaignId: other.campaign.id }); expect(res.status).toBe(403); // An unfinished character can't be copied. const unfinished = await request(app).post(`/campaigns/${source.campaign.id}/characters`).set(source.playerAuth).send({ name: 'Half Built' }); await request(app).post(`/campaigns/join/${other.campaign.inviteCode}`).set(source.playerAuth); res = await request(app) .post(`/characters/${unfinished.body.character.id}/copy`) .set(source.playerAuth) .send({ targetCampaignId: other.campaign.id }); expect(res.status).toBe(400); // The source DM can copy it, becomes the copy's owner, and never receives the player's private notes. await request(app).post(`/campaigns/join/${other.campaign.inviteCode}`).set(source.dmAuth); res = await request(app).post(`/characters/${characterId}/copy`).set(source.dmAuth).send({ targetCampaignId: other.campaign.id }); expect(res.status).toBe(201); expect(res.body.character.privateNotes).toBeNull(); const dmMe = await request(app).get('/auth/me').set(source.dmAuth); expect(res.body.character.userId).toBe(dmMe.body.user.id); }); }); describe('who can change what on a character', () => { itIfDb('keeps level, XP and location with the DM, and gold out of PATCH entirely', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('dmonly'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Ambitious'); const location = await request(app).post(`/campaigns/${campaign.id}/locations`).set(dmAuth).send({ name: 'Keep' }); const dmOnly = [ { level: 20 }, { xp: 9000 }, { currentLocationId: location.body.location.id }, { speedOverride: 90 }, // Composed by the builder from the player's picks; only the DM rewrites them. { specialAbilities: 'Flight — I can fly.' }, { background: 'Secretly the king.' }, { appearance: 'Ten feet tall.' }, ]; for (const body of dmOnly) { const res = await request(app).patch(`/characters/${characterId}`).set(playerAuth).send(body); expect(res.status).toBe(403); } expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ gold: 999 })).status).toBe(400); expect((await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ gold: 999 })).status).toBe(400); // The player can still edit the rest of their own sheet. expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ armorBonus: 2 })).status).toBe(200); const dmRes = await request(app) .patch(`/characters/${characterId}`) .set(dmAuth) .send({ level: 2, xp: 300, currentLocationId: location.body.location.id }); expect(dmRes.status).toBe(200); expect(dmRes.body.character.level).toBe(2); expect(dmRes.body.character.gold).toBe(0); }); itIfDb('only the DM hands out, removes or re-counts gear; the owner can equip and prepare', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('gear'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Packrat'); const weaponId = (await request(app).post(`/campaigns/${campaign.id}/weapons/from-library`).set(dmAuth).send({ key: 'dagger' })).body.weapon.id; const spellId = (await request(app).post(`/campaigns/${campaign.id}/spells`).set(dmAuth).send({ name: 'Spark', level: 0 })).body.spell.id; const itemRes = await request(app).post(`/campaigns/${campaign.id}/items`).set(dmAuth).send({ name: 'Rope', description: '50 ft' }); expect(itemRes.status).toBe(201); const itemId = itemRes.body.item.id; // Players can see the pool but not add to it or help themselves from it. expect((await request(app).get(`/campaigns/${campaign.id}/items`).set(playerAuth)).body.items).toHaveLength(1); expect((await request(app).post(`/campaigns/${campaign.id}/items`).set(playerAuth).send({ name: 'Crown' })).status).toBe(403); expect((await request(app).post(`/characters/${characterId}/weapons`).set(playerAuth).send({ weaponId })).status).toBe(403); expect((await request(app).post(`/characters/${characterId}/inventory`).set(playerAuth).send({ itemId })).status).toBe(403); expect((await request(app).post(`/characters/${characterId}/spells`).set(playerAuth).send({ spellId })).status).toBe(403); expect((await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId })).status).toBe(201); expect((await request(app).post(`/characters/${characterId}/spells`).set(dmAuth).send({ spellId })).status).toBe(201); expect((await request(app).post(`/characters/${characterId}/inventory`).set(dmAuth).send({ itemId, quantity: 2 })).status).toBe(201); // Giving the same item again stacks it. const stacked = await request(app).post(`/characters/${characterId}/inventory`).set(dmAuth).send({ itemId }); expect(stacked.body.inventoryItem.quantity).toBe(3); expect(stacked.body.inventoryItem.item.name).toBe('Rope'); // Owner: equip / prepare yes, quantity and removal no. expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth).send({ equipped: true })).status).toBe(200); expect((await request(app).patch(`/characters/${characterId}/weapons/${weaponId}`).set(playerAuth).send({ equipped: true })).status).toBe(200); expect((await request(app).patch(`/characters/${characterId}/spells/${spellId}`).set(playerAuth).send({ prepared: true })).status).toBe(200); expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth).send({ quantity: 99 })).status).toBe(403); expect((await request(app).delete(`/characters/${characterId}/inventory/${itemId}`).set(playerAuth)).status).toBe(403); expect((await request(app).delete(`/characters/${characterId}/weapons/${weaponId}`).set(playerAuth)).status).toBe(403); // An inventory edit can only reach the character in the URL. const otherId = await buildCharacter(campaign.id, dmAuth, 'Bystander'); expect((await request(app).patch(`/characters/${otherId}/inventory/${itemId}`).set(dmAuth).send({ equipped: true })).status).toBe(404); expect((await request(app).delete(`/characters/${otherId}/inventory/${itemId}`).set(dmAuth)).status).toBe(404); expect((await request(app).patch(`/characters/${characterId}/inventory/${itemId}`).set(dmAuth).send({ quantity: 1 })).status).toBe(200); expect((await request(app).delete(`/characters/${characterId}/weapons/${weaponId}`).set(dmAuth)).status).toBe(204); expect((await request(app).delete(`/characters/${characterId}/spells/${spellId}`).set(dmAuth)).status).toBe(204); const sheet = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character; expect(sheet.weapons).toHaveLength(0); expect(sheet.spells).toHaveLength(0); expect(sheet.inventoryItems).toHaveLength(1); expect(sheet.inventoryItems[0]).toMatchObject({ quantity: 1, equipped: true }); // Deleting the pool item takes it out of every inventory. expect((await request(app).delete(`/campaigns/${campaign.id}/items/${itemId}`).set(dmAuth)).status).toBe(204); expect((await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.inventoryItems).toHaveLength(0); }); itIfDb('a DM cannot edit or delete another campaign\'s pool entries through their own campaign', async () => { const mine = await setupCampaign('poolmine'); const theirs = await setupCampaign('pooltheirs'); const weaponId = (await request(app).post(`/campaigns/${theirs.campaign.id}/weapons/from-library`).set(theirs.dmAuth).send({ key: 'dagger' })).body.weapon.id; const itemId = (await request(app).post(`/campaigns/${theirs.campaign.id}/items`).set(theirs.dmAuth).send({ name: 'Relic' })).body.item.id; expect((await request(app).patch(`/campaigns/${mine.campaign.id}/weapons/${weaponId}`).set(mine.dmAuth).send({ name: 'Hacked' })).status).toBe(404); expect((await request(app).delete(`/campaigns/${mine.campaign.id}/weapons/${weaponId}`).set(mine.dmAuth)).status).toBe(404); expect((await request(app).delete(`/campaigns/${mine.campaign.id}/items/${itemId}`).set(mine.dmAuth)).status).toBe(404); const weapons = (await request(app).get(`/campaigns/${theirs.campaign.id}/weapons`).set(theirs.dmAuth)).body.weapons; expect(weapons.map((w) => w.name)).toEqual(['Dagger']); }); }); describe('giving to another character', () => { itIfDb('moves weapons, items, spells and gold from one character to another', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('give'); const other = await setupCampaign('give-other'); const c = `/campaigns/${campaign.id}`; const giverId = await buildCharacter(campaign.id, playerAuth, 'Aria'); const friendId = await buildCharacter(campaign.id, dmAuth, 'Bo'); const unfinishedId = (await request(app).post(`${c}/characters`).set(dmAuth).send({ name: 'Unfinished' })).body.character.id; const outsiderId = await buildCharacter(other.campaign.id, other.dmAuth, 'Outsider'); const spear = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Spear', damageDice: '1d6', damageType: 'piercing', attackAbility: 'STR' })).body.weapon; const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Potion', damageDice: '2d4+2' })).body.item; const spell = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fire Bolt', level: 0, damageDice: '1d10' })).body.spell; const g = `/characters/${giverId}`; await request(app).post(`${g}/weapons`).set(dmAuth).send({ weaponId: spear.id, level: 3 }); await request(app).post(`${g}/inventory`).set(dmAuth).send({ itemId: potion.id, quantity: 3 }); await request(app).post(`${g}/spells`).set(dmAuth).send({ spellId: spell.id }); await request(app).post(`${g}/gold`).set(dmAuth).send({ amount: 30 }); // Bo already has one potion, at level 2. await request(app).post(`/characters/${friendId}/inventory`).set(dmAuth).send({ itemId: potion.id, level: 2 }); const give = (body, auth = playerAuth, from = giverId) => request(app).post(`/characters/${from}/give`).set(auth).send(body); const sheet = async (id) => (await request(app).get(`/characters/${id}`).set(dmAuth)).body.character; // Who and where. const stranger = await request(app).post('/auth/register').send({ email: uniqueEmail('give-stranger'), password: 'password123', displayName: 'Stranger' }); cleanupUserIds.push(stranger.body.user.id); const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 1 }, strangerAuth)).status).toBe(403); // not their character expect((await give({ kind: 'gold', toCharacterId: giverId, amount: 1 })).status).toBe(400); // to itself expect((await give({ kind: 'gold', toCharacterId: outsiderId, amount: 1 })).status).toBe(400); // another campaign expect((await give({ kind: 'gold', toCharacterId: unfinishedId, amount: 1 })).status).toBe(400); // still being built // Gold: both ledgers record it, and you can't give what you don't have. expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 31 })).status).toBe(400); expect((await give({ kind: 'gold', toCharacterId: friendId, amount: 0 })).status).toBe(400); const gaveGold = await give({ kind: 'gold', toCharacterId: friendId, amount: 12 }); expect(gaveGold.status).toBe(200); expect(gaveGold.body.character.gold).toBe(18); expect((await sheet(friendId)).gold).toBe(12); const ledger = async (id) => (await request(app).get(`/characters/${id}/gold`).set(dmAuth)).body.transactions[0]; expect(await ledger(giverId)).toMatchObject({ amount: -12, reason: 'Gave to Bo', balanceAfter: 18 }); expect(await ledger(friendId)).toMatchObject({ amount: 12, reason: 'Received from Aria', balanceAfter: 12 }); // Items: part of a stack moves; the recipient's existing stack keeps its own level. expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id, quantity: 4 })).status).toBe(400); expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id, quantity: 2 })).status).toBe(200); expect((await sheet(giverId)).inventoryItems.map((i) => [i.item.name, i.quantity])).toEqual([['Potion', 1]]); expect((await sheet(friendId)).inventoryItems.map((i) => [i.item.name, i.quantity, i.level])).toEqual([['Potion', 3, 2]]); // Giving the last one empties the giver's inventory of it. expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id })).status).toBe(200); expect((await sheet(giverId)).inventoryItems).toEqual([]); expect((await give({ kind: 'item', toCharacterId: friendId, id: potion.id })).status).toBe(400); // nothing left // Weapons: arrive at the giver's level, unequipped — held but unusable if the recipient is too low. await request(app).patch(g).set(dmAuth).send({ level: 3 }); await request(app).patch(`${g}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true }); expect((await give({ kind: 'weapon', toCharacterId: friendId, id: spear.id })).status).toBe(200); expect((await sheet(giverId)).weapons).toEqual([]); expect((await sheet(friendId)).weapons.map((w) => [w.weapon.name, w.level, w.quantity, w.equipped, w.usable])).toEqual([['Spear', 3, 1, false, false]]); // Spells move too: the giver no longer knows it, and nobody ends up knowing it twice. expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(200); expect((await sheet(giverId)).spells).toEqual([]); expect((await sheet(friendId)).spells.map((s) => s.spell.name)).toEqual(['Fire Bolt']); expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(400); // no longer known await request(app).post(`${g}/spells`).set(dmAuth).send({ spellId: spell.id }); expect((await give({ kind: 'spell', toCharacterId: friendId, id: spell.id })).status).toBe(400); // Bo already knows it expect((await sheet(giverId)).spells).toHaveLength(1); // and Aria kept hers // The DM can move things between characters as well. expect((await give({ kind: 'weapon', toCharacterId: giverId, id: spear.id }, dmAuth, friendId)).status).toBe(200); expect((await sheet(giverId)).weapons.map((w) => [w.weapon.name, w.level])).toEqual([['Spear', 3]]); }); }); describe('hit points', () => { itIfDb('stay between 0 and max on the sheet, including after a level drop', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('hpclamp'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Sturdy'); const patch = (auth, body) => request(app).patch(`/characters/${characterId}`).set(auth).send(body); const level5 = (await patch(dmAuth, { level: 5 })).body.character; const full = (await patch(playerAuth, { currentHp: 9999 })).body.character; expect(full.currentHp).toBe(level5.sheet.hp.max); expect((await patch(playerAuth, { currentHp: -50 })).body.character.currentHp).toBe(0); await patch(playerAuth, { currentHp: 9999 }); const level1 = (await patch(dmAuth, { level: 1 })).body.character; expect(level1.sheet.hp.max).toBeLessThan(level5.sheet.hp.max); expect(level1.currentHp).toBe(level1.sheet.hp.max); }); itIfDb('are shared between the character sheet and the encounter tracker', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('hpsync'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Brawler'); const maxHp = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.sheet.hp.max; const encounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Brawl' })).body.encounter.id; const added = await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId, initiative: 12 }); const participantId = added.body.participant.id; const combatant = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0]; const sheetHp = async () => (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character.currentHp; // Damage in the tracker lands on the sheet. const hit = await request(app).patch(`/encounters/${encounterId}/participants/${participantId}`).set(dmAuth).send({ currentHp: maxHp - 3 }); expect(hit.status).toBe(200); expect(await sheetHp()).toBe(maxHp - 3); // Healing on the sheet shows in the tracker. await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ currentHp: maxHp - 1 }); expect((await combatant()).currentHp).toBe(maxHp - 1); // The tracker is clamped like the sheet, and can't give a character a different max. await request(app).patch(`/encounters/${encounterId}/participants/${participantId}`).set(dmAuth).send({ currentHp: -20, maxHp: 500 }); expect(await sheetHp()).toBe(0); expect((await combatant()).maxHp).toBe(maxHp); // A level-up moves the tracker's max too. await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ level: 4 }); expect((await combatant()).maxHp).toBeGreaterThan(maxHp); // Monsters are clamped to their own max. const monsterId = (await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster.id; const monster = (await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ monsterId })).body.participant; const healed = await request(app).patch(`/encounters/${encounterId}/participants/${monster.id}`).set(dmAuth).send({ currentHp: 9999 }); expect(healed.body.participant.currentHp).toBe(monster.maxHp); // A combatant can only be edited through its own encounter. const otherEncounterId = (await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Elsewhere' })).body.encounter.id; const wrong = await request(app).patch(`/encounters/${otherEncounterId}/participants/${participantId}`).set(dmAuth).send({ initiative: 1 }); expect(wrong.status).toBe(404); }); }); describe('money tracker', () => { itIfDb('logs every change to the balance and refuses to overspend', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('gold'); await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingGold: 15 }); const characterId = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Merchant' })).body.character.id; const gold = (auth, body) => request(app).post(`/characters/${characterId}/gold`).set(auth).send(body); const reward = await gold(dmAuth, { amount: 50, reason: 'Bounty on the wolf pack' }); expect(reward.status).toBe(201); expect(reward.body.gold).toBe(65); const spend = await gold(playerAuth, { amount: -20, reason: 'New boots' }); expect(spend.status).toBe(201); expect(spend.body.gold).toBe(45); const overspend = await gold(playerAuth, { amount: -46 }); expect(overspend.status).toBe(400); expect((await gold(playerAuth, { amount: 0 })).status).toBe(400); expect((await gold(playerAuth, { amount: 1.5 })).status).toBe(400); // Another player can read the ledger but not write to it. const stranger = await request(app) .post('/auth/register') .send({ email: uniqueEmail('gold-other'), password: 'password123', displayName: 'Other' }); cleanupUserIds.push(stranger.body.user.id); const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); expect((await gold(strangerAuth, { amount: 5 })).status).toBe(403); const ledger = await request(app).get(`/characters/${characterId}/gold`).set(strangerAuth); expect(ledger.status).toBe(200); expect(ledger.body.gold).toBe(45); expect(ledger.body.transactions.map((t) => [t.amount, t.balanceAfter, t.reason, t.createdBy.displayName])).toEqual([ [-20, 45, 'New boots', 'Player'], [50, 65, 'Bounty on the wolf pack', 'DM'], [15, 15, 'Starting gold', 'Player'], ]); }); }); describe('starting options', () => { itIfDb('only pool entries the DM marked can be picked while building, and items share the weapon allowance', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('starting'); await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingItemCount: 2, startingSpellCount: 1 }); const other = await setupCampaign('starting-other'); const post = (path, body, c = campaign, auth = dmAuth) => request(app).post(`/campaigns/${c.id}/${path}`).set(auth).send(body); const club = (await post('weapons', { name: 'Club', damageDice: '1d4', damageType: 'bludgeoning', attackAbility: 'STR', isStartingOption: true })).body.weapon; const vorpal = (await post('weapons/from-library', { key: 'longsword' })).body.weapon; const torch = (await post('items', { name: 'Torch', isStartingOption: true })).body.item; const bedroll = (await post('items', { name: 'Bedroll', isStartingOption: true })).body.item; const crown = (await post('items', { name: 'Crown of Kings' })).body.item; const spark = (await post('spells', { name: 'Spark', level: 0, isStartingOption: true })).body.spell; const wish = (await post('spells', { name: 'Wish', level: 9 })).body.spell; const foreign = (await post('items', { name: 'Foreign', isStartingOption: true }, other.campaign, other.dmAuth)).body.item; // Library and hand-made entries are not starting options unless marked. expect(club.isStartingOption).toBe(true); expect(vorpal.isStartingOption).toBe(false); expect(crown.isStartingOption).toBe(false); const characterId = await buildCharacter(campaign.id, playerAuth, 'Newcomer', { stopBeforeEquipment: true }); const choose = (body) => request(app).post(`/characters/${characterId}/build/choose`).set(playerAuth).send(body); expect((await choose({ weaponIds: [vorpal.id] })).status).toBe(400); // not a starting option expect((await choose({ itemIds: [crown.id] })).status).toBe(400); expect((await choose({ itemIds: [foreign.id] })).status).toBe(400); // another campaign expect((await choose({ itemIds: [torch.id, torch.id] })).status).toBe(400); // duplicates expect((await choose({ weaponIds: [club.id], itemIds: [torch.id, bedroll.id] })).status).toBe(400); // 3 > allowance of 2 const character = (await request(app).get(`/characters/${characterId}`).set(playerAuth)).body.character; const isCaster = ['RANGER', 'WIZARD', 'SORCERER', 'CLERIC', 'PALADIN', 'BARD', 'WARLOCK', 'DRUID'].includes(character.buildState.characterClass); if (isCaster) expect((await choose({ spellIds: [wish.id] })).status).toBe(400); const ok = await choose({ weaponIds: [club.id], itemIds: [torch.id], spellIds: isCaster ? [spark.id] : [] }); expect(ok.status).toBe(200); const finalized = (await request(app).post(`/characters/${characterId}/build/finalize`).set(playerAuth)).body.character; expect(finalized.weapons.map((w) => w.weapon.name)).toEqual(['Club']); expect(finalized.inventoryItems.map((i) => i.item.name)).toEqual(['Torch']); expect(finalized.spells.map((s) => s.spell.name)).toEqual(isCaster ? ['Spark'] : []); // The DM can flip the flag later. const flipped = await request(app).patch(`/campaigns/${campaign.id}/items/${crown.id}`).set(dmAuth).send({ isStartingOption: true }); expect(flipped.body.item.isStartingOption).toBe(true); const spellFlip = await request(app).patch(`/campaigns/${campaign.id}/spells/${wish.id}`).set(dmAuth).send({ isStartingOption: true }); expect(spellFlip.body.spell.isStartingOption).toBe(true); }); }); describe('gear levels', () => { itIfDb('weapons and items scale with their own level and need a character of that level', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('gearlevels'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Squire'); const c = `/campaigns/${campaign.id}`; const spear = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Spear', damageDice: '1d6', damageType: 'piercing', attackAbility: 'STR' })).body.weapon; const relic = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Relic Blade', damageDice: '1d8', damageType: 'slashing', attackAbility: 'STR', damageScaling: 3 })).body.weapon; const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Healing Potion', damageDice: '2d4+2' })).body.item; const rope = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Rope' })).body.item; expect(spear.damageScaling).toBe(1); expect(relic.damageScaling).toBe(3); expect((await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Bad', damageDice: '1d4', damageType: 'x', attackAbility: 'STR', damageScaling: 4 })).status).toBe(400); const ch = `/characters/${characterId}`; const sheet = async () => (await request(app).get(ch).set(playerAuth)).body.character; const held = async (name) => (await sheet()).weapons.find((w) => w.weapon.name === name); // Given at level 1 by default; the DM can give at a higher level. await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: spear.id }); await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: relic.id, level: 2 }); await request(app).post(`${ch}/inventory`).set(dmAuth).send({ itemId: potion.id }); await request(app).post(`${ch}/inventory`).set(dmAuth).send({ itemId: rope.id }); expect(await held('Spear')).toMatchObject({ level: 1, scaledDamageDice: '1d6', usable: true }); expect(await held('Relic Blade')).toMatchObject({ level: 2, scaledDamageDice: '2d6', usable: false }); // A level 1 character holds the level 2 blade but can't equip it. expect((await request(app).patch(`${ch}/weapons/${relic.id}`).set(playerAuth).send({ equipped: true })).status).toBe(400); expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); expect((await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: relic.id, level: 21 })).status).toBe(400); // Only the DM levels gear. Levelling the equipped spear past its holder takes it off. expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ level: 5 })).status).toBe(403); const levelled = await request(app).patch(`${ch}/weapons/${spear.id}`).set(dmAuth).send({ level: 3 }); expect(levelled.status).toBe(200); expect(levelled.body.characterWeapon).toMatchObject({ level: 3, equipped: false }); expect(await held('Spear')).toMatchObject({ scaledDamageDice: '1d10', usable: false }); // Unusable weapons stay out of quick stats and the encounter view. const quick = async () => (await request(app).get(`${ch}/quick-stats`).set(playerAuth)).body.quickStats.weapons; expect(await quick()).toEqual([]); // At character level 3 both are usable, at their own level's dice. await request(app).patch(ch).set(dmAuth).send({ level: 3 }); expect(await held('Spear')).toMatchObject({ usable: true }); expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); expect((await request(app).patch(`${ch}/weapons/${relic.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200); expect((await quick()).map((w) => [w.name, w.level, w.damageDice]).sort()).toEqual([ ['Relic Blade', 2, '2d6'], ['Spear', 3, '1d10'], ]); const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Drill' })).body.encounter.id; await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId }); const combat = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0].characterCombatInfo; expect((await combat()).weapons.map((w) => w.damageDice).sort()).toEqual(['1d10', '2d6']); // Items level the same way; an item with no dice just has a level requirement. const items = async () => (await sheet()).inventoryItems; await request(app).patch(`${ch}/inventory/${potion.id}`).set(dmAuth).send({ level: 2 }); await request(app).patch(`${ch}/inventory/${rope.id}`).set(dmAuth).send({ level: 5 }); const [potionHeld, ropeHeld] = ['Healing Potion', 'Rope'].map(async (name) => (await items()).find((i) => i.item.name === name)); expect(await potionHeld).toMatchObject({ level: 2, scaledDamageDice: '1d6+1d8', usable: true }); expect(await ropeHeld).toMatchObject({ level: 5, scaledDamageDice: null, usable: false }); expect((await request(app).patch(`${ch}/inventory/${rope.id}`).set(playerAuth).send({ equipped: true })).status).toBe(400); // Dropping the character back to level 1 unequips what is now out of reach. await request(app).patch(ch).set(dmAuth).send({ level: 1 }); expect((await sheet()).weapons.map((w) => [w.weapon.name, w.equipped, w.usable]).sort()).toEqual([ ['Relic Blade', false, false], ['Spear', false, false], ]); expect((await combat()).weapons).toEqual([]); }); itIfDb('a spell needs a character of at least its classic level, and carries a fixed damage value', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('spelllevels'); const characterId = await buildCharacter(campaign.id, playerAuth, 'Apprentice'); const c = `/campaigns/${campaign.id}`; const ch = `/characters/${characterId}`; const cantrip = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fire Bolt', level: 0, damageDice: '1d10' })).body.spell; const fireball = (await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Fireball', level: 3, damageDice: '8d6', isStartingOption: true })).body.spell; expect(fireball.damageDice).toBe('8d6'); for (const spell of [cantrip, fireball]) await request(app).post(`${ch}/spells`).set(dmAuth).send({ spellId: spell.id }); const spells = async () => (await request(app).get(ch).set(playerAuth)).body.character.spells; expect((await spells()).map((s) => [s.spell.name, s.usable]).sort()).toEqual([['Fire Bolt', true], ['Fireball', false]]); expect((await request(app).patch(`${ch}/spells/${cantrip.id}`).set(playerAuth).send({ prepared: true })).status).toBe(200); expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(playerAuth).send({ prepared: true })).status).toBe(400); // Spells have no level of their own to raise. expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(dmAuth).send({ level: 1 })).body.characterSpell.spell.level).toBe(3); await request(app).patch(ch).set(dmAuth).send({ level: 3 }); expect((await request(app).patch(`${ch}/spells/${fireball.id}`).set(playerAuth).send({ prepared: true })).status).toBe(200); const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Blast' })).body.encounter.id; await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId }); const combatSpells = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0].characterCombatInfo.spells; expect((await combatSpells()).map((s) => [s.name, s.damageDice]).sort()).toEqual([['Fire Bolt', '1d10'], ['Fireball', '8d6']]); await request(app).patch(ch).set(dmAuth).send({ level: 2 }); expect((await spells()).find((s) => s.spell.name === 'Fireball')).toMatchObject({ prepared: false, usable: false }); expect((await combatSpells()).map((s) => s.name)).toEqual(['Fire Bolt']); // A brand-new (level 1) character can't start with a level 3 spell, even a starting option. await request(app).patch(c).set(dmAuth).send({ startingSpellCount: 1 }); const newId = await buildCharacter(campaign.id, playerAuth, 'Hopeful', { stopBeforeEquipment: true }); const pick = await request(app).post(`/characters/${newId}/build/choose`).set(playerAuth).send({ spellIds: [fireball.id] }); expect(pick.status).toBe(400); }); }); describe('gear starting levels', () => { itIfDb('a weapon that starts at a higher level is given there, never goes below it, and scales from it', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('minlevel'); await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingItemCount: 2 }); const c = `/campaigns/${campaign.id}`; const greatsword = ( await request(app) .post(`${c}/weapons`) .set(dmAuth) .send({ name: 'Greatsword', damageDice: '2d6', damageType: 'slashing', attackAbility: 'STR', minLevel: 3, isStartingOption: true }) ).body.weapon; expect(greatsword.minLevel).toBe(3); expect((await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Bad', damageDice: '1d4', damageType: 'x', attackAbility: 'STR', minLevel: 10 })).status).toBe(400); const club = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Club', damageDice: '1d4', damageType: 'bludgeoning', attackAbility: 'STR', isStartingOption: true })).body.weapon; // Too high for a new character, even though it is ticked as a starting option. const newbie = await buildCharacter(campaign.id, playerAuth, 'Newbie', { stopBeforeEquipment: true }); expect((await request(app).post(`/characters/${newbie}/build/choose`).set(playerAuth).send({ weaponIds: [greatsword.id] })).status).toBe(400); expect((await request(app).post(`/characters/${newbie}/build/choose`).set(playerAuth).send({ weaponIds: [club.id] })).status).toBe(200); const characterId = await buildCharacter(campaign.id, playerAuth, 'Veteran'); const ch = `/characters/${characterId}`; const held = async (name) => (await request(app).get(ch).set(playerAuth)).body.character.weapons.find((w) => w.weapon.name === name); expect((await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: greatsword.id, level: 2 })).status).toBe(400); const given = await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: greatsword.id }); expect(given.body.characterWeapon.level).toBe(3); expect(await held('Greatsword')).toMatchObject({ level: 3, scaledDamageDice: '2d6', usable: false }); expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 2 })).status).toBe(400); expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 10 })).status).toBe(400); // gear stops at 9 await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 5 }); expect(await held('Greatsword')).toMatchObject({ level: 5, scaledDamageDice: '2d8' }); expect((await request(app).patch(`${ch}/weapons/${greatsword.id}`).set(dmAuth).send({ level: 9 })).status).toBe(200); // Raising a pool entry's starting level lifts copies that are now below it. await request(app).post(`${ch}/weapons`).set(dmAuth).send({ weaponId: club.id }); await request(app).patch(`${ch}/weapons/${club.id}`).set(playerAuth).send({ equipped: true }); await request(app).patch(`${c}/weapons/${club.id}`).set(dmAuth).send({ minLevel: 2 }); expect(await held('Club')).toMatchObject({ level: 2, scaledDamageDice: '1d4', equipped: false, usable: false }); }); }); describe('encounters', () => { async function scene(prefix) { const ctx = await setupCampaign(prefix); const c = `/campaigns/${ctx.campaign.id}`; const heroId = await buildCharacter(ctx.campaign.id, ctx.playerAuth, 'Aria'); const allyId = await buildCharacter(ctx.campaign.id, ctx.dmAuth, 'Bo'); return { ...ctx, c, heroId, allyId }; } itIfDb('have a mode, a public description and DM-only notes', async () => { const { dmAuth, playerAuth, c } = await scene('encmode'); const quest = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'The Missing Miller', mode: 'QUEST', description: 'Find the miller.' })).body.encounter; expect(quest.mode).toBe('QUEST'); const battle = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Ambush' })).body.encounter; expect(battle.mode).toBe('BATTLE'); const e = `/encounters/${quest.id}`; expect((await request(app).patch(e).set(playerAuth).send({ mode: 'BATTLE' })).status).toBe(403); const patched = await request(app).patch(e).set(dmAuth).send({ dmNotes: 'The miller is the werewolf.' }); expect(patched.body.encounter.dmNotes).toBe('The miller is the werewolf.'); const playerView = (await request(app).get(e).set(playerAuth)).body.encounter; expect(playerView.description).toBe('Find the miller.'); expect(playerView.dmNotes).toBeUndefined(); const playerList = (await request(app).get(`${c}/encounters`).set(playerAuth)).body.encounters; expect(playerList.map((x) => [x.name, x.mode]).sort()).toEqual([['Ambush', 'BATTLE'], ['The Missing Miller', 'QUEST']]); expect(playerList.every((x) => x.dmNotes === undefined)).toBe(true); const dmList = (await request(app).get(`${c}/encounters`).set(dmAuth)).body.encounters; expect(dmList.find((x) => x.id === quest.id).dmNotes).toBe('The miller is the werewolf.'); }); itIfDb('NPCs are DM-managed and join encounters without leaking the DM\'s notes or stats', async () => { const { dmAuth, playerAuth, c } = await scene('npcs'); const other = await setupCampaign('npcs-other'); expect((await request(app).post(`${c}/npcs`).set(playerAuth).send({ name: 'Nope' })).status).toBe(403); expect((await request(app).get(`${c}/npcs`).set(playerAuth)).status).toBe(403); const mayor = ( await request(app) .post(`${c}/npcs`) .set(dmAuth) .send({ name: 'Mayor Orla', role: 'Mayor', disposition: 'FRIENDLY', description: 'Tired but kind.', dmNotes: 'Secretly bankrupt.', ac: 11, maxHp: 9 }) ).body.npc; const hermit = (await request(app).post(`${c}/npcs`).set(dmAuth).send({ name: 'Old Hermit' })).body.npc; expect(hermit.disposition).toBe('NEUTRAL'); expect((await request(app).get(`${c}/npcs`).set(dmAuth)).body.npcs.map((n) => n.name)).toEqual(['Mayor Orla', 'Old Hermit']); expect((await request(app).patch(`${c}/npcs/${mayor.id}`).set(dmAuth).send({ disposition: 'HOSTILE' })).body.npc.disposition).toBe('HOSTILE'); // Another campaign's DM can't reach it. expect((await request(app).patch(`/campaigns/${other.campaign.id}/npcs/${mayor.id}`).set(other.dmAuth).send({ name: 'Hacked' })).status).toBe(404); const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Town Hall', mode: 'QUEST' })).body.encounter.id; const e = `/encounters/${encounterId}`; expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: mayor.id })).status).toBe(201); expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: hermit.id })).status).toBe(201); expect((await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: mayor.id, monsterId: 'x' })).status).toBe(400); const byName = (encounter) => Object.fromEntries(encounter.participants.map((p) => [p.displayName, p])); const dmView = byName((await request(app).get(e).set(dmAuth)).body.encounter); expect(dmView['Mayor Orla']).toMatchObject({ kind: 'NPC', currentHp: 9, maxHp: 9 }); expect(dmView['Mayor Orla'].npc).toMatchObject({ role: 'Mayor', disposition: 'HOSTILE', dmNotes: 'Secretly bankrupt.', ac: 11 }); expect(dmView['Old Hermit']).toMatchObject({ kind: 'NPC', maxHp: 0 }); // no combat stats const playerView = byName((await request(app).get(e).set(playerAuth)).body.encounter); expect(playerView['Mayor Orla'].npc).toEqual({ id: mayor.id, name: 'Mayor Orla', role: 'Mayor', disposition: 'HOSTILE', description: 'Tired but kind.' }); // Deleting an NPC takes it out of the scenes it was in. expect((await request(app).delete(`${c}/npcs/${hermit.id}`).set(dmAuth)).status).toBe(204); expect(Object.keys(byName((await request(app).get(e).set(dmAuth)).body.encounter))).toEqual(['Mayor Orla']); }); itIfDb('show the DM full monster stat blocks and everyone a character\'s headline numbers', async () => { const { dmAuth, playerAuth, c, heroId } = await scene('encdetail'); const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Cave' })).body.encounter.id; const e = `/encounters/${encounterId}`; await request(app).post(`${e}/participants`).set(dmAuth).send({ monsterId: goblin.id, initiative: 5 }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId, initiative: 15 }); const [hero, monster] = (await request(app).get(e).set(dmAuth)).body.encounter.participants; expect(hero.kind).toBe('CHARACTER'); expect(hero.characterCombatInfo).toMatchObject({ level: 1 }); for (const key of ['armorClass', 'speed', 'initiativeBonus', 'passivePerception', 'proficiencyBonus', 'tempHp']) { expect(typeof hero.characterCombatInfo[key]).toBe('number'); } expect(Object.keys(hero.characterCombatInfo.abilities)).toEqual(['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA']); expect(monster.kind).toBe('MONSTER'); expect(monster.monster).toMatchObject({ ac: goblin.ac, attackBonus: goblin.attackBonus, damageDice: goblin.damageDice }); const playerMonster = (await request(app).get(e).set(playerAuth)).body.encounter.participants[1]; expect(playerMonster.monster).toEqual({ id: goblin.id, name: goblin.name }); }); itIfDb('track whose turn it is down the initiative order and roll the round over', async () => { const { dmAuth, playerAuth, c, heroId, allyId } = await scene('turns'); const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Bridge' })).body.encounter.id; const e = `/encounters/${encounterId}`; expect((await request(app).post(`${e}/next-turn`).set(dmAuth)).status).toBe(400); // nobody to take a turn const add = async (body) => (await request(app).post(`${e}/participants`).set(dmAuth).send(body)).body.participant.id; const slow = await add({ monsterId: goblin.id, initiative: 3 }); const fast = await add({ characterId: heroId, initiative: 18 }); const mid = await add({ characterId: allyId, initiative: 10 }); const state = (res) => [res.body.encounter.activeParticipantId, res.body.encounter.currentRound, res.body.encounter.status]; expect((await request(app).post(`${e}/next-turn`).set(playerAuth)).status).toBe(403); // Beginning the battle puts the highest initiative on turn. expect(state(await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE' }))).toEqual([fast, 1, 'ACTIVE']); expect(state(await request(app).post(`${e}/next-turn`).set(dmAuth))).toEqual([mid, 1, 'ACTIVE']); // Removing whoever is on turn passes it on. const removed = await request(app).delete(`${e}/participants/${mid}`).set(dmAuth); expect(removed.body.encounter.activeParticipantId).toBe(slow); // Past the end of the order: back to the top, next round. expect(state(await request(app).post(`${e}/next-turn`).set(dmAuth))).toEqual([fast, 2, 'ACTIVE']); expect((await request(app).get(e).set(playerAuth)).body.encounter.participants.map((p) => p.id)).toEqual([fast, slow]); }); itIfDb('rewards stay secret until awarded, then land on the character exactly once', async () => { const { dmAuth, playerAuth, c, heroId, allyId } = await scene('rewards'); const other = await setupCampaign('rewards-other'); const sword = (await request(app).post(`${c}/weapons`).set(dmAuth).send({ name: 'Flame Tongue', damageDice: '1d8', damageType: 'fire', attackAbility: 'STR', minLevel: 2 })).body.weapon; const potion = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Healing Potion', damageDice: '2d4+2' })).body.item; const foreign = (await request(app).post(`/campaigns/${other.campaign.id}/items`).set(other.dmAuth).send({ name: 'Foreign' })).body.item; const encounterId = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Dragon Hoard' })).body.encounter.id; const e = `/encounters/${encounterId}`; await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId, initiative: 12 }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: allyId, initiative: 8 }); const add = (body, auth = dmAuth) => request(app).post(`${e}/rewards`).set(auth).send(body); expect((await add({ type: 'GOLD', gold: 5 }, playerAuth)).status).toBe(403); expect((await add({ type: 'GOLD', gold: 0 })).status).toBe(400); expect((await add({ type: 'ITEM', itemId: foreign.id })).status).toBe(400); expect((await add({ type: 'WEAPON', weaponId: sword.id, level: 1 })).status).toBe(400); // below its starting level const gold = (await add({ type: 'GOLD', gold: 101, note: 'The hoard' })).body.reward; const purse = (await add({ type: 'GOLD', gold: 10 })).body.reward; const blade = (await add({ type: 'WEAPON', weaponId: sword.id })).body.reward; const potions = (await add({ type: 'ITEM', itemId: potion.id, quantity: 3, level: 2 })).body.reward; const junk = (await add({ type: 'GOLD', gold: 1 })).body.reward; expect(blade.level).toBe(2); // Unawarded loot is the DM's secret. expect((await request(app).get(e).set(dmAuth)).body.encounter.rewards).toHaveLength(5); expect((await request(app).get(e).set(playerAuth)).body.encounter.rewards).toEqual([]); expect((await request(app).delete(`${e}/rewards/${junk.id}`).set(dmAuth)).status).toBe(200); const award = (rewardId, body, auth = dmAuth) => request(app).post(`${e}/rewards/${rewardId}/award`).set(auth).send(body); expect((await award(gold.id, { split: true }, playerAuth)).status).toBe(403); expect((await award(blade.id, { split: true })).status).toBe(400); // only gold splits // 101 gold between two: 51 to the higher initiative, 50 to the other. expect((await award(gold.id, { split: true })).status).toBe(200); expect((await award(gold.id, { characterId: heroId })).status).toBe(400); // already awarded expect((await award(purse.id, { characterId: allyId })).status).toBe(200); expect((await award(blade.id, { characterId: heroId })).status).toBe(200); expect((await award(potions.id, { characterId: heroId })).status).toBe(200); const hero = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character; expect(hero.gold).toBe(51); expect(hero.weapons.map((w) => [w.weapon.name, w.level, w.quantity])).toEqual([['Flame Tongue', 2, 1]]); expect(hero.inventoryItems.map((i) => [i.item.name, i.level, i.quantity, i.scaledDamageDice])).toEqual([['Healing Potion', 2, 3, '1d6+1d8']]); const heroLedger = (await request(app).get(`/characters/${heroId}/gold`).set(playerAuth)).body.transactions; expect(heroLedger.map((t) => [t.amount, t.reason, t.createdBy.displayName])).toEqual([[51, 'Reward: Dragon Hoard', 'DM']]); expect((await request(app).get(`/characters/${allyId}`).set(dmAuth)).body.character.gold).toBe(60); // Players now see what was handed out, and to whom. const seen = (await request(app).get(e).set(playerAuth)).body.encounter.rewards; expect(seen.map((r) => [r.type, r.awardedTo]).sort()).toEqual([ ['GOLD', 'Aria, Bo'], ['GOLD', 'Bo'], ['ITEM', 'Aria'], ['WEAPON', 'Aria'], ]); }); }); describe('dice mode', () => { itIfDb('rejects an out-of-range physical roll and accepts a valid one, matching the digital shape', async () => { const { dmAuth, campaign } = await setupCampaign('dicemode'); const characterRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set(dmAuth) .send({ name: 'Physical Roller' }); const characterId = characterRes.body.character.id; const modeRes = await request(app).patch(`/characters/${characterId}/build/dice-mode`).set(dmAuth).send({ diceMode: 'PHYSICAL' }); expect(modeRes.status).toBe(200); expect(modeRes.body.diceMode).toBe('PHYSICAL'); const tooHigh = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 7 }); expect(tooHigh.status).toBe(400); const validRoll = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 3 }); expect(validRoll.status).toBe(200); expect(validRoll.body.buildState.speciesRoll).toBe(3); // Dice mode can no longer change once rolling has started. const lateSwitch = await request(app).patch(`/characters/${characterId}/build/dice-mode`).set(dmAuth).send({ diceMode: 'DIGITAL' }); expect(lateSwitch.status).toBe(400); // Physical ability scores: six sets of four d6, lowest die dropped. await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ species: validRoll.body.buildState.speciesChoices.options[0] }); await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 1 }); await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass: 'FIGHTER' }); const sets = [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]]; const badSets = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ abilitySets: [[7, 1, 1, 1], ...sets.slice(1)] }); expect(badSets.status).toBe(400); const abilityRoll = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ abilitySets: sets }); expect(abilityRoll.status).toBe(200); expect(abilityRoll.body.buildState.abilityRolls.map((r) => r.total)).toEqual([17, 14, 12, 10, 10, 12]); expect(abilityRoll.body.buildState.abilityRolls[0]).toEqual({ dice: [6, 6, 5, 1], dropped: 1, total: 17 }); }); }); describe('story steps: special abilities, background and appearance', () => { itIfDb('are picked from fixed lists, composed by the server, and then only the DM can edit them', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('story'); // skipMotivationRoll: true const optionsRes = await request(app).get('/characters/build/options').set(playerAuth); expect(optionsRes.status).toBe(200); const options = optionsRes.body; expect(options.motivations).toHaveLength(6); expect(options.talentPicks).toBe(2); expect(options.background.map((g) => g.key)).toEqual(['upbringing', 'home', 'turningPoint', 'personality', 'flaw']); expect(options.appearance.map((g) => g.key)).toEqual(['build', 'height', 'hair', 'eyes', 'complexion', 'features', 'style']); expect(Object.keys(options.speciesTraits)).toHaveLength(10); expect(Object.keys(options.classFeatures)).toHaveLength(12); const id = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Storied' })).body.character.id; const b = `/characters/${id}/build`; const post = (path, body) => request(app).post(`${b}/${path}`).set(playerAuth).send(body); await request(app).patch(`${b}/dice-mode`).set(playerAuth).send({ diceMode: 'PHYSICAL' }); await post('roll', { value: 3 }); await post('choose', { species: 'DWARF' }); await post('roll', { value: 1 }); await post('choose', { characterClass: 'BARBARIAN' }); await post('roll', { abilitySets: [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]] }); await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); expect((await post('choose', {})).body.buildStage).toBe('CHOOSING_ABILITIES'); // Talents: exactly two, different, from the list. for (const talents of [[], ['ALERT'], ['ALERT', 'ALERT'], ['ALERT', 'FLIGHT'], ['ALERT', 'KEEN_EYE', 'LINGUIST']]) { expect((await post('choose', { talents })).status).toBe(400); } expect((await post('choose', { talents: ['ALERT', 'KEEN_EYE'] })).body.buildStage).toBe('CHOOSING_BACKGROUND'); // Background: one per group (one or two personality traits), nothing invented. const bg = STORY_PICKS.background; expect((await post('choose', { picks: { ...bg, upbringing: [] } })).status).toBe(400); expect((await post('choose', { picks: { ...bg, upbringing: ['SOLDIER', 'NOBLE'] } })).status).toBe(400); expect((await post('choose', { picks: { ...bg, upbringing: ['EMPEROR'] } })).status).toBe(400); expect((await post('choose', { picks: { ...bg, personality: ['BRAVE', 'KIND', 'LOYAL'] } })).status).toBe(400); const bgRes = await post('choose', { picks: { ...bg, smuggled: ['free text'] } }); expect(bgRes.body.buildStage).toBe('CHOOSING_APPEARANCE'); expect(bgRes.body.buildState.backgroundPicks).toEqual(bg); // unknown groups are dropped // Appearance: distinguishing features are optional. expect((await post('choose', { picks: { ...STORY_PICKS.appearance, hair: [] } })).status).toBe(400); expect((await post('choose', { picks: { ...STORY_PICKS.appearance, features: [] } })).body.buildStage).toBe('CHOOSING_EQUIPMENT'); await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); const character = (await post('finalize')).body.character; // Species traits, then class features, then the picked talents — one per line. expect(character.specialAbilities.split('\n').map((line) => line.split(' — ')[0])).toEqual([ 'Darkvision', 'Dwarven Resilience', 'Rage', 'Unarmored Defense', 'Alert', 'Keen Eye', ]); expect(character.background.split('\n')).toEqual([ 'Upbringing: Soldier — Served in an army or militia, and still thinks in terms of orders and watches.', 'Home: A small village — Everyone knew everyone, and nothing stayed secret.', 'Turning point: Was betrayed — By someone they trusted completely.', 'Personality: Brave, Curious', 'Flaw: Greedy — Cannot walk past treasure.', ]); expect(character.appearance.split('\n')).toEqual([ 'Build: Muscular', 'Height: Tall', 'Hair: Red', 'Eyes: Green', 'Skin: Weathered', 'Usually wears: A hooded cloak', ]); // Locked for the player; the DM can still rewrite them as the story moves on. const sheet = `/characters/${id}`; expect((await request(app).patch(sheet).set(playerAuth).send({ specialAbilities: 'Flight' })).status).toBe(403); const dmEdit = await request(app).patch(sheet).set(dmAuth).send({ specialAbilities: `${character.specialAbilities}\nReckless Attack — Gained at level 2.` }); expect(dmEdit.status).toBe(200); expect(dmEdit.body.character.specialAbilities).toContain('Reckless Attack'); }); }); describe('going back in the builder', () => { itIfDb('returns to earlier steps with the same rolls, lets the choice change, and never re-rolls', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('back'); await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ skipMotivationRoll: false }); const id = (await request(app).post(`/campaigns/${campaign.id}/characters`).set(playerAuth).send({ name: 'Undecided' })).body.character.id; const b = `/characters/${id}/build`; const post = (path, body, auth = playerAuth) => request(app).post(`${b}/${path}`).set(auth).send(body); const stage = (res) => res.body.buildStage; expect((await post('back')).status).toBe(400); // nothing before the first step await request(app).patch(`${b}/dice-mode`).set(playerAuth).send({ diceMode: 'PHYSICAL' }); // Species: a 3 offers Dwarf or Halfling. await post('roll', { value: 3 }); expect((await post('roll', { value: 6 })).status).toBe(400); // one roll only expect(stage(await post('choose', { species: 'DWARF' }))).toBe('ROLLING_CLASS'); // Back before rolling for class: same species roll, and the pick can change. const backToSpecies = await post('back'); expect(stage(backToSpecies)).toBe('ROLLING_SPECIES'); expect(backToSpecies.body.buildState).toMatchObject({ speciesRoll: 3, species: 'DWARF' }); expect((await post('roll', { value: 6 })).status).toBe(400); // still no re-roll expect((await post('choose', { species: 'ELF' })).status).toBe(400); // not offered by the roll await post('choose', { species: 'HALFLING' }); // Class: a 4 offers Cleric or Paladin. await post('roll', { value: 4 }); await post('choose', { characterClass: 'CLERIC' }); // Motivation is picked from the list, not rolled. expect((await post('roll', { value: 2 })).status).toBe(400); expect((await post('choose', {})).status).toBe(400); expect((await post('choose', { motivation: 7 })).status).toBe(400); const motivated = await post('choose', { motivation: 2 }); expect(stage(motivated)).toBe('ASSIGNING_SCORES'); expect(motivated.body.buildState).toMatchObject({ motivationChoice: 2, motivationText: 'Seeking fortune or wealth' }); await post('roll', { abilitySets: [[6, 6, 5, 1], [5, 5, 4, 2], [4, 4, 4, 1], [3, 3, 4, 2], [6, 2, 2, 1], [5, 4, 3, 3]] }); const assigned = await post('choose', { assignments: { STR: 3, DEX: 2, CON: 1, INT: 4, WIS: 0, CHA: 5 } }); expect(stage(assigned)).toBe('ASSIGNING_PROFICIENCIES'); const clericSkills = assigned.body.buildState.skillProficiencies; // Back to the scores and forward again: same rolls, same skills, new assignment. const backToScores = await post('back'); expect(stage(backToScores)).toBe('ASSIGNING_SCORES'); expect(backToScores.body.buildState.abilityRolls.map((r) => r.total)).toEqual([17, 14, 12, 10, 10, 12]); expect((await post('roll', {})).status).toBe(400); const reassigned = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); expect(reassigned.body.buildState.skillProficiencies).toEqual(clericSkills); // All the way back to class (through motivation), switch to Paladin and return. expect(stage(await post('back'))).toBe('ASSIGNING_SCORES'); expect(stage(await post('back'))).toBe('ROLLING_MOTIVATION'); const backToClass = await post('back'); expect(stage(backToClass)).toBe('ROLLING_CLASS'); expect(backToClass.body.buildState).toMatchObject({ classRoll: 4, characterClass: 'CLERIC' }); expect((await post('roll', { value: 8 })).status).toBe(400); await post('choose', { characterClass: 'PALADIN' }); await post('choose', { motivation: 5 }); // the motivation can change on the way back through const asPaladin = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); const paladinOptions = ['ATHLETICS', 'INSIGHT', 'INTIMIDATION', 'MEDICINE', 'PERSUASION', 'RELIGION']; expect(asPaladin.body.buildState.skillProficiencies.every((s) => paladinOptions.includes(s.skill))).toBe(true); // Switching back to Cleric brings back the Cleric's original skills, not a fresh draw. await post('back'); await post('back'); await post('back'); await post('choose', { characterClass: 'CLERIC' }); await post('choose', { motivation: 5 }); const asClericAgain = await post('choose', { assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); expect(asClericAgain.body.buildState.skillProficiencies).toEqual(clericSkills); // Equipment: back from the finalize prompt reopens the selection. await post('choose', {}); await storySteps(id, playerAuth); await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); const reopened = await post('back'); expect(stage(reopened)).toBe('CHOOSING_EQUIPMENT'); expect(reopened.body.buildState.equipment).toBeUndefined(); expect((await post('finalize')).status).toBe(400); // equipment must be confirmed again // Back through the story steps: each keeps what was picked. const backToAppearance = await post('back'); expect(stage(backToAppearance)).toBe('CHOOSING_APPEARANCE'); expect(backToAppearance.body.buildState.appearancePicks).toEqual(STORY_PICKS.appearance); expect(stage(await post('back'))).toBe('CHOOSING_BACKGROUND'); expect(stage(await post('back'))).toBe('CHOOSING_ABILITIES'); await storySteps(id, playerAuth); await post('choose', { weaponIds: [], itemIds: [], spellIds: [] }); // Only the owner or DM can step a build back, and not once it is finished. const stranger = await request(app).post('/auth/register').send({ email: uniqueEmail('back-other'), password: 'password123', displayName: 'Other' }); cleanupUserIds.push(stranger.body.user.id); const strangerAuth = { Authorization: `Bearer ${stranger.body.token}` }; await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(strangerAuth); expect((await post('back', undefined, strangerAuth)).status).toBe(403); const finalized = await post('finalize'); expect(finalized.body.character).toMatchObject({ species: 'HALFLING', characterClass: 'CLERIC', buildStage: 'COMPLETE', motivation: 'Driven by curiosity or knowledge', }); expect(finalized.body.character.rolledScores).toEqual({ STR: 17, DEX: 14, CON: 12, INT: 10, WIS: 10, CHA: 12 }); expect((await post('back')).status).toBe(400); }); itIfDb('skips the motivation step on the way back when the campaign skips it', async () => { const { playerAuth, campaign } = await setupCampaign('backskip'); // skipMotivationRoll: true const id = await buildCharacter(campaign.id, playerAuth, 'Brisk', { stopBeforeEquipment: true }); const back = () => request(app).post(`/characters/${id}/build/back`).set(playerAuth); expect((await back()).body.buildStage).toBe('CHOOSING_APPEARANCE'); expect((await back()).body.buildStage).toBe('CHOOSING_BACKGROUND'); expect((await back()).body.buildStage).toBe('CHOOSING_ABILITIES'); expect((await back()).body.buildStage).toBe('ASSIGNING_PROFICIENCIES'); expect((await back()).body.buildStage).toBe('ASSIGNING_SCORES'); expect((await back()).body.buildStage).toBe('ROLLING_CLASS'); expect((await back()).body.buildStage).toBe('ROLLING_SPECIES'); expect((await back()).status).toBe(400); }); }); describe('auto-generated skill proficiencies', () => { itIfDb('assigns the class\'s SRD skill count automatically once ability scores are locked in', async () => { const { dmAuth, campaign } = await setupCampaign('autoskill'); const characterRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set(dmAuth) .send({ name: 'Auto Skills' }); const characterId = characterRes.body.character.id; let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); const species = rollRes.body.buildState.speciesChoices.options[0]; await request(app) .post(`/characters/${characterId}/build/choose`) .set(dmAuth) .send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species }); rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); while (rollRes.body.buildState.classChoices.type === 'reroll') { rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); } const characterClass = rollRes.body.buildState.classChoices.options[0]; await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass }); await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); const scoresRes = await request(app) .post(`/characters/${characterId}/build/choose`) .set(dmAuth) .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); expect(scoresRes.body.buildStage).toBe('ASSIGNING_PROFICIENCIES'); expect(scoresRes.body.buildState.skillProficiencies.length).toBeGreaterThan(0); expect(new Set(scoresRes.body.buildState.skillProficiencies.map((s) => s.skill)).size).toBe( scoresRes.body.buildState.skillProficiencies.length ); // no duplicates }); }); describe('locations', () => { itIfDb('DM manages locations; a player cannot', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('locations'); const createRes = await request(app).post(`/campaigns/${campaign.id}/locations`).set(dmAuth).send({ name: 'The Rusty Tankard' }); expect(createRes.status).toBe(201); const locationId = createRes.body.location.id; const playerCreateRes = await request(app).post(`/campaigns/${campaign.id}/locations`).set(playerAuth).send({ name: 'Nope' }); expect(playerCreateRes.status).toBe(403); const listRes = await request(app).get(`/campaigns/${campaign.id}/locations`).set(playerAuth); expect(listRes.status).toBe(200); expect(listRes.body.locations.map((l) => l.id)).toContain(locationId); const charRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set(playerAuth) .send({ name: 'Wanderer' }); const playerPatchRes = await request(app) .patch(`/characters/${charRes.body.character.id}`) .set(playerAuth) .send({ currentLocationId: locationId }); expect(playerPatchRes.status).toBe(403); const patchRes = await request(app) .patch(`/characters/${charRes.body.character.id}`) .set(dmAuth) .send({ currentLocationId: locationId }); expect(patchRes.status).toBe(200); expect(patchRes.body.character.currentLocationId).toBe(locationId); }); }); describe('default content library', () => { itIfDb('lists library entries and copies one into the campaign', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('library'); const listRes = await request(app).get(`/campaigns/${campaign.id}/library`).set(playerAuth); expect(listRes.status).toBe(200); expect(listRes.body.weapons.length).toBeGreaterThan(20); expect(listRes.body.spells.length).toBeGreaterThan(50); expect(listRes.body.monsters.length).toBeGreaterThan(20); const addRes = await request(app) .post(`/campaigns/${campaign.id}/weapons/from-library`) .set(dmAuth) .send({ key: 'longsword' }); expect(addRes.status).toBe(201); expect(addRes.body.weapon.name).toBe('Longsword'); expect(addRes.body.weapon.campaignId).toBe(campaign.id); // Library spells show their level and default damage before they are added, // and carry both into the campaign. const byKey = Object.fromEntries(listRes.body.spells.map((s) => [s.key, s])); expect(byKey.fireball).toMatchObject({ level: 3, damageDice: '8d6' }); expect(byKey['fire-bolt']).toMatchObject({ level: 0, damageDice: '1d10' }); expect(byKey['cure-wounds'].damageDice).toBeUndefined(); // healing, not damage expect(listRes.body.spells.filter((s) => s.damageDice).length).toBeGreaterThan(30); const spellRes = await request(app).post(`/campaigns/${campaign.id}/spells/from-library`).set(dmAuth).send({ key: 'fireball' }); expect(spellRes.body.spell).toMatchObject({ name: 'Fireball', level: 3, damageDice: '8d6', isStartingOption: false }); // Monster stat blocks are the DM's. await request(app).post(`/campaigns/${campaign.id}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' }); expect((await request(app).get(`/campaigns/${campaign.id}/monsters`).set(dmAuth)).body.monsters).toHaveLength(1); expect((await request(app).get(`/campaigns/${campaign.id}/monsters`).set(playerAuth)).status).toBe(403); const playerAddRes = await request(app) .post(`/campaigns/${campaign.id}/monsters/from-library`) .set(playerAuth) .send({ key: 'goblin' }); expect(playerAddRes.status).toBe(403); }); }); describe('private notes', () => { itIfDb('is visible to the owning player but hidden from the DM and other players', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('privatenotes'); const charRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set(playerAuth) .send({ name: 'Secretive' }); const characterId = charRes.body.character.id; const patchRes = await request(app) .patch(`/characters/${characterId}`) .set(playerAuth) .send({ privateNotes: 'The amulet is cursed.' }); expect(patchRes.status).toBe(200); expect(patchRes.body.character.privateNotes).toBe('The amulet is cursed.'); const ownerReadRes = await request(app).get(`/characters/${characterId}`).set(playerAuth); expect(ownerReadRes.body.character.privateNotes).toBe('The amulet is cursed.'); const dmReadRes = await request(app).get(`/characters/${characterId}`).set(dmAuth); expect(dmReadRes.body.character.privateNotes).toBeUndefined(); const dmSetAttempt = await request(app) .patch(`/characters/${characterId}`) .set(dmAuth) .send({ privateNotes: 'DM trying to snoop' }); expect(dmSetAttempt.status).toBe(403); }); }); describe('DM-only campaign notes', () => { itIfDb('only the DM can post one, and only the DM can read it back', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('dmnotes'); const playerAttempt = await request(app) .post('/notes') .set(playerAuth) .send({ campaignId: campaign.id, body: 'Sneaky player note', visibility: 'DM_ONLY' }); expect(playerAttempt.status).toBe(403); const dmNoteRes = await request(app) .post('/notes') .set(dmAuth) .send({ campaignId: campaign.id, body: 'The mayor is the villain.', visibility: 'DM_ONLY' }); expect(dmNoteRes.status).toBe(201); const dmListRes = await request(app).get(`/campaigns/${campaign.id}/notes`).set(dmAuth); expect(dmListRes.body.notes.some((n) => n.body === 'The mayor is the villain.')).toBe(true); const playerListRes = await request(app).get(`/campaigns/${campaign.id}/notes`).set(playerAuth); expect(playerListRes.body.notes.some((n) => n.body === 'The mayor is the villain.')).toBe(false); }); }); describe('encounter combat info', () => { itIfDb('shows a character combatant\'s weapons to every campaign member, not just the DM', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('encountercombat'); const weaponRes = await request(app) .post(`/campaigns/${campaign.id}/weapons/from-library`) .set(dmAuth) .send({ key: 'dagger' }); const weaponId = weaponRes.body.weapon.id; const characterRes = await request(app) .post(`/campaigns/${campaign.id}/characters`) .set(dmAuth) .send({ name: 'Combatant' }); const characterId = characterRes.body.character.id; // Fast-path the build with skipMotivationRoll + a single wildcard-free walk. let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); const species = rollRes.body.buildState.speciesChoices.options[0]; await request(app) .post(`/characters/${characterId}/build/choose`) .set(dmAuth) .send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species }); rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); while (rollRes.body.buildState.classChoices.type === 'reroll') { rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); } const characterClass = rollRes.body.buildState.classChoices.options[0]; await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass }); await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth); await request(app) .post(`/characters/${characterId}/build/choose`) .set(dmAuth) .send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } }); await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({}); await storySteps(characterId, dmAuth); await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ weaponIds: [], spellIds: [] }); await request(app).post(`/characters/${characterId}/build/finalize`).set(dmAuth); await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId }); await request(app).patch(`/characters/${characterId}/weapons/${weaponId}`).set(dmAuth).send({ equipped: true }); const encounterRes = await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Ambush' }); const encounterId = encounterRes.body.encounter.id; await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId, initiative: 10 }); const playerViewRes = await request(app).get(`/encounters/${encounterId}`).set(playerAuth); expect(playerViewRes.status).toBe(200); const participant = playerViewRes.body.encounter.participants[0]; expect(participant.characterCombatInfo.weapons).toHaveLength(1); expect(participant.characterCombatInfo.weapons[0].name).toBe('Dagger'); expect(typeof participant.characterCombatInfo.weapons[0].attackBonus).toBe('number'); }); });