diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f160b66 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +.git +.github +node_modules +**/node_modules +**/.next +**/dist +.next + +# env files must never bake into an image — ECS injects them at runtime +.env +.env.* +!.env.example + +# PII — never goes into an image +*.xlsx + +docs +infra/terraform/.terraform +infra/terraform/*.tfstate* +**/*.log +**/.DS_Store +.gemini-cache.json +README.md +ReadMe.md +LICENSE diff --git a/.env.example b/.env.example index c4705f3..a4fe63f 100644 --- a/.env.example +++ b/.env.example @@ -1,10 +1,105 @@ -# Copy this file to .env.local and fill in your values -# Supabase — get these from your Supabase project settings > API -NEXT_PUBLIC_SUPABASE_URL=your_supabase_project_url -NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key +# ============================================================== +# Copy to .env and fill in. docker-compose reads .env automatically. +# Nothing here is exposed to the browser — there are no NEXT_PUBLIC_* vars. +# ============================================================== -# Service key — NEVER expose this to the browser, server/scripts only -SUPABASE_SERVICE_KEY=your_supabase_service_role_key +# ── App ─────────────────────────────────────────────────────── +# Public origin. Must match the Keycloak client's redirect URI. +APP_BASE_URL=http://localhost:3000 +WEB_PORT=3000 +DEFAULT_EVENT_SLUG=demo -# Gemini API — server-side only, never prefix with NEXT_PUBLIC_ -GEMINI_API_KEY=your_gemini_api_key_here +# Encrypts the session cookie. REQUIRED, min 32 chars. +# openssl rand -base64 48 +SESSION_SECRET= +# While rotating: the old secret(s), comma-separated, still accepted for +# reading cookies for one session lifetime so nobody is signed out. +# SESSION_SECRET_PREVIOUS= +# Hashes login codes. Defaults to SESSION_SECRET; set it separately in +# production so rotating the session secret leaves codes in flight working. +# OTP_PEPPER= + +# ── Postgres ────────────────────────────────────────────────── +POSTGRES_USER=matchmaker +POSTGRES_PASSWORD=matchmaker +POSTGRES_DB=matchmaker +POSTGRES_PORT=5432 + +# Used by scripts run on the HOST (migrate/seed/import). +# Inside docker-compose the host is `postgres`, not `localhost`. +DATABASE_URL=postgres://matchmaker:matchmaker@localhost:5432/matchmaker +# disable (local, no TLS) | require (encrypted, unverified) | verify (encrypted, +# certificate checked against DATABASE_CA_CERT or DATABASE_CA_CERT_FILE). +# Production refuses anything but verify for a remote database. +DATABASE_SSL=disable +# DATABASE_CA_CERT_FILE=/etc/ssl/certs/rds-global-bundle.pem + +# Deployed only: the migration task creates these least-privilege logins +# (packages/db/src/ensure-roles.ts); web and worker then use the runtime one. +# DATABASE_RUNTIME_USER=app_runtime +# DATABASE_RUNTIME_PASSWORD= +# KEYCLOAK_DB_USER=keycloak +# KEYCLOAK_DB_PASSWORD= + +# ── Keycloak ────────────────────────────────────────────────── +KEYCLOAK_PORT=8080 +KEYCLOAK_PUBLIC_URL=http://localhost:8080 +KEYCLOAK_ADMIN=admin +KEYCLOAK_ADMIN_PASSWORD=admin + +# Issuer as the BROWSER sees it — also the expected `iss` claim. +KEYCLOAK_ISSUER=http://localhost:8080/realms/match-maker +# Issuer as the APP sees it for server-to-server calls. Host processes use +# localhost; docker-compose overrides it with http://keycloak:8080 for the web container. +KEYCLOAK_INTERNAL_ISSUER=http://localhost:8080/realms/match-maker +KEYCLOAK_CLIENT_ID=match-maker-web +KEYCLOAK_CLIENT_SECRET=dev-client-secret-change-me +KEYCLOAK_GOOGLE_IDP_ALIAS=google + +# ── Google sign-in ──────────────────────────────────────────── +# From Google Cloud Console > APIs & Services > Credentials. +# Authorised redirect URI must be: +# http://localhost:8080/realms/match-maker/broker/google/endpoint +# Leave blank to develop with the e-mail-code path only; the login page shows +# "Sign in with Google" only when GOOGLE_CLIENT_ID is set. After changing these +# (or KEYCLOAK_CLIENT_SECRET) on an existing realm, run: npm run keycloak:sync +GOOGLE_CLIENT_ID= +GOOGLE_CLIENT_SECRET= + +# ── Resend (login e-mails) ──────────────────────────────────── +# The web app refuses to start without a key unless EMAIL_DEV_FALLBACK=true. +# EMAIL_FROM must use a domain verified in Resend. +RESEND_API_KEY= +EMAIL_FROM=Mr. Bridge + +# With no RESEND_API_KEY, print login e-mails to the server log instead of +# sending them. Local development only — never set this in a deployed +# environment, or logins will silently never arrive. +EMAIL_DEV_FALLBACK=true + +# Code + magic-link lifetime and throttling. +OTP_TTL_SECONDS=600 +OTP_MAX_PER_WINDOW=5 +OTP_RATE_WINDOW_SECONDS=900 + +# Seconds the worker waits before refreshing other people's matches after a +# profile change, so bursts of changes coalesce (default 120). +# MATCH_REFRESH_DELAY_SECONDS=120 + +# Proxies in front of the web app that append to X-Forwarded-For (1 behind +# the AWS ALB). 0 trusts no header, so per-IP login limits are skipped locally. +TRUSTED_PROXY_HOPS=0 + +# ── Gemini (matchmaking) ────────────────────────────────────── +GEMINI_API_KEY= +GEMINI_LLM_MODEL=gemini-3.8-flash +EMBEDDING_PROVIDER=gemini +# Optional self-hosted BGE endpoint, used when EMBEDDING_PROVIDER=local. +LOCAL_BGE_URL= +# Optional shared Redis retrieval cache. Docker uses PostgreSQL when these are blank. +UPSTASH_REDIS_REST_URL= +UPSTASH_REDIS_REST_TOKEN= + +# ── Local convenience ───────────────────────────────────────── +# Seed demo attendees after migrating. Never enable against production. +SEED_ON_MIGRATE=true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b1d8b60 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,260 @@ +name: CI + +on: + push: + branches: [main, dev] + # Every pull request, whatever branch it targets. + pull_request: + # deploy.yml runs these same checks before it builds anything, so there is + # one definition of what a release must pass. + workflow_call: + inputs: + build_images: + description: "Also build the images (the deploy builds and pushes its own)" + type: boolean + default: true + +# A new push supersedes an in-flight run on the same branch. The workflow name +# keeps a deploy's call to this file out of the standalone CI run's group, +# which a push to main starts at the same time. +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + NODE_VERSION: "22" + +jobs: + quality: + name: Lint, typecheck & unit tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # The migration gate compares with the base commit. + fetch-depth: 0 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: npm + + - run: npm ci + + - name: Typecheck + run: npm run typecheck + + - name: Lint + run: npm run lint + + - name: Unit tests + run: npx vitest run tests/unit + + # Migrations run before the new code starts, and a rollback runs the + # previous image on the migrated schema: released migrations never + # change and new ones only expand. + - name: Migrations are safe to roll back from + run: npx tsx tools/check-migrations.ts "${{ github.event.pull_request.base.sha || github.event.before }}" + + integration: + name: Integration tests + runs-on: ubuntu-latest + + # The same Postgres (with the Keycloak database) and Keycloak (with the + # realm import and theme) that docker compose runs locally. + env: + DATABASE_URL: postgres://matchmaker:matchmaker@localhost:5432/matchmaker + DATABASE_SSL: disable + SESSION_SECRET: ci-session-secret-long-enough-for-validation-x + KEYCLOAK_ISSUER: http://localhost:8080/realms/match-maker + KEYCLOAK_PUBLIC_URL: http://localhost:8080 + KEYCLOAK_ADMIN: admin + KEYCLOAK_ADMIN_PASSWORD: admin + KEYCLOAK_CLIENT_ID: match-maker-web + KEYCLOAK_CLIENT_SECRET: ci-client-secret + APP_BASE_URL: http://localhost:3000 + # Suites skip themselves without these services; here that is a failure. + REQUIRE_SERVICES: db,keycloak + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: npm + + - run: npm ci + + - name: Start Postgres and Keycloak + run: docker compose up -d --wait postgres keycloak + + # The suite calls migrate() itself, so this only proves the runner works + # standalone — the way the deploy pipeline invokes it. + - name: Apply migrations + run: npm run db:migrate + + - name: Configure Keycloak + run: | + npm run keycloak:wait + npm run keycloak:sync + + - name: Integration tests + run: npx vitest run tests/integration --reporter=default --reporter=json --outputFile=vitest-report.json + + # A suite that skipped itself would otherwise count as a pass. + - name: Every integration test ran + run: npx tsx tools/check-test-report.ts vitest-report.json + + - name: Service logs + if: failure() + run: docker compose logs --no-color postgres keycloak | tail -n 300 + + browser: + name: Browser acceptance + runs-on: ubuntu-latest + needs: [quality] + + # The built app and the worker against the compose Postgres and Keycloak. + # Login codes are logged instead of e-mailed and read from the app's log. + env: + DATABASE_URL: postgres://matchmaker:matchmaker@localhost:5432/matchmaker + DATABASE_SSL: disable + SESSION_SECRET: ci-session-secret-long-enough-for-validation-x + KEYCLOAK_ISSUER: http://localhost:8080/realms/match-maker + KEYCLOAK_PUBLIC_URL: http://localhost:8080 + KEYCLOAK_ADMIN: admin + KEYCLOAK_ADMIN_PASSWORD: admin + KEYCLOAK_CLIENT_ID: match-maker-web + KEYCLOAK_CLIENT_SECRET: ci-client-secret + APP_BASE_URL: http://localhost:3000 + EMAIL_DEV_FALLBACK: "true" + MATCH_REFRESH_DELAY_SECONDS: "3" + E2E_BASE_URL: http://localhost:3000 + E2E_WEB_LOG: ${{ github.workspace }}/e2e-web.log + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: npm + + - run: npm ci + + - name: Start Postgres and Keycloak + run: docker compose up -d --wait postgres keycloak + + - name: Migrate, seed and configure Keycloak + run: | + npm run db:migrate + npm run db:seed + npm run keycloak:wait + npm run keycloak:sync + + - name: Build + run: npm run build + + - name: Install Chromium + run: npx playwright install --with-deps chromium + + - name: Start app and worker + run: | + (cd apps/web && nohup npx next start -p 3000 > "$E2E_WEB_LOG" 2>&1 &) + nohup npm run worker > e2e-worker.log 2>&1 & + for i in $(seq 1 60); do + curl -fsS http://localhost:3000/api/health/ready && exit 0 + sleep 2 + done + cat "$E2E_WEB_LOG" + exit 1 + + - name: Browser tests + run: npm run test:e2e + + - name: Keep report and logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: browser-acceptance + path: | + playwright-report/ + test-results/ + e2e-web.log + e2e-worker.log + retention-days: 7 + + build: + name: Build images + runs-on: ubuntu-latest + needs: [quality] + # Push and pull_request runs have no inputs, so this is true for them. + if: ${{ inputs.build_images != false }} + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-buildx-action@v3 + + # Build only — publishing happens in deploy.yml, and only from main. + - name: Build web image + uses: docker/build-push-action@v6 + with: + context: . + file: apps/web/Dockerfile + push: false + load: false + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build migrate image + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/migrate.Dockerfile + push: false + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build worker image + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/worker.Dockerfile + push: false + load: false + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build Keycloak image + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/keycloak.Dockerfile + push: false + cache-from: type=gha + cache-to: type=gha,mode=max + + terraform: + name: Terraform validate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.9.8" + + - name: Format check + run: terraform fmt -check -recursive + working-directory: infra/terraform + + # No backend, no credentials — this only checks the configuration parses + # and is internally consistent. + - name: Init (no backend) + run: terraform init -backend=false + working-directory: infra/terraform + + - name: Validate + run: terraform validate + working-directory: infra/terraform diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..6b8dffa --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,474 @@ +name: Deploy to ECS + +on: + push: + branches: [main] + workflow_dispatch: + inputs: + environment: + description: "Where to deploy. Staging is a separate Terraform stack (environment = staging)." + type: choice + options: [production, staging] + default: production + promote_tag: + description: "Promote: copy this tag's staging images to production unchanged, then migrate and roll out (production only)" + type: string + default: "" + deploy_keycloak: + description: "Also rebuild and roll out Keycloak" + type: boolean + default: false + rollback_tag: + description: "Roll back: re-deploy this existing image tag (skips checks, build and migrations)" + type: string + default: "" + +# Never let two deploys race for the same service. +concurrency: + group: deploy-${{ inputs.environment || 'production' }} + cancel-in-progress: false + +permissions: + # Required to fetch the OIDC token that assumes the AWS deploy role. + id-token: write + contents: read + +# Staging names follow the Terraform stack (match-maker-staging-*) and never +# fall back to production's repository variables. Each job that touches AWS +# runs in the GitHub environment of the target, so its role, subnets and URL +# come from that environment's secrets and variables. +env: + TARGET: ${{ inputs.environment || 'production' }} + STACK: ${{ inputs.environment == 'staging' && 'match-maker-staging' || 'match-maker-prod' }} + AWS_REGION: ${{ vars.AWS_REGION || 'ap-south-1' }} + ECS_CLUSTER: ${{ inputs.environment == 'staging' && 'match-maker-staging-cluster' || vars.ECS_CLUSTER || 'match-maker-prod-cluster' }} + ECS_WEB_SERVICE: ${{ inputs.environment == 'staging' && 'match-maker-staging-web' || vars.ECS_WEB_SERVICE || 'match-maker-prod-web' }} + ECS_WORKER_SERVICE: ${{ inputs.environment == 'staging' && 'match-maker-staging-worker' || vars.ECS_WORKER_SERVICE || 'match-maker-prod-worker' }} + ECS_KEYCLOAK_SERVICE: ${{ inputs.environment == 'staging' && 'match-maker-staging-keycloak' || vars.ECS_KEYCLOAK_SERVICE || 'match-maker-prod-keycloak' }} + MIGRATE_TASK_FAMILY: ${{ inputs.environment == 'staging' && 'match-maker-staging-migrate' || vars.MIGRATE_TASK_FAMILY || 'match-maker-prod-migrate' }} + +jobs: + # Decides what ships: the pushed commit, or an existing tag on rollback. + plan: + name: Plan release + runs-on: ubuntu-latest + environment: ${{ inputs.environment || 'production' }} + outputs: + tag: ${{ steps.plan.outputs.tag }} + rollback: ${{ steps.plan.outputs.rollback }} + promote: ${{ steps.plan.outputs.promote }} + steps: + # A staging run must find staging's own settings, never production's. + - name: Check the target environment + env: + STACK_NAME: ${{ vars.STACK_NAME }} + run: | + set -euo pipefail + if [ "$TARGET" = "staging" ] && [ "${STACK_NAME:-}" != "match-maker-staging" ]; then + echo "::error::Set STACK_NAME=match-maker-staging (and staging's AWS secrets) in the GitHub 'staging' environment first." + exit 1 + fi + + - id: plan + env: + ROLLBACK_TAG: ${{ inputs.rollback_tag }} + PROMOTE_TAG: ${{ inputs.promote_tag }} + run: | + set -euo pipefail + echo "promote=false" >> "$GITHUB_OUTPUT" + if [ -n "${PROMOTE_TAG:-}" ]; then + if [ "$TARGET" != "production" ] || [ -n "${ROLLBACK_TAG:-}" ] || ! [[ "$PROMOTE_TAG" =~ ^[0-9a-f]{7,40}$ ]]; then + echo "::error::promote_tag takes an image tag, targets production, and cannot be combined with rollback_tag." + exit 1 + fi + echo "tag=$PROMOTE_TAG" >> "$GITHUB_OUTPUT" + echo "rollback=false" >> "$GITHUB_OUTPUT" + echo "promote=true" >> "$GITHUB_OUTPUT" + echo "Promoting the staging images tagged $PROMOTE_TAG" + elif [ -n "${ROLLBACK_TAG:-}" ]; then + if ! [[ "$ROLLBACK_TAG" =~ ^[0-9a-f]{7,40}$ ]]; then + echo "::error::rollback_tag must be an image tag (a commit SHA prefix), got '$ROLLBACK_TAG'." + exit 1 + fi + echo "tag=$ROLLBACK_TAG" >> "$GITHUB_OUTPUT" + echo "rollback=true" >> "$GITHUB_OUTPUT" + echo "Rolling back to $ROLLBACK_TAG" + else + # The commit SHA is the tag. `latest` also moves, but every deploy is + # pinned to an immutable tag so a rollback is just a re-deploy of one. + echo "tag=${GITHUB_SHA::12}" >> "$GITHUB_OUTPUT" + echo "rollback=false" >> "$GITHUB_OUTPUT" + fi + + # The full CI suite (lint, typecheck, unit + real-Postgres integration tests, + # Terraform validate) against the exact commit being shipped. Nothing is + # built or pushed unless all of it passes. + ci: + name: Required checks + needs: [plan] + # A promoted tag passed these checks when it was built for staging. + if: needs.plan.outputs.rollback != 'true' && needs.plan.outputs.promote != 'true' + uses: ./.github/workflows/ci.yml + with: + build_images: false + + build-and-push: + name: Build & push images + runs-on: ubuntu-latest + needs: [plan, ci] + if: >- + !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.rollback != 'true' && + (needs.plan.outputs.promote == 'true' || needs.ci.result == 'success') + environment: ${{ inputs.environment || 'production' }} + env: + TAG: ${{ needs.plan.outputs.tag }} + steps: + - uses: actions/checkout@v4 + + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} + aws-region: ${{ env.AWS_REGION }} + + - uses: aws-actions/amazon-ecr-login@v2 + id: ecr + + - uses: docker/setup-buildx-action@v3 + + # The same image digests that passed staging; nothing is rebuilt. Needs + # both stacks' repositories in one AWS account and registry. + - name: Copy the staging images + if: needs.plan.outputs.promote == 'true' + env: + REGISTRY: ${{ steps.ecr.outputs.registry }} + run: | + set -euo pipefail + repos="web migrate worker" + if [ "${{ inputs.deploy_keycloak }}" = "true" ]; then repos="$repos keycloak"; fi + for repo in $repos; do + docker buildx imagetools create \ + --tag "$REGISTRY/$STACK/$repo:$TAG" --tag "$REGISTRY/$STACK/$repo:latest" \ + "$REGISTRY/match-maker-staging/$repo:$TAG" + done + + - name: Build & push web + if: needs.plan.outputs.promote != 'true' + uses: docker/build-push-action@v6 + with: + context: . + file: apps/web/Dockerfile + push: true + build-args: APP_VERSION=${{ env.TAG }} + tags: | + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/web:${{ env.TAG }} + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/web:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build & push migrate + if: needs.plan.outputs.promote != 'true' + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/migrate.Dockerfile + push: true + tags: | + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/migrate:${{ env.TAG }} + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/migrate:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build & push worker + if: needs.plan.outputs.promote != 'true' + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/worker.Dockerfile + push: true + build-args: APP_VERSION=${{ env.TAG }} + tags: | + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/worker:${{ env.TAG }} + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/worker:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Build & push Keycloak + if: inputs.deploy_keycloak && needs.plan.outputs.promote != 'true' + uses: docker/build-push-action@v6 + with: + context: . + file: infra/docker/keycloak.Dockerfile + push: true + tags: | + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/keycloak:${{ env.TAG }} + ${{ steps.ecr.outputs.registry }}/${{ env.STACK }}/keycloak:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + migrate: + name: Run migrations + runs-on: ubuntu-latest + needs: [plan, build-and-push] + if: >- + !cancelled() && needs.plan.outputs.rollback != 'true' && needs.build-and-push.result == 'success' + environment: ${{ inputs.environment || 'production' }} + env: + TAG: ${{ needs.plan.outputs.tag }} + steps: + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} + aws-region: ${{ env.AWS_REGION }} + + # Running the family name would start its newest revision, which points + # at the mutable `latest` tag. Register a revision pinned to this release + # so exactly the migrator that was just built runs. + - name: Pin migrate task definition to the new image + id: migrate-taskdef + run: | + set -euo pipefail + REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" + aws ecs describe-task-definition --task-definition "$MIGRATE_TASK_FAMILY" \ + --query 'taskDefinition' > migrate-taskdef.json + jq --arg IMAGE "$REGISTRY/$STACK/migrate:$TAG" ' + .containerDefinitions[0].image = $IMAGE + | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, + .compatibilities, .registeredAt, .registeredBy, .deregisteredAt) + ' migrate-taskdef.json > new-migrate-taskdef.json + NEW_ARN=$(aws ecs register-task-definition \ + --cli-input-json file://new-migrate-taskdef.json \ + --query 'taskDefinition.taskDefinitionArn' --output text) + echo "arn=$NEW_ARN" >> "$GITHUB_OUTPUT" + echo "Registered $NEW_ARN" + + # Migrations run BEFORE the new tasks roll out, so they must be + # backwards-compatible with the version currently serving traffic. + - name: Run migration task and wait + run: | + set -euo pipefail + + TASK_ARN=$(aws ecs run-task \ + --cluster "$ECS_CLUSTER" \ + --task-definition "${{ steps.migrate-taskdef.outputs.arn }}" \ + --launch-type FARGATE \ + --network-configuration "awsvpcConfiguration={subnets=[${{ secrets.PRIVATE_SUBNET_IDS }}],securityGroups=[${{ secrets.TASK_SECURITY_GROUP_ID }}],assignPublicIp=DISABLED}" \ + --query 'tasks[0].taskArn' --output text) + + echo "Migration task: $TASK_ARN" + aws ecs wait tasks-stopped --cluster "$ECS_CLUSTER" --tasks "$TASK_ARN" + + EXIT_CODE=$(aws ecs describe-tasks --cluster "$ECS_CLUSTER" --tasks "$TASK_ARN" \ + --query 'tasks[0].containers[0].exitCode' --output text) + REASON=$(aws ecs describe-tasks --cluster "$ECS_CLUSTER" --tasks "$TASK_ARN" \ + --query 'tasks[0].stoppedReason' --output text) + + echo "Exit code: $EXIT_CODE ($REASON)" + if [ "$EXIT_CODE" != "0" ]; then + echo "::error::Migration failed — aborting deploy. Check /ecs/$STACK/migrate." + exit 1 + fi + + deploy: + name: Roll out + runs-on: ubuntu-latest + needs: [plan, build-and-push, migrate] + environment: ${{ inputs.environment || 'production' }} + # A rollback skips checks, build and migrations (the schema only moves + # forward); a normal release needs all of them to have succeeded. + if: >- + !cancelled() && needs.plan.result == 'success' && + (needs.plan.outputs.rollback == 'true' || needs.migrate.result == 'success') + env: + TAG: ${{ needs.plan.outputs.tag }} + steps: + - uses: actions/checkout@v4 + + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} + aws-region: ${{ env.AWS_REGION }} + + - name: Check the rollback images exist + if: needs.plan.outputs.rollback == 'true' + run: | + set -euo pipefail + repos="web worker" + if [ "${{ inputs.deploy_keycloak }}" = "true" ]; then repos="$repos keycloak"; fi + for repo in $repos; do + aws ecr describe-images --repository-name "$STACK/$repo" \ + --image-ids imageTag="$TAG" >/dev/null \ + || { echo "::error::No $repo image tagged $TAG in ECR."; exit 1; } + done + + # Remembered so a failed smoke test can put these back. + - name: Record the revisions currently serving + id: previous + run: | + set -euo pipefail + for svc in web worker; do + name_var="ECS_${svc^^}_SERVICE" + arn=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "${!name_var}" \ + --query 'services[0].taskDefinition' --output text) + echo "$svc=$arn" >> "$GITHUB_OUTPUT" + echo "$svc is serving $arn" + done + + - name: Pin web task definition to the new image + id: taskdef + run: | + set -euo pipefail + REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" + + # Start from the family's newest revision, not the one the service is + # running, so settings and secrets changed by Terraform ship too. + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ + --query 'taskDefinition' > taskdef.json + + # Production login must send real e-mail: never ship the dev fallback, + # and require the Resend key (an empty value fails the app's startup check). + if jq -e '[.containerDefinitions[].environment[]? | select(.name == "EMAIL_DEV_FALLBACK" and .value == "true")] | length > 0' taskdef.json >/dev/null; then + echo "::error::EMAIL_DEV_FALLBACK=true is set on the web task; login codes would be logged instead of sent." + exit 1 + fi + if ! jq -e '[.containerDefinitions[].secrets[]? | select(.name == "RESEND_API_KEY")] | length > 0' taskdef.json >/dev/null; then + echo "::error::The web task has no RESEND_API_KEY secret; login e-mail cannot be delivered." + exit 1 + fi + + # Strip the server-managed fields that RegisterTaskDefinition rejects, + # then point the container at the immutable tag. + jq --arg IMAGE "$REGISTRY/$STACK/web:$TAG" ' + .containerDefinitions[0].image = $IMAGE + | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, + .compatibilities, .registeredAt, .registeredBy, .deregisteredAt) + ' taskdef.json > new-taskdef.json + + NEW_ARN=$(aws ecs register-task-definition \ + --cli-input-json file://new-taskdef.json \ + --query 'taskDefinition.taskDefinitionArn' --output text) + + echo "arn=$NEW_ARN" >> "$GITHUB_OUTPUT" + echo "Registered $NEW_ARN" + + - name: Update web service + run: | + aws ecs update-service \ + --cluster "$ECS_CLUSTER" \ + --service "$ECS_WEB_SERVICE" \ + --task-definition "${{ steps.taskdef.outputs.arn }}" \ + --query 'service.deployments[0].id' --output text + + - name: Pin worker task definition to the new image + id: worker-taskdef + run: | + set -euo pipefail + REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" + + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_WORKER_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ + --query 'taskDefinition' > worker-taskdef.json + + jq --arg IMAGE "$REGISTRY/$STACK/worker:$TAG" ' + .containerDefinitions[0].image = $IMAGE + | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, + .compatibilities, .registeredAt, .registeredBy, .deregisteredAt) + ' worker-taskdef.json > new-worker-taskdef.json + + NEW_ARN=$(aws ecs register-task-definition \ + --cli-input-json file://new-worker-taskdef.json \ + --query 'taskDefinition.taskDefinitionArn' --output text) + echo "arn=$NEW_ARN" >> "$GITHUB_OUTPUT" + echo "Registered $NEW_ARN" + + - name: Update worker service + run: | + aws ecs update-service \ + --cluster "$ECS_CLUSTER" \ + --service "$ECS_WORKER_SERVICE" \ + --task-definition "${{ steps.worker-taskdef.outputs.arn }}" \ + --query 'service.deployments[0].id' --output text + + # Forcing a new deployment would restart Keycloak's current revision, + # which points at `latest`; pin it to the tag that was just built. + - name: Pin and roll out Keycloak + if: inputs.deploy_keycloak + run: | + set -euo pipefail + REGISTRY="$(aws sts get-caller-identity --query Account --output text).dkr.ecr.${AWS_REGION}.amazonaws.com" + FAMILY=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$ECS_KEYCLOAK_SERVICE" \ + --query 'services[0].taskDefinition' --output text | sed -E 's#^.*task-definition/([^:]+):[0-9]+$#\1#') + aws ecs describe-task-definition --task-definition "$FAMILY" \ + --query 'taskDefinition' > keycloak-taskdef.json + jq --arg IMAGE "$REGISTRY/$STACK/keycloak:$TAG" ' + .containerDefinitions[0].image = $IMAGE + | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, + .compatibilities, .registeredAt, .registeredBy, .deregisteredAt) + ' keycloak-taskdef.json > new-keycloak-taskdef.json + NEW_ARN=$(aws ecs register-task-definition \ + --cli-input-json file://new-keycloak-taskdef.json \ + --query 'taskDefinition.taskDefinitionArn' --output text) + aws ecs update-service --cluster "$ECS_CLUSTER" --service "$ECS_KEYCLOAK_SERVICE" \ + --task-definition "$NEW_ARN" >/dev/null + echo "Keycloak rolling out $NEW_ARN" + + - name: Wait for the service to stabilise + run: | + aws ecs wait services-stable --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" "$ECS_WORKER_SERVICE" + echo "Web and worker deployments are stable." + + # The deployment circuit breaker rolls a failed rollout back, after which + # the service is "stable" on the OLD revision. Check what is serving. + - name: Confirm the new revisions are serving + run: | + set -euo pipefail + check() { + local service=$1 expected=$2 serving + serving=$(aws ecs describe-services --cluster "$ECS_CLUSTER" --services "$service" \ + --query "services[0].deployments[?status=='PRIMARY'].taskDefinition | [0]" --output text) + if [ "$serving" != "$expected" ]; then + echo "::error::$service is serving $serving, not $expected (ECS rolled the deployment back)." + return 1 + fi + echo "$service is serving $expected" + } + check "$ECS_WEB_SERVICE" "${{ steps.taskdef.outputs.arn }}" + check "$ECS_WORKER_SERVICE" "${{ steps.worker-taskdef.outputs.arn }}" + + - name: Smoke test + env: + URL: ${{ vars.APP_BASE_URL }} + run: | + set -euo pipefail + if [ -z "$URL" ]; then + echo "::error::Set the APP_BASE_URL repository variable; a release is not verified without a smoke test." + exit 1 + fi + + for attempt in 1 2 3 4 5; do + version=$(curl -fsS --max-time 15 "$URL/api/health" | jq -r '.version' || true) + if [ "$version" = "$TAG" ] && curl -fsS --max-time 15 "$URL/api/health/ready" | tee /tmp/ready.json; then + echo + echo "$URL is serving $TAG and its dependencies are ready." + exit 0 + fi + echo "attempt $attempt: serving '${version:-nothing}', expected '$TAG'; retrying in 10s" + sleep 10 + done + + echo "::error::Smoke test failed for $TAG." + exit 1 + + - name: Roll back to the previous revisions + if: failure() && steps.previous.outputs.web != '' + run: | + set -euo pipefail + echo "::warning::Deploy of $TAG failed; restoring the revisions that were serving before." + aws ecs update-service --cluster "$ECS_CLUSTER" --service "$ECS_WEB_SERVICE" \ + --task-definition "${{ steps.previous.outputs.web }}" >/dev/null + aws ecs update-service --cluster "$ECS_CLUSTER" --service "$ECS_WORKER_SERVICE" \ + --task-definition "${{ steps.previous.outputs.worker }}" >/dev/null + aws ecs wait services-stable --cluster "$ECS_CLUSTER" --services "$ECS_WEB_SERVICE" "$ECS_WORKER_SERVICE" + echo "Restored ${{ steps.previous.outputs.web }} and ${{ steps.previous.outputs.worker }}." diff --git a/.gitignore b/.gitignore index 5ea9339..88b2c56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,34 +1,129 @@ # dependencies -/node_modules +node_modules /.pnp .pnp.js # next.js -/.next/ -/out/ +.next/ +out/ +next-env.d.ts # production /build +dist/ -# misc -.DS_Store +# turbo +.turbo + +# typescript +*.tsbuildinfo + +# vercel +.vercel + +# test output +coverage/ +test-results/ +playwright-report/ +blob-report/ + +# --------------------------------------------------------------------------- +# Secrets — never commit +# --------------------------------------------------------------------------- + +# env files — .env.example is the only one committed +.env +.env.* +!.env.example + +# keys and certificates *.pem +*.key +*.crt +*.cer +*.p12 +*.pfx +*.jks +*.keystore +id_rsa* +id_ed25519* -# debug -npm-debug.log* +# downloaded cloud / OAuth credentials +credentials.json +client_secret*.json +service-account*.json +*.secret +secrets/ -# env files -.env*.local +# Keycloak user exports contain password hashes (realm-export.json stays) +keycloak/*-users-*.json + +# local compose overrides often carry real credentials +docker-compose.override.yml +compose.override.yml + +# terraform +infra/terraform/.terraform/ +infra/terraform/*.tfstate +infra/terraform/*.tfstate.* +infra/terraform/*.tfvars +!infra/terraform/*.tfvars.example +infra/terraform/environments/*.tfvars +!infra/terraform/environments/*.tfvars.example +infra/terraform/*.tfplan +infra/terraform/.terraform.lock.hcl +infra/terraform/override.tf +infra/terraform/*_override.tf +.terraformrc +terraform.rc +crash.log +crash.*.log + +# --------------------------------------------------------------------------- +# Attendee data (PII) and database dumps — never commit +# --------------------------------------------------------------------------- +*.xlsx +*.xls +*.csv +*.dump +*.backup +*.sql.gz +backups/ # gemini file cache .gemini-cache.json -# attendee data (PII — never commit) -*.xlsx +# --------------------------------------------------------------------------- +# Logs, caches and temp files +# --------------------------------------------------------------------------- +*.log +logs/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +.eslintcache +.cache/ +*.pid +*.seed +*.tmp +*.temp +tmp/ +temp/ -# vercel -.vercel +# editors and IDEs +.idea/ +.vscode/* +!.vscode/extensions.json +*.swp +*.swo +*~ +# Local Claude Code settings and agents; never pushed. +.claude/ -# typescript -*.tsbuildinfo -next-env.d.ts +# OS files +.DS_Store +Thumbs.db +ehthumbs.db +desktop.ini +$RECYCLE.BIN/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/app/api/lookup-email/route.js b/app/api/lookup-email/route.js deleted file mode 100644 index 050d9ab..0000000 --- a/app/api/lookup-email/route.js +++ /dev/null @@ -1,34 +0,0 @@ -import { NextResponse } from "next/server"; -import { createClient } from "@supabase/supabase-js"; - -const supabase = createClient( - process.env.SUPABASE_URL, - process.env.SUPABASE_SERVICE_KEY -); - -export async function POST(req) { - try { - const { phone } = await req.json(); - if (!phone) return NextResponse.json({ error: "Phone required" }, { status: 400 }); - - // Normalize to E.164 - const digits = phone.replace(/\D/g, ""); - const normalized = - digits.length === 10 ? `+91${digits}` : - digits.length === 12 && digits.startsWith("91") ? `+${digits}` : - phone.startsWith("+") ? phone.trim() : `+${digits}`; - - const { data, error } = await supabase - .from("registered_attendees") - .select("email, name") - .eq("phone", normalized) - .maybeSingle(); - - if (error) return NextResponse.json({ error: "Lookup failed" }, { status: 500 }); - if (!data?.email) return NextResponse.json({ registered: false }, { status: 200 }); - - return NextResponse.json({ registered: true, email: data.email, name: data.name }); - } catch { - return NextResponse.json({ error: "Internal server error" }, { status: 500 }); - } -} diff --git a/app/api/match/route.js b/app/api/match/route.js deleted file mode 100644 index b87a5c0..0000000 --- a/app/api/match/route.js +++ /dev/null @@ -1,298 +0,0 @@ -import { NextResponse } from "next/server"; -import { createClient } from "@supabase/supabase-js"; -import fs from "fs"; -import path from "path"; - -import os from "os"; - -const supabase = createClient( - process.env.SUPABASE_URL, - process.env.SUPABASE_SERVICE_KEY -); - -const CACHE_FILE = path.join(os.tmpdir(), ".gemini-cache.json"); -const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour - -// ── In-process lock ─────────────────────────────────────────── -// If multiple users trigger /api/match simultaneously when the cache -// is cold, only ONE Gemini file upload is fired. All other concurrent -// requests wait for and reuse the same Promise — no duplicate uploads. -let uploadInFlight = null; - -// ── Gemini File API: upload attendees list once, reuse URI ──── -async function getAttendeesFileUri(candidates) { - // 1. Fast path — valid cache on disk - if (fs.existsSync(CACHE_FILE)) { - try { - const cache = JSON.parse(fs.readFileSync(CACHE_FILE, "utf8")); - if (Date.now() - cache.uploadedAt < CACHE_TTL_MS && cache.fileUri) { - console.log("Reusing cached Gemini file URI:", cache.fileUri); - return cache.fileUri; - } - } catch {} - } - - // 2. If another request is already uploading, wait for it - if (uploadInFlight) { - console.log("Upload in-flight — awaiting shared promise"); - return uploadInFlight; - } - - // 3. This request wins the race — start the upload and share the promise - uploadInFlight = _doUpload(candidates).finally(() => { - uploadInFlight = null; - }); - - return uploadInFlight; -} - -async function _doUpload(candidates) { - // Keep each line compact — truncate long free-text fields - const content = candidates - .map((a, i) => { - const about = (a.about_me || "").slice(0, 120); - const self = (a.self_description || "").slice(0, 80); - const build = (a.most_impressive_build || "").slice(0, 80); - return `${i + 1}. ID:${a.id} | ${a.name || "?"} | ${a.domain || "N/A"} | ${a.designation || "N/A"} | ${a.years_of_experience ?? "N/A"}y | About:${about} | Self:${self} | Build:${build}`; - }) - .join("\n"); - - const blob = Buffer.from(content, "utf8"); - - const initRes = await fetch( - `https://generativelanguage.googleapis.com/upload/v1beta/files?key=${process.env.GEMINI_API_KEY}`, - { - method: "POST", - headers: { - "X-Goog-Upload-Protocol": "resumable", - "X-Goog-Upload-Command": "start", - "X-Goog-Upload-Header-Content-Length": blob.length, - "X-Goog-Upload-Header-Content-Type": "text/plain", - "Content-Type": "application/json", - }, - body: JSON.stringify({ file: { display_name: "attendees-list" } }), - } - ); - - if (!initRes.ok) { - const t = await initRes.text(); - throw new Error(`File upload init failed: ${t}`); - } - - const uploadUrl = initRes.headers.get("x-goog-upload-url"); - - const uploadRes = await fetch(uploadUrl, { - method: "POST", - headers: { - "X-Goog-Upload-Command": "upload, finalize", - "X-Goog-Upload-Offset": "0", - "Content-Type": "text/plain", - }, - body: blob, - }); - - if (!uploadRes.ok) { - const t = await uploadRes.text(); - throw new Error(`File upload failed: ${t}`); - } - - const fileData = await uploadRes.json(); - const fileUri = fileData?.file?.uri; - if (!fileUri) throw new Error("No file URI returned from Gemini"); - - console.log("Uploaded attendees to Gemini, URI:", fileUri); - fs.writeFileSync(CACHE_FILE, JSON.stringify({ fileUri, uploadedAt: Date.now() })); - return fileUri; -} - -// ── Salvage complete JSON objects from a truncated array string ── -// Returns all fully-closed { } objects even if the outer array is cut off. -function recoverPartialJsonArray(raw) { - const text = raw.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim(); - - // Try straight parse first - try { return JSON.parse(text); } catch {} - - // Walk character-by-character to pull out each complete {...} block - const results = []; - let depth = 0; - let start = -1; - let inString = false; - let escape = false; - - for (let i = 0; i < text.length; i++) { - const ch = text[i]; - if (escape) { escape = false; continue; } - if (ch === "\\" && inString) { escape = true; continue; } - if (ch === '"') { inString = !inString; continue; } - if (inString) continue; - - if (ch === "{") { - if (depth === 0) start = i; - depth++; - } else if (ch === "}") { - depth--; - if (depth === 0 && start !== -1) { - try { results.push(JSON.parse(text.slice(start, i + 1))); } catch {} - start = -1; - } - } - } - - return results.length ? results : null; -} - -export async function POST(req) { - try { - const { userName, userDomain, userInterests, userProfile } = await req.json(); - - if (!userName || !userDomain || !userInterests?.length) { - return NextResponse.json({ error: "Missing required fields" }, { status: 400 }); - } - - // Fetch all attendees - const { data: attendees, error: dbErr } = await supabase - .from("registered_attendees") - .select("id, name, email, phone, designation, domain, about_me, self_description, years_of_experience, most_impressive_build") - .not("name", "is", null); - - if (dbErr) { - console.error("Supabase error:", dbErr); - return NextResponse.json({ error: "Failed to fetch attendees" }, { status: 500 }); - } - - // Exclude the logged-in user - const userEmail = userProfile?.email?.toLowerCase().trim(); - const userPhone = userProfile?.phone?.trim(); - const candidates = attendees.filter((a) => { - if (userEmail && a.email?.toLowerCase().trim() === userEmail) return false; - if (userPhone && a.phone?.trim() === userPhone) return false; - return true; - }); - - if (!candidates.length) { - return NextResponse.json({ error: "No candidates found" }, { status: 404 }); - } - - // Upload attendees to Gemini File API (cached + race-safe) - const fileUri = await getAttendeesFileUri(candidates); - - // Prompt: ask Gemini for only IDs + compact fields. - // about_me / most_impressive_build are pulled from DB after parsing — not - // echoed back — so the JSON output stays tiny regardless of attendee count. - const prompt = `You are a networking matchmaker at "AI Community Lucknow" (aicommunity.lucknow.dev). - -The attached file contains the full attendee list (one per line, pipe-separated). - -User looking for matches: -- Name: ${userName} -- Domain: ${userDomain} -- Interests: ${userInterests.join(", ")} -- Designation: ${userProfile?.designation || "N/A"} -- Experience: ${userProfile?.years_of_experience ?? "Unknown"} years -- About: ${userProfile?.about_me ? String(userProfile.about_me).slice(0, 120) : "N/A"} - -Task: Select TOP 10 best matches from the attendee list based on domain alignment, complementary skills, shared interests, and collaboration potential. Sort from MOST to LEAST experienced (years_of_experience field). - -IMPORTANT: Reply ONLY with a raw JSON array — no markdown, no prose, no extra text. -Keep every string value SHORT. The "match_reason" must be at most 15 words. -Schema (exactly 7 fields per object): -[{"id":"","name":"","designation":"","domain":"","years_of_experience":,"score":<0-99>,"match_reason":""}]`; - - const geminiRes = await fetch( - `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${process.env.GEMINI_API_KEY}`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - contents: [{ - parts: [ - { file_data: { mime_type: "text/plain", file_uri: fileUri } }, - { text: prompt }, - ], - }], - // maxOutputTokens is a ceiling, NOT a cost. Gemini stops when done - // (~600 tokens for 10 objects). High ceiling just prevents truncation. - generationConfig: { temperature: 0.4, maxOutputTokens: 65536 }, - }), - } - ); - - // Handle Gemini rate-limit gracefully (many concurrent users on free tier) - if (geminiRes.status === 429) { - console.warn("Gemini 429 — rate limit hit"); - return NextResponse.json( - { error: "The AI is busy right now. Please wait 10 seconds and try again." }, - { status: 429 } - ); - } - - if (!geminiRes.ok) { - const errText = await geminiRes.text(); - if (errText.includes("not found") || errText.includes("INVALID_ARGUMENT")) { - if (fs.existsSync(CACHE_FILE)) fs.unlinkSync(CACHE_FILE); - return NextResponse.json({ error: "Attendee cache expired, please try again" }, { status: 503 }); - } - let detail = errText; - try { detail = JSON.parse(errText)?.error?.message || errText; } catch {} - return NextResponse.json({ error: `Gemini API failed: ${detail}` }, { status: 502 }); - } - - const geminiData = await geminiRes.json(); - const finishReason = geminiData?.candidates?.[0]?.finishReason; - console.log("Finish reason:", finishReason); - const rawText = geminiData?.candidates?.[0]?.content?.parts?.[0]?.text || ""; - - // Partial-JSON recovery — salvage whatever complete objects exist - let matches = recoverPartialJsonArray(rawText); - - if (!matches || !matches.length) { - console.error("Parse failed entirely. Raw:", rawText.slice(0, 800)); - return NextResponse.json( - { error: "AI returned an unreadable response. Please try again." }, - { status: 502 } - ); - } - - if (finishReason === "MAX_TOKENS") { - console.warn(`MAX_TOKENS hit — recovered ${matches.length} of 10 matches from partial response.`); - } - - // Enrich with full DB data (about_me, most_impressive_build, avatar initials) - const enriched = matches.map((m) => { - const full = candidates.find((a) => String(a.id) === String(m.id) || a.name === m.name) || {}; - const nameParts = (m.name || full.name || "??").trim().split(" "); - const avatar = - nameParts.length >= 2 - ? nameParts[0][0].toUpperCase() + nameParts[nameParts.length - 1][0].toUpperCase() - : nameParts[0].slice(0, 2).toUpperCase(); - return { - id: full.id || m.id, - name: m.name || full.name, - avatar, - designation: m.designation || full.designation, - domain: m.domain || full.domain, - years_of_experience: m.years_of_experience ?? full.years_of_experience, - // Always pull long text from DB — never from Gemini's echoed output - about_me: full.about_me || null, - most_impressive_build: full.most_impressive_build || null, - score: m.score, - match_reason: m.match_reason, - }; - }); - - // ── Guarantee sort order: most → least experienced, nulls last ── - // Gemini is asked to sort but LLMs aren't deterministic — always enforce - // the correct order server-side so index 0 is definitively the most senior. - enriched.sort((a, b) => { - const ay = a.years_of_experience ?? -1; - const by = b.years_of_experience ?? -1; - return by - ay; - }); - - return NextResponse.json({ matches: enriched }); - } catch (err) { - console.error("Match API error:", err); - return NextResponse.json({ error: err.message || "Internal server error" }, { status: 500 }); - } -} diff --git a/app/auth/callback/page.jsx b/app/auth/callback/page.jsx deleted file mode 100644 index 5f52c18..0000000 --- a/app/auth/callback/page.jsx +++ /dev/null @@ -1,15 +0,0 @@ -"use client"; - -import AuthCallback from "../../../backend/authcallback.jsx"; -import { useRouter } from "next/navigation"; - -export default function CallbackPage() { - const router = useRouter(); - - return ( - router.push("/")} - onAuthFail={() => router.push("/login")} - /> - ); -} diff --git a/app/login/page.jsx b/app/login/page.jsx deleted file mode 100644 index 2e6606b..0000000 --- a/app/login/page.jsx +++ /dev/null @@ -1,9 +0,0 @@ -"use client"; - -import Login from "../login.jsx"; -import { useRouter } from "next/navigation"; - -export default function LoginPage() { - const router = useRouter(); - return router.push("/")} />; -} diff --git a/app/page.jsx b/app/page.jsx deleted file mode 100644 index 9b79457..0000000 --- a/app/page.jsx +++ /dev/null @@ -1,9 +0,0 @@ -"use client"; - -import dynamic from "next/dynamic"; - -const MatchApp = dynamic(() => import("./MatchApp"), { ssr: false }); - -export default function Page() { - return ; -} diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile new file mode 100644 index 0000000..e5fffc4 --- /dev/null +++ b/apps/web/Dockerfile @@ -0,0 +1,77 @@ +# syntax=docker/dockerfile:1.7 +# ============================================================== +# Mr. Bridge web — multi-stage build for ECS Fargate. +# Build context is the MONOREPO ROOT, not apps/web: +# docker build -f apps/web/Dockerfile . +# ============================================================== + +ARG NODE_VERSION=22-alpine + +# ── deps ────────────────────────────────────────────────────── +# Only manifests are copied here, so this layer is reused across +# source-only changes and npm ci runs from cache. +FROM node:${NODE_VERSION} AS deps +WORKDIR /repo + +COPY package.json package-lock.json ./ +COPY apps/web/package.json apps/web/ +COPY packages/db/package.json packages/db/ +COPY packages/auth/package.json packages/auth/ +COPY packages/email/package.json packages/email/ + +RUN --mount=type=cache,target=/root/.npm \ + npm ci --include=dev + +# ── builder ─────────────────────────────────────────────────── +FROM node:${NODE_VERSION} AS builder +WORKDIR /repo + +COPY --from=deps /repo/node_modules ./node_modules +COPY . . + +# Next.js inlines NEXT_PUBLIC_* at build time. This app has none — every secret +# is read at runtime — which is why no build-time secrets are needed here. +ENV NEXT_TELEMETRY_DISABLED=1 +ENV NODE_ENV=production + +RUN npm run build --workspace=@match-maker/web + +# ── runner ──────────────────────────────────────────────────── +FROM node:${NODE_VERSION} AS runner +WORKDIR /app + +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 +ENV PORT=3000 +ENV HOSTNAME=0.0.0.0 + +# Run unprivileged. The node image already ships a `node` user (uid 1000). +RUN apk add --no-cache curl + +# `output: "standalone"` traced exactly the files the server needs, including +# the workspace packages and their hoisted dependencies. With +# outputFileTracingRoot set to the repo root, the bundle is emitted under +# apps/web/.next/standalone but keeps the monorepo's directory shape inside. +COPY --from=builder --chown=node:node /repo/apps/web/.next/standalone ./ +COPY --from=builder --chown=node:node /repo/apps/web/.next/static ./apps/web/.next/static +COPY --from=builder --chown=node:node /repo/apps/web/public ./apps/web/public + +# Amazon's RDS CA bundle, so DATABASE_SSL=verify can check the database +# certificate (DATABASE_CA_CERT_FILE points here in the task definitions). +ADD --chmod=644 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem /etc/ssl/certs/rds-global-bundle.pem + +# The release tag (commit SHA) the deploy built, reported by /api/health so +# smoke tests and rollbacks can tell which version is serving. Declared late +# so a new tag does not invalidate the cached layers above. +ARG APP_VERSION=dev +ENV APP_VERSION=$APP_VERSION + +USER node +EXPOSE 3000 + +# ECS/ALB health checks hit this. `/api/health` is intentionally dependency-free +# so a database blip doesn't cause the load balancer to kill healthy tasks. +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD curl -fsS http://127.0.0.1:3000/api/health || exit 1 + +CMD ["node", "apps/web/server.js"] 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 new file mode 100644 index 0000000..f246a3f --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/analytics/page.tsx @@ -0,0 +1,55 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { requireOrganizerEvent } from "@/src/lib/auth"; + +export default async function AnalyticsPage({ params }: { params: Promise<{ orgSlug: string; eventSlug: string }> }) { + const { orgSlug, eventSlug } = await params; + const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); + 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
+ +

