1 Commits

Author SHA1 Message Date
481b5a536b Add security hardening: helmet, CORS allowlist, body limit, ID validation
- Install and configure helmet with basic CSP in app.js
- Restrict CORS to ALLOWED_ORIGIN env var (default localhost:5173)
- Add express.json 1mb body size limit to prevent memory exhaustion
- Add parseInt+isNaN validation for all :id route params in bills.js
  and financing.js (GET/PUT/DELETE/:id and PATCH financing-payments/:id)
- Extend bills.routes.test.js and financing.routes.test.js with ID
  validation tests (non-numeric IDs → HTTP 400)

Nightshift-Task: security-footgun
Nightshift-Ref: https://github.com/marcus/nightshift

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-20 02:35:00 -04:00
9 changed files with 119 additions and 218 deletions

View File

@@ -77,12 +77,6 @@ cd client && npm run test:watch
- Export pure functions (validators, formatters, etc.) for direct testing - Export pure functions (validators, formatters, etc.) for direct testing
- Run `npm test` in both `server/` and `client/` before committing - Run `npm test` in both `server/` and `client/` before committing
**Doc drift check:**
```bash
node scripts/doc-drift.js
```
Scans `CLAUDE.md` and `PRD.md` for verifiable code references (file paths, API routes, component names) and cross-checks each against the filesystem and source tree. Prints a PASS/FAIL report with doc name and line number. Exits non-zero on any failure — suitable for CI gating.
## Application Structure ## Application Structure
The default route `/` renders the paycheck-centric main view (`client/src/pages/PaycheckView.jsx`). It shows the current month's two paychecks side-by-side with bills, paid status, one-time expenses, and remaining balance. Month navigation (prev/next) fetches data via `GET /api/paychecks?year=&month=`. The default route `/` renders the paycheck-centric main view (`client/src/pages/PaycheckView.jsx`). It shows the current month's two paychecks side-by-side with bills, paid status, one-time expenses, and remaining balance. Month navigation (prev/next) fetches data via `GET /api/paychecks?year=&month=`.
@@ -100,3 +94,5 @@ The default route `/` renders the paycheck-centric main view (`client/src/pages/
**Financing:** `GET/POST /api/financing`, `PUT/DELETE /api/financing/:id`, `PATCH /api/financing-payments/:id/paid`. Plans track a total amount, payoff due date, and `start_date`. Payment per period is auto-calculated as `(remaining balance) / (remaining periods)`. Split plans (`assigned_paycheck = null`) divide each period's payment across both paychecks. Plans auto-close when fully paid. Financing payments are included in the paycheck remaining balance. `start_date` prevents a plan from appearing on paycheck months before it was created — both virtual previews and `generate` respect this guard. **Financing:** `GET/POST /api/financing`, `PUT/DELETE /api/financing/:id`, `PATCH /api/financing-payments/:id/paid`. Plans track a total amount, payoff due date, and `start_date`. Payment per period is auto-calculated as `(remaining balance) / (remaining periods)`. Split plans (`assigned_paycheck = null`) divide each period's payment across both paychecks. Plans auto-close when fully paid. Financing payments are included in the paycheck remaining balance. `start_date` prevents a plan from appearing on paycheck months before it was created — both virtual previews and `generate` respect this guard.
**Migrations:** SQL files in `db/migrations/` are applied in filename order on server startup. Add new migrations as `00N_description.sql` — they run once and are tracked in the `migrations` table. **Migrations:** SQL files in `db/migrations/` are applied in filename order on server startup. Add new migrations as `00N_description.sql` — they run once and are tracked in the `migrations` table.
**Security hardening:** `server/src/app.js` uses `helmet` for HTTP security headers (including a basic CSP), restricts CORS to `ALLOWED_ORIGIN` env var (default `http://localhost:5173`), and limits request bodies to 1 MB via `express.json({ limit: '1mb' })`. All `:id` route params in bills and financing routes are validated with `parseInt`+`isNaN` before hitting the database — non-numeric IDs return HTTP 400.

View File

@@ -1,203 +0,0 @@
#!/usr/bin/env node
/**
* doc-drift.js — detects documentation drift by cross-checking verifiable
* code references in CLAUDE.md and PRD.md against the filesystem and source tree.
*
* Usage: node scripts/doc-drift.js
* Exits non-zero if any drift is found.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const ROOT = path.resolve(__dirname, '..');
const DOCS = ['CLAUDE.md', 'PRD.md'].map(f => path.join(ROOT, f));
// ── Result tracking ──────────────────────────────────────────────────────────
const results = [];
function record(doc, line, kind, ref, pass, reason) {
results.push({ doc: path.basename(doc), line, kind, ref, pass, reason });
}
// ── Extraction helpers ───────────────────────────────────────────────────────
/** Extract all backtick spans from a line (may be multiple). */
function backtickSpans(line) {
const spans = [];
const re = /`([^`]+)`/g;
let m;
while ((m = re.exec(line)) !== null) spans.push(m[1]);
return spans;
}
/** Return true if a span looks like a file/dir path we can verify. */
function isFilePath(span) {
// Must contain a slash and start with a recognisable project prefix.
return (
/[/\\]/.test(span) &&
/^(client|server|db|scripts|docker-compose)/.test(span) &&
// Exclude shell commands, URLs, SQL snippets, etc.
!/\s/.test(span) &&
!span.includes('=') &&
!span.startsWith('http')
);
}
/** Return true if a span looks like a component/page reference (*.jsx). */
function isJsxRef(span) {
return /\w+\.jsx$/.test(span) && !/[/]/.test(span); // bare name, no path
}
/** Extract HTTP API route patterns like `GET /api/paychecks`. */
function extractApiRoutes(line) {
const routes = [];
const re = /\b(GET|POST|PUT|DELETE|PATCH)\s+(\/api\/[^\s,`'")\]]+)/g;
let m;
while ((m = re.exec(line)) !== null) routes.push({ method: m[1], path: m[2] });
return routes;
}
// ── Verification helpers ─────────────────────────────────────────────────────
function fileExists(relPath) {
return fs.existsSync(path.join(ROOT, relPath));
}
/**
* For API routes: grep server/src/routes/ for the route path string.
* We look for the path fragment (everything after /api) as a string literal.
*/
function apiRouteExists(routePath) {
// Strip query-string placeholders like ?year=&month=
const clean = routePath.replace(/\?.*$/, '').replace(/:id/g, ':id');
// Build a grep-friendly pattern: look for the path minus leading /api
const fragment = clean.replace(/^\/api/, '');
try {
const out = execSync(
`grep -rE --include="*.js" -l "${clean}|${fragment}" "${path.join(ROOT, 'server/src/routes')}"`,
{ stdio: ['pipe', 'pipe', 'pipe'] }
).toString().trim();
return out.length > 0;
} catch {
return false;
}
}
/**
* For bare *.jsx component names: check that a file with that name exists
* somewhere under client/src/.
*/
function jsxComponentExists(name) {
try {
const out = execSync(
`find "${path.join(ROOT, 'client/src')}" -name "${name}" -type f`,
{ stdio: ['pipe', 'pipe', 'pipe'] }
).toString().trim();
return out.length > 0;
} catch {
return false;
}
}
// ── Main ─────────────────────────────────────────────────────────────────────
for (const docPath of DOCS) {
if (!fs.existsSync(docPath)) {
console.error(`WARN: doc not found: ${docPath}`);
continue;
}
const lines = fs.readFileSync(docPath, 'utf8').split('\n');
lines.forEach((rawLine, idx) => {
const lineNo = idx + 1;
// 1. Backtick file paths
for (const span of backtickSpans(rawLine)) {
if (isFilePath(span)) {
const exists = fileExists(span);
record(
docPath,
lineNo,
'file-path',
span,
exists,
exists ? 'found on filesystem' : `not found: ${span}`
);
continue;
}
if (isJsxRef(span)) {
const exists = jsxComponentExists(span);
record(
docPath,
lineNo,
'component',
span,
exists,
exists ? 'found under client/src' : `no file named ${span} in client/src`
);
}
}
// 2. API routes (inside or outside backticks)
for (const { method, path: routePath } of extractApiRoutes(rawLine)) {
const ref = `${method} ${routePath}`;
const exists = apiRouteExists(routePath);
record(
docPath,
lineNo,
'api-route',
ref,
exists,
exists ? 'found in server/src/routes' : `route not found in server/src/routes`
);
}
});
}
// ── Report ───────────────────────────────────────────────────────────────────
const padDoc = Math.max(...results.map(r => r.doc.length), 9);
const padKind = Math.max(...results.map(r => r.kind.length), 9);
const padRef = Math.min(60, Math.max(...results.map(r => r.ref.length), 10));
const header = [
'STATUS'.padEnd(6),
'DOC'.padEnd(padDoc),
'LINE'.padStart(4),
'KIND'.padEnd(padKind),
'REFERENCE',
].join(' ');
console.log('\n' + header);
console.log('─'.repeat(header.length + 10));
let failures = 0;
for (const r of results) {
const status = r.pass ? 'PASS' : 'FAIL';
const ref = r.ref.length > padRef ? r.ref.slice(0, padRef - 1) + '…' : r.ref;
const line = [
(r.pass ? '\x1b[32m' : '\x1b[31m') + status.padEnd(6) + '\x1b[0m',
r.doc.padEnd(padDoc),
String(r.line).padStart(4),
r.kind.padEnd(padKind),
ref,
].join(' ');
console.log(line);
if (!r.pass) {
console.log(` \x1b[33m↳ ${r.reason}\x1b[0m`);
failures++;
}
}
console.log('─'.repeat(header.length + 10));
console.log(`\n${results.length} references checked — ${failures} failure(s)\n`);
process.exit(failures > 0 ? 1 : 0);

