From 0f53a159f091482a2cb25e68f01197e1ecf7da34 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Tue, 29 Sep 2026 17:49:15 -0700 Subject: [PATCH] Fix 502 on AI draft button; restyle landing page - docker-compose.yml: keep the container on both 'proxy' and 'default' networks. 'proxy' alone has no internet route, which broke the outbound call to api.anthropic.com once NPM routing was added. - server.js: replace the plain landing page with one matching both tools' existing design (dark header, IBM Plex Sans, card layout). - Update CHANGELOG. --- .env.example | 22 +++++- CHANGELOG.md | 6 ++ DOCKER_TESTING.md | 12 +++ docker-compose.yml | 13 ++++ server.js | 187 +++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 223 insertions(+), 17 deletions(-) diff --git a/.env.example b/.env.example index fe6d4c1..1a50edb 100644 --- a/.env.example +++ b/.env.example @@ -16,10 +16,30 @@ ANTHROPIC_API_KEY=your-anthropic-api-key-here APP_USERS= # Legacy single shared login. Only used if APP_USERS is blank. Everyone who -# logs in with this pair shares one identity and one token quota. +# logs in with this pair shares one identity and one token quota. Prefer +# APP_USERS instead: a shared login means the audit log below can't tell +# which real person made a given request. APP_USERNAME= APP_PASSWORD= +# Login lockout (brute-force protection). After this many failed logins from +# one address within the window, that address is locked out for the lockout +# period, even with the correct password. Only applies when a login is +# required (APP_USERS or APP_USERNAME/APP_PASSWORD is set). Defaults: 10 +# failed attempts per 10 minutes locks out for 15 minutes. +LOGIN_ATTEMPT_MAX=10 +LOGIN_ATTEMPT_WINDOW_MS=600000 +LOGIN_LOCKOUT_MS=900000 + +# Sign-in audit log. One line per login event (timestamp, source address, +# username, success or failure) - never the password. Failures are logged +# individually; successes are logged at most once per address+user within +# SIGNIN_LOG_DEBOUNCE_MS, since Basic Auth resends credentials on every +# request and logging each one would flood the file. Persists across +# restarts if AUTH_LOG_FILE's folder is a mounted volume. +AUTH_LOG_FILE=./data/auth-log.jsonl +SIGNIN_LOG_DEBOUNCE_MS=1800000 + # Optional. Caps AI draft calls per source IP, to catch a runaway script # fast. Defaults: 20 requests per 5 minutes. RATE_LIMIT_MAX=20 diff --git a/CHANGELOG.md b/CHANGELOG.md index e837fc0..0f1bfc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project are logged here, newest first. This file starts from the point the toolkit was handed off and set up in this repo. +## 2026-09-29 + +- Fixed: the AI draft button returned a 502 ("Could not reach the Anthropic API") once the container moved onto the `proxy` network. Cause: Compose only attaches a container to networks explicitly listed for it, so joining `proxy` alone dropped the container from the network that had internet access. `proxy` reaches other containers but not the public internet. `docker-compose.yml` now lists both `proxy` and `default`, so the container keeps its internet route for the outbound call to `api.anthropic.com` while staying reachable from Nginx Proxy Manager by name. +- Changed: replaced the plain, unstyled landing page (`server.js`) with one matching both tools' existing design (dark header bar, IBM Plex Sans, the same card/border/interactive-blue styling), with a short description of each tool and a link into it. +- Milestone: `MVP.controls.dev` is live through Nginx Proxy Manager, SSL issued, `*.controls.dev` already covered by an existing wildcard DNS record (no new DNS record was needed). + ## 2026-09-23 - Added: joined the toolkit's Docker container to the `proxy` network, the same shared network Nginx Proxy Manager already uses to reach Work Package Suite's internal nginx container by name. Confirmed by reading NPM's own generated config for `wp.controls.dev` (`/data/nginx/proxy_host/11.conf`), which forwards to a container named `nginx_webserver`, not an IP address. `docker-compose.yml` now declares `proxy` as an external network and attaches the container to it. diff --git a/DOCKER_TESTING.md b/DOCKER_TESTING.md index 31e154b..839920e 100644 --- a/DOCKER_TESTING.md +++ b/DOCKER_TESTING.md @@ -92,6 +92,18 @@ Use a personal or trial API key here, not the company-billed key. Keep the compa 2. Confirm the next click returns a rate-limit message instead of a normal draft or a silent failure. 3. Wait for the time window to pass, then confirm the button works again. +## Step 8b: Test the login lockout and audit log + +1. Open a new private or incognito browser window, or use `curl -u tester:wrongpass http://localhost:5173/`. +2. Enter the wrong password enough times to exceed `LOGIN_ATTEMPT_MAX` (default 10) within the window. +3. Confirm the next request — even with the correct password — is refused with a 429 and a lockout message, not a login prompt. +4. Wait past `LOGIN_LOCKOUT_MS` (default 15 minutes; lower it in `.env` for a faster test), then confirm the correct password works again. +5. Run this command to view the sign-in audit log: + ``` + cat data/auth-log.jsonl + ``` +6. Confirm it lists one line per failed attempt (username tried, address, timestamp) and one line for the eventual success. No passwords appear in the file. + ## Step 9 (optional): Test the per-user token quota Skip this step for a normal test run. The quota ships off by default; this is only for confirming the feature still works if you turn it back on. diff --git a/docker-compose.yml b/docker-compose.yml index 6d5284b..d374eeb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,6 +5,13 @@ # Package Suite's own internal nginx container. "proxy" must already exist # on the host; it is not created here (external: true), since NPM's own # stack owns it. +# +# Also stays on "default" (Compose's own auto-created network for this +# project). "proxy" is scoped to proxy-to-backend traffic only and has no +# route to the public internet, so without "default" too, the AI draft +# button's outbound call to api.anthropic.com fails (502: "Could not reach +# the Anthropic API"). Landing page and tool pages still work without it, +# since those never leave the container, which is why this was easy to miss. services: sde-meeting-toolkit: build: . @@ -20,6 +27,11 @@ services: - APP_PASSWORD=${APP_PASSWORD:-} - RATE_LIMIT_MAX=${RATE_LIMIT_MAX:-20} - RATE_LIMIT_WINDOW_MS=${RATE_LIMIT_WINDOW_MS:-300000} + - LOGIN_ATTEMPT_MAX=${LOGIN_ATTEMPT_MAX:-10} + - LOGIN_ATTEMPT_WINDOW_MS=${LOGIN_ATTEMPT_WINDOW_MS:-600000} + - LOGIN_LOCKOUT_MS=${LOGIN_LOCKOUT_MS:-900000} + - AUTH_LOG_FILE=${AUTH_LOG_FILE:-./data/auth-log.jsonl} + - SIGNIN_LOG_DEBOUNCE_MS=${SIGNIN_LOG_DEBOUNCE_MS:-1800000} - TOKEN_LIMIT_PER_USER=${TOKEN_LIMIT_PER_USER:-0} - TOKEN_USAGE_FILE=${TOKEN_USAGE_FILE:-./data/token-usage.json} volumes: @@ -28,6 +40,7 @@ services: - ./data:/app/data networks: - proxy + - default networks: proxy: diff --git a/server.js b/server.js index 5d769f6..e8001e5 100644 --- a/server.js +++ b/server.js @@ -80,22 +80,26 @@ function loadUserMap() { const USER_MAP = loadUserMap(); const AUTH_REQUIRED = Object.keys(USER_MAP).length > 0; -// Returns the identified username on success, or null on failure. +// Returns { ok, user, attempted }. "user" is the identified name on success +// (null on failure); "attempted" is the name that was tried, even on +// failure, so a failed attempt can still be logged without ever logging +// the password itself. function checkBasicAuth(req) { - if (!AUTH_REQUIRED) return 'local'; + if (!AUTH_REQUIRED) return { ok: true, user: 'local', attempted: null }; const header = req.headers['authorization'] || ''; - if (!header.startsWith('Basic ')) return null; + if (!header.startsWith('Basic ')) return { ok: false, user: null, attempted: null }; let decoded; try { decoded = Buffer.from(header.slice(6), 'base64').toString('utf8'); } catch (err) { - return null; + return { ok: false, user: null, attempted: null }; } const idx = decoded.indexOf(':'); - if (idx === -1) return null; + if (idx === -1) return { ok: false, user: null, attempted: null }; const name = decoded.slice(0, idx); const pass = decoded.slice(idx + 1); - return USER_MAP[name] === pass ? name : null; + const ok = USER_MAP[name] === pass; + return { ok, user: ok ? name : null, attempted: name }; } function requireAuth(res) { res.writeHead(401, { @@ -105,6 +109,76 @@ function requireAuth(res) { res.end('Authentication required.'); } +/* ===== Login lockout (brute-force protection) ===== + * Separate from the AI-proxy rate limiter below: this protects the login + * gate itself. Basic Auth has no built-in throttling, so without this a + * script could try passwords as fast as the network allows. + * + * After LOGIN_ATTEMPT_MAX failed logins from one IP within + * LOGIN_ATTEMPT_WINDOW_MS, that IP is locked out for LOGIN_LOCKOUT_MS - + * every request refused with 429, even with the correct password, until + * the lockout expires. In-memory only: resets if the process restarts. */ +const LOGIN_ATTEMPT_MAX = parseInt(process.env.LOGIN_ATTEMPT_MAX || '10', 10); +const LOGIN_ATTEMPT_WINDOW_MS = parseInt(process.env.LOGIN_ATTEMPT_WINDOW_MS || String(10 * 60 * 1000), 10); +const LOGIN_LOCKOUT_MS = parseInt(process.env.LOGIN_LOCKOUT_MS || String(15 * 60 * 1000), 10); +const loginFailures = new Map(); // ip -> [timestamps] +const loginLockouts = new Map(); // ip -> lockout-expires-at (ms epoch) + +function isLockedOut(ip) { + const until = loginLockouts.get(ip); + if (!until) return false; + if (Date.now() < until) return true; + loginLockouts.delete(ip); + loginFailures.delete(ip); + return false; +} +function recordLoginFailure(ip) { + const now = Date.now(); + const hits = (loginFailures.get(ip) || []).filter((t) => now - t < LOGIN_ATTEMPT_WINDOW_MS); + hits.push(now); + loginFailures.set(ip, hits); + if (hits.length > LOGIN_ATTEMPT_MAX) { + loginLockouts.set(ip, now + LOGIN_LOCKOUT_MS); + } +} +function clearLoginFailures(ip) { + loginFailures.delete(ip); +} + +/* ===== Sign-in audit log ===== + * Appends one JSON line per login event to AUTH_LOG_FILE: timestamp, + * source IP, the username, and the result. Never logs the password. + * Durable across restarts, same as the token usage file below, as long as + * AUTH_LOG_FILE's folder is a mounted volume. + * + * Basic Auth resends credentials on every request (every page, every + * asset, every AI call), not just once at "login" - logging every one of + * those would flood this file with noise. Failures are logged individually + * (that is what makes brute-force attempts visible). Successes are + * debounced per (ip, user) to roughly one line per session, not one per + * request. */ +const AUTH_LOG_FILE = process.env.AUTH_LOG_FILE || path.join(ROOT, 'data', 'auth-log.jsonl'); +const SIGNIN_LOG_DEBOUNCE_MS = parseInt(process.env.SIGNIN_LOG_DEBOUNCE_MS || String(30 * 60 * 1000), 10); +const lastLoggedSignin = new Map(); // "ip|user" -> timestamp + +function logAuthEvent(ip, user, result) { + const line = JSON.stringify({ ts: new Date().toISOString(), ip, user: user || null, result }) + '\n'; + try { + fs.mkdirSync(path.dirname(AUTH_LOG_FILE), { recursive: true }); + fs.appendFileSync(AUTH_LOG_FILE, line); + } catch (err) { + console.error('Could not write auth log:', err.message); + } +} +function shouldLogSuccess(ip, user) { + const key = ip + '|' + user; + const now = Date.now(); + const last = lastLoggedSignin.get(key) || 0; + if (now - last < SIGNIN_LOG_DEBOUNCE_MS) return false; + lastLoggedSignin.set(key, now); + return true; +} + /* ===== Rate limiting for the AI proxy ===== * Caps AI draft calls per source IP, independent of the token quota below. * This catches a runaway script quickly, before it burns through a whole @@ -250,13 +324,73 @@ function proxyToClaude(req, res, user) { function serveStatic(req, res) { const urlPath = decodeURIComponent(req.url.split('?')[0]); if (urlPath === '/') { - const index = ` -

