feat: public invite and check-in pages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 20:37:02 +08:00
1 parent 8831feaf4c
commit 65b02fb927
21 files changed
+708 -173

No files matched your search

@@ -124,7 +124,7 @@ Waves:
Every portal verify must report the exit codes of lint, tsc and vitest. Vitest exits 1 on unhandled errors even when every test passes.
- [ ] 5.1 Public pages: extract the shared registration form from `/r/[token]`; add `/i/[token]` and `/c/[token]` and their proxies; make all three paths public in `routeGuard` with one pattern, including the reset-pending exemption.
- [x] 5.1 Public pages: extract the shared registration form from `/r/[token]`; add `/i/[token]` and `/c/[token]` and their proxies; make all three paths public in `routeGuard` with one pattern, including the reset-pending exemption.
- Depends on: 3.2, the visual revamp foundation
- Tests first:
- **Route guard:** `/i/x` and `/c/x` pass signed out and with a reset pending; `/events`, `/i` and `/c/` still redirect.
@@ -0,0 +1,3 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
export const POST = publicRoute("checkin", "/lookup", "POST");
@@ -0,0 +1,3 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
export const POST = publicRoute("checkin", "/register", "POST");
@@ -0,0 +1,3 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
export const GET = publicRoute("checkin", "", "GET");
@@ -0,0 +1,3 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
export const POST = publicRoute("invite", "/checkin", "POST");
@@ -0,0 +1,4 @@
import { publicRoute } from "@/app/lib/server/publicProxy";
export const GET = publicRoute("invite", "", "GET");
export const POST = publicRoute("invite", "", "POST");
@@ -0,0 +1,44 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
import { GET as inviteGet, POST as invitePost } from "./invite/[token]/route";
import { POST as inviteCheckin } from "./invite/[token]/checkin/route";
import { GET as checkinGet } from "./checkin/[token]/route";
import { POST as lookup } from "./checkin/[token]/lookup/route";
import { POST as walkIn } from "./checkin/[token]/register/route";
type Handler = (req: never, ctx: { params: Promise<{ token: string }> }) => Promise<Response>;
const ctx = { params: Promise.resolve({ token: "tok/1" }) };
const call = (h: unknown, init: RequestInit = {}) => (h as Handler)(new Request("http://localhost/x", init) as never, ctx);
const xff = { "x-forwarded-for": "6.6.6.6, 203.0.113.7" };
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { state: "OPEN" } }));
describe("public invite and check-in proxies", () => {
it.each([
["invite GET", inviteGet, "GET", "/api/public/invite/tok%2F1"],
["invite POST", invitePost, "POST", "/api/public/invite/tok%2F1"],
["invite checkin POST", inviteCheckin, "POST", "/api/public/invite/tok%2F1/checkin"],
["checkin GET", checkinGet, "GET", "/api/public/checkin/tok%2F1"],
["lookup POST", lookup, "POST", "/api/public/checkin/tok%2F1/lookup"],
["register POST", walkIn, "POST", "/api/public/checkin/tok%2F1/register"],
])("%s maps to mobile-api with only the last X-Forwarded-For hop", async (_n, h, method, path) => {
const res = await call(h, method === "GET" ? { headers: xff } : { method, body: JSON.stringify({ a: 1 }), headers: xff });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ state: "OPEN" });
const [p, opts] = mocks.callMobileApi.mock.calls[0];
expect(p).toBe(path);
expect(opts.headers).toEqual({ "X-Forwarded-For": "203.0.113.7" });
if (method === "POST") expect(opts).toMatchObject({ method: "POST", body: { a: 1 } });
else expect(opts.method).toBeUndefined();
});
it("passes upstream failures with status and code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "This event is full", status: 409, code: "EVENT_FULL" });
const res = await call(invitePost, { method: "POST", body: "{}" });
expect(res.status).toBe(409);
expect(((await res.json()) as Record<string, unknown>).code).toBe("EVENT_FULL");
});
});
@@ -1,35 +1,5 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import { errorResponse } from "@/app/lib/server/apiRoute";
import { publicRoute } from "@/app/lib/server/publicProxy";
// Public (signed-out) proxy for the QR registration page: no session token.
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
type Ctx = { params: Promise<{ token: string }> };
function forwardedFor(req: NextRequest): Record<string, string> {
const xff = clientIp(req);
return xff ? { "X-Forwarded-For": xff } : {};
}
export async function GET(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function POST(req: NextRequest, { params }: Ctx) {
const { token } = await params;
const body = await req.json().catch(() => ({}));
const result = await callMobileApi<Record<string, unknown>>(`/api/public/registration/${encodeURIComponent(token)}`, {
method: "POST",
body,
headers: forwardedFor(req),
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
// Public (signed-out) proxy for the QR registration page; see publicProxy for the X-Forwarded-For rule.
export const GET = publicRoute("registration", "", "GET");
export const POST = publicRoute("registration", "", "POST");
@@ -0,0 +1,105 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getCheckin: vi.fn(), lookupCheckin: vi.fn(), registerWalkIn: vi.fn() }));
vi.mock("@/app/lib/services/publicInvite", () => mocks);
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "chk1" }) }));
import { ApiError } from "@/app/lib/clientApi";
import CheckinPage from "./page";
const open = {
state: "OPEN", eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", companyName: "INS",
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." }, interests: [],
};
beforeEach(() => {
mocks.getCheckin.mockReset().mockResolvedValue(open);
mocks.lookupCheckin.mockReset().mockResolvedValue({ result: "CHECKED_IN", firstName: "Aini" });
mocks.registerWalkIn.mockReset().mockResolvedValue({ eventName: "Expo 2026" });
});
describe("/c/[token] check-in page", () => {
it("shows the start date and nothing else when the event has not started", async () => {
mocks.getCheckin.mockResolvedValue({ state: "NOT_YET", startDate: "2026-12-01" });
render(<CheckinPage />);
await screen.findByText("Check-in opens on 2026-12-01.");
expect(screen.queryByLabelText("Mobile number or email")).toBeNull();
});
it("shows the ended and inactive states", async () => {
mocks.getCheckin.mockResolvedValue({ state: "ENDED", startDate: "2026-12-01" });
const { unmount } = render(<CheckinPage />);
await screen.findByText("This event has ended.");
expect(screen.queryByText("Expo 2026")).toBeNull();
expect(screen.queryByLabelText("Mobile number or email")).toBeNull();
unmount();
mocks.getCheckin.mockRejectedValue(new ApiError("x", 404, { code: "CODE_INACTIVE" }));
render(<CheckinPage />);
await screen.findByText("This code is no longer active.");
expect(screen.queryByText("Expo 2026")).toBeNull();
expect(screen.queryByLabelText("Mobile number or email")).toBeNull();
});
it("looks a known person up and welcomes them", async () => {
const user = userEvent.setup();
render(<CheckinPage />);
await screen.findByText("Expo 2026");
await user.type(screen.getByLabelText("Mobile number or email"), "0123456789");
await user.click(screen.getByRole("button", { name: "Check in" }));
await screen.findByText("Welcome, Aini. You're checked in.");
expect(mocks.lookupCheckin).toHaveBeenCalledWith("chk1", "0123456789");
});
it("shows a blank registration form for a walk-in and then checked in", async () => {
const user = userEvent.setup();
mocks.lookupCheckin.mockResolvedValue({ result: "FORM" });
render(<CheckinPage />);
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
await user.click(screen.getByRole("button", { name: "Check in" }));
const name = (await screen.findByLabelText("Your name")) as HTMLInputElement;
expect(name.value).toBe("");
await user.type(name, "Walker");
await user.type(screen.getByLabelText("Email"), "w@b.co");
await user.click(screen.getByLabelText(/I agree to INS using my details/));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("You're checked in to Expo 2026.");
expect(mocks.registerWalkIn.mock.calls[0][0]).toBe("chk1");
expect(mocks.registerWalkIn.mock.calls[0][1]).toMatchObject({ name: "Walker", email: "w@b.co", consent: true });
});
it("shows a visible message on 429 too many", async () => {
const user = userEvent.setup();
mocks.lookupCheckin.mockRejectedValue(new ApiError("x", 429, { code: "TOO_MANY" }));
render(<CheckinPage />);
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
await user.click(screen.getByRole("button", { name: "Check in" }));
expect((await screen.findByRole("alert")).textContent).toBe("Too many attempts. Try again later.");
});
it("shows the server's message for a lookup 409 and for a walk-in 409", async () => {
const user = userEvent.setup();
mocks.lookupCheckin.mockRejectedValueOnce(new ApiError("x", 409, { code: "NOT_EVENT_DAY", error: "Check-in opens on the event day" }));
render(<CheckinPage />);
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
await user.click(screen.getByRole("button", { name: "Check in" }));
expect((await screen.findByRole("alert")).textContent).toBe("Check-in opens on the event day");
mocks.lookupCheckin.mockResolvedValue({ result: "FORM" });
mocks.registerWalkIn.mockRejectedValue(new ApiError("x", 409, { code: "NOT_EVENT_DAY", error: "Check-in opens on the event day" }));
await user.click(screen.getByRole("button", { name: "Check in" }));
await user.type(await screen.findByLabelText("Email"), "w@b.co");
await user.type(screen.getByLabelText("Your name"), "W");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Check-in opens on the event day");
});
it("welcomes without a name when the first name is empty", async () => {
const user = userEvent.setup();
mocks.lookupCheckin.mockResolvedValue({ result: "CHECKED_IN", firstName: "" });
render(<CheckinPage />);
await user.type(await screen.findByLabelText("Mobile number or email"), "0123456789");
await user.click(screen.getByRole("button", { name: "Check in" }));
await screen.findByText("Welcome. You're checked in.");
});
});
@@ -0,0 +1,84 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { RegistrationForm, apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { getCheckin, lookupCheckin, registerWalkIn, type CheckinState } from "@/app/lib/services/publicInvite";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Phase = "loading" | "inactive" | "error" | "lookup" | "form" | "welcome" | "done";
// Public event check-in page (QR at the venue): a known person is looked up by mobile or email, anyone else registers as a walk-in.
export default function CheckinPage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [phase, setPhase] = useState<Phase>("loading");
const [state, setState] = useState<CheckinState | null>(null);
const [value, setValue] = useState("");
const [firstName, setFirstName] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
getCheckin(token)
.then((s) => {
setState(s);
setPhase("lookup");
})
.catch((err) => {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else {
setError(apiData(err).code === "TOO_MANY" ? t("InviteTooMany") : t("RegLoadFailed"));
setPhase("error");
}
});
}, [token, t]);
async function lookup(e: FormEvent) {
e.preventDefault();
if (!value.trim()) return;
setBusy(true);
setError(null);
try {
const r = await lookupCheckin(token, value.trim());
if (r.result === "CHECKED_IN") {
setFirstName(r.firstName);
setPhase("welcome");
} else setPhase("form");
} catch (err) {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else setError(failMessage(t, err, "InviteTooMany"));
} finally {
setBusy(false);
}
}
const open = state?.state === "OPEN" ? state : null;
let body;
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
else if (phase === "error" || !state) body = <p role="alert" className="text-sm text-destructive">{error}</p>;
else if (!open) body = <p role="status">{state.state === "NOT_YET" ? t("ChkNotYet", { date: state.startDate }) : t("ChkEnded")}</p>;
else if (phase === "welcome") body = <p role="status" className="text-lg font-medium">{firstName ? t("InviteWelcome", { name: firstName }) : t("InviteWelcomeAnon")}</p>;
else if (phase === "done") body = <p role="status" className="text-lg font-medium">{t("ChkDone", { event: open.eventName })}</p>;
else if (phase === "form") {
body = <RegistrationForm tooManyKey="InviteTooMany" info={open} submit={(b) => registerWalkIn(token, b)} onDone={() => setPhase("done")} onInactive={() => setPhase("inactive")} />;
} else {
body = (
<form onSubmit={lookup} className="space-y-4" noValidate>
<h1 className="text-2xl font-semibold">{open.eventName}</h1>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="space-y-1.5">
<Label htmlFor="chk-value">{t("ChkLookup")}</Label>
<Input id="chk-value" className="h-11" value={value} onChange={(e) => setValue(e.target.value)} disabled={busy} />
</div>
<Button type="submit" className="h-11 w-full" disabled={busy}>{t("InviteCheckin")}</Button>
</form>
);
}
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
}
@@ -0,0 +1,144 @@
"use client";
import { useState, type FormEvent } from "react";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ApiError } from "@/app/lib/clientApi";
import type { RegistrationBody, RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const EMPTY: RegistrationBody = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [], consent: false, website: "" };
// Fields the form renders; a server error for any other field goes to the form-level alert.
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const BOX = "size-6";
export function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
}
/** Message for a failed visitor call: too-many wording, the server's text for 400/409, else the generic failure. */
export function failMessage(t: (k: string) => string, err: unknown, tooMany = "RegTooMany"): string {
const { status, code, error } = apiData(err);
if (code === "TOO_MANY") return t(tooMany);
return (status === 400 || status === 409) && error ? error : t("RegFailed");
}
interface Props {
/** Heading text; the event name when omitted. */
title?: string;
/** i18n key for the too-many message (default RegTooMany, the /r wording). */
tooManyKey?: string;
info: RegistrationInfo;
/** Prefilled values (a personal invite); the form is blank without it. */
initial?: Partial<RegistrationBody>;
/** Sends the form; reject with the ApiError to have the form show it. */
submit: (body: RegistrationBody) => Promise<unknown>;
onDone: () => void;
/** The code or invitation was switched off: the page shows its own message. */
onInactive: () => void;
}
// The visitor registration form shared by /r, /i and /c: event header, fields, bilingual privacy notice and consent.
export function RegistrationForm({ title, tooManyKey, info, initial, submit, onDone, onInactive }: Props) {
const t = useT();
const [form, setForm] = useState<RegistrationBody>({ ...EMPTY, ...initial });
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const set = (patch: Partial<RegistrationBody>) => setForm((f) => ({ ...f, ...patch }));
async function onSubmit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t("RegNameRequired");
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
await submit({
...form,
name: form.name.trim(),
mobile: form.mobile.trim(),
email: form.email.trim(),
companyName: form.companyName.trim(),
jobTitle: form.jobTitle.trim(),
});
onDone();
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "CODE_INACTIVE" || code === "INVITE_INACTIVE") onInactive();
else if (code === "EVENT_FULL") setFormError(t("RegFull"));
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(failMessage(t, err, tooManyKey));
setSaving(false);
}
}
const field = (id: "name" | "mobile" | "email" | "companyName" | "jobTitle", label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`reg-${id}`}>{label}</Label>
<Input id={`reg-${id}`} className="h-11" type={type} value={form[id]} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
</div>
);
return (
<form onSubmit={onSubmit} className="space-y-4" noValidate>
<div>
<h1 className="text-2xl font-semibold">{title ?? info.eventName}</h1>
<p className="text-sm text-muted-foreground">
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
</p>
</div>
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel")}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)}
<div className="space-y-2 rounded-md border p-3 text-sm">
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={ROW}>
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span>
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
</form>
);
}
@@ -0,0 +1,133 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const mocks = vi.hoisted(() => ({ getInvite: vi.fn(), submitInvite: vi.fn(), inviteCheckin: vi.fn() }));
vi.mock("@/app/lib/services/publicInvite", () => mocks);
vi.mock("next/navigation", () => ({ useParams: () => ({ token: "inv1" }) }));
import { ApiError } from "@/app/lib/clientApi";
import InvitePage from "./page";
const info = {
eventName: "Expo 2026", startDate: "2026-12-01", endDate: "2026-12-02", location: "KLCC", companyName: "INS",
notice: { id: 7, textEn: "We keep your data safe.", textMs: "Data anda selamat." },
interests: [],
guest: { name: "Aini Binti", mobile: "+60123456789", email: "aini@b.co", companyName: "Acme" },
state: "OPEN",
};
beforeEach(() => {
mocks.getInvite.mockReset().mockResolvedValue(info);
mocks.submitInvite.mockReset().mockResolvedValue({ eventName: "Expo 2026" });
mocks.inviteCheckin.mockReset().mockResolvedValue({ firstName: "Aini" });
});
describe("/i/[token] invite page", () => {
it("prefills the shared form with the guest's details", async () => {
render(<InvitePage />);
const name = (await screen.findByLabelText("Your name")) as HTMLInputElement;
expect(name.value).toBe("Aini Binti");
expect((screen.getByLabelText("Mobile number") as HTMLInputElement).value).toBe("+60123456789");
expect((screen.getByLabelText("Email") as HTMLInputElement).value).toBe("aini@b.co");
expect((screen.getByLabelText("Company") as HTMLInputElement).value).toBe("Acme");
expect(screen.getByText("Data anda selamat.")).toBeTruthy();
expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("You're invited to Expo 2026");
expect(screen.getByText(/INS \| 2026-12-01 - 2026-12-02 \| KLCC/)).toBeTruthy();
expect(screen.getByLabelText(/I agree to INS using my details/).getAttribute("aria-checked")).toBe("false");
expect(mocks.getInvite).toHaveBeenCalledWith("inv1");
});
it("registers and thanks the guest", async () => {
const user = userEvent.setup();
render(<InvitePage />);
await screen.findByLabelText("Your name");
await user.click(screen.getByLabelText(/I agree to INS using my details/));
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("Thank you, you're registered for Expo 2026");
expect(mocks.submitInvite.mock.calls[0][0]).toBe("inv1");
expect(mocks.submitInvite.mock.calls[0][1]).toMatchObject({ name: "Aini Binti", consent: true });
});
it("shows the full state on 409 EVENT_FULL", async () => {
const user = userEvent.setup();
mocks.submitInvite.mockRejectedValue(new ApiError("x", 409, { code: "EVENT_FULL", error: "This event is full" }));
render(<InvitePage />);
await screen.findByLabelText("Your name");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("This event is full");
});
it("shows only the inactive message on 404 INVITE_INACTIVE, on load and on submit", async () => {
mocks.getInvite.mockRejectedValue(new ApiError("x", 404, { code: "INVITE_INACTIVE" }));
const { unmount } = render(<InvitePage />);
await screen.findByText("This invitation is no longer active.");
expect(screen.queryByText("Expo 2026")).toBeNull();
unmount();
mocks.getInvite.mockResolvedValue(info);
mocks.submitInvite.mockRejectedValue(new ApiError("x", 404, { code: "INVITE_INACTIVE" }));
const user = userEvent.setup();
render(<InvitePage />);
await screen.findByLabelText("Your name");
await user.click(screen.getByRole("button", { name: "Register" }));
await screen.findByText("This invitation is no longer active.");
});
it("offers Check in on an event day, then welcomes by first name", async () => {
const user = userEvent.setup();
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKIN" });
render(<InvitePage />);
await user.click(await screen.findByRole("button", { name: "Check in" }));
await screen.findByText("Welcome, Aini. You're checked in.");
expect(mocks.inviteCheckin).toHaveBeenCalledWith("inv1");
});
it("tells a registered guest, and a checked-in guest, where they stand", async () => {
mocks.getInvite.mockResolvedValue({ ...info, state: "REGISTERED" });
const { unmount } = render(<InvitePage />);
await screen.findByText("You're already registered for Expo 2026.");
expect(screen.queryByLabelText("Your name")).toBeNull();
unmount();
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKED_IN" });
render(<InvitePage />);
await screen.findByText("You're already checked in to Expo 2026.");
});
it("shows the invite wording for too many attempts on load, submit and check-in", async () => {
const user = userEvent.setup();
const many = new ApiError("x", 429, { code: "TOO_MANY", error: "Too many attempts. Try again later." });
mocks.getInvite.mockRejectedValueOnce(many);
const first = render(<InvitePage />);
await screen.findByText("Too many attempts. Try again later.");
first.unmount();
mocks.submitInvite.mockRejectedValue(new ApiError("x", 429, { code: "TOO_MANY" }));
const second = render(<InvitePage />);
await screen.findByLabelText("Your name");
await user.click(screen.getByRole("button", { name: "Register" }));
expect((await screen.findByRole("alert")).textContent).toBe("Too many attempts. Try again later.");
second.unmount();
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKIN" });
mocks.inviteCheckin.mockRejectedValue(many);
render(<InvitePage />);
await user.click(await screen.findByRole("button", { name: "Check in" }));
expect((await screen.findByRole("alert")).textContent).toBe("Too many attempts. Try again later.");
});
it("shows the server's message for a check-in 409", async () => {
const user = userEvent.setup();
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKIN" });
mocks.inviteCheckin.mockRejectedValue(new ApiError("x", 409, { code: "NOT_REGISTERED", error: "Register before checking in" }));
render(<InvitePage />);
await user.click(await screen.findByRole("button", { name: "Check in" }));
expect((await screen.findByRole("alert")).textContent).toBe("Register before checking in");
});
it("welcomes without a name when the first name is empty", async () => {
const user = userEvent.setup();
mocks.getInvite.mockResolvedValue({ ...info, state: "CHECKIN" });
mocks.inviteCheckin.mockResolvedValue({ firstName: "" });
render(<InvitePage />);
await user.click(await screen.findByRole("button", { name: "Check in" }));
await screen.findByText("Welcome. You're checked in.");
});
});
@@ -0,0 +1,80 @@
"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { RegistrationForm, apiData, failMessage } from "@/app/components/registration/RegistrationForm";
import { getInvite, inviteCheckin, submitInvite, type InviteInfo } from "@/app/lib/services/publicInvite";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Phase = "loading" | "inactive" | "error" | "ready";
// Public personal invitation page: the guest's details are prefilled; on the event day they can check in.
export default function InvitePage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [phase, setPhase] = useState<Phase>("loading");
const [info, setInfo] = useState<InviteInfo | null>(null);
const [error, setError] = useState<string | null>(null);
const [welcome, setWelcome] = useState<string | null>(null);
const [thanks, setThanks] = useState(false);
useEffect(() => {
getInvite(token)
.then((i) => {
setInfo(i);
setPhase("ready");
})
.catch((err) => {
const code = apiData(err).code;
if (code === "INVITE_INACTIVE") setPhase("inactive");
else {
setError(code === "TOO_MANY" ? t("InviteTooMany") : t("RegLoadFailed"));
setPhase("error");
}
});
}, [token, t]);
async function checkIn() {
setError(null);
try {
setWelcome((await inviteCheckin(token)).firstName);
} catch (err) {
if (apiData(err).code === "INVITE_INACTIVE") setPhase("inactive");
else setError(failMessage(t, err, "InviteTooMany"));
}
}
const event = info?.eventName ?? "";
let body;
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
else if (phase === "inactive") body = <p role="alert">{t("InviteInactive")}</p>;
else if (phase === "error" || !info) body = <p role="alert" className="text-sm text-destructive">{error}</p>;
else if (welcome !== null) body = <p role="status" className="text-lg font-medium">{welcome ? t("InviteWelcome", { name: welcome }) : t("InviteWelcomeAnon")}</p>;
else if (info.state === "CHECKED_IN") body = <p role="status" className="text-lg font-medium">{t("InviteCheckedIn", { event })}</p>;
else if (thanks) body = <p role="status" className="text-lg font-medium">{t("RegThanks", { event })}</p>;
else if (info.state === "REGISTERED") body = <p role="status" className="text-lg font-medium">{t("InviteRegistered", { event })}</p>;
else if (info.state === "CHECKIN") {
body = (
<div className="space-y-4">
<h1 className="text-2xl font-semibold">{event}</h1>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<Button className="h-11 w-full" onClick={checkIn}>{t("InviteCheckin")}</Button>
</div>
);
} else {
body = (
<RegistrationForm
info={info}
title={t("InviteTitle", { event })}
tooManyKey="InviteTooMany"
initial={{ name: info.guest.name ?? "", mobile: info.guest.mobile ?? "", email: info.guest.email ?? "", companyName: info.guest.companyName ?? "" }}
submit={(b) => submitInvite(token, b)}
onDone={() => setThanks(true)}
onInactive={() => setPhase("inactive")}
/>
);
}
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
}
@@ -485,6 +485,19 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
RegContactRequired: "Enter a mobile number or an email.",
RegTooMany: "Too many registrations from this device. Try again later.",
RegFailed: "Could not register. Try again.",
RegFull: "This event is full",
InviteInactive: "This invitation is no longer active.",
InviteCheckin: "Check in",
InviteTitle: "You're invited to {event}",
InviteTooMany: "Too many attempts. Try again later.",
InviteWelcome: "Welcome, {name}. You're checked in.",
InviteWelcomeAnon: "Welcome. You're checked in.",
InviteRegistered: "You're already registered for {event}.",
InviteCheckedIn: "You're already checked in to {event}.",
ChkNotYet: "Check-in opens on {date}.",
ChkEnded: "This event has ended.",
ChkLookup: "Mobile number or email",
ChkDone: "You're checked in to {event}.",
QrCardTitle: "Registration QR",
QrEventCode: "Event code",
QrCopy: "Copy link",
@@ -47,3 +47,17 @@ describe("guardDecision", () => {
expect(guardDecision("/login", s)).toBeNull();
});
});
describe("visitor pages /r, /i, /c", () => {
it("pass signed out and with a reset pending; the bare prefixes and admin paths do not", () => {
const pending = { present: true, resetRequired: true };
for (const p of ["/r/x", "/i/x", "/c/x"]) {
expect(guardDecision(p, null), p).toBeNull();
expect(guardDecision(p, pending), p).toBeNull();
}
for (const p of ["/events", "/i", "/c/", "/i/", "/c/x/y"]) {
expect(guardDecision(p, null), p).toBe("/login");
expect(guardDecision(p, pending), p).toBe("/reset-password");
}
});
});
+6 -3
View File
@@ -8,9 +8,12 @@
// resetPasswordRequired); it is reached right after login, so it stays public.
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
// /r/<token> is the QR self-registration page: visitors are not signed in. (A prefix, so PUBLIC_PATHS stays exact.)
// Visitor pages, not signed in: /r/<token> QR self-registration, /i/<token> personal invite, /c/<token> event check-in.
// (A pattern, so PUBLIC_PATHS stays exact.)
const VISITOR_PATH = /^\/[ric]\/[^/]+$/;
export function isPublicPath(pathname: string): boolean {
return PUBLIC_PATHS.has(pathname) || /^\/r\/[^/]+$/.test(pathname);
return PUBLIC_PATHS.has(pathname) || VISITOR_PATH.test(pathname);
}
export interface SessionState {
@@ -25,7 +28,7 @@ export function guardDecision(pathname: string, session: SessionState | null): s
return isPublicPath(pathname) ? null : "/login";
}
// A pending reset confines the session to the set-password form (/login stays reachable).
if (session?.resetRequired && !/^\/r\/[^/]+$/.test(pathname) && pathname !== "/reset-password" && pathname !== "/login") {
if (session?.resetRequired && !VISITOR_PATH.test(pathname) && pathname !== "/reset-password" && pathname !== "/login") {
return "/reset-password";
}
return null;
@@ -0,0 +1,25 @@
import "server-only";
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import { errorResponse } from "@/app/lib/server/apiRoute";
// Public (signed-out) proxy to mobile-api: no session token.
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
export type TokenCtx = { params: Promise<{ token: string }> };
export async function forwardPublic(req: NextRequest, path: string, method: "GET" | "POST") {
const xff = clientIp(req);
const headers: Record<string, string> = xff ? { "X-Forwarded-For": xff } : {};
const result = await callMobileApi<Record<string, unknown>>(
path,
method === "GET" ? { headers } : { method, body: await req.json().catch(() => ({})), headers },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
/** Route handler for `/api/public/<prefix>/<token><suffix>`. */
export const publicRoute = (prefix: string, suffix: string, method: "GET" | "POST") =>
async (req: NextRequest, { params }: TokenCtx) => forwardPublic(req, `/api/public/${prefix}/${encodeURIComponent((await params).token)}${suffix}`, method);
@@ -0,0 +1,19 @@
import { publicCall, type RegistrationBody, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
export type InviteInfo = RegistrationInfo & {
guest: { name: string | null; mobile: string | null; email: string | null; companyName: string | null };
state: "OPEN" | "REGISTERED" | "CHECKIN" | "CHECKED_IN";
};
export type CheckinState = (RegistrationInfo & { state: "OPEN" }) | { state: "NOT_YET" | "ENDED"; startDate: string };
const invite = (token: string) => `/api/public/invite/${encodeURIComponent(token)}`;
const checkin = (token: string) => `/api/public/checkin/${encodeURIComponent(token)}`;
const post = (body?: unknown) => ({ method: "POST", body: JSON.stringify(body ?? {}) });
export const getInvite = (token: string) => publicCall<InviteInfo>(invite(token));
export const submitInvite = (token: string, body: RegistrationBody) => publicCall<{ eventName: string }>(invite(token), post(body));
export const inviteCheckin = (token: string) => publicCall<{ firstName: string }>(`${invite(token)}/checkin`, post());
export const getCheckin = (token: string) => publicCall<CheckinState>(checkin(token));
export const lookupCheckin = (token: string, value: string) =>
publicCall<{ result: "CHECKED_IN"; firstName: string } | { result: "FORM" }>(`${checkin(token)}/lookup`, post({ value }));
export const registerWalkIn = (token: string, body: RegistrationBody) => publicCall<{ eventName: string }>(`${checkin(token)}/register`, post(body));
@@ -24,10 +24,10 @@ export interface RegistrationBody {
const url = (token: string) => `/api/public/registration/${encodeURIComponent(token)}`;
// Plain fetch on purpose: clientApi redirects a 401 to the admin /login, which a visitor must never see.
async function call<T>(token: string, init?: RequestInit): Promise<T> {
export async function publicCall<T>(url: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(url(token), { ...init, headers: init?.body ? { "Content-Type": "application/json" } : {} });
res = await fetch(url, { ...init, headers: init?.body ? { "Content-Type": "application/json" } : {} });
} catch {
throw new ApiError("Request failed", 0);
}
@@ -42,6 +42,6 @@ async function call<T>(token: string, init?: RequestInit): Promise<T> {
return data as T;
}
export const getRegistration = (token: string) => call<RegistrationInfo>(token);
export const getRegistration = (token: string) => publicCall<RegistrationInfo>(url(token));
export const submitRegistration = (token: string, body: RegistrationBody) =>
call<{ eventName: string }>(token, { method: "POST", body: JSON.stringify(body) });
publicCall<{ eventName: string }>(url(token), { method: "POST", body: JSON.stringify(body) });
+8 -130
View File
@@ -1,38 +1,21 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Button } from "@/app/components/ui/button";
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ApiError } from "@/app/lib/clientApi";
import { RegistrationForm, apiData } from "@/app/components/registration/RegistrationForm";
import { getRegistration, submitRegistration, type RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const EMPTY = { name: "", mobile: "", email: "", companyName: "", jobTitle: "", interestIds: [] as number[], consent: false, website: "" };
// Fields the form renders; a server error for any other field goes to the form-level alert.
const FIELDS = ["name", "mobile", "email", "companyName", "jobTitle", "consent"];
const ROW = "flex min-h-11 w-full cursor-pointer items-center gap-3 rounded-md border p-3";
const BOX = "size-6";
type Phase = "loading" | "inactive" | "form" | "done";
function apiData(err: unknown): { status?: number; code?: string; error?: string; field?: string } {
if (!(err instanceof ApiError)) return {};
const d = (err.data ?? {}) as { code?: string; error?: string; details?: { field?: string } };
return { status: err.status, code: d.code, error: d.error, field: d.details?.field };
}
// Public, signed-out, mobile-first page (no admin shell: AppShell skips it via isPublicPath).
export default function RegisterPage() {
const t = useT();
const { token } = useParams<{ token: string }>();
const [phase, setPhase] = useState<Phase>("loading");
const [info, setInfo] = useState<RegistrationInfo | null>(null);
const [form, setForm] = useState(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
useEffect(() => {
getRegistration(token)
@@ -43,52 +26,12 @@ export default function RegisterPage() {
.catch((err) => {
if (apiData(err).code === "CODE_INACTIVE") setPhase("inactive");
else {
setFormError(apiData(err).code === "TOO_MANY" ? t("RegTooMany") : t("RegLoadFailed"));
setLoadError(apiData(err).code === "TOO_MANY" ? t("RegTooMany") : t("RegLoadFailed"));
setPhase("form");
}
});
}, [token, t]);
const set = (patch: Partial<typeof EMPTY>) => setForm((f) => ({ ...f, ...patch }));
async function submit(e: FormEvent) {
e.preventDefault();
const errs: Record<string, string> = {};
if (!form.name.trim()) errs.name = t("RegNameRequired");
if (!form.mobile.trim() && !form.email.trim()) errs.mobile = t("RegContactRequired");
setErrors(errs);
setFormError(null);
if (Object.keys(errs).length) return;
setSaving(true);
try {
await submitRegistration(token, {
...form,
name: form.name.trim(),
mobile: form.mobile.trim(),
email: form.email.trim(),
companyName: form.companyName.trim(),
jobTitle: form.jobTitle.trim(),
});
setPhase("done");
} catch (err) {
const { status, code, error, field } = apiData(err);
if (code === "CODE_INACTIVE") setPhase("inactive");
else if (code === "TOO_MANY") setFormError(t("RegTooMany"));
else if (status === 400 && error && field && FIELDS.includes(field)) setErrors({ [field]: error });
else setFormError(status === 400 && error ? error : t("RegFailed"));
} finally {
setSaving(false);
}
}
const field = (id: keyof typeof EMPTY, label: string, type = "text") => (
<div className="space-y-1.5">
<Label htmlFor={`reg-${id}`}>{label}</Label>
<Input id={`reg-${id}`} className="h-11" type={type} value={String(form[id])} onChange={(e) => set({ [id]: e.target.value })} disabled={saving} aria-invalid={!!errors[id]} aria-describedby={errors[id] ? `reg-${id}-error` : undefined} />
{errors[id] && <p id={`reg-${id}-error`} className="text-sm text-destructive">{errors[id]}</p>}
</div>
);
let body;
if (phase === "loading") body = <p role="status">{t("UiLoading")}</p>;
else if (phase === "inactive") body = <p role="alert">{t("RegInactive")}</p>;
@@ -96,77 +39,12 @@ export default function RegisterPage() {
body = (
<div className="space-y-4">
<p role="status" className="text-lg font-medium">{t("RegThanks", { event: info?.eventName ?? "" })}</p>
<Button
className="h-11"
onClick={() => {
setForm(EMPTY);
setErrors({});
setPhase("form");
}}
>
{t("RegAnother")}
</Button>
<Button className="h-11" onClick={() => setPhase("form")}>{t("RegAnother")}</Button>
</div>
);
} else {
body = (
<form onSubmit={submit} className="space-y-4" noValidate>
{info && (
<div>
<h1 className="text-2xl font-semibold">{info.eventName}</h1>
<p className="text-sm text-muted-foreground">
{info.companyName} | {info.startDate} - {info.endDate} | {info.location}
</p>
</div>
)}
{formError && <p role="alert" className="text-sm text-destructive">{formError}</p>}
{info && (
<>
{field("name", t("RegName"))}
{field("mobile", t("RegMobile"), "tel")}
{field("email", t("RegEmail"), "email")}
{field("companyName", t("RegCompany"))}
{field("jobTitle", t("RegJobTitle"))}
{info.interests.length > 0 && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">{t("RegInterests")}</legend>
{info.interests.map((i) => (
<Label key={i.id} htmlFor={`reg-interest-${i.id}`} className={ROW}>
<Checkbox
className={BOX}
id={`reg-interest-${i.id}`}
checked={form.interestIds.includes(i.id)}
onCheckedChange={(on) => set({ interestIds: on ? [...form.interestIds, i.id] : form.interestIds.filter((x) => x !== i.id) })}
/>
{i.name}
</Label>
))}
</fieldset>
)}
<div className="space-y-2 rounded-md border p-3 text-sm">
<h2 className="font-medium">{t("RegNoticeEn")}</h2>
<p className="whitespace-pre-line">{info.notice.textEn}</p>
<h2 className="font-medium">{t("RegNoticeMs")}</h2>
<p className="whitespace-pre-line">{info.notice.textMs}</p>
</div>
<Label htmlFor="reg-consent" className={ROW}>
<Checkbox id="reg-consent" className={BOX} checked={form.consent} onCheckedChange={(on) => set({ consent: on === true })} aria-invalid={!!errors.consent} aria-describedby={errors.consent ? "reg-consent-error" : undefined} />
<span>
<span className="block">{t("RegConsentEn", { company: info.companyName })}</span>
<span className="block">{t("RegConsentMs", { company: info.companyName })}</span>
</span>
</Label>
{errors.consent && <p id="reg-consent-error" className="text-sm text-destructive">{errors.consent}</p>}
{/* Honeypot: people never see or reach it; bots fill it and the server drops the submission. */}
<div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
<input name="website" tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => set({ website: e.target.value })} />
</div>
<Button type="submit" className="h-11 w-full" disabled={saving}>{t("RegSubmit")}</Button>
</>
)}
</form>
);
}
} else if (info) {
body = <RegistrationForm info={info} submit={(b) => submitRegistration(token, b)} onDone={() => setPhase("done")} onInactive={() => setPhase("inactive")} />;
} else body = <p role="alert" className="text-sm text-destructive">{loadError}</p>;
return <main className="mx-auto w-full max-w-md px-4 py-6">{body}</main>;
}
@@ -13,13 +13,20 @@ describe("middleware: public registration paths", () => {
expect(res.headers.get("location")).toBeNull();
});
it("lets a signed-out visitor open /i/<token> and /c/<token>", async () => {
for (const path of ["/i/abc123", "/c/abc123"]) {
const res = await get(path);
expect(res.headers.get("x-middleware-next"), path).toBe("1");
}
});
it("lets a signed-out visitor reach the public registration proxy", async () => {
const res = await get("/api/public/registration/abc123");
expect(res.headers.get("x-middleware-next")).toBe("1");
});
it("still redirects a signed-out visitor from admin paths", async () => {
for (const path of ["/events", "/my-qr", "/r", "/r/"]) {
for (const path of ["/events", "/my-qr", "/r", "/r/", "/i", "/c/"]) {
const res = await get(path);
expect(res.headers.get("location"), path).toContain("/login");
}