@waitron/verifactu
v0.2.1
Published
AEAT Veri*Factu / SIF protocol library: huella chaining, QR payload, invoice records, XML serialise/parse, and the AEAT SOAP submission client.
Readme
@waitron/verifactu
TypeScript implementation of Spain's Veri*Factu invoicing records: construction, hashing, chaining, validation, QR payloads, SOAP submission and consulta.
Read the English documentation or Spanish documentation. Start with Getting started (English, Spanish); both sites include the API reference.
This library is a tool for building SIFs. It is not itself a SIF. A sistema informático de facturación is a deployed system. Its duties vary by operating mode and include choices that source code cannot make: permanent installation identity, invoice numbering, durable chain/retry state, invoice-document retention, operator UI, and the applicable declaración responsable. See
PROVENANCE.md.
Design
Pure and stateless. Every export is a function over plain data. There is no database, no
persistence, no ambient state and no I/O except through an injected fetch. Chain state,
ordering, retries and storage belong to the caller — chain append has to join the host's
transaction, which a stateful library could not do.
Allocate NumeroInstalacion durably and never reuse it for the same seller, including
after reinstalling the same software. Set IndicadorMultiplesOT from the invoicing operations of
the current SaaS user, not from the software's global tenant count. Drafts and imported invoices
stay outside the record-building boundary; once you issue an invoice, never delete it and reuse
its seller/serial/date identity.
Types mirror AEAT's schema names exactly (RegistroAlta, Encadenamiento, DetalleDesglose);
functions are named in English.
Usage
import {
assertValid,
buildAltaRecord,
buildQrPayload,
type SistemaInformatico,
} from "@waitron/verifactu";
const sistema: SistemaInformatico = {
NombreRazon: "Example SL",
NIF: "B12345674",
NombreSistemaInformatico: "Example POS",
IdSistemaInformatico: "01",
Version: "1.0",
NumeroInstalacion: "001",
TipoUsoPosibleSoloVerifactu: "S",
TipoUsoPosibleMultiOT: "N",
IndicadorMultiplesOT: "N",
};
const record = buildAltaRecord({
IDEmisorFactura: "89890001K",
NumSerieFactura: "T01/000123",
FechaExpedicionFactura: new Date(),
NombreRazonEmisor: "Example SL",
TipoFactura: "F2",
DescripcionOperacion: "Venta en establecimiento",
Desglose: [
{
ClaveRegimen: "01",
CalificacionOperacion: "S1",
BaseImponibleOimporteNoSujeto: "10",
CuotaRepercutida: "2.1",
TipoImpositivo: "21",
},
],
CuotaTotal: "2.1",
ImporteTotal: "12.1",
Encadenamiento: { PrimerRegistro: "S" },
SistemaInformatico: sistema,
generadoEn: new Date(),
// The offset of the zone the invoice is ISSUED in, at the moment of issue —
// not a fixed constant, and not the server's own zone. 120 is Spain's
// summer (CEST) offset; during winter (CET) it is 60. Derive this from the
// issuing location's calendar, never from the runtime environment's zone.
offsetMinutes: 120,
});
assertValid(record);
const qr = buildQrPayload(record, "production");Use NIF for a Spanish software producer. For a producer identified outside Spain, replace NIF
with IDOtro; never provide both. IdSistemaInformatico is always exactly two uppercase letters
from A to Z or digits. The software name and both TipoUsoPosible... flags must contain a value.
Local validation checks these published rules, but only AEAT can confirm that an identity is
registered.
When you upgrade, correct any one-character or lowercase system ID and any blank software name or
usage flag before deploying. Earlier versions accepted those values; assertValid now blocks them.
Use validate when you want to show several issues in a form. Call assertValid immediately before
submission when invalid records should stop the operation. It throws VerifactuValidationError
with a readable message such as SistemaInformatico.NombreSistemaInformatico: ... at most 30
characters (NOMBRE_SISTEMA_LENGTH). Its issues property contains the same structured issues, so
you can report the exact field without parsing the message. A malformed predecessor hash produces
the HUELLA_ANTERIOR_FORMAT warning rather than blocking submission because AEAT classifies the
format problem as non-rejecting. A predecessor hash longer than 64 characters or containing an
XML control character still blocks the record because it breaks the XML schema or parsing. If an
earlier version's fatal issue guarded your chain, handle the warning
explicitly when you upgrade. You should still investigate it before relying on the chain.
The builder calculates each record's own hash from the values it writes to XML. If you change a
hashed field afterward, validate reports HUELLA_MISMATCH as a warning. A malformed hash of at
most 64 characters produces HUELLA_FORMAT as a warning; a longer one is an error because it
breaks AEAT's XML schema. A missing hash or XML control character is also an error. Investigate
either warning before filing, even though AEAT may accept the record with errors.
validate now reports NIF_CONTROL for malformed nine-character Spanish tax IDs. If you block
submission on validation errors, review this new issue when updating from an earlier version.
For K/L/M IDs with letters in their seven-character body, the check covers the shape only.
validate also enforces AEAT's operation-date window, the invoice-family restrictions on
FacturaSimplificadaArt7273 and FacturaSinIdentifDestinatarioArt61d, and the required Macrodato
field at an absolute total of €100,000,000. Recipient-issued and third-party-issued invoices can be
represented with EmitidaPorTerceroODestinatario and Tercero; the builder, XML serializer, and
request parser preserve those fields, while validation checks their required combinations and local
NIF or EU VAT-number structure. Recipient identities receive the corresponding identity-choice,
Spanish-country, type-07, and EU VAT-shape checks. AEAT remains responsible for confirming
registration.
For a cancellation, keep IDEmisorFacturaAnulada equal to Cabecera.ObligadoEmision.NIF; XML
serialization rejects a mismatch. If someone other than the taxpayer generated the cancellation,
provide GeneradoPor and Generador together. The generator needs exactly one NIF or IDOtro,
and its NIF must differ from the taxpayer's. GeneradoPor: "E" requires a NIF. For a Spanish
generator using IDOtro, D permits IDType: "03" or "07", while T requires "03" and
forbids "07" in any country. Local validation also checks NIF shape and EU VAT-number structure;
only AEAT can confirm registration.
The submission header accepts either RemisionVoluntaria (optional FechaFinVeriFactu and
Incidencia) or RemisionRequerimiento (required RefRequerimiento, optional
FinRequerimiento), never both. Omit both blocks for an ordinary voluntary VeriFactu submission.
If you are submitting non-verifiable records under an AEAT requirement, supply the requirement
block explicitly and use SOAP_ENDPOINTS_REQUERIMIENTO (or
SOAP_ENDPOINTS_REQUERIMIENTO_SELLO with a sello certificate) when you create the client. AEAT
keeps that service and its records separate from voluntary VeriFactu; consulta is available only
for voluntary submissions. This library does not determine the operating mode for you. serializeEnvio
checks header NIF form, the reference's 18-character XML limit, and the end date. The date's year
must be the current or preceding year in Madrid; from 1 January 2027 it must be 31-12-20XX.
Pass { now } as its third argument for a controlled local clock. AEAT alone confirms NIF and
requirement-reference registration and uses its own clock. Each submission holds 1–1000 separate
record wrappers, each with exactly one alta or cancellation; serialization and parsing enforce that
shape at runtime.
When you answer an AEAT requirement, send the records as your SIF preserved them. Do not change
their business data to satisfy assertValid: AEAT records business-rule errors as admissible in
this mode, except that NIF or IDOtro identity errors can still reject a record. Check the
response for each record. Include FinRequerimiento: "S" in the header of the final batch, even
when there is only one batch. Voluntary submissions have different correction rules; an accepted
record with errors may still need a new corrected record, except for AEAT's published exemptions.
FechaHoraHusoGenRegistro must identify a real calendar instant with a numeric offset. When it is
more than one minute ahead of the current time, validate returns the non-blocking
FECHA_HORA_FUTURE warning for both alta and cancellation records. Pass { now } as the second
argument when you need a controlled clock; assertValid does not throw for this AEAT advisory.
Detail-line validation also applies AEAT's dated IVA rates and equivalence-surcharge pairings,
BaseImponibleACoste eligibility, reverse-charge and non-subject field rules, and IVA/IGIC
exemption codes. An IVA E5 line requires any supplied recipient to use IDOtro. Cupon: "S"
is limited to R1 and R5 invoices. Regime codes are checked against the IVA, IPSI, or IGIC
list, including each special rule for regimes 02, 03, 04, 06, 07, 08, 10, 11,
14, and IGIC 20. An invalid or missing IPSI regime remains a warning through 31 December 2026,
matching AEAT's acceptance window, and becomes an error on 1 January 2027. The boundary uses the
current instant in the numeric offset carried by FechaHoraHusoGenRegistro. A malformed timestamp
already produces FECHA_HORA_FORMAT, so the IPSI issue stays a warning rather than adding a second
date-derived error. Every S1 line must include TipoImpositivo and CuotaRepercutida; validation
checks the applicable base, sign, and AEAT's ±€10 formula tolerance, except for the published
correction cases. Outside those correction cases, a zero charged tax is valid only when its applicable base times its rate, divided by
100, rounds to 0.00, which is always the case when the base or rate is zero. A nonzero
CuotaRepercutida is otherwise rejected outside S1. For an F2, the sum of every line's base
and charged tax may reach €3,010 including AEAT's +€10 margin. The cap does not apply when you set
NumRegistroAcuerdoFacturacion or FacturaSinIdentifDestinatarioArt61d: "S".
The separate IdAcuerdoSistemaInformatico field carries an optional software-system agreement ID
up to 16 characters. It does not lift the F2 amount cap. AEAT alone can confirm whether either
agreement identifier exists.
A rectificativa (R1-R5) is built the same way, with TipoRectificativa set to say whether it
substitutes (S) or adjusts (I) the original invoice. FacturasRectificadas may identify the
invoice(s) being rectified only on R1-R5. ImporteRectificacion is required for, and allowed
only on, an S correction. FacturasSustituidas is a different field: use it only on an F3
invoice that replaces simplified invoices. For a voluntary Veri*Factu resubmission after an AEAT
rejection, set RechazoPrevio to S or X only together with Subsanacion: "S". A present
reference group must contain at least one invoice; local validation checks each reference's NIF,
1–60-character invoice number, and real date:
const rectificativa = buildAltaRecord({
IDEmisorFactura: "89890001K",
NumSerieFactura: "T01/000124",
FechaExpedicionFactura: new Date(),
NombreRazonEmisor: "Example SL",
TipoFactura: "R1",
TipoRectificativa: "S",
Destinatarios: {
IDDestinatario: [{ NombreRazon: "Customer SL", NIF: "B12345674" }],
},
FacturasRectificadas: [
{
IDEmisorFactura: "89890001K",
NumSerieFactura: "T01/000123",
FechaExpedicionFactura: new Date("2024-01-01"),
},
],
ImporteRectificacion: { BaseRectificada: "10", CuotaRectificada: "2.1" },
DescripcionOperacion: "Rectificación de T01/000123",
Desglose: [
{
ClaveRegimen: "01",
CalificacionOperacion: "S1",
BaseImponibleOimporteNoSujeto: "10",
CuotaRepercutida: "2.1",
TipoImpositivo: "21",
},
],
CuotaTotal: "2.1",
ImporteTotal: "12.1",
Encadenamiento: { PrimerRegistro: "S" },
SistemaInformatico: sistema,
generadoEn: new Date(),
offsetMinutes: 120, // the issuing zone's offset at issue time — see note above, not a constant
});Submission and consulta go through an injected fetch, so certificate handling (mTLS with the
sello de entidad or representative certificate) stays a deployment concern rather than something
this library configures:
import { createClient, SOAP_ENDPOINTS } from "@waitron/verifactu";
const client = createClient({ endpoint: SOAP_ENDPOINTS.production, fetch });
const respuesta = await client.submit(
{ ObligadoEmision: { NombreRazon: sistema.NombreRazon, NIF: "89890001K" } },
[{ RegistroAlta: record }],
);The rule that matters most
Build once and send the record unchanged. The builder formats amounts to two decimal places
and hashes those same strings. If you change a formatted field before serialising, its stored
huella no longer describes the record you send. AEAT allows one or two decimal places, but its
published examples do not establish whether 123.1 and 123.10 require different hashes. Use
the builder's two-decimal form while that boundary remains unverified in preproduction.
Releasing
The first release, 0.1.0, was published by hand from a local checkout with npm publish, so
there was a person present for npm's two-factor prompt.
Every release after that uses npm's Trusted Publishing: pushing a v* tag (for example
v0.1.0) runs the release workflow, which builds, re-runs the pack-smoke check, and publishes the
package to npm. There is no npm token and no stored secret anywhere in this repository — the
workflow proves who it is to npm using a short-lived identity token that GitHub Actions issues for
the run (OIDC). It passes --provenance so npm attaches a
provenance statement to the release.
For this to work, the package's Trusted Publisher is configured on npmjs.com to trust this exact
workflow: organisation waitron-io, repository verifactu, workflow file release.yml. Only a
publish that runs from that workflow, in that repository, is accepted. Trusted Publishing also
needs a recent npm and Node — npm 11.5.1 or later and Node 22.14 or later — which the workflow
installs and provisions itself, so nothing extra is required of a contributor.
Licence
Apache License 2.0. See LICENSE. The AEAT documents this library is implemented
from, and the references consulted, are recorded in PROVENANCE.md.
