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:
Jose Selesan
2026-10-07 12:00:38 -03:00
parent e03f510874
commit 21a4c69f38
64 changed files with 3154 additions and 425 deletions

View File

@@ -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({

View 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);
}

View 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;

View 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
);
}

View 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;

View 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),
}),
});
}
}

View 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;

View 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 });
}
}

View 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;

View 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),
});
}
}

View File

@@ -0,0 +1,3 @@
export { getMpAccessToken, type MpTokenAccount } from './access-token';
export { startMpJobs } from './jobs';
export { default as mpRoutes } from './routes';

View 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';

View File

@@ -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 };

View 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 });
}
}

View 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();
}

View 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(),
};
}

View 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');
}

View 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';

View 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;
}

View 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();
}

View 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;

View File

@@ -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({

View File

@@ -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;

View File

@@ -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,
});
}
}

View File

@@ -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 });
}

View File

@@ -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;