diff --git a/docs/evidence/anne-self-audit.md b/docs/evidence/anne-self-audit.md index ab542d5..03f9887 100644 --- a/docs/evidence/anne-self-audit.md +++ b/docs/evidence/anne-self-audit.md @@ -125,3 +125,19 @@ The implementation strictly respects the Scope Containment Invariant: - **Notice 1 (String Matching on HTTP 409 detail)**: As anticipated in Section 2.1 of `SPEC-WORKSHOP-ROSTER.md`, disambiguating between duplicate check-in (`"This attendee has already checked in."`) and session capacity (`"El taller ha alcanzado su cupo máximo..."`) relies on substring matching on `response.detail`. This is preserved as an accepted pilot accommodation to maintain backend immutability on `armonia-api`. An M5 ticket will introduce machine-readable error codes (`error_code`). + +--- + +## 6. Addendum: Post-Review Revision (Targeted 1-Commit Fix) + +Following Project Owner review of PR #9, two targeted ergonomic and security enhancements were implemented: +1. **Finding A: HTML Sanitization (`escapeHtml`)**: + - Introduced and exported `escapeHtml(str: string): string` in `src/components/WorkshopRoster.ts` (matching the pattern in `ClientDirectory.ts` and `IntakeModal.ts`). + - Sanitized all dynamic string interpolations (`attendee.client_name`, `attendee.client_phone`, `attendee.booking_code`, `session.service_name`, date strings, etc.) across visible text nodes and attribute values (`aria-label`, `title`, `href`, `data-booking-id`). +2. **Finding B: Out-of-Band 409 Capacity Counter Synchronization**: + - Implemented `reconcileAlreadyCheckedInState()` in `src/components/WorkshopRoster.ts`. + - When an `ALREADY_CHECKED_IN` 409 conflict occurs for an attendee who was locally unrecorded (`!attendee.attended`), `session.attended_count` is now incremented by 1 and `updateCapacityDisplay(session, sessionIdx)` is invoked, ensuring header capacity counters remain strictly synchronized even during out-of-band check-ins across devices. +3. **Verification**: + - Added unit test suites in `tests/roster.test.ts` validating HTML escaping (XSS vectors, attributes, plain strings) and 409 state reconciliation (incrementing when locally unrecorded, idempotent when already recorded). + - Test suite passes 100%: 33/33 tests passing (17 utils + 16 roster). + diff --git a/src/components/WorkshopRoster.ts b/src/components/WorkshopRoster.ts index 2ffff38..c1acbf1 100644 --- a/src/components/WorkshopRoster.ts +++ b/src/components/WorkshopRoster.ts @@ -97,6 +97,39 @@ export type ConflictType = | "CAPACITY_EXCEEDED" | "UNKNOWN"; +/** + * Escape HTML characters to prevent XSS in template string interpolations + */ +export function escapeHtml(str: string): string { + return str + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +/** + * Reconcile session state upon out-of-band 409 ALREADY_CHECKED_IN conflict. + * Ensures attendance status is COMPLETED / ASISTIÓ, and if the attendee was + * previously unrecorded locally, increments attended_count. + * Returns true if attended_count was incremented. + */ +export function reconcileAlreadyCheckedInState( + session: RosterSession, + attendee: RosterAttendee, +): boolean { + const wasAttended = + attendee.attended || attendee.booking_status === "COMPLETED"; + attendee.attended = true; + attendee.booking_status = "COMPLETED"; + if (!wasAttended) { + session.attended_count += 1; + return true; + } + return false; +} + /** * Disambiguate HTTP 409 Conflict based on response detail */ @@ -151,7 +184,7 @@ export function renderWorkshopRoster( type="date" id="roster-date-input" class="form-input-date" - value="${selectedDate}" + value="${escapeHtml(selectedDate)}" aria-label="Seleccionar fecha de talleres" /> @@ -247,7 +280,7 @@ export function renderWorkshopRoster(

Sin talleres programados

No hay talleres grupales programados para esta fecha.

-

Fecha seleccionada: ${dateStr}. Navega a otra fecha para consultar talleres.

+

Fecha seleccionada: ${escapeHtml(dateStr)}. Navega a otra fecha para consultar talleres.

`; } @@ -296,8 +329,8 @@ export function renderWorkshopRoster( card.innerHTML = `
- ⏰ ${timeStr} hrs -

${session.service_name}

+ ⏰ ${escapeHtml(timeStr)} hrs +

${escapeHtml(session.service_name)}

