Files
gruperly/apps/backend/test/mp.test.ts
Jose Selesan 21a4c69f38 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.
2026-10-07 12:00:38 -03:00

1043 lines
38 KiB
TypeScript

import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
mpAccount: {
findUnique: mock(),
upsert: mock(),
update: mock(),
},
mpOAuthState: {
create: mock(),
findUnique: mock(),
deleteMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account';
import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
const ownerId = 'user-1';
const otherOwnerId = 'user-2';
const WEB_URL = 'http://localhost:6173';
/** A key of the right length; the value never matters for these tests. */
const ENCRYPTION_KEY = Buffer.alloc(32, 7).toString('base64');
// Set before the fixtures below seal anything at describe-body time.
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
const storedState = {
state: 'state-abc',
ownerId,
codeVerifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk',
returnTo: 'onboarding',
expiresAt: new Date(Date.now() + 10 * 60 * 1000),
};
/**
* The wire body Mercado Pago returns, not the parsed shape: `user_id` arrives
* as a number, which the parser has to cope with.
*/
const mpWireTokens = {
access_token: 'APP_USR-access-token',
refresh_token: 'TG-refresh-token',
expires_in: 15552000,
scope: 'offline_access read write',
user_id: 9876543210,
live_mode: true,
};
const MP_USER_ID = '9876543210';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/mp', mpRoutes);
return app;
}
function locationOf(res: Response): URL {
const location = res.headers.get('Location');
if (!location) throw new Error('the callback did not redirect');
return new URL(location);
}
describe('modules/mp', () => {
beforeEach(() => {
vi.clearAllMocks();
process.env.MP_CLIENT_ID = 'client-123';
process.env.MP_CLIENT_SECRET = 'secret-abc';
process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback';
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
process.env.WEB_URL = WEB_URL;
});
describe('GET /mp/status', () => {
it('reports none when the teacher has never linked an account', async () => {
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: ownerId }).request('/mp/status');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
status: 'none',
liveMode: false,
expiresAt: null,
connectedAt: null,
mpUserIdSuffix: null,
});
});
it('reports active without leaking tokens or the full Mercado Pago id', async () => {
const expiresAt = new Date('2027-03-01T12:00:00.000Z');
prisma.mpAccount.findUnique.mockResolvedValue({
id: 'mp-1',
ownerId,
mpUserId: '9876543210',
accessTokenEnc: 'v1:sealed',
refreshTokenEnc: 'v1:sealed',
expiresAt,
scope: 'offline_access read write',
liveMode: true,
status: 'ACTIVE',
connectedAt: new Date('2026-10-01T10:00:00.000Z'),
});
const res = await makeApp({ id: ownerId }).request('/mp/status');
const body = await res.json();
expect(body).toEqual({
status: 'active',
liveMode: true,
expiresAt: expiresAt.toISOString(),
connectedAt: '2026-10-01T10:00:00.000Z',
mpUserIdSuffix: '3210',
});
expect(JSON.stringify(body)).not.toContain('sealed');
expect(JSON.stringify(body)).not.toContain('9876543210');
expect(JSON.stringify(body)).not.toContain('offline_access');
});
it('reports requires_reauth when the renewal was refused', async () => {
prisma.mpAccount.findUnique.mockResolvedValue({
id: 'mp-1',
ownerId,
mpUserId: '9876543210',
expiresAt: new Date('2027-03-01T12:00:00.000Z'),
liveMode: false,
status: 'REQUIRES_REAUTH',
connectedAt: new Date('2026-10-01T10:00:00.000Z'),
});
const res = await makeApp({ id: ownerId }).request('/mp/status');
expect((await res.json()).status).toBe('requires_reauth');
});
it('reports none for a revoked row, since there is nothing usable left', async () => {
prisma.mpAccount.findUnique.mockResolvedValue({
id: 'mp-1',
ownerId,
mpUserId: '9876543210',
expiresAt: new Date(0),
liveMode: false,
status: 'REVOKED',
connectedAt: new Date('2026-10-01T10:00:00.000Z'),
});
const res = await makeApp({ id: ownerId }).request('/mp/status');
expect((await res.json()).status).toBe('none');
});
it('rejects without a session', async () => {
const res = await makeApp(null).request('/mp/status');
expect(res.status).toBe(401);
expect(await res.json()).toMatchObject({ code: 'unauthorized' });
});
});
describe('GET /mp/connect', () => {
it('builds a PKCE authorization URL and stores the state', async () => {
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 });
prisma.mpOAuthState.create.mockResolvedValue({});
const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=onboarding');
expect(res.status).toBe(200);
const { authorizationUrl } = (await res.json()) as { authorizationUrl: string };
const url = new URL(authorizationUrl);
expect(`${url.origin}${url.pathname}`).toBe(
'https://auth.mercadopago.com/authorization',
);
expect(url.searchParams.get('client_id')).toBe('client-123');
expect(url.searchParams.get('response_type')).toBe('code');
expect(url.searchParams.get('platform_id')).toBe('mp');
expect(url.searchParams.get('redirect_uri')).toBe(
'http://localhost:4000/api/v1/mp/callback',
);
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
expect(url.searchParams.get('scope')).toBe('offline_access read write');
const state = url.searchParams.get('state');
const challenge = url.searchParams.get('code_challenge');
expect(state).toBeTruthy();
expect(challenge).toBeTruthy();
const created = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data;
expect(created.state).toBe(state);
expect(created.ownerId).toBe(ownerId);
expect(created.returnTo).toBe('onboarding');
// Only the challenge is public: the verifier stays in the row.
expect(created.codeVerifier).toBeTruthy();
expect(codeChallengeFromVerifier(created.codeVerifier)).toBe(challenge);
expect(created.expiresAt.getTime()).toBeGreaterThan(Date.now() + 9 * 60 * 1000);
});
it('never puts the code verifier in the URL it hands to the browser', async () => {
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 });
prisma.mpOAuthState.create.mockResolvedValue({});
const res = await makeApp({ id: ownerId }).request('/mp/connect');
const { authorizationUrl } = (await res.json()) as { authorizationUrl: string };
const verifier = prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.codeVerifier;
expect(authorizationUrl).not.toContain(verifier);
});
it('sweeps expired states and the previous attempt of the same teacher', async () => {
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 2 });
prisma.mpOAuthState.create.mockResolvedValue({});
await makeApp({ id: ownerId }).request('/mp/connect');
const where = prisma.mpOAuthState.deleteMany.mock.calls[0]?.[0]?.where;
expect(where.OR).toHaveLength(2);
expect(where.OR).toContainEqual({ ownerId });
});
it('defaults the return target to settings', async () => {
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 });
prisma.mpOAuthState.create.mockResolvedValue({});
await makeApp({ id: ownerId }).request('/mp/connect');
expect(prisma.mpOAuthState.create.mock.calls[0]?.[0]?.data.returnTo).toBe('settings');
});
it('rejects a return target outside the enum', async () => {
const res = await makeApp({ id: ownerId }).request('/mp/connect?returnTo=https://evil.test');
expect(res.status).toBe(400);
expect(prisma.mpOAuthState.create).not.toHaveBeenCalled();
});
it('rejects without a session', async () => {
const res = await makeApp(null).request('/mp/connect');
expect(res.status).toBe(401);
expect(prisma.mpOAuthState.create).not.toHaveBeenCalled();
});
it('reports a configuration problem when the credentials are missing', async () => {
delete process.env.MP_CLIENT_ID;
const res = await makeApp({ id: ownerId }).request('/mp/connect');
expect(res.status).toBe(503);
expect(await res.json()).toMatchObject({ code: 'mp_not_configured' });
expect(prisma.mpOAuthState.create).not.toHaveBeenCalled();
});
});
describe('GET /mp/callback', () => {
const callbackUrl = (query: string) => `/mp/callback${query}`;
/**
* The route builds the use-case itself, so `fetch` is the seam: this
* answers Mercado Pago's token endpoint and hands back the restore function.
*/
function stubTokenEndpoint(
answer: Response | Error,
): { calls: Array<Record<string, unknown>>; restore: () => void } {
const calls: Array<Record<string, unknown>> = [];
const original = globalThis.fetch;
globalThis.fetch = mock(async (_url: unknown, init: RequestInit) => {
calls.push(JSON.parse(String(init.body)) as Record<string, unknown>);
if (answer instanceof Error) throw answer;
return answer.clone();
}) as unknown as typeof fetch;
return {
calls,
restore: () => {
globalThis.fetch = original;
},
};
}
function tokenResponse(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
it('exchanges the code and stores the tokens encrypted', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('mp')).toBe('success');
const { create: data } = prisma.mpAccount.upsert.mock.calls[0]?.[0] ?? {};
expect(data.ownerId).toBe(ownerId);
expect(data.mpUserId).toBe(MP_USER_ID);
expect(data.status).toBe('ACTIVE');
expect(data.liveMode).toBe(true);
expect(data.scope).toBe('offline_access read write');
// Encrypted at rest: the ciphertext is not the token.
expect(data.accessTokenEnc).not.toBe(mpWireTokens.access_token);
expect(data.refreshTokenEnc).not.toBe(mpWireTokens.refresh_token);
expect(String(data.accessTokenEnc).startsWith('v1:')).toBe(true);
expect(openToken(data.accessTokenEnc)).toBe(mpWireTokens.access_token);
expect(openToken(data.refreshTokenEnc)).toBe(mpWireTokens.refresh_token);
// expires_at comes from expires_in, not from a guess.
const expected = Date.now() + mpWireTokens.expires_in * 1000;
expect(Math.abs(data.expiresAt.getTime() - expected)).toBeLessThan(5_000);
});
it('sends the verifier and the exact redirect_uri to Mercado Pago', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(res.status).toBe(302);
expect(stub.calls[0]).toEqual({
grant_type: 'authorization_code',
client_id: 'client-123',
client_secret: 'secret-abc',
code: 'auth-code-123',
redirect_uri: 'http://localhost:4000/api/v1/mp/callback',
code_verifier: storedState.codeVerifier,
});
});
it('lands the teacher back on the onboarding step they left', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(locationOf(res).pathname).toBe('/onboarding');
});
it('still redirects when Mercado Pago appends query params we do not model', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc&error_description=&foo=bar'),
);
stub.restore();
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('mp')).toBe('success');
});
it('refuses an unknown state and never calls Mercado Pago', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(null);
const fetchMock = mock();
const original = globalThis.fetch;
globalThis.fetch = fetchMock as unknown as typeof fetch;
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=forged'),
);
globalThis.fetch = original;
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('mp')).toBe('error');
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(fetchMock).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('refuses an expired state without touching Mercado Pago', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue({
...storedState,
expiresAt: new Date(Date.now() - 1000),
});
const fetchMock = mock();
const original = globalThis.fetch;
globalThis.fetch = fetchMock as unknown as typeof fetch;
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
globalThis.fetch = original;
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(fetchMock).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('refuses a replayed state, even with a valid looking code', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
// Already consumed by the first callback: the delete matches nothing.
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 0 });
const fetchMock = mock();
const original = globalThis.fetch;
globalThis.fetch = fetchMock as unknown as typeof fetch;
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
globalThis.fetch = original;
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(fetchMock).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('refuses a callback without a code', async () => {
const res = await makeApp({ id: ownerId }).request(callbackUrl('?state=state-abc'));
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
});
it('treats a rejected consent screen as mp_denied and burns the state', async () => {
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
const fetchMock = mock();
const original = globalThis.fetch;
globalThis.fetch = fetchMock as unknown as typeof fetch;
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?error=access_denied&error_description=user_denied&state=state-abc'),
);
globalThis.fetch = original;
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('mp')).toBe('error');
expect(locationOf(res).searchParams.get('reason')).toBe('mp_denied');
expect(prisma.mpOAuthState.deleteMany).toHaveBeenCalledWith({
where: { state: 'state-abc' },
});
expect(fetchMock).not.toHaveBeenCalled();
});
it('refuses when the Mercado Pago account belongs to another teacher', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-9', ownerId: otherOwnerId });
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use');
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('maps the unique index violation to the same clear error', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockRejectedValue({ code: 'P2002' });
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(locationOf(res).searchParams.get('reason')).toBe('mp_account_in_use');
});
it('lets a teacher re-link their own account', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId });
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(locationOf(res).searchParams.get('mp')).toBe('success');
const args = prisma.mpAccount.upsert.mock.calls[0]?.[0];
expect(args.where).toEqual({ ownerId });
// Re-linking renews the credentials and clears a `requires_reauth`.
expect(args.update.status).toBe('ACTIVE');
expect(args.update.connectedAt).toBeInstanceOf(Date);
});
it('reports mp_error when Mercado Pago rejects the exchange', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
const original = globalThis.fetch;
globalThis.fetch = mock(
async () =>
new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 }),
) as unknown as typeof fetch;
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
globalThis.fetch = original;
expect(locationOf(res).searchParams.get('reason')).toBe('mp_error');
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('reports mp_error when Mercado Pago is unreachable', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
const stub = stubTokenEndpoint(new Error('ECONNREFUSED'));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=auth-code-123&state=state-abc'),
);
stub.restore();
expect(locationOf(res).searchParams.get('reason')).toBe('mp_error');
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('never puts the code or the verifier in the redirect it sends the browser to', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue(storedState);
prisma.mpOAuthState.deleteMany.mockResolvedValue({ count: 1 });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.mpAccount.upsert.mockResolvedValue({});
const stub = stubTokenEndpoint(tokenResponse(mpWireTokens));
const res = await makeApp({ id: ownerId }).request(
callbackUrl('?code=super-secret-code&state=state-abc'),
);
stub.restore();
const location = locationOf(res);
expect(location.search).toContain('mp=success');
expect(location.href).not.toContain('super-secret-code');
expect(location.href).not.toContain(storedState.codeVerifier);
});
it('sends a teacher without a session to the login screen', async () => {
const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc'));
expect(res.status).toBe(302);
expect(locationOf(res).pathname).toBe('/login');
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
});
describe('DELETE /mp/connect', () => {
it('revokes the account and blanks the tokens', async () => {
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId });
prisma.mpAccount.update.mockResolvedValue({});
const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ disconnected: true });
expect(prisma.mpAccount.update).toHaveBeenCalledWith({
where: { ownerId },
data: {
status: 'REVOKED',
accessTokenEnc: '',
refreshTokenEnc: '',
expiresAt: new Date(0),
},
});
});
it('is a no-op when there is nothing linked', async () => {
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: ownerId }).request('/mp/connect', { method: 'DELETE' });
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ disconnected: false });
expect(prisma.mpAccount.update).not.toHaveBeenCalled();
});
it('rejects without a session', async () => {
const res = await makeApp(null).request('/mp/connect', { method: 'DELETE' });
expect(res.status).toBe(401);
});
});
});
describe('modules/mp encryption and PKCE', () => {
beforeEach(() => {
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
});
it('round-trips a token through seal and open', () => {
const token = 'APP_USR-very-long-mercadopago-access-token';
const sealed = sealToken(token);
expect(sealed.startsWith('v1:')).toBe(true);
expect(sealed).not.toContain(token);
expect(openToken(sealed)).toBe(token);
});
it('produces a different ciphertext every time', () => {
expect(sealToken('same-token')).not.toBe(sealToken('same-token'));
});
it('refuses a tampered payload instead of returning garbage', () => {
const sealed = sealToken('token');
const [version, iv, tag, ciphertext = ''] = sealed.split(':');
if (!version || !iv || !tag || !ciphertext) throw new Error('unexpected payload shape');
// Flip the first ciphertext byte: the trailing base64url char of a GCM tag
// only carries two significant bits, so editing that one can decode back to
// the original tag and the payload would still verify.
const tampered = `${ciphertext[0] === 'A' ? 'B' : 'A'}${ciphertext.slice(1)}`;
expect(() => openToken(`${version}:${iv}:${tag}:${tampered}`)).toThrow();
});
it('refuses an unknown payload version', () => {
expect(() => openToken('v9:aaa:bbb:ccc')).toThrow('Unsupported token payload');
});
it('refuses to work without a key of 32 bytes', () => {
process.env.TOKEN_ENCRYPTION_KEY = Buffer.alloc(16, 7).toString('base64');
expect(() => sealToken('token')).toThrow('must decode to 32 bytes');
});
it('derives the S256 challenge from the RFC 7636 test vector', () => {
expect(codeChallengeFromVerifier('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe(
'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
);
});
});
describe('modules/mp access token', () => {
const activeAccount = {
id: 'mp-1',
ownerId,
status: 'ACTIVE',
accessTokenEnc: sealToken('APP_USR-current-token'),
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
};
beforeEach(() => {
process.env.MP_CLIENT_ID = 'client-123';
process.env.MP_CLIENT_SECRET = 'secret-abc';
process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback';
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
});
it('fails with mp_not_connected when the teacher never linked an account', async () => {
const db = { mpAccount: { findUnique: mock(async () => null) } };
const result = await getMpAccessToken(ownerId, {
db: db as unknown as Parameters<typeof getMpAccessToken>[1] extends undefined
? never
: never,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_not_connected');
});
it('tells mp_not_connected and mp_requires_reauth apart', async () => {
const notActive = { ...activeAccount, status: 'REQUIRES_REAUTH' };
const refresh = { execute: mock() };
const result = await getMpAccessToken(ownerId, {
db: { mpAccount: { findUnique: mock(async () => notActive) } } as never,
refresh: refresh as never,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth');
// A locked account is never "fixed" by quietly attempting a renewal.
expect(refresh.execute).not.toHaveBeenCalled();
});
it('decrypts a token that is still fresh, without calling Mercado Pago', async () => {
const refresh = { execute: mock() };
const result = await getMpAccessToken(ownerId, {
db: { mpAccount: { findUnique: mock(async () => activeAccount) } } as never,
refresh: refresh as never,
});
expect(result).toEqual({
ok: true,
value: { accountId: 'mp-1', accessToken: 'APP_USR-current-token', expiresAt: activeAccount.expiresAt },
});
expect(refresh.execute).not.toHaveBeenCalled();
});
it('renews on demand when the token is about to expire', async () => {
const stale = { ...activeAccount, expiresAt: new Date(Date.now() + 60 * 1000) };
const renewed = {
ok: true as const,
value: {
accountId: 'mp-1',
accessToken: 'APP_USR-fresh-token',
expiresAt: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000),
},
};
const result = await getMpAccessToken(ownerId, {
db: { mpAccount: { findUnique: mock(async () => stale) } } as never,
refresh: { execute: mock(async () => renewed) } as never,
});
expect(result).toEqual(renewed);
});
it('passes the renewal failure through instead of returning a stale token', async () => {
const stale = { ...activeAccount, expiresAt: new Date(Date.now() - 1000) };
const failed = {
ok: false as const,
error: {
type: 'x',
title: 'Conflict',
status: 409,
detail: 'd',
code: 'mp_requires_reauth',
},
};
const result = await getMpAccessToken(ownerId, {
db: { mpAccount: { findUnique: mock(async () => stale) } } as never,
refresh: { execute: mock(async () => failed) } as never,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth');
});
});
describe('modules/mp RefreshMpAccount', () => {
const account = {
id: 'mp-1',
ownerId,
status: 'ACTIVE',
accessTokenEnc: sealToken('APP_USR-old-access'),
refreshTokenEnc: sealToken('TG-old-refresh'),
scope: 'offline_access read write',
};
beforeEach(() => {
process.env.MP_CLIENT_ID = 'client-123';
process.env.MP_CLIENT_SECRET = 'secret-abc';
process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback';
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
});
function makeStore(overrides: Record<string, unknown> = {}) {
return {
mpAccount: {
findUnique: mock(async () => account),
update: mock(async () => ({})),
...overrides,
},
};
}
it('sends the stored refresh token and stores both new tokens', async () => {
const store = makeStore();
const refresh = mock(async () => ({
accessToken: 'APP_USR-new-access',
refreshToken: 'TG-new-refresh',
expiresInSeconds: 15552000,
scope: 'offline_access read write',
mpUserId: MP_USER_ID,
liveMode: true,
}));
const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute(
'mp-1',
);
expect(result).toEqual({
ok: true,
value: {
accountId: 'mp-1',
accessToken: 'APP_USR-new-access',
expiresAt: expect.any(Date) as unknown as Date,
},
});
// `webUrl` rides along in the config object but is never part of the
// request: `refreshMpTokens` picks the three fields the endpoint needs.
expect(refresh).toHaveBeenCalledWith({
clientId: 'client-123',
clientSecret: 'secret-abc',
redirectUri: 'http://localhost:4000/api/v1/mp/callback',
webUrl: 'http://localhost:6173',
refreshToken: 'TG-old-refresh',
});
const data = store.mpAccount.update.mock.calls[0]?.[0]?.data;
// Mercado Pago rotates the refresh token: keeping the old one would break
// the next renewal.
expect(openToken(data.refreshTokenEnc)).toBe('TG-new-refresh');
expect(openToken(data.accessTokenEnc)).toBe('APP_USR-new-access');
expect(data.status).toBe('ACTIVE');
});
it('keeps the stored scope when the renewal omits it', async () => {
const store = makeStore();
const refresh = mock(async () => ({
accessToken: 'APP_USR-new-access',
refreshToken: 'TG-new-refresh',
expiresInSeconds: 15552000,
scope: null,
mpUserId: MP_USER_ID,
liveMode: true,
}));
await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute('mp-1');
expect(store.mpAccount.update.mock.calls[0]?.[0]?.data.scope).toBe(
'offline_access read write',
);
});
it('marks the account REQUIRES_REAUTH when Mercado Pago says invalid_grant', async () => {
const store = makeStore();
const refresh = mock(async () => {
throw new MpApiError(401, 'invalid_grant');
});
const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute(
'mp-1',
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth');
expect(store.mpAccount.update).toHaveBeenCalledWith({
where: { id: 'mp-1' },
data: { status: 'REQUIRES_REAUTH' },
});
});
it('leaves the account untouched on a server error, so tomorrow can retry', async () => {
const store = makeStore();
const refresh = mock(async () => {
throw new MpApiError(500, null);
});
const result = await new RefreshMpAccount({ db: store as never, refresh: refresh as never }).execute(
'mp-1',
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_provider_error');
expect(store.mpAccount.update).not.toHaveBeenCalled();
});
it('reports the account when it disappears mid-run', async () => {
const store = makeStore({ findUnique: mock(async () => null) });
const result = await new RefreshMpAccount({
db: store as never,
refresh: mock(async () => {
throw new Error('should not be called');
}) as never,
}).execute('mp-1');
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('mp_requires_reauth');
});
});
describe('modules/mp RefreshExpiringMpTokens', () => {
beforeEach(() => {
process.env.MP_CLIENT_ID = 'client-123';
process.env.MP_CLIENT_SECRET = 'secret-abc';
process.env.MP_REDIRECT_URI = 'http://localhost:4000/api/v1/mp/callback';
process.env.TOKEN_ENCRYPTION_KEY = ENCRYPTION_KEY;
});
/**
* Fakes the transaction client, capturing the tagged-template SQL. The store
* hangs off the `tx` the job forwards, since the writes have to join the
* transaction holding the lock.
*/
function makeJobDb(rows: Array<{ id: string }>, store: { mpAccount: unknown }) {
const captured: { sql: string; values: unknown[] } = { sql: '', values: [] };
const db = {
$transaction: mock(async (cb: (tx: unknown) => Promise<unknown>) =>
cb({
mpAccount: store.mpAccount,
$queryRaw: (strings: TemplateStringsArray, ...values: unknown[]) => {
captured.sql = strings.join('?');
captured.values = values;
return Promise.resolve(rows);
},
}),
),
};
return { db, captured };
}
const refreshOk = mock(async () => ({
accessToken: 'APP_USR-new-access',
refreshToken: 'TG-new-refresh',
expiresInSeconds: 15552000,
scope: 'offline_access read write',
mpUserId: MP_USER_ID,
liveMode: true,
}));
function activeRow(id: string) {
return {
id,
ownerId,
status: 'ACTIVE',
accessTokenEnc: sealToken('APP_USR-old-access'),
refreshTokenEnc: sealToken('TG-old-refresh'),
scope: 'offline_access read write',
};
}
function jobDbReturning(rows: Array<{ id: string }>) {
const store = {
mpAccount: {
findUnique: mock(async ({ where }: { where: { id: string } }) => activeRow(where.id)),
update: mock(async () => ({})),
},
};
const { db, captured } = makeJobDb(rows, store);
return { db: db as never, captured, store };
}
it('selects only accounts expiring inside the 30 day window', async () => {
const { db, captured } = jobDbReturning([]);
await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute();
// Active accounts only, and anything closer than 30 days from expiring.
expect(captured.sql).toContain(`"status" = 'ACTIVE'`);
expect(captured.sql).toContain('"expires_at" <');
// No lower bound on the window: a token that already expired is exactly the
// one worth recovering, as long as the grant is still alive.
expect(captured.sql).not.toContain('"expires_at" >');
// Bounded work per run.
expect(captured.sql).toContain('FOR UPDATE SKIP LOCKED');
expect(captured.sql).toContain('ORDER BY "expires_at" ASC');
const [horizon, limit] = captured.values;
expect(horizon).toBeInstanceOf(Date);
const daysAhead = ((horizon as Date).getTime() - Date.now()) / (24 * 60 * 60 * 1000);
expect(daysAhead).toBeGreaterThan(29.9);
expect(daysAhead).toBeLessThan(30.1);
expect(limit).toBe(20);
});
it('renews the accounts the query returned and counts them', async () => {
const { db, store } = jobDbReturning([{ id: 'mp-1' }, { id: 'mp-2' }]);
const totals = await new RefreshExpiringMpTokens({ db, refresh: refreshOk as never }).execute();
expect(totals).toEqual({ refreshed: 2, requiresReauth: 0, failed: 0 });
expect(store.mpAccount.update).toHaveBeenCalledTimes(2);
});
it('separates accounts that need a new authorization from transient failures', async () => {
const mixed = mock(async ({ refreshToken }: { refreshToken: string }) => {
if (refreshToken === 'TG-old-refresh') throw new MpApiError(500, null);
if (refreshToken === 'TG-dead-refresh') throw new MpApiError(401, 'invalid_grant');
return {
accessToken: 'APP_USR-new-access',
refreshToken: 'TG-new-refresh',
expiresInSeconds: 15552000,
scope: null,
mpUserId: MP_USER_ID,
liveMode: true,
};
});
const store = {
mpAccount: {
findUnique: mock(async ({ where }: { where: { id: string } }) => {
// mp-1: Mercado Pago is having a bad day. mp-2: the grant is dead.
// mp-3: renews fine.
const token =
where.id === 'mp-2' ? 'TG-dead-refresh' : where.id === 'mp-3' ? 'TG-live-refresh' : 'TG-old-refresh';
return { ...activeRow(where.id), refreshTokenEnc: sealToken(token) };
}),
update: mock(async () => ({})),
},
};
const { db } = makeJobDb(
[{ id: 'mp-1' }, { id: 'mp-2' }, { id: 'mp-3' }],
store as unknown as { mpAccount: unknown },
);
const totals = await new RefreshExpiringMpTokens({
db: db as never,
refresh: mixed as never,
}).execute();
expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 });
});
});