refactor(server): split public, player and residual auth into capability routers (PR 5)
All checks were successful
PR Checks / bot-install (pull_request) Successful in 17s
PR Checks / client-build (pull_request) Successful in 25s
PR Checks / server-tests (pull_request) Successful in 9m20s

The last split PR of docs/website/API_V2_PLAN.md § Phase 2. public.routes.js,
player.routes.js and auth.routes.js are deleted; each group is now a directory
whose index.js owns the group gate and the mount table and declares no routes.
Every one of the 200 manifest routes is now in a capability router.

  public/  posts (2) wiki (4) pages (2) shard (12) site (4, group root)
  player/  account (8) shard (8) appeals (4), behind noindex + requireAuth
  auth/    login (2) register (1) invite (2) password (3) session (2, root)

No URL moves. All four gates zero-diff: routes.manifest.json (200 public + 2
internal), routes.guards.json, swagger-output.json (198 operations), and
docs/website/api-route-inventory.json was already in sync. 434 tests green.

Notes on the non-mechanical parts:

- public/index.js and auth/index.js carry no group gate, deliberately, and say
  so. The public surface is anonymous by contract (logged-out SPA, Discord bot,
  Android ShardStreamClient on /public/shard/stream); /auth is where a caller
  becomes authenticated. player/index.js gates on requireAuth only, never
  requireRole('player') — staff are a superset of players.
- GET /auth/me has a mount-order dependency: use('/me', meRouter) matches the
  bare /me, so the request runs meRouter's noindex + requireAuth and falls
  through. session.router.js must stay mounted last. Verified by the
  counterfactual — mounting it first still 401s but drops X-Robots-Tag, which
  no manifest or guards file can see.
- loginGuards moved to auth/loginGuards.js (frozen) rather than being copied
  into the three routers that spread it; sso.routes.js drops its duplicate.
- The :param shadowing check was re-run in dispatch order against the built
  stack: 86 routes, 64 literal, none shadowed. /public/wiki/{categories,tags}
  ahead of /:slug is the only ordering-sensitive pair.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-07-27 20:52:14 -05:00
parent 3fcc64ab96
commit 565a7d2c20
30 changed files with 1126 additions and 775 deletions

View File

