Add Feedback domain module: public submission flow, admin CRUD, reporting

New /feedback API domain backed by its own FEEDBACK_DB, mirroring the
Calendar domain's router -> service -> DB pool layering:

- Public endpoints (no auth): eligible-events listing, event config,
  submission with honeypot + rate limiting (in-memory + DB backstop).
- Admin endpoints (session-header auth, reusing Calendar's users/sessions
  via a swappable feedback.auth.ts boundary): events/songs/questions CRUD,
  bulk reorder/assignment, aggregated reporting, CSV export.
- Schema in sql/feedback/001_init.sql (8 tables), applied and verified
  against the real FEEDBACK_DB.
- 64 Jest tests covering validation, auth, rate limiting, CSV escaping,
  and report aggregation (pure functions, no DB needed).

Includes fixes from a security review: path traversal defense doesn't
apply here (that's the frontend proxy, separate repo), but the
rate-limiter cluster does - recordSubmission now counts every processed
request (not just successful ones), the in-memory Map evicts empty
entries instead of growing unbounded, FEEDBACK_IP_SALT is required at
boot instead of silently degrading to unsalted hashing, and submission
answer/rating arrays are capped and de-duplicated to bound insert
amplification.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-05 23:32:22 +02:00
parent e7621b8290
commit 17ca6399e0
32 changed files with 3615 additions and 2 deletions
+57
View File
@@ -0,0 +1,57 @@
import {escapeCsvField, formatDatetime} from '../../src/models/feedback/admin/csv.service';
describe('escapeCsvField', () => {
it('passes plain text through unchanged', () => {
expect(escapeCsvField('Abendlied')).toBe('Abendlied');
});
it('converts null/undefined to an empty string', () => {
expect(escapeCsvField(null)).toBe('');
expect(escapeCsvField(undefined)).toBe('');
});
it('converts numbers to strings', () => {
expect(escapeCsvField(5)).toBe('5');
});
it('quotes and doubles internal quotes (RFC 4180)', () => {
expect(escapeCsvField('Sie sagte "Danke"')).toBe('"Sie sagte ""Danke"""');
});
it('quotes a field containing the ; separator', () => {
expect(escapeCsvField('Rheinberger; Bach')).toBe('"Rheinberger; Bach"');
});
it('strips embedded newlines instead of breaking the row', () => {
expect(escapeCsvField('Zeile 1\r\nZeile 2')).toBe('Zeile 1 Zeile 2');
expect(escapeCsvField('Zeile 1\nZeile 2')).toBe('Zeile 1 Zeile 2');
});
it('prefixes formula-injection characters with an apostrophe', () => {
expect(escapeCsvField('=1+1')).toBe("'=1+1");
expect(escapeCsvField('+SUM(A1)')).toBe("'+SUM(A1)");
expect(escapeCsvField('-2')).toBe("'-2");
expect(escapeCsvField('@example')).toBe("'@example");
});
it('does not treat a mid-string = as formula injection', () => {
expect(escapeCsvField('x = y')).toBe('x = y');
});
});
describe('formatDatetime', () => {
it('formats a Date as YYYY-MM-DD HH:mm:ss, not the verbose Date.toString()', () => {
const d = new Date(2026, 7, 2, 21, 59, 21); // month is 0-indexed: August
expect(formatDatetime(d)).toBe('2026-08-02 21:59:21');
expect(formatDatetime(d)).not.toContain('GMT');
});
it('pads single-digit components', () => {
const d = new Date(2026, 0, 5, 3, 4, 5);
expect(formatDatetime(d)).toBe('2026-01-05 03:04:05');
});
it('returns an empty string for null', () => {
expect(formatDatetime(null)).toBe('');
});
});
@@ -0,0 +1,59 @@
import {computeDefaultDeadline, slugBase, slugifyName} from '../../src/models/feedback/admin/events.admin.service';
describe('slugifyName', () => {
it('lowercases and hyphenates', () => {
expect(slugifyName('Sommerkonzert 2026')).toBe('sommerkonzert-2026');
});
it('transliterates umlauts', () => {
expect(slugifyName('Frühlingskonzert')).toBe('fruehlingskonzert');
expect(slugifyName('Weihnachtsgrüße')).toBe('weihnachtsgruesse');
});
it('strips punctuation and collapses separators', () => {
expect(slugifyName('Konzert: "Klänge & Farben"!')).toBe('konzert-klaenge-farben');
});
it('trims leading and trailing hyphens', () => {
expect(slugifyName(' -- Herbstkonzert -- ')).toBe('herbstkonzert');
});
});
describe('slugBase', () => {
it('appends the concert year when the name does not already carry it', () => {
expect(slugBase('Sommerkonzert', '2026-08-01')).toBe('sommerkonzert-2026');
});
it('does not double up the year when the name already ends with it', () => {
expect(slugBase('Adventskonzert 2026', '2026-12-06')).toBe('adventskonzert-2026');
});
it('still appends the year when the name contains a different year', () => {
expect(slugBase('Jubiläum 2020', '2026-08-01')).toBe('jubilaeum-2020-2026');
});
});
describe('computeDefaultDeadline', () => {
it('is 14 days after the event date, at 23:59:59', () => {
const deadline = computeDefaultDeadline('2026-08-01');
expect(deadline.getFullYear()).toBe(2026);
expect(deadline.getMonth()).toBe(7); // August = index 7
expect(deadline.getDate()).toBe(15);
expect(deadline.getHours()).toBe(23);
expect(deadline.getMinutes()).toBe(59);
expect(deadline.getSeconds()).toBe(59);
});
it('rolls over the month correctly', () => {
const deadline = computeDefaultDeadline('2026-08-25');
expect(deadline.getMonth()).toBe(8); // September
expect(deadline.getDate()).toBe(8);
});
it('rolls over the year correctly', () => {
const deadline = computeDefaultDeadline('2026-12-25');
expect(deadline.getFullYear()).toBe(2027);
expect(deadline.getMonth()).toBe(0); // January
expect(deadline.getDate()).toBe(8);
});
});
+87
View File
@@ -0,0 +1,87 @@
import {Request, Response} from 'express';
jest.mock('../../src/models/calendar/users/users.service', () => ({
checkSession: jest.fn()
}));
import * as UserService from '../../src/models/calendar/users/users.service';
import {requireAdminAuth, sessionHeaderAuthenticator} from '../../src/models/feedback/feedback.auth';
const mockCheckSession = UserService.checkSession as jest.Mock;
const makeReq = (headers: Record<string, string>): Request => {
return {
header: (name: string) => headers[name],
ip: '203.0.113.42'
} as unknown as Request;
};
const makeRes = (): Response => {
const res: any = {};
res.status = jest.fn().mockReturnValue(res);
res.send = jest.fn().mockReturnValue(res);
res.locals = {};
return res as Response;
};
describe('sessionHeaderAuthenticator', () => {
beforeEach(() => mockCheckSession.mockReset());
it('returns null when headers are missing', async () => {
const identity = await sessionHeaderAuthenticator(makeReq({}));
expect(identity).toBeNull();
expect(mockCheckSession).not.toHaveBeenCalled();
});
it('returns null when checkSession finds no user', async () => {
mockCheckSession.mockResolvedValue(null);
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toBeNull();
});
it('returns null for a valid session on an inactive account', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: false});
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toBeNull();
});
it('returns the identity for a valid session on an active account', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
const identity = await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'}));
expect(identity).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
});
it('passes the session id and key from headers through to checkSession, never from query params', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'A', isActive: true});
await sessionHeaderAuthenticator(makeReq({'X-Session-Id': '42', 'X-Session-Key': 'sekret'}));
expect(mockCheckSession).toHaveBeenCalledWith('42', 'sekret', '203.0.113.42');
});
});
describe('requireAdminAuth', () => {
beforeEach(() => mockCheckSession.mockReset());
it('responds 401 and does not call next() when unauthenticated', async () => {
mockCheckSession.mockResolvedValue(null);
const req = makeReq({});
const res = makeRes();
const next = jest.fn();
await requireAdminAuth(req, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(next).not.toHaveBeenCalled();
});
it('sets res.locals.admin and calls next() when authenticated', async () => {
mockCheckSession.mockResolvedValue({userId: 1, email: 'a@nachklang.art', fullName: 'Anna Admin', isActive: true});
const req = makeReq({'X-Session-Id': '1', 'X-Session-Key': 'k'});
const res = makeRes();
const next = jest.fn();
await requireAdminAuth(req, res, next);
expect(next).toHaveBeenCalled();
expect(res.locals.admin).toEqual({id: '1', email: 'a@nachklang.art', displayName: 'Anna Admin'});
});
});
+16
View File
@@ -0,0 +1,16 @@
import {isHoneypotTriggered} from '../../src/models/feedback/public/public.router';
describe('isHoneypotTriggered', () => {
it('is false when the field is absent', () => {
expect(isHoneypotTriggered({})).toBe(false);
});
it('is false when the field is empty', () => {
expect(isHoneypotTriggered({website: ''})).toBe(false);
expect(isHoneypotTriggered({website: ' '})).toBe(false);
});
it('is true when a bot filled it in', () => {
expect(isHoneypotTriggered({website: 'https://spam.example'})).toBe(true);
});
});
@@ -0,0 +1,28 @@
// Isolated from ratelimit.test.ts because it needs to control whether
// FEEDBACK_IP_SALT is present at module-load time, which a real dotenv.config()
// call would silently repopulate from the repo's .env file.
jest.mock('dotenv', () => ({config: jest.fn()}));
jest.mock('../../src/models/feedback/Feedback.db', () => ({
NachklangFeedbackDB: {getConnection: jest.fn()}
}));
describe('FEEDBACK_IP_SALT enforcement', () => {
const originalSalt = process.env.FEEDBACK_IP_SALT;
afterEach(() => {
process.env.FEEDBACK_IP_SALT = originalSalt;
jest.resetModules();
});
it('throws at import time when FEEDBACK_IP_SALT is unset, rather than silently hashing unsalted', () => {
jest.resetModules();
delete process.env.FEEDBACK_IP_SALT;
expect(() => require('../../src/models/feedback/feedback.ratelimit')).toThrow(/FEEDBACK_IP_SALT/);
});
it('does not throw when FEEDBACK_IP_SALT is set', () => {
jest.resetModules();
process.env.FEEDBACK_IP_SALT = 'a-real-salt';
expect(() => require('../../src/models/feedback/feedback.ratelimit')).not.toThrow();
});
});
+20
View File
@@ -0,0 +1,20 @@
import {hashIp} from '../../src/models/feedback/feedback.ratelimit';
describe('hashIp', () => {
it('never returns the raw IP', () => {
const hash = hashIp('203.0.113.42');
expect(hash).not.toContain('203.0.113.42');
});
it('is deterministic for the same input', () => {
expect(hashIp('203.0.113.42')).toBe(hashIp('203.0.113.42'));
});
it('differs for different inputs', () => {
expect(hashIp('203.0.113.42')).not.toBe(hashIp('203.0.113.43'));
});
it('is a 64-char hex SHA-256 digest', () => {
expect(hashIp('203.0.113.42')).toMatch(/^[0-9a-f]{64}$/);
});
});
+109
View File
@@ -0,0 +1,109 @@
import {aggregateReport} from '../../src/models/feedback/admin/reports.admin.service';
import {AnswerRow} from '../../src/models/feedback/admin/reports.admin.interface';
const eventMeta = {eventId: 1, name: 'Sommerkonzert', eventDate: '2026-08-01', feedbackDeadline: '2026-08-15T23:59:59'};
const emptyNewsletter = {total: 0, sent: 0, pending: 0, failed: 0};
const row = (overrides: Partial<AnswerRow>): AnswerRow => ({
submissionId: 1,
submittedAt: '2026-08-02T10:00:00.000Z',
questionId: 1,
questionLabel: 'Q',
questionType: 'FREE_TEXT',
songId: null,
songTitle: null,
rating: null,
textAnswer: null,
...overrides
});
describe('aggregateReport - song picks', () => {
it('counts votes per song and sorts by votes descending', () => {
const answers: AnswerRow[] = [
row({submissionId: 1, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({submissionId: 2, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({submissionId: 3, questionId: 5, questionLabel: 'Lieblingsstück?', questionType: 'SONG_PICK', songId: 11, songTitle: 'Morgenlied'})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 3, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songPicks).toHaveLength(1);
expect(report.songPicks[0].totalVotes).toBe(3);
expect(report.songPicks[0].results).toEqual([
{songId: 10, title: 'Abendlied', votes: 2},
{songId: 11, title: 'Morgenlied', votes: 1}
]);
});
it('keeps separate SONG_PICK questions in separate groups', () => {
const answers: AnswerRow[] = [
row({questionId: 5, questionLabel: 'Frage A', questionType: 'SONG_PICK', songId: 10, songTitle: 'Abendlied'}),
row({questionId: 6, questionLabel: 'Frage B', questionType: 'SONG_PICK', songId: 11, songTitle: 'Morgenlied'})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 2, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songPicks).toHaveLength(2);
});
});
describe('aggregateReport - song ratings', () => {
it('averages ratings per song, rounded to one decimal, sorted descending', () => {
const answers: AnswerRow[] = [
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 10, songTitle: 'Abendlied', rating: 5}),
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 10, songTitle: 'Abendlied', rating: 4}),
row({questionId: 7, questionLabel: 'Bewertung', questionType: 'SONG_RATING', songId: 11, songTitle: 'Morgenlied', rating: 3})
];
const report = aggregateReport(eventMeta, {totalSubmissions: 2, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.songRatings[0].results).toEqual([
{songId: 10, title: 'Abendlied', average: 4.5, count: 2},
{songId: 11, title: 'Morgenlied', average: 3, count: 1}
]);
});
});
describe('aggregateReport - free text', () => {
it('sorts newest first and caps at 500 with hasMore', () => {
const answers: AnswerRow[] = Array.from({length: 501}, (_, i) =>
row({
submissionId: i,
questionId: 9,
questionLabel: 'Sonstiges',
questionType: 'FREE_TEXT',
textAnswer: `Antwort ${i}`,
submittedAt: new Date(2026, 0, 1, 0, 0, i).toISOString()
})
);
const report = aggregateReport(eventMeta, {totalSubmissions: 501, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.freeText[0].responses).toHaveLength(500);
expect(report.freeText[0].hasMore).toBe(true);
expect(report.freeText[0].responses[0].text).toBe('Antwort 500');
});
it('does not set hasMore when at or under the cap', () => {
const answers: AnswerRow[] = [row({questionId: 9, questionLabel: 'Sonstiges', questionType: 'FREE_TEXT', textAnswer: 'Danke!'})];
const report = aggregateReport(eventMeta, {totalSubmissions: 1, firstSubmissionAt: null, lastSubmissionAt: null}, answers, 0, emptyNewsletter);
expect(report.freeText[0].hasMore).toBe(false);
});
});
describe('aggregateReport - top-level fields', () => {
it('passes through submission stats, guest book count, and newsletter counts unchanged', () => {
const report = aggregateReport(
eventMeta,
{totalSubmissions: 42, firstSubmissionAt: '2026-08-02T10:00:00.000Z', lastSubmissionAt: '2026-08-10T18:00:00.000Z'},
[],
7,
{total: 10, sent: 6, pending: 2, failed: 2}
);
expect(report.totalSubmissions).toBe(42);
expect(report.firstSubmissionAt).toBe('2026-08-02T10:00:00.000Z');
expect(report.lastSubmissionAt).toBe('2026-08-10T18:00:00.000Z');
expect(report.guestBookCount).toBe(7);
expect(report.newsletter).toEqual({total: 10, sent: 6, pending: 2, failed: 2});
expect(report.event).toEqual(eventMeta);
});
it('produces empty arrays for an event with no submissions', () => {
const report = aggregateReport(eventMeta, {totalSubmissions: 0, firstSubmissionAt: null, lastSubmissionAt: null}, [], 0, emptyNewsletter);
expect(report.songPicks).toEqual([]);
expect(report.songRatings).toEqual([]);
expect(report.freeText).toEqual([]);
});
});
+151
View File
@@ -0,0 +1,151 @@
import {MAX_ANSWER_ROWS, validateAnswers, validateGuestBook, validateNewsletter} from '../../src/models/feedback/public/submissions.service';
type QuestionLookup = Map<number, {eventQuestionId: number; questionId: number; type: 'SONG_PICK' | 'SONG_RATING' | 'FREE_TEXT'; label: string; position: number}>;
const songTitleById = new Map<number, string>([
[1, 'Abendlied'],
[2, 'Morgenlied']
]);
describe('validateAnswers', () => {
const questionsById: QuestionLookup = new Map([
[10, {eventQuestionId: 10, questionId: 100, type: 'SONG_PICK', label: 'Lieblingsstück?', position: 0}],
[11, {eventQuestionId: 11, questionId: 101, type: 'SONG_RATING', label: 'Bewertung', position: 1}],
[12, {eventQuestionId: 12, questionId: 102, type: 'FREE_TEXT', label: 'Sonstiges', position: 2}]
]);
it('produces a row for a valid SONG_PICK answer', () => {
const rows = validateAnswers([{eventQuestionId: 10, songId: 1}], questionsById, songTitleById);
expect(rows).toEqual([
{eventQuestionId: 10, questionId: 100, label: 'Lieblingsstück?', type: 'SONG_PICK', position: 0, songId: 1, songTitle: 'Abendlied', rating: null, text: null}
]);
});
it('ignores a SONG_PICK answer with an unknown songId', () => {
const rows = validateAnswers([{eventQuestionId: 10, songId: 999}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('ignores an answer for an unknown eventQuestionId', () => {
const rows = validateAnswers([{eventQuestionId: 999, songId: 1}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('produces one row per rated song for SONG_RATING, ignoring unknown songs', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 5}, {songId: 2, rating: 3}, {songId: 999, rating: 4}]}
], questionsById, songTitleById);
expect(rows).toHaveLength(2);
expect(rows.map(r => r.songId)).toEqual([1, 2]);
});
it('clamps ratings to the 1..5 range', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 9}, {songId: 2, rating: -3}]}
], questionsById, songTitleById);
expect(rows.find(r => r.songId === 1)?.rating).toBe(5);
expect(rows.find(r => r.songId === 2)?.rating).toBe(1);
});
it('an unrated song in a SONG_RATING block produces no row', () => {
const rows = validateAnswers([{eventQuestionId: 11, ratings: []}], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('trims FREE_TEXT and drops it if empty after trimming', () => {
const withText = validateAnswers([{eventQuestionId: 12, text: ' Danke für den Abend! '}], questionsById, songTitleById);
expect(withText[0].text).toBe('Danke für den Abend!');
const blank = validateAnswers([{eventQuestionId: 12, text: ' '}], questionsById, songTitleById);
expect(blank).toHaveLength(0);
});
it('caps FREE_TEXT at 5000 characters', () => {
const long = 'a'.repeat(6000);
const rows = validateAnswers([{eventQuestionId: 12, text: long}], questionsById, songTitleById);
expect(rows[0].text).toHaveLength(5000);
});
it('a fully empty answer set produces no rows (skipped questions produce no rows)', () => {
const rows = validateAnswers([], questionsById, songTitleById);
expect(rows).toHaveLength(0);
});
it('de-duplicates repeated ratings for the same song, keeping the last value', () => {
const rows = validateAnswers([
{eventQuestionId: 11, ratings: [{songId: 1, rating: 2}, {songId: 1, rating: 5}, {songId: 1, rating: 3}]}
], questionsById, songTitleById);
expect(rows).toHaveLength(1);
expect(rows[0].rating).toBe(3);
});
it('caps total generated rows at MAX_ANSWER_ROWS regardless of how many ratings are submitted', () => {
const massRatings = Array.from({length: MAX_ANSWER_ROWS + 500}, (_, i) => ({
songId: 1,
rating: (i % 5) + 1
}));
// Force distinct songIds so de-duplication alone can't be the thing capping the count.
const distinctSongTitleById = new Map<number, string>(
Array.from({length: MAX_ANSWER_ROWS + 500}, (_, i) => [i, `Song ${i}`])
);
const distinctRatings = massRatings.map((r, i) => ({songId: i, rating: r.rating}));
const rows = validateAnswers(
[{eventQuestionId: 11, ratings: distinctRatings}],
questionsById,
distinctSongTitleById
);
expect(rows.length).toBe(MAX_ANSWER_ROWS);
});
it('stops adding rows across multiple answers once the cap is reached', () => {
const distinctSongTitleById = new Map<number, string>(
Array.from({length: MAX_ANSWER_ROWS + 10}, (_, i) => [i, `Song ${i}`])
);
const answers = Array.from({length: MAX_ANSWER_ROWS + 10}, (_, i) => ({
eventQuestionId: 10,
songId: i
}));
// SONG_PICK only ever produces 0 or 1 row per answer entry, so this
// exercises the cap across many separate answers, not one big array.
const rows = validateAnswers(answers, questionsById, distinctSongTitleById);
expect(rows.length).toBe(MAX_ANSWER_ROWS);
});
});
describe('validateGuestBook', () => {
it('returns null when nothing was filled in', () => {
expect(validateGuestBook(undefined)).toBeNull();
expect(validateGuestBook({displayName: ' ', message: ' '})).toBeNull();
});
it('keeps a valid entry with only a display name', () => {
expect(validateGuestBook({displayName: 'Familie Müller'})).toEqual({displayName: 'Familie Müller', message: null});
});
it('caps the message at 2000 characters', () => {
const long = 'x'.repeat(3000);
const result = validateGuestBook({message: long});
expect(result?.message).toHaveLength(2000);
});
});
describe('validateNewsletter', () => {
it('returns null when the object is missing', () => {
expect(validateNewsletter(undefined)).toBeNull();
});
it('drops the signup silently when the email is invalid', () => {
expect(validateNewsletter({firstName: 'Anna', lastName: 'Beispiel', email: 'not-an-email'})).toBeNull();
});
it('drops the signup when first or last name is missing', () => {
expect(validateNewsletter({firstName: '', lastName: 'Beispiel', email: 'a@b.de'})).toBeNull();
expect(validateNewsletter({firstName: 'Anna', lastName: '', email: 'a@b.de'})).toBeNull();
});
it('accepts a fully valid signup', () => {
expect(validateNewsletter({firstName: 'Anna', lastName: 'Beispiel', email: 'anna@beispiel.de'})).toEqual({
firstName: 'Anna', lastName: 'Beispiel', email: 'anna@beispiel.de'
});
});
});