SDE Meeting Toolkit

- - `; + const index = ` + + + + +Project SDE | Meeting Toolkit + + + +
+
Project SDE | Meeting Toolkit
+
+
+

Meeting Toolkit

+

Two tools for the Micron Pilot. Cluster and name problems in the Field Problem Workshop, then lock scope decisions in the Scope Lock Meeting Suite. Clusters tagged with a candidate solution can be sent straight to the Scope Boundary Board.

+ +
+ + +`; res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end(index); return; @@ -280,13 +414,30 @@ function serveStatic(req, res) { } const server = http.createServer((req, res) => { - const user = checkBasicAuth(req); - if (!user) { + const ip = req.socket.remoteAddress || 'unknown'; + + if (AUTH_REQUIRED && isLockedOut(ip)) { + res.writeHead(429, { 'Content-Type': 'text/plain' }); + res.end('Too many failed logins from this address. Try again later.'); + return; + } + + const auth = checkBasicAuth(req); + if (!auth.ok) { + if (AUTH_REQUIRED) { + recordLoginFailure(ip); + logAuthEvent(ip, auth.attempted, 'failure'); + } requireAuth(res); return; } + const user = auth.user; + if (AUTH_REQUIRED) { + clearLoginFailures(ip); + if (shouldLogSuccess(ip, user)) logAuthEvent(ip, user, 'success'); + } + if (req.method === 'POST' && req.url === '/api/claude') { - const ip = req.socket.remoteAddress || 'unknown'; if (isRateLimited(ip)) { sendJson(res, 429, { error: `Rate limit reached (${RATE_LIMIT_MAX} AI drafts per ${Math.round(RATE_LIMIT_WINDOW_MS / 60000)} min). Wait a bit and try again.` }); return; @@ -319,5 +470,9 @@ server.listen(PORT, () => { console.log(process.env.ANTHROPIC_API_KEY ? 'ANTHROPIC_API_KEY loaded: AI draft button is live.' : 'No ANTHROPIC_API_KEY found: AI draft button will return an error until you add one to .env.'); } console.log(AUTH_REQUIRED ? `Login required: ${Object.keys(USER_MAP).length} named user(s) configured.` : 'No login required: no APP_USERS or APP_USERNAME/APP_PASSWORD are set.'); + if (AUTH_REQUIRED) { + console.log(`Login lockout: ${LOGIN_ATTEMPT_MAX} failed attempts per ${Math.round(LOGIN_ATTEMPT_WINDOW_MS / 60000)} min locks an address out for ${Math.round(LOGIN_LOCKOUT_MS / 60000)} min.`); + console.log(`Sign-in audit log: ${AUTH_LOG_FILE}`); + } console.log(TOKEN_LIMIT_ENABLED ? `Per-user daily token quota: ${TOKEN_LIMIT_PER_USER} tokens. Usage file: ${TOKEN_USAGE_FILE}` : 'No per-user token quota: TOKEN_LIMIT_PER_USER is unset or 0 (unlimited, feature on the back burner).'); });