From ea363520efa138b544b21e40e31f2bd04c86fe62 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:53:48 +0530 Subject: [PATCH 01/37] End sessions of disabled accounts and Keycloak users (R13 part 1) Session cookies were trusted until they expired, so disabling or deleting someone had no effect on a browser already signed in. - Migration 0007: registered_attendees.disabled_at and sessions_revoked_at - isSessionActive (packages/auth) runs on every request in getSession and in the /login middleware (otherwise a revoked session would loop between /login and the page): the account must exist and not be disabled, the session must be newer than sessions_revoked_at, and the Keycloak user must exist and be enabled (cached 5 minutes per replica; a Keycloak outage does not sign everyone out, the database checks still apply) - Every sign-in path refuses a disabled account (canReturnToPath) - npm run account:disable | account:enable | account:revoke-sessions update the database and the Keycloak user (disable also ends its Keycloak sessions) - Tests: unit rules, and the commands against the real database and Keycloak realm, including that repeated sign-ins keep one identity --- apps/web/lib/session.ts | 10 ++- apps/web/middleware.ts | 7 +- package.json | 5 +- packages/auth/src/index.ts | 4 + packages/auth/src/keycloak.ts | 40 ++++++++++ packages/auth/src/session-state.ts | 16 ++++ packages/db/migrations/0007_account_state.sql | 10 +++ packages/db/src/repositories/attendees.ts | 31 ++++++++ packages/db/src/types.ts | 2 + tests/integration/account-revocation.test.ts | 77 +++++++++++++++++++ tests/unit/middleware.test.ts | 11 +++ tests/unit/return-access.test.ts | 11 ++- tests/unit/session-state.test.ts | 41 ++++++++++ tools/manage-account.ts | 53 +++++++++++++ 14 files changed, 312 insertions(+), 6 deletions(-) create mode 100644 packages/auth/src/session-state.ts create mode 100644 packages/db/migrations/0007_account_state.sql create mode 100644 tests/integration/account-revocation.test.ts create mode 100644 tests/unit/session-state.test.ts create mode 100644 tools/manage-account.ts diff --git a/apps/web/lib/session.ts b/apps/web/lib/session.ts index 5b20dff..f1bd842 100644 --- a/apps/web/lib/session.ts +++ b/apps/web/lib/session.ts @@ -4,9 +4,10 @@ import { sealSession, unsealSession, sessionCookieOptions, + isSessionActive, type Session, } from "@match-maker/auth"; -import { events } from "@match-maker/db"; +import { attendees, events } from "@match-maker/db"; import { safeReturnTo } from "./safe-return-to"; export type { Session }; @@ -15,7 +16,9 @@ export type { Session }; export async function getSession(): Promise { const store = await cookies(); const raw = store.get(getSessionConfig().cookieName)?.value; - return raw ? unsealSession(raw) : null; + const session = raw ? await unsealSession(raw) : null; + // A disabled account, revoked sessions, or a disabled Keycloak user end it now. + return session && (await isSessionActive(session)) ? session : null; } /** Issue a session cookie for a freshly authenticated user. */ @@ -53,6 +56,9 @@ export function clientIp(request: Request, hops = Number(process.env.TRUSTED_PRO /** Apply the event roster gate before issuing an event-specific login session. */ export async function canReturnToPath(returnTo: string | null | undefined, attendeeId: string): Promise { + // Every sign-in path checks this, so a disabled account cannot sign in at all. + const account = await attendees.accountState(attendeeId); + if (!account || account.disabled_at) return false; returnTo = safeReturnTo(returnTo); const participantRoute = returnTo.match(/^\/e\/([^/]+)(?:\/|$)/); if (participantRoute) { diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts index acacd05..f8be377 100644 --- a/apps/web/middleware.ts +++ b/apps/web/middleware.ts @@ -1,5 +1,5 @@ import { NextResponse, type NextRequest } from "next/server"; -import { getSessionConfig, sessionCookieOptions, unsealSession } from "@match-maker/auth"; +import { getSessionConfig, isSessionActive, sessionCookieOptions, unsealSession } from "@match-maker/auth"; import { postLoginPath } from "./lib/safe-return-to"; const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); @@ -24,7 +24,10 @@ async function loginRedirect(request: NextRequest) { if (!raw) return NextResponse.next(); const { searchParams } = request.nextUrl; - const session = await unsealSession(raw); + const unsealed = await unsealSession(raw); + // Same rule as getSession, or a revoked session would loop between /login + // and the page that sent it there. + const session = unsealed && (await isSessionActive(unsealed)) ? unsealed : null; if (session && !searchParams.has("error")) { return NextResponse.redirect(new URL(postLoginPath(searchParams.get("returnTo")), request.url)); } diff --git a/package.json b/package.json index bf5dd6d..4e6833c 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,10 @@ "docker:down": "docker compose down", "docker:logs": "docker compose logs -f web", "keycloak:wait": "tsx tools/wait-for-keycloak.ts", - "keycloak:sync": "tsx tools/sync-keycloak.ts" + "keycloak:sync": "tsx tools/sync-keycloak.ts", + "account:disable": "tsx tools/manage-account.ts disable", + "account:enable": "tsx tools/manage-account.ts enable", + "account:revoke-sessions": "tsx tools/manage-account.ts revoke-sessions" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index f1d2cf9..2a7239b 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -30,6 +30,9 @@ export { buildLogoutUrl, ensureUser, findUserByEmail, + isUserEnabled, + setUserEnabled, + logoutUser, resetCaches, type Pkce, type TokenSet, @@ -49,3 +52,4 @@ export { type VerifyResult, type VerifyFailure, } from "./otp"; +export { isSessionActive } from "./session-state"; diff --git a/packages/auth/src/keycloak.ts b/packages/auth/src/keycloak.ts index 58f7a91..da23cae 100644 --- a/packages/auth/src/keycloak.ts +++ b/packages/auth/src/keycloak.ts @@ -354,10 +354,50 @@ export async function ensureUser( return created.id; } +// ── User status ────────────────────────────────────────────────────────────── +// Sessions outlive a Keycloak disable or delete, so requests re-check the user. +// The answer is cached briefly per replica; when Keycloak cannot be reached the +// user is treated as enabled, and the database checks still apply. + +const USER_STATUS_TTL_MS = 5 * 60 * 1000; +const userStatus = new Map(); + +export async function isUserEnabled(sub: string, now = Date.now()): Promise { + const cached = userStatus.get(sub); + if (cached && cached.until > now) return cached.enabled; + let enabled: boolean; + try { + const res = await adminFetch(`/users/${encodeURIComponent(sub)}`); + if (res.status === 404) enabled = false; + else if (!res.ok) throw new Error(`Keycloak user lookup failed (${res.status})`); + else enabled = ((await res.json()) as { enabled?: boolean }).enabled !== false; + } catch (error) { + console.warn("[auth] could not check Keycloak user status; allowing:", (error as Error).message); + return true; + } + userStatus.set(sub, { enabled, until: now + USER_STATUS_TTL_MS }); + return enabled; +} + +/** Enables or disables a Keycloak user, ending their Keycloak sessions on disable. */ +export async function setUserEnabled(sub: string, enabled: boolean): Promise { + const res = await adminFetch(`/users/${encodeURIComponent(sub)}`, { method: "PUT", body: JSON.stringify({ enabled }) }); + if (!res.ok) throw new Error(`Keycloak user update failed (${res.status})`); + if (!enabled) await logoutUser(sub); + userStatus.delete(sub); +} + +/** Ends the user's Keycloak (SSO) sessions, so Google sign-in asks again. */ +export async function logoutUser(sub: string): Promise { + const res = await adminFetch(`/users/${encodeURIComponent(sub)}/logout`, { method: "POST" }); + if (!res.ok && res.status !== 404) throw new Error(`Keycloak logout failed (${res.status})`); +} + /** Clear cached discovery/tokens. Exposed for tests. */ export function resetCaches(): void { discoveryCache = null; adminToken = null; + userStatus.clear(); jwks = null; jwksUri = null; } diff --git a/packages/auth/src/session-state.ts b/packages/auth/src/session-state.ts new file mode 100644 index 0000000..5357573 --- /dev/null +++ b/packages/auth/src/session-state.ts @@ -0,0 +1,16 @@ +import { attendees } from "@match-maker/db"; +import { isUserEnabled } from "./keycloak"; +import type { Session } from "./session"; + +/** + * Whether a cryptographically valid session may still be used. The cookie is + * self-contained, so this is what makes disabling an account, "sign out + * everywhere", and disabling or deleting the Keycloak user take effect on the + * next request instead of when the cookie expires. + */ +export async function isSessionActive(session: Session): Promise { + const account = await attendees.accountState(session.attendeeId); + if (!account || account.disabled_at) return false; + if (account.sessions_revoked_at && session.iat * 1000 < account.sessions_revoked_at.getTime()) return false; + return isUserEnabled(session.sub); +} diff --git a/packages/db/migrations/0007_account_state.sql b/packages/db/migrations/0007_account_state.sql new file mode 100644 index 0000000..92d0485 --- /dev/null +++ b/packages/db/migrations/0007_account_state.sql @@ -0,0 +1,10 @@ +-- Account-wide access, independent of any one event. +-- +-- disabled_at the account may not sign in or use any session +-- sessions_revoked_at sessions issued before this moment are no longer valid +-- (sign out everywhere), without disabling the account +-- +-- Session cookies are self-contained, so every request checks these columns. + +alter table registered_attendees add column if not exists disabled_at timestamptz; +alter table registered_attendees add column if not exists sessions_revoked_at timestamptz; diff --git a/packages/db/src/repositories/attendees.ts b/packages/db/src/repositories/attendees.ts index 383a7df..32866ad 100644 --- a/packages/db/src/repositories/attendees.ts +++ b/packages/db/src/repositories/attendees.ts @@ -62,6 +62,37 @@ export async function findIdsByEmails(emails: string[]): Promise { + const { rows } = await query<{ disabled_at: Date | null; sessions_revoked_at: Date | null }>( + `select disabled_at, sessions_revoked_at from registered_attendees where id = $1`, + [id] + ); + return rows[0] ?? null; +} + +/** Disables or re-enables an account; disabling also ends its sessions. Returns false when unknown. */ +export async function setDisabled(email: string, disabled: boolean): Promise { + const { rowCount } = await query( + `update registered_attendees + set disabled_at = case when $2 then coalesce(disabled_at, now()) else null end, + sessions_revoked_at = case when $2 then now() else sessions_revoked_at end, + updated_at = now() + where email = $1`, + [normalizeEmail(email), disabled] + ); + return (rowCount ?? 0) > 0; +} + +/** Ends every session issued so far ("sign out everywhere"). Returns false when unknown. */ +export async function revokeSessions(email: string): Promise { + const { rowCount } = await query( + `update registered_attendees set sessions_revoked_at = now(), updated_at = now() where email = $1`, + [normalizeEmail(email)] + ); + return (rowCount ?? 0) > 0; +} + /** True when the e-mail is on the attendee roster — the gate for every login. */ export async function isRegisteredEmail(email: string): Promise { const { rows } = await query<{ exists: boolean }>( diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index 2a835da..3ea58f1 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -10,6 +10,8 @@ export interface Attendee { self_description: string | null; years_of_experience: number | null; most_impressive_build: string | null; + disabled_at: Date | null; + sessions_revoked_at: Date | null; created_at: Date; updated_at: Date; } diff --git a/tests/integration/account-revocation.test.ts b/tests/integration/account-revocation.test.ts new file mode 100644 index 0000000..9c60ff8 --- /dev/null +++ b/tests/integration/account-revocation.test.ts @@ -0,0 +1,77 @@ +/** + * Account disable, enable and "sign out everywhere" against the real database + * and the real Keycloak realm. Creates its own attendee and Keycloak user and + * deletes both afterwards. Skipped unless DATABASE_URL and a reachable + * Keycloak (KEYCLOAK_ISSUER plus admin credentials) are configured. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { attendees, closePool, query } from "@match-maker/db"; +import { ensureUser, isSessionActive, isUserEnabled, resetCaches } from "@match-maker/auth"; +import { migrate } from "../../packages/db/src/migrate"; +import { manageAccount } from "../../tools/manage-account"; + +const issuer = (process.env.KEYCLOAK_INTERNAL_ISSUER || process.env.KEYCLOAK_ISSUER || "").replace(/\/$/, ""); +const reachable = await fetch(`${issuer}/.well-known/openid-configuration`, { signal: AbortSignal.timeout(3000) }) + .then((res) => res.ok).catch(() => false); +const describeLive = process.env.DATABASE_URL && process.env.KEYCLOAK_ADMIN_PASSWORD && reachable ? describe : describe.skip; + +const EMAIL = `revocation-${Date.now().toString(36)}@example.com`; + +async function deleteKeycloakUser(sub: string) { + const [, server, realm] = issuer.match(/^(.*)\/realms\/([^/]+)$/)!; + const token = await fetch(`${server}/realms/master/protocol/openid-connect/token`, { + method: "POST", + body: new URLSearchParams({ grant_type: "password", client_id: "admin-cli", username: process.env.KEYCLOAK_ADMIN!, password: process.env.KEYCLOAK_ADMIN_PASSWORD! }), + }).then((res) => res.json()); + await fetch(`${server}/admin/realms/${realm}/users/${sub}`, { method: "DELETE", headers: { Authorization: `Bearer ${token.access_token}` } }); +} + +describeLive("account disable and session revocation", () => { + let sub: string; + let attendeeId: string; + const session = () => ({ sub, email: EMAIL, name: "Revocation Test", attendeeId, method: "email" as const, iat: Math.floor(Date.now() / 1000) - 5 }); + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany([{ name: "Revocation Test", email: EMAIL }]); + attendeeId = (await attendees.findByEmail(EMAIL))!.id; + sub = await ensureUser(EMAIL, "Revocation Test"); + }); + + afterAll(async () => { + if (sub) await deleteKeycloakUser(sub); + await query(`delete from registered_attendees where email = $1`, [EMAIL]); + await closePool(); + }); + + it("keeps one Keycloak identity for repeated sign-ins", async () => { + expect(await ensureUser(EMAIL, "Revocation Test")).toBe(sub); + await expect(isSessionActive(session())).resolves.toBe(true); + }); + + it("disables the account in the database and in Keycloak", async () => { + const existing = session(); + const report = await manageAccount("disable", EMAIL); + expect(report.join("\n")).toMatch(/keycloak: user disabled/); + resetCaches(); + await expect(isUserEnabled(sub)).resolves.toBe(false); + await expect(isSessionActive(existing)).resolves.toBe(false); + }); + + it("enables it again, without reviving sessions from before the disable", async () => { + const beforeDisable = { ...session(), iat: Math.floor(Date.now() / 1000) - 3600 }; + await manageAccount("enable", EMAIL); + resetCaches(); + await expect(isUserEnabled(sub)).resolves.toBe(true); + await expect(isSessionActive(beforeDisable)).resolves.toBe(false); + await expect(isSessionActive({ ...session(), iat: Math.floor(Date.now() / 1000) + 1 })).resolves.toBe(true); + }); + + it("signs out everywhere without disabling", async () => { + const existing = session(); + await new Promise((resolve) => setTimeout(resolve, 1100)); + await manageAccount("revoke-sessions", EMAIL); + await expect(isSessionActive(existing)).resolves.toBe(false); + expect((await attendees.accountState(attendeeId))!.disabled_at).toBeNull(); + }); +}); diff --git a/tests/unit/middleware.test.ts b/tests/unit/middleware.test.ts index 926e8eb..b37273f 100644 --- a/tests/unit/middleware.test.ts +++ b/tests/unit/middleware.test.ts @@ -2,9 +2,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { NextRequest } from "next/server"; const unsealSession = vi.hoisted(() => vi.fn()); +const isSessionActive = vi.hoisted(() => vi.fn()); vi.mock("@match-maker/auth", () => ({ unsealSession, + isSessionActive, getSessionConfig: () => ({ cookieName: "mb_session" }), sessionCookieOptions: (maxAge: number) => ({ httpOnly: true, sameSite: "lax", path: "/", maxAge }), })); @@ -17,9 +19,18 @@ const loginRequest = (query = "", cookie?: string) => beforeEach(() => { unsealSession.mockReset(); + isSessionActive.mockReset().mockResolvedValue(true); }); describe("login middleware", () => { + it("treats a revoked or disabled session as signed out instead of looping", async () => { + unsealSession.mockResolvedValue(session); + isSessionActive.mockResolvedValue(false); + const response = await middleware(loginRequest("?returnTo=%2Fe%2Fdemo", "mb_session=valid")); + expect(response.headers.get("location")).toBeNull(); + expect(response.cookies.get("mb_session")?.value).toBe(""); + }); + 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(); diff --git a/tests/unit/return-access.test.ts b/tests/unit/return-access.test.ts index 1ecf819..4c3af22 100644 --- a/tests/unit/return-access.test.ts +++ b/tests/unit/return-access.test.ts @@ -3,7 +3,8 @@ 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 })); +const accountState = vi.hoisted(() => vi.fn()); +vi.mock("@match-maker/db", () => ({ events: mocks, attendees: { accountState } })); import { canReturnToPath } from "@/lib/session"; @@ -11,6 +12,14 @@ describe("canReturnToPath", () => { beforeEach(() => { vi.clearAllMocks(); mocks.findBySlug.mockResolvedValue(null); + accountState.mockResolvedValue({ disabled_at: null, sessions_revoked_at: null }); + }); + + it("refuses a disabled account on every path", async () => { + accountState.mockResolvedValue({ disabled_at: new Date(), sessions_revoked_at: new Date() }); + mocks.hasOrganizationAccess.mockResolvedValue(true); + await expect(canReturnToPath("/orgs/acme/events/new", "member")).resolves.toBe(false); + await expect(canReturnToPath("/", "member")).resolves.toBe(false); }); it.each(["/orgs/acme/events/new", "/orgs/acme/events", "/orgs/acme/events/"])( diff --git a/tests/unit/session-state.test.ts b/tests/unit/session-state.test.ts new file mode 100644 index 0000000..b845abb --- /dev/null +++ b/tests/unit/session-state.test.ts @@ -0,0 +1,41 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ accountState: vi.fn(), isUserEnabled: vi.fn() })); +vi.mock("@match-maker/db", () => ({ attendees: { accountState: mocks.accountState } })); +vi.mock("../../packages/auth/src/keycloak", () => ({ isUserEnabled: mocks.isUserEnabled })); + +import { isSessionActive } from "../../packages/auth/src/session-state"; + +const ISSUED = Date.parse("2026-10-19T10:00:00Z"); +const session = { sub: "kc-user", email: "a@example.com", name: null, attendeeId: "attendee", method: "email" as const, iat: ISSUED / 1000 }; + +describe("isSessionActive", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.accountState.mockResolvedValue({ disabled_at: null, sessions_revoked_at: null }); + mocks.isUserEnabled.mockResolvedValue(true); + }); + + it("accepts a session for an active account and Keycloak user", async () => { + await expect(isSessionActive(session)).resolves.toBe(true); + }); + + it("ends sessions of a deleted or disabled account", async () => { + mocks.accountState.mockResolvedValue(null); + await expect(isSessionActive(session)).resolves.toBe(false); + mocks.accountState.mockResolvedValue({ disabled_at: new Date(), sessions_revoked_at: null }); + await expect(isSessionActive(session)).resolves.toBe(false); + expect(mocks.isUserEnabled).not.toHaveBeenCalled(); + }); + + it("ends sessions issued before a revocation, but not later ones", async () => { + mocks.accountState.mockResolvedValue({ disabled_at: null, sessions_revoked_at: new Date(ISSUED + 60_000) }); + await expect(isSessionActive(session)).resolves.toBe(false); + await expect(isSessionActive({ ...session, iat: (ISSUED + 120_000) / 1000 })).resolves.toBe(true); + }); + + it("ends sessions of a user disabled in Keycloak", async () => { + mocks.isUserEnabled.mockResolvedValue(false); + await expect(isSessionActive(session)).resolves.toBe(false); + }); +}); diff --git a/tools/manage-account.ts b/tools/manage-account.ts new file mode 100644 index 0000000..b4dac45 --- /dev/null +++ b/tools/manage-account.ts @@ -0,0 +1,53 @@ +/** + * Account administration for one person, across every event: + * + * npm run account:disable -- no sign-in, every session ended + * npm run account:enable -- undo a disable + * npm run account:revoke-sessions -- sign out everywhere, keep the account + * + * Changes the database (which every request checks) and the Keycloak user, so + * Google sign-in stops too. Event-level removal is on the organizer roster page. + */ +import "dotenv/config"; +import { attendees, closePool } from "@match-maker/db"; +import { findUserByEmail, logoutUser, setUserEnabled } from "@match-maker/auth"; +import { isMainModule } from "../packages/db/src/is-main"; + +export type AccountCommand = "disable" | "enable" | "revoke-sessions"; + +export async function manageAccount(command: AccountCommand, email: string): Promise { + const report: string[] = []; + const known = command === "revoke-sessions" + ? await attendees.revokeSessions(email) + : await attendees.setDisabled(email, command === "disable"); + if (!known) throw new Error(`No attendee has the e-mail ${email}`); + report.push(`database: ${command === "enable" ? "account enabled" : command === "disable" ? "account disabled, sessions ended" : "sessions ended"}`); + + const user = await findUserByEmail(email); + if (!user) { + report.push("keycloak: no user yet (they have never signed in)"); + } else if (command === "revoke-sessions") { + await logoutUser(user.id); + report.push("keycloak: sessions ended"); + } else { + await setUserEnabled(user.id, command === "enable"); + report.push(`keycloak: user ${command === "enable" ? "enabled" : "disabled"}`); + } + return report; +} + +if (isMainModule(import.meta.url)) { + const [command, email] = process.argv.slice(2); + if (!["disable", "enable", "revoke-sessions"].includes(command ?? "") || !email) { + console.error("Usage: tsx tools/manage-account.ts "); + process.exit(1); + } + try { + for (const line of await manageAccount(command as AccountCommand, email)) console.info(`[account] ${line}`); + } catch (error) { + console.error(`[account] ${(error as Error).message}`); + process.exitCode = 1; + } finally { + await closePool(); + } +} From 3f71d1a84b7e27ea0b49111aa17164c7d894fbc1 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:58:25 +0530 Subject: [PATCH 02/37] bug fixx-roster-sideways-scroll-on-phone The visually hidden "Actions" header added to the roster table in R12 is absolutely positioned, and the table's scroll wrapper was not, so the header escaped the wrapper and widened the page by 175px on a phone. The wrapper is now the positioning context. --- .../orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 50cb89a..f91d9f8 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 @@ -57,7 +57,7 @@ export default async function RosterPage({ params, searchParams }: { label={`Send invitations to ${pending} not yet invited`} pendingLabel="Sending invitations…" />} } {!roster.length ?

No attendees yet. Import an Excel roster to invite people to this event.

: -
+
{roster.map(({ person, facts, state }) => { const id = String(person.id); From 9ac5cde6ee3127b2f8006fdb3ef22c99d9eac173 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:58:34 +0530 Subject: [PATCH 03/37] Link Google to e-mail accounts and end Keycloak sessions on sign-out (R13 part 2) - OTP then Google hit Keycloak's default first-login flow, which asks the existing account (created by e-mail sign-in, no password) to confirm with a password: a dead end. keycloak:sync now installs "mr-bridge link existing account" (create the user if the e-mail is new, otherwise link it; no review-profile form) and binds the Google provider to it. Google addresses are verified (trustEmail), and the app still rejects unverified ones. Re-running changes nothing - Sign out (button and /api/auth/logout) ends the Keycloak session of a Google sign-in through the admin API instead of sending the browser to Keycloak's "Do you want to log out?" page - A mr-bridge login theme (child of keycloak.v2) gives the remaining Keycloak screens the site's colours; shipped in the Keycloak image, mounted in compose, selected by keycloak:sync when installed - Supported shared-domain hostname setup: strict hostname (the KC_HOSTNAME_STRICT=false override is gone) and KC_HOSTNAME_BACKCHANNEL_DYNAMIC for the app's Cloud Map calls - README documents keycloak:sync and the account commands --- ReadMe.md | 4 +- apps/web/app/actions/participant.actions.ts | 4 +- apps/web/app/api/auth/logout/route.js | 27 ++---- apps/web/lib/session.ts | 15 ++++ docker-compose.yml | 1 + infra/docker/keycloak.Dockerfile | 3 + infra/terraform/ecs.tf | 4 +- .../login/resources/css/mr-bridge.css | 57 ++++++++++++ .../themes/mr-bridge/login/theme.properties | 6 ++ tests/unit/sync-keycloak.test.ts | 63 ++++++++++--- tools/sync-keycloak.ts | 88 ++++++++++++++++--- 11 files changed, 226 insertions(+), 46 deletions(-) create mode 100644 keycloak/themes/mr-bridge/login/resources/css/mr-bridge.css create mode 100644 keycloak/themes/mr-bridge/login/theme.properties diff --git a/ReadMe.md b/ReadMe.md index 76b1b32..a5d93b0 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -107,7 +107,9 @@ 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 keycloak:sync` | Bring an existing realm up to date: client secret, Google credentials, the account-linking flow (Google joins an account an e-mail code created), and the site login theme. Run after the first Keycloak start and after upgrades | +| `npm run account:disable -- ` | Block sign-in and end every session (database and Keycloak); `account:enable` undoes it | +| `npm run account:revoke-sessions -- ` | Sign the person out everywhere without disabling the account | | `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. diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts index c98e189..23a2986 100644 --- a/apps/web/app/actions/participant.actions.ts +++ b/apps/web/app/actions/participant.actions.ts @@ -5,7 +5,7 @@ import { getContainer } from "../../src/composition/container"; import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { Intent } from "../../src/domain/participant/intent"; import { ValidationError } from "../../src/domain/shared/validation"; -import { clearSession, getSession } from "../../lib/session"; +import { clearSession, endIdentityProviderSession, getSession } from "../../lib/session"; import { runFormAction, type FormState } from "../../lib/form-state"; import { redirect } from "next/navigation"; @@ -48,7 +48,9 @@ async function saveProfile(eventSlug: string, formData: FormData) { } export async function signOutCurrentUser() { + const session = await getSession(); await clearSession(); + await endIdentityProviderSession(session); redirect("/login"); } diff --git a/apps/web/app/api/auth/logout/route.js b/apps/web/app/api/auth/logout/route.js index cea567e..943469c 100644 --- a/apps/web/app/api/auth/logout/route.js +++ b/apps/web/app/api/auth/logout/route.js @@ -1,33 +1,18 @@ import { NextResponse } from "next/server"; -import { buildLogoutUrl } from "@match-maker/auth"; -import { clearSession, getSession } from "@/lib/session"; +import { clearSession, endIdentityProviderSession, getSession } from "@/lib/session"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; /** * Sign out. Clears the local session, and for Google logins also ends the - * Keycloak SSO session — otherwise the next sign-in would silently re-use it - * and appear to ignore the logout. + * Keycloak SSO session server-side — otherwise the next sign-in would silently + * re-use it and appear to ignore the logout. Same behaviour as the Sign out + * button (signOutCurrentUser). */ -export async function POST(request) { +export async function POST() { const session = await getSession(); await clearSession(); - - const origin = process.env.APP_BASE_URL || new URL(request.url).origin; - - if (session?.method === "google") { - try { - return NextResponse.json({ - ok: true, - redirectTo: await buildLogoutUrl(`${origin}/login`), - }); - } catch (err) { - // Keycloak being unreachable must not trap the user in a signed-in state; - // the local cookie is already gone. - console.error("[auth/logout] could not build Keycloak logout URL:", err); - } - } - + await endIdentityProviderSession(session); return NextResponse.json({ ok: true, redirectTo: "/login" }); } diff --git a/apps/web/lib/session.ts b/apps/web/lib/session.ts index f1bd842..793a229 100644 --- a/apps/web/lib/session.ts +++ b/apps/web/lib/session.ts @@ -5,6 +5,7 @@ import { unsealSession, sessionCookieOptions, isSessionActive, + logoutUser, type Session, } from "@match-maker/auth"; import { attendees, events } from "@match-maker/db"; @@ -34,6 +35,20 @@ export async function setSession( ); } +/** + * Google sign-ins also hold a Keycloak SSO session. Ending it server-side means + * the next Google sign-in starts fresh, without sending the browser through + * Keycloak's "Do you want to log out?" page. Never blocks signing out. + */ +export async function endIdentityProviderSession(session: Session | null): Promise { + if (session?.method !== "google") return; + try { + await logoutUser(session.sub); + } catch (error) { + console.error("[auth] could not end the Keycloak session:", error); + } +} + export async function clearSession(): Promise { const store = await cookies(); store.set(getSessionConfig().cookieName, "", sessionCookieOptions(0)); diff --git a/docker-compose.yml b/docker-compose.yml index 889f321..10e572d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -55,6 +55,7 @@ services: - "${KEYCLOAK_PORT:-8080}:8080" volumes: - ./keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json:ro + - ./keycloak/themes/mr-bridge:/opt/keycloak/themes/mr-bridge:ro depends_on: postgres: condition: service_healthy diff --git a/infra/docker/keycloak.Dockerfile b/infra/docker/keycloak.Dockerfile index a4b68a9..608a199 100644 --- a/infra/docker/keycloak.Dockerfile +++ b/infra/docker/keycloak.Dockerfile @@ -30,5 +30,8 @@ ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pe # environment (client secret, app URL, Google credentials). COPY keycloak/realm-export.json /opt/keycloak/data/import/realm-export.json +# Site-styled login theme; selected per realm by `npm run keycloak:sync`. +COPY keycloak/themes/mr-bridge /opt/keycloak/themes/mr-bridge + ENTRYPOINT ["/opt/keycloak/bin/kc.sh"] CMD ["start", "--optimized", "--import-realm"] diff --git a/infra/terraform/ecs.tf b/infra/terraform/ecs.tf index d3df2a1..f2b8095 100644 --- a/infra/terraform/ecs.tf +++ b/infra/terraform/ecs.tf @@ -327,7 +327,9 @@ resource "aws_ecs_task_definition" "keycloak" { # 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 }, - { name = "KC_HOSTNAME_STRICT", value = "false" }, + # Supported shared-domain setup: a fixed public hostname, while the app's + # back-channel calls over Cloud Map keep their internal URLs. + { name = "KC_HOSTNAME_BACKCHANNEL_DYNAMIC", value = "true" }, # TLS terminates at the ALB, so Keycloak speaks HTTP but must trust the # X-Forwarded-* headers to build correct absolute URLs. { name = "KC_PROXY_HEADERS", value = "xforwarded" }, diff --git a/keycloak/themes/mr-bridge/login/resources/css/mr-bridge.css b/keycloak/themes/mr-bridge/login/resources/css/mr-bridge.css new file mode 100644 index 0000000..999ee0f --- /dev/null +++ b/keycloak/themes/mr-bridge/login/resources/css/mr-bridge.css @@ -0,0 +1,57 @@ +/* Matches apps/web/app/globals.css: dark surfaces, amber accent. */ +:root { + --pf-v5-global--FontFamily--text: Inter, system-ui, sans-serif; + --pf-v5-global--FontFamily--heading: Inter, system-ui, sans-serif; + --pf-v5-global--primary-color--100: #f59e0b; + --pf-v5-global--primary-color--200: #d97706; + --pf-v5-global--link--Color: #f59e0b; + --pf-v5-global--link--Color--hover: #fbbf24; + --pf-v5-global--Color--100: #f4f4f5; + --pf-v5-global--Color--200: #a1a1aa; + --pf-v5-global--BackgroundColor--100: #151519; + --pf-v5-global--BorderColor--100: #3f3f46; +} + +html, body, .pf-v5-c-login { + background: #0a0a0e !important; + color: #f4f4f5; +} + +.pf-v5-c-login__main { + background: #151519; + border: 1px solid #333; + border-radius: 14px; +} + +.pf-v5-c-login__main-header, +.pf-v5-c-login__main-body, +.pf-v5-c-login__main-footer, +.pf-v5-c-title, +.pf-v5-c-form__label-text { + color: #f4f4f5; +} + +#kc-header-wrapper { + color: #f59e0b; + font-weight: 700; + letter-spacing: 2px; + text-transform: uppercase; +} + +.pf-v5-c-button.pf-m-primary { + --pf-v5-c-button--m-primary--BackgroundColor: #f59e0b; + --pf-v5-c-button--m-primary--hover--BackgroundColor: #fbbf24; + --pf-v5-c-button--m-primary--Color: #0a0a0e; + --pf-v5-c-button--m-primary--hover--Color: #0a0a0e; + font-weight: 700; +} + +.pf-v5-c-form-control { + --pf-v5-c-form-control--BackgroundColor: #0a0a0e; + --pf-v5-c-form-control--Color: #f4f4f5; +} + +:where(a, button, input):focus-visible { + outline: 2px solid #f59e0b; + outline-offset: 3px; +} diff --git a/keycloak/themes/mr-bridge/login/theme.properties b/keycloak/themes/mr-bridge/login/theme.properties new file mode 100644 index 0000000..2ef7c03 --- /dev/null +++ b/keycloak/themes/mr-bridge/login/theme.properties @@ -0,0 +1,6 @@ +# Mr. Bridge colours on the few Keycloak screens people can reach (account +# linking, errors, logout confirmation). Applied by `npm run keycloak:sync`. +parent=keycloak.v2 +import=common/keycloak +styles=css/styles.css css/mr-bridge.css +darkMode=false diff --git a/tests/unit/sync-keycloak.test.ts b/tests/unit/sync-keycloak.test.ts index 4a6b8c9..9863718 100644 --- a/tests/unit/sync-keycloak.test.ts +++ b/tests/unit/sync-keycloak.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { syncKeycloak } from "../../tools/sync-keycloak"; +import { LINKING_FLOW, syncKeycloak } from "../../tools/sync-keycloak"; const env = { KEYCLOAK_ISSUER: "http://localhost:8080/realms/match-maker", @@ -10,48 +10,89 @@ const env = { }; const admin = "http://localhost:8080/admin/realms/match-maker"; -function fakeKeycloak(currentSecret = "old-secret") { +function fakeKeycloak(currentSecret = "old-secret", loginThemes = ["keycloak.v2"]) { const calls: Array<{ method: string; url: string; body?: unknown }> = []; + const flows: Array<{ alias: string }> = []; + const executions: Array<{ id: string; providerId: string; requirement: string }> = []; 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 body = typeof init.body === "string" ? JSON.parse(init.body) : undefined; + calls.push({ method, url, body }); 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 (url.endsWith("/admin/serverinfo")) return json({ themes: { login: loginThemes.map((name) => ({ name })) } }); + if (url.endsWith("/authentication/flows")) { + if (method === "POST") { flows.push(body); return new Response(null, { status: 201 }); } + return json(flows); + } + if (url.endsWith("/executions/execution")) { + executions.push({ id: `exec-${executions.length}`, providerId: body.provider, requirement: "DISABLED" }); + return new Response(null, { status: 201 }); + } + if (url.endsWith("/executions")) { + if (method === "PUT") { executions.find((item) => item.id === body.id)!.requirement = body.requirement; return new Response(null, { status: 202 }); } + return json(executions); + } 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" } }); + if (url.endsWith("/identity-provider/instances/google")) return json({ alias: "google", enabled: false, firstBrokerLoginFlowAlias: "first broker login", config: { syncMode: "IMPORT" } }); + if (url === admin) return json({ realm: "match-maker", loginTheme: null }); return new Response(null, { status: 404 }); }); - return { http: http as unknown as typeof fetch, calls }; + return { http: http as unknown as typeof fetch, calls, flows, executions }; } +const providerPut = (calls: Array<{ method: string; url: string; body?: unknown }>) => + calls.find((call) => call.method === "PUT" && call.url.endsWith("/identity-provider/instances/google")); + describe("keycloak:sync", () => { - it("updates a stale client secret and skips Google when it is not configured", async () => { + it("updates a stale client secret and skips Google credentials when they are 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", + `flow ${LINKING_FLOW}: created`, + "identity provider google: Google credentials skipped, GOOGLE_CLIENT_ID is not set", + `identity provider google: first sign-in links existing accounts (${LINKING_FLOW})`, + "login theme: mr-bridge is not installed in this Keycloak, keeping the default", ]); expect(calls.find((call) => call.method === "PUT")).toMatchObject({ url: `${admin}/clients/client-uuid`, body: { id: "client-uuid", secret: "new-secret" }, }); + expect(providerPut(calls)?.body).toMatchObject({ enabled: false, firstBrokerLoginFlowAlias: LINKING_FLOW, trustEmail: true }); + }); + + it("builds a flow that creates new users and links existing ones, and reuses it", async () => { + const fake = fakeKeycloak("new-secret"); + await syncKeycloak(env, fake.http); + expect(fake.flows).toEqual([expect.objectContaining({ alias: LINKING_FLOW, providerId: "basic-flow", topLevel: true })]); + expect(fake.executions.map((item) => `${item.providerId}:${item.requirement}`)) + .toEqual(["idp-create-user-if-unique:ALTERNATIVE", "idp-auto-link:ALTERNATIVE"]); + const again = await syncKeycloak(env, fake.http); + expect(again.join("\n")).not.toMatch(/created/); + expect(fake.flows).toHaveLength(1); + expect(fake.executions).toHaveLength(2); + }); + + it("selects the site login theme when Keycloak has it", async () => { + const { http, calls } = fakeKeycloak("new-secret", ["keycloak.v2", "mr-bridge"]); + expect(await syncKeycloak(env, http)).toContain("login theme: mr-bridge"); + expect(calls.find((call) => call.method === "PUT" && call.url === admin)?.body).toMatchObject({ loginTheme: "mr-bridge" }); }); 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); + expect(calls.some((call) => call.method === "PUT" && call.url.includes("/clients/"))).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`, + expect(report).toContain("identity provider google: Google client updated and enabled"); + expect(providerPut(calls)).toMatchObject({ body: { enabled: true, config: { syncMode: "IMPORT", clientId: "id.apps.googleusercontent.com", clientSecret: "gsecret" } }, }); }); diff --git a/tools/sync-keycloak.ts b/tools/sync-keycloak.ts index 4ba2118..7688f75 100644 --- a/tools/sync-keycloak.ts +++ b/tools/sync-keycloak.ts @@ -1,10 +1,12 @@ /** - * Push credentials from the environment into an already-imported Keycloak realm. + * Bring an already-imported Keycloak realm up to date. * * 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. + * the admin REST API, along with the account-linking flow and the site's login + * theme. Safe to re-run; run it after the first Keycloak start and after + * upgrades. * * Run with: npm run keycloak:sync */ @@ -42,26 +44,90 @@ export async function syncKeycloak(env: Env = process.env, http: typeof fetch = } 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(); + const googleId = env.GOOGLE_CLIENT_ID?.trim(); + const configured = Boolean(googleId && googleId !== "not-configured"); + await ensureLinkingFlow(api, report); await api(path, { method: "PUT", body: JSON.stringify({ ...provider, - enabled: true, - config: { ...provider.config, clientId: googleId, clientSecret: googleSecret }, + ...(configured && { + enabled: true, + config: { ...provider.config, clientId: googleId, clientSecret: required(env, "GOOGLE_CLIENT_SECRET") }, + }), + // Google sign-in joins the account an e-mail code already created instead + // of asking for a password that account never had. + // The flow has no "review profile" step, so no Keycloak form appears. + firstBrokerLoginFlowAlias: LINKING_FLOW, + trustEmail: true, }), }); - report.push(`identity provider ${alias}: Google client updated and enabled`); + report.push(configured + ? `identity provider ${alias}: Google client updated and enabled` + : `identity provider ${alias}: Google credentials skipped, GOOGLE_CLIENT_ID is not set`); + report.push(`identity provider ${alias}: first sign-in links existing accounts (${LINKING_FLOW})`); + + const themes = await (await adminServerInfo(http, server, token)).themes?.login ?? []; + if (themes.some((theme: { name: string }) => theme.name === LOGIN_THEME)) { + const realmRep = await (await api("")).json(); + if (realmRep.loginTheme !== LOGIN_THEME) await api("", { method: "PUT", body: JSON.stringify({ ...realmRep, loginTheme: LOGIN_THEME }) }); + report.push(`login theme: ${LOGIN_THEME}`); + } else { + report.push(`login theme: ${LOGIN_THEME} is not installed in this Keycloak, keeping the default`); + } return report; } +/** First broker login flow that links a verified Google e-mail to the existing user. */ +export const LINKING_FLOW = "mr-bridge link existing account"; +const LOGIN_THEME = "mr-bridge"; + +type Api = (path: string, init?: RequestInit) => Promise; + +/** + * Keycloak's default first-login flow asks someone whose account already exists + * to confirm it with a password, which accounts created by e-mail sign-in never + * have. This flow creates the user when the e-mail is new and otherwise links + * to the existing one. Safe because Google only returns verified addresses + * (trustEmail) and the app also rejects unverified ones. + */ +async function ensureLinkingFlow(api: Api, report: string[]): Promise { + const flows = await (await api("/authentication/flows")).json() as Array<{ alias: string }>; + const flowPath = `/authentication/flows/${encodeURIComponent(LINKING_FLOW)}/executions`; + if (!flows.some((flow) => flow.alias === LINKING_FLOW)) { + await api("/authentication/flows", { + method: "POST", + body: JSON.stringify({ + alias: LINKING_FLOW, + description: "Create the user if the e-mail is new, otherwise link the existing account. Managed by npm run keycloak:sync.", + providerId: "basic-flow", + topLevel: true, + builtIn: false, + }), + }); + report.push(`flow ${LINKING_FLOW}: created`); + } + for (const provider of ["idp-create-user-if-unique", "idp-auto-link"]) { + const executions = await (await api(flowPath)).json() as Array<{ id: string; providerId: string; requirement: string }>; + let execution = executions.find((item) => item.providerId === provider); + if (!execution) { + await api(`${flowPath}/execution`, { method: "POST", body: JSON.stringify({ provider }) }); + execution = (await (await api(flowPath)).json() as typeof executions).find((item) => item.providerId === provider); + } + if (execution && execution.requirement !== "ALTERNATIVE") { + await api(flowPath, { method: "PUT", body: JSON.stringify({ ...execution, requirement: "ALTERNATIVE" }) }); + } + } +} + +async function adminServerInfo(http: typeof fetch, server: string, token: string) { + const response = await http(`${server}/admin/serverinfo`, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error(`GET /admin/serverinfo failed (${response.status}).`); + return response.json(); +} + 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", From 9632c5f610b056ef83d728d2afde2c3d0197e150 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:06:28 +0530 Subject: [PATCH 04/37] Enforce organizer roles and make roster imports atomic and non-destructive (R14) Roles existed but every organizer could do everything, and imports rewrote people's names, phones and details across organizations in batches that could fail halfway. Roles (domain/shared/organizer-permissions.ts): - Organization owners/admins manage every event in the organization - Event owners/admins configure the event, import and remove attendees - An event "organizer" views, sends invitations and starts matching - Use cases authorize per action; pages hide what the role cannot use (read-only settings, no import or remove controls) - Event lists show only events the viewer may open; organizers of one event may open the list (not the new-event page) Imports (events.importRoster): - One transaction with a per-event lock: all applied or none, and retrying the same file changes nothing - Existing people keep their name, phone and details; the sheet only fills empty fields, and the summary says how many were kept - A new person whose phone belongs to someone else is imported without it instead of failing the whole file - The roster page reports added, already on the roster, skipped, kept and phone conflicts --- .../[orgSlug]/events/[eventSlug]/page.tsx | 8 +- .../events/[eventSlug]/roster/page.tsx | 19 ++- .../orgs/[orgSlug]/events/new/page.tsx | 4 +- .../orgs/[orgSlug]/events/page.tsx | 6 +- apps/web/app/actions/organizer.actions.ts | 6 +- apps/web/lib/session.ts | 8 +- .../src/application/ports/event-repository.ts | 16 ++- .../src/application/use-cases/manage-event.ts | 14 +- .../use-cases/manage-invitations.ts | 9 +- .../domain/shared/organizer-permissions.ts | 45 ++++++ .../src/infrastructure/postgres/event.repo.ts | 19 ++- apps/web/src/lib/auth.ts | 21 ++- packages/db/src/repositories/events.ts | 131 +++++++++++++++++- .../roster-import-ownership.test.ts | 101 ++++++++++++++ tests/unit/invitations.test.ts | 4 +- tests/unit/organizer-permissions.test.ts | 33 +++++ tests/unit/return-access.test.ts | 8 ++ tests/unit/validation.test.ts | 2 +- 18 files changed, 399 insertions(+), 55 deletions(-) create mode 100644 apps/web/src/domain/shared/organizer-permissions.ts create mode 100644 tests/integration/roster-import-ownership.test.ts create mode 100644 tests/unit/organizer-permissions.test.ts 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 86ef671..a032190 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx @@ -10,7 +10,7 @@ export default async function EventDashboardPage({ params, searchParams }: { }) { const { orgSlug, eventSlug } = await params; const notice = await searchParams; - const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); + const { event, container, can } = await requireOrganizerEvent(orgSlug, eventSlug); const analytics = await container.events.analytics(event.id); const action = updateEventAction.bind(null, orgSlug, eventSlug); return
@@ -31,9 +31,11 @@ export default async function EventDashboardPage({ params, searchParams }: {

Event setup

{notice.saved &&

Event configuration saved.

} - + }} /> :

+ Registration is {event.status}. Only event owners and admins can change this event's settings. +

}
; } 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 f91d9f8..4ef91fb 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 @@ -20,11 +20,14 @@ const when = (value: Date | null) => value ? value.toLocaleString("en-IN", { dat export default async function RosterPage({ params, searchParams }: { params: Promise<{ orgSlug: string; eventSlug: string }>; - searchParams: Promise<{ imported?: string; skipped?: string; invited?: string; failed?: string; access?: string }>; + searchParams: Promise<{ + imported?: string; skipped?: string; already?: string; kept?: string; phones?: string; + invited?: string; failed?: string; access?: string; + }>; }) { const { orgSlug, eventSlug } = await params; const query = await searchParams; - const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); + const { event, container, can } = await requireOrganizerEvent(orgSlug, eventSlug); const roster = (await container.events.roster(event.id)).map((person) => { const facts = { revokedAt: date(person.revoked_at), profileUpdatedAt: date(person.profile_updated_at), claimedAt: date(person.claimed_at), @@ -41,7 +44,10 @@ export default async function RosterPage({ params, searchParams }: {

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

{query.imported &&

Added {query.imported} attendee(s) to this event. + {Number(query.already) > 0 && ` ${query.already} were already on the roster.`} {Number(query.skipped) > 0 && ` Skipped ${query.skipped} row(s) with a missing or invalid e-mail, or an e-mail/phone repeated in the file.`} + {Number(query.kept) > 0 && ` Kept the existing name, phone or details of ${query.kept} people already registered (they can update their own profile).`} + {Number(query.phones) > 0 && ` ${query.phones} new people were added without their phone, because it already belongs to someone else.`}

} {query.invited &&

0 ? "form-alert" : "notice"}> Sent {query.invited} invitation(s).{Number(query.failed) > 0 && ` ${query.failed} could not be delivered; see the roster for the reason.`} @@ -49,11 +55,12 @@ export default async function RosterPage({ params, searchParams }: { {query.access &&

{query.access === "removed" ? "Access removed. They are signed out of this event and no longer appear in anyone's results." : "Access restored."}

} - + {can("importRoster") ? + :

Only event owners and admins can import attendees or remove access.

} {roster.length > 0 &&
{(Object.keys(STATE_LABELS) as InvitationState[]).filter((state) => counts[state]).map((state) => {counts[state]} {STATE_LABELS[state].toLowerCase()})} - {pending > 0 && 0 && can("invite") && }
} {!roster.length ?

No attendees yet. Import an Excel roster to invite people to this event.

: @@ -71,9 +78,9 @@ export default async function RosterPage({ params, searchParams }: {
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 8ddcc5e..dafbb6f 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx @@ -6,8 +6,8 @@ import { NewEventForm } from "@/components/organizer/EventForms"; export default async function NewEventPage({ params }: { params: Promise<{ orgSlug: string }> }) { const { orgSlug } = await params; - const { organization, container } = await requireOrganizationMember(orgSlug, `/orgs/${orgSlug}/events/new`); - const existing = await container.events.listForOrganization(orgSlug); + const { session, organization, container } = await requireOrganizationMember(orgSlug, `/orgs/${orgSlug}/events/new`); + const existing = await container.events.listForOrganization(orgSlug, session.attendeeId); const create = createEventAction.bind(null, orgSlug); return
← Organizer diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx index ce1f3d0..bad065f 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx @@ -4,13 +4,13 @@ import { requireOrganizationMember } from "@/src/lib/auth"; export default async function OrganizationEventsPage({ params }: { params: Promise<{ orgSlug: string }> }) { const { orgSlug } = await params; - const { organization, container } = await requireOrganizationMember(orgSlug); - const events = await container.events.listForOrganization(orgSlug); + const { session, organization, container, isMember } = await requireOrganizationMember(orgSlug, `/orgs/${orgSlug}/events`, { allowEventOrganizers: true }); + const events = await container.events.listForOrganization(orgSlug, session.attendeeId); return
ORGANIZER

{organization.name} events

- Create event + {isMember && Create event}
{events.map((event) => {event.name}{event.status}{event.description} diff --git a/apps/web/app/actions/organizer.actions.ts b/apps/web/app/actions/organizer.actions.ts index a6703ac..03e0755 100644 --- a/apps/web/app/actions/organizer.actions.ts +++ b/apps/web/app/actions/organizer.actions.ts @@ -43,7 +43,11 @@ async function importRoster(organizationSlug: string, eventSlug: string, formDat if (!event) throw new Error("Event not found"); const { records, skipped } = parseRosterWorkbook(await file.arrayBuffer()); const result = await importEventRoster({ eventId: event.id, organizerId: session.attendeeId, records }, container.events); - redirect(`/orgs/${organizationSlug}/events/${eventSlug}/roster?imported=${result.attached}&skipped=${skipped}`); + const report = new URLSearchParams({ + imported: String(result.attached), skipped: String(skipped), already: String(result.alreadyOnRoster), + kept: String(result.keptExisting), phones: String(result.phoneConflicts), + }); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}/roster?${report}`); } export async function updateEventAction(organizationSlug: string, eventSlug: string, _state: FormState, formData: FormData): Promise { diff --git a/apps/web/lib/session.ts b/apps/web/lib/session.ts index 793a229..e18c544 100644 --- a/apps/web/lib/session.ts +++ b/apps/web/lib/session.ts @@ -81,8 +81,12 @@ export async function canReturnToPath(returnTo: string | null | undefined, atten 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 organizationRoute = returnTo.match(/^\/orgs\/([^/]+)\/events(\/new)?\/?$/); + if (organizationRoute) { + if (await events.hasOrganizationAccess(organizationRoute[1], attendeeId)) return true; + // Organizers of one event may open the list (not the new-event page). + return !organizationRoute[2] && (await events.listForOrganization(organizationRoute[1], attendeeId)).length > 0; + } const organizerRoute = returnTo.match(/^\/orgs\/([^/]+)\/events\/([^/]+)(?:\/|$)/); if (organizerRoute) { const event = await events.findBySlug(organizerRoute[1], organizerRoute[2]); diff --git a/apps/web/src/application/ports/event-repository.ts b/apps/web/src/application/ports/event-repository.ts index e13dfb4..f3e562b 100644 --- a/apps/web/src/application/ports/event-repository.ts +++ b/apps/web/src/application/ports/event-repository.ts @@ -1,3 +1,5 @@ +import type { OrganizerRoles } from "../../domain/shared/organizer-permissions"; + export interface EventRecord { id: string; organization_id: string; @@ -25,11 +27,21 @@ export interface RosterAttendeeInput { most_impressive_build: string | null; } +export interface RosterImportResult { + created: number; + attached: number; + alreadyOnRoster: number; + keptExisting: number; + phoneConflicts: number; +} + export interface EventRepository { findBySlug(organizationSlug: string, eventSlug: string): Promise; findByEventSlug(eventSlug: string): Promise; findOrganization(slug: string): Promise<{ id: string; name: string; slug: string } | null>; - listForOrganization(organizationSlug: string): Promise; + /** With viewerId, only the events that person may open. */ + listForOrganization(organizationSlug: string, viewerId?: string): Promise; + organizerRoles(eventId: string, attendeeId: string): Promise; hasOrganizationAccess(organizationSlug: string, attendeeId: string): Promise; isOrganizer(eventId: string, attendeeId: string): Promise; create(input: { organizationId: string; organizerId: string; name: string; slug: string; description?: string | null }): Promise; @@ -37,7 +49,7 @@ export interface EventRepository { roster(eventId: string): Promise>>; attachRoster(eventId: string, attendeeIds: string[]): Promise; participantIds(eventId: string): Promise; - importRoster(eventId: string, records: RosterAttendeeInput[]): Promise<{ upserted: number; attached: number }>; + importRoster(eventId: string, records: RosterAttendeeInput[]): Promise; analytics(eventId: string): Promise<{ roster: number; invited: number; claimed: number; profiles: number; removed: number; matches: number; pendingIntros: number; acceptedIntros: number; diff --git a/apps/web/src/application/use-cases/manage-event.ts b/apps/web/src/application/use-cases/manage-event.ts index 81e1f13..afc0c8f 100644 --- a/apps/web/src/application/use-cases/manage-event.ts +++ b/apps/web/src/application/use-cases/manage-event.ts @@ -2,6 +2,12 @@ import type { EventRepository, RosterAttendeeInput } from "../ports/event-reposi import { slugify } from "../../domain/shared/value-objects"; import { Intent } from "../../domain/participant/intent"; import { boundedItems, boundedText, LIMITS, ValidationError } from "../../domain/shared/validation"; +import { assertOrganizerCan, type OrganizerAction } from "../../domain/shared/organizer-permissions"; + +/** Throws unless the attendee's role on the event allows the action. */ +export async function authorizeOrganizer(events: EventRepository, eventId: string, attendeeId: string, action: OrganizerAction): Promise { + assertOrganizerCan(await events.organizerRoles(eventId, attendeeId), action); +} export async function createEvent(input: { organizationSlug: string; organizerId: string; name: string; slug?: string; description?: string }, events: EventRepository) { const organization = await events.findOrganization(input.organizationSlug); @@ -23,7 +29,7 @@ export async function updateEvent(input: { intents?: string[]; zones?: string[]; }, events: EventRepository) { - if (!(await events.isOrganizer(input.eventId, input.organizerId))) throw new Error("You are not an organizer for this event"); + await authorizeOrganizer(events, input.eventId, input.organizerId, "configure"); const updated = await events.update({ ...input, name: input.name === undefined ? undefined : eventName(input.name)!, @@ -38,13 +44,13 @@ export async function updateEvent(input: { } export async function importEventRoster(input: { eventId: string; organizerId: string; records: RosterAttendeeInput[] }, events: EventRepository) { - if (!(await events.isOrganizer(input.eventId, input.organizerId))) throw new Error("You are not an organizer for this event"); - if (!input.records.length) return { upserted: 0, attached: 0 }; + await authorizeOrganizer(events, input.eventId, input.organizerId, "importRoster"); + if (!input.records.length) return { created: 0, attached: 0, alreadyOnRoster: 0, keptExisting: 0, phoneConflicts: 0 }; return events.importRoster(input.eventId, input.records); } export async function queueEventMatches(input: { eventId: string; organizerId: string }, events: EventRepository, enqueue: (eventId: string, participantId: string) => Promise) { - if (!(await events.isOrganizer(input.eventId, input.organizerId))) throw new Error("You are not an organizer for this event"); + await authorizeOrganizer(events, input.eventId, input.organizerId, "computeMatches"); const participants = await events.participantIds(input.eventId); for (const participantId of participants) await enqueue(input.eventId, participantId); return participants.length; diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts index d409e54..869c987 100644 --- a/apps/web/src/application/use-cases/manage-invitations.ts +++ b/apps/web/src/application/use-cases/manage-invitations.ts @@ -1,6 +1,7 @@ import { RESEND_AFTER_MINUTES } from "../../domain/participant/invitation"; import type { EventRepository } from "../ports/event-repository"; import type { NotificationPort } from "../ports/notification"; +import { authorizeOrganizer } from "./manage-event"; export interface InvitationResult { sent: number; @@ -16,7 +17,7 @@ export async function sendInvitations( input: { eventId: string; organizerId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string }, dependencies: { events: EventRepository; notifications: NotificationPort } ): Promise { - await assertOrganizer(input.eventId, input.organizerId, dependencies.events); + await authorizeOrganizer(dependencies.events, input.eventId, input.organizerId, "invite"); 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.`); @@ -51,12 +52,8 @@ export async function setAttendeeAccess( input: { eventId: string; organizerId: string; attendeeId: string; revoked: boolean }, dependencies: { events: EventRepository } ): Promise { - await assertOrganizer(input.eventId, input.organizerId, dependencies.events); + await authorizeOrganizer(dependencies.events, input.eventId, input.organizerId, "manageAccess"); if (!(await dependencies.events.setRevoked(input.eventId, input.attendeeId, input.revoked))) { throw new Error("This attendee is not on the event roster"); } } - -async function assertOrganizer(eventId: string, organizerId: string, events: EventRepository): Promise { - if (!(await events.isOrganizer(eventId, organizerId))) throw new Error("You are not an organizer for this event"); -} diff --git a/apps/web/src/domain/shared/organizer-permissions.ts b/apps/web/src/domain/shared/organizer-permissions.ts new file mode 100644 index 0000000..b21db4b --- /dev/null +++ b/apps/web/src/domain/shared/organizer-permissions.ts @@ -0,0 +1,45 @@ +/** + * What each organizer role may do with an event. Organization owners and + * admins manage every event in their organization; on a single event, owners + * and admins configure it and control its roster, while an "organizer" runs + * it day to day (view, invite, start matching). + */ +export type OrganizerRole = "owner" | "admin" | "organizer"; + +export type OrganizerAction = "view" | "invite" | "computeMatches" | "configure" | "importRoster" | "manageAccess"; + +export interface OrganizerRoles { + event: OrganizerRole | null; + organization: OrganizerRole | null; +} + +const DAY_TO_DAY: readonly OrganizerAction[] = ["view", "invite", "computeMatches"]; + +const isManager = (role: OrganizerRole | null) => role === "owner" || role === "admin"; + +export function organizerCan(roles: OrganizerRoles, action: OrganizerAction): boolean { + if (isManager(roles.organization)) return true; + if (!roles.event) return false; + return DAY_TO_DAY.includes(action) || isManager(roles.event); +} + +/** Any member of an organization may create an event, and becomes its owner. */ +export function canCreateEvent(organizationRole: OrganizerRole | null): boolean { + return organizationRole !== null; +} + +const LABELS: Record = { + view: "view this event", + invite: "send invitations", + computeMatches: "start matching", + configure: "change this event's settings", + importRoster: "import attendees", + manageAccess: "remove or restore attendees", +}; + +export function assertOrganizerCan(roles: OrganizerRoles, action: OrganizerAction): void { + if (organizerCan(roles, action)) return; + throw new Error(roles.event || roles.organization + ? `Only event owners and admins can ${LABELS[action]}.` + : "You are not an organizer for this event"); +} diff --git a/apps/web/src/infrastructure/postgres/event.repo.ts b/apps/web/src/infrastructure/postgres/event.repo.ts index cc1f2a7..f48ce7a 100644 --- a/apps/web/src/infrastructure/postgres/event.repo.ts +++ b/apps/web/src/infrastructure/postgres/event.repo.ts @@ -1,4 +1,4 @@ -import { attendees, events, query } from "@match-maker/db"; +import { events, query } from "@match-maker/db"; import type { EventRepository, EventRecord } from "../../application/ports/event-repository"; export class PostgresEventRepository implements EventRepository { @@ -11,8 +11,11 @@ export class PostgresEventRepository implements EventRepository { findOrganization(slug: string) { return events.findOrganization(slug); } - listForOrganization(organizationSlug: string) { - return events.listForOrganization(organizationSlug); + listForOrganization(organizationSlug: string, viewerId?: string) { + return events.listForOrganization(organizationSlug, viewerId); + } + organizerRoles(eventId: string, attendeeId: string) { + return events.organizerRoles(eventId, attendeeId); } hasOrganizationAccess(organizationSlug: string, attendeeId: string) { return events.hasOrganizationAccess(organizationSlug, attendeeId); @@ -53,14 +56,8 @@ export class PostgresEventRepository implements EventRepository { return events.rosterState(eventId, attendeeId); } - async importRoster(eventId: string, records: Parameters[1]) { - let upserted = 0; - for (let offset = 0; offset < records.length; offset += 100) { - upserted += await attendees.upsertMany(records.slice(offset, offset + 100)); - } - const rows = await attendees.findIdsByEmails(records.map((record) => record.email)); - const attached = await events.attachRoster(eventId, rows.map((row) => row.id)); - return { upserted, attached }; + importRoster(eventId: string, records: Parameters[1]) { + return events.importRoster(eventId, records); } async analytics(eventId: string) { diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index fe6d58a..668e678 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -2,6 +2,7 @@ import { notFound, redirect } from "next/navigation"; import { getSession } from "../../lib/session"; import { getContainer } from "../composition/container"; import { eventAllows, type EventAction } from "../domain/shared/event-lifecycle"; +import { organizerCan, type OrganizerAction } from "../domain/shared/organizer-permissions"; /** With `action`, a page the event status does not allow sends the participant to the event landing page, which explains why. */ export async function requireParticipantEvent(eventSlug: string, returnPath?: string, action?: EventAction) { @@ -25,16 +26,26 @@ export async function requireOrganizerEvent(orgSlug: string, eventSlug: string, if (!session) redirect(`/login?returnTo=${encodeURIComponent(target)}`); const container = getContainer(); const event = await container.events.findBySlug(orgSlug, eventSlug); - if (!event || !(await container.events.isOrganizer(event.id, session.attendeeId))) notFound(); - return { session, event, container }; + if (!event) notFound(); + const roles = await container.events.organizerRoles(event.id, session.attendeeId); + if (!organizerCan(roles, "view")) notFound(); + const can = (action: OrganizerAction) => organizerCan(roles, action); + return { session, event, container, can }; } -export async function requireOrganizationMember(orgSlug: string, returnPath?: string) { +/** + * Organization pages. Members always get in; with `allowEventOrganizers`, so do + * people who organize one of its events without being members (they see only + * their events). `isMember` says whether they may create events. + */ +export async function requireOrganizationMember(orgSlug: string, returnPath?: string, options: { allowEventOrganizers?: boolean } = {}) { const target = returnPath || `/orgs/${orgSlug}/events/new`; const session = await getSession(); if (!session) redirect(`/login?returnTo=${encodeURIComponent(target)}`); const container = getContainer(); const organization = await container.events.findOrganization(orgSlug); - if (!organization || !(await container.events.hasOrganizationAccess(orgSlug, session.attendeeId))) notFound(); - return { session, organization, container }; + if (!organization) notFound(); + const isMember = await container.events.hasOrganizationAccess(orgSlug, session.attendeeId); + if (!isMember && !(options.allowEventOrganizers && (await container.events.listForOrganization(orgSlug, session.attendeeId)).length)) notFound(); + return { session, organization, container, isMember }; } diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index a2023e2..17d6ed1 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -35,11 +35,37 @@ export async function findOrganization(slug: string): Promise<{ id: string; name return rows[0] ?? null; } -export async function listForOrganization(orgSlug: string): Promise { - const { rows } = await query(`${EVENT_SELECT} where o.slug = $1 order by e.created_at desc`, [orgSlug]); +/** + * The organization's events. With a viewer, only those they may open: + * everything for organization owners and admins, otherwise their own events. + */ +export async function listForOrganization(orgSlug: string, viewerId?: string): Promise { + const { rows } = await query( + `${EVENT_SELECT} + where o.slug = $1 + and ($2::uuid is null + or exists (select 1 from organization_members m + where m.organization_id = o.id and m.attendee_id = $2 and m.role in ('owner', 'admin')) + or exists (select 1 from event_organizers eo where eo.event_id = e.id and eo.attendee_id = $2)) + order by e.created_at desc`, + [orgSlug, viewerId ?? null] + ); return rows; } +export type OrganizerRole = "owner" | "admin" | "organizer"; + +/** The attendee's role on the event and in its organization (null when none). */ +export async function organizerRoles(eventId: string, attendeeId: string): Promise<{ event: OrganizerRole | null; organization: OrganizerRole | null }> { + const { rows } = await query<{ event_role: OrganizerRole | null; organization_role: OrganizerRole | null }>( + `select (select role from event_organizers where event_id = $1 and attendee_id = $2) as event_role, + (select m.role from organization_members m join events e on e.organization_id = m.organization_id + where e.id = $1 and m.attendee_id = $2) as organization_role`, + [eventId, attendeeId] + ); + return { event: rows[0]?.event_role ?? null, organization: rows[0]?.organization_role ?? null }; +} + export async function create(input: { organizationId: string; organizerId: string; @@ -103,12 +129,10 @@ export async function statusOf(eventId: string): Promise { - const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_organizers where event_id = $1 and attendee_id = $2) as allowed`, - [eventId, attendeeId] - ); - return rows[0]?.allowed ?? false; + const roles = await organizerRoles(eventId, attendeeId); + return roles.event !== null || roles.organization === "owner" || roles.organization === "admin"; } export async function isParticipant(eventId: string, attendeeId: string): Promise { @@ -231,3 +255,96 @@ export async function rosterState(eventId: string, attendeeId: string): Promise< if (!rows[0]) return null; return rows[0].revoked ? "revoked" : "active"; } + +export interface RosterRow { + name: string | null; + email: string; + phone: string | null; + about_me: string | null; + designation: string | null; + domain: string | null; + self_description: string | null; + years_of_experience: number | null; + most_impressive_build: string | null; +} + +export interface RosterImportResult { + /** People not known before this import. */ + created: number; + /** People newly added to this event (created or already known). */ + attached: number; + /** People already on this event's roster. */ + alreadyOnRoster: number; + /** Known people whose existing details differ from the sheet and were kept. */ + keptExisting: number; + /** New people whose phone already belongs to someone else; imported without it. */ + phoneConflicts: number; +} + +const DETAIL_COLUMNS = ["name", "phone", "about_me", "designation", "domain", "self_description", "years_of_experience", "most_impressive_build"] as const; + +/** + * Imports a validated roster in one transaction, so a failure leaves nothing + * half-applied and retrying the same file is safe. + * + * People are identified by e-mail and shared across organizations, so an + * import never replaces anyone's existing name, phone or details: it only + * fills fields that are empty. A phone that already belongs to someone else + * is left off the new person instead of failing the whole import. + */ +export async function importRoster(eventId: string, rows: RosterRow[]): Promise { + return transaction(async (client) => { + await client.query(`select pg_advisory_xact_lock(hashtext('roster-import:' || $1))`, [eventId]); + const result: RosterImportResult = { created: 0, attached: 0, alreadyOnRoster: 0, keptExisting: 0, phoneConflicts: 0 }; + if (!rows.length) return result; + + const emails = rows.map((row) => row.email); + const phones = rows.map((row) => row.phone).filter((phone): phone is string => Boolean(phone)); + const { rows: known } = await client.query( + `select id, ${DETAIL_COLUMNS.join(", ")}, email from registered_attendees + where email = any($1::text[]) or phone = any($2::text[])`, + [emails, phones] + ); + const byEmail = new Map(known.filter((row) => row.email).map((row) => [row.email, row])); + const phoneOwner = new Map(known.filter((row) => row.phone).map((row) => [row.phone!, row.email])); + + for (const row of rows) { + const existing = byEmail.get(row.email); + if (existing) { + if (DETAIL_COLUMNS.some((column) => row[column] != null && existing[column] != null && String(row[column]) !== String(existing[column]))) { + result.keptExisting += 1; + } + const freePhone = row.phone && !existing.phone && !phoneOwner.has(row.phone) ? row.phone : null; + await client.query( + `update registered_attendees set + ${DETAIL_COLUMNS.map((column, index) => `${column} = coalesce(${column}, $${index + 2})`).join(", ")}, + updated_at = now() + where id = $1`, + [existing.id, ...DETAIL_COLUMNS.map((column) => column === "phone" ? freePhone : row[column])] + ); + if (freePhone) phoneOwner.set(freePhone, row.email); + continue; + } + const phoneTaken = Boolean(row.phone && phoneOwner.has(row.phone)); + if (phoneTaken) result.phoneConflicts += 1; + const columns = ["email", ...DETAIL_COLUMNS]; + await client.query( + `insert into registered_attendees (${columns.join(", ")}) values (${columns.map((_, index) => `$${index + 1}`).join(", ")})`, + [row.email, ...DETAIL_COLUMNS.map((column) => column === "phone" && phoneTaken ? null : row[column])] + ); + if (row.phone && !phoneTaken) phoneOwner.set(row.phone, row.email); + result.created += 1; + } + + const { rows: attached } = await client.query<{ attached: boolean }>( + `insert into event_participants (event_id, attendee_id) + select $1, a.id from registered_attendees a where a.email = any($2::text[]) + on conflict (event_id, attendee_id) do nothing + returning true as attached`, + [eventId, emails] + ); + result.attached = attached.length; + result.alreadyOnRoster = new Set(emails).size - attached.length; + return result; + }); +} diff --git a/tests/integration/roster-import-ownership.test.ts b/tests/integration/roster-import-ownership.test.ts new file mode 100644 index 0000000..26d7348 --- /dev/null +++ b/tests/integration/roster-import-ownership.test.ts @@ -0,0 +1,101 @@ +/** + * Organizer roles and roster import ownership against a real Postgres. Uses + * two organizations of its own. Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { attendees, closePool, events, query } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const RUN = Date.now().toString(36); +const ORG_A = `ownership-a-${RUN}`; +const ORG_B = `ownership-b-${RUN}`; +const email = (key: string) => `ownership-${key}-${RUN}@example.com`; +const PHONE_KEPT = `+9196${RUN.slice(-8).padStart(8, "0").replace(/\D/g, "7")}`; + +const row = (key: string, overrides: Record = {}) => ({ + name: `Sheet ${key}`, email: email(key), phone: null, about_me: null, designation: null, domain: null, + self_description: null, years_of_experience: null, most_impressive_build: null, ...overrides, +}); + +describeDb("organizer roles and roster import ownership", () => { + const ids: Record = {}; + let eventA: string; + let eventA2: string; + let eventB: string; + + async function org(slug: string) { + const { rows: [created] } = await query<{ id: string }>(`insert into organizations (name, slug) values ($1, $1) returning id`, [slug]); + return created.id; + } + + beforeAll(async () => { + await migrate(); + // An attendee organization A already registered, with a name and phone. + await attendees.upsertMany([ + { name: "Original Name", email: email("shared"), phone: PHONE_KEPT, designation: "Engineer" }, + { name: "Org Admin", email: email("admin") }, + { name: "Event Helper", email: email("helper") }, + { name: "Org Member", email: email("member") }, + ]); + for (const key of ["shared", "admin", "helper", "member"]) ids[key] = (await attendees.findByEmail(email(key)))!.id; + const orgA = await org(ORG_A); + const orgB = await org(ORG_B); + await query(`insert into organization_members (organization_id, attendee_id, role) values ($1, $2, 'admin'), ($1, $3, 'organizer'), ($1, $4, 'organizer')`, + [orgA, ids.admin, ids.helper, ids.member]); + eventA = (await events.create({ organizationId: orgA, organizerId: ids.member, name: "A one", slug: `${ORG_A}-one` })).id; + eventA2 = (await events.create({ organizationId: orgA, organizerId: ids.admin, name: "A two", slug: `${ORG_A}-two` })).id; + await query(`insert into event_organizers (event_id, attendee_id, role) values ($1, $2, 'organizer')`, [eventA, ids.helper]); + eventB = (await query<{ id: string }>(`insert into events (organization_id, name, slug) values ($1, 'B', $2) returning id`, [orgB, `${ORG_B}-one`])).rows[0].id; + await events.attachRoster(eventA, [ids.shared]); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = any($1::text[])`, [[ORG_A, ORG_B]]); + await query(`delete from registered_attendees where email like $1`, [`ownership-%-${RUN}@example.com`]); + await closePool(); + }); + + it("gives each role the right reach", async () => { + expect(await events.organizerRoles(eventA, ids.helper)).toEqual({ event: "organizer", organization: "organizer" }); + expect(await events.isOrganizer(eventA2, ids.admin)).toBe(true); + expect(await events.isOrganizer(eventA, ids.admin)).toBe(true); + expect(await events.isOrganizer(eventA2, ids.member)).toBe(false); + expect(await events.isOrganizer(eventB, ids.admin)).toBe(false); + }); + + it("lists only the events a viewer may open", async () => { + const slugs = async (viewer: string) => (await events.listForOrganization(ORG_A, viewer)).map((event) => event.slug).sort(); + expect(await slugs(ids.admin)).toEqual([`${ORG_A}-one`, `${ORG_A}-two`]); + expect(await slugs(ids.member)).toEqual([`${ORG_A}-one`]); + }); + + it("never replaces an existing person's details from another organization's sheet", async () => { + const result = await events.importRoster(eventB, [ + row("shared", { name: "Hijacked Name", phone: "+919000000001", designation: "Attacker" }), + row("fresh", { phone: PHONE_KEPT }), + ]); + expect(result).toEqual({ created: 1, attached: 2, alreadyOnRoster: 0, keptExisting: 1, phoneConflicts: 1 }); + const shared = (await attendees.findByEmail(email("shared")))!; + expect(shared).toMatchObject({ name: "Original Name", phone: PHONE_KEPT, designation: "Engineer" }); + const fresh = (await attendees.findByEmail(email("fresh")))!; + expect(fresh.phone).toBeNull(); + }); + + it("fills only empty fields of a known person", async () => { + await events.importRoster(eventB, [row("fresh", { domain: "Climate", name: "Different" })]); + expect(await attendees.findByEmail(email("fresh"))).toMatchObject({ name: "Sheet fresh", domain: "Climate" }); + }); + + it("is safe to retry", async () => { + const result = await events.importRoster(eventB, [row("shared"), row("fresh")]); + expect(result).toMatchObject({ created: 0, attached: 0, alreadyOnRoster: 2 }); + }); + + it("applies nothing when any row fails", async () => { + await expect(events.importRoster(eventA2, [row("rollback-ok"), row("rollback-bad", { years_of_experience: "not a number" })])).rejects.toThrow(); + expect(await attendees.findByEmail(email("rollback-ok"))).toBeNull(); + const { rows } = await query(`select 1 from event_participants where event_id = $1`, [eventA2]); + expect(rows).toHaveLength(0); + }); +}); diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts index 4b1426e..35c176b 100644 --- a/tests/unit/invitations.test.ts +++ b/tests/unit/invitations.test.ts @@ -35,7 +35,7 @@ function ports(targets: Array<{ attendee_id: string; email: string; name: string invitationTargets: vi.fn().mockResolvedValue(targets), recordInvitation: vi.fn().mockResolvedValue(undefined), setRevoked: vi.fn().mockResolvedValue(true), - isOrganizer: vi.fn().mockResolvedValue(true), + organizerRoles: vi.fn().mockResolvedValue({ event: "owner", organization: null }), }; const notifications = { invitation: vi.fn(async ({ email }: { email: string }) => { @@ -76,7 +76,7 @@ describe("setAttendeeAccess", () => { it("refuses anyone who is not an organizer of the event", async () => { const { events, notifications, raw } = ports([{ attendee_id: "a", email: "a@example.com", name: "A" }]); - raw.events.isOrganizer.mockResolvedValue(false); + raw.events.organizerRoles.mockResolvedValue({ event: null, organization: null }); await expect(setAttendeeAccess({ eventId: "event", organizerId: "x", attendeeId: "a", revoked: true }, { events })).rejects.toThrow(/not an organizer/); await expect(sendInvitations({ ...event, organizerId: "x" }, { events, notifications })).rejects.toThrow(/not an organizer/); expect(raw.events.setRevoked).not.toHaveBeenCalled(); diff --git a/tests/unit/organizer-permissions.test.ts b/tests/unit/organizer-permissions.test.ts new file mode 100644 index 0000000..4d83028 --- /dev/null +++ b/tests/unit/organizer-permissions.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { assertOrganizerCan, canCreateEvent, organizerCan, type OrganizerAction, type OrganizerRole } from "@/src/domain/shared/organizer-permissions"; + +const ACTIONS: OrganizerAction[] = ["view", "invite", "computeMatches", "configure", "importRoster", "manageAccess"]; +type Row = [string, OrganizerRole | null, OrganizerRole | null, OrganizerAction[]]; + +const POLICY: Row[] = [ + ["organization owner", null, "owner", ACTIONS], + ["organization admin", null, "admin", ACTIONS], + ["organization organizer without an event role", null, "organizer", []], + ["event owner", "owner", "organizer", ACTIONS], + ["event admin", "admin", null, ACTIONS], + ["event organizer", "organizer", "organizer", ["view", "invite", "computeMatches"]], + ["nobody", null, null, []], +]; + +describe("organizer permissions", () => { + it.each(POLICY)("%s", (_label, event, organization, allowed) => { + for (const action of ACTIONS) { + expect(organizerCan({ event, organization }, action), action).toBe(allowed.includes(action)); + } + }); + + it("lets any organization member create events", () => { + expect(canCreateEvent("organizer")).toBe(true); + expect(canCreateEvent(null)).toBe(false); + }); + + it("explains a refusal by role", () => { + expect(() => assertOrganizerCan({ event: "organizer", organization: null }, "importRoster")).toThrow("Only event owners and admins can import attendees."); + expect(() => assertOrganizerCan({ event: null, organization: null }, "view")).toThrow("You are not an organizer for this event"); + }); +}); diff --git a/tests/unit/return-access.test.ts b/tests/unit/return-access.test.ts index 4c3af22..ac19991 100644 --- a/tests/unit/return-access.test.ts +++ b/tests/unit/return-access.test.ts @@ -2,6 +2,7 @@ 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(), + listForOrganization: vi.fn(), })); const accountState = vi.hoisted(() => vi.fn()); vi.mock("@match-maker/db", () => ({ events: mocks, attendees: { accountState } })); @@ -30,6 +31,13 @@ describe("canReturnToPath", () => { expect(mocks.findBySlug).not.toHaveBeenCalled(); }); + it("lets an organizer of one event open the event list, but not create events", async () => { + mocks.hasOrganizationAccess.mockResolvedValue(false); + mocks.listForOrganization.mockResolvedValue([{ id: "event" }]); + await expect(canReturnToPath("/orgs/acme/events", "helper")).resolves.toBe(true); + await expect(canReturnToPath("/orgs/acme/events/new", "helper")).resolves.toBe(false); + }); + it("refuses someone outside the organization", async () => { mocks.hasOrganizationAccess.mockResolvedValue(false); await expect(canReturnToPath("/orgs/acme/events/new", "stranger")).resolves.toBe(false); diff --git a/tests/unit/validation.test.ts b/tests/unit/validation.test.ts index d5b365b..8131d0c 100644 --- a/tests/unit/validation.test.ts +++ b/tests/unit/validation.test.ts @@ -72,7 +72,7 @@ describe("event settings", () => { const events = { findOrganization: vi.fn(async () => ({ id: "org" })), hasOrganizationAccess: vi.fn(async () => true), - isOrganizer: vi.fn(async () => true), + organizerRoles: vi.fn(async () => ({ event: "owner", organization: null })), create: vi.fn(async (record) => record), update: vi.fn(async (record) => record), } as unknown as EventRepository; From 0405de5d07e09cc7e3763d50165f1dea6acf300f Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:07:37 +0530 Subject: [PATCH 05/37] bug fixx-org-admin-cannot-save-event-settings R14 lets organization owners and admins configure every event in their organization, but events.update still required an event_organizers row in its own SQL, so an organization admin who did not create the event got "Event not found" when saving its settings. The query now applies the same rule as the use case. Covered by a real-Postgres test that fails on the old query. --- packages/db/src/repositories/events.ts | 5 ++++- tests/integration/roster-import-ownership.test.ts | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 17d6ed1..97b8ede 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -104,7 +104,10 @@ export async function update(input: { }): Promise { const { rows } = await query( `${EVENT_SELECT} - where e.id = $1 and exists (select 1 from event_organizers eo where eo.event_id = e.id and eo.attendee_id = $2) + where e.id = $1 + and (exists (select 1 from event_organizers eo where eo.event_id = e.id and eo.attendee_id = $2) + or exists (select 1 from organization_members m + where m.organization_id = e.organization_id and m.attendee_id = $2 and m.role in ('owner', 'admin'))) limit 1`, [input.eventId, input.organizerId] ); diff --git a/tests/integration/roster-import-ownership.test.ts b/tests/integration/roster-import-ownership.test.ts index 26d7348..e908785 100644 --- a/tests/integration/roster-import-ownership.test.ts +++ b/tests/integration/roster-import-ownership.test.ts @@ -64,6 +64,12 @@ describeDb("organizer roles and roster import ownership", () => { expect(await events.isOrganizer(eventB, ids.admin)).toBe(false); }); + it("lets an organization admin save settings of an event they did not create", async () => { + const updated = await events.update({ eventId: eventA, organizerId: ids.admin, zones: ["Hall"] }); + expect(updated?.zones).toEqual(["Hall"]); + expect(await events.update({ eventId: eventA2, organizerId: ids.member, zones: ["Nope"] })).toBeNull(); + }); + it("lists only the events a viewer may open", async () => { const slugs = async (viewer: string) => (await events.listForOrganization(ORG_A, viewer)).map((event) => event.slug).sort(); expect(await slugs(ids.admin)).toEqual([`${ORG_A}-one`, `${ORG_A}-two`]); From 8e00648526f60a07185af60fbe712692e479b359 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:12:08 +0530 Subject: [PATCH 06/37] Let organizers configure the participant profile form (R15) events.form_config existed, but the participant form was fixed. - domain/participant/profile-form.ts: a catalog of the profile fields matching already reads (role, domain, about, focus, build, years, interests). Per event, organizers set each field's label, whether it is shown and whether it is required. A required field must be shown, and at least one descriptive field stays required so matching always has text. Each save bumps the form version - Organizer dashboard: "Profile form" settings (owners/admins); errors keep the edits on screen - The participant form renders from the config, and the server validates against the same config with its labels - Hidden fields keep what was saved before, and every stored field still feeds matching, so changing the form never wipes profiles or changes embeddings - Migration 0008: profile_form_version per participant; someone saved under an older form is asked for newly required answers, while their matches keep working --- .../[orgSlug]/events/[eventSlug]/page.tsx | 12 ++- .../e/[eventSlug]/profile/page.tsx | 9 ++- apps/web/app/actions/organizer.actions.ts | 20 ++++- apps/web/app/actions/participant.actions.ts | 3 +- .../organizer/ProfileFormSettings.tsx | 40 ++++++++++ .../components/participant/ProfileForm.tsx | 32 ++++---- .../src/application/use-cases/manage-event.ts | 13 ++++ .../use-cases/upsert-participant.ts | 15 +++- .../domain/participant/participant.entity.ts | 27 +++++-- .../src/domain/participant/profile-form.ts | 76 ++++++++++++++++++ .../postgres/participant.repo.ts | 8 +- .../migrations/0008_profile_form_version.sql | 8 ++ tests/unit/profile-form.test.ts | 78 +++++++++++++++++++ 13 files changed, 311 insertions(+), 30 deletions(-) create mode 100644 apps/web/components/organizer/ProfileFormSettings.tsx create mode 100644 apps/web/src/domain/participant/profile-form.ts create mode 100644 packages/db/migrations/0008_profile_form_version.sql create mode 100644 tests/unit/profile-form.test.ts 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 a032190..6c5e849 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx @@ -1,12 +1,14 @@ import Link from "next/link"; import SignOutButton from "@/components/ui/SignOutButton"; -import { updateEventAction } from "../../../../../actions/organizer.actions"; +import { updateEventAction, updateProfileFormAction } from "../../../../../actions/organizer.actions"; +import ProfileFormSettings from "@/components/organizer/ProfileFormSettings"; +import { readProfileForm } from "@/src/domain/participant/profile-form"; import { requireOrganizerEvent } from "@/src/lib/auth"; import { EventSetupForm } from "@/components/organizer/EventForms"; export default async function EventDashboardPage({ params, searchParams }: { params: Promise<{ orgSlug: string; eventSlug: string }>; - searchParams: Promise<{ saved?: string }>; + searchParams: Promise<{ saved?: string; form?: string }>; }) { const { orgSlug, eventSlug } = await params; const notice = await searchParams; @@ -36,6 +38,12 @@ export default async function EventDashboardPage({ params, searchParams }: { }} /> :

Registration is {event.status}. Only event owners and admins can change this event's settings.

} + {can("configure") && <> +

Profile form

+

Choose which questions attendees answer, what they are called, and which are required.

+ {notice.form &&

Profile form saved. Attendees missing a newly required answer are asked for it next time they open their profile.

} + + }
; } diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx index ee6f179..ff7ffa2 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx @@ -4,6 +4,7 @@ import { notFound } from "next/navigation"; import { saveParticipantProfile } from "../../../../actions/participant.actions"; import { requireParticipantEvent } from "@/src/lib/auth"; import ProfileForm from "@/components/participant/ProfileForm"; +import { missingRequiredFields, readProfileForm } from "@/src/domain/participant/profile-form"; export default async function ProfilePage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; @@ -12,13 +13,19 @@ export default async function ProfilePage({ params }: { params: Promise<{ eventS if (!profile) notFound(); const intents = event.intents?.length ? event.intents : ["NETWORKING"]; const zones = event.zones ?? []; + const form = readProfileForm(event.form_config); + // Saved under an older form that now requires something they left empty. + const missing = profile.profileComplete && (profile.formVersion ?? 0) < form.version ? missingRequiredFields(form, profile) : []; return
PARTICIPANT PROFILE

Make your next introduction count.

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

- 0 &&

+ The organizer now asks for: {missing.map((key) => form.fields[key].label).join(", ")}. Your matches keep working meanwhile. +

} + { + return runFormAction(formData, async () => { + const session = await getSession(); + if (!session) throw new Error("Sign in as an organizer first"); + const container = getContainer(); + const event = await container.events.findBySlug(organizationSlug, eventSlug); + if (!event) throw new Error("Event not found"); + const fields = Object.fromEntries(PROFILE_FIELD_KEYS.map((key) => [key, { + label: String(formData.get(`${key}.label`) ?? ""), + shown: formData.get(`${key}.shown`) === "on", + required: formData.get(`${key}.required`) === "on", + }])) as Record; + await configureProfileForm({ eventId: event.id, organizerId: session.attendeeId, fields, currentConfig: event.form_config }, container.events); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}?form=saved`); + }); +} diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts index 23a2986..5db11f3 100644 --- a/apps/web/app/actions/participant.actions.ts +++ b/apps/web/app/actions/participant.actions.ts @@ -5,6 +5,7 @@ import { getContainer } from "../../src/composition/container"; import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { Intent } from "../../src/domain/participant/intent"; import { ValidationError } from "../../src/domain/shared/validation"; +import { readProfileForm } from "../../src/domain/participant/profile-form"; import { clearSession, endIdentityProviderSession, getSession } from "../../lib/session"; import { runFormAction, type FormState } from "../../lib/form-state"; import { redirect } from "next/navigation"; @@ -44,7 +45,7 @@ async function saveProfile(eventSlug: string, formData: FormData) { selfDescription: nullable(formData.get("selfDescription")), yearsOfExperience: parseYears(formData.get("yearsOfExperience")), mostImpressiveBuild: nullable(formData.get("mostImpressiveBuild")), - }, { participants: container.participants, enqueueMatching: container.enqueueEmbedding }); + }, { participants: container.participants, enqueueMatching: container.enqueueEmbedding }, readProfileForm(event.form_config)); } export async function signOutCurrentUser() { diff --git a/apps/web/components/organizer/ProfileFormSettings.tsx b/apps/web/components/organizer/ProfileFormSettings.tsx new file mode 100644 index 0000000..e505d30 --- /dev/null +++ b/apps/web/components/organizer/ProfileFormSettings.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { useActionState } from "react"; +import { initialFormState } from "@/lib/form-state"; +import { LABEL_LIMIT, PROFILE_FIELD_KEYS, PROFILE_FIELDS, type ProfileFormConfig } from "@/src/domain/participant/profile-form"; +import { FormAlert, SubmitButton, type FormAction } from "../ui/form"; + +/** Organizer settings for the participant profile form: label, shown, required per field. */ +export default function ProfileFormSettings({ action, form }: { action: FormAction; form: ProfileFormConfig }) { + const [state, formAction] = useActionState(action, initialFormState); + const value = (name: string, fallback: string) => state.values[name] ?? fallback; + const checked = (name: string, fallback: boolean) => state.values[`${name}.submitted`] ? state.values[name] === "on" : fallback; + return
+ +
NameE-mailPhoneRoleStatusActions
{String(person.designation ?? "—")} {STATE_LABELS[state]}{detail && <>
{detail}}
- {canInvite(facts) && state !== "not_invited" && } - {state === "removed" + {!can("manageAccess") ? null : state === "removed" ? : }
+ + {PROFILE_FIELD_KEYS.map((key) => { + const setting = form.fields[key]; + const error = state.fieldErrors[`${key}.label`] ?? state.fieldErrors[`${key}.required`]; + return + + + + + ; + })} +
FieldLabel shown to attendeesShowRequired
{PROFILE_FIELDS[key].label} + + + {error && {error}} + + +
+

Hidden fields keep what attendees already saved, and everything saved still feeds matching. Name, intent and venue zone are always asked.

+
Save profile form
+ ; +} + +const input = { width: "100%", minWidth: 180, boxSizing: "border-box", padding: "9px 10px", border: "1px solid #3f3f46", borderRadius: 8, background: "#151519", color: "#f4f4f5", font: "inherit" } as const; diff --git a/apps/web/components/participant/ProfileForm.tsx b/apps/web/components/participant/ProfileForm.tsx index 1124adc..35b1672 100644 --- a/apps/web/components/participant/ProfileForm.tsx +++ b/apps/web/components/participant/ProfileForm.tsx @@ -3,6 +3,7 @@ import { useActionState } from "react"; import { initialFormState } from "@/lib/form-state"; import { LIMITS } from "@/src/domain/shared/validation"; +import type { ProfileFormConfig } from "@/src/domain/participant/profile-form"; import { FormAlert, SelectField, SubmitButton, TextField, type FormAction } from "../ui/form"; export interface ProfileFormValues { @@ -20,28 +21,33 @@ export interface ProfileFormValues { const label = (intent: string) => intent.replaceAll("_", " ").toLowerCase(); -export default function ProfileForm({ action, profile, intents, zones }: { +/** The participant profile, shaped by the event's profile form (labels, hidden and required fields). */ +export default function ProfileForm({ action, profile, intents, zones, form }: { action: FormAction; profile: ProfileFormValues; intents: string[]; zones: string[]; + form: ProfileFormConfig; }) { const [state, formAction] = useActionState(action, initialFormState); + const field = form.fields; return
- - - - - - - + {field.designation.shown && } + {field.domain.shown && } + {field.aboutMe.shown && } + {field.selfDescription.shown && } + {field.mostImpressiveBuild.shown && } + {field.yearsOfExperience.shown && } + {field.interests.shown && } ({ value: intent, label: label(intent) }))} /> {zones.length > 0 && { @@ -68,3 +69,15 @@ function eventIntents(values: string[]) { } return intents; } + +/** Saves the organizer's profile form settings as a new form version. */ +export async function configureProfileForm( + input: { eventId: string; organizerId: string; fields: Record; currentConfig: unknown }, + events: EventRepository +) { + await authorizeOrganizer(events, input.eventId, input.organizerId, "configure"); + const form = buildProfileForm(input.fields, readProfileForm(input.currentConfig)); + const updated = await events.update({ eventId: input.eventId, organizerId: input.organizerId, formConfig: { ...form } }); + if (!updated) throw new Error("Event not found"); + return form; +} diff --git a/apps/web/src/application/use-cases/upsert-participant.ts b/apps/web/src/application/use-cases/upsert-participant.ts index 0e8386a..585d9c5 100644 --- a/apps/web/src/application/use-cases/upsert-participant.ts +++ b/apps/web/src/application/use-cases/upsert-participant.ts @@ -1,11 +1,22 @@ import { validateProfile, type ParticipantProfileInput } from "../../domain/participant/participant.entity"; +import { PROFILE_FIELD_KEYS, type ProfileFormConfig } from "../../domain/participant/profile-form"; import type { ParticipantRepository } from "../ports/participant-repository"; export async function upsertParticipant( input: ParticipantProfileInput, - dependencies: { participants: ParticipantRepository; enqueueMatching?: (eventId: string, participantId: string) => Promise } + dependencies: { participants: ParticipantRepository; enqueueMatching?: (eventId: string, participantId: string) => Promise }, + form?: ProfileFormConfig ) { - const profile = await dependencies.participants.saveProfile(validateProfile(input)); + let values = input; + if (form && PROFILE_FIELD_KEYS.some((key) => !form.fields[key].shown)) { + // A hidden field keeps what was saved before, so changing the form never wipes profiles. + const existing = await dependencies.participants.findProfile(input.eventId, input.attendeeId); + values = { ...input }; + for (const key of PROFILE_FIELD_KEYS) { + if (!form.fields[key].shown) Object.assign(values, { [key]: existing?.[key] ?? (key === "interests" ? [] : null) }); + } + } + const profile = await dependencies.participants.saveProfile(validateProfile(values, form)); await dependencies.enqueueMatching?.(profile.eventId, profile.attendeeId); return profile; } diff --git a/apps/web/src/domain/participant/participant.entity.ts b/apps/web/src/domain/participant/participant.entity.ts index 28a8596..e9b51a7 100644 --- a/apps/web/src/domain/participant/participant.entity.ts +++ b/apps/web/src/domain/participant/participant.entity.ts @@ -1,5 +1,6 @@ import { Intent } from "./intent"; import { boundedItems, boundedText, LIMITS, ValidationError } from "../shared/validation"; +import { readProfileForm, type ProfileFormConfig } from "./profile-form"; export interface ParticipantProfile { eventId: string; @@ -18,6 +19,8 @@ export interface ParticipantProfile { venueZone: string | null; visible: boolean; profileComplete?: boolean; + /** Version of the event's profile form this profile was saved under. */ + formVersion?: number; embedding?: number[] | null; } @@ -34,6 +37,7 @@ export type ParticipantProfileInput = Pick< | "intent" | "interests" | "venueZone" + | "formVersion" >; export function profileText(profile: ParticipantProfile): string { @@ -51,22 +55,31 @@ export function profileText(profile: ParticipantProfile): string { .join("\n"); } -export function validateProfile(input: ParticipantProfileInput): ParticipantProfileInput { +export function validateProfile(input: ParticipantProfileInput, form: ProfileFormConfig = readProfileForm({})): ParticipantProfileInput { + // Required fields and their labels come from the event's profile form. + const text = (key: "designation" | "domain" | "aboutMe" | "selfDescription" | "mostImpressiveBuild", value: string | null, limit: number) => + boundedText(value, key, form.fields[key].label, limit, { required: form.fields[key].required }); if (!input.eventId || !input.attendeeId) throw new ValidationError(null, "Participant and event are required"); if (!Object.values(Intent).includes(input.intent)) throw new ValidationError("intent", "Choose a valid networking intent"); if (!Array.isArray(input.interests)) throw new ValidationError("interests", "Interests must be a list"); const years = input.yearsOfExperience; + if (years == null && form.fields.yearsOfExperience.required) { + throw new ValidationError("yearsOfExperience", `${form.fields.yearsOfExperience.label} is required`); + } if (years != null && (!Number.isInteger(years) || years < 0 || years > LIMITS.yearsOfExperience)) { throw new ValidationError("yearsOfExperience", `Years of experience must be a whole number from 0 to ${LIMITS.yearsOfExperience}`); } + const interests = boundedItems(input.interests, "interests", "interests", { count: LIMITS.interestCount, length: LIMITS.interestLength }); + if (!interests.length && form.fields.interests.required) throw new ValidationError("interests", `${form.fields.interests.label} is required`); return { ...input, - designation: boundedText(input.designation, "designation", "Role or designation", LIMITS.designation, { required: true }), - domain: boundedText(input.domain, "domain", "Professional domain", LIMITS.domain, { required: true }), - aboutMe: boundedText(input.aboutMe, "aboutMe", "About you", LIMITS.aboutMe, { required: true }), - selfDescription: boundedText(input.selfDescription, "selfDescription", "Current focus", LIMITS.selfDescription), - mostImpressiveBuild: boundedText(input.mostImpressiveBuild, "mostImpressiveBuild", "Most impressive build", LIMITS.mostImpressiveBuild), + designation: text("designation", input.designation, LIMITS.designation), + domain: text("domain", input.domain, LIMITS.domain), + aboutMe: text("aboutMe", input.aboutMe, LIMITS.aboutMe), + selfDescription: text("selfDescription", input.selfDescription, LIMITS.selfDescription), + mostImpressiveBuild: text("mostImpressiveBuild", input.mostImpressiveBuild, LIMITS.mostImpressiveBuild), venueZone: boundedText(input.venueZone, "venueZone", "Venue zone", LIMITS.zoneLength), - interests: boundedItems(input.interests, "interests", "interests", { count: LIMITS.interestCount, length: LIMITS.interestLength }), + interests, + formVersion: form.version, }; } diff --git a/apps/web/src/domain/participant/profile-form.ts b/apps/web/src/domain/participant/profile-form.ts new file mode 100644 index 0000000..edff91a --- /dev/null +++ b/apps/web/src/domain/participant/profile-form.ts @@ -0,0 +1,76 @@ +import { boundedText, LIMITS, ValidationError } from "../shared/validation"; + +/** + * The profile fields an organizer can configure for an event. They are the + * fields matching already reads, so whatever the form shows, every stored + * value keeps feeding matching the same way. Intent and venue zone are + * configured separately (event intents and zones). + */ +export const PROFILE_FIELDS = { + designation: { label: "Role or designation", kind: "text", limit: LIMITS.designation, required: true, descriptive: true }, + domain: { label: "Professional domain", kind: "text", limit: LIMITS.domain, required: true, descriptive: true }, + aboutMe: { label: "About you", kind: "multiline", limit: LIMITS.aboutMe, required: true, descriptive: true }, + selfDescription: { label: "Current focus", kind: "multiline", limit: LIMITS.selfDescription, required: false, descriptive: true }, + mostImpressiveBuild: { label: "Most impressive thing you have built", kind: "multiline", limit: LIMITS.mostImpressiveBuild, required: false, descriptive: true }, + yearsOfExperience: { label: "Years of experience", kind: "number", limit: LIMITS.yearsOfExperience, required: false, descriptive: false }, + interests: { label: "Interests", kind: "list", limit: LIMITS.interestCount, required: false, descriptive: false }, +} as const; + +export type ProfileFieldKey = keyof typeof PROFILE_FIELDS; +export const PROFILE_FIELD_KEYS = Object.keys(PROFILE_FIELDS) as ProfileFieldKey[]; + +export interface ProfileFieldSetting { + shown: boolean; + required: boolean; + label: string; +} + +export interface ProfileFormConfig { + /** Goes up on every change, so profiles saved under an older form can be found. */ + version: number; + fields: Record; +} + +export const LABEL_LIMIT = 60; + +/** The event's stored form_config, with defaults for anything missing or malformed. */ +export function readProfileForm(raw: unknown): ProfileFormConfig { + const stored = (raw && typeof raw === "object" ? raw : {}) as { version?: unknown; fields?: Record> }; + const fields = {} as Record; + for (const key of PROFILE_FIELD_KEYS) { + const field = stored.fields?.[key] ?? {}; + const shown = typeof field.shown === "boolean" ? field.shown : true; + fields[key] = { + shown, + required: shown && (typeof field.required === "boolean" ? field.required : PROFILE_FIELDS[key].required), + label: typeof field.label === "string" && field.label.trim() ? field.label.trim().slice(0, LABEL_LIMIT) : PROFILE_FIELDS[key].label, + }; + } + return { version: Number.isInteger(stored.version) ? stored.version as number : 0, fields }; +} + +/** Validates an organizer's form settings and stamps the next version. */ +export function buildProfileForm(settings: Record, previous: ProfileFormConfig): ProfileFormConfig { + const fields = {} as Record; + for (const key of PROFILE_FIELD_KEYS) { + const setting = settings[key]; + const label = boundedText(setting.label, `${key}.label`, `${PROFILE_FIELDS[key].label} label`, LABEL_LIMIT) ?? PROFILE_FIELDS[key].label; + if (setting.required && !setting.shown) { + throw new ValidationError(`${key}.required`, `"${label}" cannot be required while it is hidden`); + } + fields[key] = { shown: setting.shown, required: setting.required, label }; + } + if (!PROFILE_FIELD_KEYS.some((key) => PROFILE_FIELDS[key].descriptive && fields[key].required)) { + throw new ValidationError(null, "Keep at least one descriptive field (role, domain, about, focus or build) required, so matching has something to read."); + } + return { version: previous.version + 1, fields }; +} + +/** Required fields a saved profile leaves empty under the current form. */ +export function missingRequiredFields(form: ProfileFormConfig, values: Partial>): ProfileFieldKey[] { + return PROFILE_FIELD_KEYS.filter((key) => { + if (!form.fields[key].required) return false; + const value = values[key]; + return value == null || (Array.isArray(value) ? value.length === 0 : String(value).trim() === ""); + }); +} diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index 54ce014..2787c84 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -21,6 +21,7 @@ interface ProfileRow { visible: boolean; embedding: string | number[] | null; profile_updated_at?: Date | null; + profile_form_version?: number; } const PROFILE_COLUMNS = `p.event_id, a.id as attendee_id, a.name, @@ -31,7 +32,7 @@ const PROFILE_COLUMNS = `p.event_id, a.id as attendee_id, a.name, coalesce(p.years_of_experience, a.years_of_experience) as years_of_experience, coalesce(p.most_impressive_build, a.most_impressive_build) as most_impressive_build, p.intent, p.interests, - p.venue_zone, p.visible, p.embedding::text as embedding, p.profile_updated_at`; + p.venue_zone, p.visible, p.embedding::text as embedding, p.profile_updated_at, p.profile_form_version`; const PROFILE_FROM = `from event_participants p join registered_attendees a on a.id = p.attendee_id`; /** @@ -57,11 +58,11 @@ export class PostgresParticipantRepository implements ParticipantRepository { intent = $3, interests = $4, venue_zone = $5, about_me = $6, designation = $7, domain = $8, self_description = $9, years_of_experience = $10, - most_impressive_build = $11, embedding = null, profile_updated_at = now(), updated_at = now() + most_impressive_build = $11, profile_form_version = $12, embedding = null, profile_updated_at = now(), updated_at = now() where event_id = $1 and attendee_id = $2`, [input.eventId, input.attendeeId, input.intent, input.interests, input.venueZone, input.aboutMe, input.designation, input.domain, input.selfDescription, - input.yearsOfExperience, input.mostImpressiveBuild] + input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0] ); if (!rowCount) throw new Error("This attendee is not on the event roster"); const saved = await this.findProfile(input.eventId, input.attendeeId); @@ -148,6 +149,7 @@ function mapProfile(row: ProfileRow): ParticipantProfile { venueZone: row.venue_zone, visible: row.visible, profileComplete: Boolean(row.profile_updated_at), + formVersion: row.profile_form_version ?? 0, embedding: parseEmbedding(row.embedding), }; } diff --git a/packages/db/migrations/0008_profile_form_version.sql b/packages/db/migrations/0008_profile_form_version.sql new file mode 100644 index 0000000..c6da017 --- /dev/null +++ b/packages/db/migrations/0008_profile_form_version.sql @@ -0,0 +1,8 @@ +-- Which version of the event's profile form a profile was last saved under. +-- +-- Organizers can change field labels, visibility and required fields +-- (events.form_config). Existing profiles stay valid and keep matching; this +-- lets the profile page ask someone saved under an older form to fill in +-- fields that have since become required. + +alter table event_participants add column if not exists profile_form_version integer not null default 0; diff --git a/tests/unit/profile-form.test.ts b/tests/unit/profile-form.test.ts new file mode 100644 index 0000000..5dc5730 --- /dev/null +++ b/tests/unit/profile-form.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it, vi } from "vitest"; +import { buildProfileForm, missingRequiredFields, PROFILE_FIELD_KEYS, readProfileForm, type ProfileFieldSetting } from "@/src/domain/participant/profile-form"; +import { validateProfile, type ParticipantProfileInput } from "@/src/domain/participant/participant.entity"; +import { upsertParticipant } from "@/src/application/use-cases/upsert-participant"; +import { Intent } from "@/src/domain/participant/intent"; +import { ValidationError } from "@/src/domain/shared/validation"; + +const defaults = readProfileForm({}); +const settings = (changes: Partial>> = {}) => + Object.fromEntries(PROFILE_FIELD_KEYS.map((key) => [key, { ...defaults.fields[key], ...changes[key] }])) as Record<(typeof PROFILE_FIELD_KEYS)[number], ProfileFieldSetting>; + +const input: ParticipantProfileInput = { + eventId: "event", attendeeId: "attendee", designation: "Engineer", domain: "AI", aboutMe: "Builds things", + selfDescription: null, yearsOfExperience: null, mostImpressiveBuild: null, intent: Intent.NETWORKING, interests: [], venueZone: null, +}; + +describe("readProfileForm", () => { + it("defaults to today's form for events never configured or with bad data", () => { + expect(defaults.version).toBe(0); + expect(defaults.fields.aboutMe).toEqual({ shown: true, required: true, label: "About you" }); + expect(defaults.fields.interests).toEqual({ shown: true, required: false, label: "Interests" }); + expect(readProfileForm({ fields: { aboutMe: { shown: "yes", label: 42 } } }).fields.aboutMe.label).toBe("About you"); + }); + + it("never treats a hidden field as required", () => { + expect(readProfileForm({ fields: { domain: { shown: false, required: true } } }).fields.domain.required).toBe(false); + }); +}); + +describe("buildProfileForm", () => { + it("bumps the version on every save", () => { + expect(buildProfileForm(settings(), defaults).version).toBe(1); + expect(buildProfileForm(settings(), { ...defaults, version: 4 }).version).toBe(5); + }); + + it("refuses a required hidden field", () => { + expect(() => buildProfileForm(settings({ aboutMe: { shown: false, required: true } }), defaults)).toThrow(/cannot be required while it is hidden/); + }); + + it("keeps at least one descriptive field required for matching", () => { + const none = settings(Object.fromEntries(["designation", "domain", "aboutMe"].map((key) => [key, { required: false }]))); + expect(() => buildProfileForm(none, defaults)).toThrow(ValidationError); + }); + + it("bounds labels and keeps the default for an empty one", () => { + expect(() => buildProfileForm(settings({ domain: { label: "x".repeat(61) } }), defaults)).toThrow(/60 characters/); + expect(buildProfileForm(settings({ domain: { label: " " } }), defaults).fields.domain.label).toBe("Professional domain"); + }); +}); + +describe("validateProfile with an event form", () => { + const form = buildProfileForm(settings({ + aboutMe: { required: false }, interests: { required: true, label: "Topics" }, domain: { label: "Industry" }, + }), defaults); + + it("uses the event's required fields and labels", () => { + expect(() => validateProfile({ ...input, aboutMe: null }, form)).toThrow(/Topics is required/); + expect(() => validateProfile({ ...input, domain: null, interests: ["AI"] }, form)).toThrow(/Industry/); + expect(validateProfile({ ...input, aboutMe: null, interests: ["AI"] }, form)).toMatchObject({ aboutMe: null, formVersion: 1 }); + }); + + it("finds required answers missing from a profile saved under an older form", () => { + expect(missingRequiredFields(form, { ...input, interests: [] })).toEqual(["interests"]); + }); +}); + +describe("upsertParticipant with hidden fields", () => { + it("keeps what was saved before instead of wiping it", async () => { + const form = buildProfileForm(settings({ mostImpressiveBuild: { shown: false, required: false } }), defaults); + const participants = { + findProfile: vi.fn().mockResolvedValue({ ...input, mostImpressiveBuild: "A search engine" }), + saveProfile: vi.fn(async (profile) => profile), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await upsertParticipant({ ...input, mostImpressiveBuild: null }, { participants: participants as any }, form); + expect(participants.saveProfile).toHaveBeenCalledWith(expect.objectContaining({ mostImpressiveBuild: "A search engine", formVersion: 1 })); + }); +}); From 34b6cc18945ba8b29a2dcdb33cd7299001092c6f Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:19:09 +0530 Subject: [PATCH 07/37] Make search query-aware with intent and domain filters (R16) Search replaced the searcher's profile embedding with the query's, so query relevance and personal compatibility were blurred together, and without embeddings (no API key) retrieval was alphabetical, so every query returned the same people. There were no filters. - domain/matching/search-query.ts: query words, query relevance (semantic when both vectors exist, else word-prefix matches), and a final score of 60% query relevance and 40% personal compatibility; both appear in the score breakdown - The pipeline's search path keeps the searcher's own profile for compatibility and uses the query only for retrieval and relevance, so the same query ranks differently for different people - Without a query embedding, retrieval uses Postgres full-text search (any word, prefix match) ranked by ts_rank - Intent and domain filters, validated against the event's intents and the domains present among eligible participants; applied in SQL and again on shared-cache hits, and part of the cache key with the normalized query and retrieval kind - Search page: filter selects with their own labels --- .../e/[eventSlug]/search/SearchForm.tsx | 26 +++- .../e/[eventSlug]/search/page.tsx | 5 +- apps/web/app/actions/match.actions.ts | 8 +- .../ports/participant-repository.ts | 6 + .../use-cases/search-participants.ts | 12 +- apps/web/src/domain/matching/pipeline.ts | 50 +++++-- apps/web/src/domain/matching/search-query.ts | 79 +++++++++++ .../domain/matching/stages/retrieve.stage.ts | 17 ++- .../postgres/participant.repo.ts | 30 ++++- tests/integration/search-retrieval.test.ts | 74 +++++++++++ tests/unit/search.test.ts | 124 ++++++++++++++++++ 11 files changed, 404 insertions(+), 27 deletions(-) create mode 100644 apps/web/src/domain/matching/search-query.ts create mode 100644 tests/integration/search-retrieval.test.ts create mode 100644 tests/unit/search.test.ts diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx index e124e5d..cb0b6aa 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx @@ -18,8 +18,12 @@ interface SearchResult { mutualInterest: boolean; } -export default function SearchForm({ eventSlug }: { eventSlug: string }) { +const intentLabel = (intent: string) => intent.replaceAll("_", " ").toLowerCase(); + +export default function SearchForm({ eventSlug, intents, domains }: { eventSlug: string; intents: string[]; domains: string[] }) { const [query, setQuery] = useState(""); + const [intent, setIntent] = useState(""); + const [domain, setDomain] = useState(""); const [results, setResults] = useState([]); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); @@ -30,7 +34,7 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { setBusy(true); setError(""); try { - const response = await searchEventParticipants(eventSlug, query); + const response = await searchEventParticipants(eventSlug, query, { intent: intent || null, domain: domain || null }); setResults(response.results); setError(response.error ?? ""); setSearched(response.error ? "" : query.trim()); @@ -47,6 +51,22 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { setQuery(event.target.value)} required maxLength={LIMITS.searchQuery} placeholder="e.g. a product designer interested in climate AI" style={input} /> +
+
+ + +
+ {domains.length > 0 &&
+ + +
} +
{error &&

{error}

}

{busy ? "Searching" : searched ? `${results.length} results for ${searched}` : ""}

@@ -69,3 +89,5 @@ export default function SearchForm({ eventSlug }: { eventSlug: string }) { const input = { flex: "1 1 240px", minWidth: 0, padding: 13, borderRadius: 8, border: "1px solid #3f3f46", background: "#151519", color: "#f4f4f5" } as const; const card = { display: "flex", gap: 18, flexWrap: "wrap", alignItems: "center", padding: 20, borderRadius: 12, background: "#151519", border: "1px solid #333" } as const; const muted = { color: "#a1a1aa" } as const; +const filterLabel = { display: "grid", gap: 4, fontSize: 14, color: "#a1a1aa" } as const; +const select = { padding: 10, borderRadius: 8, border: "1px solid #3f3f46", background: "#151519", color: "#f4f4f5", font: "inherit" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx index cd0fcbc..a46c084 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx @@ -5,11 +5,12 @@ import SearchForm from "./SearchForm"; export default async function SearchPage({ params }: { params: Promise<{ eventSlug: string }> }) { const { eventSlug } = await params; - await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); + const { event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/search`, "search"); + const domains = await container.participants.listDomains(event.id); return

Search your event

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

- +
; } diff --git a/apps/web/app/actions/match.actions.ts b/apps/web/app/actions/match.actions.ts index 23099e1..2de5008 100644 --- a/apps/web/app/actions/match.actions.ts +++ b/apps/web/app/actions/match.actions.ts @@ -8,22 +8,22 @@ import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; import { getSession } from "../../lib/session"; import { runFormAction, userMessage, type FormState } from "../../lib/form-state"; -export async function searchEventParticipants(eventSlug: string, searchText: string) { +export async function searchEventParticipants(eventSlug: string, searchText: string, filters: { intent?: string | null; domain?: string | null } = {}) { try { - return { results: await searchEvent(eventSlug, searchText), error: null }; + return { results: await searchEvent(eventSlug, searchText, filters), error: null }; } catch (error) { return { results: [], error: userMessage(error, "Search failed. Please try again.") }; } } -async function searchEvent(eventSlug: string, searchText: string) { +async function searchEvent(eventSlug: string, searchText: string, filters: { intent?: string | null; domain?: string | null }) { const session = await getSession(); if (!session) throw new Error("Sign in to search this event"); const container = getContainer(); const event = await container.events.findByEventSlug(eventSlug); if (!event || !(await container.participants.hasEventAccess(event.id, session.attendeeId))) throw new Error("You are not registered for this event"); assertEventAllows(event.status, "search"); - const results = await searchParticipants({ eventId: event.id, participantId: session.attendeeId, query: searchText }, container); + const results = await searchParticipants({ eventId: event.id, participantId: session.attendeeId, query: searchText, eventIntents: event.intents, filters }, container); return results.map((match) => ({ id: match.participant.attendeeId, name: match.participant.name, diff --git a/apps/web/src/application/ports/participant-repository.ts b/apps/web/src/application/ports/participant-repository.ts index b54e77b..0bab47e 100644 --- a/apps/web/src/application/ports/participant-repository.ts +++ b/apps/web/src/application/ports/participant-repository.ts @@ -1,4 +1,5 @@ import type { ParticipantProfile, ParticipantProfileInput } from "../../domain/participant/participant.entity"; +import type { SearchFilters } from "../../domain/matching/search-query"; export interface ParticipantRepository { findProfile(eventId: string, attendeeId: string): Promise; @@ -7,8 +8,13 @@ export interface ParticipantRepository { eventId: string; excludeAttendeeId: string | null; embedding?: number[] | null; + /** Without an embedding, only candidates matching one of these words, best first. */ + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise; + /** Domains present among eligible participants, for the search filter. */ + listDomains(eventId: string): Promise; findCandidatesByIds(eventId: string, ids: string[]): Promise; setEmbedding(eventId: string, attendeeId: string, embedding: number[]): Promise; shareVenueZone(eventId: string, attendeeId: string, zone: string): Promise; diff --git a/apps/web/src/application/use-cases/search-participants.ts b/apps/web/src/application/use-cases/search-participants.ts index bb6f1e2..3e66fde 100644 --- a/apps/web/src/application/use-cases/search-participants.ts +++ b/apps/web/src/application/use-cases/search-participants.ts @@ -1,14 +1,20 @@ import { MatchingPipeline } from "../../domain/matching/pipeline"; +import { normalizeFilters } from "../../domain/matching/search-query"; +import type { ParticipantRepository } from "../ports/participant-repository"; import type { RateLimiter } from "../ports/rate-limiter"; import { boundedText, LIMITS } from "../../domain/shared/validation"; export async function searchParticipants( - input: { eventId: string; participantId: string; query: string; limit?: number }, - dependencies: { pipeline: MatchingPipeline; limiter?: RateLimiter } + input: { eventId: string; participantId: string; query: string; eventIntents: string[]; filters?: { intent?: string | null; domain?: string | null }; limit?: number }, + dependencies: { pipeline: MatchingPipeline; participants: ParticipantRepository; limiter?: RateLimiter } ) { if (dependencies.limiter && !(await dependencies.limiter.consume(`search:${input.participantId}`, 30, 60))) { throw new Error("Too many searches. Wait a moment and try again."); } const query = boundedText(input.query, "query", "Search", LIMITS.searchQuery, { required: true })!; - return dependencies.pipeline.run({ ...input, query, mode: "search" }); + const filters = normalizeFilters(input.filters ?? {}, { + intents: input.eventIntents, + domains: input.filters?.domain ? await dependencies.participants.listDomains(input.eventId) : [], + }); + return dependencies.pipeline.run({ eventId: input.eventId, participantId: input.participantId, query, filters, limit: input.limit, mode: "search" }); } diff --git a/apps/web/src/domain/matching/pipeline.ts b/apps/web/src/domain/matching/pipeline.ts index 0a4351a..89ea3b6 100644 --- a/apps/web/src/domain/matching/pipeline.ts +++ b/apps/web/src/domain/matching/pipeline.ts @@ -3,7 +3,8 @@ import type { CandidateCache } from "../../application/ports/candidate-cache"; import type { LlmProvider } from "../../application/ports/llm-provider"; import type { MatchRepository } from "../../application/ports/match-repository"; import type { ParticipantRepository } from "../../application/ports/participant-repository"; -import { profileText } from "../participant/participant.entity"; +import { profileText, type ParticipantProfile } from "../participant/participant.entity"; +import { NO_FILTERS, queryRelevance, queryTerms, searchScore, type SearchFilters } from "./search-query"; import { ComplementarityScorer } from "./scorers/complementarity.scorer"; import { DomainScorer } from "./scorers/domain.scorer"; import { IntentScorer } from "./scorers/intent.scorer"; @@ -22,6 +23,7 @@ export interface MatchingInput { participantId: string; mode: "profile" | "search"; query?: string; + filters?: SearchFilters; limit?: number; } @@ -65,11 +67,10 @@ export class MatchingPipeline { // Hidden viewers may still browse; only a saved profile is required. if (!storedProfile?.profileComplete) throw new Error("Complete your event profile before continuing"); - const embeddingText = input.mode === "search" ? input.query!.trim() : profileText(storedProfile); - const embedding = input.mode === "profile" && storedProfile.embedding - ? storedProfile.embedding - : await this.embeddings.embed(embeddingText, input.mode === "search" ? "query" : "profile"); - if (input.mode === "profile" && embedding) { + if (input.mode === "search") return this.search(input, storedProfile); + + const embedding = storedProfile.embedding ?? await this.embeddings.embed(profileText(storedProfile), "profile"); + if (embedding && !storedProfile.embedding) { await this.participants.setEmbedding(input.eventId, input.participantId, embedding); } const viewer = { ...storedProfile, embedding: embedding ?? storedProfile.embedding }; @@ -78,7 +79,6 @@ export class MatchingPipeline { eventId: input.eventId, viewerId: input.participantId, embedding, - query: input.mode === "search" ? input.query : undefined, limit: 50, }); const compatible = this.filter.execute(viewer, retrieved); @@ -86,9 +86,39 @@ export class MatchingPipeline { const top = this.topK.execute(scored, input.limit ?? 12); const { candidates: ranked, rankedBy } = await this.rerank.execute(viewer, top); - if (input.mode === "profile") { - await this.persist.execute(input.eventId, input.participantId, ranked, `${MATCHING_PIPELINE_VERSION}+${rankedBy}`); - } + await this.persist.execute(input.eventId, input.participantId, ranked, `${MATCHING_PIPELINE_VERSION}+${rankedBy}`); + return ranked; + } + + /** + * Search: the query embedding (or its words, without embeddings) retrieves + * and measures relevance; the searcher's own profile measures compatibility. + * Both feed the score, so the same query ranks differently per person. + */ + private async search(input: MatchingInput, viewer: ParticipantProfile) { + const query = input.query!.trim(); + const terms = queryTerms(query); + const queryEmbedding = await this.embeddings.embed(query, "query"); + const retrieved = await this.retrieve.execute({ + eventId: input.eventId, + viewerId: input.participantId, + embedding: queryEmbedding, + query, + terms, + filters: input.filters ?? NO_FILTERS, + limit: 50, + }); + const compatible = this.filter.execute(viewer, retrieved); + const scored = this.score.execute(viewer, compatible).map((candidate) => { + const relevance = queryRelevance(terms, queryEmbedding, candidate.participant); + return { + ...candidate, + score: searchScore(relevance, candidate.score), + scoreBreakdown: { ...candidate.scoreBreakdown, query: relevance, profile: candidate.score / 100 }, + }; + }).sort((a, b) => b.score - a.score); + const top = this.topK.execute(scored, input.limit ?? 12); + const { candidates: ranked } = await this.rerank.execute(viewer, top); return ranked; } } diff --git a/apps/web/src/domain/matching/search-query.ts b/apps/web/src/domain/matching/search-query.ts new file mode 100644 index 0000000..31ee5aa --- /dev/null +++ b/apps/web/src/domain/matching/search-query.ts @@ -0,0 +1,79 @@ +import { Intent } from "../participant/intent"; +import { profileText, type ParticipantProfile } from "../participant/participant.entity"; +import { ValidationError } from "../shared/validation"; +import { cosineSimilarity } from "./scorers/scorer"; + +/** + * What a search means. The query decides who is relevant; the searcher's own + * profile decides who is compatible. The two are scored separately and then + * combined, so the same query ranks differently for different people. + */ +export interface SearchFilters { + intent: Intent | null; + /** One of the domains present among the event's participants. */ + domain: string | null; +} + +export const NO_FILTERS: SearchFilters = { intent: null, domain: null }; + +/** Share of the final search score that comes from the query; the rest is personal compatibility. */ +export const QUERY_WEIGHT = 0.6; + +const MAX_TERMS = 12; +const STOPWORDS = new Set([ + "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "from", "has", "have", "i", "in", "into", "is", "it", + "looking", "me", "my", "of", "on", "or", "people", "person", "someone", "somebody", "the", "their", "they", "to", + "want", "who", "with", "working", "works", "someone's", "interested", "like", "find", "need", "about", +]); + +/** Meaningful lowercase words from a query, used for lexical retrieval and relevance. */ +export function queryTerms(query: string): string[] { + const words = query.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; + return [...new Set(words.filter((word) => word.length > 1 && !STOPWORDS.has(word)))].slice(0, MAX_TERMS); +} + +/** Validates filters against what the event offers; unknown values are rejected, not ignored. */ +export function normalizeFilters( + raw: { intent?: string | null; domain?: string | null }, + allowed: { intents: string[]; domains: string[] } +): SearchFilters { + const intent = raw.intent?.trim() || null; + if (intent && (!allowed.intents.includes(intent) || !Object.values(Intent).includes(intent as Intent))) { + throw new ValidationError("intent", "Choose an intent offered by this event"); + } + const wanted = raw.domain?.trim().toLowerCase() || null; + const domain = wanted ? allowed.domains.find((value) => value.toLowerCase() === wanted) ?? null : null; + if (wanted && !domain) throw new ValidationError("domain", "Choose a domain from the list"); + return { intent: intent as Intent | null, domain }; +} + +export function matchesFilters(profile: ParticipantProfile, filters: SearchFilters): boolean { + if (filters.intent && profile.intent !== filters.intent) return false; + if (filters.domain && profile.domain?.toLowerCase() !== filters.domain.toLowerCase()) return false; + return true; +} + +/** Fraction of query terms that start a word of the candidate's profile (0–1). */ +export function lexicalRelevance(terms: string[], profile: ParticipantProfile): number { + if (!terms.length) return 0; + const words = profileText(profile).toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []; + const found = terms.filter((term) => words.some((word) => word.startsWith(term))); + return found.length / terms.length; +} + +/** How well a candidate answers the query: semantic when both vectors exist, otherwise lexical. */ +export function queryRelevance(terms: string[], queryEmbedding: number[] | null, profile: ParticipantProfile): number { + const semantic = cosineSimilarity(queryEmbedding, profile.embedding); + return semantic > 0 ? semantic : lexicalRelevance(terms, profile); +} + +/** Final search score (0–100) from query relevance (0–1) and personal compatibility (0–100). */ +export function searchScore(relevance: number, personal: number): number { + return Math.round(QUERY_WEIGHT * relevance * 100 + (1 - QUERY_WEIGHT) * personal); +} + +/** Postgres to_tsquery text matching any term as a prefix; terms are already letters and digits only. */ +export function lexicalTsQuery(terms: string[]): string | null { + const safe = terms.map((term) => term.replace(/[^\p{L}\p{N}]/gu, "")).filter(Boolean); + return safe.length ? safe.map((term) => `${term}:*`).join(" | ") : null; +} diff --git a/apps/web/src/domain/matching/stages/retrieve.stage.ts b/apps/web/src/domain/matching/stages/retrieve.stage.ts index 9bc9b66..f544a85 100644 --- a/apps/web/src/domain/matching/stages/retrieve.stage.ts +++ b/apps/web/src/domain/matching/stages/retrieve.stage.ts @@ -3,6 +3,7 @@ import type { ParticipantRepository } from "../../../application/ports/participa import type { MatchRepository } from "../../../application/ports/match-repository"; import type { CandidateCache } from "../../../application/ports/candidate-cache"; import type { ParticipantProfile } from "../../participant/participant.entity"; +import { matchesFilters, NO_FILTERS, type SearchFilters } from "../search-query"; export class RetrieveStage { constructor( @@ -15,29 +16,37 @@ export class RetrieveStage { viewerId: string; embedding: number[] | null; query?: string; + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise { const limit = input.limit ?? 50; - const normalizedQuery = input.query?.trim().toLowerCase(); + const filters = input.filters ?? NO_FILTERS; + const normalizedQuery = input.query?.trim().toLowerCase().replace(/\s+/g, " "); if (normalizedQuery) { + // Shared across viewers for the same event, query, filters and retrieval + // kind; the ranking that follows is still personal. const key = createHash("sha256") - .update(`${input.eventId}:${normalizedQuery}`) + .update(JSON.stringify([input.eventId, normalizedQuery, filters.intent, filters.domain?.toLowerCase() ?? null, input.embedding ? "semantic" : "lexical"])) .digest("hex"); const cachedIds = await this.cache.get(key); if (cachedIds) { const cached = await this.participants.findCandidatesByIds(input.eventId, cachedIds); const byId = new Map(cached.map((profile) => [profile.attendeeId, profile])); - return cachedIds.map((id) => byId.get(id)).filter((row): row is ParticipantProfile => row !== undefined && row.attendeeId !== input.viewerId); + return cachedIds.map((id) => byId.get(id)) + .filter((row): row is ParticipantProfile => row !== undefined && row.attendeeId !== input.viewerId && matchesFilters(row, filters)); } const candidates = await this.participants.listCandidates({ eventId: input.eventId, excludeAttendeeId: null, embedding: input.embedding, + terms: input.terms, + filters, limit, }); await this.cache.set(key, candidates.map((c) => c.attendeeId), 300); - return candidates.filter((candidate) => candidate.attendeeId !== input.viewerId); + return candidates.filter((candidate) => candidate.attendeeId !== input.viewerId && matchesFilters(candidate, filters)); } return this.participants.listCandidates({ diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index 2787c84..0fbcf1d 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -1,4 +1,5 @@ import { query } from "@match-maker/db"; +import { lexicalTsQuery, type SearchFilters } from "../../domain/matching/search-query"; import type { ParticipantRepository } from "../../application/ports/participant-repository"; import { Intent } from "../../domain/participant/intent"; import type { ParticipantProfile, ParticipantProfileInput } from "../../domain/participant/participant.entity"; @@ -40,6 +41,10 @@ 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. */ +/** Profile text searched when no embeddings are available. */ +const SEARCH_DOCUMENT = `to_tsvector('simple', concat_ws(' ', a.name, p.designation, p.domain, p.about_me, + p.self_description, p.most_impressive_build, array_to_string(p.interests, ' ')))`; + 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 { @@ -74,20 +79,41 @@ export class PostgresParticipantRepository implements ParticipantRepository { eventId: string; excludeAttendeeId: string | null; embedding?: number[] | null; + terms?: string[]; + filters?: SearchFilters; limit?: number; }): Promise { const vector = toVector(input.embedding ?? null); + // Lexical retrieval only when there is no query vector to rank by. + const tsQuery = vector ? null : lexicalTsQuery(input.terms ?? []); const { rows } = await query( `select ${PROFILE_COLUMNS} ${PROFILE_FROM} where p.event_id = $1 and ($2::uuid is null or a.id <> $2::uuid) and ${ELIGIBLE_CANDIDATE} + and ($5::text is null or p.intent = $5) + and ($6::text is null or lower(p.domain) = lower($6)) + and ($7::text is null or ${SEARCH_DOCUMENT} @@ to_tsquery('simple', $7)) order by case when $3::vector is not null and p.embedding is not null then 0 else 1 end, - p.embedding <=> $3::vector nulls last, a.name asc + p.embedding <=> $3::vector nulls last, + case when $7::text is null then 0 else ts_rank(${SEARCH_DOCUMENT}, to_tsquery('simple', $7)) end desc, + a.name asc limit $4`, - [input.eventId, input.excludeAttendeeId, vector, Math.max(1, Math.min(100, input.limit ?? 50))] + [input.eventId, input.excludeAttendeeId, vector, Math.max(1, Math.min(100, input.limit ?? 50)), + input.filters?.intent ?? null, input.filters?.domain ?? null, tsQuery] ); return rows.map(mapProfile); } + async listDomains(eventId: string): Promise { + const { rows } = await query<{ domain: string }>( + // One entry per domain ignoring case, preferring a capitalised spelling. + `select (array_agg(trim(p.domain) order by trim(p.domain) = lower(trim(p.domain)), trim(p.domain)))[1] as domain ${PROFILE_FROM} + where p.event_id = $1 and ${ELIGIBLE_CANDIDATE} and coalesce(trim(p.domain), '') <> '' + group by lower(trim(p.domain)) order by 1`, + [eventId] + ); + return rows.map((row) => row.domain.trim()); + } + async findCandidatesByIds(eventId: string, ids: string[]): Promise { if (!ids.length) return []; const { rows } = await query( diff --git a/tests/integration/search-retrieval.test.ts b/tests/integration/search-retrieval.test.ts new file mode 100644 index 0000000..b404d42 --- /dev/null +++ b/tests/integration/search-retrieval.test.ts @@ -0,0 +1,74 @@ +/** + * Query-sensitive retrieval without embeddings, and search filters, against a + * real Postgres. Uses its own organization, event and attendees. + * Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { attendees, closePool, events, query } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; +import { Intent } from "../../apps/web/src/domain/participant/intent"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const RUN = Date.now().toString(36); +const ORG = `search-${RUN}`; +const email = (key: string) => `search-${key}-${RUN}@example.com`; + +// Neutral names: names are part of the searchable text. +const NAMES: Record = { designer: "Ana Rao", engineer: "Ben Iyer", founder: "Cy Das" }; +const PEOPLE = { + designer: { designation: "Product Designer", domain: "Design", about_me: "Designing climate tools", intent: "NETWORKING", interests: ["climate"] }, + engineer: { designation: "ML Engineer", domain: "AI", about_me: "Builds retrieval and search systems", intent: "NETWORKING", interests: ["rag"] }, + founder: { designation: "Founder", domain: "ai", about_me: "Hiring engineers for search", intent: "HIRING", interests: ["search"] }, +} as const; + +describeDb("search retrieval", () => { + const repo = new PostgresParticipantRepository(); + let eventId: string; + const ids: Record = {}; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(Object.keys(PEOPLE).map((key) => ({ name: NAMES[key], email: email(key) }))); + for (const key of Object.keys(PEOPLE)) ids[key] = (await attendees.findByEmail(email(key)))!.id; + const { rows: [org] } = await query<{ id: string }>(`insert into organizations (name, slug) values ($1, $1) returning id`, [ORG]); + eventId = (await query<{ id: string }>(`insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') returning id`, [org.id, ORG])).rows[0].id; + await events.attachRoster(eventId, Object.values(ids)); + for (const [key, person] of Object.entries(PEOPLE)) { + await query( + `update event_participants set designation = $3, domain = $4, about_me = $5, intent = $6, interests = $7, profile_updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, ids[key], person.designation, person.domain, person.about_me, person.intent, person.interests] + ); + } + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email like $1`, [`search-%-${RUN}@example.com`]); + await closePool(); + }); + + const names = async (input: Parameters[0]) => + (await repo.listCandidates(input)).map((profile) => profile.name); + + it("returns only people matching the query words, best match first", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["climate"] })).toEqual(["Ana Rao"]); + const searchers = await names({ eventId, excludeAttendeeId: null, terms: ["search", "engineer"] }); + expect(searchers.sort()).toEqual(["Ben Iyer", "Cy Das"]); + expect(await names({ eventId, excludeAttendeeId: null, terms: ["quantum"] })).toEqual([]); + }); + + it("matches word prefixes", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["design"] })).toEqual(["Ana Rao"]); + }); + + it("applies intent and domain filters, ignoring domain case", async () => { + expect(await names({ eventId, excludeAttendeeId: null, terms: ["search"], filters: { intent: Intent.HIRING, domain: null } })).toEqual(["Cy Das"]); + expect((await names({ eventId, excludeAttendeeId: null, filters: { intent: null, domain: "AI" } })).sort()).toEqual(["Ben Iyer", "Cy Das"]); + }); + + it("lists each domain present once", async () => { + expect(await repo.listDomains(eventId)).toEqual(["AI", "Design"]); + }); +}); diff --git a/tests/unit/search.test.ts b/tests/unit/search.test.ts new file mode 100644 index 0000000..0de3900 --- /dev/null +++ b/tests/unit/search.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it, vi } from "vitest"; +import { MatchingPipeline } from "@/src/domain/matching/pipeline"; +import { + lexicalRelevance, lexicalTsQuery, matchesFilters, normalizeFilters, queryRelevance, queryTerms, searchScore, +} from "@/src/domain/matching/search-query"; +import type { ParticipantRepository } from "@/src/application/ports/participant-repository"; +import { Intent } from "@/src/domain/participant/intent"; +import type { ParticipantProfile } from "@/src/domain/participant/participant.entity"; +import { ValidationError } from "@/src/domain/shared/validation"; + +const profile = (attendeeId: string, overrides: Partial = {}): ParticipantProfile => ({ + eventId: "event", attendeeId, name: attendeeId, designation: null, domain: null, aboutMe: null, + selfDescription: null, yearsOfExperience: null, mostImpressiveBuild: null, + intent: Intent.NETWORKING, interests: [], venueZone: null, visible: true, profileComplete: true, embedding: null, ...overrides, +}); + +const designer = profile("designer", { designation: "Product Designer", domain: "Design", aboutMe: "Designing climate tools", interests: ["climate"] }); +const engineer = profile("engineer", { designation: "ML Engineer", domain: "AI", aboutMe: "Builds retrieval systems", interests: ["rag", "search"] }); +const founder = profile("founder", { designation: "Founder", domain: "AI", aboutMe: "Hiring engineers", intent: Intent.HIRING, interests: ["search"] }); + +describe("query terms and relevance", () => { + it("keeps meaningful words only", () => { + expect(queryTerms("Someone working on Climate design, with RAG!")).toEqual(["climate", "design", "rag"]); + }); + + it("matches words by prefix against the profile", () => { + expect(lexicalRelevance(["climat", "design"], designer)).toBe(1); + expect(lexicalRelevance(["climate", "rag"], engineer)).toBe(0.5); + expect(lexicalRelevance([], engineer)).toBe(0); + }); + + it("prefers semantic relevance when both vectors exist", () => { + const withVector = { ...engineer, embedding: [1, 0] }; + expect(queryRelevance(["nothing"], [1, 0], withVector)).toBeCloseTo(1); + expect(queryRelevance(["rag"], null, withVector)).toBe(1); + }); + + it("weights query relevance over personal compatibility", () => { + expect(searchScore(1, 0)).toBe(60); + expect(searchScore(0, 100)).toBe(40); + }); + + it("builds a prefix OR query from safe words", () => { + expect(lexicalTsQuery(["climate", "ml"])).toBe("climate:* | ml:*"); + expect(lexicalTsQuery([])).toBeNull(); + }); +}); + +describe("search filters", () => { + const allowed = { intents: ["NETWORKING", "HIRING"], domains: ["AI", "Design"] }; + + it("accepts the event's intents and present domains, matching case", () => { + expect(normalizeFilters({ intent: "HIRING", domain: "ai" }, allowed)).toEqual({ intent: "HIRING", domain: "AI" }); + expect(normalizeFilters({}, allowed)).toEqual({ intent: null, domain: null }); + }); + + it("rejects values outside the catalog", () => { + expect(() => normalizeFilters({ intent: "INVESTING" }, allowed)).toThrow(ValidationError); + expect(() => normalizeFilters({ domain: "Biotech" }, allowed)).toThrow(/Choose a domain/); + }); + + it("checks a profile against the filters", () => { + expect(matchesFilters(founder, { intent: Intent.HIRING, domain: "ai" })).toBe(true); + expect(matchesFilters(engineer, { intent: Intent.HIRING, domain: null })).toBe(false); + }); +}); + +function searchPipeline(candidates: ParticipantProfile[], viewer: ParticipantProfile, cached: string[] | null = null) { + const participants = { + findProfile: vi.fn(async () => viewer), + listCandidates: vi.fn(async () => candidates), + findCandidatesByIds: vi.fn(async (_event: string, ids: string[]) => candidates.filter((c) => ids.includes(c.attendeeId))), + setEmbedding: vi.fn(), + } as unknown as ParticipantRepository; + const cache = { get: vi.fn(async () => cached), set: vi.fn() }; + const matches = { save: vi.fn(), listForParticipant: vi.fn() }; + const pipeline = new MatchingPipeline(participants, matches, { embed: vi.fn(async () => null) }, null, cache); + return { pipeline, participants, cache, matches }; +} + +const search = (pipeline: MatchingPipeline, query: string, filters = { intent: null, domain: null }) => + pipeline.run({ eventId: "event", participantId: "viewer", mode: "search", query, filters }).then((ranked) => ranked.map((c) => c.participant.attendeeId)); + +describe("search pipeline", () => { + const viewer = profile("viewer", { domain: "AI", interests: ["search"] }); + + it("ranks by the query: different queries, different order", async () => { + const { pipeline } = searchPipeline([designer, engineer, founder], viewer); + expect((await search(pipeline, "climate designer"))[0]).toBe("designer"); + expect((await search(pipeline, "retrieval engineer"))[0]).toBe("engineer"); + }); + + it("still ranks personally: the same query orders differently for different people", async () => { + const twins = [profile("ai-person", { domain: "AI", interests: ["search"], aboutMe: "Builds products" }), + profile("design-person", { domain: "Design", interests: ["climate"], aboutMe: "Builds products" })]; + const aiViewer = await search(searchPipeline(twins, profile("viewer", { domain: "AI", interests: ["search"] })).pipeline, "products"); + const designViewer = await search(searchPipeline(twins, profile("viewer", { domain: "Design", interests: ["climate"] })).pipeline, "products"); + expect(aiViewer[0]).toBe("ai-person"); + expect(designViewer[0]).toBe("design-person"); + }); + + it("passes words and filters to retrieval, and keeps the searcher's profile for compatibility", async () => { + const { pipeline, participants, matches } = searchPipeline([engineer], viewer); + await search(pipeline, "RAG engineers", { intent: null, domain: "AI" }); + expect(participants.listCandidates).toHaveBeenCalledWith(expect.objectContaining({ terms: ["rag", "engineers"], filters: { intent: null, domain: "AI" } })); + expect(matches.save).not.toHaveBeenCalled(); + }); + + it("applies filters to cache hits too", async () => { + const { pipeline, participants } = searchPipeline([designer, engineer, founder], viewer, ["designer", "engineer", "founder"]); + expect(await search(pipeline, "search", { intent: Intent.HIRING, domain: null })).toEqual(["founder"]); + expect(participants.listCandidates).not.toHaveBeenCalled(); + }); + + it("keys the shared cache by query and filters", async () => { + const { pipeline, cache } = searchPipeline([engineer], viewer); + await search(pipeline, "search"); + await search(pipeline, " SEARCH "); + await search(pipeline, "search", { intent: null, domain: "AI" }); + const keys = cache.set.mock.calls.map((call) => call[0]); + expect(keys[0]).toBe(keys[1]); + expect(keys[2]).not.toBe(keys[0]); + }); +}); From 111331463163310ac256a308c3dc53fb1fcc74b6 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:23:25 +0530 Subject: [PATCH 08/37] Score mutual interest in both directions with a versioned config (R17) mutualInterest was set from intent compatibility alone, so any two people with compatible goals were shown "Your event goals align" however poorly they fit. Every scorer was also symmetric, so a two-direction rule would have meant nothing. - domain/matching/scoring-config.ts: scorer weights, the mutual interest threshold and a version in one place; the version is part of the persisted computation version (v2.s2), so older results can be found and recomputed - Interests are now directional (how much of what the viewer cares about the candidate shares), so score(A->B) and score(B->A) can differ - ScoreStage computes both directions; the flag needs both to reach the threshold (0.65, calibrated on documented examples). The reverse score is stored in the breakdown - Wording: "Likely a strong fit for each other"; the fallback reason no longer presents intent compatibility as a prediction - Calibration tests: both high flags; compatible goals alone, or a one-way fit, do not; works with and without embeddings --- .../e/[eventSlug]/matches/page.tsx | 2 +- .../e/[eventSlug]/search/SearchForm.tsx | 2 +- apps/web/src/domain/matching/pipeline.ts | 24 ++++--- .../scorers/complementarity.scorer.ts | 3 +- .../domain/matching/scorers/domain.scorer.ts | 3 +- .../domain/matching/scorers/intent.scorer.ts | 3 +- .../domain/matching/scorers/jaccard.scorer.ts | 20 ++++-- .../matching/scorers/semantic.scorer.ts | 3 +- .../matching/scorers/seniority.scorer.ts | 3 +- .../web/src/domain/matching/scoring-config.ts | 33 +++++++++ .../matching/stages/llm-rerank.stage.ts | 4 +- .../src/domain/matching/stages/score.stage.ts | 31 +++++---- tests/unit/mutual-interest.test.ts | 68 +++++++++++++++++++ 13 files changed, 162 insertions(+), 37 deletions(-) create mode 100644 apps/web/src/domain/matching/scoring-config.ts create mode 100644 tests/unit/mutual-interest.test.ts diff --git a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx index 1526903..8e5bd80 100644 --- a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx +++ b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx @@ -43,7 +43,7 @@ export default async function MatchesPage({ params, searchParams }: { {match.participant.aboutMe &&

{match.participant.aboutMe}

} {match.participant.mostImpressiveBuild &&

Built: {match.participant.mostImpressiveBuild}

}

{match.reason || "A promising person to meet at this event."}

-

{match.mutualInterest ? "Your event goals align" : "Suggested for your profile"}

+

{match.mutualInterest ? "Likely a strong fit for each other" : "Suggested for your profile"}

{Math.round(match.score)}%
{canRequestIntro &&