Event analytics

+

{event.name} · {event.status}

+
+ + + + + + + +
+

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}}
; +} + +const shell = { minHeight: "100vh", maxWidth: 1000, margin: "0 auto", padding: "36px 24px", color: "#f4f4f5" } as const; +const grid = { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(190px,1fr))", gap: 14, marginTop: 28 } as const; +const card = { display: "grid", gap: 10, padding: 20, background: "#151519", border: "1px solid #333", borderRadius: 12 } as const; diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx new file mode 100644 index 0000000..967ca4e --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/matching/page.tsx @@ -0,0 +1,49 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { computeEventMatchesAction } from "../../../../../../actions/organizer.actions"; +import { requireOrganizerEvent } from "@/src/lib/auth"; +import { ActionForm } from "@/components/ui/form"; +import { getEventQueueSummary } from "@/src/application/use-cases/get-match-status"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; + +const QUEUE_LABELS = [ + ["queued", "Queued"], ["running", "Running"], ["stuck", "Stuck (running over 10 min)"], ["failed", "Failed"], ["done", "Finished"], +] as const; + +export default async function MatchingPage({ params, searchParams }: { + params: Promise<{ orgSlug: string; eventSlug: string }>; + searchParams: Promise<{ queued?: string }>; +}) { + const { orgSlug, eventSlug } = await params; + const query = await searchParams; + const { event, container } = await requireOrganizerEvent(orgSlug, eventSlug); + const [analytics, queue] = await Promise.all([ + container.events.analytics(event.id), + getEventQueueSummary({ eventId: event.id }, container.matchQueue), + ]); + const action = computeEventMatchesAction.bind(null, orgSlug, eventSlug); + return
+ +

