2 Commits

Author SHA1 Message Date
758828c70a Fix test import style and document hooks in CLAUDE.md
- Replace mixed ESM/CJS import syntax in test file with consistent ESM
  imports throughout (both vitest and normalizer use import)
- Add Git Hooks section to CLAUDE.md documenting install-hooks.sh
  and the commit-msg normalizer for new contributors

Nightshift-Task: commit-normalize
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:07:30 -04:00
73e7967735 Add commit message normalizer hook and install script
- scripts/normalize-commit-msg.js: capitalizes subject, strips trailing
  period, trims whitespace, warns when subject > 72 chars
- scripts/commit-msg: shell wrapper symlinked into .git/hooks/commit-msg
- scripts/install-hooks.sh: contributor setup script (sh scripts/install-hooks.sh)
- scripts/package.json: test runner + hooks:install npm script
- scripts/__tests__/normalize-commit-msg.test.js: 15 unit tests

Nightshift-Task: commit-normalize
Nightshift-Ref: https://github.com/marcus/nightshift
2026-03-20 02:04:04 -04:00
14 changed files with 1506 additions and 119 deletions

View File

@@ -29,6 +29,19 @@ td session --new # force a new session in the same terminal context
Task state is stored in `.todos/issues.db` (SQLite). Task state is stored in `.todos/issues.db` (SQLite).
## Git Hooks
A commit-msg hook normalizes commit messages on every commit (capitalizes subject, strips trailing period, trims whitespace, warns when subject exceeds 72 characters). The hook never blocks a commit.
**Wire hooks after cloning:**
```bash
sh scripts/install-hooks.sh
# or via npm script:
cd scripts && npm run hooks:install
```
The hook script lives at `scripts/commit-msg` and is invoked by `.git/hooks/commit-msg`. The normalizer logic is in `scripts/normalize-commit-msg.js` with unit tests in `scripts/__tests__/normalize-commit-msg.test.js` (run with `cd scripts && npm test`).
## Development ## Development
**Run production stack (Docker):** **Run production stack (Docker):**
@@ -94,5 +107,3 @@ 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

@@ -0,0 +1,90 @@
import { describe, it, expect } from 'vitest';
import { normalizeSubject, normalizeMessage } from '../normalize-commit-msg.js';
describe('normalizeSubject', () => {
it('passes an already-valid subject unchanged', () => {
const { subject, warned } = normalizeSubject('Add feature flag support');
expect(subject).toBe('Add feature flag support');
expect(warned).toBe(false);
});
it('capitalizes the first letter', () => {
const { subject } = normalizeSubject('add feature flag support');
expect(subject).toBe('Add feature flag support');
});
it('strips a trailing period', () => {
const { subject } = normalizeSubject('Add feature flag support.');
expect(subject).toBe('Add feature flag support');
});
it('trims leading whitespace', () => {
const { subject } = normalizeSubject(' Fix the bug');
expect(subject).toBe('Fix the bug');
});
it('trims trailing whitespace', () => {
const { subject } = normalizeSubject('Fix the bug ');
expect(subject).toBe('Fix the bug');
});
it('capitalizes and strips period together', () => {
const { subject } = normalizeSubject('fix the bug.');
expect(subject).toBe('Fix the bug');
});
it('does not strip a period that is not trailing', () => {
const { subject } = normalizeSubject('Fix bug in v1.0 release');
expect(subject).toBe('Fix bug in v1.0 release');
});
it('warns when subject exceeds 72 characters', () => {
const long = 'A'.repeat(73);
const { warned } = normalizeSubject(long);
expect(warned).toBe(true);
});
it('does not warn when subject is exactly 72 characters', () => {
const exact = 'A'.repeat(72);
const { warned } = normalizeSubject(exact);
expect(warned).toBe(false);
});
it('does not warn when subject is under 72 characters', () => {
const { warned } = normalizeSubject('Short message');
expect(warned).toBe(false);
});
it('handles an empty subject gracefully', () => {
const { subject, warned } = normalizeSubject('');
expect(subject).toBe('');
expect(warned).toBe(false);
});
});
describe('normalizeMessage', () => {
it('normalizes only the subject line of a multi-line message', () => {
const input = 'fix the bug.\n\nThis is the body paragraph.';
const { message } = normalizeMessage(input);
expect(message).toBe('Fix the bug\n\nThis is the body paragraph.');
});
it('skips comment lines when finding the subject', () => {
const input = '# Comment\nfix the bug.';
const { message } = normalizeMessage(input);
expect(message).toBe('# Comment\nFix the bug');
});
it('returns warned true for long subject inside full message', () => {
const longSubject = 'x'.repeat(73);
const input = `${longSubject}\n\nBody.`;
const { warned } = normalizeMessage(input);
expect(warned).toBe(true);
});
it('preserves body lines exactly as-is', () => {
const input = 'Fix bug\n\n - detail one\n - detail two.';
const { message } = normalizeMessage(input);
expect(message).toBe('Fix bug\n\n - detail one\n - detail two.');
});
});

4
scripts/commit-msg Executable file
View File

@@ -0,0 +1,4 @@
#!/bin/sh
# Git commit-msg hook — delegates to normalize-commit-msg.js
# This file is symlinked into .git/hooks/commit-msg by scripts/install-hooks.sh
node "$(git rev-parse --show-toplevel)/scripts/normalize-commit-msg.js" "$1"

