fix(roster): escape HTML interpolations and sync capacity counter on 409 reconciliation

This commit is contained in:
anneux committed 2026-10-27 07:32:45 -05:00
1 parent faa2d34b54
commit 9191899154
3 files changed
+144 -18

No files matched your search

+16
View File
@@ -125,3 +125,19 @@ The implementation strictly respects the Scope Containment Invariant:
- **Notice 1 (String Matching on HTTP 409 detail)**: - **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`). 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).
+55 -18
View File
@@ -97,6 +97,39 @@ export type ConflictType =
| "CAPACITY_EXCEEDED" | "CAPACITY_EXCEEDED"
| "UNKNOWN"; | "UNKNOWN";
/**
* Escape HTML characters to prevent XSS in template string interpolations
*/
export function escapeHtml(str: string): string {
return str
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
/**
* 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 * Disambiguate HTTP 409 Conflict based on response detail
*/ */
@@ -151,7 +184,7 @@ export function renderWorkshopRoster(
type="date" type="date"
id="roster-date-input" id="roster-date-input"
class="form-input-date" class="form-input-date"
value="${selectedDate}" value="${escapeHtml(selectedDate)}"
aria-label="Seleccionar fecha de talleres" aria-label="Seleccionar fecha de talleres"
/> />
</div> </div>
@@ -247,7 +280,7 @@ export function renderWorkshopRoster(
<div class="empty-icon" aria-hidden="true">🪷</div> <div class="empty-icon" aria-hidden="true">🪷</div>
<h3 class="empty-title">Sin talleres programados</h3> <h3 class="empty-title">Sin talleres programados</h3>
<p class="empty-message">No hay talleres grupales programados para esta fecha.</p> <p class="empty-message">No hay talleres grupales programados para esta fecha.</p>
<p class="text-xs text-muted mt-2">Fecha seleccionada: ${dateStr}. Navega a otra fecha para consultar talleres.</p> <p class="text-xs text-muted mt-2">Fecha seleccionada: ${escapeHtml(dateStr)}. Navega a otra fecha para consultar talleres.</p>
</div> </div>
`; `;
} }
@@ -296,8 +329,8 @@ export function renderWorkshopRoster(
card.innerHTML = ` card.innerHTML = `
<div class="session-card-header"> <div class="session-card-header">
<div class="session-title-block"> <div class="session-title-block">
<span class="session-time-pill" title="Horario del taller">⏰ ${timeStr} hrs</span> <span class="session-time-pill" title="Horario del taller">⏰ ${escapeHtml(timeStr)} hrs</span>
<h3 class="session-title">${session.service_name}</h3> <h3 class="session-title">${escapeHtml(session.service_name)}</h3>
</div> </div>
<div class="session-header-actions"> <div class="session-header-actions">
<span class="session-capacity-counter font-mono font-medium" id="capacity-counter-${sessionIdx}"> <span class="session-capacity-counter font-mono font-medium" id="capacity-counter-${sessionIdx}">
@@ -343,6 +376,7 @@ export function renderWorkshopRoster(
attendee.attended || attendee.booking_status === "COMPLETED"; attendee.attended || attendee.booking_status === "COMPLETED";
const waUrl = buildWhatsAppUrl(attendee.client_phone); const waUrl = buildWhatsAppUrl(attendee.client_phone);
const formattedPhone = formatMexicanPhone(attendee.client_phone); const formattedPhone = formatMexicanPhone(attendee.client_phone);
const cleanPhoneDigits = getCleanDigitsPhone(attendee.client_phone);
const attendanceBadge = renderAttendanceStatusBadge( const attendanceBadge = renderAttendanceStatusBadge(
isAttended, isAttended,
@@ -365,7 +399,7 @@ export function renderWorkshopRoster(
type="checkbox" type="checkbox"
id="cash-check-${sessionIdx}-${attIdx}" id="cash-check-${sessionIdx}-${attIdx}"
class="cash-checkbox" class="cash-checkbox"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
/> />
<span class="text-xs">Cobro en efectivo recibido</span> <span class="text-xs">Cobro en efectivo recibido</span>
</label> </label>
@@ -374,7 +408,7 @@ export function renderWorkshopRoster(
class="btn btn-primary btn-sm btn-checkin" class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}" data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}" data-att-idx="${attIdx}"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
> >
Registrar Asistencia Registrar Asistencia
</button> </button>
@@ -389,7 +423,7 @@ export function renderWorkshopRoster(
class="btn btn-primary btn-sm btn-checkin" class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}" data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}" data-att-idx="${attIdx}"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
> >
Registrar Asistencia Registrar Asistencia
</button> </button>
@@ -398,24 +432,24 @@ export function renderWorkshopRoster(
} }
return ` return `
<div class="roster-attendee-row ${isAttended ? "row-attended" : ""}" data-booking-id="${attendee.booking_id}"> <div class="roster-attendee-row ${isAttended ? "row-attended" : ""}" data-booking-id="${escapeHtml(attendee.booking_id)}">
<div class="attendee-col-client"> <div class="attendee-col-client">
<span class="attendee-name font-medium">${attendee.client_name}</span> <span class="attendee-name font-medium">${escapeHtml(attendee.client_name)}</span>
<span class="attendee-code font-mono">${attendee.booking_code}</span> <span class="attendee-code font-mono">${escapeHtml(attendee.booking_code)}</span>
</div> </div>
<div class="attendee-col-phone"> <div class="attendee-col-phone">
<span class="attendee-phone-text">${formattedPhone}</span> <span class="attendee-phone-text">${escapeHtml(formattedPhone)}</span>
<a <a
href="${waUrl}" href="${escapeHtml(waUrl)}"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="btn-wa-link" class="btn-wa-link"
title="Abrir chat en WhatsApp" title="Abrir chat en WhatsApp"
aria-label="Contactar a ${attendee.client_name} por WhatsApp" aria-label="Contactar a ${escapeHtml(attendee.client_name)} por WhatsApp"
> >
<span class="wa-icon" aria-hidden="true">💬</span> <span class="wa-icon" aria-hidden="true">💬</span>
<span class="wa-label font-mono text-xs">wa.me/${getCleanDigitsPhone(attendee.client_phone)}</span> <span class="wa-label font-mono text-xs">wa.me/${escapeHtml(cleanPhoneDigits)}</span>
</a> </a>
</div> </div>
@@ -528,10 +562,13 @@ export function renderWorkshopRoster(
if (conflictType === "ALREADY_CHECKED_IN") { if (conflictType === "ALREADY_CHECKED_IN") {
// 409 Case A: Reconcile row to ASISTIÓ, disable button, informative toast // 409 Case A: Reconcile row to ASISTIÓ, disable button, informative toast
attendee.attended = true; const incremented = reconcileAlreadyCheckedInState(session, attendee);
attendee.booking_status = "COMPLETED"; if (incremented) {
updateCapacityDisplay(session, sessionIdx);
}
updateRowAttendanceState(rowEl, attendee); updateRowAttendanceState(rowEl, attendee);
showToast("El asistente ya contaba con asistencia registrada", "info"); showToast("El asistente ya contaba con asistencia registrada", "info");
onStateChange?.();
} else { } else {
// Ordinary failure / timeout // Ordinary failure / timeout
button.disabled = false; button.disabled = false;
@@ -613,11 +650,11 @@ export function renderWorkshopRoster(
<div class="summary-box"> <div class="summary-box">
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Taller:</span> <span class="summary-label">Taller:</span>
<span class="summary-value font-medium">${session.service_name}</span> <span class="summary-value font-medium">${escapeHtml(session.service_name)}</span>
</div> </div>
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Horario:</span> <span class="summary-label">Horario:</span>
<span class="summary-value font-mono font-bold">${timeStr} hrs</span> <span class="summary-value font-mono font-bold">${escapeHtml(timeStr)} hrs</span>
</div> </div>
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Capacidad Actual:</span> <span class="summary-label">Capacidad Actual:</span>
+73
View File
@@ -2,10 +2,13 @@ import { describe, expect, it } from "vitest";
import { import {
buildWhatsAppUrl, buildWhatsAppUrl,
disambiguate409Error, disambiguate409Error,
escapeHtml,
formatRosterCapacity, formatRosterCapacity,
reconcileAlreadyCheckedInState,
renderAttendanceStatusBadge, renderAttendanceStatusBadge,
renderPaymentStatusPill, renderPaymentStatusPill,
} from "../src/components/WorkshopRoster"; } from "../src/components/WorkshopRoster";
import type { RosterAttendee, RosterSession } from "../src/types";
describe("Workshop Roster Utilities", () => { describe("Workshop Roster Utilities", () => {
describe("Capacity Formatting", () => { describe("Capacity Formatting", () => {
@@ -97,4 +100,74 @@ describe("Workshop Roster Utilities", () => {
expect(disambiguate409Error(undefined)).toBe("UNKNOWN"); expect(disambiguate409Error(undefined)).toBe("UNKNOWN");
}); });
}); });
describe("HTML Sanitization (escapeHtml)", () => {
it("escapes dangerous HTML characters to prevent XSS", () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
"&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;",
);
expect(escapeHtml("Tom & Jerry's")).toBe("Tom &amp; Jerry&#039;s");
expect(escapeHtml('<img src="x" onerror="alert(1)">')).toBe(
"&lt;img src=&quot;x&quot; onerror=&quot;alert(1)&quot;&gt;",
);
});
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);
});
});
}); });