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.
This commit is contained in:
2026-09-29 17:49:15 -07:00
parent 2e8d699a36
commit 0f53a159f0
5 changed files with 223 additions and 17 deletions

View File

@@ -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

View File

@@ -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.

View File

@@ -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.

View File

@@ -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:

187
server.js
View File

@@ -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 = `<!doctype html><html><body style="font:14px system-ui;padding:2rem">
<h1>SDE Meeting Toolkit</h1>
<ul>
<li><a href="/tools/field-problem-workshop.html">Field Problem Workshop</a></li>
<li><a href="/tools/scope-lock-meeting-suite.html">Scope Lock Meeting Suite</a></li>
</ul>
</body></html>`;
const index = `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project SDE | Meeting Toolkit</title>
<style>
:root{
--bg:#f4f4f4; --layer:#ffffff; --layer-hover:#e8e8e8;
--border:#e0e0e0; --border-strong:#8d8d8d;
--text:#161616; --text-secondary:#525252; --text-helper:#6f6f6f;
--interactive:#0f62fe; --interactive-hover:#0353e9;
--focus:#0f62fe;
}
*{box-sizing:border-box; margin:0; padding:0;}
body{
font-family:'IBM Plex Sans','Segoe UI',system-ui,-apple-system,sans-serif;
background:var(--bg); color:var(--text); font-size:16px; line-height:1.4;
}
a{color:inherit; text-decoration:none;}
a:focus-visible, button:focus-visible{outline:2px solid var(--focus); outline-offset:1px;}
header{
background:var(--text); color:#fff; padding:0 24px;
display:flex; align-items:center; gap:24px; height:56px;
}
header .brand{font-size:15px; letter-spacing:.16px;}
header .brand strong{font-weight:600;}
header .brand span{color:#c6c6c6; font-weight:400;}
main{max-width:900px; margin:0 auto; padding:56px 24px;}
main h1{font-size:28px; font-weight:600; margin-bottom:8px;}
main p.lead{color:var(--text-secondary); font-size:16px; margin-bottom:40px; max-width:640px;}
.cards{display:grid; grid-template-columns:repeat(auto-fit, minmax(280px, 1fr)); gap:16px;}
.card{
display:block; background:var(--layer); border:1px solid var(--border);
border-top:3px solid var(--interactive); padding:24px; transition:background .1s;
}
.card:hover{background:var(--layer-hover);}
.card h2{font-size:18px; font-weight:600; margin-bottom:8px;}
.card p{color:var(--text-secondary); font-size:14px; margin-bottom:16px;}
.card .go{color:var(--interactive); font-size:14px; font-weight:600;}
.card:hover .go{color:var(--interactive-hover);}
footer{max-width:900px; margin:0 auto; padding:0 24px 40px; color:var(--text-helper); font-size:13px;}
</style>
</head>
<body>
<header>
<div class="brand"><strong>Project SDE</strong> <span>| Meeting Toolkit</span></div>
</header>
<main>
<h1>Meeting Toolkit</h1>
<p class="lead">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.</p>
<div class="cards">
<a class="card" href="/tools/field-problem-workshop.html">
<h2>Field Problem Workshop</h2>
<p>Cluster raw problems, write breadcrumbs, and promote root causes into tracked outcomes.</p>
<span class="go">Open the workshop &rarr;</span>
</a>
<a class="card" href="/tools/scope-lock-meeting-suite.html">
<h2>Scope Lock Meeting Suite</h2>
<p>Sort scope into MVP, Later, Out, or Parking Lot, rank priorities, and log decisions.</p>
<span class="go">Open the suite &rarr;</span>
</a>
</div>
</main>
<footer>Project SDE &middot; Innovation Team</footer>
</body>
</html>`;
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).');
});