: asapien/superpulse

commit 6bce14b54811cf3d672b1243c31fad99071ac014
parent 350166f8ba4921a8878e0b5531c7a327e554f8bd
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 29 Oct 2026 22:41:45 +0530

Move device lookup into project-owned edge proxy configuration
14 files changed, 453 insertions(+), 787 deletions(-)
M
AGENTS.md
|
19
+++++++++----------
M
DEV.md
|
10
++++++----
D
composer.json
|
5
-----
D
composer.lock
|
671
-------------------------------------------------------------------------------
A
deploy/README.md
|
114
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
deploy/superpulse-proxy.conf
|
42
++++++++++++++++++++++++++++++++++++++++++
M
dev-server.mjs
|
43
++++++++++++++++++++++++-------------------
M
logs.js
|
15
++++++++++++---
D
logs.php
|
70
----------------------------------------------------------------------
M
out/logs.js
|
6
+++---
M
package.json
|
2
+-
A
tests/device-lookup.test.js
|
54
++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
tests/proxy-config.test.py
|
187
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
tests/scroll.test.mjs
|
2
+-
diff --git a/AGENTS.md b/AGENTS.md
@@ -12,8 +12,9 @@ grouped by day, flags LPG leak alerts with sound and desktop notifications, and
 lets the user click to copy OTP codes.
 
 No framework, no bundler, no build step for the page itself. Plain HTML, CSS,
-vanilla JS, plus one small PHP proxy. Open `index.html` behind a server that
-also exposes `/kidang.fcgi` and `logs.php`.
+vanilla JS. Open `index.html` behind a server that exposes `/kidang.fcgi` and
+the edge-proxied `/api/devices/<tag>` route. Before changing device lookup or
+proxy deployment, read `deploy/README.md` for the secret and authentication contract.
 
 ## File map
 

@@ -22,8 +23,8 @@ also exposes `/kidang.fcgi` and `logs.php`.
 | `index.html` | Page shell: two panels ("Events", "Action Required"), filter bar, device-info popover. Loads `logs.js` **before** `.content` exists in the DOM (see "Load order" below). |
 | `logs.js` | The entire frontend. Polling, parsing, rendering, filtering, alerts, device lookup. |
 | `gt.js` | `parseGT()` — parser for "GT", a JSON-like format the backend may return: single-quoted strings, unquoted bare words, **no commas** between entries. |
-| `logs.php` | Proxy: `GET logs.php?id=<tag>` → Snipe-IT asset API at `equipment.saikrupagas.com/api/v1/hardware/bytag/<tag>` → trimmed JSON `{name, serial, assigned_to, image, category_color, notes}`. |
-| `.env.php` | Defines `$accessToken` (Snipe-IT bearer token). **Live secret. Never commit, log, or echo it.** |
+| `deploy/superpulse-proxy.conf` | Project-owned include for the authenticated `lighttpd-proxy` edge vhost; device lookup routing and token injection. Secrets live outside the document root under `/etc/superpulse/`. |
+| `.env.php` | Legacy untracked secret file; may remain locally or on the server until administrator migration. **Never commit, log, or echo it.** |
 | `logs.css` | Styles specific to this page (message rows, dispatch card, date dividers, popover, panels). |
 | `style.css` | Shared site-wide stylesheet copied from the main saikrupagas.com repo. ~2,500 lines; treat as read-only. Note `body { overflow-x: hidden }` here is why sticky dividers must be top-level `<li>`s (see CONTEXT.md §1). |
 | `CONTEXT.md` | Design notes on `serverMassage`, message templates, date dividers, and the action panel. Authoritative for rendering code. |

@@ -31,7 +32,6 @@ also exposes `/kidang.fcgi` and `logs.php`.
 | `templates.html` | Duplicate of the `#custom-date` `<template>` already inline in `index.html`. Neither is cloned at runtime; kept as a visual reference only. |
 | `Makefile` | **Does not belong to this project.** Copied from the main site repo; references m4 templates, `html/*.html.in`, `privacy.html`, `404.html`, `css/`, `js/` — none exist here. Do not run it. |
 | `assets/` | Icons. Runtime paths in `logs.js` are `/assets/logs/...`, so this folder is deployed under that prefix on the live site. |
-| `vendor/`, `composer.*` | Guzzle 8 for `logs.php`. Vendored; don't edit. |
 
 ## Backend contract
 

@@ -41,12 +41,12 @@ also exposes `/kidang.fcgi` and `logs.php`.
   - Each row: `{ sndr, sentstamp, mid, cid, msg, extra }`
     - `sndr` — sender string
     - `sentstamp` — epoch; seconds, ms, or µs are all accepted by `getDateFromEpoch()`
-    - `mid` — device id (looked up via `logs.php`)
+    - `mid` — device id (looked up via `/api/devices/<mid>`)
     - `cid` — category id, mapped by the hardcoded table in `getCategoryNameFromId()`: 1 sms, 2 econnect, 3 paytm, 4 tampermonkey, 5 printer
     - `msg` — raw message text, or a JSON string with a `type` field
     - `extra` — optional JSON string, e.g. `{"sim": "..."}`
 - **Action feed**: `table=action`. Currently **disabled** (`config.actionTable = null`) because the table doesn't exist on the backend and returned HTTP 500. `fetchActionUpdates()` also self-disables on the first 404/500.
-- **Device lookup**: `GET logs.php?id=<mid>`.
+- **Device lookup**: `GET /api/devices/<mid>` returns raw Snipe-IT asset JSON. `fetchDeviceDetails()` maps its display fields; the edge proxy owns the secret and access policy.
 
 ## Runtime flow (per poll, every 3 s)
 

@@ -65,7 +65,7 @@ also exposes `/kidang.fcgi` and `logs.php`.
 5. `applyFilters()` / `applyActionFilters()` toggle visibility by device, category, and text.
 6. `syncDateDividers()` rebuilds sticky per-day `<li class="date-divider">` rows.
 
-**Device names** resolve lazily: rows first show `Device <mid>`, then `fetchDeviceDetails()` hits `logs.php`, caches in `deviceMapCache` (promise or object), and `updateDeviceReferences()` rewrites every button and dropdown option for that id. Clicking a device button opens the `#device-info-popover`, positioned by `placeDevicePopoverNear()`.
+**Device names** resolve lazily: rows first show `Device <mid>`, then `fetchDeviceDetails()` hits `/api/devices/<mid>`, caches in `deviceMapCache` (promise or object), and `updateDeviceReferences()` rewrites every button and dropdown option for that id. Clicking a device button opens the `#device-info-popover`, positioned by `placeDevicePopoverNear()`.
 
 ## Load order gotcha
 

@@ -104,7 +104,6 @@ Use these names consistently in code and docs:
 ## Known issues and rough edges
 
 - `Notification.requestPermission()` is never called. It lives inside a commented-out line near the bottom of `logs.js`, so desktop alerts only fire if the browser already granted permission.
-- `logs.php` does no validation of `$_GET['id']` and no error handling. A missing device yields PHP warnings mixed into the JSON body. The id is concatenated into the upstream URL path.
 - The iob-debit/credit regexes in `serverMassage()` hardcode the card suffix `CC-xxx2081`.
 - Category id → name mapping is hardcoded; the TODO says it should come from kidang.
 - The "To" range input is hidden (`#range-to`) and always set to "now"; only "From" is user-editable.

@@ -115,4 +114,4 @@ Use these names consistently in code and docs:
 
 Production deploys should go through the CI job defined in `.config/Jobfile` on the `integ` branch. The Jobfile intentionally lives only on `integ`; do not copy it to `main`. Push intended app changes to `main`; the integ CI trigger runs `lint`, `package`, and `deploy`, archives the pushed commit, and deploys to `maa-1:/srv/www/logs.saikrupagas.com` with `rsync --delete` while preserving production-only `.env.php` and `vendor/`.
 
-The live site serves these files alongside `/kidang.fcgi` and expects `assets/` under `/assets/logs/`. `.env.php` must exist on the server but must not be web-readable in plain text; `logs.php` includes it with `require_once`.
+The live site serves these files alongside `/kidang.fcgi` and expects `assets/` under `/assets/logs/`. The new device route requires administrator integration of `deploy/superpulse-proxy.conf` into the edge service before frontend deployment; see `deploy/README.md`. Existing CI does not provision secrets, reload the edge, or remove the legacy preserved `.env.php`/`vendor/` files.
diff --git a/DEV.md b/DEV.md
@@ -16,7 +16,7 @@ The server serves files from this checkout with `Cache-Control: no-store` so rel
 
 ## Remote endpoints
 
-- `/logs.php` is executed on the deployed `maa-1:/srv/www/logs.saikrupagas.com/` checkout through SSH. This avoids needing local PHP, Composer dependencies, or `.env.php` secrets.
+- `/api/devices/<tag>` is forwarded to `DEV_DEVICE_ORIGIN` when configured. Use a local synthetic fixture server or an administrator-provided authorized proxy that serves this path. Without it, device lookup returns 503 and the UI keeps its `Device <id>` fallback. This server does not read production secrets or bypass device-lookup authentication.
 - `/kidang.fcgi` is proxied through `maa-1` directly to the deployed FastCGI socket, bypassing SSO so the browser receives the GT payload instead of the login HTML.
 
 Optional environment variables:

@@ -25,12 +25,14 @@ Optional environment variables:
 PORT=9090 node dev-server.mjs
 HOST=127.0.0.1 node dev-server.mjs
 DEV_REMOTE_HOST=maa-1 node dev-server.mjs
-DEV_REMOTE_VHOST=logs.saikrupagas.com node dev-server.mjs
-DEV_REMOTE_ORIGIN=http://127.0.0.1:81 node dev-server.mjs
+DEV_DEVICE_ORIGIN=http://127.0.0.1:9091 node dev-server.mjs
 ```
 
+For edge-proxy installation and the `/etc/superpulse/` secret contract, see
+[`deploy/README.md`](deploy/README.md). No PHP or Composer is needed locally.
+
 Quick endpoint check:
 
 ```sh
