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.
This commit is contained in:
@@ -18,4 +18,16 @@ EMAIL_SERVER_HOST=""
|
||||
EMAIL_SERVER_PORT="587"
|
||||
EMAIL_SERVER_USER=""
|
||||
EMAIL_SERVER_PASSWORD=""
|
||||
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# 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=""
|
||||
@@ -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";
|
||||
@@ -18,7 +18,7 @@ model User {
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
merchantAccount MerchantAccount?
|
||||
mpAccount MpAccount?
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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<PrismaClient, 'group' | 'groupMember' | 'merchantAccount'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
@@ -23,14 +21,8 @@ export class CreateGroup {
|
||||
data: CreateGroupInput,
|
||||
userId: string,
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
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({
|
||||
|
||||
58
apps/backend/src/modules/mp/access-token.ts
Normal file
58
apps/backend/src/modules/mp/access-token.ts
Normal file
@@ -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<PrismaClient, 'mpAccount'>;
|
||||
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<Result<MpTokenAccount, ProblemDetails>> {
|
||||
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);
|
||||
}
|
||||
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
@@ -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;
|
||||
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
@@ -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<PrismaClient, 'mpOAuthState' | 'mpAccount'>;
|
||||
/** 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<Result<MpCallbackResult, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
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<MpCallbackResult, ProblemDetails> {
|
||||
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
|
||||
);
|
||||
}
|
||||
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
@@ -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;
|
||||
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
@@ -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<PrismaClient, 'mpOAuthState'> };
|
||||
|
||||
/** 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<Result<MpAuthorizationUrlDto, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
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),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
@@ -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;
|
||||
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
@@ -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<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/**
|
||||
* 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<Result<MpDisconnectResultDto, ProblemDetails>> {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
@@ -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;
|
||||
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
@@ -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<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/** 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<Result<MpStatusDto, ProblemDetails>> {
|
||||
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),
|
||||
});
|
||||
}
|
||||
}
|
||||
3
apps/backend/src/modules/mp/index.ts
Normal file
3
apps/backend/src/modules/mp/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { getMpAccessToken, type MpTokenAccount } from './access-token';
|
||||
export { startMpJobs } from './jobs';
|
||||
export { default as mpRoutes } from './routes';
|
||||
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
@@ -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';
|
||||
@@ -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<RefreshExpiringMpTokensResult> {
|
||||
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<LockedAccountRow[]>`
|
||||
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 };
|
||||
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
@@ -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<Result<MpTokenAccount, ProblemDetails>> {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
@@ -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();
|
||||
}
|
||||
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
@@ -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(),
|
||||
};
|
||||
}
|
||||
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
@@ -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:<iv>:<tag>:<ciphertext>`, 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');
|
||||
}
|
||||
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
@@ -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';
|
||||
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
@@ -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<MpTokenResponse> {
|
||||
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<MpTokenResponse> {
|
||||
return requestToken({
|
||||
grant_type: 'refresh_token',
|
||||
client_id: input.clientId,
|
||||
client_secret: input.clientSecret,
|
||||
refresh_token: input.refreshToken,
|
||||
});
|
||||
}
|
||||
|
||||
async function requestToken(body: Record<string, string>): Promise<MpTokenResponse> {
|
||||
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<string, unknown> | 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<string, unknown> | 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<string, unknown> | 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<string, unknown> | 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;
|
||||
}
|
||||
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
@@ -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();
|
||||
}
|
||||
16
apps/backend/src/modules/mp/routes.ts
Normal file
16
apps/backend/src/modules/mp/routes.ts
Normal file
@@ -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;
|
||||
@@ -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<PrismaClient, 'user' | 'merchantAccount'>;
|
||||
db?: Pick<PrismaClient, 'user'>;
|
||||
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({
|
||||
|
||||
@@ -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;
|
||||
@@ -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<Result<ConnectPaymentResult, ProblemDetails>> {
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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<PrismaClient, 'user' | 'mpAccount'> };
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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<void> {
|
||||
server.stop(true);
|
||||
await getPrismaClient().$disconnect();
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
1042
apps/backend/test/mp.test.ts
Normal file
1042
apps/backend/test/mp.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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',
|
||||
|
||||
Reference in New Issue
Block a user