diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5eb30d6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +node_modules +.env +*.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..568b3c4 --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# Public hostname Traefik routes to this app +APP_HOST=km.example.com + +# Your running Traefik setup +TRAEFIK_NETWORK=traefik +TRAEFIK_ENTRYPOINT=websecure +TRAEFIK_CERTRESOLVER=letsencrypt + +# PostgreSQL (created by this compose file; choose a strong password) +POSTGRES_DB=kilometerlog +POSTGRES_USER=kilometerlog +POSTGRES_PASSWORD=change-me + +# Optional basic auth (htpasswd format, escape every $ as $$) +# BASIC_AUTH_USERS=mitchell:$$apr1$$.... diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6138acf --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM node:20-alpine +WORKDIR /app +ENV NODE_ENV=production +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev && npm cache clean --force +COPY server.js ./ +COPY public ./public +USER node +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD wget -qO- http://127.0.0.1:3000/healthz >/dev/null || exit 1 +CMD ["node", "server.js"] diff --git a/README.md b/README.md index 3676e4a..4891aee 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,151 @@ -# kilometer_logbook +# Kilometer Log +Trip log (kilometres, start/end date, license plate with country, location, category) with a statistics page. +A Node app and its own PostgreSQL database, served behind your existing Traefik. + +## Deploy with Portainer + +All settings live in the stack's **Environment variables** in Portainer. No `.env` file is used. + +1. **Build the app image** on the Docker host, from this folder. The web editor can't build, and the image is not on Docker Hub: + + ```sh + docker build -t kilometer-log:latest . + ``` + +2. **Create the stack:** *Stacks → Add stack → Web editor*, and paste `docker-compose.portainer.yml`. + +3. **Add the variables:** under *Environment variables*, switch to *Advanced mode* and paste the lines from `stack.env.example`, or use *Load variables from .env file* with that file. + - Set `APP_HOST` and a strong `POSTGRES_PASSWORD`. + - Check that `TRAEFIK_NETWORK`, `TRAEFIK_ENTRYPOINT` and `TRAEFIK_CERTRESOLVER` match your Traefik setup. To find the network name: + + ```sh + docker inspect traefik --format '{{json .NetworkSettings.Networks}}' + ``` + +4. **Deploy the stack.** + +How the variables are used: +- Portainer fills them into the compose file, which is how the Traefik labels get your hostname. +- Portainer also writes them to `stack.env`, which both containers load. The database and the app read the same `POSTGRES_*` values, so you enter them only once. + +To update the app later, rebuild the image (step 1) and redeploy the stack, or use *Update the stack*. + +## Deploy with the Docker CLI (alternative) + +`docker-compose.yml` builds the image itself and reads the same variables from your shell or a `.env` file next to it: + +```sh +cp stack.env.example .env # then edit it +docker compose up -d --build +``` + +Then open `https://`. + +The database runs in the `kilometer-log-db` container. +- Its data lives in the `pgdata` volume. +- It sits on an internal network, so only the app can reach it, not Traefik or the internet. +- The app creates its table on first start. + +## Importing your Excel sheet + +In Excel, select the rows including the header row, copy them, and choose **Import from Excel**. +Paste the rows there. + +- Distances can be in a `km` column or a `miles` column, or written as `120 mi`. Miles are converted to km. +- Headers such as `km`, `start`, `end`, `licenseplate`, `country`, `make/model`, `location` and `category` are recognised. +- Make/model is optional. You can also fill it in afterwards per vehicle on the Admin page. +- The country column is optional. Country names or codes both work (`Norway`, `NO`, `N`, `GB`, `UK`, `USA`). +- For US plates, add a `state` column (`CA`, `New York`), or write it in the country cell (`USA - CA`, `California`). +- Without a country column, Dutch-looking plates get NL and other plates are marked with a grey `?`. +- Categories: the names you set on the Admin page (default `Business`, `Rental`, `Personal`). `PNOD`, `business`, `zakelijk`, `hire`, `huur` and `privé` are recognised too. +- Dates like `14-10-2026`, `09-jan-24`, `9 maart 2024` and `2026-10-14` work (Dutch and English month names), as do decimal commas. + +## Home Assistant: personal trips from the odometer + +Each time the car's odometer changes, Home Assistant sends the new reading to the app. +The app adds the distance since the previous reading as a trip: +- **Category:** personal (you can pick another one in the setup). +- **Date:** the day of the reading, in the `TZ` time zone. +- **Location:** the town where the trip **started**, looked up from the car's GPS position. + - The departure place is where the car stood at the previous reading. + - Prefer the arrival place? Change *Location of these trips* in Admin → Home Assistant. + - The town's country becomes the location's country, unless you already set one for that town. +- **Plate, country and make/model:** copied from the trips already in the log for that plate. +- **Tag:** these trips show a small **HA** tag in the trip list. You can edit or delete them like any other trip. + +### Set it up + +Ready-made files are in the `home-assistant` folder of this zip (see its README); the steps below explain where they go. + +1. **Turn it on in the app.** Add a long random `HA_TOKEN` to the stack's environment variables in Portainer (`openssl rand -hex 32` makes one) and redeploy. +2. **Copy the YAML.** On the Admin page, open **Home Assistant → Set up Home Assistant**. Fill in the plate and your entities, for example `sensor.volvo_xc40_odometer` and `device_tracker.volvo_xc40_location`. It shows three blocks: one for `configuration.yaml`, one for `secrets.yaml`, and the automation. Paste the automation in Home Assistant under *Settings → Automations & scenes → Create automation → Edit in YAML*. + Choose how Home Assistant reaches the app. An internal route skips Traefik, so no redirects or public domain are involved: + - **Docker network: `http://kilometer-log:3000`.** Home Assistant runs in Docker on a network the app is also on, for example your Traefik network. + If Home Assistant has its own network, uncomment the `homeassistant` network in the compose file. + - **Same host: `http://127.0.0.1:3077`.** Home Assistant runs with `network_mode: host`. Uncomment the `ports:` lines in the compose file; the port is then reachable from the server only. + - **Public address:** through Traefik. Use the exact `https://` address, because a redirect from `http://` turns Home Assistant's POST into a GET and drops the data. + + Not sure which one applies? This shows Home Assistant's networks (use your container's name): + + ```sh + docker inspect homeassistant --format '{{.HostConfig.NetworkMode}} {{json .NetworkSettings.Networks}}' + ``` + +3. **Add the token** to Home Assistant's `secrets.yaml`: + + ```yaml + kilometer_log_auth: "Bearer " + ``` + +4. **Restart Home Assistant.** + +The first reading only sets the starting point; trips start with the second reading. +The Admin page shows the last reading per car and what happened with it. + +### Good to know + +- **Town names** come from OpenStreetMap (Nominatim), in Dutch by default (`GEOCODER_LANG`). + - The app follows OpenStreetMap's fair-use rules: at most one lookup per 1.5 seconds, a recognisable app name, and places it has already looked up are remembered. + - Only readings that become a trip are looked up. + - If a lookup fails, the zone name from Home Assistant is used ("Home", "Office"); outside a zone the location stays empty. The Admin page shows why. + - `GEOCODER=off` turns the lookup off, and `GEOCODER_URL` can point to your own Nominatim server. + - The car's position is sent to OpenStreetMap for this; nothing else is. +- **Several trips at once:** some cars only report a new odometer value now and then. If the reading jumps by several trips at once, they arrive as one trip. +- **Ignored readings:** readings that are the same or lower than before (for example after a Home Assistant restart) are ignored. +- **Large jumps:** a jump of more than 5000 km (`HA_MAX_JUMP_KM`) is skipped and becomes the new starting point, so a wrong value can't create a huge trip. +- **Restart button:** on the Admin page this forgets a car's last reading. The next reading then becomes the new starting point. +- **With Traefik basic auth:** the `Authorization` header is then used for the password. Instead: + - In the `rest_command`, add `username:` and `password:`. + - Send the token as an `X-HA-Token: ` header instead of `Authorization`. + +### The API (for other tools) + +`POST /api/ha/odometer`, with header `Authorization: Bearer ` and a JSON body: + +```json +{"plate": "S-123-AB", "odometer": 243950, "unit": "km", "time": "2026-10-22T19:19:47Z", "location": "Home", "category": "personal"} +``` + +Only `plate` and `odometer` are required. The answer says whether a trip was created. + +## Protecting it + +The app has no login. To add basic auth through Traefik: + +```sh +htpasswd -nb mitchell 'your-password' | sed -e 's/\$/\$\$/g' +``` + +Add the output as `BASIC_AUTH_USERS` to the stack's environment variables in Portainer. Then uncomment the two middleware labels in `docker-compose.yml`. + +## Backup and restore + +```sh +docker exec kilometer-log-db pg_dump -U kilometerlog kilometerlog > kilometerlog.sql +docker exec -i kilometer-log-db psql -U kilometerlog kilometerlog < kilometerlog.sql +``` + +## Updating + +Replace the files and run `docker compose up -d --build`. The data in the `pgdata` volume is kept. diff --git a/docker-compose.portainer.yml b/docker-compose.portainer.yml new file mode 100644 index 0000000..241dbcb --- /dev/null +++ b/docker-compose.portainer.yml @@ -0,0 +1,64 @@ +# Kilometer Log — Portainer stack (web editor). +# +# All settings come from the stack's "Environment variables" in Portainer, not from a .env file: +# - ${...} below is filled in by Portainer from those variables (needed for the Traefik labels); +# - stack.env is the file Portainer writes from those same variables; both containers load it. +# See stack.env.example for the variables to add. +# +# The app image is built on the Docker host first (the web editor cannot build): +# docker build -t kilometer-log:latest . +services: + kilometer-log: + image: kilometer-log:latest + pull_policy: never # use the image built on this server, never pull it + container_name: kilometer-log + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + env_file: + - stack.env # Portainer's environment variables (POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD, ...) + environment: + DB_HOST: postgres + DB_PORT: 5432 + networks: + - traefik + - backend + labels: + - "traefik.enable=true" + - "traefik.docker.network=${TRAEFIK_NETWORK:-traefik}" + - "traefik.http.routers.kilometer-log.rule=Host(`${APP_HOST:?Add APP_HOST to the stack's environment variables in Portainer}`)" + - "traefik.http.routers.kilometer-log.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}" + - "traefik.http.routers.kilometer-log.tls=true" + - "traefik.http.routers.kilometer-log.tls.certresolver=${TRAEFIK_CERTRESOLVER:-letsencrypt}" + - "traefik.http.services.kilometer-log.loadbalancer.server.port=3000" + # The app has no login of its own. Uncomment to protect it with basic auth + # (add BASIC_AUTH_USERS to the stack's environment variables, see README): + # - "traefik.http.routers.kilometer-log.middlewares=kilometer-log-auth" + # - "traefik.http.middlewares.kilometer-log-auth.basicauth.users=${BASIC_AUTH_USERS}" + + postgres: + image: postgres:16-alpine + container_name: kilometer-log-db + restart: unless-stopped + env_file: + - stack.env # POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD from Portainer + volumes: + - pgdata:/var/lib/postgresql/data + networks: + - backend + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-kilometerlog} -d $${POSTGRES_DB:-kilometerlog}"] + interval: 10s + timeout: 5s + retries: 10 + +volumes: + pgdata: + +networks: + traefik: + external: true + name: ${TRAEFIK_NETWORK:-traefik} + backend: + internal: true diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e0e3f22 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,71 @@ +services: + kilometer-log: + build: . + image: kilometer-log:latest + pull_policy: build # built locally from the Dockerfile, never pulled from a registry + container_name: kilometer-log + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + environment: + DB_HOST: postgres + DB_PORT: 5432 + DB_NAME: ${POSTGRES_DB:-kilometerlog} + DB_USER: ${POSTGRES_USER:-kilometerlog} + DB_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD} + HA_TOKEN: ${HA_TOKEN:-} # optional: turns on the Home Assistant import + TZ: ${TZ:-Europe/Amsterdam} + GEOCODER: ${GEOCODER:-nominatim} + GEOCODER_LANG: ${GEOCODER_LANG:-nl} + GEOCODER_URL: ${GEOCODER_URL:-https://nominatim.openstreetmap.org} + GEOCODER_EMAIL: ${GEOCODER_EMAIL:-} + networks: + - traefik2_proxy + - backend + - chrony + labels: + - "traefik.enable=true" + - "traefik.docker.network=${TRAEFIK_NETWORK:-traefik}" + - "traefik.http.routers.kilometer-log.rule=Host(`${APP_HOST:?Set APP_HOST}`)" + - "traefik.http.routers.kilometer-log.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}" + - "traefik.http.routers.kilometer-log.tls=true" + - "traefik.http.routers.kilometer-log.tls.certresolver=${TRAEFIK_CERTRESOLVER:-letsencrypt}" + - "traefik.http.services.kilometer-log.loadbalancer.server.port=3000" + - "traefik.http.middlewares.kilometer-auth.basicauth.users=mitchell:$$2a$$12$$L5VPOJNginfCuCud381pcuw75lztg/Qyi8noJXVM3z8n/ubntbvPy" + - "traefik.http.routers.kilometer-log.middlewares=kilometer-auth" + + # The app has no login of its own. Uncomment to protect it with basic auth + # (set BASIC_AUTH_USERS, see README): + # - "traefik.http.routers.kilometer-log.middlewares=kilometer-log-auth" + # - "traefik.http.middlewares.kilometer-log-auth.basicauth.users=${BASIC_AUTH_USERS}" + + postgres: + image: postgres:16-alpine + container_name: kilometer-log-db + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:-kilometerlog} + POSTGRES_USER: ${POSTGRES_USER:-kilometerlog} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD} + volumes: + - pgdata:/var/lib/postgresql/data + networks: + - backend + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 10s + timeout: 5s + retries: 10 + +volumes: + pgdata: + +networks: + traefik2_proxy: + external: true + name: ${TRAEFIK_NETWORK:-traefik} + backend: + internal: true + chrony: + external: false diff --git a/home-assistant/README.md b/home-assistant/README.md new file mode 100644 index 0000000..ee9836f --- /dev/null +++ b/home-assistant/README.md @@ -0,0 +1,20 @@ +# Home Assistant files + +Three files to connect Home Assistant to Kilometer Log. They are the same as what the app shows under **Admin → Home Assistant**, filled in for a Volvo XC40. + +| File | Where it goes | +|---|---| +| `configuration.yaml` | Add to Home Assistant's `configuration.yaml`, then restart Home Assistant. | +| `secrets.yaml.example` | Add the line to Home Assistant's `secrets.yaml`, with your `HA_TOKEN` after `Bearer `. | +| `automation.yaml` | *Settings → Automations & scenes → Create automation → ⋮ → Edit in YAML*: replace everything with it and save. | + +Before you use them: + +- **Plate:** replace `AB-123-C` in `configuration.yaml` with your car's plate. +- **Entity names:** if your car's entities have other names than `sensor.volvo_xc40_odometer` and `device_tracker.volvo_xc40_location`, change them in `automation.yaml`. +- **Address:** `configuration.yaml` reaches the app over Docker's internal network, at `http://kilometer-log:3000`. + - Home Assistant runs with `network_mode: host`? Use `http://127.0.0.1:3077` and uncomment the `ports:` lines in the compose file. + - Using the public address instead? Use the exact `https://` address, without a redirect. + +To test it, open the automation and choose **Run actions**. After a minute, Admin → Home Assistant shows "First reading saved". +The automation reads the sensor directly, so this manual test works; older versions used `trigger.to_state` and failed when run by hand. diff --git a/home-assistant/automation.yaml b/home-assistant/automation.yaml new file mode 100644 index 0000000..4dc1751 --- /dev/null +++ b/home-assistant/automation.yaml @@ -0,0 +1,31 @@ +# Kilometer Log — paste this in Settings → Automations & scenes → Create automation → ⋮ → Edit in YAML +# Generated from the app's Admin → Home Assistant page. Replace AB-123-C with your plate, +# and the sensor/tracker names if yours differ. + +alias: "Kilometer Log: send odometer" +description: "Sends the odometer and position to Kilometer Log, which adds the distance as a trip." +mode: queued +triggers: + - trigger: state + entity_id: sensor.volvo_xc40_odometer +conditions: + - condition: template + value_template: "{{ states('sensor.volvo_xc40_odometer') | is_number }}" +actions: + # give the car's position a moment to update after the odometer + - delay: "00:01:00" + - action: rest_command.kilometer_log_odometer + # the app's answer (status and message) shows up in this automation's trace + response_variable: kilometer_log + data: + # read from the sensor itself, so "Run actions" (a manual test) works too + odometer: "{{ states('sensor.volvo_xc40_odometer') }}" + unit: "{{ state_attr('sensor.volvo_xc40_odometer', 'unit_of_measurement') or 'km' }}" + time: "{{ states['sensor.volvo_xc40_odometer'].last_changed.isoformat() }}" + # the app looks up the town and country for this position + latitude: "{{ state_attr('device_tracker.volvo_xc40_location', 'latitude') }}" + longitude: "{{ state_attr('device_tracker.volvo_xc40_location', 'longitude') }}" + # only used if the town can't be looked up: the zone name, when the car is in one + location: >- + {% set s = states('device_tracker.volvo_xc40_location') %} + {% if s == 'home' %}{{ state_attr('zone.home', 'friendly_name') }}{% elif s not in ['not_home', 'unknown', 'unavailable'] %}{{ s }}{% endif %} diff --git a/home-assistant/configuration.yaml b/home-assistant/configuration.yaml new file mode 100644 index 0000000..e21800b --- /dev/null +++ b/home-assistant/configuration.yaml @@ -0,0 +1,15 @@ +# Kilometer Log — add this to Home Assistant's configuration.yaml, then restart Home Assistant +# Generated from the app's Admin → Home Assistant page. Replace AB-123-C with your plate, +# and the sensor/tracker names if yours differ. + +rest_command: + kilometer_log_odometer: + url: "http://kilometer-log:3000/api/ha/odometer" + method: POST + headers: + Authorization: !secret kilometer_log_auth + content_type: "application/json" + payload: >- + {"plate": "AB-123-C", "odometer": {{ odometer }}, "unit": "{{ unit }}", + "time": "{{ time }}", "latitude": {{ latitude | to_json }}, "longitude": {{ longitude | to_json }}, + "location": {{ location | to_json }}, "category": "personal"} diff --git a/home-assistant/secrets.yaml.example b/home-assistant/secrets.yaml.example new file mode 100644 index 0000000..ea55dd0 --- /dev/null +++ b/home-assistant/secrets.yaml.example @@ -0,0 +1,4 @@ +# Kilometer Log — add this line to Home Assistant's secrets.yaml. +# Use the same token as HA_TOKEN in the app's stack, after "Bearer ". + +kilometer_log_auth: "Bearer " diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e8d3277 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,971 @@ +{ + "name": "kilometer-log", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "kilometer-log", + "version": "1.0.0", + "dependencies": { + "express": "4.21.2", + "pg": "8.13.1" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/pg": { + "version": "8.13.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.13.1.tgz", + "integrity": "sha512-OUir1A0rPNZlX//c7ksiu7crsGZTKSOXJPgtNiHGIlC9H0lO+NC6ZDYksSgBYY/thSWhnSRBv8w1lieNNGATNQ==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.7.0", + "pg-pool": "^3.7.0", + "pg-protocol": "^1.7.0", + "pg-types": "^2.1.0", + "pgpass": "1.x" + }, + "engines": { + "node": ">= 8.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.1.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.6.tgz", + "integrity": "sha512-lqIfH7bdgsxHAY/ZnUOwm+aCFKrsHBDhSFuk9O0B9uCqJAIkrKTo/+LQqLPLUS4e04+jCmQVikxE3QipH5chPw==", + "license": "MIT" + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..53dfabb --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "kilometer-log", + "version": "1.0.0", + "private": true, + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "4.21.2", + "pg": "8.13.1" + } +} \ No newline at end of file diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..a055c60 --- /dev/null +++ b/public/index.html @@ -0,0 +1,1352 @@ + + + + + +Kilometer Log + + + + + + + + +
+
+
+ +

