WIP 2.0.0: v1 removed; Argon2id passwords; node-fetch gone

- /api (v1) answers 410 API_V1_REMOVED, except provider webhooks
  (/api/webhooks/*, /api/whatsapp/webhook) and links in sent messages
  (308s, one-click POST). 43 v1 route files and deprecation.ts removed;
  /docs redirects to /docs/v2; API_DOCUMENTATION.md points there.
- Read-only and impersonation lists name v2 paths only. The campus
  scope route test now runs over v2 routes (v2CampusScope.test.ts).
- Passwords hashed with Argon2id (@node-rs/argon2); bcrypt hashes still
  sign in and are re-hashed at the next sign-in.
- e2e on /api/v2 only (v2() helper); Playwright waits on /api/v2.
- MIGRATING-TO-2.md with the full v1 -> v2 table.
- Two documented response shapes corrected.

Backend 690 tests and e2e 102/102 (PayFast sandbox skipped) pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 16:35:06 +02:00
co-authored by Claude Opus 5.5
parent 89a952dedb
commit 9913a13f70
97 changed files with 1099 additions and 4398 deletions
+26 -1
View File
@@ -9,7 +9,8 @@ const mockDb = {
};
jest.mock('../src/config/db', () => mockDb);
const mockCompare = jest.fn(async () => false);
jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't' }));
const mockNeedsRehash = jest.fn(() => false);
jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't', needsRehash: (...a: unknown[]) => (mockNeedsRehash as jest.Mock)(...a) }));
const mockSendMail = jest.fn(async () => undefined);
jest.mock('../src/utils/email', () => ({ sendMail: (...a: unknown[]) => (mockSendMail as jest.Mock)(...a), buildPasswordResetEmail: () => ({ html: '', text: 'reset' }) }));
jest.mock('../src/utils/notify', () => ({ waText: async () => undefined }));
@@ -81,3 +82,27 @@ describe('sign-in', () => {
expect(mockCompare).toHaveBeenCalledWith('guess', 'stand-in-hash');
});
});
describe('password re-hashing (2.0)', () => {
// Stop logIn at its first save, to see what it saves.
const firstSave = () => new Promise<Record<string, unknown>>(resolve => {
mockDb.user.update.mockImplementationOnce(async (args: { data: Record<string, unknown> }) => { resolve(args.data); throw new Error('stop'); });
});
test('a right password on an old hash saves a new hash', async () => {
mockDb.user.findFirst.mockResolvedValueOnce({ ...realUser, password: '$2a$10$old' });
mockCompare.mockResolvedValueOnce(true as never);
mockNeedsRehash.mockReturnValueOnce(true);
const saved = firstSave();
await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined);
expect(await saved).toMatchObject({ failedAttempts: 0, password: 'stand-in-hash' });
});
test('a current hash is left as it is', async () => {
mockDb.user.findFirst.mockResolvedValueOnce(realUser);
mockCompare.mockResolvedValueOnce(true as never);
const saved = firstSave();
await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined);
expect(await saved).not.toHaveProperty('password');
});
});
+1 -1
View File
@@ -73,7 +73,7 @@ test('moving keeps the same lines and tickets, repriced; checks places; not othe
test('payments and ticket changes are refused in licence read-only mode; cancelling is not', async () => {
mockLicence.mockResolvedValueOnce({ readOnly: true });
await expect(bulk.runBulk(req, { action: 'markPaid', registrationIds: ['a'], method: 'cash' })).rejects.toMatchObject({ statusCode: 403 });
expect(isBlocked('POST', '/api/registrations/bulk')).toBe(false);
expect(isBlocked('POST', '/api/v2/registrations/bulk')).toBe(false);
});
test('allocating places each named person; a registration without names says so', async () => {
-46
View File
@@ -1,46 +0,0 @@
// Every staff/supervisor route must say how it handles campus-scoped staff (utils/campusScope.js):
// scopeEvent(...), scopeList, unscopedOnly or campusIndependent('reason'). A route that says
// nothing would show a campus-limited supervisor every campus's data, so this fails on it.
const fs = require('fs');
const path = require('path');
const { staff, supervisor } = require('../src/middleware/authMiddleware');
const ROUTES_DIR = path.join(__dirname, '..', 'src', 'routes');
function staffRoutes() {
const out = [];
for (const file of fs.readdirSync(ROUTES_DIR).filter(f => f.endsWith('.js'))) {
const router = require(path.join(ROUTES_DIR, file));
for (const layer of router.stack || []) {
if (!layer.route) continue;
for (const method of Object.keys(layer.route.methods)) {
// router.route('/x').get(...).put(...) puts every method's handlers on one route, so the
// role is checked per method (admin-only methods are never campus-scoped).
const forMethod = layer.route.stack.filter(s => s.method === method || s.method === undefined).map(s => s.handle);
if (!forMethod.includes(staff) && !forMethod.includes(supervisor)) continue;
const marker = forMethod.find(h => h && h.campusScope);
out.push({ file, method: method.toUpperCase(), path: layer.route.path, marker: marker ? marker.campusScope : null });
}
}
}
return out;
}
describe('campus scope on staff and supervisor routes', () => {
const routes = staffRoutes();
test('finds the staff and supervisor routes', () => {
expect(routes.length).toBeGreaterThan(100);
});
test('every one says how it handles campus-scoped staff', () => {
const missing = routes.filter(r => !r.marker).map(r => `${r.file} ${r.method} ${r.path}`);
expect(missing).toEqual([]);
});
test('a campus-independent route gives a reason', () => {
for (const r of routes.filter(x => x.marker && x.marker.startsWith('independent'))) {
expect(r.marker.length).toBeGreaterThan('independent: '.length + 5);
}
});
});
+1 -1
View File
@@ -26,6 +26,6 @@ describe('event cloning', () => {
});
test('copying setup is blocked in licence read-only mode', () => {
expect(isBlocked('POST', '/api/events/abc/copy-from')).toBe(true);
expect(isBlocked('POST', '/api/v2/events/abc/copy-from')).toBe(true);
});
});
+1 -29
View File
@@ -78,35 +78,7 @@ describe('heartbeat report', () => {
});
describe('read-only mode', () => {
test.each([
['POST', '/api/events'],
['PUT', '/api/events/ev_1'],
['PUT', '/api/events/options/opt_1'],
['PUT', '/api/events/variants/var_1'],
['POST', '/api/registrations'],
['POST', '/api/registrations/manual'],
['PUT', '/api/registrations/abc/options'],
['POST', '/api/payments'],
['POST', '/api/payments/checkout'],
['POST', '/api/payments/pay/chk_1'],
['POST', '/api/waitlist'],
])('%s %s is blocked', (m, p) => expect(isBlocked(m, p)).toBe(true));
test.each([
['POST', '/api/tickets/scan/QR123'],
['GET', '/api/events'],
['PUT', '/api/events/ev_1/notify-recipients'],
['PUT', '/api/registrations/abc'],
['POST', '/api/payments/refund'],
['POST', '/api/privacy/me/requests'],
['POST', '/api/hub/connect'],
['POST', '/api/hub/update-request/cancel'],
['POST', '/api/hub/update-snooze'],
['POST', '/api/users/login'],
['POST', '/api/reports/pdf'],
])('%s %s keeps working', (m, p) => expect(isBlocked(m, p)).toBe(false));
// 1.52.3: the screens use /api/v2, so its routes must be blocked too.
// /api/v2 only (2.0 removed v1).
test.each([
['POST', '/api/v2/events'],
['PATCH', '/api/v2/events/ev_1'],
+4 -4
View File
@@ -20,10 +20,10 @@ describe('allowedWhileImpersonating', () => {
});
test('except ending the session and logging page views', () => {
expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/end')).toBe(true);
expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/log?x=1')).toBe(true);
expect(allowedWhileImpersonating('DELETE', '/api/admin/impersonate/end')).toBe(false);
expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/end/../../users')).toBe(false);
expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end')).toBe(true);
expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/log?x=1')).toBe(true);
expect(allowedWhileImpersonating('DELETE', '/api/v2/me/impersonation/end')).toBe(false);
expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end/../../users')).toBe(false);
});
});
+23 -3
View File
@@ -10,7 +10,7 @@ jest.mock('../src/controllers/privacyController', () => ({
oneClickUnsubscribe: (req: { params: { token: string }; body: unknown }, res: { json(b: unknown): void }) => { mockCalls.push({ name: 'one-click', body: req.body }); res.json({ ok: true }); },
}));
import { webhooksRouter, linksRouter, legacyLinkRedirects } from '../src/v2/links';
import { webhooksRouter, linksRouter, legacyLinkRedirects, legacyV1Router, v1Removed } from '../src/v2/links';
// The same order and raw-body handling as app.js.
function app() {
@@ -27,7 +27,9 @@ function app() {
a.use(express.json());
a.use('/api/v2', linksRouter);
a.use(legacyLinkRedirects);
a.post('/api/privacy/unsubscribe/:token/one-click', (_req, res) => { mockCalls.push({ name: 'v1 one-click' }); res.json({ ok: true }); });
a.use('/api', legacyV1Router);
a.use('/api', v1Removed);
a.use((_req, res) => { res.status(404).json({ notFound: true }); });
return a;
}
@@ -72,6 +74,24 @@ describe('links in sent messages', () => {
expect(mockCalls[0]).toEqual({ name: 'one-click', body: { 'List-Unsubscribe': 'One-Click' } });
const old = await request(app()).post('/api/privacy/unsubscribe/tok/one-click').type('form').send('List-Unsubscribe=One-Click');
expect(old.status).toBe(200);
expect(mockCalls[1].name).toBe('v1 one-click');
expect(mockCalls[1]).toEqual({ name: 'one-click', body: { 'List-Unsubscribe': 'One-Click' } });
});
});
describe('v1, removed in 2.0', () => {
test("WAWP's oldest webhook address still reaches the handler", async () => {
await request(app()).post('/api/whatsapp/webhook?secret=s3').send({ event: 'message' });
expect(mockCalls[0]).toEqual({ name: 'whatsapp', body: { event: 'message' }, query: { secret: 's3' } });
});
test('any other v1 address answers 410 and points at v2', async () => {
const res = await request(app()).get('/api/events');
expect(res.status).toBe(410);
expect(res.body).toMatchObject({ code: 'API_V1_REMOVED', message: expect.stringContaining('/api/v2') });
expect((await request(app()).post('/api/users/login').send({})).status).toBe(410);
});
test('an unknown v2 address is still a 404', async () => {
expect((await request(app()).get('/api/v2/nothing-here')).status).toBe(404);
});
});
+37
View File
@@ -0,0 +1,37 @@
// 2.0: new passwords are hashed with Argon2id; bcrypt hashes from before still work and are
// re-hashed the next time the person signs in (services/auth.ts logIn).
const bcrypt = require('bcryptjs');
const { hashPassword, comparePassword, needsRehash } = require('../src/config/auth');
describe('password hashing', () => {
test('new hashes are Argon2id and check out', async () => {
const hash = await hashPassword('Correct-horse-1');
expect(hash.startsWith('$argon2id$')).toBe(true);
expect(await comparePassword('Correct-horse-1', hash)).toBe(true);
expect(await comparePassword('wrong', hash)).toBe(false);
expect(needsRehash(hash)).toBe(false);
});
test('two hashes of the same password differ (salted)', async () => {
expect(await hashPassword('same')).not.toBe(await hashPassword('same'));
});
test('old bcrypt hashes still sign in, and are marked for re-hashing', async () => {
const old = await bcrypt.hash('Legacy-pass-1', 10);
expect(await comparePassword('Legacy-pass-1', old)).toBe(true);
expect(await comparePassword('nope', old)).toBe(false);
expect(needsRehash(old)).toBe(true);
});
test('anything else never matches', async () => {
for (const stored of ['', null, undefined, 'plain-text', '$argon2id$broken']) {
expect(await comparePassword('plain-text', stored)).toBe(false);
}
expect(await comparePassword(undefined, await hashPassword('x'))).toBe(false);
});
test('weaker Argon2 settings are re-hashed too', () => {
expect(needsRehash('$argon2id$v=19$m=4096,t=3,p=1$c2FsdHNhbHQ$aGFzaGhhc2g')).toBe(true);
expect(needsRehash('$argon2i$v=19$m=19456,t=2,p=1$c2FsdHNhbHQ$aGFzaGhhc2g')).toBe(true);
});
});
+4 -4
View File
@@ -112,9 +112,9 @@ describe('season passes', () => {
});
test('making, changing and buying passes is blocked in licence read-only mode', () => {
expect(isBlocked('POST', '/api/season-passes')).toBe(true);
expect(isBlocked('PUT', '/api/season-passes/p1')).toBe(true);
expect(isBlocked('POST', '/api/season-passes/p1/buy')).toBe(true);
expect(isBlocked('POST', '/api/season-passes/purchases/pp1/checkout')).toBe(true);
expect(isBlocked('POST', '/api/v2/season-passes')).toBe(true);
expect(isBlocked('PATCH', '/api/v2/season-passes/p1')).toBe(true);
expect(isBlocked('POST', '/api/v2/season-passes/p1/buy')).toBe(true);
expect(isBlocked('POST', '/api/v2/season-pass-purchases/pp1/checkout')).toBe(true);
});
});
+3 -3
View File
@@ -41,9 +41,9 @@ describe('event series', () => {
});
test('creating and changing series is blocked in licence read-only mode; following is not', () => {
expect(isBlocked('POST', '/api/series')).toBe(true);
expect(isBlocked('PUT', '/api/series/abc')).toBe(true);
expect(isBlocked('POST', '/api/series/abc/follow')).toBe(false);
expect(isBlocked('POST', '/api/v2/series')).toBe(true);
expect(isBlocked('PATCH', '/api/v2/series/abc')).toBe(true);
expect(isBlocked('PUT', '/api/v2/series/abc/follow')).toBe(false);
});
describe('year-on-year comparison', () => {
-18
View File
@@ -392,24 +392,6 @@ describe('check-in', () => {
expect(res.body.data.ticket).toMatchObject({ attendee: 'Lulu', bookedBy: 'Thandi', ticketOptionId: 'o1', remaining: 2, consentStatus: 'not_required' });
});
});
describe('v1 deprecation headers', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { successorOf } = require('../src/v2/deprecation');
test('v1 endpoints with a v2 replacement point at it; the rest say nothing', () => {
expect(successorOf('GET', '/api/events')).toBe('/api/v2/events');
expect(successorOf('GET', '/api/events/e1')).toBe('/api/v2/events/e1/full');
expect(successorOf('PUT', '/api/events/options/o1')).toBe('/api/v2/ticket-options/o1');
expect(successorOf('DELETE', '/api/events/e1/attachments/a1')).toBe('/api/v2/events/e1/attachments/a1');
expect(successorOf('GET', '/api/events/all')).toBe('/api/v2/events/manage');
expect(successorOf('PUT', '/api/events/e1')).toBe('/api/v2/events/e1');
expect(successorOf('DELETE', '/api/registrations/r1')).toBe('/api/v2/registrations/r1/cancel');
expect(successorOf('POST', '/api/tickets/scan/QR1')).toBe('/api/v2/checkin/QR1');
expect(successorOf('GET', '/api/reports/summary')).toBeNull();
expect(successorOf('GET', '/api/v2/events')).toBeNull();
});
});
describe('shared middleware on v2', () => {
test("v1-style refusals become v2 errors, keeping the specific code as reason", async () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
+53
View File
@@ -0,0 +1,53 @@
// Every staff/supervisor route on /api/v2 must really check campus-scoped staff (utils/campusScope.js).
// A route has to declare `campusScope` (start-up fails otherwise), but the declaration is only text:
// the check itself is a marked middleware — scopeEvent(...), scopeBody(...), scopeList,
// unscopedOnly, campusIndependent('reason') or scopeBroadcast(...). A route without one would show
// a campus-limited supervisor every campus's data, so this fails on it.
//
// (Until 2.0 the same test ran over the v1 route files, which held the markers.)
//
// The routes below check campuses inside their TypeScript service or handler instead, as their
// `campusScope` text says. Adding a route here means its handler does the check itself.
const CHECKED_IN_HANDLER = new Set([
'GET /events/manage', 'POST /events', 'GET /sections', 'POST /uploads/event-image',
'GET /series', 'POST /series', 'PATCH /series/:id', 'GET /series/:id/compare',
'GET /season-passes', 'POST /season-passes', 'PATCH /season-passes/:id', 'DELETE /season-passes/:id',
'GET /coupons', 'GET /coupons/redemptions', 'GET /coupons/:id', 'POST /coupons', 'PATCH /coupons/:id',
'GET /campuses/:id/audience', 'GET /registrations',
'GET /saved-filters', 'POST /saved-filters', 'PUT /saved-filters/:id', 'DELETE /saved-filters/:id',
'GET /checkin/:qrCode', 'POST /checkin/:qrCode',
]);
/* eslint-disable @typescript-eslint/no-require-imports */
const { v2Router } = require('../src/v2');
const { routes } = require('../src/v2/route');
type Route = { method: string; path: string; access: string; campusScope?: string; middleware?: { campusScope?: string }[] };
describe('campus scope on v2 staff and supervisor routes', () => {
v2Router();
const staffRoutes = (routes as Route[]).filter(r => r.access === 'staff' || r.access === 'supervisor');
const key = (r: Route) => `${r.method.toUpperCase()} ${r.path}`;
const marker = (r: Route) => (r.middleware || []).find(h => h && h.campusScope)?.campusScope;
test('finds the staff and supervisor routes', () => {
expect(staffRoutes.length).toBeGreaterThan(150);
});
test('each one has a campus-scope middleware, or checks in its handler', () => {
const missing = staffRoutes.filter(r => !marker(r) && !CHECKED_IN_HANDLER.has(key(r))).map(key);
expect(missing).toEqual([]);
});
test('the handler-checked list holds only real staff routes without a middleware', () => {
const real = new Set(staffRoutes.filter(r => !marker(r)).map(key));
expect([...CHECKED_IN_HANDLER].filter(k => !real.has(k))).toEqual([]);
});
test('a campus-independent route gives a reason', () => {
for (const r of staffRoutes) {
const m = marker(r);
if (m && m.startsWith('independent')) expect(m.length).toBeGreaterThan('independent: '.length + 5);
}
});
});
+6 -6
View File
@@ -80,13 +80,13 @@ describe('reserved tickets', () => {
describe('read-only licence', () => {
test.each([
['POST', '/api/volunteers/roles/r1/sign-up'],
['POST', '/api/volunteers/manage/events/e1/roles'],
['POST', '/api/volunteers/manage/roles/r1/assign'],
['POST', '/api/v2/volunteer-roles/r1/sign-up'],
['POST', '/api/v2/events/e1/volunteer-roles'],
['POST', '/api/v2/volunteer-roles/r1/assign'],
])('%s %s is blocked', (m, p) => expect(isBlocked(m, p)).toBe(true));
test.each([
['POST', '/api/volunteers/check-in'],
['POST', '/api/volunteers/swaps/w1/accept'],
['DELETE', '/api/volunteers/slots/s1'],
['POST', '/api/v2/volunteering/check-in'],
['POST', '/api/v2/volunteer-swaps/w1/accept'],
['DELETE', '/api/v2/volunteer-slots/s1'],
])('%s %s keeps working', (m, p) => expect(isBlocked(m, p)).toBe(false));
});