@@ -1,214 +0,0 @@
const express = require('express')
const { body, param } = require('express-validator')
const { login, register, loginTotp, logout, me, HONEYPOT_FIELD } = require('./auth.controller')
const { getInvite, acceptInvite } = require('./invite.controller')
const { requestReset, lookupReset, confirmReset } = require('./passwordReset.controller')
const { isLoggedIn } = require('../../../utils/auth')
const { attachSession } = require('../../../auth/session.middleware')
const {
loginLimiter,
registerLimiter,
passwordResetRequestLimiter,
passwordResetConfirmLimiter,
} = require('../../../middleware/rateLimit')
const { slowLogin, backoffGuard } = require('../../../middleware/loginProtection')
const validate = require('../../../middleware/validate')
const mobileRouter = require('./mobile.routes')
const ssoRouter = require('./sso.routes')
const meRouter = require('./me.routes')
const notifRouter = require('./notifications.routes')
const authRouter = express.Router()
// Native/Android bearer-token auth. Additive alongside the web cookie flow below.
authRouter.use('/mobile', mobileRouter)
// SSO discovery + OAuth redirect flow (/auth/providers, /auth/sso/:provider/*).
// Additive; the web cookie + TOTP flow below is unchanged.
authRouter.use(ssoRouter)
// Role-agnostic self-service ("me") — /auth/me/account*, reusing the same
// account.controller handlers as /player/account/* and /admin/account/* behind
// requireAuth (any role). Additive; gives the app one self surface that never
// touches /admin. The bare GET /me below is unaffected (meRouter has no /account-
// free route, so /me falls through to its own handler).
authRouter.use('/me', meRouter)
// Push-notification self-service — /auth/me/devices*, /auth/me/notifications/*.
// A second sub-router at /me (Express allows multiple), same requireAuth gate,
// keeping the notification surface separate from the account/identity handlers.
authRouter.use('/me', notifRouter)
// Login protection order (cheapest rejection first):
// backoffGuard → per-IP exponential lockout on repeated failures
// slowLogin → progressive per-request delay within the window
// loginLimiter → hard 10-per-15-min cap
const loginGuards = [backoffGuard, slowLogin, loginLimiter]
authRouter.post(
'/login',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Log in with username and password'
// #swagger.description = 'On success sets the httpOnly session cookie. If the account has 2FA enabled, returns { totpRequired, challenge } instead and no cookie is set — complete login at POST /login/totp. Rate limited and behind bot/backoff guards.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/LoginRequest" } } } } */
/* #swagger.responses[200] = { description: 'Session issued, or TOTP challenge required', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[401] = { description: 'Incorrect username or password', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
body('username').isString().trim().notEmpty(),
body('password').isString().notEmpty(),
// Honeypot must be absent/empty for humans; bots that fill it are caught in
// the controller. Accept-but-ignore here so a filled value still reaches it.
body(HONEYPOT_FIELD).optional(),
validate,
login,
)
// Public self-registration (player accounts). Gated in the controller by the
// player_registration setting; here it reuses the login backoff/limiter stack
// plus its own per-IP cap, and accepts the honeypot field.
authRouter.post(
'/register',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Register a player account'
// #swagger.description = 'Creates a self-service player account and logs it in (sets the session cookie). Available only when an admin has enabled password registration (player_registration = password|both); otherwise returns 403. Rate limited and behind bot/backoff guards; a hidden honeypot field must stay empty.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/RegisterRequest" } } } } */
/* #swagger.responses[200] = { description: 'Account created and session issued', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error or unavailable username', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[403] = { description: 'Registration is not open', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'Username already taken', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
registerLimiter,
body('username').isString().trim().isLength({ min: 3, max: 32 }),
body('password').isString().isLength({ min: 8, max: 64 }),
body('email').optional({ values: 'falsy' }).isEmail().isLength({ max: 255 }),
body(HONEYPOT_FIELD).optional(),
validate,
register,
)
// Second factor: same throttling, since it's a code-guessing surface too.
authRouter.post(
'/login/totp',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Complete login with a TOTP or recovery code'
// #swagger.description = 'Second step for 2FA accounts. Exchange the challenge from /login plus either the current authenticator code OR a single-use recovery code for a session cookie. Set trustDevice to remember this browser and skip TOTP on future logins (30 days); if the trusted-device limit is reached the session is still issued and the response carries { trustLimitReached, devices } so the user can revoke one first.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpLoginRequest" } } } } */
/* #swagger.responses[200] = { description: 'Session issued (optionally with a trusted-device-limit prompt)', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[401] = { description: 'Invalid code or expired challenge', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
body('challenge').isString().notEmpty(),
// Either a TOTP code or a recovery code satisfies the second factor; the
// controller rejects the request when neither verifies.
body('code').optional({ values: 'falsy' }).isString().trim().isLength({ min: 6, max: 8 }),
body('recoveryCode').optional({ values: 'falsy' }).isString().trim().isLength({ min: 8, max: 32 }),
body('trustDevice').optional().isBoolean(),
body('deviceName').optional({ values: 'falsy' }).isString().trim().isLength({ max: 100 }),
validate,
loginTotp,
)
// ── Email-invite acceptance (public, token-gated) ──────────────────────────
authRouter.get(
'/invite/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Look up an email invite by token'
// #swagger.description = 'Returns the pre-assigned email + role for a valid, pending, unexpired invite so the accept form can render. 404 for anything not currently acceptable.'
/* #swagger.responses[200] = { description: 'Invite details', content: { "application/json": { schema: { type: "object", properties: { email: { type: "string" }, role: { type: "string" } } } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired invite', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('token').isString().isLength({ min: 8, max: 128 }),
validate,
getInvite,
)
authRouter.post(
'/invite/:token/accept',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Accept an email invite (creates the account at the invited role)'
// #swagger.description = 'Creates the website user at the invites pre-assigned role and logs them in (sets the session cookie). Bypasses the player_registration gate — the invite is its own authority. Rate limited + honeypot-guarded like registration.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["username","password"], properties: { username: { type: "string" }, password: { type: "string" } } } } } */
/* #swagger.responses[200] = { description: 'Account created and session issued', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired invite', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'Username taken or invite already used', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
registerLimiter,
param('token').isString().isLength({ min: 8, max: 128 }),
body('username').isString().trim().isLength({ min: 3, max: 32 }),
body('password').isString().isLength({ min: 8, max: 64 }),
body(HONEYPOT_FIELD).optional(),
validate,
acceptInvite,
)
// ── Self-service password reset (public, token-gated) ──────────────────────
// Request → email a tokened link; then validate the link and set a new password.
// The request step never reveals whether an email exists (always 200, generic).
authRouter.post(
'/password/forgot',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Request a password-reset link by email'
// #swagger.description = 'Emails a single-use, ~1h reset link to every active account on the address. Always returns the same generic 200 whether or not the email matches (no account enumeration). Email is non-unique, so multiple accounts may each receive a link naming their username. Rate limited per IP.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["email"], properties: { email: { type: "string", format: "email" } } } } } } */
/* #swagger.responses[200] = { description: 'Generic acknowledgement (sent if the account exists)', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[429] = { description: 'Too many requests', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
passwordResetRequestLimiter,
body('email').isString().trim().isEmail().isLength({ max: 255 }),
validate,
requestReset,
)
authRouter.get(
'/password/reset/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Validate a password-reset link'
// #swagger.description = 'Returns the target username for a valid, pending, unexpired reset link so the reset form can render. 404 for anything not currently usable (never distinguishes expired from used from never-existed).'
/* #swagger.responses[200] = { description: 'Reset link is valid', content: { "application/json": { schema: { type: "object", properties: { username: { type: "string" } } } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired reset link', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('token').isString().isLength({ min: 8, max: 128 }),
validate,
lookupReset,
)
authRouter.post(
'/password/reset/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Set a new password from a reset link'
// #swagger.description = 'Consumes the single-use link and sets the new password. Rotates the hash and revokes every existing session (web + mobile). Does NOT sign the user in — they log in fresh afterwards (so a 2FA account still passes TOTP). Rate limited per IP.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["password"], properties: { password: { type: "string", minLength: 8, maxLength: 64 } } } } } } */
/* #swagger.responses[200] = { description: 'Password changed', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[404] = { description: 'Invalid, expired, or already-used reset link', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
passwordResetConfirmLimiter,
param('token').isString().isLength({ min: 8, max: 128 }),
body('password').isString().isLength({ min: 8, max: 64 }),
validate,
confirmReset,
)
authRouter.post(
'/logout',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Log out (clear the cookie and revoke this session)'
/* #swagger.responses[200] = { description: 'Logged out', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
// Best-effort attach (never rejects) so the controller can revoke this session's
// jti — logout stays a no-op for an already-anonymous caller.
attachSession,
logout,
)
authRouter.get(
'/me',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Current authenticated user'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The signed-in user', content: { "application/json": { schema: { type: "object", properties: { user: { $ref: "#/components/schemas/User" } } } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
isLoggedIn,
me,
)
module.exports = authRouter

View File

@@ -0,0 +1,67 @@
// /api/v1/auth — the authentication surface, assembled from per-capability
// routers.
//
// This file owns the mount table and nothing else; no route is declared here.
// Each capability router mounts at the prefix it already owned inside the old
// monolithic auth.routes.js, so the emitted URL set is byte-identical — proved by
// a zero-line diff in server/routes.manifest.json (`npm run routes:manifest`).
//
// **There is deliberately no group gate.** /auth is where an anonymous caller
// becomes authenticated, so most of it must stay reachable logged-out. The
// authenticated parts gate themselves: meRouter and notifRouter each apply
// `noindex, requireAuth` at their own router level, and /sso/:provider/link
// carries requireAuth per route.
//
// **Mount order is load-bearing** — see the two notes inline below.
//
// See docs/website/API_V2_PLAN.md § Phase 2 for the split.
const express = require('express')
const mobileRouter = require('./mobile.routes')
const ssoRouter = require('./sso.routes')
const meRouter = require('./me.routes')
const notifRouter = require('./notifications.routes')
const loginRouter = require('./login.router')
const registerRouter = require('./register.router')
const inviteRouter = require('./invite.router')
const passwordRouter = require('./password.router')
const sessionRouter = require('./session.router')
const authRouter = express.Router()
// Native/Android bearer-token auth. Additive alongside the web cookie flow below.
authRouter.use('/mobile', mobileRouter)
// SSO discovery + OAuth redirect flow. Mounted **pathless** because it owns two
// prefixes (/auth/providers and /auth/sso/*); it declares no router-level
// middleware, so passing through it is a no-op for every other route.
authRouter.use(ssoRouter)
// Role-agnostic self-service ("me") — /auth/me/account*, reusing the same
// account.controller handlers as /player/account/* and /admin/account/* behind
// requireAuth (any role). Additive; gives the app one self surface that never
// touches /admin.
authRouter.use('/me', meRouter)
// Push-notification self-service — /auth/me/devices*, /auth/me/notifications/*.
// A second sub-router at /me (Express allows multiple), same requireAuth gate,
// keeping the notification surface separate from the account/identity handlers.
authRouter.use('/me', notifRouter)
// Credential surfaces, each at the prefix it owns.
authRouter.use('/login', loginRouter)
authRouter.use('/register', registerRouter)
authRouter.use('/invite', inviteRouter)
authRouter.use('/password', passwordRouter)
// The two singletons that own no path segment of their own: POST /logout and
// GET /me. Mounted at the group root and **last**, because `use('/me', …)` above
// matches the bare path /me too: GET /auth/me runs meRouter's and notifRouter's
// `noindex, requireAuth`, matches no route inside either, and falls through to
// here. Mounting this ahead of them would drop the X-Robots-Tag header they set.
// Safe at the root only because session.router.js declares no router-level
// middleware (see the note in that file).
authRouter.use('/', sessionRouter)
module.exports = authRouter

View File

@@ -0,0 +1,51 @@
// Auth · Invite — email-invite acceptance. Public but token-gated: the invite
// token is the whole authority, which is why acceptance bypasses the
// player_registration setting that register.router.js honours.
//
// Mounted at /api/v1/auth/invite by auth/index.js, so the routes below emit
// GET /auth/invite/:token and POST /auth/invite/:token/accept. Staff issue the
// invites from admin/invites.router.js.
const express = require('express')
const { body, param } = require('express-validator')
const { getInvite, acceptInvite } = require('./invite.controller')
const { HONEYPOT_FIELD } = require('./auth.controller')
const { loginGuards } = require('./loginGuards')
const { registerLimiter } = require('../../../middleware/rateLimit')
const validate = require('../../../middleware/validate')
const inviteRouter = express.Router()
inviteRouter.get(
'/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Look up an email invite by token'
// #swagger.description = 'Returns the pre-assigned email + role for a valid, pending, unexpired invite so the accept form can render. 404 for anything not currently acceptable.'
/* #swagger.responses[200] = { description: 'Invite details', content: { "application/json": { schema: { type: "object", properties: { email: { type: "string" }, role: { type: "string" } } } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired invite', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('token').isString().isLength({ min: 8, max: 128 }),
validate,
getInvite,
)
inviteRouter.post(
'/:token/accept',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Accept an email invite (creates the account at the invited role)'
// #swagger.description = 'Creates the website user at the invites pre-assigned role and logs them in (sets the session cookie). Bypasses the player_registration gate — the invite is its own authority. Rate limited + honeypot-guarded like registration.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["username","password"], properties: { username: { type: "string" }, password: { type: "string" } } } } } */
/* #swagger.responses[200] = { description: 'Account created and session issued', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired invite', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'Username taken or invite already used', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
registerLimiter,
param('token').isString().isLength({ min: 8, max: 128 }),
body('username').isString().trim().isLength({ min: 3, max: 32 }),
body('password').isString().isLength({ min: 8, max: 64 }),
body(HONEYPOT_FIELD).optional(),
validate,
acceptInvite,
)
module.exports = inviteRouter

View File

@@ -0,0 +1,64 @@
// Auth · Login — the web cookie login flow and its TOTP second step.
//
// Mounted at /api/v1/auth/login by auth/index.js, so the two routes below emit
// POST /auth/login and POST /auth/login/totp. No group gate: this is the
// unauthenticated front door. Both routes carry the shared loginGuards stack —
// the TOTP step is a code-guessing surface too.
//
// The bearer-token equivalents for native clients live in mobile.routes.js, and
// the OAuth/OIDC flow in sso.routes.js. Logout and GET /auth/me are in
// session.router.js.
const express = require('express')
const { body } = require('express-validator')
const { login, loginTotp, HONEYPOT_FIELD } = require('./auth.controller')
const { loginGuards } = require('./loginGuards')
const validate = require('../../../middleware/validate')
const loginRouter = express.Router()
loginRouter.post(
'/',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Log in with username and password'
// #swagger.description = 'On success sets the httpOnly session cookie. If the account has 2FA enabled, returns { totpRequired, challenge } instead and no cookie is set — complete login at POST /login/totp. Rate limited and behind bot/backoff guards.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/LoginRequest" } } } } */
/* #swagger.responses[200] = { description: 'Session issued, or TOTP challenge required', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[401] = { description: 'Incorrect username or password', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
body('username').isString().trim().notEmpty(),
body('password').isString().notEmpty(),
// Honeypot must be absent/empty for humans; bots that fill it are caught in
// the controller. Accept-but-ignore here so a filled value still reaches it.
body(HONEYPOT_FIELD).optional(),
validate,
login,
)
// Second factor: same throttling, since it's a code-guessing surface too.
loginRouter.post(
'/totp',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Complete login with a TOTP or recovery code'
// #swagger.description = 'Second step for 2FA accounts. Exchange the challenge from /login plus either the current authenticator code OR a single-use recovery code for a session cookie. Set trustDevice to remember this browser and skip TOTP on future logins (30 days); if the trusted-device limit is reached the session is still issued and the response carries { trustLimitReached, devices } so the user can revoke one first.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpLoginRequest" } } } } */
/* #swagger.responses[200] = { description: 'Session issued (optionally with a trusted-device-limit prompt)', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[401] = { description: 'Invalid code or expired challenge', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
body('challenge').isString().notEmpty(),
// Either a TOTP code or a recovery code satisfies the second factor; the
// controller rejects the request when neither verifies.
body('code').optional({ values: 'falsy' }).isString().trim().isLength({ min: 6, max: 8 }),
body('recoveryCode').optional({ values: 'falsy' }).isString().trim().isLength({ min: 8, max: 32 }),
body('trustDevice').optional().isBoolean(),
body('deviceName').optional({ values: 'falsy' }).isString().trim().isLength({ max: 100 }),
validate,
loginTotp,
)
module.exports = loginRouter

View File

@@ -0,0 +1,23 @@
// The shared login-protection stack, ordered cheapest-rejection-first:
//
// backoffGuard → per-IP exponential lockout on repeated failures
// slowLogin → progressive per-request delay within the window
// loginLimiter → hard 10-per-15-min cap
//
// Every credential-guessing surface spreads it with `...loginGuards`: local
// login, the TOTP second step, registration, invite acceptance and the SSO TOTP
// step. It lived inline in auth.routes.js while all but one of those were in the
// same file; the domain split (docs/website/API_V2_PLAN.md § Phase 2) puts them in
// five, so it moved here rather than being copied five times. Duplicating a
// throttling stack is how the copies drift — and the copy that drifts is the one
// that stops throttling.
//
// The array is exported frozen: it is module-level shared state, and a router
// that pushed onto it would silently add middleware to every other login surface.
const { loginLimiter } = require('../../../middleware/rateLimit')
const { slowLogin, backoffGuard } = require('../../../middleware/loginProtection')
const loginGuards = Object.freeze([backoffGuard, slowLogin, loginLimiter])
module.exports = { loginGuards }

View File

@@ -12,7 +12,7 @@
//
// requireAuth sets req.user to the fresh DB row and enforces the status + session
// cutoff/revocation checks on every request, exactly as the account handlers
// expect. Mounted at /me by auth.routes.js, so paths below are /auth/me/account*.
// expect. Mounted at /me by auth/index.js, so paths below are /auth/me/account*.
const express = require('express')
const { body, param } = require('express-validator')

View File

@@ -1,7 +1,7 @@
// ── Push-notification self-service under /auth/me ──────────────────────────
//
// Device registration + per-user stream subscriptions for the app's opt-in push
// (docs/android/PLAN.md §11). Mounted at /me by auth.routes.js alongside
// (docs/android/PLAN.md §11). Mounted at /me by auth/index.js alongside
// me.routes.js, behind requireAuth ONLY (role-agnostic — every authenticated
// role manages its own devices/subscriptions), and noindex. The app calls these
// and never touches /admin.

View File

@@ -0,0 +1,70 @@
// Auth · Password — self-service password reset. Public but token-gated: request
// a link by email, then validate the link and set a new password.
//
// Mounted at /api/v1/auth/password by auth/index.js, so the routes below emit
// POST /auth/password/forgot and GET|POST /auth/password/reset/:token.
//
// Two anti-enumeration properties are load-bearing and must survive any edit
// here: the request step always returns the same generic 200 whether or not the
// email matches an account, and the lookup step never distinguishes expired from
// used from never-existed. Both live in passwordReset.controller; the per-IP
// limiters below are what stop the endpoints being used as an oracle by volume.
//
// Changing a password while signed in is a different route —
// PATCH /player/account/password (and its /auth/me and /admin twins).
const express = require('express')
const { body, param } = require('express-validator')
const { requestReset, lookupReset, confirmReset } = require('./passwordReset.controller')
const {
passwordResetRequestLimiter,
passwordResetConfirmLimiter,
} = require('../../../middleware/rateLimit')
const validate = require('../../../middleware/validate')
const passwordRouter = express.Router()
passwordRouter.post(
'/forgot',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Request a password-reset link by email'
// #swagger.description = 'Emails a single-use, ~1h reset link to every active account on the address. Always returns the same generic 200 whether or not the email matches (no account enumeration). Email is non-unique, so multiple accounts may each receive a link naming their username. Rate limited per IP.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["email"], properties: { email: { type: "string", format: "email" } } } } } } */
/* #swagger.responses[200] = { description: 'Generic acknowledgement (sent if the account exists)', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[429] = { description: 'Too many requests', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
passwordResetRequestLimiter,
body('email').isString().trim().isEmail().isLength({ max: 255 }),
validate,
requestReset,
)
passwordRouter.get(
'/reset/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Validate a password-reset link'
// #swagger.description = 'Returns the target username for a valid, pending, unexpired reset link so the reset form can render. 404 for anything not currently usable (never distinguishes expired from used from never-existed).'
/* #swagger.responses[200] = { description: 'Reset link is valid', content: { "application/json": { schema: { type: "object", properties: { username: { type: "string" } } } } } } */
/* #swagger.responses[404] = { description: 'Invalid or expired reset link', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('token').isString().isLength({ min: 8, max: 128 }),
validate,
lookupReset,
)
passwordRouter.post(
'/reset/:token',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Set a new password from a reset link'
// #swagger.description = 'Consumes the single-use link and sets the new password. Rotates the hash and revokes every existing session (web + mobile). Does NOT sign the user in — they log in fresh afterwards (so a 2FA account still passes TOTP). Rate limited per IP.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["password"], properties: { password: { type: "string", minLength: 8, maxLength: 64 } } } } } } */
/* #swagger.responses[200] = { description: 'Password changed', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
/* #swagger.responses[400] = { description: 'Validation error', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[404] = { description: 'Invalid, expired, or already-used reset link', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
passwordResetConfirmLimiter,
param('token').isString().isLength({ min: 8, max: 128 }),
body('password').isString().isLength({ min: 8, max: 64 }),
validate,
confirmReset,
)
module.exports = passwordRouter

View File

@@ -0,0 +1,43 @@
// Auth · Register — public self-registration of player accounts.
//
// Mounted at /api/v1/auth/register by auth/index.js, so the single route below
// emits POST /auth/register. Gated in the controller by the player_registration
// setting (403 when closed); here it reuses the shared loginGuards stack plus its
// own per-IP registerLimiter, and accepts the honeypot field.
//
// Invite acceptance is the other account-creating route and lives in
// invite.router.js — it deliberately bypasses the player_registration gate, since
// the invite is its own authority.
const express = require('express')
const { body } = require('express-validator')
const { register, HONEYPOT_FIELD } = require('./auth.controller')
const { loginGuards } = require('./loginGuards')
const { registerLimiter } = require('../../../middleware/rateLimit')
const validate = require('../../../middleware/validate')
const registerRouter = express.Router()
registerRouter.post(
'/',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Register a player account'
// #swagger.description = 'Creates a self-service player account and logs it in (sets the session cookie). Available only when an admin has enabled password registration (player_registration = password|both); otherwise returns 403. Rate limited and behind bot/backoff guards; a hidden honeypot field must stay empty.'
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/RegisterRequest" } } } } */
/* #swagger.responses[200] = { description: 'Account created and session issued', content: { "application/json": { schema: { $ref: "#/components/schemas/LoginResponse" } } } } */
/* #swagger.responses[400] = { description: 'Validation error or unavailable username', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[403] = { description: 'Registration is not open', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'Username already taken', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Too many attempts (rate limited / backoff)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
...loginGuards,
registerLimiter,
body('username').isString().trim().isLength({ min: 3, max: 32 }),
body('password').isString().isLength({ min: 8, max: 64 }),
body('email').optional({ values: 'falsy' }).isEmail().isLength({ max: 255 }),
body(HONEYPOT_FIELD).optional(),
validate,
register,
)
module.exports = registerRouter

View File

@@ -0,0 +1,51 @@
// Auth · Session — the two session-lifecycle singletons that own no path segment
// of their own: POST /auth/logout and GET /auth/me.
//
// Mounted at the group root by auth/index.js, **last**. This is the auth group's
// counterpart to admin/dashboard.router.js, and the same two rules apply:
//
// 1. **No router-level middleware here.** A bare `use(gate)` in a root-mounted
// router runs for every request passing through toward another mount, so it
// would gate /auth/login and /auth/mobile/* too. Keep gates on the routes.
//
// 2. **The mount must stay last.** `authRouter.use('/me', meRouter)` matches the
// bare path /me as well as /me/*, so a request to GET /auth/me runs meRouter's
// `noindex, requireAuth` (and notifRouter's), finds no matching route inside
// either, and falls through to the handler below. Mounting this router ahead
// of them would answer /auth/me first and silently drop the X-Robots-Tag
// header those routers apply. Verified by asserting the response headers, not
// by reading the mount table.
//
// Splitting the session is elsewhere by client: mobile.routes.js revokes refresh
// tokens, and me.routes.js owns DELETE /auth/me/sessions/:id.
const express = require('express')
const { logout, me } = require('./auth.controller')
const { isLoggedIn } = require('../../../utils/auth')
const { attachSession } = require('../../../auth/session.middleware')
const sessionRouter = express.Router()
sessionRouter.post(
'/logout',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Log out (clear the cookie and revoke this session)'
/* #swagger.responses[200] = { description: 'Logged out', content: { "application/json": { schema: { $ref: "#/components/schemas/Message" } } } } */
// Best-effort attach (never rejects) so the controller can revoke this session's
// jti — logout stays a no-op for an already-anonymous caller.
attachSession,
logout,
)
sessionRouter.get(
'/me',
// #swagger.tags = ['Auth']
// #swagger.summary = 'Current authenticated user'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The signed-in user', content: { "application/json": { schema: { type: "object", properties: { user: { $ref: "#/components/schemas/User" } } } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
isLoggedIn,
me,
)
module.exports = sessionRouter

View File

@@ -2,17 +2,13 @@ const express = require('express')
const { body } = require('express-validator')
const ctrl = require('./sso.controller')
const { loginGuards } = require('./loginGuards')
const { requireAuth } = require('../../../auth/session.middleware')
const { ssoStartLimiter, loginLimiter } = require('../../../middleware/rateLimit')
const { slowLogin, backoffGuard } = require('../../../middleware/loginProtection')
const { ssoStartLimiter } = require('../../../middleware/rateLimit')
const validate = require('../../../middleware/validate')
const ssoRouter = express.Router()
// Same throttling stack the local login/TOTP endpoints use — the SSO TOTP step is
// a code-guessing surface too (cheapest rejection first).
const loginGuards = [backoffGuard, slowLogin, loginLimiter]
// Public discovery — the login page reads this to render provider buttons.
ssoRouter.get(
'/providers',