From d5acf5f0e229321eeded6831152aeb6c625d1b95 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:13:07 +0530 Subject: [PATCH 01/48] Ignore the local .claude folder --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 22f52aa..d1464f3 100644 --- a/.gitignore +++ b/.gitignore @@ -116,7 +116,8 @@ temp/ *.swp *.swo *~ -.claude/settings.local.json +# Local Claude Code settings and agents; never pushed. +.claude/ # OS files .DS_Store From 4d1ba919f438f1c1b6a2e2b1432ea66a3b0e325b Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:18:28 +0530 Subject: [PATCH 02/48] bug fixx-organizer-cannot-sign-in-to-new-event canReturnToPath read /orgs//events/new as an event called "new", found no such event, and refused the sign-in, so an organization owner following the "create event" link was told they were "not on the attendee list". The organization's event list and new-event pages now check organization membership instead. --- apps/web/lib/session.ts | 3 +++ tests/unit/return-access.test.ts | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tests/unit/return-access.test.ts diff --git a/apps/web/lib/session.ts b/apps/web/lib/session.ts index 3e25a75..5b20dff 100644 --- a/apps/web/lib/session.ts +++ b/apps/web/lib/session.ts @@ -59,6 +59,9 @@ export async function canReturnToPath(returnTo: string | null | undefined, atten const event = await events.findByEventSlug(participantRoute[1]); return Boolean(event && await events.isParticipant(event.id, attendeeId)); } + // The event list and "new event" pages belong to the organization, not to an event. + const organizationRoute = returnTo.match(/^\/orgs\/([^/]+)\/events(?:\/new)?\/?$/); + if (organizationRoute) return events.hasOrganizationAccess(organizationRoute[1], attendeeId); const organizerRoute = returnTo.match(/^\/orgs\/([^/]+)\/events\/([^/]+)(?:\/|$)/); if (organizerRoute) { const event = await events.findBySlug(organizerRoute[1], organizerRoute[2]); diff --git a/tests/unit/return-access.test.ts b/tests/unit/return-access.test.ts new file mode 100644 index 0000000..1ecf819 --- /dev/null +++ b/tests/unit/return-access.test.ts @@ -0,0 +1,41 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + findByEventSlug: vi.fn(), findBySlug: vi.fn(), isParticipant: vi.fn(), isOrganizer: vi.fn(), hasOrganizationAccess: vi.fn(), +})); +vi.mock("@match-maker/db", () => ({ events: mocks })); + +import { canReturnToPath } from "@/lib/session"; + +describe("canReturnToPath", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.findBySlug.mockResolvedValue(null); + }); + + it.each(["/orgs/acme/events/new", "/orgs/acme/events", "/orgs/acme/events/"])( + "lets an organization member sign in to %s", async (path) => { + mocks.hasOrganizationAccess.mockResolvedValue(true); + await expect(canReturnToPath(path, "member")).resolves.toBe(true); + expect(mocks.hasOrganizationAccess).toHaveBeenCalledWith("acme", "member"); + expect(mocks.findBySlug).not.toHaveBeenCalled(); + }); + + it("refuses someone outside the organization", async () => { + mocks.hasOrganizationAccess.mockResolvedValue(false); + await expect(canReturnToPath("/orgs/acme/events/new", "stranger")).resolves.toBe(false); + }); + + it("still checks event organizers for event pages", async () => { + mocks.findBySlug.mockResolvedValue({ id: "event" }); + mocks.isOrganizer.mockResolvedValue(true); + await expect(canReturnToPath("/orgs/acme/events/summit/roster", "organizer")).resolves.toBe(true); + expect(mocks.findBySlug).toHaveBeenCalledWith("acme", "summit"); + }); + + it("still checks participants for event pages", async () => { + mocks.findByEventSlug.mockResolvedValue({ id: "event" }); + mocks.isParticipant.mockResolvedValue(false); + await expect(canReturnToPath("/e/summit/matches", "outsider")).resolves.toBe(false); + }); +}); From d9c227fbb226b9ced89d40a3fbca4b8dda51aea4 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:21:36 +0530 Subject: [PATCH 03/48] bug fixx-rate-limiter-query-always-fails PostgresRateLimiter passed the limit as $2 but the SQL never used $2, so Postgres rejected every call with "could not determine data type of parameter $2". Search failed for every participant, and in production (TRUSTED_PROXY_HOPS=1) every sign-in would have failed at the per-IP limit. Unit tests mocked the limiter, so it was never exercised. The query now takes only the key and window. A new real-Postgres test covers the limit, simultaneous requests and window reset; it fails on the old code. --- .../cache/postgres-rate-limiter.ts | 6 +-- tests/integration/rate-limiter.test.ts | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 tests/integration/rate-limiter.test.ts diff --git a/apps/web/src/infrastructure/cache/postgres-rate-limiter.ts b/apps/web/src/infrastructure/cache/postgres-rate-limiter.ts index 5e2a591..528265d 100644 --- a/apps/web/src/infrastructure/cache/postgres-rate-limiter.ts +++ b/apps/web/src/infrastructure/cache/postgres-rate-limiter.ts @@ -9,13 +9,13 @@ export class PostgresRateLimiter implements RateLimiter { values ($1, now(), 1) on conflict (bucket_key) do update set window_started_at = case - when rate_limit_buckets.window_started_at <= now() - ($3 || ' seconds')::interval then now() + when rate_limit_buckets.window_started_at <= now() - make_interval(secs => $2) then now() else rate_limit_buckets.window_started_at end, count = case - when rate_limit_buckets.window_started_at <= now() - ($3 || ' seconds')::interval then 1 + when rate_limit_buckets.window_started_at <= now() - make_interval(secs => $2) then 1 else rate_limit_buckets.count + 1 end returning count`, - [key, limit, String(windowSeconds)] + [key, windowSeconds] ); return Number(rows[0]?.count ?? limit + 1) <= limit; } diff --git a/tests/integration/rate-limiter.test.ts b/tests/integration/rate-limiter.test.ts new file mode 100644 index 0000000..8eb2246 --- /dev/null +++ b/tests/integration/rate-limiter.test.ts @@ -0,0 +1,47 @@ +/** + * The shared limiter backs search and the per-IP sign-in limits, so it runs + * against a real Postgres here (unit tests mock it). Uses its own bucket keys. + * Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { query, closePool } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresRateLimiter } from "../../apps/web/src/infrastructure/cache/postgres-rate-limiter"; + +const hasDatabase = Boolean(process.env.DATABASE_URL); +const describeDb = hasDatabase ? describe : describe.skip; +const PREFIX = "test:rate-limiter:"; + +describeDb("PostgresRateLimiter", () => { + const limiter = new PostgresRateLimiter(); + + beforeAll(async () => { + await migrate(); + await query(`delete from rate_limit_buckets where bucket_key like $1`, [`${PREFIX}%`]); + }); + + afterAll(async () => { + await query(`delete from rate_limit_buckets where bucket_key like $1`, [`${PREFIX}%`]); + await closePool(); + }); + + it("allows up to the limit, then refuses", async () => { + const key = `${PREFIX}sequential`; + const allowed = []; + for (let i = 0; i < 4; i++) allowed.push(await limiter.consume(key, 3, 60)); + expect(allowed).toEqual([true, true, true, false]); + }); + + it("holds the limit for simultaneous requests", async () => { + const results = await Promise.all(Array.from({ length: 10 }, () => limiter.consume(`${PREFIX}parallel`, 4, 60))); + expect(results.filter(Boolean)).toHaveLength(4); + }); + + it("starts a new window once the old one has passed", async () => { + const key = `${PREFIX}window`; + await limiter.consume(key, 1, 60); + expect(await limiter.consume(key, 1, 60)).toBe(false); + await query(`update rate_limit_buckets set window_started_at = now() - interval '2 minutes' where bucket_key = $1`, [key]); + expect(await limiter.consume(key, 1, 60)).toBe(true); + }); +}); From 7480e937e26cfe914b565632f0ee379fbe45fd5b Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:27:17 +0530 Subject: [PATCH 04/48] bug fixx-no-way-to-sign-out A signed-in participant or organizer had no sign-out control: the only Sign out button was on the "not on this roster" page, while open events redirect straight to matches/profile and no other page offered one. A shared SignOutButton (the existing signOutCurrentUser action) now ends every participant and organizer page nav, and the closed/draft event page has one too. The organizer event list and new-event pages get a nav for it. --- .../orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx | 3 ++- .../orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx | 3 ++- .../orgs/[orgSlug]/events/[eventSlug]/page.tsx | 3 ++- .../orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx | 3 ++- .../app/(organizer)/orgs/[orgSlug]/events/new/page.tsx | 2 ++ apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx | 2 ++ .../app/(participant)/e/[eventSlug]/connections/page.tsx | 3 ++- apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx | 3 ++- apps/web/app/(participant)/e/[eventSlug]/page.tsx | 1 + apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx | 3 ++- apps/web/app/(participant)/e/[eventSlug]/search/page.tsx | 3 ++- apps/web/app/globals.css | 2 ++ apps/web/components/ui/SignOutButton.tsx | 8 ++++++++ 13 files changed, 31 insertions(+), 8 deletions(-) create mode 100644 apps/web/components/ui/SignOutButton.tsx diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx index ea60a5e..3eeb077 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { requireOrganizerEvent } from "@/src/lib/auth"; export default async function AnalyticsPage({ params }: { params: Promise<{ orgSlug: string; eventSlug: string }> }) { @@ -7,7 +8,7 @@ export default async function AnalyticsPage({ params }: { params: Promise<{ orgS const analytics = await container.events.analytics(event.id); const completion = analytics.roster ? Math.round(analytics.profiles / analytics.roster * 100) : 0; return
- +

Event analytics

{event.name} · {event.status}

diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx index c12ac21..967ca4e 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { computeEventMatchesAction } from "../../../../../../actions/organizer.actions"; import { requireOrganizerEvent } from "@/src/lib/auth"; import { ActionForm } from "@/components/ui/form"; @@ -22,7 +23,7 @@ export default async function MatchingPage({ params, searchParams }: { ]); const action = computeEventMatchesAction.bind(null, orgSlug, eventSlug); return
- +

Matching pipeline

Embeddings and ranked matches run in the background for profiles already completed.

