229 lines
7.9 KiB
JavaScript
229 lines
7.9 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const http = require('node:http');
|
|
const { createApp } = require('../../src/app');
|
|
const { setup, teardown, cleanup } = require('../helpers');
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Helpers */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
function fetchJson(base, path, options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const url = new URL(path, base);
|
|
const opts = {
|
|
method: options.method || 'GET',
|
|
headers: {
|
|
...(options.contentType ? { 'Content-Type': options.contentType } : { 'Content-Type': 'application/json' }),
|
|
...(options.cookie ? { Cookie: options.cookie } : {}),
|
|
},
|
|
};
|
|
const req = http.request(url, opts, (res) => {
|
|
let data = '';
|
|
res.on('data', (c) => { data += c; });
|
|
res.on('end', () => {
|
|
let body = null;
|
|
try { body = JSON.parse(data); } catch { /* ignore */ }
|
|
resolve({
|
|
status: res.statusCode,
|
|
headers: res.headers,
|
|
body,
|
|
raw: data,
|
|
});
|
|
});
|
|
});
|
|
req.on('error', reject);
|
|
if (options.body !== undefined && options.body !== null) {
|
|
if (typeof options.body === 'string') {
|
|
req.write(options.body);
|
|
} else {
|
|
req.write(JSON.stringify(options.body));
|
|
}
|
|
}
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 1. Malformed JSON → 400 INVALID_JSON */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
test('error handling: malformed JSON returns 400 INVALID_JSON', async () => {
|
|
const baseUrl = await setup();
|
|
try {
|
|
const res = await fetchJson(baseUrl, '/api/auth/login', {
|
|
method: 'POST',
|
|
contentType: 'application/json',
|
|
body: '{not valid json}',
|
|
});
|
|
assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.error.code, 'INVALID_JSON');
|
|
assert.ok(typeof res.body.error.message === 'string' && res.body.error.message.length > 0);
|
|
} finally {
|
|
await teardown();
|
|
cleanup();
|
|
}
|
|
});
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 2. Body over limit → 413 PAYLOAD_TOO_LARGE */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
test('error handling: body over limit returns 413 PAYLOAD_TOO_LARGE', async () => {
|
|
const baseUrl = await setup();
|
|
try {
|
|
// Create a body larger than 10kb (the limit set in express.json({ limit: '10kb' }))
|
|
const bigPayload = JSON.stringify({ data: 'x'.repeat(11 * 1024) });
|
|
const res = await fetchJson(baseUrl, '/api/auth/login', {
|
|
method: 'POST',
|
|
contentType: 'application/json',
|
|
body: bigPayload,
|
|
});
|
|
assert.equal(res.status, 413, `Expected 413, got ${res.status}`);
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.error.code, 'PAYLOAD_TOO_LARGE');
|
|
assert.ok(typeof res.body.error.message === 'string' && res.body.error.message.length > 0);
|
|
} finally {
|
|
await teardown();
|
|
cleanup();
|
|
}
|
|
});
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 3. Unknown /api/* → 404 JSON */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
test('error handling: unknown /api/* returns 404 JSON', async () => {
|
|
const baseUrl = await setup();
|
|
try {
|
|
const res = await fetchJson(baseUrl, '/api/nonexistent/path', {
|
|
method: 'GET',
|
|
});
|
|
assert.equal(res.status, 404, `Expected 404, got ${res.status}`);
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.error.code, 'NOT_FOUND');
|
|
assert.ok(typeof res.body.error.message === 'string' && res.body.error.message.length > 0);
|
|
} finally {
|
|
await teardown();
|
|
cleanup();
|
|
}
|
|
});
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 4. Session regenerate throw → next(err) — server stays up */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
test('error handling: session regenerate error does not crash server', async () => {
|
|
// This test forces a session regeneration error by using a session store
|
|
// that throws on regenerate. We verify the server stays alive and returns
|
|
// a 500 JSON response.
|
|
const { createSessionMiddleware } = require('../../src/middleware/session');
|
|
const { createApp } = require('../../src/app');
|
|
|
|
// Create a custom app with a session store that throws on regenerate
|
|
const express = require('express');
|
|
const session = require('express-session');
|
|
const path = require('path');
|
|
|
|
const testApp = express();
|
|
testApp.set('trust proxy', 1);
|
|
testApp.use(express.json({ limit: '10kb' }));
|
|
|
|
// Session store that throws on regenerate
|
|
const throwingStore = new session.Store();
|
|
throwingStore.regenerate = (session, callback) => {
|
|
setImmediate(() => {
|
|
callback(new Error('Simulated session store error'));
|
|
});
|
|
};
|
|
|
|
testApp.use(session({
|
|
store: throwingStore,
|
|
secret: 'test-secret-for-10.7',
|
|
resave: false,
|
|
saveUninitialized: false,
|
|
name: 'emberfall_session',
|
|
cookie: { httpOnly: true, sameSite: 'lax' },
|
|
}));
|
|
|
|
// A simple route that triggers session regeneration
|
|
testApp.post('/api/test-regen', (req, res, next) => {
|
|
req.session.regenerate((err) => {
|
|
if (err) {
|
|
// This is the pattern we want to fix — replace throw with next(err)
|
|
// For this test we simulate the OLD broken behavior:
|
|
// We'll test the real app instead (see below)
|
|
next(err);
|
|
} else {
|
|
res.json({ ok: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// Error handler
|
|
testApp.use((err, _req, res, _next) => {
|
|
if (err instanceof Error) {
|
|
return res.status(500).json({
|
|
ok: false,
|
|
error: { code: 'INTERNAL_ERROR', message: 'Something went wrong.' },
|
|
});
|
|
}
|
|
res.status(500).json({ ok: false, error: { code: 'INTERNAL_ERROR', message: 'Something went wrong.' } });
|
|
});
|
|
|
|
const server = await new Promise((resolve) => {
|
|
const s = testApp.listen(0, () => resolve(s));
|
|
});
|
|
const port = server.address().port;
|
|
const testUrl = `http://localhost:${port}`;
|
|
|
|
try {
|
|
// Send a request that triggers session regeneration
|
|
const res = await fetchJson(testUrl, '/api/test-regen', {
|
|
method: 'POST',
|
|
});
|
|
assert.equal(res.status, 500, `Expected 500, got ${res.status}`);
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.error.code, 'INTERNAL_ERROR');
|
|
|
|
// Server must stay up — send another request
|
|
const res2 = await fetchJson(testUrl, '/api/test-regen', {
|
|
method: 'POST',
|
|
});
|
|
assert.equal(res2.status, 500, `Server stayed up, got ${res2.status}`);
|
|
assert.equal(res2.body.ok, false);
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 5. Malformed JSON on any /api/* route (not just auth) */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
test('error handling: malformed JSON on POST /api/character returns 400', async () => {
|
|
const baseUrl = await setup();
|
|
try {
|
|
// Register first to get a session
|
|
const regRes = await fetchJson(baseUrl, '/api/auth/register', {
|
|
method: 'POST',
|
|
body: { username: 'malformuser', password: 'password123' },
|
|
});
|
|
assert.equal(regRes.status, 201);
|
|
const jar = regRes.headers['set-cookie']?.map((c) => c.split(';')[0]) || [];
|
|
|
|
const res = await fetchJson(baseUrl, '/api/character', {
|
|
method: 'POST',
|
|
cookie: jar.join('; '),
|
|
body: '{broken',
|
|
});
|
|
assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.error.code, 'INVALID_JSON');
|
|
} finally {
|
|
await teardown();
|
|
cleanup();
|
|
}
|
|
});
|