-curl 'http://127.0.0.1:8088/logs.php?id=1'
+curl 'http://127.0.0.1:8088/api/devices/1'
 ```
diff --git a/composer.json b/composer.json
@@ -1,5 +0,0 @@
-{
-    "require": {
-        "guzzlehttp/guzzle": "^8.0"
-    }
-}
diff --git a/composer.lock b/composer.lock
@@ -1,671 +0,0 @@
-{
-    "_readme": [
-        "This file locks the dependencies of your project to a known state",
-        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
-        "This file is @generated automatically"
-    ],
-    "content-hash": "7a0eda22374a9e977ccd013b8485f1fc",
-    "packages": [
-        {
-            "name": "guzzlehttp/guzzle",
-            "version": "8.0.2",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/guzzle/guzzle.git",
-                "reference": "d1cbca76970939a9c2ced55b1e25ea26f34fc773"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/guzzle/zipball/d1cbca76970939a9c2ced55b1e25ea26f34fc773",
-                "reference": "d1cbca76970939a9c2ced55b1e25ea26f34fc773",
-                "shasum": ""
-            },
-            "require": {
-                "ext-json": "*",
-                "guzzlehttp/promises": "^3.0.1",
-                "guzzlehttp/psr7": "^3.0",
-                "php": "^7.4 || ^8.0",
-                "psr/http-client": "^1.0",
-                "psr/http-factory": "^1.0",
-                "symfony/polyfill-php80": "^1.25",
-                "symfony/polyfill-php82": "^1.27"
-            },
-            "provide": {
-                "psr/http-client-implementation": "1.0"
-            },
-            "require-dev": {
-                "bamarni/composer-bin-plugin": "^1.8.2",
-                "ext-curl": "*",
-                "guzzle/client-integration-tests": "4.0.1",
-                "guzzlehttp/test-server": "^1.0",
-                "php-http/message-factory": "^1.1",
-                "phpunit/phpunit": "^9.6.34",
-                "psr/log": "^1.1 || ^2.0 || ^3.0"
-            },
-            "suggest": {
-                "ext-curl": "Required for CURL handler support",
-                "ext-intl": "Required for Internationalized Domain Name (IDN) support",
-                "psr/log": "Required for using the Log middleware"
-            },
-            "type": "library",
-            "extra": {
-                "bamarni-bin": {
-                    "bin-links": true,
-                    "forward-command": false
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "GuzzleHttp\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Graham Campbell",
-                    "email": "hello@gjcampbell.co.uk",
-                    "homepage": "https://github.com/GrahamCampbell"
-                },
-                {
-                    "name": "Michael Dowling",
-                    "email": "mtdowling@gmail.com",
-                    "homepage": "https://github.com/mtdowling"
-                },
-                {
-                    "name": "Jeremy Lindblom",
-                    "email": "jeremeamia@gmail.com",
-                    "homepage": "https://github.com/jeremeamia"
-                },
-                {
-                    "name": "George Mponos",
-                    "email": "gmponos@gmail.com",
-                    "homepage": "https://github.com/gmponos"
-                },
-                {
-                    "name": "Tobias Nyholm",
-                    "email": "tobias.nyholm@gmail.com",
-                    "homepage": "https://github.com/Nyholm"
-                },
-                {
-                    "name": "Márk Sági-Kazár",
-                    "email": "mark.sagikazar@gmail.com",
-                    "homepage": "https://github.com/sagikazarmark"
-                },
-                {
-                    "name": "Tobias Schultze",
-                    "email": "webmaster@tubo-world.de",
-                    "homepage": "https://github.com/Tobion"
-                }
-            ],
-            "description": "Guzzle is a PHP HTTP client library",
-            "keywords": [
-                "client",
-                "curl",
-                "framework",
-                "http",
-                "http client",
-                "psr-18",
-                "psr-7",
-                "rest",
-                "web service"
-            ],
-            "support": {
-                "issues": "https://github.com/guzzle/guzzle/issues",
-                "source": "https://github.com/guzzle/guzzle/tree/8.0.2"
-            },
-            "funding": [
-                {
-                    "url": "https://github.com/GrahamCampbell",
-                    "type": "github"
-                },
-                {
-                    "url": "https://github.com/Nyholm",
-                    "type": "github"
-                },
-                {
-                    "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle",
-                    "type": "tidelift"
-                }
-            ],
-            "time": "2026-08-05T19:50:26+00:00"
-        },
-        {
-            "name": "guzzlehttp/promises",
-            "version": "3.0.1",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/guzzle/promises.git",
-                "reference": "64f38b87fa7d371853804161bfc701c9bc2cc00a"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/promises/zipball/64f38b87fa7d371853804161bfc701c9bc2cc00a",
-                "reference": "64f38b87fa7d371853804161bfc701c9bc2cc00a",
-                "shasum": ""
-            },
-            "require": {
-                "php": "^7.4 || ^8.0"
-            },
-            "require-dev": {
-                "bamarni/composer-bin-plugin": "^1.8.2",
-                "phpunit/phpunit": "^9.6.34"
-            },
-            "type": "library",
-            "extra": {
-                "bamarni-bin": {
-                    "bin-links": true,
-                    "forward-command": false
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "GuzzleHttp\\Promise\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Graham Campbell",
-                    "email": "hello@gjcampbell.co.uk",
-                    "homepage": "https://github.com/GrahamCampbell"
-                },
-                {
-                    "name": "Michael Dowling",
-                    "email": "mtdowling@gmail.com",
-                    "homepage": "https://github.com/mtdowling"
-                },
-                {
-                    "name": "Tobias Nyholm",
-                    "email": "tobias.nyholm@gmail.com",
-                    "homepage": "https://github.com/Nyholm"
-                },
-                {
-                    "name": "Tobias Schultze",
-                    "email": "webmaster@tubo-world.de",
-                    "homepage": "https://github.com/Tobion"
-                }
-            ],
-            "description": "Guzzle promises library",
-            "keywords": [
-                "promise"
-            ],
-            "support": {
-                "issues": "https://github.com/guzzle/promises/issues",
-                "source": "https://github.com/guzzle/promises/tree/3.0.1"
-            },
-            "funding": [
-                {
-                    "url": "https://github.com/GrahamCampbell",
-                    "type": "github"
-                },
-                {
-                    "url": "https://github.com/Nyholm",
-                    "type": "github"
-                },
-                {
-                    "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises",
-                    "type": "tidelift"
-                }
-            ],
-            "time": "2026-08-05T19:35:04+00:00"
-        },
-        {
-            "name": "guzzlehttp/psr7",
-            "version": "3.0.0",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/guzzle/psr7.git",
-                "reference": "b094ded77ee97a6027ad6cf0e8c7b9f88381814c"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/guzzle/psr7/zipball/b094ded77ee97a6027ad6cf0e8c7b9f88381814c",
-                "reference": "b094ded77ee97a6027ad6cf0e8c7b9f88381814c",
-                "shasum": ""
-            },
-            "require": {
-                "php": "^7.4 || ^8.0",
-                "psr/http-factory": "^1.1",
-                "psr/http-message": "^2.0",
-                "symfony/polyfill-php80": "^1.25",
-                "symfony/polyfill-php82": "^1.27"
-            },
-            "provide": {
-                "psr/http-factory-implementation": "1.1",
-                "psr/http-message-implementation": "2.0"
-            },
-            "require-dev": {
-                "bamarni/composer-bin-plugin": "^1.8.2",
-                "http-interop/http-factory-tests": "1.1.0",
-                "jshttp/mime-db": "1.54.0.1",
-                "php-http/psr7-integration-tests": "^1.5.1",
-                "phpunit/phpunit": "^9.6.34"
-            },
-            "suggest": {
-                "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
-            },
-            "type": "library",
-            "extra": {
-                "bamarni-bin": {
-                    "bin-links": true,
-                    "forward-command": false
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "GuzzleHttp\\Psr7\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Graham Campbell",
-                    "email": "hello@gjcampbell.co.uk",
-                    "homepage": "https://github.com/GrahamCampbell"
-                },
-                {
-                    "name": "Michael Dowling",
-                    "email": "mtdowling@gmail.com",
-                    "homepage": "https://github.com/mtdowling"
-                },
-                {
-                    "name": "George Mponos",
-                    "email": "gmponos@gmail.com",
-                    "homepage": "https://github.com/gmponos"
-                },
-                {
-                    "name": "Tobias Nyholm",
-                    "email": "tobias.nyholm@gmail.com",
-                    "homepage": "https://github.com/Nyholm"
-                },
-                {
-                    "name": "Márk Sági-Kazár",
-                    "email": "mark.sagikazar@gmail.com",
-                    "homepage": "https://github.com/sagikazarmark"
-                },
-                {
-                    "name": "Tobias Schultze",
-                    "email": "webmaster@tubo-world.de",
-                    "homepage": "https://github.com/Tobion"
-                },
-                {
-                    "name": "Márk Sági-Kazár",
-                    "email": "mark.sagikazar@gmail.com",
-                    "homepage": "https://sagikazarmark.hu"
-                }
-            ],
-            "description": "PSR-7 message implementation that also provides common utility methods",
-            "keywords": [
-                "http",
-                "message",
-                "psr-7",
-                "request",
-                "response",
-                "stream",
-                "uri",
-                "url"
-            ],
-            "support": {
-                "issues": "https://github.com/guzzle/psr7/issues",
-                "source": "https://github.com/guzzle/psr7/tree/3.0.0"
-            },
-            "funding": [
-                {
-                    "url": "https://github.com/GrahamCampbell",
-                    "type": "github"
-                },
-                {
-                    "url": "https://github.com/Nyholm",
-                    "type": "github"
-                },
-                {
-                    "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7",
-                    "type": "tidelift"
-                }
-            ],
-            "time": "2026-07-20T13:48:31+00:00"
-        },
-        {
-            "name": "psr/http-client",
-            "version": "1.0.3",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/php-fig/http-client.git",
-                "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
-                "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
-                "shasum": ""
-            },
-            "require": {
-                "php": "^7.0 || ^8.0",
-                "psr/http-message": "^1.0 || ^2.0"
-            },
-            "type": "library",
-            "extra": {
-                "branch-alias": {
-                    "dev-master": "1.0.x-dev"
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "Psr\\Http\\Client\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "PHP-FIG",
-                    "homepage": "https://www.php-fig.org/"
-                }
-            ],
-            "description": "Common interface for HTTP clients",
-            "homepage": "https://github.com/php-fig/http-client",
-            "keywords": [
-                "http",
-                "http-client",
-                "psr",
-                "psr-18"
-            ],
-            "support": {
-                "source": "https://github.com/php-fig/http-client"
-            },
-            "time": "2023-09-23T14:17:50+00:00"
-        },
-        {
-            "name": "psr/http-factory",
-            "version": "1.1.0",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/php-fig/http-factory.git",
-                "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
-                "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
-                "shasum": ""
-            },
-            "require": {
-                "php": ">=7.1",
-                "psr/http-message": "^1.0 || ^2.0"
-            },
-            "type": "library",
-            "extra": {
-                "branch-alias": {
-                    "dev-master": "1.0.x-dev"
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "Psr\\Http\\Message\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "PHP-FIG",
-                    "homepage": "https://www.php-fig.org/"
-                }
-            ],
-            "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
-            "keywords": [
-                "factory",
-                "http",
-                "message",
-                "psr",
-                "psr-17",
-                "psr-7",
-                "request",
-                "response"
-            ],
-            "support": {
-                "source": "https://github.com/php-fig/http-factory"
-            },
-            "time": "2024-04-15T12:06:14+00:00"
-        },
-        {
-            "name": "psr/http-message",
-            "version": "2.0",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/php-fig/http-message.git",
-                "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
-                "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
-                "shasum": ""
-            },
-            "require": {
-                "php": "^7.2 || ^8.0"
-            },
-            "type": "library",
-            "extra": {
-                "branch-alias": {
-                    "dev-master": "2.0.x-dev"
-                }
-            },
-            "autoload": {
-                "psr-4": {
-                    "Psr\\Http\\Message\\": "src/"
-                }
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "PHP-FIG",
-                    "homepage": "https://www.php-fig.org/"
-                }
-            ],
-            "description": "Common interface for HTTP messages",
-            "homepage": "https://github.com/php-fig/http-message",
-            "keywords": [
-                "http",
-                "http-message",
-                "psr",
-                "psr-7",
-                "request",
-                "response"
-            ],
-            "support": {
-                "source": "https://github.com/php-fig/http-message/tree/2.0"
-            },
-            "time": "2023-04-04T09:54:51+00:00"
-        },
-        {
-            "name": "symfony/polyfill-php80",
-            "version": "v1.37.0",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/symfony/polyfill-php80.git",
-                "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
-                "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411",
-                "shasum": ""
-            },
-            "require": {
-                "php": ">=7.2"
-            },
-            "type": "library",
-            "extra": {
-                "thanks": {
-                    "url": "https://github.com/symfony/polyfill",
-                    "name": "symfony/polyfill"
-                }
-            },
-            "autoload": {
-                "files": [
-                    "bootstrap.php"
-                ],
-                "psr-4": {
-                    "Symfony\\Polyfill\\Php80\\": ""
-                },
-                "classmap": [
-                    "Resources/stubs"
-                ]
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Ion Bazan",
-                    "email": "ion.bazan@gmail.com"
-                },
-                {
-                    "name": "Nicolas Grekas",
-                    "email": "p@tchwork.com"
-                },
-                {
-                    "name": "Symfony Community",
-                    "homepage": "https://symfony.com/contributors"
-                }
-            ],
-            "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
-            "homepage": "https://symfony.com",
-            "keywords": [
-                "compatibility",
-                "polyfill",
-                "portable",
-                "shim"
-            ],
-            "support": {
-                "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0"
-            },
-            "funding": [
-                {
-                    "url": "https://symfony.com/sponsor",
-                    "type": "custom"
-                },
-                {
-                    "url": "https://github.com/fabpot",
-                    "type": "github"
-                },
-                {
-                    "url": "https://github.com/nicolas-grekas",
-                    "type": "github"
-                },
-                {
-                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
-                    "type": "tidelift"
-                }
-            ],
-            "time": "2026-04-10T16:19:22+00:00"
-        },
-        {
-            "name": "symfony/polyfill-php82",
-            "version": "v1.38.1",
-            "source": {
-                "type": "git",
-                "url": "https://github.com/symfony/polyfill-php82.git",
-                "reference": "002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b"
-            },
-            "dist": {
-                "type": "zip",
-                "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b",
-                "reference": "002dc0cfe5fd4ed6033d48f27d4f19a486c4b04b",
-                "shasum": ""
-            },
-            "require": {
-                "php": ">=7.2"
-            },
-            "type": "library",
-            "extra": {
-                "thanks": {
-                    "url": "https://github.com/symfony/polyfill",
-                    "name": "symfony/polyfill"
-                }
-            },
-            "autoload": {
-                "files": [
-                    "bootstrap.php"
-                ],
-                "psr-4": {
-                    "Symfony\\Polyfill\\Php82\\": ""
-                },
-                "classmap": [
-                    "Resources/stubs"
-                ]
-            },
-            "notification-url": "https://packagist.org/downloads/",
-            "license": [
-                "MIT"
-            ],
-            "authors": [
-                {
-                    "name": "Nicolas Grekas",
-                    "email": "p@tchwork.com"
-                },
-                {
-                    "name": "Symfony Community",
-                    "homepage": "https://symfony.com/contributors"
-                }
-            ],
-            "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions",
-            "homepage": "https://symfony.com",
-            "keywords": [
-                "compatibility",
-                "polyfill",
-                "portable",
-                "shim"
-            ],
-            "support": {
-                "source": "https://github.com/symfony/polyfill-php82/tree/v1.38.1"
-            },
-            "funding": [
-                {
-                    "url": "https://symfony.com/sponsor",
-                    "type": "custom"
-                },
-                {
-                    "url": "https://github.com/fabpot",
-                    "type": "github"
-                },
-                {
-                    "url": "https://github.com/nicolas-grekas",
-                    "type": "github"
-                },
-                {
-                    "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
-                    "type": "tidelift"
-                }
-            ],
-            "time": "2026-05-26T12:45:58+00:00"
-        }
-    ],
-    "packages-dev": [],
-    "aliases": [],
-    "minimum-stability": "stable",
-    "stability-flags": {},
-    "prefer-stable": false,
-    "prefer-lowest": false,
-    "platform": {},
-    "platform-dev": {},
-    "plugin-api-version": "2.9.0"
-}
diff --git a/deploy/README.md b/deploy/README.md
@@ -0,0 +1,114 @@
+# Superpulse edge-proxy integration
+
+`superpulse-proxy.conf` belongs in **lighttpd-proxy**, the TLS termination
+service, not the lighttpd application server on port 81. The application owns
+the route/credential policy; the administrator owns secrets and service wiring.
+No PHP runtime, Composer installation, or additional proxy service is needed.
+
+## Administrator integration
+
+1. Provision `/etc/superpulse/snipeit.conf` **outside every document root**:
+
+   ```lighttpd
+   var.superpulse.snipeit-token = "REPLACE_WITH_A_READ_ONLY_SNIPE_IT_TOKEN"
+   ```
+
+   Use a least-privilege account with only the asset-read permissions required.
+   Keep the file accessible only to root and, if needed, the proxy service
+   account (for example, directory mode 0750 and file mode 0640 with the
+   appropriate service group). Provision it through the administrator's secret
+   workflow; never put the value in Git, command-line arguments, frontend build
+   variables, or public configuration dumps. A missing include/variable fails
+   configuration validation. An invalid token fails at Snipe-IT.
+
+2. Inside the **existing authenticated** `logs.saikrupagas.com` edge vhost,
+   after its normal proxy and authentication configuration, add:
+
+   ```lighttpd
+   include "/srv/www/logs.saikrupagas.com/deploy/superpulse-proxy.conf"
+   ```
+
+   Use the actual absolute project path if different. This is an explicit
+   include, not automatic `.htaccess` discovery. Restrict the vhost to the
+   intended hostname. Required modules: `mod_access`, `mod_setenv`, `mod_proxy`,
+   plus the existing authentication modules. Load FastCGI authentication before
+   `mod_proxy`, as in the current edge configuration.
+
+3. Preserve the dashboard's session-based authentication/authorization on
+   `/api/devices/…`. **The include is not an authentication provider.**
+   `enable-authelia-authorizer.conf` currently configures forwarding safeguards;
+   it is not, by itself, the FastCGI authorizer. On the current deployment,
+   include `var.macrodir + "include-authelia-fcgi-authz.conf"` in the logs vhost
+   to install the `/` authorizer as well as `/auth/user`. A responder mapping
+   for `/auth/user` alone does not protect device requests. Missing or expired
+   sessions must be denied before any request reaches Snipe-IT.
+
+   `mod_setenv` replaces Authorization during URI processing, before FastCGI
+   authorization. The authorizer must authenticate the browser session cookie,
+   not treat the injected Snipe-IT token as user authentication. It is a trusted
+   local component and may see that header. Browser cookies also travel to the
+   trusted equipment backend; this minimal configuration is not suitable for
+   an untrusted third-party upstream.
+
+4. Confirm `127.0.0.1:81` reaches Snipe-IT when the HTTP Host is
+   `equipment.saikrupagas.com`. The include changes the upstream Host and URL
+   path; it does not use the equipment site's public HTTPS endpoint. If the
+   edge runs elsewhere, adapt the upstream to an administrator-provided secure
+   transport. Never carry the token over public plaintext HTTP. Keep port 81
+   restricted to the intended proxy; enforce equivalent private-file denies
+   there if anything can access it directly.
+
+5. Validate the complete edge configuration, for example:
+
+   ```sh
+   lighttpd -tt -f /etc/lighttpd/lighttpd-proxy.conf
+   ```
+
+   Stage the include on the edge independently (at the path used by its
+   `include` directive), and integrate/reload it **before deploying the new
+   frontend**. Pushing to main triggers application deployment, so do not push
+   this migration before the administrator has prepared the edge. Keep the
+   existing `logs.php` application release until the new route is ready. After
+   frontend rollout, retire the old PHP route/pool as appropriate and securely
+   remove the old document-root `.env.php`. Existing CI deliberately preserves
+   `.env.php` and `vendor/`; source deletion does not remove those server files.
+   Do not remove a PHP pool used by other applications. Application deployments
+   do not automatically reload the edge proxy: validate/reload it explicitly
+   whenever this include changes. On the deployed OpenRC service,
+   `rc-service lighttpd-proxy reload` only reopens log files; apply configuration
+   with `rc-service lighttpd-proxy graceful` after successful validation.
+
+## Endpoint and exposure
+
+- Browser: `GET /api/devices/<tag>` (one tag starting with a letter, digit,
+  underscore or hyphen, followed by letters, digits, underscores, dots or
+  hyphens). Only GET without query parameters is permitted.
+- Upstream: `GET /api/v1/hardware/bytag/<tag>` on the equipment vhost, with the
+  server's bearer token replacing any browser-supplied Authorization value.
+- Other application paths retain their existing routing and headers.
+- Responses are `Cache-Control: no-store`; upstream Set-Cookie is suppressed.
+  `/deploy/`, `/.env.php` and the retired `/logs.php` route are denied.
+- The **full upstream asset JSON** is returned to authenticated callers, not
+  the former PHP field allowlist. The frontend maps display name (falling back
+  to model name), serial, assignee, image, category color, and notes. Display
+  mapping is not data filtering: confirm the account's asset responses are
+  appropriate for every authorized dashboard user. If field-level restriction
+  is required, retain an adapter instead of a plain proxy.
+
+## Verification
+
+```sh
+python3 tests/proxy-config.test.py
+node tests/device-lookup.test.js
+```
+
+The proxy test runs a real local lighttpd against synthetic HTTP and FastCGI
+services and a dummy token. It checks authorization-before-upstream, token
+replacement, fixed host/path mapping, invalid methods/queries/tags, private
+paths, no-store, cookie suppression, vhost isolation, and missing-secret failure.
+It never contacts production. Set `LIGHTTPD` and optionally `LIGHTTPD_MODULES`
+when the binary/modules are not on the standard path.
+
+Before enabling production, verify a signed-in device lookup, anonymous and
+expired-session denial, invalid-tag/method rejection, and unchanged event-feed
+behavior. These synthetic tests do not verify the deployed Authelia policy.
diff --git a/deploy/superpulse-proxy.conf b/deploy/superpulse-proxy.conf
@@ -0,0 +1,42 @@
+# Include INSIDE the authenticated logs.saikrupagas.com vhost in lighttpd-proxy,
+# after its existing routing/authentication configuration. See deploy/README.md.
+# Requires mod_access, mod_setenv and mod_proxy (after the auth modules).
+# The private include defines var.superpulse.snipeit-token. Missing file/variable
+# is a startup error, not an anonymous upstream request.
+include "/etc/superpulse/snipeit.conf"
+
+# Protect project configuration and the retired PHP endpoint/secret file.
+$HTTP["url"] =~ "^/(?:deploy(?:/|$)|[.]env[.]php(?:/|$)|logs[.]php(?:/|$))" {
+    url.access-deny = ( "" )
+}
+
+$HTTP["url"] =~ "^/api/devices(?:/|$)" {
+    # One device tag, GET only, no upstream query parameters or traversal.
+    $HTTP["url"] !~ "^/api/devices/[A-Za-z0-9_-][A-Za-z0-9_.-]*$" {
+        url.access-deny = ( "" )
+    }
+    $HTTP["request-method"] != "GET" {
+        url.access-deny = ( "" )
+    }
+    $HTTP["querystring"] != "" {
+        url.access-deny = ( "" )
+    }
+
+    $HTTP["url"] =~ "^/api/devices/[A-Za-z0-9_-][A-Za-z0-9_.-]*$" {
+        # HTTP stays on loopback. Select Snipe-IT's vhost on the port-81 backend,
+        # not the Superpulse vhost (which would loop back into this route).
+        proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => 81 )) )
+        proxy.header = (
+            "map-host-request" => ( "-" => "equipment.saikrupagas.com" ),
+            "map-urlpath" => ( "/api/devices/" => "/api/v1/hardware/bytag/" )
+        )
+        setenv.set-request-header += (
+            "Authorization" => "Bearer " + var.superpulse.snipeit-token,
+            "Accept" => "application/json"
+        )
+        setenv.set-response-header += (
+            "Cache-Control" => "no-store",
+            "Set-Cookie" => ""
+        )
+    }
+}
diff --git a/dev-server.mjs b/dev-server.mjs
@@ -10,8 +10,7 @@ const root = process.cwd();
 const port = Number(process.env.PORT || 8088);
 const host = process.env.HOST || '127.0.0.1';
 const remoteHost = process.env.DEV_REMOTE_HOST || 'maa-1';
-const remoteVhost = process.env.DEV_REMOTE_VHOST || 'logs.saikrupagas.com';
-const remoteOrigin = process.env.DEV_REMOTE_ORIGIN || 'http://127.0.0.1:81';
+const deviceOrigin = process.env.DEV_DEVICE_ORIGIN;
 
 const contentTypes = {
   '.html': 'text/html; charset=utf-8',

@@ -42,23 +41,20 @@ function shellQuote(value) {
   return `'${String(value).replace(/'/g, `'\\''`)}'`;
 }
 