Matching pipeline

+

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

+ {query.queued &&

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

} +
+
{analytics.profiles} completed profiles
{analytics.matches} saved match results
+ {eventAllows(event.status, "computeMatches") + ? + :

This event is closed. Reopen it from the dashboard to compute matches again.

} +
+ {event.status === "draft" &&

Registration is currently draft. Starting matching opens the event to participants.

} +

Queue

+

Where each participant's latest matching job stands.

+
+ {QUEUE_LABELS.map(([key, label]) =>
{label}
{queue[key]}
)} +
+ {(queue.failed > 0 || queue.stuck > 0) &&

Some participants have no fresh matches. “Compute matches” queues failed and stuck participants again.

} +
; +} + +const shell = { minHeight: "100vh", maxWidth: 900, margin: "0 auto", padding: "36px 24px", color: "#f4f4f5" } as const; +const card = { display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 20, alignItems: "center", padding: 24, background: "#151519", border: "1px solid #333", borderRadius: 12, marginTop: 24 } as const; +const grid = { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(140px,1fr))", gap: 12, margin: "16px 0" } as const; +const stat = { display: "grid", gap: 6, padding: 16, borderRadius: 12, background: "#151519", border: "1px solid #333" } as const; diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx new file mode 100644 index 0000000..6c5e849 --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/page.tsx @@ -0,0 +1,56 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +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; form?: string }>; +}) { + const { orgSlug, eventSlug } = await params; + const notice = await searchParams; + const { event, container, can } = await requireOrganizerEvent(orgSlug, eventSlug); + const analytics = await container.events.analytics(event.id); + const action = updateEventAction.bind(null, orgSlug, eventSlug); + return
+ ORGANIZER · {event.organization_name} +

