Fix security and correctness issues found in full-codebase audit

- Restrict meetingPassword field so it isn't leaked via the public REST/GraphQL API
- Fix booking slot computation to use Europe/Berlin time instead of the server's UTC clock
- Reset email verification when a customer changes their email address
- Fix ICS calendar injection via unescaped carriage returns in event descriptions
- Bind WebRTC meeting kicks to a persistent client id so they survive a rejoin
- Move the meeting signaling token out of the WebSocket query string into the first message
- Prevent duplicate signaling connections from leaking when the same participant reconnects
- Use the rightmost X-Forwarded-For entry for rate limiting (single trusted reverse proxy)
- Use constant-time comparison for the cron endpoint's bearer token
- Remove SVG from allowed Media upload types (stored-XSS risk, unused anyway)
- Add baseline security headers and a CSP to next.config.ts
- Fix CI/CD script injection via unsanitized git ref names in release.yml
This commit is contained in:
2026-09-06 21:59:39 +02:00
parent 1b7dbad843
commit 82c4261a81
19 changed files with 399 additions and 122 deletions
+13 -1
View File
@@ -32,7 +32,19 @@ export function checkRateLimit(key: string, opts: { max: number; windowMs: numbe
}
export function getClientIp(request: Request): string {
// Deployment is always behind exactly one trusted reverse proxy (see
// DEPLOYMENT.md — Nginx Proxy Manager; the app port isn't published
// directly to the host). nginx's default `$proxy_add_x_forwarded_for`
// *appends* the real client IP to any X-Forwarded-For it already
// received rather than replacing it, so a directly-connecting client
// could prepend arbitrary spoofed entries of their own. Only the
// right-most (last) entry — the one the trusted proxy itself appended —
// is trustworthy; taking the first entry would let a client bypass this
// rate limit entirely by sending a fake X-Forwarded-For header.
const forwarded = request.headers.get("x-forwarded-for");
if (forwarded) return forwarded.split(",")[0]!.trim();
if (forwarded) {
const parts = forwarded.split(",");
return parts[parts.length - 1]!.trim();
}
return "unknown";
}
+70 -9
View File
@@ -3,6 +3,8 @@ import { WEEKDAYS } from "@/collections/Availability";
export type TimeSlot = { start: Date; end: Date };
const BERLIN_TZ = "Europe/Berlin";
const WEEKDAY_BY_INDEX = [
"sunday",
"monday",
@@ -13,18 +15,73 @@ const WEEKDAY_BY_INDEX = [
"saturday",
] as const;
type CalendarDate = { year: number; month: number; day: number };
// Availability/AvailabilityOverrides times are entered by the admin in their
// browser (Europe/Berlin) and stored as UTC instants. All wall-clock reads
// and writes here go through Intl's Berlin timezone data (not local Date
// accessors, and not manual UTC+1/+2 arithmetic), so the server process's
// own timezone (this app runs in UTC in production) never leaks into the
// computed availability — see lib/calendar/timezone.ts for the same pattern.
function berlinParts(date: Date): CalendarDate & { hour: number; minute: number } {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: BERLIN_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).formatToParts(date);
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? "0");
return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour"), minute: get("minute") };
}
function berlinOffsetMinutes(date: Date): number {
const tzName = new Intl.DateTimeFormat("en-US", { timeZone: BERLIN_TZ, timeZoneName: "shortOffset" })
.formatToParts(date)
.find((p) => p.type === "timeZoneName")?.value ?? "GMT+1";
const match = tzName.match(/GMT([+-]\d+)(?::(\d+))?/);
const hours = match ? Number(match[1]) : 1;
const minutes = match?.[2] ? Number(match[2]) : 0;
return hours * 60 + (hours < 0 ? -minutes : minutes);
}
/** Converts a Europe/Berlin wall-clock date+time into the UTC instant it represents. */
function berlinWallTimeToUTC(date: CalendarDate, hour: number, minute: number): Date {
const guess = Date.UTC(date.year, date.month - 1, date.day, hour, minute);
return new Date(guess - berlinOffsetMinutes(new Date(guess)) * 60_000);
}
function dateKey(date: Date): string {
return date.toISOString().slice(0, 10);
const { year, month, day } = berlinParts(date);
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
function calendarDate(date: Date): CalendarDate {
const { year, month, day } = berlinParts(date);
return { year, month, day };
}
function addCalendarDays({ year, month, day }: CalendarDate, delta: number): CalendarDate {
// Pure calendar-rollover arithmetic (month/year boundaries) — no timezone
// conversion happens here, so using the UTC constructor is safe and simple.
const utc = new Date(Date.UTC(year, month - 1, day + delta));
return { year: utc.getUTCFullYear(), month: utc.getUTCMonth() + 1, day: utc.getUTCDate() };
}
function weekdayOf({ year, month, day }: CalendarDate): (typeof WEEKDAY_BY_INDEX)[number] {
return WEEKDAY_BY_INDEX[new Date(Date.UTC(year, month - 1, day)).getUTCDay()];
}
function timeOfDayMinutes(date: Date): number {
return date.getHours() * 60 + date.getMinutes();
const { hour, minute } = berlinParts(date);
return hour * 60 + minute;
}
function atMinutesOfDay(day: Date, minutes: number): Date {
const d = new Date(day);
d.setHours(0, Math.round(minutes), 0, 0);
return d;
function atMinutesOfDay(day: CalendarDate, minutes: number): Date {
const rounded = Math.round(minutes);
return berlinWallTimeToUTC(day, Math.floor(rounded / 60), rounded % 60);
}
function overlaps(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
@@ -67,8 +124,12 @@ export async function getAvailableSlots(
const overridesByDate = new Map(overrides.map((o) => [dateKey(new Date(o.date)), o]));
const now = new Date();
for (let day = new Date(from); day <= to; day = new Date(day.getTime() + 24 * 60 * 60 * 1000)) {
const key = dateKey(day);
for (
let day = calendarDate(from);
atMinutesOfDay(day, 0) <= to;
day = addCalendarDays(day, 1)
) {
const key = `${day.year}-${String(day.month).padStart(2, "0")}-${String(day.day).padStart(2, "0")}`;
const override = overridesByDate.get(key);
let windows: { startMinutes: number; endMinutes: number }[] = [];
@@ -83,7 +144,7 @@ export async function getAvailableSlots(
},
];
} else {
const weekdayName = WEEKDAY_BY_INDEX[day.getDay()];
const weekdayName = weekdayOf(day);
windows = weekly
.filter((w) => w.weekday === weekdayName)
.map((w) => ({
+5
View File
@@ -15,6 +15,11 @@ function escapeICSText(value: string): string {
.replace(/\\/g, "\\\\")
.replace(/;/g, "\\;")
.replace(/,/g, "\\,")
// \r must be stripped (not just \n escaped): many ICS parsers split
// lines on a bare CR too, so leaving it unescaped lets untrusted text
// (e.g. a customer's booking message ending up in DESCRIPTION) break
// out of the property value and inject extra iCalendar lines/properties.
.replace(/\r\n?/g, "\\n")
.replace(/\n/g, "\\n");
}
+3 -1
View File
@@ -7,6 +7,7 @@ export type ParticipantSummary = {
};
export type ClientToServerMessage =
| { type: "auth"; token: string }
| { type: "offer"; to: string; payload: RTCSessionDescriptionInit }
| { type: "answer"; to: string; payload: RTCSessionDescriptionInit }
| { type: "ice-candidate"; to: string; payload: RTCIceCandidateInit }
@@ -19,4 +20,5 @@ export type ServerToClientMessage =
| { type: "offer"; from: string; payload: RTCSessionDescriptionInit }
| { type: "answer"; from: string; payload: RTCSessionDescriptionInit }
| { type: "ice-candidate"; from: string; payload: RTCIceCandidateInit }
| { type: "kicked" };
| { type: "kicked" }
| { type: "auth-error"; reason: string };
+19 -3
View File
@@ -4,6 +4,7 @@ import type { MeetingRole } from "./token";
export type Participant = {
ws: WebSocket;
participantId: string;
clientId?: string;
name: string;
role: MeetingRole;
};
@@ -11,6 +12,11 @@ export type Participant = {
type Room = {
participants: Map<string, Participant>;
kickedParticipantIds: Set<string>;
// Keyed by the client-declared, localStorage-persisted clientId (see
// token.ts) rather than the per-connection participantId, so a kick
// survives the participant simply reconnecting (which always mints a
// fresh participantId) — see isKicked below.
kickedClientIds: Set<string>;
};
// In-memory only — this server process is the single source of truth for
@@ -22,19 +28,27 @@ const rooms = new Map<string, Room>();
function getOrCreateRoom(eventSlug: string): Room {
let room = rooms.get(eventSlug);
if (!room) {
room = { participants: new Map(), kickedParticipantIds: new Set() };
room = { participants: new Map(), kickedParticipantIds: new Set(), kickedClientIds: new Set() };
rooms.set(eventSlug, room);
}
return room;
}
export function isKicked(eventSlug: string, participantId: string): boolean {
return rooms.get(eventSlug)?.kickedParticipantIds.has(participantId) ?? false;
export function isKicked(eventSlug: string, participantId: string, clientId?: string): boolean {
const room = rooms.get(eventSlug);
if (!room) return false;
if (room.kickedParticipantIds.has(participantId)) return true;
return clientId ? room.kickedClientIds.has(clientId) : false;
}
export function joinRoom(eventSlug: string, participant: Participant): Participant[] {
const room = getOrCreateRoom(eventSlug);
const existing = [...room.participants.values()];
// Two connections claiming the same participantId (e.g. two tabs replaying
// the same stored session) would otherwise silently overwrite the map
// entry here and orphan the first socket — close it first so it doesn't
// leak as an unreachable broadcast target.
room.participants.get(participant.participantId)?.ws.close(4002, "replaced-by-new-connection");
room.participants.set(participant.participantId, participant);
return existing;
}
@@ -50,6 +64,8 @@ export function kickFromRoom(eventSlug: string, participantId: string) {
const room = rooms.get(eventSlug);
if (!room) return;
room.kickedParticipantIds.add(participantId);
const target = room.participants.get(participantId);
if (target?.clientId) room.kickedClientIds.add(target.clientId);
room.participants.delete(participantId);
}
+65 -40
View File
@@ -1,4 +1,3 @@
import type { IncomingMessage } from "node:http";
import type { WebSocket, WebSocketServer } from "ws";
import { verifyMeetingToken } from "./token";
import {
@@ -12,46 +11,61 @@ import {
} from "./rooms";
import type { ClientToServerMessage, ParticipantSummary } from "./protocol";
// A connection has this long to send its "auth" message before being
// dropped. The token travels as the first WS message rather than a
// `?token=` query parameter so it doesn't end up persisted in reverse-proxy
// or access logs; it's still HMAC-signed and short-lived either way.
const AUTH_TIMEOUT_MS = 10_000;
function participantSummary(p: Participant): ParticipantSummary {
return { participantId: p.participantId, name: p.name, role: p.role };
}
export function attachSignalingServer(wss: WebSocketServer) {
wss.on("connection", (ws: WebSocket, req: IncomingMessage) => {
const url = new URL(req.url ?? "", "http://internal");
const token = url.searchParams.get("token") ?? "";
const payload = verifyMeetingToken(token);
wss.on("connection", (ws: WebSocket) => {
let self: Participant | null = null;
let eventSlug: string | null = null;
if (!payload) {
ws.close(4000, "invalid-token");
return;
const authTimeout = setTimeout(() => {
if (!self) ws.close(4000, "auth-timeout");
}, AUTH_TIMEOUT_MS);
function handleAuth(token: string) {
const payload = verifyMeetingToken(token);
if (!payload) {
ws.send(JSON.stringify({ type: "auth-error", reason: "invalid-token" }));
ws.close(4000, "invalid-token");
return;
}
if (isKicked(payload.eventSlug, payload.participantId, payload.clientId)) {
ws.close(4001, "removed-by-host");
return;
}
eventSlug = payload.eventSlug;
self = {
ws,
participantId: payload.participantId,
clientId: payload.clientId,
name: payload.name,
role: payload.role,
};
const existing = joinRoom(eventSlug, self);
ws.send(
JSON.stringify({
type: "welcome",
participantId: self.participantId,
role: self.role,
participants: existing.map(participantSummary),
}),
);
broadcast(eventSlug, { type: "peer-joined", ...participantSummary(self) }, {
exclude: self.participantId,
});
}
if (isKicked(payload.eventSlug, payload.participantId)) {
ws.close(4001, "removed-by-host");
return;
}
const self: Participant = {
ws,
participantId: payload.participantId,
name: payload.name,
role: payload.role,
};
const existing = joinRoom(payload.eventSlug, self);
ws.send(
JSON.stringify({
type: "welcome",
participantId: self.participantId,
role: self.role,
participants: existing.map(participantSummary),
}),
);
broadcast(payload.eventSlug, { type: "peer-joined", ...participantSummary(self) }, {
exclude: self.participantId,
});
ws.on("message", (raw) => {
let message: ClientToServerMessage;
@@ -61,8 +75,17 @@ export function attachSignalingServer(wss: WebSocketServer) {
return;
}
if (message.type === "auth") {
clearTimeout(authTimeout);
if (self) return; // already authenticated on this connection
handleAuth(message.token);
return;
}
if (!self || !eventSlug) return; // no messages accepted before auth
if (message.type === "offer" || message.type === "answer" || message.type === "ice-candidate") {
const target = getParticipant(payload.eventSlug, message.to);
const target = getParticipant(eventSlug, message.to);
if (target && target.ws.readyState === target.ws.OPEN) {
target.ws.send(
JSON.stringify({ type: message.type, from: self.participantId, payload: message.payload }),
@@ -73,18 +96,20 @@ export function attachSignalingServer(wss: WebSocketServer) {
if (message.type === "kick") {
if (self.role !== "host") return; // server-side authority, not client-claimed
const target = getParticipant(payload.eventSlug, message.targetParticipantId);
const target = getParticipant(eventSlug, message.targetParticipantId);
if (!target) return;
kickFromRoom(payload.eventSlug, target.participantId);
kickFromRoom(eventSlug, target.participantId);
target.ws.send(JSON.stringify({ type: "kicked" }));
target.ws.close(4001, "removed-by-host");
broadcast(payload.eventSlug, { type: "peer-left", participantId: target.participantId });
broadcast(eventSlug, { type: "peer-left", participantId: target.participantId });
}
});
ws.on("close", () => {
leaveRoom(payload.eventSlug, self.participantId);
broadcast(payload.eventSlug, { type: "peer-left", participantId: self.participantId });
clearTimeout(authTimeout);
if (!self || !eventSlug) return;
leaveRoom(eventSlug, self.participantId);
broadcast(eventSlug, { type: "peer-left", participantId: self.participantId });
});
});
}
+16
View File
@@ -5,6 +5,16 @@ export type MeetingRole = "host" | "participant";
export type MeetingTokenPayload = {
eventSlug: string;
participantId: string;
// Self-declared, persisted client-side (localStorage, not sessionStorage)
// identity for participants — participantId is fresh per /join call, so
// without this a kick could always be undone by simply rejoining. Only
// used to make a kick stick across a rejoin (see rooms.ts kickedClientIds);
// never used to key live room membership, so a client choosing an
// arbitrary/colliding value can only affect their own future kick status,
// never another participant's connection. Still bypassable by clearing
// localStorage or joining from a different browser — there's no real
// identity to anchor to for an unauthenticated participant.
clientId?: string;
name: string;
role: MeetingRole;
exp: number; // unix ms
@@ -29,12 +39,18 @@ export function createMeetingToken(args: {
eventSlug: string;
name: string;
role: MeetingRole;
clientId?: string;
ttlMs?: number;
}): { token: string; participantId: string } {
const participantId = randomUUID();
const clientId =
typeof args.clientId === "string" && args.clientId.length > 0 && args.clientId.length <= 100
? args.clientId
: undefined;
const payload: MeetingTokenPayload = {
eventSlug: args.eventSlug,
participantId,
clientId,
name: args.name,
role: args.role,
exp: Date.now() + (args.ttlMs ?? 6 * 60 * 60 * 1000), // 6h default