34
scripts/install-hooks.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/sh
# install-hooks.sh
# Installs the project's git hooks into .git/hooks/.
# Run this once after cloning: sh scripts/install-hooks.sh
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
HOOKS_DIR="$REPO_ROOT/.git/hooks"
SCRIPTS_DIR="$REPO_ROOT/scripts"
install_hook() {
local name="$1"
local src="$SCRIPTS_DIR/$name"
local dst="$HOOKS_DIR/$name"
if [ ! -f "$src" ]; then
echo "install-hooks: source not found: $src" >&2
return 1
fi
if [ -f "$dst" ] && [ ! -L "$dst" ]; then
echo "install-hooks: warning: $dst already exists and is not a symlink — skipping"
return 0
fi
ln -sf "$src" "$dst"
chmod +x "$src"
echo "install-hooks: installed $name -> $dst"
}
install_hook "commit-msg"
echo "install-hooks: done"

95
scripts/normalize-commit-msg.js Executable file
View File

@@ -0,0 +1,95 @@
#!/usr/bin/env node
/**
* normalize-commit-msg.js
*
* Git commit-msg hook: reads the commit message file, applies normalization
* rules to the subject line, rewrites the file in place.
*
* Rules:
* 1. Trim leading/trailing whitespace from the subject line
* 2. Capitalize the first letter of the subject
* 3. Strip a trailing period from the subject
* 4. Warn (but do not block) if the subject exceeds 72 characters
*/
'use strict';
const fs = require('fs');
const MAX_SUBJECT_LEN = 72;
/**
* Normalize the subject line of a commit message.
* Returns { subject, warned } where warned is true if a length warning was emitted.
*
* @param {string} subject
* @returns {{ subject: string, warned: boolean }}
*/
function normalizeSubject(subject) {
let s = subject.trimEnd();
// Trim leading whitespace
s = s.trimStart();
// Capitalize first letter
if (s.length > 0) {
s = s[0].toUpperCase() + s.slice(1);
}
// Strip trailing period
if (s.endsWith('.')) {
s = s.slice(0, -1);
}
const warned = s.length > MAX_SUBJECT_LEN;
return { subject: s, warned };
}
/**
* Normalize a full commit message string.
* Only the subject line (first non-empty, non-comment line) is modified.
*
* @param {string} message
* @returns {{ message: string, warned: boolean }}
*/
function normalizeMessage(message) {
const lines = message.split('\n');
let warned = false;
// Find the subject line (first non-comment line)
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.startsWith('#')) {
const result = normalizeSubject(line);
lines[i] = result.subject;
warned = result.warned;
break;
}
}
return { message: lines.join('\n'), warned };
}
// Only run as a hook when invoked directly (not when required in tests)
if (require.main === module) {
const msgFile = process.argv[2];
if (!msgFile) {
process.stderr.write('commit-msg hook: no message file argument\n');
process.exit(1);
}
const original = fs.readFileSync(msgFile, 'utf8');
const { message, warned } = normalizeMessage(original);
if (warned) {
process.stderr.write(
`commit-msg warning: subject line exceeds ${MAX_SUBJECT_LEN} characters — consider shortening it.\n`
);
}
fs.writeFileSync(msgFile, message, 'utf8');
process.exit(0);
}
module.exports = { normalizeSubject, normalizeMessage };

1249
scripts/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

12
scripts/package.json Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "budget-scripts",
"version": "1.0.0",
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"hooks:install": "sh install-hooks.sh"
},
"devDependencies": {
"vitest": "^4.1.0"
}
}

View File

@@ -11,7 +11,6 @@
"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": {
@@ -1283,15 +1282,6 @@
"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,7 +12,6 @@
"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,35 +131,3 @@ 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,39 +338,4 @@ 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,6 +1,5 @@
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');
@@ -13,20 +12,8 @@ const { router: financingRouter } = require('./routes/financing');
const app = express(); const app = express();
const allowedOrigin = process.env.ALLOWED_ORIGIN || 'http://localhost:5173'; app.use(cors());
app.use(cors({ origin: allowedOrigin })); app.use(express.json());
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,10 +85,8 @@ 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', [id]); const result = await pool.query('SELECT * FROM bills WHERE id = $1', [req.params.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' });
} }
@@ -101,9 +99,6 @@ 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 });
@@ -134,7 +129,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),
id, req.params.id,
] ]
); );
if (result.rows.length === 0) { if (result.rows.length === 0) {
@@ -149,12 +144,10 @@ 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',
[id] [req.params.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' });
@@ -168,12 +161,10 @@ 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 *',
[id] [req.params.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,11 +109,9 @@ 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', [id] 'SELECT * FROM financing_plans WHERE id = $1', [req.params.id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
@@ -138,9 +136,6 @@ 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' });
@@ -150,7 +145,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), id] [name.trim(), parseFloat(total_amount), due_date, assigned_paycheck ?? null, start_date || new Date().toISOString().slice(0, 10), req.params.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]));
@@ -162,11 +157,9 @@ 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', [id] 'DELETE FROM financing_plans WHERE id=$1 RETURNING id', [req.params.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 });
@@ -179,7 +172,6 @@ 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' });