Skip to content

About

Dashboard for DHCP leases on your lan, find new devices easy.

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

leasewatch

Who is on the network, newest first. A small self-hosted page that watches an OPNsense firewall's DHCP leases and ARP table, remembers every device it has ever seen, mails you when a new one appears, and lets you name and acknowledge devices so a newcomer is noticed once and then known.

What changed between releases: CHANGELOG.md.

screenshot: the device list, light on the left and dark on the right

  • One row per MAC with vendor, IP, hostname, network (VLAN), lease type, first seen / last online, a history of address changes and an event log. The events list under the table shows 60 at a time ("Load more" adds the next 60), can be filtered by kind and by a From / To day (kept in the address as ek, es, eu), and has an "Export CSV" link for the same filter.
  • Newest first, a "not yet known" review queue, name + note per device, CSV export, search, filters, light/dark, phone layout.
  • Optional "Connected via": switch port over SNMPv3 (Q-BRIDGE / IF / LLDP MIBs — any managed switch; uplink ports are named after the AP or switch behind them; tested on Comware, LLDP port numbers are mapped through lldpLocPortId) and Wi-Fi SSID / AP / signal from a UniFi Network controller.
  • Backend: Python 3.12 standard library (urllib, sqlite3, http.server); the only pip dependency is pysnmp for the optional switch lookup. Frontend: one HTML page, vanilla JS/CSS, no build step.
  • Read-only towards the firewall: only lease, reservation, ARP and (with IPV6=1) NDP searches are called. The API user needs Diagnostics: ARP Table and the DHCP server's privilege (Services: DHCP: Kea(v4), Services: Dnsmasq DNS/DHCP: Settings for dnsmasq, or Services: ISC DHCPv4: Leases for the legacy ISC server; LW_CONNECTOR__<NAME>__DHCP_BACKEND).

Run

cp .env.example .env && chmod 600 .env      # set LW_CONNECTOR__FW1__URL, __KEY, __SECRET (and the optional sources)
install -d -o 10001 -g 10001 data           # the container runs as uid:gid 10001:10001; for an existing data/ run chown -R 10001:10001 data
docker compose up -d --build                # publishes port 8080 on the host; for nginx-proxy see the commented variant in docker-compose.yml
docker compose exec leasewatch wget -qO- http://127.0.0.1:8080/api/stats   # the meta block shows the last poll; /healthz is for monitors (503 + reason on failure, which busybox wget does not print)

The default compose file publishes 8080:8080 and needs no external network. leasewatch tracks IPv4; IPv6 is opt-in per firewall instance (LW_CONNECTOR__<NAME>__IPV6=1) and adds one IPv6 address per device, never presence or a new device (see IPv6 under Semantics). Timestamps in logs and CSV are UTC unless TZ is set (the image has tzdata). LOG_FORMAT=plain|json|auto (default auto) sets the log line layout: under systemd/journald the time is left out automatically (journald adds its own); with Docker use LOG_FORMAT=json if a log driver parses JSON. UI_LANG=auto|en|sv (default auto) sets the page's language (see Language under Semantics). MAIL_LANG=en|sv (default en) sets the language of mails and webhook texts. The base image is pinned by digest in the Dockerfile; Dependabot proposes the weekly refresh of the base image, the actions and the Python version ranges; the hash lock is refreshed by hand as the build notes describe. The image installs the Python packages from the hash-locked requirements.lock; docs/image-build.md explains how to refresh it. Tagged releases are also published as ghcr.io/the-louie/leasewatch:<version> (and :1.7, :latest; amd64 and arm64; latest follows the newest release tag without a suffix): in docker-compose.yml replace image: leasewatch:local with image: ghcr.io/the-louie/leasewatch:1.7.1 and remove the build: . line to run the published image instead of building. The package is public once the owner has made it so after the first publish.

Without Docker: pip install . (or pip install '.[snmp]' for the SNMP switch connector) installs the leasewatch command, which runs like python3 -m leasewatch. It reads its settings from the environment only (it does not read .env) and needs a writable DATA_DIR (default /data), e.g. DATA_DIR=./data.

Local development: DATA_DIR=./data LISTEN_PORT=8089 LW_CONNECTORS=fw1 LW_CONNECTOR__FW1__TYPE=opnsense LW_CONNECTOR__FW1__URL=… LW_CONNECTOR__FW1__KEY=… LW_CONNECTOR__FW1__SECRET=… python3 -m leasewatch.

Sources are configured only as connector instances (LW_CONNECTORS, see Connectors). Upgrading from 1.0: the 1.0 source variables (firewall, switch, UniFi, and the DHCP backend, interface and proxy settings) are gone; a start with any of them set stops with a message that names the new variables, and CHANGELOG.md has the migration table.

OPNsense API user

Supported DHCP back ends: OPNsense with ISC DHCPv4, Kea or dnsmasq (built in); a dnsmasq leases file (Pi-hole, OpenWrt, Linux) and MikroTik RouterOS 7 through the connectors in contrib/.

