// 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't see what is in the pool, add to it, or help themselves from it. expect((await request(app).get(`/campaigns/${campaign.id}/items`).set(playerAuth)).body.items).toHaveLength(0); 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: -1 })).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, initiativeRoll: 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: -1, 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({ initiativeRoll: 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 neither write to the ledger nor read 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); expect((await request(app).get(`/characters/${characterId}/gold`).set(strangerAuth)).status).toBe(403); const ledger = await request(app).get(`/characters/${characterId}/gold`).set(playerAuth); 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, heroId } = 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}`; // A player whose character isn't in a scene can't see it exists. expect((await request(app).get(e).set(playerAuth)).status).toBe(404); expect((await request(app).get(`${c}/encounters`).set(playerAuth)).body.encounters).toEqual([]); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId }); 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])).toEqual([['The Missing Miller', 'QUEST']]); expect((await request(app).get(`/encounters/${battle.id}`).set(playerAuth)).status).toBe(404); expect(playerList.every((x) => x.dmNotes === undefined)).toBe(true); const dmList = (await request(app).get(`${c}/encounters`).set(dmAuth)).body.encounters; expect(dmList.map((x) => x.name).sort()).toEqual(['Ambush', 'The Missing Miller']); expect(dmList.find((x) => x.id === quest.id).dmNotes).toBe('The miller is the werewolf.'); // Taken out of the scene, the player loses sight of it again. const heroRow = (await request(app).get(e).set(dmAuth)).body.encounter.participants.find((p) => p.characterId === heroId); await request(app).delete(`${e}/participants/${heroRow.id}`).set(dmAuth); expect((await request(app).get(e).set(playerAuth)).status).toBe(404); }); itIfDb('NPCs are DM-managed and join encounters without leaking the DM\'s notes or stats', async () => { const { dmAuth, playerAuth, c, heroId } = 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 await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId }); 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)).sort()).toEqual(['Aria', '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, initiativeRoll: 5 }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId, initiativeRoll: 20 }); 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, initiativeRoll: 1 }); const fast = await add({ characterId: heroId, initiativeRoll: 20 }); const mid = await add({ characterId: allyId, initiativeRoll: 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, initiativeRoll: 20 }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: allyId, initiativeRoll: 1 }); 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).toEqual([]); // nowhere this player's character has been 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'); expect((await request(app).get(`/campaigns/${campaign.id}/library`).set(playerAuth)).status).toBe(403); const listRes = await request(app).get(`/campaigns/${campaign.id}/library`).set(dmAuth); 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 the other players in the encounter, 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, initiativeRoll: 10 }); const watcherId = await buildCharacter(campaign.id, playerAuth, 'Watcher'); await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId: watcherId }); 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'); }); }); describe('changing a password', () => { itIfDb('needs the current password, then only the new one logs in', async () => { const email = uniqueEmail('pw'); const registerRes = await request(app).post('/auth/register').send({ email, password: 'password123', displayName: 'Pw' }); cleanupUserIds.push(registerRes.body.user.id); const auth = { Authorization: `Bearer ${registerRes.body.token}` }; expect((await request(app).post('/auth/password').send({ currentPassword: 'password123', newPassword: 'new-password1' })).status).toBe(401); const wrong = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'nope', newPassword: 'new-password1' }); expect(wrong.status).toBe(400); const short = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'short' }); expect(short.status).toBe(400); const same = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'password123' }); expect(same.status).toBe(400); const changed = await request(app).post('/auth/password').set(auth).send({ currentPassword: 'password123', newPassword: 'new-password1' }); expect(changed.status).toBe(204); expect((await request(app).post('/auth/login').send({ email, password: 'password123' })).status).toBe(401); expect((await request(app).post('/auth/login').send({ email, password: 'new-password1' })).status).toBe(200); }); }); describe('archiving and deleting a campaign', () => { itIfDb('the DM archives and restores; an archived campaign keeps its contents but takes no new members', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('archive'); const c = `/campaigns/${campaign.id}`; expect(campaign.archivedAt).toBeNull(); expect((await request(app).patch(c).set(playerAuth).send({ archived: true })).status).toBe(403); const archived = await request(app).patch(c).set(dmAuth).send({ archived: true }); expect(archived.status).toBe(200); expect(archived.body.campaign.archivedAt).toBeTruthy(); // Still there for its members, and flagged in their lists. const playerList = await request(app).get('/campaigns').set(playerAuth); expect(playerList.body.campaigns.find((x) => x.id === campaign.id).archivedAt).toBeTruthy(); expect((await request(app).get(c).set(playerAuth)).status).toBe(200); const outsider = await request(app) .post('/auth/register') .send({ email: uniqueEmail('archive-outsider'), password: 'password123', displayName: 'Outsider' }); cleanupUserIds.push(outsider.body.user.id); const outsiderAuth = { Authorization: `Bearer ${outsider.body.token}` }; expect((await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(outsiderAuth)).status).toBe(403); // Other settings can change without un-archiving it. const renamed = await request(app).patch(c).set(dmAuth).send({ startingGold: 7 }); expect(renamed.body.campaign.archivedAt).toBeTruthy(); const restored = await request(app).patch(c).set(dmAuth).send({ archived: false }); expect(restored.body.campaign.archivedAt).toBeNull(); expect(restored.body.campaign.startingGold).toBe(7); expect((await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(outsiderAuth)).status).toBe(201); }); itIfDb('only the owner deletes, and everything in the campaign goes with it', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('delete'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Doomed'); const encounterRes = await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Last Stand' }); const encounterId = encounterRes.body.encounter.id; await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId: heroId }); await request(app).post('/notes').set(dmAuth).send({ campaignId: campaign.id, body: 'Secret', visibility: 'DM_ONLY' }); expect((await request(app).delete(c).set(playerAuth)).status).toBe(403); expect((await request(app).get(c).set(dmAuth)).status).toBe(200); expect((await request(app).delete(c).set(dmAuth)).status).toBe(204); expect((await request(app).get(c).set(dmAuth)).status).toBe(404); expect((await request(app).get(`/characters/${heroId}`).set(playerAuth)).status).toBe(404); expect((await request(app).get(`/encounters/${encounterId}`).set(dmAuth)).status).toBe(404); expect(await prisma.note.count({ where: { campaignId: campaign.id } })).toBe(0); const dmList = await request(app).get('/campaigns').set(dmAuth); expect(dmList.body.campaigns.find((x) => x.id === campaign.id)).toBeUndefined(); }); }); describe('ordering, archiving and deleting encounters', () => { itIfDb('the DM arranges the list, archives out of players\' sight, and deletes without undoing rewards', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('encorder'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Keeper'); const ids = {}; for (const name of ['One', 'Two', 'Three']) { ids[name] = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name })).body.encounter.id; await request(app).post(`/encounters/${ids[name]}/participants`).set(dmAuth).send({ characterId: heroId }); } const names = async (auth) => (await request(app).get(`${c}/encounters`).set(auth)).body.encounters.map((e) => e.name); // New encounters go to the top. expect(await names(dmAuth)).toEqual(['Three', 'Two', 'One']); const order = (encounterIds, auth = dmAuth) => request(app).put(`${c}/encounters/order`).set(auth).send({ encounterIds }); expect((await order([ids.One, ids.Two, ids.Three], playerAuth)).status).toBe(403); expect((await order([ids.One, ids.One])).status).toBe(400); expect((await order([ids.One, 'not-an-encounter'])).status).toBe(400); expect((await order([ids.One, ids.Two, ids.Three])).status).toBe(204); expect(await names(playerAuth)).toEqual(['One', 'Two', 'Three']); // Archived: the DM still lists it, players don't, and it can still be opened. expect((await request(app).patch(`/encounters/${ids.Two}`).set(playerAuth).send({ archived: true })).status).toBe(403); const archived = await request(app).patch(`/encounters/${ids.Two}`).set(dmAuth).send({ archived: true }); expect(archived.body.encounter.archivedAt).toBeTruthy(); expect(await names(playerAuth)).toEqual(['One', 'Three']); expect(await names(dmAuth)).toEqual(['One', 'Two', 'Three']); expect((await request(app).get(`/encounters/${ids.Two}`).set(playerAuth)).status).toBe(200); const restored = await request(app).patch(`/encounters/${ids.Two}`).set(dmAuth).send({ archived: false }); expect(restored.body.encounter.archivedAt).toBeNull(); expect(await names(playerAuth)).toEqual(['One', 'Two', 'Three']); // Deleting takes the scene but leaves what it already gave out. const rewardRes = await request(app).post(`/encounters/${ids.One}/rewards`).set(dmAuth).send({ type: 'GOLD', gold: 12 }); await request(app).post(`/encounters/${ids.One}/rewards/${rewardRes.body.reward.id}/award`).set(dmAuth).send({ characterId: heroId }); const goldBefore = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character.gold; expect((await request(app).delete(`/encounters/${ids.One}`).set(playerAuth)).status).toBe(403); expect((await request(app).delete(`/encounters/${ids.One}`).set(dmAuth)).status).toBe(204); expect((await request(app).get(`/encounters/${ids.One}`).set(dmAuth)).status).toBe(404); expect(await names(dmAuth)).toEqual(['Two', 'Three']); const after = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character; expect(after.gold).toBe(goldBefore); expect(goldBefore).toBeGreaterThanOrEqual(12); }); }); describe('what a player may see', () => { itIfDb('the pools: starting options while building, then only what their character holds', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('poolview'); const c = `/campaigns/${campaign.id}`; const weapon = (name, isStartingOption) => request(app).post(`${c}/weapons`).set(dmAuth).send({ name, damageDice: '1d6', damageType: 'slashing', attackAbility: 'STR', isStartingOption }); await weapon('Starter Sword', true); const secret = (await weapon('Secret Blade', false)).body.weapon; await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Rope', isStartingOption: true }); await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Crown Shard' }); await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Spark', level: 0, isStartingOption: true }); await request(app).post(`${c}/spells`).set(dmAuth).send({ name: 'Doom', level: 5 }); const names = async (pool, auth) => (await request(app).get(`${c}/${pool}`).set(auth)).body[pool].map((x) => x.name); expect(await names('weapons', dmAuth)).toEqual(['Secret Blade', 'Starter Sword']); // No character yet: nothing to choose from, nothing held. expect(await names('weapons', playerAuth)).toEqual([]); expect(await names('items', playerAuth)).toEqual([]); expect(await names('spells', playerAuth)).toEqual([]); // Building: the starting options, and only those. const hero = (await request(app).post(`${c}/characters`).set(playerAuth).send({ name: 'Newcomer' })).body.character; expect(await names('weapons', playerAuth)).toEqual(['Starter Sword']); expect(await names('items', playerAuth)).toEqual(['Rope']); expect(await names('spells', playerAuth)).toEqual(['Spark']); await request(app).delete(`/characters/${hero.id}`).set(dmAuth); // Built: only what the character holds. const heroId = await buildCharacter(campaign.id, playerAuth, 'Veteran'); expect(await names('weapons', playerAuth)).toEqual([]); await request(app).post(`/characters/${heroId}/weapons`).set(dmAuth).send({ weaponId: secret.id }); expect(await names('weapons', playerAuth)).toEqual(['Secret Blade']); expect(await names('items', playerAuth)).toEqual([]); // The built-in library is the DM's tool. expect((await request(app).get(`${c}/library`).set(playerAuth)).status).toBe(403); expect((await request(app).get(`${c}/library`).set(dmAuth)).status).toBe(200); }); itIfDb('the invite code is the DM’s alone', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('invitehide'); const c = `/campaigns/${campaign.id}`; expect((await request(app).get(c).set(dmAuth)).body.campaign.inviteCode).toBe(campaign.inviteCode); expect((await request(app).get(c).set(playerAuth)).body.campaign.inviteCode).toBeUndefined(); const listed = (await request(app).get('/campaigns').set(playerAuth)).body.campaigns.find((x) => x.id === campaign.id); expect(listed.inviteCode).toBeUndefined(); }); itIfDb('another player’s character: HP and AC, but not their gold, pack or money log', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('sheetview'); const c = `/campaigns/${campaign.id}`; await request(app).patch(c).set(dmAuth).send({ startingGold: 20 }); const mineId = await buildCharacter(campaign.id, playerAuth, 'Mine'); const theirsId = await buildCharacter(campaign.id, dmAuth, 'Theirs'); const item = (await request(app).post(`${c}/items`).set(dmAuth).send({ name: 'Love Letter' })).body.item; await request(app).post(`/characters/${theirsId}/inventory`).set(dmAuth).send({ itemId: item.id }); const theirs = (await request(app).get(`/characters/${theirsId}`).set(playerAuth)).body.character; expect(theirs.restricted).toBe(true); expect(theirs.gold).toBeNull(); expect(theirs.inventoryItems).toEqual([]); expect(theirs.sheet.armorClass).toEqual(expect.any(Number)); expect(theirs.currentHp).toEqual(expect.any(Number)); expect((await request(app).get(`/characters/${theirsId}/gold`).set(playerAuth)).status).toBe(403); const mine = (await request(app).get(`/characters/${mineId}`).set(playerAuth)).body.character; expect(mine.restricted).toBe(false); expect(mine.gold).toBe(20); expect((await request(app).get(`/characters/${mineId}/gold`).set(playerAuth)).status).toBe(200); const dmView = (await request(app).get(`/characters/${theirsId}`).set(dmAuth)).body.character; expect(dmView.gold).toBe(20); expect(dmView.inventoryItems.map((i) => i.item.name)).toEqual(['Love Letter']); const list = (await request(app).get(`${c}/characters`).set(playerAuth)).body.characters; expect(list.find((x) => x.id === mineId).gold).toBe(20); expect(list.find((x) => x.id === theirsId)).toMatchObject({ gold: null, armorClass: expect.any(Number), currentHp: expect.any(Number) }); const dmList = (await request(app).get(`${c}/characters`).set(dmAuth)).body.characters; expect(dmList.find((x) => x.id === theirsId).gold).toBe(20); }); itIfDb('locations: only where their character has been, and an encounter in progress takes them there', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('locview'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Wanderer'); const strangerId = await buildCharacter(campaign.id, dmAuth, 'Stranger'); const place = async (name) => (await request(app).post(`${c}/locations`).set(dmAuth).send({ name, description: `About ${name}.` })).body.location; const cave = await place('Cave'); const keep = await place('Keep'); const vault = await place('Vault'); const seen = async () => (await request(app).get(`${c}/locations`).set(playerAuth)).body.locations.map((l) => l.name); expect((await request(app).get(`${c}/locations`).set(dmAuth)).body.locations).toHaveLength(3); expect(await seen()).toEqual([]); // A planned encounter with a location moves nobody and reveals nothing. const other = await setupCampaign('locview-other'); const foreign = (await request(app).post(`/campaigns/${other.campaign.id}/locations`).set(other.dmAuth).send({ name: 'Elsewhere' })).body.location; expect((await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Bad', locationId: foreign.id })).status).toBe(400); const enc = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Into the Cave', locationId: cave.id })).body.encounter; const e = `/encounters/${enc.id}`; await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId }); expect(await seen()).toEqual([]); expect((await request(app).get(e).set(playerAuth)).body.encounter.location).toBeNull(); expect((await request(app).get(e).set(dmAuth)).body.encounter.location.name).toBe('Cave'); // Beginning it puts the characters in it there. await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE' }); expect((await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character.currentLocation.name).toBe('Cave'); expect(await seen()).toEqual(['Cave']); expect((await request(app).get(e).set(playerAuth)).body.encounter.location).toMatchObject({ name: 'Cave', description: 'About Cave.' }); // Moving a running encounter, or joining one, does the same. expect((await request(app).patch(e).set(dmAuth).send({ locationId: foreign.id })).status).toBe(400); await request(app).patch(e).set(dmAuth).send({ locationId: keep.id }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: strangerId }); expect((await request(app).get(`/characters/${strangerId}`).set(dmAuth)).body.character.currentLocation.name).toBe('Keep'); expect(await seen()).toEqual(['Cave', 'Keep']); // Places stay known after moving on, and after the encounter is archived or deleted. await request(app).patch(e).set(dmAuth).send({ status: 'COMPLETE', archived: true }); expect(await seen()).toEqual(['Cave', 'Keep']); await request(app).delete(e).set(dmAuth); expect(await seen()).toEqual(['Cave', 'Keep']); // The DM placing a character by hand counts as a visit too. await request(app).patch(`/characters/${heroId}`).set(dmAuth).send({ currentLocationId: vault.id }); expect(await seen()).toEqual(['Cave', 'Keep', 'Vault']); // Where the party is: named only if this player has been there themselves. await request(app).patch(`/characters/${strangerId}`).set(dmAuth).send({ currentLocationId: cave.id }); const list = async () => (await request(app).get(`${c}/characters`).set(playerAuth)).body.characters.find((x) => x.id === strangerId); expect((await list()).currentLocationName).toBe('Cave'); const hidden = await place('Hidden Grove'); await request(app).patch(`/characters/${strangerId}`).set(dmAuth).send({ currentLocationId: hidden.id }); expect((await list()).currentLocationName).toBeNull(); expect((await request(app).get(`/characters/${strangerId}`).set(playerAuth)).body.character.currentLocation).toBeNull(); }); itIfDb('monster hit points: numbers, or only a bar when the campaign says so', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('hpview'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Watcher'); const monster = (await request(app).post(`${c}/monsters`).set(dmAuth).send({ name: 'Ogre', ac: 11, maxHp: 59 })).body.monster; const npc = (await request(app).post(`${c}/npcs`).set(dmAuth).send({ name: 'Captain', maxHp: 40 })).body.npc; const enc = (await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Bridge' })).body.encounter; const e = `/encounters/${enc.id}`; await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId }); const ogreRow = (await request(app).post(`${e}/participants`).set(dmAuth).send({ monsterId: monster.id })).body.participant; await request(app).post(`${e}/participants`).set(dmAuth).send({ npcId: npc.id }); const view = async (auth) => Object.fromEntries((await request(app).get(e).set(auth)).body.encounter.participants.map((p) => [p.displayName, p])); expect(campaign.showMonsterHp).toBe(true); expect((await view(playerAuth)).Ogre).toMatchObject({ currentHp: 59, maxHp: 59 }); expect((await request(app).patch(c).set(playerAuth).send({ showMonsterHp: false })).status).toBe(403); expect((await request(app).patch(c).set(dmAuth).send({ showMonsterHp: false })).body.campaign.showMonsterHp).toBe(false); await request(app).patch(`${e}/participants/${ogreRow.id}`).set(dmAuth).send({ currentHp: 1 }); const player = await view(playerAuth); expect(player.Ogre).toMatchObject({ currentHp: null, maxHp: null, hpPercent: 2 }); // 1 of 59, rounded up expect(player.Captain).toMatchObject({ currentHp: null, maxHp: null, hpPercent: 100 }); expect(player.Watcher.currentHp).toEqual(expect.any(Number)); // characters keep their numbers expect(player.Watcher.hpPercent).toBeUndefined(); const dm = await view(dmAuth); expect(dm.Ogre).toMatchObject({ currentHp: 1, maxHp: 59 }); expect(dm.Ogre.hpPercent).toBeUndefined(); await request(app).patch(`${e}/participants/${ogreRow.id}`).set(dmAuth).send({ currentHp: 0 }); // At 0 HP it is out of the fight, and out of the players' sight. expect((await view(playerAuth)).Ogre).toBeUndefined(); expect((await view(dmAuth)).Ogre).toMatchObject({ currentHp: 0, hidden: true }); }); }); describe('initiative', () => { itIfDb('is the d20 roll plus the combatant\'s bonus, and a player enters only their own', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('initroll'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Quick'); const allyId = await buildCharacter(campaign.id, dmAuth, 'Steady'); const heroBonus = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character.sheet.initiative; const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; // DEX 14: +2 const npc = (await request(app).post(`${c}/npcs`).set(dmAuth).send({ name: 'Mayor', maxHp: 9 })).body.npc; const e = `/encounters/${(await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Roll for it' })).body.encounter.id}`; const add = (body) => request(app).post(`${e}/participants`).set(dmAuth).send(body); // A roll is a d20: nothing outside 1 to 20, and no fractions. expect((await add({ monsterId: goblin.id, initiativeRoll: 21 })).status).toBe(400); expect((await add({ monsterId: goblin.id, initiativeRoll: 0 })).status).toBe(400); expect((await add({ monsterId: goblin.id, initiativeRoll: 7.5 })).status).toBe(400); const goblinRow = (await add({ monsterId: goblin.id, initiativeRoll: 10 })).body.participant; expect(goblinRow).toMatchObject({ initiativeRoll: 10, initiative: 12 }); const npcRow = (await add({ npcId: npc.id, initiativeRoll: 10 })).body.participant; expect(npcRow).toMatchObject({ initiativeRoll: 10, initiative: 10 }); // an NPC has no bonus const heroRow = (await add({ characterId: heroId })).body.participant; expect(heroRow).toMatchObject({ initiativeRoll: null, initiative: 0 }); const allyRow = (await add({ characterId: allyId })).body.participant; const patch = (row, auth, body) => request(app).patch(`${e}/participants/${row.id}`).set(auth).send(body); const order = async (auth) => (await request(app).get(e).set(auth)).body.encounter.participants; // Not rolled yet: at the bottom of the order. expect((await order(dmAuth)).slice(0, 2).map((p) => p.displayName)).toEqual(['Goblin', 'Mayor']); // The player types what their die showed; the bonus is added for them. expect((await patch(heroRow, playerAuth, { initiativeRoll: 25 })).status).toBe(400); const rolled = await patch(heroRow, playerAuth, { initiativeRoll: 20 }); expect(rolled.status).toBe(200); expect(rolled.body.participant).toMatchObject({ initiativeRoll: 20, initiative: 20 + heroBonus }); expect((await order(playerAuth))[0]).toMatchObject({ displayName: 'Quick', initiativeRoll: 20, initiativeBonus: heroBonus }); // ...and nothing else: not someone else's roll, not a monster's, not their own HP. expect((await patch(allyRow, playerAuth, { initiativeRoll: 15 })).status).toBe(403); expect((await patch(goblinRow, playerAuth, { initiativeRoll: 1 })).status).toBe(403); expect((await patch(heroRow, playerAuth, { initiativeRoll: 20, currentHp: 999 })).status).toBe(403); expect((await patch(heroRow, playerAuth, { conditions: ['hasted'] })).status).toBe(403); // The DM sees every bonus; a player isn't handed a monster's. const dmView = Object.fromEntries((await order(dmAuth)).map((p) => [p.displayName, p])); expect(dmView.Goblin.initiativeBonus).toBe(2); expect(dmView.Mayor.initiativeBonus).toBe(0); const playerView = Object.fromEntries((await order(playerAuth)).map((p) => [p.displayName, p])); expect(playerView.Goblin.initiativeBonus).toBeUndefined(); expect(playerView.Goblin.initiative).toBe(12); expect(playerView.Quick.character.userId).toBeTruthy(); // Only the die stops at 20: a natural 20 plus a bonus goes past it. expect((await patch(goblinRow, dmAuth, { initiativeRoll: 20 })).body.participant).toMatchObject({ initiativeRoll: 20, initiative: 22 }); // Quests take initiative exactly as battles do. await request(app).patch(e).set(dmAuth).send({ mode: 'QUEST' }); expect((await patch(heroRow, playerAuth, { initiativeRoll: 19 })).body.participant.initiative).toBe(19 + heroBonus); await request(app).patch(e).set(dmAuth).send({ mode: 'BATTLE' }); await patch(heroRow, playerAuth, { initiativeRoll: 20 }); // The DM can re-roll anyone, or clear a roll. expect((await patch(goblinRow, dmAuth, { initiativeRoll: 1 })).body.participant.initiative).toBe(3); expect((await patch(heroRow, dmAuth, { initiativeRoll: null })).body.participant).toMatchObject({ initiativeRoll: null, initiative: 0 }); expect((await order(dmAuth)).map((p) => p.displayName).slice(0, 2)).toEqual(['Mayor', 'Goblin']); }); }); describe('targets', () => { itIfDb('are picked by the DM or the player on turn, shown to all, and go when the turn does', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('target'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Archer'); const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; const e = `/encounters/${(await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Ambush' })).body.encounter.id}`; const add = async (body) => (await request(app).post(`${e}/participants`).set(dmAuth).send(body)).body.participant; const hero = await add({ characterId: heroId, initiativeRoll: 20 }); const first = await add({ monsterId: goblin.id, initiativeRoll: 10 }); const second = await add({ monsterId: goblin.id, initiativeRoll: 1 }); const target = (auth, ...participantIds) => request(app).put(`${e}/targets`).set(auth).send({ participantIds }); const seen = async (auth) => (await request(app).get(e).set(auth)).body.encounter.targetParticipantIds; // Before the battle only the DM can mark anyone. expect((await target(playerAuth, first.id)).status).toBe(403); expect((await target(dmAuth, first.id)).body.encounter.targetParticipantIds).toEqual([first.id]); expect(await seen(playerAuth)).toEqual([first.id]); expect((await target(dmAuth, first.id, 'nobody')).status).toBe(400); // Beginning the battle clears them and puts the hero on turn: now the // player can, and several at once is an area attack, kept in the order picked. await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE' }); expect(await seen(dmAuth)).toEqual([]); expect((await target(playerAuth, second.id, first.id, second.id)).status).toBe(200); expect(await seen(dmAuth)).toEqual([second.id, first.id]); // Removing a target unmarks it and leaves the rest. await request(app).delete(`${e}/participants/${second.id}`).set(dmAuth); expect(await seen(dmAuth)).toEqual([first.id]); // The turn passing clears them, and the player is no longer on turn. await request(app).post(`${e}/next-turn`).set(dmAuth); expect(await seen(dmAuth)).toEqual([]); expect((await target(playerAuth, first.id)).status).toBe(403); // Whoever is on turn can't be a target, their own or as part of a group. expect((await target(dmAuth, first.id)).status).toBe(400); expect((await target(dmAuth, hero.id, first.id)).status).toBe(400); // The goblin's turn: the DM marks the hero, and can clear it again. expect((await target(dmAuth, hero.id)).body.encounter.targetParticipantIds).toEqual([hero.id]); expect((await target(dmAuth)).body.encounter.targetParticipantIds).toEqual([]); }); }); describe('area attack AC penalty', () => { itIfDb('is a campaign setting the DM changes, 2 unless told otherwise', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('areapenalty'); const c = `/campaigns/${campaign.id}`; expect(campaign.areaAttackAcPenalty).toBe(2); expect((await request(app).patch(c).set(playerAuth).send({ areaAttackAcPenalty: 0 })).status).toBe(403); expect((await request(app).patch(c).set(dmAuth).send({ areaAttackAcPenalty: 11 })).status).toBe(400); expect((await request(app).patch(c).set(dmAuth).send({ areaAttackAcPenalty: -1 })).status).toBe(400); expect((await request(app).patch(c).set(dmAuth).send({ areaAttackAcPenalty: 0 })).body.campaign.areaAttackAcPenalty).toBe(0); // Players are told it too: their cards show the penalty on a marked target. expect((await request(app).get(c).set(playerAuth)).body.campaign.areaAttackAcPenalty).toBe(0); }); }); describe('number limits', () => { itIfDb('are enforced by the server, whatever a form sends', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('limits'); const c = `/campaigns/${campaign.id}`; const heroId = await buildCharacter(campaign.id, playerAuth, 'Bounded'); const sheet = (body) => request(app).patch(`/characters/${heroId}`).set(dmAuth).send(body); expect((await sheet({ level: 21 })).status).toBe(400); expect((await sheet({ level: 0 })).status).toBe(400); expect((await sheet({ level: 20 })).status).toBe(200); expect((await sheet({ armorBonus: 31 })).status).toBe(400); expect((await sheet({ tempHp: -1 })).status).toBe(400); expect((await sheet({ tempHp: 10000 })).status).toBe(400); expect((await request(app).patch(c).set(dmAuth).send({ startingGold: -5 })).status).toBe(400); expect((await request(app).patch(c).set(dmAuth).send({ startingItemCount: 51 })).status).toBe(400); expect((await request(app).post(`${c}/monsters`).set(dmAuth).send({ name: 'Wall', ac: 51, maxHp: 10 })).status).toBe(400); expect((await request(app).post(`${c}/monsters`).set(dmAuth).send({ name: 'Ghost', ac: 10, maxHp: 0 })).status).toBe(400); expect((await request(app).post(`${c}/npcs`).set(dmAuth).send({ name: 'Titan', attackBonus: 51 })).status).toBe(400); }); }); describe('temporary hit points', () => { itIfDb('soak damage before real HP, on the sheet and in an encounter; healing leaves them alone', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('temphp'); const heroId = await buildCharacter(campaign.id, playerAuth, 'Shielded'); const ch = `/characters/${heroId}`; const sheet = async () => (await request(app).get(ch).set(playerAuth)).body.character; const max = (await sheet()).sheet.hp.max; expect((await sheet()).currentHp).toBe(max); // On the sheet: 5 temp, 3 damage — all of it soaked. await request(app).patch(ch).set(playerAuth).send({ tempHp: 5 }); let now = (await request(app).patch(ch).set(playerAuth).send({ currentHp: max - 3 })).body.character; expect([now.currentHp, now.tempHp]).toEqual([max, 2]); // More damage than is left: the rest reaches real HP. now = (await request(app).patch(ch).set(playerAuth).send({ currentHp: max - 3 })).body.character; expect([now.currentHp, now.tempHp]).toEqual([max - 1, 0]); // Healing doesn't touch temp HP, and setting temp HP doesn't touch HP. await request(app).patch(ch).set(playerAuth).send({ tempHp: 4 }); now = (await request(app).patch(ch).set(playerAuth).send({ currentHp: max })).body.character; expect([now.currentHp, now.tempHp]).toEqual([max, 4]); // In an encounter the damage lands on the same sheet, the same way. const e = `/encounters/${(await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Arrows' })).body.encounter.id}`; const row = (await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId })).body.participant; const hit = await request(app).patch(`${e}/participants/${row.id}`).set(dmAuth).send({ currentHp: max - 6 }); expect(hit.body.participant.currentHp).toBe(max - 2); now = await sheet(); expect([now.currentHp, now.tempHp]).toEqual([max - 2, 0]); // A blow far past zero still only takes what there is. await request(app).patch(ch).set(playerAuth).send({ tempHp: 2 }); await request(app).patch(`${e}/participants/${row.id}`).set(dmAuth).send({ currentHp: -500 }); now = await sheet(); expect([now.currentHp, now.tempHp]).toEqual([0, 0]); }); }); describe('death saves', () => { itIfDb('start at 0 HP, are settled by three of a kind, and end with healing', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('deathsaves'); const heroId = await buildCharacter(campaign.id, playerAuth, 'Fallen'); const ch = `/characters/${heroId}`; const sheet = async () => (await request(app).get(ch).set(playerAuth)).body.character; const hp = (auth, currentHp) => request(app).patch(ch).set(auth).send({ currentHp }); const save = (auth, body) => request(app).post(`${ch}/death-saves`).set(auth).send(body); const max = (await sheet()).sheet.hp.max; expect((await sheet()).deathSaves).toEqual({ state: 'UP', successes: 0, failures: 0 }); // No saves while standing, and a save is a d20. expect((await save(playerAuth, { action: 'roll', roll: 12 })).status).toBe(400); await hp(playerAuth, 0); expect((await sheet()).deathSaves).toEqual({ state: 'DYING', successes: 0, failures: 0 }); expect((await save(playerAuth, { action: 'roll', roll: 21 })).status).toBe(400); // 10 and up succeeds, below fails, and a 1 fails twice. expect((await save(playerAuth, { action: 'roll', roll: 10 })).body.character.deathSaves).toEqual({ state: 'DYING', successes: 1, failures: 0 }); expect((await save(playerAuth, { action: 'roll', roll: 9 })).body.character.deathSaves).toEqual({ state: 'DYING', successes: 1, failures: 1 }); // Being hit while down is a failed save; healing clears the lot. expect((await hp(dmAuth, -1)).body.character.deathSaves).toEqual({ state: 'DYING', successes: 1, failures: 2 }); expect((await hp(playerAuth, 3)).body.character.deathSaves).toEqual({ state: 'UP', successes: 0, failures: 0 }); // Three successes: stable, at 0 HP, with nothing left to roll. await hp(playerAuth, 0); for (const roll of [15, 11, 19]) await save(playerAuth, { action: 'roll', roll }); let now = await sheet(); expect([now.currentHp, now.deathSaves]).toEqual([0, { state: 'STABLE', successes: 0, failures: 0 }]); expect((await save(playerAuth, { action: 'roll', roll: 12 })).status).toBe(400); // Damage ends that; a 20 puts them back up with 1 HP. expect((await hp(dmAuth, -1)).body.character.deathSaves).toEqual({ state: 'DYING', successes: 0, failures: 1 }); now = (await save(playerAuth, { action: 'roll', roll: 20 })).body.character; expect([now.currentHp, now.deathSaves]).toEqual([1, { state: 'UP', successes: 0, failures: 0 }]); // Someone else can steady them without a roll. await hp(playerAuth, 0); expect((await save(playerAuth, { action: 'stabilize' })).body.character.deathSaves.state).toBe('STABLE'); // The tallies are the DM's to set by hand; a 1 on top of two failures kills. expect((await save(playerAuth, { action: 'set', successes: 0, failures: 0 })).status).toBe(403); expect((await save(dmAuth, { action: 'set', successes: 2, failures: 2 })).body.character.deathSaves).toEqual({ state: 'DYING', successes: 2, failures: 2 }); expect((await save(playerAuth, { action: 'roll', roll: 1 })).body.character.deathSaves.state).toBe('DEAD'); // The dead can't be healed or roll; only the DM brings them back. expect((await hp(playerAuth, max)).status).toBe(400); expect((await save(playerAuth, { action: 'roll', roll: 20 })).status).toBe(400); expect((await save(playerAuth, { action: 'revive' })).status).toBe(403); now = (await save(dmAuth, { action: 'revive' })).body.character; expect([now.currentHp, now.deathSaves]).toEqual([1, { state: 'UP', successes: 0, failures: 0 }]); }); itIfDb('follow the character into an encounter, where one huge blow kills outright', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('deathsaves-enc'); const heroId = await buildCharacter(campaign.id, playerAuth, 'Doomed'); const ch = `/characters/${heroId}`; const max = (await request(app).get(ch).set(playerAuth)).body.character.sheet.hp.max; const e = `/encounters/${(await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Last Stand' })).body.encounter.id}`; const row = (await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId })).body.participant; const strike = (currentHp) => request(app).patch(`${e}/participants/${row.id}`).set(dmAuth).send({ currentHp }); const combatant = async () => (await request(app).get(e).set(playerAuth)).body.encounter.participants[0]; // Temp HP that soaks the whole blow keeps them on their feet. await request(app).patch(ch).set(playerAuth).send({ tempHp: 2 }); await strike(max - 2); expect((await combatant()).characterCombatInfo.deathSaves.state).toBe('UP'); // Dropped by the DM in the tracker; the player's own save shows there. await strike(1 - max); // max - 1 past zero: one short of killing outright expect((await combatant()).characterCombatInfo.deathSaves).toEqual({ state: 'DYING', successes: 0, failures: 0 }); await request(app).post(`${ch}/death-saves`).set(playerAuth).send({ action: 'roll', roll: 4 }); expect((await combatant()).characterCombatInfo.deathSaves).toEqual({ state: 'DYING', successes: 0, failures: 1 }); // The party list carries it too. const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(dmAuth)).body.characters.find((c) => c.id === heroId); expect(listed.deathSaves.state).toBe('DYING'); // Healed, then hit for max HP more than they have left. await strike(max); await strike(-max); const dmView = (await request(app).get(e).set(dmAuth)).body.encounter.participants[0]; expect([dmView.hidden, dmView.characterCombatInfo.deathSaves.state]).toEqual([true, 'DEAD']); expect((await strike(5)).status).toBe(400); }); itIfDb('hide the fallen from players, skip their turns, and let an ally with a reviving spell bring a character back', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('fallen'); const c = `/campaigns/${campaign.id}`; const healerId = await buildCharacter(campaign.id, playerAuth, 'Healer'); const doomedId = await buildCharacter(campaign.id, playerAuth, 'Doomed'); const goblin = (await request(app).post(`${c}/monsters/from-library`).set(dmAuth).send({ key: 'goblin' })).body.monster; const e = `/encounters/${(await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Crypt' })).body.encounter.id}`; const add = async (body) => (await request(app).post(`${e}/participants`).set(dmAuth).send(body)).body.participant.id; const healer = await add({ characterId: healerId, initiativeRoll: 20 }); const doomed = await add({ characterId: doomedId, initiativeRoll: 10 }); const gob = await add({ monsterId: goblin.id, initiativeRoll: 1 }); const setHp = (id, currentHp) => request(app).patch(`${e}/participants/${id}`).set(dmAuth).send({ currentHp }); const view = async (auth) => (await request(app).get(e).set(auth)).body.encounter; const ids = (encounter) => encounter.participants.map((p) => p.id); const revive = (auth, id) => request(app).post(`${e}/participants/${id}/revive`).set(auth); const nextTurn = async () => (await request(app).post(`${e}/next-turn`).set(dmAuth)).body.encounter; await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE' }); // the healer is on turn await request(app).put(`${e}/targets`).set(dmAuth).send({ participantIds: [gob] }); // A monster at 0 HP is gone from the player's list, target mark and all; the DM keeps it. await setHp(gob, 0); let seen = await view(playerAuth); expect([ids(seen), seen.targetParticipantIds, seen.fallen]).toEqual([[healer, doomed], [], []]); seen = await view(dmAuth); expect([ids(seen), seen.targetParticipantIds]).toEqual([[healer, doomed, gob], [gob]]); expect(seen.participants.map((p) => p.hidden)).toEqual([false, false, true]); expect((await request(app).put(`${e}/targets`).set(playerAuth).send({ participantIds: [gob] })).status).toBe(400); // A dying character stays in view; a dead one is hidden, and named among the fallen. await setHp(doomed, 0); expect(ids(await view(playerAuth))).toEqual([healer, doomed]); await request(app).post(`/characters/${doomedId}/death-saves`).set(dmAuth).send({ action: 'set', successes: 0, failures: 3 }); seen = await view(playerAuth); expect([ids(seen), seen.fallen]).toEqual([[healer], [{ participantId: doomed, characterId: doomedId, name: 'Doomed' }]]); // The dead join no other scene until they are revived. const elsewhere = `/encounters/${(await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Elsewhere' })).body.encounter.id}`; const join = () => request(app).post(`${elsewhere}/participants`).set(dmAuth).send({ characterId: doomedId }); expect((await join()).status).toBe(400); // The fallen have no turn: with only the healer standing, the round rolls straight over. seen = await nextTurn(); expect([seen.activeParticipantId, seen.currentRound]).toEqual([healer, 2]); // Reviving takes a spell that brings back the dead, at a level the caster can use. expect(seen.participants[0].characterCombatInfo.canRevive).toBe(false); expect((await revive(playerAuth, doomed)).status).toBe(400); const revivify = (await request(app).post(`${c}/spells/from-library`).set(dmAuth).send({ key: 'revivify' })).body.spell; expect(revivify.revives).toBe(true); await request(app).post(`/characters/${healerId}/spells`).set(dmAuth).send({ spellId: revivify.id }); expect((await revive(playerAuth, doomed)).status).toBe(400); // level 1 can't cast a level 3 spell await request(app).patch(`/characters/${healerId}`).set(dmAuth).send({ level: 3 }); expect((await view(playerAuth)).participants[0].characterCombatInfo.canRevive).toBe(true); expect((await revive(playerAuth, gob)).status).toBe(400); // monsters are healed, not revived const revived = await revive(playerAuth, doomed); expect([revived.status, revived.body.revivedWith]).toEqual([200, 'Revivify']); expect([ids(revived.body.encounter), revived.body.encounter.fallen]).toEqual([[healer, doomed], []]); const back = (await request(app).get(`/characters/${doomedId}`).set(playerAuth)).body.character; expect([back.currentHp, back.deathSaves]).toEqual([1, { state: 'UP', successes: 0, failures: 0 }]); expect((await revive(playerAuth, doomed)).status).toBe(400); // not dead any more expect((await join()).status).toBe(201); // Only on the reviver's own turn, and healing a monster brings it back into view. expect((await nextTurn()).activeParticipantId).toBe(doomed); await setHp(gob, 3); expect(ids(await view(playerAuth))).toEqual([healer, doomed, gob]); expect((await nextTurn()).activeParticipantId).toBe(gob); expect((await revive(playerAuth, doomed)).status).toBe(403); }); }); describe('silver and copper', () => { itIfDb('are kept as separate coins, exchanged at fixed worth, given and rewarded', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('coins'); const c = `/campaigns/${campaign.id}`; await request(app).patch(c).set(dmAuth).send({ startingGold: 5 }); const heroId = await buildCharacter(campaign.id, playerAuth, 'Purse'); const friendId = await buildCharacter(campaign.id, dmAuth, 'Friend'); const ch = `/characters/${heroId}`; const purse = async (id = heroId, auth = playerAuth) => { const { gold, silver, copper } = (await request(app).get(`/characters/${id}`).set(auth)).body.character; return [gold, silver, copper]; }; const money = (body) => request(app).post(`${ch}/gold`).set(playerAuth).send(body); const exchange = (body) => request(app).post(`${ch}/gold/exchange`).set(playerAuth).send(body); expect(await purse()).toEqual([5, 0, 0]); // Each coin has its own balance; an amount with no coin named is gold. expect((await money({ amount: 7, currency: 'SILVER', reason: 'Sold a pelt' })).status).toBe(201); expect((await money({ amount: 3, currency: 'COPPER' })).body.copper).toBe(3); expect((await money({ amount: 1 })).body.gold).toBe(6); expect(await purse()).toEqual([6, 7, 3]); expect((await money({ amount: 1, currency: 'PLATINUM' })).status).toBe(400); // A spend the whole purse can't cover is refused and moves nothing. const short = await money({ amount: -1000, currency: 'SILVER' }); expect(short.status).toBe(400); expect(short.body.error).toMatch(/Not enough money/); expect(await purse()).toEqual([6, 7, 3]); expect((await request(app).patch(ch).set(dmAuth).send({ silver: 99 })).status).toBe(400); // 1 gold = 10 silver = 100 copper. expect((await exchange({ from: 'GOLD', to: 'SILVER', amount: 1 })).body.received).toBe(10); expect(await purse()).toEqual([5, 17, 3]); expect((await exchange({ from: 'GOLD', to: 'COPPER', amount: 1 })).body.received).toBe(100); expect((await exchange({ from: 'SILVER', to: 'COPPER', amount: 1 })).body.received).toBe(10); expect(await purse()).toEqual([4, 16, 113]); expect((await exchange({ from: 'COPPER', to: 'SILVER', amount: 20 })).body.received).toBe(2); expect((await exchange({ from: 'SILVER', to: 'GOLD', amount: 10 })).body.received).toBe(1); expect((await exchange({ from: 'COPPER', to: 'SILVER', amount: 90 })).body.received).toBe(9); expect(await purse()).toEqual([5, 17, 3]); // It has to come to whole coins, be affordable, and be between two different coins. const uneven = await exchange({ from: 'SILVER', to: 'GOLD', amount: 5 }); expect(uneven.status).toBe(400); expect(uneven.body.error).toMatch(/multiples of 10/); expect((await exchange({ from: 'COPPER', to: 'SILVER', amount: 1 })).status).toBe(400); expect((await exchange({ from: 'COPPER', to: 'GOLD', amount: 50 })).body.error).toMatch(/multiples of 100/); expect((await exchange({ from: 'SILVER', to: 'COPPER', amount: 18 })).status).toBe(400); expect((await exchange({ from: 'GOLD', to: 'GOLD', amount: 1 })).status).toBe(400); expect((await request(app).post(`/characters/${friendId}/gold/exchange`).set(playerAuth).send({ from: 'GOLD', to: 'SILVER', amount: 1 })).status).toBe(403); expect(await purse()).toEqual([5, 17, 3]); // The ledger says which coin every entry is in. const ledger = (await request(app).get(`${ch}/gold`).set(playerAuth)).body; expect([ledger.gold, ledger.silver, ledger.copper]).toEqual([5, 17, 3]); expect(ledger.transactions[0]).toMatchObject({ currency: 'SILVER', amount: 9, balanceAfter: 17, reason: 'Exchanged from 90 copper' }); expect(ledger.transactions.find((t) => t.reason === 'Sold a pelt')).toMatchObject({ currency: 'SILVER', amount: 7, balanceAfter: 7 }); // Giving and rewards work per coin. expect((await request(app).post(`${ch}/give`).set(playerAuth).send({ kind: 'gold', currency: 'SILVER', amount: 3, toCharacterId: friendId })).status).toBe(200); expect((await request(app).post(`${ch}/give`).set(playerAuth).send({ kind: 'gold', currency: 'COPPER', amount: 5000, toCharacterId: friendId })).status).toBe(400); expect(await purse()).toEqual([5, 14, 3]); expect(await purse(friendId, dmAuth)).toEqual([5, 3, 0]); const e = `/encounters/${(await request(app).post(`${c}/encounters`).set(dmAuth).send({ name: 'Loose change' })).body.encounter.id}`; await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId }); await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: friendId }); const reward = (await request(app).post(`${e}/rewards`).set(dmAuth).send({ type: 'GOLD', gold: 9, currency: 'COPPER' })).body.reward; expect(reward).toMatchObject({ gold: 9, currency: 'COPPER' }); await request(app).post(`${e}/rewards/${reward.id}/award`).set(dmAuth).send({ split: true }); const split = [(await purse())[2] - 3, (await purse(friendId, dmAuth))[2]].sort(); expect(split).toEqual([4, 5]); // 9 copper between two // Another player still sees none of it. const outsiderView = (await request(app).get(`/characters/${friendId}`).set(playerAuth)).body.character; expect([outsiderView.gold, outsiderView.silver, outsiderView.copper]).toEqual([null, null, null]); }); }); describe('paying with change', () => { itIfDb('a spend or a gift is paid from the whole purse: bigger coins are broken, smaller ones counted out', async () => { const { dmAuth, playerAuth, campaign } = await setupCampaign('change'); await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ startingGold: 5 }); const heroId = await buildCharacter(campaign.id, playerAuth, 'Spender'); const friendId = await buildCharacter(campaign.id, dmAuth, 'Friend'); const ch = `/characters/${heroId}`; const purse = async (id = heroId, auth = playerAuth) => { const { gold, silver, copper } = (await request(app).get(`/characters/${id}`).set(auth)).body.character; return [gold, silver, copper]; }; const money = (body) => request(app).post(`${ch}/gold`).set(playerAuth).send(body); const newest = async (count) => (await request(app).get(`${ch}/gold`).set(playerAuth)).body.transactions.slice(0, count).map((t) => [t.currency, t.amount, t.balanceAfter, t.reason]); // 3 silver from a purse of 5 gold: one gold is broken, 7 silver comes back. const boots = await money({ amount: -3, currency: 'SILVER', reason: 'New boots' }); expect(boots.status).toBe(201); expect([boots.body.gold, boots.body.silver, boots.body.copper]).toEqual([4, 7, 0]); expect(await purse()).toEqual([4, 7, 0]); expect((await newest(2)).sort()).toEqual([ ['GOLD', -1, 4, 'New boots (paid 3 silver, with change)'], ['SILVER', 7, 7, 'New boots (paid 3 silver, with change)'], ]); // 5 copper: the nearest bigger coin is a silver, so that is what breaks. expect((await money({ amount: -5, currency: 'COPPER' })).status).toBe(201); expect(await purse()).toEqual([4, 6, 5]); // Enough of the coin named: nothing else moves, and the entry reads as usual. await money({ amount: -2, reason: 'Horse feed' }); expect(await purse()).toEqual([2, 6, 5]); expect((await newest(1))[0]).toEqual(['GOLD', -2, 2, 'Horse feed']); // More than the whole purse is worth (2.65 gold): refused, nothing moves. const tooMuch = await money({ amount: -3 }); expect(tooMuch.status).toBe(400); expect(tooMuch.body.error).toMatch(/Not enough money/); expect(tooMuch.body.error).toMatch(/2\.65 gold/); expect(await purse()).toEqual([2, 6, 5]); // No bigger coin to break: smaller ones are counted out, biggest first. await money({ amount: -2 }); await money({ amount: 40, currency: 'COPPER' }); expect(await purse()).toEqual([0, 6, 45]); expect((await money({ amount: -1, reason: 'Toll' })).status).toBe(201); expect(await purse()).toEqual([0, 0, 5]); // Giving works the same way for the giver; the recipient gets the coins named. await money({ amount: 1 }); expect((await request(app).post(`${ch}/give`).set(playerAuth).send({ kind: 'gold', currency: 'SILVER', amount: 4, toCharacterId: friendId })).status).toBe(200); expect(await purse()).toEqual([0, 6, 5]); expect(await purse(friendId, dmAuth)).toEqual([5, 4, 0]); const beyond = await request(app).post(`${ch}/give`).set(playerAuth).send({ kind: 'gold', amount: 1, toCharacterId: friendId }); expect(beyond.status).toBe(400); expect(beyond.body.error).toMatch(/Not enough money/); // Exchanging is the exception: it moves exactly the coins named. expect((await request(app).post(`${ch}/gold/exchange`).set(playerAuth).send({ from: 'SILVER', to: 'COPPER', amount: 7 })).status).toBe(400); expect(await purse()).toEqual([0, 6, 5]); }); });