{event.name}

+

{event.description}

+ +
+ + + + +
+

Event setup

+ {notice.saved &&

Event configuration saved.

} + {can("configure") ? :

+ 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.

} + + } +
; +} + +function Stat({ label, value }: { label: string; value: number }) { + return
{value}{label}
; +} + +const shell = { minHeight: "100vh", maxWidth: 1040, margin: "0 auto", padding: "36px 24px 80px", color: "#f4f4f5" } as const; +const stats = { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(150px,1fr))", gap: 12, margin: "28px 0" } as const; +const stat = { display: "grid", gap: 6, background: "#151519", borderRadius: 12, padding: 18, border: "1px solid #333" } as const; 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 new file mode 100644 index 0000000..4ef91fb --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/[eventSlug]/roster/page.tsx @@ -0,0 +1,95 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { importEventRosterAction, sendInvitationsAction, setAttendeeAccessAction } from "../../../../../../actions/organizer.actions"; +import { requireOrganizerEvent } from "@/src/lib/auth"; +import { RosterUploadForm } from "@/components/organizer/EventForms"; +import { ActionForm } from "@/components/ui/form"; +import { canInvite, invitationState, type InvitationState } from "@/src/domain/participant/invitation"; + +const STATE_LABELS: Record = { + not_invited: "Not invited", + invited: "Invited", + failed: "Invitation failed", + claimed: "Signed in", + complete: "Profile complete", + removed: "Access removed", +}; + +const date = (value: unknown) => value instanceof Date ? value : value ? new Date(String(value)) : null; +const when = (value: Date | null) => value ? value.toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" }) : ""; + +export default async function RosterPage({ params, searchParams }: { + params: Promise<{ orgSlug: string; eventSlug: 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, 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), + invitedAt: date(person.invited_at), inviteError: person.invite_error ? String(person.invite_error) : null, + }; + return { person, facts, state: invitationState(facts) }; + }); + const counts = roster.reduce>((all, row) => ({ ...all, [row.state]: (all[row.state] ?? 0) + 1 }), {}); + const pending = (counts.not_invited ?? 0); + const action = importEventRosterAction.bind(null, orgSlug, eventSlug); + return
+ +

Attendee roster

+

{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.`} +

} + {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 && can("invite") && } +
} + {!roster.length ?

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

: +
+ + {roster.map(({ person, facts, state }) => { + const id = String(person.id); + const detail = state === "failed" ? facts.inviteError + : state === "removed" ? `since ${when(facts.revokedAt)}` + : state === "claimed" || state === "complete" ? `signed in ${when(date(person.claimed_at))}` + : state === "invited" ? `${when(facts.invitedAt)}${Number(person.invite_count) > 1 ? ` · sent ${person.invite_count} times` : ""}` + : ""; + return + + + + + ; + })} +
NameE-mailPhoneRoleStatusActions
{String(person.name ?? "—")}{String(person.email ?? "—")}{String(person.phone ?? "—")}{String(person.designation ?? "—")}{STATE_LABELS[state]}{detail && <>
{detail}}
+ {can("invite") && canInvite(facts) && state !== "not_invited" && } + {!can("manageAccess") ? null : state === "removed" + ? + : } +
} +
; +} + +const shell = { minHeight: "100vh", maxWidth: 1100, margin: "0 auto", padding: "36px 24px", color: "#f4f4f5" } as const; +const table = { width: "100%", borderCollapse: "collapse" as const, textAlign: "left" as const }; +const summary = { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px 20px", marginTop: 24 } as const; diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx new file mode 100644 index 0000000..dafbb6f --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/new/page.tsx @@ -0,0 +1,22 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { createEventAction } from "../../../../../actions/organizer.actions"; +import { requireOrganizationMember } from "@/src/lib/auth"; +import { NewEventForm } from "@/components/organizer/EventForms"; + +export default async function NewEventPage({ params }: { params: Promise<{ orgSlug: string }> }) { + const { orgSlug } = await params; + 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 + +

Create an event

+

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

+ + {existing.length > 0 ?

Your events

    {existing.map((event) =>
  • {event.name} · {event.status}
  • )}
:

No events yet. Your first event will appear here.

} +
; +} + +const shell = { minHeight: "100vh", maxWidth: 760, margin: "0 auto", padding: "40px 24px", color: "#f4f4f5" } as const; diff --git a/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx new file mode 100644 index 0000000..bad065f --- /dev/null +++ b/apps/web/app/(organizer)/orgs/[orgSlug]/events/page.tsx @@ -0,0 +1,23 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { requireOrganizationMember } from "@/src/lib/auth"; + +export default async function OrganizationEventsPage({ params }: { params: Promise<{ orgSlug: string }> }) { + const { orgSlug } = await params; + 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

+ {isMember && Create event} +
+ {events.map((event) => + {event.name}{event.status}{event.description} + )} +
+
; +} + +const button = { display: "inline-block", padding: 12, borderRadius: 8, background: "#f59e0b", color: "#0a0a0e", textDecoration: "none", fontWeight: 700 } as const; +const card = { display: "grid", gap: 8, padding: 18, border: "1px solid #333", borderRadius: 12, background: "#151519", color: "#f4f4f5", textDecoration: "none" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx new file mode 100644 index 0000000..e961833 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/connections/page.tsx @@ -0,0 +1,75 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { answerLocationAction, getParticipantConnections, requestLocationAction, respondToParticipantIntro, shareVenueZoneAction } from "../../../../actions/intro.actions"; +import { requireParticipantEvent } from "@/src/lib/auth"; +import { ActionForm } from "@/components/ui/form"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; + +export default async function ConnectionsPage({ params, searchParams }: { + params: Promise<{ eventSlug: string }>; + searchParams: Promise<{ requested?: string; location?: string; asked?: string; replied?: string; declined?: string }>; +}) { + const { eventSlug } = await params; + const notice = await searchParams; + const { event } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/connections`, "viewMatches"); + const connections = await getParticipantConnections(eventSlug); + return
+ + INTRODUCTIONS · {event.name} +

Connections