Kilometer Log

+
+
+ + + +
+ +
+
+ +
+ + +
+
+
+ +
+
+
+ + + +
+
+
+
+ + + + +
+ +
+
+ + + + + diff --git a/server.js b/server.js new file mode 100644 index 0000000..cf969f6 --- /dev/null +++ b/server.js @@ -0,0 +1,480 @@ +// Kilometer Log — small API + static page, backed by PostgreSQL. +const path = require("path"); +const crypto = require("crypto"); +const express = require("express"); +const { Pool, types } = require("pg"); + +// Return DATE columns as 'YYYY-MM-DD' strings and NUMERIC as numbers. +types.setTypeParser(1082, v => v); +types.setTypeParser(1700, v => parseFloat(v)); + +const PORT = Number(process.env.PORT || 3000); +const CATEGORIES = ["PNOD", "hire", "personal"]; +// Home Assistant: the webhook is only enabled when a token is set (HA_TOKEN in the stack's environment variables). +const HA_TOKEN = String(process.env.HA_TOKEN || "").trim(); +const TZ = process.env.TZ || "Europe/Amsterdam"; // used to turn a reading's time into the trip date +const HA_MAX_JUMP_KM = Number(process.env.HA_MAX_JUMP_KM || 5000); +// Turning coordinates into a town name: OpenStreetMap Nominatim by default (GEOCODER=off disables it). +const GEOCODER = String(process.env.GEOCODER || "nominatim").toLowerCase(); +const GEOCODER_URL = String(process.env.GEOCODER_URL || "https://nominatim.openstreetmap.org").replace(/\/+$/, ""); +const GEOCODER_LANG = process.env.GEOCODER_LANG || "nl"; +const GEOCODER_EMAIL = process.env.GEOCODER_EMAIL || ""; + +const pool = new Pool({ + host: process.env.DB_HOST || "postgres", + port: Number(process.env.DB_PORT || 5432), + // DB_* wins; otherwise the same POSTGRES_* variables the database container uses (e.g. from Portainer's stack.env) + user: process.env.DB_USER || process.env.POSTGRES_USER || "kilometerlog", + password: process.env.DB_PASSWORD || process.env.POSTGRES_PASSWORD || "", + database: process.env.DB_NAME || process.env.POSTGRES_DB || "kilometerlog", + max: 5, +}); + +async function migrate() { + await pool.query(` + CREATE TABLE IF NOT EXISTS trips ( + id SERIAL PRIMARY KEY, + km NUMERIC(8,1) NOT NULL CHECK (km > 0), + start_date DATE NOT NULL, + end_date DATE NOT NULL, + plate VARCHAR(16) NOT NULL, + country VARCHAR(3) NOT NULL DEFAULT 'NL', + region VARCHAR(3) NOT NULL DEFAULT '', + model VARCHAR(60) NOT NULL DEFAULT '', + location VARCHAR(255) NOT NULL DEFAULT '', + category VARCHAR(10) NOT NULL CHECK (category IN ('PNOD','hire','personal')), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (end_date >= start_date) + )`); + // Upgrade tables created before make/model existed. + await pool.query("ALTER TABLE trips ADD COLUMN IF NOT EXISTS model VARCHAR(60) NOT NULL DEFAULT ''"); + // Each location's country, stored once per location name. + await pool.query(`CREATE TABLE IF NOT EXISTS locations ( + name VARCHAR(255) PRIMARY KEY, + country VARCHAR(3) NOT NULL DEFAULT '' + )`); + // App settings (key/value), e.g. the category names. + await pool.query(`CREATE TABLE IF NOT EXISTS settings ( + key VARCHAR(64) PRIMARY KEY, + value JSONB NOT NULL + )`); + // Where a trip came from ('' = typed or imported, 'ha' = Home Assistant). + await pool.query("ALTER TABLE trips ADD COLUMN IF NOT EXISTS source VARCHAR(16) NOT NULL DEFAULT ''"); + // Last odometer reading per car, received from Home Assistant. + await pool.query(`CREATE TABLE IF NOT EXISTS ha_odometer ( + plate_key VARCHAR(16) PRIMARY KEY, -- plate without spaces/dashes, upper case + plate VARCHAR(16) NOT NULL, + odometer_km NUMERIC(10,1) NOT NULL, + read_at TIMESTAMPTZ NOT NULL, + last_event TEXT NOT NULL DEFAULT '', + last_event_at TIMESTAMPTZ NOT NULL DEFAULT now() + )`); + // Where the car was at that reading: the departure place of the next trip. + await pool.query("ALTER TABLE ha_odometer ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION"); + await pool.query("ALTER TABLE ha_odometer ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION"); + await pool.query("ALTER TABLE ha_odometer ADD COLUMN IF NOT EXISTS place_text VARCHAR(255) NOT NULL DEFAULT ''"); + await pool.query("CREATE INDEX IF NOT EXISTS trips_start_idx ON trips (start_date)"); + await pool.query("CREATE INDEX IF NOT EXISTS trips_plate_idx ON trips (plate)"); +} + +async function waitForDb(retries = 30) { + for (let i = 1; i <= retries; i++) { + try { await pool.query("SELECT 1"); return; } + catch (e) { + console.log(`Waiting for PostgreSQL (${i}/${retries}): ${e.code || e.message}`); + await new Promise(r => setTimeout(r, 2000)); + } + } + throw new Error("PostgreSQL not reachable"); +} + +const isDate = s => typeof s === "string" && /^\d{4}-\d{2}-\d{2}$/.test(s) && !isNaN(Date.parse(s)); + +function validate(b) { + const t = { + km: Math.round(Number(b.km) * 10) / 10, + start: b.start, + end: b.end || b.start, + plate: String(b.plate || "").trim().toUpperCase().replace(/\s+/g, " ").slice(0, 16), + country: String(b.country ?? "").trim().toUpperCase(), + region: String(b.region ?? "").trim().toUpperCase(), + model: String(b.model ?? "").trim().replace(/\s+/g, " ").slice(0, 60), + location: String(b.location || "").trim().slice(0, 255), + category: b.category, + }; + if (!isDate(t.start)) return { error: "Start date must be YYYY-MM-DD." }; + if (!isDate(t.end)) return { error: "End date must be YYYY-MM-DD." }; + if (t.end < t.start) return { error: "The end date is before the start date." }; + if (!(t.km > 0) || t.km > 9999999) return { error: "Kilometres must be a number above 0." }; + if (!t.plate) return { error: "License plate is required." }; + if (!/^[A-Z]{0,3}$/.test(t.country)) return { error: "Country must be a code of 1 to 3 letters, like NL, N, UK or USA." }; + if (!/^[A-Z]{0,3}$/.test(t.region)) return { error: "State must be a 2-letter code, like CA or NY." }; + if (t.country !== "USA") t.region = ""; + if (!CATEGORIES.includes(t.category)) return { error: "Category must be business (PNOD), rental (hire) or personal." }; + return { trip: t }; +} +const COLS = "km, start_date, end_date, plate, country, region, model, location, category"; +const NCOLS = 9; +const row = t => [t.km, t.start, t.end, t.plate, t.country, t.region, t.model, t.location, t.category]; +const placeholders = (n, offset = 0) => "(" + Array.from({ length: n }, (_, i) => "$" + (offset + i + 1)).join(",") + ")"; + +const app = express(); +app.use(express.json({ limit: "5mb" })); +const wrap = fn => (req, res) => fn(req, res).catch(e => { + console.error(e); + res.status(500).json({ error: "Database error" }); +}); + +app.get("/healthz", wrap(async (req, res) => { await pool.query("SELECT 1"); res.json({ ok: true }); })); + +app.get("/api/trips", wrap(async (req, res) => { + const { rows } = await pool.query( + `SELECT id, km, start_date AS start, end_date AS "end", plate, country, region, model, location, category, source + FROM trips ORDER BY start_date DESC, id DESC`); + res.json(rows); +})); + +app.post("/api/trips", wrap(async (req, res) => { + const v = validate(req.body || {}); + if (v.error) return res.status(400).json({ error: v.error }); + const { rows } = await pool.query(`INSERT INTO trips (${COLS}) VALUES ${placeholders(NCOLS)} RETURNING id`, row(v.trip)); + res.status(201).json({ id: rows[0].id }); +})); + +app.post("/api/trips/bulk", wrap(async (req, res) => { + const list = Array.isArray(req.body && req.body.trips) ? req.body.trips : null; + if (!list || !list.length) return res.status(400).json({ error: "No trips to import." }); + if (list.length > 10000) return res.status(400).json({ error: "Import at most 10,000 trips at once." }); + const rows = []; + for (let i = 0; i < list.length; i++) { + const v = validate(list[i]); + if (v.error) return res.status(400).json({ error: `Row ${i + 1}: ${v.error}` }); + rows.push(row(v.trip)); + } + const client = await pool.connect(); + try { + await client.query("BEGIN"); + for (let i = 0; i < rows.length; i += 500) { + const chunk = rows.slice(i, i + 500); + const values = chunk.map((_, j) => placeholders(NCOLS, j * NCOLS)).join(","); + await client.query(`INSERT INTO trips (${COLS}) VALUES ${values}`, chunk.flat()); + } + await client.query("COMMIT"); + } catch (e) { await client.query("ROLLBACK"); throw e; } + finally { client.release(); } + res.status(201).json({ inserted: rows.length }); +})); + +app.put("/api/trips/:id", wrap(async (req, res) => { + const v = validate(req.body || {}); + if (v.error) return res.status(400).json({ error: v.error }); + const r = await pool.query( + `UPDATE trips SET km=$1, start_date=$2, end_date=$3, plate=$4, country=$5, region=$6, model=$7, location=$8, category=$9, updated_at=now() + WHERE id=$10`, [...row(v.trip), Number(req.params.id)]); + if (!r.rowCount) return res.status(404).json({ error: "Trip not found." }); + res.status(204).end(); +})); + +// Update a vehicle (plate + its current country) on all its trips: country, US state and make/model. +app.post("/api/vehicles/update", wrap(async (req, res) => { + const b = req.body || {}; + const plate = String(b.plate || "").trim().toUpperCase(); + const from = String(b.from ?? "").trim().toUpperCase(), to = String(b.country ?? "").trim().toUpperCase(); + const region = to === "USA" ? String(b.region ?? "").trim().toUpperCase() : ""; + const model = String(b.model ?? "").trim().replace(/\s+/g, " ").slice(0, 60); + if (!plate || !/^[A-Z]{0,3}$/.test(from) || !/^[A-Z]{0,3}$/.test(to) || !/^[A-Z]{0,3}$/.test(region)) + return res.status(400).json({ error: "Give a plate and country codes of up to 3 letters." }); + const r = await pool.query( + "UPDATE trips SET country=$1, region=$2, model=$3, updated_at=now() WHERE plate=$4 AND country=$5", + [to, region, model, plate, from]); + res.json({ updated: r.rowCount }); +})); + +// Rewrite plates in their standard format (e.g. GX482T -> GX-482-T) for a list of vehicles, in one transaction. +app.post("/api/plates/rename", wrap(async (req, res) => { + const list = Array.isArray(req.body && req.body.changes) ? req.body.changes : null; + if (!list || !list.length || list.length > 5000) return res.status(400).json({ error: "No plates to rename." }); + const clean = v => String(v ?? "").trim().toUpperCase().replace(/\s+/g, " ").slice(0, 16); + const client = await pool.connect(); let updated = 0; + try { + await client.query("BEGIN"); + for (const c of list) { + const from = clean(c.from), to = clean(c.to), country = String(c.country ?? "").trim().toUpperCase(); + if (!from || !to || !/^[A-Z]{0,3}$/.test(country)) throw Object.assign(new Error("bad"), { status: 400 }); + const r = await client.query("UPDATE trips SET plate=$1, updated_at=now() WHERE plate=$2 AND country=$3", [to, from, country]); + updated += r.rowCount; + } + await client.query("COMMIT"); + } catch (e) { + await client.query("ROLLBACK"); + if (e.status === 400) return res.status(400).json({ error: "Each change needs a plate, a new plate and a country code." }); + throw e; + } finally { client.release(); } + res.json({ updated }); +})); + +app.get("/api/settings", wrap(async (req, res) => { + const { rows } = await pool.query("SELECT value FROM settings WHERE key='categoryLabels'"); + res.json({ categoryLabels: rows[0] ? rows[0].value : {} }); +})); + +// Category names shown in the app. The stored categories (PNOD, hire, personal) never change. +app.put("/api/settings/categories", wrap(async (req, res) => { + const l = (req.body && req.body.labels) || {}; + const labels = {}; + for (const k of CATEGORIES) labels[k] = String(l[k] ?? "").trim().replace(/\s+/g, " ").slice(0, 30); + await pool.query( + "INSERT INTO settings (key, value) VALUES ('categoryLabels', $1) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value", + [JSON.stringify(labels)]); + res.status(204).end(); +})); + +app.get("/api/locations", wrap(async (req, res) => { + const { rows } = await pool.query("SELECT name, country FROM locations ORDER BY name"); + res.json(rows); +})); + +// Set (or clear) the country of a location. +app.put("/api/locations", wrap(async (req, res) => { + const b = req.body || {}; + const name = String(b.name ?? "").trim().replace(/\s+/g, " ").slice(0, 255); + const country = String(b.country ?? "").trim().toUpperCase(); + if (!name || !/^[A-Z]{0,3}$/.test(country)) return res.status(400).json({ error: "Give a location name and a country code of up to 3 letters." }); + if (country) await pool.query( + "INSERT INTO locations (name, country) VALUES ($1,$2) ON CONFLICT (name) DO UPDATE SET country=EXCLUDED.country", [name, country]); + else await pool.query("DELETE FROM locations WHERE name=$1", [name]); + res.status(204).end(); +})); + +// Rename a location on every trip that uses it; renaming to an existing name merges them. +// The location's country moves along, unless the target already has one. +app.post("/api/locations/rename", wrap(async (req, res) => { + const b = req.body || {}; + const from = String(b.from ?? ""); + const to = String(b.to ?? "").trim().replace(/\s+/g, " ").slice(0, 255); + if (!to) return res.status(400).json({ error: "Enter the new location name." }); + const client = await pool.connect(); let updated = 0; + try { + await client.query("BEGIN"); + const r = await client.query("UPDATE trips SET location=$1, updated_at=now() WHERE location=$2", [to, from]); + updated = r.rowCount; + if (from && from !== to) { + await client.query( + `INSERT INTO locations (name, country) SELECT $2, country FROM locations WHERE name=$1 + ON CONFLICT (name) DO NOTHING`, [from, to]); + await client.query("DELETE FROM locations WHERE name=$1", [from]); + } + await client.query("COMMIT"); + } catch (e) { await client.query("ROLLBACK"); throw e; } + finally { client.release(); } + res.json({ updated }); +})); + +// Delete every trip of one vehicle (plate + country + US state). +app.post("/api/vehicles/delete", wrap(async (req, res) => { + const b = req.body || {}; + const plate = String(b.plate || "").trim().toUpperCase(); + const country = String(b.country ?? "").trim().toUpperCase(), region = String(b.region ?? "").trim().toUpperCase(); + if (!plate || !/^[A-Z]{0,3}$/.test(country) || !/^[A-Z]{0,3}$/.test(region)) + return res.status(400).json({ error: "Give the plate and its country." }); + const r = await pool.query("DELETE FROM trips WHERE plate=$1 AND country=$2 AND region=$3", [plate, country, region]); + res.json({ deleted: r.rowCount }); +})); + +/* ---------- Reverse geocoding (coordinates -> town + country) ---------- */ +// ISO country codes from OpenStreetMap -> the international plate codes the app uses. +const ISO_TO_PLATE = { nl:"NL", be:"B", de:"D", fr:"F", lu:"L", gb:"UK", ie:"IRL", no:"N", se:"S", dk:"DK", fi:"FIN", si:"SLO", + hr:"HR", at:"A", ch:"CH", it:"I", es:"E", pt:"P", pl:"PL", cz:"CZ", sk:"SK", hu:"H", ro:"RO", bg:"BG", gr:"GR", md:"MD", + ua:"UA", is:"IS", al:"AL", rs:"SRB", ba:"BIH", me:"MNE", mk:"NMK", tr:"TR", us:"USA", ca:"CDN", li:"FL", mc:"MC", ad:"AND" }; +const geoCache = new Map(); // "lat,lon" rounded to ~100 m -> {town, country} +let geoQueue = Promise.resolve(), geoLast = 0; +// Nominatim's usage policy: at most 1 request per second, identify the app, cache results. +function reverseGeocode(lat, lon) { + if (GEOCODER === "off") return Promise.resolve(null); + const key = lat.toFixed(3) + "," + lon.toFixed(3); + if (geoCache.has(key)) return Promise.resolve(geoCache.get(key)); + const run = async () => { + // at least 1.5 s between lookups: comfortably under Nominatim's 1 request per second + const wait = geoLast + 1500 - Date.now(); if (wait > 0) await new Promise(r => setTimeout(r, wait)); + geoLast = Date.now(); + const url = `${GEOCODER_URL}/reverse?format=jsonv2&zoom=12&addressdetails=1&lat=${lat}&lon=${lon}&accept-language=${encodeURIComponent(GEOCODER_LANG)}` + + (GEOCODER_EMAIL ? `&email=${encodeURIComponent(GEOCODER_EMAIL)}` : ""); + const r = await fetch(url, { headers: { "User-Agent": "KilometerLog/1.0 (self-hosted trip log)" }, signal: AbortSignal.timeout(8000) }); + if (!r.ok) throw new Error(`place lookup answered ${r.status}`); + const j = await r.json(), a = j.address || {}; + const town = a.city || a.town || a.village || a.municipality || a.hamlet || a.suburb || a.county || ""; + const iso = String(a.country_code || "").toLowerCase(); + const out = town ? { town: String(town).slice(0, 255), country: ISO_TO_PLATE[iso] || iso.toUpperCase().slice(0, 3) } : null; + if (geoCache.size > 2000) geoCache.clear(); + geoCache.set(key, out); + return out; + }; + const p = geoQueue.then(run, run); + geoQueue = p.catch(() => {}); + return p; +} + +/* ---------- Home Assistant ---------- */ +// Which place a Home Assistant trip gets: where it started ("start", the default) or where it ended ("end"). +async function haLocationFrom() { + const { rows } = await pool.query("SELECT value FROM settings WHERE key='haLocationFrom'"); + return rows[0] && rows[0].value === "end" ? "end" : "start"; +} +const plateKey = p => String(p || "").toUpperCase().replace(/[\s\-.·]/g, "").slice(0, 16); +function tokenOk(req) { + const h = String(req.get("authorization") || ""), given = h.startsWith("Bearer ") ? h.slice(7).trim() : String(req.get("x-ha-token") || ""); + if (!HA_TOKEN || !given) return false; + const a = Buffer.from(given), b = Buffer.from(HA_TOKEN); + return a.length === b.length && crypto.timingSafeEqual(a, b); +} +const localDate = d => new Intl.DateTimeFormat("en-CA", { timeZone: TZ, year: "numeric", month: "2-digit", day: "2-digit" }).format(d); + +// Home Assistant sends the odometer each time it changes. The distance since the previous reading becomes a trip. +// Body: { plate, odometer, unit?: "km"|"mi", time?: ISO string, latitude?, longitude?, location?: string, category?, model? } +// With latitude/longitude the location becomes the town there (and the town's country is stored); +// a "location" text is only used when there are no coordinates or the lookup fails. +app.post("/api/ha/odometer", wrap(async (req, res) => { + if (!HA_TOKEN) return res.status(404).json({ error: "Home Assistant import is off. Set HA_TOKEN to turn it on." }); + if (!tokenOk(req)) return res.status(401).json({ error: "Wrong or missing token." }); + const b = req.body || {}; + const key = plateKey(b.plate); + const unit = String(b.unit || "km").toLowerCase().startsWith("mi") ? "mi" : "km"; + const odo = Number(String(b.odometer ?? "").replace(",", ".")); + const when = b.time ? new Date(b.time) : new Date(); + const category = CATEGORIES.includes(b.category) ? b.category : "personal"; + let location = String(b.location ?? "").trim().replace(/\s+/g, " ").slice(0, 255); + const lat = Number(b.latitude), lon = Number(b.longitude); + const hasPos = Number.isFinite(lat) && Number.isFinite(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180 && !(lat === 0 && lon === 0); + if (!key) return res.status(400).json({ error: "Send the license plate as 'plate'." }); + if (!Number.isFinite(odo) || odo < 0) return res.status(400).json({ error: "Send the odometer reading as a number in 'odometer'." }); + if (isNaN(when)) return res.status(400).json({ error: "'time' is not a valid date." }); + const odoKm = Math.round((unit === "mi" ? odo * 1.609344 : odo) * 10) / 10; + + // Decide the trip's place before taking the database lock, so a slow town lookup never blocks other requests. + // - departure ("start"): where the car stood at the previous reading, i.e. where this trip began; + // - arrival ("end"): where the car is now. + // Only readings that become a trip are looked up (not repeats after a Home Assistant restart). + const here = { lat: hasPos ? lat : null, lon: hasPos ? lon : null, text: location }; // stored for the next trip + const from = await haLocationFrom(); + let place = null, placeNote = "", tripLocation = ""; + const { rows: [p] } = await pool.query("SELECT odometer_km, lat, lon, place_text FROM ha_odometer WHERE plate_key=$1", [key]); + if (p && odoKm > p.odometer_km && odoKm - p.odometer_km <= HA_MAX_JUMP_KM) { + let src = here; + if (from === "start") { + if (p.lat !== null || p.place_text) src = { lat: p.lat, lon: p.lon, text: p.place_text }; + else placeNote = " (departure place not known yet, so the arrival place is used)"; + } + tripLocation = src.text; + if (src.lat !== null && src.lon !== null) { + try { place = await reverseGeocode(src.lat, src.lon); if (!place && GEOCODER !== "off") placeNote += ` (no town found at ${src.lat.toFixed(4)}, ${src.lon.toFixed(4)})`; } + catch (e) { placeNote += ` (town lookup failed: ${e.message})`; console.log(`[ha] place lookup failed: ${e.message}`); } + if (place) tripLocation = place.town; + } + } + + const client = await pool.connect(); + try { + await client.query("BEGIN"); + // The vehicle as it is already in the log (exact plate spelling, country, state, model), if any. + const { rows: known } = await client.query( + `SELECT plate, country, region, model FROM trips + WHERE upper(translate(plate, ' -.', '')) = $1 ORDER BY start_date DESC, id DESC LIMIT 1`, [key]); + const v = known[0] || { plate: String(b.plate).trim().toUpperCase().slice(0, 16), country: "", region: "", model: "" }; + const model = v.model || String(b.model || "").trim().slice(0, 60); + + const first = await client.query( + `INSERT INTO ha_odometer (plate_key, plate, odometer_km, read_at, last_event, lat, lon, place_text) + VALUES ($1,$2,$3,$4,'First reading saved; the next reading creates a trip',$5,$6,$7) ON CONFLICT (plate_key) DO NOTHING`, + [key, v.plate, odoKm, when, here.lat, here.lon, here.text]); + const { rows: [prev] } = await client.query("SELECT * FROM ha_odometer WHERE plate_key=$1 FOR UPDATE", [key]); + const diff = Math.round((odoKm - prev.odometer_km) * 10) / 10; + let result; + + if (first.rowCount === 1) { + result = { status: "baseline", message: `First reading saved (${odoKm} km); the next reading creates a trip` }; + await client.query("UPDATE ha_odometer SET last_event=$2 WHERE plate_key=$1", [key, result.message]); + } else if (diff <= 0) { + // Same or lower reading (Home Assistant restart, duplicate message): nothing to add. + result = { status: "unchanged", message: `Odometer ${odoKm} km, no new distance` }; + // the car hasn't moved: only fill in a position if none was known yet + await client.query(`UPDATE ha_odometer SET last_event=$2, last_event_at=now(), + lat=COALESCE(lat,$3), lon=COALESCE(lon,$4), place_text=CASE WHEN place_text='' THEN $5 ELSE place_text END WHERE plate_key=$1`, + [key, result.message, here.lat, here.lon, here.text]); + } else if (diff > HA_MAX_JUMP_KM) { + result = { status: "skipped", message: `Skipped a jump of ${diff} km (more than ${HA_MAX_JUMP_KM} km); new starting point ${odoKm} km` }; + await client.query("UPDATE ha_odometer SET odometer_km=$2, read_at=$3, last_event=$4, last_event_at=now(), lat=$5, lon=$6, place_text=$7 WHERE plate_key=$1", + [key, odoKm, when, result.message, here.lat, here.lon, here.text]); + } else { + const day = localDate(when); + const { rows: [t] } = await client.query( + `INSERT INTO trips (km, start_date, end_date, plate, country, region, model, location, category, source) + VALUES ($1,$2,$2,$3,$4,$5,$6,$7,$8,'ha') RETURNING id`, + [diff, day, v.plate, v.country, v.region, model, tripLocation, category]); + const location = tripLocation; + // The town's country, unless you already set one for this location yourself. + let country; + if (place && place.country && location) { + await client.query("INSERT INTO locations (name, country) VALUES ($1,$2) ON CONFLICT (name) DO NOTHING", [location, place.country]); + const { rows: [lc] } = await client.query("SELECT country FROM locations WHERE name=$1", [location]); + country = lc ? lc.country : place.country; + } + result = { status: "created", trip: t.id, km: diff, location, country, + message: `Trip of ${diff} km added for ${day}${location ? (from === "start" ? " from " : " at ") + location : ""}${country ? " (" + country + ")" : ""}${placeNote}` }; + // where the car is now becomes the departure place of the next trip + await client.query("UPDATE ha_odometer SET odometer_km=$2, read_at=$3, plate=$4, last_event=$5, last_event_at=now(), lat=$6, lon=$7, place_text=$8 WHERE plate_key=$1", + [key, odoKm, when, v.plate, result.message, here.lat, here.lon, here.text]); + } + await client.query("COMMIT"); + console.log(`[ha] ${v.plate}: ${result.message}`); + res.status(result.status === "created" ? 201 : 200).json(result); + } catch (e) { await client.query("ROLLBACK"); throw e; } + finally { client.release(); } +})); + +// A GET here is either someone opening the address in a browser, or Home Assistant's POST after a 301/302 +// redirect (e.g. http -> https), which turns it into a GET without the data. Explain instead of "Cannot GET". +let haLastGet = null; +app.get("/api/ha/odometer", (req, res) => { + haLastGet = { at: new Date().toISOString(), agent: String(req.get("user-agent") || "").slice(0, 120) }; + console.log(`[ha] GET /api/ha/odometer from ${haLastGet.agent || "unknown"} — expected POST; probably a redirect`); + res.status(405).set("Allow", "POST").json({ + error: "This address only accepts POST requests from Home Assistant.", + hint: "If Home Assistant gets this answer, its request was redirected (for example from http:// to https://) and turned into a GET without the data. Use the exact https:// address of the app in configuration.yaml.", + }); +}); + +// What the Admin page shows: is the import on, and the last reading per car. Never returns the token. +app.get("/api/ha/status", wrap(async (req, res) => { + const { rows } = await pool.query( + "SELECT plate, odometer_km, read_at, last_event, last_event_at FROM ha_odometer ORDER BY plate"); + res.json({ enabled: !!HA_TOKEN, timezone: TZ, lastGet: haLastGet, locationFrom: await haLocationFrom(), geocoder: GEOCODER === "off" ? null : { url: GEOCODER_URL, lang: GEOCODER_LANG }, vehicles: rows }); +})); + +app.put("/api/settings/ha", wrap(async (req, res) => { + const v = (req.body && req.body.locationFrom) === "end" ? "end" : "start"; + await pool.query("INSERT INTO settings (key, value) VALUES ('haLocationFrom', $1) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value", + [JSON.stringify(v)]); + res.status(204).end(); +})); + +// Forget a car's last reading, so the next reading starts fresh (no trip is created from it). +app.delete("/api/ha/odometer/:plate", wrap(async (req, res) => { + await pool.query("DELETE FROM ha_odometer WHERE plate_key=$1", [plateKey(req.params.plate)]); + res.status(204).end(); +})); + +app.delete("/api/trips/:id", wrap(async (req, res) => { + await pool.query("DELETE FROM trips WHERE id=$1", [Number(req.params.id)]); + res.status(204).end(); +})); + +app.use(express.static(path.join(__dirname, "public"))); + +(async () => { + await waitForDb(); + await migrate(); + app.listen(PORT, () => console.log(`Kilometer Log listening on :${PORT}`)); +})().catch(e => { console.error(e); process.exit(1); }); + +process.on("SIGTERM", () => pool.end().finally(() => process.exit(0))); diff --git a/stack.env.example b/stack.env.example new file mode 100644 index 0000000..589d063 --- /dev/null +++ b/stack.env.example @@ -0,0 +1,31 @@ +# Variables for the Portainer stack. In Portainer: Stacks → your stack → Environment variables → +# "Advanced mode", and paste these lines (or use "Load variables from .env file" with this file). + +# Public hostname Traefik routes to this app +APP_HOST=km.example.com + +# Your running Traefik setup +TRAEFIK_NETWORK=traefik +TRAEFIK_ENTRYPOINT=websecure +TRAEFIK_CERTRESOLVER=letsencrypt + +# PostgreSQL (the database is created by the stack; choose a strong password) +POSTGRES_DB=kilometerlog +POSTGRES_USER=kilometerlog +POSTGRES_PASSWORD=change-me + +# Optional: Home Assistant import. A long random token, also put in Home Assistant's secrets.yaml. +# Generate one with: openssl rand -hex 32 +# HA_TOKEN= + +# Town names for Home Assistant trips are looked up on OpenStreetMap (Nominatim). +# GEOCODER=off turns this off; GEOCODER_LANG sets the language of the names (default nl); +# GEOCODER_URL can point to your own Nominatim server. +# GEOCODER_LANG=nl +# GEOCODER_EMAIL=you@example.com + +# Time zone used to date trips that come from Home Assistant +TZ=Europe/Amsterdam + +# Optional basic auth (htpasswd format, escape every $ as $$) +# BASIC_AUTH_USERS=mitchell:$$apr1$$....