# Self-hosting

> Run the Open Factura API on your machine with the MH simulator, or deploy it to your own Cloudflare account.

Open Factura is open source ([AGPL-3.0](https://github.com/xaviigna/openfactura/blob/main/LICENSE)
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.

> **No dashboard**
>
>   The self-hosted version has no web dashboard: you manage it with the API, the CLI, or your agent.
>   The dashboard, guided onboarding, and automatic certification tests are part of
>   [Open Factura Cloud](https://openfactura.co).

## On your machine

Requirements: [Bun](https://bun.sh) (the repository pins `bun@1.4.4` in `packageManager`) and Node 20+.

1. **Clone, install, and start the server.**

   ```bash
   git clone https://github.com/xaviigna/openfactura && cd openfactura
   bun install
   cp 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 credentials
   echo "WEBHOOKS_LOCAL=1" >> server/.dev.vars      # webhooks to http://localhost (development only)
   bun run build
   cd server && bun run db:migrate:local
   bun run dev                                      # API and MCP on :8788; leave it running
   ```

   This terminal stays busy: run everything else in another one, from the repository root.

   > **Note**
   >
   > Start the server with `bun run dev` inside `server/`. At the root, `bun run dev` also starts the
   > docs and the CLI `dev` script, which exits with «Falta el comando» and stops everything.

2. **Example files.** Made-up data, but with valid catalog codes (department `06`, municipality
   `23`, district `14`, and activity `62010`, all from San Salvador):

   ```bash
   mkdir -p ~/openfactura-ejemplo
   cat > ~/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": "facturas@empresa-de-prueba.example"
   }
   EOF
   cat > ~/openfactura-ejemplo/factura.json <<'EOF'
   {
     "tipoDte": "01",
     "datos": {
       "items": [
         { "descripcion": "Servicio de consultoría", "cantidad": 3, "precioUni": 56.5, "tipoItem": 2 }
       ]
     }
   }
   EOF
   cat > ~/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": "compras@cliente-de-prueba.example"
       },
       "items": [{ "descripcion": "Licencia anual", "cantidad": 1, "precioUni": 100, "tipoItem": 2 }]
     }
   }
   EOF
   ```

   In the invoice (`01`) `precioUni` includes VAT; in the CCF (`03`) it does not
   ([Issue documents](https://docs.openfactura.co/en/guias/emitir/)). The NIT and NRC are fake; the NIT must have 14 digits
   (or 9) and the NRC 2 to 8.

3. **Create the organization and connect the simulator.** From the repository root, in another
   terminal. You need `jq`. The CLI you just built runs with `node packages/cli/dist/index.js` (the
   `openfactura` `bin` in `packages/cli/package.json`); the function below makes it `openfactura`.
   `OPENFACTURA_PROFILE=local` avoids overwriting any session in `~/.config/openfactura`.

   ```bash
   REPO=$PWD
   openfactura() { node "$REPO/packages/cli/dist/index.js" "$@"; }
   export OPENFACTURA_PROFILE=local OPENFACTURA_URL=http://localhost:8788
   export 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 data
   admin /emisor/credenciales-prueba -X POST                         # simulated certificate and password
   ```

   `alta` creates the organization and stores an `of_test_…` key in the `local` profile; the
   following commands use it through `OPENFACTURA_PROFILE=local`. If you would rather not build the
   CLI, `npx @openfactura/cli` (the version published on npm) does the same: replace the
   `openfactura` function with that command.

4. **Issue and fetch.**

   ```bash
   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`, with `selloRecibido`; the invoice totals `169.5`. Use
   `dte pdf <codigo> -o factura.pdf` for the PDF.

### 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:

```bash
# 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

> **Caution**
>
> The Workers free plan limits CPU to 10 ms per request. Signing (RSA) and generating the PDF exceed
> that limit: use the Workers paid plan.

1. **Database.**

   ```bash
   cd server
   bunx wrangler d1 create openfactura
   ```

   Copy the `database_id` into `server/wrangler.jsonc` and apply the migrations with
   `bun run db:migrate:remote`.

2. **Configuration.** In `server/wrangler.jsonc`, change `vars.APP_URL` to your public URL. Then the
   secrets:

   ```bash
   openssl rand -base64 32 | bunx wrangler secret put BETTER_AUTH_SECRET
   openssl rand -base64 32 | bunx wrangler secret put CRED_KEK_V1
   openssl rand -base64 48 | tee admin-token.txt | bunx wrangler secret put ADMIN_TOKEN
   ```

   `ADMIN_TOKEN` is your operator credential: it creates organizations and manages the issuer, its
   MH credentials, and the API keys. Treat it like a password.

   `CRED_KEK_V1` encrypts the MH credentials of every issuer. **Keep a copy outside Cloudflare.**
   Don't set `WEBHOOKS_LOCAL` in production.

3. **Deploy.**

   ```bash
   cd .. && bun run deploy
   ```

4. **First use.** `npx @openfactura/cli alta "Mi Empresa" --url https://YOUR-DOMAIN`, then with
   `ADMIN_TOKEN` + `X-Organizacion`: `PUT /api/v1/emisor`, `PUT /api/v1/emisor/credenciales/00`
   (API password, `.crt` certificate, and its password), and `POST /api/v1/emisor/probar`. Step by
   step in [`docs/self-hosting.md`](https://github.com/xaviigna/openfactura/blob/main/docs/self-hosting.md)
   (in Spanish).

## 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)

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

1. `bunx wrangler secret put CRED_KEK_V2` with a new key. New values are encrypted with V2; older
   ones are still decrypted with V1.
2. Save each issuer's credentials again.
3. Once no value starts with `v1.`, delete `CRED_KEK_V1`.

Your installation's OpenAPI document is at `https://YOUR-DOMAIN/api/v1/openapi.json`.
