From 21a4c69f383187446acdb92b78cc453e38fbf041 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 7 Oct 2026 12:00:38 -0300 Subject: [PATCH] feat(mp): add Mercado Pago reauthorization notice and status card components - Implemented MpReauthNotice component to notify users when reauthorization is needed. - Created MpStatusCard component to display the current status of the Mercado Pago account. - Added utility functions and constants for handling Mercado Pago status and messages. - Introduced hooks for managing the connection and disconnection of Mercado Pago accounts. - Developed a disconnect confirmation modal for user actions. - Added tests for the new functionality and utility functions. - Defined schemas for Mercado Pago account status and callback reasons in shared package. --- .env.example | 11 + AGENTS.md | 3 +- README.md | 52 + apps/backend/.env.example | 14 +- .../migration.sql | 56 + apps/backend/prisma/models/auth.prisma | 2 +- apps/backend/prisma/models/domain.prisma | 55 +- apps/backend/src/app.ts | 2 + apps/backend/src/http/problem-builders.ts | 42 +- .../groups/features/create/use-case.ts | 12 +- apps/backend/src/modules/mp/access-token.ts | 58 + .../src/modules/mp/features/callback/route.ts | 50 + .../modules/mp/features/callback/use-case.ts | 145 +++ .../src/modules/mp/features/connect/route.ts | 21 + .../modules/mp/features/connect/use-case.ts | 71 ++ .../modules/mp/features/disconnect/route.ts | 16 + .../mp/features/disconnect/use-case.ts | 39 + .../src/modules/mp/features/status/route.ts | 16 + .../modules/mp/features/status/use-case.ts | 52 + apps/backend/src/modules/mp/index.ts | 3 + apps/backend/src/modules/mp/jobs/index.ts | 7 + .../mp/jobs/refresh-expiring-mp-tokens.ts | 85 ++ .../src/modules/mp/jobs/refresh-mp-account.ts | 86 ++ apps/backend/src/modules/mp/jobs/schedule.ts | 33 + apps/backend/src/modules/mp/lib/config.ts | 51 + apps/backend/src/modules/mp/lib/crypto.ts | 79 ++ apps/backend/src/modules/mp/lib/index.ts | 21 + apps/backend/src/modules/mp/lib/mp-oauth.ts | 170 +++ apps/backend/src/modules/mp/lib/return-url.ts | 25 + apps/backend/src/modules/mp/routes.ts | 16 + .../features/first-group/use-case.ts | 12 +- .../features/payment-setup/route.ts | 20 - .../features/payment-setup/use-case.ts | 38 - .../onboarding/features/status/use-case.ts | 9 +- apps/backend/src/modules/onboarding/routes.ts | 2 - apps/backend/src/server.ts | 3 + apps/backend/test/groups.test.ts | 21 +- apps/backend/test/mp.test.ts | 1042 +++++++++++++++++ apps/backend/test/onboarding.test.ts | 83 +- apps/web/src/components/layout/RootLayout.tsx | 7 +- apps/web/src/features/mp/MpReauthNotice.tsx | 51 + apps/web/src/features/mp/MpStatusCard.tsx | 188 +++ apps/web/src/features/mp/copy.ts | 87 ++ apps/web/src/features/mp/index.ts | 16 + apps/web/src/features/mp/useDisconnectMp.ts | 30 + apps/web/src/features/mp/useMpStatus.ts | 19 + .../features/mp/useStartMpAuthorization.ts | 33 + .../features/onboarding/ConfirmationStep.tsx | 41 +- .../features/onboarding/FirstGroupStep.tsx | 2 +- .../onboarding/OnboardingProvider.tsx | 65 +- .../features/onboarding/OnboardingView.tsx | 34 +- .../src/features/onboarding/PaymentStep.tsx | 231 ++-- .../src/features/onboarding/WelcomeStep.tsx | 2 +- apps/web/src/features/onboarding/constants.ts | 22 +- .../src/features/settings/AppearanceCard.tsx | 2 +- .../src/features/settings/SettingsView.tsx | 5 +- apps/web/src/lib/api.ts | 25 +- apps/web/src/routes/onboarding.tsx | 9 +- apps/web/test/mp-copy.test.ts | 81 ++ docker-compose.yml | 10 + packages/shared/src/index.ts | 1 + packages/shared/src/schemas/enums.ts | 4 - packages/shared/src/schemas/mp.ts | 66 ++ packages/shared/src/schemas/onboarding.ts | 25 +- 64 files changed, 3154 insertions(+), 425 deletions(-) create mode 100644 apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql create mode 100644 apps/backend/src/modules/mp/access-token.ts create mode 100644 apps/backend/src/modules/mp/features/callback/route.ts create mode 100644 apps/backend/src/modules/mp/features/callback/use-case.ts create mode 100644 apps/backend/src/modules/mp/features/connect/route.ts create mode 100644 apps/backend/src/modules/mp/features/connect/use-case.ts create mode 100644 apps/backend/src/modules/mp/features/disconnect/route.ts create mode 100644 apps/backend/src/modules/mp/features/disconnect/use-case.ts create mode 100644 apps/backend/src/modules/mp/features/status/route.ts create mode 100644 apps/backend/src/modules/mp/features/status/use-case.ts create mode 100644 apps/backend/src/modules/mp/index.ts create mode 100644 apps/backend/src/modules/mp/jobs/index.ts create mode 100644 apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts create mode 100644 apps/backend/src/modules/mp/jobs/refresh-mp-account.ts create mode 100644 apps/backend/src/modules/mp/jobs/schedule.ts create mode 100644 apps/backend/src/modules/mp/lib/config.ts create mode 100644 apps/backend/src/modules/mp/lib/crypto.ts create mode 100644 apps/backend/src/modules/mp/lib/index.ts create mode 100644 apps/backend/src/modules/mp/lib/mp-oauth.ts create mode 100644 apps/backend/src/modules/mp/lib/return-url.ts create mode 100644 apps/backend/src/modules/mp/routes.ts delete mode 100644 apps/backend/src/modules/onboarding/features/payment-setup/route.ts delete mode 100644 apps/backend/src/modules/onboarding/features/payment-setup/use-case.ts create mode 100644 apps/backend/test/mp.test.ts create mode 100644 apps/web/src/features/mp/MpReauthNotice.tsx create mode 100644 apps/web/src/features/mp/MpStatusCard.tsx create mode 100644 apps/web/src/features/mp/copy.ts create mode 100644 apps/web/src/features/mp/index.ts create mode 100644 apps/web/src/features/mp/useDisconnectMp.ts create mode 100644 apps/web/src/features/mp/useMpStatus.ts create mode 100644 apps/web/src/features/mp/useStartMpAuthorization.ts create mode 100644 apps/web/test/mp-copy.test.ts create mode 100644 packages/shared/src/schemas/mp.ts diff --git a/.env.example b/.env.example index ac8239f..9ad1ad6 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,17 @@ BETTER_AUTH_SECRET="" # EMAIL_SERVER_PASSWORD="" # EMAIL_FROM="Gruperly " +# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales +# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando +# (el paso "Cobros" del onboarding es salteable). +# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded. +# TOKEN_ENCRYPTION_KEY="" +# Redirect URL registered in the Mercado Pago panel, character for character. +# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel. +# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback" +# MP_CLIENT_ID="" +# MP_CLIENT_SECRET="" + # Only if you want the API on another domain: it is baked into the Vite bundle # and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same # origin (recommended). diff --git a/AGENTS.md b/AGENTS.md index 6298e14..a807358 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,13 +31,14 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/logger.ts` — pino + pino-pretty. - - Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. + - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). ## Gotchas operativos +- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. diff --git a/README.md b/README.md index a808ab9..78427dd 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,56 @@ En DevTools → Application: el manifest sin warnings, el service worker `activa 1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`. 2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo). +## Mercado Pago (OAuth) + +Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). Los links de pago, webhooks y WhatsApp quedan fuera de este módulo. + +**Panel de Mercado Pago** (Developer panel → Tu aplicación): + +- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio. +- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador. +- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar. + +**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy): + +| Variable | ¿Obligatoria? | Descripción | +| --- | --- | --- | +| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP | +| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP | +| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel | +| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta | + +Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**. + +En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los pagos, cuando existan, se prueban aparte con credenciales de prueba. + +### Cómo funciona + +```text +onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min) + → https://auth.mercadopago.com/authorization + → GET /mp/callback → ?code&state (se quema el state, se cambia el código) + → 302 a /onboarding?mp=success o /settings?mp=error&reason=… +``` + +- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor). +- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta). +- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer. + +### Verificar a mano + +1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros". +2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos. +3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes. +4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`. +5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece. +6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción). + +```bash +# Estado real, con la sesión del profesor: +curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: ' | jq +``` + ## Deploy en producción (Docker / Dokploy) Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx). @@ -87,6 +137,8 @@ El compose las interpola desde el entorno. En Dokploy van en la pestaña **Envir | `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` | | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider | | `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) | +| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) | +| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo | | `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio | | `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones | diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 951c986..4f23b9f 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -18,4 +18,16 @@ EMAIL_SERVER_HOST="" EMAIL_SERVER_PORT="587" EMAIL_SERVER_USER="" EMAIL_SERVER_PASSWORD="" -EMAIL_FROM="Gruperly " \ No newline at end of file +EMAIL_FROM="Gruperly " + +# Mercado Pago (OAuth, Authorization Code + PKCE) +MP_CLIENT_ID="" +MP_CLIENT_SECRET="" +# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP. +# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel +# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá +# la URL del túnel acá y en el panel. +MP_REDIRECT_URI="" +# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM). +# Generar con: openssl rand -base64 32 +TOKEN_ENCRYPTION_KEY="" \ No newline at end of file diff --git a/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql new file mode 100644 index 0000000..dd94bf1 --- /dev/null +++ b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql @@ -0,0 +1,56 @@ +-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated +-- payment setup, where a fake access token was stored in plaintext. + +-- CreateEnum +CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED'); + +-- CreateTable +CREATE TABLE "mp_accounts" ( + "id" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "mp_user_id" TEXT NOT NULL, + "access_token_enc" TEXT NOT NULL, + "refresh_token_enc" TEXT NOT NULL, + "expires_at" TIMESTAMP(3) NOT NULL, + "scope" TEXT, + "live_mode" BOOLEAN NOT NULL DEFAULT false, + "status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE', + "connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "mp_oauth_states" ( + "state" TEXT NOT NULL, + "owner_id" TEXT NOT NULL, + "code_verifier" TEXT NOT NULL, + "return_to" TEXT NOT NULL, + "expires_at" TIMESTAMP(3) NOT NULL, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state") +); + +-- CreateIndex +CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id"); + +-- CreateIndex +CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id"); + +-- CreateIndex +CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at"); + +-- AddForeignKey +ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- DropTable +DROP TABLE "merchant_accounts"; + +-- DropEnum +DROP TYPE "PaymentProvider"; diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma index 4e35bd7..ea6e4ee 100644 --- a/apps/backend/prisma/models/auth.prisma +++ b/apps/backend/prisma/models/auth.prisma @@ -18,7 +18,7 @@ model User { orgMemberships Member[] orgInvitations Invitation[] @relation("InvitedBy") waitlist WaitlistEntry[] - merchantAccount MerchantAccount? + mpAccount MpAccount? @@map("users") } diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index 14636c7..77b122b 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -182,22 +182,49 @@ model GroupPreRegistration { @@map("group_pre_registrations") } -enum PaymentProvider { - MERCADO_PAGO - STRIPE +enum MpAccountStatus { + ACTIVE + REQUIRES_REAUTH + REVOKED } -model MerchantAccount { - id String @id @default(cuid()) - userId String @unique(map: "merchant_accounts_userId_key") @map("user_id") - provider PaymentProvider - accessToken String? @map("access_token") - sandbox Boolean @default(true) - connectedAt DateTime @default(now()) @map("connected_at") - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @updatedAt @map("updated_at") +// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE). +// Tokens are stored encrypted (AES-256-GCM); there is a single active account per +// teacher and a Mercado Pago user cannot be linked to two teachers. +model MpAccount { + id String @id @default(cuid()) + ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id") + mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id") + accessTokenEnc String @map("access_token_enc") + refreshTokenEnc String @map("refresh_token_enc") + expiresAt DateTime @map("expires_at") + scope String? + liveMode Boolean @default(false) @map("live_mode") + status MpAccountStatus @default(ACTIVE) + connectedAt DateTime @default(now()) @map("connected_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") - user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "merchant_accounts_userId_fkey") + owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey") - @@map("merchant_accounts") + // The daily refresh job looks for ACTIVE accounts expiring within 30 days. + @@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx") + @@map("mp_accounts") +} + +// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE +// `code_verifier`. The `state` is the primary key because consuming it (deleting +// the row) is what makes it single use. +model MpOAuthState { + state String @id + ownerId String @map("owner_id") + codeVerifier String @map("code_verifier") + // Constrained to 'onboarding' | 'settings'; decides where the callback lands. + returnTo String @map("return_to") + expiresAt DateTime @map("expires_at") + createdAt DateTime @default(now()) @map("created_at") + + // Expired rows are swept on every new authorization request. + @@index([expiresAt], map: "mp_oauth_states_expiresAt_idx") + @@map("mp_oauth_states") } diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index e6e1e6d..2d6bc7e 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -21,6 +21,7 @@ import { groupsRoutes } from './modules/groups'; import { healthCheckRoutes } from './modules/health-check'; import { homeRoutes } from './modules/home'; import { invitationsRoutes } from './modules/invitations'; +import { mpRoutes } from './modules/mp'; import { onboardingRoutes } from './modules/onboarding'; import { paymentsRoutes } from './modules/payments'; import { waitlistRoutes } from './modules/waitlist'; @@ -44,6 +45,7 @@ api.route('/invitations', invitationsRoutes); api.route('/groups', groupsRoutes); api.route('/home', homeRoutes); api.route('/onboarding', onboardingRoutes); +api.route('/mp', mpRoutes); api.route('/attendees', attendeesRoutes); api.route('/payments', paymentsRoutes); api.route('/waitlist', waitlistRoutes); diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts index b94f2c0..6a0e57a 100644 --- a/apps/backend/src/http/problem-builders.ts +++ b/apps/backend/src/http/problem-builders.ts @@ -71,13 +71,49 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl return notFoundProblem(`${resourceName} ${id}`); } -export function paymentNotSetupProblem(): ProblemDetails { +export function mpNotConnectedProblem(): ProblemDetails { return conflictProblem({ - detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.', - code: 'payment_not_setup', + detail: 'No tenés una cuenta de Mercado Pago vinculada.', + code: 'mp_not_connected', }); } +export function mpRequiresReauthProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.', + code: 'mp_requires_reauth', + }); +} + +export function mpAccountInUseProblem(): ProblemDetails { + return conflictProblem({ + detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.', + code: 'mp_account_in_use', + }); +} + +/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */ +export function mpNotConfiguredProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`, + title: 'Service Unavailable', + status: 503, + detail: 'La vinculación con Mercado Pago no está disponible en este momento.', + code: 'mp_not_configured', + }; +} + +/** Mercado Pago refused the request, or could not be reached. */ +export function mpProviderErrorProblem(): ProblemDetails { + return { + type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`, + title: 'Bad Gateway', + status: 502, + detail: 'No pudimos completar la vinculación con Mercado Pago.', + code: 'mp_provider_error', + }; +} + export function onboardingAlreadyCompletedProblem(): ProblemDetails { return conflictProblem({ detail: 'Ya completaste el onboarding de Gruperly.', diff --git a/apps/backend/src/modules/groups/features/create/use-case.ts b/apps/backend/src/modules/groups/features/create/use-case.ts index d731a85..e423644 100644 --- a/apps/backend/src/modules/groups/features/create/use-case.ts +++ b/apps/backend/src/modules/groups/features/create/use-case.ts @@ -1,4 +1,4 @@ -import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { Prisma } from '@generated/prisma/client'; import { Role } from '@generated/prisma/client'; import type { CreateFirstGroup as CreateGroupInput, @@ -6,13 +6,11 @@ import type { ProblemDetails, Result, } from '@gruperly/shared'; -import { err, ok } from '@gruperly/shared'; -import { paymentNotSetupProblem } from '@/http/problem-builders'; +import { ok } from '@gruperly/shared'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { type GroupRecord, toGroupDto } from '../../lib'; type CreateGroupDeps = { - db?: Pick; unitOfWork?: UnitOfWork; }; @@ -23,14 +21,8 @@ export class CreateGroup { data: CreateGroupInput, userId: string, ): Promise> { - const db = this.deps.db ?? prisma; const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); - const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } }); - if (!merchantAccount) { - return err(paymentNotSetupProblem()); - } - const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { const created = await tx.group.create({ diff --git a/apps/backend/src/modules/mp/access-token.ts b/apps/backend/src/modules/mp/access-token.ts new file mode 100644 index 0000000..4a50ac3 --- /dev/null +++ b/apps/backend/src/modules/mp/access-token.ts @@ -0,0 +1,58 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpNotConnectedProblem, mpRequiresReauthProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { RefreshMpAccount } from './jobs'; +import { openToken } from './lib'; + +export type MpTokenAccount = { + accountId: string; + accessToken: string; + expiresAt: Date; +}; + +/** + * Below this, the on-demand path refreshes. The daily job renews much earlier + * (30 days out), so hitting this only means the job did not run, which is exactly + * when a payment link cannot be allowed to fail. + */ +const NEAR_EXPIRY_MS = 5 * 60 * 1000; + +type GetMpAccessTokenDeps = { + db?: Pick; + refresh?: RefreshMpAccount; +}; + +/** + * A usable access token for a teacher's Mercado Pago account. + * + * This is the entry point for payment links and webhook verification, so it fails + * explicitly instead of returning something unusable: an unlinked account and an + * account that needs re-authorization are different problems and the caller has + * to be able to tell them apart. + */ +export async function getMpAccessToken( + ownerId: string, + deps: GetMpAccessTokenDeps = {}, +): Promise> { + const db = deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) return err(mpNotConnectedProblem()); + if (account.status !== 'ACTIVE') return err(mpRequiresReauthProblem()); + + if (account.expiresAt.getTime() - Date.now() > NEAR_EXPIRY_MS) { + return ok({ + accountId: account.id, + accessToken: openToken(account.accessTokenEnc), + expiresAt: account.expiresAt, + }); + } + + const refresh = deps.refresh ?? new RefreshMpAccount(); + const refreshed = await refresh.execute(account.id); + if (!refreshed.ok) return refreshed; + + return ok(refreshed.value); +} diff --git a/apps/backend/src/modules/mp/features/callback/route.ts b/apps/backend/src/modules/mp/features/callback/route.ts new file mode 100644 index 0000000..2ac60bd --- /dev/null +++ b/apps/backend/src/modules/mp/features/callback/route.ts @@ -0,0 +1,50 @@ +import type { MpCallbackQuery, MpCallbackReason, ProblemDetails } from '@gruperly/shared'; +import { MpCallbackQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { validate } from '@/http/validate'; +import { logger } from '@/logger'; +import { buildMpReturnUrl, getWebOrigin } from '../../lib'; +import { CompleteMpAuthorization, type MpCallbackResult } from './use-case'; + +/** + * The browser arrives here from Mercado Pago, so this route always answers with + * a redirect back to the app and never renders or returns a problem body: there + * is nothing on the other side to render a failure into. + */ +const route = new Hono(); + +route.get('/', validate.query(MpCallbackQuerySchema), async (c) => { + const { code, state, error } = c.req.valid('query') as MpCallbackQuery; + + const user = c.get('user'); + if (!user) { + // Without a session there is nobody to credit the tokens to. The state was + // issued to whoever was signed in when the flow started, so guessing would + // be a way to attach somebody else's Mercado Pago account to this account. + logger.warn('Mercado Pago callback arrived without a session'); + return c.redirect(new URL('/login', getWebOrigin()).toString()); + } + + const useCase = new CompleteMpAuthorization(); + const result = await useCase.execute({ code, state, error }); + + if (!result.ok) { + logger.warn( + { code: result.error.code, status: result.error.status }, + 'Mercado Pago callback failed', + ); + } + + const outcome = result.ok ? result.value.outcome : problemToOutcome(result.error); + const returnTo = result.ok ? result.value.returnTo : 'settings'; + + return c.redirect(buildMpReturnUrl(getWebOrigin(), returnTo, outcome)); +}); + +/** Reduces an internal problem to a reason code that is safe in a URL. */ +function problemToOutcome(problem: ProblemDetails): MpCallbackResult['outcome'] { + const reason: MpCallbackReason = problem.code === 'mp_account_in_use' ? 'mp_account_in_use' : 'mp_error'; + return { kind: 'error', reason }; +} + +export default route; diff --git a/apps/backend/src/modules/mp/features/callback/use-case.ts b/apps/backend/src/modules/mp/features/callback/use-case.ts new file mode 100644 index 0000000..6114478 --- /dev/null +++ b/apps/backend/src/modules/mp/features/callback/use-case.ts @@ -0,0 +1,145 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { + mpAccountInUseProblem, + mpNotConfiguredProblem, + mpProviderErrorProblem, +} from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + exchangeAuthorizationCode, + getMpOAuthConfig, + type MpTokenResponse, + sealToken, +} from '../../lib'; + +type CompleteMpAuthorizationDeps = { + db?: Pick; + /** Swapped in tests; defaults to the real Mercado Pago exchange. */ + exchange?: typeof exchangeAuthorizationCode; +}; + +export type MpCallbackResult = { + returnTo: MpReturnTo; + outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason }; +}; + +/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */ +const UNIQUE_VIOLATION = 'P2002'; + +/** Where we land if the state is gone and there is nothing to recover. */ +const DEFAULT_RETURN_TO: MpReturnTo = 'settings'; + +export class CompleteMpAuthorization { + constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {} + + async execute(input: { + code?: string; + state?: string; + error?: string; + }): Promise> { + let config: ReturnType; + try { + config = getMpOAuthConfig(); + } catch (configError) { + logger.error({ err: configError }, 'Mercado Pago is not configured'); + return err(mpNotConfiguredProblem()); + } + + const db = this.deps.db ?? prisma; + + // The teacher closed the consent screen. There is nothing to exchange, but + // the state is still burned so it cannot be replayed later. + if (input.error) { + if (input.state) { + await db.mpOAuthState.deleteMany({ where: { state: input.state } }); + } + return failure('mp_denied'); + } + + if (!input.code || !input.state) { + return failure('invalid_state'); + } + + const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } }); + if (!stored || stored.expiresAt.getTime() <= Date.now()) { + return failure('invalid_state'); + } + + const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO; + + // Single use, and burned *before* we talk to Mercado Pago: a `count` of zero + // means someone replayed a state we already consumed. + const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } }); + if (consumed.count === 0) { + return failure('invalid_state', returnTo); + } + + const exchange = this.deps.exchange ?? exchangeAuthorizationCode; + let tokens: MpTokenResponse; + try { + tokens = await exchange({ + clientId: config.clientId, + clientSecret: config.clientSecret, + redirectUri: config.redirectUri, + code: input.code, + codeVerifier: stored.codeVerifier, + }); + } catch (exchangeError) { + // `MpApiError` already logged the status and MP's own error code. Nothing + // added here mentions the authorization code or the verifier. + logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed'); + return err(mpProviderErrorProblem()); + } + + const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } }); + if (claimed && claimed.ownerId !== stored.ownerId) { + return err(mpAccountInUseProblem()); + } + + const encrypted = { + accessTokenEnc: sealToken(tokens.accessToken), + refreshTokenEnc: sealToken(tokens.refreshToken), + expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000), + scope: tokens.scope, + liveMode: tokens.liveMode, + status: 'ACTIVE' as const, + }; + + try { + await db.mpAccount.upsert({ + where: { ownerId: stored.ownerId }, + create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted }, + // Re-linking renews the credentials and clears a `requires_reauth`. + update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() }, + }); + } catch (writeError) { + // Two teachers linked the same Mercado Pago id at the same time: the + // unique index is the real arbiter, not the read above. + if (isUniqueViolation(writeError)) { + return err(mpAccountInUseProblem()); + } + throw writeError; + } + + return ok({ returnTo, outcome: { kind: 'success' } }); + } +} + +function failure( + reason: MpCallbackReason, + returnTo: MpReturnTo = DEFAULT_RETURN_TO, +): Result { + return ok({ returnTo, outcome: { kind: 'error', reason } }); +} + +function isUniqueViolation(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { code?: unknown }).code === UNIQUE_VIOLATION + ); +} diff --git a/apps/backend/src/modules/mp/features/connect/route.ts b/apps/backend/src/modules/mp/features/connect/route.ts new file mode 100644 index 0000000..e60cd5a --- /dev/null +++ b/apps/backend/src/modules/mp/features/connect/route.ts @@ -0,0 +1,21 @@ +import type { MpConnectQuery, MpReturnTo } from '@gruperly/shared'; +import { MpConnectQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { StartMpAuthorization } from './use-case'; + +const route = new Hono(); + +route.get('/', validate.query(MpConnectQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const { returnTo } = c.req.valid('query') as MpConnectQuery; + + const useCase = new StartMpAuthorization(); + const result = await useCase.execute(user.id, returnTo as MpReturnTo); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/connect/use-case.ts b/apps/backend/src/modules/mp/features/connect/use-case.ts new file mode 100644 index 0000000..7c7c485 --- /dev/null +++ b/apps/backend/src/modules/mp/features/connect/use-case.ts @@ -0,0 +1,71 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + MpAuthorizationUrlDto, + MpReturnTo, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpNotConfiguredProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import { + buildAuthorizationUrl, + codeChallengeFromVerifier, + getMpOAuthConfig, + newCodeVerifier, + newState, +} from '../../lib'; + +type StartMpAuthorizationDeps = { db?: Pick }; + +/** The teacher has ten minutes to finish at Mercado Pago before the state dies. */ +export const STATE_TTL_MS = 10 * 60 * 1000; + +export class StartMpAuthorization { + constructor(private readonly deps: StartMpAuthorizationDeps = {}) {} + + async execute( + ownerId: string, + returnTo: MpReturnTo, + ): Promise> { + let config: ReturnType; + try { + config = getMpOAuthConfig(); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago is not configured'); + return err(mpNotConfiguredProblem()); + } + + const db = this.deps.db ?? prisma; + const now = new Date(); + + // Two jobs in one sweep: drop anything expired, and drop this teacher's + // previous attempt so a teacher clicking twice cannot leave rows behind. + await db.mpOAuthState.deleteMany({ + where: { OR: [{ expiresAt: { lt: now } }, { ownerId }] }, + }); + + const state = newState(); + const codeVerifier = newCodeVerifier(); + + await db.mpOAuthState.create({ + data: { + state, + ownerId, + codeVerifier, + returnTo, + expiresAt: new Date(now.getTime() + STATE_TTL_MS), + }, + }); + + return ok({ + authorizationUrl: buildAuthorizationUrl({ + clientId: config.clientId, + redirectUri: config.redirectUri, + state, + codeChallenge: codeChallengeFromVerifier(codeVerifier), + }), + }); + } +} diff --git a/apps/backend/src/modules/mp/features/disconnect/route.ts b/apps/backend/src/modules/mp/features/disconnect/route.ts new file mode 100644 index 0000000..3f481f2 --- /dev/null +++ b/apps/backend/src/modules/mp/features/disconnect/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { DisconnectMp } from './use-case'; + +const route = new Hono(); + +route.delete('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new DisconnectMp(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/disconnect/use-case.ts b/apps/backend/src/modules/mp/features/disconnect/use-case.ts new file mode 100644 index 0000000..5bd5fba --- /dev/null +++ b/apps/backend/src/modules/mp/features/disconnect/use-case.ts @@ -0,0 +1,39 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpDisconnectResultDto, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; + +type DisconnectMpDeps = { db?: Pick }; + +/** + * Mercado Pago has no seller-side token revocation endpoint for these grants, so + * the tokens are dropped here and the row is kept as `REVOKED`. It is not + * deleted on purpose: the Mercado Pago id stays reserved for the same teacher, + * which stops someone else from claiming their account later. + */ +export class DisconnectMp { + constructor(private readonly deps: DisconnectMpDeps = {}) {} + + async execute(ownerId: string): Promise> { + const db = this.deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) { + return ok({ disconnected: false }); + } + + await db.mpAccount.update({ + where: { ownerId }, + data: { + status: 'REVOKED', + // The columns are NOT NULL, so the values are blanked rather than nulled. + // Nothing reads them: every consumer filters on `status` first. + accessTokenEnc: '', + refreshTokenEnc: '', + expiresAt: new Date(0), + }, + }); + + return ok({ disconnected: true }); + } +} diff --git a/apps/backend/src/modules/mp/features/status/route.ts b/apps/backend/src/modules/mp/features/status/route.ts new file mode 100644 index 0000000..0461dda --- /dev/null +++ b/apps/backend/src/modules/mp/features/status/route.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetMpStatus } from './use-case'; + +const route = new Hono(); + +route.get('/', async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new GetMpStatus(); + const result = await useCase.execute(user.id); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/mp/features/status/use-case.ts b/apps/backend/src/modules/mp/features/status/use-case.ts new file mode 100644 index 0000000..a635053 --- /dev/null +++ b/apps/backend/src/modules/mp/features/status/use-case.ts @@ -0,0 +1,52 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { MpAccountStatus, MpStatusDto, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; + +type GetMpStatusDeps = { db?: Pick }; + +/** How many trailing digits of the Mercado Pago id we show, to confirm the account. */ +const SUFFIX_LENGTH = 4; + +const NOT_LINKED: MpStatusDto = { + status: 'none', + liveMode: false, + expiresAt: null, + connectedAt: null, + mpUserIdSuffix: null, +}; + +/** + * An account the teacher unlinked stays in the table (so the Mercado Pago id + * stays reserved for them), but from the outside it is simply "not linked". + */ +function toVisibleStatus(status: 'ACTIVE' | 'REQUIRES_REAUTH' | 'REVOKED'): MpAccountStatus { + switch (status) { + case 'ACTIVE': + return 'active'; + case 'REQUIRES_REAUTH': + return 'requires_reauth'; + case 'REVOKED': + return 'none'; + } +} + +export class GetMpStatus { + constructor(private readonly deps: GetMpStatusDeps = {}) {} + + async execute(ownerId: string): Promise> { + const db = this.deps.db ?? prisma; + + const account = await db.mpAccount.findUnique({ where: { ownerId } }); + if (!account) return ok(NOT_LINKED); + + // Deliberately no tokens and no scope in the response. + return ok({ + status: toVisibleStatus(account.status), + liveMode: account.liveMode, + expiresAt: account.expiresAt.toISOString(), + connectedAt: account.connectedAt.toISOString(), + mpUserIdSuffix: account.mpUserId.slice(-SUFFIX_LENGTH), + }); + } +} diff --git a/apps/backend/src/modules/mp/index.ts b/apps/backend/src/modules/mp/index.ts new file mode 100644 index 0000000..5bc3d3a --- /dev/null +++ b/apps/backend/src/modules/mp/index.ts @@ -0,0 +1,3 @@ +export { getMpAccessToken, type MpTokenAccount } from './access-token'; +export { startMpJobs } from './jobs'; +export { default as mpRoutes } from './routes'; diff --git a/apps/backend/src/modules/mp/jobs/index.ts b/apps/backend/src/modules/mp/jobs/index.ts new file mode 100644 index 0000000..e653d80 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/index.ts @@ -0,0 +1,7 @@ +export { + RENEWAL_WINDOW_DAYS, + RefreshExpiringMpTokens, + type RefreshExpiringMpTokensResult, +} from './refresh-expiring-mp-tokens'; +export { type MpAccountStore, RefreshMpAccount } from './refresh-mp-account'; +export { startMpJobs } from './schedule'; diff --git a/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts b/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts new file mode 100644 index 0000000..dbc38f7 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/refresh-expiring-mp-tokens.ts @@ -0,0 +1,85 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import prisma from '@/lib/prisma'; +import { refreshMpTokens } from '../lib'; +import { RefreshMpAccount } from './refresh-mp-account'; + +/** + * Mercado Pago hands out access tokens valid for about six months. Renewing at + * 30 days leaves room for the job to fail a few times before a token is at risk. + */ +const RENEWAL_WINDOW_DAYS = 30; +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * Keeps a bounded batch: the query below holds row locks for the life of the + * transaction, which means it holds them across the calls to Mercado Pago. + */ +const BATCH_LIMIT = 20; +const TRANSACTION_TIMEOUT_MS = 120_000; + +export type RefreshExpiringMpTokensResult = { + refreshed: number; + requiresReauth: number; + failed: number; +}; + +type RefreshExpiringMpTokensDeps = { + db?: PrismaClient; + /** Swapped in tests; defaults to the real Mercado Pago renewal. */ + refresh?: typeof refreshMpTokens; +}; + +type LockedAccountRow = { id: string }; + +export class RefreshExpiringMpTokens { + constructor(private readonly deps: RefreshExpiringMpTokensDeps = {}) {} + + async execute(): Promise { + const db = this.deps.db ?? prisma; + const now = new Date(); + const totals: RefreshExpiringMpTokensResult = { refreshed: 0, requiresReauth: 0, failed: 0 }; + + await db.$transaction( + async (tx) => { + const horizon = new Date(now.getTime() + RENEWAL_WINDOW_DAYS * DAY_MS); + + // FOR UPDATE SKIP LOCKED: two instances of the API never renew the same + // account, and a row already claimed by another instance is skipped + // instead of blocking the batch. The trade-off is that the lock stays + // held across the HTTP calls below; if MP's latency ever became a + // problem, this becomes an atomic `updateMany` claim on a + // `refresh_claimed_at` column and the rows are released immediately. + const rows = await tx.$queryRaw` + SELECT "id" + FROM "mp_accounts" + WHERE "status" = 'ACTIVE' AND "expires_at" < ${horizon} + ORDER BY "expires_at" ASC + LIMIT ${BATCH_LIMIT} + FOR UPDATE SKIP LOCKED + `; + + for (const row of rows) { + // Built per row with the transaction client, so the writes join the + // transaction holding the lock. With the shared client the lock would + // protect nothing. + const result = await new RefreshMpAccount({ db: tx, refresh: this.deps.refresh }).execute( + row.id, + ); + + if (result.ok) { + totals.refreshed += 1; + } else if (result.error.code === 'mp_requires_reauth') { + totals.requiresReauth += 1; + } else { + totals.failed += 1; + } + } + }, + { timeout: TRANSACTION_TIMEOUT_MS }, + ); + + return totals; + } +} + +export { RENEWAL_WINDOW_DAYS }; diff --git a/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts b/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts new file mode 100644 index 0000000..9ca9b06 --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/refresh-mp-account.ts @@ -0,0 +1,86 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { mpProviderErrorProblem, mpRequiresReauthProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { logger } from '@/logger'; +import type { MpTokenAccount } from '../access-token'; +import { + getMpOAuthConfig, + isGrantRejected, + type MpTokenResponse, + openToken, + refreshMpTokens, + sealToken, +} from '../lib'; + +/** Either the client or a transaction client: the job runs this inside a transaction. */ +export type MpAccountStore = { mpAccount: PrismaClient['mpAccount'] }; + +export type RefreshMpAccountDeps = { + db?: MpAccountStore; + refresh?: typeof refreshMpTokens; +}; + +/** + * Renews one account's access token. + * + * Shared by the daily job and by the on-demand path in `getMpAccessToken`. + * + * Mercado Pago rotates the refresh token on every renewal, so the new one is + * always stored: keeping the old one would make the next renewal fail. + * + * Only `invalid_grant` marks the account as `REQUIRES_REAUTH`. A 5xx or a network + * failure means no decision was taken about the grant, and locking a teacher out + * over a bad afternoon at Mercado Pago would be worse than retrying tomorrow. + */ +export class RefreshMpAccount { + constructor(private readonly deps: RefreshMpAccountDeps = {}) {} + + async execute(accountId: string): Promise> { + const db = this.deps.db ?? prisma; + const refresh = this.deps.refresh ?? refreshMpTokens; + + const account = await db.mpAccount.findUnique({ where: { id: accountId } }); + if (!account) { + logger.warn({ accountId }, 'Mercado Pago account vanished mid-renewal'); + return err(mpRequiresReauthProblem()); + } + + let tokens: MpTokenResponse; + try { + const config = getMpOAuthConfig(); + tokens = await refresh({ + ...config, + refreshToken: openToken(account.refreshTokenEnc), + }); + } catch (error) { + if (isGrantRejected(error)) { + logger.warn({ accountId }, 'Mercado Pago refresh token is no longer valid'); + await db.mpAccount.update({ + where: { id: accountId }, + data: { status: 'REQUIRES_REAUTH' }, + }); + return err(mpRequiresReauthProblem()); + } + + logger.error({ accountId, err: error }, 'Mercado Pago token renewal failed'); + return err(mpProviderErrorProblem()); + } + + const expiresAt = new Date(Date.now() + tokens.expiresInSeconds * 1000); + + await db.mpAccount.update({ + where: { id: accountId }, + data: { + accessTokenEnc: sealToken(tokens.accessToken), + refreshTokenEnc: sealToken(tokens.refreshToken), + expiresAt, + scope: tokens.scope ?? account.scope, + status: 'ACTIVE', + }, + }); + + return ok({ accountId, accessToken: tokens.accessToken, expiresAt }); + } +} diff --git a/apps/backend/src/modules/mp/jobs/schedule.ts b/apps/backend/src/modules/mp/jobs/schedule.ts new file mode 100644 index 0000000..b3b490a --- /dev/null +++ b/apps/backend/src/modules/mp/jobs/schedule.ts @@ -0,0 +1,33 @@ +import { logger } from '@/logger'; +import { RefreshExpiringMpTokens } from './refresh-expiring-mp-tokens'; + +/** + * 03:17 UTC. Not on the hour: every instance of the API fires this job at the + * same time, and the lock is only there to make the overlap harmless. + */ +const REFRESH_CRON = '17 3 * * *'; + +/** + * Registers the background jobs. Called once from `server.ts`. + * + * Two things are not obvious here: + * + * - `try/catch` is mandatory. Bun's in-process cron follows `setTimeout` error + * semantics: a rejected promise becomes an `unhandledRejection`, and without a + * listener the process exits with code 1. + * - `unref()` so the job does not keep the process alive on its own. + */ +export function startMpJobs(): void { + Bun.cron( + REFRESH_CRON, + async () => { + try { + const totals = await new RefreshExpiringMpTokens().execute(); + logger.info(totals, 'Mercado Pago token renewal finished'); + } catch (error) { + logger.error({ err: error }, 'Mercado Pago token renewal failed'); + } + }, + { tz: 'UTC' }, + ).unref(); +} diff --git a/apps/backend/src/modules/mp/lib/config.ts b/apps/backend/src/modules/mp/lib/config.ts new file mode 100644 index 0000000..fb39260 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/config.ts @@ -0,0 +1,51 @@ +export type MpOAuthConfig = { + clientId: string; + clientSecret: string; + /** Registered as the app's "Redirect URL". Mercado Pago matches it exactly. */ + redirectUri: string; + /** Frontend origin, used to land the teacher back in the app after the callback. */ + webUrl: string; +}; + +const DEFAULT_WEB_URL = 'http://localhost:6173'; + +export function getWebOrigin(): string { + return process.env.WEB_URL?.trim() || DEFAULT_WEB_URL; +} + +/** + * Reads the Mercado Pago credentials from the environment. + * + * Throws instead of returning a `Result`: these are deployment mistakes, not + * something the teacher did wrong, so they surface as a 500 with a named + * variable in the logs rather than as a problem the UI has to explain. The + * names of the missing variables are safe to log; their values never are. + */ +export function getMpOAuthConfig(): MpOAuthConfig { + const missing: string[] = []; + const read = (name: string): string => { + const value = process.env[name]?.trim(); + if (!value) { + missing.push(name); + return ''; + } + return value; + }; + + const clientId = read('MP_CLIENT_ID'); + const clientSecret = read('MP_CLIENT_SECRET'); + const redirectUri = read('MP_REDIRECT_URI'); + + if (missing.length > 0) { + throw new Error( + `Missing Mercado Pago environment variables: ${missing.join(', ')}. See .env.example.`, + ); + } + + return { + clientId, + clientSecret, + redirectUri, + webUrl: getWebOrigin(), + }; +} diff --git a/apps/backend/src/modules/mp/lib/crypto.ts b/apps/backend/src/modules/mp/lib/crypto.ts new file mode 100644 index 0000000..83289f7 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/crypto.ts @@ -0,0 +1,79 @@ +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'; +import { nanoid } from 'nanoid'; + +/** + * Tokens are encrypted at rest with AES-256-GCM. The payload carries a version + * prefix so the scheme can be rotated later without a data migration: an unknown + * version fails loudly instead of being decrypted with the wrong assumptions. + * + * Layout: `v1:::`, each part base64url. GCM authenticates + * the ciphertext, so a tampered payload throws on `openToken` rather than + * yielding garbage that would later be sent to Mercado Pago as a token. + */ +const PAYLOAD_VERSION = 'v1'; +const KEY_BYTES = 32; +const IV_BYTES = 12; + +function getKey(): Buffer { + const raw = process.env.TOKEN_ENCRYPTION_KEY; + if (!raw) { + throw new Error('TOKEN_ENCRYPTION_KEY environment variable is required'); + } + + const key = Buffer.from(raw, 'base64'); + if (key.length !== KEY_BYTES) { + // Length only, never the value. + throw new Error( + `TOKEN_ENCRYPTION_KEY must decode to ${KEY_BYTES} bytes in base64, got ${key.length}`, + ); + } + + return key; +} + +export function sealToken(plaintext: string): string { + const iv = randomBytes(IV_BYTES); + const cipher = createCipheriv('aes-256-gcm', getKey(), iv); + const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); + + return [ + PAYLOAD_VERSION, + iv.toString('base64url'), + cipher.getAuthTag().toString('base64url'), + ciphertext.toString('base64url'), + ].join(':'); +} + +export function openToken(payload: string): string { + const [version, ivPart, tagPart, ciphertextPart] = payload.split(':'); + + if (version !== PAYLOAD_VERSION || !ivPart || !tagPart || ciphertextPart === undefined) { + throw new Error('Unsupported token payload'); + } + + const decipher = createDecipheriv('aes-256-gcm', getKey(), Buffer.from(ivPart, 'base64url')); + decipher.setAuthTag(Buffer.from(tagPart, 'base64url')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertextPart, 'base64url')), + decipher.final(), + ]).toString('utf8'); +} + +/** CSRF token echoed back by Mercado Pago. 32 chars of entropy. */ +export function newState(): string { + return nanoid(32); +} + +/** + * PKCE verifier. Mercado Pago requires 43 to 128 characters, so 32 random bytes + * in base64url (43 chars) is the smallest value that fits. + */ +export function newCodeVerifier(): string { + return randomBytes(32).toString('base64url'); +} + +/** PKCE S256 challenge: base64url(SHA256(verifier)) — RFC 7636 section 4.2. */ +export function codeChallengeFromVerifier(codeVerifier: string): string { + return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url'); +} diff --git a/apps/backend/src/modules/mp/lib/index.ts b/apps/backend/src/modules/mp/lib/index.ts new file mode 100644 index 0000000..7c4d73b --- /dev/null +++ b/apps/backend/src/modules/mp/lib/index.ts @@ -0,0 +1,21 @@ +export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config'; +export { + codeChallengeFromVerifier, + newCodeVerifier, + newState, + openToken, + sealToken, +} from './crypto'; +export { + buildAuthorizationUrl, + exchangeAuthorizationCode, + isGrantRejected, + MP_AUTHORIZE_URL, + MP_SCOPES, + MP_TOKEN_URL, + MpApiError, + type MpAuthorizationUrlInput, + type MpTokenResponse, + refreshMpTokens, +} from './mp-oauth'; +export { buildMpReturnUrl, type MpCallbackOutcome } from './return-url'; diff --git a/apps/backend/src/modules/mp/lib/mp-oauth.ts b/apps/backend/src/modules/mp/lib/mp-oauth.ts new file mode 100644 index 0000000..8ebb495 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/mp-oauth.ts @@ -0,0 +1,170 @@ +import { logger } from '@/logger'; + +export const MP_AUTHORIZE_URL = 'https://auth.mercadopago.com/authorization'; +export const MP_TOKEN_URL = 'https://api.mercadopago.com/oauth/token'; + +/** + * `offline_access` is what makes Mercado Pago return a refresh token. Without + * it the daily renewal job has nothing to work with. + */ +export const MP_SCOPES = 'offline_access read write'; + +export type MpTokenResponse = { + accessToken: string; + refreshToken: string; + expiresInSeconds: number; + scope: string | null; + mpUserId: string; + liveMode: boolean; +}; + +export type MpAuthorizationUrlInput = { + clientId: string; + redirectUri: string; + state: string; + codeChallenge: string; +}; + +/** + * A failure from Mercado Pago's token endpoint. + * + * `reason` is the safe subset of what MP returned. `error_description` is + * deliberately dropped: it echoes back request content, and the request is the + * authorization code. + */ +export class MpApiError extends Error { + constructor( + readonly status: number, + readonly reason: string | null, + ) { + super(`Mercado Pago token request failed with status ${status}`); + this.name = 'MpApiError'; + } +} + +/** Permanent rejection of the grant: the refresh token is dead. */ +export function isGrantRejected(error: unknown): boolean { + return error instanceof MpApiError && error.reason === 'invalid_grant'; +} + +export function buildAuthorizationUrl({ + clientId, + redirectUri, + state, + codeChallenge, +}: MpAuthorizationUrlInput): string { + const url = new URL(MP_AUTHORIZE_URL); + url.searchParams.set('client_id', clientId); + url.searchParams.set('response_type', 'code'); + // Declares this as a direct (non-marketplace) integration: the money lands in + // the seller's own account, so no platform_id of ours and no fee split. + url.searchParams.set('platform_id', 'mp'); + url.searchParams.set('redirect_uri', redirectUri); + url.searchParams.set('state', state); + url.searchParams.set('code_challenge', codeChallenge); + url.searchParams.set('code_challenge_method', 'S256'); + url.searchParams.set('scope', MP_SCOPES); + return url.toString(); +} + +type TokenRequestInput = { + clientId: string; + clientSecret: string; + redirectUri: string; +}; + +export function exchangeAuthorizationCode( + input: TokenRequestInput & { code: string; codeVerifier: string }, +): Promise { + return requestToken({ + grant_type: 'authorization_code', + client_id: input.clientId, + client_secret: input.clientSecret, + code: input.code, + redirect_uri: input.redirectUri, + code_verifier: input.codeVerifier, + }); +} + +export function refreshMpTokens( + input: TokenRequestInput & { refreshToken: string }, +): Promise { + return requestToken({ + grant_type: 'refresh_token', + client_id: input.clientId, + client_secret: input.clientSecret, + refresh_token: input.refreshToken, + }); +} + +async function requestToken(body: Record): Promise { + let response: Response; + + try { + response = await fetch(MP_TOKEN_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(body), + }); + } catch (error) { + // Network level: no grant decision has been made, so callers must treat the + // account as still fine. + logger.error({ err: error }, 'Mercado Pago token endpoint unreachable'); + throw new MpApiError(0, null); + } + + const payload = (await response.json().catch(() => null)) as Record | null; + + if (!response.ok) { + const reason = typeof payload?.error === 'string' ? payload.error : null; + // Only the status and MP's own error code. The body may echo the `code` or + // the `code_verifier` back, and neither may reach the logs. + logger.error({ status: response.status, reason }, 'Mercado Pago rejected the token request'); + throw new MpApiError(response.status, reason); + } + + return parseTokenResponse(payload); +} + +function parseTokenResponse(payload: Record | null): MpTokenResponse { + const accessToken = pickString(payload, 'access_token'); + const refreshToken = pickString(payload, 'refresh_token'); + const mpUserId = pickString(payload, 'user_id'); + const expiresInSeconds = pickNumber(payload, 'expires_in'); + + if (!accessToken || !refreshToken || !mpUserId || expiresInSeconds === null) { + logger.error( + { received: payload ? Object.keys(payload) : null }, + 'Mercado Pago token response is missing required fields', + ); + throw new MpApiError(200, 'malformed_token_response'); + } + + return { + accessToken, + refreshToken, + expiresInSeconds, + // The response omits `scope` when it matches what was requested. + scope: pickString(payload, 'scope') ?? null, + mpUserId, + liveMode: payload?.live_mode === true, + }; +} + +function pickString(payload: Record | null, key: string): string | null { + const value = payload?.[key]; + if (typeof value === 'string' && value.length > 0) return value; + // Mercado Pago sends `user_id` as a number. + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return null; +} + +function pickNumber(payload: Record | null, key: string): number | null { + const value = payload?.[key]; + if (typeof value === 'number' && Number.isFinite(value)) return value; + if (typeof value === 'string') { + const parsed = Number(value); + if (Number.isFinite(parsed)) return parsed; + } + return null; +} diff --git a/apps/backend/src/modules/mp/lib/return-url.ts b/apps/backend/src/modules/mp/lib/return-url.ts new file mode 100644 index 0000000..c1eec79 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/return-url.ts @@ -0,0 +1,25 @@ +import type { MpCallbackReason, MpReturnTo } from '@gruperly/shared'; + +export type MpCallbackOutcome = + | { kind: 'success' } + | { kind: 'error'; reason: MpCallbackReason }; + +/** + * Where the OAuth callback sends the teacher back to. + * + * Only `mp` and a reason code ever go in the URL: the authorization code and the + * PKCE verifier stay on the server. `returnTo` comes from a stored enum, never + * from the request, so this cannot be turned into an open redirect. + */ +export function buildMpReturnUrl( + webUrl: string, + returnTo: MpReturnTo, + outcome: MpCallbackOutcome, +): string { + const url = new URL(`/${returnTo}`, webUrl); + url.searchParams.set('mp', outcome.kind); + if (outcome.kind === 'error') { + url.searchParams.set('reason', outcome.reason); + } + return url.toString(); +} diff --git a/apps/backend/src/modules/mp/routes.ts b/apps/backend/src/modules/mp/routes.ts new file mode 100644 index 0000000..6ef40a8 --- /dev/null +++ b/apps/backend/src/modules/mp/routes.ts @@ -0,0 +1,16 @@ +import { Hono } from 'hono'; +import callbackRoute from './features/callback/route'; +import connectRoute from './features/connect/route'; +import disconnectRoute from './features/disconnect/route'; +import statusRoute from './features/status/route'; + +const routes = new Hono(); + +// `disconnectRoute` only declares `DELETE /`, so mounting it at the same path as +// `connectRoute` gives the unlink endpoint its RESTful `DELETE /mp/connect`. +routes.route('/connect', connectRoute); +routes.route('/connect', disconnectRoute); +routes.route('/callback', callbackRoute); +routes.route('/status', statusRoute); + +export default routes; diff --git a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts index a2d8e4b..5fa8070 100644 --- a/apps/backend/src/modules/onboarding/features/first-group/use-case.ts +++ b/apps/backend/src/modules/onboarding/features/first-group/use-case.ts @@ -7,16 +7,13 @@ import type { Result, } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; -import { - onboardingAlreadyCompletedProblem, - paymentNotSetupProblem, -} from '@/http/problem-builders'; +import { onboardingAlreadyCompletedProblem } from '@/http/problem-builders'; import { problemDetails } from '@/http/problem-details'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { toOnboardingGroupDto } from '../../lib'; type CreateFirstGroupDeps = { - db?: Pick; + db?: Pick; unitOfWork?: UnitOfWork; }; @@ -38,11 +35,6 @@ export class CreateFirstGroup { return err(onboardingAlreadyCompletedProblem()); } - const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } }); - if (!merchantAccount) { - return err(paymentNotSetupProblem()); - } - const transaction = unitOfWork.executeResult( async (tx: Prisma.TransactionClient) => { const created = await tx.group.create({ diff --git a/apps/backend/src/modules/onboarding/features/payment-setup/route.ts b/apps/backend/src/modules/onboarding/features/payment-setup/route.ts deleted file mode 100644 index 83f94ec..0000000 --- a/apps/backend/src/modules/onboarding/features/payment-setup/route.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { ConnectPayment } from '@gruperly/shared'; -import { ConnectPaymentSchema } from '@gruperly/shared'; -import { Hono } from 'hono'; -import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; -import { validate } from '@/http/validate'; -import { PaymentSetup } from './use-case'; - -const route = new Hono(); - -route.post('/', validate.json(ConnectPaymentSchema), async (c) => { - const user = c.get('user'); - if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); - - const data = c.req.valid('json') as ConnectPayment; - const useCase = new PaymentSetup(); - const result = await useCase.execute(data, user.id); - return resultJson(c, result); -}); - -export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/features/payment-setup/use-case.ts b/apps/backend/src/modules/onboarding/features/payment-setup/use-case.ts deleted file mode 100644 index d266212..0000000 --- a/apps/backend/src/modules/onboarding/features/payment-setup/use-case.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { PrismaClient } from '@generated/prisma/client'; -import type { ConnectPayment, ConnectPaymentResult, ProblemDetails, Result } from '@gruperly/shared'; -import { ok } from '@gruperly/shared'; -import prisma from '@/lib/prisma'; - -type PaymentSetupDeps = { db?: PrismaClient }; - -export class PaymentSetup { - constructor(private readonly deps: PaymentSetupDeps = {}) {} - - async execute( - data: ConnectPayment, - userId: string, - ): Promise> { - const db = this.deps.db ?? prisma; - - await db.merchantAccount.upsert({ - where: { userId }, - create: { - userId, - provider: data.provider, - accessToken: data.accessToken, - sandbox: data.sandbox, - }, - update: { - provider: data.provider, - accessToken: data.accessToken, - sandbox: data.sandbox, - }, - }); - - return ok({ - provider: data.provider, - sandbox: data.sandbox, - connected: true, - }); - } -} \ No newline at end of file diff --git a/apps/backend/src/modules/onboarding/features/status/use-case.ts b/apps/backend/src/modules/onboarding/features/status/use-case.ts index 00852f5..492a653 100644 --- a/apps/backend/src/modules/onboarding/features/status/use-case.ts +++ b/apps/backend/src/modules/onboarding/features/status/use-case.ts @@ -4,7 +4,7 @@ import { err, ok } from '@gruperly/shared'; import { problemDetails } from '@/http/problem-details'; import prisma from '@/lib/prisma'; -type GetOnboardingStatusDeps = { db?: PrismaClient }; +type GetOnboardingStatusDeps = { db?: Pick }; export class GetOnboardingStatus { constructor(private readonly deps: GetOnboardingStatusDeps = {}) {} @@ -28,8 +28,11 @@ export class GetOnboardingStatus { return ok({ step: 'COMPLETED', paymentConnected: true, completed: true }); } - const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } }); - if (merchantAccount) { + // Linking Mercado Pago is optional, so `paymentConnected` here only resumes + // the flow where the teacher left off: with a usable account, they do not + // need to see the "Cobros" step again. A `revoked` row is not usable. + const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } }); + if (mpAccount && mpAccount.status === 'ACTIVE') { return ok({ step: 'PAYMENT_CONNECTED', paymentConnected: true, completed: false }); } diff --git a/apps/backend/src/modules/onboarding/routes.ts b/apps/backend/src/modules/onboarding/routes.ts index 5fb471f..225f20b 100644 --- a/apps/backend/src/modules/onboarding/routes.ts +++ b/apps/backend/src/modules/onboarding/routes.ts @@ -1,12 +1,10 @@ import { Hono } from 'hono'; import firstGroupRoute from './features/first-group/route'; -import paymentSetupRoute from './features/payment-setup/route'; import statusRoute from './features/status/route'; const routes = new Hono(); routes.route('/status', statusRoute); -routes.route('/payment-setup', paymentSetupRoute); routes.route('/first-group', firstGroupRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index a490a6c..2e22be7 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -1,6 +1,7 @@ import app from '@/app'; import { getPrismaClient } from '@/lib/prisma'; import { logger } from '@/logger'; +import { startMpJobs } from '@/modules/mp'; const port = Number(process.env.PORT ?? 4000); @@ -11,6 +12,8 @@ const server = Bun.serve({ fetch: app.fetch, }); +startMpJobs(); + async function shutdown(): Promise { server.stop(true); await getPrismaClient().$disconnect(); diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts index 9e141a6..6104538 100644 --- a/apps/backend/test/groups.test.ts +++ b/apps/backend/test/groups.test.ts @@ -10,9 +10,6 @@ const db = { groupMember: { create: mock(), }, - merchantAccount: { - findUnique: mock(), - }, }; mock.module('@/lib/prisma', () => ({ @@ -171,7 +168,6 @@ describe('groups routes', () => { }); it('creates a group with billing configuration', async () => { - prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId }); prisma.group.create.mockResolvedValue({ ...group, days: ['MONDAY'], @@ -227,8 +223,16 @@ describe('groups routes', () => { }); }); - it('rejects creating a group without a linked merchant account', async () => { - prisma.merchantAccount.findUnique.mockResolvedValue(null); + it('creates a group without Mercado Pago linked, since linking is optional', async () => { + prisma.group.create.mockResolvedValue({ + ...group, + days: ['MONDAY'], + time: '09:00', + capacity: 20, + price: 500, + billingType: 'MONTHLY', + dueDay: 5, + }); const res = await makeApp({ id: userId }).request('/groups', { method: 'POST', @@ -244,9 +248,8 @@ describe('groups routes', () => { headers: { 'Content-Type': 'application/json' }, }); - expect(res.status).toBe(409); - expect(await res.json()).toMatchObject({ code: 'payment_not_setup' }); - expect(prisma.group.create).not.toHaveBeenCalled(); + expect(res.status).toBe(201); + expect(prisma.group.create).toHaveBeenCalled(); }); it('rejects creating a group with an invalid payload', async () => { diff --git a/apps/backend/test/mp.test.ts b/apps/backend/test/mp.test.ts new file mode 100644 index 0000000..cc81ba3 --- /dev/null +++ b/apps/backend/test/mp.test.ts @@ -0,0 +1,1042 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + mpAccount: { + findUnique: mock(), + upsert: mock(), + update: mock(), + }, + mpOAuthState: { + create: mock(), + findUnique: mock(), + deleteMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { getMpAccessToken, mpRoutes } from '@/modules/mp'; +import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens'; +import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account'; +import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto'; +import { MpApiError } from '@/modules/mp/lib/mp-oauth'; + +const ownerId = 'user-1'; +const otherOwnerId = 'user-2'; +const WEB_URL = 'http://localhost:6173'; + +/** A key of the right length; the value never matters for these tests. */ +const ENCRYPTION_KEY = Buffer.alloc(32, 7).toString('base64'); +// Set before the fixtures below seal anything at describe-body time. +process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + +const storedState = { + state: 'state-abc', + ownerId, + codeVerifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', + returnTo: 'onboarding', + expiresAt: new Date(Date.now() + 10 * 60 * 1000), +}; + +/** + * The wire body Mercado Pago returns, not the parsed shape: `user_id` arrives + * as a number, which the parser has to cope with. + */ +const mpWireTokens = { + access_token: 'APP_USR-access-token', + refresh_token: 'TG-refresh-token', + expires_in: 15552000, + scope: 'offline_access read write', + user_id: 9876543210, + live_mode: true, +}; + +const MP_USER_ID = '9876543210'; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/mp', mpRoutes); + return app; +} + +function locationOf(res: Response): URL { + const location = res.headers.get('Location'); + if (!location) throw new Error('the callback did not redirect'); + return new URL(location); +} + +describe('modules/mp', () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + process.env.WEB_URL = WEB_URL; + }); + + describe('GET /mp/status', () => { + it('reports none when the teacher has never linked an account', async () => { + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + status: 'none', + liveMode: false, + expiresAt: null, + connectedAt: null, + mpUserIdSuffix: null, + }); + }); + + it('reports active without leaking tokens or the full Mercado Pago id', async () => { + const expiresAt = new Date('2027-03-01T12:00:00.000Z'); + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + accessTokenEnc: 'v1:sealed', + refreshTokenEnc: 'v1:sealed', + expiresAt, + scope: 'offline_access read write', + liveMode: true, + status: 'ACTIVE', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + const body = await res.json(); + + expect(body).toEqual({ + status: 'active', + liveMode: true, + expiresAt: expiresAt.toISOString(), + connectedAt: '2026-10-01T10:00:00.000Z', + mpUserIdSuffix: '3210', + }); + expect(JSON.stringify(body)).not.toContain('sealed'); + expect(JSON.stringify(body)).not.toContain('9876543210'); + expect(JSON.stringify(body)).not.toContain('offline_access'); + }); + + it('reports requires_reauth when the renewal was refused', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + expiresAt: new Date('2027-03-01T12:00:00.000Z'), + liveMode: false, + status: 'REQUIRES_REAUTH', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect((await res.json()).status).toBe('requires_reauth'); + }); + + it('reports none for a revoked row, since there is nothing usable left', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId, + mpUserId: '9876543210', + expiresAt: new Date(0), + liveMode: false, + status: 'REVOKED', + connectedAt: new Date('2026-10-01T10:00:00.000Z'), + }); + + const res = await makeApp({ id: ownerId }).request('/mp/status'); + + expect((await res.json()).status).toBe('none'); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/status'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + }); + + describe('GET /mp/connect', () => { + it('builds a PKCE authorization URL and stores the state', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=onboarding'); + + expect(res.status).toBe(200); + const { authorizationUrl } = (await res.json()) as { authorizationUrl: string }; + const url = new URL(authorizationUrl); + + expect(`${url.origin}${url.pathname}`).toBe( + 'https://auth.mercadopago.com/authorization', + ); + expect(url.searchParams.get('client_id')).toBe('client-123'); + expect(url.searchParams.get('response_type')).toBe('code'); + expect(url.searchParams.get('platform_id')).toBe('mp'); + expect(url.searchParams.get('redirect_uri')).toBe( + 'http://localhost:4000/api/v1/mp/callback', + ); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('scope')).toBe('offline_access read write'); + + const state = url.searchParams.get('state'); + const challenge = url.searchParams.get('code_challenge'); + expect(state).toBeTruthy(); + expect(challenge).toBeTruthy(); + + const created = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data; + expect(created.state).toBe(state); + expect(created.ownerId).toBe(ownerId); + expect(created.returnTo).toBe('onboarding'); + // Only the challenge is public: the verifier stays in the row. + expect(created.codeVerifier).toBeTruthy(); + expect(codeChallengeFromVerifier(created.codeVerifier)).toBe(challenge); + expect(created.expiresAt.getTime()).toBeGreaterThan(Date.now() + 9 * 60 * 1000); + }); + + it('never puts the code verifier in the URL it hands to the browser', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect'); + const { authorizationUrl } = (await res.json()) as { authorizationUrl: string }; + + const verifier = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.codeVerifier; + expect(authorizationUrl).not.toContain(verifier); + }); + + it('sweeps expired states and the previous attempt of the same teacher', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 2 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + await makeApp({ id: ownerId }).request('/mp/connect'); + + const where = prisma.mpOAuthState.deleteMany.mock.calls[0]?.[0]?.where; + expect(where.OR).toHaveLength(2); + expect(where.OR).toContainEqual({ ownerId }); + }); + + it('defaults the return target to settings', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + prisma.mpOAuthState.create.mockResolvedValue({}); + + await makeApp({ id: ownerId }).request('/mp/connect'); + + expect(prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.returnTo).toBe('settings'); + }); + + it('rejects a return target outside the enum', async () => { + const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=https://evil.test'); + + expect(res.status).toBe(400); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/connect'); + + expect(res.status).toBe(401); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + + it('reports a configuration problem when the credentials are missing', async () => { + delete process.env.MP_CLIENT_ID; + + const res = await makeApp({ id: ownerId }).request('/mp/connect'); + + expect(res.status).toBe(503); + expect(await res.json()).toMatchObject({ code: 'mp_not_configured' }); + expect(prisma.mpOAuthState.create).not.toHaveBeenCalled(); + }); + }); + + describe('GET /mp/callback', () => { + const callbackUrl = (query: string) => `/mp/callback${query}`; + + /** + * The route builds the use-case itself, so `fetch` is the seam: this + * answers Mercado Pago's token endpoint and hands back the restore function. + */ + function stubTokenEndpoint( + answer: Response | Error, + ): { calls: Array>; restore: () => void } { + const calls: Array> = []; + const original = globalThis.fetch; + globalThis.fetch = mock(async (_url: unknown, init: RequestInit) => { + calls.push(JSON.parse(String(init.body)) as Record); + if (answer instanceof Error) throw answer; + return answer.clone(); + }) as unknown as typeof fetch; + + return { + calls, + restore: () => { + globalThis.fetch = original; + }, + }; + } + + function tokenResponse(payload: unknown, status = 200): Response { + return new Response(JSON.stringify(payload), { + status, + headers: { 'Content-Type': 'application/json' }, + }); + } + + it('exchanges the code and stores the tokens encrypted', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + + const { create: data } = prisma.mpAccount.upsert.mock.calls[0]?.[0] ?? {}; + expect(data.ownerId).toBe(ownerId); + expect(data.mpUserId).toBe(MP_USER_ID); + expect(data.status).toBe('ACTIVE'); + expect(data.liveMode).toBe(true); + expect(data.scope).toBe('offline_access read write'); + + // Encrypted at rest: the ciphertext is not the token. + expect(data.accessTokenEnc).not.toBe(mpWireTokens.access_token); + expect(data.refreshTokenEnc).not.toBe(mpWireTokens.refresh_token); + expect(String(data.accessTokenEnc).startsWith('v1:')).toBe(true); + expect(openToken(data.accessTokenEnc)).toBe(mpWireTokens.access_token); + expect(openToken(data.refreshTokenEnc)).toBe(mpWireTokens.refresh_token); + + // expires_at comes from expires_in, not from a guess. + const expected = Date.now() + mpWireTokens.expires_in * 1000; + expect(Math.abs(data.expiresAt.getTime() - expected)).toBeLessThan(5_000); + }); + + it('sends the verifier and the exact redirect_uri to Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(stub.calls[0]).toEqual({ + grant_type: 'authorization_code', + client_id: 'client-123', + client_secret: 'secret-abc', + code: 'auth-code-123', + redirect_uri: 'http://localhost:4000/api/v1/mp/callback', + code_verifier: storedState.codeVerifier, + }); + }); + + it('lands the teacher back on the onboarding step they left', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).pathname).toBe('/onboarding'); + }); + + it('still redirects when Mercado Pago appends query params we do not model', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc&error_description=&foo=bar'), + ); + stub.restore(); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + }); + + it('refuses an unknown state and never calls Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(null); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=forged'), + ); + globalThis.fetch = original; + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('error'); + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses an expired state without touching Mercado Pago', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue({ + ...storedState, + expiresAt: new Date(Date.now() - 1000), + }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses a replayed state, even with a valid looking code', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + // Already consumed by the first callback: the delete matches nothing. + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('refuses a callback without a code', async () => { + const res = await makeApp({ id: ownerId }).request(callbackUrl('?state=state-abc')); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + }); + + it('treats a rejected consent screen as mp_denied and burns the state', async () => { + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + + const fetchMock = mock(); + const original = globalThis.fetch; + globalThis.fetch = fetchMock as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?error=access_denied&error_description=user_denied&state=state-abc'), + ); + globalThis.fetch = original; + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('mp')).toBe('error'); + expect(locationOf(res).searchParams.get('reason')).toBe('mp_denied'); + expect(prisma.mpOAuthState.deleteMany).toHaveBeenCalledWith({ + where: { state: 'state-abc' }, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('refuses when the Mercado Pago account belongs to another teacher', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-9', ownerId: otherOwnerId }); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('maps the unique index violation to the same clear error', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockRejectedValue({ code: 'P2002' }); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use'); + }); + + it('lets a teacher re-link their own account', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId }); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('mp')).toBe('success'); + + const args = prisma.mpAccount.upsert.mock.calls[0]?.[0]; + expect(args.where).toEqual({ ownerId }); + // Re-linking renews the credentials and clears a `requires_reauth`. + expect(args.update.status).toBe('ACTIVE'); + expect(args.update.connectedAt).toBeInstanceOf(Date); + }); + + it('reports mp_error when Mercado Pago rejects the exchange', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const original = globalThis.fetch; + globalThis.fetch = mock( + async () => + new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }), + ) as unknown as typeof fetch; + + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + globalThis.fetch = original; + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_error'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('reports mp_error when Mercado Pago is unreachable', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const stub = stubTokenEndpoint(new Error('ECONNREFUSED')); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=auth-code-123&state=state-abc'), + ); + stub.restore(); + + expect(locationOf(res).searchParams.get('reason')).toBe('mp_error'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + + it('never puts the code or the verifier in the redirect it sends the browser to', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue(storedState); + prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 }); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.upsert.mockResolvedValue({}); + + const stub = stubTokenEndpoint(tokenResponse(mpWireTokens)); + const res = await makeApp({ id: ownerId }).request( + callbackUrl('?code=super-secret-code&state=state-abc'), + ); + stub.restore(); + + const location = locationOf(res); + expect(location.search).toContain('mp=success'); + expect(location.href).not.toContain('super-secret-code'); + expect(location.href).not.toContain(storedState.codeVerifier); + }); + + it('sends a teacher without a session to the login screen', async () => { + const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc')); + + expect(res.status).toBe(302); + expect(locationOf(res).pathname).toBe('/login'); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + }); + + describe('DELETE /mp/connect', () => { + it('revokes the account and blanks the tokens', async () => { + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId }); + prisma.mpAccount.update.mockResolvedValue({}); + + const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ disconnected: true }); + expect(prisma.mpAccount.update).toHaveBeenCalledWith({ + where: { ownerId }, + data: { + status: 'REVOKED', + accessTokenEnc: '', + refreshTokenEnc: '', + expiresAt: new Date(0), + }, + }); + }); + + it('is a no-op when there is nothing linked', async () => { + prisma.mpAccount.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ disconnected: false }); + expect(prisma.mpAccount.update).not.toHaveBeenCalled(); + }); + + it('rejects without a session', async () => { + const res = await makeApp(null).request('/mp/connect', { method: 'DELETE' }); + + expect(res.status).toBe(401); + }); + }); +}); + +describe('modules/mp encryption and PKCE', () => { + beforeEach(() => { + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + it('round-trips a token through seal and open', () => { + const token = 'APP_USR-very-long-mercadopago-access-token'; + const sealed = sealToken(token); + + expect(sealed.startsWith('v1:')).toBe(true); + expect(sealed).not.toContain(token); + expect(openToken(sealed)).toBe(token); + }); + + it('produces a different ciphertext every time', () => { + expect(sealToken('same-token')).not.toBe(sealToken('same-token')); + }); + + it('refuses a tampered payload instead of returning garbage', () => { + const sealed = sealToken('token'); + const [version, iv, tag, ciphertext = ''] = sealed.split(':'); + if (!version || !iv || !tag || !ciphertext) throw new Error('unexpected payload shape'); + + // Flip the first ciphertext byte: the trailing base64url char of a GCM tag + // only carries two significant bits, so editing that one can decode back to + // the original tag and the payload would still verify. + const tampered = `${ciphertext[0] === 'A' ? 'B' : 'A'}${ciphertext.slice(1)}`; + + expect(() => openToken(`${version}:${iv}:${tag}:${tampered}`)).toThrow(); + }); + + it('refuses an unknown payload version', () => { + expect(() => openToken('v9:aaa:bbb:ccc')).toThrow('Unsupported token payload'); + }); + + it('refuses to work without a key of 32 bytes', () => { + process.env.TOKEN_ENCRYPTION_KEY = Buffer.alloc(16, 7).toString('base64'); + + expect(() => sealToken('token')).toThrow('must decode to 32 bytes'); + }); + + it('derives the S256 challenge from the RFC 7636 test vector', () => { + expect(codeChallengeFromVerifier('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe( + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + ); + }); +}); + +describe('modules/mp access token', () => { + const activeAccount = { + id: 'mp-1', + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-current-token'), + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + }; + + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + it('fails with mp_not_connected when the teacher never linked an account', async () => { + const db = { mpAccount: { findUnique: mock(async () => null) } }; + + const result = await getMpAccessToken(ownerId, { + db: db as unknown as Parameters[1] extends undefined + ? never + : never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_not_connected'); + }); + + it('tells mp_not_connected and mp_requires_reauth apart', async () => { + const notActive = { ...activeAccount, status: 'REQUIRES_REAUTH' }; + const refresh = { execute: mock() }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => notActive) } } as never, + refresh: refresh as never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + // A locked account is never "fixed" by quietly attempting a renewal. + expect(refresh.execute).not.toHaveBeenCalled(); + }); + + it('decrypts a token that is still fresh, without calling Mercado Pago', async () => { + const refresh = { execute: mock() }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => activeAccount) } } as never, + refresh: refresh as never, + }); + + expect(result).toEqual({ + ok: true, + value: { accountId: 'mp-1', accessToken: 'APP_USR-current-token', expiresAt: activeAccount.expiresAt }, + }); + expect(refresh.execute).not.toHaveBeenCalled(); + }); + + it('renews on demand when the token is about to expire', async () => { + const stale = { ...activeAccount, expiresAt: new Date(Date.now() + 60 * 1000) }; + const renewed = { + ok: true as const, + value: { + accountId: 'mp-1', + accessToken: 'APP_USR-fresh-token', + expiresAt: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000), + }, + }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => stale) } } as never, + refresh: { execute: mock(async () => renewed) } as never, + }); + + expect(result).toEqual(renewed); + }); + + it('passes the renewal failure through instead of returning a stale token', async () => { + const stale = { ...activeAccount, expiresAt: new Date(Date.now() - 1000) }; + const failed = { + ok: false as const, + error: { + type: 'x', + title: 'Conflict', + status: 409, + detail: 'd', + code: 'mp_requires_reauth', + }, + }; + + const result = await getMpAccessToken(ownerId, { + db: { mpAccount: { findUnique: mock(async () => stale) } } as never, + refresh: { execute: mock(async () => failed) } as never, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + }); +}); + +describe('modules/mp RefreshMpAccount', () => { + const account = { + id: 'mp-1', + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-old-access'), + refreshTokenEnc: sealToken('TG-old-refresh'), + scope: 'offline_access read write', + }; + + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + function makeStore(overrides: Record = {}) { + return { + mpAccount: { + findUnique: mock(async () => account), + update: mock(async () => ({})), + ...overrides, + }, + }; + } + + it('sends the stored refresh token and stores both new tokens', async () => { + const store = makeStore(); + const refresh = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: 'offline_access read write', + mpUserId: MP_USER_ID, + liveMode: true, + })); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result).toEqual({ + ok: true, + value: { + accountId: 'mp-1', + accessToken: 'APP_USR-new-access', + expiresAt: expect.any(Date) as unknown as Date, + }, + }); + // `webUrl` rides along in the config object but is never part of the + // request: `refreshMpTokens` picks the three fields the endpoint needs. + expect(refresh).toHaveBeenCalledWith({ + clientId: 'client-123', + clientSecret: 'secret-abc', + redirectUri: 'http://localhost:4000/api/v1/mp/callback', + webUrl: 'http://localhost:6173', + refreshToken: 'TG-old-refresh', + }); + + const data = store.mpAccount.update.mock.calls[0]?.[0]?.data; + // Mercado Pago rotates the refresh token: keeping the old one would break + // the next renewal. + expect(openToken(data.refreshTokenEnc)).toBe('TG-new-refresh'); + expect(openToken(data.accessTokenEnc)).toBe('APP_USR-new-access'); + expect(data.status).toBe('ACTIVE'); + }); + + it('keeps the stored scope when the renewal omits it', async () => { + const store = makeStore(); + const refresh = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: null, + mpUserId: MP_USER_ID, + liveMode: true, + })); + + await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute('mp-1'); + + expect(store.mpAccount.update.mock.calls[0]?.[0]?.data.scope).toBe( + 'offline_access read write', + ); + }); + + it('marks the account REQUIRES_REAUTH when Mercado Pago says invalid_grant', async () => { + const store = makeStore(); + const refresh = mock(async () => { + throw new MpApiError(401, 'invalid_grant'); + }); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + expect(store.mpAccount.update).toHaveBeenCalledWith({ + where: { id: 'mp-1' }, + data: { status: 'REQUIRES_REAUTH' }, + }); + }); + + it('leaves the account untouched on a server error, so tomorrow can retry', async () => { + const store = makeStore(); + const refresh = mock(async () => { + throw new MpApiError(500, null); + }); + + const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute( + 'mp-1', + ); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_provider_error'); + expect(store.mpAccount.update).not.toHaveBeenCalled(); + }); + + it('reports the account when it disappears mid-run', async () => { + const store = makeStore({ findUnique: mock(async () => null) }); + + const result = await new RefreshMpAccount({ + db: store as never, + refresh: mock(async () => { + throw new Error('should not be called'); + }) as never, + }).execute('mp-1'); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth'); + }); +}); + +describe('modules/mp RefreshExpiringMpTokens', () => { + beforeEach(() => { + process.env.MP_CLIENT_ID = 'client-123'; + process.env.MP_CLIENT_SECRET = 'secret-abc'; + process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback'; + process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY; + }); + + /** + * Fakes the transaction client, capturing the tagged-template SQL. The store + * hangs off the `tx` the job forwards, since the writes have to join the + * transaction holding the lock. + */ + function makeJobDb(rows: Array<{ id: string }>, store: { mpAccount: unknown }) { + const captured: { sql: string; values: unknown[] } = { sql: '', values: [] }; + const db = { + $transaction: mock(async (cb: (tx: unknown) => Promise) => + cb({ + mpAccount: store.mpAccount, + $queryRaw: (strings: TemplateStringsArray, ...values: unknown[]) => { + captured.sql = strings.join('?'); + captured.values = values; + return Promise.resolve(rows); + }, + }), + ), + }; + return { db, captured }; + } + + const refreshOk = mock(async () => ({ + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: 'offline_access read write', + mpUserId: MP_USER_ID, + liveMode: true, + })); + + function activeRow(id: string) { + return { + id, + ownerId, + status: 'ACTIVE', + accessTokenEnc: sealToken('APP_USR-old-access'), + refreshTokenEnc: sealToken('TG-old-refresh'), + scope: 'offline_access read write', + }; + } + + function jobDbReturning(rows: Array<{ id: string }>) { + const store = { + mpAccount: { + findUnique: mock(async ({ where }: { where: { id: string } }) => activeRow(where.id)), + update: mock(async () => ({})), + }, + }; + const { db, captured } = makeJobDb(rows, store); + return { db: db as never, captured, store }; + } + + it('selects only accounts expiring inside the 30 day window', async () => { + const { db, captured } = jobDbReturning([]); + + await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute(); + + // Active accounts only, and anything closer than 30 days from expiring. + expect(captured.sql).toContain(`"status" = 'ACTIVE'`); + expect(captured.sql).toContain('"expires_at" <'); + // No lower bound on the window: a token that already expired is exactly the + // one worth recovering, as long as the grant is still alive. + expect(captured.sql).not.toContain('"expires_at" >'); + // Bounded work per run. + expect(captured.sql).toContain('FOR UPDATE SKIP LOCKED'); + expect(captured.sql).toContain('ORDER BY "expires_at" ASC'); + + const [horizon, limit] = captured.values; + expect(horizon).toBeInstanceOf(Date); + const daysAhead = ((horizon as Date).getTime() - Date.now()) / (24 * 60 * 60 * 1000); + expect(daysAhead).toBeGreaterThan(29.9); + expect(daysAhead).toBeLessThan(30.1); + expect(limit).toBe(20); + }); + + it('renews the accounts the query returned and counts them', async () => { + const { db, store } = jobDbReturning([{ id: 'mp-1' }, { id: 'mp-2' }]); + + const totals = await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute(); + + expect(totals).toEqual({ refreshed: 2, requiresReauth: 0, failed: 0 }); + expect(store.mpAccount.update).toHaveBeenCalledTimes(2); + }); + + it('separates accounts that need a new authorization from transient failures', async () => { + const mixed = mock(async ({ refreshToken }: { refreshToken: string }) => { + if (refreshToken === 'TG-old-refresh') throw new MpApiError(500, null); + if (refreshToken === 'TG-dead-refresh') throw new MpApiError(401, 'invalid_grant'); + return { + accessToken: 'APP_USR-new-access', + refreshToken: 'TG-new-refresh', + expiresInSeconds: 15552000, + scope: null, + mpUserId: MP_USER_ID, + liveMode: true, + }; + }); + const store = { + mpAccount: { + findUnique: mock(async ({ where }: { where: { id: string } }) => { + // mp-1: Mercado Pago is having a bad day. mp-2: the grant is dead. + // mp-3: renews fine. + const token = + where.id === 'mp-2' ? 'TG-dead-refresh' : where.id === 'mp-3' ? 'TG-live-refresh' : 'TG-old-refresh'; + return { ...activeRow(where.id), refreshTokenEnc: sealToken(token) }; + }), + update: mock(async () => ({})), + }, + }; + const { db } = makeJobDb( + [{ id: 'mp-1' }, { id: 'mp-2' }, { id: 'mp-3' }], + store as unknown as { mpAccount: unknown }, + ); + + const totals = await new RefreshExpiringMpTokens({ + db: db as never, + refresh: mixed as never, + }).execute(); + + expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 }); + }); +}); diff --git a/apps/backend/test/onboarding.test.ts b/apps/backend/test/onboarding.test.ts index 8ca6d3d..f9a21c1 100644 --- a/apps/backend/test/onboarding.test.ts +++ b/apps/backend/test/onboarding.test.ts @@ -6,9 +6,8 @@ const db = { findUnique: mock(), update: mock(), }, - merchantAccount: { + mpAccount: { findUnique: mock(), - upsert: mock(), }, group: { create: mock(), @@ -75,7 +74,7 @@ describe('onboarding routes', () => { describe('GET /onboarding/status', () => { it('returns NOT_STARTED for a user that has not started', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); - prisma.merchantAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.findUnique.mockResolvedValue(null); const res = await makeApp({ id: userId }).request('/onboarding/status'); @@ -87,9 +86,9 @@ describe('onboarding routes', () => { }); }); - it('returns PAYMENT_CONNECTED when the merchant account exists', async () => { + it('returns PAYMENT_CONNECTED when Mercado Pago is linked and active', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); - prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId }); + prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId: userId, status: 'ACTIVE' }); const res = await makeApp({ id: userId }).request('/onboarding/status'); @@ -101,6 +100,24 @@ describe('onboarding routes', () => { }); }); + it('returns NOT_STARTED when the account needs to be linked again', async () => { + prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); + prisma.mpAccount.findUnique.mockResolvedValue({ + id: 'mp-1', + ownerId: userId, + status: 'REQUIRES_REAUTH', + }); + + const res = await makeApp({ id: userId }).request('/onboarding/status'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + step: 'NOT_STARTED', + paymentConnected: false, + completed: false, + }); + }); + it('returns COMPLETED when onboarding is already done', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true }); @@ -122,54 +139,9 @@ describe('onboarding routes', () => { }); }); - describe('POST /onboarding/payment-setup', () => { - it('connects a merchant account in sandbox mode', async () => { - prisma.merchantAccount.upsert.mockResolvedValue({ id: 'ma-1', userId }); - - const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', { - method: 'POST', - body: JSON.stringify({ provider: 'MERCADO_PAGO', sandbox: true }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ - provider: 'MERCADO_PAGO', - sandbox: true, - connected: true, - }); - expect(prisma.merchantAccount.upsert).toHaveBeenCalledWith({ - where: { userId }, - create: { userId, provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true }, - update: { provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true }, - }); - }); - - it('rejects an unknown provider', async () => { - const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', { - method: 'POST', - body: JSON.stringify({ provider: 'PAYPAL' }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(400); - }); - - it('rejects without a session', async () => { - const res = await makeApp(null).request('/onboarding/payment-setup', { - method: 'POST', - body: JSON.stringify({ provider: 'STRIPE', sandbox: true }), - headers: { 'Content-Type': 'application/json' }, - }); - - expect(res.status).toBe(401); - }); - }); - describe('POST /onboarding/first-group', () => { it('creates the first group and completes onboarding', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); - prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId }); prisma.group.create.mockResolvedValue(group); const res = await makeApp({ id: userId }).request('/onboarding/first-group', { @@ -217,9 +189,10 @@ describe('onboarding routes', () => { }); }); - it('rejects when the payment has not been set up', async () => { + it('creates the group without Mercado Pago linked, since that step is skippable', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); - prisma.merchantAccount.findUnique.mockResolvedValue(null); + prisma.mpAccount.findUnique.mockResolvedValue(null); + prisma.group.create.mockResolvedValue(group); const res = await makeApp({ id: userId }).request('/onboarding/first-group', { method: 'POST', @@ -227,9 +200,8 @@ describe('onboarding routes', () => { headers: { 'Content-Type': 'application/json' }, }); - expect(res.status).toBe(409); - expect(await res.json()).toMatchObject({ code: 'payment_not_setup' }); - expect(prisma.group.create).not.toHaveBeenCalled(); + expect(res.status).toBe(201); + expect(prisma.group.create).toHaveBeenCalled(); }); it('rejects when onboarding is already completed', async () => { @@ -248,7 +220,6 @@ describe('onboarding routes', () => { it('rejects invalid payloads', async () => { prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false }); - prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId }); const res = await makeApp({ id: userId }).request('/onboarding/first-group', { method: 'POST', diff --git a/apps/web/src/components/layout/RootLayout.tsx b/apps/web/src/components/layout/RootLayout.tsx index f41084e..2a9d538 100644 --- a/apps/web/src/components/layout/RootLayout.tsx +++ b/apps/web/src/components/layout/RootLayout.tsx @@ -1,11 +1,12 @@ import { useLocation } from '@tanstack/react-router' import type { ReactNode } from 'react' import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider' +import { MpReauthNotice } from '../../features/mp' import { isImmersiveRoute } from '../../lib/immersive-routes' import { cn } from '../../lib/utils' +import { BottomNav } from './BottomNav' import { Header } from './Header' import { Sidebar } from './Sidebar' -import { BottomNav } from './BottomNav' export function RootLayout({ children }: { children: ReactNode }) { const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) }) @@ -31,6 +32,10 @@ export function RootLayout({ children }: { children: ReactNode }) { )} > {immersive ? : null} + {/* Aviso de que Mercado Pago necesita volver a autorizarse. Va dentro + de
para que fluya con el contenido y no tape la barra + immersive ni el bottom nav; se oculta solo en Ajustes. */} + {children}
diff --git a/apps/web/src/features/mp/MpReauthNotice.tsx b/apps/web/src/features/mp/MpReauthNotice.tsx new file mode 100644 index 0000000..5547976 --- /dev/null +++ b/apps/web/src/features/mp/MpReauthNotice.tsx @@ -0,0 +1,51 @@ +import { useLocation } from '@tanstack/react-router' +import { Loader2, TriangleAlert } from 'lucide-react' +import { Button } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { shouldShowMpReauthNotice } from './copy' +import { useMpStatus } from './useMpStatus' +import { useStartMpAuthorization } from './useStartMpAuthorization' + +/** + * Aviso global de que la cuenta de Mercado Pago necesita volver a autorizarse. + * + * Solo aparece con sesión iniciada y cuando el estado es `requires_reauth`: que + * la cuenta esté sin vincular es legítimo (el paso del onboarding es + * salteable), pero un cobro que no va a entrar hay que decirlo aunque el + * profesor esté en cualquier pantalla. En Ajustes no se muestra porque ahí la + * tarjeta de Cobros ya ofrece la acción, con más contexto. + */ +export function MpReauthNotice() { + const { user } = useAuth() + const statusQuery = useMpStatus({ enabled: !!user }) + const startAuthorization = useStartMpAuthorization() + const pathname = useLocation({ select: (location) => location.pathname }) + + const status = statusQuery.data?.status + if (!user || pathname === '/settings') return null + if (!status || !shouldShowMpReauthNotice(status)) return null + + return ( +
+ +
+

Volvé a vincular Mercado Pago

+

+ Tu autorización venció, así que los cobros de tus grupos no se están procesando. +

+
+ {startAuthorization.isStarting ? ( + + ) : ( + + )} +
+ ) +} \ No newline at end of file diff --git a/apps/web/src/features/mp/MpStatusCard.tsx b/apps/web/src/features/mp/MpStatusCard.tsx new file mode 100644 index 0000000..8a956cf --- /dev/null +++ b/apps/web/src/features/mp/MpStatusCard.tsx @@ -0,0 +1,188 @@ +import { BadgeCheck, CreditCard, Loader2, Unlink } from 'lucide-react' +import { useState } from 'react' +import { Badge, Button, Modal } from '../../components/ui' +import { + formatMpConnectionDate, + MP_PROVIDER_NAME, + mpStatusBadgeVariant, + mpStatusLabel, +} from './copy' +import { useDisconnectMp } from './useDisconnectMp' +import { useMpStatus } from './useMpStatus' +import { useStartMpAuthorization } from './useStartMpAuthorization' + +/** + * Estado de la cuenta de Mercado Pago en Ajustes: vincular, ver que está + * vinculada o volver a vincularla. El mismo control vive en el paso del + * onboarding; acá es el lugar al que se llega cuando ese paso ya pasó. + */ +export function MpStatusCard() { + const statusQuery = useMpStatus() + const startAuthorization = useStartMpAuthorization() + const { disconnectMp: disconnect, isDisconnecting } = useDisconnectMp() + const [isConfirmingDisconnect, setIsConfirmingDisconnect] = useState(false) + + const status = statusQuery.data?.status ?? 'none' + const accountIdSuffix = statusQuery.data?.mpUserIdSuffix + const connectedAt = formatMpConnectionDate(statusQuery.data?.connectedAt ?? null) + + if (statusQuery.isPending) { + return ( +
+ +

Consultando tu cuenta de {MP_PROVIDER_NAME}…

+
+ ) + } + + return ( +
+
+
+
+

Cobros

+ {mpStatusLabel(status)} +
+

+ Tu cuenta de {MP_PROVIDER_NAME} para recibir los pagos de tus grupos. +

+
+ + {status === 'active' && accountIdSuffix ? ( +
+ + + +
+

+ Cuenta terminada en ••{accountIdSuffix} +

+ {connectedAt ? ( +

Vinculada el {connectedAt}

+ ) : null} +
+ +
+ ) : null} + + {status === 'requires_reauth' ? ( +
+ + + +
+

Hay que volver a vincular la cuenta

+

+ Mercado Pago ya no acepta la autorización anterior. Volvé a autorizar para poder + seguir cobrando. +

+
+ void startAuthorization.start('settings')} + > + Volver a vincular + +
+ ) : null} + + {status === 'none' ? ( +
+ + + +
+

Vinculá tu cuenta

+

+ Te llevamos a {MP_PROVIDER_NAME} para autorizar los cobros. Es gratis y lo podés + hacer más adelante. +

+
+ void startAuthorization.start('settings')} + > + Vincular + +
+ ) : null} +
+ + {startAuthorization.error ? ( +

+ {startAuthorization.error} +

+ ) : null} + + setIsConfirmingDisconnect(false)} + onConfirm={() => { + setIsConfirmingDisconnect(false) + disconnect() + }} + /> +
+ ) +} + +type ConnectButtonProps = { + isStarting: boolean + onClick: () => void + children: string +} + +function ConnectButton({ isStarting, onClick, children }: ConnectButtonProps) { + return ( + + ) +} + +type DisconnectModalProps = { + isOpen: boolean + isPending: boolean + onClose: () => void + onConfirm: () => void +} + +/** + * Desvincular se puede revertir volviendo a autorizar, pero los cobros quedan + * suspendidos mientras tanto, así que se pregunta antes. + */ +function DisconnectModal({ isOpen, isPending, onClose, onConfirm }: DisconnectModalProps) { + return ( + +
+ + +
+
+ ) +} \ No newline at end of file diff --git a/apps/web/src/features/mp/copy.ts b/apps/web/src/features/mp/copy.ts new file mode 100644 index 0000000..5a48b48 --- /dev/null +++ b/apps/web/src/features/mp/copy.ts @@ -0,0 +1,87 @@ +import type { MpAccountStatus, MpCallbackReason } from '@gruperly/shared' + +/* Copy de Mercado Pago en un solo lugar: el paso del onboarding, la tarjeta de + Ajustes y el aviso global tienen que decir exactamente lo mismo. Las funciones + son puras para poder cubrirlas con tests sin renderizar nada. */ + +export const MP_PROVIDER_NAME = 'Mercado Pago' + +export const MP_CONNECT_ERROR_MESSAGE = + 'No pudimos abrir Mercado Pago. Revisá tu conexión e intentá de nuevo.' + +/** El resultado de la vinculación, tal como vuelve en `?mp=` de la URL. */ +export type MpCallbackFeedback = + | { kind: 'success' } + | { kind: 'error'; reason: MpCallbackReason } + +/** Traduce `?mp=` de la URL a la retroalimentación que se muestra en pantalla. */ +export function readMpCallbackFeedback( + mp: string | undefined, + reason: string | undefined, +): MpCallbackFeedback | null { + if (mp === 'success') return { kind: 'success' } + if (mp !== 'error') return null + + // Un `reason` desconocido o ausente se trata como un fallo genérico: el + // backend manda el código, nunca el mensaje. + const known: readonly MpCallbackReason[] = [ + 'invalid_state', + 'mp_denied', + 'mp_error', + 'mp_account_in_use', + ] + return { + kind: 'error', + reason: known.includes(reason as MpCallbackReason) ? (reason as MpCallbackReason) : 'mp_error', + } +} + +const REASON_MESSAGES: Record = { + invalid_state: 'La vinculación venció o ya se había usado. Volvé a intentarlo.', + mp_denied: 'No autorizaste la conexión en Mercado Pago.', + mp_error: 'Mercado Pago no pudo completar la vinculación.', + mp_account_in_use: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.', +} + +export function mpCallbackErrorMessage(reason: MpCallbackReason): string { + return REASON_MESSAGES[reason] +} + +export function mpStatusLabel(status: MpAccountStatus): string { + switch (status) { + case 'active': + return 'Vinculada' + case 'requires_reauth': + return 'Necesita vincularse de nuevo' + case 'none': + return 'Sin vincular' + } +} + +export function mpStatusBadgeVariant( + status: MpAccountStatus, +): 'success' | 'warning' | 'neutral' { + switch (status) { + case 'active': + return 'success' + case 'requires_reauth': + return 'warning' + case 'none': + return 'neutral' + } +} + +/** `2026-10-05T12:00:00.000Z` → `5 oct 2026`. */ +export function formatMpConnectionDate(iso: string | null): string | null { + if (!iso) return null + const date = new Date(iso) + if (Number.isNaN(date.getTime())) return null + return new Intl.DateTimeFormat('es', { day: 'numeric', month: 'short', year: 'numeric' }).format( + date, + ) +} + +/** Cuándo conviene avisarle al profesor que vuelva a vincular. */ +export function shouldShowMpReauthNotice(status: MpAccountStatus): boolean { + return status === 'requires_reauth' +} \ No newline at end of file diff --git a/apps/web/src/features/mp/index.ts b/apps/web/src/features/mp/index.ts new file mode 100644 index 0000000..d7ceeb0 --- /dev/null +++ b/apps/web/src/features/mp/index.ts @@ -0,0 +1,16 @@ +export { + formatMpConnectionDate, + MP_CONNECT_ERROR_MESSAGE, + MP_PROVIDER_NAME, + type MpCallbackFeedback, + mpCallbackErrorMessage, + mpStatusBadgeVariant, + mpStatusLabel, + readMpCallbackFeedback, + shouldShowMpReauthNotice, +} from './copy' +export { MpReauthNotice } from './MpReauthNotice' +export { MpStatusCard } from './MpStatusCard' +export { useDisconnectMp } from './useDisconnectMp' +export { mpStatusQueryKey, useMpStatus } from './useMpStatus' +export { useStartMpAuthorization } from './useStartMpAuthorization' \ No newline at end of file diff --git a/apps/web/src/features/mp/useDisconnectMp.ts b/apps/web/src/features/mp/useDisconnectMp.ts new file mode 100644 index 0000000..bbcb657 --- /dev/null +++ b/apps/web/src/features/mp/useDisconnectMp.ts @@ -0,0 +1,30 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { useToast } from '../../components/ui' +import { disconnectMp } from '../../lib/api' +import { mpStatusQueryKey } from './useMpStatus' + +export function useDisconnectMp() { + const queryClient = useQueryClient() + const toast = useToast() + + const mutation = useMutation({ + mutationFn: disconnectMp, + onSuccess: (result) => { + if (result.disconnected) { + toast.success('Desvinculamos tu cuenta de Mercado Pago.') + } + // `invalidateQueries` y no `setQueryData`: el estado real (si la fila quedó + // reservada o no) lo responde el backend. + void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey }) + void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] }) + }, + onError: (error: Error) => { + toast.error(error.message || 'No pudimos desvincular la cuenta de Mercado Pago.') + }, + }) + + return { + disconnectMp: () => mutation.mutate(), + isDisconnecting: mutation.isPending, + } +} \ No newline at end of file diff --git a/apps/web/src/features/mp/useMpStatus.ts b/apps/web/src/features/mp/useMpStatus.ts new file mode 100644 index 0000000..83b0791 --- /dev/null +++ b/apps/web/src/features/mp/useMpStatus.ts @@ -0,0 +1,19 @@ +import type { MpStatusDto } from '@gruperly/shared' +import { useQuery } from '@tanstack/react-query' +import { getMpStatus } from '../../lib/api' + +/** La misma clave en toda la app: el onboarding, Ajustes y el aviso global. */ +export const mpStatusQueryKey = ['mp', 'status'] as const + +type UseMpStatusOptions = { + /** `RootLayout` se renderiza sin sesión, así que la consulta se puede apagar. */ + enabled?: boolean +} + +export function useMpStatus({ enabled = true }: UseMpStatusOptions = {}) { + return useQuery({ + queryKey: mpStatusQueryKey, + queryFn: getMpStatus, + enabled, + }) +} \ No newline at end of file diff --git a/apps/web/src/features/mp/useStartMpAuthorization.ts b/apps/web/src/features/mp/useStartMpAuthorization.ts new file mode 100644 index 0000000..6893d06 --- /dev/null +++ b/apps/web/src/features/mp/useStartMpAuthorization.ts @@ -0,0 +1,33 @@ +import type { MpReturnTo } from '@gruperly/shared' +import { useState } from 'react' +import { startMpAuthorization } from '../../lib/api' +import { MP_CONNECT_ERROR_MESSAGE } from './copy' + +/** + * Empieza la vinculación de Mercado Pago. + * + * OAuth no se puede hacer con `fetch`: el navegador tiene que navegar a la + * pantalla de consentimiento de Mercado Pago, y el backend devuelve el control al + * frontend con `?mp=success` o `?mp=error&reason=…`. Por eso el botón no navega + * con el router sino con `location.assign`. + */ +export function useStartMpAuthorization() { + const [error, setError] = useState(null) + const [isStarting, setIsStarting] = useState(false) + + const start = async (returnTo: MpReturnTo) => { + setError(null) + setIsStarting(true) + try { + const { authorizationUrl } = await startMpAuthorization(returnTo) + window.location.assign(authorizationUrl) + } catch { + // Perder la red contra nuestra propia API no es un error de Mercado Pago, + // pero para el profesor el botón falló y tiene que poder reintentarlo. + setError(MP_CONNECT_ERROR_MESSAGE) + setIsStarting(false) + } + } + + return { start, isStarting, error } +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/ConfirmationStep.tsx b/apps/web/src/features/onboarding/ConfirmationStep.tsx index cca8c43..eda4ca1 100644 --- a/apps/web/src/features/onboarding/ConfirmationStep.tsx +++ b/apps/web/src/features/onboarding/ConfirmationStep.tsx @@ -1,20 +1,22 @@ -import { useNavigate } from '@tanstack/react-router' -import { useQueryClient } from '@tanstack/react-query' import type { OnboardingGroupDto } from '@gruperly/shared' +import { useQueryClient } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react' -import { useAuth } from '../../context/AuthProvider' import { Badge, Button } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { MP_PROVIDER_NAME, useMpStatus } from '../mp' import { BILLING_LABELS, formatPrice, formatSchedule } from './constants' type ConfirmationStepProps = { group: OnboardingGroupDto - providerName?: string } -export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) { +export function ConfirmationStep({ group }: ConfirmationStepProps) { const navigate = useNavigate() const queryClient = useQueryClient() const { refresh } = useAuth() + const statusQuery = useMpStatus() + const isMpConnected = statusQuery.data?.status === 'active' const goToDashboard = () => { // Revalidates the cache (onboarding state, session, groups) before redirecting. @@ -31,7 +33,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)

¡Todo listo!

- Tu grupo se creó y ya podés empezar a cobrar a tus miembros. + Tu grupo se creó. Ya podés invitar miembros y pasar lista.

@@ -65,15 +67,24 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) - {providerName ? ( -
- -

- Vas a cobrar con {providerName} en modo - prueba. -

-
- ) : null} +
+ +