@@ -343,6 +376,7 @@ export function renderWorkshopRoster( attendee.attended || attendee.booking_status === "COMPLETED"; const waUrl = buildWhatsAppUrl(attendee.client_phone); const formattedPhone = formatMexicanPhone(attendee.client_phone); + const cleanPhoneDigits = getCleanDigitsPhone(attendee.client_phone); const attendanceBadge = renderAttendanceStatusBadge( isAttended, @@ -365,7 +399,7 @@ export function renderWorkshopRoster( type="checkbox" id="cash-check-${sessionIdx}-${attIdx}" class="cash-checkbox" - data-booking-id="${attendee.booking_id}" + data-booking-id="${escapeHtml(attendee.booking_id)}" /> Cobro en efectivo recibido @@ -374,7 +408,7 @@ export function renderWorkshopRoster( class="btn btn-primary btn-sm btn-checkin" data-session-idx="${sessionIdx}" data-att-idx="${attIdx}" - data-booking-id="${attendee.booking_id}" + data-booking-id="${escapeHtml(attendee.booking_id)}" > Registrar Asistencia @@ -389,7 +423,7 @@ export function renderWorkshopRoster( class="btn btn-primary btn-sm btn-checkin" data-session-idx="${sessionIdx}" data-att-idx="${attIdx}" - data-booking-id="${attendee.booking_id}" + data-booking-id="${escapeHtml(attendee.booking_id)}" > Registrar Asistencia @@ -398,24 +432,24 @@ export function renderWorkshopRoster( } return ` -
+
- ${attendee.client_name} - ${attendee.booking_code} + ${escapeHtml(attendee.client_name)} + ${escapeHtml(attendee.booking_code)}
@@ -528,10 +562,13 @@ export function renderWorkshopRoster( if (conflictType === "ALREADY_CHECKED_IN") { // 409 Case A: Reconcile row to ASISTIÓ, disable button, informative toast - attendee.attended = true; - attendee.booking_status = "COMPLETED"; + const incremented = reconcileAlreadyCheckedInState(session, attendee); + if (incremented) { + updateCapacityDisplay(session, sessionIdx); + } updateRowAttendanceState(rowEl, attendee); showToast("El asistente ya contaba con asistencia registrada", "info"); + onStateChange?.(); } else { // Ordinary failure / timeout button.disabled = false; @@ -613,11 +650,11 @@ export function renderWorkshopRoster(
Taller: - ${session.service_name} + ${escapeHtml(session.service_name)}
Horario: - ${timeStr} hrs + ${escapeHtml(timeStr)} hrs
Capacidad Actual: diff --git a/tests/roster.test.ts b/tests/roster.test.ts index 94740a6..65185d6 100644 --- a/tests/roster.test.ts +++ b/tests/roster.test.ts @@ -2,10 +2,13 @@ import { describe, expect, it } from "vitest"; import { buildWhatsAppUrl, disambiguate409Error, + escapeHtml, formatRosterCapacity, + reconcileAlreadyCheckedInState, renderAttendanceStatusBadge, renderPaymentStatusPill, } from "../src/components/WorkshopRoster"; +import type { RosterAttendee, RosterSession } from "../src/types"; describe("Workshop Roster Utilities", () => { describe("Capacity Formatting", () => { @@ -97,4 +100,74 @@ describe("Workshop Roster Utilities", () => { expect(disambiguate409Error(undefined)).toBe("UNKNOWN"); }); }); + + describe("HTML Sanitization (escapeHtml)", () => { + it("escapes dangerous HTML characters to prevent XSS", () => { + expect(escapeHtml('')).toBe( + "<script>alert("xss")</script>", + ); + expect(escapeHtml("Tom & Jerry's")).toBe("Tom & Jerry's"); + expect(escapeHtml('')).toBe( + "<img src="x" onerror="alert(1)">", + ); + }); + + it("leaves strings without special characters untouched", () => { + expect(escapeHtml("Elena Gómez")).toBe("Elena Gómez"); + expect(escapeHtml("ADS-1001")).toBe("ADS-1001"); + expect(escapeHtml("+52 55 1111 2222")).toBe("+52 55 1111 2222"); + }); + }); + + describe("409 Out-of-Band Counter Reconciliation", () => { + function createMockSession(occupied = 2, attended = 0): RosterSession { + return { + service_id: "srv-123", + service_name: "Círculo de Cacao", + scheduled_at: "2026-10-26T18:00:00Z", + max_capacity: 15, + occupied_count: occupied, + attended_count: attended, + attendees: [], + }; + } + + function createMockAttendee(attended = false): RosterAttendee { + return { + booking_id: "bk-123", + booking_code: "ADS-1001", + client_id: "cl-123", + client_name: "Elena Gómez", + client_phone: "525511112222", + booking_status: attended ? "COMPLETED" : "RESERVED", + payment_arrangement: "PREPAID_DEFAULT", + payment_status: "ACKNOWLEDGED", + amount_mxn: 350, + attended, + }; + } + + it("increments attended_count and reconciles attendee when locally unrecorded", () => { + const session = createMockSession(2, 0); + const attendee = createMockAttendee(false); + + const incremented = reconcileAlreadyCheckedInState(session, attendee); + + expect(incremented).toBe(true); + expect(session.attended_count).toBe(1); + expect(attendee.attended).toBe(true); + expect(attendee.booking_status).toBe("COMPLETED"); + }); + + it("does not increment attended_count if attendee was already marked attended locally", () => { + const session = createMockSession(2, 1); + const attendee = createMockAttendee(true); + + const incremented = reconcileAlreadyCheckedInState(session, attendee); + + expect(incremented).toBe(false); + expect(session.attended_count).toBe(1); // Unchanged + expect(attendee.attended).toBe(true); + }); + }); });