# Frictionless NFC-e capture — options and plan

Status: **Phases 0–2 implemented** (Passes 11–12), QR pairing included.
**Phase 3 dropped** by the owner's decision (Pass 13): SEFAZ deliberately
breaks bots, so a server-side fetch would almost always miss and only add
waiting. **Phase 4 is on hold** until the phone capture has been tested for
real — tracked in `docs/BACKLOG.md`.

What shipped, and where it deviates from the plan below:

| Plan item | Shipped as | Deviation |
| --- | --- | --- |
| Pairing codes | `POST /auth/pairing-code`, `POST /auth/pair`, table `pairing_codes` (migration `0022`) | **8 characters** (`ABCD-EFGH`, no 0/O/1/I/L) instead of 6 digits — `/auth/pair` is public and 10⁶ codes can be swept inside the validity window; ~10¹² cannot. 10-minute TTL, single use, HMAC-stored. Stored in Postgres, not Redis (nothing used Redis yet). |
| `POST /nfce/capture` | as planned (`app/services/capture.py` detects NFC-e vs NF-e 55) | Falls back to personal if the saved capture household no longer resolves, so an unattended capture is never rejected. |
| CORS for other extension schemes | `moz-extension://`, `safari-web-extension://` added | — |
| Shared detectors | `extras/chrome-extension/detect.js`, loaded by the extension and inlined into the userscript by the server | Lives inside the extension folder (an unpacked extension cannot load files outside it). |
| Userscript | `extras/userscript/nota-capture.user.js` (template), served at `/capture/nota-capture.user.js` with this instance's address baked in | Pairing on the phone happens on Nota's own `capturar.html` through a DOM-attribute bridge, so the token goes straight into the userscript manager's storage. |
| Setup page with QR | `static/capturar.html` | QR rendered server-side with `segno`. Admin choice in Configurações: QR + código / só QR (24-char secret, typed codes refused) / só código. |
| **Phase 3** — server-first | **Not shipped (dropped).** Built in Pass 13, then removed. What stayed: a read-only `GET /nfce/invoices/by-key/{key}` so the scanner says "Já está no Nota" instead of reopening SEFAZ for a cupom already captured (Nota's own records only, never SEFAZ). Fixed on the way: `BrowserManager.get_browser` had a stray `@property`, so `/nfce/parse` — the Notas page's "Colar URL" — always failed with a 500; it now answers `retry` cleanly when SEFAZ/playwright-server don't cooperate. | Owner: SEFAZ breaks bots by design (DDoS protection); the person's own browser is the capture path. |
| **Phase 2** — scanner + home-screen icon | `static/escanear.html`, `static/scan-rules.js` (tested via node), `static/sw.js`, `static/manifest.webmanifest` | **`display: "browser"`, not standalone**: a standalone PWA opens SEFAZ links in an in-app browser where Safari extensions/userscripts do not run, which would silently break capture. For the same reason there is **no `share_target`** (it requires an installed standalone app). The scanner also reads the DANFE barcode (Code-128, where `BarcodeDetector` exists — Chrome/Edge Android; iOS Safari and Firefox read QR only, via jsQR) and opens the NF-e portal with the key pre-filled by the userscript. Offline queue is "scan now, open later" in `localStorage` — a SEFAZ page cannot be opened offline anyway. The service worker controls only `escanear.html`, network-first, shell files only. |

Not yet verified on real devices — see FABLE_HANDOFF.md, "Pass 11".

## The constraint that shapes everything

SEFAZ portals refuse automated clients. The page with the receipt only renders
for a real browser driven by a real person (bot check on SEFAZ-RJ, captcha on
the national NF-e portal). So every viable design has the same two halves:

1. **Get the person onto the receipt page with zero typing** — scan the QR,
   land on the page.
2. **Lift the already-rendered HTML out of *their* browser** and POST it to
   Nota (`/api/v1/nfce/parse-html`, `/nfce/parse-nfe-html`), which already
   parses, de-duplicates and reconciles it.

Nota never talks to SEFAZ on the capture path. What differs between options is
only *who runs half 2* and *how many taps it costs*.

## Where we are today

| Surface | Flow today | Friction |
| --- | --- | --- |
| Desktop Chrome | Extension (`extras/chrome-extension`): content script detects a loaded note, floating button / shortcut / context menu sends it; webcam QR reader built in | Low — one click. Fine as is. |
| Android (Tasker + AutoBarcode) | Scan → Tasker opens page → JS checks loaded → HTTP Request | Clunky: two paid apps, hand-built tasks, breaks silently when a step times out |
| iOS (Shortcuts) | Camera → Safari → Share → "Nota: Cupom" shortcut runs JS on page | 3–4 taps, share sheet every time, per-phone setup by hand |

Target: **scan → page opens → it's saved**, with a visible confirmation, the
same on your Android and your wife's iPhone, with setup simple enough to do
once on a sofa.

## Options

### A. Userscript ("auto-capture in the browser you already use")  ★ recommended first step

One `nota-capture.user.js`, served by Nota itself, containing the *same*
detection + extraction logic as the extension's `content.js` (`span.chave`
for NFC-e, `legend.titulo-aba` for NF-e 55). It runs only on the SEFAZ hosts,
waits for the receipt to be really loaded, and sends it **without any tap**,
then shows a toast: "Nota salva — R$ 86,40 · Mundial".

