fiscalapi 4.0.439 → 4.0.450

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 (34) hide show
  1. package/README.md +60 -0
  2. package/dist/cjs/index.d.ts +5 -0
  3. package/dist/cjs/index.d.ts.map +1 -1
  4. package/dist/cjs/index.js +7 -1
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/models/webhook-event.d.ts +78 -0
  7. package/dist/cjs/models/webhook-event.d.ts.map +1 -0
  8. package/dist/cjs/models/webhook-event.js +31 -0
  9. package/dist/cjs/models/webhook-event.js.map +1 -0
  10. package/dist/cjs/webhooks/webhook-verification-error.d.ts +11 -0
  11. package/dist/cjs/webhooks/webhook-verification-error.d.ts.map +1 -0
  12. package/dist/cjs/webhooks/webhook-verification-error.js +20 -0
  13. package/dist/cjs/webhooks/webhook-verification-error.js.map +1 -0
  14. package/dist/cjs/webhooks/webhook.d.ts +48 -0
  15. package/dist/cjs/webhooks/webhook.d.ts.map +1 -0
  16. package/dist/cjs/webhooks/webhook.js +252 -0
  17. package/dist/cjs/webhooks/webhook.js.map +1 -0
  18. package/dist/esm/index.d.ts +5 -0
  19. package/dist/esm/index.d.ts.map +1 -1
  20. package/dist/esm/index.js +3 -0
  21. package/dist/esm/index.js.map +1 -1
  22. package/dist/esm/models/webhook-event.d.ts +78 -0
  23. package/dist/esm/models/webhook-event.d.ts.map +1 -0
  24. package/dist/esm/models/webhook-event.js +28 -0
  25. package/dist/esm/models/webhook-event.js.map +1 -0
  26. package/dist/esm/webhooks/webhook-verification-error.d.ts +11 -0
  27. package/dist/esm/webhooks/webhook-verification-error.d.ts.map +1 -0
  28. package/dist/esm/webhooks/webhook-verification-error.js +16 -0
  29. package/dist/esm/webhooks/webhook-verification-error.js.map +1 -0
  30. package/dist/esm/webhooks/webhook.d.ts +48 -0
  31. package/dist/esm/webhooks/webhook.d.ts.map +1 -0
  32. package/dist/esm/webhooks/webhook.js +248 -0
  33. package/dist/esm/webhooks/webhook.js.map +1 -0
  34. package/package.json +1 -1
