From 9632c5f610b056ef83d728d2afde2c3d0197e150 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:06:28 +0530 Subject: [PATCH 01/34] 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 }: { {String(person.designation ?? "—")} {STATE_LABELS[state]}{detail && <>
{detail}}
- {canInvite(facts) && state !== "not_invited" && } - {state === "removed" + {!can("manageAccess") ? null : state === "removed" ? : }
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 02/34] 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 03/34] 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
+ +
+ + {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 04/34] 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 05/34] 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 &&
; } diff --git a/apps/web/app/actions/participant.actions.ts b/apps/web/app/actions/participant.actions.ts index 5db11f3..e0f0aa0 100644 --- a/apps/web/app/actions/participant.actions.ts +++ b/apps/web/app/actions/participant.actions.ts @@ -45,6 +45,7 @@ async function saveProfile(eventSlug: string, formData: FormData) { selfDescription: nullable(formData.get("selfDescription")), yearsOfExperience: parseYears(formData.get("yearsOfExperience")), mostImpressiveBuild: nullable(formData.get("mostImpressiveBuild")), + visible: formData.get("visible") === "on", }, { participants: container.participants, enqueueMatching: container.enqueueEmbedding }, readProfileForm(event.form_config)); } diff --git a/apps/web/components/participant/ProfileForm.tsx b/apps/web/components/participant/ProfileForm.tsx index 35b1672..e05f743 100644 --- a/apps/web/components/participant/ProfileForm.tsx +++ b/apps/web/components/participant/ProfileForm.tsx @@ -17,6 +17,7 @@ export interface ProfileFormValues { interests: string[]; intent: string; venueZone: string | null; + visible: boolean; } const label = (intent: string) => intent.replaceAll("_", " ").toLowerCase(); @@ -52,6 +53,14 @@ export default function ProfileForm({ action, profile, intents, zones, form }: { options={intents.map((intent) => ({ value: intent, label: label(intent) }))} /> {zones.length > 0 && ({ value: zone, label: zone }))} />} +
+ + Hidden, you can still browse and keep your accepted connections; nobody new can find you or request an introduction. +
Save profile and find matches
; } diff --git a/apps/web/src/application/ports/intro-repository.ts b/apps/web/src/application/ports/intro-repository.ts index 2b1167c..bc9e54b 100644 --- a/apps/web/src/application/ports/intro-repository.ts +++ b/apps/web/src/application/ports/intro-repository.ts @@ -4,6 +4,10 @@ export interface IntroRepository { create(input: { eventId: string; requesterId: string; recipientId: string; message?: string | null }): Promise; findById(eventId: string, introId: string): Promise; respond(eventId: string, introId: string, actorId: string, status: Extract): Promise; + /** Requests in either direction between two people. */ + findBetween(eventId: string, a: string, b: string): Promise; + countPendingOutgoing(eventId: string, requesterId: string): Promise; + /** The participant's requests, excluding those with someone removed from the event. */ listForParticipant(eventId: string, participantId: string): Promise; getRevealedContacts(eventId: string, participantId: string): Promise>; } diff --git a/apps/web/src/application/use-cases/request-intro.ts b/apps/web/src/application/use-cases/request-intro.ts index 1dc00b1..ed31eee 100644 --- a/apps/web/src/application/use-cases/request-intro.ts +++ b/apps/web/src/application/use-cases/request-intro.ts @@ -2,11 +2,14 @@ import type { IntroRepository } from "../ports/intro-repository"; import type { ParticipantRepository } from "../ports/participant-repository"; import type { NotificationPort } from "../ports/notification"; import { boundedText, LIMITS } from "../../domain/shared/validation"; +import { INTRO_LIMITS, introRequestRefusal } from "../../domain/connection/connection.rules"; +import type { RateLimiter } from "../ports/rate-limiter"; export async function requestIntro( input: { eventId: string; requesterId: string; recipientId: string; message?: string | null; eventName?: string }, - dependencies: { participants: ParticipantRepository; intros: IntroRepository; notifications?: NotificationPort } + dependencies: { participants: ParticipantRepository; intros: IntroRepository; notifications?: NotificationPort; limiter?: RateLimiter } ) { + if (input.requesterId === input.recipientId) throw new Error("You cannot request an intro to yourself"); if (!(await dependencies.participants.hasEventAccess(input.eventId, input.requesterId))) throw new Error("You are not registered for this event"); if (!(await dependencies.participants.hasEventAccess(input.eventId, input.recipientId))) throw new Error("This participant is not in the event"); const [requester, recipient] = await Promise.all([ @@ -15,6 +18,14 @@ export async function requestIntro( ]); if (!requester || !recipient || !recipient.visible || !recipient.profileComplete) throw new Error("This participant is unavailable"); const message = boundedText(input.message, "message", "Message", LIMITS.introMessage); + const refusal = introRequestRefusal(input.requesterId, await dependencies.intros.findBetween(input.eventId, input.requesterId, input.recipientId)); + if (refusal) throw new Error(refusal); + if (await dependencies.intros.countPendingOutgoing(input.eventId, input.requesterId) >= INTRO_LIMITS.pendingOutgoing) { + throw new Error(`You have ${INTRO_LIMITS.pendingOutgoing} requests waiting for an answer. Wait for replies before asking more people.`); + } + if (dependencies.limiter && !(await dependencies.limiter.consume(`intro:${input.eventId}:${input.requesterId}`, INTRO_LIMITS.perHour, 3600))) { + throw new Error("You have sent many introduction requests this hour. Please try again later."); + } const intro = await dependencies.intros.create({ ...input, message }); if (recipient.email && dependencies.notifications) { await dependencies.notifications.introRequested({ diff --git a/apps/web/src/application/use-cases/respond-to-intro.ts b/apps/web/src/application/use-cases/respond-to-intro.ts index c7f880c..3ee9ba2 100644 --- a/apps/web/src/application/use-cases/respond-to-intro.ts +++ b/apps/web/src/application/use-cases/respond-to-intro.ts @@ -8,6 +8,9 @@ export async function respondToIntro( ) { const existing = await dependencies.intros.findById(input.eventId, input.introId); if (!existing) throw new Error("Intro request not found"); + if (input.accept && !(await dependencies.participants.hasEventAccess(input.eventId, existing.requesterId))) { + throw new Error("This person is no longer part of the event"); + } const updated = await dependencies.intros.respond(input.eventId, input.introId, input.actorId, input.accept ? "accepted" : "declined"); if (updated.status === "accepted" && dependencies.notifications) { const requester = await dependencies.participants.findProfile(input.eventId, updated.requesterId); diff --git a/apps/web/src/domain/connection/connection.rules.ts b/apps/web/src/domain/connection/connection.rules.ts index e18d7f7..684899d 100644 --- a/apps/web/src/domain/connection/connection.rules.ts +++ b/apps/web/src/domain/connection/connection.rules.ts @@ -4,3 +4,26 @@ import type { IntroRequest } from "./intro-request.entity"; export function mayRevealContact(request: IntroRequest): boolean { return request.status === "accepted"; } + +/** Limits on introduction requests, per requester and event. */ +export const INTRO_LIMITS = { + perHour: 20, + pendingOutgoing: 25, +} as const; + +/** + * Whether a new request from `requesterId` may be created, given the requests + * already existing between the two people (either direction). A decline is + * final for the event, and a pending request the other way should be + * answered rather than duplicated. + */ +export function introRequestRefusal(requesterId: string, existing: IntroRequest[]): string | null { + for (const intro of existing) { + const mine = intro.requesterId === requesterId; + if (intro.status === "accepted") return "You are already connected"; + if (mine && intro.status === "pending") return "You already asked to meet them"; + if (mine && intro.status === "declined") return "They declined an earlier request, so you cannot ask again at this event"; + if (!mine && intro.status === "pending") return "They already asked to meet you. Accept their request on your Connections page"; + } + return null; +} diff --git a/apps/web/src/domain/participant/participant.entity.ts b/apps/web/src/domain/participant/participant.entity.ts index c82b367..53fe075 100644 --- a/apps/web/src/domain/participant/participant.entity.ts +++ b/apps/web/src/domain/participant/participant.entity.ts @@ -40,7 +40,7 @@ export type ParticipantProfileInput = Pick< | "interests" | "venueZone" | "formVersion" ->; +> & { visible?: boolean }; export function profileText(profile: ParticipantProfile): string { return [ diff --git a/apps/web/src/infrastructure/postgres/intro.repo.ts b/apps/web/src/infrastructure/postgres/intro.repo.ts index 4f58db0..88595fe 100644 --- a/apps/web/src/infrastructure/postgres/intro.repo.ts +++ b/apps/web/src/infrastructure/postgres/intro.repo.ts @@ -23,9 +23,7 @@ export class PostgresIntroRepository implements IntroRepository { const { rows } = await query( `insert into intro_requests (event_id, requester_id, recipient_id, message) values ($1, $2, $3, $4) - on conflict (event_id, requester_id, recipient_id) do update - set status = 'pending', message = excluded.message, created_at = now(), responded_at = null - where intro_requests.status = 'declined' + on conflict (event_id, requester_id, recipient_id) do nothing returning ${INTRO_COLUMNS}`, [input.eventId, input.requesterId, input.recipientId, message] ); @@ -52,11 +50,30 @@ export class PostgresIntroRepository implements IntroRepository { return mapIntro(rows[0]); } - async listForParticipant(eventId: string, participantId: string): Promise { + async findBetween(eventId: string, a: string, b: string): Promise { const { rows } = await query( `select ${INTRO_COLUMNS} from intro_requests - where event_id = $1 and (requester_id = $2 or recipient_id = $2) - order by created_at desc`, + where event_id = $1 and ((requester_id = $2 and recipient_id = $3) or (requester_id = $3 and recipient_id = $2))`, + [eventId, a, b] + ); + return rows.map(mapIntro); + } + + async countPendingOutgoing(eventId: string, requesterId: string): Promise { + const { rows } = await query<{ count: number }>( + `select count(*)::int as count from intro_requests where event_id = $1 and requester_id = $2 and status = 'pending'`, + [eventId, requesterId] + ); + return rows[0]?.count ?? 0; + } + + async listForParticipant(eventId: string, participantId: string): Promise { + const { rows } = await query( + `select ${INTRO_COLUMNS_R} from intro_requests r + join event_participants other on other.event_id = r.event_id + and other.attendee_id = case when r.requester_id = $2 then r.recipient_id else r.requester_id end + where r.event_id = $1 and (r.requester_id = $2 or r.recipient_id = $2) and other.revoked_at is null + order by r.created_at desc`, [eventId, participantId] ); return rows.map(mapIntro); @@ -71,6 +88,8 @@ export class PostgresIntroRepository implements IntroRepository { left join event_participants cp on cp.event_id = r.event_id and cp.attendee_id = c.id where r.event_id = $1 and r.status = 'accepted' and (r.requester_id = $2 or r.recipient_id = $2) + -- Someone removed from the event no longer has their contact shown. + and cp.revoked_at is null order by r.responded_at desc`, [eventId, participantId] ); diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index 8318ef0..c6bddb0 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -63,11 +63,12 @@ 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, profile_form_version = $12, embedding = null, profile_updated_at = now(), updated_at = now() + most_impressive_build = $11, profile_form_version = $12, visible = coalesce($13, visible), + 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.formVersion ?? 0] + input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0, input.visible ?? null] ); if (!rowCount) throw new Error("This attendee is not on the event roster"); const saved = await this.findProfile(input.eventId, input.attendeeId); diff --git a/tests/integration/connection-privacy.test.ts b/tests/integration/connection-privacy.test.ts new file mode 100644 index 0000000..ddd16b9 --- /dev/null +++ b/tests/integration/connection-privacy.test.ts @@ -0,0 +1,62 @@ +/** + * Connection privacy against a real Postgres: a declined request stays + * declined, and an attendee removed from the event disappears from other + * people's connections and contacts. 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 { PostgresIntroRepository } from "../../apps/web/src/infrastructure/postgres/intro.repo"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const RUN = Date.now().toString(36); +const ORG = `privacy-${RUN}`; +const email = (key: string) => `privacy-${key}-${RUN}@example.com`; + +describeDb("connection privacy", () => { + const intros = new PostgresIntroRepository(); + const ids: Record = {}; + let eventId: string; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(["ann", "bo", "cy"].map((key) => ({ name: key, email: email(key), phone: null }))); + for (const key of ["ann", "bo", "cy"]) 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)); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email like $1`, [`privacy-%-${RUN}@example.com`]); + await closePool(); + }); + + it("keeps a declined request declined", async () => { + const declined = await intros.create({ eventId, requesterId: ids.ann, recipientId: ids.bo }); + await intros.respond(eventId, declined.id, ids.bo, "declined"); + await expect(intros.create({ eventId, requesterId: ids.ann, recipientId: ids.bo })).rejects.toThrow(/already exists/); + expect((await intros.findById(eventId, declined.id))?.status).toBe("declined"); + expect(await intros.findBetween(eventId, ids.bo, ids.ann)).toHaveLength(1); + }); + + it("counts pending outgoing requests", async () => { + await intros.create({ eventId, requesterId: ids.cy, recipientId: ids.bo }); + expect(await intros.countPendingOutgoing(eventId, ids.cy)).toBe(1); + }); + + it("hides a removed attendee from connections and contacts", async () => { + const accepted = await intros.create({ eventId, requesterId: ids.ann, recipientId: ids.cy }); + await intros.respond(eventId, accepted.id, ids.cy, "accepted"); + expect((await intros.getRevealedContacts(eventId, ids.ann)).map((row) => row.contact.id)).toEqual([ids.cy]); + + await events.setRevoked(eventId, ids.cy, true); + expect((await intros.listForParticipant(eventId, ids.ann)).some((intro) => intro.id === accepted.id)).toBe(false); + expect(await intros.getRevealedContacts(eventId, ids.ann)).toEqual([]); + + await events.setRevoked(eventId, ids.cy, false); + expect((await intros.getRevealedContacts(eventId, ids.ann)).map((row) => row.contact.id)).toEqual([ids.cy]); + }); +}); diff --git a/tests/unit/candidate-eligibility.test.ts b/tests/unit/candidate-eligibility.test.ts index 5ac19bc..eab1454 100644 --- a/tests/unit/candidate-eligibility.test.ts +++ b/tests/unit/candidate-eligibility.test.ts @@ -64,7 +64,9 @@ describe("intro request recipient", () => { hasEventAccess: vi.fn(async () => true), findProfile: vi.fn(async (_eventId: string, id: string) => (id === "requester" ? profile("requester") : recipient)), } as unknown as ParticipantRepository; - const intros = { create: vi.fn(async () => ({ id: "intro" })) } as unknown as IntroRepository; + const intros = { + create: vi.fn(async () => ({ id: "intro" })), findBetween: vi.fn(async () => []), countPendingOutgoing: vi.fn(async () => 0), + } as unknown as IntroRepository; return { participants, intros }; } const send = (dependencies: ReturnType, recipientId: string) => diff --git a/tests/unit/intro-rules.test.ts b/tests/unit/intro-rules.test.ts new file mode 100644 index 0000000..e6ffc3e --- /dev/null +++ b/tests/unit/intro-rules.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from "vitest"; +import { INTRO_LIMITS, introRequestRefusal } from "@/src/domain/connection/connection.rules"; +import { requestIntro } from "@/src/application/use-cases/request-intro"; +import type { IntroRequest } from "@/src/domain/connection/intro-request.entity"; + +const intro = (requesterId: string, recipientId: string, status: IntroRequest["status"]): IntroRequest => ({ + id: `${requesterId}-${recipientId}`, eventId: "event", requesterId, recipientId, status, message: null, createdAt: new Date(), respondedAt: null, +}); + +describe("intro request rules", () => { + it.each([ + [[], null], + [[intro("a", "b", "pending")], /already asked to meet them/], + [[intro("a", "b", "declined")], /declined an earlier request/], + [[intro("b", "a", "pending")], /already asked to meet you/], + [[intro("b", "a", "accepted")], /already connected/], + [[intro("b", "a", "declined")], null], + ] as const)("refuses or allows a request from a given %o", (existing, expected) => { + const refusal = introRequestRefusal("a", [...existing]); + if (expected === null) expect(refusal).toBeNull(); + else expect(refusal).toMatch(expected); + }); +}); + +function deps(overrides: { existing?: IntroRequest[]; pending?: number; allowed?: boolean } = {}) { + const profile = (id: string) => ({ attendeeId: id, name: id, visible: true, profileComplete: true, email: `${id}@example.com` }); + return { + participants: { hasEventAccess: vi.fn(async () => true), findProfile: vi.fn(async (_e: string, id: string) => profile(id)) }, + intros: { + findBetween: vi.fn(async () => overrides.existing ?? []), + countPendingOutgoing: vi.fn(async () => overrides.pending ?? 0), + create: vi.fn(async () => intro("a", "b", "pending")), + }, + limiter: { consume: vi.fn(async () => overrides.allowed ?? true) }, + }; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const ask = (dependencies: ReturnType) => requestIntro({ eventId: "event", requesterId: "a", recipientId: "b" }, dependencies as any); + +describe("requestIntro abuse controls", () => { + it("creates a request when nothing blocks it", async () => { + const d = deps(); + await ask(d); + expect(d.intros.create).toHaveBeenCalled(); + expect(d.limiter.consume).toHaveBeenCalledWith("intro:event:a", INTRO_LIMITS.perHour, 3600); + }); + + it("refuses a request to yourself", async () => { + const d = deps(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await expect(requestIntro({ eventId: "event", requesterId: "a", recipientId: "a" }, d as any)).rejects.toThrow(/yourself/); + }); + + it("refuses after a decline, with too many pending, or over the hourly limit", async () => { + await expect(ask(deps({ existing: [intro("a", "b", "declined")] }))).rejects.toThrow(/declined/); + await expect(ask(deps({ pending: INTRO_LIMITS.pendingOutgoing }))).rejects.toThrow(/waiting for an answer/); + await expect(ask(deps({ allowed: false }))).rejects.toThrow(/this hour/); + }); +}); From b81b1e5d22112a3f8fd3a251553d2dcae0ce2788 Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 03:35:15 +0530 Subject: [PATCH 08/34] Record sensitive actions and enforce data retention (R19 part 2) - Migration 0010: audit_events (event, actor, action, subject, details with counts and field names only). Recorded: roster imports, invitations, access removed/restored, settings and profile-form changes, introductions accepted (contacts shared), and account disable/enable/revoke/erase. Recording failures are logged and never block the action. Organizers see "Recent activity" on the analytics page. Records are kept for a year by the hourly sweep and survive their event's deletion - Removing someone from an event deletes cached explanations written about or for them; hiding a profile deletes explanations of it - npm run account:erase -- --yes for deletion requests: deletes the Keycloak user first (so a failure leaves data to retry), then the attendee and everything cascading from it, cached explanations and login challenges; refuses without --yes - Tests: real Postgres for records, sweep, retention on removal and hiding, and erasure against the local Keycloak realm --- ReadMe.md | 1 + .../events/[eventSlug]/analytics/page.tsx | 25 ++++- apps/web/app/actions/organizer.actions.ts | 8 +- apps/web/src/application/ports/audit-log.ts | 14 +++ .../src/application/use-cases/manage-event.ts | 15 ++- .../use-cases/manage-invitations.ts | 12 ++- .../application/use-cases/respond-to-intro.ts | 6 +- apps/web/src/composition/container.ts | 2 + .../src/infrastructure/postgres/audit.repo.ts | 19 ++++ .../postgres/participant.repo.ts | 4 + package.json | 3 +- packages/auth/src/index.ts | 1 + packages/auth/src/keycloak.ts | 7 ++ packages/db/migrations/0010_audit_events.sql | 17 ++++ packages/db/src/index.ts | 1 + packages/db/src/repositories/attendees.ts | 17 ++++ packages/db/src/repositories/audit.ts | 43 ++++++++ packages/db/src/repositories/events.ts | 4 + packages/db/src/repositories/housekeeping.ts | 5 +- tests/integration/audit-retention.test.ts | 97 +++++++++++++++++++ tests/unit/invitations.test.ts | 11 +++ tools/manage-account.ts | 37 +++++-- 22 files changed, 329 insertions(+), 20 deletions(-) create mode 100644 apps/web/src/application/ports/audit-log.ts create mode 100644 apps/web/src/infrastructure/postgres/audit.repo.ts create mode 100644 packages/db/migrations/0010_audit_events.sql create mode 100644 packages/db/src/repositories/audit.ts create mode 100644 tests/integration/audit-retention.test.ts diff --git a/ReadMe.md b/ReadMe.md index a5d93b0..818de3f 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -110,6 +110,7 @@ The first command imports the global attendee directory so the organizer account | `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 account:erase -- --yes` | Deletion request: delete the person, their event profiles, matches, introductions, cached explanations and Keycloak user (recorded in the audit log) | | `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/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx index a7a028c..f246a3f 100644 --- a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx @@ -5,7 +5,7 @@ import { requireOrganizerEvent } from "@/src/lib/auth"; export default async function AnalyticsPage({ params }: { params: Promise<{ orgSlug: string; eventSlug: string }> }) { const { orgSlug, eventSlug } = await params; const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); - const analytics = await container.events.analytics(event.id); + const [analytics, activity] = await Promise.all([container.events.analytics(event.id), container.audit.recent(event.id)]); const completion = analytics.roster ? Math.round(analytics.profiles / analytics.roster * 100) : 0; return
@@ -20,9 +20,32 @@ export default async function AnalyticsPage({ params }: { params: Promise<{ orgS +

Recent activity

+ {!activity.length ?

No recorded activity yet.

:
    + {activity.map((item) =>
  • + {ACTIVITY_LABELS[item.action] ?? item.action} + {item.subjectName && <> · {item.subjectName}} +
    {item.actorName ?? "System"} · {item.createdAt.toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" })}{summary(item.details)} +
  • )} +
}
; } +const ACTIVITY_LABELS: Record = { + "roster.imported": "Roster imported", + "invitations.sent": "Invitations sent", + "access.removed": "Access removed", + "access.restored": "Access restored", + "event.updated": "Settings changed", + "profile_form.updated": "Profile form changed", + "contacts.revealed": "Introduction accepted, contacts shared", +}; + +function summary(details: Record): string { + const parts = ["attached", "sent", "failed", "version"].filter((key) => typeof details[key] === "number").map((key) => `${key} ${details[key]}`); + return parts.length ? ` · ${parts.join(", ")}` : ""; +} + function Card({ label, value, note }: { label: string; value: number | string; note?: string }) { return
{label}{value}{note && {note}}
; } diff --git a/apps/web/app/actions/organizer.actions.ts b/apps/web/app/actions/organizer.actions.ts index a1d756a..fa5c761 100644 --- a/apps/web/app/actions/organizer.actions.ts +++ b/apps/web/app/actions/organizer.actions.ts @@ -43,7 +43,7 @@ async function importRoster(organizationSlug: string, eventSlug: string, formDat const event = await container.events.findBySlug(organizationSlug, eventSlug); 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); + const result = await importEventRoster({ eventId: event.id, organizerId: session.attendeeId, records }, container.events, container.audit); const report = new URLSearchParams({ imported: String(result.attached), skipped: String(skipped), already: String(result.alreadyOnRoster), kept: String(result.keptExisting), phones: String(result.phoneConflicts), @@ -73,7 +73,7 @@ async function saveEvent(organizationSlug: string, eventSlug: string, formData: status: status as "draft" | "open" | "closed", intents, zones, - }, container.events); + }, container.events, container.audit); redirect(`/orgs/${organizationSlug}/events/${eventSlug}?saved=1`); } @@ -88,7 +88,7 @@ async function queueMatches(organizationSlug: string, eventSlug: string) { const event = await container.events.findBySlug(organizationSlug, eventSlug); if (!event) throw new Error("Event not found"); assertEventAllows(event.status, "computeMatches"); - if (event.status === "draft") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events); + if (event.status === "draft") await updateEvent({ eventId: event.id, organizerId: session.attendeeId, status: "open" }, container.events, container.audit); const queued = await queueEventMatches({ eventId: event.id, organizerId: session.attendeeId }, container.events, container.enqueueEmbedding); redirect(`/orgs/${organizationSlug}/events/${eventSlug}/matching?queued=${queued}`); } @@ -138,7 +138,7 @@ export async function updateProfileFormAction(organizationSlug: string, eventSlu 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); + await configureProfileForm({ eventId: event.id, organizerId: session.attendeeId, fields, currentConfig: event.form_config }, container.events, container.audit); redirect(`/orgs/${organizationSlug}/events/${eventSlug}?form=saved`); }); } diff --git a/apps/web/src/application/ports/audit-log.ts b/apps/web/src/application/ports/audit-log.ts new file mode 100644 index 0000000..228950f --- /dev/null +++ b/apps/web/src/application/ports/audit-log.ts @@ -0,0 +1,14 @@ +/** Records sensitive actions. Recording must never block or fail the action itself. */ +export interface AuditLog { + record(entry: { + eventId?: string | null; + actorId?: string | null; + action: string; + subjectId?: string | null; + details?: Record; + }): Promise; + /** The event's most recent records, newest first, with people's names. */ + recent(eventId: string, limit?: number): Promise; createdAt: Date; + }>>; +} diff --git a/apps/web/src/application/use-cases/manage-event.ts b/apps/web/src/application/use-cases/manage-event.ts index fcbd9f2..d800e8f 100644 --- a/apps/web/src/application/use-cases/manage-event.ts +++ b/apps/web/src/application/use-cases/manage-event.ts @@ -1,4 +1,5 @@ import type { EventRepository, RosterAttendeeInput } from "../ports/event-repository"; +import type { AuditLog } from "../ports/audit-log"; import { slugify } from "../../domain/shared/value-objects"; import { Intent } from "../../domain/participant/intent"; import { boundedItems, boundedText, LIMITS, ValidationError } from "../../domain/shared/validation"; @@ -29,7 +30,7 @@ export async function updateEvent(input: { status?: "draft" | "open" | "closed"; intents?: string[]; zones?: string[]; -}, events: EventRepository) { +}, events: EventRepository, audit?: AuditLog) { await authorizeOrganizer(events, input.eventId, input.organizerId, "configure"); const updated = await events.update({ ...input, @@ -41,13 +42,17 @@ export async function updateEvent(input: { : boundedItems(input.zones, "zones", "venue zones", { count: LIMITS.zoneCount, length: LIMITS.zoneLength }), }); if (!updated) throw new Error("Event not found"); + const fields = Object.keys(input).filter((key) => !["eventId", "organizerId"].includes(key) && input[key as keyof typeof input] !== undefined); + await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "event.updated", details: { fields, status: updated.status } }); return updated; } -export async function importEventRoster(input: { eventId: string; organizerId: string; records: RosterAttendeeInput[] }, events: EventRepository) { +export async function importEventRoster(input: { eventId: string; organizerId: string; records: RosterAttendeeInput[] }, events: EventRepository, audit?: AuditLog) { 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); + const result = await events.importRoster(input.eventId, input.records); + await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "roster.imported", details: { rows: input.records.length, ...result } }); + return result; } export async function queueEventMatches(input: { eventId: string; organizerId: string }, events: EventRepository, enqueue: (eventId: string, participantId: string) => Promise) { @@ -73,11 +78,13 @@ function eventIntents(values: string[]) { /** 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 + events: EventRepository, + audit?: AuditLog ) { 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"); + await audit?.record({ eventId: input.eventId, actorId: input.organizerId, action: "profile_form.updated", details: { version: form.version } }); return form; } diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts index 869c987..f6bb05d 100644 --- a/apps/web/src/application/use-cases/manage-invitations.ts +++ b/apps/web/src/application/use-cases/manage-invitations.ts @@ -2,6 +2,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"; +import type { AuditLog } from "../ports/audit-log"; export interface InvitationResult { sent: number; @@ -15,7 +16,7 @@ export interface InvitationResult { */ export async function sendInvitations( input: { eventId: string; organizerId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string }, - dependencies: { events: EventRepository; notifications: NotificationPort } + dependencies: { events: EventRepository; notifications: NotificationPort; audit?: AuditLog } ): Promise { await authorizeOrganizer(dependencies.events, input.eventId, input.organizerId, "invite"); const targets = await dependencies.events.invitationTargets(input.eventId, input.attendeeId ?? null, RESEND_AFTER_MINUTES); @@ -40,6 +41,10 @@ export async function sendInvitations( result.failed += 1; } } + await dependencies.audit?.record({ + eventId: input.eventId, actorId: input.organizerId, action: "invitations.sent", + subjectId: input.attendeeId ?? null, details: { ...result, resend: Boolean(input.attendeeId) }, + }); return result; } @@ -50,10 +55,13 @@ export async function sendInvitations( */ export async function setAttendeeAccess( input: { eventId: string; organizerId: string; attendeeId: string; revoked: boolean }, - dependencies: { events: EventRepository } + dependencies: { events: EventRepository; audit?: AuditLog } ): Promise { 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"); } + await dependencies.audit?.record({ + eventId: input.eventId, actorId: input.organizerId, action: input.revoked ? "access.removed" : "access.restored", subjectId: input.attendeeId, + }); } diff --git a/apps/web/src/application/use-cases/respond-to-intro.ts b/apps/web/src/application/use-cases/respond-to-intro.ts index 3ee9ba2..fe9492d 100644 --- a/apps/web/src/application/use-cases/respond-to-intro.ts +++ b/apps/web/src/application/use-cases/respond-to-intro.ts @@ -1,10 +1,11 @@ import type { IntroRepository } from "../ports/intro-repository"; import type { NotificationPort } from "../ports/notification"; import type { ParticipantRepository } from "../ports/participant-repository"; +import type { AuditLog } from "../ports/audit-log"; export async function respondToIntro( input: { eventId: string; introId: string; actorId: string; accept: boolean; eventName?: string }, - dependencies: { intros: IntroRepository; participants: ParticipantRepository; notifications?: NotificationPort } + dependencies: { intros: IntroRepository; participants: ParticipantRepository; notifications?: NotificationPort; audit?: AuditLog } ) { const existing = await dependencies.intros.findById(input.eventId, input.introId); if (!existing) throw new Error("Intro request not found"); @@ -12,6 +13,9 @@ export async function respondToIntro( throw new Error("This person is no longer part of the event"); } const updated = await dependencies.intros.respond(input.eventId, input.introId, input.actorId, input.accept ? "accepted" : "declined"); + if (updated.status === "accepted") { + await dependencies.audit?.record({ eventId: input.eventId, actorId: input.actorId, action: "contacts.revealed", subjectId: updated.requesterId }); + } if (updated.status === "accepted" && dependencies.notifications) { const requester = await dependencies.participants.findProfile(input.eventId, updated.requesterId); const recipient = await dependencies.participants.findProfile(input.eventId, updated.recipientId); diff --git a/apps/web/src/composition/container.ts b/apps/web/src/composition/container.ts index 636323a..05b44b7 100644 --- a/apps/web/src/composition/container.ts +++ b/apps/web/src/composition/container.ts @@ -4,6 +4,7 @@ import { PostgresMatchRepository } from "../infrastructure/postgres/match.repo"; import { PostgresParticipantRepository } from "../infrastructure/postgres/participant.repo"; import { PostgresRateLimiter } from "../infrastructure/cache/postgres-rate-limiter"; import { PostgresEventRepository } from "../infrastructure/postgres/event.repo"; +import { PostgresAuditLog } from "../infrastructure/postgres/audit.repo"; import { PostgresMatchQueue } from "../infrastructure/postgres/match-queue.repo"; import { PostgresCandidateCache } from "../infrastructure/cache/postgres-candidate-cache"; import { PostgresExplanationCache } from "../infrastructure/cache/postgres-explanation-cache"; @@ -31,6 +32,7 @@ function buildContainer() { llm, candidateCache, matchQueue: new PostgresMatchQueue(), + audit: new PostgresAuditLog(), notifications: new RealtimeNotifier(), limiter: new PostgresRateLimiter(), pipeline: new MatchingPipeline(participants, matches, embeddings, llm, candidateCache, new PostgresExplanationCache()), diff --git a/apps/web/src/infrastructure/postgres/audit.repo.ts b/apps/web/src/infrastructure/postgres/audit.repo.ts new file mode 100644 index 0000000..69603c3 --- /dev/null +++ b/apps/web/src/infrastructure/postgres/audit.repo.ts @@ -0,0 +1,19 @@ +import { audit } from "@match-maker/db"; +import type { AuditLog } from "../../application/ports/audit-log"; + +export class PostgresAuditLog implements AuditLog { + async record(entry: Parameters[0]): Promise { + try { + await audit.record(entry); + } catch (error) { + // An unavailable audit table must not undo or block the action it records. + console.error("[audit] could not record", entry.action, error); + } + } + + async recent(eventId: string, limit = 20) { + return (await audit.listForEvent(eventId, limit)).map((row) => ({ + id: row.id, action: row.action, actorName: row.actor_name, subjectName: row.subject_name, details: row.details, createdAt: row.created_at, + })); + } +} diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index c6bddb0..6063788 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -71,6 +71,10 @@ export class PostgresParticipantRepository implements ParticipantRepository { input.yearsOfExperience, input.mostImpressiveBuild, input.formVersion ?? 0, input.visible ?? null] ); if (!rowCount) throw new Error("This attendee is not on the event roster"); + if (input.visible === false) { + // Hidden profiles are not explained to others any more. + await query(`delete from pair_explanations where event_id = $1 and candidate_id = $2`, [input.eventId, input.attendeeId]); + } const saved = await this.findProfile(input.eventId, input.attendeeId); if (!saved) throw new Error("Could not load the saved profile"); return saved; diff --git a/package.json b/package.json index 4e6833c..3001b6e 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "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" + "account:revoke-sessions": "tsx tools/manage-account.ts revoke-sessions", + "account:erase": "tsx tools/manage-account.ts erase" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index 2a7239b..6c82d83 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -33,6 +33,7 @@ export { isUserEnabled, setUserEnabled, logoutUser, + deleteUser, resetCaches, type Pkce, type TokenSet, diff --git a/packages/auth/src/keycloak.ts b/packages/auth/src/keycloak.ts index da23cae..aca8fe5 100644 --- a/packages/auth/src/keycloak.ts +++ b/packages/auth/src/keycloak.ts @@ -387,6 +387,13 @@ export async function setUserEnabled(sub: string, enabled: boolean): Promise { + const res = await adminFetch(`/users/${encodeURIComponent(sub)}`, { method: "DELETE" }); + if (!res.ok && res.status !== 404) throw new Error(`Keycloak user deletion failed (${res.status})`); + 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" }); diff --git a/packages/db/migrations/0010_audit_events.sql b/packages/db/migrations/0010_audit_events.sql new file mode 100644 index 0000000..d9c0983 --- /dev/null +++ b/packages/db/migrations/0010_audit_events.sql @@ -0,0 +1,17 @@ +-- Security audit records: who did what to whom, for sensitive actions +-- (roster imports, invitations, access changes, settings, contact reveals, +-- account administration). Details hold counts and field names, never +-- contact data. Kept for a year by the housekeeping sweep. + +create table if not exists audit_events ( + id bigserial primary key, + event_id uuid references events(id) on delete set null, + actor_id uuid, + action text not null, + subject_id uuid, + details jsonb not null default '{}'::jsonb, + created_at timestamptz not null default now() +); + +create index if not exists idx_audit_events_event on audit_events (event_id, created_at desc); +create index if not exists idx_audit_events_created on audit_events (created_at); diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 8d37dd8..596eb49 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -12,3 +12,4 @@ export * as matches from "./repositories/matches"; export * as events from "./repositories/events"; export * as matchingJobs from "./repositories/matching-jobs"; export * as housekeeping from "./repositories/housekeeping"; +export * as audit from "./repositories/audit"; diff --git a/packages/db/src/repositories/attendees.ts b/packages/db/src/repositories/attendees.ts index 32866ad..d41a6ee 100644 --- a/packages/db/src/repositories/attendees.ts +++ b/packages/db/src/repositories/attendees.ts @@ -93,6 +93,23 @@ export async function revokeSessions(email: string): Promise { return (rowCount ?? 0) > 0; } +/** + * Erases a person for a deletion request: their attendee row and everything + * that cascades from it (event participation, matches, introductions, login + * challenges), plus cached explanations and login challenges by e-mail. + * Returns the erased id, or null when the e-mail is unknown. + */ +export async function erase(email: string): Promise { + const normalized = normalizeEmail(email); + const { rows } = await query<{ id: string }>(`select id from registered_attendees where email = $1`, [normalized]); + const id = rows[0]?.id; + if (!id) return null; + await query(`delete from pair_explanations where viewer_id = $1 or candidate_id = $1`, [id]); + await query(`delete from login_challenges where email = $1`, [normalized]); + await query(`delete from registered_attendees where id = $1`, [id]); + return id; +} + /** 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/repositories/audit.ts b/packages/db/src/repositories/audit.ts new file mode 100644 index 0000000..e433f61 --- /dev/null +++ b/packages/db/src/repositories/audit.ts @@ -0,0 +1,43 @@ +import { query } from "../client"; + +export interface AuditEntry { + eventId?: string | null; + actorId?: string | null; + action: string; + subjectId?: string | null; + /** Counts and field names only, never contact data. */ + details?: Record; +} + +export interface AuditRecord { + id: string; + action: string; + actor_name: string | null; + subject_name: string | null; + details: Record; + created_at: Date; +} + +/** Audit records are kept this long, then swept. */ +export const AUDIT_RETENTION_DAYS = 365; + +export async function record(entry: AuditEntry): Promise { + await query( + `insert into audit_events (event_id, actor_id, action, subject_id, details) values ($1, $2, $3, $4, $5::jsonb)`, + [entry.eventId ?? null, entry.actorId ?? null, entry.action, entry.subjectId ?? null, JSON.stringify(entry.details ?? {})] + ); +} + +export async function listForEvent(eventId: string, limit = 20): Promise { + const { rows } = await query( + `select e.id::text as id, e.action, actor.name as actor_name, subject.name as subject_name, e.details, e.created_at + from audit_events e + left join registered_attendees actor on actor.id = e.actor_id + left join registered_attendees subject on subject.id = e.subject_id + where e.event_id = $1 + order by e.created_at desc, e.id desc + limit $2`, + [eventId, limit] + ); + return rows; +} diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 97b8ede..979dc01 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -246,6 +246,10 @@ export async function setRevoked(eventId: string, attendeeId: string, revoked: b where event_id = $1 and attendee_id = $2`, [eventId, attendeeId, revoked] ); + // Explanations written about or for a removed attendee are not kept. + if (revoked && rowCount) { + await query(`delete from pair_explanations where event_id = $1 and (viewer_id = $2 or candidate_id = $2)`, [eventId, attendeeId]); + } return (rowCount ?? 0) > 0; } diff --git a/packages/db/src/repositories/housekeeping.ts b/packages/db/src/repositories/housekeeping.ts index 42226c9..36f995e 100644 --- a/packages/db/src/repositories/housekeeping.ts +++ b/packages/db/src/repositories/housekeeping.ts @@ -1,5 +1,6 @@ import { query } from "../client"; import { deleteExpired as deleteExpiredChallenges } from "./login-challenges"; +import { AUDIT_RETENTION_DAYS } from "./audit"; /** How long a dead row is kept before the sweep removes it. */ export const RETENTION = { @@ -14,6 +15,7 @@ export interface SweepResult { rateLimitBuckets: number; retrievalCache: number; pairExplanations: number; + auditEvents: number; } /** Deletes rows that can no longer be used. Safe to run on any schedule. */ @@ -25,8 +27,9 @@ export async function sweepExpired(): Promise { ); const cache = await query(`delete from retrieval_cache where expires_at < now()`); const explanations = await query(`delete from pair_explanations where expires_at < now()`); + const audits = await query(`delete from audit_events where created_at < now() - make_interval(days => $1)`, [AUDIT_RETENTION_DAYS]); return { loginChallenges, rateLimitBuckets: buckets.rowCount ?? 0, retrievalCache: cache.rowCount ?? 0, - pairExplanations: explanations.rowCount ?? 0, + pairExplanations: explanations.rowCount ?? 0, auditEvents: audits.rowCount ?? 0, }; } diff --git a/tests/integration/audit-retention.test.ts b/tests/integration/audit-retention.test.ts new file mode 100644 index 0000000..d9b8b61 --- /dev/null +++ b/tests/integration/audit-retention.test.ts @@ -0,0 +1,97 @@ +/** + * Audit records and data retention against a real Postgres (and the local + * Keycloak realm for erasure). Uses its own organization, event and people. + * Skipped when DATABASE_URL is unset; the erase case also needs Keycloak. + */ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { attendees, audit, closePool, events, housekeeping, query } from "@match-maker/db"; +import { ensureUser, findUserByEmail } from "@match-maker/auth"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; +import { manageAccount } from "../../tools/manage-account"; +import { Intent } from "../../apps/web/src/domain/participant/intent"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const issuer = (process.env.KEYCLOAK_INTERNAL_ISSUER || process.env.KEYCLOAK_ISSUER || "").replace(/\/$/, ""); +const keycloakUp = await fetch(`${issuer}/.well-known/openid-configuration`, { signal: AbortSignal.timeout(3000) }).then((res) => res.ok).catch(() => false); +const RUN = Date.now().toString(36); +const ORG = `audit-${RUN}`; +const email = (key: string) => `audit-${key}-${RUN}@example.com`; + +describeDb("audit records and retention", () => { + const participants = new PostgresParticipantRepository(); + const ids: Record = {}; + let eventId: string; + + const explain = (viewer: string, candidate: string) => query( + `insert into pair_explanations (cache_key, event_id, viewer_id, candidate_id, reason, expires_at) + values ($1, $2, $3, $4, 'reason', now() + interval '1 day')`, [randomUUID(), eventId, viewer, candidate]); + const explanationsAbout = async (id: string) => + (await query(`select 1 from pair_explanations where viewer_id = $1 or candidate_id = $1`, [id])).rows.length; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(["org", "kim", "lou", "max"].map((key) => ({ name: `Audit ${key}`, email: email(key) }))); + for (const key of ["org", "kim", "lou", "max"]) 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, [ids.kim, ids.lou, ids.max]); + }); + + afterAll(async () => { + await query(`delete from audit_events where subject_id = any($1::uuid[]) or actor_id = any($1::uuid[])`, [Object.values(ids)]); + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email like $1`, [`audit-%-${RUN}@example.com`]); + await closePool(); + }); + + it("records actions with the people involved, newest first", async () => { + await audit.record({ eventId, actorId: ids.org, action: "roster.imported", details: { attached: 3 } }); + await audit.record({ eventId, actorId: ids.org, action: "access.removed", subjectId: ids.kim }); + const recent = await audit.listForEvent(eventId); + expect(recent.map((row) => row.action)).toEqual(["access.removed", "roster.imported"]); + expect(recent[0]).toMatchObject({ actor_name: "Audit org", subject_name: "Audit kim" }); + expect(recent[1].details).toEqual({ attached: 3 }); + }); + + it("sweeps records older than the retention period", async () => { + await audit.record({ eventId, action: "old.action", subjectId: ids.lou }); + await query(`update audit_events set created_at = now() - interval '400 days' where action = 'old.action' and subject_id = $1`, [ids.lou]); + await housekeeping.sweepExpired(); + expect((await query(`select 1 from audit_events where action = 'old.action' and subject_id = $1`, [ids.lou])).rows).toHaveLength(0); + }); + + it("drops cached explanations about someone removed from the event", async () => { + await explain(ids.kim, ids.lou); + await explain(ids.lou, ids.kim); + await events.setRevoked(eventId, ids.kim, true); + expect(await explanationsAbout(ids.kim)).toBe(0); + }); + + it("drops explanations of a profile that is hidden", async () => { + await explain(ids.max, ids.lou); + await participants.saveProfile({ + eventId, attendeeId: ids.lou, designation: "Engineer", domain: "AI", aboutMe: "x", selfDescription: null, + yearsOfExperience: null, mostImpressiveBuild: null, intent: Intent.NETWORKING, interests: [], venueZone: null, visible: false, + }); + expect(await explanationsAbout(ids.lou)).toBe(0); + }); + + (keycloakUp && process.env.KEYCLOAK_ADMIN_PASSWORD ? it : it.skip)("erases a person, their event data and their Keycloak user", async () => { + await ensureUser(email("max"), "Audit max"); + await explain(ids.lou, ids.max); + const report = await manageAccount("erase", email("max")); + expect(report.join("\n")).toMatch(/keycloak: user deleted/); + expect(await attendees.findByEmail(email("max"))).toBeNull(); + expect((await query(`select 1 from event_participants where attendee_id = $1`, [ids.max])).rows).toHaveLength(0); + expect(await explanationsAbout(ids.max)).toBe(0); + expect(await findUserByEmail(email("max"))).toBeNull(); + expect((await query(`select 1 from audit_events where action = 'account.erased' and subject_id = $1`, [ids.max])).rows).toHaveLength(1); + }); + + it("keeps records when their event is deleted", async () => { + await query(`delete from events where id = $1`, [eventId]); + expect((await query(`select event_id from audit_events where action = 'roster.imported' and actor_id = $1`, [ids.org])).rows[0].event_id).toBeNull(); + }); +}); diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts index 35c176b..595497e 100644 --- a/tests/unit/invitations.test.ts +++ b/tests/unit/invitations.test.ts @@ -84,6 +84,17 @@ describe("setAttendeeAccess", () => { }); }); +describe("audit records", () => { + it("records invitations sent and access changes", async () => { + const { events, notifications } = ports([{ attendee_id: "a", email: "a@example.com", name: "A" }]); + const audit = { record: vi.fn(async () => {}), recent: vi.fn() }; + await sendInvitations(event, { events, notifications, audit }); + await setAttendeeAccess({ eventId: "event", organizerId: "organizer", attendeeId: "a", revoked: true }, { events, audit }); + expect(audit.record).toHaveBeenCalledWith(expect.objectContaining({ action: "invitations.sent", actorId: "organizer", details: expect.objectContaining({ sent: 1 }) })); + expect(audit.record).toHaveBeenCalledWith(expect.objectContaining({ action: "access.removed", subjectId: "a" })); + }); +}); + describe("renderInvitationEmail", () => { it("links to the event and escapes names in the HTML", () => { const mail = renderInvitationEmail({ name: "