Files
crosscode-platform/apps/events/backend/tests/hub.test.js
T
joshuaandClaude Opus 5.5 3f59164ab2 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>
2026-11-02 16:35:06 +02:00

221 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
jest.mock('../src/config/db', () => ({}));
const crypto = require('crypto');
const { verifyToken, stateFor } = require('../src/hub/licence');
const { incomeBand } = require('../src/hub/report');
const { isBlocked } = require('../src/hub/readOnly');
const { compareVersions, pendingUpdateRequest, newerReleases, updateSnoozed, activeNotices } = require('../src/controllers/hubController');
const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');
function sign(payload, key = privateKey) {
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
return `hel1.${body}.${crypto.sign(null, Buffer.from(`hel1.${body}`), key).toString('base64url')}`;
}
const NOW = new Date('2026-10-26T10:00:00Z');
const base = {
v: 1, installId: 'inst_1', status: 'active', graceDays: 14,
licenceExpiresAt: '2027-10-31T21:59:59.000Z',
issuedAt: '2026-10-26T09:45:00.000Z', validUntil: '2026-11-25T09:45:00.000Z',
};
describe('licence tokens', () => {
test('a token the Hub signed verifies; edited or foreign ones do not', () => {
expect(verifyToken(sign(base), publicKey)).toMatchObject({ installId: 'inst_1', status: 'active' });
const [p, , s] = sign(base).split('.');
const edited = `${p}.${Buffer.from(JSON.stringify({ ...base, status: 'active', licenceExpiresAt: '2099-01-01' })).toString('base64url')}.${s}`;
expect(verifyToken(edited, publicKey)).toBeNull();
const other = crypto.generateKeyPairSync('ed25519');
expect(verifyToken(sign(base, other.privateKey), publicKey)).toBeNull();
expect(verifyToken('', publicKey)).toBeNull();
expect(verifyToken(sign(base), null)).toBeNull();
});
});
describe('licence states', () => {
test('never connected → unlicensed, read-only like suspended', () => {
expect(stateFor(null, null, NOW)).toMatchObject({ state: 'unlicensed', readOnly: true });
});
test('a token for another install counts as none', () => {
expect(stateFor(base, 'inst_other', NOW).state).toBe('unlicensed');
});
test('active until the earlier of the licence end and validUntil', () => {
expect(stateFor(base, 'inst_1', NOW)).toMatchObject({ state: 'active', readOnly: false });
expect(stateFor(base, 'inst_1', NOW).endsAt.toISOString()).toBe('2026-11-25T09:45:00.000Z');
});
test('grace after the end date for graceDays, with days left — then read-only', () => {
const expired = { ...base, licenceExpiresAt: '2026-10-20T00:00:00.000Z' };
expect(stateFor(expired, 'inst_1', NOW)).toMatchObject({ state: 'grace', readOnly: false, daysLeft: 8 });
expect(stateFor(expired, 'inst_1', new Date('2026-11-05T00:00:00Z'))).toMatchObject({ state: 'suspended', readOnly: true, expired: true });
});
test('Hub unreachable: still active for 30 days, then grace, then read-only', () => {
expect(stateFor({ ...base, licenceExpiresAt: null }, 'inst_1', new Date('2026-11-20T00:00:00Z')).state).toBe('active');
expect(stateFor({ ...base, licenceExpiresAt: null }, 'inst_1', new Date('2026-12-01T00:00:00Z')).state).toBe('grace');
expect(stateFor({ ...base, licenceExpiresAt: null }, 'inst_1', new Date('2026-12-15T00:00:00Z')).state).toBe('suspended');
});
test('suspended and revoked are read-only straight away', () => {
expect(stateFor({ ...base, status: 'suspended' }, 'inst_1', NOW)).toMatchObject({ state: 'suspended', readOnly: true });
expect(stateFor({ ...base, status: 'revoked' }, 'inst_1', NOW)).toMatchObject({ state: 'revoked', readOnly: true });
});
});
describe('heartbeat report', () => {
test('income is sent as a band, never an amount', () => {
expect(incomeBand(0)).toBe('R0–R1 000');
expect(incomeBand(1000)).toBe('R0–R1 000');
expect(incomeBand(1000.4)).toBe('R0–R1 000');
expect(incomeBand(1001)).toBe('R1 001–R5 000');
expect(incomeBand(19999)).toBe('R5 001–R20 000');
expect(incomeBand(100000)).toBe('R50 001–R100 000');
expect(incomeBand(250000)).toBe('over R100 000');
expect(incomeBand(null)).toBe('R0–R1 000');
});
});
describe('read-only mode', () => {
// /api/v2 only (2.0 removed v1).
test.each([
['POST', '/api/v2/events'],
['PATCH', '/api/v2/events/ev_1'],
['POST', '/api/v2/events/ev_1/copy-from'],
['POST', '/api/v2/events/ev_1/ticket-options'],
['PATCH', '/api/v2/ticket-options/opt_1'],
['PATCH', '/api/v2/variants/var_1'],
['POST', '/api/v2/registrations'],
['POST', '/api/v2/registrations/manual'],
['PUT', '/api/v2/registrations/abc/items'],
['POST', '/api/v2/registrations/abc/checkout'],
['POST', '/api/v2/registrations/abc/payment-link/send'],
['POST', '/api/v2/payments'],
['POST', '/api/v2/payment-links/chk_1'],
['POST', '/api/v2/waitlist'],
['POST', '/api/v2/season-passes/p1/buy'],
['POST', '/api/v2/volunteer-roles/r1/sign-up'],
])('v2 %s %s is blocked', (m, p) => expect(isBlocked(m, p)).toBe(true));
test.each([
['POST', '/api/v2/checkin/QR123'],
['GET', '/api/v2/events'],
['PUT', '/api/v2/events/ev_1/notify-recipients'],
['POST', '/api/v2/registrations/abc/cancel'],
['POST', '/api/v2/payments/refunds'],
['POST', '/api/v2/me/privacy/requests'],
['POST', '/api/v2/auth/login'],
])('v2 %s %s keeps working', (m, p) => expect(isBlocked(m, p)).toBe(false));
test('every blocked v2 path is a real v2 route', () => {
const doc = require('../../frontend/src/lib/api-v2/openapi.json');
const routes = Object.entries(doc.paths).flatMap(([p, ops]) =>
Object.keys(ops).map(m => [m.toUpperCase(), `/api/v2${p.replace(/\{[^}]+\}/g, 'x1')}`]));
const { BLOCKED } = require('../src/hub/readOnly');
const unmatched = BLOCKED
.filter(([, re]) => re.source.startsWith('^\\/api\\/v2'))
.filter(([m, re]) => !routes.some(([rm, rp]) => rm === m && re.test(rp)))
.map(([m, re]) => `${m} ${re}`);
expect(unmatched).toEqual([]);
});
});
describe('pasting the Hub public key', () => {
const { normalisePem } = require('../src/hub/publicKey');
const pem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
const base64 = pem.replace(/-----(BEGIN|END) PUBLIC KEY-----|\s/g, '');
test.each([
['proper PEM', pem],
['with \\n', pem.replace(/\n/g, '\\n')],
['all on one line', `-----BEGIN PUBLIC KEY-----${base64}-----END PUBLIC KEY-----`],
['just the base64', base64],
])('%s works', (label, input) => {
expect(() => crypto.createPublicKey(normalisePem(input))).not.toThrow();
expect(verifyToken(sign(base), crypto.createPublicKey(normalisePem(input)))).not.toBeNull();
});
test('empty means none', () => {
expect(normalisePem('')).toBeNull();
expect(normalisePem(undefined)).toBeNull();
});
test('without HUB_PUBLIC_KEY the built-in production key is used', () => {
const { hubPublicKey, PRODUCTION_PUBLIC_KEY } = require('../src/hub/publicKey');
const saved = process.env.HUB_PUBLIC_KEY;
delete process.env.HUB_PUBLIC_KEY;
try {
expect(PRODUCTION_PUBLIC_KEY).toBeTruthy();
expect(crypto.createPublicKey(hubPublicKey()).asymmetricKeyType).toBe('ed25519');
} finally {
if (saved !== undefined) process.env.HUB_PUBLIC_KEY = saved;
}
});
});
test('version comparison for "update available"', () => {
expect(compareVersions('1.41.0', '1.41.1')).toBeLessThan(0);
expect(compareVersions('1.41.0', '1.41.0')).toBe(0);
expect(compareVersions('2.0.0', '1.50.3')).toBeGreaterThan(0);
});
test('an update request shows until the site runs the version asked for', () => {
const at = '2026-10-27T09:00:00.000Z';
expect(pendingUpdateRequest('1.41.2', at, '1.42.0')).toEqual({ requestedAt: at, version: '1.42.0', outdated: false });
expect(pendingUpdateRequest('1.42.0', at, '1.42.0')).toBeNull();
expect(pendingUpdateRequest('1.43.0', at, '1.42.0')).toBeNull();
expect(pendingUpdateRequest('1.41.2', null, null)).toBeNull();
});
test('a request for a version that has since been overtaken can be changed', () => {
const at = '2026-10-27T09:00:00.000Z';
expect(pendingUpdateRequest('1.46.2', at, '1.47.0', '1.47.3')).toEqual({ requestedAt: at, version: '1.47.0', outdated: true });
expect(pendingUpdateRequest('1.46.2', at, '1.47.3', '1.47.3')).toEqual({ requestedAt: at, version: '1.47.3', outdated: false });
});
describe("what's new", () => {
const releases = [
{ version: '1.46.0', notes: 'Older', urgent: false, releasedAt: '2026-10-20T10:00:00.000Z' },
{ version: '1.48.0', notes: '- Webhooks', urgent: false, releasedAt: '2026-10-30T10:00:00.000Z' },
{ version: '1.47.1', notes: '- Security fix', urgent: true, releasedAt: '2026-10-29T10:00:00.000Z' },
{ version: 'bogus', notes: 'x' },
];
test('only versions newer than this site, newest first', () => {
expect(newerReleases(releases, '1.47.0').map(r => r.version)).toEqual(['1.48.0', '1.47.1']);
expect(newerReleases(releases, '1.48.0')).toEqual([]);
expect(newerReleases(null, '1.0.0')).toEqual([]);
});
test('"Not now" holds until a newer version than the one put off', () => {
expect(updateSnoozed({ latestVersion: '1.47.0', snoozedVersion: '1.47.0', urgent: false })).toBe(true);
expect(updateSnoozed({ latestVersion: '1.48.0', snoozedVersion: '1.47.0', urgent: false })).toBe(false);
expect(updateSnoozed({ latestVersion: '1.47.0', snoozedVersion: null, urgent: false })).toBe(false);
});
test('urgent updates can\'t be put off', () => {
expect(updateSnoozed({ latestVersion: '1.47.1', snoozedVersion: '1.47.1', urgent: true })).toBe(false);
});
});
describe("the provider's notices", () => {
const NOW_N = new Date('2026-11-01T18:30:00Z');
const n = (id, extra = {}) => ({ id, level: 'info', title: 'T', message: 'M', startsAt: null, endsAt: null, ...extra });
test('show between their start and end', () => {
const notices = [
n('now'),
n('window', { startsAt: '2026-11-01T18:00:00Z', endsAt: '2026-11-01T20:00:00Z' }),
n('later', { startsAt: '2026-11-02T18:00:00Z' }),
n('ended', { endsAt: '2026-11-01T18:00:00Z' }),
];
expect(activeNotices(notices, NOW_N).map(x => x.id)).toEqual(['now', 'window']);
});
test('an unknown level shows as information', () => {
expect(activeNotices([n('x', { level: 'party' })], NOW_N)[0].level).toBe('info');
expect(activeNotices([n('x', { level: 'maintenance' })], NOW_N)[0].level).toBe('maintenance');
});
});