- **iOS**: Safari + the free, open-source *Userscripts* extension (App Store).
  Safari is already the browser the Camera app opens QR links in → the native
  camera becomes the scanner. Scan, tap the yellow link, done.
- **Android**: Firefox (Tampermonkey/Violentmonkey) or Edge (extensions are
  supported on Android). Set that browser as default, or pick it once in the
  QR prompt. Chrome for Android cannot run extensions or userscripts.
- **Desktop**: also works anywhere Tampermonkey does — a fallback for
  browsers the MV3 extension isn't loaded in.

Why it's the best first step: no app stores, no developer accounts, no build
pipeline, one file shared by both phones, and it removes the share-sheet tap
entirely. `GM.xmlHttpRequest` is not subject to page CORS/mixed-content rules,
so it can reach the homelab from an `https://…fazenda…` page.

Costs/risks: needs a userscript manager installed once per phone; SEFAZ markup
changes break extraction (already true for every option — mitigated by
keeping extraction dumb: send the whole HTML, parse on the server, as today).

### B. Nota PWA with built-in scanner ("one icon on the home screen")

Make `static/` installable (web manifest + small service worker) and add an
**Escanear** page: camera → `BarcodeDetector`, falling back to the vendored
`jsQR` → validates the URL is a known SEFAZ host → opens it. With option A
installed the capture then completes by itself; the PWA polls a "recent
captures" endpoint and flips to a ✓ card with the parsed total.

Extras this unlocks: Android **Web Share Target** (share a link from any QR
app straight into Nota), offline queue for scans made with no signal,
manual-entry and "pending review" one tap away, push-style confirmation.

On its own a PWA cannot read the SEFAZ page (cross-origin), so B is a better
*front door*, not a replacement for A. Requires HTTPS (camera and service
workers need a secure context) — see Phase 0.

### C. Real browser extensions on mobile

- **Firefox for Android / Edge for Android**: port `extras/chrome-extension`
  (MV3 → add `browser_specific_settings`, event-page background for Firefox).
  Same UX as desktop. Moderate effort, sideloading on Firefox release needs
  AMO signing (unlisted is fine).
- **iOS Safari Web Extension**: same code wrapped by Xcode. Needs a Mac and
  either a 7-day free-signing reinstall loop or a paid Apple Developer account
  (TestFlight). Best native feel on iOS, highest fixed cost.

Only worth it if A proves too fiddly to keep installed.

### D. Native wrapper with an in-app WebView (Capacitor)

One app: scanner → in-app WebView loads the SEFAZ page as the user → injected
JS extracts → POST. Truly one tap. Android APK sideloads easily; iOS again
needs a developer account. Risk specific to this option: embedded WebViews
identify themselves (e.g. `X-Requested-With`) and are scored harder by bot
checks — the very thing we are trying not to trip. Keep as a last resort.

### E. Server-side fetch first, human fallback second

Nota already has a Playwright fetch path (`POST /nfce/parse`) that sometimes
works. Use it opportunistically: the PWA scanner posts the QR URL; if the
server gets the receipt, the user never leaves the app; if it answers
`retry` / `manual_entry_required`, the app opens the page and A takes over.
Cheap to add once B exists; never rely on it alone.

### F. Keep Tasker / Shortcuts

Leave both guides in `extras/` as documented fallbacks. No further investment.

## Comparison

