diff --git a/server/src/router/v1/auth/auth.routes.js b/server/src/router/v1/auth/auth.routes.js deleted file mode 100644 index 4d4a9ea..0000000 --- a/server/src/router/v1/auth/auth.routes.js +++ /dev/null @@ -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 invite’s 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 diff --git a/server/src/router/v1/auth/index.js b/server/src/router/v1/auth/index.js new file mode 100644 index 0000000..f4ed16b --- /dev/null +++ b/server/src/router/v1/auth/index.js @@ -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 diff --git a/server/src/router/v1/auth/invite.router.js b/server/src/router/v1/auth/invite.router.js new file mode 100644 index 0000000..f145de8 --- /dev/null +++ b/server/src/router/v1/auth/invite.router.js @@ -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 invite’s 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 diff --git a/server/src/router/v1/auth/login.router.js b/server/src/router/v1/auth/login.router.js new file mode 100644 index 0000000..f959560 --- /dev/null +++ b/server/src/router/v1/auth/login.router.js @@ -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 diff --git a/server/src/router/v1/auth/loginGuards.js b/server/src/router/v1/auth/loginGuards.js new file mode 100644 index 0000000..6df0fd8 --- /dev/null +++ b/server/src/router/v1/auth/loginGuards.js @@ -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 } diff --git a/server/src/router/v1/auth/me.routes.js b/server/src/router/v1/auth/me.routes.js index a9a715e..24bd3d0 100644 --- a/server/src/router/v1/auth/me.routes.js +++ b/server/src/router/v1/auth/me.routes.js @@ -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') diff --git a/server/src/router/v1/auth/notifications.routes.js b/server/src/router/v1/auth/notifications.routes.js index 91e44c6..579777f 100644 --- a/server/src/router/v1/auth/notifications.routes.js +++ b/server/src/router/v1/auth/notifications.routes.js @@ -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. diff --git a/server/src/router/v1/auth/password.router.js b/server/src/router/v1/auth/password.router.js new file mode 100644 index 0000000..25d209e --- /dev/null +++ b/server/src/router/v1/auth/password.router.js @@ -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 diff --git a/server/src/router/v1/auth/register.router.js b/server/src/router/v1/auth/register.router.js new file mode 100644 index 0000000..bec3c81 --- /dev/null +++ b/server/src/router/v1/auth/register.router.js @@ -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 diff --git a/server/src/router/v1/auth/session.router.js b/server/src/router/v1/auth/session.router.js new file mode 100644 index 0000000..a47745f --- /dev/null +++ b/server/src/router/v1/auth/session.router.js @@ -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 diff --git a/server/src/router/v1/auth/sso.routes.js b/server/src/router/v1/auth/sso.routes.js index f224e82..6665b79 100644 --- a/server/src/router/v1/auth/sso.routes.js +++ b/server/src/router/v1/auth/sso.routes.js @@ -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', diff --git a/server/src/router/v1/player/account.router.js b/server/src/router/v1/player/account.router.js new file mode 100644 index 0000000..1bcbad3 --- /dev/null +++ b/server/src/router/v1/player/account.router.js @@ -0,0 +1,130 @@ +// Player · Account — self-service credentials, 2FA and linked identities for the +// signed-in account. +// +// Mounted at /api/v1/player/account by player/index.js, which already applied +// `noindex, requireAuth`. No extra gate: every handler is self-scoped to +// req.user.id, and staff are a superset of players (see player/index.js). +// +// The handlers are admin/account.controller — the same code serving +// /admin/account/* and /auth/me/account/*. Three URL surfaces, one implementation; +// this file must not grow a fourth copy of the logic. +// +// The swagger tag stays 'Player', matching the committed spec. + +const express = require('express') +const { body, param } = require('express-validator') + +const account = require('../admin/account.controller') +const validate = require('../../../middleware/validate') +const { accountChangeLimiter } = require('../../../middleware/rateLimit') + +const accountRouter = express.Router() + +accountRouter.get( + '/', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Get the current player account (self)' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'The player account', content: { "application/json": { schema: { $ref: "#/components/schemas/PlayerAccount" } } } } */ + /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + account.getAccount, +) + +accountRouter.patch( + '/username', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Change the current player’s username' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ChangeUsernameRequest" } } } } */ + /* #swagger.responses[200] = { description: 'Updated username (session cookie re-issued)', content: { "application/json": { schema: { type: "object", properties: { username: { type: "string" } } } } } } */ + /* #swagger.responses[400] = { description: 'Validation error or unavailable username', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ + /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', 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 changes (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + accountChangeLimiter, + body('username').isString().trim().isLength({ min: 3, max: 32 }), + validate, + account.changeUsername, +) + +accountRouter.patch( + '/password', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Change or set the current player’s password' + // #swagger.description = 'If the account already has a password, currentPassword is required and verified. SSO-provisioned accounts with no password may set an initial one without a current password. On success the caller’s session is re-issued (they stay logged in) while all other sessions are revoked.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ChangePasswordRequest" } } } } */ + /* #swagger.responses[200] = { description: 'Password changed', content: { "application/json": { schema: { $ref: "#/components/schemas/OkFlag" } } } } */ + /* #swagger.responses[400] = { description: 'Validation error or wrong current password', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[429] = { description: 'Too many changes (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + accountChangeLimiter, + body('newPassword').isString().isLength({ min: 8, max: 64 }), + body('currentPassword').optional({ values: 'falsy' }).isString(), + validate, + account.changePassword, +) + +// TOTP self-enrollment — identical to the admin account flow (disable requires a +// valid current code; it does not take a password). +accountRouter.post( + '/totp/setup', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Begin 2FA enrollment (returns secret + QR)' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'otpauth URL and QR data to scan', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpSetup" } } } } */ + /* #swagger.responses[409] = { description: 'Two-factor already enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + account.totpSetup, +) +accountRouter.post( + '/totp/enable', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Enable 2FA by confirming a code' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpCodeRequest" } } } } */ + /* #swagger.responses[200] = { description: '2FA enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpState" } } } } */ + /* #swagger.responses[400] = { description: 'Setup not started, or invalid code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[409] = { description: 'Two-factor already enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + body('code').isString().trim().isLength({ min: 6, max: 8 }), + validate, + account.totpEnable, +) +accountRouter.post( + '/totp/disable', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Disable 2FA by confirming a code' + // #swagger.description = 'Requires a valid current authenticator code (proves control of the authenticator); it does not take a password.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpCodeRequest" } } } } */ + /* #swagger.responses[200] = { description: '2FA disabled', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpState" } } } } */ + /* #swagger.responses[400] = { description: 'Not enabled, or invalid code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + body('code').isString().trim().isLength({ min: 6, max: 8 }), + validate, + account.totpDisable, +) + +// Linked SSO identities (self-service). Linking itself starts at +// GET /auth/sso/:provider/link (already behind requireAuth; works for players). +accountRouter.get( + '/identities', + // #swagger.tags = ['Player'] + // #swagger.summary = 'List linked SSO identities (self)' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'Linked identities', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/LinkedIdentity" } } } } } */ + account.listIdentities, +) +accountRouter.delete( + '/identities/:provider', + // #swagger.tags = ['Player'] + // #swagger.summary = 'Unlink an SSO identity (self)' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + // #swagger.parameters['provider'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Provider id.' } + /* #swagger.responses[200] = { description: 'Unlinked', content: { "application/json": { schema: { $ref: "#/components/schemas/UnlinkedFlag" } } } } */ + /* #swagger.responses[404] = { description: 'No linked account for that provider', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + param('provider').matches(/^[a-z0-9-]+$/), + validate, + account.unlinkIdentity, +) + +module.exports = accountRouter diff --git a/server/src/router/v1/player/appeals.controller.js b/server/src/router/v1/player/appeals.controller.js index 50b74d5..1878cd0 100644 --- a/server/src/router/v1/player/appeals.controller.js +++ b/server/src/router/v1/player/appeals.controller.js @@ -4,7 +4,8 @@ // one that hasn't been resolved yet. Ownership is proven by matching the // action's target_user_id against the caller's linked Discord identity — the // same (provider='discord', subject=) link the SSO flow writes. -// Mounted behind the player-role gate (see player.routes.js). +// Mounted behind the /player group gate — authenticated only, no role restriction +// (see player/index.js); ownership is enforced per handler. const appeals = require('../../../model/appeals/appeals.model') const appealsDb = require('../../../model/appeals/appeals.db') const { isAppealableType, isTerminal } = require('../../../model/appeals/appeals.pure') diff --git a/server/src/router/v1/player/appeals.router.js b/server/src/router/v1/player/appeals.router.js new file mode 100644 index 0000000..31ff9a1 --- /dev/null +++ b/server/src/router/v1/player/appeals.router.js @@ -0,0 +1,73 @@ +// Player · Appeals — a player appeals one of their own ban/mute mod_actions. +// Ownership is proven by matching the action against the caller's linked Discord +// identity (see appeals.controller); the staff side of the queue lives in +// admin/moderation.router.js. +// +// Mounted at /api/v1/player/appeals by player/index.js, which already applied +// `noindex, requireAuth`. No extra gate — every handler is self-scoped. +// +// Declaration order: GET /eligible is a literal path and sits ahead of the only +// :param route (POST /:id/withdraw), which is a different method at a different +// depth, so nothing here can shadow anything else. + +const express = require('express') +const { body, param } = require('express-validator') + +const appeals = require('./appeals.controller') +const validate = require('../../../middleware/validate') +const { accountChangeLimiter } = require('../../../middleware/rateLimit') + +const appealsRouter = express.Router() + +appealsRouter.get( + '/', + // #swagger.tags = ['Player · Appeals'] + // #swagger.summary = 'List the caller’s moderation appeals' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'The caller’s appeals', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Appeal" } } } } } */ + /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + appeals.listMine, +) +appealsRouter.get( + '/eligible', + // #swagger.tags = ['Player · Appeals'] + // #swagger.summary = 'List the caller’s ban/mute actions eligible for appeal' + // #swagger.description = 'The caller’s ban/mute mod_actions that have no active appeal. Returns an empty array when the caller has no linked Discord account (the UI shows a “link Discord” hint).' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'Appealable actions', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AppealEligibleAction" } } } } } */ + /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + appeals.listEligible, +) +appealsRouter.post( + '/', + // #swagger.tags = ['Player · Appeals'] + // #swagger.summary = 'Submit a moderation appeal for one of the caller’s actions' + // #swagger.description = 'Opens an appeal for a ban/mute mod_action that belongs to the caller (its target matches the caller’s linked Discord identity) and has no active appeal.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/CreateAppealRequest" } } } } */ + /* #swagger.responses[201] = { description: 'Appeal created', content: { "application/json": { schema: { $ref: "#/components/schemas/Appeal" } } } } */ + /* #swagger.responses[400] = { description: 'Validation error, or the action type is not appealable', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ + /* #swagger.responses[403] = { description: 'The action does not belong to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[404] = { description: 'Mod action not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[409] = { description: 'An appeal for this action is already open', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + accountChangeLimiter, + body('mod_action_id').isInt({ min: 1 }).toInt(), + body('submitted_text').isString().trim().isLength({ min: 1, max: 4000 }), + validate, + appeals.create, +) +appealsRouter.post( + '/:id/withdraw', + // #swagger.tags = ['Player · Appeals'] + // #swagger.summary = 'Withdraw one of the caller’s pending appeals' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Appeal id (must belong to the caller).' } + /* #swagger.responses[200] = { description: 'The withdrawn appeal', content: { "application/json": { schema: { $ref: "#/components/schemas/Appeal" } } } } */ + /* #swagger.responses[404] = { description: 'No such appeal for the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[409] = { description: 'Appeal is already resolved', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + param('id').isInt({ min: 1 }), + validate, + appeals.withdraw, +) + +module.exports = appealsRouter diff --git a/server/src/router/v1/player/index.js b/server/src/router/v1/player/index.js new file mode 100644 index 0000000..179ee92 --- /dev/null +++ b/server/src/router/v1/player/index.js @@ -0,0 +1,43 @@ +// /api/v1/player — the player self-service surface, assembled from +// per-capability routers. +// +// This file owns exactly two things: the gate every player route shares, and the +// mount table. No route is declared here. Each capability router mounts at the +// prefix it already owned inside the old monolithic player.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`). +// +// **Staff are a superset of players.** This group is open to any authenticated +// account, not just role 'player': every read/write is self-scoped to req.user.id, +// and a staff member has every player ability plus their staff tools on top. +// Adding a requireRole('player') here would 403 an admin off their own characters +// (it happened once — see docs/website/BACKEND_DESIGN.md). Staff also reach the +// identical self-scoped handlers under /admin/shard and /auth/me/account; those +// are alternative URLs onto the same controllers, not duplicated logic. +// +// See docs/website/API_V2_PLAN.md § Phase 2 for the split. + +const express = require('express') + +const { requireAuth } = require('../../../auth/session.middleware') +const noindex = require('../../../middleware/noindex') + +const accountRouter = require('./account.router') +const shardRouter = require('./shard.router') +const appealsRouter = require('./appeals.router') + +const playerRouter = express.Router() + +// Group gate: authenticated only (no role restriction). Keep it out of search +// indexes. requireAuth also enforces the account status check (a disabled/banned +// account is rejected here with 403 before any handler runs). +// +// It lives here, ahead of every mount, so a capability router added later cannot +// silently ship without it. +playerRouter.use(noindex, requireAuth) + +playerRouter.use('/account', accountRouter) +playerRouter.use('/shard', shardRouter) +playerRouter.use('/appeals', appealsRouter) + +module.exports = playerRouter diff --git a/server/src/router/v1/player/player.routes.js b/server/src/router/v1/player/player.routes.js deleted file mode 100644 index e63e4f0..0000000 --- a/server/src/router/v1/player/player.routes.js +++ /dev/null @@ -1,296 +0,0 @@ -// ── Player self-service (any authenticated account) ───────────────────────── -// -// The player self-service surface: linked game accounts, character/vendor/house -// reads, and account-credential changes, all self-scoped to the caller by -// req.user.id. Staff are a *superset* of players — they have every player ability -// plus their staff tools on top — so this group is open to any authenticated -// account, not just role 'player'. Staff also reach the identical self-scoped -// handlers under /admin/shard (they are the same controller); this group lets a -// staff account use the player surface directly. Handlers are shared with the -// admin account view (account.controller) — the same TOTP / identity logic, plus -// the net-new self-scoped credential changes. Future self-service endpoints hang -// off this group. - -const express = require('express') -const { body, param } = require('express-validator') - -const account = require('../admin/account.controller') -const shard = require('./shard.controller') -const appeals = require('./appeals.controller') -const { requireAuth } = require('../../../auth/session.middleware') -const noindex = require('../../../middleware/noindex') -const validate = require('../../../middleware/validate') -const { accountChangeLimiter } = require('../../../middleware/rateLimit') - -const playerRouter = express.Router() - -// Group gate: authenticated only (no role restriction) — players and staff alike -// use this self-service surface; every read/write is scoped to the caller. Keep it -// out of search indexes. requireAuth also enforces the account status check (a -// disabled/banned account is rejected here with 403 before any handler runs). -playerRouter.use(noindex, requireAuth) - -playerRouter.get( - '/account', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Get the current player account (self)' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'The player account', content: { "application/json": { schema: { $ref: "#/components/schemas/PlayerAccount" } } } } */ - /* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - account.getAccount, -) - -playerRouter.patch( - '/account/username', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Change the current player’s username' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ChangeUsernameRequest" } } } } */ - /* #swagger.responses[200] = { description: 'Updated username (session cookie re-issued)', content: { "application/json": { schema: { type: "object", properties: { username: { type: "string" } } } } } } */ - /* #swagger.responses[400] = { description: 'Validation error or unavailable username', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ - /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', 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 changes (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - accountChangeLimiter, - body('username').isString().trim().isLength({ min: 3, max: 32 }), - validate, - account.changeUsername, -) - -playerRouter.patch( - '/account/password', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Change or set the current player’s password' - // #swagger.description = 'If the account already has a password, currentPassword is required and verified. SSO-provisioned accounts with no password may set an initial one without a current password. On success the caller’s session is re-issued (they stay logged in) while all other sessions are revoked.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ChangePasswordRequest" } } } } */ - /* #swagger.responses[200] = { description: 'Password changed', content: { "application/json": { schema: { $ref: "#/components/schemas/OkFlag" } } } } */ - /* #swagger.responses[400] = { description: 'Validation error or wrong current password', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[429] = { description: 'Too many changes (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - accountChangeLimiter, - body('newPassword').isString().isLength({ min: 8, max: 64 }), - body('currentPassword').optional({ values: 'falsy' }).isString(), - validate, - account.changePassword, -) - -// TOTP self-enrollment — identical to the admin account flow (disable requires a -// valid current code; it does not take a password). -playerRouter.post( - '/account/totp/setup', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Begin 2FA enrollment (returns secret + QR)' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'otpauth URL and QR data to scan', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpSetup" } } } } */ - /* #swagger.responses[409] = { description: 'Two-factor already enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - account.totpSetup, -) -playerRouter.post( - '/account/totp/enable', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Enable 2FA by confirming a code' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpCodeRequest" } } } } */ - /* #swagger.responses[200] = { description: '2FA enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpState" } } } } */ - /* #swagger.responses[400] = { description: 'Setup not started, or invalid code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[409] = { description: 'Two-factor already enabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - body('code').isString().trim().isLength({ min: 6, max: 8 }), - validate, - account.totpEnable, -) -playerRouter.post( - '/account/totp/disable', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Disable 2FA by confirming a code' - // #swagger.description = 'Requires a valid current authenticator code (proves control of the authenticator); it does not take a password.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TotpCodeRequest" } } } } */ - /* #swagger.responses[200] = { description: '2FA disabled', content: { "application/json": { schema: { $ref: "#/components/schemas/TotpState" } } } } */ - /* #swagger.responses[400] = { description: 'Not enabled, or invalid code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - body('code').isString().trim().isLength({ min: 6, max: 8 }), - validate, - account.totpDisable, -) - -// Linked SSO identities (self-service). Linking itself starts at -// GET /auth/sso/:provider/link (already behind requireAuth; works for players). -playerRouter.get( - '/account/identities', - // #swagger.tags = ['Player'] - // #swagger.summary = 'List linked SSO identities (self)' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'Linked identities', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/LinkedIdentity" } } } } } */ - account.listIdentities, -) -playerRouter.delete( - '/account/identities/:provider', - // #swagger.tags = ['Player'] - // #swagger.summary = 'Unlink an SSO identity (self)' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - // #swagger.parameters['provider'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Provider id.' } - /* #swagger.responses[200] = { description: 'Unlinked', content: { "application/json": { schema: { $ref: "#/components/schemas/UnlinkedFlag" } } } } */ - /* #swagger.responses[404] = { description: 'No linked account for that provider', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - param('provider').matches(/^[a-z0-9-]+$/), - validate, - account.unlinkIdentity, -) - -// ── Game account linking (uo-link) ───────────────────────────────────────── -// Link an in-game account with a one-time code from [link, then read the -// account's roster / vendors (ownership-checked against the local link mirror). -const ACCOUNT_RE = /^[A-Za-z0-9_.-]{1,120}$/ -playerRouter.post( - '/shard/link', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Link an in-game account with a one-time code' - // #swagger.description = 'The player runs [link in game to get a code, then submits it here. The server confirms it with the sidecar and mirrors the link.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkRequest" } } } } */ - /* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkResult" } } } } */ - /* #swagger.responses[400] = { description: 'Unknown or expired code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - body('code').isString().trim().isLength({ min: 4, max: 32 }), - validate, - shard.link, -) -playerRouter.post( - '/shard/account', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Create a game account (hybrid signup) and link it to the caller' - // #swagger.description = 'Provisions a new game account with its own username + password and auto-links it to the signed-in website user. Available only when game_account_signup is enabled and the shard accepts website signups. The password is hashed on the shard and never stored or logged by the site.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } */ - /* #swagger.responses[201] = { description: 'Account created and linked', content: { "application/json": { schema: { type: "object", properties: { account: { type: "string" }, linked: { type: "boolean" } } } } } } */ - /* #swagger.responses[400] = { description: 'Validation error or rejected name/password', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ - /* #swagger.responses[403] = { description: 'Game-account signup unavailable (site or shard)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[409] = { description: 'Account name already taken', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[429] = { description: 'Per-IP account cap reached', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - accountChangeLimiter, - body('account').matches(/^[A-Za-z0-9][A-Za-z0-9_.-]{2,29}$/), - body('password').isString().isLength({ min: 8, max: 64 }), - validate, - shard.createGameAccount, -) -playerRouter.get( - '/shard/accounts', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'List the caller’s linked game accounts' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardLink" } } } } } */ - shard.listAccounts, -) -playerRouter.get( - '/shard/roster/:account', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Character roster for a linked account' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - // #swagger.parameters['account'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'A game account linked to the caller.' } - /* #swagger.responses[200] = { description: 'Account roster', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - /* #swagger.responses[403] = { description: 'Account not linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - param('account').matches(ACCOUNT_RE), - validate, - shard.roster, -) -playerRouter.get( - '/shard/vendors/:account', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Player vendors for a linked account' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - // #swagger.parameters['account'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'A game account linked to the caller.' } - /* #swagger.responses[200] = { description: 'Vendor snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - /* #swagger.responses[403] = { description: 'Account not linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - param('account').matches(ACCOUNT_RE), - validate, - shard.vendors, -) -playerRouter.get( - '/shard/char/:serial', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Character sheet — only for a character on the caller’s linked account' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - // #swagger.parameters['serial'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Mobile serial, e.g. 0x24C.' } - /* #swagger.responses[200] = { description: 'Character profile', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - /* #swagger.responses[403] = { description: 'Character not on an account linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - param('serial').matches(/^0x[0-9a-fA-F]+$/), - validate, - shard.getChar, -) -playerRouter.get( - '/shard/sales', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'Recent player-vendor sales for the caller’s linked accounts' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardVendorSale" } } } } } */ - shard.getSales, -) -playerRouter.get( - '/shard/houses', - // #swagger.tags = ['Player · Shard'] - // #swagger.summary = 'The caller’s own houses (home status)' - // #swagger.description = 'Houses owned by the caller’s linked accounts, with decay/IDOC status. Only the caller’s own houses — never anyone else’s.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'The caller’s houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ - shard.getHouses, -) - -// ── Moderation appeals (uo-link / Discord moderation) ────────────────────── -// A player appeals one of their own ban/mute mod_actions. Ownership is proven by -// matching the action against the caller's linked Discord identity. -playerRouter.get( - '/appeals', - // #swagger.tags = ['Player · Appeals'] - // #swagger.summary = 'List the caller’s moderation appeals' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'The caller’s appeals', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Appeal" } } } } } */ - /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - appeals.listMine, -) -playerRouter.get( - '/appeals/eligible', - // #swagger.tags = ['Player · Appeals'] - // #swagger.summary = 'List the caller’s ban/mute actions eligible for appeal' - // #swagger.description = 'The caller’s ban/mute mod_actions that have no active appeal. Returns an empty array when the caller has no linked Discord account (the UI shows a “link Discord” hint).' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.responses[200] = { description: 'Appealable actions', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AppealEligibleAction" } } } } } */ - /* #swagger.responses[403] = { description: 'Account not active (disabled/banned)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - appeals.listEligible, -) -playerRouter.post( - '/appeals', - // #swagger.tags = ['Player · Appeals'] - // #swagger.summary = 'Submit a moderation appeal for one of the caller’s actions' - // #swagger.description = 'Opens an appeal for a ban/mute mod_action that belongs to the caller (its target matches the caller’s linked Discord identity) and has no active appeal.' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/CreateAppealRequest" } } } } */ - /* #swagger.responses[201] = { description: 'Appeal created', content: { "application/json": { schema: { $ref: "#/components/schemas/Appeal" } } } } */ - /* #swagger.responses[400] = { description: 'Validation error, or the action type is not appealable', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ - /* #swagger.responses[403] = { description: 'The action does not belong to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[404] = { description: 'Mod action not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[409] = { description: 'An appeal for this action is already open', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - accountChangeLimiter, - body('mod_action_id').isInt({ min: 1 }).toInt(), - body('submitted_text').isString().trim().isLength({ min: 1, max: 4000 }), - validate, - appeals.create, -) -playerRouter.post( - '/appeals/:id/withdraw', - // #swagger.tags = ['Player · Appeals'] - // #swagger.summary = 'Withdraw one of the caller’s pending appeals' - // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] - // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Appeal id (must belong to the caller).' } - /* #swagger.responses[200] = { description: 'The withdrawn appeal', content: { "application/json": { schema: { $ref: "#/components/schemas/Appeal" } } } } */ - /* #swagger.responses[404] = { description: 'No such appeal for the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[409] = { description: 'Appeal is already resolved', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - param('id').isInt({ min: 1 }), - validate, - appeals.withdraw, -) - -module.exports = playerRouter diff --git a/server/src/router/v1/player/shard.router.js b/server/src/router/v1/player/shard.router.js new file mode 100644 index 0000000..0f14b0f --- /dev/null +++ b/server/src/router/v1/player/shard.router.js @@ -0,0 +1,124 @@ +// Player · Shard — game-account linking and the caller's own roster / vendors / +// characters / sales / houses, ownership-checked against the local link mirror. +// +// Mounted at /api/v1/player/shard by player/index.js, which already applied +// `noindex, requireAuth`. No extra gate: every handler is self-scoped to +// req.user.id. +// +// These are the *same* handlers (player/shard.controller) that admin/shard.router.js +// serves under /admin/shard for the seven self-service routes — staff are a +// superset of players, and the controller keys off req.user.id either way. Two +// URL surfaces, one implementation. + +const express = require('express') +const { body, param } = require('express-validator') + +const shard = require('./shard.controller') +const validate = require('../../../middleware/validate') +const { accountChangeLimiter } = require('../../../middleware/rateLimit') + +const shardRouter = express.Router() + +// Link an in-game account with a one-time code from [link, then read the +// account's roster / vendors (ownership-checked against the local link mirror). +const ACCOUNT_RE = /^[A-Za-z0-9_.-]{1,120}$/ + +shardRouter.post( + '/link', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Link an in-game account with a one-time code' + // #swagger.description = 'The player runs [link in game to get a code, then submits it here. The server confirms it with the sidecar and mirrors the link.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkRequest" } } } } */ + /* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkResult" } } } } */ + /* #swagger.responses[400] = { description: 'Unknown or expired code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + body('code').isString().trim().isLength({ min: 4, max: 32 }), + validate, + shard.link, +) +shardRouter.post( + '/account', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Create a game account (hybrid signup) and link it to the caller' + // #swagger.description = 'Provisions a new game account with its own username + password and auto-links it to the signed-in website user. Available only when game_account_signup is enabled and the shard accepts website signups. The password is hashed on the shard and never stored or logged by the site.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } */ + /* #swagger.responses[201] = { description: 'Account created and linked', content: { "application/json": { schema: { type: "object", properties: { account: { type: "string" }, linked: { type: "boolean" } } } } } } */ + /* #swagger.responses[400] = { description: 'Validation error or rejected name/password', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */ + /* #swagger.responses[403] = { description: 'Game-account signup unavailable (site or shard)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[409] = { description: 'Account name already taken', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[429] = { description: 'Per-IP account cap reached', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + accountChangeLimiter, + body('account').matches(/^[A-Za-z0-9][A-Za-z0-9_.-]{2,29}$/), + body('password').isString().isLength({ min: 8, max: 64 }), + validate, + shard.createGameAccount, +) +shardRouter.get( + '/accounts', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'List the caller’s linked game accounts' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardLink" } } } } } */ + shard.listAccounts, +) +shardRouter.get( + '/roster/:account', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Character roster for a linked account' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + // #swagger.parameters['account'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'A game account linked to the caller.' } + /* #swagger.responses[200] = { description: 'Account roster', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + /* #swagger.responses[403] = { description: 'Account not linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + param('account').matches(ACCOUNT_RE), + validate, + shard.roster, +) +shardRouter.get( + '/vendors/:account', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Player vendors for a linked account' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + // #swagger.parameters['account'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'A game account linked to the caller.' } + /* #swagger.responses[200] = { description: 'Vendor snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + /* #swagger.responses[403] = { description: 'Account not linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + param('account').matches(ACCOUNT_RE), + validate, + shard.vendors, +) +shardRouter.get( + '/char/:serial', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Character sheet — only for a character on the caller’s linked account' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + // #swagger.parameters['serial'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Mobile serial, e.g. 0x24C.' } + /* #swagger.responses[200] = { description: 'Character profile', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + /* #swagger.responses[403] = { description: 'Character not on an account linked to the caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + param('serial').matches(/^0x[0-9a-fA-F]+$/), + validate, + shard.getChar, +) +shardRouter.get( + '/sales', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'Recent player-vendor sales for the caller’s linked accounts' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardVendorSale" } } } } } */ + shard.getSales, +) +shardRouter.get( + '/houses', + // #swagger.tags = ['Player · Shard'] + // #swagger.summary = 'The caller’s own houses (home status)' + // #swagger.description = 'Houses owned by the caller’s linked accounts, with decay/IDOC status. Only the caller’s own houses — never anyone else’s.' + // #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }] + /* #swagger.responses[200] = { description: 'The caller’s houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ + shard.getHouses, +) + +module.exports = shardRouter diff --git a/server/src/router/v1/public/index.js b/server/src/router/v1/public/index.js new file mode 100644 index 0000000..3f90671 --- /dev/null +++ b/server/src/router/v1/public/index.js @@ -0,0 +1,43 @@ +// /api/v1/public — the anonymous public 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 public.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.** Unlike /admin (staffOnly) and /player +// (requireAuth), this group is unauthenticated by design and must stay that way: +// the SPA renders logged-out, the Discord bot reads it anonymously, and the +// Android app's ShardStreamClient consumes /public/shard/stream with no +// Authorization header. Content visibility during maintenance is handled by the +// per-route `siteMode` middleware, not by an auth gate. +// +// See docs/website/API_V2_PLAN.md § Phase 2 for the split. + +const express = require('express') + +const postsRouter = require('./posts.router') +const wikiRouter = require('./wiki.router') +const pagesRouter = require('./pages.router') +const shardRouter = require('./shard.router') +const siteRouter = require('./site.router') + +const publicRouter = express.Router() + +// Content. All three are site-mode gated per route (the /pages draft-preview +// route is the one deliberate exception — see pages.router.js). +publicRouter.use('/posts', postsRouter) +publicRouter.use('/wiki', wikiRouter) +publicRouter.use('/pages', pagesRouter) +// Live shard data, never site-mode gated. +publicRouter.use('/shard', shardRouter) + +// The four singletons that own no path segment of their own: /settings, /status, +// /version and /contact. Mounted at the group root, last — safe only because +// site.router.js declares no router-level middleware (a bare `use(gate)` in a +// root-mounted router runs for every request passing through toward another +// mount). Same arrangement as admin/dashboard.router.js. +publicRouter.use('/', siteRouter) + +module.exports = publicRouter diff --git a/server/src/router/v1/public/pages.router.js b/server/src/router/v1/public/pages.router.js new file mode 100644 index 0000000..406d898 --- /dev/null +++ b/server/src/router/v1/public/pages.router.js @@ -0,0 +1,40 @@ +// Public · Pages — the block-based CMS pages, read side. Counterpart of +// admin/pages.router.js (the page builder). Unrelated to /admin/shard/pages, +// which is the in-game help-page queue. +// +// Mounted at /api/v1/public/pages by public/index.js. No group gate. +// +// Declaration order is load-bearing: the draft-preview route is registered ahead +// of /:slug, and it is deliberately NOT site-mode gated so a preview link keeps +// working during maintenance — the single-use token is the access control. + +const express = require('express') + +const ctrl = require('./public.controller') +const siteMode = require('../../../middleware/siteMode') + +const pagesRouter = express.Router() + +pagesRouter.get( + '/:id/preview/:token', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Render a page from a draft-preview token' + // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Page id.' } + // #swagger.parameters['token'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Preview token from POST /admin/pages/:id/preview.' } + /* #swagger.responses[200] = { description: 'The page (any status)', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + /* #swagger.responses[404] = { description: 'Token invalid/expired or page missing', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + ctrl.getPagePreview, +) +pagesRouter.get( + '/:slug', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Get a published CMS page by slug' + // #swagger.description = 'Drafts 404 for the public; staff sessions see drafts. Gated by site mode.' + // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Page slug.' } + /* #swagger.responses[200] = { description: 'The page', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + siteMode, + ctrl.getPage, +) + +module.exports = pagesRouter diff --git a/server/src/router/v1/public/posts.router.js b/server/src/router/v1/public/posts.router.js new file mode 100644 index 0000000..c66d835 --- /dev/null +++ b/server/src/router/v1/public/posts.router.js @@ -0,0 +1,39 @@ +// Public · Posts — the published news / five-on-friday / newsletter / screenshots +// feed. The read-only counterpart of admin/posts.router.js, sharing the same +// posts model through public.controller. +// +// Mounted at /api/v1/public/posts by public/index.js. No group gate: this is the +// anonymous public surface. `siteMode` is applied per route — during maintenance +// only an admin with a valid session sees content. + +const express = require('express') + +const ctrl = require('./public.controller') +const siteMode = require('../../../middleware/siteMode') + +const postsRouter = express.Router() + +postsRouter.get( + '/:category', + // #swagger.tags = ['Public'] + // #swagger.summary = 'List published posts in a category' + // #swagger.description = 'Gated by site mode: during maintenance only admins with a valid session see content.' + // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'news | five-on-friday | newsletter | screenshots' } + /* #swagger.responses[200] = { description: 'Published posts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Post" } } } } } */ + /* #swagger.responses[404] = { description: 'Unknown category', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + siteMode, + ctrl.getPosts, +) +postsRouter.get( + '/:category/:idOrSlug', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Get a single published post' + // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Post category.' } + // #swagger.parameters['idOrSlug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Numeric id or slug.' } + /* #swagger.responses[200] = { description: 'The post', content: { "application/json": { schema: { $ref: "#/components/schemas/Post" } } } } */ + /* #swagger.responses[404] = { description: 'Unknown category or post not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + siteMode, + ctrl.getPost, +) + +module.exports = postsRouter diff --git a/server/src/router/v1/public/public.routes.js b/server/src/router/v1/public/public.routes.js deleted file mode 100644 index 247f28b..0000000 --- a/server/src/router/v1/public/public.routes.js +++ /dev/null @@ -1,248 +0,0 @@ -const express = require('express') -const { body, param, query } = require('express-validator') - -const ctrl = require('./public.controller') -const shard = require('./shard.controller') -const siteMode = require('../../../middleware/siteMode') -const validate = require('../../../middleware/validate') -const { contactLimiter } = require('../../../middleware/rateLimit') - -const publicRouter = express.Router() - -// Always available (so the client can render the maintenance page + contact). -publicRouter.get( - '/settings', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Public site settings + branding' - // #swagger.description = 'Whitelisted, non-sensitive settings plus the per-shard brand block (name/colors/logo/hero/favicon) a client themes itself from, and derived registration / game-account-signup availability flags.' - /* #swagger.responses[200] = { description: 'Public settings + branding', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicSettings" } } } } */ - ctrl.getSettings, -) -publicRouter.get( - '/status', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Site mode / status' - // #swagger.description = 'Current site mode (live or maintenance) so the client can show the maintenance page, plus a version block (service id + API/server versions) for a client first-run probe and version-mismatch guard.' - /* #swagger.responses[200] = { description: 'Site status', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicStatus" } } } } */ - ctrl.getStatus, -) -publicRouter.get( - '/version', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Backend identity + version' - // #swagger.description = 'Lightweight, DB-free descriptor of this backend: a stable service id and the API/server versions. A client uses it to recognize a Runic Gateway backend on first-run and to run a version-mismatch guard. Doubles as a cheap liveness check.' - /* #swagger.responses[200] = { description: 'Backend version', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicVersion" } } } } */ - ctrl.getVersion, -) -publicRouter.post( - '/contact', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Send a contact message' - // #swagger.description = 'Emails the site owner (or falls back to a mailto). Rate limited.' - /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ContactRequest" } } } } */ - /* #swagger.responses[200] = { description: 'Message sent', 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 messages (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - /* #swagger.responses[502] = { description: 'Mail delivery failed', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - contactLimiter, - body('message').isString().trim().notEmpty().isLength({ max: 5000 }), - body('email').optional({ values: 'falsy' }).isEmail(), - body('name').optional({ values: 'falsy' }).isString().trim().isLength({ max: 100 }), - validate, - ctrl.contact, -) - -// Content — gated by site mode (admins with a valid token bypass for preview). -publicRouter.get( - '/posts/:category', - // #swagger.tags = ['Public'] - // #swagger.summary = 'List published posts in a category' - // #swagger.description = 'Gated by site mode: during maintenance only admins with a valid session see content.' - // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'news | five-on-friday | newsletter | screenshots' } - /* #swagger.responses[200] = { description: 'Published posts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/Post" } } } } } */ - /* #swagger.responses[404] = { description: 'Unknown category', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - siteMode, - ctrl.getPosts, -) -publicRouter.get( - '/posts/:category/:idOrSlug', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Get a single published post' - // #swagger.parameters['category'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Post category.' } - // #swagger.parameters['idOrSlug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Numeric id or slug.' } - /* #swagger.responses[200] = { description: 'The post', content: { "application/json": { schema: { $ref: "#/components/schemas/Post" } } } } */ - /* #swagger.responses[404] = { description: 'Unknown category or post not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - siteMode, - ctrl.getPost, -) -publicRouter.get( - '/wiki', - // #swagger.tags = ['Public'] - // #swagger.summary = 'List published wiki pages' - /* #swagger.responses[200] = { description: 'Published wiki pages', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiPage" } } } } } */ - siteMode, - ctrl.getWikiList, -) -// Static paths must precede the :slug route so they aren't captured as a slug. -publicRouter.get( - '/wiki/categories', - // #swagger.tags = ['Public'] - // #swagger.summary = 'List wiki categories' - /* #swagger.responses[200] = { description: 'Wiki categories', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiCategory" } } } } } */ - siteMode, - ctrl.getWikiCategories, -) -publicRouter.get( - '/wiki/tags', - // #swagger.tags = ['Public'] - // #swagger.summary = 'List wiki tags' - /* #swagger.responses[200] = { description: 'Wiki tags', content: { "application/json": { schema: { type: "array", items: { type: "string" } } } } } */ - siteMode, - ctrl.getWikiTags, -) -publicRouter.get( - '/wiki/:slug', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Get a single published wiki page' - // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Wiki page slug.' } - /* #swagger.responses[200] = { description: 'The wiki page', content: { "application/json": { schema: { $ref: "#/components/schemas/WikiPage" } } } } */ - /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - siteMode, - ctrl.getWikiPage, -) - -// ── CMS pages (block-based) ──────────────────────────────────────────── -// Preview is registered before /pages/:slug and is NOT site-mode gated, so a -// draft-preview link keeps working during maintenance. The token itself is the -// access control. -publicRouter.get( - '/pages/:id/preview/:token', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Render a page from a draft-preview token' - // #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'Page id.' } - // #swagger.parameters['token'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Preview token from POST /admin/pages/:id/preview.' } - /* #swagger.responses[200] = { description: 'The page (any status)', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - /* #swagger.responses[404] = { description: 'Token invalid/expired or page missing', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - ctrl.getPagePreview, -) -publicRouter.get( - '/pages/:slug', - // #swagger.tags = ['Public'] - // #swagger.summary = 'Get a published CMS page by slug' - // #swagger.description = 'Drafts 404 for the public; staff sessions see drafts. Gated by site mode.' - // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Page slug.' } - /* #swagger.responses[200] = { description: 'The page', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ - siteMode, - ctrl.getPage, -) - -// ── Shard live data (uo-link) ────────────────────────────────────────────── -// Token-free, same-origin reads. The status/feed/economy/idoc endpoints read -// the site's own ingested data; /char round-trips the live shard (cached). Not -// site-mode gated — shard status is useful even during site maintenance. -publicRouter.get( - '/shard/status', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Shard connection state, online count and latest economy' - /* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardStatus" } } } } */ - shard.getStatus, -) -publicRouter.get( - '/shard/feed', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Recent notable shard events (from the ingested log)' - // #swagger.parameters['kind'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Filter to a single event kind, e.g. vendor.sale.' } - // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max rows (default 100, max 1000).' } - /* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */ - query('kind').optional({ values: 'falsy' }).isString().isLength({ max: 48 }), - query('limit').optional().isInt({ min: 1, max: 1000 }), - validate, - shard.getFeed, -) -publicRouter.get( - '/shard/economy', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Gold-supply time series (oldest → newest)' - // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max samples (default 100, max 1000).' } - /* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEconomyPoint" } } } } } */ - query('limit').optional().isInt({ min: 1, max: 1000 }), - validate, - shard.getEconomy, -) -publicRouter.get( - '/shard/online', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Staff online now (linked staff accounts; location is admin/moderator-only)' - /* #swagger.responses[200] = { description: 'Online players', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardOnlinePlayer" } } } } } */ - shard.getOnline, -) -publicRouter.get( - '/shard/idoc', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Houses currently in danger (IDOC)' - /* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ - shard.getIdoc, -) -publicRouter.get( - '/shard/champs', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Current champion-spawn board (all categories)' - // #swagger.description = 'The live board of every champion / mini-champ / sea-boss spawn. Update in place via the champ.update / champ.remove frames on /shard/stream.' - /* #swagger.responses[200] = { description: 'Champion spawns, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ - shard.getChamps, -) -publicRouter.get( - '/shard/guilds', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Current guild board (rosters, alliances, leaders)' - // #swagger.description = 'The live board of every guild. Update in place via the guild.update / guild.remove / guild.join frames on /shard/stream.' - /* #swagger.responses[200] = { description: 'Guilds, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ - shard.getGuilds, -) -publicRouter.get( - '/shard/governors', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Current town-governor board (City Loyalty)' - // #swagger.description = 'One entry per city with its governor and election phase. Empty if the shard does not run the City Loyalty system. Live via city.update on /shard/stream.' - /* #swagger.responses[200] = { description: 'Cities, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ - shard.getGovernors, -) -publicRouter.get( - '/shard/governors/:city/history', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Governor term history for a city' - // #swagger.parameters['city'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'City name, e.g. Britain.' } - // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max terms (default 100, max 500).' } - /* #swagger.responses[200] = { description: 'Terms, newest first', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ - param('city').isString().isLength({ min: 1, max: 40 }), - query('limit').optional().isInt({ min: 1, max: 500 }), - validate, - shard.getGovernorHistory, -) -publicRouter.get( - '/shard/presence', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Online population aggregate (count + per-facet + per-region)' - // #swagger.description = 'The latest presence.online snapshot powering the "Players Online" widget. Live via presence.online on /shard/stream.' - /* #swagger.responses[200] = { description: 'Population snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ - shard.getPresence, -) -publicRouter.get( - '/shard/houses', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'House registry (owner, co-owners, price, decay)' - // #swagger.description = 'Every house seen via the house.update registry feed. `price` is the placement value, not a for-sale flag. Live via house.update / house.remove on /shard/stream.' - /* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ - shard.getHouses, -) -publicRouter.get( - '/shard/stream', - // #swagger.tags = ['Public · Shard'] - // #swagger.summary = 'Live shard event stream (Server-Sent Events, public/safe kinds)' - // #swagger.description = 'text/event-stream of curated live events. Sensitive kinds (staff audit, cheat detection, login attempts, IPs) are NOT sent on this channel.' - /* #swagger.responses[200] = { description: 'An SSE stream (Content-Type: text/event-stream).' } */ - shard.stream, -) - -module.exports = publicRouter diff --git a/server/src/router/v1/public/shard.router.js b/server/src/router/v1/public/shard.router.js new file mode 100644 index 0000000..372a51a --- /dev/null +++ b/server/src/router/v1/public/shard.router.js @@ -0,0 +1,128 @@ +// Public · Shard — token-free, same-origin reads of the live shard. The +// status/feed/economy/idoc/champs/guilds/governors/presence/houses endpoints read +// the site's own ingested data; nothing here round-trips the sidecar per request. +// +// Mounted at /api/v1/public/shard by public/index.js. Deliberately NOT site-mode +// gated — shard status is useful (and wanted) while the site itself is in +// maintenance. +// +// **GET /shard/stream stays anonymous.** It is consumed by logged-out browser +// visitors *and* by the Android ShardStreamClient, neither of which sends an +// Authorization header; adding requireAuth here blacks out the public live boards +// on web and mobile. The sensitive kinds (staff audit, cheat detection, login +// attempts, IPs) are withheld by the allowlist in utils/shardBroadcast.js, not by +// a route gate — that allowlist split is the security boundary, not this file. + +const express = require('express') +const { param, query } = require('express-validator') + +const shard = require('./shard.controller') +const validate = require('../../../middleware/validate') + +const shardRouter = express.Router() + +shardRouter.get( + '/status', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Shard connection state, online count and latest economy' + /* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardStatus" } } } } */ + shard.getStatus, +) +shardRouter.get( + '/feed', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Recent notable shard events (from the ingested log)' + // #swagger.parameters['kind'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Filter to a single event kind, e.g. vendor.sale.' } + // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max rows (default 100, max 1000).' } + /* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */ + query('kind').optional({ values: 'falsy' }).isString().isLength({ max: 48 }), + query('limit').optional().isInt({ min: 1, max: 1000 }), + validate, + shard.getFeed, +) +shardRouter.get( + '/economy', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Gold-supply time series (oldest → newest)' + // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max samples (default 100, max 1000).' } + /* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEconomyPoint" } } } } } */ + query('limit').optional().isInt({ min: 1, max: 1000 }), + validate, + shard.getEconomy, +) +shardRouter.get( + '/online', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Staff online now (linked staff accounts; location is admin/moderator-only)' + /* #swagger.responses[200] = { description: 'Online players', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardOnlinePlayer" } } } } } */ + shard.getOnline, +) +shardRouter.get( + '/idoc', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Houses currently in danger (IDOC)' + /* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ + shard.getIdoc, +) +shardRouter.get( + '/champs', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Current champion-spawn board (all categories)' + // #swagger.description = 'The live board of every champion / mini-champ / sea-boss spawn. Update in place via the champ.update / champ.remove frames on /shard/stream.' + /* #swagger.responses[200] = { description: 'Champion spawns, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ + shard.getChamps, +) +shardRouter.get( + '/guilds', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Current guild board (rosters, alliances, leaders)' + // #swagger.description = 'The live board of every guild. Update in place via the guild.update / guild.remove / guild.join frames on /shard/stream.' + /* #swagger.responses[200] = { description: 'Guilds, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ + shard.getGuilds, +) +shardRouter.get( + '/governors', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Current town-governor board (City Loyalty)' + // #swagger.description = 'One entry per city with its governor and election phase. Empty if the shard does not run the City Loyalty system. Live via city.update on /shard/stream.' + /* #swagger.responses[200] = { description: 'Cities, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ + shard.getGovernors, +) +shardRouter.get( + '/governors/:city/history', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Governor term history for a city' + // #swagger.parameters['city'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'City name, e.g. Britain.' } + // #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max terms (default 100, max 500).' } + /* #swagger.responses[200] = { description: 'Terms, newest first', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */ + param('city').isString().isLength({ min: 1, max: 40 }), + query('limit').optional().isInt({ min: 1, max: 500 }), + validate, + shard.getGovernorHistory, +) +shardRouter.get( + '/presence', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Online population aggregate (count + per-facet + per-region)' + // #swagger.description = 'The latest presence.online snapshot powering the "Players Online" widget. Live via presence.online on /shard/stream.' + /* #swagger.responses[200] = { description: 'Population snapshot', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */ + shard.getPresence, +) +shardRouter.get( + '/houses', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'House registry (owner, co-owners, price, decay)' + // #swagger.description = 'Every house seen via the house.update registry feed. `price` is the placement value, not a for-sale flag. Live via house.update / house.remove on /shard/stream.' + /* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */ + shard.getHouses, +) +shardRouter.get( + '/stream', + // #swagger.tags = ['Public · Shard'] + // #swagger.summary = 'Live shard event stream (Server-Sent Events, public/safe kinds)' + // #swagger.description = 'text/event-stream of curated live events. Sensitive kinds (staff audit, cheat detection, login attempts, IPs) are NOT sent on this channel.' + /* #swagger.responses[200] = { description: 'An SSE stream (Content-Type: text/event-stream).' } */ + shard.stream, +) + +module.exports = shardRouter diff --git a/server/src/router/v1/public/site.router.js b/server/src/router/v1/public/site.router.js new file mode 100644 index 0000000..fc699b8 --- /dev/null +++ b/server/src/router/v1/public/site.router.js @@ -0,0 +1,67 @@ +// Public · Site — the four group-root singletons: settings, status, version and +// contact. None of them owns a path segment that could become a prefix, so this +// is the public group's counterpart to admin/dashboard.router.js: one file for +// the routes that own no prefix, mounted at the group root. +// +// It is safe at the root **only** because this file declares no router-level +// middleware. A bare `use(gate)` in a root-mounted router runs for every request +// passing through toward another mount — it would gate /public/wiki and +// /public/shard/* too. Keep gates on the individual routes here (siteMode is +// deliberately absent: settings/status/version/contact must answer during +// maintenance so the client can render the maintenance page and let a visitor +// get in touch). +// +// Mounted at /api/v1/public by public/index.js. + +const express = require('express') +const { body } = require('express-validator') + +const ctrl = require('./public.controller') +const validate = require('../../../middleware/validate') +const { contactLimiter } = require('../../../middleware/rateLimit') + +const siteRouter = express.Router() + +siteRouter.get( + '/settings', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Public site settings + branding' + // #swagger.description = 'Whitelisted, non-sensitive settings plus the per-shard brand block (name/colors/logo/hero/favicon) a client themes itself from, and derived registration / game-account-signup availability flags.' + /* #swagger.responses[200] = { description: 'Public settings + branding', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicSettings" } } } } */ + ctrl.getSettings, +) +siteRouter.get( + '/status', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Site mode / status' + // #swagger.description = 'Current site mode (live or maintenance) so the client can show the maintenance page, plus a version block (service id + API/server versions) for a client first-run probe and version-mismatch guard.' + /* #swagger.responses[200] = { description: 'Site status', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicStatus" } } } } */ + ctrl.getStatus, +) +siteRouter.get( + '/version', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Backend identity + version' + // #swagger.description = 'Lightweight, DB-free descriptor of this backend: a stable service id and the API/server versions. A client uses it to recognize a Runic Gateway backend on first-run and to run a version-mismatch guard. Doubles as a cheap liveness check.' + /* #swagger.responses[200] = { description: 'Backend version', content: { "application/json": { schema: { $ref: "#/components/schemas/PublicVersion" } } } } */ + ctrl.getVersion, +) +siteRouter.post( + '/contact', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Send a contact message' + // #swagger.description = 'Emails the site owner (or falls back to a mailto). Rate limited.' + /* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ContactRequest" } } } } */ + /* #swagger.responses[200] = { description: 'Message sent', 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 messages (rate limited)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + /* #swagger.responses[502] = { description: 'Mail delivery failed', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + contactLimiter, + body('message').isString().trim().notEmpty().isLength({ max: 5000 }), + body('email').optional({ values: 'falsy' }).isEmail(), + body('name').optional({ values: 'falsy' }).isString().trim().isLength({ max: 100 }), + validate, + ctrl.contact, +) + +module.exports = siteRouter diff --git a/server/src/router/v1/public/wiki.router.js b/server/src/router/v1/public/wiki.router.js new file mode 100644 index 0000000..2e330b9 --- /dev/null +++ b/server/src/router/v1/public/wiki.router.js @@ -0,0 +1,56 @@ +// Public · Wiki — the published wiki: the page list, categories, tags and a +// single page by slug. Read-only counterpart of admin/wiki.router.js. +// +// Mounted at /api/v1/public/wiki by public/index.js. No group gate; `siteMode` +// is applied per route. +// +// Declaration order is load-bearing: `/categories` and `/tags` are literal paths +// and MUST stay ahead of `/:slug`, or GET /public/wiki/categories dispatches as a +// wiki page whose slug is "categories". routes.manifest.json sorts its entries +// and therefore cannot catch a reordering — the same trap admin/wiki.router.js +// carries (see docs/website/API_V2_PLAN.md § PR 3). + +const express = require('express') + +const ctrl = require('./public.controller') +const siteMode = require('../../../middleware/siteMode') + +const wikiRouter = express.Router() + +wikiRouter.get( + '/', + // #swagger.tags = ['Public'] + // #swagger.summary = 'List published wiki pages' + /* #swagger.responses[200] = { description: 'Published wiki pages', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiPage" } } } } } */ + siteMode, + ctrl.getWikiList, +) +// Static paths must precede the :slug route so they aren't captured as a slug. +wikiRouter.get( + '/categories', + // #swagger.tags = ['Public'] + // #swagger.summary = 'List wiki categories' + /* #swagger.responses[200] = { description: 'Wiki categories', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/WikiCategory" } } } } } */ + siteMode, + ctrl.getWikiCategories, +) +wikiRouter.get( + '/tags', + // #swagger.tags = ['Public'] + // #swagger.summary = 'List wiki tags' + /* #swagger.responses[200] = { description: 'Wiki tags', content: { "application/json": { schema: { type: "array", items: { type: "string" } } } } } */ + siteMode, + ctrl.getWikiTags, +) +wikiRouter.get( + '/:slug', + // #swagger.tags = ['Public'] + // #swagger.summary = 'Get a single published wiki page' + // #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Wiki page slug.' } + /* #swagger.responses[200] = { description: 'The wiki page', content: { "application/json": { schema: { $ref: "#/components/schemas/WikiPage" } } } } */ + /* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */ + siteMode, + ctrl.getWikiPage, +) + +module.exports = wikiRouter diff --git a/server/src/router/v1/v1.router.js b/server/src/router/v1/v1.router.js index 98e30dc..d354db9 100644 --- a/server/src/router/v1/v1.router.js +++ b/server/src/router/v1/v1.router.js @@ -2,10 +2,10 @@ const express = require('express') const v1Router = express.Router() -const authRouter = require('./auth/auth.routes') -const publicRouter = require('./public/public.routes') +const authRouter = require('./auth') +const publicRouter = require('./public') const adminRouter = require('./admin') -const playerRouter = require('./player/player.routes') +const playerRouter = require('./player') v1Router.use('/auth', authRouter) v1Router.use('/public', publicRouter) diff --git a/server/src/utils/auth.js b/server/src/utils/auth.js index e5f85a5..29c5c2c 100644 --- a/server/src/utils/auth.js +++ b/server/src/utils/auth.js @@ -2,7 +2,7 @@ // // The auth logic now lives in server/src/auth/ (token primitives, the session // service, and session middleware). This module stays as a thin facade so every -// existing import site (auth.routes, the admin/* routers, siteMode, auth.controller) +// existing import site (the auth/* and admin/* routers, siteMode, auth.controller) // keeps working with the exact same names and behavior — nothing else in the // codebase needs to change. New code should prefer requiring ../auth/* directly. diff --git a/server/test/authMe.test.js b/server/test/authMe.test.js index ed7a819..6783799 100644 --- a/server/test/authMe.test.js +++ b/server/test/authMe.test.js @@ -8,7 +8,7 @@ const { test, after } = require('node:test') const assert = require('node:assert/strict') const { startApp } = require('./_helper') -const authRouter = require('../src/router/v1/auth/auth.routes') +const authRouter = require('../src/router/v1/auth') const db = require('../src/utils/db') after(() => db.close()) diff --git a/server/test/notificationsRoutes.test.js b/server/test/notificationsRoutes.test.js index a1b2b34..adff96e 100644 --- a/server/test/notificationsRoutes.test.js +++ b/server/test/notificationsRoutes.test.js @@ -7,7 +7,7 @@ const { test, after } = require('node:test') const assert = require('node:assert/strict') const { startApp } = require('./_helper') -const authRouter = require('../src/router/v1/auth/auth.routes') +const authRouter = require('../src/router/v1/auth') const db = require('../src/utils/db') after(() => db.close()) diff --git a/server/test/playerRouteAccess.test.js b/server/test/playerRouteAccess.test.js index 5066d9a..6e451f2 100644 --- a/server/test/playerRouteAccess.test.js +++ b/server/test/playerRouteAccess.test.js @@ -8,7 +8,7 @@ const { test, after, afterEach } = require('node:test') const assert = require('node:assert/strict') const { startApp } = require('./_helper') -const playerRouter = require('../src/router/v1/player/player.routes') +const playerRouter = require('../src/router/v1/player') const sessionService = require('../src/auth/session.service') const users = require('../src/model/users/users.model') const shardLinks = require('../src/model/shardLinks/shardLinks.model') diff --git a/server/test/publicVersion.test.js b/server/test/publicVersion.test.js index 49a88bf..e2927b0 100644 --- a/server/test/publicVersion.test.js +++ b/server/test/publicVersion.test.js @@ -9,7 +9,7 @@ const assert = require('node:assert/strict') const { startApp } = require('./_helper') const version = require('../src/config/version') -const publicRouter = require('../src/router/v1/public/public.routes') +const publicRouter = require('../src/router/v1/public') const db = require('../src/utils/db') after(() => db.close())