diff --git a/src/middleware/rateLimit.js b/src/middleware/rateLimit.js new file mode 100644 index 0000000..5bfd79b --- /dev/null +++ b/src/middleware/rateLimit.js @@ -0,0 +1,17 @@ +// Fixed-window rate limiter. Windows start at multiples of windowMs. +export function createRateLimiter({ limit, windowMs, now = Date.now }) { + let currentWindow = null; + let counts = new Map(); + + return function allow(key) { + const window = Math.floor(now() / windowMs); + if (window !== currentWindow) { + currentWindow = window; + counts = new Map(); + } + const used = counts.get(key) ?? 0; + if (used >= limit) return false; + counts.set(key, used + 1); + return true; + }; +} diff --git a/src/routes/notes.js b/src/routes/notes.js index 8248dc1..15be40d 100644 --- a/src/routes/notes.js +++ b/src/routes/notes.js @@ -1,8 +1,15 @@ import { createNote, deleteNote, getNote, listNotes, updateNote } from '../services/notes.js'; import { noteSummary } from '../utils/format.js'; +import { positiveInt } from '../utils/validate.js'; export const notesRoutes = { - 'GET /notes': (req) => ({ status: 200, body: listNotes(req.user.id).map(noteSummary) }), + 'GET /notes': (req) => { + const page = positiveInt(req.query, 'page', 1); + const pageSize = positiveInt(req.query, 'pageSize', 5, { max: 50 }); + const notes = listNotes(req.user.id); + const items = notes.slice((page - 1) * pageSize, page * pageSize).map(noteSummary); + return { status: 200, body: { items, page, pageSize, total: notes.length } }; + }, 'GET /notes/:id': (req) => { const note = getNote(req.user.id, req.params.id); return note ? { status: 200, body: note } : { status: 404, body: { error: 'not found' } }; diff --git a/src/utils/format.js b/src/utils/format.js index 24a3a09..4c90f41 100644 --- a/src/utils/format.js +++ b/src/utils/format.js @@ -3,7 +3,7 @@ // Dates are shown as YYYY-MM-DD in UTC. export function formatDate(ms) { const d = new Date(ms); - const month = String(d.getUTCMonth()).padStart(2, '0'); + const month = String(d.getUTCMonth() + 1).padStart(2, '0'); const day = String(d.getUTCDate()).padStart(2, '0'); return `${d.getUTCFullYear()}-${month}-${day}`; } diff --git a/src/utils/validate.js b/src/utils/validate.js index 72f348f..cb54c9c 100644 --- a/src/utils/validate.js +++ b/src/utils/validate.js @@ -19,6 +19,14 @@ export function optionalTags(obj) { return [...new Set(tags.map((t) => String(t).toLowerCase().trim()).filter(Boolean))]; } +// Reads a positive integer query param; missing values fall back to `fallback`, values above `max` are clamped. +export function positiveInt(query, field, fallback, { max = Infinity } = {}) { + const raw = query?.[field]; + if (raw === undefined || raw === '') return fallback; + if (!/^\d+$/.test(String(raw)) || Number(raw) < 1) throw new ValidationError(field, 'must be a positive integer'); + return Math.min(Number(raw), max); +} + export function requireEmail(obj, field = 'email') { const value = requireString(obj, field); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) throw new ValidationError(field, 'must be an email address'); diff --git a/tests/api.test.js b/tests/api.test.js index 32d499e..8a6558b 100644 --- a/tests/api.test.js +++ b/tests/api.test.js @@ -18,8 +18,42 @@ test('notes need a valid token', () => { test('lists only my notes, newest first', () => { const res = as('u1', { method: 'GET', path: '/notes' }); assert.equal(res.status, 200); - assert.equal(res.body.length, 8); - assert.equal(res.body[0].title, 'Car service'); + assert.equal(res.body.total, 8); + assert.equal(res.body.items[0].title, 'Car service'); +}); + +test('notes are paginated with defaults page=1 pageSize=5', () => { + const res = as('u1', { method: 'GET', path: '/notes' }); + assert.equal(res.body.page, 1); + assert.equal(res.body.pageSize, 5); + assert.equal(res.body.items.length, 5); +}); + +test('notes pages are consecutive and the last is partial', () => { + const p1 = as('u1', { method: 'GET', path: '/notes', query: { page: '1', pageSize: '5' } }).body; + const p2 = as('u1', { method: 'GET', path: '/notes', query: { page: '2', pageSize: '5' } }).body; + assert.equal(p2.items.length, 3); + assert.equal(p2.total, 8); + assert.equal(new Set([...p1.items, ...p2.items].map((n) => n.id)).size, 8); +}); + +test('notes page past the end is empty', () => { + const res = as('u1', { method: 'GET', path: '/notes', query: { page: '9' } }); + assert.equal(res.status, 200); + assert.deepEqual(res.body.items, []); + assert.equal(res.body.total, 8); +}); + +test('notes pageSize is capped at 50', () => { + const res = as('u1', { method: 'GET', path: '/notes', query: { pageSize: '500' } }); + assert.equal(res.body.pageSize, 50); + assert.equal(res.body.items.length, 8); +}); + +test('notes pagination rejects invalid params', () => { + for (const query of [{ page: '0' }, { page: 'abc' }, { pageSize: '-1' }, { pageSize: '1.5' }]) { + assert.equal(as('u1', { method: 'GET', path: '/notes', query }).status, 400); + } }); test('creates and deletes a note', () => { diff --git a/tests/format.test.js b/tests/format.test.js new file mode 100644 index 0000000..51e6465 --- /dev/null +++ b/tests/format.test.js @@ -0,0 +1,14 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { formatDate, noteSummary } from '../src/utils/format.js'; + +test('formatDate uses 1-based months', () => { + assert.equal(formatDate(Date.UTC(2026, 2, 15)), '2026-03-15'); + assert.equal(formatDate(Date.UTC(2026, 0, 1)), '2026-01-01'); + assert.equal(formatDate(Date.UTC(2026, 11, 31)), '2026-12-31'); +}); + +test('note summary shows the correct created month', () => { + const note = { id: 'n1', title: 'T', body: 'B', tags: [], createdAt: Date.UTC(2026, 2, 15) }; + assert.equal(noteSummary(note).created, '2026-03-15'); +}); diff --git a/tests/rateLimit.test.js b/tests/rateLimit.test.js new file mode 100644 index 0000000..9fd2851 --- /dev/null +++ b/tests/rateLimit.test.js @@ -0,0 +1,54 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createRateLimiter } from '../src/middleware/rateLimit.js'; + +function setup(limit = 3, windowMs = 1000) { + const clock = { t: 0 }; + const allow = createRateLimiter({ limit, windowMs, now: () => clock.t }); + return { clock, allow }; +} + +test('allows up to limit calls then rejects', () => { + const { allow } = setup(); + assert.deepEqual([1, 2, 3, 4, 5].map(() => allow('a')), [true, true, true, false, false]); +}); + +test('keys are counted independently', () => { + const { allow } = setup(1); + assert.equal(allow('a'), true); + assert.equal(allow('a'), false); + assert.equal(allow('b'), true); +}); + +test('counter resets at the next window boundary', () => { + const { clock, allow } = setup(2, 1000); + clock.t = 999; + assert.equal(allow('a'), true); + assert.equal(allow('a'), true); + assert.equal(allow('a'), false); + clock.t = 1000; + assert.equal(allow('a'), true); +}); + +test('windows are aligned to multiples of windowMs, not first call', () => { + const { clock, allow } = setup(1, 1000); + clock.t = 1900; + assert.equal(allow('a'), true); + clock.t = 1999; + assert.equal(allow('a'), false); + clock.t = 2000; + assert.equal(allow('a'), true); +}); + +test('stays blocked for the rest of the window', () => { + const { clock, allow } = setup(1, 1000); + assert.equal(allow('a'), true); + clock.t = 999; + assert.equal(allow('a'), false); +}); + +test('defaults to Date.now', () => { + const allow = createRateLimiter({ limit: 1, windowMs: 3600_000 }); + assert.equal(allow('a'), true); + assert.equal(allow('a'), false); +});