s-t-e-f-a-n/BillCollector
About
Let BillCollector collect your bills from different personalized web portals.
Productivity & AutomationMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- +2
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
OriginalBillCollector

Chromium's sandbox is required by the daemon and batch launchers. The reference Compose service includes a pinned seccomp profile. See sandbox prerequisites and isolated checks.
Table of Contents
- What is BillCollector?
- How does it work?
- Your data stays local
- Contributing
- Quick Start
- Daemon Mode
- Using the Web UI
- Manual Tasks
- Configure BillCollector
- Migrating from Cron to the Daemon
- Debugging
- Legacy Batch Mode (Deprecated)
- Local Regression Test Environment
- Docker Build Context Check
- Docker Layer Cache Reuse
- Development & Deployment
- What's Next
What is BillCollector?
BillCollector is the automated front end for processing important documents in personal web portals that previously had to be tediously downloaded by hand.
Invoices and documents that are regularly stored by service providers in the respective online account are automatically retrieved by BillCollector and stored locally in a download folder from where it may be consumed by a document management system like Paperless-ngx.
BillCollector uses:
- Vaultwarden as a safe vault of the login data for the online accounts
- Playwright (for Python) driving a Chromium as the browser front end of the service provider's online portal
- SQLite to record the step-by-step progress of every run (performed actions, interactive elements found, results)
The primary mode is a self-hosted daemon with a web UI: it schedules each task on its own cron expression, runs the browser headful on an allocated virtual display (watchable live over noVNC), supervises every run, and pauses for your help when a portal changes - all without shell access to the daemon. The legacy cron-driven batch mode (a headless docker run per cron tick) is deprecated; it keeps working unchanged as the rollback path (see Legacy Batch Mode).
Following diagram depicts the complete BillCollector Ecosystem:
How does it work?
Your server runs the BillCollector daemon (in Docker, per the Quick Start), which exposes a download folder to the server's file system. The daemon integrates Chromium (via Playwright) to interact with the service provider's online portal; its scheduler fires each task on its own cron expression, and every run is visible live in the web UI.
For each run, BillCollector scripts the service, gets the secret login data from Vaultwarden via the Bitwarden API, accesses the web service via the configured Playwright recipes, and downloads the documents.
Every step of every service run is recorded in a local SQLite database (apps/db/bc.db): the method chain that was executed, the interactive elements that were found on the page, and the result. This makes failed runs diagnosable and is the foundation for the planned self-healing/assisted-repair features. A failed service/user pair aborts only its own run: the remaining services continue, every started run is finalized in the DB, and the process exits with code 1 if any pair failed. A second concurrent start of the legacy batch path (overlapping cron starts, two manual runs) is rejected by a flock guard; the daemon rejects a double start of a task by its run claim.
With a document-processing document management system (DMS) such as Paperless ngx in place, the downloaded file is consumed, automatically analyzed, tagged, and sorted.
Your data stays local
BillCollector runs entirely on your hardware and keeps your data there:
- Credentials never touch disk or the image. Login data is read from your Vaultwarden vault at run time through the Bitwarden API and substituted into the browser session in memory; nothing is written into the image, the download folder, or the local database.
- No telemetry. The daemon sends no usage, run, or diagnostic data anywhere. Its only outbound calls are to the portals it collects from, your vault API, and - when you opt in - the ntfy push server.
- Notifications are opt-in. A fresh installation sends no pushes; you enable them by setting an ntfy topic in Settings, and you can run your own push server instead of the public ntfy.sh.
- Your documents stay yours. Collected documents land in a local download folder you own, ready for consumption by your own document management system.
Contributing
How You Can Help
- Star this project on GitHub.
- Share it with your network.
- Contribute recipes for more web services - see how to Configure BillCollector and get familiar with the YAML recipes. Share your recipes 🙂🙂🙂
- Contribute code - fork this repository, create a branch from
main, and open a pull request againstmain. There is no CI pipeline yet: changes are validated in the local regression test environment and in production runs before being integrated. The contribution rules (ownership, PR requirements, proof, security, AI-assisted code) are in CONTRIBUTING.md. - Discuss your ideas for improvements, more use cases and any comments by leaving notes in the Discussion area.
💡 Tip
Make yourself familiar with the Playwright Locator API: BillCollector recipes are nothing but chains of locator calls and actions.playwright codegen <url>lets you walk through your web portal to record a draft of the procedure - don't forget to delete the cookies of that web portal to start with a clean session when training the procedure.helpers/BillCollectorCreateRecipe_pw.pycan translate the codegen Python output into a BillCollector YAML recipe.
In service (an existing portal on the daemon), a manual task session supersedes this workflow: the session browser runs on the task's production profile with real downloads, and the captured session trains the recipe proposal directly. The helper stays for offline and dev use.
Contributors
External contributions are welcome and credited:
- flowcool — secret-free vault request diagnostics (PR #11), Docker build context hardening that keeps private runtime artifacts out of the image (PR #12), the vault transport: in-process DNS vetting with requests pinned to validated local targets (PR #13), and Playwright image hardening that validates Python dependencies at build time and strips the pip/wheel installers from the runtime image (PR #16).
Quick Start
For a local first check, follow Start the daemon. Use Troubleshooting for a failed run and Recipe authoring for synthetic recipe proof.
BillCollector requires the following services:
- Docker environment
- Vaultwarden (docker image: vaultwarden/server:latest) with Bitwarden API (https://bitwarden.com/help/vault-management-api/) in one docker stack
- Secure HTTPS access for account management and usage of Vaultwarden with:
- nginxproxymanager with Let's Encrypt (docker image: jc21/nginx-proxy-manager:latest)
- Duckdns account & config -> redirect to local IP address
Prerequisites
Docker Environment
It is assumed that you have a docker environment up and running. There are different options you can choose from: Docker Desktop on a Linux or Windows machine or for your Mac, docker on the command line, etc.
I have it running on my self-built Mini-ITX Intel Pentium J5040 NAS hardware equipped with the Debian Linux based NAS operating system openmediavault (OMV).
Vault of Secrets
BillCollector uses the self-hosted Vaultwarden password manager.
Why Vaultwarden?
- It is a resource-light-weight alternative to Bitwarden.
- It is compatible with the Bitwarden Vault Management API integrated in the Bitwarden CLI which BillCollector uses for login data retrieval.
- It stores your login data safely.
- It is feature-rich, including the management of Time-Based One-Time (TOTP) passwords.
💡 Tip
On Vaultwarden Docker, you'll get the Vaultwarden and the Bitwarden CLI as aDockerfileand adocker-compose.yml. Follow the installation guide over there.
Enabling DNS and HTTPS with Let's Encrypt certs
💡 Tip
This configuration will not only support your BillCollector setup but also improves the user experience when accessing all your other locally running dockerized web services:**
Vaultwarden only allows secure HTTPS access by default. Suppose you want to run an instance of Vaultwarden that can only be accessed from your local network by name instead of IP address and you want to use Let's Encrypt certificates.
Currently, the simplest option is offered by Duck DNS as a free Domain Name Service (DNS) in combination with the locally dockerized Nginx Proxy Manager.
The cool thing about DuckDNS is not only that it is free of charge but also that it allows wildcard domains and local IP address names. For the latter, however, DNS rebind protection must also be configured in your router.
The only downside of Duck DNS is that you cannot freely choose your domain name because it will follow the naming scheme https://<your subdomain>.duckdns.org.
Steps to follow:
If you don't already have an account, create one at https://www.duckdns.org/. Define a subdomain name either used as a wildcard domain (e.g., my-domain.duckdns.org) or just a single domain name.

Configure the DNS Rebind Protection in your router: For Fritz!Box routers go to
/Heimnetz/Netzwerk/Netzwerkeinstellungen/DNS-Rebind-Schutzand enter the hostname you configured in Duck DNS.Check the setup of your domain name was successful. On your Windows machine
<WIN>R cmdand enternslookup <your subdomain\>.duckdns.org. The response should look similar as follows:
Alternatively, on your Linux machine use a tool like
digto check Duck DNS is resolving your domain name.Now we are ready to install NPM from the guide at the Nginx Proxy Manager.
a. After you've run your NPM container the first time, enter the web UI using the default credentials and change them to your private ones.
b. Go to
SSL Certificates, PressAdd SSL Certificateand chooseLet's Encrypt.- In the form fill in the field
Domain Nameseither with wildcard like*.my-domain.duckdns.organdmy-domain.duckdns.orgor just a single domain likemy-vw.duckdns.org. - In the same form fill in the field
Email address for Let's Encryptyou want Let's Encrypt to link the certificates in their database with. - Enable the switch
Use DNS Challenge, chooseDuckDNSfrom the list and enter the token from step 1 into the text box by replacingyour-duckdns-tokenindns_duckdns_token=your-duckdns-token. - You may leave
Propagation Secondsblank or fill in a number of seconds to wait for DNS propagation before it fails. - Enable the switch
I agree...and pressSave. - Now it may take some seconds to finalize the Let's Encrypt DNS Challenge.
- When finished successfully, a new SSL certificate is configured with an expiry in some months which will be updated automatically by your NPM.
c. Go to
Hosts, chooseProxy Hosts, and PressAdd Proxy Host.- In the form of tab
Detailsfill in the domain name you want to access Vaultwarden locally, likevault.my-domain.duckdns.org(using your wildcard domain) ormy-vw.duckdns.org. - In the same form fill
Schemewithhttp,Forward Hostname/IPwith the IP address of your Vaultwarden Host (i.e., the IP of your Host running the docker in your local environment), andForward Portwith the port Vaultwarden is listening on (typically 80 for HTTP). - In the form of tab
SSLenter the SSL certificate name(s) configured in step b. and enable the switchesForce SSLandHTTP/2 Support. - Press
Save.
d. Test the accessibility of your Vaultwarden Web UI in your browser by entering https://vault.my-domain.duckdns.org or https://my-vw.duckdns.org.
- In the form fill in the field
Installing the Daemon
Now that we have done a good job installing all the prerequisites, we are focusing on installing the BillCollector daemon. There are two paths:
- Run the published image - pull the prebuilt image from the GitHub Container Registry; no git clone and no local build needed.
- Build from source - clone the repository and build the image on the host (maintainer, NAS, and development setups).
Both paths share the same host setup: the data folders the container writes to and the apps/.env configuration.
Host setup (both paths)
Create the data folders the container user (UID/GID 1000 by default, or your
APP_UID/APP_GID) writes to - before the firstup, because Docker would create a missing bind-mount folder root-owned, and the container could not write into it:mkdir -p apps/Downloads apps/db apps/data apps/browser/profiles apps/recipes sudo chown -R 1000:1000 apps/Downloads apps/db apps/data apps/browser apps/recipes(Use your own uid/gid if you override
APP_UID/APP_GIDin the root.env.) The folders are the compose bind targets: downloads, the SQLite database, runtime data, per-task browser profiles, and the user recipe overlay (it may stay empty: it only holds recipes you add or update yourself).Create the app configuration the container reads read-only at
/apps/.env(a missing file makes Docker create a directory instead, which breaks the mount). The build-from-source path copies the example from the checkout; the published-image path fetches it:# build from source: from the checkout cp apps/.env.example apps/.env # run the published image: without a checkout curl -fsSL -o apps/.env https://raw.githubusercontent.com/s-t-e-f-a-n/BillCollector/main/apps/.env.exampleand set
BW_API_URLto the HTTP URL of your localbw serveAPI (e.g.,http://<local-ip>:8087; it must resolve only to loopback/private addresses, HTTPS is refused). See Vaultwarden and Bitwarden.Optionally, create a root
.envwith the compose variables - all of them have defaults, the file is optional:TZ(daemon calendar dates and cron schedules, defaultUTC),BC_UI_PORT(published UI port, default8766),NTFY_HOST(push server for the ntfy notifications, defaulthttps://ntfy.sh),NTFY_BASE_URL(LAN-absolute deep links, with the bundled ntfy),APP_UID/APP_GID(container user).Set
TZ=Europe/Zurich, for example, to use local dates and schedules. Compose readsTZfrom the shell first, then the root.env; an unset or empty value usesUTC. The image imposes no timezone. Compose passes its resolved value into the container, soTZinapps/.envcannot override it. For direct Python execution, an exportedTZwins overapps/.env. Withdocker run, pass--env TZ=Europe/Zurichor mountapps/.envread-only at/apps/.env. Docker does not automatically forward the host shell'sTZ. If neither runtime source setsTZ, the daemon usesUTC. Use an IANA name such asEurope/Zurich; an invalid zone stops startup. After changing the Compose setting, recreate the daemon withdocker compose up -d billcollectorand check the task schedules.
Run the published image
Pull the prebuilt image. The sample tag in the docs is updated with each release:
docker pull ghcr.io/s-t-e-f-a-n/billcollector:v0.6Save the compose file below as
docker-compose.ymlin the project folder. It is the reference service from the repository'sdocker-compose.ymlwithout itsbuild:section; the pinned Chromium seccomp profile it references is fetched from the repository too:mkdir -p docker curl -fsSL -o docker/chromium-seccomp.json \ https://raw.githubusercontent.com/s-t-e-f-a-n/BillCollector/main/docker/chromium-seccomp.jsonservices: billcollector: image: ghcr.io/s-t-e-f-a-n/billcollector:v0.6 container_name: billcollector restart: unless-stopped init: true security_opt: - seccomp=./docker/chromium-seccomp.json command: ["python3", "-m", "billcollector", "serve"] environment: TZ: ${TZ:-UTC} BC_UI_HOST: "0.0.0.0" NTFY_HOST: ${NTFY_HOST:-https://ntfy.sh} BC_RECIPE_EXTRA_DIR: /apps/recipes ports: - "${BC_UI_PORT:-8766}:8000" volumes: - ./apps/.env:/apps/.env:ro - ./apps/Downloads:/apps/Downloads - ./apps/db:/apps/db - ./apps/data:/apps/data - ./apps/browser/profiles:/apps/browser/profiles - ./apps/recipes:/apps/recipes extra_hosts: - "host.docker.internal:host-gateway" healthcheck: test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/_alive', timeout=5)"] interval: 30s timeout: 10s retries: 3 start_period: 30s(With a checkout of the repository you do not need this file: use the reference
docker-compose.ymlplus a small override that sets theimage:and resets thebuild:section to null.)Start the daemon and check the health endpoint:
docker compose up -d curl --fail --silent --show-error http://127.0.0.1:8766/_aliveThe published image is built with the default container user (UID/GID 1000); give that identity ownership of the folders as in the host setup.
Build from source
Download this git repository to a folder in your local docker environment assuming a Linux bash terminal, e.g.,
git clone https://github.com/s-t-e-f-a-n/BillCollector.git.On your Linux console enter
docker compose up -d --buildwhich builds the docker imagebillcollector:latestfrom the rootDockerfileand starts the daemon (python3 -m billcollector serve). The image runs as a non-root user (UID/GID 1000, overridable at build time with theAPP_UID/APP_GIDbuild args).Python dependencies are validated during the image build. The final container does not include
piporwheel; updateapps/requirements.txtand rebuild the image when changing dependencies. Local virtual environments keep their installers.
First start (both paths)
Open the published UI port in your browser (default
http://<your-host>:8766/). The first start shows a set-password form (or seeds the password fromBC_UI_PASSWORDinapps/.env); afterwards you sign in with that password.Walk the onboarding wizard: check and save your vault API URL (or skip it and fix it later in Settings), review the tasks imported from your INI file (or add a new task), enable the tasks the daemon should run on schedule, and finish.
Collect your first document: on the Dashboard press Run now for an enabled task - watch the run live (session page, noVNC tab) until it reaches
success; the document appears on the Downloads page and in the consumer folder. Every step is driven from the browser, no shell access to the daemon needed.
Notifications (ntfy)
A fresh installation sends no notifications: the ntfy topic setting starts empty, and a paused run, a blocked login, or a terminal run outcome only pushes when you set a topic. To opt in, open Settings and set an ntfy topic - choose your own topic name, it is the install-specific destination the pushes are sent to.
Terminal run notices are fixed and account-free: every run that ends as success, failed, interrupted, or attention-timeout sends one push (including a run the daemon reclaims at startup), carrying the run's collection outcome and, when known, the window start; cancelled runs stay silent. Delivery is best-effort - a failed push never changes the run outcome.
The push server defaults to the public ntfy.sh. To run your own push server in the same stack instead:
- Add
NTFY_HOST=http://ntfyto the root.env(optional:NTFY_BASE_URL=http://<your-host>:2086for LAN-absolute deep links). - Start the stack with
docker compose --profile ntfy up -d- thentfyservice (imagebinwiederhier/ntfy, port2086) comes up together with BillCollector.
Daemon Mode
The daemon is BillCollector's primary mode: python3 -m billcollector serve (the command of the compose service). It binds to 127.0.0.1:8000 by default (--host/--port, or BC_UI_HOST, override both) - inside the container BC_UI_HOST=0.0.0.0 makes the UI reachable from the LAN.
On the first start (while the task list is still empty), the [Playwright] sections of bc_default.ini and bc_test.ini are imported as tasks - each (service, user) pair becomes one task, initially disabled, with a default monthly cron (0 0 1 * *). You enable a task and set its cron schedule per task from the UI; the Task table in the database is the source of truth, and the daemon rebuilds its scheduler jobs from it on every start (a missed run coalesces into a single catch-up run).
Environment Variables
apps/.env (mounted read-only at /apps/.env) is the app configuration; the compose service additionally sets BC_UI_HOST and NTFY_HOST itself (these win over the file):
BW_API_URL=<http-URL of your local bw serve API, e.g., http://<local-ip>:8087>; it must resolve only to loopback/private addresses, HTTPS is refusedBW_API_HOST=127.0.0.1:8087(optional): Host header for abw servein another containerBC_UI_HOST: daemon UI bind host (default127.0.0.1; set0.0.0.0inside the container)BC_UI_PASSWORD(optional): seeds the UI password hash on the first start (a hash set via the UI is never overwritten)NTFY_HOST: push server for the ntfy notifications (defaulthttps://ntfy.sh)BC_CHROMIUM_ARGS=--disable-software-rasterizer: dev-host launch workaround only; leave unset for stock behaviorBC_BROWSER_CHANNEL=chrome: launch the installed browser binary (e.g.google-chrome-stable) instead of the bundled Chromium build; leave unset for stock behavior. The Docker image ships Google Chrome, so thechromechannel is available out of the box; on a bare host the channel binary must be installed first. Useful for bot-challenged portals (e.g. freenet's Cloudflare) that flag the bundled Chromium buildVAULT_HOSTis no longer used, see doc/vault_transport.md
The vault API can also be configured from the UI (the onboarding wizard's vault step or the Settings page, fields vault_api_url / vault_api_host): a non-empty Settings value wins over the environment, so a wrong URL can be fixed from the browser even though apps/.env is mounted read-only. An empty value falls back to the environment (legacy env-only deployments are unchanged).
Container Semantics
From the compose file (docker-compose.yml):
- UI port
${BC_UI_PORT:-8766}:8000- the daemon UI. - noVNC live view - no separate noVNC ports: the per-run live view is served by the daemon at
/vnc/<port>/on the UI port, authenticated by the UI session (one loopback-bound websockify port per allocated Xvfb display,6080 + (display - display_start), reached through the daemon's/vnc/<port>/websockifytunnel). - Volumes:
./apps/.env(read-only),./apps/Downloads,./apps/db,./apps/data,./apps/browser/profiles(profiles only - mounting all ofapps/browserwould hide the Chromium build installed in the image),./apps/recipes(the user recipe overlay, read-write - the UI recipe editor saves there). host.docker.internal:host-gateway- reach host-local services (Vaultwarden,bw serve, the mock portal) from the container ashttp://host.docker.internal:<port>. Vaultwarden itself stays a prerequisite in its own compose stack.restart: unless-stopped,init: true, a health check on/_alive, and the non-root user from theAPP_UID/APP_GIDbuild args.
Using the Web UI
All pages require sign-in (a session cookie set on /login).
- Login (
/login) - the one-time set-password form on a fresh start, then the password login. - Onboarding (
/onboarding) - the first-start wizard, active until you finish it (while active, every other authenticated page redirects to it). Upgraded installs (a password is set and at least one task is enabled) are auto-completed on daemon start, so you normally see it once, on a fresh install:- Vault - the vault API URL (+ optional host override) with a Check button (the same DNS vetting + status check the run preflight makes: reachable and unlocked / reachable but locked / network error) and Save (the Settings keys
vault_api_url/vault_api_host; empty is allowed = environment fallback). Skipping is allowed but flagged: while no URL resolves, runs fail at the vault preflight. - Tasks - the imported task list (id, service, user, cron, whether the recipe file exists) with per-task enable toggles, an Import from INI button (re-runs the import: only (service, user) pairs missing from the table are added - including ones you deleted; existing tasks are left untouched), and a New task form (service, user, cron, enabled; the recipe path and the per-task browser profile dir are derived as in the INI import).
- Finish - a summary (task counts, missing recipe files, vault state) and Finish onboarding.
- Vault - the vault API URL (+ optional host override) with a Check button (the same DNS vetting + status check the run preflight makes: reachable and unlocked / reachable but locked / network error) and Save (the Settings keys
- Dashboard (
/) - all tasks with their status (color-coded,waitingrows highlighted), last/next run (the last-run cell shows the run's collection outcome when set), latest download, a Login column (available / pending / blocked for tasks with a phased login), and a[N waiting]badge for paused runs; a live log pane following the active run and a step-screenshot strip; per row the icon actions Run now / Pause / Resume (one morphing button: works for disabled tasks as a manual one-off, schedule untouched; disabled only while the login is blocked; while the run is active it morphs into Pause, which pauses it at the next step boundary, and while it is paused it morphs back into Resume, which resumes the paused run), Stop (enabled while the run is active or paused), Edit (cron + enabled), and View run (opens the task's newest run, live or ended); toolbar Run (filtered) (enqueues all enabled tasks in the filtered set, skipping blocked ones) and Add task. - Tasks (
/tasks) - one row per task: the status badge (running / waiting / idle), the enabled flag, the cron, the last run (timestamp + result badge), and the next scheduled fire; a row click opens the task detail. No run actions live here - those stay on the dashboard and the task detail. - Task detail (
/tasks/<id>) - the run history of one task with the per-step records, step screenshots, and downloads; each history entry shows the run result and, when set, its collection outcome (new_documents/duplicates_only/proved_empty/partial/failed), and carries a View run link to the run's session page (live view while the run is open, ended view after it finishes); the action buttons are the morphing Run now / Pause / Resume button (see the dashboard), Stop (enabled while the run is active or paused), Reset profile (confirm dialog), and - for a phased login - the budget state (unproven attempts / limit) and, while idle and locked, a Clear login block button (grants exactly one further attempt, profile and schedule preserved). - Recipes (
/recipes) - one row per recipe file: the service name (link to the recipe editor), the task count, an overlay badge for user-overlay files, a valid/invalid badge (the tooltip carries the first error line), and the Last evidence badge - the service's newest conclusive run (success/failure/needs_attention) as verified or failing with the run date, linked to the run's session page, or unverified when no conclusive run exists; a service with tasks but no recipe file gets a flagged row. - Session (
/runs/<id>) - the live view of one run (the ntfy deep-link target): while it runs, you watch the progress; while it is paused, you get the "Copilot" view - a screenshot, the numbered interactive elements, click/fill/press/drag actions, and Resume / Cancel - plus a noVNC tab that shows the actual browser window. A step that failed and paused also offers a Repair link into the recipe editor. - Recipe editor (
/recipes/<service>) - edit the YAML recipe with schema and method-chain validation (see recipe method contract), and optionally auto-commit the change to git (Settings switch). - Downloads (
/downloads) - the downloaded files of all runs; a file whose sha256 was already seen for the same task is marked as a duplicate (the consumer hook is not re-run for it). The Delivery column shows each row's delivery state (downloaded / pending delivery / delivered / failed delivery with its attempt count), and a Retry delivery action on undelivered, non-duplicate rows re-delivers the row at-least-once on the task + sha256 key. See download recovery for the state machine and retry semantics, staged publication, recovery and the at-least-once consumer contract. - Settings (
/settings) - the fields grouped into cards (Security / Notifications / Runs / Storage & session / Vault / Git): UI password, ntfy topic, UI base URL, pause deadline, manual session deadline, max concurrency, display start, download directory, VNC password, the vault API URL/host (an empty field shows the effective environment value in its hint), and the git auto-commit switch. One Save button writes all daemon settings with all-or-nothing validation (an invalid value writes nothing and names the failing fields); the UI password keeps its own Change password action.
Pausing a stuck run. A non-graceful step that still fails after three attempts, a failed download, or an explicit wait_user recipe step does not abort the run: it pauses (the task shows waiting), stores a machine-readable pause context on the run, pushes an ntfy notification with a deep link to the session page, and waits - until you resume or cancel it from the UI, or the pause deadline passes (default 30 minutes, configurable in Settings). A run can also be paused manually: while it is active, the morphing Run now / Pause button (dashboard row or task detail) signals the runner to pause at the next step boundary - the pause then behaves exactly like a portal-triggered one, and a pause requested after the last step completes the run normally. While a run is paused, the same button morphs back into Resume and Stop stays enabled, so a paused run can be resumed or stopped directly from the dashboard row or the task detail, without opening the session page. A wait_user step pauses before execution and is consumed on resume (not re-executed - a consumed CAPTCHA code cannot be re-entered); it can carry an optional prompt and an optional until locator, the pause then completing as soon as that element appears on the page.
Blocking repeated login failures. A task whose recipe uses the phased login step (contract in doc/SAFE_LOGIN.md) consumes one attempt of a persistent budget per unproven login transaction (default limit 2, configurable per task and per recipe); reaching the limit locks the task for login runs until you clear the block from the task detail page - one attempt, schedule and profile preserved - or a later run proves the session. Locking sends one ntfy notification (deep link when the UI base URL is set), and a concurrent second start of the same task is refused by a per-task file lock held for the duration of the run.
For a cron-style single-shot run without the daemon, python3 -m billcollector run <task_id> executes one task run.
Manual Tasks
Some portals cannot be automated - for example, a bot challenge (Cloudflare Turnstile) blocks the scripted browser, or the login flow is too unstable to keep a recipe maintained. For such services, run the task in manual mode: instead of executing a recipe, the daemon opens a user-driven browser session on its display stack, driven live through the noVNC view of the session page (/runs/<id>). The downloads land in the normal pipeline (Downloads page, per-task deduplication, consumer), and the session can optionally record your steps and generate a recipe proposal for future automation.
Defining a manual task. In the task dialog (the dashboard toolbar's Add task, a row's Edit), set Mode to manual (default auto). A manual task needs no recipe - the recipe label reads "(not required for manual mode)" and the missing-recipe warning is suppressed - and can carry an optional Start URL. The session's start page is resolved in this order: the task's vault item URI -> the task's Start URL -> a blank tab (the session page then hints to navigate manually).
Running a session (two phases). Press Run now for the manual task (the dashboard row shows a Manual badge; a waiting manual run reads Session instead of waiting). The daemon starts the display stack and a plain browser - no Playwright, no CDP connection (the Docker image ships Google Chrome, so the session runs in it) - and holds the run open. With an ntfy topic set, the push reads "session is live" and carries the deep link to the session page. The session page shows an assist panel beside the noVNC tab:
- Phase A - no automation. The browser behaves exactly like a desktop browser: you pass any challenge and log in yourself, in the noVNC view. The Copy username / Copy password / Copy TOTP buttons put the task's vault item value onto the browser's own X11 clipboard (written with
xclipon the daemon's display) - you just pressCtrl+Vin the noVNC view. Your own browser's clipboard is never involved, and the value is wiped from the clipboard when the session ends. Username and password come from the vault fetched once at session start: if the vault was unavailable then (or the exact<service> <user>item was missing), the buttons stay disabled for the whole session - restart the session after unlocking the vault. The TOTP is fetched fresh on every click. - Phase B - capture (optional). Once you are logged in and about to navigate to the documents, press Start capture: the runner attaches to the already-running browser over the loopback-only debug port (enabled at launch, never connected during phase A - attaching after a passed challenge cannot re-trigger it) and records the rest of the session: clicks and field changes (element metadata only, never field values), navigations, and the download URLs. The session page's Copilot tab becomes available while capturing.
The session browser shares the task's persistent profile with the auto runs, so a manual login persists for later auto runs (and vice versa).
Ending the session. Finish session ends the run (the same protocol path a resume takes), Cancel cancels it, and closing the browser window yourself ends the run as well. The run result follows the collection outcome: at least one tracked download -> success (new documents, or duplicates only if every file was already collected); a Finish with zero downloads -> success (the empty portal is confirmed); a browser close with zero downloads -> needs attention. Cancel ends the run as cancelled, and reaching the Manual session deadline (seconds) setting (manual_session_deadline_seconds, default 3600, Settings -> Runs) ends the run with needs attention.
Training: from a session to a recipe. If the capture trace contains a download, the daemon trains a recipe proposal deterministically at session end (no LLM): a goto start step, a single wait_user step covering everything before capture (the challenge, the login - you log in manually, then resume), the captured events as locator steps, and the download-triggering click wrapped in expect_download. The proposal is validated against the recipe schema but never auto-applied: the ended session view offers a Review generated recipe link that opens the recipe editor with the proposal preloaded ("Generated from run ... - review, then save to activate"), and saving goes through the usual validation gate. Switching the task back to auto mode is your explicit action in the task dialog; from then on the scheduled runs execute the recipe, and the wait_user step keeps every run recoverable by hand. For in-service re-authoring, the manual session supersedes the codegen helper workflow (see the Contributing tip): same production profile, real downloads, no separate codegen login.
Configure BillCollector
Vaultwarden and Bitwarden
First and once, for the basic configuration you need to adapt the .env file located in the /apps folder. Use the .env.example as a template (the Quick Start does this in step 3):
cp apps/.env.example apps/.env- The Docker wrapper mounts
apps/.envread-only at/apps/.env; credentials are excluded from the image and Python retains dotenv quoting/interpolation. For directdocker run, mount the same file read-only..envchanges take effect at the next run without a rebuild. Built-in INI files and recipes are baked into the image and update with it (the legacy batch path still needs a rebuild for changes - legacy step 4 of Legacy Batch Mode); to add or shadow a per-service recipe without a rebuild, use the user recipe overlay (theapps/recipesfolder mounted by the reference Compose deployment). - define the .env-variables:
BW_API_URL=<http-URL of your local bw serve API e.g., http://<local-ip>:8087>; it must resolve only to loopback/private addresses, HTTPS is refusedBW_API_HOST=127.0.0.1:8087(optional): Host header for abw servein another containerVAULT_HOSTis no longer used, see doc/vault_transport.md
The vault API can equally be configured from the UI (wizard or Settings; Daemon Mode → Environment Variables).
Web Service Config
The BillCollector configuration for each web service from which you want to retrieve documents consists of three parts:
A Vaultwarden entry provides the login data for each of your private web service login:
Name: name of the web serviceUser Name: your secret login name to the web servicePassword: your secret password to the web service- (optional and dependent on the web service)
TOTP: key from your web service URI 1: the web service's web address where BillCollector should start from
A list of service entries in
/apps/bc_default.inirepresents the script for collecting all bills:Under the
[Playwright]section, enter line by line the name of the web service matching theNameof the service's entry in Vaultwarden (1).For web services where you have more than one login data for (e.g., family members having different accounts at the same mobile phone provider) you can enter the line in the following format:
<Name of web service>=<your name>, <additional name>.Example ini script (synthetic names - replace with your own services and accounts):
[Playwright] ExampleMobile=John, Jane ExampleUtility=
In daemon mode this INI list is the starting point for the task list: it is imported into the Task table on the first daemon start (or via Import from INI in the wizard), and from then on the per-task cron and enabled state live in the UI, not in the INI.
A YAML recipe defines the browser automation, which typically starts at login and ends at the download of the wanted document from the web service portal:
- The recipes are placed in the subfolder
apps/recipes_playwrightand follow the naming conventionrecipe-pw__<serviceName>.yamlwhere<serviceName>is the service'sNamefrom Vaultwarden in lower case with spaces replaced by underscores (e.g.,Freenet Mobilfunk->recipe-pw__freenet_mobilfunk.yaml). - The basic concept of the BillCollector recipes is summarized as follows:
- YAML format
- One recipe per web portal identified by the yaml element
serviceNameand its filenamerecipe-pw__<serviceName>. - Each recipe is structured in numbered
steps, executed in ascendingsteporder. - Each step is a chain of
methods: Playwright Page/Locator calls executed in order. Locator methods (locatorfor CSS selectors,get_by_role,get_by_label,get_by_text,get_by_title,get_by_placeholder,get_by_test_id) yield a locator that is chained into the following action (click,fill,press,first). Page-level methods includegoto(open the start URL),content_frame(enter an iframe) andclose. - Downloads: a step with the
expect_downloadmethod wraps the nestedstepsthat trigger the download; the file is saved into the Downloads folder. A re-downloaded file that is byte-identical to one already tracked for the same task (same sha256) is recorded as a duplicate and the consumer hook is not re-run for it. An opt-innotice_identitystep option switches a download step from byte-hash deduplication to source-scoped identity plus a conservative PDF revision digest; see notice identity. - Bounded pagination: use one page locator followed by
click_until_absent. Its single options object requiresprogress_selector,max_clicks, andtimeout_ms.timeout_msis the total browser-action budget. Every click must increase the visible progress count or make the pager absent or hidden. This action supports cumulative "load more" controls. It rejects page-replacement pagination and virtualized lists because their visible item count does not increase. For monthly replacement calendars, use the daemon's replacement_calendar action. - Bounded collections: use one page locator followed by
download_all. Its single options object requireskey_attribute,max_items,timeout_ms, andevent_window_ms.timeout_msbounds the browser actions and observations for the whole collection. Persistence (save_as, hashing, consumers, and SQLite) remains synchronous and cannot be preempted by that browser deadline.event_window_msis the full attribution window observed after each click, sotimeout_msmust exceed the actual item count multiplied byevent_window_ms, with additional time for browser actions. The engine reports the required and remaining budgets before its first click when the minimum attribution-window budget cannot fit. The key must be non-empty and unique for every item. The ordered key set must remain stable while each control produces exactly one download.download_allalso rejects a suggested filename already saved earlier in the run instead of overwriting it. The opt-inallow_empty(default off) completes an empty listing with zero records and proves the window empty for the run outcome; without it an empty listing fails closed as before. Set optionalunpack: pdfto save one bounded regular PDF from a ZIP transport. See the ZIP transport contract. - Collection actions are terminal steps. They cannot be nested below
expect_downloador usegraceful: true. Their explicit bounds prevent silent truncation and automatic retry after partial side effects. An operator-requested resume ofdownload_allskips the stable item keys already persisted by that step and processes only the remaining items. - Variables:
{{USERNAME}},{{PASSWORD}}and{{OTP}}(all three from Vaultwarden, linked to the web service) are substituted at run time. - Daemon date variables (issue #26):
{{TODAY}},{{DATE_TO}},{{DATE_FROM}}, and{{TODAY-Nd}}/{{TODAY+Nd}}expand inside any method argument string, including nested lists and dictionaries. Dictionary keys stay unchanged. Credential placeholders also work inline; replacement values are never parsed a second time. Each task has a Date window (inclusive days), default 90:DATE_TO = TODAY,DATE_FROM = TODAY - (window - 1)calendar days.TZselects the daemon date and scheduling timezone; absentTZmeans UTC, and an invalid zone is rejected. One instant is captured before browser launch and remains fixed through retries and interactive resume. Output defaults toYYYY-MM-DD; a suffix such as{{DATE_FROM|%d/%m/%Y}}allows only%Y,%m,%d,%%and literal separators-,/,.,_, or ASCII space. A format must contain a date directive. Dates must stay within0001-01-01to9999-12-31. Unknown variables, malformed delimiters, invalid formats and date overflow fail before browser or vault access. Errors identify the argument location without its value. The daemon recipe editor shares the syntax validator. On the task detail page, Start date for this run accepts a strictYYYY-MM-DDno later thanDATE_TO. It replaces onlyDATE_FROM, stays in memory through resume and is never saved or replayed on restart. The next run uses the normal window. The legacy batch checker and its exact-key credential substitution remain unchanged. graceful: trueon a step: a failure of that step is recorded (log + DB) and the run continues with the next step; without it, a failure aborts the service's run (after three attempts, in daemon mode the run pauses for your help instead - see Using the Web UI).- A
wait_userstep: an explicit pause point for operator input (e.g., a CAPTCHA you have to solve by hand). It can carry an optionalpromptand an optionaluntillocator (the pause completes when that element appears, or on resume); the step is consumed, not re-executed. - There is a YAML schema named
recipe-pw-schema.yamlwhich includes the rules to be followed by the YAML recipes. In daemon mode, validation goes beyond the schema: every method chain is checked against the installed Playwright (method names, argument names and types, properties, reservedwait_useroptions), and unknown methods and unsupported variables are rejected before vault or browser access, with errors that identify the service and step without argument values - the supported surface is documented in the recipe method contract. - In daemon mode the recipe can also be edited in the UI recipe editor (schema and method-chain validation, optional git auto-commit) - handy when a portal changes and a paused run links you straight to the failing recipe.
- In the reference Compose deployment,
apps/recipesis mounted as a user recipe overlay (BC_RECIPE_EXTRA_DIR): a file of the same name shadows the built-in recipe, and the UI editor saves into it, so recipes can be added or updated without a rebuild - see Adding or updating recipes via the mounted directory.
- The recipes are placed in the subfolder
💡 Tip
When creating new recipes, make use of AI, e.g., let yourself be helped by Copilot - that speeds up creating the YAML recipe 🚀.helpers/BillCollectorCheckRecipe.pyvalidates a recipe (YAML syntax + schema) and is also used byBillCollector.pyat run time:Usage: python3 helpers/BillCollectorCheckRecipe.py <recipe.yaml> [<schema.yaml>].
Example of a YAML recipe (excerpt, real winsim recipe):
services:
- serviceName: winsim
steps:
- step: 1
methods:
- method: goto
arguments:
- url: "https://service.winsim.de/"
- step: 3
methods:
- method: locator
arguments:
- selector: "#UserLoginType_alias"
- method: fill
arguments:
- value: "{{USERNAME}}"
- step: 5
methods:
- method: get_by_label
arguments:
- text: "Servicewelt-Passwort:"
- method: fill
arguments:
- value: "{{PASSWORD}}"
- step: 6
methods:
- method: get_by_title
arguments:
- text: "Login"
- exact: true
- method: click
# ... further steps: confirm the dialog, open "Meine Rechnung", select the invoice ...
- step: 11
methods:
- method: expect_download
steps:
- step: 12
methods:
- method: get_by_role
arguments:
- role: "link"
- name: "Rechnung"
- exact: true
- method: click
- step: 13
methods:
- method: close
Migrating from Cron to the Daemon
You are running BillCollector with cron (BillCollector.sh in the crontab) and want to move to the daemon:
- Import the tasks. Your INI file is already known to the daemon: on its first start the
[Playwright]sections ofbc_default.ini/bc_test.iniare imported as tasks (each (service, user) pair, initially disabled with a default monthly cron). If the daemon already started, press Import from INI in the onboarding wizard, or add a task from the dashboard Add task dialog. - Set the schedules. Open each task's Edit dialog on the Dashboard, set its cron (a 5-field crontab expression, e.g.,
0 6 1,15 * *for the 1st and 15th at 06:00), and enable it. - Verify one run. Press Run now for the task, watch the session page until the run reaches
success, and check the document on the Downloads page and in the consumer folder. - Stop the cron entry. Comment out or delete the crontab line that calls
BillCollector.sh. Rollback = re-enable the cron entry: the legacy path keeps working unchanged.
During the overlap period both paths can coexist safely against themselves: the legacy wrapper holds the shared apps/.bc.lock run lock (an overlapping cron start is rejected), and the daemon serializes its own runs per task. Just don't let both run the same (service, user) pair at the same time - they share the download folder and the same database.
Debugging
Local Development Environment
Use vscode when extending BillCollector - either the coded or, more likely, the collection of recipes.
There is an installation script for the local environment. It installs Python3, a Python virtual environment with all required Python modules, and Playwright's Chromium (plus the required system dependencies) into apps/.venv. It is tested under WSL2 and Ubuntu 24.04 LTS. Run the following command on your Linux command line:
bash install_local.sh playwright
F5 Debug Workflow
Debug one task run (a new or a broken recipe) against the daemon's task table:
cd apps && source .venv/bin/activate
python3 -m billcollector run <task_id> --debug
(or PYTHONPATH=apps python3 -m billcollector run <task_id> --debug from the repository root.)
What happens:
- The run uses the same engine as the daemon: the task's recipe, the vault credentials, the per-task browser profile, and the per-step DB recording.
- The browser runs headful on an allocated virtual display (Xvfb, from the configured range - default
:99), so no physical display is needed. The display stack must be installed on the dev host:install_local.shalready installsxvfb; additionallysudo apt install x11vnc websockify novnc. - The run's browser is viewable over noVNC. When the run goes through the daemon, the session page's noVNC tab shows the live browser (same-origin, UI-session-authenticated). In a standalone F5 debug run, websockify serves the noVNC web client (the
novncapt package) on loopback - openhttp://localhost:<websockify port>/vnc.htmlon the dev host. The port is printed in the log lineDisplay stack started for :N (x11vnc port ..., websockify port ...); websockify port =6080 + (display - display_start). --debugpauses before every step:Step N: <description> [press Enter to continue]on stdin - step through the portal and watch what the engine sees. A closed stdin (EOF) logs once and continues without pausing.- Every step is recorded in the SQLite DB (
apps/db/bc.db) together with the interactive elements that were found on the page - use these records to identify and fix failing steps.
VS Code launch configuration (.vscode/launch.json in your local clone - not committed to the repository):
{
"version": "0.2.0",
"configurations": [
{
"name": "BillCollector: run task 1 (debug)",
"type": "debugpy",
"request": "launch",
"module": "billcollector",
"args": ["run", "1", "--debug"],
"cwd": "${workspaceFolder}/apps",
"console": "integratedTerminal"
}
]
}
The integratedTerminal console is what makes the per-step Enter pause work under F5 (the debugger shares that terminal's stdin). Adjust the task id, and add "justMyCode": false when you want to step into Playwright.
Legacy Batch Mode (Deprecated)
Deprecated — the cron-driven batch mode (this section) is superseded by the daemon: per-task scheduling, live supervision, and pause-and-step-in.
BillCollector.shkeeps working unchanged as the rollback path for the daemon; new setups should use the Quick Start, and existing cron setups should follow Migrating from Cron to the Daemon.
The BillCollector Installation and Docker Deployment
Download this git repository to a folder in your local docker environment assuming a Linux bash terminal, e.g.,
git clone https://github.com/s-t-e-f-a-n/BillCollector.git.Configure BillCollector needs to be done. After each change in configuration proceed again with step 4.
Create a
.envfile in the repository folder from the template.env.exampleand setCONSUMER_DIRto yourPaperless-ngxinstance's consumption folder andDB_DIRto the database folder inside it (the installation script reads both; the soft links are created automatically).On your Linux console enter
./install_docker-image.shwhich builds the docker imagebillcollector:latestand sets the soft links to the inbox of yourPaperless-ngxto let BillCollector collect bills periodically. The image runs as a non-root user (UID/GID 1000, overridable at build time with theAPP_UID/APP_GIDbuild args).Let your server's cron call your BillCollector periodically (e.g., bi-monthly) by calling
</path/to/your/billcollector-git-clone-folder/BillCollector.sh bc_default.ini>.
The wrapper's call format is <ini> [debug]: the ini is the list of web services to run, and debug (or True/1) runs Chromium headed with per-step logging instead of headless. BillCollector.sh holds an exclusive flock on apps/.bc.lock for the whole run, so an overlapping cron start is rejected, and it runs the same billcollector:latest image the daemon uses (docker run … python3 ./BillCollector.py <ini> [debug], with apps/.env mounted read-only).
Local Regression Test Environment
A self-contained regression environment tests the scraping engine against a local mock portal instead of the real web services:
tests/mock_portal/- a small web portal (ASGI/uvicorn,127.0.0.1:8787) with sites covering the main scenarios: happy path with OTP and downloads, bad login, graceful step failure, download failure, empty document list, and CAPTCHA-style friction.tests/scenarios.py- the expected outcome of every (service, user) pair.tests/run_regression.py- the harness: starts the mock portal, executes every pair of a scope INI through the production scraping engine, and checks the engine return value, the DB rows, the downloaded files, and the exit semantics.
From the repository root:
apps/.venv/bin/python tests/run_regression.py --ini tests/bc_regression.ini
Useful options: --ini tests/bc_regression_happy.ini (success-only scope), --keep-downloads (don't delete the test downloads afterwards), --port <n>, and --vault (preflight a real Vaultwarden - env, DNS, unlock, sync - and fetch credentials, URL and TOTP from the corresponding vault items instead of scenarios.py; requires a vault provisioned with those test items, i.e. the maintainer's dev setup - the default mode above is fully self-contained and needs no vault).
Exit codes: 0 all expectations matched · 1 at least one expectation deviated · 2 the mock portal could not be started · 3 a real BillCollector run holds the run lock · 4 the --vault preflight failed.
Docker Build Context Check
The .dockerignore keeps local credentials, logs, browser sessions and other runtime artifacts out of the Docker build context. To prove that it really works, tests/check_docker_context.py builds a worst-case image (FROM scratch, COPY . /) from a scratch context filled with synthetic canary files — no real checkout data, no registry access — and checks that every excluded artifact stays out of the image while every source file stays in:
From the repository root, on a machine with Docker and BuildKit:
python3 tests/check_docker_context.py
Expected output: Docker context: 19 private canaries excluded, 5 source files retained. Useful options: --dockerignore <path> to check a different .dockerignore (e.g., a previous version as a negative control). Run this check whenever you change the .dockerignore, the Dockerfile or add new runtime artifacts.
Docker Layer Cache Reuse
The Dockerfile orders the expensive, rarely-changing steps (python3/pip apt install, pip3 install -r requirements.txt, playwright install --with-deps chromium ffmpeg, the fonts apt install) before the application code is copied, and the build is deliberately given no build arg whose value changes on every deploy — a Dockerfile ARG value is part of the BuildKit cache key of every RUN step, so a per-commit value (like a git revision) would force a full rebuild on every deploy. The result:
- Rebuilding the same tree (re-running
install_docker-image.shordeploy_remote.shwithout a new commit) is an all-CACHEDbuild. - A code-only change under
apps/re-runs only the finalCOPYandchownsteps. - A
requirements.txtchange re-runspip3 installand the steps after it, but not the python3aptstep or the base image.
The deployed commit is recorded in the deploy log (deploy_remote.sh prints git log -1) rather than as an image label.
The published-image workflow (.github/workflows/publish.yml) is the one exception: it passes VERSION - the release tag - as a build arg on every publication. The image LABEL block is kept at the end of the Dockerfile for exactly this reason, so a per-tag VERSION invalidates only the final metadata layer and a new tag still reuses the pip/playwright build cache. The tag is carried as the org.opencontainers.image.version label of the published image.
Development & Deployment
BillCollector uses a trunk-based model with release tags:
main— the verified production state. It only moves forward once a milestone has been validated in a production run, somainis always safe to deploy from.- Release tags (e.g.
v0.3) — snapshots of validated releases, for pinning a deployment or rolling it back: point the deployment'sGIT_BRANCHvariable (see.env.example) at the tag and re-rundeploy_remote.sh, or simplygit checkout v0.3in your clone and rebuild the image.
Day-to-day development happens on an upstream repository that is not mirrored here. Once a milestone has been validated, it is promoted to main and this repository is updated accordingly - so main reflects the published production state, not in-flight work.
To contribute code, see Contributing.
What's Next
The self-hosted daemon with its web UI is now the primary mode: per-task scheduling, live supervision, pause-and-step-in, a first-start onboarding wizard, and a Docker Compose package to stand it up. The cron-driven batch system is deprecated but keeps running unchanged alongside it as the rollback path. The recorded step data and the machine-readable pause context are the foundation for the planned self-healing / assisted-repair features: when a portal changes, BillCollector pauses, shows what it found, and - with your help or on its own - adapts the recipe. See CHANGELOG.md for the history of feature updates and changes.
Explore related projects
Loading…