Create a user with only the privileges Diagnostics: ARP Table and the leases page of the DHCPv4 server you run — Services: DHCP: Kea(v4) (LW_CONNECTOR__FW1__DHCP_BACKEND=kea, the default; leasewatch reads the leases, /api/kea/leases4/search, and the reservations, /api/kea/dhcpv4/searchReservation; OPNsense has no read-only Kea privilege, so this one also allows configuration writes), Services: Dnsmasq DNS/DHCP: Settings (LW_CONNECTOR__FW1__DHCP_BACKEND=dnsmasq, OPNsense 25.1.6 or later; leasewatch reads the leases, /api/dnsmasq/leases/search, and skips IPv6 leases unless IPV6=1; dnsmasq static hosts (Services > Dnsmasq DNS & DHCP > Hosts, /api/dnsmasq/settings/search_host) are read the same way as Kea reservations, built from the OPNsense model and unverified against a live firewall: a host without a lease is listed as static and offline, its description as label; the interface of a host without a lease is taken from an ARP entry or lease with the same address, else guessed from another device in the same /24 (wrong on smaller subnets), else left empty; OPNsense has no read-only dnsmasq privilege, so this one also allows writes to all dnsmasq settings) or, for the legacy ISC server, Services: ISC DHCPv4: Leases (LW_CONNECTOR__FW1__DHCP_BACKEND=isc; ISC DHCP is end-of-life in OPNsense and moves to a plugin from 26.1, so new installs should use Kea or dnsmasq) — generate an API key for it (System › Access › Users › the user › API keys) and put key and secret in .env (LW_CONNECTOR__FW1__KEY, LW_CONNECTOR__FW1__SECRET). The ACL for the ARP table matches the snake_case endpoint (get_arp), which is what leasewatch calls. With LW_CONNECTOR__FW1__IPV6=1 the user also needs Diagnostics: NDP Table (read-only; /api/diagnostics/interface/get_ndp), and under Kea also Services: DHCP: Kea(v6) (/api/kea/leases6/search), which allows configuration writes as the v4 one does. Under dnsmasq the IPv6 leases come from the same lease list, with no further privilege. A key without either privilege logs one WARNING per spell and the poll continues with IPv4 (ndp_unavailable / kea6_unavailable in the instance's stats).

Optional sources

  • Switch port (SNMPv3): a read-only v3 user on the switch with a view that includes 1.3.6.1.2.1 (mib-2) and 1.0.8802.1.1.2 (LLDP), authentication SHA, SHA-256, SHA-224, SHA-384 or SHA-512, privacy AES-128 (default) or AES-192/256. Add an instance of type snmp_switch (e.g. switch in LW_CONNECTORS) with HOST (a host name or IP without a port), PORT (SNMP UDP port, default 161), USER (default leasewatch), AUTH (SHA (default), SHA256, SHA224, SHA384 or SHA512), AUTH_KEY, PRIV (AES = AES-128 (default), AES192, AES256, AES192B, AES256B), PRIV_KEY, and optionally NAME (shown in the UI). AES192/AES256 extend the key the way Cisco does; AES192B/AES256B follow the Blumenthal draft (net-snmp's plain AES-192/256): if a switch answers with a wrong digest or not at all, try the other variant. A choice the installed pysnmp lacks disables the instance with a message. Ports with an LLDP neighbour or ≥ 6 MACs are shown as port → what hangs there.
    • PROFILE / PROFILE_FILE / MIN_MACS (per snmp_switch instance): the SNMP profile says which tables are walked and which vendor quirks apply. Without them leasewatch detects the profile from sysObjectID/sysDescr (first match wins, else standard). A profile file is your own JSON profile and wins over the profile name; it may extends a built-in one. It may start with a UTF-8 BOM; keys starting with _ are comments, at the top level and inside sections; oids values are numeric OIDs (a leading dot is allowed), and fdb.vlan_source and fdb.private_oids cannot name a _ key (such a profile is rejected at load); a snmp.no_bulk entry is an oids key name or an OID and also covers the OIDs under it. MIN_MACS (default: the profile's uplink.min_macs, 6) is how many MACs on a port without an LLDP neighbour make it an uplink.
    • Cisco IOS (cisco_ios): the forwarding table is read per VLAN through SNMPv3 contexts named vlan-<N>; the SNMPv3 group needs context vlan- match prefix (or one context per VLAN). Without them leasewatch logs "per-VLAN contexts unavailable, using Q-BRIDGE" once and reads Q-BRIDGE instead. Q-BRIDGE is read only when every context fails or none has rows; if some contexts answer and others fail, the poll fails and names the failing context.
    • Port names are shortened on every profile (GigabitEthernet1/0/1 → GE1/0/1, Ten-GigabitEthernet → XGE, FortyGigE → FGE, HundredGigE → HGE, TwentyFiveGigE → TGE, Bridge-Aggregation → BAGG, Port-channel → Po); a profile's port_name.short replaces the map; it is applied longest key first, and its keys must not be empty.
  • Wi-Fi (UniFi Network): a read-only admin on the controller; add an instance of type unifi (e.g. unifi) with URL, USER, PASSWORD and optionally SITE (default default) (session API; PLATFORM = auto (default) detects the controller type, classic for the self-hosted Network application, unifi_os for UniFi OS consoles such as UDM, UCG, Cloud Key Gen2+ or UniFi OS Server — supported but untested on hardware; use a local console user, cloud/SSO accounts with MFA cannot log in this way). The login session is kept between polls; leasewatch logs in again when it expires (a 401), at most once per 60 s. The controller's device alias becomes the display name when no name or hostname exists. Alternatively, on a UniFi OS console (UDM, UCG, Cloud Key Gen2+, UniFi OS Server), set AUTH=apikey and API_KEY (or API_KEY_FILE) instead of USER and PASSWORD: create the key under Settings > Control Plane > Integrations on the console; leasewatch then talks to the Integration API (/proxy/network/integration/v1, header X-API-KEY) and needs Network 9.3 or later. SITE may be the site's id (UUID), its internal reference (default) or its name. The standalone Network application (the classic self-hosted controller) has no API keys, so PLATFORM=classic with a key is refused, and so is a key together with USER/PASSWORD. What you lose with a key: the Integration API reports no SSID, signal strength, radio or channel, so the SSID column, the SSID filter, the Wi-Fi history per SSID and the SSID-change events stop for that controller (a device's stored SSID and signal are cleared, and each device with a stored SSID gets one wifi event, SSID unknown (controller reports none), at the switch; link wifi/wired, the AP name and the operator alias stay); VPN and Teleport clients are not listed; a client whose controller name is just its MAC gets no alias. Key mode is untested on hardware: it is built from the public OpenAPI spec (10.6.109) and fixtures and has never run against a real console. In session mode the controller's hostname and vendor (OUI) are also used for a device's name and vendor after the lease's (HOSTNAMES=1, default; 0 turns it off); key mode reports neither. The session mode (user and password, the default) is unchanged and remains the mode with the full Wi-Fi picture.
  • Login (basic auth): set AUTH_USER and AUTH_PASSWORD_HASH (both or neither; see Security notes). Make the hash with docker compose run --rm -it leasewatch python -m leasewatch hash-password and paste the line it prints into .env. A second login AUTH_RO_USER/AUTH_RO_PASSWORD_HASH can look but not change anything (the page hides the edit controls, a POST gets 403); AUTH_RO_PASSWORD_HASH must use the same iteration count as AUTH_PASSWORD_HASH (make both with the same hash-password --iterations). For scripts and monitors, AUTH_TOKENS holds read-only API tokens as a comma list of name:hash: python -m leasewatch make-token NAME prints a new token once (stdout) and its NAME:<sha256> entry (stderr) to append, and a client sends Authorization: Bearer <token> (it can read like AUTH_RO_USER, a POST gets 403). To revoke a token, remove its entry and restart; tokens need AUTH_USER.
  • Notifications on new devices: Mailgun, SMTP and/or a webhook; see Notifications.
  • Either source failing only turns its dot in the status pill red; the last values stay.

Commands

  • python -m leasewatch snmp-profiles lists the built-in SNMP profiles and their match rules.
  • python -m leasewatch snmp-detect <instance> (or --host 10.0.0.2 --auth-key-env MY_AUTH_KEY --priv-key-env MY_PRIV_KEY, with --port, --user, --auth and --priv as for an instance) prints sysObjectID, sysDescr, the chosen profile and the first rows of each walk. With an instance it uses that instance's settings; with --host both --auth-key-env and --priv-key-env are required and name the environment variables that hold the keys (there is no default name). Keys are read from environment variables, never from the command line. Needs pysnmp.
  • python -m leasewatch check [instance ...] prints the loaded connector types, any plugin that failed to load, plugin: <type> refused: <reason> for a plugin that declares a built-in type name, the config problems, and one line per instance: ok (<ms> ms), disabled: <problems> or check failed: <error> (only validate() and check() run). Exit code 0 when all are ok, 1 when a check failed or timed out, 2 on a config or load problem or an unknown name.
  • python -m leasewatch collect <instance> [--json] runs check() and collect() once and prints the records as leasewatch would merge them (MACs normalised, source filled, dropped counted). With --json it prints exactly one JSON object, also on failure ("ok": false, phase, error). Same exit codes as check. Neither command starts the server or opens the database; secret settings and the source's host are masked in all output.
  • python -m leasewatch hash-password [--iterations N] prints the AUTH_PASSWORD_HASH value for a password (format pbkdf2_sha256:<iterations>:<salt>:<hash>, PBKDF2-SHA256, default 600000 iterations, allowed 100000–10000000). On a terminal it asks twice; otherwise it reads one line from stdin (printf '%s' "$PW" | docker compose run --rm -T leasewatch python -m leasewatch hash-password). The password is never taken from the command line. An empty password is refused; one shorter than 12 characters gets a warning. Only the hash goes to stdout. Exit code 0, 1 on an error, 2 for a bad argument. AUTH_RO_PASSWORD_HASH must use the same iteration count as AUTH_PASSWORD_HASH: make both with the same --iterations.
  • python -m leasewatch make-token NAME prints a new read-only API token (secrets.token_urlsafe(32), 43 characters) as the only line on stdout, and the line AUTH_TOKENS entry: NAME:<sha256hex> plus a hint on stderr; append the entry to AUTH_TOKENS and restart. The token is shown only this once. NAME is 1-32 characters of a-z, 0-9, _ and -. Exit code 0, or 1 on a bad name. The start line counts the configured tokens (auth tokens: N).
  • python -m leasewatch backup [--to PATH] [--keep N] writes a consistent copy of the database and rotates data/backups/; python -m leasewatch vacuum rebuilds the database file on a stopped service (see Backup and reset).
  • python -m leasewatch reset-baseline [--yes] [--clear-acks] [--include-archived] marks every listed device as baseline without deleting the database; python -m leasewatch import-csv [--dry-run] [--fields LIST] [--fill-empty | --overwrite] FILE restores name, note, acked, archived, watch and tags from the CSV export (see Backup and reset).

Connectors

Every source (the firewall, a switch, a UniFi controller) is a connector instance: a configured copy of a connector type (opnsense, snmp_switch, unifi) that reads its device once per poll and hands leasewatch plain records; it never writes to the database or to the device. A connector emits two kinds of record: a sighting says a MAC was seen with an IP, hostname or network (a lease, an ARP entry) and whether it is on the wire now, and an attachment says where a MAC hangs (a switch port, a Wi-Fi AP and SSID). At least one instance must produce sightings and be neither a controller nor a name source (the firewall is the usual one): a controller or a name source only adds to devices the firewall knows. Text in a record has control and bidi characters removed and tab and every line break turned into spaces (an SSID, AP or alias is not trimmed); a flag given as text (or bytes) is read with the same words as the settings (true/false, 1/0, yes/no).

LW_CONNECTORS is required: list the instance names (only a-z and 0-9, so every variable can be exported from a POSIX shell; the order breaks ties in the merge) and configure each one with LW_CONNECTOR__<NAME>__<KEY>, the name upper-cased; TYPE is required, TIMEOUT (seconds, default 60) caps one collection (for a switch also the SNMP walk and the probe, formerly a fixed 60 s), and any secret key also accepts <KEY>_FILE, a file whose content is the value (e.g. a Docker secret; a UTF-8 BOM at its start is ignored). The keys are the type's settings in upper case (opnsense: URL, KEY, SECRET, VERIFY_TLS, DHCP_BACKEND, IGNORE_INTERFACES, IPV6, PROXY; snmp_switch: HOST, NAME, USER, AUTH, AUTH_KEY, PRIV, PRIV_KEY, PORT, PROFILE, PROFILE_FILE, MIN_MACS; unifi: URL, SITE, AUTH, USER, PASSWORD, API_KEY, VERIFY_TLS, PROXY, PLATFORM, HOSTNAMES); see .env.example. A wrong setting stops the start with a message such as connector swrack (snmp_switch): HOST is required; so do LW_CONNECTOR__* variables for an instance not in LW_CONNECTORS, a variable not of the form LW_CONNECTOR__<NAME>__<KEY>, and any of the removed 1.0 source variables.

opnsense DHCP_BACKEND is kea (default), dnsmasq or isc. With dnsmasq the lease search is read, and dnsmasq static hosts (Services > Dnsmasq DNS & DHCP > Hosts) are read the same way as Kea reservations, built from the OPNsense model and unverified against a live firewall: a host without a lease is listed as static and offline, its description as label, and its interface is taken from an ARP entry or lease with the same address, else guessed from another device in the same /24 (wrong on smaller subnets), else left empty (IPv6 leases, leases with a non-Ethernet hardware address and leases whose expiry has passed are skipped), and its privilege Services: Dnsmasq DNS/DHCP: Settings also grants write access: OPNsense has no read-only one. IPv6 leases are skipped unless IPV6=1.

opnsense IPV6 is 0 (default) or 1. With 0 nothing IPv6 is called and nothing changes. With 1 the connector also reads the firewall's NDP table (ndp sightings), under dnsmasq the IPv6 leases already in the lease list, and under kea the DHCPv6 leases (dhcp6 sightings); the privileges are listed under OPNsense API user above. NDP rows without a MAC ((incomplete)), on an ignored interface, link-local, of the firewall's own interfaces or with an unparsable address are skipped.

Connectors that are not built in (e.g. dnsmasq_leases for a dnsmasq leases file, mdns for listen-only names and models from mDNS and, with SSDP=1, product labels from SSDP announcements, which needs host networking) live in contrib/, each with its own README. docs/connectors.md explains how to write one (connector API 1).

Connector types that are not built in are loaded from two places: installed Python distributions with an entry point in the group leasewatch.connectors.v1 (name = type, value = module:Class), and LW_CONNECTORS_DIR, a directory with one subdirectory per connector package that declares the same entry point in its pyproject.toml (the layout of contrib/<package>/; loose .py files are not loaded). LW_CONNECTORS_DIR has no default; in the container, mount it read-only, e.g. ./connectors:/connectors:ro with LW_CONNECTORS_DIR=/connectors (see the commented lines in docker-compose.yml), and copy each package directory into it as it is (cp -r contrib/leasewatch-dnsmasq ./connectors/). The files must be readable by the container's user. Outside a container, pip install contrib/<package> also works (its build needs setuptools); do not use both for one package, as a type declared twice is refused and the start stops. A connector runs with leasewatch's full privileges and sees the whole environment, other instances' secrets included: load only code you trust. A package written for another connector API version is not loaded. A type name that is declared twice is refused from every origin; a package that declares a built-in type name is refused and the built-in kept. A package that fails to load, or would shadow another module, is logged; the start stops only when an instance uses its type (connector dhcp1 (dnsmasq_leases): cannot be loaded: …) or when LW_CONNECTORS_DIR itself is wrong (not a directory, an unreadable pyproject.toml, a package that would shadow another module). The start log lists every loaded type and where it came from (connector types: …).

Each instance collects in its own thread. One that fails, or takes longer than its TIMEOUT, turns its status dot red and keeps its last values (while polls fail, an instance not read since the last good poll shows a grey dot); a collection still running at the next poll is skipped, not doubled. An instance that fails its first probe is retried with a backoff from POLL_SECONDS up to 10 minutes (a sighting producer the held-back baseline still waits for is retried every poll instead, see Semantics); after that (at once when POLL_SECONDS is 10 minutes or more) it is collected every poll. The poll fails only when every sighting-producing instance failed; a controller or a name source (the controller and names roles) never fails a poll on its own. /api/status shows each instance's state (ok, error, last time, duration, record count).

Notifications

New devices are reported through every channel whose settings are complete; any number of them can be on at once; with MQTT_EVENTS=1, MQTT is one of them (see MQTT / Home Assistant below). The start log names them (mail on (mailgun, smtp, webhook) or mail off). Each batch (up to 50 devices) goes to every channel; when at least one channel delivered it, the queue is cleared and a channel that failed is logged (smtp failed (3 device(s)): smtp: timeout) and misses that batch. Every device in the text mail (Mailgun and SMTP) and in the JSON webhook gets its own link (ntfy and Discord link the device when there is one, else the list), <PUBLIC_URL>/?device=<mac>, which opens that device's page; the mail ends with the link to the list of unchecked devices. Without PUBLIC_URL there are no links. When all fail, the queue is kept and retried at the next poll. A channel that fails is not called again until a wait has passed: POLL_SECONDS after the first failure, then twice as long after each further failure in a row, at most 30 minutes (with 120 s polls: the next poll, then 2, 4, 8 polls later, then every 30 minutes). A dead server therefore costs its timeout (20 s for Mailgun and SMTP, 10 s for the webhook) once per wait and not at every poll. A channel that waits misses the batches sent meanwhile, as one that failed; when every channel waits, nothing is called and the queue is kept. The log has one warning when a channel starts failing (smtp failed (3 device(s)): smtp: timeout; retrying with backoff up to 30 min) and one line when it delivers again; the other attempts are debug lines. meta.notify in /api/status ({"smtp": true, ...}) is true or false for the last attempt of each channel; mqtt is in it whenever MQTT_URL is set (the presence publisher counts), not only with MQTT_EVENTS=1. The wait is kept in memory only: after a restart every channel is tried at once (the queue itself survives a restart). Error texts name the channel and a code only, never a password, URL, address or server reply.

  • Mailgun: MAILGUN_KEY, MAILGUN_DOMAIN, MAIL_TO; for an EU-region domain also MAILGUN_API_BASE=https://api.eu.mailgun.net. Uses http_proxy/https_proxy when set; a redirect is not followed (it is an error), so the API key never goes to another host.

  • SMTP: SMTP_HOST, SMTP_FROM (the sender address, plain name@domain in ASCII, without <>) and MAIL_TO (one address or a comma-separated list, without <>; shared with Mailgun, as is MAIL_FROM_NAME). SMTP_TLS = starttls (default, port 587; STARTTLS is required, a server that does not offer it gets no mail, never plain text), tls (implicit TLS, port 465) or none (port 25, for a LAN relay). SMTP_PORT overrides the port. SMTP_USER and SMTP_PASSWORD (both or neither, ASCII only) log in; a password with SMTP_TLS=none is refused at startup. A recipient the server refuses while it accepts another is logged as a warning (a count, no address); the mail counts as sent. The certificate and host name are always checked; SMTP_VERIFY_TLS=0 accepts any certificate (self-signed relay on the LAN). Timeout 20 s. SMTP does not use HTTP proxies.

  • Webhook: WEBHOOK_URL (http/https, no user:pass@; the path and query in ASCII, percent-encode other characters). The URL is treated as a secret, because services put their token in it: it never appears in logs or errors. One POST per batch, Content-Type: application/json, timeout 10 s; any 2xx is success; a redirect is not followed (it is an error). Uses http_proxy/https_proxy; add the receiver to no_proxy when it is on the LAN. WEBHOOK_FORMAT:

    • json (default): {"event": "new_devices", "site": SITE_NAME, "count": 2, "title": "<subject>", "message": "<text>", "url": "<PUBLIC_URL>/?filter=unacked" or null, "devices": [{"mac", "ip", "hostname", "vendor", "vlan", "lease_type", "url": "<PUBLIC_URL>/?device=<mac>" or null}]}. Readable by Home Assistant webhook triggers, Gotify relays and most automation tools. title and message follow MAIL_LANG; the keys and the event values stay English.
    • ntfy: WEBHOOK_URL is the topic URL (https://ntfy.example.com/<topic>, ?auth=… allowed); leasewatch publishes JSON (topic, title, message, click) to the server's root URL. click is the device's page for one new device, else the list of unchecked ones. The message is cut to ntfy's 4096 bytes ("… and N more"); a device line and its link are kept or cut together.
    • discord: WEBHOOK_URL is the channel's webhook URL; the devices are shown in a code block, one link follows the code block (the device's page for one new device, else the list of unchecked ones), the message is cut to Discord's 2000 characters, and mentions are disabled (a hostname cannot ping anyone).

    The language of the mails and of all webhook texts is MAIL_LANG (en default, sv). The new-device subject is New device: <hostname> (<ip>, <vlan>) in English and Ny enhet: <hostname> (<ip>, <vlan>) in Swedish (the hostname, else the vendor, else the MAC; an empty IP or network is left out of the parentheses). See Language under Semantics.

    The event field of the JSON format is new_devices, or source_down/source_up for a source alert, watch for a watched-device digest; a message that mixes watched-device events with a source event carries the source kind; all with the same envelope (site, title, message, url, count, devices), so a receiver should branch on event. count and devices are 0 and empty for source and watch messages; the text carries the lines.

    WEBHOOK_SECRET (optional) signs every request per Standard Webhooks: headers webhook-id, webhook-timestamp and webhook-signature: v1,<base64 HMAC-SHA256 of "<id>.<timestamp>.<body>">. A whsec_<base64> secret is base64-decoded first (an empty key after whsec_ is refused at startup); any other value is used as UTF-8 bytes.

  • Source alerts: MAIL_ON_SOURCE=1 (default 0, off) also sends the source_down and source_up events (see Events under Semantics) through the channels above: source_down when a connector instance has failed 3 polls in a row, dated to the first of them, and source_up at its first good poll after that. One message per poll, sent after the poll is written: one event gives the subject <instance> is down: <error> or <instance> is back after <length> (e.g. fw1 is down: connection refused, fw1 is back after 2h0m; at most 80 characters; with MAIL_LANG=sv fw1 är nere: connection refused and fw1 är uppe igen efter 2h0m, the detail stays English), several give N source events (at most 50, the rest go at the next poll); each text line is <time> <kind>: <detail>, the time in the container's TZ. The webhook event is source_down or source_up (the newest event in the message), with devices empty. An outage that spans a restart gives no second source_down. The meta row notify.alert_event_id keeps how far the events were considered: it moves to the newest event sent, or to the newest event when none is to be sent, so an event that was no alert when it was written (a device watched later, the other flag turned on later) is never sent as new. When no channel delivered, the same events go at the next poll (at-least-once, with the same backoff); at the first start with it on, and after a start with it off, only events written from then on are sent. The collector dying sends nothing: that is a job for an outside monitor on /healthz (reason collector).

  • Watch alerts: MAIL_ON_WATCH=1 (default 0, off) also sends what happens to a watched device (the Watch flag on its page; unwatched devices are never sent): its offline, online, ip, vlan, port and wifi events (with MAIL_LANG=sv the kind in the subject and the lines is a Swedish phrase: printer: ny IP, källa nere: fw1: timeout). offline is written when the ONLINE_GRACE_MINUTES grace has passed, so the grace is the debounce; online when it is on the wire again within a day (later, it is the back event, which is not sent). offline/online are written on the first poll after the grace in which every source answered (and the poll before it was good); during an outage nothing is written, and a device that left meanwhile is reported once the sources are back. A device just watched starts from its state at that time: no event for it. One digest per poll, on the same mark and with the same delivery rules as the source alerts: one event gives the subject <name>: <kind> (the device's name, else its hostname, else its MAC), several give N changes on watched devices, or N alerts when source alerts are in the same message; each text line is <time> <name> <kind>: <detail>. With PUBLIC_URL set, the page of each device in the message (<PUBLIC_URL>/?device=<mac>) follows the lines, one per line after an empty one (on Discord after the code block, so it can be clicked); with one device it is also ntfy's click and the webhook JSON's url. The webhook event is watch (source_down/source_up, the newest source event, when the message holds one too). Acknowledging or archiving the device does not drop alerts already written; unwatching it does. After a start, more than 50 pending events are skipped with a log line (for example after running an older version in between).

MQTT / Home Assistant

Setting MQTT_URL (mqtt://<host>[:1883] or mqtts://<host>[:8883], no path and no credentials in the URL; empty = off, the default) makes leasewatch publish device presence to an MQTT broker. After each good poll it sends what changed since the last publish (everything after a (re)connect), for the devices chosen by MQTT_DEVICES. Topics, all under MQTT_TOPIC (default leasewatch):

Topic Payload Retained
<topic>/status online or offline yes
<topic>/device/<id>/state home or not_home, QoS 1, sent when it changes yes
<topic>/device/<id>/attributes JSON: ip, ip6, hostname, name, vlan, switch_port, wifi_ssid, tags (a list), last_online (ISO 8601 UTC, or null), url (the device's page, null without PUBLIC_URL), mac; sent when the state or another field changes, not for last_online alone yes
<topic>/stats JSON: {"devices", "online", "unacked", "new"} yes
<topic>/event with MQTT_EVENTS=1 only: the webhook's JSON body, QoS 1; title and message follow MAIL_LANG, the keys do not no

<id> is the MAC in lower case without colons (12 hex digits). not_home means the device is offline by the page's rule (not seen for ONLINE_GRACE_MINUTES). status is online while leasewatch is connected (the broker publishes offline as the Will if it dies), offline on a clean shutdown, and offline after 3 polls in a row that fail, so Home Assistant shows the trackers as unavailable and not every device as away; it is online again, with a full publish, at the next good poll.

  • MQTT_USER and MQTT_PASSWORD (or MQTT_PASSWORD_FILE): both or neither.
  • MQTT_VERIFY_TLS (default 1) and MQTT_CA_FILE: certificate check for mqtts://, and a CA file (PEM) to trust instead of the system's.
  • MQTT_TOPIC (default leasewatch) and MQTT_CLIENT_ID (default leasewatch-<SITE_NAME as a slug>, at most 23 characters).
  • MQTT_DISCOVERY (default 1) and MQTT_DISCOVERY_PREFIX (default homeassistant): the Home Assistant configs below.
  • MQTT_DEVICES: watched (default; the devices with the Watch flag), named (a name set), known (acknowledged or named) or all. Archived devices are never published.
  • MQTT_EVENTS (default 0): 1 also sends the events that go to the webhook (new devices, and source and watch alerts when MAIL_ON_SOURCE and MAIL_ON_WATCH are on) to <topic>/event, as a notification channel like mail and webhook. A delivery there counts like a delivery by any channel: when MQTT delivers and mail fails, the new-device queue is cleared and the alert mark moves on, and the mail is not retried.

Home Assistant: with discovery on, leasewatch publishes a device_tracker config per device (homeassistant/device_tracker/leasewatch_<site>/<id>/config; source type router, availability from <topic>/status) and four sensors (devices, online, not yet known, new) on one leasewatch device. The configs are retained and sent again when Home Assistant announces it has started (on <prefix>/status; a broker that refuses that subscription gets one WARNING and no resend). The tracker carries the device's MAC in connections, so Home Assistant groups it with that device's other entities. When a device leaves the selection (unwatched, archived), its retained messages and config are cleared with empty payloads. When discovery is turned off, only the discovery configs are cleared; state and attributes keep publishing. The published set is kept in the database with its node, so a restart also cleans what an earlier run left, and a changed SITE_NAME clears the configs under the old leasewatch_<site> node. If Home Assistant's own UniFi integration is on too, a client gets two trackers, since that integration makes its own device_tracker per client with a different away timeout; because of the shared MAC, Home Assistant shows both under one device.

The start log shows mqtt on (mqtt://broker:1883, discovery, watched); python -m leasewatch check prints mqtt: <url> (<devices>, discovery on|off) or mqtt: off, without connecting to the broker. In Compose, put leasewatch on the same network as the broker and set MQTT_URL=mqtt://mosquitto:1883; no port is published for it.

A broker that cannot be reached never fails a poll. The client closes the connection, logs one WARNING per outage (further attempts are debug lines, and one line when it publishes again), retries on the notification backoff (see above), and publishes everything again after it reconnects. notify.mqtt in /api/status shows the last attempt. The client is a small MQTT 3.1.1 subset written for this (QoS 0 and 1, no QoS 2, no stored session); it needs no extra package.

Names, hostnames, IP addresses and MAC addresses go to the broker and to everything subscribed to it: use a user and password, and mqtts:// when the broker is not on the same host. The password never appears in logs.

Without a broker, a Home Assistant REST sensor can poll /api/stats (with a read-only login) for the counts; it cannot make a device_tracker.

API

Method Path What
GET /api/devices all devices (archived ones included) + collector meta; each device has private (true for a locally administered MAC), archived_ts (when it was archived, or null), split_from (the MAC of the device it was split from, or null), tags (a comma list, "" when none), baseline (1 for a device from the first poll), acked_at (when it was marked known, or null), label (text from the DHCP source, "" when none: a Kea reservation's or a dnsmasq host's description; not in the CSV exports), ip6 (the IPv6 address, "" when none), ip6_stable (the stable IPv6 address, "" when none; see IPv6 under Semantics), aliases (the MACs merged into it, newest merge first, [] without any) and wifi_presence (the SSIDs it was seen on, newest last_seen first, [] without any; each ssid, first_seen, last_seen, seconds_seen)
GET /api/devices/<mac> <mac> in lower case (aa:bb:cc:dd:ee:ff; upper case gets 404; a merged alias MAC resolves to its device, whose mac is then the device's own): one device (the list row's fields, private, split_from and label included) with history, events, seen (per connector instance: source, last_seen, last_present) and aliases: the private MACs merged into it, newest first (mac, reason client-id or hostname, detail = the matched value, merged_ts, last_seen), and wifi_presence: the SSIDs it was seen on, newest last_seen first ([] without any; each ssid, first_seen, last_seen, seconds_seen, polls_seen, last_ap)
POST /api/devices/<mac> {"acked": bool, "name": str, "note": str, "archived": bool, "watch": bool, "tags": str} (any subset); a merged alias MAC resolves to its device. Or {"split": "<alias mac>"} alone: turns one of the device's merged alias MACs back into a device of its own (the device keeps its history and events); split not a MAC → 400 split must be a MAC, with any other key → 400 split cannot be combined with other fields, not an alias of this device (a second split too) → 404 not an alias of this device, the MAC already has a device row → 409 MAC already has a device row; 200 {"device": ..., "split": <the new device>}. 403 {"error": "read-only"} when READ_ONLY=1; 403 {"error": "writes are not allowed from this address"} when WRITE_ALLOW is set and the client is outside it (both after the login check, so without credentials the answer is 401)
POST /api/devices bulk: {"macs": [...]} with "acked": bool or "archived": bool (not both), "tags_add" and/or "tags_remove" (comma lists of tags, normalised as the single POST's tags, so a bad tag gets the same 400), alone or together (both acked and archived, none of the four, name, note, tags or watch → 400 bulk takes acked, archived, tags_add or tags_remove; a tag in both lists → 400 a tag cannot be both added and removed). A device's new tags are its own minus tags_remove, in their order, then the added ones it lacks; if that gives any device more than 8 tags → 400 {"error": "at most 8 tags", "full": [mac, ...]} and nothing is written for any device. macs: 1 to 200 lower-case MACs (else 400 macs must be a list of 1 to 200 MACs, or 400 {"error": "bad mac", "index": i} for the first bad entry); a merged alias MAC resolves to its device, and a device named twice counts once. All or nothing in one transaction: any unknown MAC → 404 {"error": "unknown device", "unknown": [mac, ...]} and nothing is written. The events are those of the same single POSTs. 200 {"changed": n, "unchanged": n} (devices whose ack, archive state or tags changed, and those already in that state). The same write, login, JSON and same-origin checks as the single POST
GET /?device=<mac> the page with that device's drawer open (a merged alias MAC opens its device; an unknown MAC opens nothing); closing the drawer removes the key. Other keys: q, filter, vlan, ssid, ssidnow, tag, sort, ek, es, eu, lang
GET /api/stats counts (including baseline_unchecked), per-network, first-seen times of the last 30 days' newcomers, ssids (per SSID: ssid, devices_ever = devices ever seen on it, devices_now = online devices whose current wifi_ssid it is)
GET /api/wifi/ssids {"since": <epoch or null>, "ssids": [{"ssid", "devices", "devices_now", "last_seen"}]}, most devices first. since is when Wi-Fi presence recording began (null before the first record); devices = devices not archived that were ever seen on the SSID; devices_now = those online now with it as wifi_ssid; last_seen = latest sighting of any device on it
GET /api/wifi?ssid=<urlencoded> {"ssid", "since", "devices": [{"mac", "name", "wifi_alias", "hostname", "vendor", "ip", "private", "archived_ts", "online", "on_now", "first_seen", "last_seen", "seconds_seen", "polls_seen", "last_ap"}]}, by first_seen on that SSID, archived devices included. ssid is compared exactly (a space counts); missing, repeated or longer than 64 characters gives 400; an unknown SSID gives 200 with an empty list. on_now = online and wifi_ssid is this SSID. ip is the device's current address. No ETag
GET /api/wifi.csv?ssid=<urlencoded> the same devices as CSV, columns mac,name,vendor,last_ip,private,archived,first_seen,last_seen,hours_seen,polls_seen,last_ap (name: the display name, as the page shows it: the name you set, else the Wi-Fi alias, else the hostname, else the label; there is no hostname column; hours_seen = seconds/3600 rounded to 1 decimal; formulas neutralised in name, vendor and last_ap); UTF-8 with BOM, attachment; filename="leasewatch-wifi.csv", no ETag
GET /api/events {"events": [...], "next": <id>|null}, newest first (ts then id, descending); each event has id, ts, mac (empty for a connector's source_down/source_up), kind, detail, name, hostname, vlan. Parameters: kind (1 to 20 comma-separated kinds, [a-z0-9_]{1,20}; an unknown kind matches nothing), since (epoch seconds, inclusive), until (epoch seconds, exclusive), limit (1 to 500, default 300), before (an event id: the page after it; an id that no longer exists gives an empty page). next is the last event's id when more events follow, else null: pass it as before for the next page. A repeated parameter, a bad value or since after until gives 400 {"error": ...}. Every accepted parameter set carries its own ETag (see below)
GET /api/status collector meta (incl. mail: whether a notification channel is configured, and last_attempt_ts/last_attempt_age: the last poll attempt, a failed one too), with types (every loaded connector type: type, origin, dist, version, type_version and instances, how many configured instances use it), refused (plugins dropped for declaring a built-in type name: type, reason), broken (types that failed to load: type, reason; no paths), and connectors: one entry per instance (name, label — the switch's NAME, "Wi-Fi", or "Wi-Fi " with several controllers —, type, ok, error, ts, ms, count, enabled, strategy for a switch, warnings: the stat keys of reads the connector could not make in its last poll, such as ndp_unavailable, kea6_unavailable, labels_unavailable or dropped; the status tooltip names them), and notify (true/false per channel for its last attempt, mqtt included whenever MQTT_URL is set). The 1.0 switch and unifi objects were removed in 1.2
GET /api/events.csv the events as CSV with the kind, since, until and limit rules above, except limit defaults to 10 000 (maximum 50 000) and there is no before; columns id,time,mac,kind,detail,name,hostname,vlan; UTF-8 with BOM, attachment; filename="leasewatch-events.csv", no ETag
GET /api/devices.csv CSV export (timestamps ISO 8601 in the container's TZ; private is 1 for a locally administered MAC, then archived: when the device was archived, empty when it is in the list (archived devices are included), before note; aliases, the merged MACs space-separated, then watch, 1 for a watched device, then tags, then baseline (1 for a device from the first poll), acked_at (when it was marked known, empty when it was not), split_from (the MAC it was split from, empty otherwise) and ip6 (the device's IPv6 address when one was seen, else empty), which are last; those four are exported for the record: import-csv does not read them, the SQLite backup is the restore path)
GET /healthz 200 when the last poll succeeded and is fresh, else 503; body {"ok", "reason", ...meta} with reason ok, source (polls run but fail, or the data is stale: see last_error and connectors) or collector (no poll attempt within attempt_limit s: the poll loop is hung or dead, restart)
GET /metrics Prometheus text format 0.0.4 (text/plain; version=0.0.4; charset=utf-8): device counts per network, poll and connector state, database size, mail queue. Behind the login when it is on (Prometheus basic_auth in the scrape config, or an AUTH_TOKENS token as authorization: {type: Bearer, credentials: ...}); gzip when accepted; no ETag

The server answers at most 64 requests at once (a 503 with Retry-After: 5 beyond that) and gives a request 15 s to send its headers and body. /api/devices and /api/events send a weak ETag that changes with every database write (a write from another process (import-csv, reset-baseline) is seen at the next refresh), the stale flag, the collector-stale flag, the client's write permission and each server start; a request with a matching If-None-Match (or *) gets 304 Not Modified with no body. /api/devices, /api/events, /api/status, /api/wifi/ssids and /api/wifi are gzip-compressed when the client accepts it (bodies over 1 KiB). /api/devices carries the ETag; /api/events carries one for every accepted parameter set (the tag includes a hash of the query, so each filter revalidates on its own). The tag differs per client write permission, so a cache must not share it between clients (Cache-Control: no-store already says so).

Semantics

  • Baseline: everything present at the very first poll is marked baseline — not "new", no mail, sorted after real newcomers. An empty first poll is not taken as the baseline. With several sighting producers (e.g. two firewalls) the baseline waits until each enabled one has answered at least once: devices seen meanwhile are recorded as baseline without a mail, and details a late producer adds (hostname, lease type, …) are no change: no events and no history rows until the poll that takes the baseline, which writes one history row per device with its complete values. A producer that never answers holds the baseline back (logged once as a warning); for as long as it does, no change events and no history rows are written for any device, though the rows stay current. While it waits, a producer that fails its first probe is retried every poll, not with the backoff below; after 10 minutes of failed probes it is collected every poll.
  • Wi-Fi presence: every poll adds, per device and SSID, the time since the last sighting to a total (a gap of more than one missed poll, or a clock step, counts one POLL_SECONDS), with first and last seen, the poll count and the last access point. WIFI_PRESENCE_DAYS (default 365, 0-3650) keeps a row that long after it was last seen (the prune clock of the event log); 0 = off: nothing is stored and stored rows are deleted at the next poll. In the page, a chip row under the networks shows each SSID as online now/devices ever; a click lists the devices ever seen on it (with "now only": those online on it now; in the address as ?ssid=<name>&ssidnow=1), and while it is on the First and Last columns show the time on that SSID. The device page has a Wi-Fi history block (one row per SSID: first and last time, time on it, last access point), and /api/wifi.csv?ssid= exports the devices of one SSID. The time is accurate to about one poll interval per visit: a visit shorter than one interval can be missed, and the time of a poll that lists the device is counted as the real time since the last one (at most two intervals plus the longest connector TIMEOUT plus a minute, so one poll lost to a hung controller still bridges; a longer gap counts one interval). "Since" in the chip titles is the day counting started with 1.3; nothing earlier is known. Only a device with a device row is counted, so the firewall must list it (a lease or an ARP entry); a client the controller lists and the firewall does not has no presence. A merged private MAC counts on its device (the alias lands on the device under its first MAC), and archived devices are included in the lists and the CSV (not in the chips' counts). Use case: "who was on the guest network, and when" is ?ssid=Guest in the page or /api/wifi.csv?ssid=Guest. Only the totals per device and SSID are kept, not the single visits, and a phone that rotates its private MAC shows as one row per address until it is merged.
  • /healthz reason: every poll attempt, failed ones too, stores its time; attempt_limit = 2 x POLL_SECONDS + 2 x the longest TIMEOUT of the enabled instances + 120 s (480 s with the defaults). No attempt within the limit (or none since start, once the process is older than the limit) gives collector (the loop is hung or dead: restart), otherwise a failed or stale poll gives source; between 3 x POLL_SECONDS and the limit a hung collector still reads source. The page then shows a banner to restart the service.
  • New = first seen within NEW_DAYS and not baseline. Not yet known = not marked known and not baseline. Baseline, not checked = present at the start and not yet marked checked or known (the fifth card, shown while the count is above 0 or while that filter is chosen; stats.baseline_unchecked).
  • Online = in the ARP table now (or the lease says online), re-evaluated every poll. A device that leaves the ARP table (or is no longer listed) stays online for ONLINE_GRACE_MINUTES after it was last seen on the wire, then goes offline. last_online is the last time it was actually online; last_seen (CSV last_listed) the last time the firewall listed it at all — static mappings are always listed (under Kea, which lists only reservations with an active lease, the reservations are read for the same effect), so the UI shows last online.
  • History rows are written only when IP, hostname, network or lease type change, and when the stable IPv6 address changes (each row also keeps the device's stable IPv6 address at that time, history.ip6; the device panel's History shows it under the IPv4) (capped at HISTORY_PER_DEVICE per device, default 200, 10-1000; the device page shows up to that many rows). Events: new, ip, ip6 (the stable IPv6 address changed, old -> new), hostname, vlan, lease_type, port, wifi, back (online again after > 1 day, or back from the archive), merged (a private MAC was merged into the device), split (an alias was split off into a device of its own; one event on each of the two devices), acked / unacked, archived / restored (archived by hand or by PRUNE_DAYS, restored to the list by hand), watched / unwatched, offline / online (watched devices only: offline after the grace, online when back within a day; back covers the rest; written on the first poll in which every source answered, after a good one, so an outage writes none and a device that left during it gets its offline once the sources are back), renamed (old -> new, 40 characters each, (none) for an empty side), note (only the lengths, never the text), tags (old -> new, (none) for an empty side, with who did it), source_down / source_up (a connector instance, not a device: mac is empty and detail is <instance>: <text>; source_down after 3 failed polls in a row, dated to the first of them, with the instance's error; source_up at its first good poll after that, with the outage length, e.g. fw1: up after 3h12m; none before the baseline is taken, none for a disabled instance, and an outage that spans a restart gets one of each); kept EVENT_DAYS days (default 365, 1-3650). Events written from the page carry who did it: the client address (the proxy's address behind a reverse proxy, since forwarded headers are not trusted) and the login name when the login is on, e.g. by 10.0.0.5 alice. wifi: the SSID changed, or the device moved between Wi-Fi and a cable (a switch edge port, or the controller listing it as wired); leaving Wi-Fi with no cable shown (a phone walking out while the firewall's ARP table still lists it; a switch still holding it on an uplink, such as the access point's, is no cable) and the first SSID of a client already on Wi-Fi are not events; roaming between access points is not an event (the AP, signal and radio are updated silently, with no history row). The prune clock moves at most a day per start and at most twice real time while running, so a clock that jumps ahead does not delete the event log; after a long downtime older events stay until it catches up.
  • Lease type of a device whose lease is gone (LEASE_TYPE_MODE): keep (default) keeps the last type, so an expiring lease that is still in ARP does not flap between types on every poll; grace clears it once the device has been listed without a lease for ONLINE_GRACE_MINUTES (timed in memory, so a restart starts the clock again); immediate clears it at the first poll without a lease. Neither clears it while an instance that produces sightings failed this poll: that instance may hold the lease (a failed switch or Wi-Fi controller does not count). Clearing writes a lease_type event and a history row. sources shows what listed it last.
  • A Wi-Fi device that leaves keeps its last SSID/AP for the record. The Wi-Fi details are dropped when the device is on the wire this poll, every controller answered and none lists it; link is then wired if a switch lists it, else empty. A controller that lists it as wired drops them too. If a controller failed this poll and none that answered lists the device, it keeps its Wi-Fi details and no switch port is taken (blind). A controller whose answer had malformed records dropped counts as failed (blind). A client listed without an SSID keeps its stored SSID; one without any SSID leaves Wi-Fi under the same rule; one that never had an SSID and has since been placed on a switch port is shown on that port. When two controllers disagree, the first one in LW_CONNECTORS wins.
  • Private MACs (locally administered: the second hex digit is 2, 6, A or E): a new private MAC never sends a new-device mail, merged or not; it is still listed (as new when it does not merge). A new private MAC is merged into an existing device when one device matches it, and its records (IP, hostname, network, port, Wi-Fi, Seen by) then land on that device under the device's first MAC; the alias is stored with the reason, the matched value and when it was merged, and a merged event is written (" (client-id)" or " (hostname )"; a deferred merge, below, adds ", own row for min"). Once merged, the MAC belongs to that device until you split it off (below). The rule: (1) never at the first poll or while the baseline waits; (2) only the new MAC must be private, so two hardware MACs never merge; (3) by DHCP client-id first: the lease's client-id (at least 2 bytes) equals the stored client-id of exactly one device; else by hostname: the lease's own hostname (not one from ARP or a controller), in lower case without the domain, at least 3 characters and not generic (e.g. iphone, android-1a2b, a MAC-like name, or any name that starts with a brand or model stem such as galaxy, pixel, chromecast, iphone, ipad or android, so galaxy-s21 and pixel-7 are generic), equals the hostname of exactly one device, and that device was online or listed within the last 30 days; the first signal with exactly one device decides; (4) for a hostname match only, that device is not on the wire this poll under any of its MACs (a client-id match merges even while the old MAC is still seen, e.g. in the firewall's ARP table after the phone changed its address); (5) no other new MAC this poll has the same client-id or hostname, and no other new MAC is merged into the same device this poll. Archived devices count. While a source that has listed leases (the firewall) failed this poll (it may hold the lease), no merge is decided: a new private MAC is held back, with no row, for up to 30 minutes, then merges once the lease is back, or gets its own row. A private MAC that got its own row because rule (4) blocked it is merged later, within a day, when its device has left the wire within 30 minutes of the new MAC's arrival and has not been back. Its history, events (except "new device"), Seen by and Wi-Fi rows move to the device. A row that is named, has a note, is marked known, is archived or was present at the start is never merged. Split under Merged addresses undoes one merge: the MAC becomes its own device, what it recorded stays on the device it was merged into, and it is never merged back into that device automatically. Phones that derive the client-id from the current MAC and send no or a generic hostname (iPhone with a rotating address) are not merged.
  • Private MACs in the page: a device whose MAC is private shows the MAC in gold in the device list and the words private address under its name (on narrow screens, where the MAC column is hidden, the words alone mark it); the device panel marks the address with 🕵️ and says it is private (locally administered). Network colours follow the sorted list of networks of all devices, archived ones included, so archiving a network's last device does not recolour the others; a network that no device row carries any more drops out of that list. A device with merged MACs lists them under Merged addresses with the matched client-id or hostname, when they were merged and when they were last seen; Split on a row turns that address back into a device of its own (after a confirmation), which stays private, shows Split from and is never merged back automatically.
  • Copy: click the MAC or IP in the device list (or focus it with Tab and press Enter or Space) to copy it; "Copied" shows briefly. Over plain HTTP, where the browser has no clipboard API, an older copy method is used; if the browser refuses it too, the text is selected and a hint says to press Ctrl+C.
  • Display name in the list: the name you set, else the UniFi alias, else the hostname, else the label (a Kea reservation's or a dnsmasq host's description, stored in label), else the vendor, else the MAC. The label is replaced on every poll that lists the device while the reservation list could be read, so it follows the reservation (removing the description clears it); a poll whose reservation search fails, or whose firewall instance fails, keeps the stored label; changing it writes no event. The search also matches it.
  • IPv6 (only with IPV6=1 on a firewall instance): a device has one ip6, the preferred address among those the NDP table and the DHCPv6 leases list for its MAC: global (2000::/3) before unique-local (fc00::/7); one a DHCPv6 lease carries before a neighbour-only one; the MAC's own EUI-64 address (stable) before a temporary one; the lowest last. The stored address stays while it is still listed in the winning class, or while none is listed (NDP ages entries out). Link-local, loopback, multicast and IPv4-embedded addresses are never stored. A device listed only by NDP or DHCPv6 in a poll changes nothing but its IPv6 addresses, its last-seen time and the sources line (which then names the IPv6 source), plus the history row and ip6 event below when its stable address changes. A change of the shown ip6 alone writes no history row and no event: temporary (RFC 8981) addresses rotate daily and identify sessions, so leasewatch keeps one shown address per device and prefers the stable one. A device also has a stable IPv6 address (ip6_stable): the EUI-64 address of one of its MACs (its own, or a private MAC merged into it) or the address of a DHCPv6 lease (IA_NA; IA_TA and IA_PD leases are skipped), the best by class (global before unique-local before other; DHCPv6 before EUI-64). A temporary address is never stored as stable. A worse class never replaces the stored one; when nothing stable is listed it stays; within its class it stays while still listed, and an EUI-64 address also while its /64 prefix is still listed for any device (two prefixes live at once, as with two uplinks, do not make it flap when NDP ages one entry out), so after a renumbering the change is recorded once the old prefix has left the NDP table (up to a day late, once its entries have aged out); a DHCPv6 address that no lease lists any more gives way to a new lease of the same class at once. When the stable address changes, a history row is written (it keeps the address in history.ip6) and, if the old value was not empty, an ip6 event <old> -> <new>. The first stable address writes a history row and no event. The ip6 event is not among the kinds MAIL_ON_WATCH sends. The shown ip6 (page, /api, MQTT attributes) is the stable address while it is among the candidates of the best prefix class (a unique-local stable address beside a global temporary one is not shown), and a shown EUI-64 address stays shown while the NDP table ages its entry out for a poll, so it does not flip to a temporary one and back; a DHCPv6 address whose lease is gone gives way to a listed address of the same or a better prefix class; without a stable address the rule above holds. The MQTT attributes are not republished by such a poll. A split takes the alias's own EUI-64 address (ip6 and ip6_stable, each on its own) to the new device and leaves other addresses on the device. An NDP entry has no expiry and can stay for a day, so NDP and DHCPv6 sightings never make a device online (the built-in connector sends them with presence off), and a MAC seen only by IPv6 gets no device: IPv6 enriches a device that another source created. The page shows the address under the IPv4 in the IP column (and in the phone layout's meta line), cut with an ellipsis, the full address in the tooltip and copied on click; the device drawer has an "IPv6" row; the search matches it; sorting stays by IPv4. The CSV has ip6 as its last column (so the export carries the address) and the JSON has ip6 on every device ("" when none).
  • Hostname falls back DHCP → ARP → controller client → scan; vendor DHCP → ARP → controller → scan. Between several rows for one MAC, rows with an empty IP or network rank last in these fallbacks, so the result does not depend on the order the firewall returns rows in.
  • When a device moves (new IP or network), IP, network and interface are taken from the new sighting; one that is unknown there is shown empty, not the old value. A network that was unknown before and becomes known is not a move: the stored IP is kept.
  • Seen by (device page): one line per connector instance that listed the device (by its status-dot label), with when it last did; "on the wire" when that instance last saw it present within ONLINE_GRACE_MINUTES. A listing without presence (a lease alone, an FDB entry) moves the time but not "on the wire"; a controller's active client is present (this does not change Online). Rows of instances no longer in the configuration are removed at startup.
  • Switch port when several switches see a device: the first wired attachment per instance is its candidate; a MAC learned on several ports of one switch is placed on the edge (non-uplink) port, as the uplink only relays it; the same between a device and its merged MAC on one switch, and a controller that lists both places the device where its active client is. An edge port beats an uplink port (shown "via X"); between two edge ports the switch that already holds the device wins (if it still lists it), then the order in LW_CONNECTORS; between two uplinks the same. A port with an empty label ranks after every labelled one. Wi-Fi beats any switch port: a client listed by the controller stays on Wi-Fi whatever the switches say. If the switch that holds a wired device fails a poll (or answers with malformed records dropped), the device keeps its port and no port event is written, whatever the other switches offer. The instance that placed the device is stored as loc_source (CSV column too) and named after the port on the device page (a Wi-Fi controller is not: it lists a wired client without a port, so the port is an older switch reading). A port event is written when the chosen port changes, or when another switch places the device on a port with the same label (the event then names both instances).
  • Watch: "Watch" on the device page marks a device you want alerts about (see MAIL_ON_WATCH under Notifications); "Unwatch" clears it, and a watched device has a watch badge in the list. The watched state is in the CSV as watch and in the device JSON (watch, 0 or 1); a change writes a watched or unwatched event. Only the single POST sets it, not the bulk route.
  • Name and note: to record who owns a device, write owner:alex as a tag (see Tags); a note that starts with owner: <name> still works for the search box (owner: alex), and the CSV exports it.
  • Tags: free tags per device, typed comma-separated in the device page (typed text that a failed save would lose is kept until the next open). The Select bar adds or removes a tag on the selected devices (a device whose own tags plus the added ones would pass eight is named in a confirm and left out). Tags are normalised: lower-case, blanks become dashes, only letters, digits, _, :, . and -, the first character a letter or digit (so -legacy and .old are refused), 1-24 characters each, at most 8 per device; anything else is refused with the reason. owner:alex is the way to record who owns a device (the page groups those under Owner). The toolbar shows a chip per tag with online/total counts (the 12 most used, then "+N more"); a click filters the table and the address carries ?tag=. The search box finds tags. A tagged device counts as named: it is never folded into another device, archived by PRUNE_DAYS or PRUNE_PRIVATE_DAYS, or deleted by PURGE_DAYS. A tags event records every change with who did it. The CSV has a tags column and import-csv restores it. Only the single POST sets the whole tags text; the bulk route (POST /api/devices) adds tags with tags_add and removes them with tags_remove on many devices at once, all or nothing: if a device would get more than 8 tags, the answer names it in full and no device changes. Each changed device gets the same tags event as the single POST.
  • Archive: "Archive" on the device page takes a device out of the list (the status filter "Archived" shows the archived ones; "Restore to list" puts one back). Several at once: "Select" in the toolbar shows a checkbox per row (and hides the Type column meanwhile; on windows of 1400 px and less the First column too, at 1100 px and less also Last and Where); tick rows, or all visible rows with the header box, and the bar at the bottom offers Mark known, Archive (Restore to list under the "Archived" filter), a tag input with Add and Remove, and Clear. A selection covers only the rows on screen; "Done" leaves the mode and clears it. A client that may not write has no "Select" button. An archived device keeps its history, events, name, note and ack, is still updated while the firewall lists it, is not counted in the cards and network chips, and leaves the new-device mail queue. It comes back to the list by itself when it is online again (on the wire, not merely listed: a static lease is listed every poll) after it has been offline, with one back event ("back from the archive (archived N days ago)"), no new event and no mail; one archived while still online stays archived until then. PRUNE_DAYS (default 0 = off) archives, once per poll, every device that is offline, has not been online for that many days (since first seen if never online), has no name, is not tagged and is not marked known or marked Watch, devices present at the start included, but not one restored by hand since it was last online, for as long as its restored event is kept (events are kept EVENT_DAYS, default 365, so EVENT_DAYS below PRUNE_DAYS or PRUNE_PRIVATE_DAYS shortens that hold and a start warning says so); event archived "auto: not online for N days". PRUNE_PRIVATE_DAYS (default 0 = use PRUNE_DAYS, else 2-3650) is a shorter threshold (never longer than PRUNE_DAYS) for private (randomised) MACs that never merged: no name, note or ack, not tagged, not marked Watch, not made by a split, and no merged address pointing at it; event archived "auto (private): not online for N days". It runs with PRUNE_DAYS off too, then archives only those devices; the hand-restore hold applies to it as well. It never runs at the first poll or while the baseline waits. PRUNE_DAYS follows the same prune clock as the event log (it moves at most a day per start and at most twice real time), so a clock that jumps ahead does not archive devices early; after a long downtime pruning lags until the clock catches up. PURGE_DAYS (default 0 = off, e.g. 180) deletes, once per poll, every archived device that has been archived longer than that by the prune clock, is offline, that no source has listed for that long, has no name, no note, no tags and is not marked known or marked Watch, together with its history, events, Seen-by rows, Wi-Fi history and merged addresses (other devices' merged or split events that name it stay). A purged MAC that is seen again is a new device (and mails as one). It never runs at the first poll or while the baseline waits, and it follows the same prune clock as PRUNE_DAYS. For a long-lived install set PURGE_DAYS: archived rows cost every poll and every page load. The database file does not shrink until python -m leasewatch vacuum (see Backup and reset).
  • Interfaces in a firewall instance's LW_CONNECTOR__<NAME>__IGNORE_INTERFACES (default WAN and loopback) are skipped.
  • Layout: the page is 1280 px wide at most (1380 px from a 1400 px window); the table fits a 400 px phone window (the IPv6 line and the badges move into a meta line) and never scrolls sideways from a 1200 px window (a long date phrase wraps instead; the row's known button reads "✅ Known" so it fits on one line); below that it scrolls, as before; the Type column shows from 1280 px; the search applies 150 ms after the last key, Enter and Escape at once. The first column shows the link type as an icon (Wi-Fi arcs, a wired plug, or a ring when no switch or Wi-Fi controller has placed the device), green while the device is online and grey when it is not; its tooltip gives the type and the online state.
  • Language: the page is available in English and Swedish. ?lang=sv or ?lang=en in the address decides first (it stays across filter clicks and Clear filters, and is per address: nothing is stored in the browser, and there is no switch in the page); else the UI_LANG setting (auto default, en, sv; any other value logs a WARNING at start and counts as auto); else the browser's language (Swedish when its first language starts with sv); else English. Counts follow the language's plural forms, decimals use the page's language (a comma in Swedish) and sorting follows its alphabet (å, ä, ö last). The texts are in leasewatch/static/i18n.js; the English text stays in the HTML as the fallback without script. Mails, webhook texts (ntfy, Discord, and title/message of the JSON body) and the MQTT event text follow MAIL_LANG (en default, sv), which is set explicitly and never taken from the browser or the page's language; any other value logs a WARNING at start and counts as en. Server-written event details (the text beside an event kind, e.g. old -> new), connector error texts, log lines, the CSV headers, the JSON keys and the API's error strings stay English, so a Swedish "down" subject quotes the connector's English error text (fw1 är nere: connection refused) and the body lines quote the stored English event details.

Backup and reset

  • Backup: docker compose exec -T leasewatch python -m leasewatch backup [--to PATH] [--keep N] writes a consistent copy while the service runs (SQLite online backup; it does not need a valid connector setup). By default the copy goes to data/backups/leasewatch-<YYYYMMDD-HHMMSS>.sqlite3 (local time, mode 0600, a -1, -2 suffix if the name is taken), and only the newest BACKUP_KEEP (default 7, 0 = keep all; --keep N overrides it) files with that name pattern are kept; other files in the folder are never touched, except half-written .leasewatch-*.part files older than a day, which are removed. --to PATH writes one new file there (an existing file is refused, exit 2; in the container PATH must be under /data or another mounted volume, because the root file system is read-only) and rotates nothing; it cannot be combined with --keep. The copy is integrity-checked before it gets its final name. It prints one line, backup: <file> (13.2 MB; 7 kept, 1 removed). Exit code 0, 1 on a failure (backup failed: <text> on stderr), 2 on a usage error or an existing --to file.
  • Daily backup from cron: 15 3 * * * cd /srv/leasewatch && docker compose exec -T leasewatch python -m leasewatch backup. Copy data/backups/ off the host: it is on the same volume as the database.
  • Restore: 1. docker compose stop. 2. mv data/leasewatch.sqlite3 data/leasewatch.sqlite3.old and remove data/leasewatch.sqlite3-wal and data/leasewatch.sqlite3-shm: they belong to the old file, and a leftover -wal is replayed into a restored file. 3. cp data/backups/leasewatch-<stamp>.sqlite3 data/leasewatch.sqlite3; chown 10001:10001 data/leasewatch.sqlite3. 4. docker compose start.
  • A plain file copy of data/leasewatch.sqlite3 is safe only of a stopped service whose last log lines say database closed and no WAL warning (the WAL is not merged, WAL checkpoint incomplete, WAL checkpoint at shutdown failed); otherwise use backup.
  • Shrink the file (deleted rows, e.g. after PURGE_DAYS or a shorter EVENT_DAYS, free space inside the file only): python -m leasewatch vacuum rebuilds the database (VACUUM, then a WAL checkpoint and PRAGMA optimize) and prints vacuum: 52.8 MB -> 27.1 MB. Run it on a stopped service: docker compose stop && docker compose run --rm leasewatch python -m leasewatch vacuum && docker compose start. It needs about twice the database size free, as VACUUM writes a temporary copy to /tmp (tmpfs in the container). Exit code 0, or 1 on a failure (vacuum failed: <text>).
  • A full disk or size limit shows in the page as database full (disk or size limit) (likewise locked, read-only, I/O error, damaged file) and is logged once per spell with a traceback. If the status write fails too, last_error keeps its old text and /healthz reports collector after the attempt limit.
  • Upgrade to 1.1: the first start migrates the database one-way to schema 2 (the switch and Wi-Fi columns); back up data/ first. The 1.0 source variables are refused at start (see Connectors; the migration table is in the CHANGELOG).
  • Upgrade to 1.2: the first start migrates the database one-way (schema 3: new device columns and an aliases table). Back up data/ first if you may go back to 1.1; 1.1 opens a migrated database but logs that its schema is newer. 1.1 runs as uid:gid 100:101, so to go back run chown -R 100:101 data after restoring the backup.
  • Upgrade to 1.3: the first start migrates the database to schema 4: the wifi_presence table, the devices columns split_from and label, and two indexes; nothing is removed or rewritten. 1.2 opens a schema-4 database and leaves all of it alone, so going back to 1.2 is safe (unlike 1.1 to 1.2); back up data/ first anyway. Before going back, remove PORT and PRIV from any snmp_switch instance in .env: 1.2 refuses to start on an unknown connector setting (the new global settings such as WIFI_PRESENCE_DAYS or READ_ONLY it ignores). The Wi-Fi time counted meanwhile is lost to 1.2 and not counted back; split devices stay split.
  • Upgrade to 1.4: the schema stays 4; the devices columns watch and watch_online arrive by migration at the first start, and 1.3 still opens the file. Every new setting is optional: EVENT_DAYS, HISTORY_PER_DEVICE, PURGE_DAYS, PRUNE_PRIVATE_DAYS, LOG_FORMAT, MAIL_ON_SOURCE, MAIL_ON_WATCH, AUTH_RO_USER/AUTH_RO_PASSWORD_HASH, and AUTH/API_KEY of a unifi instance. To go back to 1.3, first remove AUTH and API_KEY from any unifi instance in .env (1.3 refuses to start on an unknown connector setting); under 1.3 the watch flags, the audit events and the alerts pause. The alert mark is kept, so after 1.3 has run for a while 1.4 skips more than 50 pending alerts at its start (with a log line).
  • Upgrade to 1.5: the schema stays 4; the devices columns tags and ip6 arrive by migration at the first start, and 1.4 still opens the file. Every new setting is optional: UI_LANG, MQTT_*, AUTH_TOKENS, and IPV6 and HOSTNAMES of connector instances. To go back to 1.4, first remove IPV6 and HOSTNAMES from the connector instances in .env (1.4 refuses to start on an unknown connector setting). 1.4 does not read tags: a device kept only by its tags is archived by PRUNE_DAYS and deleted by PURGE_DAYS under 1.4. The Swedish page, MQTT, tokens and the IPv6 column pause under 1.4; it ignores the new meta rows.
  • Upgrade to 1.6: the schema stays 4; the devices column ip6_stable and the history column ip6 arrive by migration at the first start, and 1.5 still opens the file. With IPV6=1, the first 1.6 poll writes one history row per device that has a stable IPv6 address, and no event. MAIL_LANG is optional (default en). The mDNS plugin is version 0.2.0 with the optional settings RELAYS and SSDP: copy contrib/leasewatch-mdns into your plugin directory again, since the 1.5 copy refuses the two settings as unknown. To go back to 1.5, remove RELAYS and SSDP from the mdns instance (a 1.5 host does not read MAIL_LANG and ignores it).
  • Upgrade to 1.7.1: the row button that marks a device known reads "✅ Known" ("✅ Känd") instead of "Mark known" ("Markera som känd"), which took two or three lines in Swedish; the tooltip and the screen-reader name still say "Acknowledge: I know this device". Static files only.
  • Upgrade to 1.7: no schema or setting change; only the page's static files and the docs changed (golden private MACs, link-type icons, the wrapping Mark known button, the 1380 px page from a 1400 px window). Going back to 1.6 needs nothing.
  • reset-baseline: docker compose exec leasewatch python -m leasewatch reset-baseline [--yes] [--clear-acks] [--include-archived] marks every listed device as baseline (present from the start: it never merges and never mails), empties the new-device mail queue and sets baseline_ts, without deleting the database. Names, notes, acks, events and history stay; no events are written. Archived devices are left alone unless --include-archived; --clear-acks also sets the targeted devices to not acknowledged. It asks for a y on a terminal; --yes is required in a script or without a terminal (exec -T). It prints reset-baseline: N devices marked as baseline (M were new). The page shows the change after the next poll.
  • import-csv: docker compose run --rm -T -v "$PWD:/in:ro" leasewatch python -m leasewatch import-csv [--dry-run] [--fields LIST] [--overwrite] /in/devices.csv restores name, note, acked, archived, watch and tags from the page's CSV export, also after Excel saved it again with ;. By default it only fills an empty name, note or tags and only sets acked, archived or watch (--fill-empty); --overwrite applies every value as it is in the file. --fields name,note limits what is imported (default name,note,acked,archived,watch,tags; a tags cell is normalised like the page does (lower-case, dashes for blanks, at most 8), and an invalid tag skips that row). --dry-run counts what would change: it runs the import on a copy and leaves the file untouched. A MAC that no device has is listed and never added; a MAC that is a merged address of a device lands on that device. Rows that land on one device merge field by field: a later non-empty value wins, an empty cell keeps the earlier row's value, and the device is listed as duplicate: <mac> (N rows). The export puts an apostrophe before a -, +, = or @ that starts a cell or follows ; or a line break; import-csv strips them again. The one lossy case: a typed apostrophe is dropped too whenever it stands where the export would have put one, that is at the start of a cell or right after ; or a line break, before a character the export treats as a formula start (=, +, -, @, a tab or CR, also after blanks or quotes). Limits: 1 MiB and 20 000 rows.
  • Full wipe: stop the container, delete data/leasewatch.sqlite3*, start again. This loses names, notes, acks, tags, archive state, watch flags, events, history, merged addresses, Wi-Fi history, first-seen dates and baseline_ts; the first poll then treats every device as baseline. Export the CSV first; after the first poll has listed the devices again, import-csv puts the user fields back (merged addresses and history do not come back). To keep the data and only mark everything as known, use reset-baseline.
  • Mail on new devices (never for a private MAC or a merge, see Semantics): a new device is queued in the database (devices.mail_queued) when it is first stored, so the queue survives a restart; devices found while mail is off are never queued. Each poll mails up to 50 queued devices (oldest first; the rest wait for the next poll) with their current IP and hostname. If every channel fails, the queue is kept and retried at the next poll; a device acknowledged or archived in the meantime leaves the queue; otherwise it stays queued until it is sent, however long the channels fail. When at least one channel delivered, the queue is cleared (see Notifications). Delivery is at-least-once: a crash or database error between the send and clearing the queue mails those devices again at the next poll.

Security notes

Login is optional and off by default. Without it the page is meant for a trusted LAN behind a reverse proxy: anyone who can reach it can read the device list and mark devices known. With AUTH_USER and AUTH_PASSWORD_HASH set, every path (the page, /static/, every /api/ call, the CSV export and /healthz) needs HTTP basic auth (realm leasewatch); without the right user and password the answer is 401. Monitors that poll /healthz must send the credentials; the container healthcheck accepts 401 as alive. Basic auth is safe only over HTTPS (a reverse proxy): on plain HTTP the password is readable on the wire. There is no logout: the browser keeps the credentials until it is closed. Wrong logins are not locked out; they are logged at most once a minute with a count and the last client address, never the user name or password, and at most two password checks run at once (a request that waits more than 10 s for one gets 503 with Retry-After). A correct login is remembered for 10 minutes, so a change of AUTH_PASSWORD_HASH needs a restart (it does anyway, as an environment variable). The read-only login AUTH_RO_USER shares the same limit of two password checks and the same cache, and READ_ONLY and WRITE_ALLOW apply on top of either login. An AUTH_TOKENS token (Authorization: Bearer) is always read-only; the environment holds only its SHA-256, never the token, and a token check is one SHA-256 (outside the password-check limit and cache), as a 32-byte random token needs no slow hash. A wrong token counts as a failed login; the 401 still offers only Basic. Alternatively let the reverse proxy do the login, e.g. nginx auth_basic "leasewatch"; with auth_basic_user_file /etc/nginx/leasewatch.htpasswd; in the location. Use one or the other: with both, the proxy forwards its own Authorization header to leasewatch. leasewatch never sends a packet to an end device: it reads the firewall, the switch and the controller over their APIs, and the optional mdns connector only listens to what devices announce on the LAN. Nothing can be changed on the firewall through the page. POSTs require Content-Type: application/json and a same-origin Sec-Fetch-Site, so a page on another site cannot submit them. Requests whose Host header is neither an IP address, localhost nor a name in ALLOWED_HOSTS (default: the host of PUBLIC_URL) get 421, which blocks DNS rebinding; set ALLOWED_HOSTS=* to turn that off (only the literal * does; an entry without a host name, such as *. or :80, stops the start; non-ASCII names are matched in the punycode form browsers send, so the deviation characters ß, ς, ZWNJ and ZWJ are kept, an upper-case Σ counts as σ, invisible characters such as a soft hyphen are removed, and an ideographic or fullwidth full stop counts as a dot). A request with more than one Host header gets 400. Every response carries Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none': the page runs only its own script and style, with no inline script or style attribute, talks only to its own origin and cannot be framed. A reverse proxy that adds its own CSP must allow at least this. The CSV export neutralises spreadsheet formula injection from untrusted hostnames, also a formula after ; or a line break (quotes and blanks in between do not hide it) and in the switch_port column. So in a note or other text cell a -, +, = or @ after ; or a line break gets a leading apostrophe (a list line - milk becomes '- milk), as only that stops a semicolon-separated Excel (e.g. sv-SE) from starting a formula there; import-csv strips them again. Requests to the firewall and the UniFi controller ignore http_proxy/https_proxy unless the instance sets PROXY=1, so a proxy never sees their credentials; mail to Mailgun and webhooks always use them (SMTP never does).

Write protection: READ_ONLY=1 refuses every change (POST gets 403 read-only); the page stays readable. WRITE_ALLOW (a comma list of addresses and networks, e.g. 10.0.10.0/24; empty = no limit) refuses changes from every other client with 403 writes are not allowed from this address. When both are set, READ_ONLY wins. With login on, both apply on top of it: the user must log in and be allowed to write. The page shows Name, Note and Tags read-only, without the Save, Mark known, Archive and Watch buttons, to a client that may not write. Refusals outside WRITE_ALLOW are logged at most once a minute with a count and the last client address. The address checked is the socket peer only, never X-Forwarded-For (any client can send that header). So behind the nginx-proxy variant every request comes from the proxy and WRITE_ALLOW can only allow all or none of the proxied clients: restrict writes at the proxy instead, e.g. location /api/ { limit_except GET HEAD { allow 10.0.10.0/24; deny all; } ... } (with nginx-proxy, in its per-host vhost.d file), or set READ_ONLY=1. With login off, also bind to the admin VLAN (LISTEN_HOST, or compose ports: ["10.0.10.5:8080:8080"] with the host's address on the admin VLAN instead of 8080:8080) and set WRITE_ALLOW to the admin VLAN.

Tests

python3 -m unittest discover -s tests -v — collector, enrichers and a full HTTP API suite (fake firewall, no network).

python3 -m unittest tests.test_ui_browser -v — UI tests in headless Chrome (node + puppeteer from npm root -g, Chrome from LW_TEST_CHROME or the usual paths); they skip without node, puppeteer or Chrome.

No test may reach the network: tests/_netguard.py (installed for every module, and for the contrib suites) fails any test that connects to or resolves a non-loopback address, even when the code under test swallows the error; fake or stub the client instead.

ruff check . — lint (rules and exceptions in pyproject.toml); install it for development with pip install ruff.

License

MIT — see LICENSE.

About

Dashboard for DHCP leases on your lan, find new devices easy.

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages