From 87a3844255bb23c2f98b845b5d32997b00777348 Mon Sep 17 00:00:00 2001 From: Karl Date: Thu, 7 May 2026 14:46:36 +0100 Subject: [PATCH] feat: implement Ollama cloud usage server Add a lightweight Node.js server that scrapes Ollama cloud usage data from ollama.com/settings and exposes it as a JSON API. - Support for email/password and cookie-based authentication - Automated polling and Home Assistant integration - Endpoints for usage data, manual refresh, and cookie management - Comprehensive README and environment configuration --- .env.example | 18 + .gitignore | 3 + README.md | 148 ++++++++ package-lock.json | 855 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 13 + server.js | 439 ++++++++++++++++++++++++ 6 files changed, 1476 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 server.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..7457be1 --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Auth mode: "email" for automated login, "cookies" to use exported browser cookies +# For Google accounts without a password, use "cookies" mode +# Default: "email" if OLLAMA_PASSWORD is set, otherwise "cookies" +AUTH_MODE=email + +# For email auth mode +OLLAMA_EMAIL=you@example.com +OLLAMA_PASSWORD=your-password + +# Server port (default: 3214) +PORT=3214 + +# Polling interval in minutes (default: 10) +POLL_MINUTES=30 + +# Optional: Home Assistant push +HA_URL=http://homeassistant.local:8123 +HA_TOKEN=eyJhbGciOi... \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7c6b4b0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.env +.cookies.json +node_modules/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3d0d881 --- /dev/null +++ b/README.md @@ -0,0 +1,148 @@ +# Ollama Cloud Usage Server + +A lightweight Node.js server that scrapes your Ollama cloud usage from `ollama.com/settings` and exposes it as a JSON API. Works on headless servers. Optionally pushes to Home Assistant. + +**No browser on the server needed** — uses pure HTTP requests with cookie management. + +## Setup + +```bash +cp .env.example .env # Edit with your settings +npm install +npm start +``` + +## Authentication + +You have two options: + +### Option 1: Email/Password (for accounts with a password) + +Set in `.env`: +``` +AUTH_MODE=email +OLLAMA_EMAIL=you@example.com +OLLAMA_PASSWORD=your-password +``` + +If your account was created via Google OAuth and has no password set, use Option 2. + +### Option 2: Export cookies from your browser (works with Google/GitHub accounts) + +Use this if you sign in with Google/GitHub and don't have a password on your Ollama account. + +**Using a cookie export extension** (e.g. [EditThisCookie](https://editthiscookie.com/) or [Cookie-Editor](https://cookie-editor.com/)): +1. Install the extension, sign into ollama.com +2. Export cookies for ollama.com as JSON +3. POST the JSON array to the server: + +```bash +curl -X POST http://localhost:3214/api/cookies \ + -H "Content-Type: application/json" \ + -d @cookies.json +``` + +**Using DevTools directly:** +1. Sign into ollama.com in your browser +2. Open DevTools → Application → Cookies → `https://ollama.com` +3. Copy each cookie's name/value and POST as JSON + +Cookies are saved to `.cookies.json` and reused across polls. They eventually expire, at which point you'll need to re-export them. + +**Set in `.env`:** +``` +AUTH_MODE=cookies +``` + +## API Endpoints + +| Endpoint | Method | Description | +|---|---|---| +| `/api/usage` | GET | Latest polled usage data | +| `/api/usage/refresh` | GET | Force a fresh poll right now | +| `/api/health` | GET | Server status and config | +| `/api/cookies` | POST | Upload/replace cookies (JSON array) | + +### Example response (`/api/usage`) + +```json +{ + "session": { + "percent": 9.2, + "resetsIn": "2 hours" + }, + "weekly": { + "percent": 32.9, + "resetsIn": "3 days" + }, + "fetchedAt": "2026-05-07T13:08:44.194Z" +} +``` + +## Home Assistant Integration + +### Option A: Automatic push + +Set `HA_URL` and `HA_TOKEN` in `.env`. The server pushes to `sensor.ollama_session_usage` and `sensor.ollama_weekly_usage` after every poll. Sensors are created automatically in HA — no need to define them manually. + +### Option B: REST sensor (pull from HA) + +Add to `configuration.yaml`: + +```yaml +sensor: + - platform: rest + name: Ollama Session Usage + resource: http://localhost:3214/api/usage + value_template: "{{ value_json.session.percent | default('unavailable') }}" + unit_of_measurement: "%" + state_class: measurement + json_attributes: + - session + - weekly + - fetchedAt + scan_interval: 1800 + + - platform: rest + name: Ollama Weekly Usage + resource: http://localhost:3214/api/usage + value_template: "{{ value_json.weekly.percent | default('unavailable') }}" + unit_of_measurement: "%" + state_class: measurement + scan_interval: 1800 +``` + +## Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `AUTH_MODE` | `email` if password set, else `cookies` | `email` or `cookies` | +| `OLLAMA_EMAIL` | — | Email for email auth mode | +| `OLLAMA_PASSWORD` | — | Password for email auth mode | +| `PORT` | 3214 | Server port | +| `POLL_MINUTES` | 30 | Poll interval in minutes | +| `HA_URL` | — | Home Assistant URL (no trailing slash) | +| `HA_TOKEN` | — | HA long-lived access token | +| `COOKIE_FILE` | `.cookies.json` | Path to persist cookies | + +## Updating Cookies + +When cookies expire, re-export from your browser and POST again — it overwrites the old ones: + +```bash +curl -X POST http://localhost:3214/api/cookies \ + -H "Content-Type: application/json" \ + -d @fresh-cookies.json +``` + +The server logs will show `needsLogin` when cookies have expired. + +## Running as a Service + +```bash +# Using pm2 +npm install -g pm2 +pm2 start server.js --name ollama-usage +pm2 save +pm2 startup +``` \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..a01f436 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,855 @@ +{ + "name": "ollama-usage-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ollama-usage-server", + "version": "1.0.0", + "dependencies": { + "dotenv": "^16.4.5", + "express": "^4.21.0" + } + }, + "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.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "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.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "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/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "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.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "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.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "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.14.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.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "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.2", + "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.3", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", + "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "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.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "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.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "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.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "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.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "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.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "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.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "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" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..00a90f1 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "ollama-usage-server", + "version": "1.0.0", + "description": "Polls ollama.com/settings for cloud usage data and exposes it as a JSON API. Optionally pushes to Home Assistant.", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "dotenv": "^16.4.5", + "express": "^4.21.0" + } +} \ No newline at end of file diff --git a/server.js b/server.js new file mode 100644 index 0000000..17eea8e --- /dev/null +++ b/server.js @@ -0,0 +1,439 @@ +require("dotenv").config(); + +const express = require("express"); +const fs = require("fs"); +const path = require("path"); + +const SETTINGS_URL = "https://ollama.com/settings"; +const SIGNIN_URL = "https://ollama.com/signin"; +const POLL_MINUTES = parseInt(process.env.POLL_MINUTES || "30", 10); +const PORT = parseInt(process.env.PORT || "3214", 10); + +const OLLAMA_EMAIL = process.env.OLLAMA_EMAIL || ""; +const OLLAMA_PASSWORD = process.env.OLLAMA_PASSWORD || ""; +const AUTH_MODE = (process.env.AUTH_MODE || "").toLowerCase(); +const HA_URL = (process.env.HA_URL || "").replace(/\/+$/, ""); +const HA_TOKEN = process.env.HA_TOKEN || ""; +const COOKIE_FILE = process.env.COOKIE_FILE || path.join(__dirname, ".cookies.json"); + +let latestState = null; +let authCookies = null; + +function loadCookies() { + try { + const data = fs.readFileSync(COOKIE_FILE, "utf-8"); + authCookies = JSON.parse(data); + console.log("[auth] Loaded cookies from file"); + return true; + } catch { + return false; + } +} + +function saveCookies(cookies) { + authCookies = cookies; + try { + fs.writeFileSync(COOKIE_FILE, JSON.stringify(cookies, null, 2)); + } catch (err) { + console.error("[auth] Failed to save cookies:", err.message); + } +} + +function cookieString(cookies) { + return cookies.map((c) => `${c.name}=${c.value}`).join("; "); +} + +function parseSetCookies(setCookieHeaders) { + if (!setCookieHeaders) return []; + const arr = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders]; + return arr.map((header) => { + const parts = header.split(";")[0].split("="); + const name = parts[0].trim(); + const value = parts.slice(1).join("=").trim(); + return { name, value }; + }); +} + +function mergeCookies(existing, incoming) { + const map = new Map(); + for (const c of existing) map.set(c.name, c); + for (const c of incoming) map.set(c.name, c); + return [...map.values()]; +} + +async function httpRequest(url, options = {}) { + const headers = { ...options.headers }; + if (authCookies && authCookies.length > 0) { + headers["Cookie"] = cookieString(authCookies); + } + headers["User-Agent"] = headers["User-Agent"] || "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"; + + const res = await fetch(url, { + ...options, + headers, + redirect: "manual", + }); + + const setCookies = res.headers.getSetCookie?.() || []; + if (setCookies.length > 0 && authCookies) { + const parsed = parseSetCookies(setCookies); + authCookies = mergeCookies(authCookies, parsed); + saveCookies(authCookies); + } + + return res; +} + +async function fetchWithCookies(url, options = {}) { + let res = await httpRequest(url, options); + + const location = res.headers.get("location"); + if (location && (res.status === 301 || res.status === 302 || res.status === 303 || res.status === 307 || res.status === 308)) { + const nextUrl = new URL(location, url).href; + return fetchWithCookies(nextUrl, options); + } + + return res; +} + +function findUsage(html, label) { + const idx = html.indexOf(label); + if (idx === -1) return null; + const slice = html.slice(idx, idx + 3000); + const pct = slice.match(/(\d+(?:\.\d+)?)\s*%/); + const reset = slice.match(/Resets?\s+in\s+([^<\n.]+?)(?:<|\n|$)/i); + if (!pct) return null; + return { + percent: parseFloat(pct[1]), + resetsIn: reset ? reset[1].trim().replace(/\s+/g, " ") : null, + }; +} + +async function loginWithEmail() { + console.log("[auth] Logging in with email/password..."); + + authCookies = []; + + const getRes = await fetch(SIGNIN_URL, { + headers: { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36" }, + redirect: "manual", + }); + + const setCookies = getRes.headers.getSetCookie?.() || []; + authCookies = mergeCookies(authCookies, parseSetCookies(setCookies)); + + let csrfToken = null; + if (getRes.status >= 200 && getRes.status < 400) { + const html = await getRes.text(); + const csrfMatch = html.match(/name="csrf[_-]token"\s+(?:value|content)="([^"]+)"/i) || + html.match(/ 0) formHeaders["Cookie"] = cookieString(authCookies); + + let body = `email=${encodeURIComponent(OLLAMA_EMAIL)}&password=${encodeURIComponent(OLLAMA_PASSWORD)}`; + if (csrfToken) body += `&csrf_token=${encodeURIComponent(csrfToken)}&_csrf=${encodeURIComponent(csrfToken)}`; + + const loginRes = await fetch(SIGNIN_URL, { + method: "POST", + headers: formHeaders, + body, + redirect: "manual", + }); + + const loginCookies = loginRes.headers.getSetCookie?.() || []; + authCookies = mergeCookies(authCookies, parseSetCookies(loginCookies)); + + const location = loginRes.headers.get("location"); + + if (loginRes.status === 303 || loginRes.status === 302 || loginRes.status === 301) { + if (location && !location.includes("/signin")) { + console.log("[auth] Login successful (redirected to", location, ")"); + saveCookies(authCookies); + return true; + } + } + + if (loginRes.status === 200) { + const text = await loginRes.text(); + if (text.includes("/settings") || text.includes("dashboard")) { + console.log("[auth] Login appears successful (200 with settings link)"); + saveCookies(authCookies); + return true; + } + if (text.includes("invalid") || text.includes("wrong") || text.includes("error")) { + throw new Error("Login failed: invalid credentials"); + } + } + + if (location && location.includes("/signin")) { + throw new Error("Login failed: redirected back to signin. Check your credentials."); + } + + saveCookies(authCookies); + + const verifyRes = await fetchWithCookies(SETTINGS_URL); + if (verifyRes.url?.includes("/settings") || verifyRes.status === 200) { + const html = await verifyRes.text(); + if (!html.includes("/signin") || html.includes("Session usage") || html.includes("Weekly usage")) { + console.log("[auth] Login verified via settings page"); + return true; + } + } + + throw new Error("Login failed: could not authenticate with email/password"); +} + +async function tryWithSavedCookies() { + console.log("[auth] Trying with saved cookies..."); + const res = await fetchWithCookies(SETTINGS_URL); + + if (res.status !== 200) { + console.log("[auth] Settings page returned", res.status); + return false; + } + + const html = await res.text(); + + if (html.includes("Session usage") || html.includes("Weekly usage")) { + console.log("[auth] Saved cookies are valid!"); + return true; + } + + if (html.includes("/signin") || html.includes("sign in") || html.length < 2000) { + console.log("[auth] Cookies expired or invalid, need to re-authenticate"); + return false; + } + + console.log("[auth] Page doesn't contain usage data, might need re-auth"); + return false; +} + +async function pollUsage() { + let state; + + try { + if (!authCookies || authCookies.length === 0) { + if (!loadCookies()) { + const mode = AUTH_MODE || (OLLAMA_PASSWORD ? "email" : "cookies"); + if (mode === "email") { + await loginWithEmail(); + } else { + console.error("[auth] No cookies file found. Export cookies from your browser first (see README)."); + console.error("[auth] Or set OLLAMA_EMAIL + OLLAMA_PASSWORD for email auth."); + state = { needsLogin: true, error: "No authentication available. Export cookies or set credentials.", fetchedAt: new Date().toISOString() }; + latestState = state; + return state; + } + } + } + + if (!(await tryWithSavedCookies())) { + const mode = AUTH_MODE || (OLLAMA_PASSWORD ? "email" : "cookies"); + if (mode === "email") { + await loginWithEmail(); + } else { + console.error("[auth] Cookies expired and no email/password configured."); + state = { needsLogin: true, error: "Session expired. Re-export cookies or set OLLAMA_EMAIL/OLLAMA_PASSWORD.", fetchedAt: new Date().toISOString() }; + latestState = state; + return state; + } + } + + const res = await fetchWithCookies(SETTINGS_URL); + const html = await res.text(); + + const session = findUsage(html, "Session usage"); + const weekly = findUsage(html, "Weekly usage"); + + if (session || weekly) { + state = { session, weekly, fetchedAt: new Date().toISOString() }; + } else { + if (html.includes("/signin") || html.includes('href="/signin"') || html.length < 2000) { + console.log("[auth] Session expired, re-authenticating..."); + const mode = AUTH_MODE || (OLLAMA_PASSWORD ? "email" : "cookies"); + if (mode === "email") { + await loginWithEmail(); + const retryRes = await fetchWithCookies(SETTINGS_URL); + const retryHtml = await retryRes.text(); + const retrySession = findUsage(retryHtml, "Session usage"); + const retryWeekly = findUsage(retryHtml, "Weekly usage"); + if (retrySession || retryWeekly) { + state = { session: retrySession, weekly: retryWeekly, fetchedAt: new Date().toISOString() }; + } else { + state = { needsLogin: true, error: "Re-authentication succeeded but couldn't find usage data.", fetchedAt: new Date().toISOString() }; + } + } else { + state = { needsLogin: true, error: "Session expired. Re-export cookies or set OLLAMA_EMAIL/OLLAMA_PASSWORD.", fetchedAt: new Date().toISOString() }; + } + } else { + const titleMatch = html.match(/([^<]+)<\/title>/i); + state = { + scrapeFailed: true, + fetchedAt: new Date().toISOString(), + debug: { + length: html.length, + title: titleMatch ? titleMatch[1] : null, + hasSessionUsage: html.includes("Session usage"), + hasWeeklyUsage: html.includes("Weekly usage"), + hasCloudUsage: html.includes("Cloud Usage"), + sample: html.slice(0, 600), + }, + }; + } + } + } catch (err) { + state = { error: String(err), fetchedAt: new Date().toISOString() }; + } + + latestState = state; + console.log("[poll]", JSON.stringify(state, null, 2)); + + if (state.session || state.weekly) { + pushToHA(state).catch((err) => console.error("[ha] push failed:", err.message)); + } + + return state; +} + +async function pushToHA(state) { + if (!HA_URL || !HA_TOKEN) return; + + const sensors = []; + if (state.session) { + sensors.push({ + entity_id: "sensor.ollama_session_usage", + body: stateBody("Ollama Session Usage", "mdi:chart-arc", state.session, state.fetchedAt), + }); + } + if (state.weekly) { + sensors.push({ + entity_id: "sensor.ollama_weekly_usage", + body: stateBody("Ollama Weekly Usage", "mdi:chart-donut", state.weekly, state.fetchedAt), + }); + } + + const haHeaders = { + Authorization: `Bearer ${HA_TOKEN}`, + "Content-Type": "application/json", + }; + + for (const s of sensors) { + const url = `${HA_URL}/api/states/${s.entity_id}`; + console.log(`[ha] POST ${url}`); + + const res = await fetch(url, { + method: "POST", + headers: haHeaders, + body: JSON.stringify(s.body), + }); + + if (res.ok) { + console.log(`[ha] Updated ${s.entity_id}`); + } else { + const text = await res.text(); + console.error(`[ha] Failed ${s.entity_id}: HTTP ${res.status} - ${text}`); + + if (res.status === 404) { + console.error(`[ha] Hint: 404 usually means the HA URL is wrong or missing /api/states path.`); + console.error(`[ha] Current HA_URL: ${HA_URL}`); + console.error(`[ha] Full URL attempted: ${url}`); + const checkRes = await fetch(`${HA_URL}/api/`, { headers: haHeaders }).catch(() => null); + if (checkRes) { + const checkText = await checkRes.text().catch(() => ""); + console.error(`[ha] HA /api/ check: HTTP ${checkRes.status} - ${checkText.slice(0, 200)}`); + } + } + } + } +} + +function stateBody(friendlyName, icon, usage, fetchedAt) { + return { + state: usage.percent.toString(), + attributes: { + unit_of_measurement: "%", + state_class: "measurement", + friendly_name: friendlyName, + icon, + resets_in: usage.resetsIn || null, + last_fetched: fetchedAt, + }, + }; +} + +const app = express(); +app.set("json spaces", 2); + +app.get("/api/usage", (_req, res) => { + if (!latestState) { + return res.json({ status: "no_data", message: "No data yet. Wait for first poll." }); + } + res.json(latestState); +}); + +app.get("/api/usage/refresh", async (_req, res) => { + try { + const state = await pollUsage(); + res.json(state); + } catch (err) { + res.status(500).json({ error: String(err) }); + } +}); + +app.get("/api/health", (_req, res) => { + res.json({ + status: "running", + authMode: AUTH_MODE || (OLLAMA_PASSWORD ? "email" : "cookies"), + pollInterval: POLL_MINUTES, + haConfigured: !!(HA_URL && HA_TOKEN), + lastFetch: latestState?.fetchedAt || null, + }); +}); + +app.post("/api/cookies", express.json(), (req, res) => { + const cookies = req.body; + if (!Array.isArray(cookies)) { + return res.status(400).json({ error: "Expected JSON array of cookie objects: [{name, value, ...}]" }); + } + saveCookies(cookies); + console.log(`[auth] Received ${cookies.length} cookies via API`); + res.json({ ok: true, count: cookies.length }); +}); + +async function main() { + const mode = AUTH_MODE || (OLLAMA_PASSWORD ? "email" : "cookies"); + + if (mode === "email" && (!OLLAMA_EMAIL || !OLLAMA_PASSWORD)) { + console.error("ERROR: OLLAMA_EMAIL and OLLAMA_PASSWORD required for email auth."); + console.error("For cookie mode: export cookies from your browser (see README) and POST to /api/cookies."); + process.exit(1); + } + + console.log(`[start] Auth: ${mode} | Poll: ${POLL_MINUTES} min | API: :${PORT} | HA: ${HA_URL ? "configured" : "off"}`); + loadCookies(); + + await pollUsage(); + + setInterval(() => { + pollUsage().catch((err) => console.error("[poll] error:", err.message)); + }, POLL_MINUTES * 60 * 1000); + + app.listen(PORT, () => { + console.log(`[start] API listening on http://0.0.0.0:${PORT}`); + }); +} + +main().catch((err) => { + console.error("[fatal]", err); + process.exit(1); +}); \ No newline at end of file