fix(tickets): staff scans skip the public ticket limit; order lookups for naming are rate-limited

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-04 17:56:55 +08:00
1 parent 051fca9a13
commit 02aa19a686
8 files changed
+45 -13

No files matched your search

+3 -3
View File
@@ -51,7 +51,7 @@ Product design: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (a
- Normalisation and the `MOBILE_OR_EMAIL_REQUIRED`, name-length and email-format errors reuse the QR registration helpers in mobile-api.
4. **Consent creates the lead through `RegistrationService.register`.** It is called with source `TICKET`, no salesperson, the company's current notice and `attend=false`. At check-in it is called with `attend=true`. The returned event lead uuid is stored on the ticket. An attendee whose details match a lead is linked to it, as QR registration already does.
- **Unnamed tickets:** the consent needs a name and contact, so on the public page it is offered only for a named ticket. At the door, staff enter them first.
5. **Staff view detection.** The `/t/[code]` page always loads the public view (`GET /api/public/tickets/{code}`). It also calls the portal's `/api/tickets/{code}`, which answers 401 at once when there is no session and otherwise calls `GET /api/admin/tickets/{code}`. That call is guarded by `@AdminModule("BO_EVENTS")` and scoped by company in mobile-api with `loadEvent(uuid, null)`, so another company's event is a 404. On 401, 403 or 404 the page stays public. The admin call uses a plain `fetch`, not `clientApi`, so a signed-out visitor is never bounced to login.
5. **Staff view detection.** The `/t/[code]` page first calls the portal's `/api/tickets/{code}`, which answers 401 at once when there is no session and otherwise calls `GET /api/admin/tickets/{code}`. Only when that fails does it load the public view (`GET /api/public/tickets/{code}`), so a door scan never counts toward the public `tkt:load` limit. That call is guarded by `@AdminModule("BO_EVENTS")` and scoped by company in mobile-api with `loadEvent(uuid, null)`, so another company's event is a 404. On 401, 403 or 404 the page stays public. The admin call uses a plain `fetch`, not `clientApi`, so a signed-out visitor is never bounced to login.
6. **Check-in.** `POST /api/admin/tickets/{code}/checkin` takes optional `{name, mobile, email, consent}`, which are required when the ticket is unnamed. Refusals are 409 with the codes `ALREADY_CHECKED_IN|<time>`, `NOT_VALID|<state>` and `NOT_EVENT_DAY`. The update is conditional (`checked_in_at IS NULL`), so two scanners cannot both check a ticket in; the loser gets `ALREADY_CHECKED_IN`. The action is `@Audited`.
7. **Self check-in on a ticketed event.** For `tickets_enabled` events only, `EventCheckInService.lookup` checks, in order:
1. the oldest `ACTIVE` ticket on a `PAID` order of the event, not checked in, whose attendee mobile or email matches, or whose attendee is blank and whose order's buyer mobile or email matches. It is checked in with `checked_in_by = 'self'`, and the lead is marked attended when the ticket has one;
@@ -74,7 +74,7 @@ Product design: `docs/superpowers/specs/2026-12-04-event-ticketing-design.md` (a
11. **Counts.** `EventHeadcountService.Headcount` gains `ticketsAwaiting`, `ticketsPaid` and `ticketsCheckedIn`, from one grouped query over active tickets joined to their order status. The portal's GuestsCard shows them when the event sells tickets.
12. **Limits.**
- `tkt:load:<ip>` allows 120 per 10 minutes, for the ticket page and the QR together.
- `tkt:submit:<ip>:<event>` allows 60 per 10 minutes, for naming and consent.
- `tkt:submit:<ip>:<event>` allows 60 per 10 minutes, for naming and consent. Naming first looks up the order by its token, which counts toward the order page's `ord:load:<ip>` limit (120 per 10 minutes).
- Staff check-in has no IP limit: it is an authenticated admin call.
## Data
@@ -101,7 +101,7 @@ ALTER TABLE `ticket`
| counter | `POST ticket/attendee` (order token, ticket id, attendee, permission) | public via gateway |
| counter | `POST ticket/consent` (code, notice id) | public via gateway |
| counter | `POST ticket/staff` and `POST ticket/checkin` (company id and code in the body) | JWT (from mobile-api admin) |
| counter | `POST ticketOrder/{id}/tickets/{ticketId}/resend` | JWT |
| counter | `POST ticketOrder/resendTicket` (company, event, order and ticket ids in the body) | JWT |
| mobile-api | `GET /api/public/tickets/{code}`, `GET .../qr.png`, `POST .../consent` | public |
| mobile-api | `POST /api/public/orders/{token}/tickets/{ticketId}/attendee` | public |
| mobile-api | `GET /api/admin/tickets/{code}`, `POST /api/admin/tickets/{code}/checkin` | `BO_EVENTS` |
@@ -111,6 +111,7 @@ export interface PublicTicket extends TicketEvent {
}
export interface StaffTicket extends TicketEvent {
companyName: string | null;
typeName: string | null;
attendeeName: string | null;
named: boolean;
@@ -22,7 +22,7 @@ const VALID = {
checkedInAt: null, consented: false, notice: NOTICE,
};
const STAFF = {
...EVENT, typeName: "General", attendeeName: "Tan Mei Ling", named: true, consented: false, state: "VALID",
...EVENT, companyName: "INS", typeName: "General", attendeeName: "Tan Mei Ling", named: true, consented: false, state: "VALID",
checkedInAt: null, checkedInBy: null, notice: NOTICE,
};
@@ -95,6 +95,16 @@ describe("/t/[code] staff view", () => {
expect(screen.queryByRole("button", { name: "Check in" })).not.toBeInTheDocument();
});
it("needs only the staff call, so the public limit never blocks door staff", async () => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
mocks.getPublicTicket.mockRejectedValue(new ApiError("x", 429, { code: "TOO_MANY" }));
render(<TicketPage />);
expect(await screen.findByRole("button", { name: "Check in" })).toBeInTheDocument();
expect(screen.getByRole("heading", { level: 1, name: "KL Hotel Tech Day" })).toBeInTheDocument();
expect(mocks.getPublicTicket).not.toHaveBeenCalled();
expect(screen.queryByRole("img", { name: "Ticket QR code" })).not.toBeInTheDocument();
});
it("shows the state banner and checks a named ticket in", async () => {
mocks.getStaffTicket.mockResolvedValue(STAFF);
render(<TicketPage />);
+12 -8
View File
@@ -36,24 +36,28 @@ export default function TicketPage() {
const [error, setError] = useState<string | null>(null);
useEffect(() => {
getPublicTicket(code)
// Staff first: a door scan then never touches the rate-limited public view. Signed out, another company's staff
// or no BO_EVENTS: the staff call fails and the page loads the public view.
getStaffTicket(code)
.then(setStaff)
.catch(() => getPublicTicket(code)
.then(setTicket)
.catch((err) => {
const c = apiData(err).code;
setError(t(c === "TICKET_INVALID" ? "TktTicketInvalid" : c === "TOO_MANY" ? "RegTooMany" : "RegLoadFailed"));
});
// Signed out, another company's staff or no BO_EVENTS: the call fails and the page stays public.
getStaffTicket(code).then(setStaff).catch(() => setStaff(null));
}));
}, [code, t]);
const shown = staff ?? ticket;
if (error) return <VisitorCard><VisitorState h1 icon={AlertCircle} heading={error} role="alert" tone="error" /></VisitorCard>;
if (!ticket) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
if (!shown) return <VisitorCard><VisitorState h1 icon={Loader2} iconClassName="motion-safe:animate-spin" heading={t("UiLoading")} role="status" /></VisitorCard>;
const event = { ...ticket, startDate: ticket.startDate ?? ticket.endDate ?? "", endDate: ticket.endDate ?? "", location: ticket.location ?? "" };
const event = { ...shown, companyName: shown.companyName ?? "", startDate: shown.startDate ?? shown.endDate ?? "",
endDate: shown.endDate ?? "", location: shown.location ?? "" };
return (
<VisitorCard event={event}>
{staff ? <StaffView code={code} staff={staff} companyName={ticket.companyName} onChange={setStaff} />
: <PublicView code={code} ticket={ticket} />}
{staff ? <StaffView code={code} staff={staff} companyName={event.companyName} onChange={setStaff} />
: ticket && <PublicView code={code} ticket={ticket} />}
</VisitorCard>
);
}
@@ -185,6 +185,9 @@ public class AdminTicketService {
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
out.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
out.put("location", e.getLocation());
Map<String, Object> company = PublicRegistrationService.found(() -> rest.getForEntity(
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID), MAP, e.getCompanyId()).getBody());
out.put("companyName", company == null ? null : company.get("name"));
if (!Boolean.TRUE.equals(out.get("consented"))) {
Map<String, Object> n = notice(e);
if (n.get("id") != null) {
@@ -38,6 +38,7 @@ import java.util.Set;
public class PublicTicketService {
private static final int LOAD_LIMIT = 120;
private static final int SUBMIT_LIMIT = 60;
private static final int ORDER_LOAD_LIMIT = 120;
private static final int QR_PX = 300;
private static final String TOO_MANY = "Too many requests from this device. Try again later.";
private static final Set<String> CONSENT_STATES = Set.of("VALID", "CHECKED_IN");
@@ -107,6 +108,8 @@ public class PublicTicketService {
/** The buyer names or renames a ticket of their Paid order; the counter issues a new code and emails the attendee. */
public Map<String, Object> attendee(String token, long ticketId, AttendeeRequest r) {
if (token == null || !PublicRegistrationService.TOKEN_SHAPE.matcher(token).matches()) throw orderInvalid();
// Probing order tokens counts as order loads, as on the order page, before the per-event submit limit.
registration.limit("ord:load:" + PublicRegistrationService.ip(), ORDER_LOAD_LIMIT, TOO_MANY);
Map<String, Object> order = PublicRegistrationService.found(() -> rest.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_TICKET_ORDER_BY_TOKEN), MAP, token).getBody());
if (order == null || !(order.get("eventUuid") instanceof Number uuid)) throw orderInvalid();
@@ -74,6 +74,8 @@ class AdminTicketCheckInTest {
when(auth.loadUserByToken("tok")).thenReturn(caller);
stubEvent(COMPANY);
stubTicket(COMPANY);
when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), eq(COMPANY)))
.thenReturn(ResponseEntity.ok(Map.of("id", COMPANY, "name", "INS", "status", "A")));
when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY)))
.thenReturn(ResponseEntity.ok(Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis")));
when(rest.postForEntity(anyString(), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of()));
@@ -126,7 +128,8 @@ class AdminTicketCheckInTest {
Map.of("typeName", "General", "attendeeName", "Tan Mei Ling", "named", true, "consented", false, "state", "VALID")));
Map<String, Object> out = service.ticket(CODE);
assertThat(sent(STAFF)).containsEntry("companyId", COMPANY).containsEntry("code", CODE);
assertThat(out).containsEntry("attendeeName", "Tan Mei Ling").containsEntry("eventName", "KL Hotel Tech Day");
assertThat(out).containsEntry("attendeeName", "Tan Mei Ling").containsEntry("eventName", "KL Hotel Tech Day")
.containsEntry("companyName", "INS");
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L);
}
@@ -263,6 +263,14 @@ class PublicTicketPageTest {
HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
}
@Test
void orderLookupsForNamingCountTowardTheOrderLoadLimitFirst() {
when(ops.increment("ord:load:1.2.3.4")).thenReturn(121L);
assertCoded(() -> service.attendee("zzzzzzzzzzzzzzzzzzzzzz", 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),
HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
verify(rest, never()).getForEntity(eq(BY_TOKEN), any(ParameterizedTypeReference.class), anyString());
}
@Test
void aBadOrderTokenIsNotValid() {
assertCoded(() -> service.attendee("bad", 1L, new PublicTicketService.AttendeeRequest("Tan", null, "t@x.test", true)),