idoodev-sdk 1.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -0
  3. package/idoodev.js +92 -0
  4. package/package.json +19 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Idoo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # SDK de idoo.dev para creadores — Node.js
2
+
3
+ Verifica en tu backend que cada petición proviene realmente del gateway de
4
+ [idoo.dev](https://idoo.dev) y accede al contexto del consumidor. Sin
5
+ dependencias; Node 16+.
6
+
7
+ ## Instalación
8
+
9
+ ```bash
10
+ npm install idoodev-sdk
11
+ ```
12
+
13
+ O copia `idoodev.js` a tu proyecto y haz `require` directo.
14
+
15
+ ## Uso con Express
16
+
17
+ ```js
18
+ const express = require('express');
19
+ const { middlewareExpress } = require('idoodev-sdk');
20
+
21
+ const app = express();
22
+
23
+ // El SDK necesita el body CRUDO (el mismo que firmó el gateway):
24
+ app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
25
+
26
+ // Rechaza con 401 todo lo que no venga firmado por idoo.dev:
27
+ app.use(middlewareExpress(process.env.IDOO_HMAC_SECRET));
28
+
29
+ app.post('/pedidos', (req, res) => {
30
+ // req.idoo = { consumidorId, plan, ambiente, esSandbox }
31
+ const tabla = req.idoo.esSandbox ? 'sandbox_pedidos' : 'pedidos';
32
+ res.json({ ok: true, consumidor: req.idoo.consumidorId, tabla });
33
+ });
34
+
35
+ app.listen(3000);
36
+ ```
37
+
38
+ ## Uso sin framework
39
+
40
+ ```js
41
+ const { firmaValida, consumidor } = require('idoodev-sdk');
42
+
43
+ // dentro de tu handler http.createServer, con el body crudo acumulado:
44
+ if (!firmaValida({ secret: process.env.IDOO_HMAC_SECRET, headers: req.headers, body })) {
45
+ res.writeHead(401, { 'Content-Type': 'application/json' });
46
+ return res.end(JSON.stringify({ error: 'Firma de idoo.dev inválida' }));
47
+ }
48
+ const ctx = consumidor(req.headers); // { consumidorId, plan, ambiente, esSandbox }
49
+ ```
50
+
51
+ ## Referencia de headers del gateway
52
+
53
+ | Header | Contenido |
54
+ |---|---|
55
+ | `X-Idoo-Signature` | `HMAC-SHA256("{timestamp}.{body}", secret)` en hexadecimal |
56
+ | `X-Idoo-Timestamp` | Unix timestamp con el que se calculó la firma |
57
+ | `X-Idoo-Consumer-Id` | Id del consumidor en idoo.dev |
58
+ | `X-Idoo-Ambiente` | `sandbox` o `produccion` |
59
+ | `X-Idoo-Plan` | Nombre del plan del consumidor |
60
+
61
+ La firma cubre `timestamp.body` y caduca a los 5 minutos (`toleranciaSegundos`
62
+ configurable). El HMAC secret se obtiene y regenera en el panel de creador.
package/idoodev.js ADDED
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * SDK de idoo.dev para creadores de APIs — Node.js (>= 16).
5
+ *
6
+ * Verifica que una petición entrante proviene del gateway de idoo.dev
7
+ * (firma HMAC-SHA256) y expone el contexto del consumidor.
8
+ * Sin dependencias externas.
9
+ */
10
+
11
+ const crypto = require('crypto');
12
+
13
+ const TOLERANCIA_DEFAULT = 300; // segundos
14
+
15
+ /**
16
+ * Normaliza un objeto de headers a minúsculas.
17
+ */
18
+ function normalizarHeaders(headers = {}) {
19
+ const salida = {};
20
+ for (const [nombre, valor] of Object.entries(headers)) {
21
+ salida[nombre.toLowerCase()] = Array.isArray(valor) ? valor[0] : String(valor);
22
+ }
23
+ return salida;
24
+ }
25
+
26
+ /**
27
+ * ¿La firma de la petición es válida?
28
+ *
29
+ * @param {Object} opciones
30
+ * @param {string} opciones.secret HMAC secret del panel de creador
31
+ * @param {Object} opciones.headers Headers de la petición (req.headers)
32
+ * @param {string|Buffer} opciones.body Body CRUDO (el mismo que firmó el gateway)
33
+ * @param {number} [opciones.toleranciaSegundos=300]
34
+ * @returns {boolean}
35
+ */
36
+ function firmaValida({ secret, headers, body = '', toleranciaSegundos = TOLERANCIA_DEFAULT }) {
37
+ const h = normalizarHeaders(headers);
38
+ const firma = h['x-idoo-signature'];
39
+ const timestamp = h['x-idoo-timestamp'];
40
+
41
+ if (!firma || !timestamp || !/^\d+$/.test(timestamp)) return false;
42
+ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranciaSegundos) return false;
43
+
44
+ const cuerpo = Buffer.isBuffer(body) ? body.toString('utf8') : String(body);
45
+ const esperada = crypto.createHmac('sha256', secret).update(`${timestamp}.${cuerpo}`).digest('hex');
46
+
47
+ const a = Buffer.from(esperada, 'utf8');
48
+ const b = Buffer.from(firma, 'utf8');
49
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
50
+ }
51
+
52
+ /**
53
+ * Contexto del consumidor a partir de los headers del gateway.
54
+ *
55
+ * @param {Object} headers req.headers
56
+ * @returns {{consumidorId: number|null, plan: string|null, ambiente: 'sandbox'|'produccion', esSandbox: boolean}}
57
+ */
58
+ function consumidor(headers = {}) {
59
+ const h = normalizarHeaders(headers);
60
+ const id = h['x-idoo-consumer-id'];
61
+ const ambiente = h['x-idoo-ambiente'] === 'produccion' ? 'produccion' : 'sandbox';
62
+ return {
63
+ consumidorId: id && /^\d+$/.test(id) ? Number(id) : null,
64
+ plan: h['x-idoo-plan'] || null,
65
+ ambiente,
66
+ esSandbox: ambiente === 'sandbox',
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Middleware para Express: rechaza con 401 las peticiones sin firma válida
72
+ * y agrega `req.idoo` con el contexto del consumidor.
73
+ *
74
+ * IMPORTANTE: necesita el body crudo. Configura tu parser así:
75
+ * app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
76
+ *
77
+ * @param {string} secret
78
+ * @param {Object} [opciones]
79
+ * @param {number} [opciones.toleranciaSegundos=300]
80
+ */
81
+ function middlewareExpress(secret, opciones = {}) {
82
+ return function (req, res, next) {
83
+ const body = req.rawBody ?? '';
84
+ if (!firmaValida({ secret, headers: req.headers, body, ...opciones })) {
85
+ return res.status(401).json({ error: 'Petición no autorizada: firma de idoo.dev inválida o ausente.' });
86
+ }
87
+ req.idoo = consumidor(req.headers);
88
+ next();
89
+ };
90
+ }
91
+
92
+ module.exports = { firmaValida, consumidor, middlewareExpress, TOLERANCIA_DEFAULT };
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "idoodev-sdk",
3
+ "version": "1.0.0",
4
+ "description": "SDK oficial de idoo.dev para creadores de APIs: verificación de la firma HMAC del gateway y contexto del consumidor.",
5
+ "main": "idoodev.js",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=16"
9
+ },
10
+ "files": [
11
+ "idoodev.js"
12
+ ],
13
+ "keywords": ["idoo", "idoodev", "api", "gateway", "hmac", "marketplace"],
14
+ "homepage": "https://idoo.dev",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://gitlab.idoo.mx/publico/idoo-sdk-node.git"
18
+ }
19
+ }