@miguelmorales13/nestkit 0.28.0 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -0
- package/dist/chunk-33KFVAUZ.cjs +151 -0
- package/dist/chunk-LU3HO7B3.js +151 -0
- package/dist/payments/connect/credentials-cipher.d.ts +14 -0
- package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
- package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
- package/dist/payments/connect/online-checkout.d.ts +69 -0
- package/dist/payments/connect/rejection.d.ts +7 -0
- package/dist/payments/connect/status.d.ts +20 -0
- package/dist/payments/connect/terminal-connections.d.ts +291 -0
- package/dist/payments/index.cjs +1394 -3
- package/dist/payments/index.d.ts +14 -0
- package/dist/payments/index.js +1392 -1
- package/dist/payments/openpay/openpay-api.d.ts +127 -0
- package/dist/payments/openpay/openpay-connections.d.ts +201 -0
- package/dist/security/index.cjs +27 -152
- package/dist/security/index.js +13 -138
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1152,6 +1152,123 @@ await (pagos as ClipTerminalPayments).setKioskMode(['PP35542235000286'], { enabl
|
|
|
1152
1152
|
await (pagos as ClipTerminalPayments).cancelByTerminal('PP35542235000286'); // si quedó algo colgado
|
|
1153
1153
|
```
|
|
1154
1154
|
|
|
1155
|
+
#### Conexiones de terminal: todo lo que rodea a los adaptadores (`TerminalConnections`)
|
|
1156
|
+
|
|
1157
|
+
Los adaptadores cobran; **conectar a cada vendedor, guardar sus llaves, elegir su terminal, esperar el aviso y
|
|
1158
|
+
devolver el dinero** es lo que una app termina escribiendo a mano (~1.500 líneas). `TerminalConnections` lo trae
|
|
1159
|
+
hecho para un sistema **multi-cliente** (tienda, sucursal, empresa): vos ponés dónde se guardan las filas y
|
|
1160
|
+
la llave de cifrado; el resto es configuración.
|
|
1161
|
+
|
|
1162
|
+
```ts
|
|
1163
|
+
import {
|
|
1164
|
+
TerminalConnections, CredentialsCipher, MercadoPagoConnect,
|
|
1165
|
+
type TerminalConnectionStore,
|
|
1166
|
+
} from '@miguelmorales13/nestkit/payments';
|
|
1167
|
+
|
|
1168
|
+
// 1. Dónde viven las conexiones — cualquier tabla (el contrato está en el tipo).
|
|
1169
|
+
class MiAlmacen implements TerminalConnectionStore { /* list, find, insert, update, delete, setPrimary,
|
|
1170
|
+
findByWebhookToken, listActiveByProvider */ }
|
|
1171
|
+
|
|
1172
|
+
// 2. Armarlo una vez.
|
|
1173
|
+
const terminales = new TerminalConnections({
|
|
1174
|
+
store: new MiAlmacen(),
|
|
1175
|
+
cipher: CredentialsCipher.fromHex(process.env.APP_ENCRYPTION_KEY), // null → la función se apaga sola
|
|
1176
|
+
fetchImpl: (proveedor, tenantId) => miFetchConReintentos(proveedor, tenantId),
|
|
1177
|
+
mercadoPagoConnect: () => new MercadoPagoConnect({ clientId, clientSecret, redirectUri }),
|
|
1178
|
+
mercadoPagoWebhookSecret: process.env.MERCADOPAGO_WEBHOOK_SECRET,
|
|
1179
|
+
stateSecret: process.env.JWT_ACCESS_SECRET,
|
|
1180
|
+
publicWebhookUrl: (token) => `https://api.tuapp.com/terminal/clip/webhook/${token}`,
|
|
1181
|
+
describeScope: async (tenantId) => ({ name: (await tiendas.get(tenantId)).nombre }),
|
|
1182
|
+
onPaymentChanged: (tenantId, pagoId, cobro) => sse.publicar(tenantId, 'cobro', pagoId, cobro),
|
|
1183
|
+
});
|
|
1184
|
+
|
|
1185
|
+
// 3. Usarlo.
|
|
1186
|
+
await terminales.connectClip(tenantId, { apiKey, secretKey }); // verifica las llaves
|
|
1187
|
+
const { url, csrf } = terminales.mercadoPagoAuthorizationUrl(tenantId, userId); // OAuth: csrf → cookie httpOnly
|
|
1188
|
+
await terminales.completeMercadoPagoOAuth(code, state, cookie); // en el callback
|
|
1189
|
+
await terminales.chooseTerminal(tenantId, id, terminalId); // MP: crea Sucursal/Caja y pasa a PDV
|
|
1190
|
+
const cobro = await terminales.charge(tenantId, id, 12_500, ventaId); // mínimo por proveedor, idempotente
|
|
1191
|
+
await terminales.handleClipNotice(token, body.id); // webhooks: nunca lanzan, siempre 200
|
|
1192
|
+
await terminales.handleMercadoPagoNotice({ dataIdQuery, xSignature, xRequestId, body });
|
|
1193
|
+
await terminales.refundMercadoPago(tenantId, { orderId, amountCents, key, providerRefundId: null, claimed: [] });
|
|
1194
|
+
```
|
|
1195
|
+
|
|
1196
|
+
Qué resuelve por vos, y por qué cada cosa existe:
|
|
1197
|
+
|
|
1198
|
+
- **Secretos cifrados** (AES-256-GCM, `CredentialsCipher`); la API nunca devuelve una llave (`ConnectionView`
|
|
1199
|
+
no las tiene). Sin llave de cifrado, `available === false` y nada intenta cobrar.
|
|
1200
|
+
- **Renovación del token de Mercado Pago** 5 min antes de caducar, guardando el `refresh_token` nuevo (rota).
|
|
1201
|
+
- **Aprovisionamiento**: reutiliza la Sucursal/Caja que la terminal ya trae antes de crear otra, y rechaza con
|
|
1202
|
+
`MERCADOPAGO_TERMINAL_NO_SOPORTADA` una Point Air (solo Smart 1 y 2 operan por API). Si algo falla no bloquea la elección.
|
|
1203
|
+
- **Estados que el adaptador no entiende** (`processing`, `partially_refunded`, un `status` nuevo de Clip) se
|
|
1204
|
+
resuelven con `resolveTerminalStatus` en vez de dejar la caja en «Esperando…» con el cobro ya hecho.
|
|
1205
|
+
- **Avisos**: el webhook solo dispara; se consulta al proveedor con las llaves del cliente y `onPaymentChanged`
|
|
1206
|
+
corre una vez por cambio de estado. Mercado Pago: firma `x-signature` (`verifyMercadoPagoSignature`) y el
|
|
1207
|
+
`user_id` ubica a los clientes; Clip: token en la URL, en tiempo constante.
|
|
1208
|
+
- **Reembolsos de Mercado Pago** (API de órdenes): llave de idempotencia estable por reembolso (24 h), parcial vs
|
|
1209
|
+
total, errores oficiales clasificados en definitivos (con texto claro) y transitorios (quedan `pending`). Nunca
|
|
1210
|
+
lanza por el proveedor y nunca da por hecho un reembolso que la orden no muestra.
|
|
1211
|
+
- **Checkout en línea** (`OnlineCheckoutClient` + `checkoutCredentials`): enlace de Checkout Pro / Clip Checkout con
|
|
1212
|
+
las llaves del vendedor, y consulta del estado leyéndolo siempre del proveedor.
|
|
1213
|
+
|
|
1214
|
+
Errores con código estable: `TERMINAL_NO_DISPONIBLE`, `TERMINAL_NO_CONECTADA`, `TERMINAL_NO_ENCONTRADA`,
|
|
1215
|
+
`TERMINAL_SIN_ELEGIR`, `TERMINAL_CREDENCIALES`, `MONTO_MINIMO_TERMINAL`, `MERCADOPAGO_NO_CONFIGURADO`,
|
|
1216
|
+
`MERCADOPAGO_STATE_INVALIDO`, `MERCADOPAGO_TERMINAL_NO_SOPORTADA`, `PAGO_SIN_PROVEEDOR`, `PAGO_PROVEEDOR_ERROR`.
|
|
1217
|
+
Los textos que lee una persona traen un valor en español y se pueden reemplazar (`messages`, `refundMessages`,
|
|
1218
|
+
`OnlineCheckoutClient({ messages })`) para traducirlos con `t()`.
|
|
1219
|
+
|
|
1220
|
+
Es una clase sin dependencia de Nest: envolvela en tu propio servicio para el plan, la auditoría y los eventos de tu
|
|
1221
|
+
dominio. El formato de las credenciales guardadas (`MercadoPagoCredentials`: `accessToken`, `refreshToken`,
|
|
1222
|
+
`mpUserId`, `expira`, `mpStoreId`, `mpPosId`) es el persistido: no lo renombres si ya tenés filas.
|
|
1223
|
+
|
|
1224
|
+
#### Cobro con Openpay: el comercio inicia sesión y listo (`OpenpayConnections`)
|
|
1225
|
+
|
|
1226
|
+
Para que **cada comercio cobre en su propia cuenta de Openpay (BBVA) sin copiar llaves**: el comercio toca «Conectar»,
|
|
1227
|
+
Openpay le deja elegir «usar mi cuenta» (inicia sesión y autoriza) o «cuenta nueva» (se registra ahí mismo) y vuelve a tu
|
|
1228
|
+
app ya conectado. Es el esquema de *partners* con OAuth 2 de Openpay: recibís el `merchant_id` y las llaves del comercio,
|
|
1229
|
+
y cobrás **a su nombre**; el dinero cae en su cuenta, nunca pasa por la tuya.
|
|
1230
|
+
|
|
1231
|
+
```ts
|
|
1232
|
+
import { OpenpayConnections, CredentialsCipher } from '@miguelmorales13/nestkit/payments';
|
|
1233
|
+
|
|
1234
|
+
const openpay = new OpenpayConnections({
|
|
1235
|
+
store, // tu tabla: find / upsert / update / delete / findByWebhookToken
|
|
1236
|
+
cipher: () => CredentialsCipher.fromHex(process.env.APP_ENCRYPTION_KEY),
|
|
1237
|
+
partner: () => ({ clientId, clientSecret, redirectUri }), // el correo que manda Openpay al registrarte como integrador
|
|
1238
|
+
sandbox: () => process.env.OPENPAY_SANDBOX === 'true',
|
|
1239
|
+
stateSecret: () => process.env.JWT_SECRET,
|
|
1240
|
+
publicWebhookUrl: (token) => `https://api.tuapp.mx/api/v1/openpay/avisos/${token}`,
|
|
1241
|
+
fetchImpl: () => fetchResiliente, // tiempos límite / reintentos / alertas
|
|
1242
|
+
});
|
|
1243
|
+
|
|
1244
|
+
openpay.authorizationUrl(tiendaId, { returnTo: '/ajustes' }); // → redirige al comercio
|
|
1245
|
+
await openpay.complete({ code, state, error }); // callback: guarda llaves cifradas + registra el webhook
|
|
1246
|
+
const p = await openpay.createPayment(tiendaId, {
|
|
1247
|
+
method: 'transfer', // o 'card'
|
|
1248
|
+
reference: pedido.id, description: 'Pedido 123', amountCents: 25_000,
|
|
1249
|
+
returnUrl, // solo tarjeta
|
|
1250
|
+
});
|
|
1251
|
+
// card → p.url es el formulario de Openpay (se manda por WhatsApp, correo, QR…)
|
|
1252
|
+
// transfer → p.transfer = { clabe, reference (20 dígitos), bank, agreement, dueDate }; p.url = recibo imprimible
|
|
1253
|
+
await openpay.lookup(tiendaId, p.chargeId); // estado leído de Openpay: paid | pending | failed | refunded
|
|
1254
|
+
await openpay.refund(tiendaId, chargeId, centavos?); // solo tarjeta (Openpay no devuelve SPEI)
|
|
1255
|
+
await openpay.handleNotice(token, req.headers.authorization, req.body); // webhook: nunca le cree al cuerpo, relee el cargo
|
|
1256
|
+
```
|
|
1257
|
+
|
|
1258
|
+
Cosas que conviene saber:
|
|
1259
|
+
|
|
1260
|
+
- **La transferencia es SPEI con CLABE + referencia de 20 dígitos**; la referencia va en el concepto y es lo que Openpay
|
|
1261
|
+
usa para saber de qué cobro es. Vence a los días que pongas (máximo 30) y Openpay expira en días hábiles.
|
|
1262
|
+
- **El webhook lo registra la librería** con la llave del comercio y autenticación Basic (usuario = token de la URL,
|
|
1263
|
+
contraseña = una por comercio). Si no se pudo registrar, la conexión queda y `lookup` sigue diciendo la verdad;
|
|
1264
|
+
`ensureNotices(tiendaId)` lo reintenta.
|
|
1265
|
+
- `handleNotice` responde siempre algo que debes contestar con 200; solo lanza ante una contraseña mala. Un abono de saldo
|
|
1266
|
+
del propio comercio (`spei.received` sin pedido) se ignora.
|
|
1267
|
+
- Las llaves del comercio van **cifradas** con `CredentialsCipher`; el sandbox y producción no se mezclan (cada conexión
|
|
1268
|
+
recuerda de cuál es).
|
|
1269
|
+
- Las cifras y flujos salen de la documentación pública de Openpay; el registro como *partner* y el paso a producción son
|
|
1270
|
+
trámites tuyos con Openpay.
|
|
1271
|
+
|
|
1155
1272
|
#### Agregar un tercer proveedor
|
|
1156
1273
|
|
|
1157
1274
|
Una clase que implemente `TerminalPaymentsPort`, un `case` en `createTerminalPaymentsAdapter`, su
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/security/signed-state.ts
|
|
2
|
+
var _crypto = require('crypto');
|
|
3
|
+
function signState(payload, options) {
|
|
4
|
+
const body = JSON.stringify({ ts: Date.now(), nonce: _crypto.randomBytes.call(void 0, 8).toString("hex"), ...payload });
|
|
5
|
+
const b64 = Buffer.from(body).toString("base64url");
|
|
6
|
+
const sig = _crypto.createHmac.call(void 0, "sha256", options.secret).update(b64).digest("base64url");
|
|
7
|
+
return `${b64}.${sig}`;
|
|
8
|
+
}
|
|
9
|
+
function readState(state, options) {
|
|
10
|
+
if (!state) return null;
|
|
11
|
+
const parts = state.split(".");
|
|
12
|
+
if (parts.length !== 2) return null;
|
|
13
|
+
const [b64, sig] = parts;
|
|
14
|
+
const expected = _crypto.createHmac.call(void 0, "sha256", options.secret).update(b64).digest("base64url");
|
|
15
|
+
const provided = Buffer.from(sig);
|
|
16
|
+
const wanted = Buffer.from(expected);
|
|
17
|
+
if (provided.length !== wanted.length || !_crypto.timingSafeEqual.call(void 0, provided, wanted)) return null;
|
|
18
|
+
let parsed;
|
|
19
|
+
try {
|
|
20
|
+
parsed = JSON.parse(Buffer.from(b64, "base64url").toString());
|
|
21
|
+
} catch (e) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const ts = parsed.ts;
|
|
25
|
+
const ttl = _nullishCoalesce(options.ttlMs, () => ( 10 * 6e4));
|
|
26
|
+
if (typeof ts !== "number" || !Number.isFinite(ts) || Date.now() - ts >= ttl) return null;
|
|
27
|
+
const { ts: _ts, nonce: _nonce, ...rest } = parsed;
|
|
28
|
+
return rest;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/security/mask.ts
|
|
32
|
+
function maskEmail(email) {
|
|
33
|
+
const clean = email.trim();
|
|
34
|
+
const at = clean.lastIndexOf("@");
|
|
35
|
+
if (at < 1) return "***";
|
|
36
|
+
return `${clean[0]}***${clean.slice(at)}`;
|
|
37
|
+
}
|
|
38
|
+
function maskPhone(phone, visible = 4) {
|
|
39
|
+
const digits = phone.replace(/\D/g, "");
|
|
40
|
+
if (digits.length <= visible) return "***";
|
|
41
|
+
return `***${digits.slice(-visible)}`;
|
|
42
|
+
}
|
|
43
|
+
function maskToken(token, keep = 2) {
|
|
44
|
+
if (token.length <= keep * 2) return "***";
|
|
45
|
+
return `${token.slice(0, keep)}***${token.slice(-keep)}`;
|
|
46
|
+
}
|
|
47
|
+
function shapeOf(value, depth = 4) {
|
|
48
|
+
if (value === null) return "null";
|
|
49
|
+
if (Array.isArray(value)) return depth <= 0 ? "array" : value.slice(0, 3).map((v) => shapeOf(v, depth - 1));
|
|
50
|
+
if (typeof value === "object") {
|
|
51
|
+
if (depth <= 0) return "object";
|
|
52
|
+
return Object.fromEntries(
|
|
53
|
+
Object.entries(value).map(([k, v]) => [k, shapeOf(v, depth - 1)])
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return typeof value;
|
|
57
|
+
}
|
|
58
|
+
var apply = (rule, value) => {
|
|
59
|
+
if (typeof rule === "function") return rule(value);
|
|
60
|
+
if (rule === "drop") return void 0;
|
|
61
|
+
if (rule === "redact" || typeof value !== "string") return "***";
|
|
62
|
+
if (rule === "email") return maskEmail(value);
|
|
63
|
+
if (rule === "phone") return maskPhone(value);
|
|
64
|
+
return maskToken(value);
|
|
65
|
+
};
|
|
66
|
+
function maskFields(value, rules, maxDepth = 8) {
|
|
67
|
+
const byKey = new Map(Object.entries(rules).map(([k, r]) => [k.toLowerCase(), r]));
|
|
68
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
69
|
+
const walk = (v, depth) => {
|
|
70
|
+
if (v === null || typeof v !== "object") return v;
|
|
71
|
+
if (depth > maxDepth || seen.has(v)) return "[\u2026]";
|
|
72
|
+
seen.add(v);
|
|
73
|
+
if (Array.isArray(v)) return v.map((x) => walk(x, depth + 1));
|
|
74
|
+
const out = {};
|
|
75
|
+
for (const [k, x] of Object.entries(v)) {
|
|
76
|
+
const rule = byKey.get(k.toLowerCase());
|
|
77
|
+
if (rule === void 0) out[k] = walk(x, depth + 1);
|
|
78
|
+
else {
|
|
79
|
+
try {
|
|
80
|
+
const masked = apply(rule, x);
|
|
81
|
+
if (masked !== void 0) out[k] = masked;
|
|
82
|
+
} catch (e2) {
|
|
83
|
+
out[k] = "***";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
return walk(value, 0);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/security/hash.ts
|
|
93
|
+
|
|
94
|
+
var hashSha256 = (value) => _crypto.createHash.call(void 0, "sha256").update(value).digest("hex");
|
|
95
|
+
function constantTimeEqual(a, b) {
|
|
96
|
+
const ba = Buffer.from(a);
|
|
97
|
+
const bb = Buffer.from(b);
|
|
98
|
+
if (ba.length !== bb.length) {
|
|
99
|
+
_crypto.timingSafeEqual.call(void 0, ba, ba);
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
return _crypto.timingSafeEqual.call(void 0, ba, bb);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/security/signed-grant.ts
|
|
106
|
+
|
|
107
|
+
var sign = (b64, secret) => _crypto.createHmac.call(void 0, "sha256", secret).update(b64).digest("base64url");
|
|
108
|
+
function signGrant(claims, secret, ttlMs = 6e4) {
|
|
109
|
+
const body = JSON.stringify({
|
|
110
|
+
a: claims.actor,
|
|
111
|
+
p: claims.permission,
|
|
112
|
+
r: claims.resource,
|
|
113
|
+
t: claims.tenant,
|
|
114
|
+
exp: Date.now() + ttlMs,
|
|
115
|
+
n: _crypto.randomBytes.call(void 0, 8).toString("hex")
|
|
116
|
+
});
|
|
117
|
+
const b64 = Buffer.from(body).toString("base64url");
|
|
118
|
+
return `${b64}.${sign(b64, secret)}`;
|
|
119
|
+
}
|
|
120
|
+
function verifyGrant(token, secret, expected) {
|
|
121
|
+
if (!token) return null;
|
|
122
|
+
const parts = token.split(".");
|
|
123
|
+
if (parts.length !== 2) return null;
|
|
124
|
+
const [b64, sig] = parts;
|
|
125
|
+
if (!constantTimeEqual(sig, sign(b64, secret))) return null;
|
|
126
|
+
let p;
|
|
127
|
+
try {
|
|
128
|
+
p = JSON.parse(Buffer.from(b64, "base64url").toString());
|
|
129
|
+
} catch (e3) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (typeof p.exp !== "number" || !Number.isFinite(p.exp) || Date.now() >= p.exp) return null;
|
|
133
|
+
if (typeof p.a !== "string" || typeof p.p !== "string" || typeof p.r !== "string" || typeof p.t !== "string") return null;
|
|
134
|
+
if (p.p !== expected.permission || p.r !== expected.resource || p.t !== expected.tenant) return null;
|
|
135
|
+
if (expected.actor !== void 0 && p.a !== expected.actor) return null;
|
|
136
|
+
return { actor: p.a, permission: p.p, resource: p.r, tenant: p.t };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
exports.signState = signState; exports.readState = readState; exports.maskEmail = maskEmail; exports.maskPhone = maskPhone; exports.maskToken = maskToken; exports.shapeOf = shapeOf; exports.maskFields = maskFields; exports.hashSha256 = hashSha256; exports.constantTimeEqual = constantTimeEqual; exports.signGrant = signGrant; exports.verifyGrant = verifyGrant;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// src/security/signed-state.ts
|
|
2
|
+
import { createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
3
|
+
function signState(payload, options) {
|
|
4
|
+
const body = JSON.stringify({ ts: Date.now(), nonce: randomBytes(8).toString("hex"), ...payload });
|
|
5
|
+
const b64 = Buffer.from(body).toString("base64url");
|
|
6
|
+
const sig = createHmac("sha256", options.secret).update(b64).digest("base64url");
|
|
7
|
+
return `${b64}.${sig}`;
|
|
8
|
+
}
|
|
9
|
+
function readState(state, options) {
|
|
10
|
+
if (!state) return null;
|
|
11
|
+
const parts = state.split(".");
|
|
12
|
+
if (parts.length !== 2) return null;
|
|
13
|
+
const [b64, sig] = parts;
|
|
14
|
+
const expected = createHmac("sha256", options.secret).update(b64).digest("base64url");
|
|
15
|
+
const provided = Buffer.from(sig);
|
|
16
|
+
const wanted = Buffer.from(expected);
|
|
17
|
+
if (provided.length !== wanted.length || !timingSafeEqual(provided, wanted)) return null;
|
|
18
|
+
let parsed;
|
|
19
|
+
try {
|
|
20
|
+
parsed = JSON.parse(Buffer.from(b64, "base64url").toString());
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const ts = parsed.ts;
|
|
25
|
+
const ttl = options.ttlMs ?? 10 * 6e4;
|
|
26
|
+
if (typeof ts !== "number" || !Number.isFinite(ts) || Date.now() - ts >= ttl) return null;
|
|
27
|
+
const { ts: _ts, nonce: _nonce, ...rest } = parsed;
|
|
28
|
+
return rest;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/security/mask.ts
|
|
32
|
+
function maskEmail(email) {
|
|
33
|
+
const clean = email.trim();
|
|
34
|
+
const at = clean.lastIndexOf("@");
|
|
35
|
+
if (at < 1) return "***";
|
|
36
|
+
return `${clean[0]}***${clean.slice(at)}`;
|
|
37
|
+
}
|
|
38
|
+
function maskPhone(phone, visible = 4) {
|
|
39
|
+
const digits = phone.replace(/\D/g, "");
|
|
40
|
+
if (digits.length <= visible) return "***";
|
|
41
|
+
return `***${digits.slice(-visible)}`;
|
|
42
|
+
}
|
|
43
|
+
function maskToken(token, keep = 2) {
|
|
44
|
+
if (token.length <= keep * 2) return "***";
|
|
45
|
+
return `${token.slice(0, keep)}***${token.slice(-keep)}`;
|
|
46
|
+
}
|
|
47
|
+
function shapeOf(value, depth = 4) {
|
|
48
|
+
if (value === null) return "null";
|
|
49
|
+
if (Array.isArray(value)) return depth <= 0 ? "array" : value.slice(0, 3).map((v) => shapeOf(v, depth - 1));
|
|
50
|
+
if (typeof value === "object") {
|
|
51
|
+
if (depth <= 0) return "object";
|
|
52
|
+
return Object.fromEntries(
|
|
53
|
+
Object.entries(value).map(([k, v]) => [k, shapeOf(v, depth - 1)])
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return typeof value;
|
|
57
|
+
}
|
|
58
|
+
var apply = (rule, value) => {
|
|
59
|
+
if (typeof rule === "function") return rule(value);
|
|
60
|
+
if (rule === "drop") return void 0;
|
|
61
|
+
if (rule === "redact" || typeof value !== "string") return "***";
|
|
62
|
+
if (rule === "email") return maskEmail(value);
|
|
63
|
+
if (rule === "phone") return maskPhone(value);
|
|
64
|
+
return maskToken(value);
|
|
65
|
+
};
|
|
66
|
+
function maskFields(value, rules, maxDepth = 8) {
|
|
67
|
+
const byKey = new Map(Object.entries(rules).map(([k, r]) => [k.toLowerCase(), r]));
|
|
68
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
69
|
+
const walk = (v, depth) => {
|
|
70
|
+
if (v === null || typeof v !== "object") return v;
|
|
71
|
+
if (depth > maxDepth || seen.has(v)) return "[\u2026]";
|
|
72
|
+
seen.add(v);
|
|
73
|
+
if (Array.isArray(v)) return v.map((x) => walk(x, depth + 1));
|
|
74
|
+
const out = {};
|
|
75
|
+
for (const [k, x] of Object.entries(v)) {
|
|
76
|
+
const rule = byKey.get(k.toLowerCase());
|
|
77
|
+
if (rule === void 0) out[k] = walk(x, depth + 1);
|
|
78
|
+
else {
|
|
79
|
+
try {
|
|
80
|
+
const masked = apply(rule, x);
|
|
81
|
+
if (masked !== void 0) out[k] = masked;
|
|
82
|
+
} catch {
|
|
83
|
+
out[k] = "***";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
return walk(value, 0);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/security/hash.ts
|
|
93
|
+
import { createHash, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
94
|
+
var hashSha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
95
|
+
function constantTimeEqual(a, b) {
|
|
96
|
+
const ba = Buffer.from(a);
|
|
97
|
+
const bb = Buffer.from(b);
|
|
98
|
+
if (ba.length !== bb.length) {
|
|
99
|
+
timingSafeEqual2(ba, ba);
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
return timingSafeEqual2(ba, bb);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/security/signed-grant.ts
|
|
106
|
+
import { createHmac as createHmac2, randomBytes as randomBytes2 } from "crypto";
|
|
107
|
+
var sign = (b64, secret) => createHmac2("sha256", secret).update(b64).digest("base64url");
|
|
108
|
+
function signGrant(claims, secret, ttlMs = 6e4) {
|
|
109
|
+
const body = JSON.stringify({
|
|
110
|
+
a: claims.actor,
|
|
111
|
+
p: claims.permission,
|
|
112
|
+
r: claims.resource,
|
|
113
|
+
t: claims.tenant,
|
|
114
|
+
exp: Date.now() + ttlMs,
|
|
115
|
+
n: randomBytes2(8).toString("hex")
|
|
116
|
+
});
|
|
117
|
+
const b64 = Buffer.from(body).toString("base64url");
|
|
118
|
+
return `${b64}.${sign(b64, secret)}`;
|
|
119
|
+
}
|
|
120
|
+
function verifyGrant(token, secret, expected) {
|
|
121
|
+
if (!token) return null;
|
|
122
|
+
const parts = token.split(".");
|
|
123
|
+
if (parts.length !== 2) return null;
|
|
124
|
+
const [b64, sig] = parts;
|
|
125
|
+
if (!constantTimeEqual(sig, sign(b64, secret))) return null;
|
|
126
|
+
let p;
|
|
127
|
+
try {
|
|
128
|
+
p = JSON.parse(Buffer.from(b64, "base64url").toString());
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (typeof p.exp !== "number" || !Number.isFinite(p.exp) || Date.now() >= p.exp) return null;
|
|
133
|
+
if (typeof p.a !== "string" || typeof p.p !== "string" || typeof p.r !== "string" || typeof p.t !== "string") return null;
|
|
134
|
+
if (p.p !== expected.permission || p.r !== expected.resource || p.t !== expected.tenant) return null;
|
|
135
|
+
if (expected.actor !== void 0 && p.a !== expected.actor) return null;
|
|
136
|
+
return { actor: p.a, permission: p.p, resource: p.r, tenant: p.t };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export {
|
|
140
|
+
signState,
|
|
141
|
+
readState,
|
|
142
|
+
maskEmail,
|
|
143
|
+
maskPhone,
|
|
144
|
+
maskToken,
|
|
145
|
+
shapeOf,
|
|
146
|
+
maskFields,
|
|
147
|
+
hashSha256,
|
|
148
|
+
constantTimeEqual,
|
|
149
|
+
signGrant,
|
|
150
|
+
verifyGrant
|
|
151
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AES-256-GCM for third-party secrets stored per tenant (Mercado Pago tokens, Clip keys).
|
|
3
|
+
* Format: `base64(iv).base64(tag).base64(ciphertext)`. The key is 64 hex chars (32 bytes).
|
|
4
|
+
*/
|
|
5
|
+
export declare class CredentialsCipher {
|
|
6
|
+
private readonly key;
|
|
7
|
+
constructor(key: Buffer);
|
|
8
|
+
/** `null` when the value is missing or not 64 hex chars: the feature that needs it should switch itself off. */
|
|
9
|
+
static fromHex(hex: string | undefined | null): CredentialsCipher | null;
|
|
10
|
+
encrypt(text: string): string;
|
|
11
|
+
decrypt(packed: string): string;
|
|
12
|
+
encryptJson(value: unknown): string;
|
|
13
|
+
decryptJson<T>(packed: string): T;
|
|
14
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Card refunds through Mercado Pago's Orders API (`POST /v1/orders/{id}/refund`) with a stable `X-Idempotency-Key` per
|
|
3
|
+
* refund. Mercado Pago remembers a key's answer for 24 h: retrying with the SAME key returns the same refund, never a
|
|
4
|
+
* new one. Only the pure part (reading the order, deciding the status) and the HTTP call live here; who stores what is
|
|
5
|
+
* up to the app. Never mark something "refunded" without Mercado Pago confirming it.
|
|
6
|
+
*/
|
|
7
|
+
/** What Mercado Pago says about ONE refund of ours. */
|
|
8
|
+
export type RefundStatus = 'confirmed' | 'pending' | 'rejected';
|
|
9
|
+
export interface RefundResult {
|
|
10
|
+
status: RefundStatus;
|
|
11
|
+
/** The refund id at Mercado Pago, once known. */
|
|
12
|
+
providerRefundId: string | null;
|
|
13
|
+
/** Why it is still pending or why it was rejected (text for a person, no internals). */
|
|
14
|
+
detail: string | null;
|
|
15
|
+
}
|
|
16
|
+
/** Window in which Mercado Pago remembers an idempotency key (24 h); a margin is left. */
|
|
17
|
+
export declare const IDEMPOTENCY_WINDOW_MS: number;
|
|
18
|
+
interface OrderRefund {
|
|
19
|
+
id?: unknown;
|
|
20
|
+
amount?: unknown;
|
|
21
|
+
status?: unknown;
|
|
22
|
+
}
|
|
23
|
+
export interface MercadoPagoOrder {
|
|
24
|
+
id?: string;
|
|
25
|
+
status?: string;
|
|
26
|
+
status_detail?: string;
|
|
27
|
+
total_amount?: string;
|
|
28
|
+
transactions?: {
|
|
29
|
+
payments?: {
|
|
30
|
+
id?: string;
|
|
31
|
+
amount?: string;
|
|
32
|
+
paid_amount?: string;
|
|
33
|
+
status?: string;
|
|
34
|
+
}[];
|
|
35
|
+
refunds?: OrderRefund[];
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** A Mercado Pago amount (`"10.00"`) in integer cents. */
|
|
39
|
+
export declare const centsOf: (v: unknown) => number;
|
|
40
|
+
/** What the order collected (cents) and the payment id a partial refund is made against. */
|
|
41
|
+
export declare function paymentOfOrder(o: MercadoPagoOrder): {
|
|
42
|
+
paymentId: string | null;
|
|
43
|
+
collectedCents: number;
|
|
44
|
+
};
|
|
45
|
+
/** Texts shown to people. Override any of them (e.g. to translate); the defaults are Spanish. */
|
|
46
|
+
export interface RefundMessages {
|
|
47
|
+
notYetListed: string;
|
|
48
|
+
processing: string;
|
|
49
|
+
rejected: string;
|
|
50
|
+
rejectedWith: (reason: string) => string;
|
|
51
|
+
}
|
|
52
|
+
export declare const DEFAULT_REFUND_MESSAGES: RefundMessages;
|
|
53
|
+
/**
|
|
54
|
+
* Finds OUR refund inside the order and tells its status. With `providerRefundId` it looks it up by id; without it
|
|
55
|
+
* (the answer was lost) it takes the latest refund of that amount that no other refund of ours already claimed.
|
|
56
|
+
* If it is not found it stays `pending`: nothing is ever assumed.
|
|
57
|
+
*/
|
|
58
|
+
export declare function interpretOrder(o: MercadoPagoOrder, wanted: {
|
|
59
|
+
providerRefundId: string | null;
|
|
60
|
+
amountCents: number;
|
|
61
|
+
claimed: string[];
|
|
62
|
+
}, messages?: RefundMessages): RefundResult;
|
|
63
|
+
/** Readable message of a Mercado Pago 4xx body (its `message` or the first error's), trimmed. */
|
|
64
|
+
export declare function refundErrorMessage(body: unknown, messages?: RefundMessages): string;
|
|
65
|
+
/** Stable code of a Mercado Pago error (`errors[0].code`, or flat `error`/`code`). */
|
|
66
|
+
export declare function refundErrorCode(body: unknown): string | null;
|
|
67
|
+
/**
|
|
68
|
+
* Codes from Point's official refund-error table that are FINAL (the refund will not happen as asked) and what to tell
|
|
69
|
+
* the person. Source: mercadopago.com.mx/developers/es/docs/mp-point/resources/refund-errors.
|
|
70
|
+
*/
|
|
71
|
+
export declare const DEFINITIVE_REFUND_REJECTIONS: Record<string, string>;
|
|
72
|
+
/** An HTTP status from Mercado Pago that is not final: stays pending (the key makes retrying safe). */
|
|
73
|
+
export declare const isTransientStatus: (status: number) => boolean;
|
|
74
|
+
/**
|
|
75
|
+
* What to do with an error response of the refund POST. The official code first; with no code, the HTTP status:
|
|
76
|
+
* 408/425/429/5xx and any unknown 409 stay pending.
|
|
77
|
+
*/
|
|
78
|
+
export declare function classifyRefundError(status: number, body: unknown, messages?: RefundMessages): {
|
|
79
|
+
transient: true;
|
|
80
|
+
} | {
|
|
81
|
+
transient: false;
|
|
82
|
+
detail: string;
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Minimal client over a merchant's access token. `fetchImpl` should add a timeout and retries: a POST with an
|
|
86
|
+
* idempotency key is safe to retry.
|
|
87
|
+
*/
|
|
88
|
+
export declare class MercadoPagoRefunds {
|
|
89
|
+
private readonly o;
|
|
90
|
+
constructor(o: {
|
|
91
|
+
accessToken: string;
|
|
92
|
+
baseUrl?: string;
|
|
93
|
+
fetchImpl?: typeof fetch;
|
|
94
|
+
});
|
|
95
|
+
private get base();
|
|
96
|
+
private get http();
|
|
97
|
+
private headers;
|
|
98
|
+
/** The order, or `null` if it does not exist in this account (404). Throws if Mercado Pago does not answer. */
|
|
99
|
+
order(orderId: string): Promise<{
|
|
100
|
+
status: number;
|
|
101
|
+
order: MercadoPagoOrder | null;
|
|
102
|
+
}>;
|
|
103
|
+
/**
|
|
104
|
+
* Asks for the refund. `amountCents` equal to everything collected = total refund (empty body, as documented);
|
|
105
|
+
* less = partial with `transactions: [{ id, amount }]`. Returns the HTTP status and raw body: the caller decides.
|
|
106
|
+
*/
|
|
107
|
+
refund(a: {
|
|
108
|
+
orderId: string;
|
|
109
|
+
key: string;
|
|
110
|
+
total: boolean;
|
|
111
|
+
paymentId: string | null;
|
|
112
|
+
amountCents: number;
|
|
113
|
+
}): Promise<{
|
|
114
|
+
status: number;
|
|
115
|
+
body: unknown;
|
|
116
|
+
}>;
|
|
117
|
+
}
|
|
118
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verifies a Mercado Pago webhook. Header `x-signature: ts=…,v1=…`; the signed manifest is
|
|
3
|
+
* `id:<data.id lowercased>;request-id:<x-request-id>;ts:<ts>;` (absent parts are left out).
|
|
4
|
+
* Timing-safe. A notification is only a trigger: still read the order from the API, never from the body.
|
|
5
|
+
*/
|
|
6
|
+
export declare function verifyMercadoPagoSignature(secret: string, dataId: string | null, xSignature: string | undefined, xRequestId: string | undefined): boolean;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { I18nMessage } from '../../i18n/message.js';
|
|
2
|
+
export type OnlineCheckoutProvider = 'mercadopago' | 'clip';
|
|
3
|
+
export type OnlineCheckoutCredentials = {
|
|
4
|
+
provider: 'mercadopago';
|
|
5
|
+
accessToken: string;
|
|
6
|
+
} | {
|
|
7
|
+
provider: 'clip';
|
|
8
|
+
apiKey: string;
|
|
9
|
+
secretKey: string;
|
|
10
|
+
};
|
|
11
|
+
export interface CreateOnlineCheckout {
|
|
12
|
+
/** Your id for the sale; comes back on lookup and prevents charging the same thing twice. */
|
|
13
|
+
reference: string;
|
|
14
|
+
description: string;
|
|
15
|
+
/** Integer cents (converted to pesos at the edge). */
|
|
16
|
+
amountCents: number;
|
|
17
|
+
/** Where the buyer lands afterwards. */
|
|
18
|
+
returnUrl: string;
|
|
19
|
+
/** Where the provider notifies (your public API). */
|
|
20
|
+
noticeUrl: string;
|
|
21
|
+
/** Minutes the payment link lives. */
|
|
22
|
+
validForMinutes: number;
|
|
23
|
+
}
|
|
24
|
+
export interface OnlineCheckout {
|
|
25
|
+
provider: OnlineCheckoutProvider;
|
|
26
|
+
/** Provider id (Mercado Pago preference or Clip `payment_request_id`). */
|
|
27
|
+
ref: string;
|
|
28
|
+
url: string;
|
|
29
|
+
}
|
|
30
|
+
export type OnlinePaymentState = 'paid' | 'pending' | 'failed';
|
|
31
|
+
export interface OnlineCheckoutLookup {
|
|
32
|
+
state: OnlinePaymentState;
|
|
33
|
+
/** What the provider says was collected, in cents (null while it has not). */
|
|
34
|
+
paidCents: number | null;
|
|
35
|
+
}
|
|
36
|
+
/** Error messages. Override to translate; defaults are Spanish. */
|
|
37
|
+
export interface OnlineCheckoutMessages {
|
|
38
|
+
mercadoPagoNotOpened: string | I18nMessage;
|
|
39
|
+
mercadoPagoNoAnswer: string | I18nMessage;
|
|
40
|
+
clipNotOpened: string | I18nMessage;
|
|
41
|
+
clipNoAnswer: string | I18nMessage;
|
|
42
|
+
}
|
|
43
|
+
export interface OnlineCheckoutOptions {
|
|
44
|
+
/** Pass the fetch you use for each provider (timeouts, retries). Defaults to global `fetch`. */
|
|
45
|
+
fetchImpl?: (provider: OnlineCheckoutProvider) => typeof fetch;
|
|
46
|
+
mercadoPagoBaseUrl?: string;
|
|
47
|
+
clipBaseUrl?: string;
|
|
48
|
+
messages?: Partial<OnlineCheckoutMessages>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Online payment link of a merchant: Mercado Pago Checkout Pro or Clip Checkout, always with the MERCHANT's own
|
|
52
|
+
* credentials (the money goes to their account). Creates the link and looks its state up; the state is ALWAYS read
|
|
53
|
+
* from the provider, never from what the buyer or a notification body says.
|
|
54
|
+
*/
|
|
55
|
+
export declare class OnlineCheckoutClient {
|
|
56
|
+
private readonly o;
|
|
57
|
+
private readonly msg;
|
|
58
|
+
constructor(o?: OnlineCheckoutOptions);
|
|
59
|
+
private http;
|
|
60
|
+
private get mpBase();
|
|
61
|
+
private get clipBase();
|
|
62
|
+
private clipAuth;
|
|
63
|
+
create(cred: OnlineCheckoutCredentials, c: CreateOnlineCheckout): Promise<OnlineCheckout>;
|
|
64
|
+
/**
|
|
65
|
+
* Current state of the payment according to the provider (`ref` = preference or payment_request_id).
|
|
66
|
+
* `since`: when the current link was opened — a rejection older than that belongs to an earlier attempt.
|
|
67
|
+
*/
|
|
68
|
+
lookup(cred: OnlineCheckoutCredentials, reference: string, ref: string, since?: Date): Promise<OnlineCheckoutLookup>;
|
|
69
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-line summary of a provider rejection (`TERMINAL_PAYMENT_PROVIDER_ERROR`) for the log: provider, HTTP status and
|
|
3
|
+
* the body it answered with (trimmed). The exception already carries that body in `details`, but a log that only says
|
|
4
|
+
* "clip rejected the request (HTTP 400)" cannot diagnose a production rejection. Provider bodies never carry your
|
|
5
|
+
* secrets (credentials travel in headers). Returns `null` when the error is not a provider error.
|
|
6
|
+
*/
|
|
7
|
+
export declare function summarizeProviderRejection(error: unknown, limit?: number): string | null;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { TerminalPayment, TerminalPaymentStatus } from '../payments.port.js';
|
|
2
|
+
/**
|
|
3
|
+
* The Clip adapter only recognises PENDING / COMPLETED / FAILED; any other value arrives as `unknown`, which a
|
|
4
|
+
* point of sale can never treat as final, so the screen keeps saying "waiting" after the card already went through.
|
|
5
|
+
* This reads the raw `status` with more synonyms and, failing that, the paid amount: Clip only sends `amount_paid`
|
|
6
|
+
* once the charge completed. Returns the same status when the adapter already recognised it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function clipStatus(p: TerminalPayment): TerminalPaymentStatus;
|
|
9
|
+
/**
|
|
10
|
+
* Mercado Pago (Orders): the adapter knows created / action_required / at_terminal / processed / failed / canceled /
|
|
11
|
+
* expired / refunded; anything else (`processing`, `partially_refunded`) arrived as `unknown`. `processing` means the
|
|
12
|
+
* card already went through the reader and is being credited; `partially_refunded` and credited payments inside the
|
|
13
|
+
* order mean the charge did happen.
|
|
14
|
+
*/
|
|
15
|
+
export declare function mercadoPagoStatus(p: TerminalPayment): TerminalPaymentStatus;
|
|
16
|
+
/**
|
|
17
|
+
* The status a point of sale should act on: the adapter's when it recognised it, otherwise the provider-specific
|
|
18
|
+
* reading above. Call this on every `TerminalPayment` you get back from `charge`/`get`/`cancel`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function resolveTerminalStatus(p: TerminalPayment): TerminalPaymentStatus;
|