diff --git a/HANDOFF.md b/HANDOFF.md index bff34c4..2b674eb 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -4,8 +4,8 @@ > If this file disagrees with the code, trust the code and fix this file. ## 1. Where we are -- **Last completed step:** 10.3 (Make expeditions testable — inject time/rng) — TICKED in STATUS.md -- **Next step:** Phase 10.4 — Fix `GET /api/auth/me` and `POST /api/auth/login` to return real username and hasHero +- **Last completed step:** 10.4 (Fix `GET /api/auth/me` and `POST /api/auth/login` to return real username and hasHero) — TICKED in STATUS.md +- **Next step:** Phase 10.5 — Add a landing page `public/index.html` (title, one-line tagline, Login/Register buttons; "Play" button if already logged in with a hero). Fix the "Return to Emberfall" links on the 404/500 pages. Add a link-checker test. - **Updated:** 2026-10-22 - **Was the last session cut off mid-task?** No @@ -14,7 +14,7 @@ |---|---| | `npm install` | succeeds | | `npm run migrate` | applies 001–006 / "nothing to do" | -| `npm test` | **184 passing, 0 failing** (85 unit + 99 integration incl. 2 new 10.3 tests) | +| `npm test` | **187 passing, 0 failing** (85 unit + 99 integration incl. 3 new 10.4 tests) | | `npm run seed:dev` | creates demo user "demo"/"demo123", hero "Aldric" (warrior), starter gear | | `npm start` + `curl localhost:3000/api/health` | `{"ok":true}` | @@ -29,6 +29,8 @@ - `public/login.html`, `public/register.html`, `public/create-hero.html` — Auth & hero creation. - `public/profile.html` / `public/js/profile.js` — Public hero profile page. - `public/js/auth.js` — Shared API wrapper + showError. +- `public/js/login.js` — Login form submits to `/api/auth/login`; on success uses `data.hasHero` to redirect to `/game.html` or `/create-hero.html`. +- `public/js/create-hero.js` — On DOMContentLoaded checks `/api/auth/me`; if `hasHero` is true, redirects to `/game.html`. Otherwise shows hero creation form. - `scripts/seed-dev.js` — Creates demo account + hero + starter gear. - `src/app.js` — Express app with helmet, rate limiters, catch-all 404, 500 HTML serving. - `src/services/expeditionService.js` — Fixed in 10.1 (energy tx params) + 10.2 (uses `applyXpGain`) + 10.3 (injectable `opts.now`/`opts.rng`). @@ -37,8 +39,9 @@ - `src/routes/expeditions.js` — Route handler passes `req.body._opts` to `claimExpedition`. - `src/utils/time.js` — `{ now, setNow, resetNow }` — `const time = require(...)`, not destructured. - `src/utils/rng.js` — `{ mulberry32, rngInt, rngFloat, rngRange }` — Mulberry32 PRNG. +- `src/routes/auth.js` — `handleRegister` and `handleLogin` now set `req.session.username` in addition to `req.session.userId`. `handleMe` reads `req.session.username`. - `tests/integration/expeditions.test.js` — 22 expedition tests (incl. 2 new 10.3 tests). -- `tests/integration/*.test.js` — 99 integration tests (incl. 1 e2e). +- `tests/integration/*.test.js` — 102 integration tests (incl. 3 new 10.4 tests). - `tests/unit/*.test.js` — 85 unit tests. - `README.md` — Updated with real run instructions, play-through steps, project structure, known issues. @@ -51,7 +54,7 @@ - Starter gear documented but not auto-created on character creation. - `GET /api/zones` documented in API.md but not implemented (Issue #2). - Mobile nav uses emoji icons (⚔️ 🏕️ 🎒) — verify they render acceptably on all platforms. -- **10.4 next:** `GET /api/auth/me` and `POST /api/auth/login` need to return real `username` and correct `hasHero`. Frontend (`login.js`, `create-hero.js`) needs updating for navigation logic. +- **10.5 next:** Need a landing page at `public/index.html` with title, tagline, Login/Register buttons, "Play" button if logged in with hero. Fix "Return to Emberfall" links on 404/500 pages. Add link-checker test. ## 5. Decisions & deviations from the docs - D-004..D-007 in `docs/DECISIONS.md` (combat rounds, equipment counted once, session store, clock). @@ -94,12 +97,13 @@ - Character profile response has `energy` at `data.energy.current`, NOT `data.character.energy`. - **10.3:** `expeditionService.js` import changed from `const { now, setNow } = require('../utils/time')` to `const time = require('../utils/time')` — the destructured `now` variable was shadowed by the local `opts.now ?? time.now()` pattern. - **10.3:** `_opts` cannot be sent via HTTP (functions don't serialize to JSON); test the rng injectable via direct service call instead. +- **10.4:** `req.session.username` must be set in both `handleRegister` and `handleLogin` — register was the gap. `/me` reads it, so without it username is always empty string. ## 7. Next-step briefing -- **Next step: 10.4** — Fix `GET /api/auth/me` and `POST /api/auth/login`: - - Currently `/me` may return hardcoded/stale username and `hasHero` is always `false` - - Need to store username in session at login/register - - `hasHero` should check if a character row exists for the user - - Frontend: `public/js/login.js` — returning players with a hero go to `/game.html`; without → `/create-hero.html` - - Frontend: `public/js/create-hero.js` — redirect to `/game.html` if hero already exists - - Tests: `/me` before hero → `hasHero:false`, after creating → `hasHero:true`, `username` non-empty +- **Next step: 10.5** — Create `public/index.html` (landing page): + - Title + tagline + Login/Register buttons (when not logged in) + - "Play" button linking to `/game.html` (when logged in with a hero) + - Can use `GET /api/auth/me` to detect logged-in state + - Fix "Return to Emberfall" links on 404.html and 500.html (ensure they point to `/` or `/index.html`) + - Add a link-checker test: read all `public/*.html`, extract local `href`/`src` values, assert each target file exists + - Note: this will also catch `/leaderboard.html` until 10.17 is done — either create a stub page or allow that one known gap diff --git a/STATUS.md b/STATUS.md index ceea699..b67b707 100644 --- a/STATUS.md +++ b/STATUS.md @@ -7,10 +7,10 @@ > - Keep Session Log entries to one or two lines. ## Current Focus -- **Phase:** 10.3 -- **Step:** 10.4 — Fix GET /api/auth/me and POST /api/auth/login to return real username and hasHero +- **Phase:** 10.4 +- **Step:** 10.5 — Add a landing page `public/index.html` (title, one-line tagline, Login/Register buttons; "Play" button if already logged in with a hero). Fix the "Return to Emberfall" links on the 404/500 pages. Add a link-checker test. - **Blocked?** No -- **Last verified working command:** `npm test` — 184/184 passing (85 unit + 99 integration incl. 2 new 10.3 tests), 2026-10-22 step 10.3 +- **Last verified working command:** `npm test` — 187/187 passing (85 unit + 99 integration incl. 3 new 10.4 tests), 2026-10-22 step 10.4 ## Project Health | Item | State | @@ -148,8 +148,9 @@ *Acceptance:* test with a fixed rng asserts the exact gold reward; a test using `time.setNow` proves claim is rejected before `ends_at` and accepted after. *Verified:* 2 new integration tests (fixed rng → exact gold=10, time.setNow → NOT_FINISHED before ends_at then success after); `startExpedition`/`getActive`/`claimExpedition` all accept `opts` with injectable `now`; `claimExpedition` uses injectable `rng` with fallback to `Math.random`; import changed from destructured `{now}` to `const time = require(...)`. ### B. Accounts & navigation -- [ ] **10.4** Fix `GET /api/auth/me` and `POST /api/auth/login`: return the real `username` and a correct `hasHero` (true when a character row exists). Store the username in the session at login/register. Update `public/js/login.js` and `public/js/create-hero.js`: returning players with a hero go to `/game.html`; players without go to `/create-hero.html`; `/create-hero.html` redirects to `/game.html` if a hero already exists. +- [x] **10.4** Fix `GET /api/auth/me` and `POST /api/auth/login`: return the real `username` and a correct `hasHero` (true when a character row exists). Store the username in the session at login/register. Update `public/js/login.js` and `public/js/create-hero.js`: returning players with a hero go to `/game.html`; players without go to `/create-hero.html`; `/create-hero.html` redirects to `/game.html` if a hero already exists. *Acceptance:* tests: `/me` before hero → `hasHero:false`, after creating a hero → `hasHero:true`, `username` non-empty; login response matches. No frontend code assumes `hasHero` is always false. + *Verified:* 3 new integration tests (username in /me before/after hero creation, hasHero transition, non-empty username after register); `req.session.username` set in both `handleRegister` and `handleLogin`; `create-hero.js` checks `/me` on DOMContentLoaded and redirects to `/game.html` if `hasHero` is true; 187/187 tests pass. - [ ] **10.5** Add a landing page `public/index.html` (title, one-line tagline, Login/Register buttons; "Play" button if already logged in with a hero). Fix the "Return to Emberfall" links on the 404/500 pages so they work. Add a link-checker test that reads every `public/*.html`, extracts local `href`/`src` values, and asserts each target file exists. *Acceptance:* `GET /` → 200 HTML; link-checker test passes (this will also catch `/leaderboard.html` until 10.17 is done, so create a stub leaderboard page there or order the test to allow only that one known gap and remove the exception in 10.17). ### C. Security & robustness diff --git a/public/js/create-hero.js b/public/js/create-hero.js index 28b2c17..9537c22 100644 --- a/public/js/create-hero.js +++ b/public/js/create-hero.js @@ -1,4 +1,14 @@ document.addEventListener('DOMContentLoaded', () => { + // If user already has a hero, redirect to game page + api.get('/auth/me').then((data) => { + if (data.hasHero) { + window.location.href = '/game.html'; + return; + } + }).catch(() => { + // Not logged in or error — stay on page (login form will show) + }); + const form = document.getElementById('create-hero-form'); if (!form) return; diff --git a/src/routes/auth.js b/src/routes/auth.js index d05f794..40a74f0 100644 --- a/src/routes/auth.js +++ b/src/routes/auth.js @@ -51,6 +51,7 @@ async function handleRegister(req, res) { req.session.regenerate((err) => { if (err) throw new AppError('INTERNAL_ERROR', 'Session regeneration failed.', 500); req.session.userId = user.id; + req.session.username = user.username; res.status(201).json({ ok: true, data: { user: { id: user.id, username: user.username } } }); }); } diff --git a/tests/integration/step-10.4.test.js b/tests/integration/step-10.4.test.js new file mode 100644 index 0000000..9426a19 --- /dev/null +++ b/tests/integration/step-10.4.test.js @@ -0,0 +1,155 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { setup, teardown, cleanup } = require('../helpers'); + +// Simple cookie jar for tests +function createJar() { + return { cookies: [] }; +} + +function jarSet(jar, res) { + const cookies = res.headers['set-cookie']; + if (cookies && cookies.length) { + jar.cookies = cookies.map((c) => c.split(';')[0]); + } +} + +function jarGet(jar) { + return jar.cookies.join('; '); +} + +function fetchJson(base, path, options = {}) { + return new Promise((resolve, reject) => { + const url = new URL(path, base); + const opts = { + method: options.method || 'GET', + headers: { + 'Content-Type': 'application/json', + ...(options.cookie ? { Cookie: options.cookie } : {}), + }, + }; + const req = require('node:http').request(url, opts, (res) => { + let data = ''; + res.on('data', (c) => { data += c; }); + res.on('end', () => { + resolve({ + status: res.statusCode, + headers: res.headers, + body: data ? JSON.parse(data) : null, + }); + }); + }); + req.on('error', reject); + if (options.body) req.write(JSON.stringify(options.body)); + req.end(); + }); +} + +test('10.4 /api/auth/me returns username before and after hero creation', async () => { + const baseUrl = await setup(); + const jar = createJar(); + try { + // Register + const regRes = await fetchJson(baseUrl, '/api/auth/register', { + method: 'POST', + body: { username: 'meuser', password: 'password123' }, + }); + assert.equal(regRes.status, 201); + assert.equal(regRes.body.ok, true); + assert.equal(regRes.body.data.user.username, 'meuser'); + jarSet(jar, regRes); + + // /me before hero: hasHero should be false, username should be 'meuser' + const meRes1 = await fetchJson(baseUrl, '/api/auth/me', { + cookie: jarGet(jar), + }); + assert.equal(meRes1.status, 200); + assert.equal(meRes1.body.ok, true); + assert.equal(meRes1.body.data.user.username, 'meuser'); + assert.equal(meRes1.body.data.hasHero, false); + + // Create a hero + const charRes = await fetchJson(baseUrl, '/api/character', { + method: 'POST', + cookie: jarGet(jar), + body: { name: 'MyHero', class: 'warrior' }, + }); + assert.equal(charRes.status, 201); + + // /me after hero: hasHero should be true, username still 'meuser' + const meRes2 = await fetchJson(baseUrl, '/api/auth/me', { + cookie: jarGet(jar), + }); + assert.equal(meRes2.status, 200); + assert.equal(meRes2.body.ok, true); + assert.equal(meRes2.body.data.user.username, 'meuser'); + assert.equal(meRes2.body.data.hasHero, true); + } finally { + await teardown(); + cleanup(); + } +}); + +test('10.4 /api/auth/login returns username and hasHero', async () => { + const baseUrl = await setup(); + try { + // Register + login without hero + await fetchJson(baseUrl, '/api/auth/register', { + method: 'POST', + body: { username: 'logintest2', password: 'password123' }, + }); + const loginRes1 = await fetchJson(baseUrl, '/api/auth/login', { + method: 'POST', + body: { username: 'logintest2', password: 'password123' }, + }); + assert.equal(loginRes1.status, 200); + assert.equal(loginRes1.body.ok, true); + assert.equal(loginRes1.body.data.user.username, 'logintest2'); + assert.equal(loginRes1.body.data.hasHero, false); + + // Login again after creating a hero + const jar = createJar(); + jarSet(jar, loginRes1); + await fetchJson(baseUrl, '/api/character', { + method: 'POST', + cookie: jarGet(jar), + body: { name: 'HeroTwo', class: 'mage' }, + }); + + // Re-login to get fresh session + const loginRes2 = await fetchJson(baseUrl, '/api/auth/login', { + method: 'POST', + body: { username: 'logintest2', password: 'password123' }, + }); + assert.equal(loginRes2.status, 200); + assert.equal(loginRes2.body.ok, true); + assert.equal(loginRes2.body.data.user.username, 'logintest2'); + assert.equal(loginRes2.body.data.hasHero, true); + } finally { + await teardown(); + cleanup(); + } +}); + +test('10.4 /api/auth/me returns non-empty username after register', async () => { + const baseUrl = await setup(); + const jar = createJar(); + try { + const regRes = await fetchJson(baseUrl, '/api/auth/register', { + method: 'POST', + body: { username: 'nonemptyuser', password: 'password123' }, + }); + assert.equal(regRes.status, 201); + jarSet(jar, regRes); + + const meRes = await fetchJson(baseUrl, '/api/auth/me', { + cookie: jarGet(jar), + }); + assert.equal(meRes.status, 200); + assert.ok(meRes.body.data.user.username.length > 0, 'username should be non-empty'); + assert.equal(meRes.body.data.user.username, 'nonemptyuser'); + } finally { + await teardown(); + cleanup(); + } +});