+ {notice.requested &&

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

} + {notice.location &&

Your venue zone is shared with all your accepted connections for 15 minutes.

} + {notice.asked &&

Request sent. They decide whether to share where they are.

} + {notice.replied &&

Your zone is shared with them for 15 minutes.

} + {notice.declined &&

Request declined. They have been told you would rather not share right now.

} + {!connections.length ?

Your intro requests will show up here. Find someone you would like to meet from your matches or search.

:
+ {connections.map((connection) =>
+
+

{connection.participant.name}

+

{[connection.participant.designation, connection.participant.domain].filter(Boolean).join(" · ")}

+

{connection.incoming ? "They requested to meet you." : "You requested an introduction."} · {connection.status}

+ {connection.message &&

“{connection.message}”

} + {connection.status === "accepted" && connection.contact &&
+ Contact revealed + {connection.contact.email && } + {connection.contact.phone && } + {connection.contact.venueZone &&
At the venue: {connection.contact.venueZone}
} + {connection.locationAsked?.status === "answered" &&
Replied: at {connection.locationAsked.zone}
} + {connection.locationAsked?.status === "pending" &&
Asked where they are. Waiting for a reply.
} + {connection.locationAsked?.status === "declined" &&
They would rather not share where they are right now.
} + {event.zones.length > 0 && eventAllows(event.status, "shareZone") && <> + {connection.locationIncoming &&
+ {connection.participant.name} is asking where you are. Sharing is up to you; only they will see it, for 15 minutes. +
+ + + + + +
+
} + {connection.locationAsked?.status !== "pending" && } + } + {event.zones.length > 0 && eventAllows(event.status, "shareZone") && + + + } +
} +
+ {connection.incoming && connection.status === "pending" &&
+ + +
} +
)} +
} +
; +} + +const card = { display: "flex", flexWrap: "wrap", alignItems: "center", gap: 16, padding: 20, borderRadius: 12, background: "#151519", border: "1px solid #333" } as const; +const muted = { color: "#a1a1aa" } as const; +const contact = { background: "#111", border: "1px solid #3f3f46", borderRadius: 8, padding: 14, lineHeight: 1.8 } as const; +const ask = { marginTop: 10, padding: 12, borderRadius: 8, border: "1px solid #f59e0b", background: "rgba(245,158,11,0.08)" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx new file mode 100644 index 0000000..8e5bd80 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/matches/page.tsx @@ -0,0 +1,63 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { redirect } from "next/navigation"; +import { getMyMatches } from "@/src/application/use-cases/get-my-matches"; +import { requireParticipantEvent } from "@/src/lib/auth"; +import { refreshParticipantMatches } from "../../../../actions/match.actions"; +import { requestParticipantIntro } from "../../../../actions/intro.actions"; +import { ActionForm } from "@/components/ui/form"; +import MatchStatus from "@/components/participant/MatchStatus"; +import { getMatchStatus } from "@/src/application/use-cases/get-match-status"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; + +export default async function MatchesPage({ params, searchParams }: { + params: Promise<{ eventSlug: string }>; + searchParams: Promise<{ saved?: string }>; +}) { + const { eventSlug } = await params; + const notice = await searchParams; + const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/matches`, "viewMatches"); + const viewer = await container.participants.findProfile(event.id, session.attendeeId); + if (!viewer?.profileComplete) redirect(`/e/${eventSlug}/profile`); + const [matches, state] = await Promise.all([ + getMyMatches({ eventId: event.id, participantId: session.attendeeId, limit: 12 }, container.matches), + getMatchStatus({ eventId: event.id, participantId: session.attendeeId }, container.matchQueue), + ]); + const canRefresh = eventAllows(event.status, "refreshMatches"); + const canRequestIntro = eventAllows(event.status, "requestIntro"); + + return
+ + YOUR EVENT MATCHES +

People worth meeting.

+

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

+ {notice.saved &&

Profile saved. Your matches will update in the background.

} + {event.status === "closed" &&

This event has closed. Your matches stay here; new introductions are no longer possible.

} + 0} refresh={canRefresh ? refreshParticipantMatches.bind(null, eventSlug) : undefined} /> + {matches.length > 0 &&
+ {matches.map((match, index) =>
+
#{index + 1}
+
+

{match.participant.name}

+

{[match.participant.designation, match.participant.domain].filter(Boolean).join(" · ")}

+ {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 ? "Likely a strong fit for each other" : "Suggested for your profile"}

+
+
{Math.round(match.score)}%
+ {canRequestIntro &&
)} +
} +
; +} + +const shell = { minHeight: "100vh", maxWidth: 1000, margin: "0 auto", padding: "36px 24px 80px", color: "#f4f4f5" } as const; +const eyebrow = { color: "#f59e0b", fontSize: 12, letterSpacing: 2, fontWeight: 700 } as const; +const list = { display: "grid", gap: 14, marginTop: 30 } as const; +const card = { display: "flex", alignItems: "flex-start", gap: 18, flexWrap: "wrap", background: "#151519", border: "1px solid #333", borderRadius: 14, padding: 22 } as const; +const rank = { color: "#f59e0b", fontSize: 15, fontWeight: 800 } as const; +const score = { color: "#f59e0b", fontWeight: 800, fontSize: 20 } as const; +const muted = { color: "#a1a1aa", lineHeight: 1.5 } as const; +const reason = { color: "#fbbf24", lineHeight: 1.5 } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/page.tsx new file mode 100644 index 0000000..7471eb7 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/page.tsx @@ -0,0 +1,58 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { getSession } from "@/lib/session"; +import { getContainer } from "@/src/composition/container"; +import { signOutCurrentUser } from "../../../actions/participant.actions"; +import { eventAllows } from "@/src/domain/shared/event-lifecycle"; + +export default async function EventLandingPage({ params }: { params: Promise<{ eventSlug: string }> }) { + const { eventSlug } = await params; + const container = getContainer(); + const event = await container.events.findByEventSlug(eventSlug); + if (!event) notFound(); + + const session = await getSession(); + const returnTo = `/e/${eventSlug}/profile`; + if (!session) { + return
+ MR. BRIDGE · EVENT NETWORKING +

{event.name}

+

{event.description || "Meet the right people at this event."}

+

{event.status === "open" ? "Join the registered attendees and build your event profile." : `Registration is ${event.status}.`}

+ {event.status === "open" && Claim your attendee login} +
; + } + + if (!(await container.participants.hasEventAccess(event.id, session.attendeeId))) { + const removed = await container.events.rosterState(event.id, session.attendeeId) === "revoked"; + return
+ MR. BRIDGE · EVENT NETWORKING +

{event.name}

+

{removed + ? "The organizer removed this account's access to the event. Contact them if you think this is a mistake." + : "This account is not on the event roster. If you were invited with a different e-mail or phone, sign out and use that one, or ask the organizer to add this e-mail."}

+
+
; + } + + await container.events.markClaimed(event.id, session.attendeeId); + const profile = await container.participants.findProfile(event.id, session.attendeeId); + if (event.status === "open") redirect(profile?.profileComplete ? `/e/${eventSlug}/matches` : `/e/${eventSlug}/profile`); + + return
+ {event.status.toUpperCase()} +

{event.name}

+ {eventAllows(event.status, "viewMatches") + ? <> +

This event has closed. Your matches and accepted connections stay available, and you can still reply to pending introductions.

+ View your matches{" "} + Connections + + :

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

} +
+
; +} + +const shell = { minHeight: "100vh", maxWidth: 760, margin: "0 auto", padding: "12vh 24px", color: "#f4f4f5", background: "#0a0a0e" } as const; +const eyebrow = { color: "#f59e0b", fontSize: 12, letterSpacing: 2, fontWeight: 700 } as const; +const button = { display: "inline-block", marginTop: 20, border: 0, borderRadius: 8, padding: "13px 18px", background: "#f59e0b", color: "#0a0a0e", fontWeight: 700, textDecoration: "none", cursor: "pointer" } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx new file mode 100644 index 0000000..277c435 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/profile/page.tsx @@ -0,0 +1,37 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { notFound } from "next/navigation"; +import { saveParticipantProfile } from "../../../../actions/participant.actions"; +import { requireParticipantEvent } from "@/src/lib/auth"; +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; + const { session, event, container } = await requireParticipantEvent(eventSlug, `/e/${eventSlug}/profile`, "saveProfile"); + const profile = await container.participants.findProfile(event.id, session.attendeeId); + 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.

+ {missing.length > 0 &&

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

} + +
; +} + +const shell = { minHeight: "100vh", maxWidth: 820, margin: "0 auto", padding: "36px 24px 80px", color: "#f4f4f5" } as const; +const eyebrow = { color: "#f59e0b", fontSize: 12, letterSpacing: 2, fontWeight: 700 } as const; diff --git a/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx new file mode 100644 index 0000000..83b9193 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/search/SearchForm.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { useState } from "react"; +import { searchEventParticipants } from "../../../../actions/match.actions"; +import { requestParticipantIntro } from "../../../../actions/intro.actions"; +import { ActionForm } from "@/components/ui/form"; +import { LIMITS } from "@/src/domain/shared/validation"; + +interface SearchResult { + id: string; + name: string; + designation: string | null; + domain: string | null; + aboutMe: string | null; + yearsOfExperience: number | null; + score: number; + reason: string | null; + mutualInterest: boolean; +} + +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); + const [searched, setSearched] = useState(""); + + async function search(event: React.FormEvent) { + event.preventDefault(); + setBusy(true); + setError(""); + try { + const response = await searchEventParticipants(eventSlug, query, { intent: intent || null, domain: domain || null }); + setResults(response.results); + setError(response.error ?? ""); + setSearched(response.error ? "" : query.trim()); + } catch (cause) { + setError(cause instanceof Error ? cause.message : "Search failed. Please try again."); + } finally { + setBusy(false); + } + } + + return
+
+ + 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}` : ""}

+ {!busy && searched && !results.length && !error &&

No one matched “{searched}”. Try a broader description or different skills.

} +
+ {results.map((person) =>
+
+

{person.name}

+

{[person.designation, person.domain].filter(Boolean).join(" · ")}

+ {person.aboutMe &&

{person.aboutMe}

} +

{person.reason}

+ {person.mutualInterest && Likely a strong fit for each other} +
+
)} +
+
; +} + +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 new file mode 100644 index 0000000..a46c084 --- /dev/null +++ b/apps/web/app/(participant)/e/[eventSlug]/search/page.tsx @@ -0,0 +1,16 @@ +import Link from "next/link"; +import SignOutButton from "@/components/ui/SignOutButton"; +import { requireParticipantEvent } from "@/src/lib/auth"; +import SearchForm from "./SearchForm"; + +export default async function SearchPage({ params }: { params: Promise<{ eventSlug: string }> }) { + const { eventSlug } = await params; + 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/app/MatchApp.jsx b/apps/web/app/MatchApp.jsx similarity index 94% rename from app/MatchApp.jsx rename to apps/web/app/MatchApp.jsx index b154788..57f5798 100644 --- a/app/MatchApp.jsx +++ b/apps/web/app/MatchApp.jsx @@ -1,14 +1,15 @@ "use client"; +/** + * RETIRED (R07) - kept for reference only; nothing imports or routes to it. + * This was the original single-page matcher. It calls /api/domains and + * /api/match, which now answer 410 Gone. Participants use the event pages + * under app/(participant)/e/[eventSlug] instead. Do not wire it back up. + */ + import { useState, useEffect, useRef, useCallback } from "react"; -import { createClient } from "@supabase/supabase-js"; import { useRouter } from "next/navigation"; -const supabase = createClient( - process.env.NEXT_PUBLIC_SUPABASE_URL, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY -); - const GLITCH_CHARS = "!@#$%^&*()_+-=[]{}|;:,.<>?/~`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; function glitchText(text, progress) { @@ -336,34 +337,37 @@ export default function App() { const [matchError, setMatchError] = useState(null); const [hoverBtn, setHoverBtn] = useState(false); + // Session and profile arrive together from /api/me, which reads the encrypted + // session cookie server-side. The browser holds no auth SDK and no database + // credential — an unauthenticated response simply means "go to /login". useEffect(() => { - supabase.auth.getSession().then(({ data: { session } }) => { - if (!session) { router.replace("/login"); } - else { setAuthUser(session.user); fetchUserProfile(session.user); } - setAuthLoading(false); - }); - const { data: { subscription } } = supabase.auth.onAuthStateChange((_e, session) => { - if (!session) router.replace("/login"); - }); - return () => subscription.unsubscribe(); + let cancelled = false; + + fetch("/api/me") + .then(async (res) => { + if (cancelled) return; + if (!res.ok) { router.replace("/login"); return; } + + const data = await res.json(); + setAuthUser(data.user); + if (data.profile) { + setUserProfile(data.profile); + if (data.profile.name) setUserName(data.profile.name); + if (data.profile.domain) setUserDomain(data.profile.domain); + } + }) + .catch(() => { if (!cancelled) router.replace("/login"); }) + .finally(() => { if (!cancelled) setAuthLoading(false); }); + + return () => { cancelled = true; }; }, [router]); - const fetchUserProfile = async (user) => { - const identifier = user.email || user.phone; - const field = user.email ? "email" : "phone"; - const { data } = await supabase.from("registered_attendees").select("*").eq(field, identifier).maybeSingle(); - if (data) { - setUserProfile(data); - if (data.name) setUserName(data.name); - if (data.domain) setUserDomain(data.domain); - } - }; - useEffect(() => { if (!authUser) return; - supabase.from("registered_attendees").select("domain").then(({ data }) => { - if (!data) return; - const domains = [...new Set(data.map(a => a.domain).filter(Boolean))].sort(); + fetch("/api/domains") + .then(res => (res.ok ? res.json() : { domains: [] })) + .catch(() => ({ domains: [] })) + .then(({ domains = [] }) => { setAllDomains(domains.length ? domains : [ "Frontend Development", "Backend Development", "Full-Stack Development", "Mobile App Development", "Desktop Application Development", @@ -404,8 +408,9 @@ export default function App() { const res = await fetch("/api/match", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userName, userDomain, userInterests, userProfile }), + body: JSON.stringify({ userInterests }), }); + if (res.status === 401) { router.replace("/login"); return; } const data = await res.json(); if (!res.ok || data.error) throw new Error(data.error || "Match failed"); setCandidates(data.matches); @@ -415,6 +420,25 @@ export default function App() { } }; + // Identity, profile and the candidate list are all resolved from the session + // server-side, so the request body only carries the interests the user picked. + const handleSignOut = async () => { + try { + const res = await fetch("/api/auth/logout", { method: "POST" }); + const data = await res.json().catch(() => ({})); + // A Google login also has a Keycloak SSO session to end; an e-mail login + // just goes back to /login. + if (data.redirectTo?.startsWith("http")) { + window.location.href = data.redirectTo; + return; + } + } catch { + // Fall through — the cookie is cleared server-side regardless. + } + router.replace("/login"); + router.refresh(); + }; + const toggleInterest = (interest) => { setUserInterests(prev => prev.includes(interest) ? prev.filter(i => i !== interest) : prev.length < 8 ? [...prev, interest] : prev); }; @@ -468,12 +492,12 @@ export default function App() {
-
{userProfile?.name || authUser.email || authUser.phone}
+
{userProfile?.name || authUser.email}
LIVE
- @@ -609,8 +633,9 @@ export default function App() { const res = await fetch("/api/match", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ userName, userDomain, userInterests, userProfile }), + body: JSON.stringify({ userInterests }), }); + if (res.status === 401) { router.replace("/login"); return; } const data = await res.json(); if (!res.ok || data.error) throw new Error(data.error || "Match failed"); setCandidates(data.matches); diff --git a/apps/web/app/actions/intro.actions.ts b/apps/web/app/actions/intro.actions.ts new file mode 100644 index 0000000..0a4484e --- /dev/null +++ b/apps/web/app/actions/intro.actions.ts @@ -0,0 +1,127 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { requestIntro } from "../../src/application/use-cases/request-intro"; +import { respondToIntro } from "../../src/application/use-cases/respond-to-intro"; +import { shareVenueZone } from "../../src/application/use-cases/share-venue-zone"; +import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; +import { answerLocation, requestLocation } from "../../src/application/use-cases/location-requests"; +import { getSession } from "../../lib/session"; +import { runFormAction, type FormState } from "../../lib/form-state"; + +export async function requestParticipantIntro(eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => requestIntroFor(eventSlug, formData)); +} + +async function requestIntroFor(eventSlug: string, formData: FormData) { + const session = await getSession(); + if (!session) throw new Error("Sign in before requesting an introduction"); + const container = getContainer(); + const event = await container.events.findByEventSlug(eventSlug); + if (!event) throw new Error("Event not found"); + assertEventAllows(event.status, "requestIntro"); + const recipientId = String(formData.get("recipientId") || ""); + if (!recipientId) throw new Error("Choose a participant"); + await requestIntro({ + eventId: event.id, + requesterId: session.attendeeId, + recipientId, + message: String(formData.get("message") || ""), + eventName: event.name, + }, container); + redirect(`/e/${eventSlug}/connections?requested=1`); +} + +export async function respondToParticipantIntro(eventSlug: string, introId: string, accept: boolean, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => respondToIntroFor(eventSlug, introId, accept)); +} + +async function respondToIntroFor(eventSlug: string, introId: string, accept: boolean) { + const session = await getSession(); + if (!session) throw new Error("Sign in before responding to introductions"); + 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, "respondToIntro"); + await respondToIntro({ eventId: event.id, introId, actorId: session.attendeeId, accept, eventName: event.name }, container); + redirect(`/e/${eventSlug}/connections`); +} + +export async function shareVenueZoneAction(eventSlug: string, introId: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => shareZoneFor(eventSlug, introId, formData)); +} + +async function shareZoneFor(eventSlug: string, introId: string, formData: FormData) { + const session = await getSession(); + if (!session) throw new Error("Sign in before sharing your location"); + 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, "shareZone"); + await shareVenueZone({ + eventId: event.id, + introId, + participantId: session.attendeeId, + zone: String(formData.get("venueZone") || ""), + allowedZones: event.zones, + }, container); + redirect(`/e/${eventSlug}/connections?location=shared`); +} + +export async function getParticipantConnections(eventSlug: string) { + const session = await getSession(); + if (!session) throw new Error("Sign in to view your connections"); + 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, "viewMatches"); + const [requests, revealed, locationRequests] = await Promise.all([ + container.intros.listForParticipant(event.id, session.attendeeId), + container.intros.getRevealedContacts(event.id, session.attendeeId), + container.locations.forParticipant(event.id, session.attendeeId), + ]); + const contacts = new Map(revealed.map(({ intro, contact }) => [intro.id, contact])); + return Promise.all(requests.map(async (intro) => { + const otherId = intro.requesterId === session.attendeeId ? intro.recipientId : intro.requesterId; + const other = await container.participants.findProfile(event.id, otherId); + return { + id: intro.id, + status: intro.status, + message: intro.message, + createdAt: intro.createdAt.toISOString(), + incoming: intro.recipientId === session.attendeeId, + participant: { id: otherId, name: other?.name ?? "Participant", designation: other?.designation, domain: other?.domain }, + contact: contacts.get(intro.id) ?? null, + locationAsked: locationRequests.find((request) => request.introId === intro.id && request.direction === "outgoing") ?? null, + locationIncoming: locationRequests.find((request) => request.introId === intro.id && request.direction === "incoming" && request.status === "pending") ?? null, + }; + })); +} + +async function participantContext(eventSlug: string, action: "shareZone") { + const session = await getSession(); + if (!session) throw new Error("Sign in first"); + 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, action); + return { session, container, event }; +} + +export async function requestLocationAction(eventSlug: string, introId: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, async () => { + const { session, container, event } = await participantContext(eventSlug, "shareZone"); + await requestLocation({ eventId: event.id, introId, requesterId: session.attendeeId }, container); + redirect(`/e/${eventSlug}/connections?asked=1#intro-${introId}`); + }); +} + +export async function answerLocationAction(eventSlug: string, introId: string, requestId: string, share: boolean, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, async () => { + const { session, container, event } = await participantContext(eventSlug, "shareZone"); + const zone = share ? String(formData.get("venueZone") ?? "") : null; + await answerLocation({ eventId: event.id, requestId, recipientId: session.attendeeId, zone, allowedZones: event.zones }, container); + redirect(`/e/${eventSlug}/connections?${share ? "replied=1" : "declined=1"}#intro-${introId}`); + }); +} diff --git a/apps/web/app/actions/match.actions.ts b/apps/web/app/actions/match.actions.ts new file mode 100644 index 0000000..2de5008 --- /dev/null +++ b/apps/web/app/actions/match.actions.ts @@ -0,0 +1,77 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { searchParticipants } from "../../src/application/use-cases/search-participants"; +import { getMyMatches } from "../../src/application/use-cases/get-my-matches"; +import { getContainer } from "../../src/composition/container"; +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, filters: { intent?: string | null; domain?: string | null } = {}) { + try { + 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, 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, eventIntents: event.intents, filters }, container); + return results.map((match) => ({ + id: match.participant.attendeeId, + name: match.participant.name, + designation: match.participant.designation, + domain: match.participant.domain, + aboutMe: match.participant.aboutMe, + yearsOfExperience: match.participant.yearsOfExperience, + mostImpressiveBuild: match.participant.mostImpressiveBuild, + score: match.score, + reason: match.reason, + mutualInterest: match.mutualInterest, + })); +} + +export async function getParticipantMatches(eventSlug: string) { + const session = await getSession(); + if (!session) throw new Error("Sign in to view your matches"); + 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, "viewMatches"); + const results = await getMyMatches({ eventId: event.id, participantId: session.attendeeId }, container.matches); + return results.map((match) => ({ + id: match.participant.attendeeId, + name: match.participant.name, + designation: match.participant.designation, + domain: match.participant.domain, + aboutMe: match.participant.aboutMe, + yearsOfExperience: match.participant.yearsOfExperience, + mostImpressiveBuild: match.participant.mostImpressiveBuild, + score: match.score, + scoreBreakdown: match.scoreBreakdown, + reason: match.reason, + mutualInterest: match.mutualInterest, + })); +} + +export async function refreshParticipantMatches(eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => queueRefresh(eventSlug)); +} + +async function queueRefresh(eventSlug: string) { + const session = await getSession(); + if (!session) throw new Error("Sign in to refresh your matches"); + 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, "refreshMatches"); + await container.enqueueEmbedding(event.id, session.attendeeId); + redirect(`/e/${eventSlug}/matches`); +} diff --git a/apps/web/app/actions/organizer.actions.ts b/apps/web/app/actions/organizer.actions.ts new file mode 100644 index 0000000..fa5c761 --- /dev/null +++ b/apps/web/app/actions/organizer.actions.ts @@ -0,0 +1,144 @@ +"use server"; + +import { redirect } from "next/navigation"; +import { configureProfileForm, createEvent, importEventRoster, queueEventMatches, updateEvent } from "../../src/application/use-cases/manage-event"; +import { PROFILE_FIELD_KEYS, type ProfileFieldKey, type ProfileFieldSetting } from "../../src/domain/participant/profile-form"; +import { getContainer } from "../../src/composition/container"; +import { assertEventAllows } from "../../src/domain/shared/event-lifecycle"; +import { LIMITS, ValidationError } from "../../src/domain/shared/validation"; +import { runFormAction, type FormState } from "../../lib/form-state"; +import { parseRosterWorkbook } from "../../src/lib/excel-importer"; +import { getSession } from "../../lib/session"; +import { sendInvitations, setAttendeeAccess } from "../../src/application/use-cases/manage-invitations"; + +export async function createEventAction(organizationSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, async () => { + const session = await getSession(); + if (!session) throw new Error("Sign in as an organizer first"); + const event = await createEvent({ + organizationSlug, + organizerId: session.attendeeId, + name: String(formData.get("name") ?? ""), + slug: String(formData.get("slug") ?? ""), + description: String(formData.get("description") ?? ""), + }, getContainer().events).catch((error) => { + if (error?.code === "23505") throw new ValidationError("slug", "That URL slug is already used by another event"); + throw error; + }); + redirect(`/orgs/${organizationSlug}/events/${event.slug}`); + }); +} + +export async function importEventRosterAction(organizationSlug: string, eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => importRoster(organizationSlug, eventSlug, formData)); +} + +async function importRoster(organizationSlug: string, eventSlug: string, formData: FormData) { + const session = await getSession(); + if (!session) throw new Error("Sign in as an organizer first"); + const file = formData.get("file"); + if (!(file instanceof File) || !file.size) throw new ValidationError("file", "Choose an Excel roster file"); + if (file.size > LIMITS.rosterBytes) throw new ValidationError("file", "Roster files are limited to 10 MB"); + const container = getContainer(); + 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, 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), + }); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}/roster?${report}`); +} + +export async function updateEventAction(organizationSlug: string, eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => saveEvent(organizationSlug, eventSlug, formData)); +} + +async function saveEvent(organizationSlug: string, eventSlug: string, formData: FormData) { + 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 status = String(formData.get("status") || event.status); + if (!["draft", "open", "closed"].includes(status)) throw new ValidationError("status", "Choose a valid event status"); + const intents = String(formData.get("intents") ?? "").split(","); + const zones = String(formData.get("zones") ?? "").split(","); + await updateEvent({ + eventId: event.id, + organizerId: session.attendeeId, + name: String(formData.get("name") ?? ""), + description: String(formData.get("description") || ""), + status: status as "draft" | "open" | "closed", + intents, + zones, + }, container.events, container.audit); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}?saved=1`); +} + +export async function computeEventMatchesAction(organizationSlug: string, eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, () => queueMatches(organizationSlug, eventSlug)); +} + +async function queueMatches(organizationSlug: string, eventSlug: string) { + 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"); + assertEventAllows(event.status, "computeMatches"); + 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}`); +} + +/** Invites everyone never invited, or (with attendeeId) resends to one person. */ +export async function sendInvitationsAction(organizationSlug: string, eventSlug: string, attendeeId: string | null, _state: FormState, formData: FormData): Promise { + 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 base = (process.env.APP_BASE_URL || "").replace(/\/$/, ""); + const result = await sendInvitations({ + eventId: event.id, + organizerId: session.attendeeId, + eventName: event.name, + organizationName: event.organization_name, + eventUrl: `${base}/e/${event.slug}`, + attendeeId: attendeeId ?? undefined, + }, container); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}/roster?invited=${result.sent}&failed=${result.failed}`); + }); +} + +export async function setAttendeeAccessAction(organizationSlug: string, eventSlug: string, attendeeId: string, revoked: boolean, _state: FormState, formData: FormData): Promise { + 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"); + await setAttendeeAccess({ eventId: event.id, organizerId: session.attendeeId, attendeeId, revoked }, container); + redirect(`/orgs/${organizationSlug}/events/${eventSlug}/roster?access=${revoked ? "removed" : "restored"}`); + }); +} + +export async function updateProfileFormAction(organizationSlug: string, eventSlug: string, _state: FormState, formData: FormData): Promise { + 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, container.audit); + 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 new file mode 100644 index 0000000..b55335b --- /dev/null +++ b/apps/web/app/actions/participant.actions.ts @@ -0,0 +1,70 @@ +"use server"; + +import { upsertParticipant } from "../../src/application/use-cases/upsert-participant"; +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"; + +export async function saveParticipantProfile(eventSlug: string, _state: FormState, formData: FormData): Promise { + return runFormAction(formData, async () => { + await saveProfile(eventSlug, formData); + redirect(`/e/${eventSlug}/matches?saved=1`); + }); +} + +async function saveProfile(eventSlug: string, formData: FormData) { + const session = await getSession(); + if (!session) throw new Error("Sign in before saving your profile"); + 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 on this event's registration list"); + } + assertEventAllows(event.status, "saveProfile"); + + const intentValue = String(formData.get("intent") || Intent.NETWORKING); + if (!event.intents.includes(intentValue) || !Object.values(Intent).includes(intentValue as Intent)) { + throw new ValidationError("intent", "Choose an intent configured for this event"); + } + const venueZone = nullable(formData.get("venueZone")); + if (venueZone && !event.zones.includes(venueZone)) throw new ValidationError("venueZone", "Choose a venue zone configured for this event"); + await upsertParticipant({ + eventId: event.id, + attendeeId: session.attendeeId, + intent: intentValue as Intent, + interests: String(formData.get("interests") || "").split(","), + venueZone, + aboutMe: nullable(formData.get("aboutMe")), + designation: nullable(formData.get("designation")), + domain: nullable(formData.get("domain")), + selfDescription: nullable(formData.get("selfDescription")), + yearsOfExperience: parseYears(formData.get("yearsOfExperience")), + mostImpressiveBuild: nullable(formData.get("mostImpressiveBuild")), + visible: formData.get("visible") === "on", + }, { participants: container.participants }, readProfileForm(event.form_config)); +} + +export async function signOutCurrentUser() { + const session = await getSession(); + await clearSession(); + await endIdentityProviderSession(session); + redirect("/login"); +} + +function nullable(value: FormDataEntryValue | null): string | null { + const result = String(value ?? "").trim(); + return result || null; +} + +function parseYears(value: FormDataEntryValue | null): number | null { + const text = String(value ?? "").trim(); + if (!text) return null; + const years = Number(text); + if (!Number.isInteger(years)) throw new ValidationError("yearsOfExperience", "Years of experience must be a whole number"); + return years; +} diff --git a/apps/web/app/api/auth/google/start/route.js b/apps/web/app/api/auth/google/start/route.js new file mode 100644 index 0000000..026be95 --- /dev/null +++ b/apps/web/app/api/auth/google/start/route.js @@ -0,0 +1,68 @@ +import { NextResponse } from "next/server"; +import { attendees } from "@match-maker/db"; +import { canReturnToPath } from "@/lib/session"; +import { loginErrorPath, safeReturnTo } from "@/lib/safe-return-to"; +import { + buildAuthorizationUrl, + createPkce, + randomUrlSafe, + sealOAuthState, + sessionCookieOptions, + isGoogleSignInEnabled, + OAUTH_COOKIE_NAME, + OAUTH_COOKIE_MAX_AGE, +} from "@match-maker/auth"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Begin Google sign-in. + * + * `kc_idp_hint` makes Keycloak forward straight to Google instead of rendering + * its own login page, so the user's journey is unchanged from the Supabase + * version: our login screen → Google → back here. + */ +export async function GET(request) { + const url = new URL(request.url); + const email = url.searchParams.get("email")?.toLowerCase().trim() || ""; + const returnTo = safeReturnTo(url.searchParams.get("returnTo")); + if (!isGoogleSignInEnabled()) { + return NextResponse.redirect(new URL(loginErrorPath("google_unavailable", returnTo), url.origin)); + } + + try { + // The browser already checked the roster, but that check is advisory — + // re-run it here so the redirect itself cannot be forged. + if (email) { + const attendee = await attendees.findByEmail(email); + if (!attendee || !(await canReturnToPath(returnTo, attendee.id))) { + return NextResponse.redirect(new URL(loginErrorPath("unregistered", returnTo), url.origin)); + } + } + + const { codeVerifier, codeChallenge } = createPkce(); + const state = randomUrlSafe(16); + const nonce = randomUrlSafe(16); + + const authorizationUrl = await buildAuthorizationUrl({ + state, + nonce, + codeChallenge, + loginHint: email || undefined, + useGoogleIdp: true, + }); + + const response = NextResponse.redirect(authorizationUrl); + response.cookies.set( + OAUTH_COOKIE_NAME, + await sealOAuthState({ state, nonce, codeVerifier, returnTo }), + sessionCookieOptions(OAUTH_COOKIE_MAX_AGE) + ); + return response; + } catch (err) { + console.error("[auth/google/start]", err); + return NextResponse.redirect(new URL(loginErrorPath("provider", returnTo), url.origin)); + } +} + diff --git a/apps/web/app/api/auth/logout/route.js b/apps/web/app/api/auth/logout/route.js new file mode 100644 index 0000000..943469c --- /dev/null +++ b/apps/web/app/api/auth/logout/route.js @@ -0,0 +1,18 @@ +import { NextResponse } from "next/server"; +import { clearSession, endIdentityProviderSession, getSession } from "@/lib/session"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Sign out. Clears the local session, and for Google logins also ends the + * Keycloak SSO session server-side — otherwise the next sign-in would silently + * re-use it and appear to ignore the logout. Same behaviour as the Sign out + * button (signOutCurrentUser). + */ +export async function POST() { + const session = await getSession(); + await clearSession(); + await endIdentityProviderSession(session); + return NextResponse.json({ ok: true, redirectTo: "/login" }); +} diff --git a/apps/web/app/api/auth/lookup/route.js b/apps/web/app/api/auth/lookup/route.js new file mode 100644 index 0000000..30f8a2f --- /dev/null +++ b/apps/web/app/api/auth/lookup/route.js @@ -0,0 +1,16 @@ +import { NextResponse } from "next/server"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Retired (R09). This roster lookup returned an attendee's name and e-mail + * for any phone number or address, without a rate limit, so it could be used + * to enumerate the roster. The login page never called it: sign-in goes + * through /api/auth/otp/request, which is rate limited per e-mail and per IP. + * + * The route file stays so old clients get a clear answer instead of a 404. + */ +export async function POST() { + return NextResponse.json({ error: "This endpoint has been retired." }, { status: 410 }); +} diff --git a/apps/web/app/api/auth/otp/request/route.js b/apps/web/app/api/auth/otp/request/route.js new file mode 100644 index 0000000..c02e1e3 --- /dev/null +++ b/apps/web/app/api/auth/otp/request/route.js @@ -0,0 +1,93 @@ +import { NextResponse } from "next/server"; +import { attendees } from "@match-maker/db"; +import { issueChallenge, getOtpConfig, RateLimitError } from "@match-maker/auth"; +import { sendLoginEmail } from "@match-maker/email"; +import { canReturnToPath, clientIp } from "@/lib/session"; +import { safeReturnTo } from "@/lib/safe-return-to"; +import { limitByIp, requireJson } from "@/lib/rate-limit"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Start an e-mail login. Accepts either a phone number or an e-mail address, + * resolves it against the roster server-side, and sends one message containing + * both a 6-digit code and a one-click magic link. + * + * The caller never learns the resolved address in full — it only gets a masked + * form for display, so this endpoint cannot be used to turn phone numbers into + * e-mail addresses. + */ +export async function POST(request) { + try { + const refused = requireJson(request) ?? await limitByIp(request, "otpRequest"); + if (refused) return refused; + const { phone, email, returnTo: requestedReturnTo } = await request.json().catch(() => ({})); + const returnTo = safeReturnTo(requestedReturnTo); + + if (!phone && !email) { + return NextResponse.json( + { error: "Provide a phone number or an e-mail address" }, + { status: 400 } + ); + } + + const attendee = phone + ? await attendees.findByPhone(String(phone)) + : await attendees.findByEmail(String(email)); + + if (!attendee?.email) { + return NextResponse.json({ registered: false }); + } + if (!(await canReturnToPath(returnTo, attendee.id))) return NextResponse.json({ registered: false }); + + const { code, token, expiresAt } = await issueChallenge({ + email: attendee.email, + attendeeId: attendee.id, + ipAddress: clientIp(request), + }); + + const baseUrl = (process.env.APP_BASE_URL || new URL(request.url).origin).replace( + /\/$/, + "" + ); + + const { ttlSeconds } = getOtpConfig(); + const result = await sendLoginEmail(attendee.email, { + name: attendee.name, + code, + magicLinkUrl: `${baseUrl}/auth/callback?token=${encodeURIComponent(token)}&returnTo=${encodeURIComponent(returnTo)}`, + expiresInMinutes: Math.round(ttlSeconds / 60), + }); + + return NextResponse.json({ + registered: true, + sent: true, + email: maskEmail(attendee.email), + expiresAt: expiresAt.toISOString(), + // Surfaces the local no-API-key path so developers know why no e-mail + // arrived; always true in production. + delivered: result.delivered, + }); + } catch (err) { + if (err instanceof RateLimitError) { + return NextResponse.json( + { error: err.message }, + { status: 429, headers: { "Retry-After": String(err.retryAfterSeconds) } } + ); + } + console.error("[auth/otp/request]", err); + return NextResponse.json( + { error: "Could not send the login e-mail. Please try again." }, + { status: 500 } + ); + } +} + +function maskEmail(email) { + const [user, domain] = email.split("@"); + if (!user || !domain) return email; + const visible = user.slice(0, Math.min(2, user.length)); + return `${visible}${"•".repeat(Math.max(user.length - 2, 1))}@${domain}`; +} + diff --git a/apps/web/app/api/auth/otp/verify/route.js b/apps/web/app/api/auth/otp/verify/route.js new file mode 100644 index 0000000..27512c4 --- /dev/null +++ b/apps/web/app/api/auth/otp/verify/route.js @@ -0,0 +1,82 @@ +import { NextResponse } from "next/server"; +import { attendees } from "@match-maker/db"; +import { verifyCode, ensureUser, CODE_LENGTH } from "@match-maker/auth"; +import { canReturnToPath, setSession } from "@/lib/session"; +import { limitByIp, requireJson } from "@/lib/rate-limit"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +const FAILURE_MESSAGES = { + not_found: "That code has expired. Request a new one.", + expired: "That code has expired. Request a new one.", + too_many_attempts: "Too many incorrect attempts. Request a new code.", + invalid_code: "Incorrect code. Please check and try again.", + already_used: "That code has already been used.", +}; + +/** + * Redeem a typed 6-digit code and open a session. + * + * The identifier is re-resolved server-side rather than trusted from the body, + * so a caller cannot submit someone else's e-mail with their own code. + */ +export async function POST(request) { + try { + const refused = requireJson(request) ?? await limitByIp(request, "otpVerify"); + if (refused) return refused; + const { phone, email, code, returnTo } = await request.json().catch(() => ({})); + + const normalizedCode = String(code ?? "").replace(/\D/g, ""); + if (normalizedCode.length !== CODE_LENGTH) { + return NextResponse.json( + { error: `Enter the ${CODE_LENGTH}-digit code from your e-mail.` }, + { status: 400 } + ); + } + + const attendee = phone + ? await attendees.findByPhone(String(phone)) + : email + ? await attendees.findByEmail(String(email)) + : null; + + if (!attendee?.email) { + return NextResponse.json( + { error: FAILURE_MESSAGES.not_found }, + { status: 400 } + ); + } + if (!(await canReturnToPath(returnTo, attendee.id))) { + return NextResponse.json({ error: FAILURE_MESSAGES.not_found }, { status: 400 }); + } + + const result = await verifyCode(attendee.email, normalizedCode); + if (!result.ok) { + return NextResponse.json( + { error: FAILURE_MESSAGES[result.reason] ?? "Verification failed." }, + { status: result.reason === "too_many_attempts" ? 429 : 400 } + ); + } + + // Give the account a Keycloak identity so an e-mail login and a later + // Google login for the same address resolve to the same `sub`. + const subject = await ensureUser(attendee.email, attendee.name); + + await setSession({ + sub: subject, + email: attendee.email, + name: attendee.name, + attendeeId: attendee.id, + method: "email", + }); + + return NextResponse.json({ ok: true }); + } catch (err) { + console.error("[auth/otp/verify]", err); + return NextResponse.json( + { error: "Verification failed. Please try again." }, + { status: 500 } + ); + } +} diff --git a/apps/web/app/api/domains/route.js b/apps/web/app/api/domains/route.js new file mode 100644 index 0000000..dbe77bf --- /dev/null +++ b/apps/web/app/api/domains/route.js @@ -0,0 +1,18 @@ +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/session"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Retired (R07). Listed the domains of every attendee across all + * organizations for the old single-page matcher (app/MatchApp.jsx). The + * event profile form now uses free-text domains scoped to its event. + */ +export async function GET() { + const session = await getSession(); + if (!session) { + return NextResponse.json({ error: "Not authenticated" }, { status: 401 }); + } + return NextResponse.json({ error: "This endpoint has been retired." }, { status: 410 }); +} diff --git a/apps/web/app/api/health/ready/route.js b/apps/web/app/api/health/ready/route.js new file mode 100644 index 0000000..b7e6302 --- /dev/null +++ b/apps/web/app/api/health/ready/route.js @@ -0,0 +1,45 @@ +import { NextResponse } from "next/server"; +import { query } from "@match-maker/db"; +import { discover } from "@match-maker/auth"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Readiness probe — reports whether dependencies are actually reachable. + * + * Used by deploy scripts and dashboards, NOT by the ALB target group (see + * /api/health for why). Checks run in parallel so one slow dependency doesn't + * serialise the whole response. + */ +export async function GET() { + const [database, keycloak] = await Promise.all([ + check(async () => { + await query("select 1"); + }), + check(async () => { + await discover(); + }), + ]); + + const ready = database.ok && keycloak.ok; + + return NextResponse.json( + { ready, checks: { database, keycloak }, timestamp: new Date().toISOString() }, + { status: ready ? 200 : 503 } + ); +} + +async function check(fn) { + const startedAt = Date.now(); + try { + await fn(); + return { ok: true, latencyMs: Date.now() - startedAt }; + } catch (err) { + return { + ok: false, + latencyMs: Date.now() - startedAt, + error: err instanceof Error ? err.message : String(err), + }; + } +} diff --git a/apps/web/app/api/health/route.js b/apps/web/app/api/health/route.js new file mode 100644 index 0000000..b89f473 --- /dev/null +++ b/apps/web/app/api/health/route.js @@ -0,0 +1,23 @@ +import { NextResponse } from "next/server"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Liveness probe for the ALB target group and the container HEALTHCHECK. + * + * Deliberately touches nothing external. If this returned unhealthy whenever + * Postgres or Keycloak hiccuped, the load balancer would drain every task at + * once and turn a recoverable dependency blip into a full outage. Dependency + * health is reported separately by /api/health/ready. + */ +export async function GET() { + return NextResponse.json({ + status: "ok", + service: "match-maker-web", + // Release tag baked into the image; the deploy smoke test checks it. + version: process.env.APP_VERSION || "dev", + uptime: Math.round(process.uptime()), + timestamp: new Date().toISOString(), + }); +} diff --git a/apps/web/app/api/match/route.js b/apps/web/app/api/match/route.js new file mode 100644 index 0000000..14d9a89 --- /dev/null +++ b/apps/web/app/api/match/route.js @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server"; +import { getSession } from "@/lib/session"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * Retired (R07). This endpoint used to rank the whole attendee directory — + * every organization and event, hidden profiles included — through its own + * Gemini prompt and a process-wide uploaded file. Matching now happens only + * inside an event, through the shared pipeline: saved matches at + * /e//matches and search at /e//search, both of which check + * event membership and profile eligibility. + * + * The route file stays so old clients get a clear answer instead of a 404. + */ +export async function POST() { + const session = await getSession(); + if (!session) { + return NextResponse.json({ error: "Not authenticated" }, { status: 401 }); + } + return NextResponse.json( + { + error: "This matching endpoint has been retired. Open your event's matches page instead.", + matchesPath: "/e//matches", + }, + { status: 410 } + ); +} diff --git a/apps/web/app/api/me/route.js b/apps/web/app/api/me/route.js new file mode 100644 index 0000000..a1e8b0d --- /dev/null +++ b/apps/web/app/api/me/route.js @@ -0,0 +1,46 @@ +import { NextResponse } from "next/server"; +import { attendees } from "@match-maker/db"; +import { getSession } from "@/lib/session"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * The signed-in user's session plus their roster profile. + * + * Replaces the browser's direct `registered_attendees` query. The profile is + * read by id from the session, so a caller can only ever fetch their own row. + */ +export async function GET() { + const session = await getSession(); + if (!session) { + return NextResponse.json({ authenticated: false }, { status: 401 }); + } + + const profile = await attendees.findById(session.attendeeId); + if (!profile) { + // On the roster at login, removed since. Treat as signed out. + return NextResponse.json({ authenticated: false }, { status: 401 }); + } + + return NextResponse.json({ + authenticated: true, + user: { + email: session.email, + name: session.name, + method: session.method, + }, + profile: { + id: profile.id, + name: profile.name, + email: profile.email, + phone: profile.phone, + about_me: profile.about_me, + designation: profile.designation, + domain: profile.domain, + self_description: profile.self_description, + years_of_experience: profile.years_of_experience, + most_impressive_build: profile.most_impressive_build, + }, + }); +} diff --git a/apps/web/app/api/webhooks/.gitkeep b/apps/web/app/api/webhooks/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/app/auth/callback/route.js b/apps/web/app/auth/callback/route.js new file mode 100644 index 0000000..90d752e --- /dev/null +++ b/apps/web/app/auth/callback/route.js @@ -0,0 +1,139 @@ +import { NextResponse } from "next/server"; +import { attendees } from "@match-maker/db"; +import { canReturnToPath } from "@/lib/session"; +import { loginErrorPath, safeReturnTo } from "@/lib/safe-return-to"; +import { + exchangeCodeForTokens, + verifyIdToken, + unsealOAuthState, + verifyToken, + ensureUser, + sealSession, + sessionCookieOptions, + getSessionConfig, + OAUTH_COOKIE_NAME, +} from "@match-maker/auth"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * The single return point for both login methods. + * + * ?token=… magic link from the login e-mail + * ?code=…&state=… authorization code from Keycloak (Google) + * + * This replaced the old client-side callback page. Running server-side means + * the code and token are redeemed without ever being handed to browser + * JavaScript, and the user lands on the destination in one redirect. + */ +export async function GET(request) { + const url = new URL(request.url); + const origin = process.env.APP_BASE_URL || url.origin; + + const providerError = url.searchParams.get("error"); + if (providerError) { + // A cancelled Google consent lands here; the state cookie still knows + // which event the user was joining. + console.warn("[auth/callback] provider error:", providerError); + const stored = await unsealOAuthState(request.cookies.get(OAUTH_COOKIE_NAME)?.value ?? ""); + return redirectTo(origin, loginErrorPath("provider", stored?.returnTo)); + } + + const token = url.searchParams.get("token"); + if (token) return handleMagicLink(token, origin, safeReturnTo(url.searchParams.get("returnTo"))); + + const code = url.searchParams.get("code"); + const state = url.searchParams.get("state"); + if (code && state) return handleAuthorizationCode(request, code, state, origin); + + return redirectTo(origin, loginErrorPath("invalid_callback", url.searchParams.get("returnTo"))); +} + +async function handleMagicLink(token, origin, returnTo) { + try { + const result = await verifyToken(token); + if (!result.ok) { + return redirectTo(origin, loginErrorPath(result.reason, returnTo)); + } + + const attendee = result.attendeeId + ? await attendees.findById(result.attendeeId) + : await attendees.findByEmail(result.email); + + if (!attendee) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + + const subject = await ensureUser(attendee.email, attendee.name); + return await redirectWithSession(origin, returnTo, { + sub: subject, + email: attendee.email, + name: attendee.name, + attendeeId: attendee.id, + method: "email", + }); + } catch (err) { + console.error("[auth/callback] magic link:", err); + return redirectTo(origin, loginErrorPath("verification_failed", returnTo)); + } +} + +async function handleAuthorizationCode(request, code, state, origin) { + let stored = null; + try { + stored = await unsealOAuthState( + request.cookies.get(OAUTH_COOKIE_NAME)?.value ?? "" + ); + + // No cookie means the flow was started in another browser or expired; + // a mismatch means someone tried to inject their own authorization code. + if (!stored || stored.state !== state) { + return redirectTo(origin, loginErrorPath("state_mismatch", stored?.returnTo)); + } + + const tokens = await exchangeCodeForTokens(code, stored.codeVerifier); + const claims = await verifyIdToken(tokens.id_token, stored.nonce); + + const email = claims.email?.toLowerCase().trim(); + const returnTo = safeReturnTo(stored.returnTo); + if (!email) return redirectTo(origin, loginErrorPath("no_email", returnTo)); + if (claims.email_verified !== true) return redirectTo(origin, loginErrorPath("email_unverified", returnTo)); + + // The roster is still the gate: a valid Google account that is not an + // attendee gets no session, matching the previous sign-out-on-callback + // behaviour. + const attendee = await attendees.findByEmail(email); + if (!attendee) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + if (!(await canReturnToPath(returnTo, attendee.id))) return redirectTo(origin, loginErrorPath("unregistered", returnTo)); + + const response = await redirectWithSession(origin, returnTo, { + sub: claims.sub, + email, + name: attendee.name ?? claims.name ?? null, + attendeeId: attendee.id, + method: "google", + }); + + return response; + } catch (err) { + console.error("[auth/callback] authorization code:", err); + return redirectTo(origin, loginErrorPath("verification_failed", stored?.returnTo)); + } +} + +async function redirectWithSession(origin, path, session) { + const config = getSessionConfig(); + const response = redirectTo(origin, path); + response.cookies.set( + config.cookieName, + await sealSession(session), + sessionCookieOptions(config.maxAge) + ); + return response; +} + +function redirectTo(origin, path) { + const response = NextResponse.redirect(new URL(safeReturnTo(path), origin)); + response.cookies.set(OAUTH_COOKIE_NAME, "", sessionCookieOptions(0)); + return response; +} diff --git a/apps/web/app/error.tsx b/apps/web/app/error.tsx new file mode 100644 index 0000000..5dab20a --- /dev/null +++ b/apps/web/app/error.tsx @@ -0,0 +1,23 @@ +"use client"; + +import Link from "next/link"; +import { useEffect } from "react"; + +/** Shown instead of a blank crash page when a page fails to render. */ +export default function ErrorPage({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) { + useEffect(() => { + console.error(error); + }, [error]); + + return
+

Something went wrong.

+

This page could not load. Please try again; if it keeps happening, sign in again or contact the event organizer.

+ {error.digest &&

Reference: {error.digest}

} +
+ + Go to the start +
+
; +} + +const shell = { minHeight: "100vh", maxWidth: 680, margin: "0 auto", padding: "12vh 24px" } as const; diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css new file mode 100644 index 0000000..1454048 --- /dev/null +++ b/apps/web/app/globals.css @@ -0,0 +1,100 @@ +/* Shared styles for things inline styles cannot express: focus, form states, + small screens, and reduced motion. Page layout stays in each page. */ +:root { + --bg: #0a0a0e; + --surface: #151519; + --border: #3f3f46; + --text: #f4f4f5; + --muted: #a1a1aa; + --accent: #f59e0b; + --danger: #fca5a5; + --success: #86efac; + color-scheme: dark; +} + +body { color: var(--text); line-height: 1.5; } +a { color: var(--accent); } +h1 { font-size: clamp(1.75rem, 5vw, 2.5rem); line-height: 1.2; } + +:where(a, button, input, select, textarea, summary):focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} + +nav { display: flex; flex-wrap: wrap; gap: 8px 20px; margin-bottom: 24px; } +.nav-signout { margin-left: auto; } +.link-button { border: 0; padding: 0; background: none; color: var(--accent); font: inherit; text-decoration: underline; cursor: pointer; } + +/* Forms */ +.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px; margin-top: 28px; } +.form-stack { display: grid; gap: 16px; max-width: 680px; margin: 20px 0; } +.form-grid > .form-alert, .form-grid > .form-actions { grid-column: 1 / -1; } +.field { display: grid; gap: 6px; align-content: start; } +.field label { font-weight: 600; font-size: 14px; } +.field :where(input, select, textarea) { + width: 100%; + box-sizing: border-box; + padding: 11px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + color: var(--text); + font: inherit; +} +.field input[readonly] { color: var(--muted); } +.field input[type="file"] { padding: 9px; } +.field [aria-invalid="true"] { border-color: var(--danger); } +.field-hint { color: var(--muted); } +.field-error { color: var(--danger); margin: 0; } +.form-alert { margin: 0; padding: 12px 14px; border: 1px solid var(--danger); border-radius: 8px; color: var(--danger); background: rgba(248, 113, 113, 0.08); } +.notice { padding: 12px 14px; border: 1px solid var(--success); border-radius: 8px; color: var(--success); background: rgba(134, 239, 172, 0.06); } +.empty-state { padding: 20px; border-radius: 12px; background: var(--surface); color: var(--muted); } +.action-form { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } +.action-form select { padding: 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface); color: var(--text); font: inherit; } +.upload-form { display: flex; flex-wrap: wrap; align-items: end; gap: 16px; padding: 20px; border-radius: 12px; background: var(--surface); } +.upload-form > .form-alert { flex-basis: 100%; } + +/* Buttons */ +.btn { + border: 0; + border-radius: 8px; + padding: 12px 16px; + min-height: 44px; + background: var(--accent); + color: var(--bg); + font: inherit; + font-weight: 700; + cursor: pointer; +} +.btn-secondary { border: 1px solid #52525b; background: transparent; color: var(--text); font-weight: 500; } +.btn:disabled { opacity: 0.6; cursor: progress; } + +table th, table td { padding: 10px 12px; border-bottom: 1px solid #27272a; } + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +@media (max-width: 600px) { + main { padding-left: 16px !important; padding-right: 16px !important; } + .form-actions .btn, .upload-form .btn { width: 100%; } + table { font-size: 14px; } +} + +/* Also overrides the login page's inline animations. */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} diff --git a/app/icon.png b/apps/web/app/icon.png similarity index 100% rename from app/icon.png rename to apps/web/app/icon.png diff --git a/app/layout.jsx b/apps/web/app/layout.jsx similarity index 90% rename from app/layout.jsx rename to apps/web/app/layout.jsx index 622817b..d1324ab 100644 --- a/app/layout.jsx +++ b/apps/web/app/layout.jsx @@ -1,3 +1,5 @@ +import "./globals.css"; + export const metadata = { title: "Mr. Bridge · AI Community Lucknow", description: "AI-powered attendee matchmaking for the AI Community Lucknow. Find your perfect collaborator at the event.", @@ -11,7 +13,7 @@ export default function RootLayout({ children }) { - + {children} diff --git a/app/login.jsx b/apps/web/app/login.jsx similarity index 64% rename from app/login.jsx rename to apps/web/app/login.jsx index 8e6b552..4fda5fd 100644 --- a/app/login.jsx +++ b/apps/web/app/login.jsx @@ -4,15 +4,36 @@ * Login.jsx — AI Community Lucknow · Mr. Bridge * Premium dark theme matching the AI Community Lucknow brand. * Amber/orange accent palette, Inter typography, glassmorphism cards. + * + * Auth is Keycloak-backed: + * · Phone → server resolves the registered e-mail, Resend delivers a + * 6-digit code and a magic link; either one signs the user in. + * · E-mail → the same on-site code and magic-link flow. + * · Google → Keycloak brokers Google authentication using kc_idp_hint. + * No browser-side database client and no auth SDK — every call is a fetch to + * this app's own API. */ import { useState, useEffect, useRef } from "react"; -import { createClient } from "@supabase/supabase-js"; - -const supabase = createClient( - process.env.NEXT_PUBLIC_SUPABASE_URL, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY -); +import { useSearchParams } from "next/navigation"; +import { safeReturnTo } from "../lib/safe-return-to"; + +const CODE_LENGTH = 6; + +// Callback failures come back as ?error=… — map them to human copy. +const ERROR_MESSAGES = { + unregistered: "That account is not on the attendee list.", + provider: "Google sign-in failed. Please try again.", + google_unavailable: "Google sign-in isn't available yet. Please use an email code.", + state_mismatch: "Your sign-in session expired. Please start again.", + verification_failed: "We couldn't verify that sign-in. Please try again.", + invalid_callback: "That sign-in link is incomplete. Please try again.", + no_email: "Google didn't share an e-mail address with us.", + email_unverified: "Google couldn't verify your email address. Please use an email code.", + not_found: "That login link has expired. Request a new one.", + expired: "That login link has expired. Request a new one.", + already_used: "That login link has already been used.", +}; // ── Particle background (warm amber tones) ───────────────────── function ParticleBackground() { @@ -74,21 +95,25 @@ function StatusPill({ type, text }) { const s = cfg[type] || cfg.info; return (
- {s.icon} {text} + {s.icon} {text}
); } -export default function Login({ onAuthSuccess }) { +export default function Login({ onAuthSuccess, googleEnabled = false }) { + const searchParams = useSearchParams(); + const returnTo = safeReturnTo(searchParams.get("returnTo")); const [step, setStep] = useState("choose"); const [method, setMethod] = useState(null); const [input, setInput] = useState(""); const [resolvedEmail, setResolvedEmail] = useState(""); + const [code, setCode] = useState(""); + const [verifying, setVerifying] = useState(false); const [loading, setLoading] = useState(false); const [status, setStatus] = useState(null); const [resendTimer, setResendTimer] = useState(0); const [hoveredCard, setHoveredCard] = useState(null); - const [btnHover, setBtnHover] = useState(false); + const identifier = method === "phone" ? { phone: input } : { email: input.trim() }; useEffect(() => { if (resendTimer <= 0) return; @@ -96,72 +121,61 @@ export default function Login({ onAuthSuccess }) { return () => clearInterval(t); }, [resendTimer]); + // Surface a failure handed back by /auth/callback. useEffect(() => { - supabase.auth.onAuthStateChange(async (event, session) => { - if (event === "SIGNED_IN" && session) { - onAuthSuccess?.(session.user); - } - }); - }, []); - - const handlePhoneSubmit = async () => { - setLoading(true); setStatus(null); + const err = searchParams.get("error"); + if (!err) return; + if (err === "unregistered") { setStep("error-unregistered"); return; } + setStatus({ type: "error", text: ERROR_MESSAGES[err] || "Sign-in failed. Please try again." }); + }, [searchParams]); + + const requestCode = async (isResend = false) => { + setLoading(true); + if (!isResend) setStatus(null); try { - const res = await fetch("/api/lookup-email", { + const res = await fetch("/api/auth/otp/request", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ phone: input }), + body: JSON.stringify({ ...identifier, returnTo }), }); const data = await res.json(); + if (res.status === 429) throw new Error(data.error); + if (!res.ok) throw new Error(data.error || "Failed to send login email"); if (!data.registered) { setStep("error-unregistered"); setLoading(false); return; } - const { error } = await supabase.auth.signInWithOtp({ - email: data.email, - options: { shouldCreateUser: true }, - }); - if (error) throw error; + setResolvedEmail(data.email); + setCode(""); setStep("magic-link-sent"); setResendTimer(30); + if (isResend) setStatus({ type: "success", text: "A new code is on its way." }); } catch (err) { setStatus({ type: "error", text: err.message || "Failed to send login email" }); } setLoading(false); }; - const checkEmailRegistered = async (email) => { - const { data, error } = await supabase - .from("registered_attendees") - .select("id") - .eq("email", email.toLowerCase().trim()) - .maybeSingle(); - if (error) throw new Error("Registry lookup failed"); - return !!data; - }; - - const handleEmailSubmit = async () => { - setLoading(true); setStatus(null); + const handleCodeSubmit = async () => { + if (code.length !== CODE_LENGTH || verifying) return; + setVerifying(true); setStatus(null); try { - const registered = await checkEmailRegistered(input); - if (!registered) { setStep("error-unregistered"); setLoading(false); return; } - sessionStorage.setItem("pending_email", input.toLowerCase().trim()); - const { error } = await supabase.auth.signInWithOAuth({ - provider: "google", - options: { - redirectTo: `${window.location.origin}/auth/callback`, - queryParams: { login_hint: input.trim() }, - }, + const res = await fetch("/api/auth/otp/verify", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...identifier, code, returnTo }), }); - if (error) throw error; - setStep("email-pending"); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || "Verification failed"); + onAuthSuccess?.(returnTo); } catch (err) { - setStatus({ type: "error", text: err.message || "Google sign-in failed" }); + setStatus({ type: "error", text: err.message || "Verification failed" }); + setCode(""); + setVerifying(false); } - setLoading(false); }; - const reset = () => { setStep("choose"); setMethod(null); setInput(""); setStatus(null); setResolvedEmail(""); }; + const reset = () => { setStep("choose"); setMethod(null); setInput(""); setStatus(null); setResolvedEmail(""); setCode(""); setVerifying(false); }; - const isValid = method === "phone" ? input.length === 10 : input.length > 4; + const isValid = method === "phone" ? /^\d{10}$/.test(input) : /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.trim()); return (
@@ -177,8 +191,9 @@ export default function Login({ onAuthSuccess }) { input::placeholder { color:#52525b; } ::-webkit-scrollbar { width:4px; } ::-webkit-scrollbar-thumb { background:#3f3f46; border-radius:2px; } - .method-card { cursor:pointer; padding:18px 20px; background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.08); border-radius:12px; transition:all 0.25s ease; display:flex; align-items:center; gap:16px; } + .method-card { width:100%; text-align:left; font:inherit; text-decoration:none; cursor:pointer; padding:18px 20px; background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.08); border-radius:12px; transition:all 0.25s ease; display:flex; align-items:center; gap:16px; } .method-card:hover { border-color:rgba(245,158,11,0.5); background:rgba(245,158,11,0.05); box-shadow:0 0 24px rgba(245,158,11,0.08); } + .method-card:focus-visible, .amber-btn:focus-visible, .ghost-btn:focus-visible { outline:2px solid #f59e0b; outline-offset:4px; } .method-card.active { border-color:rgba(245,158,11,0.7); background:rgba(245,158,11,0.08); } .amber-btn { width:100%; padding:13px; background:linear-gradient(135deg,#f59e0b,#d97706); border:none; border-radius:10px; color:#0a0a0e; font-family:Inter,sans-serif; font-size:14px; font-weight:700; letter-spacing:0.5px; cursor:pointer; transition:all 0.25s ease; box-shadow:0 4px 20px rgba(245,158,11,0.3); } .amber-btn:hover { background:linear-gradient(135deg,#fbbf24,#f59e0b); box-shadow:0 6px 28px rgba(245,158,11,0.45); transform:translateY(-1px); } @@ -186,6 +201,8 @@ export default function Login({ onAuthSuccess }) { .ghost-btn { background:none; border:1px solid rgba(255,255,255,0.1); border-radius:8px; color:#a1a1aa; padding:7px 14px; font-size:12px; cursor:pointer; letter-spacing:0.5px; font-family:Inter,sans-serif; transition:all 0.2s ease; } .ghost-btn:hover { border-color:rgba(245,158,11,0.4); color:#f59e0b; } .cyber-input { width:100%; padding:13px 16px; background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.1); border-radius:10px; color:#f4f4f5; font-family:Inter,sans-serif; font-size:14px; outline:none; transition:all 0.2s; caret-color:#f59e0b; } + .code-input { width:100%; padding:15px 16px; background:rgba(245,158,11,0.04); border:1px solid rgba(245,158,11,0.25); border-radius:10px; color:#f59e0b; font-family:'Courier New',monospace; font-size:24px; font-weight:700; letter-spacing:12px; text-align:center; outline:none; transition:all 0.2s; caret-color:#f59e0b; } + .code-input::placeholder { color:#3f3f46; letter-spacing:12px; } `} @@ -215,10 +232,11 @@ export default function Login({ onAuthSuccess }) { {step === "choose" && ( <>
Welcome back
-
Sign in to access the attendee matching system
+
Invited to an event? Verify your account to get started.
-
setHoveredCard("phone")} onMouseLeave={() => setHoveredCard(null)} @@ -227,12 +245,13 @@ export default function Login({ onAuthSuccess }) {
📱
Phone Number
-
We'll send a magic link to your registered email
+
Get a code at your registered email
›
-
+ -
setHoveredCard("email")} onMouseLeave={() => setHoveredCard(null)} @@ -241,12 +260,30 @@ export default function Login({ onAuthSuccess }) {
✉️
Email Address
-
Continue with Google OAuth
+
Get a sign-in code and stay on this website
›
-
+ + + {googleEnabled && +
+ +
+
+
Sign in with Google
+
Choose the Google account on your invitation
+
+ +
}
+ {status && } +
◈ Access is restricted to pre-registered attendees.
@@ -266,8 +303,8 @@ export default function Login({ onAuthSuccess }) {
{method === "phone" - ? "We'll look up your registered email and send you a magic link." - : "We'll verify you're registered, then redirect to Google."} + ? "We'll send a code to your registered email. Enter it here to sign in." + : "We'll send a code to your invited email. Enter it here to sign in."}
{method === "phone" ? ( @@ -275,11 +312,15 @@ export default function Login({ onAuthSuccess }) {
+91
setInput(e.target.value.replace(/\D/g, ""))} placeholder="9876543210" maxLength={10} - onKeyDown={e => e.key === "Enter" && handlePhoneSubmit()} + onKeyDown={e => e.key === "Enter" && isValid && !loading && requestCode(false)} style={{ paddingLeft: 52 }} />
@@ -287,10 +328,12 @@ export default function Login({ onAuthSuccess }) { setInput(e.target.value)} placeholder="you@example.com" - onKeyDown={e => e.key === "Enter" && handleEmailSubmit()} + onKeyDown={e => e.key === "Enter" && isValid && !loading && requestCode(false)} /> )} @@ -299,15 +342,15 @@ export default function Login({ onAuthSuccess }) { )} - {/* ── MAGIC LINK SENT ── */} + {/* ── CODE SENT ── magic link + typed code, same challenge ── */} {step === "magic-link-sent" && (
@@ -318,17 +361,41 @@ export default function Login({ onAuthSuccess }) {
Check your inbox
- A login link has been sent to
+ A login code has been sent to
{resolvedEmail}
-
+ setCode(e.target.value.replace(/\D/g, "").slice(0, CODE_LENGTH))} + placeholder="······" + inputMode="numeric" + autoComplete="one-time-code" + maxLength={CODE_LENGTH} + autoFocus + onKeyDown={e => e.key === "Enter" && code.length === CODE_LENGTH && handleCodeSubmit()} + /> + + {status && } + + + +
How to sign in
1. Open your email app
- 2. Find the email from Build with AI
- 3. Click the "Log In" button inside
- You'll be signed in automatically. + 2. Find the email from Mr. Bridge
+ 3. Type the 6-digit code above, or click the "Log In" button inside
+ Either one signs you in.
@@ -337,7 +404,8 @@ export default function Login({ onAuthSuccess }) { Resend available in {resendTimer}s ) : (
)} - {/* ── EMAIL PENDING ── */} - {step === "email-pending" && ( -
-
↗
-
Redirecting to Google…
-
- Taking you to Google sign-in.
- Only your registered email will be accepted. -
-
- )} - {/* ── NOT REGISTERED ── */} {step === "error-unregistered" && (
⛔
Not Registered
- {input} is not on the attendee list.
+ {input ? <>{input} is not on the attendee list. : "This account is not on the attendee list for this event."}
Please contact the event organiser to get added.
@@ -380,4 +436,4 @@ export default function Login({ onAuthSuccess }) {
); -} \ No newline at end of file +} diff --git a/apps/web/app/login/login-route.jsx b/apps/web/app/login/login-route.jsx new file mode 100644 index 0000000..b845c53 --- /dev/null +++ b/apps/web/app/login/login-route.jsx @@ -0,0 +1,19 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import Login from "../login.jsx"; + +export default function LoginRoute({ googleEnabled }) { + const router = useRouter(); + return ( + { + // The session cookie is set by the API response, so a refresh is needed + // for the server to see it on the next request. + router.replace(returnTo || "/"); + router.refresh(); + }} + /> + ); +} diff --git a/apps/web/app/login/page.jsx b/apps/web/app/login/page.jsx new file mode 100644 index 0000000..396275c --- /dev/null +++ b/apps/web/app/login/page.jsx @@ -0,0 +1,15 @@ +import { Suspense } from "react"; +import { isGoogleSignInEnabled } from "@match-maker/auth"; +import LoginRoute from "./login-route.jsx"; + +// Read Google availability per request, not once at build time. +export const dynamic = "force-dynamic"; + +export default function LoginPage() { + // `useSearchParams` (used for the ?error= handling) needs a Suspense boundary. + return ( + }> + + + ); +} diff --git a/apps/web/app/not-found.tsx b/apps/web/app/not-found.tsx new file mode 100644 index 0000000..3025d59 --- /dev/null +++ b/apps/web/app/not-found.tsx @@ -0,0 +1,9 @@ +import Link from "next/link"; + +export default function NotFound() { + return
+

Page not found.

+

This event or page does not exist, or it is not open right now.

+ Go to the start +
; +} diff --git a/apps/web/app/page.jsx b/apps/web/app/page.jsx new file mode 100644 index 0000000..37d734f --- /dev/null +++ b/apps/web/app/page.jsx @@ -0,0 +1,7 @@ +import { redirect } from "next/navigation"; + +export const dynamic = "force-dynamic"; + +export default function HomePage() { + redirect(`/e/${process.env.DEFAULT_EVENT_SLUG || "demo"}`); +} diff --git a/apps/web/components/organizer/.gitkeep b/apps/web/components/organizer/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/components/organizer/EventForms.tsx b/apps/web/components/organizer/EventForms.tsx new file mode 100644 index 0000000..30a7309 --- /dev/null +++ b/apps/web/components/organizer/EventForms.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { useActionState } from "react"; +import { initialFormState } from "@/lib/form-state"; +import { LIMITS } from "@/src/domain/shared/validation"; +import { FormAlert, SelectField, SubmitButton, TextField, type FormAction } from "../ui/form"; + +export function NewEventForm({ action }: { action: FormAction }) { + const [state, formAction] = useActionState(action, initialFormState); + return
+ + + + +
Create event
+ ; +} + +export function EventSetupForm({ action, event }: { + action: FormAction; + event: { name: string; description: string | null; status: string; intents: string[]; zones: string[] }; +}) { + const [state, formAction] = useActionState(action, initialFormState); + return
+ + + + + + +
Save event configuration
+ ; +} + +export function RosterUploadForm({ action }: { action: FormAction }) { + const [state, formAction] = useActionState(action, initialFormState); + const error = state.fieldErrors.file; + return
+ +
+ + + Up to 10 MB and {LIMITS.rosterRows.toLocaleString("en")} rows. Needs an e-mail column. + {error && {error}} +
+ Import roster + ; +} 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/.gitkeep b/apps/web/components/participant/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/components/participant/AutoRefresh.tsx b/apps/web/components/participant/AutoRefresh.tsx new file mode 100644 index 0000000..11b8f74 --- /dev/null +++ b/apps/web/components/participant/AutoRefresh.tsx @@ -0,0 +1,21 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +/** + * Re-renders the page from the server every `everyMs` while mounted, giving + * up after `forMs`. The page stops rendering it once matching settles. + */ +export default function AutoRefresh({ everyMs = 10_000, forMs = 180_000 }: { everyMs?: number; forMs?: number }) { + const router = useRouter(); + useEffect(() => { + const started = Date.now(); + const timer = setInterval(() => { + if (Date.now() - started > forMs) clearInterval(timer); + else router.refresh(); + }, everyMs); + return () => clearInterval(timer); + }, [router, everyMs, forMs]); + return null; +} diff --git a/apps/web/components/participant/MatchStatus.tsx b/apps/web/components/participant/MatchStatus.tsx new file mode 100644 index 0000000..1e02d9f --- /dev/null +++ b/apps/web/components/participant/MatchStatus.tsx @@ -0,0 +1,44 @@ +import { isInProgress, type QueueState } from "@/src/domain/matching/match-status"; +import { ActionForm, type FormAction } from "../ui/form"; +import AutoRefresh from "./AutoRefresh"; + +const EMPTY: Record = { + none: { title: "Your matches have not been computed yet.", body: "Start matching to rank attendees for your profile.", button: "Find my matches" }, + queued: { title: "Your matches are queued.", body: "Attendees are ranked in the background. This page updates on its own." }, + running: { title: "Ranking attendees for you…", body: "This usually takes under a minute. This page updates on its own." }, + stuck: { title: "Matching is taking longer than expected.", body: "Something may have interrupted it.", button: "Try again" }, + failed: { title: "We could not compute your matches.", body: "Matching failed after several attempts. Try again, or tell the organizer if it keeps failing.", button: "Try again" }, + done: { title: "No matches yet.", body: "Nobody compatible has completed a profile yet. Check back as more attendees join.", button: "Check again" }, +}; + +/** + * What the matches page says about background matching. With no matches it + * explains the state; with matches it only flags an update in progress or a + * failed one. `refresh` is omitted when the event no longer allows refreshing. + */ +export default function MatchStatus({ state, hasMatches, refresh }: { state: QueueState; hasMatches: boolean; refresh?: FormAction }) { + const working = isInProgress(state) && ; + const retry = (label: string) => refresh && ; + + if (hasMatches) { + if (isInProgress(state)) return

Updating your matches…{working}

; + if (state === "stuck" || state === "failed") { + return
+

The last update did not finish. These are your previous matches.

+ {retry("Try again")} +
; + } + return null; + } + + if (!refresh && !isInProgress(state)) { + return

No matches were saved for you.

This event has closed.

; + } + const copy = EMPTY[state]; + return
+

{copy.title}

+

{copy.body}

+ {working} + {copy.button && retry(copy.button)} +
; +} diff --git a/apps/web/components/participant/ProfileForm.tsx b/apps/web/components/participant/ProfileForm.tsx new file mode 100644 index 0000000..e05f743 --- /dev/null +++ b/apps/web/components/participant/ProfileForm.tsx @@ -0,0 +1,66 @@ +"use client"; + +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 { + name: string; + designation: string | null; + domain: string | null; + aboutMe: string | null; + selfDescription: string | null; + mostImpressiveBuild: string | null; + yearsOfExperience: number | null; + interests: string[]; + intent: string; + venueZone: string | null; + visible: boolean; +} + +const label = (intent: string) => intent.replaceAll("_", " ").toLowerCase(); + +/** 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 && ({ 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/components/ui/.gitkeep b/apps/web/components/ui/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/components/ui/SignOutButton.tsx b/apps/web/components/ui/SignOutButton.tsx new file mode 100644 index 0000000..ddf9d9b --- /dev/null +++ b/apps/web/components/ui/SignOutButton.tsx @@ -0,0 +1,8 @@ +import { signOutCurrentUser } from "@/app/actions/participant.actions"; + +/** Ends the session from any signed-in page; sits at the end of the page nav. */ +export default function SignOutButton() { + return
+ +
; +} diff --git a/apps/web/components/ui/form.tsx b/apps/web/components/ui/form.tsx new file mode 100644 index 0000000..15528f1 --- /dev/null +++ b/apps/web/components/ui/form.tsx @@ -0,0 +1,97 @@ +"use client"; + +import { useActionState, type ReactNode } from "react"; +import { useFormStatus } from "react-dom"; +import { initialFormState, type FormState } from "@/lib/form-state"; + +export type FormAction = (state: FormState, formData: FormData) => Promise; + +/** Disabled while its form is submitting, so a slow save cannot be sent twice. */ +export function SubmitButton({ children, pendingLabel, secondary }: { children: ReactNode; pendingLabel: string; secondary?: boolean }) { + const { pending } = useFormStatus(); + return ; +} + +/** Form-level error, announced to screen readers when it appears. */ +export function FormAlert({ state }: { state: FormState }) { + return state.error ?

{state.error}

: null; +} + +interface FieldProps { + label: string; + name: string; + state: FormState; + defaultValue?: string | number | null; + hint?: string; + required?: boolean; +} + +function fieldAria(name: string, state: FormState, hint?: string) { + const error = state.fieldErrors[name]; + const describedBy = [hint && `${name}-hint`, error && `${name}-error`].filter(Boolean).join(" ") || undefined; + return { error, props: { id: `field-${name}`, name, "aria-invalid": error ? true : undefined, "aria-describedby": describedBy } }; +} + +function FieldShell({ label, name, hint, error, required, children }: { label: string; name: string; hint?: string; error?: string; required?: boolean; children: ReactNode }) { + return
+ + {children} + {hint && {hint}} + {error && {error}} +
; +} + +/** Text input or textarea that keeps the submitted value after a rejected save. */ +export function TextField({ label, name, state, defaultValue, hint, required, multiline, rows, ...input }: FieldProps & { + multiline?: boolean; + rows?: number; + maxLength?: number; + type?: "text" | "number"; + min?: number; + max?: number; + placeholder?: string; + readOnly?: boolean; +}) { + const { error, props } = fieldAria(name, state, hint); + const value = state.values[name] ?? (defaultValue == null ? "" : String(defaultValue)); + return + {multiline + ?