View File

@@ -11,6 +11,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
"helmet": "^8.1.0",
"pg": "^8.11.5" "pg": "^8.11.5"
}, },
"devDependencies": { "devDependencies": {
@@ -1282,6 +1283,15 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/helmet": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz",
"integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/http-errors": { "node_modules/http-errors": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",

View File

@@ -12,6 +12,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
"helmet": "^8.1.0",
"pg": "^8.11.5" "pg": "^8.11.5"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -131,3 +131,35 @@ describe('PATCH /api/bills/:id/toggle', () => {
expect(res.body).toEqual(toggled); expect(res.body).toEqual(toggled);
}); });
}); });
describe('ID validation — bills routes', () => {
beforeEach(() => {
db.pool.query.mockReset();
});
it('GET /api/bills/:id returns 400 for non-numeric id', async () => {
const res = await request(app).get('/api/bills/abc');
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
it('PUT /api/bills/:id returns 400 for non-numeric id', async () => {
const res = await request(app)
.put('/api/bills/abc')
.send({ name: 'X', amount: 10, due_day: 1, assigned_paycheck: 1 });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
it('DELETE /api/bills/:id returns 400 for non-numeric id', async () => {
const res = await request(app).delete('/api/bills/abc');
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
it('PATCH /api/bills/:id/toggle returns 400 for non-numeric id', async () => {
const res = await request(app).patch('/api/bills/abc/toggle');
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
});

View File

@@ -338,4 +338,39 @@ describe('PATCH /api/financing-payments/:id/paid', () => {
expect(res.status).toBe(404); expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Payment not found' }); expect(res.body).toEqual({ error: 'Payment not found' });
}); });
it('returns 400 for non-numeric payment id', async () => {
const res = await request(app)
.patch('/api/financing-payments/abc/paid')
.send({ paid: true });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
});
describe('ID validation — financing routes', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('GET /api/financing/:id returns 400 for non-numeric id', async () => {
const res = await request(app).get('/api/financing/abc');
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
it('PUT /api/financing/:id returns 400 for non-numeric id', async () => {
const res = await request(app)
.put('/api/financing/abc')
.send({ name: 'X', total_amount: 100, due_date: '2027-01-01' });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
it('DELETE /api/financing/:id returns 400 for non-numeric id', async () => {
const res = await request(app).delete('/api/financing/abc');
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'Invalid id' });
});
}); });

View File

@@ -1,5 +1,6 @@
const express = require('express'); const express = require('express');
const cors = require('cors'); const cors = require('cors');
const helmet = require('helmet');
const path = require('path'); const path = require('path');
const healthRouter = require('./routes/health'); const healthRouter = require('./routes/health');
const configRouter = require('./routes/config'); const configRouter = require('./routes/config');
@@ -12,8 +13,20 @@ const { router: financingRouter } = require('./routes/financing');
const app = express(); const app = express();
app.use(cors()); const allowedOrigin = process.env.ALLOWED_ORIGIN || 'http://localhost:5173';
app.use(express.json()); app.use(cors({ origin: allowedOrigin }));
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:'],
connectSrc: ["'self'"],
},
},
}));
app.use(express.json({ limit: '1mb' }));
// API routes // API routes
app.use('/api', healthRouter); app.use('/api', healthRouter);

