# Deploying Nota behind HTTPS + Authelia

Goal: `https://nota.example.com` is reachable from anywhere, every page of the
web UI sits behind Authelia, and still **everything works** — the phone capture
userscript, the Chrome extension, Tasker/Shortcuts, cron jobs (due-date
reminders, Tandoor sync), the public shopping-list links and `safe-update.sh`.

Written for Authelia **4.38 or newer** (the `/api/authz/*` endpoints and the
`session.cookies` list). Replace `nota.example.com`, `auth.example.com` and
`example.com` throughout. Cross-check proxy snippets against the official
integration guides if your proxy version differs:
<https://www.authelia.com/integration/proxies/>.

## 1. Why some paths must bypass Authelia

Authelia works by cookie: a browser that has logged in to `auth.example.com`
carries a session cookie, and the proxy asks Authelia "may this request
through?" before forwarding it. That is exactly right for people using the web
UI, and wrong for everything that **cannot** carry that cookie:

| Caller | Why it can't use Authelia | Protected instead by |
| --- | --- | --- |
| Phone capture userscript (`GM.xmlHttpRequest`) | runs from the SEFAZ page; userscript managers don't reliably send cookies for another site | automation token (Bearer), from pairing |
| Chrome extension | cross-origin, and the CORS **preflight** (`OPTIONS`) would be redirected to the login page → fails before any request is sent | automation token |
| Tasker / iOS Shortcuts / cron / n8n | no browser at all | automation token |
| Userscript install **and auto-update** (`/capture/nota-capture.user.js`) | the userscript manager re-downloads it itself, without your cookies; it would receive Authelia's login page and break | nothing needed: the file holds no secret |
| Pairing link from the QR (`/static/capturar.html#pair=…`) | **the part after `#` never reaches a server**, so after an Authelia login redirect the pairing code is gone. A phone with no Authelia session (e.g. your wife's, first time) could never pair from the QR | the page holds no data; everything on it needs the app login or a pairing code |
| Public shopping-list links (`/static/lista-publica.html?token=…`) | meant for people without an account | the unguessable share token |
| Home-screen icon (`/static/manifest.webmanifest`, `/static/icons/`) | browsers fetch them for "Add to Home Screen" without the session cookie | nothing needed: name + icon only |

Everything under `/api/v1/` already refuses requests without a valid token
(the app's own JWT login), so bypassing Authelia there removes the *second*
lock, not the only one. Two API paths are the exception and **stay behind
Authelia**: `auth/login` and `auth/register`. That keeps password guessing and
self-registration reachable only by people who already passed Authelia — the
web UI's own login form still works, because a same-origin `fetch` from the
browser carries the Authelia cookie.

Swagger/ReDoc (`/docs`, `/redoc`, `/openapi.json`), `/extras`, `/guides`,
`/readme` and every other page stay behind Authelia.

## 2. Nota's `.env`

```dotenv
PUBLIC_BASE_URL=https://nota.example.com   # baked into the userscript and pairing QR
APP_BIND=127.0.0.1                          # host port only for local health checks
APP_PORT=8010
# the proxy talks to the container over the Docker network; let uvicorn
# trust its X-Forwarded-* headers (your Docker network range):
FORWARDED_ALLOW_IPS=172.16.0.0/12
HOMELAB_NETWORK=homelab_default             # the network your proxy + Authelia are on
```

`APP_BIND=127.0.0.1` matters: without it, `http://<server-ip>:8010` would be a
side door around Authelia. `scripts/safe-update.sh` keeps working — it checks
`http://127.0.0.1:8010/health/ready` on the host.

The proxy container must be on the same Docker network as `nfce-app`
(`HOMELAB_NETWORK`) and forwards to `http://nfce-app:8000`.

Apply with `docker compose up -d` (or `scripts/safe-update.sh --force --no-pull`).

## 3. Authelia `configuration.yml`

Only the parts that matter for Nota. Rule **order matters** — the first rule
that matches wins.

```yaml
session:
  cookies:
    - domain: 'example.com'
      authelia_url: 'https://auth.example.com'
      default_redirection_url: 'https://nota.example.com'
      # Phones re-logging every hour is the main annoyance; with
      # remember_me the session lasts a month on a trusted device.
      expiration: '12h'
      inactivity: '2h'
      remember_me: '1M'

access_control:
  default_policy: 'deny'
  rules:
    # 1. Logging in / registering to Nota itself: only after Authelia.
    - domain: 'nota.example.com'
      resources:
        - '^/api/v1/auth/(login|register)([/?].*)?$'
      policy: 'two_factor'      # or one_factor
      subject:
        - 'group:nota'

    # 2. Token-protected API, capture and public endpoints (see section 1).
    - domain: 'nota.example.com'
      resources:
        - '^/api/v1/.*$'
        - '^/capture/nota-capture\.user\.js$'
        - '^/static/capturar\.html([?#].*)?$'
        - '^/static/lista-publica\.html([?#].*)?$'
        - '^/static/(api\.js|style\.css)([?].*)?$'   # loaded by the two pages above
        - '^/static/(manifest\.webmanifest|icons/.*)$'  # home-screen icon: fetched without cookies
        - '^/health(/ready)?$'
      policy: 'bypass'

    # 3. Everything else (the web UI, /docs, /extras, /guides): your users.
    - domain: 'nota.example.com'
      policy: 'two_factor'      # or one_factor
      subject:
        - 'group:nota'
```

Put yourself and your wife in an Authelia group `nota` (users file or LDAP),
or drop the `subject:` lines to allow any Authelia user.

## 4. Reverse proxy

Pick the one you run. All of them: send **everything** for `nota.example.com`
through Authelia — the bypass decisions live in Authelia's rules above, in one
place.

### Caddy

```caddyfile
nota.example.com {
	forward_auth authelia:9091 {
		uri /api/authz/forward-auth
		copy_headers Remote-User Remote-Groups Remote-Email Remote-Name
	}
	reverse_proxy nfce-app:8000
}
```

### Traefik (labels on the `nfce-app` service)

Add to `docker-compose.override.yml` next to `docker-compose.yml` (compose
merges it automatically; `safe-update.sh` keeps it since it is untracked):

```yaml
services:
  nfce-app:
    labels:
      - traefik.enable=true
      - traefik.http.routers.nota.rule=Host(`nota.example.com`)
      - traefik.http.routers.nota.entrypoints=websecure
      - traefik.http.routers.nota.tls.certresolver=letsencrypt
      - traefik.http.routers.nota.middlewares=authelia@docker
      - traefik.http.services.nota.loadbalancer.server.port=8000
```

and, once, on the Authelia container:

```yaml
      - traefik.http.middlewares.authelia.forwardAuth.address=http://authelia:9091/api/authz/forward-auth
      - traefik.http.middlewares.authelia.forwardAuth.trustForwardHeader=true
      - traefik.http.middlewares.authelia.forwardAuth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name
```

### nginx / Nginx Proxy Manager / SWAG

```nginx
server {
    listen 443 ssl http2;
    server_name nota.example.com;
    # ssl_certificate ... ;

    # Captured receipt pages are posted as full HTML: nginx's 1 MB default
    # body limit rejects big NF-e pages with a 413.
    client_max_body_size 10m;

    location = /internal/authelia/authz {
        internal;
        proxy_pass http://authelia:9091/api/authz/auth-request;
        proxy_set_header X-Original-Method $request_method;
        proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Content-Length "";
        proxy_set_header Connection "";
        proxy_pass_request_body off;
    }

    location / {
        auth_request /internal/authelia/authz;
        auth_request_set $redirection_url $upstream_http_location;
        error_page 401 =302 $redirection_url;

        proxy_pass http://nfce-app:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 120s;   # NFC-e parse via Playwright can take a while
    }
}
```

In Nginx Proxy Manager, paste the two `location` blocks and
`client_max_body_size` into the host's *Advanced* tab.

## 5. Certificates

Use a certificate phones trust (Let's Encrypt through your proxy, or
`tailscale serve`/`tailscale cert` if Nota is only on your tailnet). A
self-signed certificate is **not** enough: iOS Safari and the userscript
managers refuse it for background requests, so captures would fail silently
with "Sem conexão com o Nota".

## 6. Check it from outside

From a machine that is **not** logged in to Authelia:

```bash
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://nota.example.com/static/index.html
# 302 https://auth.example.com/?rd=...           -> UI is behind Authelia

curl -s https://nota.example.com/health/ready
# {"status":"ok","database":"ok"}                -> bypass works, DB reachable

curl -s -o /dev/null -w '%{http_code}\n' https://nota.example.com/api/v1/auth/me
# 403                                             -> reached Nota (no token), not Authelia

curl -s -o /dev/null -w '%{http_code}\n' -X POST https://nota.example.com/api/v1/auth/login
# 302 or 401                                      -> login is behind Authelia

curl -s https://nota.example.com/capture/nota-capture.user.js | grep -E '@connect|NOTA_BASE_URL ='
# // @connect      nota.example.com
# const NOTA_BASE_URL = 'https://nota.example.com';   -> PUBLIC_BASE_URL is right

curl -s -o /dev/null -w '%{http_code}\n' http://<server-lan-ip>:8010/health
# 000 (connection refused)                        -> no side door (APP_BIND=127.0.0.1)
```

Then on each phone: open `https://nota.example.com/static/capturar.html`,
install the script, pair, scan a cupom (see FABLE_HANDOFF.md, "Pass 11" for
the full device test).

## 7. Update the other clients

- **Chrome extension:** popup → base URL `https://nota.example.com`.
- **Tasker / Shortcuts:** the same base URL; prefer `POST /api/v1/nfce/capture`.
- **Cron / n8n** (`/notifications/check-due-dates`,
  `/integrations/tandoor/pantry-sync`): call either the public URL with the
  Bearer token, or `http://nfce-app:8000` directly from a container on the same
  Docker network (skips the proxy entirely).

## 8. What this does *not* do (yet)

Authelia and Nota keep **separate logins**: after Authelia you still sign in to
Nota once per browser (the Nota session lasts 7 days). Trusting Authelia's
`Remote-User` header to log you into Nota automatically is possible, but it is
only safe when the app port is unreachable except through the proxy, and it
needs a mapping from Authelia users to Nota accounts — a separate, deliberate
change, not part of this setup.