-async function proxyRemotePhp(req, res, query) {
+async function proxyDevice(res, pathname) {
+  const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
+  if (!deviceOrigin) {
+    send(res, 503, JSON.stringify({ error: 'Set DEV_DEVICE_ORIGIN to a local device API fixture or authorized proxy' }), headers);
+    return;
+  }
   try {
-    const phpCode = `parse_str(${JSON.stringify(query)}, $_GET); chdir('/srv/www/logs.saikrupagas.com'); include 'logs.php';`;
-    const remoteCommand = ['php', '-d', 'display_errors=0', '-r', shellQuote(phpCode)].join(' ');
-    const { stdout, stderr } = await execFileAsync('ssh', [remoteHost, remoteCommand], { maxBuffer: 10 * 1024 * 1024 });
-
-    if (stderr) console.warn(`[dev-server] remote php stderr: ${stderr.trim()}`);
-    send(res, 200, stdout, {
-      'Content-Type': 'application/json; charset=utf-8',
-      'Cache-Control': 'no-store'
+    const response = await fetch(new URL(pathname, deviceOrigin), {
+      redirect: 'manual', signal: AbortSignal.timeout(5000)
     });
+    send(res, response.status, Buffer.from(await response.arrayBuffer()), headers);
   } catch (error) {
-    console.error('[dev-server] remote PHP failed:', error.message);
-    send(res, 502, JSON.stringify({ error: 'Remote PHP failed', detail: error.message }), {
-      'Content-Type': 'application/json; charset=utf-8',
-      'Cache-Control': 'no-store'
-    });
+    console.warn('[dev-server] device lookup failed:', error.message);
+    send(res, 502, JSON.stringify({ error: 'Device lookup failed' }), headers);
   }
 }
 

@@ -154,8 +150,17 @@ async function proxyRemoteKidang(res, query) {
 createServer(async (req, res) => {
   const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
 
-  if (url.pathname === '/logs.php') {
-    await proxyRemotePhp(req, res, url.searchParams.toString());
+  if (url.pathname === '/api/devices' || url.pathname.startsWith('/api/devices/')) {
+    if (req.method !== 'GET' || url.search || !/^\/api\/devices\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/.test(url.pathname)) {
+      send(res, 403, 'Forbidden\n');
+      return;
+    }
+    await proxyDevice(res, url.pathname);
+    return;
+  }
+
+  if (url.pathname === '/logs.php' || url.pathname.startsWith('/deploy/') || url.pathname.startsWith('/.')) {
+    send(res, 403, 'Forbidden\n');
     return;
   }
 

@@ -176,5 +181,5 @@ createServer(async (req, res) => {
   }
 }).listen(port, host, () => {
   console.log(`Local dev server: http://${host}:${port}`);
-  console.log(`Proxying /logs.php and /kidang.fcgi through ${remoteHost} (${remoteVhost})`);
+  console.log(`Device API: ${deviceOrigin || 'disabled (set DEV_DEVICE_ORIGIN)'}; kidang via ${remoteHost}`);
 });
diff --git a/logs.js b/logs.js
@@ -1257,11 +1257,12 @@ let deviceMapCache = {};
 function fetchDeviceDetails(id) {
   if (!id) return Promise.resolve(null);
   const key = String(id);
+  if (!/^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/.test(key)) return Promise.resolve(null);
   const cached = deviceMapCache[key];
   if (cached && typeof cached.then === "function") return cached;
   if (cached && typeof cached === "object") return Promise.resolve(cached);
 
-  const promise = fetch("/logs.php?id=" + encodeURIComponent(key))
+  const promise = fetch("/api/devices/" + encodeURIComponent(key))
     .then(async (r) => {
       let device = null;
       try {

@@ -1273,8 +1274,16 @@ function fetchDeviceDetails(id) {
         throw new Error(
           device && device.error ? device.error : `Device lookup failed: ${r.status}`,
         );
-      if (!device || !device.name) throw new Error("Device lookup response missing name");
-      return device;
+      const name = device && (device.name || (device.model && device.model.name));
+      if (!name) throw new Error("Device lookup response missing name");
+      return {
+        name,
+        serial: device.serial,
+        assigned_to: device.assigned_to && device.assigned_to.name,
+        image: device.image,
+        category_color: device.category && device.category.tag_color,
+        notes: device.notes,
+      };
     })
     .then((device) => {
       deviceMapCache[key] = device;
diff --git a/logs.php b/logs.php
@@ -1,70 +0,0 @@
-<?php
-require_once(__DIR__ . '/.env.php');
-require_once(__DIR__ . '/vendor/autoload.php');
-
-header('Content-Type: application/json; charset=utf-8');
-
-function respond_json($payload, $status = 200) {
-    http_response_code($status);
-    echo json_encode($payload);
-    exit;
-}
-
-function value_or_null($value, $path) {
-    foreach ($path as $key) {
-        if (is_object($value) && isset($value->{$key})) {
-            $value = $value->{$key};
-        } else {
-            return null;
-        }
-    }
-    return $value;
-}
-
-$id = isset($_GET['id']) ? trim((string) $_GET['id']) : '';
-if ($id === '' || !preg_match('/^[A-Za-z0-9_.-]+$/', $id)) {
-    respond_json(['error' => 'Invalid device id'], 400);
-}
-
-$client = new \GuzzleHttp\Client([
-    'timeout' => 5,
-    'connect_timeout' => 3,
-    'headers' => [
-        'Authorization' => 'Bearer '.$accessToken,
-        'Content-Type' => 'application/json',
-        'Accept' => 'application/json',
-        'User-Agent' => 'Integration Script'
-    ]
-]);
-
-try {
-    $url = 'https://equipment.saikrupagas.com/api/v1/hardware/bytag/'.rawurlencode($id);
-    $response = $client->request('GET', $url);
-    $obj = json_decode((string) $response->getBody());
-
-    if (!$obj || !is_object($obj)) {
-        respond_json(['error' => 'Invalid device lookup response'], 502);
-    }
-
-    $device = new stdClass();
-    // Prefer the asset's own display name, then the model name, then leave null
-    // so the frontend keeps its "Device <id>" fallback.
-    $device->name = value_or_null($obj, ['name']) ?: value_or_null($obj, ['model', 'name']);
-    $device->serial = value_or_null($obj, ['serial']);
-    $device->assigned_to = value_or_null($obj, ['assigned_to', 'name']);
-    $device->image = value_or_null($obj, ['image']);
-    $device->category_color = value_or_null($obj, ['category', 'tag_color']);
-    $device->notes = value_or_null($obj, ['notes']);
-
-    if (!$device->name) {
-        respond_json(['error' => 'Device name not found'], 404);
-    }
-
-    echo json_encode($device);
-} catch (\GuzzleHttp\Exception\ClientException $e) {
-    respond_json(['error' => 'Device not found'], $e->getResponse() ? $e->getResponse()->getStatusCode() : 404);
-} catch (Throwable $e) {
-    error_log('Device lookup failed for asset tag '.$id.': '.$e->getMessage());
-    respond_json(['error' => 'Device lookup failed'], 502);
-}
-?>
diff --git a/out/logs.js b/out/logs.js
@@ -1,5 +1,5 @@
 (()=>{window.parseGT=function(t){let n=0,a=t.length;function r(){for(;n<a&&/\s/.test(t[n]);)n++}function s(o){let y=Math.max(0,n-10),b=Math.min(a,n+10),k=t.slice(y,b);throw new Error(`${o} at position ${n}. Context: "...${k}..."`)}function i(){r();let o=t[n];return o==="{"?l():o==="["?d():o==="'"?c():/[0-9-]/.test(o)?h():m()}function l(){t[n]!=="{"&&s("Expected '{'"),n++;let o={};for(r();n<a&&t[n]!=="}";){let y=w();r();let b=i();if(o[y]=b,r(),t[n]==="}")break}return t[n]!=="}"&&s("Expected '}' to close object"),n++,o}function d(){t[n]!=="["&&s("Expected '['"),n++;let o=[];for(r();n<a&&t[n]!=="]";){let y=i();if(o.push(y),r(),t[n]==="]")break}return t[n]!=="]"&&s("Expected ']' to close array"),n++,o}function c(){t[n]!=="'"&&s("Expected single quote"),n++;let o="";for(;n<a&&t[n]!=="'";){if(t[n]==="\\")switch(n++,n>=a&&s("Unterminated escape sequence"),t[n]){case"'":o+="'";break;case"\\":o+="\\";break;case"/":o+="/";break;case"b":o+="\b";break;case"f":o+="\f";break;case"n":o+=`
-`;break;case"r":o+="\r";break;case"t":o+="	";break;default:o+=t[n];break}else o+=t[n];n++}return t[n]!=="'"&&s("Unterminated string"),n++,o}function w(){return r(),t[n]==="'"?c():m()}function m(){let o="";for(;n<a&&!/[\]}\s]/.test(t[n]);)o+=t[n],n++;return o}function h(){let o=n;for(t[n]==="-"&&n++;n<a&&/[0-9]/.test(t[n]);)n++;if(t[n]===".")for(n++;n<a&&/[0-9]/.test(t[n]);)n++;if(/[eE]/.test(t[n]))for(n++,/[+-]/.test(t[n])&&n++;n<a&&/[0-9]/.test(t[n]);)n++;let y=t.slice(o,n);return/^-?\d+\.?\d*([eE][+-]?\d+)?$/.test(y)?parseFloat(y):(n=o,m())}try{r();let o=i();return r(),n<a&&s("Unexpected characters at end of input"),o}catch(o){throw new Error(`Failed to parse input: ${o.message}`)}};var ue={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},A={endpoint:"/kidang.fcgi",otpTable:"otp",actionTable:null,defaultRangeHours:48,displayTimestampsAsLocalWallClock:!1},F=new Set,q=new Set,G={theme:"auto",ambientGlow:!0},g=me();function me(){try{return{...G,...JSON.parse(localStorage.getItem("logs_settings"))||{}}}catch{return{...G}}}function fe(){localStorage.setItem("logs_settings",JSON.stringify(g))}var z={title:"OPERATIONS",blinkMs:1100,aliases:{bookingAgeDays:"refillSpreadDays",bookingSpreadDays:"refillSpreadDays",bpclDeposit:"bpclDepositLakhs"},ambientGlow:{enabled:g.ambientGlow!==!1,alpha:.14,radius:74,blur:42},warningLevels:[{key:"amber",label:"AMBER ALERT",priority:1,showAxis:!0,dominance:.6,axisAlpha:.52,axisWidth:1.45,axisTheme:{light:{alpha:.8,width:2.2}},axisDash:[3,5],glowAlpha:.12},{key:"red",label:"CRITICAL",priority:2,showAxis:!0,dominance:.7,axisAlpha:.42,axisWidth:1.45,axisDash:[6,6],glowAlpha:.16},{key:"double-red",label:"DOUBLE RED",priority:3,showAxis:!1,dominance:.7,borderBlink:!0,glowAlpha:.18,glowRadius:88,glowBlur:54}],colors:{amber:"#ffcc00",red:"#ff0055",critical:"#ff0055","double-red":"#ff1a1a",doubleRed:"#ff1a1a",disabled:"#777777"},staleAlpha:.35,charts:[{key:"operations",label:"OPERATIONS",parameters:["complaintsOpen","invoiceActions","deliveryPersonLeave","refillSpreadDays","pendencyDays","bpclDepositLakhs"]},{key:"compliance",label:"COMPLIANCE",parameters:["safetyClinicDone"]},{key:"excellence",label:"EXCELLENCE",parameters:["tenKgSales","fiveKgSales"]}],parameters:[{key:"complaintsOpen",label:"Complaints Open",icon:"warning",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:52.5,redUpper:75,amberLower:-52.5,redLower:-75}},{key:"invoiceActions",label:"Invoice Actions",icon:"invoice",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:59.5,redUpper:85,amberLower:-59.5,redLower:-85}},{key:"deliveryPersonLeave",label:"Delivery Person Leave",icon:"person",scale:"count10",refreshMinutes:720,thresholds:{amberUpper:49,redUpper:70,amberLower:-49,redLower:-70}},{key:"refillSpreadDays",label:"Refill Spread",icon:"calendar",scale:"daysCritical",scaleBase:10,scaleMax:165,refreshMinutes:1440,display:{suffix:"d"},thresholds:{amberUpper:50,redUpper:100,doubleRedUpper:150,amberLower:-70,redLower:-100},areaScanView:"refillSpreadAreaScan",areaKey:"refillSpreadAreas",areaScanTitle:"REFILL SPREAD AREA SCAN",areaScanLevels:[{level:"amber",above:5},{level:"red",above:10}]},{key:"pendencyDays",label:"Pendency",icon:"hourglass",scale:"pendency",scaleIdeal:1,scaleBase:3,scaleMax:115,refreshMinutes:720,display:{suffix:"d",decimals:1},thresholds:{amberUpper:33.33,redUpper:100,amberLower:-70,redLower:-100},areaScanView:"pendencyAreaScan",areaKey:"pendencyAreas",areaScanTitle:"PENDENCY AREA SCAN",areaScanLevels:[{level:"amber",above:1},{level:"red",above:3}]},{key:"bpclDepositLakhs",label:"BPCL Deposit",icon:"deposit",scale:"raw",refreshMinutes:30,display:{prefix:"\u20B9",suffix:"L",decimals:1},thresholds:{amberUpper:4,redUpper:6,amberLower:-1,redLower:-3}},{key:"safetyClinicDone",label:"Safety Clinic",icon:"calendar",scale:"raw",refreshMinutes:43200,display:{suffix:"/1"},thresholds:{amberLower:.75,redLower:.25}},{key:"tenKgSales",label:"10kg Sales",icon:"deposit",scale:"raw",refreshMinutes:43200,thresholds:{amberLower:10,redLower:5}},{key:"fiveKgSales",label:"5kg Sales",icon:"deposit",scale:"raw",refreshMinutes:43200,thresholds:{amberLower:10,redLower:5}}],extraAxes:[{label:"BPCL Deposit Good",parameterKey:"bpclDepositLakhs",value:6,color:"rgba(0,255,120,.5)",width:1.8,dash:[4,4]},{label:"BPCL Deposit Soft",parameterKey:"bpclDepositLakhs",value:4,color:"rgba(120,255,160,.34)",width:1.4,dash:[2,5]}]},f=null,S=null,_=!1,ge=null,C={complaintsOpen:0,invoiceActions:2,deliveryPersonLeave:0,refillSpreadDays:be(-1,25),amberRefillSpreadDays:5,criticalRefillSpreadDays:10,doubleRedRefillSpreadDays:15,bpclDepositLakhs:3,safetyClinicDone:0,tenKgSales:0,fiveKgSales:0,pendencyDays:2.7,idealPendencyMaxDays:1,criticalPendencyDays:3,refillSpreadAreas:[{name:"KK NAGAR",days:12},{name:"WEST MAMBALAM",days:9},{name:"ASHOK NAGAR",days:7},{name:"T NAGAR",days:11},{name:"VADAPALANI",days:6},{name:"KODAMBAKKAM",days:8},{name:"SALIGRAMAM",days:5},{name:"VIRUGAMBAKKAM",days:10},{name:"NESAPAKKAM",days:13},{name:"JAFFERKHANPET",days:6},{name:"EKKATTUTHANGAL",days:4},{name:"MGR NAGAR",days:9},{name:"SAIDAPET",days:7}],pendencyAreas:[{name:"KK NAGAR",days:3.4},{name:"WEST MAMBALAM",days:2.9},{name:"ASHOK NAGAR",days:2.6},{name:"T NAGAR",days:3.1},{name:"VADAPALANI",days:2.2},{name:"KODAMBAKKAM",days:2.8},{name:"SALIGRAMAM",days:1.9},{name:"VIRUGAMBAKKAM",days:2.4},{name:"NESAPAKKAM",days:3},{name:"JAFFERKHANPET",days:2.1},{name:"EKKATTUTHANGAL",days:1.7},{name:"MGR NAGAR",days:2.5},{name:"SAIDAPET",days:2}]};function he(e=new Date){let t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=a=>Number(t.find(r=>r.type===a).value);return{year:n("year"),month:n("month"),day:n("day")}}function ye(e,t,n){return Date.UTC(e,t-1,n,-5,-30,0,0)}function be(e,t){let n=he(),a=new Date(Date.UTC(n.year,n.month-1+e,1)),r=a.getUTCFullYear(),s=a.getUTCMonth()+1,i=ye(r,s,t),l=Date.now();return Math.max(0,Math.floor((l-i)/(1440*60*1e3)))}function Z(e){let t=Number(e);return Number.isFinite(t)?t:null}function p(e,t,n){if(!Object.prototype.hasOwnProperty.call(n,e))return;let a=Z(n[e]);a!==null&&(C[t]=a)}function Y(e){return(Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([n,a])=>({name:n,days:a})):[]).map((n,a)=>{let r=String(n.name||n.area||n.areaName||`Area ${a+1}`).trim(),s=Z(n.days??n.pendencyDays??n.currentDays);return r&&s!==null?{name:r,days:s}:null}).filter(Boolean)}function we(e){if(!Object.prototype.hasOwnProperty.call(e,"pendencyAreas"))return;let t=Y(e.pendencyAreas);t.length&&(C.pendencyAreas=t)}function Ae(e){if(!Object.prototype.hasOwnProperty.call(e,"refillSpreadAreas"))return;let t=Y(e.refillSpreadAreas);t.length&&(C.refillSpreadAreas=t)}function Q(e){return!e||String(e.type||"").toLowerCase()!=="tva-metrics"?!1:(S={...S||{},...e},delete S.type,p("complaintsOpen","complaintsOpen",e),p("invoiceActions","invoiceActions",e),p("deliveryPersonLeave","deliveryPersonLeave",e),p("refillSpreadDays","refillSpreadDays",e),p("bookingAgeDays","refillSpreadDays",e),p("bookingSpreadDays","refillSpreadDays",e),p("amberRefillSpreadDays","amberRefillSpreadDays",e),p("criticalRefillSpreadDays","criticalRefillSpreadDays",e),p("doubleRedRefillSpreadDays","doubleRedRefillSpreadDays",e),p("bpclDepositLakhs","bpclDepositLakhs",e),p("bpclDeposit","bpclDepositLakhs",e),p("safetyClinicDone","safetyClinicDone",e),p("tenKgSales","tenKgSales",e),p("fiveKgSales","fiveKgSales",e),p("pendencyDays","pendencyDays",e),p("idealPendencyMaxDays","idealPendencyMaxDays",e),p("criticalPendencyDays","criticalPendencyDays",e),we(e),Ae(e),!0)}function X(e){[...e].sort((t,n)=>t.sentstamp-n.sentstamp).forEach(t=>{let n=L(t.msg,t.extra),a=P(t.sentstamp)?.getTime();a&&(n.updatedAt=Object.fromEntries(Object.keys(n).map(r=>[r,a]))),Q(n)})}function ee(e){return String(L(e.msg,e.extra).type||"").toLowerCase()==="tva-metrics"}window.setTvaControlData=function(e){typeof e=="string"&&(e=JSON.parse(e)),Q({type:"tva-metrics",...e||{}}),N()};window.getTvaControlData=function(){return f?f.getData():JSON.parse(JSON.stringify(C))};function T(){let e=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,t=g.theme==="dark"||g.theme==="auto"&&e,n=g.theme==="light"||g.theme==="auto"&&!e;document.body.classList.toggle("logs-dark",t),document.body.classList.toggle("logs-light",n),document.querySelectorAll(".action-chart-container, .tva-control-container").forEach(a=>{g.theme==="auto"?a.removeAttribute("data-tva-theme"):a.dataset.tvaTheme=g.theme}),z.ambientGlow.enabled=g.ambientGlow!==!1,f&&typeof f.refreshTheme=="function"&&f.refreshTheme()}function te(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");!e||!t||(e.value=g.theme,t.checked=g.ambientGlow!==!1)}window.openLogsSettings=function(){te();let e=document.getElementById("logs-settings-dialog");e&&e.showModal()};window.closeLogsSettings=function(){let e=document.getElementById("logs-settings-dialog");e&&e.close()};window.saveLogsSettings=function(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");g={theme:e?e.value:"auto",ambientGlow:t?t.checked:!0},fe(),T(),closeLogsSettings()};function ve(){let e=document.querySelector(".app-chart-header");if(!e||e.dataset.scrollBound)return;e.dataset.scrollBound="1";let t=document.querySelector(".segment-container"),n=document.querySelector(".mobile-panel-switch"),a=e.querySelector(".app-header-chart"),r=e.querySelector(".chat-launcher"),s=document.querySelectorAll(".log-filter-bar"),i=0,l=0,d=()=>{let m=f.getDisplayMode();if(m==="pulseGraphMax")return;m!=="pulseBar"&&(e.style.minHeight="");let o=t.getBoundingClientRect().top-l<=i;m==="pulseGraph"&&o?(e.style.minHeight=`${e.getBoundingClientRect().height}px`,f.setDisplayMode("pulseBar")):e.style.minHeight&&!o&&(e.style.minHeight="",f.setDisplayMode("pulseGraph"))},c=()=>{let m=getComputedStyle(a),h=getComputedStyle(e),o=r?getComputedStyle(r):null;i=(r?r.getBoundingClientRect().height+parseFloat(o.marginTop)+parseFloat(o.marginBottom):0)+parseFloat(m.getPropertyValue("--tva-pulse-bar-height"))+parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth)+parseFloat(h.paddingTop)+parseFloat(h.paddingBottom);let b=n.getBoundingClientRect().height;l=b?b+parseFloat(getComputedStyle(n).marginBottom):0;let k=document.documentElement.style;k.setProperty("--superpulse-sticky-offset",`${Math.ceil(i)}px`),k.setProperty("--panel-switch-height",`${Math.ceil(b)}px`),s.forEach(U=>U.parentElement.style.setProperty("--filter-height",`${Math.ceil(U.getBoundingClientRect().height)}px`)),d()};window.addEventListener("scroll",d,{passive:!0}),window.addEventListener("resize",c);let w=new ResizeObserver(c);[e,a,n,r,...s].filter(Boolean).forEach(m=>w.observe(m)),c()}function ne(){let e=document.getElementById("tvaReactiveChart");!e||f||typeof Chart>"u"||typeof createTvaControl!="function"||(T(),f=createTvaControl({canvas:e,config:z,data:C}),ve())}function N(){f||ne(),f&&S&&(f.update(S),S=null)}function ae(){try{let e=sessionStorage.getItem("seen_lpg_leaks");return e?JSON.parse(e):[]}catch{return[]}}function Se(e){try{let t=ae();t.includes(e)||(t.push(e),sessionStorage.setItem("seen_lpg_leaks",JSON.stringify(t)))}catch(t){console.error(t)}}function De(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;let t=new e;[0,.25].forEach(n=>{let a=t.createOscillator(),r=t.createGain();a.type="sine",a.frequency.setValueAtTime(880,t.currentTime+n),r.gain.setValueAtTime(.3,t.currentTime+n),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+n+.2),a.connect(r),r.connect(t.destination),a.start(t.currentTime+n),a.stop(t.currentTime+n+.2)})}catch{console.warn("Audio Context blocked. Click anywhere on the webpage once to enable sound alerts.")}}function Ce(e,t,n){"Notification"in window&&Notification.permission==="granted"&&new Notification("CRITICAL ALERT: LPG Leakage",{body:`From: ${e} (${n})
+`;break;case"r":o+="\r";break;case"t":o+="	";break;default:o+=t[n];break}else o+=t[n];n++}return t[n]!=="'"&&s("Unterminated string"),n++,o}function w(){return r(),t[n]==="'"?c():m()}function m(){let o="";for(;n<a&&!/[\]}\s]/.test(t[n]);)o+=t[n],n++;return o}function h(){let o=n;for(t[n]==="-"&&n++;n<a&&/[0-9]/.test(t[n]);)n++;if(t[n]===".")for(n++;n<a&&/[0-9]/.test(t[n]);)n++;if(/[eE]/.test(t[n]))for(n++,/[+-]/.test(t[n])&&n++;n<a&&/[0-9]/.test(t[n]);)n++;let y=t.slice(o,n);return/^-?\d+\.?\d*([eE][+-]?\d+)?$/.test(y)?parseFloat(y):(n=o,m())}try{r();let o=i();return r(),n<a&&s("Unexpected characters at end of input"),o}catch(o){throw new Error(`Failed to parse input: ${o.message}`)}};var ue={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},A={endpoint:"/kidang.fcgi",otpTable:"otp",actionTable:null,defaultRangeHours:48,displayTimestampsAsLocalWallClock:!1},F=new Set,_=new Set,q={theme:"auto",ambientGlow:!0},g=me();function me(){try{return{...q,...JSON.parse(localStorage.getItem("logs_settings"))||{}}}catch{return{...q}}}function fe(){localStorage.setItem("logs_settings",JSON.stringify(g))}var W={title:"OPERATIONS",blinkMs:1100,aliases:{bookingAgeDays:"refillSpreadDays",bookingSpreadDays:"refillSpreadDays",bpclDeposit:"bpclDepositLakhs"},ambientGlow:{enabled:g.ambientGlow!==!1,alpha:.14,radius:74,blur:42},warningLevels:[{key:"amber",label:"AMBER ALERT",priority:1,showAxis:!0,dominance:.6,axisAlpha:.52,axisWidth:1.45,axisTheme:{light:{alpha:.8,width:2.2}},axisDash:[3,5],glowAlpha:.12},{key:"red",label:"CRITICAL",priority:2,showAxis:!0,dominance:.7,axisAlpha:.42,axisWidth:1.45,axisDash:[6,6],glowAlpha:.16},{key:"double-red",label:"DOUBLE RED",priority:3,showAxis:!1,dominance:.7,borderBlink:!0,glowAlpha:.18,glowRadius:88,glowBlur:54}],colors:{amber:"#ffcc00",red:"#ff0055",critical:"#ff0055","double-red":"#ff1a1a",doubleRed:"#ff1a1a",disabled:"#777777"},staleAlpha:.35,charts:[{key:"operations",label:"OPERATIONS",parameters:["complaintsOpen","invoiceActions","deliveryPersonLeave","refillSpreadDays","pendencyDays","bpclDepositLakhs"]},{key:"compliance",label:"COMPLIANCE",parameters:["safetyClinicDone"]},{key:"excellence",label:"EXCELLENCE",parameters:["tenKgSales","fiveKgSales"]}],parameters:[{key:"complaintsOpen",label:"Complaints Open",icon:"warning",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:52.5,redUpper:75,amberLower:-52.5,redLower:-75}},{key:"invoiceActions",label:"Invoice Actions",icon:"invoice",scale:"count10",refreshMinutes:15,thresholds:{amberUpper:59.5,redUpper:85,amberLower:-59.5,redLower:-85}},{key:"deliveryPersonLeave",label:"Delivery Person Leave",icon:"person",scale:"count10",refreshMinutes:720,thresholds:{amberUpper:49,redUpper:70,amberLower:-49,redLower:-70}},{key:"refillSpreadDays",label:"Refill Spread",icon:"calendar",scale:"daysCritical",scaleBase:10,scaleMax:165,refreshMinutes:1440,display:{suffix:"d"},thresholds:{amberUpper:50,redUpper:100,doubleRedUpper:150,amberLower:-70,redLower:-100},areaScanView:"refillSpreadAreaScan",areaKey:"refillSpreadAreas",areaScanTitle:"REFILL SPREAD AREA SCAN",areaScanLevels:[{level:"amber",above:5},{level:"red",above:10}]},{key:"pendencyDays",label:"Pendency",icon:"hourglass",scale:"pendency",scaleIdeal:1,scaleBase:3,scaleMax:115,refreshMinutes:720,display:{suffix:"d",decimals:1},thresholds:{amberUpper:33.33,redUpper:100,amberLower:-70,redLower:-100},areaScanView:"pendencyAreaScan",areaKey:"pendencyAreas",areaScanTitle:"PENDENCY AREA SCAN",areaScanLevels:[{level:"amber",above:1},{level:"red",above:3}]},{key:"bpclDepositLakhs",label:"BPCL Deposit",icon:"deposit",scale:"raw",refreshMinutes:30,display:{prefix:"\u20B9",suffix:"L",decimals:1},thresholds:{amberUpper:4,redUpper:6,amberLower:-1,redLower:-3}},{key:"safetyClinicDone",label:"Safety Clinic",icon:"calendar",scale:"raw",refreshMinutes:43200,display:{suffix:"/1"},thresholds:{amberLower:.75,redLower:.25}},{key:"tenKgSales",label:"10kg Sales",icon:"deposit",scale:"raw",refreshMinutes:43200,thresholds:{amberLower:10,redLower:5}},{key:"fiveKgSales",label:"5kg Sales",icon:"deposit",scale:"raw",refreshMinutes:43200,thresholds:{amberLower:10,redLower:5}}],extraAxes:[{label:"BPCL Deposit Good",parameterKey:"bpclDepositLakhs",value:6,color:"rgba(0,255,120,.5)",width:1.8,dash:[4,4]},{label:"BPCL Deposit Soft",parameterKey:"bpclDepositLakhs",value:4,color:"rgba(120,255,160,.34)",width:1.4,dash:[2,5]}]},f=null,S=null,G=!1,ge=null,C={complaintsOpen:0,invoiceActions:2,deliveryPersonLeave:0,refillSpreadDays:be(-1,25),amberRefillSpreadDays:5,criticalRefillSpreadDays:10,doubleRedRefillSpreadDays:15,bpclDepositLakhs:3,safetyClinicDone:0,tenKgSales:0,fiveKgSales:0,pendencyDays:2.7,idealPendencyMaxDays:1,criticalPendencyDays:3,refillSpreadAreas:[{name:"KK NAGAR",days:12},{name:"WEST MAMBALAM",days:9},{name:"ASHOK NAGAR",days:7},{name:"T NAGAR",days:11},{name:"VADAPALANI",days:6},{name:"KODAMBAKKAM",days:8},{name:"SALIGRAMAM",days:5},{name:"VIRUGAMBAKKAM",days:10},{name:"NESAPAKKAM",days:13},{name:"JAFFERKHANPET",days:6},{name:"EKKATTUTHANGAL",days:4},{name:"MGR NAGAR",days:9},{name:"SAIDAPET",days:7}],pendencyAreas:[{name:"KK NAGAR",days:3.4},{name:"WEST MAMBALAM",days:2.9},{name:"ASHOK NAGAR",days:2.6},{name:"T NAGAR",days:3.1},{name:"VADAPALANI",days:2.2},{name:"KODAMBAKKAM",days:2.8},{name:"SALIGRAMAM",days:1.9},{name:"VIRUGAMBAKKAM",days:2.4},{name:"NESAPAKKAM",days:3},{name:"JAFFERKHANPET",days:2.1},{name:"EKKATTUTHANGAL",days:1.7},{name:"MGR NAGAR",days:2.5},{name:"SAIDAPET",days:2}]};function he(e=new Date){let t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=a=>Number(t.find(r=>r.type===a).value);return{year:n("year"),month:n("month"),day:n("day")}}function ye(e,t,n){return Date.UTC(e,t-1,n,-5,-30,0,0)}function be(e,t){let n=he(),a=new Date(Date.UTC(n.year,n.month-1+e,1)),r=a.getUTCFullYear(),s=a.getUTCMonth()+1,i=ye(r,s,t),l=Date.now();return Math.max(0,Math.floor((l-i)/(1440*60*1e3)))}function Z(e){let t=Number(e);return Number.isFinite(t)?t:null}function p(e,t,n){if(!Object.prototype.hasOwnProperty.call(n,e))return;let a=Z(n[e]);a!==null&&(C[t]=a)}function Y(e){return(Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([n,a])=>({name:n,days:a})):[]).map((n,a)=>{let r=String(n.name||n.area||n.areaName||`Area ${a+1}`).trim(),s=Z(n.days??n.pendencyDays??n.currentDays);return r&&s!==null?{name:r,days:s}:null}).filter(Boolean)}function we(e){if(!Object.prototype.hasOwnProperty.call(e,"pendencyAreas"))return;let t=Y(e.pendencyAreas);t.length&&(C.pendencyAreas=t)}function Ae(e){if(!Object.prototype.hasOwnProperty.call(e,"refillSpreadAreas"))return;let t=Y(e.refillSpreadAreas);t.length&&(C.refillSpreadAreas=t)}function Q(e){return!e||String(e.type||"").toLowerCase()!=="tva-metrics"?!1:(S={...S||{},...e},delete S.type,p("complaintsOpen","complaintsOpen",e),p("invoiceActions","invoiceActions",e),p("deliveryPersonLeave","deliveryPersonLeave",e),p("refillSpreadDays","refillSpreadDays",e),p("bookingAgeDays","refillSpreadDays",e),p("bookingSpreadDays","refillSpreadDays",e),p("amberRefillSpreadDays","amberRefillSpreadDays",e),p("criticalRefillSpreadDays","criticalRefillSpreadDays",e),p("doubleRedRefillSpreadDays","doubleRedRefillSpreadDays",e),p("bpclDepositLakhs","bpclDepositLakhs",e),p("bpclDeposit","bpclDepositLakhs",e),p("safetyClinicDone","safetyClinicDone",e),p("tenKgSales","tenKgSales",e),p("fiveKgSales","fiveKgSales",e),p("pendencyDays","pendencyDays",e),p("idealPendencyMaxDays","idealPendencyMaxDays",e),p("criticalPendencyDays","criticalPendencyDays",e),we(e),Ae(e),!0)}function X(e){[...e].sort((t,n)=>t.sentstamp-n.sentstamp).forEach(t=>{let n=L(t.msg,t.extra),a=P(t.sentstamp)?.getTime();a&&(n.updatedAt=Object.fromEntries(Object.keys(n).map(r=>[r,a]))),Q(n)})}function ee(e){return String(L(e.msg,e.extra).type||"").toLowerCase()==="tva-metrics"}window.setTvaControlData=function(e){typeof e=="string"&&(e=JSON.parse(e)),Q({type:"tva-metrics",...e||{}}),N()};window.getTvaControlData=function(){return f?f.getData():JSON.parse(JSON.stringify(C))};function T(){let e=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,t=g.theme==="dark"||g.theme==="auto"&&e,n=g.theme==="light"||g.theme==="auto"&&!e;document.body.classList.toggle("logs-dark",t),document.body.classList.toggle("logs-light",n),document.querySelectorAll(".action-chart-container, .tva-control-container").forEach(a=>{g.theme==="auto"?a.removeAttribute("data-tva-theme"):a.dataset.tvaTheme=g.theme}),W.ambientGlow.enabled=g.ambientGlow!==!1,f&&typeof f.refreshTheme=="function"&&f.refreshTheme()}function te(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");!e||!t||(e.value=g.theme,t.checked=g.ambientGlow!==!1)}window.openLogsSettings=function(){te();let e=document.getElementById("logs-settings-dialog");e&&e.showModal()};window.closeLogsSettings=function(){let e=document.getElementById("logs-settings-dialog");e&&e.close()};window.saveLogsSettings=function(){let e=document.getElementById("settings-theme"),t=document.getElementById("settings-ambient-glow");g={theme:e?e.value:"auto",ambientGlow:t?t.checked:!0},fe(),T(),closeLogsSettings()};function ve(){let e=document.querySelector(".app-chart-header");if(!e||e.dataset.scrollBound)return;e.dataset.scrollBound="1";let t=document.querySelector(".segment-container"),n=document.querySelector(".mobile-panel-switch"),a=e.querySelector(".app-header-chart"),r=e.querySelector(".chat-launcher"),s=document.querySelectorAll(".log-filter-bar"),i=0,l=0,d=()=>{let m=f.getDisplayMode();if(m==="pulseGraphMax")return;m!=="pulseBar"&&(e.style.minHeight="");let o=t.getBoundingClientRect().top-l<=i;m==="pulseGraph"&&o?(e.style.minHeight=`${e.getBoundingClientRect().height}px`,f.setDisplayMode("pulseBar")):e.style.minHeight&&!o&&(e.style.minHeight="",f.setDisplayMode("pulseGraph"))},c=()=>{let m=getComputedStyle(a),h=getComputedStyle(e),o=r?getComputedStyle(r):null;i=(r?r.getBoundingClientRect().height+parseFloat(o.marginTop)+parseFloat(o.marginBottom):0)+parseFloat(m.getPropertyValue("--tva-pulse-bar-height"))+parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth)+parseFloat(h.paddingTop)+parseFloat(h.paddingBottom);let b=n.getBoundingClientRect().height;l=b?b+parseFloat(getComputedStyle(n).marginBottom):0;let k=document.documentElement.style;k.setProperty("--superpulse-sticky-offset",`${Math.ceil(i)}px`),k.setProperty("--panel-switch-height",`${Math.ceil(b)}px`),s.forEach(U=>U.parentElement.style.setProperty("--filter-height",`${Math.ceil(U.getBoundingClientRect().height)}px`)),d()};window.addEventListener("scroll",d,{passive:!0}),window.addEventListener("resize",c);let w=new ResizeObserver(c);[e,a,n,r,...s].filter(Boolean).forEach(m=>w.observe(m)),c()}function ne(){let e=document.getElementById("tvaReactiveChart");!e||f||typeof Chart>"u"||typeof createTvaControl!="function"||(T(),f=createTvaControl({canvas:e,config:W,data:C}),ve())}function N(){f||ne(),f&&S&&(f.update(S),S=null)}function ae(){try{let e=sessionStorage.getItem("seen_lpg_leaks");return e?JSON.parse(e):[]}catch{return[]}}function Se(e){try{let t=ae();t.includes(e)||(t.push(e),sessionStorage.setItem("seen_lpg_leaks",JSON.stringify(t)))}catch(t){console.error(t)}}function De(){try{let e=window.AudioContext||window.webkitAudioContext;if(!e)return;let t=new e;[0,.25].forEach(n=>{let a=t.createOscillator(),r=t.createGain();a.type="sine",a.frequency.setValueAtTime(880,t.currentTime+n),r.gain.setValueAtTime(.3,t.currentTime+n),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+n+.2),a.connect(r),r.connect(t.destination),a.start(t.currentTime+n),a.stop(t.currentTime+n+.2)})}catch{console.warn("Audio Context blocked. Click anywhere on the webpage once to enable sound alerts.")}}function Ce(e,t,n){"Notification"in window&&Notification.permission==="granted"&&new Notification("CRITICAL ALERT: LPG Leakage",{body:`From: ${e} (${n})
 ${t}`})}function u(e,t){return e==null?"":typeof e!="string"?e:e?e.replace(t?/[&<>'"]/g:/[&<>]/g,n=>ue[n]):""}function P(e){if(!e)return;let t;if(e<1e10)t=new Date(e*1e3);else if(e<1e13)t=new Date(e);else if(e<1e16)t=new Date(Math.floor(e/1e3));else return;return A.displayTimestampsAsLocalWallClock?new Date(t.getTime()+t.getTimezoneOffset()*60*1e3):t}function ke(e){return!(e instanceof Date)||isNaN(e)?"":`<strong>${new Intl.DateTimeFormat("en-IN",{timeZone:"Asia/Kolkata",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}</strong>`}function Te(e){if(!(e instanceof Date)||isNaN(e))return"";let t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Kolkata",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=a=>t.find(r=>r.type===a).value;return`${n("year")}-${n("month")}-${n("day")}`}function Le(e){if(!(e instanceof Date)||isNaN(e))return"";let t=new Intl.DateTimeFormat("en-US",{timeZone:"Asia/Kolkata",day:"numeric",month:"short"}).formatToParts(e),n=t.find(r=>r.type==="day").value,a=t.find(r=>r.type==="month").value;return`<div class="date-p"><p>${n}</p><small>${a}</small><hr></div>`}function M(e){if(!e)return;e.querySelectorAll("li.date-divider").forEach(n=>n.remove());let t=null;e.querySelectorAll("li.msg-list-item").forEach(n=>{let a=P(parseInt(n.dataset.timestamp,10));if(!a)return;let r=Te(a);if(r===t)return;t=r;let s=document.createElement("li");s.className="date-divider",s.innerHTML=Le(a),e.insertBefore(s,n)})}window.copyToClipboard=function(e,t){navigator.clipboard.writeText(e).then(()=>{let n=t.innerText;t.innerText="Copied!",t.style.background="#d4edda",t.style.borderColor="#c3e6cb",setTimeout(()=>{t.innerText=n,t.style.background="#f0f0f0",t.style.borderColor="#ddd"},1200)}).catch(n=>console.error(n))};function Ee(e){return`<span class="copyable-code" onclick="copyToClipboard('${e}', this)" style="cursor:pointer; background:#f0f0f0; padding:2px 6px; border-radius:4px; font-weight:bold; display:inline-block; margin-top:4px; border:1px solid #ddd; transition: all 0.2s;">${e}</span>`}function xe(e){return`<div class="leakage-alert">${u(e,!0)} detected</div>`}function L(e,t){if(e&&typeof e=="object"&&e.type)return e;if(e=e||"",typeof e=="string"&&e.trim().startsWith("{"))try{let d=JSON.parse(e);if(d&&typeof d=="object"&&d.type)return d}catch{}let n=e.match(/^rs\.([0-9.]*) debited to CC-xxx2081 .* \[(.*)\]/i);if(n)return{type:"iob-debit",amount:n[1],merchant:n[2]||"",msg:e};let a=e.match(/^rs\.([0-9.]*) credited to CC-xxx2081 .* \[(.*)\]/i);if(a)return{type:"iob-credit",amount:a[1],merchant:a[2]||"",msg:e};let r="";try{let d=t?JSON.parse(t):null;d&&d.sim&&(r=d.sim)}catch{}let s={type:"sms",msg:e,sim:r},i=e.match(/\b\d{6}\b/);i&&(s.otp=i[0]);let l=e.match(/(lpg leakage|gas leak|leakage detected)/i);return l&&(s.leakage=l[0]),s}var H={"iob-debit":e=>`<div>
                             <details style="display: inline-block; width: 100%;"><summary style="margin-left: 6rem; display: block; color: red;">- Rs. ${u(e.amount,!0)}</summary>${u(e.msg)}</details>
                         </div>`,"iob-credit":e=>`<div>

@@ -36,7 +36,7 @@ ${t}`})}function u(e,t){return e==null?"":typeof e!="string"?e:e?e.replace(t?/[&
                             <small style="font-weight: lighter; color: #727272;">${i}${a}</small>
                         </div>
                         <button class="device-name-button" popovertarget="device-info-popover" data-mid="${u(String(r),!0)}" onfocus="deviceCardUpdate(event)" onclick="deviceCardUpdate(event)" style="flex: 1; text-align: end; font-size: 11px; color:#aaa; font-weight:normal; font-family:monospace;">${s}</button>
-            </div>`}function re(e,t){e.style.setProperty("display",t?"flex":"none","important")}window.applyFilters=function(){let e=document.getElementById("filter-device").value,t=document.getElementById("filter-category").value,n=document.getElementById("filter-search").value.toLowerCase();document.querySelectorAll("#data-list .msg-list-item").forEach(a=>{let r=!e||a.dataset.device===e,s=!t||a.dataset.category===t,i=!n||a.innerText.toLowerCase().includes(n);re(a,r&&s&&i)})};window.applyActionFilters=function(){let e=document.getElementById("action-filter-search"),t=e?e.value.toLowerCase():"";document.querySelectorAll("#action-list .msg-list-item").forEach(n=>{let a=!t||n.innerText.toLowerCase().includes(t);re(n,a)})};window.showMobileSegment=function(e){document.querySelectorAll(".segment").forEach(t=>{t.classList.toggle("active",t.dataset.segment===String(e))}),document.querySelectorAll(".mobile-panel-switch button").forEach(t=>{let n=t.dataset.targetSegment===String(e);t.classList.toggle("active",n),t.setAttribute("aria-pressed",n?"true":"false")})};function j(e){if(!e)return null;let t=String(e).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);if(!t)return null;let[,n,a,r,s,i]=t.map(Number);return Math.floor(Date.UTC(n,a-1,r,s-5,i-30,0,0)/1e3)}function J(e){let t=new Date(e.getTime()+198e5),n=a=>String(a).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}T${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}function O(e=!1){let t=document.getElementById("range-from"),n=document.getElementById("range-to");if(!t||!n)return;let a=new Date;if(e||!_||!t.value){let r=new Date(a.getTime()-A.defaultRangeHours*60*60*1e3);t.value=J(r),_=!0}n.value=J(a)}function se(){O();let e=document.getElementById("range-from"),t=document.getElementById("range-to"),n={},a=j(e&&e.value),r=j(t&&t.value);return a&&(n.sentstamp=a,n.fromTimestamp=a),r&&(n.toTimestamp=r),n}window.refreshRangeFeeds=function(){O(),x(),R()};function Re(e){if(!e||F.has(String(e)))return;F.add(String(e));let t=document.getElementById("filter-device");if(!t)return;let n=document.createElement("option");n.value=String(e),n.textContent=oe(e)||E(e),t.appendChild(n)}function Be(e){if(!e||q.has(e))return;q.add(e);let t=document.getElementById("filter-category");if(!t)return;let n=document.createElement("option");n.value=e,e==="otp"||e==="sms"?n.textContent=`${e.toUpperCase()} Only`:n.textContent=e.charAt(0).toUpperCase()+e.slice(1),t.appendChild(n)}function E(e){return e?`Device ${e}`:"unknown"}function oe(e){let t=D[e];return t&&typeof t=="object"&&t.name?t.name:(pe(e).then(n=>ie(e,n)),E(e))}function I(e){return window.CSS&&CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function ie(e,t){if(!e||!t||!t.name)return;document.querySelectorAll(`.device-name-button[data-mid="${I(String(e))}"]`).forEach(a=>{a.textContent=t.name;let r=a.closest(".msg-list-item");r&&(r.dataset.device=String(e))});let n=document.querySelector(`#filter-device option[value="${I(String(e))}"]`);n&&(n.textContent=t.name)}function K(e){return{1:"sms",2:"econnect",3:"paytm",4:"tampermonkey",5:"printer"}[e+""]}function Ne(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return`hsl(${Math.abs(t)%360}, 65%, 42%)`}function ce(e,t,n){let a=e.querySelectorAll("li.msg-list-item");for(let r=0;r<a.length;r++){let s=parseInt(a[r].dataset.timestamp,10);if(n>s){e.insertBefore(t,a[r]);return}}e.appendChild(t)}function Pe(e){let t=String(e.sndr||"").toLowerCase(),n=String(e.msg||"").toLowerCase(),a=K(e.cid)||"";return t==="complaints"||a==="econnect"&&/\b(urgent|emergency|complain|complaint|leak)/i.test(n)}function $(e,t){let n=t.map(a=>`msg-${a.sndr}-${a.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"));e.querySelectorAll('li[id^="msg-"]').forEach(a=>{n.includes(a.id)||a.remove()})}function le(e){let t=P(e.sentstamp);if(!t)return null;let n=oe(e.mid)||E(e.mid),a=K(e.cid)||"unknown",r=L(e.msg,e.extra),s=document.createElement("li");s.id=`msg-${e.sndr}-${e.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"),s.className="msg-list-item",s.dataset.device=String(e.mid||"unknown"),s.dataset.category=a,s.dataset.timestamp=e.sentstamp,s.style.display="flex",s.style.alignItems="flex-start",s.style.padding="10px 12px",s.style.borderBottom="1px solid #f2f2f2",r.leakage&&(s.style.background="#fff5f5",s.style.borderLeft="4px solid #dc3545");let i=Ne(e.sndr||"Unknown"),l="";return a==="sms"?l=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${i}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
+            </div>`}function re(e,t){e.style.setProperty("display",t?"flex":"none","important")}window.applyFilters=function(){let e=document.getElementById("filter-device").value,t=document.getElementById("filter-category").value,n=document.getElementById("filter-search").value.toLowerCase();document.querySelectorAll("#data-list .msg-list-item").forEach(a=>{let r=!e||a.dataset.device===e,s=!t||a.dataset.category===t,i=!n||a.innerText.toLowerCase().includes(n);re(a,r&&s&&i)})};window.applyActionFilters=function(){let e=document.getElementById("action-filter-search"),t=e?e.value.toLowerCase():"";document.querySelectorAll("#action-list .msg-list-item").forEach(n=>{let a=!t||n.innerText.toLowerCase().includes(t);re(n,a)})};window.showMobileSegment=function(e){document.querySelectorAll(".segment").forEach(t=>{t.classList.toggle("active",t.dataset.segment===String(e))}),document.querySelectorAll(".mobile-panel-switch button").forEach(t=>{let n=t.dataset.targetSegment===String(e);t.classList.toggle("active",n),t.setAttribute("aria-pressed",n?"true":"false")})};function j(e){if(!e)return null;let t=String(e).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);if(!t)return null;let[,n,a,r,s,i]=t.map(Number);return Math.floor(Date.UTC(n,a-1,r,s-5,i-30,0,0)/1e3)}function z(e){let t=new Date(e.getTime()+198e5),n=a=>String(a).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}T${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}function O(e=!1){let t=document.getElementById("range-from"),n=document.getElementById("range-to");if(!t||!n)return;let a=new Date;if(e||!G||!t.value){let r=new Date(a.getTime()-A.defaultRangeHours*60*60*1e3);t.value=z(r),G=!0}n.value=z(a)}function se(){O();let e=document.getElementById("range-from"),t=document.getElementById("range-to"),n={},a=j(e&&e.value),r=j(t&&t.value);return a&&(n.sentstamp=a,n.fromTimestamp=a),r&&(n.toTimestamp=r),n}window.refreshRangeFeeds=function(){O(),x(),R()};function Re(e){if(!e||F.has(String(e)))return;F.add(String(e));let t=document.getElementById("filter-device");if(!t)return;let n=document.createElement("option");n.value=String(e),n.textContent=oe(e)||E(e),t.appendChild(n)}function Be(e){if(!e||_.has(e))return;_.add(e);let t=document.getElementById("filter-category");if(!t)return;let n=document.createElement("option");n.value=e,e==="otp"||e==="sms"?n.textContent=`${e.toUpperCase()} Only`:n.textContent=e.charAt(0).toUpperCase()+e.slice(1),t.appendChild(n)}function E(e){return e?`Device ${e}`:"unknown"}function oe(e){let t=D[e];return t&&typeof t=="object"&&t.name?t.name:(pe(e).then(n=>ie(e,n)),E(e))}function I(e){return window.CSS&&CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function ie(e,t){if(!e||!t||!t.name)return;document.querySelectorAll(`.device-name-button[data-mid="${I(String(e))}"]`).forEach(a=>{a.textContent=t.name;let r=a.closest(".msg-list-item");r&&(r.dataset.device=String(e))});let n=document.querySelector(`#filter-device option[value="${I(String(e))}"]`);n&&(n.textContent=t.name)}function K(e){return{1:"sms",2:"econnect",3:"paytm",4:"tampermonkey",5:"printer"}[e+""]}function Ne(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return`hsl(${Math.abs(t)%360}, 65%, 42%)`}function ce(e,t,n){let a=e.querySelectorAll("li.msg-list-item");for(let r=0;r<a.length;r++){let s=parseInt(a[r].dataset.timestamp,10);if(n>s){e.insertBefore(t,a[r]);return}}e.appendChild(t)}function Pe(e){let t=String(e.sndr||"").toLowerCase(),n=String(e.msg||"").toLowerCase(),a=K(e.cid)||"";return t==="complaints"||a==="econnect"&&/\b(urgent|emergency|complain|complaint|leak)/i.test(n)}function $(e,t){let n=t.map(a=>`msg-${a.sndr}-${a.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"));e.querySelectorAll('li[id^="msg-"]').forEach(a=>{n.includes(a.id)||a.remove()})}function le(e){let t=P(e.sentstamp);if(!t)return null;let n=oe(e.mid)||E(e.mid),a=K(e.cid)||"unknown",r=L(e.msg,e.extra),s=document.createElement("li");s.id=`msg-${e.sndr}-${e.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_"),s.className="msg-list-item",s.dataset.device=String(e.mid||"unknown"),s.dataset.category=a,s.dataset.timestamp=e.sentstamp,s.style.display="flex",s.style.alignItems="flex-start",s.style.padding="10px 12px",s.style.borderBottom="1px solid #f2f2f2",r.leakage&&(s.style.background="#fff5f5",s.style.borderLeft="4px solid #dc3545");let i=Ne(e.sndr||"Unknown"),l="";return a==="sms"?l=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${i}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
             <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
             </svg>`:a==="tampermonkey"?l='<img src="/assets/tampermonkey.svg">':a==="printer"?l='<img src="/assets/printer.svg">':l='<img style="height: 16px; width: 16px;" src="/assets/logs/cid-2-16x.png">',s.innerHTML=`
                     <div style="flex-grow: 1; min-width: 0; display: flex; flex-direction: column;">

@@ -47,4 +47,4 @@ ${t}`})}function u(e,t){return e==null?"":typeof e!="string"?e:e?e.replace(t?/[&
                     ${Me(r)}
                     </div>
                     </div>
-                    `,s}function Oe(e){let t=e.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{"))try{let a=JSON.parse(t);return Array.isArray(a)?a:Array.isArray(a.rows)?a.rows:Array.isArray(a.data)?a.data:[a]}catch{}let n=window.parseGT(e);return Array.isArray(n)?n:[n]}async function de(e,t={}){let n=new URLSearchParams({table:e});Object.entries(t).forEach(([r,s])=>{s!=null&&s!==""&&n.set(r,s)});let a=await fetch(`${A.endpoint}?${n.toString()}`);if(!a.ok)throw new Error(`${e} fetch failed: ${a.status}`);return Oe(await a.text())}async function x(){try{let e=se(),t=await de(A.otpTable,e),n=document.getElementById("data-list"),a=e.toTimestamp?e.toTimestamp*1e3:null,r=a?t.filter(c=>c.sentstamp<=a):t;r.sort((c,w)=>w.sentstamp-c.sentstamp),X(r);let s=ae(),i=[],l=[];r.forEach(c=>{if(ee(c))return;let w=K(c.cid)||"unknown";Re(c.mid),Be(w);let m=Pe(c),h=m?document.getElementById("action-list"):n;m?l.push(c):i.push(c);let o=`msg-${c.sndr}-${c.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(h&&h.querySelector(`#${I(o)}`))return;L(c.msg,c.extra).leakage&&!s.includes(o)&&(Se(o),s.push(o),De(),Ce(c.sndr,c.msg,c.mid));let b=le(c);h&&b&&ce(h,b,c.sentstamp)}),$(n,i);let d=document.getElementById("action-list");d&&($(d,l),N(l),applyActionFilters(),M(d)),applyFilters(),M(n)}catch(e){console.error("Error fetching updates:",e)}}async function R(){let e=document.getElementById("action-list");if(!(!e||!A.actionTable))try{let t=se(),n=await de(A.actionTable,t),a=t.toTimestamp?t.toTimestamp*1e3:null,r=a?n.filter(s=>s.sentstamp<=a):n;r.sort((s,i)=>i.sentstamp-s.sentstamp),X(r),r.forEach(s=>{if(ee(s))return;let i=`msg-${s.sndr}-${s.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(document.getElementById(i))return;let l=le(s);l&&ce(e,l,s.sentstamp)}),$(e,r),N(r),applyActionFilters(),M(e)}catch(t){if(String(t.message||"").match(/\b(404|500)\b/)){console.warn("Action-required feed unavailable; stopping action polling.",t),A.actionTable=null,B&&clearInterval(B);return}console.error("Error fetching action-required updates:",t)}}function v(e){return document.getElementById(e)}var D={};function pe(e){if(!e)return Promise.resolve(null);let t=String(e),n=D[t];if(n&&typeof n.then=="function")return n;if(n&&typeof n=="object")return Promise.resolve(n);let a=fetch("/logs.php?id="+encodeURIComponent(t)).then(async r=>{let s=null;try{s=await r.json()}catch{throw new Error(`Device lookup returned invalid JSON: ${r.status}`)}if(!r.ok)throw new Error(s&&s.error?s.error:`Device lookup failed: ${r.status}`);if(!s||!s.name)throw new Error("Device lookup response missing name");return s}).then(r=>(D[t]=r,ie(t,r),r)).catch(r=>(console.warn("Device lookup failed",t,r),delete D[t],null));return D[t]=a,a}function V(e){e=e||{};let t=typeof e.assigned_to=="object"?e.assigned_to&&e.assigned_to.name:e.assigned_to;v("p-name").textContent=e.name||"Loading device\u2026",v("p-assigned-to").textContent=t||"",v("p-assigned-to").closest("p").hidden=!t,v("p-image").src=e.image||"",v("p-notes").textContent=e.notes||"",v("p-serial").textContent=e.serial||""}function W(e){let t=document.getElementById("device-info-popover");if(!t||!e)return;let n=e.getBoundingClientRect();t.style.position="fixed",t.style.left=`${Math.min(n.left,window.innerWidth-320)}px`,t.style.top=`${Math.min(n.bottom+6,window.innerHeight-180)}px`,t.style.inset="auto"}function Ke(e){let t=e.target,n=t.dataset.mid;W(t),V({name:E(n)}),n&&pe(n).then(a=>{a&&V(a),W(t)})}window.deviceCardUpdate=Ke;ge=setInterval(x,3e3);var B=null;x();document.addEventListener("DOMContentLoaded",()=>{window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",T),te(),T(),O(),ne(),x(),R(),B=setInterval(R,3e3)});})();
+                    `,s}function Oe(e){let t=e.trim();if(!t)return[];if(t.startsWith("[")||t.startsWith("{"))try{let a=JSON.parse(t);return Array.isArray(a)?a:Array.isArray(a.rows)?a.rows:Array.isArray(a.data)?a.data:[a]}catch{}let n=window.parseGT(e);return Array.isArray(n)?n:[n]}async function de(e,t={}){let n=new URLSearchParams({table:e});Object.entries(t).forEach(([r,s])=>{s!=null&&s!==""&&n.set(r,s)});let a=await fetch(`${A.endpoint}?${n.toString()}`);if(!a.ok)throw new Error(`${e} fetch failed: ${a.status}`);return Oe(await a.text())}async function x(){try{let e=se(),t=await de(A.otpTable,e),n=document.getElementById("data-list"),a=e.toTimestamp?e.toTimestamp*1e3:null,r=a?t.filter(c=>c.sentstamp<=a):t;r.sort((c,w)=>w.sentstamp-c.sentstamp),X(r);let s=ae(),i=[],l=[];r.forEach(c=>{if(ee(c))return;let w=K(c.cid)||"unknown";Re(c.mid),Be(w);let m=Pe(c),h=m?document.getElementById("action-list"):n;m?l.push(c):i.push(c);let o=`msg-${c.sndr}-${c.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(h&&h.querySelector(`#${I(o)}`))return;L(c.msg,c.extra).leakage&&!s.includes(o)&&(Se(o),s.push(o),De(),Ce(c.sndr,c.msg,c.mid));let b=le(c);h&&b&&ce(h,b,c.sentstamp)}),$(n,i);let d=document.getElementById("action-list");d&&($(d,l),N(l),applyActionFilters(),M(d)),applyFilters(),M(n)}catch(e){console.error("Error fetching updates:",e)}}async function R(){let e=document.getElementById("action-list");if(!(!e||!A.actionTable))try{let t=se(),n=await de(A.actionTable,t),a=t.toTimestamp?t.toTimestamp*1e3:null,r=a?n.filter(s=>s.sentstamp<=a):n;r.sort((s,i)=>i.sentstamp-s.sentstamp),X(r),r.forEach(s=>{if(ee(s))return;let i=`msg-${s.sndr}-${s.sentstamp}`.replace(/[^a-zA-Z0-9-]/g,"_");if(document.getElementById(i))return;let l=le(s);l&&ce(e,l,s.sentstamp)}),$(e,r),N(r),applyActionFilters(),M(e)}catch(t){if(String(t.message||"").match(/\b(404|500)\b/)){console.warn("Action-required feed unavailable; stopping action polling.",t),A.actionTable=null,B&&clearInterval(B);return}console.error("Error fetching action-required updates:",t)}}function v(e){return document.getElementById(e)}var D={};function pe(e){if(!e)return Promise.resolve(null);let t=String(e);if(!/^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/.test(t))return Promise.resolve(null);let n=D[t];if(n&&typeof n.then=="function")return n;if(n&&typeof n=="object")return Promise.resolve(n);let a=fetch("/api/devices/"+encodeURIComponent(t)).then(async r=>{let s=null;try{s=await r.json()}catch{throw new Error(`Device lookup returned invalid JSON: ${r.status}`)}if(!r.ok)throw new Error(s&&s.error?s.error:`Device lookup failed: ${r.status}`);let i=s&&(s.name||s.model&&s.model.name);if(!i)throw new Error("Device lookup response missing name");return{name:i,serial:s.serial,assigned_to:s.assigned_to&&s.assigned_to.name,image:s.image,category_color:s.category&&s.category.tag_color,notes:s.notes}}).then(r=>(D[t]=r,ie(t,r),r)).catch(r=>(console.warn("Device lookup failed",t,r),delete D[t],null));return D[t]=a,a}function J(e){e=e||{};let t=typeof e.assigned_to=="object"?e.assigned_to&&e.assigned_to.name:e.assigned_to;v("p-name").textContent=e.name||"Loading device\u2026",v("p-assigned-to").textContent=t||"",v("p-assigned-to").closest("p").hidden=!t,v("p-image").src=e.image||"",v("p-notes").textContent=e.notes||"",v("p-serial").textContent=e.serial||""}function V(e){let t=document.getElementById("device-info-popover");if(!t||!e)return;let n=e.getBoundingClientRect();t.style.position="fixed",t.style.left=`${Math.min(n.left,window.innerWidth-320)}px`,t.style.top=`${Math.min(n.bottom+6,window.innerHeight-180)}px`,t.style.inset="auto"}function Ke(e){let t=e.target,n=t.dataset.mid;V(t),J({name:E(n)}),n&&pe(n).then(a=>{a&&J(a),V(t)})}window.deviceCardUpdate=Ke;ge=setInterval(x,3e3);var B=null;x();document.addEventListener("DOMContentLoaded",()=>{window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",T),te(),T(),O(),ne(),x(),R(),B=setInterval(R,3e3)});})();
diff --git a/package.json b/package.json
@@ -3,7 +3,7 @@
     "build": "pnpm run build:tva && pnpm run build:logs",
     "build:tva": "esbuild tva-control.js --bundle --minify --legal-comments=none --outfile=out/tva-control.js",
     "build:logs": "node -e 'import(\"esbuild\").then(({build})=>build({stdin:{contents:\"import \\\"./gt.js\\\";import \\\"./logs.js\\\"\",resolveDir:\".\"},outfile:\"out/logs.js\",bundle:true,minify:true,legalComments:\"none\"}))'",
-    "test": "node --check tva-control.js && node --check logs.js && node --check out/tva-control.js && node --check out/logs.js && node tests/tva-control.test.js"
+    "test": "node --check tva-control.js && node --check logs.js && node --check out/tva-control.js && node --check out/logs.js && node tests/tva-control.test.js && node tests/device-lookup.test.js"
   },
   "devDependencies": {
     "esbuild": "latest"
diff --git a/tests/device-lookup.test.js b/tests/device-lookup.test.js
@@ -0,0 +1,54 @@
+const assert = require('node:assert/strict');
+const { readFileSync } = require('node:fs');
+const vm = require('node:vm');
+const source = readFileSync('logs.js', 'utf8');
+const lookup = source.slice(source.indexOf('let deviceMapCache = {}'), source.indexOf('function updateDeviceCard'));
+
+async function main() {
+  let requests = 0;
+  let mode = 'success';
+  const updates = [];
+  const context = vm.createContext({
+    console: { warn() {} },
+    updateDeviceReferences: (...args) => updates.push(args),
+    fetch: async (path) => {
+      requests++;
+      assert.match(path, /^\/api\/devices\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/);
+      return {
+        ok: mode !== 'http-error', status: mode === 'http-error' ? 404 : 200,
+        json: async () => {
+          if (mode === 'invalid-json') throw new Error('not JSON');
+          if (mode === 'missing-name') return { status: 'error' };
+          if (mode === 'http-error') return { error: 'Not found' };
+          return {
+            name: null, model: { name: 'Model fallback' }, serial: 'SERIAL',
+            assigned_to: { name: 'Synthetic user' }, image: '/image.png',
+            category: { tag_color: '#123456' }, notes: 'Synthetic notes'
+          };
+        }
+      };
+    }
+  });
+  vm.runInContext(lookup, context);
+  const first = context.fetchDeviceDetails('TEST_1-2.3');
+  assert.equal(context.fetchDeviceDetails('TEST_1-2.3'), first, 'dedupe pending requests');
+  const device = await first;
+  assert.deepEqual(JSON.parse(JSON.stringify(device)), {
+    name: 'Model fallback', serial: 'SERIAL', assigned_to: 'Synthetic user',
+    image: '/image.png', category_color: '#123456', notes: 'Synthetic notes'
+  });
+  assert.equal(await context.fetchDeviceDetails('TEST_1-2.3'), device);
+  assert.equal(requests, 1);
+  assert.equal(updates.length, 1);
+  for (const id of ['', '../secret', '.hidden', 'a/b', 'a?x=y']) {
+    assert.equal(await context.fetchDeviceDetails(id), null);
+  }
+  assert.equal(requests, 1, 'invalid tags never request the proxy');
+  for (mode of ['http-error', 'invalid-json', 'missing-name']) {
+    assert.equal(await context.fetchDeviceDetails('RETRY'), null);
+  }
+  mode = 'success';
+  assert.ok(await context.fetchDeviceDetails('RETRY'), 'failed lookups can retry');
+  console.log('PASS: raw Snipe-IT mapping, model-name fallback, cache/dedupe, invalid IDs, errors/retry');
+}
+main().catch((error) => { console.error(error); process.exitCode = 1; });
diff --git a/tests/proxy-config.test.py b/tests/proxy-config.test.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+"""Real lighttpd + synthetic HTTP/FastCGI services; no production or real secrets."""
+import http.client
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import socketserver
+import struct
+import subprocess
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ROOT = Path(__file__).resolve().parents[1]
+LIGHTTPD = os.environ.get('LIGHTTPD', shutil.which('lighttpd') or 'lighttpd')
+hits = []
+
+
+class Upstream(BaseHTTPRequestHandler):
+    def do_GET(self):
+        hits.append((self.path, dict(self.headers)))
+        self.send_response(200)
+        self.send_header('Content-Type', 'application/json')
+        self.send_header('Set-Cookie', 'upstream=must-not-reach-browser')
+        self.end_headers()
+        self.wfile.write(json.dumps({'name': 'Synthetic device'}).encode())
+
+    def log_message(self, *args):
+        pass
+
+
+def exact(conn, size):
+    data = b''
+    while len(data) < size:
+        chunk = conn.recv(size - len(data))
+        if not chunk:
+            raise EOFError()
+        data += chunk
+    return data
+
+
+def record(kind, rid, body=b''):
+    return struct.pack('!BBHHBB', 1, kind, rid, len(body), 0, 0) + body
+
+
+class Authorizer(socketserver.BaseRequestHandler):
+    def handle(self):
+        params = b''
+        while True:
+            _, kind, rid, size, padding, _ = struct.unpack('!BBHHBB', exact(self.request, 8))
+            body = exact(self.request, size)
+            exact(self.request, padding)
+            if kind == 4:
+                if body:
+                    params += body
+                    continue
+                # Decode FastCGI name/value pairs, including 4-byte lengths.
+                values = {}
+                pos = 0
+                def length():
+                    nonlocal pos
+                    value = params[pos]
+                    if value & 128:
+                        value = struct.unpack('!I', params[pos:pos + 4])[0] & 0x7fffffff
+                        pos += 4
+                    else:
+                        pos += 1
+                    return value
+                while pos < len(params):
+                    n, v = length(), length()
+                    name = params[pos:pos + n].decode()
+                    pos += n
+                    values[name] = params[pos:pos + v].decode()
+                    pos += v
+                allowed = values.get('HTTP_COOKIE') == 'session=allowed'
+                output = (b'Status: 200\r\nVariable-REMOTE_USER: synthetic\r\n\r\n' if allowed
+                          else b'Status: 403\r\nContent-Type: text/plain\r\n\r\nDenied')
+                self.request.sendall(record(6, rid, output) + record(6, rid)
+                                     + record(3, rid, b'\0' * 8))
+                return
+
+
+with tempfile.TemporaryDirectory(prefix='superpulse-proxy-') as directory:
+    tmp = Path(directory)
+    upstream = ThreadingHTTPServer(('127.0.0.1', 0), Upstream)
+    auth = socketserver.ThreadingUnixStreamServer(str(tmp / 'auth.sock'), Authorizer)
+    for server in (upstream, auth):
+        threading.Thread(target=server.serve_forever, daemon=True).start()
+    with socket.socket() as probe:
+        probe.bind(('127.0.0.1', 0))
+        port = probe.getsockname()[1]
+    secret = tmp / 'snipeit.conf'
+    secret.write_text('var.superpulse.snipeit-token = "synthetic-not-a-secret"\n')
+    secret.chmod(0o600)
+    # Only substitute deployment addresses; exercise the actual shipped policy.
+    snippet = (ROOT / 'deploy/superpulse-proxy.conf').read_text()
+    snippet = snippet.replace('/etc/superpulse/snipeit.conf', str(secret))
+    snippet = snippet.replace('"port" => 81', f'"port" => {upstream.server_port}')
+    (tmp / 'policy.conf').write_text(snippet)
+    config = tmp / 'lighttpd.conf'
+    config.write_text(f'''
+server.document-root = "{tmp}"
+server.bind = "127.0.0.1"
+server.port = {port}
+server.errorlog = "{tmp}/error.log"
+server.modules = ( "mod_access", "mod_fastcgi", "mod_setenv", "mod_proxy" )
+$HTTP["host"] == "logs.saikrupagas.com" {{
+    fastcgi.server = ( "/" => (( "socket" => "{tmp}/auth.sock",
+        "check-local" => "disable", "mode" => "authorizer" )) )
+    proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => {upstream.server_port} )) )
+    include "{tmp}/policy.conf"
+}}
+''')
+    command = [LIGHTTPD]
+    if os.environ.get('LIGHTTPD_MODULES'):
+        command += ['-m', os.environ['LIGHTTPD_MODULES']]
+    subprocess.run(command + ['-tt', '-f', str(config)], check=True)
+    with (tmp / 'process.log').open('w+') as log:
+        process = subprocess.Popen(command + ['-D', '-f', str(config)], stdout=log, stderr=log)
+        try:
+            for _ in range(100):
+                if process.poll() is not None:
+                    raise RuntimeError((tmp / 'error.log').read_text())
+                try:
+                    with socket.create_connection(('127.0.0.1', port), timeout=.1):
+                        break
+                except OSError:
+                    time.sleep(.05)
+            else:
+                raise RuntimeError('lighttpd startup timeout')
+
+            def request(path, method='GET', authorized=True, host='logs.saikrupagas.com'):
+                conn = http.client.HTTPConnection('127.0.0.1', port, timeout=5)
+                headers = {'Host': host, 'Authorization': 'Bearer attacker-value'}
+                if authorized:
+                    headers['Cookie'] = 'session=allowed'
+                conn.request(method, path, headers=headers)
+                response = conn.getresponse()
+                result = response.status, dict(response.getheaders()), response.read()
+                conn.close()
+                return result
+
+            status, headers, body = request('/api/devices/TEST_1-2.3')
+            assert status == 200, (status, body)
+            path, received = hits[-1]
+            assert path == '/api/v1/hardware/bytag/TEST_1-2.3', path
+            assert received['Host'] == 'equipment.saikrupagas.com', received
+            assert received['Authorization'] == 'Bearer synthetic-not-a-secret'
+            assert headers['Cache-Control'] == 'no-store', headers
+            assert not any(k.lower() == 'set-cookie' for k in headers), headers
+            assert b'synthetic-not-a-secret' not in body
+
+            count = len(hits)
+            for path, method, allowed in [
+                ('/api/devices/TEST', 'GET', False),
+                ('/api/devices/TEST', 'POST', True),
+                ('/api/devices/TEST', 'HEAD', True),
+                ('/api/devices/TEST?search=anything', 'GET', True),
+                ('/api/devices', 'GET', True),
+                ('/api/devices/', 'GET', True),
+                ('/api/devices/TEST/extra', 'GET', True),
+                ('/api/devices/.hidden', 'GET', True),
+                ('/.env.php', 'GET', True),
+                ('/logs.php?id=TEST', 'GET', True),
+                ('/deploy/superpulse-proxy.conf', 'GET', True),
+            ]:
+                status, _, _ = request(path, method, allowed)
+                assert status in (400, 403, 405), (path, method, status)
+                assert len(hits) == count, (path, 'unexpected upstream request')
+            request('/index.html')
+            assert hits[-1][0] == '/index.html'
+            assert hits[-1][1]['Host'] == 'logs.saikrupagas.com'
+            assert hits[-1][1]['Authorization'] == 'Bearer attacker-value'
+            assert request('/api/devices/TEST', host='unrelated.example')[0] == 404
+            secret.unlink()
+            assert subprocess.run(command + ['-tt', '-f', str(config)],
+                                  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0
+            print('PASS: auth gate, fixed route/host, token replacement, method/query restrictions, '
+                  'private paths, no-store, cookie suppression, vhost isolation, missing-secret failure')
+        finally:
+            process.terminate()
+            process.wait(timeout=5)
+            upstream.shutdown()
+            auth.shutdown()
diff --git a/tests/scroll.test.mjs b/tests/scroll.test.mjs
@@ -22,7 +22,7 @@ const server = createServer(async (req, res) => {
     let body;
     if (path === '/chart.js') body = chart;
     else if (path === '/kidang.fcgi') body = JSON.stringify(rows);
-    else if (path === '/logs.php') body = JSON.stringify({ name: 'Test device' });
+    else if (path.startsWith('/api/devices/')) body = JSON.stringify({ name: 'Test device' });
     else body = await readFile(new URL(`.${path === '/' ? '/index.html' : path}`, root));
     if (path === '/') body = body.toString()
       .replace('https://cdn.jsdelivr.net/npm/chart.js', '/chart.js')