View File

@@ -85,8 +85,10 @@ router.post('/bills', async (req, res) => {
// GET /api/bills/:id — get single bill // GET /api/bills/:id — get single bill
router.get('/bills/:id', async (req, res) => { router.get('/bills/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
try { try {
const result = await pool.query('SELECT * FROM bills WHERE id = $1', [req.params.id]); const result = await pool.query('SELECT * FROM bills WHERE id = $1', [id]);
if (result.rows.length === 0) { if (result.rows.length === 0) {
return res.status(404).json({ error: 'Bill not found' }); return res.status(404).json({ error: 'Bill not found' });
} }
@@ -99,6 +101,9 @@ router.get('/bills/:id', async (req, res) => {
// PUT /api/bills/:id — update bill // PUT /api/bills/:id — update bill
router.put('/bills/:id', async (req, res) => { router.put('/bills/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
const validationError = validateBillFields(req.body); const validationError = validateBillFields(req.body);
if (validationError) { if (validationError) {
return res.status(400).json({ error: validationError }); return res.status(400).json({ error: validationError });
@@ -129,7 +134,7 @@ router.put('/bills/:id', async (req, res) => {
category || 'General', category || 'General',
active !== undefined ? active : true, active !== undefined ? active : true,
Boolean(variable_amount), Boolean(variable_amount),
req.params.id, id,
] ]
); );
if (result.rows.length === 0) { if (result.rows.length === 0) {
@@ -144,10 +149,12 @@ router.put('/bills/:id', async (req, res) => {
// DELETE /api/bills/:id — hard delete // DELETE /api/bills/:id — hard delete
router.delete('/bills/:id', async (req, res) => { router.delete('/bills/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
try { try {
const result = await pool.query( const result = await pool.query(
'DELETE FROM bills WHERE id = $1 RETURNING id', 'DELETE FROM bills WHERE id = $1 RETURNING id',
[req.params.id] [id]
); );
if (result.rows.length === 0) { if (result.rows.length === 0) {
return res.status(404).json({ error: 'Bill not found' }); return res.status(404).json({ error: 'Bill not found' });
@@ -161,10 +168,12 @@ router.delete('/bills/:id', async (req, res) => {
// PATCH /api/bills/:id/toggle — toggle active field // PATCH /api/bills/:id/toggle — toggle active field
router.patch('/bills/:id/toggle', async (req, res) => { router.patch('/bills/:id/toggle', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
try { try {
const result = await pool.query( const result = await pool.query(
'UPDATE bills SET active = NOT active WHERE id = $1 RETURNING *', 'UPDATE bills SET active = NOT active WHERE id = $1 RETURNING *',
[req.params.id] [id]
); );
if (result.rows.length === 0) { if (result.rows.length === 0) {
return res.status(404).json({ error: 'Bill not found' }); return res.status(404).json({ error: 'Bill not found' });

View File

@@ -109,9 +109,11 @@ router.post('/financing', async (req, res) => {
// GET /api/financing/:id // GET /api/financing/:id
router.get('/financing/:id', async (req, res) => { router.get('/financing/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
try { try {
const { rows } = await pool.query( const { rows } = await pool.query(
'SELECT * FROM financing_plans WHERE id = $1', [req.params.id] 'SELECT * FROM financing_plans WHERE id = $1', [id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
@@ -136,6 +138,9 @@ router.get('/financing/:id', async (req, res) => {
// PUT /api/financing/:id // PUT /api/financing/:id
router.put('/financing/:id', async (req, res) => { router.put('/financing/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
const { name, total_amount, due_date, assigned_paycheck, start_date } = req.body; const { name, total_amount, due_date, assigned_paycheck, start_date } = req.body;
if (!name || !total_amount || !due_date) { if (!name || !total_amount || !due_date) {
return res.status(400).json({ error: 'name, total_amount, and due_date are required' }); return res.status(400).json({ error: 'name, total_amount, and due_date are required' });
@@ -145,7 +150,7 @@ router.put('/financing/:id', async (req, res) => {
const { rows } = await pool.query( const { rows } = await pool.query(
`UPDATE financing_plans SET name=$1, total_amount=$2, due_date=$3, assigned_paycheck=$4, start_date=$5 `UPDATE financing_plans SET name=$1, total_amount=$2, due_date=$3, assigned_paycheck=$4, start_date=$5
WHERE id=$6 RETURNING *`, WHERE id=$6 RETURNING *`,
[name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), req.params.id] [name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
res.json(await enrichPlan(pool, rows[0])); res.json(await enrichPlan(pool, rows[0]));
@@ -157,9 +162,11 @@ router.put('/financing/:id', async (req, res) => {
// DELETE /api/financing/:id // DELETE /api/financing/:id
router.delete('/financing/:id', async (req, res) => { router.delete('/financing/:id', async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
try { try {
const { rows } = await pool.query( const { rows } = await pool.query(
'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [req.params.id] 'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
res.json({ deleted: true }); res.json({ deleted: true });
@@ -172,6 +179,7 @@ router.delete('/financing/:id', async (req, res) => {
// PATCH /api/financing-payments/:id/paid // PATCH /api/financing-payments/:id/paid
router.patch('/financing-payments/:id/paid', async (req, res) => { router.patch('/financing-payments/:id/paid', async (req, res) => {
const id = parseInt(req.params.id, 10); const id = parseInt(req.params.id, 10);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid id' });
const { paid } = req.body; const { paid } = req.body;
if (typeof paid !== 'boolean') { if (typeof paid !== 'boolean') {
return res.status(400).json({ error: 'paid must be a boolean' }); return res.status(400).json({ error: 'paid must be a boolean' });