Commit Graph

118 Commits

Author SHA1 Message Date
60d2121b83 Fix bot container inheriting site PORT/LOG_FILE from shared .env
The app and bot services share env_file: .env, so the site's PORT=3000
leaked into the bot container. The bot code is `PORT || 4100`, so it
bound 3000 instead of 4100 — and the server's BOT_INTERNAL_URL
(http://bot:4100) then couldn't reach it, surfacing as "failed to fetch"
on the admin Discord Bot page even though the bot was otherwise healthy
and connected to Discord.

Pin PORT: 4100 on the bot service so it binds where the server expects.
Also override LOG_FILE: bot.log so the bot doesn't inherit the site's
LOG_FILE and write into app.log, keeping the two logs distinct.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-05 00:39:16 -05:00
20d3fbf594 Merge pull request 'Audit and fix Swagger/OpenAPI accuracy; regenerate served spec' (#40) from docs/swagger-audit into main
Reviewed-on: UOM/website#40
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-05 04:33:36 +00:00
f8db61025b Audit and fix Swagger/OpenAPI accuracy; regenerate served spec
The route-level annotations were 100% present, but the committed/served
spec (swagger-output.json) was stale and several response schemas had
drifted from the controllers. This aligns the docs with actual behavior
and regenerates the spec.

Served spec was stale (64/67 operations). Regenerating picks up three
routes that were added after the last generation:
  - POST /api/v1/auth/sso/totp
  - GET  /api/v1/admin/discord-bot/config
  - PUT  /api/v1/admin/discord-bot/config
plus a stale /auth/logout summary.

Response-shape corrections (annotation now matches controller output):
  - Mutation endpoints do NOT return the generic { message } envelope.
    Deletes echo { id } / { slug }; toggles return { deleted },
    { unlinked }, { totp_enabled }, or { ip, removed }. Documented as-is
    via new DeletedId/DeletedSlug/DeletedFlag/UnlinkedFlag/TotpState/
    UnbanResult components. (The API is intentionally inconsistent here;
    recorded rather than normalized — see follow-up note.)
  - POST /account/totp/setup: otpauth_url -> otpauthUrl (TotpSetup)
  - PUT  /admin/site-mode: { mode } -> { site_mode, changed_at, changed_by }
  - GET  /account: full User -> AccountStatus (id/username/role/totp_enabled)
  - GET  /account/identities: add linked_at (LinkedIdentity)
  - GET  /public/status: add status_message (PublicStatus)
  - POST /auth/sso/totp: user is SafeUser, not full User
  - GET  /dashboard: description/shape corrected (posts+users, no wiki)

Schema completeness:
  - Provider (public discovery): { id, name, icon, loginUrl, priority },
    not { id, name, kind }
  - ProviderConfig: add hasSecret, builtin, health (ProviderHealth)
  - Post: add excerpt, author_id, published_at
  - MobileTokenResponse.expiresIn: duration string ("15m"), not integer

Config: declare the Admin · Discord Bot tag (was used but undeclared).

Auth model and the internal/external boundary were verified correct and
left unchanged: cookie + bearer are both accepted on session routes (dual
security annotations are accurate), and /internal/* runs on a separate
listener already excluded from the scan.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-04 22:51:16 -05:00
2067028070 Merge pull request 'Enforce TOTP second factor on SSO login (#31)' (#39) from bugfix/sso-totp-bypass-31 into main
Reviewed-on: UOM/website#39
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-05 03:34:49 +00:00
03e62b56ad Enforce TOTP second factor on SSO login (#31)
SSO login minted a full session immediately, ignoring the account's
totp_enabled flag — so a 2FA admin with a linked Google/Discord/OIDC
identity could sign in without their authenticator code, silently
downgrading the account to single-factor (the strength of the IdP login).
The local password flow already gates on needsTotp(); SSO did not.

Wire SSO through the same staged-TOTP gate:

- ssoState: createTotpPending/verifyTotpPending + a short-lived httpOnly
  sso_totp cookie. The pending token carries stage:'totp' (session
  validation rejects it) + kind:'sso_totp' (scoped to the SSO endpoint)
  plus the resolved context (userId, provider, authMethod, returnTo).
- sso.controller: finishLogin now stages the challenge and redirects to
  /admin/login?sso_totp=1 instead of creating a session when the account
  has TOTP on. New finishSsoTotp verifies the code (backoff + bot-scoring
  on failure, mirroring loginTotp) and only then mints the session.
- sso.routes: POST /auth/sso/totp behind the same backoff/slow/limiter
  stack and code validation as the local TOTP endpoint.
- client: AdminLogin detects ?sso_totp=1 and completes over fetch via
  api.ssoLoginTotp; the challenge never touches the URL or JS.

Keeps the second factor httpOnly throughout, consistent with the SSO tx
cookie. 12 new tests; full suite 106/106.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-04 22:17:35 -05:00
15cf8ea286 Merge pull request 'Fix SSO flow-token / session type confusion (#32)' (#38) from bugfix/sso-token-confusion-32 into main
Reviewed-on: UOM/website#38
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-05 02:56:31 +00:00
5f62eccdd8 Fix SSO flow-token / session type confusion (#32)
sessionFromDecoded validated sessions with a blocklist — it rejected a
token only when `decoded.stage` was present (the TOTP challenge). Because
every JWT is signed with the same JWT_SECRET and distinguished only by
claims, the SSO transaction cookie (sso_tx, which carries kind:'sso_tx'
and id:'sso' but no stage) passed validation and was accepted as a bogus
{ userId:'sso' } session.

requireAuth's DB re-load blocked protected admin routes, but non-DB
identity checks were fooled — notably siteMode's maintenance-preview
bypass, which trusts any truthy getUserFromRequest. An attacker could
start an SSO flow to obtain an sso_tx cookie and replay it as the auth
cookie / Bearer token to bypass the maintenance gate. The broader risk
was latent: any future code path trusting attachSession/getUserFromRequest
without a DB round-trip inherited an auth bypass.

Make session validation positively typed: real sessions are now stamped
with typ:'session' (createSession + mintMobileTokens), and
sessionFromDecoded accepts a token only when that marker is present. As
belt-and-suspenders it also rejects any token carrying a non-session
marker (stage || kind). Flow/challenge tokens are never stamped, so they
can no longer be mistaken for sessions.

Note: existing web cookie sessions predating this change lack the typ
claim and will be rejected once — users re-login. Mobile clients recover
automatically on next refresh.

Adds regression tests: the sso_tx flow token and a bare identity token
are both rejected by validateSession / decodeIdentity / getUserFromRequest.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:54:58 -05:00
e8a54d9ff7 Merge pull request 'Implement web session/token revocation (#30)' (#37) from bugfix/session-revocation-30 into main
Reviewed-on: UOM/website#37
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-05 02:08:15 +00:00
933206a1b8 Implement web session/token revocation (#30)
Web sessions were stateless JWTs with no server-side store: the revocation
hooks in session.service were stubs that only logged. As a result web logout
was client-side only (a copied cookie stayed valid until natural JWT expiry)
and a password change never invalidated existing sessions. The mobile bearer
flow already had revocable, DB-stored tokens; this brings the web/cookie flow
to parity.

Two-layer revocation, both enforced in requireAuth (which already loads the
fresh user row each request):

- Per-session denylist: new `revoked_sessions` table keyed on the JWT `jti`
  (already minted per session). A single logout adds this session's jti;
  rows self-expire at the token's own exp and are pruned on boot. New model
  `revokedSessions` mirrors the `mobileSessions` db/model split.
- Per-user cutoff: new `users.tokens_valid_after` column. A password change
  (and the new `invalidateSessions` helper) bumps it to NOW(); any token whose
  iat is at or before the cutoff is rejected. The comparison is inclusive so a
  token minted in the same wall-clock second as the change is still revoked.

Wiring:
- session.service: revokeSession / invalidateSession / invalidateAllUserSessions
  now delegate to the stores; sessions carry `expiresAt` (JWT exp) so logout can
  set a self-pruning denylist row.
- /logout gains best-effort attachSession so the controller can revoke this
  session's jti and log auth.logout; stays a no-op for anonymous callers.
- users.model.update bumps the cutoff whenever the password hash is rotated.
- schema.sql: revoked_sessions table + tokens_valid_after column, added to the
  CREATE and to the idempotent migration block (ensureSchema on boot).

Verified end-to-end against the local dev DB: a captured cookie is rejected
after logout, and an existing session is rejected after a password change while
re-login with the new password succeeds. Full server test suite green (96).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-04 21:06:50 -05:00
1cfb79f5ae Merge pull request 'Isolate internal bot-config route from the public listener (#33)' (#36) from bugfix/internal-token-endpoint-33 into main
Reviewed-on: UOM/website#36
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-04 22:50:05 +00:00
3ef84b41ef Merge branch 'main' into bugfix/internal-token-endpoint-33 2026-07-04 22:49:33 +00:00
5df943095d Isolate internal bot-config route from the public listener (#33)
The GET /internal/bot-config route returns the DECRYPTED Discord bot
token and was mounted on the same Express app / port 3000 that Pangolin
proxies publicly. Its only guard was the BOT_INTERNAL_KEY shared secret,
and .env.example shipped a placeholder default — so a forwarded path or a
weak/unrotated key would expose the plaintext token to the internet.

Move server<->bot internal traffic onto its own listener and fail fast on
a weak key:

- Add server/src/internalApp.js: a standalone Express app mounting
  requireInternalKey + /internal (and a no-secret /health), mirroring the
  bot's unpublished port-4100 pattern.
- server.js starts a second listener on INTERNAL_PORT (default 3001),
  closed on graceful shutdown.
- Remove the /internal mount from the public v1.router; the public app now
  404s /api/v1/internal/bot-config even with a valid key.
- Fail fast: new utils/botInternalKey.js rejects an empty, placeholder, or
  <16-char BOT_INTERNAL_KEY — fatal in production (exit 1), warning in dev.
- docker-compose: bot SITE_INTERNAL_URL -> app:3001/internal/bot-config;
  document that INTERNAL_PORT stays unpublished.
- .env.example (root/server/bot): document INTERNAL_PORT, the fail-fast
  behavior, and a defense-in-depth Pangolin deny rule for /api/v1/internal.

Tests: add requireInternalKey.test.js and botInternalKey.test.js
(node --test: 93 pass).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-04 17:35:07 -05:00
bb5cc68c54 Merge pull request 'Add Discord bot: moderation, filters, scheduling, roles, invites, site integration' (#29) from feature/discord-bot into main
Reviewed-on: UOM/website#29
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-04 21:19:41 +00:00
17c1eb07e8 Merge branch 'main' into feature/discord-bot 2026-07-04 21:19:23 +00:00
7a21cc636c Add Discord bot (moderation, filters, scheduling, roles, invites, site integration)
Standalone bot/ service (its own package.json/Dockerfile) managed entirely
through a new admin-only Discord Bot panel — token stored encrypted in the
DB and pushed to the bot process in-memory, never an env var. Built in
phases, each independently verified against a live Discord guild:

- Bot skeleton: gateway connection, internal shared-secret API, self-heals
  on its own restart by pulling config from the site
- Moderation core: /ban /kick /mute /warn /warnings + mod-log channel
- Word/invite/spam filtering with leetspeak-resistant normalization and a
  staff role/channel allowlist
- Scheduled messages: recurring (cron) and one-off channel posts
- Role assignment: button role menus, auto-role on join, temp roles,
  bulk role ops
- Auto-rotating primary invite with an audit log
- Site integration: news-publish -> Discord announce webhook, manual
  /announce, read-only /wiki search

Also fixes a pre-existing bug in both DB pools (server + bot): the mariadb
driver defaulted to timezone 'local', silently mis-serializing bound Date
params by the host's local offset instead of the DB's UTC session.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:54:41 -05:00
ad7aebb3ba Merge pull request 'Hero editor: fullscreen landing, remove two-card row, quick links into hero' (#28) from feature/hero-fullscreen-landing into main
Reviewed-on: UOM/website#28
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-04 02:55:50 +00:00
0318d6fe9f Make hero the full landing page; move quick links into hero editor
Remove the two-card destination row and the below-hero quick-links nav
from the portal so the hero fills the viewport with nothing rendered
after it. The 5 quick links (News, Screenshots, Five on Friday,
Monthly Newsletter, About) move into the hero editor as a third
buttons element in defaultLayout(), reusing the existing buttons
element type so they stay fully editable with no schema changes.

Also drop overflow:hidden on the hero section: on mobile, 100vh can
compute smaller than window.innerHeight, and with overflow hidden the
wrapped quick-links text was getting clipped at the bottom edge.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 21:49:45 -05:00
433e02d3ef Merge pull request 'Add Swagger/OpenAPI API docs (swagger-ui + swagger-autogen)' (#27) from feature/swagger-docs into main
Reviewed-on: UOM/website#27
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 20:30:14 +00:00
a1f0675577 Add Swagger/OpenAPI API docs (swagger-ui + swagger-autogen)
Generate an OpenAPI 3.0 spec from route annotations and serve it with
Swagger UI so the full REST API is browsable and testable.

- Add swagger-ui-express (runtime) and swagger-autogen (dev) deps, plus
  an `npm run swagger` script.
- server/swagger/swagger.js: generator config with API metadata, servers,
  14 tag groups, cookie + bearer security schemes, and 28 reusable
  component schemas. Follows the Express mount chain from src/app.js so
  generated paths are fully-qualified (/api/v1/...).
- Annotate every route (auth, mobile, sso, public, admin, health) with
  #swagger tags/summaries/parameters/request bodies/security and the
  actual response codes each handler returns (400/401/403/404/409/429/
  302/502, multipart uploads).
- Serve Swagger UI at /api/docs and the raw spec at /api/docs.json,
  guarded so a missing spec disables docs instead of crashing.
- Commit the generated swagger-output.json so docs work with no build
  step; swagger-autogen stays dev-only and is not needed at runtime.
- README: new "API documentation (Swagger)" section plus tech-stack and
  project-structure entries.

Covers 51 paths / 64 operations. Existing test suite (83) still passes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:28:13 -05:00
d7fb274bad Merge pull request 'Hero editor: scale text-block fonts with the resize handle (#25)' (#26) from enhancement/hero into main
Reviewed-on: UOM/website#26
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 20:01:50 +00:00
6af85c30b6 Hero editor: scale text block fonts with the resize handle (#25)
The text_block corner handle previously only changed the wrap width, so
the font size never tracked the box — making the editor un-WYSIWYG and
awkward to tune. Now dragging the handle scales every line's font
proportionally with the box, acting as a zoom that preserves the
h1/h2/p size ratios and keeps each line's manually-set baseline.

- Add scaleFontSize(): numeric px sizes (floored at 6px) and simple
  rem/em/px strings scale by the box ratio; responsive clamp()/vw
  strings are left untouched so the default hero stays fluid.
- Snapshot the box width + lines at drag start so scaling is computed
  against the origin (no rounding drift mid-drag).
- Update the canvas hint to note the handle scales text.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:59:15 -05:00
86e44a94a2 Merge pull request 'Add session abstraction, mobile bearer auth, and pluggable SSO (Google/Discord/OIDC)' (#24) from feature/auth-session-abstraction into main
Reviewed-on: UOM/website#24
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 15:35:44 +00:00
31b31c3a17 Add session abstraction, mobile bearer auth, and pluggable SSO
Refactor authentication into a provider-agnostic session layer and build
two new auth surfaces on top of it, without changing local password/TOTP
behavior. Every flow now issues sessions through
sessionService.createSession(user, authMethod).

Part 1 — Session abstraction (backward-compatible refactor):
- New server/src/auth/: token.js (JWT/cookie primitives), session.service.js
  (create/validate/partial-TOTP/revoke), session.middleware.js
  (attachSession/requireAuth/requireRole). utils/auth.js is now a thin
  compat facade so existing imports are unchanged.

Part 2 — Mobile bearer auth (additive):
- /api/v1/auth/mobile/{login,refresh,logout}: short-lived access JWT +
  long-lived refresh token, stored hashed and rotated on use, in a new
  mobile_refresh_tokens table. Reuses web bot-scoring/backoff; single-request
  TOTP. token.signToken gains a backward-compatible expiresIn option.

Part 3 — Pluggable SSO (Google, Discord, generic OIDC):
- OAuth2Provider base + built-in Google/Discord (fixed endpoints) + generic
  OIDC, a registry with health/validation, PKCE+CSRF transaction state, and
  discovery (GET /auth/providers), start/link/callback routes.
- Link-only policy: SSO signs in only to an already-linked account; external
  identities are never auto-provisioned. Client secrets encrypted at rest
  (AES-256-GCM, utils/secretBox.js). Admin CRUD (/admin/auth/providers) and
  account linking (/admin/account/identities). New auth_providers +
  user_identities tables.

Frontend:
- Login page renders provider buttons from /auth/providers (inline SVG icons,
  graceful with zero providers). New Authentication admin view
  (Local/Google/Discord/Custom). Account page linked-accounts section.

Tests: 83 passing (session, mobile, providers, registry, secretBox, ssoState,
ssoCallback) — all DB-free via fetch mocks + model stubs. README + .env.example
updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 10:31:29 -05:00
8fa34ca68e Merge pull request 'Add Bot Activity admin panel: banned-IP view + recent events + emergency unban' (#23) from feature/bot-activity-admin into main
Reviewed-on: UOM/website#23
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 08:29:54 +00:00
870971fc12 Add Bot Activity admin panel: banned-IP view + recent events + emergency unban
Expose the botScore middleware's in-memory scoring/ban state to admins.
Previously state lived only in the store Map with no persistence or API — the
only visibility was tailing container logs.

- botScore: bounded ring buffer (300) recording scan/login-fail/honeypot and
  ban events (most-recent-first); listState() snapshot of all scored IPs;
  unban() to clear a single IP.
- New admin-only endpoints GET /admin/bot-activity and
  POST /admin/bot-activity/unban (RBAC admin gate, IP validated). Unban is
  activity-logged with the admin username.
- Bot Activity tab: currently-banned table with Unban, plus a recent-events
  feed, following the existing admin table patterns.
- Tests for the buffer, listState, and unban (guard lets an unbanned IP back
  through). README updated.

Read + emergency-unban only — no ban-add or weight-editing surface. Buffer is
in-memory, matching the store; not persisted.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 02:31:25 -05:00
58852a5078 Merge pull request 'Update README for today's security hardening and 2FA work' (#22) from docs/readme-refresh into main
Reviewed-on: UOM/website#22
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 06:09:53 +00:00
cd678e75ce Merge branch 'main' into docs/readme-refresh 2026-07-03 06:09:41 +00:00
a82f839c61 Update README for today's security hardening and 2FA work
Several changes merged today were not reflected in the README. Bring it
back in sync with main:

- Security section: rewrite into Session/authorization, Login hardening,
  Uploads/input, and Platform groups — documents DB re-validation of the
  JWT per request (#12), role-based authorization (#10), optional TOTP
  2FA (#9), login throttling + per-IP backoff, honeypot, bot-scoring/IP
  ban, and mimetype-derived upload extensions (#11) + username
  uniqueness checks on update (#13).
- Environment variables: add TRUST_PROXY, DEBUG_TRUST_PROXY, TOTP_ISSUER,
  TOTP_CHALLENGE_TTL, and UPLOAD_DIR.
- Routes/API tables: add /admin/account and the account/totp endpoints
  plus the login/totp second-factor step.
- Tech stack + project structure: note TOTP (speakeasy/qrcode), the
  loginProtection/botScore middleware, the totp util, and the Account view.

Docs-only; no code changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:07:22 -05:00
05933f8d94 Merge pull request 'Fail fast when JWT_SECRET is missing in production (closes #14)' (#21) from fix/jwt-secret-fail-fast into main
Reviewed-on: UOM/website#21
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 05:58:16 +00:00
073c010d72 Fail fast when JWT_SECRET is missing in production (#14)
auth.js previously only logged a warning when JWT_SECRET was unset and
then continued to boot. With no secret, jwt.sign/jwt.verify cannot
produce or validate a usable token, so every login silently fails while
the server appears healthy — and booting a production instance without a
configured secret is a safety hazard.

Resolve the secret through resolveJwtSecret():
  - production (NODE_ENV=production): throw, so the process refuses to
    start without a real secret instead of running unusable.
  - dev/other: fall back to a known insecure secret so local login keeps
    working, with a loud warning to set JWT_SECRET before deploying.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 00:55:07 -05:00
f305019c54 Merge pull request 'Make the hero Moon image configurable (src/alt), backwards-compatible' (#20) from feature/configurable-moon-image into main
Reviewed-on: UOM/website#20
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 04:45:24 +00:00
7e8ffeee6f Raise hero upload soft-warning from 1 MB to 5 MB
The "may slow the page" prompt is only a client-side nudge — the server
hard-limits uploads at 8 MB. 1 MB was arbitrarily low and nagged on
perfectly normal hero images. Bump to 5 MB (still well under the hard cap)
and pull the threshold + message into a single tooLargeToUpload() helper so
the background, moon, and image upload paths stay in sync.
2026-07-02 23:42:23 -05:00
6ab3e47d38 Make the hero Moon image configurable via props.src
The Moon stays a dedicated, first-class hero element — only its image
source becomes configurable. Adds optional src/alt props alongside the
existing size/glow.

- HeroElement: the moon renders props.src when present, else falls back to
  the default /assets/img/hero-moon.png. Size, glow, and animation are
  unchanged. alt is now props.alt (default '', same as before).
- HeroEditor MoonPanel: adds an image upload (reusing the existing shared
  api.admin.upload workflow, same as the image/background panels) that sets
  props.src, an alt-text field, and a "Use default" reset. Size/glow
  controls unchanged.

Fully backwards compatible: existing layouts with only size/glow and no
src render exactly as today via the fallback. No DB, API, or hero-JSON
changes; no migration.
2026-07-02 23:38:03 -05:00
ea46b5d346 Merge pull request 'Admin login hardening: RBAC-safe controls, optional TOTP, bot-scoring + IP ban (closes #9)' (#19) from feature/admin-login-hardening into main
Reviewed-on: UOM/website#19
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 04:27:50 +00:00
d38c98ad9e Harden admin login: RBAC-safe controls, 2FA, bot-scoring, rate limits (#9)
Adds a layered set of protections around the admin login and the app edge.

Trust proxy (server/src/utils/trustProxy.js)
- Configurable via TRUST_PROXY; pin to the newt agent ("ptero") LAN IP so
  X-Forwarded-For is trusted ONLY from that peer. A blanket "true" is
  rejected (coerced to 1) to prevent XFF spoofing that would dodge every
  IP-based control. DEBUG_TRUST_PROXY logs peer/XFF/req.ip to re-verify the
  proxy IP without a redeploy. Documents the Omada static-reservation
  assumption.

Login throttling (server/src/middleware/loginProtection.js, rateLimit.js)
- express-slow-down progressive delay + the existing hard rate cap + a
  separate per-IP exponential backoff that persists across the rate window.
  All failures return one generic message (no user/pass disclosure).

Honeypot (login form + auth.controller)
- Hidden, plausibly-named field ("company"); a filled value fails
  generically and is scored as an unambiguous bot.

Optional per-user TOTP 2FA (speakeasy/qrcode)
- totp_secret/totp_enabled columns (+ idempotent migration). Self-service
  Account page: enroll via QR, confirm a code to enable, code-gated disable.
- Login is two-step for enrolled users: after the password, a short-lived
  signed challenge (stage:'totp', not a session) is required before the
  real session is issued.

Bot / scanner scoring + IP ban (server/src/middleware/botScore.js)
- Weighted CMS-scanner paths (this app uses none). Junk paths 404 FIRST,
  unconditionally — independent of score/ban state, so a scanner rotating
  through fresh Cloudflare IPs gets no free pass. /wp-admin/install.php is
  the top-weighted near-1-hit ban (worst offender in prod logs). Per-IP
  score with quiet-period decay temp-bans an IP from ALL routes once past a
  (deliberately low) threshold, to protect /admin from credential stuffing.
  Failed logins and honeypot hits feed the same score.
- Periodic sweep evicts stale, unbanned, quiet entries so the in-memory
  store can't grow unbounded; the interval is unref'd and cleared on
  graceful shutdown.

Tests: node --test suite (40) covering trust-proxy parsing + live req.ip
(incl. pinned-IP), rate limiter + exponential backoff, honeypot rejection,
TOTP verify (enabled/disabled) + challenge-isn't-a-session, bot-score
threshold/decay/ban + junk-404-independence + install.php + store sweep.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:22:35 -05:00
ad9c556c9a Merge pull request 'Derive uploaded file extension from mimetype, not originalname (fixes #11)' (#18) from fix/upload-extension-xss into main
Reviewed-on: UOM/website#18
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 02:44:28 +00:00
e84835a0fb Derive uploaded file extension from mimetype, not originalname (#11)
The multer filename kept path.extname(file.originalname), while the
fileFilter only checked the spoofable client-supplied mimetype. An
attacker could send Content-Type: image/png with originalname x.html,
landing an .html file in /uploads that express.static serves as
text/html — same-origin stored XSS.

- Store the extension from a whitelist keyed by the accepted mimetype
  (MIME_EXT), never from originalname. The fileFilter uses the same map
  as its single source of truth, so only mimetypes with a safe mapped
  extension pass.
- Use crypto.randomBytes for the random filename component.
- Serve /uploads with an explicit X-Content-Type-Options: nosniff
  (defense in depth alongside helmet's global setting).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 21:41:56 -05:00
d89cc7e691 Merge pull request 'Validate and uniqueness-check username on user update (fixes #13)' (#17) from fix/username-validation-update into main
Reviewed-on: UOM/website#17
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 02:39:42 +00:00
43db509293 Validate and uniqueness-check username on user update (#13)
PUT /admin/users/:id validated password and role but not username, even
though updateUser writes req.body.username. A blank/too-short username
could be saved, and a duplicate hit the DB unique constraint and
surfaced as an opaque 500.

- Route: add the same validator used on create,
  body('username').optional().isString().trim().isLength({min:3,max:32}).
  The trim sanitizer also collapses whitespace-only input so it fails
  the min-length check.
- Controller: when the username is changing, pre-check for another user
  with that name and return 409 instead of letting the DB throw a 500.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 21:38:16 -05:00
6b04aa72c1 Merge pull request 'Re-validate JWT against the DB in isLoggedIn (fixes #12)' (#16) from fix/stale-jwt-revalidation into main
Reviewed-on: UOM/website#16
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 02:32:07 +00:00
81318ae264 Merge branch 'main' into fix/stale-jwt-revalidation 2026-07-03 02:31:59 +00:00
853224b578 Merge pull request 'Enforce role-based authorization on admin-only routes (fixes #10)' (#15) from fix/role-authorization into main
Reviewed-on: UOM/website#15
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-07-03 02:31:06 +00:00
8ad18140d0 Re-validate JWT against the DB in isLoggedIn (#12)
isLoggedIn trusted id and role straight from the JWT and never
re-checked the database, so a demoted admin kept their old role and a
deleted user kept a working session until the token expired (up to
JWT_EXPIRES_IN). This also undercut the "last admin" guards.

isLoggedIn now loads the user from the DB by the token's id on every
request: a missing user returns 401 (deleted), and req.user carries the
fresh DB row so the current role is always used downstream.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 21:16:43 -05:00
20d7150ab4 Enforce role-based authorization on admin-only routes (#10)
isLoggedIn only verified a valid JWT, so an authenticated editor could
call any admin endpoint (create/promote/delete users, flip site mode,
change settings). Add a requireRole middleware factory and gate the
sensitive routes with admin-only:

- PUT  /site-mode
- GET/PUT /settings
- all /users/* (list/create/update/delete)

Content routes (posts, wiki, categories, tags, uploads, dashboard,
activity) remain available to editors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 21:15:12 -05:00
52c74db825 Merge pull request 'Fix #6: larger RTE toolbar buttons + bigger, both-axis-scrolling editor' (#8) from fix/rte-editor-sizing into main
Reviewed-on: UOM/website#8
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-06-30 18:49:22 +00:00
4c16040373 Fix #6: larger RTE toolbar buttons + bigger, both-axis-scrolling editor
The shared rich-text editor's toolbar buttons (especially the link and
image icons) were too small, and the editor body was short and only
scrolled vertically. These styles are shared by every RichTextEditor on
the site, so the fix applies to the wiki editor, the post editor, and any
future ones.

- Toolbar buttons: 30px -> 38px, base font 0.85rem -> 1rem, with roomier
  toolbar padding and gap.
- Icon (glyph) buttons (Link, Insert image, wiki-page, Quote, Divider,
  Undo, Redo) bumped to 1.25rem so they read clearly.
- Editor body: max-height 460px -> min(640px, 65vh); ProseMirror
  min-height 220px -> 320px.
- Body now scrolls both ways: overflow-y:auto -> overflow:auto (wide
  images, code blocks, tables can scroll sideways).
- Nudged the internal-link popover offset to match the taller toolbar.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:47:15 -05:00
103007e49a Merge pull request 'RTE Posts upgrade: TipTap rich-text editing + sanitization for posts' (#7) from rte-posts-upgrade into main
Reviewed-on: UOM/website#7
Reviewed-by: Colby Whitlock <whitlocktech@gmail.com>
2026-06-30 18:34:01 +00:00
438d252c05 Merge branch 'main' into rte-posts-upgrade 2026-06-30 18:33:16 +00:00
a5a8c1930c RTE Posts upgrade: TipTap editor + sanitization for posts
Extend the wiki's RichTextEditor to the Posts editor and close the
stored-XSS gap on public post bodies.

- RichTextEditor: add `variant` prop — `full` (wiki), `post` (no
  internal wiki-page link picker), `minimal` (image-only, for
  Screenshots captions). Toolbar sections rendered conditionally.
- PostEditor: replace the body textarea with a lazy-loaded
  RichTextEditor in Suspense; variant chosen by category
  (minimal for screenshots, post otherwise).
- posts.model: sanitize body via shared cleanBody on create/update,
  treat an empty TipTap `<p></p>` as null, and auto-derive the
  excerpt from the body (max 280 chars) when left blank.
- sanitizeHtml util: add deriveExcerpt() helper.
- FiveOnFriday / NewsletterIssue: wrap dangerouslySetInnerHTML with
  DOMPurify.sanitize() as defense-in-depth on render.

No schema or dependency changes. Verified end-to-end against the
local stack: 24/24 API assertions and a full UI round-trip across
all four post categories.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 13:14:54 -05:00
fecd28238d Merge pull request 'hero-feature' (#4) from hero-feature into main
Reviewed-on: UOM/website#4
2026-06-28 14:22:41 +00:00