Self-hosting
Open Factura is open source (AGPL-3.0 for the server; MIT for the SDK, the CLI, and the skills). It runs as a single Cloudflare Worker with a D1 database: REST API, MCP, webhooks, and reconciliation.
On your machine
Section titled “On your machine”Requirements: Bun (the repository pins [email protected] in packageManager) and Node 20+.
-
Clone, install, and start the server.
Ventana de terminal git clone https://github.com/xaviigna/openfactura && cd openfacturabun installcp server/.dev.vars.example server/.dev.vars # fill in the secrets (openssl rand -base64 32/48)echo "MH_SIMULADO=1" >> server/.dev.vars # MH simulator: issue without Hacienda credentialsecho "WEBHOOKS_LOCAL=1" >> server/.dev.vars # webhooks to http://localhost (development only)bun run buildcd server && bun run db:migrate:localbun run dev # API and MCP on :8788; leave it runningThis terminal stays busy: run everything else in another one, from the repository root.
-
Example files. Made-up data, but with valid catalog codes (department
06, municipality23, district14, and activity62010, all from San Salvador):Ventana de terminal mkdir -p ~/openfactura-ejemplocat > ~/openfactura-ejemplo/emisor.json <<'EOF'{"nit": "0614-010190-101-0","nrc": "1234567","nombre": "EMPRESA DE PRUEBA, S.A. DE C.V.","nombreComercial": "Empresa de Prueba","codActividad": "62010","descActividad": "Programación informática","departamento": "06","municipio": "23","distrito": "14","complemento": "Calle de Prueba #123, San Salvador","telefono": "22220000","correo": "[email protected]"}EOFcat > ~/openfactura-ejemplo/factura.json <<'EOF'{"tipoDte": "01","datos": {"items": [{ "descripcion": "Servicio de consultoría", "cantidad": 3, "precioUni": 56.5, "tipoItem": 2 }]}}EOFcat > ~/openfactura-ejemplo/ccf.json <<'EOF'{"tipoDte": "03","datos": {"receptor": {"nit": "0614-290786-103-1","nrc": "234567-8","nombre": "CLIENTE DE PRUEBA, S.A. DE C.V.","codActividad": "46900","descActividad": "Venta al por mayor de otros productos","direccion": {"departamento": "06","municipio": "23","distrito": "14","complemento": "Av. Olímpica #100"},"correo": "[email protected]"},"items": [{ "descripcion": "Licencia anual", "cantidad": 1, "precioUni": 100, "tipoItem": 2 }]}}EOFIn the invoice (
01)precioUniincludes VAT; in the CCF (03) it does not (Issue documents). The NIT and NRC are fake; the NIT must have 14 digits (or 9) and the NRC 2 to 8. -
Create the organization and connect the simulator. From the repository root, in another terminal. You need
jq. The CLI you just built runs withnode packages/cli/dist/index.js(theopenfacturabininpackages/cli/package.json); the function below makes itopenfactura.OPENFACTURA_PROFILE=localavoids overwriting any session in~/.config/openfactura.Ventana de terminal REPO=$PWDopenfactura() { node "$REPO/packages/cli/dist/index.js" "$@"; }export OPENFACTURA_PROFILE=local OPENFACTURA_URL=http://localhost:8788export OPENFACTURA_ADMIN_TOKEN=$(grep '^ADMIN_TOKEN=' server/.dev.vars | cut -d= -f2-)export ORG=$(openfactura alta "Empresa de Prueba" --json | jq -r .organizacion.id)admin() { curl -sS "$OPENFACTURA_URL/api/v1$1" -H "Authorization: Bearer $OPENFACTURA_ADMIN_TOKEN" \-H "X-Organizacion: $ORG" -H 'Content-Type: application/json' "${@:2}"; }admin /emisor -X PUT -d @$HOME/openfactura-ejemplo/emisor.json # issuer dataadmin /emisor/credenciales-prueba -X POST # simulated certificate and passwordaltacreates the organization and stores anof_test_…key in thelocalprofile; the following commands use it throughOPENFACTURA_PROFILE=local. If you would rather not build the CLI,npx @openfactura/cli(the version published on npm) does the same: replace theopenfacturafunction with that command. -
Issue and fetch.
Ventana de terminal openfactura dte emitir ~/openfactura-ejemplo/factura.json --json | tee /tmp/dte.json | jq '{estado, total}'openfactura dte get "$(jq -r .codigoGeneracion /tmp/dte.json)"openfactura dte emitir ~/openfactura-ejemplo/ccf.json --json | jq '{estado, total}'The state must be
procesado, withselloRecibido; the invoice totals169.5. Usedte pdf <codigo> -o factura.pdffor the PDF.
Establishments and points of sale
Section titled “Establishments and points of sale”The first time you save the issuer, the head office M001 (type 02) and its point of sale
P001 are created automatically. That is enough to issue: the control number comes out as
DTE-01-M001P001-…. You do not need to create anything else for the walkthrough above.
Create your own only if Hacienda assigned you others. The codes (M001, S002, P002…) are
assigned by the MH: use the ones from your registration. An establishment codMh is M, B, S,
or P plus three digits; a point of sale codMh is P plus three digits. Both require
emisor:write (the operator with ADMIN_TOKEN; API keys cannot) and return 201 with the list of
establishments and their points of sale:
# tipo: 01 branch/agency, 02 head office, 04 warehouse, 07 yard (default 01)admin /establecimientos -X POST -d '{"nombre":"Sucursal Centro","tipo":"01","codMh":"S001"}' \ | jq -r '.[] | "\(.id) \(.codMh)"'
admin /puntos-venta -X POST -d '{"establecimientoId":"<establishment id>","nombre":"Caja 2","codMh":"P002"}'A repeated code answers codigo_repetido. To issue from another point of sale, pass its
puntoVentaId in the POST /dte body (otherwise the issuer’s first one is used). Address and phone
data you leave out of the establishment are taken from the issuer.
On your Cloudflare account
Section titled “On your Cloudflare account”-
Database.
Ventana de terminal cd serverbunx wrangler d1 create openfacturaCopy the
database_idintoserver/wrangler.jsoncand apply the migrations withbun run db:migrate:remote. -
Configuration. In
server/wrangler.jsonc, changevars.APP_URLto your public URL. Then the secrets:Ventana de terminal openssl rand -base64 32 | bunx wrangler secret put BETTER_AUTH_SECRETopenssl rand -base64 32 | bunx wrangler secret put CRED_KEK_V1openssl rand -base64 48 | tee admin-token.txt | bunx wrangler secret put ADMIN_TOKENADMIN_TOKENis your operator credential: it creates organizations and manages the issuer, its MH credentials, and the API keys. Treat it like a password.CRED_KEK_V1encrypts the MH credentials of every issuer. Keep a copy outside Cloudflare. Don’t setWEBHOOKS_LOCALin production. -
Deploy.
Ventana de terminal cd .. && bun run deploy -
First use.
npx @openfactura/cli alta "Mi Empresa" --url https://YOUR-DOMAIN, then withADMIN_TOKEN+X-Organizacion:PUT /api/v1/emisor,PUT /api/v1/emisor/credenciales/00(API password,.crtcertificate, and its password), andPOST /api/v1/emisor/probar. Step by step indocs/self-hosting.md(in Spanish).
Variables
Section titled “Variables”| Name | Type | Description |
|---|---|---|
APP_URL |
var | Public URL of the service |
BETTER_AUTH_SECRET |
secret | Session signing |
ADMIN_TOKEN |
secret | Operator credential (32+ characters); without it there is no administration |
CRED_KEK_V1 (V2, …) |
secret | AES-256 master key, 32 bytes in base64 |
LIMITE_CLAVE_POR_MINUTO |
var | Requests per minute per API key (120) |
TRUSTED_ORIGINS |
var | Additional trusted origins, comma-separated |
MH_BASE_URL |
var | Overrides the MH URL (testing only) |
MH_SIMULADO |
var | 1 enables POST /emisor/credenciales-prueba (MH simulator, environment 00) |
WEBHOOKS_LOCAL |
var | 1 allows webhooks to http://localhost (development only) |
TURNSTILE_SECRET |
secret | Cloudflare Turnstile (optional). With it, sign-up, sign-in and the password-reset request require the widget token |
TURNSTILE_SITE_KEY |
var or secret | Public widget key; the dashboard gets it from GET /api/v1/acceso |
TURNSTILE_HOSTNAMES |
var or secret | Domains where the widget is shown, comma-separated; with the secret and no domains, everything is rejected |
Cloudflare Turnstile (optional)
Section titled “Cloudflare Turnstile (optional)”With TURNSTILE_SECRET set, POST /api/auth/sign-up/email, /api/auth/sign-in/email and
/api/auth/request-password-reset require the widget token in the x-turnstile-token header. The
server checks it with Cloudflare (siteverify, with the IP from cf-connecting-ip) before
hashing the password, and requires the action to match that screen (signup, login or
password_reset) and the domain to be in TURNSTILE_HOSTNAMES. Missing or invalid token, or
Cloudflare not answering: 403 turnstile_invalido. All three variables can be secrets or vars;
without TURNSTILE_SECRET everything works as before. Don’t put localhost in production domains.
To test locally or in CI, use Cloudflare’s test keys: site key 1x00000000000000000000AA with
secret 1x0000000000000000000000000000000AA always pass; secret
2x0000000000000000000000000000000AA (and site key 2x00000000000000000000AB) always block. With
them, Cloudflare answers without action, with hostname example.com and the
metadata.result_with_testing_key flag: only then does the server accept a response without an
action, and example.com must be in TURNSTILE_HOSTNAMES (e.g. localhost,example.com). If the
widget can’t load (an ad blocker or a firewall), the dashboard says so and offers to retry.
Rotating the master key
Section titled “Rotating the master key”bunx wrangler secret put CRED_KEK_V2with a new key. New values are encrypted with V2; older ones are still decrypted with V1.- Save each issuer’s credentials again.
- Once no value starts with
v1., deleteCRED_KEK_V1.
Your installation’s OpenAPI document is at https://YOUR-DOMAIN/api/v1/openapi.json.
For AI assistants: llms.txt ·llms-full.txt ·every page as Markdown by adding .md to its path.