{query.queued &&

Queued profile matching for {query.queued} attendee(s).

} diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx index 2b38d84..86ef671 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { updateEventAction } from "../../../../../actions/organizer.actions"; import { requireOrganizerEvent } from "@/src/lib/auth"; import { EventSetupForm } from "@/components/organizer/EventForms"; @@ -21,7 +22,7 @@ export default async function EventDashboardPage({ params, searchParams }: { Matching Analytics Create event - +
diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx index fc89463..18f420c 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { importEventRosterAction } from "../../../../../../actions/organizer.actions"; import { requireOrganizerEvent } from "@/src/lib/auth"; import { RosterUploadForm } from "@/components/organizer/EventForms"; @@ -13,7 +14,7 @@ export default async function RosterPage({ params, searchParams }: { const roster = await container.events.roster(event.id); const action = importEventRosterAction.bind(null, orgSlug, eventSlug); return
- +

Attendee roster

{roster.length} registered attendee{roster.length === 1 ? "" : "s"} for {event.name}.

{query.imported &&

diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx index bfaba3d..8ddcc5e 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { createEventAction } from "../../../../../actions/organizer.actions"; import { requireOrganizationMember } from "@/src/lib/auth"; import { NewEventForm } from "@/components/organizer/EventForms"; @@ -10,6 +11,7 @@ export default async function NewEventPage({ params }: { params: Promise<{ orgSl const create = createEventAction.bind(null, orgSlug); return

← Organizer +

Create an event

Set up a roster, participant profile, and matching flow for {organization.name}.

diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx index 8cbd130..ce1f3d0 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { requireOrganizationMember } from "@/src/lib/auth"; export default async function OrganizationEventsPage({ params }: { params: Promise<{ orgSlug: string }> }) { @@ -7,6 +8,7 @@ export default async function OrganizationEventsPage({ params }: { params: Promi const events = await container.events.listForOrganization(orgSlug); return
ORGANIZER +

{organization.name} events

Create event
diff --git a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx index 7e65b69..f95bc06 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { getParticipantConnections, respondToParticipantIntro, shareVenueZoneAction } from "../../../../actions/intro.actions"; import { requireParticipantEvent } from "@/src/lib/auth"; import { ActionForm } from "@/components/ui/form"; @@ -13,7 +14,7 @@ export default async function ConnectionsPage({ params, searchParams }: { const { event } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/connections`, "viewMatches"); const connections = await getParticipantConnections(eventSlug); return
- + INTRODUCTIONS · {event.name}

Connections

{notice.requested &&

Intro request sent. You will see their contact details once they accept.

} diff --git a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx index 0ac596c..1526903 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { redirect } from "next/navigation"; import { getMyMatches } from "@/src/application/use-cases/get-my-matches"; import { requireParticipantEvent } from "@/src/lib/auth"; @@ -26,7 +27,7 @@ export default async function MatchesPage({ params, searchParams }: { const canRequestIntro = eventAllows(event.status, "requestIntro"); return
- + YOUR EVENT MATCHES

People worth meeting.

Matches are ranked for your profile. Contact details stay private until you both accept an introduction.

diff --git a/apps/web/app/(participant)/e/[eventSlug]/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/page.tsx index dc08191..7a14dbf 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/page.tsx @@ -45,6 +45,7 @@ export default async function EventLandingPage({ params }: { params: Promise<{ e Connections :

This event has not opened yet. Come back when the organizer opens registration.

} +
; } diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx index c99ba23..ee6f179 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { notFound } from "next/navigation"; import { saveParticipantProfile } from "../../../../actions/participant.actions"; import { requireParticipantEvent } from "@/src/lib/auth"; @@ -13,7 +14,7 @@ export default async function ProfilePage({ params }: { params: Promise<{ eventS const zones = event.zones ?? []; return
- + PARTICIPANT PROFILE

Make your next introduction count.

Confirm the profile other attendees will see, then set what you want from this event.

diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx index e4eac77..cd0fcbc 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx @@ -1,4 +1,5 @@ import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; import { requireParticipantEvent } from "@/src/lib/auth"; import SearchForm from "./SearchForm"; @@ -6,7 +7,7 @@ export default async function SearchPage({ params }: { params: Promise<{ eventSl const { eventSlug } = await params; await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); return
- +

Search your event

Describe the people, skills, or collaboration you are looking for.

diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index a130fed..1454048 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -22,6 +22,8 @@ h1 { font-size: clamp(1.75rem, 5vw, 2.5rem); line-height: 1.2; } } nav { display: flex; flex-wrap: wrap; gap: 8px 20px; margin-bottom: 24px; } +.nav-signout { margin-left: auto; } +.link-button { border: 0; padding: 0; background: none; color: var(--accent); font: inherit; text-decoration: underline; cursor: pointer; } /* Forms */ .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px; margin-top: 28px; } diff --git a/apps/web/components/ui/SignOutButton.tsx b/apps/web/components/ui/SignOutButton.tsx new file mode 100644 index 0000000..ddf9d9b --- /dev/null +++ b/apps/web/components/ui/SignOutButton.tsx @@ -0,0 +1,8 @@ +import { signOutCurrentUser } from "@/app/actions/participant.actions"; + +/** Ends the session from any signed-in page; sits at the end of the page nav. */ +export default function SignOutButton() { + return
+ +
; +} From e8d92d3f26ebd3ad3ec6e26fb005db4be8584329 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sat, 17 Oct 2026 12:46:58 +0530 Subject: [PATCH 05/48] bug fixx-r03-missing-from-main-line The R03 fix (expired/tampered cookies loop on /login, lost return paths) was committed on a side branch from R01 and never reached the R04-R10 line, so a stale cookie again bounced users from /login to /e/demo and a reused magic link left them on the wrong event. Brings in "Fix expired-session login dead end and keep return paths (R03)" (cherry picked from commit e6f2743). The middleware conflict is resolved by keeping R09's same-origin check for /api requests and R03's session-aware /login redirect, on the nodejs runtime; the R09 middleware test now awaits the async middleware. --- apps/web/app/api/auth/google/start/route.js | 6 +- apps/web/app/auth/callback/route.js | 34 ++++++----- apps/web/lib/safe-return-to.ts | 16 +++++- apps/web/middleware.ts | 35 ++++++++---- tests/unit/auth-redirect.test.ts | 23 +++++++- tests/unit/auth-routes.test.ts | 37 +++++++++++- tests/unit/middleware.test.ts | 63 +++++++++++++++++++++ tests/unit/request-guards.test.ts | 4 +- 8 files changed, 185 insertions(+), 33 deletions(-) create mode 100644 tests/unit/middleware.test.ts diff --git a/apps/web/app/api/auth/google/start/route.js b/apps/web/app/api/auth/google/start/route.js index c2df7ce..14c2c0f 100644 --- a/apps/web/app/api/auth/google/start/route.js +++ b/apps/web/app/api/auth/google/start/route.js @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { attendees } from "@match-maker/db"; import { canReturnToPath } from "@/lib/session"; -import { safeReturnTo } from "@/lib/safe-return-to"; +import { loginErrorPath, safeReturnTo } from "@/lib/safe-return-to"; import { buildAuthorizationUrl, createPkce, @@ -33,7 +33,7 @@ export async function GET(request) { if (email) { const attendee = await attendees.findByEmail(email); if (!attendee || !(await canReturnToPath(returnTo, attendee.id))) { - return NextResponse.redirect(new URL("/login?error=unregistered", url.origin)); + return NextResponse.redirect(new URL(loginErrorPath("unregistered", returnTo), url.origin)); } } @@ -58,7 +58,7 @@ export async function GET(request) { return response; } catch (err) { console.error("[auth/google/start]", err); - return NextResponse.redirect(new URL("/login?error=provider", url.origin)); + return NextResponse.redirect(new URL(loginErrorPath("provider", returnTo), url.origin)); } } diff --git a/apps/web/app/auth/callback/route.js b/apps/web/app/auth/callback/route.js index 91f8b05..90d752e 100644 --- a/apps/web/app/auth/callback/route.js +++ b/apps/web/app/auth/callback/route.js @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { attendees } from "@match-maker/db"; import { canReturnToPath } from "@/lib/session"; -import { safeReturnTo } from "@/lib/safe-return-to"; +import { loginErrorPath, safeReturnTo } from "@/lib/safe-return-to"; import { exchangeCodeForTokens, verifyIdToken, @@ -33,8 +33,11 @@ export async function GET(request) { const providerError = url.searchParams.get("error"); if (providerError) { + // A cancelled Google consent lands here; the state cookie still knows + // which event the user was joining. console.warn("[auth/callback] provider error:", providerError); - return redirectTo(origin, "/login?error=provider"); + const stored = await unsealOAuthState(request.cookies.get(OAUTH_COOKIE_NAME)?.value ?? ""); + return redirectTo(origin, loginErrorPath("provider", stored?.returnTo)); } const token = url.searchParams.get("token"); @@ -44,22 +47,22 @@ export async function GET(request) { const state = url.searchParams.get("state"); if (code && state) return handleAuthorizationCode(request, code, state, origin); - return redirectTo(origin, "/login?error=invalid_callback"); + return redirectTo(origin, loginErrorPath("invalid_callback", url.searchParams.get("returnTo"))); } async function handleMagicLink(token, origin, returnTo) { try { const result = await verifyToken(token); if (!result.ok) { - return redirectTo(origin, `/login?error=${result.reason}`); + return redirectTo(origin, loginErrorPath(result.reason, returnTo)); } const attendee = result.attendeeId ? await attendees.findById(result.attendeeId) : await attendees.findByEmail(result.email); - if (!attendee) return redirectTo(origin, "/login?error=unregistered"); - if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, "/login?error=unregistered"); + if (!attendee) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); const subject = await ensureUser(attendee.email, attendee.name); return await redirectWithSession(origin, returnTo, { @@ -71,36 +74,37 @@ async function handleMagicLink(token, origin, returnTo) { }); } catch (err) { console.error("[auth/callback] magic link:", err); - return redirectTo(origin, "/login?error=verification_failed"); + return redirectTo(origin, loginErrorPath("verification_failed", returnTo)); } } async function handleAuthorizationCode(request, code, state, origin) { + let stored = null; try { - const stored = await unsealOAuthState( + stored = await unsealOAuthState( request.cookies.get(OAUTH_COOKIE_NAME)?.value ?? "" ); // No cookie means the flow was started in another browser or expired; // a mismatch means someone tried to inject their own authorization code. if (!stored || stored.state !== state) { - return redirectTo(origin, "/login?error=state_mismatch"); + return redirectTo(origin, loginErrorPath("state_mismatch", stored?.returnTo)); } const tokens = await exchangeCodeForTokens(code, stored.codeVerifier); const claims = await verifyIdToken(tokens.id_token, stored.nonce); const email = claims.email?.toLowerCase().trim(); - if (!email) return redirectTo(origin, "/login?error=no_email"); - if (claims.email_verified !== true) return redirectTo(origin, "/login?error=email_unverified"); + const returnTo = safeReturnTo(stored.returnTo); + if (!email) return redirectTo(origin, loginErrorPath("no_email", returnTo)); + if (claims.email_verified !== true) return redirectTo(origin, loginErrorPath("email_unverified", returnTo)); // The roster is still the gate: a valid Google account that is not an // attendee gets no session, matching the previous sign-out-on-callback // behaviour. const attendee = await attendees.findByEmail(email); - if (!attendee) return redirectTo(origin, "/login?error=unregistered"); - const returnTo = safeReturnTo(stored.returnTo); - if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, "/login?error=unregistered"); + if (!attendee) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); const response = await redirectWithSession(origin, returnTo, { sub: claims.sub, @@ -113,7 +117,7 @@ async function handleAuthorizationCode(request, code, state, origin) { return response; } catch (err) { console.error("[auth/callback] authorization code:", err); - return redirectTo(origin, "/login?error=verification_failed"); + return redirectTo(origin, loginErrorPath("verification_failed", stored?.returnTo)); } } diff --git a/apps/web/lib/safe-return-to.ts b/apps/web/lib/safe-return-to.ts index 881a867..cfb0179 100644 --- a/apps/web/lib/safe-return-to.ts +++ b/apps/web/lib/safe-return-to.ts @@ -4,7 +4,7 @@ export function safeReturnTo(value: unknown): string { typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || - /[\\\u0000-\u0020\u007f]/.test(value) + /[\\\u0000- \u007f]/.test(value) ) return "/"; try { @@ -16,3 +16,17 @@ export function safeReturnTo(value: unknown): string { return "/"; } } + +/** Where a signed-in user goes; never back to /login, which would loop. */ +export function postLoginPath(value: unknown): string { + const destination = safeReturnTo(value); + return /^\/login(?:[/?#]|$)/.test(destination) ? "/" : destination; +} + +/** Login URL for a failed attempt that keeps the user's intended destination. */ +export function loginErrorPath(error: string, returnTo?: unknown): string { + const params = new URLSearchParams({ error }); + const destination = postLoginPath(returnTo); + if (destination !== "/") params.set("returnTo", destination); + return `/login?${params}`; +} diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index 85ba812..acacd05 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -1,23 +1,37 @@ import { NextResponse, type NextRequest } from "next/server"; +import { getSessionConfig, sessionCookieOptions, unsealSession } from "@match-maker/auth"; +import { postLoginPath } from "./lib/safe-return-to"; -const SESSION_COOKIE = process.env.SESSION_COOKIE_NAME || "mb_session"; const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); -export function middleware(request: NextRequest) { +export async function middleware(request: NextRequest) { if (request.nextUrl.pathname.startsWith("/api/")) { return SAFE_METHODS.has(request.method) || isSameOrigin(request) ? NextResponse.next() : NextResponse.json({ error: "Cross-site requests are not allowed" }, { status: 403 }); } + return loginRedirect(request); +} - // The login route can skip its form when a session cookie is present. - if (request.cookies.has(SESSION_COOKIE)) { - const url = request.nextUrl.clone(); - url.pathname = `/e/${process.env.DEFAULT_EVENT_SLUG || "demo"}`; - url.search = ""; - return NextResponse.redirect(url); +/** + * A valid session skips the login form and continues to `returnTo`. An expired + * or tampered cookie is cleared so the form shows instead of bouncing the user + * away. An `?error=` stays on the form so the user can switch accounts. + */ +async function loginRedirect(request: NextRequest) { + const { cookieName } = getSessionConfig(); + const raw = request.cookies.get(cookieName)?.value; + if (!raw) return NextResponse.next(); + + const { searchParams } = request.nextUrl; + const session = await unsealSession(raw); + if (session && !searchParams.has("error")) { + return NextResponse.redirect(new URL(postLoginPath(searchParams.get("returnTo")), request.url)); } - return NextResponse.next(); + + const response = NextResponse.next(); + if (!session) response.cookies.set(cookieName, "", sessionCookieOptions(0)); + return response; } /** @@ -44,4 +58,5 @@ function originOf(url: string | null): string | null { } } -export const config = { matcher: ["/login", "/api/:path*"] }; +// Session cookies are decrypted with node:crypto, so this cannot run on Edge. +export const config = { runtime: "nodejs", matcher: ["/login", "/api/:path*"] }; diff --git a/tests/unit/auth-redirect.test.ts b/tests/unit/auth-redirect.test.ts index 06cfb8f..d6e00e1 100644 --- a/tests/unit/auth-redirect.test.ts +++ b/tests/unit/auth-redirect.test.ts @@ -1,5 +1,26 @@ import { describe, expect, it } from "vitest"; -import { safeReturnTo } from "../../apps/web/lib/safe-return-to"; +import { loginErrorPath, postLoginPath, safeReturnTo } from "../../apps/web/lib/safe-return-to"; + +describe("post-login destinations", () => { + it.each(["/login", "/login?returnTo=%2Fe%2Fdemo", "/login/", "/login#form"])("never returns to the login page: %s", (value) => { + expect(postLoginPath(value)).toBe("/"); + }); + + it("keeps ordinary destinations, including look-alike paths", () => { + expect(postLoginPath("/e/demo/matches")).toBe("/e/demo/matches"); + expect(postLoginPath("/loginhelp")).toBe("/loginhelp"); + }); + + it("builds an error URL that keeps the destination", () => { + expect(loginErrorPath("unregistered", "/e/demo/profile")).toBe("/login?error=unregistered&returnTo=%2Fe%2Fdemo%2Fprofile"); + }); + + it("omits an empty, external, or looping destination from the error URL", () => { + expect(loginErrorPath("provider")).toBe("/login?error=provider"); + expect(loginErrorPath("provider", "https://outside.example")).toBe("/login?error=provider"); + expect(loginErrorPath("provider", "/login")).toBe("/login?error=provider"); + }); +}); describe("login return destinations", () => { it.each([ diff --git a/tests/unit/auth-routes.test.ts b/tests/unit/auth-routes.test.ts index fb40a08..10ed3dc 100644 --- a/tests/unit/auth-routes.test.ts +++ b/tests/unit/auth-routes.test.ts @@ -6,7 +6,7 @@ const mocks = vi.hoisted(() => ({ issueChallenge: vi.fn(), sendLoginEmail: vi.fn(), verifyCode: vi.fn(), ensureUser: vi.fn(), setSession: vi.fn(), exchangeCodeForTokens: vi.fn(), verifyIdToken: vi.fn(), unsealOAuthState: vi.fn(), sealSession: vi.fn(), - buildAuthorizationUrl: vi.fn(), sealOAuthState: vi.fn(), + buildAuthorizationUrl: vi.fn(), sealOAuthState: vi.fn(), verifyToken: vi.fn(), })); vi.mock("@match-maker/db", () => ({ @@ -135,3 +135,38 @@ describe("Google sign-in", () => { expect(mocks.exchangeCodeForTokens).not.toHaveBeenCalled(); }); }); + +describe("failed sign-in keeps the event destination", () => { + it("returns a cancelled Google consent to login for the same event", async () => { + const response = await callback(new NextRequest("http://localhost:3000/auth/callback?error=access_denied", { + headers: { cookie: "mb_oauth=sealed-state" }, + })); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=provider&returnTo=%2Fe%2Fdemo"); + expect(response.cookies.get("mb_oauth")?.value).toBe(""); + }); + + it("keeps the destination when the roster rejects a Google account", async () => { + mocks.findByEmail.mockResolvedValue(null); + const response = await callback(callbackRequest()); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=unregistered&returnTo=%2Fe%2Fdemo"); + }); + + it("keeps the destination when token exchange fails", async () => { + mocks.exchangeCodeForTokens.mockRejectedValue(new Error("keycloak down")); + vi.spyOn(console, "error").mockImplementation(() => {}); + const response = await callback(callbackRequest()); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=verification_failed&returnTo=%2Fe%2Fdemo"); + }); + + it("keeps the magic link destination when the link has expired", async () => { + mocks.verifyToken.mockResolvedValue({ ok: false, reason: "expired" }); + const response = await callback(new NextRequest("http://localhost:3000/auth/callback?token=old&returnTo=%2Fe%2Fdemo%2Fprofile")); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=expired&returnTo=%2Fe%2Fdemo%2Fprofile"); + }); + + it("keeps the destination when Google start rejects an uninvited email", async () => { + mocks.findByEmail.mockResolvedValue(null); + const response = await startGoogle(new NextRequest("http://localhost:3000/api/auth/google/start?email=x%40example.com&returnTo=%2Fe%2Fdemo")); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=unregistered&returnTo=%2Fe%2Fdemo"); + }); +}); diff --git a/tests/unit/middleware.test.ts b/tests/unit/middleware.test.ts new file mode 100644 index 0000000..926e8eb --- /dev/null +++ b/tests/unit/middleware.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; + +const unsealSession = vi.hoisted(() => vi.fn()); + +vi.mock("@match-maker/auth", () => ({ + unsealSession, + getSessionConfig: () => ({ cookieName: "mb_session" }), + sessionCookieOptions: (maxAge: number) => ({ httpOnly: true, sameSite: "lax", path: "/", maxAge }), +})); + +import { middleware } from "../../apps/web/middleware"; + +const session = { sub: "kc-user", email: "invited@example.com", name: null, attendeeId: "attendee-id", method: "email", iat: 0 }; +const loginRequest = (query = "", cookie?: string) => + new NextRequest(`http://localhost:3000/login${query}`, cookie ? { headers: { cookie } } : undefined); + +beforeEach(() => { + unsealSession.mockReset(); +}); + +describe("login middleware", () => { + it("shows the form when there is no session cookie", async () => { + const response = await middleware(loginRequest("?returnTo=%2Fe%2Fdemo")); + expect(response.headers.get("location")).toBeNull(); + expect(unsealSession).not.toHaveBeenCalled(); + }); + + it("sends a valid session to its requested destination", async () => { + unsealSession.mockResolvedValue(session); + const response = await middleware(loginRequest("?returnTo=%2Forgs%2Fai%2Fevents%2Fdemo", "mb_session=valid")); + expect(response.headers.get("location")).toBe("http://localhost:3000/orgs/ai/events/demo"); + }); + + it("sends a valid session without a destination to the home route", async () => { + unsealSession.mockResolvedValue(session); + const response = await middleware(loginRequest("", "mb_session=valid")); + expect(response.headers.get("location")).toBe("http://localhost:3000/"); + }); + + it.each(["/login", "/login?returnTo=%2Flogin", "https://outside.example"])( + "never redirects a valid session back to login or off-site: %s", + async (returnTo) => { + unsealSession.mockResolvedValue(session); + const response = await middleware(loginRequest(`?returnTo=${encodeURIComponent(returnTo)}`, "mb_session=valid")); + expect(response.headers.get("location")).toBe("http://localhost:3000/"); + } + ); + + it("keeps a valid session on the form when a sign-in error is shown", async () => { + unsealSession.mockResolvedValue(session); + const response = await middleware(loginRequest("?error=unregistered&returnTo=%2Fe%2Fother", "mb_session=valid")); + expect(response.headers.get("location")).toBeNull(); + expect(response.cookies.get("mb_session")).toBeUndefined(); + }); + + it("clears an expired or tampered cookie and shows the form", async () => { + unsealSession.mockResolvedValue(null); + const response = await middleware(loginRequest("?returnTo=%2Fe%2Fdemo%2Fprofile", "mb_session=expired")); + expect(response.headers.get("location")).toBeNull(); + expect(response.cookies.get("mb_session")).toMatchObject({ value: "", maxAge: 0 }); + }); +}); diff --git a/tests/unit/request-guards.test.ts b/tests/unit/request-guards.test.ts index 10aa22a..2b192de 100644 --- a/tests/unit/request-guards.test.ts +++ b/tests/unit/request-guards.test.ts @@ -84,8 +84,8 @@ describe("same-origin check", () => { }); it("blocks cross-site API mutations but not reads", async () => { - expect(middleware(post({ origin: "https://evil.example" })).status).toBe(403); - expect(middleware(post({ origin: "https://evil.example" }, "GET")).headers.get("x-middleware-next")).toBe("1"); + expect((await middleware(post({ origin: "https://evil.example" }))).status).toBe(403); + expect((await middleware(post({ origin: "https://evil.example" }, "GET"))).headers.get("x-middleware-next")).toBe("1"); }); }); From 7a6856a5747ecc175bc84ba326d4131a381e5296 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sat, 17 Oct 2026 13:52:19 +0530 Subject: [PATCH 06/48] Fail fast on undeliverable login e-mail; gate Google sign-in (R02 part 1) - Web startup refuses to boot without RESEND_API_KEY unless EMAIL_DEV_FALLBACK=true, and validates EMAIL_FROM once Resend is set - Offer "Sign in with Google" only when GOOGLE_CLIENT_ID is configured; the start route redirects to a clear error otherwise - Login page reads the flag per request (server component wrapper) - Pass GOOGLE_CLIENT_ID to the web container in Compose and ECS (cherry picked from commit 36a13d68ea8b1b21efbbee15c324fabac26f546c) --- apps/web/app/api/auth/google/start/route.js | 4 +++ apps/web/app/login.jsx | 7 +++-- apps/web/app/login/login-route.jsx | 19 ++++++++++++ apps/web/app/login/page.jsx | 23 +++----------- apps/web/src/lib/env.ts | 17 +++++++++++ docker-compose.yml | 2 ++ infra/terraform/ecs.tf | 2 ++ packages/auth/src/config.ts | 9 ++++++ packages/auth/src/index.ts | 1 + tests/unit/auth-config.test.ts | 18 +++++++++++ tests/unit/auth-routes.test.ts | 9 ++++++ tests/unit/env.test.ts | 34 ++++++++++++++++++++- turbo.json | 1 + 13 files changed, 124 insertions(+), 22 deletions(-) create mode 100644 apps/web/app/login/login-route.jsx create mode 100644 tests/unit/auth-config.test.ts diff --git a/apps/web/app/api/auth/google/start/route.js b/apps/web/app/api/auth/google/start/route.js index 14c2c0f..026be95 100644 --- a/apps/web/app/api/auth/google/start/route.js +++ b/apps/web/app/api/auth/google/start/route.js @@ -8,6 +8,7 @@ import { randomUrlSafe, sealOAuthState, sessionCookieOptions, + isGoogleSignInEnabled, OAUTH_COOKIE_NAME, OAUTH_COOKIE_MAX_AGE, } from "@match-maker/auth"; @@ -26,6 +27,9 @@ export async function GET(request) { const url = new URL(request.url); const email = url.searchParams.get("email")?.toLowerCase().trim() || ""; const returnTo = safeReturnTo(url.searchParams.get("returnTo")); + if (!isGoogleSignInEnabled()) { + return NextResponse.redirect(new URL(loginErrorPath("google_unavailable", returnTo), url.origin)); + } try { // The browser already checked the roster, but that check is advisory — diff --git a/apps/web/app/login.jsx b/apps/web/app/login.jsx index c426028..4fda5fd 100644 --- a/apps/web/app/login.jsx +++ b/apps/web/app/login.jsx @@ -24,6 +24,7 @@ const CODE_LENGTH = 6; const ERROR_MESSAGES = { unregistered: "That account is not on the attendee list.", provider: "Google sign-in failed. Please try again.", + google_unavailable: "Google sign-in isn't available yet. Please use an email code.", state_mismatch: "Your sign-in session expired. Please start again.", verification_failed: "We couldn't verify that sign-in. Please try again.", invalid_callback: "That sign-in link is incomplete. Please try again.", @@ -99,7 +100,7 @@ function StatusPill({ type, text }) { ); } -export default function Login({ onAuthSuccess }) { +export default function Login({ onAuthSuccess, googleEnabled = false }) { const searchParams = useSearchParams(); const returnTo = safeReturnTo(searchParams.get("returnTo")); const [step, setStep] = useState("choose"); @@ -264,7 +265,7 @@ export default function Login({ onAuthSuccess }) {
›
- + {googleEnabled &&
Choose the Google account on your invitation
-
+ }
{status && } diff --git a/apps/web/app/login/login-route.jsx b/apps/web/app/login/login-route.jsx new file mode 100644 index 0000000..b845c53 --- /dev/null +++ b/apps/web/app/login/login-route.jsx @@ -0,0 +1,19 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import Login from "../login.jsx"; + +export default function LoginRoute({ googleEnabled }) { + const router = useRouter(); + return ( + { + // The session cookie is set by the API response, so a refresh is needed + // for the server to see it on the next request. + router.replace(returnTo || "/"); + router.refresh(); + }} + /> + ); +} diff --git a/apps/web/app/login/page.jsx b/apps/web/app/login/page.jsx index 7d1fe1e..396275c 100644 --- a/apps/web/app/login/page.jsx +++ b/apps/web/app/login/page.jsx @@ -1,28 +1,15 @@ -"use client"; - import { Suspense } from "react"; -import { useRouter } from "next/navigation"; -import Login from "../login.jsx"; +import { isGoogleSignInEnabled } from "@match-maker/auth"; +import LoginRoute from "./login-route.jsx"; -function LoginRoute() { - const router = useRouter(); - return ( - { - // The session cookie is set by the API response, so a refresh is needed - // for the server to see it on the next request. - router.replace(returnTo || "/"); - router.refresh(); - }} - /> - ); -} +// Read Google availability per request, not once at build time. +export const dynamic = "force-dynamic"; export default function LoginPage() { // `useSearchParams` (used for the ?error= handling) needs a Suspense boundary. return ( }> - + ); } diff --git a/apps/web/src/lib/env.ts b/apps/web/src/lib/env.ts index 07e909e..36902de 100644 --- a/apps/web/src/lib/env.ts +++ b/apps/web/src/lib/env.ts @@ -68,6 +68,18 @@ export function checkEnv(role: EnvRole, env: Env = process.env): string[] { if (secret && secret.length < 32) { problems.push("SESSION_SECRET must be at least 32 characters."); } + + // Login depends on e-mail, so a deploy that cannot send it must not boot. + if (!value("RESEND_API_KEY") && value("EMAIL_DEV_FALLBACK") !== "true") { + problems.push("RESEND_API_KEY is required to send login e-mail (EMAIL_DEV_FALLBACK=true logs codes instead, local only)."); + } + const from = value("EMAIL_FROM"); + if (value("RESEND_API_KEY") && !from) { + problems.push("EMAIL_FROM is required when RESEND_API_KEY is set, using a sender on a domain verified in Resend."); + } + if (from && !isSenderAddress(from)) { + problems.push(`EMAIL_FROM must be "address@domain" or "Name ", got "${from}".`); + } } if (value("EMBEDDING_PROVIDER") === "local" && !value("LOCAL_BGE_URL")) { @@ -92,6 +104,11 @@ export function assertEnv(role: EnvRole, env: Env = process.env): void { ); } +function isSenderAddress(raw: string): boolean { + const address = raw.match(/^[^<>]*<([^<>]+)>$/)?.[1] ?? raw; + return /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(address.trim()); +} + function isHttpUrl(raw: string): boolean { try { const { protocol } = new URL(raw); diff --git a/docker-compose.yml b/docker-compose.yml index d60efc2..889f321 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -101,6 +101,8 @@ services: KEYCLOAK_INTERNAL_ISSUER: http://keycloak:8080/realms/match-maker KEYCLOAK_CLIENT_ID: match-maker-web KEYCLOAK_CLIENT_SECRET: ${KEYCLOAK_CLIENT_SECRET:-dev-client-secret-change-me} + # Shows the Google option only when Keycloak's Google provider is configured. + GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} SESSION_SECRET: ${SESSION_SECRET:?SESSION_SECRET is required - see .env.example} RESEND_API_KEY: ${RESEND_API_KEY:-} diff --git a/infra/terraform/ecs.tf b/infra/terraform/ecs.tf index 8d7ec90..e93cd80 100644 --- a/infra/terraform/ecs.tf +++ b/infra/terraform/ecs.tf @@ -232,6 +232,8 @@ resource "aws_ecs_task_definition" "web" { { name = "SESSION_SECRET", valueFrom = local.secret_ref.SESSION_SECRET }, { name = "KEYCLOAK_CLIENT_SECRET", valueFrom = local.secret_ref.KEYCLOAK_CLIENT_SECRET }, { name = "RESEND_API_KEY", valueFrom = local.secret_ref.RESEND_API_KEY }, + # Only its presence is read: it switches the Google sign-in option on. + { name = "GOOGLE_CLIENT_ID", valueFrom = local.secret_ref.GOOGLE_CLIENT_ID }, { name = "GEMINI_API_KEY", valueFrom = local.secret_ref.GEMINI_API_KEY }, { name = "UPSTASH_REDIS_REST_URL", valueFrom = local.secret_ref.UPSTASH_REDIS_REST_URL }, { name = "UPSTASH_REDIS_REST_TOKEN", valueFrom = local.secret_ref.UPSTASH_REDIS_REST_TOKEN }, diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.ts index 0099a84..4168037 100644 --- a/packages/auth/src/config.ts +++ b/packages/auth/src/config.ts @@ -55,6 +55,15 @@ export function getAuthConfig(): AuthConfig { }; } +/** + * Google sign-in is offered only when the Google client is configured; the + * same GOOGLE_CLIENT_ID feeds Keycloak's identity provider. + */ +export function isGoogleSignInEnabled(): boolean { + const clientId = process.env.GOOGLE_CLIENT_ID?.trim(); + return Boolean(clientId && clientId !== "not-configured"); +} + export interface SessionConfig { secret: string; cookieName: string; diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 0f199df..f1d2cf9 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -2,6 +2,7 @@ export { getAuthConfig, getSessionConfig, getOtpConfig, + isGoogleSignInEnabled, type AuthConfig, type SessionConfig, type OtpConfig, diff --git a/tests/unit/auth-config.test.ts b/tests/unit/auth-config.test.ts new file mode 100644 index 0000000..fcf1001 --- /dev/null +++ b/tests/unit/auth-config.test.ts @@ -0,0 +1,18 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { isGoogleSignInEnabled } from "@match-maker/auth"; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("Google sign-in availability", () => { + it.each(["", " ", "not-configured"])("is off without a real Google client id: %j", (clientId) => { + vi.stubEnv("GOOGLE_CLIENT_ID", clientId); + expect(isGoogleSignInEnabled()).toBe(false); + }); + + it("is on once a Google client id is configured", () => { + vi.stubEnv("GOOGLE_CLIENT_ID", "1234.apps.googleusercontent.com"); + expect(isGoogleSignInEnabled()).toBe(true); + }); +}); diff --git a/tests/unit/auth-routes.test.ts b/tests/unit/auth-routes.test.ts index 10ed3dc..a7abde7 100644 --- a/tests/unit/auth-routes.test.ts +++ b/tests/unit/auth-routes.test.ts @@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({ ensureUser: vi.fn(), setSession: vi.fn(), exchangeCodeForTokens: vi.fn(), verifyIdToken: vi.fn(), unsealOAuthState: vi.fn(), sealSession: vi.fn(), buildAuthorizationUrl: vi.fn(), sealOAuthState: vi.fn(), verifyToken: vi.fn(), + isGoogleSignInEnabled: vi.fn(), })); vi.mock("@match-maker/db", () => ({ @@ -59,6 +60,7 @@ beforeEach(() => { mocks.sealSession.mockResolvedValue("sealed-session"); mocks.buildAuthorizationUrl.mockResolvedValue("http://localhost:8080/realms/match-maker/protocol/openid-connect/auth?kc_idp_hint=google"); mocks.sealOAuthState.mockResolvedValue("sealed-state"); + mocks.isGoogleSignInEnabled.mockReturnValue(true); }); describe("on-site email and phone login", () => { @@ -98,6 +100,13 @@ describe("Google sign-in", () => { expect(mocks.sealOAuthState).toHaveBeenCalledWith(expect.objectContaining({ returnTo: "/e/demo" })); }); + it("refuses to start Google when it is not configured", async () => { + mocks.isGoogleSignInEnabled.mockReturnValue(false); + const response = await startGoogle(new NextRequest("http://localhost:3000/api/auth/google/start?returnTo=%2Fe%2Fdemo")); + expect(response.headers.get("location")).toBe("http://localhost:3000/login?error=google_unavailable&returnTo=%2Fe%2Fdemo"); + expect(mocks.buildAuthorizationUrl).not.toHaveBeenCalled(); + }); + it("returns a verified invited account to its event with a session", async () => { const response = await callback(callbackRequest()); expect(response.headers.get("location")).toBe("http://localhost:3000/e/demo"); diff --git a/tests/unit/env.test.ts b/tests/unit/env.test.ts index c0a5807..d5f2b85 100644 --- a/tests/unit/env.test.ts +++ b/tests/unit/env.test.ts @@ -7,6 +7,7 @@ const validWeb = { KEYCLOAK_ISSUER: "http://localhost:8080/realms/match-maker", KEYCLOAK_CLIENT_ID: "match-maker-web", KEYCLOAK_CLIENT_SECRET: "secret", + EMAIL_DEV_FALLBACK: "true", }; describe("checkEnv", () => { @@ -16,7 +17,7 @@ describe("checkEnv", () => { it("lists every missing web setting at once", () => { const problems = checkEnv("web", {}); - expect(problems).toHaveLength(5); + expect(problems).toHaveLength(6); expect(problems.join("\n")).toContain("SESSION_SECRET is required"); expect(problems.join("\n")).toContain("KEYCLOAK_CLIENT_SECRET is required"); }); @@ -69,6 +70,37 @@ describe("checkEnv", () => { }); }); +describe("login e-mail settings", () => { + const { EMAIL_DEV_FALLBACK: _fallback, ...production } = validWeb; + + it("refuses to boot the web app when login e-mail cannot be delivered", () => { + expect(checkEnv("web", production)).toEqual([ + "RESEND_API_KEY is required to send login e-mail (EMAIL_DEV_FALLBACK=true logs codes instead, local only).", + ]); + expect(checkEnv("web", { ...production, EMAIL_DEV_FALLBACK: "false" })).toHaveLength(1); + }); + + it("does not require e-mail settings for the worker", () => { + expect(checkEnv("worker", { DATABASE_URL: validWeb.DATABASE_URL })).toEqual([]); + }); + + it("requires a sender address once Resend is configured", () => { + expect(checkEnv("web", { ...production, RESEND_API_KEY: "re_key" })).toEqual([ + "EMAIL_FROM is required when RESEND_API_KEY is set, using a sender on a domain verified in Resend.", + ]); + }); + + it.each(["login@bridge.example", "Mr. Bridge "])("accepts the sender %s", (from) => { + expect(checkEnv("web", { ...production, RESEND_API_KEY: "re_key", EMAIL_FROM: from })).toEqual([]); + }); + + it.each(["Mr. Bridge", "Mr. Bridge ", "login@localhost"])("rejects the sender %s", (from) => { + expect(checkEnv("web", { ...production, RESEND_API_KEY: "re_key", EMAIL_FROM: from })).toEqual([ + `EMAIL_FROM must be "address@domain" or "Name ", got "${from}".`, + ]); + }); +}); + describe("assertEnv", () => { it("throws one error naming every problem", () => { expect(() => assertEnv("web", {})).toThrowError(/Invalid web configuration:[\s\S]*DATABASE_URL[\s\S]*SESSION_SECRET/); diff --git a/turbo.json b/turbo.json index e10e99e..5116589 100644 --- a/turbo.json +++ b/turbo.json @@ -17,6 +17,7 @@ "KEYCLOAK_CLIENT_ID", "KEYCLOAK_CLIENT_SECRET", "KEYCLOAK_GOOGLE_IDP_ALIAS", + "GOOGLE_CLIENT_ID", "RESEND_API_KEY", "EMAIL_FROM", "EMAIL_DEV_FALLBACK", From 6c1ba2d1f859cad07b6688f44496e04318287bb9 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Sat, 17 Oct 2026 13:54:11 +0530 Subject: [PATCH 07/48] Add keycloak:sync and production e-mail deploy guard (R02 part 2) - New `npm run keycloak:sync` applies KEYCLOAK_CLIENT_SECRET and the Google client id/secret from the environment to an already-imported realm via the admin API (realm import only runs on first boot) - Deploy workflow rejects a web task that enables EMAIL_DEV_FALLBACK or has no RESEND_API_KEY secret - Document activating Resend and Google, locally and in AWS (cherry picked from commit 55165034f1a1798a5def76cadc6901a3b091c5fb) --- .env.example | 6 ++- .github/workflows/deploy.yml | 11 ++++ ReadMe.md | 17 ++++++ package.json | 3 +- tests/unit/sync-keycloak.test.ts | 68 ++++++++++++++++++++++++ tools/sync-keycloak.ts | 88 ++++++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 tests/unit/sync-keycloak.test.ts create mode 100644 tools/sync-keycloak.ts diff --git a/.env.example b/.env.example index 1a8f555..5e1a5d0 100644 --- a/.env.example +++ b/.env.example @@ -43,11 +43,15 @@ KEYCLOAK_GOOGLE_IDP_ALIAS=google # From Google Cloud Console > APIs & Services > Credentials. # Authorised redirect URI must be: # http://localhost:8080/realms/match-maker/broker/google/endpoint -# Leave blank to develop with the e-mail-code path only. +# Leave blank to develop with the e-mail-code path only; the login page shows +# "Sign in with Google" only when GOOGLE_CLIENT_ID is set. After changing these +# (or KEYCLOAK_CLIENT_SECRET) on an existing realm, run: npm run keycloak:sync GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= # ── Resend (login e-mails) ──────────────────────────────────── +# The web app refuses to start without a key unless EMAIL_DEV_FALLBACK=true. +# EMAIL_FROM must use a domain verified in Resend. RESEND_API_KEY= EMAIL_FROM=Mr. Bridge diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bf9fb36..1a48e80 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -256,6 +256,17 @@ jobs: --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" --query 'services[0].taskDefinition' --output text)" \ --query 'taskDefinition' > taskdef.json + # Production login must send real e-mail: never ship the dev fallback, + # and require the Resend key (an empty value fails the app's startup check). + if jq -e '[.containerDefinitions[].environment[]? | select(.name == "EMAIL_DEV_FALLBACK" and .value == "true")] | length > 0' taskdef.json >/dev/null; then + echo "::error::EMAIL_DEV_FALLBACK=true is set on the web task; login codes would be logged instead of sent." + exit 1 + fi + if ! jq -e '[.containerDefinitions[].secrets[]? | select(.name == "RESEND_API_KEY")] | length > 0' taskdef.json >/dev/null; then + echo "::error::The web task has no RESEND_API_KEY secret; login e-mail cannot be delivered." + exit 1 + fi + # Strip the server-managed fields that RegisterTaskDefinition rejects, # then point the container at the immutable tag. jq --arg IMAGE "$REGISTRY/match-maker-prod/web:$TAG" ' diff --git a/ReadMe.md b/ReadMe.md index f003029..76b1b32 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -107,6 +107,7 @@ The first command imports the global attendee directory so the organizer account | `npm run db:seed` | Upsert demo roster, organization, event, and organizer | | `npm run db:import -- [event-slug]` | Import attendee rows and optionally attach them to an event | | `npm run keycloak:wait` | Wait for the configured Keycloak realm to respond | +| `npm run keycloak:sync` | Apply the client secret and Google credentials from `.env` to an existing realm | | `npm run docker:up` | Build images and start the local Compose stack | `DATABASE_URL` should point at `localhost` for commands run on the host. Compose sets the service hostname `postgres` inside containers. @@ -125,6 +126,22 @@ See `.env.example` for the full list. The main settings are: | `DEFAULT_EVENT_SLUG` | Event used by the `/` redirect | | `SEED_ON_MIGRATE` | Seeds demo data in the local stack; leave false in production | +## Activating real e-mail and Google sign-in + +Locally, login codes are printed to the web log (`EMAIL_DEV_FALLBACK=true`) and the Google option is hidden. To switch on the real services: + +1. **E-mail:** verify a sending domain in [Resend](https://resend.com), then set `RESEND_API_KEY` and `EMAIL_FROM` (for example `Mr. Bridge `). Set `EMAIL_DEV_FALLBACK=false` to prove delivery works. +2. **Google:** create an OAuth web client in Google Cloud Console with the authorised redirect URI `http://localhost:8080/realms/match-maker/broker/google/endpoint` (use your Keycloak host in other environments). Set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. +3. Apply the credentials to the running realm and restart the web app: + + ```powershell + npm run keycloak:sync + ``` + + Keycloak imports `realm-export.json` only on first boot, so editing `.env` alone does not update an existing realm. + +In AWS, put the same values in the app's Secrets Manager secret (see `terraform output`). The web app refuses to start without `RESEND_API_KEY`, and the deploy workflow rejects a web task that enables `EMAIL_DEV_FALLBACK` or lacks the Resend secret. + ## Docker and deployment Build from the repository root: diff --git a/package.json b/package.json index 849b513..bf5dd6d 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,8 @@ "docker:up": "docker compose up -d --build", "docker:down": "docker compose down", "docker:logs": "docker compose logs -f web", - "keycloak:wait": "tsx tools/wait-for-keycloak.ts" + "keycloak:wait": "tsx tools/wait-for-keycloak.ts", + "keycloak:sync": "tsx tools/sync-keycloak.ts" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/tests/unit/sync-keycloak.test.ts b/tests/unit/sync-keycloak.test.ts new file mode 100644 index 0000000..4a6b8c9 --- /dev/null +++ b/tests/unit/sync-keycloak.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from "vitest"; +import { syncKeycloak } from "../../tools/sync-keycloak"; + +const env = { + KEYCLOAK_ISSUER: "http://localhost:8080/realms/match-maker", + KEYCLOAK_CLIENT_ID: "match-maker-web", + KEYCLOAK_CLIENT_SECRET: "new-secret", + KEYCLOAK_ADMIN: "admin", + KEYCLOAK_ADMIN_PASSWORD: "admin", +}; +const admin = "http://localhost:8080/admin/realms/match-maker"; + +function fakeKeycloak(currentSecret = "old-secret") { + const calls: Array<{ method: string; url: string; body?: unknown }> = []; + const http = vi.fn(async (url: string, init: RequestInit = {}) => { + const method = init.method ?? "GET"; + calls.push({ method, url, body: typeof init.body === "string" ? JSON.parse(init.body) : undefined }); + const json = (data: unknown) => new Response(JSON.stringify(data), { status: 200 }); + if (url.endsWith("/realms/master/protocol/openid-connect/token")) return json({ access_token: "admin-token" }); + if (method === "PUT") return new Response(null, { status: 204 }); + if (url.includes("/clients?clientId=")) return json([{ id: "client-uuid", clientId: env.KEYCLOAK_CLIENT_ID }]); + if (url.endsWith("/client-secret")) return json({ value: currentSecret }); + if (url.endsWith("/identity-provider/instances/google")) return json({ alias: "google", enabled: false, config: { syncMode: "IMPORT" } }); + return new Response(null, { status: 404 }); + }); + return { http: http as unknown as typeof fetch, calls }; +} + +describe("keycloak:sync", () => { + it("updates a stale client secret and skips Google when it is not configured", async () => { + const { http, calls } = fakeKeycloak(); + const report = await syncKeycloak(env, http); + expect(report).toEqual([ + "client match-maker-web: secret updated", + "identity provider google: skipped, GOOGLE_CLIENT_ID is not set", + ]); + expect(calls.find((call) => call.method === "PUT")).toMatchObject({ + url: `${admin}/clients/client-uuid`, + body: { id: "client-uuid", secret: "new-secret" }, + }); + }); + + it("leaves a matching client secret alone", async () => { + const { http, calls } = fakeKeycloak("new-secret"); + expect((await syncKeycloak(env, http))[0]).toBe("client match-maker-web: secret already matches"); + expect(calls.some((call) => call.method === "PUT")).toBe(false); + }); + + it("enables the Google provider with the configured credentials", async () => { + const { http, calls } = fakeKeycloak("new-secret"); + const report = await syncKeycloak({ ...env, GOOGLE_CLIENT_ID: "id.apps.googleusercontent.com", GOOGLE_CLIENT_SECRET: "gsecret" }, http); + expect(report[1]).toBe("identity provider google: Google client updated and enabled"); + expect(calls.find((call) => call.method === "PUT")).toMatchObject({ + url: `${admin}/identity-provider/instances/google`, + body: { enabled: true, config: { syncMode: "IMPORT", clientId: "id.apps.googleusercontent.com", clientSecret: "gsecret" } }, + }); + }); + + it("requires the Google secret alongside the Google client id", async () => { + const { http } = fakeKeycloak("new-secret"); + await expect(syncKeycloak({ ...env, GOOGLE_CLIENT_ID: "id" }, http)).rejects.toThrow("GOOGLE_CLIENT_SECRET is required"); + }); + + it("reports a failed admin login clearly", async () => { + const http = vi.fn(async () => new Response(null, { status: 401 })) as unknown as typeof fetch; + await expect(syncKeycloak(env, http)).rejects.toThrow("Keycloak admin login failed (401)"); + }); +}); diff --git a/tools/sync-keycloak.ts b/tools/sync-keycloak.ts new file mode 100644 index 0000000..4ba2118 --- /dev/null +++ b/tools/sync-keycloak.ts @@ -0,0 +1,88 @@ +/** + * Push credentials from the environment into an already-imported Keycloak realm. + * + * Keycloak imports realm-export.json only when the realm does not exist yet, so + * changing KEYCLOAK_CLIENT_SECRET or the Google credentials in .env (or in AWS + * Secrets Manager) has no effect on a running realm. This applies them through + * the admin REST API. Safe to re-run. + * + * Run with: npm run keycloak:sync + */ +import { isMainModule } from "../packages/db/src/is-main"; + +type Env = Record; + +export async function syncKeycloak(env: Env = process.env, http: typeof fetch = fetch): Promise { + const issuer = (env.KEYCLOAK_INTERNAL_ISSUER || env.KEYCLOAK_ISSUER || "").replace(/\/$/, ""); + const match = issuer.match(/^(https?:\/\/.+)\/realms\/([^/]+)$/); + if (!match) throw new Error("KEYCLOAK_ISSUER must look like http://host:port/realms/."); + const [, server, realm] = match; + const clientId = required(env, "KEYCLOAK_CLIENT_ID"); + const clientSecret = required(env, "KEYCLOAK_CLIENT_SECRET"); + + const token = await adminToken(http, server, required(env, "KEYCLOAK_ADMIN"), required(env, "KEYCLOAK_ADMIN_PASSWORD")); + const api = async (path: string, init: RequestInit = {}) => { + const response = await http(`${server}/admin/realms/${realm}${path}`, { + ...init, + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + }); + if (!response.ok) throw new Error(`${init.method ?? "GET"} ${path} failed (${response.status}).`); + return response; + }; + + const report: string[] = []; + const [client] = await (await api(`/clients?clientId=${encodeURIComponent(clientId)}`)).json(); + if (!client) throw new Error(`Client "${clientId}" does not exist in realm "${realm}".`); + const current = await (await api(`/clients/${client.id}/client-secret`)).json(); + if (current.value === clientSecret) { + report.push(`client ${clientId}: secret already matches`); + } else { + await api(`/clients/${client.id}`, { method: "PUT", body: JSON.stringify({ ...client, secret: clientSecret }) }); + report.push(`client ${clientId}: secret updated`); + } + + const alias = env.KEYCLOAK_GOOGLE_IDP_ALIAS || "google"; + const googleId = env.GOOGLE_CLIENT_ID?.trim(); + if (!googleId || googleId === "not-configured") { + report.push(`identity provider ${alias}: skipped, GOOGLE_CLIENT_ID is not set`); + return report; + } + const googleSecret = required(env, "GOOGLE_CLIENT_SECRET"); + const path = `/identity-provider/instances/${encodeURIComponent(alias)}`; + const provider = await (await api(path)).json(); + await api(path, { + method: "PUT", + body: JSON.stringify({ + ...provider, + enabled: true, + config: { ...provider.config, clientId: googleId, clientSecret: googleSecret }, + }), + }); + report.push(`identity provider ${alias}: Google client updated and enabled`); + return report; +} + +async function adminToken(http: typeof fetch, server: string, username: string, password: string): Promise { + const response = await http(`${server}/realms/master/protocol/openid-connect/token`, { + method: "POST", + body: new URLSearchParams({ grant_type: "password", client_id: "admin-cli", username, password }), + }); + if (!response.ok) throw new Error(`Keycloak admin login failed (${response.status}). Check KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD.`); + return (await response.json()).access_token; +} + +function required(env: Env, name: string): string { + const value = env[name]?.trim(); + if (!value) throw new Error(`${name} is required. See .env.example.`); + return value; +} + +if (isMainModule(import.meta.url)) { + await import("dotenv/config"); + try { + for (const line of await syncKeycloak()) console.info(`[keycloak:sync] ${line}`); + } catch (error) { + console.error(`[keycloak:sync] ${(error as Error).message}`); + process.exit(1); + } +} From 8c75c8fe6f7f5d8173f3c32da0738b3ca4660776 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:34:22 +0530 Subject: [PATCH 08/48] Verify database TLS and add least-privilege logins (R11 part 1) - DATABASE_SSL=verify checks the server certificate against DATABASE_CA_CERT or DATABASE_CA_CERT_FILE and refuses to run without one; "require" stays encrypted-but-unverified. ensure-database uses the same rules instead of always skipping verification - Production startup (web and worker) refuses a remote database without verify + CA, and the web app refuses a non-https APP_BASE_URL; local hosts stay exempt so docker-compose still runs - HSTS is sent when APP_BASE_URL is https - Web, worker, migrate and Keycloak images ship Amazon's RDS CA bundle - ensure-roles.ts (run by the migration task as the master user): a runtime login with row-level read/write and no DDL, and a Keycloak login that owns the Keycloak database, including tables an earlier deploy created as master (handed over object by object, since REASSIGN OWNED would also move databases). CONNECT is revoked from PUBLIC on both databases. Re-running rotates passwords - Real-Postgres test of what each login can and cannot do --- apps/web/Dockerfile | 4 + apps/web/next.config.mjs | 4 + apps/web/src/lib/env.ts | 27 ++++- infra/docker/keycloak.Dockerfile | 3 + infra/docker/migrate.Dockerfile | 4 + infra/docker/worker.Dockerfile | 5 + packages/db/src/client.ts | 43 +++++-- packages/db/src/ensure-database.ts | 6 +- packages/db/src/ensure-roles.ts | 148 +++++++++++++++++++++++ tests/integration/database-roles.test.ts | 100 +++++++++++++++ tests/unit/env.test.ts | 2 +- tests/unit/production-transport.test.ts | 73 +++++++++++ 12 files changed, 400 insertions(+), 19 deletions(-) create mode 100644 packages/db/src/ensure-roles.ts create mode 100644 tests/integration/database-roles.test.ts create mode 100644 tests/unit/production-transport.test.ts diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 4b1eae2..e5fffc4 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -56,6 +56,10 @@ COPY --from=builder --chown=node:node /repo/apps/web/.next/standalone ./ COPY --from=builder --chown=node:node /repo/apps/web/.next/static ./apps/web/.next/static COPY --from=builder --chown=node:node /repo/apps/web/public ./apps/web/public +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + # The release tag (commit SHA) the deploy built, reported by /api/health so # smoke tests and rollbacks can tell which version is serving. Declared late # so a new tag does not invalidate the cached layers above. diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs index e6f283f..e50b24c 100644 --- a/apps/web/next.config.mjs +++ b/apps/web/next.config.mjs @@ -42,6 +42,10 @@ const nextConfig = { { key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Frame-Options", value: "DENY" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, + // Browsers that have seen the HTTPS site never fall back to HTTP. + ...(process.env.APP_BASE_URL?.startsWith("https://") + ? [{ key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" }] + : []), ], }, ]; diff --git a/apps/web/src/lib/env.ts b/apps/web/src/lib/env.ts index 36902de..2a9f2b3 100644 --- a/apps/web/src/lib/env.ts +++ b/apps/web/src/lib/env.ts @@ -26,7 +26,7 @@ const POSITIVE_INTEGERS = [ ]; const ALLOWED: Record = { - DATABASE_SSL: ["disable", "require"], + DATABASE_SSL: ["disable", "require", "verify"], EMBEDDING_PROVIDER: ["gemini", "local"], EMAIL_DEV_FALLBACK: ["true", "false"], TRUSTED_PROXY_HOPS: ["0", "1", "2", "3"], @@ -63,6 +63,23 @@ export function checkEnv(role: EnvRole, env: Env = process.env): string[] { problems.push("DATABASE_URL must start with postgres:// or postgresql://."); } + // Production must not quietly fall back to unverified or plain transport. + // Local hosts are exempt so the docker-compose stack still runs as production. + if (value("NODE_ENV") === "production") { + if (databaseUrl && !isLocalHost(databaseUrl)) { + if (value("DATABASE_SSL") !== "verify") { + problems.push("DATABASE_SSL must be verify in production, so the database certificate is checked."); + } else if (!value("DATABASE_CA_CERT") && !value("DATABASE_CA_CERT_FILE")) { + problems.push("DATABASE_SSL=verify needs DATABASE_CA_CERT or DATABASE_CA_CERT_FILE (the RDS CA bundle)."); + } + } + const base = value("APP_BASE_URL"); + if (role === "web" && !base) problems.push("APP_BASE_URL is required in production."); + if (role === "web" && base && isHttpUrl(base) && !isLocalHost(base) && new URL(base).protocol !== "https:") { + problems.push(`APP_BASE_URL must use https in production, got "${base}".`); + } + } + if (role === "web") { const secret = value("SESSION_SECRET"); if (secret && secret.length < 32) { @@ -109,6 +126,14 @@ function isSenderAddress(raw: string): boolean { return /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(address.trim()); } +function isLocalHost(raw: string): boolean { + try { + return ["localhost", "127.0.0.1", "postgres"].includes(new URL(raw).hostname); + } catch { + return false; + } +} + function isHttpUrl(raw: string): boolean { try { const { protocol } = new URL(raw); diff --git a/infra/docker/keycloak.Dockerfile b/infra/docker/keycloak.Dockerfile index e3b197c..a4b68a9 100644 --- a/infra/docker/keycloak.Dockerfile +++ b/infra/docker/keycloak.Dockerfile @@ -23,6 +23,9 @@ FROM quay.io/keycloak/keycloak:26.0 COPY --from=builder /opt/keycloak/ /opt/keycloak/ +# Amazon's RDS CA bundle, referenced by KC_DB_URL (sslmode=verify-full). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /opt/keycloak/conf/rds-global-bundle.pem + # Imported on first boot. Placeholders inside are filled from the task's # environment (client secret, app URL, Google credentials). COPY keycloak/realm-export.json /opt/keycloak/data/import/realm-export.json diff --git a/infra/docker/migrate.Dockerfile b/infra/docker/migrate.Dockerfile index 5ff48e9..dc200b4 100644 --- a/infra/docker/migrate.Dockerfile +++ b/infra/docker/migrate.Dockerfile @@ -19,5 +19,9 @@ RUN --mount=type=cache,target=/root/.npm \ COPY packages/db packages/db COPY tools tools +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + # Seeding is opt-in: it must run on a fresh local stack, never against prod data. CMD ["sh", "-c", "npx tsx packages/db/src/migrate.ts && if [ \"$SEED_ON_MIGRATE\" = \"true\" ]; then npx tsx packages/db/src/seed.ts; fi"] diff --git a/infra/docker/worker.Dockerfile b/infra/docker/worker.Dockerfile index ca7b4e8..fb4e9eb 100644 --- a/infra/docker/worker.Dockerfile +++ b/infra/docker/worker.Dockerfile @@ -1,3 +1,4 @@ +# syntax=docker/dockerfile:1.7 # Runs the async profile embedding and matching queue processors. FROM node:22-alpine WORKDIR /repo @@ -15,6 +16,10 @@ COPY packages/db packages/db COPY packages/auth packages/auth COPY packages/email packages/email +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + ENV NODE_ENV=production # Release tag (commit SHA), logged when the worker starts. ARG APP_VERSION=dev diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 1a49db3..40c6aaa 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -1,4 +1,5 @@ import pg from "pg"; +import { readFileSync } from "node:fs"; import type { ConnectionOptions as TlsOptions } from "node:tls"; const { Pool } = pg; @@ -38,8 +39,6 @@ export function getPool(): pg.Pool { pool = new Pool({ connectionString, - // RDS terminates TLS with an Amazon-issued CA that is not in Node's default - // trust store. Verification is enabled only when a CA bundle is supplied. ssl: resolveSsl(connectionString), max: Number(process.env.DATABASE_POOL_MAX ?? 10), idleTimeoutMillis: 30_000, @@ -56,18 +55,36 @@ export function getPool(): pg.Pool { return pool; } -function resolveSsl(connectionString: string): TlsOptions | false { - if (process.env.DATABASE_SSL === "disable") return false; - - // Local docker-compose Postgres has no TLS at all. - const isLocal = - connectionString.includes("@localhost") || - connectionString.includes("@127.0.0.1") || - connectionString.includes("@postgres:"); - if (isLocal && process.env.DATABASE_SSL !== "require") return false; +/** + * TLS for a connection, from DATABASE_SSL: + * disable plain connection (local docker-compose Postgres has no TLS) + * require encrypted, certificate not checked + * verify encrypted and the server certificate is checked against + * DATABASE_CA_CERT (PEM text) or DATABASE_CA_CERT_FILE (a path); + * production images ship the RDS bundle for this + * Unset: off for local hosts, otherwise verify when a CA is configured and + * require when not. Production startup refuses `require` for remote hosts. + */ +export function resolveSsl(connectionString: string, env: NodeJS.ProcessEnv = process.env): TlsOptions | false { + const mode = env.DATABASE_SSL; + if (mode === "disable") return false; + if (!mode && isLocalDatabase(connectionString)) return false; + + const ca = env.DATABASE_CA_CERT || (env.DATABASE_CA_CERT_FILE ? readFileSync(env.DATABASE_CA_CERT_FILE, "utf8") : ""); + if (mode === "verify" && !ca) { + throw new Error("DATABASE_SSL=verify needs DATABASE_CA_CERT or DATABASE_CA_CERT_FILE"); + } + if (mode === "verify" || (!mode && ca)) return { ca, rejectUnauthorized: true }; + return { rejectUnauthorized: false }; +} - const ca = process.env.DATABASE_CA_CERT; - return ca ? { ca, rejectUnauthorized: true } : { rejectUnauthorized: false }; +/** Local docker-compose or developer databases, which have no TLS. */ +export function isLocalDatabase(connectionString: string): boolean { + try { + return ["localhost", "127.0.0.1", "postgres"].includes(new URL(connectionString).hostname); + } catch { + return false; + } } /** Run a parameterised query. Never interpolate user input into `text`. */ diff --git a/packages/db/src/ensure-database.ts b/packages/db/src/ensure-database.ts index 0ffeeea..a61ab19 100644 --- a/packages/db/src/ensure-database.ts +++ b/packages/db/src/ensure-database.ts @@ -10,6 +10,7 @@ import "dotenv/config"; import pg from "pg"; import { isMainModule } from "./is-main"; +import { resolveSsl } from "./client"; /** * Connect to the `postgres` maintenance database rather than the target, since @@ -32,10 +33,7 @@ export async function ensureDatabase(name: string): Promise { const client = new pg.Client({ connectionString: maintenanceUrl(databaseUrl), - ssl: - process.env.DATABASE_SSL === "disable" - ? false - : { rejectUnauthorized: false }, + ssl: resolveSsl(databaseUrl), }); await client.connect(); diff --git a/packages/db/src/ensure-roles.ts b/packages/db/src/ensure-roles.ts new file mode 100644 index 0000000..15388da --- /dev/null +++ b/packages/db/src/ensure-roles.ts @@ -0,0 +1,148 @@ +/** + * Create or update the least-privilege database logins. The migration task runs + * this as the master user, before migrations: + * + * runtime web and worker: read and write application rows; no DDL, and no + * access to other databases + * keycloak owns the Keycloak database and nothing in the application one + * + * The master login is then used only by migrations. Passwords come from the + * task's secrets, and re-running updates them, so rotation is a redeploy. + * + * Usage: tsx packages/db/src/ensure-roles.ts + * DATABASE_URL master connection to the application database + * DATABASE_RUNTIME_USER / _PASSWORD runtime login (skipped when unset) + * KEYCLOAK_DB_USER / _PASSWORD Keycloak login (skipped when unset) + * KEYCLOAK_DB_NAME Keycloak database (default "keycloak") + */ +import "dotenv/config"; +import pg from "pg"; +import { isMainModule } from "./is-main"; +import { resolveSsl } from "./client"; + +export interface RoleSpec { + runtime?: { user: string; password: string }; + keycloak?: { user: string; password: string; database: string }; +} + +const IDENTIFIER = /^[a-z_][a-z0-9_]{0,62}$/; + +export async function ensureRoles(databaseUrl: string, spec: RoleSpec): Promise { + for (const name of [spec.runtime?.user, spec.keycloak?.user, spec.keycloak?.database]) { + if (name !== undefined && !IDENTIFIER.test(name)) throw new Error(`Invalid role or database name: ${name}`); + } + + const app = await connect(databaseUrl); + try { + if (spec.runtime) await ensureRuntime(app, spec.runtime.user, spec.runtime.password, new URL(databaseUrl).pathname.slice(1)); + if (spec.keycloak) await ensureLogin(app, spec.keycloak.user, spec.keycloak.password); + } finally { + await app.end(); + } + + if (spec.keycloak) { + const url = new URL(databaseUrl); + url.pathname = `/${spec.keycloak.database}`; + const identity = await connect(url.toString()); + try { + await ensureKeycloakOwner(identity, spec.keycloak.user, spec.keycloak.database); + } finally { + await identity.end(); + } + } +} + +async function connect(connectionString: string): Promise { + const client = new pg.Client({ connectionString, ssl: resolveSsl(connectionString) }); + await client.connect(); + return client; +} + +async function ensureLogin(client: pg.Client, user: string, password: string): Promise { + const role = client.escapeIdentifier(user); + const { rowCount } = await client.query(`select 1 from pg_roles where rolname = $1`, [user]); + if (!rowCount) await client.query(`create role ${role} login`); + await client.query(`alter role ${role} with login nosuperuser nocreatedb nocreaterole password ${client.escapeLiteral(password)}`); + console.log(`[ensure-roles] login ${user} ready`); +} + +async function ensureRuntime(client: pg.Client, user: string, password: string, database: string): Promise { + await ensureLogin(client, user, password); + const role = client.escapeIdentifier(user); + const db = client.escapeIdentifier(database); + for (const statement of [ + // Only named logins may connect to the application database. + `revoke connect on database ${db} from public`, + `grant connect on database ${db} to ${role}`, + `grant usage on schema public to ${role}`, + `grant select, insert, update, delete on all tables in schema public to ${role}`, + `grant usage, select on all sequences in schema public to ${role}`, + // Tables and sequences that later migrations create (as this master login). + `alter default privileges in schema public grant select, insert, update, delete on tables to ${role}`, + `alter default privileges in schema public grant usage, select on sequences to ${role}`, + ]) await client.query(statement); + console.log(`[ensure-roles] ${user} can read and write ${database} rows, without DDL`); +} + +/** + * Makes the Keycloak login own its database and every object in it, including + * tables an earlier deploy created as the master user. Objects are handed over + * one by one: REASSIGN OWNED would also move databases the master owns. + */ +async function ensureKeycloakOwner(client: pg.Client, user: string, database: string): Promise { + const role = client.escapeIdentifier(user); + const db = client.escapeIdentifier(database); + // A non-superuser master (RDS) may only transfer ownership to roles it belongs to. + await client.query(`grant ${role} to current_user`).catch(() => {}); + await client.query(`alter database ${db} owner to ${role}`); + await client.query(`revoke connect on database ${db} from public`); + await client.query(`grant connect on database ${db} to ${role}`); + await client.query( + `do $$ + declare item record; + begin + for item in + select 'table' as kind, format('%I.%I', schemaname, tablename) as name from pg_tables + where schemaname = 'public' and tableowner = current_user + union all + select 'view', format('%I.%I', schemaname, viewname) from pg_views + where schemaname = 'public' and viewowner = current_user + union all + select 'sequence', format('%I.%I', schemaname, sequencename) from pg_sequences + where schemaname = 'public' and sequenceowner = current_user + loop + begin + execute format('alter %s %s owner to %s', item.kind, item.name, ${client.escapeLiteral(role)}); + exception when others then + -- Sequences owned by a column move with their table. + null; + end; + end loop; + end $$` + ); + console.log(`[ensure-roles] ${user} owns database ${database}`); +} + +function pair(user: string | undefined, password: string | undefined, label: string) { + if (!user && !password) return undefined; + if (!user || !password) throw new Error(`${label} user and password must be set together`); + return { user, password }; +} + +if (isMainModule(import.meta.url)) { + const databaseUrl = process.env.DATABASE_URL; + if (!databaseUrl) { + console.error("[ensure-roles] DATABASE_URL is not set"); + process.exit(1); + } + const runtime = pair(process.env.DATABASE_RUNTIME_USER, process.env.DATABASE_RUNTIME_PASSWORD, "DATABASE_RUNTIME"); + const keycloakLogin = pair(process.env.KEYCLOAK_DB_USER, process.env.KEYCLOAK_DB_PASSWORD, "KEYCLOAK_DB"); + const keycloak = keycloakLogin && { ...keycloakLogin, database: process.env.KEYCLOAK_DB_NAME || "keycloak" }; + if (!runtime && !keycloak) console.log("[ensure-roles] no logins configured; nothing to do"); + ensureRoles(databaseUrl, { runtime, keycloak }) + .then(() => process.exit(0)) + .catch((err) => { + console.error("[ensure-roles] failed:", err.message); + process.exit(1); + }); +} diff --git a/tests/integration/database-roles.test.ts b/tests/integration/database-roles.test.ts new file mode 100644 index 0000000..3afad1d --- /dev/null +++ b/tests/integration/database-roles.test.ts @@ -0,0 +1,100 @@ +/** + * The least-privilege logins against a real Postgres. Creates its own roles and + * Keycloak-style database, removes them afterwards, and restores the default + * CONNECT grant it revokes on the local application database. + * Skipped when DATABASE_URL is unset. + */ +import { randomBytes } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import pg from "pg"; +import { migrate } from "../../packages/db/src/migrate"; +import { ensureRoles } from "../../packages/db/src/ensure-roles"; + +const databaseUrl = process.env.DATABASE_URL; +const describeDb = databaseUrl ? describe : describe.skip; + +const suffix = randomBytes(3).toString("hex"); +const runtime = { user: `test_runtime_${suffix}`, password: randomBytes(12).toString("hex") }; +const keycloak = { user: `test_kc_${suffix}`, password: randomBytes(12).toString("hex"), database: `test_kc_db_${suffix}` }; + +function urlFor(user?: { user: string; password: string }, database?: string): string { + const url = new URL(databaseUrl!); + if (user) { + url.username = user.user; + url.password = user.password; + } + if (database) url.pathname = `/${database}`; + return url.toString(); +} + +async function as(connection: string, work: (client: pg.Client) => Promise): Promise { + const client = new pg.Client({ connectionString: connection }); + await client.connect(); + try { + return await work(client); + } finally { + await client.end(); + } +} + +describeDb("least-privilege database logins", () => { + const appDatabase = () => new URL(databaseUrl!).pathname.slice(1); + + beforeAll(async () => { + await migrate(); + // A Keycloak database that an earlier deploy filled as the master user. + await as(urlFor(undefined, "postgres"), (c) => c.query(`create database ${keycloak.database}`)); + await as(urlFor(undefined, keycloak.database), (c) => c.query(`create table realm (id serial primary key, name text)`)); + await ensureRoles(databaseUrl!, { runtime, keycloak }); + }); + + afterAll(async () => { + await as(urlFor(undefined, "postgres"), (c) => c.query(`drop database if exists ${keycloak.database}`)); + await as(databaseUrl!, async (c) => { + await c.query(`grant connect on database ${c.escapeIdentifier(appDatabase())} to public`); + await c.query(`drop owned by ${runtime.user}, ${keycloak.user}`); + await c.query(`drop role if exists ${runtime.user}`); + await c.query(`drop role if exists ${keycloak.user}`); + }); + }); + + it("lets the runtime login read and write application rows", async () => { + await as(urlFor(runtime), async (c) => { + const key = `test:roles:${suffix}`; + await c.query(`insert into rate_limit_buckets (bucket_key, window_started_at, count) values ($1, now(), 1)`, [key]); + expect((await c.query(`select count(*)::int as n from rate_limit_buckets where bucket_key = $1`, [key])).rows[0].n).toBe(1); + await c.query(`delete from rate_limit_buckets where bucket_key = $1`, [key]); + }); + }); + + it("refuses the runtime login any schema change", async () => { + await as(urlFor(runtime), async (c) => { + await expect(c.query(`create table test_forbidden (id int)`)).rejects.toThrow(/permission denied/); + await expect(c.query(`drop table rate_limit_buckets`)).rejects.toThrow(/must be owner|permission denied/); + }); + }); + + it("keeps the runtime login out of the Keycloak database", async () => { + await expect(as(urlFor(runtime, keycloak.database), (c) => c.query("select 1"))).rejects.toThrow(/permission denied/); + }); + + it("makes the Keycloak login own its database, including older tables", async () => { + await as(urlFor(keycloak, keycloak.database), async (c) => { + const owner = await c.query(`select tableowner from pg_tables where tablename = 'realm'`); + expect(owner.rows[0].tableowner).toBe(keycloak.user); + await c.query(`alter table realm add column if not exists display_name text`); + await c.query(`insert into realm (name) values ('match-maker')`); + }); + }); + + it("keeps the Keycloak login out of the application database", async () => { + await expect(as(urlFor(keycloak), (c) => c.query("select 1"))).rejects.toThrow(/permission denied/); + }); + + it("is safe to run again and updates passwords", async () => { + const rotated = { ...runtime, password: randomBytes(12).toString("hex") }; + await ensureRoles(databaseUrl!, { runtime: rotated }); + await expect(as(urlFor(rotated), (c) => c.query("select 1 from events limit 1"))).resolves.toBeDefined(); + await expect(as(urlFor(runtime), (c) => c.query("select 1"))).rejects.toThrow(/password/); + }); +}); diff --git a/tests/unit/env.test.ts b/tests/unit/env.test.ts index d5f2b85..29a12fb 100644 --- a/tests/unit/env.test.ts +++ b/tests/unit/env.test.ts @@ -47,7 +47,7 @@ describe("checkEnv", () => { expect(problems).toEqual([ 'APP_BASE_URL must be an http(s) URL, got "localhost:3000".', 'DATABASE_POOL_MAX must be a positive integer, got "ten".', - 'DATABASE_SSL must be one of disable, require, got "on".', + 'DATABASE_SSL must be one of disable, require, verify, got "on".', ]); }); diff --git a/tests/unit/production-transport.test.ts b/tests/unit/production-transport.test.ts new file mode 100644 index 0000000..2f25bd7 --- /dev/null +++ b/tests/unit/production-transport.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { checkEnv } from "@/src/lib/env"; +import { isLocalDatabase, resolveSsl } from "../../packages/db/src/client"; + +const REMOTE = "postgres://app:pw@db.abc.ap-south-1.rds.amazonaws.com:5432/match_maker"; +const LOCAL = "postgres://matchmaker:matchmaker@postgres:5432/matchmaker"; +const CA = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----"; + +describe("resolveSsl", () => { + it("leaves local databases unencrypted unless asked", () => { + expect(isLocalDatabase(LOCAL)).toBe(true); + expect(resolveSsl(LOCAL, {})).toBe(false); + expect(resolveSsl(LOCAL, { DATABASE_SSL: "require" })).toEqual({ rejectUnauthorized: false }); + }); + + it("verifies the certificate in verify mode, from inline PEM or a file", () => { + expect(resolveSsl(REMOTE, { DATABASE_SSL: "verify", DATABASE_CA_CERT: CA })).toEqual({ ca: CA, rejectUnauthorized: true }); + const file = join(mkdtempSync(join(tmpdir(), "ca-")), "bundle.pem"); + writeFileSync(file, CA); + expect(resolveSsl(REMOTE, { DATABASE_SSL: "verify", DATABASE_CA_CERT_FILE: file })).toEqual({ ca: CA, rejectUnauthorized: true }); + }); + + it("refuses verify mode without a CA instead of silently skipping the check", () => { + expect(() => resolveSsl(REMOTE, { DATABASE_SSL: "verify" })).toThrow(/DATABASE_CA_CERT/); + }); + + it("does not treat a hostname merely containing 'postgres' as local", () => { + expect(isLocalDatabase("postgres://u:p@postgres.example.com/db")).toBe(false); + }); +}); + +describe("production startup checks", () => { + const web = { + NODE_ENV: "production", + DATABASE_URL: REMOTE, + DATABASE_SSL: "verify", + DATABASE_CA_CERT_FILE: "/etc/ssl/certs/rds-global-bundle.pem", + SESSION_SECRET: "x".repeat(32), + KEYCLOAK_ISSUER: "https://bridge.example.com/realms/match-maker", + KEYCLOAK_CLIENT_ID: "match-maker-web", + KEYCLOAK_CLIENT_SECRET: "secret", + RESEND_API_KEY: "re_key", + EMAIL_FROM: "Bridge ", + APP_BASE_URL: "https://bridge.example.com", + }; + + it("accepts verified TLS and an https base URL", () => { + expect(checkEnv("web", web)).toEqual([]); + }); + + it.each([ + [{ DATABASE_SSL: "require" }, /DATABASE_SSL must be verify/], + [{ DATABASE_SSL: undefined }, /DATABASE_SSL must be verify/], + [{ DATABASE_CA_CERT_FILE: undefined }, /needs DATABASE_CA_CERT/], + [{ APP_BASE_URL: "http://bridge.example.com" }, /must use https/], + [{ APP_BASE_URL: undefined }, /APP_BASE_URL is required/], + ])("refuses %o", (change, message) => { + expect(checkEnv("web", { ...web, ...change }).join("\n")).toMatch(message); + }); + + it("applies the database rule to the worker too", () => { + expect(checkEnv("worker", { NODE_ENV: "production", DATABASE_URL: REMOTE, DATABASE_SSL: "require" }).join("\n")) + .toMatch(/DATABASE_SSL must be verify/); + }); + + it("still lets the local docker-compose stack run as production", () => { + const local = { ...web, DATABASE_URL: LOCAL, DATABASE_SSL: "disable", APP_BASE_URL: "http://localhost:3000" }; + expect(checkEnv("web", local)).toEqual([]); + }); +}); From b4d1327c750febe902e799c5ede16378d2fc804b Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:38:50 +0530 Subject: [PATCH 09/48] Require HTTPS, restrict Keycloak admin, separate DB logins (R11 part 2) - An environment = "prod" plan fails unless domain_name and acm_certificate_arn are set, so production never serves over HTTP - /admin on Keycloak is no longer routed publicly: a 404 rule blocks it at the load balancer, with an allow rule only for var.keycloak_admin_cidrs (empty by default). The app's admin API calls already go over Cloud Map inside the VPC - Web and worker connect as app_runtime (row access only), Keycloak as its own keycloak login over JDBC sslmode=verify-full, and only the migration task holds the master login; it runs ensure-roles.ts after migrations to create/rotate the other two - Secrets split into app (web/worker), identity (Keycloak) and migrate (master login and the passwords it sets) - Every task uses DATABASE_SSL=verify with the RDS bundle in the image - deploy.yml pins images onto the family's newest task definition revision instead of the one the service is running, so environment and secret changes applied by Terraform (these, and R09's TRUSTED_PROXY_HOPS) actually reach the services --- .env.example | 11 +++++ .github/workflows/deploy.yml | 17 ++++--- infra/terraform/alb.tf | 61 ++++++++++++++++++++++-- infra/terraform/database.tf | 34 ++++++++++++- infra/terraform/ecs.tf | 40 +++++++++------- infra/terraform/iam.tf | 8 +++- infra/terraform/outputs.tf | 7 +-- infra/terraform/secrets.tf | 56 +++++++++++++++++----- infra/terraform/terraform.tfvars.example | 9 +++- infra/terraform/variables.tf | 8 +++- 10 files changed, 205 insertions(+), 46 deletions(-) diff --git a/.env.example b/.env.example index 5e1a5d0..a64d1d3 100644 --- a/.env.example +++ b/.env.example @@ -22,7 +22,18 @@ POSTGRES_PORT=5432 # Used by scripts run on the HOST (migrate/seed/import). # Inside docker-compose the host is `postgres`, not `localhost`. DATABASE_URL=postgres://matchmaker:matchmaker@localhost:5432/matchmaker +# disable (local, no TLS) | require (encrypted, unverified) | verify (encrypted, +# certificate checked against DATABASE_CA_CERT or DATABASE_CA_CERT_FILE). +# Production refuses anything but verify for a remote database. DATABASE_SSL=disable +# DATABASE_CA_CERT_FILE=/etc/ssl/certs/rds-global-bundle.pem + +# Deployed only: the migration task creates these least-privilege logins +# (packages/db/src/ensure-roles.ts); web and worker then use the runtime one. +# DATABASE_RUNTIME_USER=app_runtime +# DATABASE_RUNTIME_PASSWORD= +# KEYCLOAK_DB_USER=keycloak +# KEYCLOAK_DB_PASSWORD= # ── Keycloak ────────────────────────────────────────────────── KEYCLOAK_PORT=8080 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1a48e80..25ad537 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -252,8 +252,11 @@ jobs: set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + # Start from the family's newest revision, not the one the service is + # running, so settings and secrets changed by Terraform ship too. + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > taskdef.json # Production login must send real e-mail: never ship the dev fallback, @@ -296,8 +299,9 @@ jobs: set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WORKER_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WORKER_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > worker-taskdef.json jq --arg IMAGE "$REGISTRY/match-maker-prod/worker:$TAG" ' @@ -327,8 +331,9 @@ jobs: run: | set -euo pipefail REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" - aws ecs describe-task-definition \ - --task-definition "$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_KEYCLOAK_SERVICE" --query 'services[0].taskDefinition' --output text)" \ + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_KEYCLOAK_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ --query 'taskDefinition' > keycloak-taskdef.json jq --arg IMAGE "$REGISTRY/match-maker-prod/keycloak:$TAG" ' .containerDefinitions[0].image = $IMAGE diff --git a/infra/terraform/alb.tf b/infra/terraform/alb.tf index 1e41e9c..c363314 100644 --- a/infra/terraform/alb.tf +++ b/infra/terraform/alb.tf @@ -104,6 +104,14 @@ resource "aws_lb_listener" "http" { port = 80 protocol = "HTTP" + lifecycle { + # Production must never serve logins and session cookies over plain HTTP. + precondition { + condition = var.environment != "prod" || (local.https_enabled && var.domain_name != "") + error_message = "environment = \"prod\" requires domain_name and acm_certificate_arn so the app is served over HTTPS." + } + } + dynamic "default_action" { for_each = local.https_enabled ? [1] : [] content { @@ -166,9 +174,56 @@ resource "aws_lb_listener_rule" "keycloak_host" { } } +# The admin console is not public: only var.keycloak_admin_cidrs reach it, and +# everyone else gets a 404 before the request is routed to Keycloak. The app's +# own admin API calls go over Cloud Map inside the VPC, not through the ALB. +resource "aws_lb_listener_rule" "keycloak_admin_allow" { + count = length(var.keycloak_admin_cidrs) > 0 ? 1 : 0 + + listener_arn = local.active_listener_arn + priority = 5 + + action { + type = "forward" + target_group_arn = aws_lb_target_group.keycloak.arn + } + + condition { + path_pattern { + values = ["/admin", "/admin/*"] + } + } + + condition { + source_ip { + values = var.keycloak_admin_cidrs + } + } +} + +resource "aws_lb_listener_rule" "keycloak_admin_deny" { + listener_arn = local.active_listener_arn + priority = 6 + + action { + type = "fixed-response" + fixed_response { + content_type = "text/plain" + message_body = "Not found" + status_code = "404" + } + } + + condition { + path_pattern { + values = ["/admin", "/admin/*"] + } + } +} + # Fallback: share the app hostname and split on the paths Keycloak owns. -# /auth/callback belongs to the APP, and is not listed here — Keycloak's own -# paths are /realms/*, /resources/* and /admin/*. +# /auth/callback belongs to the APP, and is not listed here. /admin/* is +# handled by the two rules above. resource "aws_lb_listener_rule" "keycloak_path" { count = local.keycloak_has_own_domain ? 0 : 1 @@ -182,7 +237,7 @@ resource "aws_lb_listener_rule" "keycloak_path" { condition { path_pattern { - values = ["/realms/*", "/resources/*", "/admin/*", "/js/*"] + values = ["/realms/*", "/resources/*", "/js/*"] } } } diff --git a/infra/terraform/database.tf b/infra/terraform/database.tf index a25b411..1d9f46c 100644 --- a/infra/terraform/database.tf +++ b/infra/terraform/database.tf @@ -19,6 +19,18 @@ resource "random_password" "db" { override_special = "!#$%&*()-_=+[]{}<>:?" } +# Least-privilege logins, created by the migration task (ensure-roles.ts). The +# master login above is used only to run migrations. +resource "random_password" "db_runtime" { + length = 40 + special = false +} + +resource "random_password" "db_keycloak" { + length = 40 + special = false +} + resource "aws_db_parameter_group" "main" { name = "${local.name}-pg16" family = "postgres16" @@ -86,7 +98,11 @@ resource "aws_db_instance" "main" { locals { db_password_encoded = urlencode(random_password.db.result) - app_database_url = format( + db_runtime_user = "app_runtime" + db_keycloak_user = "keycloak" + + # Migrations only. + admin_database_url = format( "postgres://%s:%s@%s:%s/%s", aws_db_instance.main.username, local.db_password_encoded, @@ -95,9 +111,23 @@ locals { aws_db_instance.main.db_name, ) + # Web and worker: row access only. + app_database_url = format( + "postgres://%s:%s@%s:%s/%s", + local.db_runtime_user, + random_password.db_runtime.result, + aws_db_instance.main.address, + aws_db_instance.main.port, + aws_db_instance.main.db_name, + ) + + # verify-full checks the RDS certificate with the bundle baked into the image. keycloak_jdbc_url = format( - "jdbc:postgresql://%s:%s/keycloak", + "jdbc:postgresql://%s:%s/keycloak?sslmode=verify-full&sslrootcert=/opt/keycloak/conf/rds-global-bundle.pem", aws_db_instance.main.address, aws_db_instance.main.port, ) + + # Path of the RDS CA bundle inside the web, worker and migrate images. + database_ca_file = "/etc/ssl/certs/rds-global-bundle.pem" } diff --git a/infra/terraform/ecs.tf b/infra/terraform/ecs.tf index e93cd80..d3df2a1 100644 --- a/infra/terraform/ecs.tf +++ b/infra/terraform/ecs.tf @@ -221,10 +221,10 @@ resource "aws_ecs_task_definition" "web" { { name = "KEYCLOAK_CLIENT_ID", value = var.keycloak_client_id }, { name = "KEYCLOAK_GOOGLE_IDP_ALIAS", value = "google" }, { name = "EMAIL_FROM", value = var.email_from }, - # RDS enforces TLS (rds.force_ssl), and the AWS CA is not in Node's - # default trust store, so verification is relaxed for this hop inside - # the VPC. Set DATABASE_CA_CERT to the RDS bundle to tighten it. - { name = "DATABASE_SSL", value = "require" }, + # RDS enforces TLS (rds.force_ssl); the certificate is checked against + # the RDS CA bundle baked into the image. + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, ] secrets = [ @@ -323,7 +323,7 @@ resource "aws_ecs_task_definition" "keycloak" { environment = [ { name = "KC_DB", value = "postgres" }, { name = "KC_DB_URL", value = local.keycloak_jdbc_url }, - { name = "KC_DB_USERNAME", value = aws_db_instance.main.username }, + { name = "KC_DB_USERNAME", value = local.db_keycloak_user }, # Tokens must be issued with the hostname the browser uses, or `iss` # will not match what the app verifies. { name = "KC_HOSTNAME", value = local.keycloak_public_origin }, @@ -341,12 +341,12 @@ resource "aws_ecs_task_definition" "keycloak" { ] secrets = [ - { name = "KC_DB_PASSWORD", valueFrom = local.secret_ref.KEYCLOAK_DB_PASSWORD }, - { name = "KC_BOOTSTRAP_ADMIN_PASSWORD", valueFrom = local.secret_ref.KEYCLOAK_ADMIN_PASSWORD }, + { name = "KC_DB_PASSWORD", valueFrom = local.identity_secret_ref.KEYCLOAK_DB_PASSWORD }, + { name = "KC_BOOTSTRAP_ADMIN_PASSWORD", valueFrom = local.identity_secret_ref.KEYCLOAK_ADMIN_PASSWORD }, # Substituted into realm-export.json during import. - { name = "KEYCLOAK_CLIENT_SECRET", valueFrom = local.secret_ref.KEYCLOAK_CLIENT_SECRET }, - { name = "GOOGLE_CLIENT_ID", valueFrom = local.secret_ref.GOOGLE_CLIENT_ID }, - { name = "GOOGLE_CLIENT_SECRET", valueFrom = local.secret_ref.GOOGLE_CLIENT_SECRET }, + { name = "KEYCLOAK_CLIENT_SECRET", valueFrom = local.identity_secret_ref.KEYCLOAK_CLIENT_SECRET }, + { name = "GOOGLE_CLIENT_ID", valueFrom = local.identity_secret_ref.GOOGLE_CLIENT_ID }, + { name = "GOOGLE_CLIENT_SECRET", valueFrom = local.identity_secret_ref.GOOGLE_CLIENT_SECRET }, ] logConfiguration = { @@ -420,23 +420,30 @@ resource "aws_ecs_task_definition" "migrate" { image = "${aws_ecr_repository.migrate.repository_url}:latest" essential = true - # Creates Keycloak's database on first run, then applies app migrations. - # Both steps are idempotent, so re-running a deploy is safe. + # Creates Keycloak's database on first run, applies app migrations, then + # creates/updates the runtime and Keycloak logins (after migrations, so + # grants cover every table). All steps are idempotent. command = [ "sh", "-c", - "npx tsx packages/db/src/ensure-database.ts keycloak && npx tsx packages/db/src/migrate.ts" + "npx tsx packages/db/src/ensure-database.ts keycloak && npx tsx packages/db/src/migrate.ts && npx tsx packages/db/src/ensure-roles.ts" ] environment = [ { name = "NODE_ENV", value = "production" }, - { name = "DATABASE_SSL", value = "require" }, + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, + { name = "DATABASE_RUNTIME_USER", value = local.db_runtime_user }, + { name = "KEYCLOAK_DB_USER", value = local.db_keycloak_user }, + { name = "KEYCLOAK_DB_NAME", value = "keycloak" }, # Seeding is for local development only; production data comes from the # Excel importer. { name = "SEED_ON_MIGRATE", value = "false" }, ] secrets = [ - { name = "DATABASE_URL", valueFrom = local.secret_ref.DATABASE_URL }, + { name = "DATABASE_URL", valueFrom = local.migrate_secret_ref.DATABASE_ADMIN_URL }, + { name = "DATABASE_RUNTIME_PASSWORD", valueFrom = local.migrate_secret_ref.DATABASE_RUNTIME_PASSWORD }, + { name = "KEYCLOAK_DB_PASSWORD", valueFrom = local.migrate_secret_ref.KEYCLOAK_DB_PASSWORD }, ] logConfiguration = { @@ -468,7 +475,8 @@ resource "aws_ecs_task_definition" "worker" { essential = true environment = [ { name = "NODE_ENV", value = "production" }, - { name = "DATABASE_SSL", value = "require" }, + { name = "DATABASE_SSL", value = "verify" }, + { name = "DATABASE_CA_CERT_FILE", value = local.database_ca_file }, { name = "GEMINI_LLM_MODEL", value = "gemini-3.8-flash" }, { name = "EMBEDDING_PROVIDER", value = "gemini" }, ] diff --git a/infra/terraform/iam.tf b/infra/terraform/iam.tf index 18a0ef1..3061fd9 100644 --- a/infra/terraform/iam.tf +++ b/infra/terraform/iam.tf @@ -37,8 +37,12 @@ resource "aws_iam_role_policy_attachment" "ecs_execution_managed" { # read access — not the task role. data "aws_iam_policy_document" "secrets_read" { statement { - actions = ["secretsmanager:GetSecretValue"] - resources = [aws_secretsmanager_secret.app.arn] + actions = ["secretsmanager:GetSecretValue"] + resources = [ + aws_secretsmanager_secret.app.arn, + aws_secretsmanager_secret.identity.arn, + aws_secretsmanager_secret.migrate.arn, + ] } } diff --git a/infra/terraform/outputs.tf b/infra/terraform/outputs.tf index cb2f601..f3c3043 100644 --- a/infra/terraform/outputs.tf +++ b/infra/terraform/outputs.tf @@ -94,7 +94,7 @@ output "secrets_manager_secret_name" { } output "keycloak_admin_console_url" { - description = "Keycloak admin console. The bootstrap password is in Secrets Manager." + description = "Keycloak admin console, reachable only from var.keycloak_admin_cidrs. The bootstrap password is in the identity secret." value = "${local.keycloak_public_origin}/admin" } @@ -103,8 +103,9 @@ output "post_apply_checklist" { value = <<-EOT 1. Create a Google OAuth client and set its authorised redirect URI to: ${local.keycloak_public_origin}/realms/${var.keycloak_realm}/broker/google/endpoint - Then put the id/secret into the ${aws_secretsmanager_secret.app.name} secret - (GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET) and redeploy Keycloak. + Then put the id/secret into the ${aws_secretsmanager_secret.identity.name} secret + (GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET), and GOOGLE_CLIENT_ID into + ${aws_secretsmanager_secret.app.name} too, then redeploy web and Keycloak. 2. Verify your sending domain in Resend and set RESEND_API_KEY in the same secret. 3. Set GEMINI_API_KEY in the same secret. 4. Import the attendee roster: npm run db:import -- attendees.xlsx diff --git a/infra/terraform/secrets.tf b/infra/terraform/secrets.tf index ecb51fa..f3b1e51 100644 --- a/infra/terraform/secrets.tf +++ b/infra/terraform/secrets.tf @@ -22,25 +22,40 @@ resource "random_password" "keycloak_admin_password" { override_special = "!#$%&*()-_=+" } +# Three secrets, so each task reads only its own credentials: +# app web and worker (runtime database login, no master password) +# identity Keycloak (its own database login and admin bootstrap) +# migrate the migration task (master login plus the passwords it sets) locals { secret_values = { DATABASE_URL = local.app_database_url SESSION_SECRET = random_password.session_secret.result KEYCLOAK_CLIENT_SECRET = random_password.keycloak_client_secret.result - KEYCLOAK_ADMIN_PASSWORD = random_password.keycloak_admin_password.result - KEYCLOAK_DB_PASSWORD = random_password.db.result GEMINI_API_KEY = var.gemini_api_key UPSTASH_REDIS_REST_URL = var.upstash_redis_rest_url UPSTASH_REDIS_REST_TOKEN = var.upstash_redis_rest_token RESEND_API_KEY = var.resend_api_key GOOGLE_CLIENT_ID = var.google_client_id - GOOGLE_CLIENT_SECRET = var.google_client_secret + } + + identity_secret_values = { + KEYCLOAK_ADMIN_PASSWORD = random_password.keycloak_admin_password.result + KEYCLOAK_DB_PASSWORD = random_password.db_keycloak.result + KEYCLOAK_CLIENT_SECRET = random_password.keycloak_client_secret.result + GOOGLE_CLIENT_ID = var.google_client_id + GOOGLE_CLIENT_SECRET = var.google_client_secret + } + + migrate_secret_values = { + DATABASE_ADMIN_URL = local.admin_database_url + DATABASE_RUNTIME_PASSWORD = random_password.db_runtime.result + KEYCLOAK_DB_PASSWORD = random_password.db_keycloak.result } } resource "aws_secretsmanager_secret" "app" { name = "${local.name}/app" - description = "Runtime secrets for the Mr. Bridge web and Keycloak services." + description = "Runtime secrets for the Mr. Bridge web and worker services." # Zero means immediate deletion, which keeps `terraform destroy` from leaving # a name reserved for 30 days and blocking a re-apply. @@ -52,13 +67,32 @@ resource "aws_secretsmanager_secret_version" "app" { secret_string = jsonencode(local.secret_values) } -# Individual ARNs, referenced one-by-one from the task definitions so each +resource "aws_secretsmanager_secret" "identity" { + name = "${local.name}/identity" + description = "Keycloak's database login, admin bootstrap and identity-provider secrets." + recovery_window_in_days = 0 +} + +resource "aws_secretsmanager_secret_version" "identity" { + secret_id = aws_secretsmanager_secret.identity.id + secret_string = jsonencode(local.identity_secret_values) +} + +resource "aws_secretsmanager_secret" "migrate" { + name = "${local.name}/migrate" + description = "Database master login, used only by the migration task." + recovery_window_in_days = 0 +} + +resource "aws_secretsmanager_secret_version" "migrate" { + secret_id = aws_secretsmanager_secret.migrate.id + secret_string = jsonencode(local.migrate_secret_values) +} + +# Individual keys, referenced one by one from the task definitions so each # container receives only the values it actually needs. locals { - secret_arn = aws_secretsmanager_secret.app.arn - - secret_ref = { - for key in keys(local.secret_values) : - key => "${local.secret_arn}:${key}::" - } + secret_ref = { for key in keys(local.secret_values) : key => "${aws_secretsmanager_secret.app.arn}:${key}::" } + identity_secret_ref = { for key in keys(local.identity_secret_values) : key => "${aws_secretsmanager_secret.identity.arn}:${key}::" } + migrate_secret_ref = { for key in keys(local.migrate_secret_values) : key => "${aws_secretsmanager_secret.migrate.arn}:${key}::" } } diff --git a/infra/terraform/terraform.tfvars.example b/infra/terraform/terraform.tfvars.example index 5137123..c6385b3 100644 --- a/infra/terraform/terraform.tfvars.example +++ b/infra/terraform/terraform.tfvars.example @@ -6,13 +6,18 @@ environment = "prod" default_event_slug = "demo" # ── DNS / TLS ───────────────────────────────────────────────── -# Leave all three empty for a first apply; the stack comes up on the ALB's own -# DNS name over HTTP, and you can add the domain later. +# Required when environment = "prod": the plan refuses to serve production +# over plain HTTP. For an HTTP-only evaluation stack, set environment = "staging" +# and leave these empty. domain_name = "" keycloak_domain_name = "" acm_certificate_arn = "" route53_zone_id = "" +# CIDR blocks allowed to open the Keycloak admin console through the load +# balancer, e.g. ["203.0.113.10/32"]. Empty keeps it off the internet. +keycloak_admin_cidrs = [] + # ── CI/CD ───────────────────────────────────────────────────── # Enables the GitHub OIDC deploy role. Format: "owner/repo". github_repository = "LucknowAI/Bridge" diff --git a/infra/terraform/variables.tf b/infra/terraform/variables.tf index a58730a..028ca0f 100644 --- a/infra/terraform/variables.tf +++ b/infra/terraform/variables.tf @@ -54,7 +54,7 @@ variable "enable_nat_gateway" { # ── DNS / TLS ───────────────────────────────────────────────── variable "domain_name" { - description = "Public hostname for the app, e.g. bridge.example.com. Leave empty to serve on the ALB's own DNS name over HTTP only." + description = "Public hostname for the app, e.g. bridge.example.com. Required (with acm_certificate_arn) when environment is prod; leave empty only for a non-prod evaluation stack served over HTTP." type = string default = "" } @@ -71,6 +71,12 @@ variable "acm_certificate_arn" { default = "" } +variable "keycloak_admin_cidrs" { + description = "IPv4 CIDR blocks allowed to reach the Keycloak admin console (/admin) through the load balancer. Empty keeps it unreachable from the internet; use ECS Exec port forwarding instead." + type = list(string) + default = [] +} + variable "route53_zone_id" { description = "Route53 hosted zone to create records in. Leave empty to manage DNS elsewhere." type = string From aa5e020831712a9ba0f3f8eb9f8ca4f79254916e Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:42:58 +0530 Subject: [PATCH 10/48] Track invitations, claims and revoked access per event (R12 part 1) - Migration 0006: event_participants gains invited_at, invite_count, invite_error, claimed_at and revoked_at; existing profiles count as claimed - Revoked attendees lose event sign-in (isParticipant), page and action access (hasEventAccess, so existing sessions too), matching (participantIds) and every results path (ELIGIBLE_CANDIDATE). Re-importing the roster does not silently restore them - The first signed-in visit to the event records the claim time - sendInvitations e-mails everyone never invited, or one attendee as a resend (at most every 10 minutes, never after claiming or removal); each attempt is recorded, failures with their reason - setAttendeeAccess removes or restores access - Invitation e-mail template and NotificationPort.invitation - Analytics count invited, claimed and removed attendees separately --- .../src/application/ports/event-repository.ts | 10 ++- .../web/src/application/ports/notification.ts | 1 + .../use-cases/manage-invitations.ts | 56 ++++++++++++ apps/web/src/domain/participant/invitation.ts | 32 +++++++ .../notifications/realtime.notifier.ts | 6 +- .../src/infrastructure/postgres/event.repo.ts | 28 +++++- .../postgres/participant.repo.ts | 6 +- apps/web/src/lib/auth.ts | 1 + packages/db/migrations/0006_invitations.sql | 18 ++++ packages/db/src/repositories/events.ts | 76 +++++++++++++++- packages/email/src/index.ts | 1 + .../email/src/templates/invitation-email.ts | 34 +++++++ tests/integration/invitations.test.ts | 90 +++++++++++++++++++ tests/unit/invitations.test.ts | 84 +++++++++++++++++ 14 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/application/use-cases/manage-invitations.ts create mode 100644 apps/web/src/domain/participant/invitation.ts create mode 100644 packages/db/migrations/0006_invitations.sql create mode 100644 packages/email/src/templates/invitation-email.ts create mode 100644 tests/integration/invitations.test.ts create mode 100644 tests/unit/invitations.test.ts diff --git a/apps/web/src/application/ports/event-repository.ts b/apps/web/src/application/ports/event-repository.ts index c902136..e13dfb4 100644 --- a/apps/web/src/application/ports/event-repository.ts +++ b/apps/web/src/application/ports/event-repository.ts @@ -38,5 +38,13 @@ export interface EventRepository { attachRoster(eventId: string, attendeeIds: string[]): Promise; participantIds(eventId: string): Promise; importRoster(eventId: string, records: RosterAttendeeInput[]): Promise<{ upserted: number; attached: number }>; - analytics(eventId: string): Promise<{ roster: number; profiles: number; matches: number; pendingIntros: number; acceptedIntros: number }>; + analytics(eventId: string): Promise<{ + roster: number; invited: number; claimed: number; profiles: number; removed: number; + matches: number; pendingIntros: number; acceptedIntros: number; + }>; + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number): Promise>; + recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise; + markClaimed(eventId: string, attendeeId: string): Promise; + setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise; + rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null>; } diff --git a/apps/web/src/application/ports/notification.ts b/apps/web/src/application/ports/notification.ts index bd84477..7db58ee 100644 --- a/apps/web/src/application/ports/notification.ts +++ b/apps/web/src/application/ports/notification.ts @@ -1,4 +1,5 @@ export interface NotificationPort { + invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise; introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise; introResponded(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; accepted: boolean }): Promise; } diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts new file mode 100644 index 0000000..56b67c9 --- /dev/null +++ b/apps/web/src/application/use-cases/manage-invitations.ts @@ -0,0 +1,56 @@ +import { RESEND_AFTER_MINUTES } from "../../domain/participant/invitation"; +import type { EventRepository } from "../ports/event-repository"; +import type { NotificationPort } from "../ports/notification"; + +export interface InvitationResult { + sent: number; + failed: number; +} + +/** + * E-mails invitations: to one attendee (a resend), or to everyone on the + * roster never invited. Each attempt is recorded, so a failed delivery shows + * up on the roster instead of disappearing. + */ +export async function sendInvitations( + input: { eventId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string }, + dependencies: { events: EventRepository; notifications: NotificationPort } +): Promise { + const targets = await dependencies.events.invitationTargets(input.eventId, input.attendeeId ?? null, RESEND_AFTER_MINUTES); + if (input.attendeeId && !targets.length) { + throw new Error(`This attendee cannot be invited right now: they may have signed in already, been removed, or been invited in the last ${RESEND_AFTER_MINUTES} minutes.`); + } + const result: InvitationResult = { sent: 0, failed: 0 }; + for (const target of targets) { + try { + await dependencies.notifications.invitation({ + email: target.email, + name: target.name, + eventName: input.eventName, + organizationName: input.organizationName, + eventUrl: input.eventUrl, + }); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, null); + result.sent += 1; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, message.slice(0, 300)); + result.failed += 1; + } + } + return result; +} + +/** + * Removes or restores one attendee's access. Removal takes effect on their + * next request (existing sessions included) and drops them from matching and + * everyone's results; their history stays for the organizer. + */ +export async function setAttendeeAccess( + input: { eventId: string; attendeeId: string; revoked: boolean }, + dependencies: { events: EventRepository } +): Promise { + if (!(await dependencies.events.setRevoked(input.eventId, input.attendeeId, input.revoked))) { + throw new Error("This attendee is not on the event roster"); + } +} diff --git a/apps/web/src/domain/participant/invitation.ts b/apps/web/src/domain/participant/invitation.ts new file mode 100644 index 0000000..93509cc --- /dev/null +++ b/apps/web/src/domain/participant/invitation.ts @@ -0,0 +1,32 @@ +/** + * Where an invited attendee stands for one event, as the organizer sees it. + * Removed overrides everything; otherwise the furthest step reached wins. + */ +export type InvitationState = "removed" | "complete" | "claimed" | "invited" | "failed" | "not_invited"; + +/** A resend for the same attendee is refused until this much time has passed. */ +export const RESEND_AFTER_MINUTES = 10; + +export interface InvitationFacts { + revokedAt: Date | null; + profileUpdatedAt: Date | null; + claimedAt: Date | null; + invitedAt: Date | null; + inviteError: string | null; +} + +export function invitationState(facts: InvitationFacts): InvitationState { + if (facts.revokedAt) return "removed"; + if (facts.profileUpdatedAt) return "complete"; + if (facts.claimedAt) return "claimed"; + if (facts.inviteError) return "failed"; + if (facts.invitedAt) return "invited"; + return "not_invited"; +} + +/** Whether the organizer can send this attendee an invitation now. */ +export function canInvite(facts: InvitationFacts, now = Date.now()): boolean { + const state = invitationState(facts); + if (state === "removed" || state === "claimed" || state === "complete") return false; + return !facts.invitedAt || now - facts.invitedAt.getTime() >= RESEND_AFTER_MINUTES * 60_000; +} diff --git a/apps/web/src/infrastructure/notifications/realtime.notifier.ts b/apps/web/src/infrastructure/notifications/realtime.notifier.ts index ab37a8f..b5ca8fa 100644 --- a/apps/web/src/infrastructure/notifications/realtime.notifier.ts +++ b/apps/web/src/infrastructure/notifications/realtime.notifier.ts @@ -1,7 +1,11 @@ -import { sendNotificationEmail } from "@match-maker/email"; +import { renderInvitationEmail, sendNotificationEmail } from "@match-maker/email"; import type { NotificationPort } from "../../application/ports/notification"; export class RealtimeNotifier implements NotificationPort { + async invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise { + await sendNotificationEmail({ to: input.email, ...renderInvitationEmail(input) }); + } + async introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise { const subject = `${input.requesterName} would like to meet at ${input.eventName}`; const text = `Hi ${input.recipientName},\n\n${input.requesterName} requested an introduction at ${input.eventName}. Sign in to Mr. Bridge to respond.`; diff --git a/apps/web/src/infrastructure/postgres/event.repo.ts b/apps/web/src/infrastructure/postgres/event.repo.ts index 821ebbf..cc1f2a7 100644 --- a/apps/web/src/infrastructure/postgres/event.repo.ts +++ b/apps/web/src/infrastructure/postgres/event.repo.ts @@ -37,6 +37,21 @@ export class PostgresEventRepository implements EventRepository { participantIds(eventId: string) { return events.participantIds(eventId); } + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number) { + return events.invitationTargets(eventId, attendeeId, resendAfterMinutes); + } + recordInvitation(eventId: string, attendeeId: string, error: string | null) { + return events.recordInvitation(eventId, attendeeId, error); + } + markClaimed(eventId: string, attendeeId: string) { + return events.markClaimed(eventId, attendeeId); + } + setRevoked(eventId: string, attendeeId: string, revoked: boolean) { + return events.setRevoked(eventId, attendeeId, revoked); + } + rosterState(eventId: string, attendeeId: string) { + return events.rosterState(eventId, attendeeId); + } async importRoster(eventId: string, records: Parameters[1]) { let upserted = 0; @@ -51,14 +66,20 @@ export class PostgresEventRepository implements EventRepository { async analytics(eventId: string) { const { rows } = await query<{ roster: string; + invited: string; + claimed: string; + removed: string; profiles: string; matches: string; pending_intros: string; accepted_intros: string; }>( `select - (select count(*) from event_participants where event_id = $1) as roster, - (select count(*) from event_participants where event_id = $1 and profile_updated_at is not null) as profiles, + (select count(*) from event_participants where event_id = $1 and revoked_at is null) as roster, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and invited_at is not null) as invited, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and claimed_at is not null) as claimed, + (select count(*) from event_participants where event_id = $1 and revoked_at is not null) as removed, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and profile_updated_at is not null) as profiles, (select count(*) from event_matches where event_id = $1) as matches, (select count(*) from intro_requests where event_id = $1 and status = 'pending') as pending_intros, (select count(*) from intro_requests where event_id = $1 and status = 'accepted') as accepted_intros`, @@ -66,6 +87,9 @@ export class PostgresEventRepository implements EventRepository { ); return { roster: Number(rows[0]?.roster ?? 0), + invited: Number(rows[0]?.invited ?? 0), + claimed: Number(rows[0]?.claimed ?? 0), + removed: Number(rows[0]?.removed ?? 0), profiles: Number(rows[0]?.profiles ?? 0), matches: Number(rows[0]?.matches ?? 0), pendingIntros: Number(rows[0]?.pending_intros ?? 0), diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index c93ed7a..54ce014 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -39,7 +39,7 @@ const PROFILE_FROM = `from event_participants p * join), visible, named, and with a saved event profile. Every results path — * fresh retrieval, cached ids, saved matches — applies this same rule. */ -export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null`; +export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null and p.revoked_at is null`; export class PostgresParticipantRepository implements ParticipantRepository { async findProfile(eventId: string, attendeeId: string): Promise { @@ -118,7 +118,9 @@ export class PostgresParticipantRepository implements ParticipantRepository { async hasEventAccess(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index e95b9fd..0259401 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -13,6 +13,7 @@ export async function requireParticipantEvent(eventSlug: string, returnPath?: st if (!event) notFound(); const registered = await container.participants.hasEventAccess(event.id, session.attendeeId); if (!registered) notFound(); + await container.events.markClaimed(event.id, session.attendeeId); if (action && !eventAllows(event.status, action)) redirect(`/e/${eventSlug}`); return { session, event, container }; } diff --git a/packages/db/migrations/0006_invitations.sql b/packages/db/migrations/0006_invitations.sql new file mode 100644 index 0000000..b5daed9 --- /dev/null +++ b/packages/db/migrations/0006_invitations.sql @@ -0,0 +1,18 @@ +-- Invited account lifecycle per event. +-- +-- The roster row is the invitation. These columns record whether the +-- invitation e-mail went out (and why it failed), when the attendee first +-- signed in to the event (claimed), and whether the organizer removed their +-- access. A revoked row keeps its history but grants nothing: no sign-in to +-- the event, no matching, no appearance in anyone's results. + +alter table event_participants add column if not exists invited_at timestamptz; +alter table event_participants add column if not exists invite_count integer not null default 0; +alter table event_participants add column if not exists invite_error text; +alter table event_participants add column if not exists claimed_at timestamptz; +alter table event_participants add column if not exists revoked_at timestamptz; + +-- Anyone who already saved a profile has evidently claimed their invitation. +update event_participants + set claimed_at = profile_updated_at + where claimed_at is null and profile_updated_at is not null; diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 55e88db..a2023e2 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -113,7 +113,9 @@ export async function isOrganizer(eventId: string, attendeeId: string): Promise< export async function isParticipant(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; @@ -131,7 +133,8 @@ export async function hasOrganizationAccess(organizationSlug: string, attendeeId export async function participantIds(eventId: string): Promise { const { rows } = await query<{ attendee_id: string }>( - `select attendee_id from event_participants where event_id = $1 and profile_updated_at is not null`, [eventId] + `select attendee_id from event_participants + where event_id = $1 and profile_updated_at is not null and revoked_at is null`, [eventId] ); return rows.map((row) => row.attendee_id); } @@ -155,9 +158,76 @@ export async function roster(eventId: string): Promise { + const { rows } = await query( + `select a.id as attendee_id, a.email, a.name + from event_participants p join registered_attendees a on a.id = p.attendee_id + where p.event_id = $1 and p.revoked_at is null and p.claimed_at is null and a.email is not null + and ($2::uuid is null and p.invited_at is null + or a.id = $2::uuid and (p.invited_at is null or p.invited_at < now() - make_interval(mins => $3))) + order by a.name nulls last`, + [eventId, attendeeId, resendAfterMinutes] + ); + return rows; +} + +/** Records one delivery attempt; a failure keeps the last successful send time. */ +export async function recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise { + await query( + `update event_participants + set invited_at = case when $3::text is null then now() else invited_at end, + invite_count = invite_count + case when $3::text is null then 1 else 0 end, + invite_error = $3, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, error] + ); +} + +/** The first signed-in visit to the event claims the invitation. */ +export async function markClaimed(eventId: string, attendeeId: string): Promise { + await query( + `update event_participants set claimed_at = now() + where event_id = $1 and attendee_id = $2 and claimed_at is null and revoked_at is null`, + [eventId, attendeeId] + ); +} + +/** Removes or restores an attendee's access; returns false when they are not on the roster. */ +export async function setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise { + const { rowCount } = await query( + `update event_participants + set revoked_at = case when $3 then coalesce(revoked_at, now()) else null end, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, revoked] + ); + return (rowCount ?? 0) > 0; +} + +/** Whether an attendee is on the roster, and if so whether access was removed. */ +export async function rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null> { + const { rows } = await query<{ revoked: boolean }>( + `select revoked_at is not null as revoked from event_participants where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId] + ); + if (!rows[0]) return null; + return rows[0].revoked ? "revoked" : "active"; +} diff --git a/packages/email/src/index.ts b/packages/email/src/index.ts index c48847d..461b011 100644 --- a/packages/email/src/index.ts +++ b/packages/email/src/index.ts @@ -1,4 +1,5 @@ export { sendLoginEmail, sendNotificationEmail, type SendResult } from "./client"; +export { renderInvitationEmail, type InvitationEmailInput } from "./templates/invitation-email"; export { renderLoginEmail, type LoginEmailInput, diff --git a/packages/email/src/templates/invitation-email.ts b/packages/email/src/templates/invitation-email.ts new file mode 100644 index 0000000..e9f6384 --- /dev/null +++ b/packages/email/src/templates/invitation-email.ts @@ -0,0 +1,34 @@ +/** The invitation an organizer sends to everyone on an event roster. */ +export interface InvitationEmailInput { + name: string | null; + eventName: string; + organizationName: string; + /** The event page, where the attendee signs in and claims the invitation. */ + eventUrl: string; +} + +export function renderInvitationEmail(input: InvitationEmailInput): { subject: string; html: string; text: string } { + const greeting = input.name ? `Hi ${input.name},` : "Hi,"; + const subject = `You're invited to ${input.eventName} on Mr. Bridge`; + const text = [ + greeting, + "", + `${input.organizationName} added you to ${input.eventName}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.`, + "", + input.eventUrl, + "", + "If you did not expect this, you can ignore this e-mail.", + ].join("\n"); + const html = `
+

Mr. Bridge

+

${escapeHtml(greeting)}

+

${escapeHtml(input.organizationName)} added you to ${escapeHtml(input.eventName)}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.

+

Claim your invitation

+

If you did not expect this, you can ignore this e-mail.

+
`; + return { subject, html, text }; +} + +function escapeHtml(value: string): string { + return value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); +} diff --git a/tests/integration/invitations.test.ts b/tests/integration/invitations.test.ts new file mode 100644 index 0000000..b48d3f5 --- /dev/null +++ b/tests/integration/invitations.test.ts @@ -0,0 +1,90 @@ +/** + * Invitation lifecycle against a real Postgres: who gets invited, claims, + * and what removing access takes away. Uses its own organization, event and + * attendees. Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { query, closePool, attendees, events } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const ORG = "integration-invitations"; +const KEYS = ["new", "invited", "claimed", "removed", "viewer"] as const; +const emailOf = (key: string) => `invite-${key}@example.com`; + +describeDb("invitation lifecycle", () => { + const participants = new PostgresParticipantRepository(); + let eventId: string; + let ids: Record; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(KEYS.map((key) => ({ name: `Invite ${key}`, email: emailOf(key) }))); + const found = await attendees.findIdsByEmails(KEYS.map(emailOf)); + ids = Object.fromEntries(KEYS.map((key) => [key, found.find((row) => row.email === emailOf(key))!.id])); + const { rows: [org] } = await query<{ id: string }>( + `insert into organizations (name, slug) values ('Invitations', $1) + on conflict (slug) do update set name = excluded.name returning id`, [ORG]); + const { rows: [event] } = await query<{ id: string }>( + `insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') + on conflict (organization_id, slug) do update set status = 'open' returning id`, [org.id, ORG]); + eventId = event.id; + await query(`delete from event_participants where event_id = $1`, [eventId]); + await events.attachRoster(eventId, Object.values(ids)); + await query( + `update event_participants set profile_updated_at = now(), designation = 'Engineer', domain = 'AI', about_me = 'Builds things' + where event_id = $1 and attendee_id = any($2::uuid[])`, [eventId, [ids.removed, ids.viewer]]); + await query(`update event_participants set invited_at = now() - interval '2 minutes', invite_count = 1 where event_id = $1 and attendee_id = $2`, [eventId, ids.invited]); + await events.markClaimed(eventId, ids.claimed); + await events.setRevoked(eventId, ids.removed, true); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email = any($1::text[])`, [KEYS.map(emailOf)]); + await closePool(); + }); + + it("invites only people never invited, never claimed and not removed", async () => { + const targets = await events.invitationTargets(eventId, null, 10); + expect(targets.map((target) => target.email).sort()).toEqual([emailOf("new"), emailOf("viewer")]); + }); + + it("throttles a resend to the same person", async () => { + expect(await events.invitationTargets(eventId, ids.invited, 10)).toEqual([]); + expect(await events.invitationTargets(eventId, ids.invited, 1)).toHaveLength(1); + expect(await events.invitationTargets(eventId, ids.claimed, 0)).toEqual([]); + }); + + it("records a failure without pretending the e-mail went out", async () => { + await events.recordInvitation(eventId, ids.new, "Resend rejected the address"); + await events.recordInvitation(eventId, ids.invited, null); + const rows = await events.roster(eventId); + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get(ids.new)).toMatchObject({ invited_at: null, invite_count: 0, invite_error: "Resend rejected the address" }); + expect(byId.get(ids.invited)).toMatchObject({ invite_count: 2, invite_error: null }); + }); + + it("keeps the first claim time", async () => { + const before = (await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at; + await events.markClaimed(eventId, ids.claimed); + expect((await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at).toEqual(before); + }); + + it("removes every kind of access from a revoked attendee", async () => { + expect(await events.isParticipant(eventId, ids.removed)).toBe(false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(false); + expect(await events.participantIds(eventId)).not.toContain(ids.removed); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + const candidates = await participants.findCandidatesByIds(eventId, [ids.removed, ids.viewer]); + expect(candidates.map((candidate) => candidate.attendeeId)).toEqual([ids.viewer]); + }); + + it("restores access explicitly, and re-importing does not do it silently", async () => { + await events.attachRoster(eventId, [ids.removed]); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + await events.setRevoked(eventId, ids.removed, false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(true); + }); +}); diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts new file mode 100644 index 0000000..6eb09e5 --- /dev/null +++ b/tests/unit/invitations.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from "vitest"; +import { canInvite, invitationState, RESEND_AFTER_MINUTES, type InvitationFacts } from "@/src/domain/participant/invitation"; +import { sendInvitations, setAttendeeAccess } from "@/src/application/use-cases/manage-invitations"; +import { renderInvitationEmail } from "@match-maker/email"; + +const NOW = Date.parse("2026-10-19T12:00:00Z"); +const facts = (overrides: Partial): InvitationFacts => ({ + revokedAt: null, profileUpdatedAt: null, claimedAt: null, invitedAt: null, inviteError: null, ...overrides, +}); +const at = (minutesAgo: number) => new Date(NOW - minutesAgo * 60_000); + +describe("invitationState", () => { + it.each([ + [facts({}), "not_invited"], + [facts({ invitedAt: at(1) }), "invited"], + [facts({ inviteError: "bounced" }), "failed"], + [facts({ invitedAt: at(5), claimedAt: at(1) }), "claimed"], + [facts({ claimedAt: at(5), profileUpdatedAt: at(1) }), "complete"], + [facts({ profileUpdatedAt: at(5), revokedAt: at(1) }), "removed"], + ] as const)("%o is %s", (input, state) => { + expect(invitationState(input)).toBe(state); + }); + + it("allows a resend only after the waiting period, and never after claiming or removal", () => { + expect(canInvite(facts({}), NOW)).toBe(true); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES - 1) }), NOW)).toBe(false); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES) }), NOW)).toBe(true); + expect(canInvite(facts({ claimedAt: at(1) }), NOW)).toBe(false); + expect(canInvite(facts({ revokedAt: at(1) }), NOW)).toBe(false); + }); +}); + +function ports(targets: Array<{ attendee_id: string; email: string; name: string | null }>, fail: string[] = []) { + const events = { + invitationTargets: vi.fn().mockResolvedValue(targets), + recordInvitation: vi.fn().mockResolvedValue(undefined), + setRevoked: vi.fn().mockResolvedValue(true), + }; + const notifications = { + invitation: vi.fn(async ({ email }: { email: string }) => { + if (fail.includes(email)) throw new Error("Resend rejected the address"); + }), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { events: events as any, notifications: notifications as any, raw: { events, notifications } }; +} + +const event = { eventId: "event", eventName: "Summit", organizationName: "Acme", eventUrl: "https://bridge.example.com/e/summit" }; + +describe("sendInvitations", () => { + it("sends to every target and records successes and failures separately", async () => { + const { events, notifications, raw } = ports([ + { attendee_id: "a", email: "a@example.com", name: "A" }, + { attendee_id: "b", email: "bad@example.com", name: null }, + ], ["bad@example.com"]); + await expect(sendInvitations(event, { events, notifications })).resolves.toEqual({ sent: 1, failed: 1 }); + expect(raw.events.invitationTargets).toHaveBeenCalledWith("event", null, RESEND_AFTER_MINUTES); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "a", null); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "b", "Resend rejected the address"); + }); + + it("explains why a single resend is refused", async () => { + const { events, notifications } = ports([]); + await expect(sendInvitations({ ...event, attendeeId: "a" }, { events, notifications })).rejects.toThrow(/cannot be invited right now/); + }); +}); + +describe("setAttendeeAccess", () => { + it("refuses someone not on the roster", async () => { + const { events, raw } = ports([]); + raw.events.setRevoked.mockResolvedValue(false); + await expect(setAttendeeAccess({ eventId: "event", attendeeId: "x", revoked: true }, { events })).rejects.toThrow(/not on the event roster/); + }); +}); + +describe("renderInvitationEmail", () => { + it("links to the event and escapes names in the HTML", () => { + const mail = renderInvitationEmail({ name: "