+ {isMpConnected ? ( + <> + Vas a cobrar con {MP_PROVIDER_NAME}. Los + pagos entran directo en tu cuenta. + + ) : ( + <> + Cuando quieras cobrar, vinculá + {MP_PROVIDER_NAME} + {' '} + desde Ajustes. Tu grupo ya quedó creado. + + )} +

+
- - - - ) - } + const status = statusQuery.data?.status ?? 'none' + const isConnected = status === 'active' + const connectedAt = formatMpConnectionDate(statusQuery.data?.connectedAt ?? null) return (
-

Elegí tu procesador de cobro

+

Conectá tus cobros

- Los pagos de tus miembros van a llegar por esta plataforma. + Vinculá tu cuenta de {MP_PROVIDER_NAME} y cobrale a tus miembros desde el grupo.

-
- {PAYMENT_PROVIDERS.map((provider) => { - const isSelected = selected === provider.value - return ( - - ) - })} -
- -
- -

- Por ahora la conexión se hace en modo prueba (sandbox). Más adelante vas a poder - vincular tu cuenta real de {selected === 'STRIPE' ? 'Stripe' : 'Mercado Pago'}. + {feedback?.kind === 'success' ? ( +

+ + Tu cuenta de {MP_PROVIDER_NAME} quedó vinculada.

+ ) : null} + + {feedback?.kind === 'error' ? ( +

+ {mpCallbackErrorMessage(feedback.reason)} +

+ ) : null} + +
+
+

{MP_PROVIDER_NAME}

+ {mpStatusLabel(status)} +
+ +
+ {statusQuery.isPending ? ( +

+ + Consultando tu cuenta… +

+ ) : isConnected ? ( +

+ {connectedAt ? `Vinculada el ${connectedAt}. ` : ''} + Los pagos de tus grupos van a entrar a esta cuenta. +

+ ) : ( +

+ Te llevamos a {MP_PROVIDER_NAME} para autorizar los cobros. Los pagos entran + directo en tu cuenta, sin intermediarios. +

+ )} +
+ +
+ +
- {connect.isError ? ( + {startAuthorization.error ? (

- No pudimos conectar la cuenta. Intentalo de nuevo. + {startAuthorization.error}

) : null}
- -
diff --git a/apps/web/src/features/onboarding/WelcomeStep.tsx b/apps/web/src/features/onboarding/WelcomeStep.tsx index 74021ac..136b4d1 100644 --- a/apps/web/src/features/onboarding/WelcomeStep.tsx +++ b/apps/web/src/features/onboarding/WelcomeStep.tsx @@ -10,7 +10,7 @@ const STEPS_TO_SETUP = [ { icon: Wallet, title: 'Conectá tu cuenta de cobro', - description: 'Mercado Pago o Stripe, en modo prueba por ahora.', + description: 'Vinculá Mercado Pago y cobrale a tus miembros desde el grupo.', }, { icon: Users, diff --git a/apps/web/src/features/onboarding/constants.ts b/apps/web/src/features/onboarding/constants.ts index 308199a..9ea72f7 100644 --- a/apps/web/src/features/onboarding/constants.ts +++ b/apps/web/src/features/onboarding/constants.ts @@ -1,5 +1,6 @@ -import type { BillingType, PaymentProvider, WeekDay } from '@gruperly/shared' -export { BILLING_LABELS, WEEK_DAY_FULL_LABELS, formatPrice, formatSchedule } from '../../lib/format' +import type { BillingType, WeekDay } from '@gruperly/shared' + +export { BILLING_LABELS, formatPrice, formatSchedule, WEEK_DAY_FULL_LABELS } from '../../lib/format' export const WEEK_DAYS: readonly WeekDay[] = [ 'MONDAY', @@ -21,23 +22,6 @@ export const WEEK_DAY_CHIPS: readonly { value: WeekDay; label: string }[] = [ { value: 'SUNDAY', label: 'Dom' }, ] -export const PAYMENT_PROVIDERS: readonly { - value: PaymentProvider - name: string - description: string -}[] = [ - { - value: 'MERCADO_PAGO', - name: 'Mercado Pago', - description: 'El procesador más usado en Latinoamérica', - }, - { - value: 'STRIPE', - name: 'Stripe', - description: 'Cobrá con tarjetas e internacionalmente', - }, -] - export const BILLING_TYPES: readonly { value: BillingType; label: string; hint: string }[] = [ { value: 'MONTHLY', label: 'Mensual', hint: 'Un cobro por mes' }, { value: 'PER_CLASS', label: 'Por clase', hint: 'Cada clase que asista' }, diff --git a/apps/web/src/features/settings/AppearanceCard.tsx b/apps/web/src/features/settings/AppearanceCard.tsx index df88949..f3fbfa0 100644 --- a/apps/web/src/features/settings/AppearanceCard.tsx +++ b/apps/web/src/features/settings/AppearanceCard.tsx @@ -1,6 +1,6 @@ import { Check } from 'lucide-react' -import { cn } from '../../lib/utils' import { useTheme } from '../../context/ThemeProvider' +import { cn } from '../../lib/utils' import { THEME_ICONS, THEME_OPTIONS } from './constants' export function AppearanceCard() { diff --git a/apps/web/src/features/settings/SettingsView.tsx b/apps/web/src/features/settings/SettingsView.tsx index 25b3212..72e5f77 100644 --- a/apps/web/src/features/settings/SettingsView.tsx +++ b/apps/web/src/features/settings/SettingsView.tsx @@ -1,7 +1,8 @@ import { Link } from '@tanstack/react-router' import { Fingerprint } from 'lucide-react' -import { signOut } from '../../lib/auth-client' import { Button } from '../../components/ui' +import { signOut } from '../../lib/auth-client' +import { MpStatusCard } from '../mp' import { AppearanceCard } from './AppearanceCard' export function SettingsView() { @@ -31,6 +32,8 @@ export function SettingsView() { + +