| | Taps after scan | iOS | Android | Setup per phone | Build cost | Bot-check risk |
| --- | --- | --- | --- | --- | --- | --- |
| A. Userscript | **0** | ✅ Safari | ✅ Firefox/Edge | install manager + 1 link | **S** | none (real browser) |
| B. PWA scanner (+A) | 0–1 | ✅ | ✅ | add to home screen | M | none |
| C. Mobile extensions | 0–1 | ⚠ needs Mac/dev account | ✅ | install extension | M–L | none |
| D. Native WebView app | 0 | ⚠ dev account | ✅ APK | install app | L | **higher** |
| E. Server-first | 0 when it works | ✅ | ✅ | none | S (after B) | high, by design a gamble |
| F. Tasker/Shortcuts (today) | 2–4 | ✅ | ✅ | long, manual | — | none |

## Recommendation

**A + B, with E as a bonus, in that order.** A removes the friction you feel
today within a day of work and works identically on both phones. B then gives
the "commercial app" feel (one icon, scan button, confirmation, queue) without
any store or signing. C/D stay on the shelf unless real use shows A is not
sticking.

## Phased plan

### Phase 0 — prerequisites (½ day)
- Serve Nota over **HTTPS** on the LAN/tailnet (existing reverse proxy, or
  `tailscale serve`). Required for camera access, service workers, and for
  iOS to allow the userscript's request without ATS exceptions.
- CORS: extend the allow-list in `app/main.py` from `chrome-extension://` to
  also `moz-extension://` and `safari-web-extension://` (still no wildcard).
- **Pairing instead of pasting tokens**: `POST /auth/pairing-code` (logged-in
  user gets a 6-digit code valid 5 minutes, stored in Redis) and
  `POST /auth/pair` (code → automation token). The phone types 6 digits, not
  a JWT. Reuses `create_automation_token` and token versioning from Pass 6.
- `POST /nfce/capture`: one endpoint taking `{html, url}` that detects NFC-e
  vs NF-e 55 server-side and dispatches to the existing parsers — clients
  stop needing to know which endpoint to call.

*Done when*: `curl` with a paired token can post a saved receipt HTML to
`/nfce/capture` over HTTPS and get the parsed invoice back.

### Phase 1 — userscript capture (1 day)
- `extras/userscript/nota-capture.user.js`: metadata block with the four core
  hosts (`sites.js`), `@grant GM.xmlHttpRequest`, `@connect *`; detection
  functions lifted from `content.js` into a shared `extras/shared/detect.js`
  that the extension also imports, so there is one copy of the selectors.
- Auto-send once per access key (remember sent keys in `GM.setValue`), toast
  with supplier/total from the response, "desfazer" link → opens the note in
  Nota, clear error states: not paired / offline (queued, retried on next
  page) / duplicate ("já estava salva") / needs review.
- Configurações → **Capturar no celular**: a page that shows the install link
  for the script, the pairing code, and a QR of that same page so the other
  phone gets there by scanning the screen.
- Update `extras/ios-shortcuts` and `extras/tasker` READMEs to point here
  first.

*Done when*: on both phones, scanning a real receipt with the stock camera
ends with the note in Nota and a toast, with no tap after the page loads.

### Phase 2 — PWA + scanner (1–2 days)
- `static/manifest.webmanifest`, icons, `static/sw.js` (cache the shell only;
  never cache `/api`).
- `static/escanear.html`: camera scanner (BarcodeDetector → jsQR), torch
  toggle, host allow-list check, opens the receipt; "últimas capturas" list
  from `GET /nfce/invoices?limit=5` polled while the page is visible.
- Android `share_target` in the manifest → `escanear.html?url=…`.
- Offline queue (IndexedDB) for scanned URLs.

*Done when*: Nota is on both home screens and Scan → ✓ happens without
touching the browser's address bar.

### Phase 3 — server-first shortcut (½ day, optional)
- Scanner posts to `/nfce/parse` first with a short timeout; only opens the
  SEFAZ page on `retry` / `manual_entry_required`.

### Phase 4 — only if needed
- Port the extension to Firefox/Edge Android; evaluate Safari Web Extension
  or a Capacitor shell if, after a month, captures are still being skipped.

## Security notes

- Automation tokens stay scoped, expiring and revocable (Pass 6); pairing
  codes are single-use and short-lived; revoking from Configurações logs every
  paired device out at once.
- The userscript only matches the SEFAZ hosts and only ever sends data **to**
  the configured Nota origin; it never reads other tabs.
- Whole-page HTML is sent; it contains the buyer's CPF when one was given at
  the till. It already does today — keep the transport HTTPS-only.