package/README.md CHANGED
@@ -476,6 +476,66 @@ try {
476
476
 
477
477
  Tras una firma exitosa, todas las personas del tenant con el RFC del certificado quedan con `manifestStatusId` en `Signed`; `fiscalApi.persons.getById(...)` lo refleja.
478
478
 
479
+ ### 10. Recibir webhooks
480
+
481
+ FiscalAPI firma cada entrega con [Standard Webhooks](https://www.standardwebhooks.com) y el secreto `whsec_…` de tu webhook. `Webhook.verify` comprueba la firma (en tiempo constante) y que `webhook-timestamp` no difiera más de 5 minutos del reloj del receptor, y devuelve el `WebhookEvent`. La firma es la única prueba de que la entrega viene de FiscalAPI.
482
+
483
+ **Verifica el cuerpo crudo**: en Express, recíbelo con `express.raw({ type: 'application/json' })` y pasa el `Buffer` tal cual. Un cuerpo deserializado y vuelto a serializar (`JSON.stringify(req.body)` después de `express.json()`) cambia sus bytes y la firma deja de coincidir. Registra la ruta antes de un `app.use(express.json())` global: si ese parser corre primero, `req.body` ya no es el cuerpo crudo.
484
+
485
+ ```javascript
486
+ const express = require('express');
487
+ const { FiscalapiClient, Webhook, WebhookEventTypes, WebhookVerificationError } = require('fiscalapi');
488
+
489
+ const app = express();
490
+ const fiscalApi = FiscalapiClient.create(settings);
491
+ const webhookSecret = process.env.FISCALAPI_WEBHOOK_SECRET; // whsec_… del webhook, desde tu configuración segura
492
+
493
+ app.post('/webhooks/fiscalapi', express.raw({ type: 'application/json' }), (req, res) => {
494
+ // Sin cuerpo o con otro Content-Type, express.raw no deja un Buffer: no es una entrega de FiscalAPI.
495
+ if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
496
+
497
+ let webhookEvent;
498
+ try {
499
+ webhookEvent = Webhook.verify(req.headers, req.body, webhookSecret);
500
+ } catch (error) {
501
+ if (error instanceof WebhookVerificationError) {
502
+ return res.sendStatus(400); // firma inválida, header faltante o timestamp fuera de tolerancia
503
+ }
504
+ throw error; // secreto mal configurado: error del receptor, no de la entrega
505
+ }
506
+
507
+ // Responde 2xx rápido y procesa después: FiscalAPI corta cada intento a los 15 s y lo reintenta.
508
+ res.sendStatus(200);
509
+ // Procesa fuera de la petición. setImmediate es ilustrativo: en producción usa una cola durable.
510
+ setImmediate(() => processEvent(webhookEvent).catch(console.error));
511
+ });
512
+
513
+ async function processEvent(webhookEvent) {
514
+ // La entrega es al menos una vez: webhookEvent.id (el header webhook-id) se repite en cada reintento;
515
+ // descarta los ya procesados. El orden de llegada no está garantizado: el estado autoritativo se lee del recurso.
516
+ switch (webhookEvent.type) {
517
+ case WebhookEventTypes.InvoiceCanceled: {
518
+ const invoice = await fiscalApi.invoices.getById(webhookEvent.data.relatedObject.id);
519
+ break;
520
+ }
521
+ case WebhookEventTypes.DownloadRequestCompleted: {
522
+ const request = await fiscalApi.downloadRequests.getById(webhookEvent.data.relatedObject.id);
523
+ break;
524
+ }
525
+ default:
526
+ break; // un tipo que no conoces se ignora: el catálogo puede crecer
527
+ }
528
+ }
529
+ ```
530
+
531
+ - `WebhookEvent` es el mismo sobre para todo evento: `id`, `type` (texto; compáralo con las constantes de `WebhookEventTypes`), `createdAt` (un `Date`; el sobre lo trae en UTC), `personId` (`null` si el recurso no tiene persona) y `data` con `relatedObject` (`id`, `type`, `url`), `status` y `previousStatus`.
532
+ - `relatedObject.url` es la ruta relativa del GET v4 del recurso (`/api/v4/invoices/{id}`); para leerlo, usa el servicio de su tipo con `relatedObject.id`.
533
+ - El botón "Enviar prueba" del webhook (`POST /api/v4/webhooks/{id}/test`) envía `WebhookEventTypes.WebhookTest` (`webhook.test`), cuyo `relatedObject` es el webhook mismo (`type` `webhook`, `url` `/api/v4/webhooks/{id}`), sin persona ni estados; no se suscribe.
534
+ - `headers` acepta el objeto `req.headers` de Node/Express o un `Headers` de fetch; los nombres no distinguen mayúsculas. `body` acepta el `Buffer` crudo o ese mismo cuerpo como texto; un cuerpo que no es UTF-8 válido se rechaza.
535
+ - Durante una rotación del secreto, FiscalAPI firma con el nuevo y con el anterior por 24 h: pasa ambos, `Webhook.verify(req.headers, req.body, [secretoNuevo, secretoAnterior])`.
536
+ - La tolerancia es configurable en segundos (`Webhook.verify(req.headers, req.body, secreto, 120)`); el valor por omisión es `Webhook.DEFAULT_TOLERANCE_SECONDS` (300).
537
+ - Un secreto mal copiado (no es base64) o una lista de secretos vacía lanza `TypeError` con la posición del secreto (nunca su valor), y una tolerancia negativa `RangeError`: son errores de configuración, no de la entrega.
538
+
479
539
  ## 📂 Más Ejemplos
480
540
 
481
541
  - [Gestión de Timbres](examples/ejemplo-timbres.ts)
@@ -32,6 +32,11 @@ export type { SatValidationType, SatValidationTypeStatus, SatValidationStatus, S
32
32
  export { SatValidationTypeIds, SatValidationStatusIds } from './models/sat-validation';
33
33
  export type { Ticket, TicketIssuer, TicketItem, TicketItemTax, TicketEvent, TicketIngestionResult, TicketCodeResult, TicketListFilters } from './models/ticket';
34
34
  export { TicketStatus, TicketEventType, TicketActorType } from './models/ticket';
35
+ export type { WebhookEvent, WebhookEventData, WebhookRelatedObject } from './models/webhook-event';
36
+ export { WebhookEventTypes } from './models/webhook-event';
37
+ export type { WebhookHeaders, WebhookHeadersGetter } from './webhooks/webhook';
38
+ export { Webhook } from './webhooks/webhook';
39
+ export { WebhookVerificationError } from './webhooks/webhook-verification-error';
35
40
  export type { FiscalapiSettings } from './common/fiscalapi-settings';
36
41
  export type { ApiResponse, ValidationFailure, ProblemDetails } from './common/api-response';
37
42
  export type { FileResponse } from './common/file-response';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,YAAY,EAAE,gBAAgB,EAAE,MAAM,2CAA2C,CAAC;AAElF,YAAY,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAClJ,YAAY,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAA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c,EAAE,MAAM,uBAAuB,CAAC;AAC5F,YAAY,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAI3D,OAAQ,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAQ,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC"}
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  //Export public API
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.isObjectEmpty = exports.isArrayNullOrEmpty = exports.isNullOrEmpty = exports.isNullOrUndefined = exports.decodeFromBase64 = exports.encodeToBase64 = exports.SAT_DATE_FORMAT = exports.parseSatDate = exports.formatSatDate = exports.CatalogDto = exports.SerializableDto = exports.AuditableDto = exports.BaseDto = exports.PagedList = exports.TicketActorType = exports.TicketEventType = exports.TicketStatus = exports.SatValidationStatusIds = exports.SatValidationTypeIds = exports.CreditType = exports.StampTransactionStatus = exports.StampTransactionType = exports.FiscalapiClient = void 0;
4
+ exports.isObjectEmpty = exports.isArrayNullOrEmpty = exports.isNullOrEmpty = exports.isNullOrUndefined = exports.decodeFromBase64 = exports.encodeToBase64 = exports.SAT_DATE_FORMAT = exports.parseSatDate = exports.formatSatDate = exports.CatalogDto = exports.SerializableDto = exports.AuditableDto = exports.BaseDto = exports.PagedList = exports.WebhookVerificationError = exports.Webhook = exports.WebhookEventTypes = exports.TicketActorType = exports.TicketEventType = exports.TicketStatus = exports.SatValidationStatusIds = exports.SatValidationTypeIds = exports.CreditType = exports.StampTransactionStatus = exports.StampTransactionType = exports.FiscalapiClient = void 0;
5
5
  var fiscalapi_client_1 = require("./services/fiscalapi-client");
6
6
  Object.defineProperty(exports, "FiscalapiClient", { enumerable: true, get: function () { return fiscalapi_client_1.FiscalapiClient; } });
7
7
  var stamp_1 = require("./models/stamp");
@@ -15,6 +15,12 @@ var ticket_1 = require("./models/ticket");
15
15
  Object.defineProperty(exports, "TicketStatus", { enumerable: true, get: function () { return ticket_1.TicketStatus; } });
16
16
  Object.defineProperty(exports, "TicketEventType", { enumerable: true, get: function () { return ticket_1.TicketEventType; } });
17
17
  Object.defineProperty(exports, "TicketActorType", { enumerable: true, get: function () { return ticket_1.TicketActorType; } });
18
+ var webhook_event_1 = require("./models/webhook-event");
19
+ Object.defineProperty(exports, "WebhookEventTypes", { enumerable: true, get: function () { return webhook_event_1.WebhookEventTypes; } });
20
+ var webhook_1 = require("./webhooks/webhook");
21
+ Object.defineProperty(exports, "Webhook", { enumerable: true, get: function () { return webhook_1.Webhook; } });
22
+ var webhook_verification_error_1 = require("./webhooks/webhook-verification-error");
23
+ Object.defineProperty(exports, "WebhookVerificationError", { enumerable: true, get: function () { return webhook_verification_error_1.WebhookVerificationError; } });
18
24
  //Values
19
25
  var paged_list_1 = require("./common/paged-list");
20
26
  Object.defineProperty(exports, "PagedList", { enumerable: true, get: function () { return paged_list_1.PagedList; } });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,mBAAmB;;;AAEnB,gEAA8D;AAArD,mHAAA,eAAe,OAAA;AAsIxB,wCAIwB;AAHtB,6GAAA,oBAAoB,OAAA;AACpB,+GAAA,sBAAsB,OAAA;AACtB,mGAAA,UAAU,OAAA;AAWZ,0DAGiC;AAF/B,sHAAA,oBAAoB,OAAA;AACpB,wH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AAA7C,6GAAA,YAAY,OAAA;AACrB,8DAA4D;AAAnD,mHAAA,eAAe,OAAA;AACxB,oDAAkD;AAAzC,yGAAA,UAAU,OAAA;AACnB,iDAAkF;AAAzE,2GAAA,aAAa,OAAA;AAAE,0GAAA,YAAY,OAAA;AAAE,6GAAA,eAAe,OAAA;AACrD,yDAA0E;AAAjE,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AACzC,6DAA+G;AAAtG,qHAAA,iBAAiB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,sHAAA,kBAAkB,OAAA;AAAE,iHAAA,aAAa,OAAA"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Un evento de webhook de FiscalAPI: el mismo sobre para todo tipo de evento. Lo devuelve `Webhook.verify` después de
3
+ * validar la firma. Es una notificación ligera: para el estado autoritativo del recurso (el orden de llegada no está
4
+ * garantizado), consulte `data.relatedObject` con el servicio de su tipo (por ejemplo `client.invoices.getById(id)`).
5
+ */
6
+ export interface WebhookEvent {
7
+ /**
8
+ * Id del evento; es también el header `webhook-id` y no cambia entre reintentos: úselo para descartar entregas
9
+ * repetidas.
10
+ */
11
+ id: string;
12
+ /**
13
+ * Tipo de evento (ver `WebhookEventTypes`). Es texto y no un enum: un tipo que esta versión del SDK no conoce llega
14
+ * tal cual, sin error, y se ignora.
15
+ */
16
+ type: string;
17
+ /** Momento del cambio de estado, al segundo. El sobre lo trae en UTC (`2026-10-12T18:47:53Z`). */
18
+ createdAt: Date;
19
+ /** Persona del tenant dueña del recurso; null si el recurso no tiene una (factura emitida por valores). */
20
+ personId: string | null;
21
+ /** El recurso que cambió y sus estados. */
22
+ data: WebhookEventData;
23
+ }
24
+ /** Datos de un `WebhookEvent`. */
25
+ export interface WebhookEventData {
26
+ /** El recurso que cambió de estado. */
27
+ relatedObject: WebhookRelatedObject;
28
+ /**
29
+ * Estado al que llegó el recurso, con los códigos públicos de la API v4 (factura `V`, `C`, `X`; solicitud de descarga
30
+ * `1`, `2`, `3`, `-1`; regla de descarga `1`..`4`, `-1`); null si el tipo de evento no lo lleva.
31
+ */
32
+ status: string | null;
33
+ /** Estado del que salió el recurso, con los mismos códigos que `status`; null si no aplica. */
34
+ previousStatus: string | null;
35
+ }
36
+ /** El recurso al que se refiere un `WebhookEvent`. */
37
+ export interface WebhookRelatedObject {
38
+ /** Id del recurso: el que reciben los `getById` de los servicios del SDK. */
39
+ id: string;
40
+ /**
41
+ * Tipo de recurso: `invoice`, `download_request`, `download_rule` o `webhook` (el de
42
+ * `WebhookEventTypes.WebhookTest`); el conjunto puede crecer.
43
+ */
44
+ type: string;
45
+ /**
46
+ * Ruta relativa del GET v4 del recurso (por ejemplo `/api/v4/invoices/{id}`), sin host: el mismo evento es idéntico
47
+ * en pruebas y en producción. Para leer el recurso use su servicio con `id`.
48
+ */
49
+ url: string;
50
+ }
51
+ /**
52
+ * Tipos de evento de webhook, como llegan en `WebhookEvent.type`. Los de un cambio de estado nombran el estado al que
53
+ * llegó el recurso. Son una ayuda para comparar: el catálogo puede crecer y un tipo desconocido se ignora.
54
+ */
55
+ export declare const WebhookEventTypes: {
56
+ /** La factura pasó de vigente a cancelación en proceso (`V` → `C`). */
57
+ readonly InvoiceCancellationRequested: "invoice.cancellation_requested";
58
+ /** La cancelación en proceso terminó y la factura quedó cancelada (`C` → `X`). */
59
+ readonly InvoiceCanceled: "invoice.canceled";
60
+ /** La cancelación en proceso se rechazó y la factura volvió a vigente (`C` → `V`). */
61
+ readonly InvoiceCancellationRejected: "invoice.cancellation_rejected";
62
+ /** La solicitud de descarga masiva terminó con éxito (→ `3`). */
63
+ readonly DownloadRequestCompleted: "download_request.completed";
64
+ /**
65
+ * La solicitud de descarga masiva se abandonó (→ `-1`). No implica un error: el motivo está en la solicitud
66
+ * (`client.downloadRequests.getById(id)`).
67
+ */
68
+ readonly DownloadRequestAbandoned: "download_request.abandoned";
69
+ /** La regla de descarga masiva quedó suspendida (`2` → `4`). */
70
+ readonly DownloadRuleSuspended: "download_rule.suspended";
71
+ /**
72
+ * Prueba de un webhook: no se suscribe; llega solo al pulsar "Enviar prueba" (`POST /api/v4/webhooks/{id}/test`), y
73
+ * solo a ese webhook. Su `data.relatedObject` es el webhook mismo (`type` `webhook`, `url` `/api/v4/webhooks/{id}`),
74
+ * sin persona ni estados.
75
+ */
76
+ readonly WebhookTest: "webhook.test";
77
+ };
78
+ //# sourceMappingURL=webhook-event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-event.d.ts","sourceRoot":"","sources":["../../../src/models/webhook-event.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb,kGAAkG;IAClG,SAAS,EAAE,IAAI,CAAC;IAEhB,2GAA2G;IAC3G,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAExB,2CAA2C;IAC3C,IAAI,EAAE,gBAAgB,CAAC;CACxB;AAED,kCAAkC;AAClC,MAAM,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,aAAa,EAAE,oBAAoB,CAAC;IAEpC;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEtB,+FAA+F;IAC/F,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,sDAAsD;AACtD,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB;IAC5B,uEAAuE;;IAEvE,kFAAkF;;IAElF,sFAAsF;;IAEtF,iEAAiE;;IAEjE;;;OAGG;;IAEH,gEAAgE;;IAEhE;;;;OAIG;;CAEK,CAAC"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhookEventTypes = void 0;
4
+ /**
5
+ * Tipos de evento de webhook, como llegan en `WebhookEvent.type`. Los de un cambio de estado nombran el estado al que
6
+ * llegó el recurso. Son una ayuda para comparar: el catálogo puede crecer y un tipo desconocido se ignora.
7
+ */
8
+ exports.WebhookEventTypes = {
9
+ /** La factura pasó de vigente a cancelación en proceso (`V` → `C`). */
10
+ InvoiceCancellationRequested: 'invoice.cancellation_requested',
11
+ /** La cancelación en proceso terminó y la factura quedó cancelada (`C` → `X`). */
12
+ InvoiceCanceled: 'invoice.canceled',
13
+ /** La cancelación en proceso se rechazó y la factura volvió a vigente (`C` → `V`). */
14
+ InvoiceCancellationRejected: 'invoice.cancellation_rejected',
15
+ /** La solicitud de descarga masiva terminó con éxito (→ `3`). */
16
+ DownloadRequestCompleted: 'download_request.completed',
17
+ /**
18
+ * La solicitud de descarga masiva se abandonó (→ `-1`). No implica un error: el motivo está en la solicitud
19
+ * (`client.downloadRequests.getById(id)`).
20
+ */
21
+ DownloadRequestAbandoned: 'download_request.abandoned',
22
+ /** La regla de descarga masiva quedó suspendida (`2` → `4`). */
23
+ DownloadRuleSuspended: 'download_rule.suspended',
24
+ /**
25
+ * Prueba de un webhook: no se suscribe; llega solo al pulsar "Enviar prueba" (`POST /api/v4/webhooks/{id}/test`), y
26
+ * solo a ese webhook. Su `data.relatedObject` es el webhook mismo (`type` `webhook`, `url` `/api/v4/webhooks/{id}`),
27
+ * sin persona ni estados.
28
+ */
29
+ WebhookTest: 'webhook.test',
30
+ };
31
+ //# sourceMappingURL=webhook-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-event.js","sourceRoot":"","sources":["../../../src/models/webhook-event.ts"],"names":[],"mappings":";;;AA6DA;;;GAGG;AACU,QAAA,iBAAiB,GAAG;IAC/B,uEAAuE;IACvE,4BAA4B,EAAE,gCAAgC;IAC9D,kFAAkF;IAClF,eAAe,EAAE,kBAAkB;IACnC,sFAAsF;IACtF,2BAA2B,EAAE,+BAA+B;IAC5D,iEAAiE;IACjE,wBAAwB,EAAE,4BAA4B;IACtD;;;OAGG;IACH,wBAAwB,EAAE,4BAA4B;IACtD,gEAAgE;IAChE,qBAAqB,EAAE,yBAAyB;IAChD;;;;OAIG;IACH,WAAW,EAAE,cAAc;CACnB,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * La entrega no se puede tratar como auténtica: falta un header de Standard Webhooks, ninguna firma coincide, el
3
+ * timestamp está fuera de la tolerancia, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento. El
4
+ * receptor la rechaza (por ejemplo con un 400) y no la procesa.
5
+ */
6
+ export declare class WebhookVerificationError extends Error {
7
+ /** El error original cuando la causa es otra excepción (por ejemplo el `SyntaxError` de un JSON inválido). */
8
+ readonly cause?: unknown;
9
+ constructor(message: string, cause?: unknown);
10
+ }
11
+ //# sourceMappingURL=webhook-verification-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-verification-error.d.ts","sourceRoot":"","sources":["../../../src/webhooks/webhook-verification-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,8GAA8G;IAC9G,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;gBAEb,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAQ7C"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhookVerificationError = void 0;
4
+ /**
5
+ * La entrega no se puede tratar como auténtica: falta un header de Standard Webhooks, ninguna firma coincide, el
6
+ * timestamp está fuera de la tolerancia, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento. El
7
+ * receptor la rechaza (por ejemplo con un 400) y no la procesa.
8
+ */
9
+ class WebhookVerificationError extends Error {
10
+ constructor(message, cause) {
11
+ super(message);
12
+ this.name = 'WebhookVerificationError';
13
+ // `cause` como propiedad propia: la opción `{ cause }` de Error no existe en todas las versiones de Node que soporta el SDK.
14
+ if (cause !== undefined) {
15
+ this.cause = cause;
16
+ }
17
+ }
18
+ }
19
+ exports.WebhookVerificationError = WebhookVerificationError;
20
+ //# sourceMappingURL=webhook-verification-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-verification-error.js","sourceRoot":"","sources":["../../../src/webhooks/webhook-verification-error.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,MAAa,wBAAyB,SAAQ,KAAK;IAIjD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,6HAA6H;QAC7H,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACrB,CAAC;IACH,CAAC;CACF;AAZD,4DAYC"}
@@ -0,0 +1,48 @@
1
+ import { WebhookEvent } from '../models/webhook-event';
2
+ /** Un `Headers` de fetch (o cualquier objeto con `get` que no distinga mayúsculas). */
3
+ export interface WebhookHeadersGetter {
4
+ get(name: string): string | null;
5
+ }
6
+ /**
7
+ * Los headers de la petición recibida: el objeto `req.headers` de Node/Express (valores `string` o `string[]`; de un
8
+ * arreglo se usa el primer valor) o un `Headers` de fetch. Los nombres se comparan sin distinguir mayúsculas.
9
+ */
10
+ export type WebhookHeaders = WebhookHeadersGetter | Readonly<Record<string, string | readonly string[] | undefined>>;
11
+ /**
12
+ * Verificación de las entregas de webhooks de FiscalAPI, que se firman con Standard Webhooks
13
+ * (https://www.standardwebhooks.com): HMAC-SHA256 sobre `webhook-id.webhook-timestamp.cuerpo` con el secreto `whsec_…`
14
+ * del webhook, en el header `webhook-signature` como `v1,<base64>`. La firma es la única prueba de que una entrega viene
15
+ * de FiscalAPI.
16
+ */
17
+ export declare class Webhook {
18
+ /**
19
+ * Diferencia máxima, en segundos, entre `webhook-timestamp` y el reloj del receptor, hacia atrás o hacia adelante: una
20
+ * entrega capturada no se puede repetir después. 5 minutos.
21
+ */
22
+ static readonly DEFAULT_TOLERANCE_SECONDS: number;
23
+ private constructor();
24
+ /**
25
+ * Verifica una entrega y devuelve su evento. Con varios secretos basta que una firma `v1` del header coincida con uno
26
+ * de ellos: sirve durante una rotación, mientras el receptor despliega el secreto nuevo y conserva el anterior
27
+ * (FiscalAPI firma con ambos durante 24 h).
28
+ *
29
+ * Responda 2xx rápido y procese el evento después, fuera de la petición: FiscalAPI corta cada intento a los 15 s y lo
30
+ * reintenta.
31
+ *
32
+ * @param headers Los headers de la petición recibida: `req.headers` de Node/Express o un `Headers` de fetch.
33
+ * @param body El cuerpo **crudo** tal como llegó (en Express, el `Buffer` de `express.raw({ type: 'application/json' })`),
34
+ * o ese mismo cuerpo como texto. Nunca uno deserializado y vuelto a serializar (`JSON.stringify(req.body)`): cambian
35
+ * sus bytes (espacios, orden, escapes) y la firma deja de coincidir.
36
+ * @param secret El secreto del webhook (`whsec_…`; se acepta también sin el prefijo), o varios.
37
+ * @param toleranceSeconds Tolerancia del timestamp en segundos; por omisión `Webhook.DEFAULT_TOLERANCE_SECONDS`.
38
+ * @returns El evento del cuerpo verificado.
39
+ * @throws {WebhookVerificationError} Falta un header, el timestamp está fuera de la tolerancia, ninguna firma `v1`
40
+ * coincide, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento: rechace la entrega sin procesarla.
41
+ * @throws {TypeError} Un argumento falta o no es del tipo esperado, no hay secretos o uno no es base64: es un error de
42
+ * configuración del receptor, no de la entrega. En una lista indica la posición del secreto, nunca su valor.
43
+ * @throws {RangeError} La tolerancia es negativa o infinita.
44
+ */
45
+ static verify(headers: WebhookHeaders, body: string | Uint8Array, secret: string, toleranceSeconds?: number): WebhookEvent;
46
+ static verify(headers: WebhookHeaders, body: string | Uint8Array, secrets: readonly string[], toleranceSeconds?: number): WebhookEvent;
47
+ }
48
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../../src/webhooks/webhook.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGvD,uFAAuF;AACvF,MAAM,WAAW,oBAAoB;IACnC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAClC;AAED;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,oBAAoB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC;AA8BrH;;;;;GAKG;AACH,qBAAa,OAAO;IAClB;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,yBAAyB,SAAU;IAEnD,OAAO;IAEP;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,YAAY;IAC1H,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,YAAY;CAyBvI"}
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Webhook = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const webhook_verification_error_1 = require("./webhook-verification-error");
6
+ const ID_HEADER = 'webhook-id';
7
+ const TIMESTAMP_HEADER = 'webhook-timestamp';
8
+ const SIGNATURE_HEADER = 'webhook-signature';
9
+ const SIGNATURE_VERSION = 'v1';
10
+ const SIGNATURE_SEPARATOR = ' ';
11
+ const VERSION_SEPARATOR = ',';
12
+ const SECRET_PREFIX = 'whsec_';
13
+ // Base64 estricto, como Convert.FromBase64String: Buffer.from(texto, 'base64') ignora en silencio lo que no es base64.
14
+ const STRICT_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
15
+ // Solo dígitos: un signo, espacios o decimales no son segundos Unix.
16
+ const UNIX_SECONDS = /^[0-9]+$/;
17
+ // El mayor entero de 64 bits con signo: un timestamp mayor no es un número de segundos Unix.
18
+ const MAX_INT64 = '9223372036854775807';
19
+ // Un sustituto alto sin bajo detrás, o uno bajo sin alto delante: no tiene representación UTF-8. Buffer y TextEncoder lo
20
+ // cambian en silencio por U+FFFD, así que se busca explícitamente (String.prototype.isWellFormed exige Node 20).
21
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
22
+ // ISO 8601 con la hora: fecha, hora, fracción opcional y zona opcional (Z o ±hh:mm). Sin zona se lee en UTC, como el
23
+ // back la escribe, y no en la zona del proceso.
24
+ const ISO_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
25
+ const NOT_AN_EVENT = 'El cuerpo firmado no es un evento de webhook en JSON.';
26
+ const NOT_AN_EVENT_PREFIX = 'El cuerpo firmado no es un evento de webhook';
27
+ /**
28
+ * Verificación de las entregas de webhooks de FiscalAPI, que se firman con Standard Webhooks
29
+ * (https://www.standardwebhooks.com): HMAC-SHA256 sobre `webhook-id.webhook-timestamp.cuerpo` con el secreto `whsec_…`
30
+ * del webhook, en el header `webhook-signature` como `v1,<base64>`. La firma es la única prueba de que una entrega viene
31
+ * de FiscalAPI.
32
+ */
33
+ class Webhook {
34
+ constructor() { }
35
+ static verify(headers, body, secretOrSecrets, toleranceSeconds = Webhook.DEFAULT_TOLERANCE_SECONDS) {
36
+ const keys = decodeSecrets(secretOrSecrets);
37
+ if (headers === null || typeof headers !== 'object') {
38
+ throw new TypeError('Los headers de la petición son obligatorios.');
39
+ }
40
+ if (typeof body !== 'string' && !(body instanceof Uint8Array)) {
41
+ throw new TypeError('El cuerpo debe ser el texto o los bytes crudos de la petición.');
42
+ }
43
+ ensureValidTolerance(toleranceSeconds);
44
+ const id = requiredHeader(headers, ID_HEADER);
45
+ const timestamp = requiredHeader(headers, TIMESTAMP_HEADER);
46
+ const signatures = requiredHeader(headers, SIGNATURE_HEADER);
47
+ ensureWithinTolerance(timestamp, toleranceSeconds);
48
+ const text = bodyText(body);
49
+ ensureSigned(keys, signedContent(id, timestamp, text), signatures);
50
+ return readEvent(text);
51
+ }
52
+ }
53
+ exports.Webhook = Webhook;
54
+ /**
55
+ * Diferencia máxima, en segundos, entre `webhook-timestamp` y el reloj del receptor, hacia atrás o hacia adelante: una
56
+ * entrega capturada no se puede repetir después. 5 minutos.
57
+ */
58
+ Webhook.DEFAULT_TOLERANCE_SECONDS = 5 * 60;
59
+ function decodeSecrets(secretOrSecrets) {
60
+ if (typeof secretOrSecrets === 'string') {
61
+ return [decodeSecret(secretOrSecrets, 'El secreto de firma')];
62
+ }
63
+ if (!Array.isArray(secretOrSecrets)) {
64
+ throw new TypeError('El secreto de firma (whsec_…) o la lista de secretos es obligatorio.');
65
+ }
66
+ if (secretOrSecrets.length === 0) {
67
+ throw new TypeError('Se necesita al menos un secreto de firma (whsec_…).');
68
+ }
69
+ return secretOrSecrets.map((secret, index) => decodeSecret(secret, `El secreto de firma en la posición ${index} de secrets`));
70
+ }
71
+ // Los mensajes nombran el secreto por su posición y nunca incluyen su valor: terminarían en los logs del receptor.
72
+ function decodeSecret(secret, description) {
73
+ if (typeof secret !== 'string') {
74
+ throw new TypeError(`${description} no es texto.`);
75
+ }
76
+ const encoded = secret.startsWith(SECRET_PREFIX) ? secret.substring(SECRET_PREFIX.length) : secret;
77
+ if (!STRICT_BASE64.test(encoded)) {
78
+ throw new TypeError(`${description} no es whsec_ seguido de base64: cópielo completo del webhook.`);
79
+ }
80
+ const key = Buffer.from(encoded, 'base64');
81
+ if (key.length === 0) {
82
+ throw new TypeError(`${description} está vacío.`);
83
+ }
84
+ return key;
85
+ }
86
+ function ensureValidTolerance(toleranceSeconds) {
87
+ if (typeof toleranceSeconds !== 'number' || Number.isNaN(toleranceSeconds)) {
88
+ throw new TypeError('La tolerancia debe ser un número de segundos.');
89
+ }
90
+ if (toleranceSeconds < 0 || !Number.isFinite(toleranceSeconds)) {
91
+ throw new RangeError('La tolerancia no puede ser negativa ni infinita.');
92
+ }
93
+ }
94
+ // El texto del cuerpo; uno en bytes debe ser UTF-8 válido: decodificarlo con reemplazos verificaría otro texto.
95
+ function bodyText(body) {
96
+ if (typeof body === 'string') {
97
+ return body;
98
+ }
99
+ const bytes = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
100
+ const text = bytes.toString('utf8');
101
+ if (!Buffer.from(text, 'utf8').equals(bytes)) {
102
+ throw new webhook_verification_error_1.WebhookVerificationError('El cuerpo o un header no es texto UTF-8 válido.');
103
+ }
104
+ return text;
105
+ }
106
+ function requiredHeader(headers, name) {
107
+ const value = isHeadersGetter(headers) ? headers.get(name) : recordHeader(headers, name);
108
+ if (!value) {
109
+ throw new webhook_verification_error_1.WebhookVerificationError(`Falta el header ${name}.`);
110
+ }
111
+ return value;
112
+ }
113
+ function isHeadersGetter(headers) {
114
+ return typeof headers.get === 'function';
115
+ }
116
+ function recordHeader(headers, name) {
117
+ const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name);
118
+ const value = key === undefined ? undefined : headers[key];
119
+ return typeof value === 'string' ? value : value === null || value === void 0 ? void 0 : value[0];
120
+ }
121
+ function ensureWithinTolerance(timestamp, toleranceSeconds) {
122
+ if (!isInt64UnixSeconds(timestamp)) {
123
+ throw new webhook_verification_error_1.WebhookVerificationError(`El header ${TIMESTAMP_HEADER} no es un número de segundos Unix.`);
124
+ }
125
+ // En segundos enteros. Un timestamp enorme pierde precisión como número, pero sigue lejísimos del reloj y se rechaza
126
+ // por la tolerancia, sin desbordarse.
127
+ const nowSeconds = Math.floor(Date.now() / 1000);
128
+ if (Math.abs(nowSeconds - Number(timestamp)) > toleranceSeconds) {
129
+ throw new webhook_verification_error_1.WebhookVerificationError(`El header ${TIMESTAMP_HEADER} difiere más de ${toleranceSeconds} s del reloj del receptor: ` +
130
+ 'puede ser una entrega repetida o un reloj desajustado.');
131
+ }
132
+ }
133
+ function isInt64UnixSeconds(timestamp) {
134
+ if (!UNIX_SECONDS.test(timestamp)) {
135
+ return false;
136
+ }
137
+ const digits = timestamp.replace(/^0+(?=\d)/, '');
138
+ return digits.length < MAX_INT64.length || (digits.length === MAX_INT64.length && digits <= MAX_INT64);
139
+ }
140
+ // El contenido firmado en UTF-8 estricto, con el timestamp tal como llegó.
141
+ function signedContent(id, timestamp, body) {
142
+ const content = `${id}.${timestamp}.${body}`;
143
+ if (LONE_SURROGATE.test(content)) {
144
+ throw new webhook_verification_error_1.WebhookVerificationError('El cuerpo o un header no es texto UTF-8 válido.');
145
+ }
146
+ return Buffer.from(content, 'utf8');
147
+ }
148
+ function ensureSigned(keys, content, signatureHeader) {
149
+ const expected = keys.map((key) => Buffer.from((0, crypto_1.createHmac)('sha256', key).update(content).digest('base64'), 'utf8'));
150
+ const verified = signatureHeader
151
+ .split(SIGNATURE_SEPARATOR)
152
+ .map(v1Signature)
153
+ .some((signature) => signature !== null && expected.some((candidate) => constantTimeEquals(candidate, signature)));
154
+ if (!verified) {
155
+ throw new webhook_verification_error_1.WebhookVerificationError(`Ninguna firma ${SIGNATURE_VERSION} del header ${SIGNATURE_HEADER} coincide con el cuerpo y el secreto.`);
156
+ }
157
+ }
158
+ // La firma de una entrada "v1,<base64>"; null si es de otra versión o no tiene versión.
159
+ function v1Signature(entry) {
160
+ const separator = entry.indexOf(VERSION_SEPARATOR);
161
+ if (separator < 0 || entry.substring(0, separator) !== SIGNATURE_VERSION) {
162
+ return null;
163
+ }
164
+ return Buffer.from(entry.substring(separator + 1), 'utf8');
165
+ }
166
+ // timingSafeEqual exige el mismo largo; el largo de una firma v1 es público (44), así que comparar el largo antes no
167
+ // filtra nada.
168
+ function constantTimeEquals(expected, actual) {
169
+ return expected.length === actual.length && (0, crypto_1.timingSafeEqual)(expected, actual);
170
+ }
171
+ // JSON.parse no tiene configuración global y rechaza el contenido sobrante; aquí se exige además un objeto.
172
+ function readEvent(body) {
173
+ let parsed;
174
+ try {
175
+ parsed = JSON.parse(body);
176
+ }
177
+ catch (error) {
178
+ throw new webhook_verification_error_1.WebhookVerificationError(NOT_AN_EVENT, error);
179
+ }
180
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
181
+ throw new webhook_verification_error_1.WebhookVerificationError(NOT_AN_EVENT);
182
+ }
183
+ const envelope = parsed;
184
+ ensureEnvelopeShape(envelope);
185
+ if (isPresent(envelope.createdAt)) {
186
+ envelope.createdAt = createdAtDate(envelope.createdAt);
187
+ }
188
+ return envelope;
189
+ }
190
+ // Validación mínima de la forma: los campos que el SDK lee tienen el tipo del contrato si vienen; ausentes o null se
191
+ // aceptan, igual que los campos desconocidos.
192
+ function ensureEnvelopeShape(envelope) {
193
+ ensureTextIfPresent(envelope, 'id');
194
+ ensureTextIfPresent(envelope, 'type');
195
+ ensureTextIfPresent(envelope, 'createdAt');
196
+ ensureObjectIfPresent(envelope, 'data');
197
+ if (isPresent(envelope.data)) {
198
+ ensureObjectIfPresent(envelope.data, 'relatedObject');
199
+ }
200
+ }
201
+ function ensureTextIfPresent(owner, field) {
202
+ if (isPresent(owner[field]) && typeof owner[field] !== 'string') {
203
+ throw invalidField(`el campo ${field} no es texto`);
204
+ }
205
+ }
206
+ function ensureObjectIfPresent(owner, field) {
207
+ const value = owner[field];
208
+ if (isPresent(value) && (typeof value !== 'object' || Array.isArray(value))) {
209
+ throw invalidField(`el campo ${field} no es un objeto`);
210
+ }
211
+ }
212
+ function isPresent(value) {
213
+ return value !== undefined && value !== null;
214
+ }
215
+ function invalidField(problem) {
216
+ return new webhook_verification_error_1.WebhookVerificationError(`${NOT_AN_EVENT_PREFIX}: ${problem}.`);
217
+ }
218
+ // new Date() rueda una fecha imposible (30 de febrero → 2 de marzo, 24:00 → día siguiente): la fecha y la hora
219
+ // reconstruidas deben ser las mismas que llegaron.
220
+ function createdAtDate(value) {
221
+ const parts = ISO_DATE_TIME.exec(value);
222
+ if (parts === null) {
223
+ throw invalidField('el campo createdAt no es una fecha ISO 8601');
224
+ }
225
+ const [year, month, day, hour, minute, second] = parts.slice(1, 7).map(Number);
226
+ const wallClock = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
227
+ const sameWallClock = wallClock.getUTCFullYear() === year &&
228
+ wallClock.getUTCMonth() === month - 1 &&
229
+ wallClock.getUTCDate() === day &&
230
+ wallClock.getUTCHours() === hour &&
231
+ wallClock.getUTCMinutes() === minute &&
232
+ wallClock.getUTCSeconds() === second;
233
+ const offsetMinutes = utcOffsetMinutes(parts[8], parts[9], parts[10]);
234
+ if (!sameWallClock || offsetMinutes === null) {
235
+ throw invalidField('el campo createdAt no es una fecha ISO 8601 posible');
236
+ }
237
+ const fractionMs = parts[7] ? Math.floor(Number(parts[7]) * 1000) : 0;
238
+ return new Date(wallClock.getTime() + fractionMs - offsetMinutes * 60000);
239
+ }
240
+ // Minutos de la zona ±hh:mm (0 sin zona o con Z); null si la zona no existe.
241
+ function utcOffsetMinutes(sign, hours, minutes) {
242
+ if (sign === undefined) {
243
+ return 0;
244
+ }
245
+ const h = Number(hours);
246
+ const m = Number(minutes);
247
+ if (h > 23 || m > 59) {
248
+ return null;
249
+ }
250
+ return (sign === '-' ? -1 : 1) * (h * 60 + m);
251
+ }
252
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","sourceRoot":"","sources":["../../../src/webhooks/webhook.ts"],"names":[],"mappings":";;;AAAA,mCAAqD;AAErD,6EAAwE;AAa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AAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAChD,CAAC"}
@@ -32,6 +32,11 @@ export type { SatValidationType, SatValidationTypeStatus, SatValidationStatus, S
32
32
  export { SatValidationTypeIds, SatValidationStatusIds } from './models/sat-validation';
33
33
  export type { Ticket, TicketIssuer, TicketItem, TicketItemTax, TicketEvent, TicketIngestionResult, TicketCodeResult, TicketListFilters } from './models/ticket';
34
34
  export { TicketStatus, TicketEventType, TicketActorType } from './models/ticket';
35
+ export type { WebhookEvent, WebhookEventData, WebhookRelatedObject } from './models/webhook-event';
36
+ export { WebhookEventTypes } from './models/webhook-event';
37
+ export type { WebhookHeaders, WebhookHeadersGetter } from './webhooks/webhook';
38
+ export { Webhook } from './webhooks/webhook';
39
+ export { WebhookVerificationError } from './webhooks/webhook-verification-error';
35
40
  export type { FiscalapiSettings } from './common/fiscalapi-settings';
36
41
  export type { ApiResponse, ValidationFailure, ProblemDetails } from './common/api-response';
37
42
  export type { FileResponse } from './common/file-response';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,YAAY,EAAE,gBAAgB,EAAE,MAAM,2CAA2C,CAAC;AAElF,YAAY,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,4CAA4C,CAAC;AAClJ,YAAY,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC/E,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAChF,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAChF,YAAY,EAAE,gBAAgB,EAAE,MAAM,2CAA2C,CAAC;AAClF,YAAY,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AAC9E,YAAY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M,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC"}
package/dist/esm/index.js CHANGED
@@ -3,6 +3,9 @@ export { FiscalapiClient } from './services/fiscalapi-client.js';
3
3
  export { StampTransactionType, StampTransactionStatus, CreditType } from './models/stamp.js';
4
4
  export { SatValidationTypeIds, SatValidationStatusIds } from './models/sat-validation.js';
5
5
  export { TicketStatus, TicketEventType, TicketActorType } from './models/ticket.js';
6
+ export { WebhookEventTypes } from './models/webhook-event.js';
7
+ export { Webhook } from './webhooks/webhook.js';
8
+ export { WebhookVerificationError } from './webhooks/webhook-verification-error.js';
6
9
  //Values
7
10
  export { PagedList } from './common/paged-list.js';
8
11
  export { BaseDto } from './common/base-dto.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,mBAAmB;AAEnB,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAsI9D,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,UAAU,EACX,MAAM,gBAAgB,CAAC;AAUxB,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACvB,MAAM,yBAAyB,CAAC;AAajC,OAAO,EACL,YAAY,EACZ,eAAe,EACf,eAAe,EAChB,MAAM,iBAAiB,CAAC;AASzB,QAAQ;AACR,OAAQ,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAQ,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC7C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C;AAClF,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Un evento de webhook de FiscalAPI: el mismo sobre para todo tipo de evento. Lo devuelve `Webhook.verify` después de
3
+ * validar la firma. Es una notificación ligera: para el estado autoritativo del recurso (el orden de llegada no está
4
+ * garantizado), consulte `data.relatedObject` con el servicio de su tipo (por ejemplo `client.invoices.getById(id)`).
5
+ */
6
+ export interface WebhookEvent {
7
+ /**
8
+ * Id del evento; es también el header `webhook-id` y no cambia entre reintentos: úselo para descartar entregas
9
+ * repetidas.
10
+ */
11
+ id: string;
12
+ /**
13
+ * Tipo de evento (ver `WebhookEventTypes`). Es texto y no un enum: un tipo que esta versión del SDK no conoce llega
14
+ * tal cual, sin error, y se ignora.
15
+ */
16
+ type: string;
17
+ /** Momento del cambio de estado, al segundo. El sobre lo trae en UTC (`2026-10-12T18:47:53Z`). */
18
+ createdAt: Date;
19
+ /** Persona del tenant dueña del recurso; null si el recurso no tiene una (factura emitida por valores). */
20
+ personId: string | null;
21
+ /** El recurso que cambió y sus estados. */
22
+ data: WebhookEventData;
23
+ }
24
+ /** Datos de un `WebhookEvent`. */
25
+ export interface WebhookEventData {
26
+ /** El recurso que cambió de estado. */
27
+ relatedObject: WebhookRelatedObject;
28
+ /**
29
+ * Estado al que llegó el recurso, con los códigos públicos de la API v4 (factura `V`, `C`, `X`; solicitud de descarga
30
+ * `1`, `2`, `3`, `-1`; regla de descarga `1`..`4`, `-1`); null si el tipo de evento no lo lleva.
31
+ */
32
+ status: string | null;
33
+ /** Estado del que salió el recurso, con los mismos códigos que `status`; null si no aplica. */
34
+ previousStatus: string | null;
35
+ }
36
+ /** El recurso al que se refiere un `WebhookEvent`. */
37
+ export interface WebhookRelatedObject {
38
+ /** Id del recurso: el que reciben los `getById` de los servicios del SDK. */
39
+ id: string;
40
+ /**
41
+ * Tipo de recurso: `invoice`, `download_request`, `download_rule` o `webhook` (el de
42
+ * `WebhookEventTypes.WebhookTest`); el conjunto puede crecer.
43
+ */
44
+ type: string;
45
+ /**
46
+ * Ruta relativa del GET v4 del recurso (por ejemplo `/api/v4/invoices/{id}`), sin host: el mismo evento es idéntico
47
+ * en pruebas y en producción. Para leer el recurso use su servicio con `id`.
48
+ */
49
+ url: string;
50
+ }
51
+ /**
52
+ * Tipos de evento de webhook, como llegan en `WebhookEvent.type`. Los de un cambio de estado nombran el estado al que
53
+ * llegó el recurso. Son una ayuda para comparar: el catálogo puede crecer y un tipo desconocido se ignora.
54
+ */
55
+ export declare const WebhookEventTypes: {
56
+ /** La factura pasó de vigente a cancelación en proceso (`V` → `C`). */
57
+ readonly InvoiceCancellationRequested: "invoice.cancellation_requested";
58
+ /** La cancelación en proceso terminó y la factura quedó cancelada (`C` → `X`). */
59
+ readonly InvoiceCanceled: "invoice.canceled";
60
+ /** La cancelación en proceso se rechazó y la factura volvió a vigente (`C` → `V`). */
61
+ readonly InvoiceCancellationRejected: "invoice.cancellation_rejected";
62
+ /** La solicitud de descarga masiva terminó con éxito (→ `3`). */
63
+ readonly DownloadRequestCompleted: "download_request.completed";
64
+ /**
65
+ * La solicitud de descarga masiva se abandonó (→ `-1`). No implica un error: el motivo está en la solicitud
66
+ * (`client.downloadRequests.getById(id)`).
67
+ */
68
+ readonly DownloadRequestAbandoned: "download_request.abandoned";
69
+ /** La regla de descarga masiva quedó suspendida (`2` → `4`). */
70
+ readonly DownloadRuleSuspended: "download_rule.suspended";
71
+ /**
72
+ * Prueba de un webhook: no se suscribe; llega solo al pulsar "Enviar prueba" (`POST /api/v4/webhooks/{id}/test`), y
73
+ * solo a ese webhook. Su `data.relatedObject` es el webhook mismo (`type` `webhook`, `url` `/api/v4/webhooks/{id}`),
74
+ * sin persona ni estados.
75
+ */
76
+ readonly WebhookTest: "webhook.test";
77
+ };
78
+ //# sourceMappingURL=webhook-event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-event.d.ts","sourceRoot":"","sources":["../../../src/models/webhook-event.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb,kGAAkG;IAClG,SAAS,EAAE,IAAI,CAAC;IAEhB,2GAA2G;IAC3G,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IAExB,2CAA2C;IAC3C,IAAI,EAAE,gBAAgB,CAAC;CACxB;AAED,kCAAkC;AAClC,MAAM,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,aAAa,EAAE,oBAAoB,CAAC;IAEpC;;;OAGG;IACH,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEtB,+FAA+F;IAC/F,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,sDAAsD;AACtD,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB;IAC5B,uEAAuE;;IAEvE,kFAAkF;;IAElF,sFAAsF;;IAEtF,iEAAiE;;IAEjE;;;OAGG;;IAEH,gEAAgE;;IAEhE;;;;OAIG;;CAEK,CAAC"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Tipos de evento de webhook, como llegan en `WebhookEvent.type`. Los de un cambio de estado nombran el estado al que
3
+ * llegó el recurso. Son una ayuda para comparar: el catálogo puede crecer y un tipo desconocido se ignora.
4
+ */
5
+ export const WebhookEventTypes = {
6
+ /** La factura pasó de vigente a cancelación en proceso (`V` → `C`). */
7
+ InvoiceCancellationRequested: 'invoice.cancellation_requested',
8
+ /** La cancelación en proceso terminó y la factura quedó cancelada (`C` → `X`). */
9
+ InvoiceCanceled: 'invoice.canceled',
10
+ /** La cancelación en proceso se rechazó y la factura volvió a vigente (`C` → `V`). */
11
+ InvoiceCancellationRejected: 'invoice.cancellation_rejected',
12
+ /** La solicitud de descarga masiva terminó con éxito (→ `3`). */
13
+ DownloadRequestCompleted: 'download_request.completed',
14
+ /**
15
+ * La solicitud de descarga masiva se abandonó (→ `-1`). No implica un error: el motivo está en la solicitud
16
+ * (`client.downloadRequests.getById(id)`).
17
+ */
18
+ DownloadRequestAbandoned: 'download_request.abandoned',
19
+ /** La regla de descarga masiva quedó suspendida (`2` → `4`). */
20
+ DownloadRuleSuspended: 'download_rule.suspended',
21
+ /**
22
+ * Prueba de un webhook: no se suscribe; llega solo al pulsar "Enviar prueba" (`POST /api/v4/webhooks/{id}/test`), y
23
+ * solo a ese webhook. Su `data.relatedObject` es el webhook mismo (`type` `webhook`, `url` `/api/v4/webhooks/{id}`),
24
+ * sin persona ni estados.
25
+ */
26
+ WebhookTest: 'webhook.test',
27
+ };
28
+ //# sourceMappingURL=webhook-event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-event.js","sourceRoot":"","sources":["../../../src/models/webhook-event.ts"],"names":[],"mappings":"AA6DA;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,uEAAuE;IACvE,4BAA4B,EAAE,gCAAgC;IAC9D,kFAAkF;IAClF,eAAe,EAAE,kBAAkB;IACnC,sFAAsF;IACtF,2BAA2B,EAAE,+BAA+B;IAC5D,iEAAiE;IACjE,wBAAwB,EAAE,4BAA4B;IACtD;;;OAGG;IACH,wBAAwB,EAAE,4BAA4B;IACtD,gEAAgE;IAChE,qBAAqB,EAAE,yBAAyB;IAChD;;;;OAIG;IACH,WAAW,EAAE,cAAc;CACnB,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * La entrega no se puede tratar como auténtica: falta un header de Standard Webhooks, ninguna firma coincide, el
3
+ * timestamp está fuera de la tolerancia, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento. El
4
+ * receptor la rechaza (por ejemplo con un 400) y no la procesa.
5
+ */
6
+ export declare class WebhookVerificationError extends Error {
7
+ /** El error original cuando la causa es otra excepción (por ejemplo el `SyntaxError` de un JSON inválido). */
8
+ readonly cause?: unknown;
9
+ constructor(message: string, cause?: unknown);
10
+ }
11
+ //# sourceMappingURL=webhook-verification-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-verification-error.d.ts","sourceRoot":"","sources":["../../../src/webhooks/webhook-verification-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,wBAAyB,SAAQ,KAAK;IACjD,8GAA8G;IAC9G,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;gBAEb,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAQ7C"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * La entrega no se puede tratar como auténtica: falta un header de Standard Webhooks, ninguna firma coincide, el
3
+ * timestamp está fuera de la tolerancia, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento. El
4
+ * receptor la rechaza (por ejemplo con un 400) y no la procesa.
5
+ */
6
+ export class WebhookVerificationError extends Error {
7
+ constructor(message, cause) {
8
+ super(message);
9
+ this.name = 'WebhookVerificationError';
10
+ // `cause` como propiedad propia: la opción `{ cause }` de Error no existe en todas las versiones de Node que soporta el SDK.
11
+ if (cause !== undefined) {
12
+ this.cause = cause;
13
+ }
14
+ }
15
+ }
16
+ //# sourceMappingURL=webhook-verification-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook-verification-error.js","sourceRoot":"","sources":["../../../src/webhooks/webhook-verification-error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAIjD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,6HAA6H;QAC7H,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACrB,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,48 @@
1
+ import { WebhookEvent } from '../models/webhook-event';
2
+ /** Un `Headers` de fetch (o cualquier objeto con `get` que no distinga mayúsculas). */
3
+ export interface WebhookHeadersGetter {
4
+ get(name: string): string | null;
5
+ }
6
+ /**
7
+ * Los headers de la petición recibida: el objeto `req.headers` de Node/Express (valores `string` o `string[]`; de un
8
+ * arreglo se usa el primer valor) o un `Headers` de fetch. Los nombres se comparan sin distinguir mayúsculas.
9
+ */
10
+ export type WebhookHeaders = WebhookHeadersGetter | Readonly<Record<string, string | readonly string[] | undefined>>;
11
+ /**
12
+ * Verificación de las entregas de webhooks de FiscalAPI, que se firman con Standard Webhooks
13
+ * (https://www.standardwebhooks.com): HMAC-SHA256 sobre `webhook-id.webhook-timestamp.cuerpo` con el secreto `whsec_…`
14
+ * del webhook, en el header `webhook-signature` como `v1,<base64>`. La firma es la única prueba de que una entrega viene
15
+ * de FiscalAPI.
16
+ */
17
+ export declare class Webhook {
18
+ /**
19
+ * Diferencia máxima, en segundos, entre `webhook-timestamp` y el reloj del receptor, hacia atrás o hacia adelante: una
20
+ * entrega capturada no se puede repetir después. 5 minutos.
21
+ */
22
+ static readonly DEFAULT_TOLERANCE_SECONDS: number;
23
+ private constructor();
24
+ /**
25
+ * Verifica una entrega y devuelve su evento. Con varios secretos basta que una firma `v1` del header coincida con uno
26
+ * de ellos: sirve durante una rotación, mientras el receptor despliega el secreto nuevo y conserva el anterior
27
+ * (FiscalAPI firma con ambos durante 24 h).
28
+ *
29
+ * Responda 2xx rápido y procese el evento después, fuera de la petición: FiscalAPI corta cada intento a los 15 s y lo
30
+ * reintenta.
31
+ *
32
+ * @param headers Los headers de la petición recibida: `req.headers` de Node/Express o un `Headers` de fetch.
33
+ * @param body El cuerpo **crudo** tal como llegó (en Express, el `Buffer` de `express.raw({ type: 'application/json' })`),
34
+ * o ese mismo cuerpo como texto. Nunca uno deserializado y vuelto a serializar (`JSON.stringify(req.body)`): cambian
35
+ * sus bytes (espacios, orden, escapes) y la firma deja de coincidir.
36
+ * @param secret El secreto del webhook (`whsec_…`; se acepta también sin el prefijo), o varios.
37
+ * @param toleranceSeconds Tolerancia del timestamp en segundos; por omisión `Webhook.DEFAULT_TOLERANCE_SECONDS`.
38
+ * @returns El evento del cuerpo verificado.
39
+ * @throws {WebhookVerificationError} Falta un header, el timestamp está fuera de la tolerancia, ninguna firma `v1`
40
+ * coincide, el cuerpo no es texto UTF-8 válido o el cuerpo firmado no es un evento: rechace la entrega sin procesarla.
41
+ * @throws {TypeError} Un argumento falta o no es del tipo esperado, no hay secretos o uno no es base64: es un error de
42
+ * configuración del receptor, no de la entrega. En una lista indica la posición del secreto, nunca su valor.
43
+ * @throws {RangeError} La tolerancia es negativa o infinita.
44
+ */
45
+ static verify(headers: WebhookHeaders, body: string | Uint8Array, secret: string, toleranceSeconds?: number): WebhookEvent;
46
+ static verify(headers: WebhookHeaders, body: string | Uint8Array, secrets: readonly string[], toleranceSeconds?: number): WebhookEvent;
47
+ }
48
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../../src/webhooks/webhook.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAGvD,uFAAuF;AACvF,MAAM,WAAW,oBAAoB;IACnC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAClC;AAED;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,oBAAoB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC;AA8BrH;;;;;GAKG;AACH,qBAAa,OAAO;IAClB;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAAC,yBAAyB,SAAU;IAEnD,OAAO;IAEP;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,YAAY;IAC1H,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,YAAY;CAyBvI"}
@@ -0,0 +1,248 @@
1
+ import { createHmac, timingSafeEqual } from 'crypto';
2
+ import { WebhookVerificationError } from './webhook-verification-error.js';
3
+ const ID_HEADER = 'webhook-id';
4
+ const TIMESTAMP_HEADER = 'webhook-timestamp';
5
+ const SIGNATURE_HEADER = 'webhook-signature';
6
+ const SIGNATURE_VERSION = 'v1';
7
+ const SIGNATURE_SEPARATOR = ' ';
8
+ const VERSION_SEPARATOR = ',';
9
+ const SECRET_PREFIX = 'whsec_';
10
+ // Base64 estricto, como Convert.FromBase64String: Buffer.from(texto, 'base64') ignora en silencio lo que no es base64.
11
+ const STRICT_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
12
+ // Solo dígitos: un signo, espacios o decimales no son segundos Unix.
13
+ const UNIX_SECONDS = /^[0-9]+$/;
14
+ // El mayor entero de 64 bits con signo: un timestamp mayor no es un número de segundos Unix.
15
+ const MAX_INT64 = '9223372036854775807';
16
+ // Un sustituto alto sin bajo detrás, o uno bajo sin alto delante: no tiene representación UTF-8. Buffer y TextEncoder lo
17
+ // cambian en silencio por U+FFFD, así que se busca explícitamente (String.prototype.isWellFormed exige Node 20).
18
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/;
19
+ // ISO 8601 con la hora: fecha, hora, fracción opcional y zona opcional (Z o ±hh:mm). Sin zona se lee en UTC, como el
20
+ // back la escribe, y no en la zona del proceso.
21
+ const ISO_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))?$/;
22
+ const NOT_AN_EVENT = 'El cuerpo firmado no es un evento de webhook en JSON.';
23
+ const NOT_AN_EVENT_PREFIX = 'El cuerpo firmado no es un evento de webhook';
24
+ /**
25
+ * Verificación de las entregas de webhooks de FiscalAPI, que se firman con Standard Webhooks
26
+ * (https://www.standardwebhooks.com): HMAC-SHA256 sobre `webhook-id.webhook-timestamp.cuerpo` con el secreto `whsec_…`
27
+ * del webhook, en el header `webhook-signature` como `v1,<base64>`. La firma es la única prueba de que una entrega viene
28
+ * de FiscalAPI.
29
+ */
30
+ export class Webhook {
31
+ constructor() { }
32
+ static verify(headers, body, secretOrSecrets, toleranceSeconds = Webhook.DEFAULT_TOLERANCE_SECONDS) {
33
+ const keys = decodeSecrets(secretOrSecrets);
34
+ if (headers === null || typeof headers !== 'object') {
35
+ throw new TypeError('Los headers de la petición son obligatorios.');
36
+ }
37
+ if (typeof body !== 'string' && !(body instanceof Uint8Array)) {
38
+ throw new TypeError('El cuerpo debe ser el texto o los bytes crudos de la petición.');
39
+ }
40
+ ensureValidTolerance(toleranceSeconds);
41
+ const id = requiredHeader(headers, ID_HEADER);
42
+ const timestamp = requiredHeader(headers, TIMESTAMP_HEADER);
43
+ const signatures = requiredHeader(headers, SIGNATURE_HEADER);
44
+ ensureWithinTolerance(timestamp, toleranceSeconds);
45
+ const text = bodyText(body);
46
+ ensureSigned(keys, signedContent(id, timestamp, text), signatures);
47
+ return readEvent(text);
48
+ }
49
+ }
50
+ /**
51
+ * Diferencia máxima, en segundos, entre `webhook-timestamp` y el reloj del receptor, hacia atrás o hacia adelante: una
52
+ * entrega capturada no se puede repetir después. 5 minutos.
53
+ */
54
+ Webhook.DEFAULT_TOLERANCE_SECONDS = 5 * 60;
55
+ function decodeSecrets(secretOrSecrets) {
56
+ if (typeof secretOrSecrets === 'string') {
57
+ return [decodeSecret(secretOrSecrets, 'El secreto de firma')];
58
+ }
59
+ if (!Array.isArray(secretOrSecrets)) {
60
+ throw new TypeError('El secreto de firma (whsec_…) o la lista de secretos es obligatorio.');
61
+ }
62
+ if (secretOrSecrets.length === 0) {
63
+ throw new TypeError('Se necesita al menos un secreto de firma (whsec_…).');
64
+ }
65
+ return secretOrSecrets.map((secret, index) => decodeSecret(secret, `El secreto de firma en la posición ${index} de secrets`));
66
+ }
67
+ // Los mensajes nombran el secreto por su posición y nunca incluyen su valor: terminarían en los logs del receptor.
68
+ function decodeSecret(secret, description) {
69
+ if (typeof secret !== 'string') {
70
+ throw new TypeError(`${description} no es texto.`);
71
+ }
72
+ const encoded = secret.startsWith(SECRET_PREFIX) ? secret.substring(SECRET_PREFIX.length) : secret;
73
+ if (!STRICT_BASE64.test(encoded)) {
74
+ throw new TypeError(`${description} no es whsec_ seguido de base64: cópielo completo del webhook.`);
75
+ }
76
+ const key = Buffer.from(encoded, 'base64');
77
+ if (key.length === 0) {
78
+ throw new TypeError(`${description} está vacío.`);
79
+ }
80
+ return key;
81
+ }
82
+ function ensureValidTolerance(toleranceSeconds) {
83
+ if (typeof toleranceSeconds !== 'number' || Number.isNaN(toleranceSeconds)) {
84
+ throw new TypeError('La tolerancia debe ser un número de segundos.');
85
+ }
86
+ if (toleranceSeconds < 0 || !Number.isFinite(toleranceSeconds)) {
87
+ throw new RangeError('La tolerancia no puede ser negativa ni infinita.');
88
+ }
89
+ }
90
+ // El texto del cuerpo; uno en bytes debe ser UTF-8 válido: decodificarlo con reemplazos verificaría otro texto.
91
+ function bodyText(body) {
92
+ if (typeof body === 'string') {
93
+ return body;
94
+ }
95
+ const bytes = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
96
+ const text = bytes.toString('utf8');
97
+ if (!Buffer.from(text, 'utf8').equals(bytes)) {
98
+ throw new WebhookVerificationError('El cuerpo o un header no es texto UTF-8 válido.');
99
+ }
100
+ return text;
101
+ }
102
+ function requiredHeader(headers, name) {
103
+ const value = isHeadersGetter(headers) ? headers.get(name) : recordHeader(headers, name);
104
+ if (!value) {
105
+ throw new WebhookVerificationError(`Falta el header ${name}.`);
106
+ }
107
+ return value;
108
+ }
109
+ function isHeadersGetter(headers) {
110
+ return typeof headers.get === 'function';
111
+ }
112
+ function recordHeader(headers, name) {
113
+ const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name);
114
+ const value = key === undefined ? undefined : headers[key];
115
+ return typeof value === 'string' ? value : value === null || value === void 0 ? void 0 : value[0];
116
+ }
117
+ function ensureWithinTolerance(timestamp, toleranceSeconds) {
118
+ if (!isInt64UnixSeconds(timestamp)) {
119
+ throw new WebhookVerificationError(`El header ${TIMESTAMP_HEADER} no es un número de segundos Unix.`);
120
+ }
121
+ // En segundos enteros. Un timestamp enorme pierde precisión como número, pero sigue lejísimos del reloj y se rechaza
122
+ // por la tolerancia, sin desbordarse.
123
+ const nowSeconds = Math.floor(Date.now() / 1000);
124
+ if (Math.abs(nowSeconds - Number(timestamp)) > toleranceSeconds) {
125
+ throw new WebhookVerificationError(`El header ${TIMESTAMP_HEADER} difiere más de ${toleranceSeconds} s del reloj del receptor: ` +
126
+ 'puede ser una entrega repetida o un reloj desajustado.');
127
+ }
128
+ }
129
+ function isInt64UnixSeconds(timestamp) {
130
+ if (!UNIX_SECONDS.test(timestamp)) {
131
+ return false;
132
+ }
133
+ const digits = timestamp.replace(/^0+(?=\d)/, '');
134
+ return digits.length < MAX_INT64.length || (digits.length === MAX_INT64.length && digits <= MAX_INT64);
135
+ }
136
+ // El contenido firmado en UTF-8 estricto, con el timestamp tal como llegó.
137
+ function signedContent(id, timestamp, body) {
138
+ const content = `${id}.${timestamp}.${body}`;
139
+ if (LONE_SURROGATE.test(content)) {
140
+ throw new WebhookVerificationError('El cuerpo o un header no es texto UTF-8 válido.');
141
+ }
142
+ return Buffer.from(content, 'utf8');
143
+ }
144
+ function ensureSigned(keys, content, signatureHeader) {
145
+ const expected = keys.map((key) => Buffer.from(createHmac('sha256', key).update(content).digest('base64'), 'utf8'));
146
+ const verified = signatureHeader
147
+ .split(SIGNATURE_SEPARATOR)
148
+ .map(v1Signature)
149
+ .some((signature) => signature !== null && expected.some((candidate) => constantTimeEquals(candidate, signature)));
150
+ if (!verified) {
151
+ throw new WebhookVerificationError(`Ninguna firma ${SIGNATURE_VERSION} del header ${SIGNATURE_HEADER} coincide con el cuerpo y el secreto.`);
152
+ }
153
+ }
154
+ // La firma de una entrada "v1,<base64>"; null si es de otra versión o no tiene versión.
155
+ function v1Signature(entry) {
156
+ const separator = entry.indexOf(VERSION_SEPARATOR);
157
+ if (separator < 0 || entry.substring(0, separator) !== SIGNATURE_VERSION) {
158
+ return null;
159
+ }
160
+ return Buffer.from(entry.substring(separator + 1), 'utf8');
161
+ }
162
+ // timingSafeEqual exige el mismo largo; el largo de una firma v1 es público (44), así que comparar el largo antes no
163
+ // filtra nada.
164
+ function constantTimeEquals(expected, actual) {
165
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
166
+ }
167
+ // JSON.parse no tiene configuración global y rechaza el contenido sobrante; aquí se exige además un objeto.
168
+ function readEvent(body) {
169
+ let parsed;
170
+ try {
171
+ parsed = JSON.parse(body);
172
+ }
173
+ catch (error) {
174
+ throw new WebhookVerificationError(NOT_AN_EVENT, error);
175
+ }
176
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
177
+ throw new WebhookVerificationError(NOT_AN_EVENT);
178
+ }
179
+ const envelope = parsed;
180
+ ensureEnvelopeShape(envelope);
181
+ if (isPresent(envelope.createdAt)) {
182
+ envelope.createdAt = createdAtDate(envelope.createdAt);
183
+ }
184
+ return envelope;
185
+ }
186
+ // Validación mínima de la forma: los campos que el SDK lee tienen el tipo del contrato si vienen; ausentes o null se
187
+ // aceptan, igual que los campos desconocidos.
188
+ function ensureEnvelopeShape(envelope) {
189
+ ensureTextIfPresent(envelope, 'id');
190
+ ensureTextIfPresent(envelope, 'type');
191
+ ensureTextIfPresent(envelope, 'createdAt');
192
+ ensureObjectIfPresent(envelope, 'data');
193
+ if (isPresent(envelope.data)) {
194
+ ensureObjectIfPresent(envelope.data, 'relatedObject');
195
+ }
196
+ }
197
+ function ensureTextIfPresent(owner, field) {
198
+ if (isPresent(owner[field]) && typeof owner[field] !== 'string') {
199
+ throw invalidField(`el campo ${field} no es texto`);
200
+ }
201
+ }
202
+ function ensureObjectIfPresent(owner, field) {
203
+ const value = owner[field];
204
+ if (isPresent(value) && (typeof value !== 'object' || Array.isArray(value))) {
205
+ throw invalidField(`el campo ${field} no es un objeto`);
206
+ }
207
+ }
208
+ function isPresent(value) {
209
+ return value !== undefined && value !== null;
210
+ }
211
+ function invalidField(problem) {
212
+ return new WebhookVerificationError(`${NOT_AN_EVENT_PREFIX}: ${problem}.`);
213
+ }
214
+ // new Date() rueda una fecha imposible (30 de febrero → 2 de marzo, 24:00 → día siguiente): la fecha y la hora
215
+ // reconstruidas deben ser las mismas que llegaron.
216
+ function createdAtDate(value) {
217
+ const parts = ISO_DATE_TIME.exec(value);
218
+ if (parts === null) {
219
+ throw invalidField('el campo createdAt no es una fecha ISO 8601');
220
+ }
221
+ const [year, month, day, hour, minute, second] = parts.slice(1, 7).map(Number);
222
+ const wallClock = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
223
+ const sameWallClock = wallClock.getUTCFullYear() === year &&
224
+ wallClock.getUTCMonth() === month - 1 &&
225
+ wallClock.getUTCDate() === day &&
226
+ wallClock.getUTCHours() === hour &&
227
+ wallClock.getUTCMinutes() === minute &&
228
+ wallClock.getUTCSeconds() === second;
229
+ const offsetMinutes = utcOffsetMinutes(parts[8], parts[9], parts[10]);
230
+ if (!sameWallClock || offsetMinutes === null) {
231
+ throw invalidField('el campo createdAt no es una fecha ISO 8601 posible');
232
+ }
233
+ const fractionMs = parts[7] ? Math.floor(Number(parts[7]) * 1000) : 0;
234
+ return new Date(wallClock.getTime() + fractionMs - offsetMinutes * 60000);
235
+ }
236
+ // Minutos de la zona ±hh:mm (0 sin zona o con Z); null si la zona no existe.
237
+ function utcOffsetMinutes(sign, hours, minutes) {
238
+ if (sign === undefined) {
239
+ return 0;
240
+ }
241
+ const h = Number(hours);
242
+ const m = Number(minutes);
243
+ if (h > 23 || m > 59) {
244
+ return null;
245
+ }
246
+ return (sign === '-' ? -1 : 1) * (h * 60 + m);
247
+ }
248
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","sourceRoot":"","sources":["../../../src/webhooks/webhook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AAErD,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAaxE,MAAM,SAAS,GAAG,YAAY,CAAC;AAC/B,MAAM,gBAAgB,GAAG,mBAAmB,CAAC;AAC7C,MAAM,gBAAgB,GAAG,mBAAmB,CAAC;AAC7C,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,aAAa,GAAG,QAAQ,CAAC;AAE/B,uHAAuH;AACvH,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEzF,qEAAqE;AACrE,MAAM,YAAY,GAAG,UAAU,CAAC;AAEhC,6FAA6F;AAC7F,MAAM,SAAS,GAAG,qBAAqB,CAAC;AAExC,yHAAyH;AACzH,iHAAiH;AACjH,MAAM,cAAc,GAAG,0EAA0E,CAAC;AAElG,qHAAqH;AACrH,gDAAgD;AAChD,MAAM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C,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtE,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,UAAU,GAAG,aAAa,GAAG,KAAK,CAAC,CAAC;AAC5E,CAAC;AAED,6EAA6E;AAC7E,SAAS,gBAAgB,CAAC,IAAwB,EAAE,KAAyB,EAAE,OAA2B;IACxG,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,CAAC,CAAC;IACX,CAAC;IACD,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACxB,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAC1B,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAChD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fiscalapi",
3
- "version": "4.0.439",
3
+ "version": "4.0.450",
4
4
  "description": "SDK de Node.js para Fiscalapi",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",