From d9ce2ec01573c18f93b9d0c6672fa75c28f4510b Mon Sep 17 00:00:00 2001 From: "Isaac J. Newton" Date: Sun, 15 Nov 2026 20:14:04 +0000 Subject: [PATCH] feat: revamp desktop and add M3ter Manager Add shared desktop themes, responsive windows, persistent icon layouts, and per-app appearance controls. Integrate ChirpStack and M3ter Manager with authenticated monitoring, nonce-aware energy accounting, telemetry history, and validated downlinks. Harden existing console services, add a build-and-replace Docker installer, and cover the changes with unit and browser tests. --- .dockerignore | 10 + .env.example | 24 ++ .github/workflows/ci.yml | 6 + .gitignore | 8 +- Dockerfile | 3 +- README.md | 386 +++++++++++++++++++- compose.dev.yaml | 8 +- compose.local.yaml | 13 + compose.yaml | 8 +- entrypoint.sh | 84 +---- install.sh | 35 ++ jest.config.cjs | 3 + package-lock.json | 64 ++++ package.json | 6 +- playwright.config.cjs | 16 + scripts/healthcheck.cjs | 9 + scripts/install-modules.cjs | 46 +++ src/index.ts | 20 +- src/lib/core/is_on/index.ts | 8 +- src/lib/core/prover/index.ts | 17 +- src/lib/core/streamr/index.ts | 17 +- src/lib/core/streamr/ui.ts | 65 ++-- src/lib/encode.ts | 39 +- src/lib/modules.ts | 45 +++ src/lib/sync.ts | 28 +- src/lib/utils.ts | 35 +- src/m3ter/api.ts | 138 +++++++ src/m3ter/auth.ts | 63 ++++ src/m3ter/chirpstack.ts | 61 ++++ src/m3ter/commands.ts | 45 +++ src/m3ter/decoder.ts | 23 ++ src/m3ter/monitor.ts | 96 +++++ src/m3ter/store.ts | 145 ++++++++ src/public/css/global.css | 434 +++++++++++++++++----- src/public/css/m3ter-manager.css | 85 +++++ src/public/js/actions.js | 79 +--- src/public/js/chirpstack-bridge.js | 51 +++ src/public/js/click.js | 19 +- src/public/js/desktop-layout.js | 51 +++ src/public/js/desktop-preferences.js | 66 ++++ src/public/js/desktop.js | 519 +++++++++++++++++++++++++++ src/public/js/m3ter-charts.js | 41 +++ src/public/js/m3ter-commands.js | 120 +++++++ src/public/js/m3ter-manager.js | 220 ++++++++++++ src/public/js/terminal.js | 271 +++++--------- src/public/js/toggle.js | 20 +- src/services/auth.ts | 50 +++ src/services/chirpstack.ts | 140 ++++++++ src/services/grpc.ts | 11 +- src/services/mqtt.ts | 339 +++++++---------- src/services/server.ts | 73 ++-- src/services/socket-router.ts | 22 ++ src/services/ssh.ts | 144 ++++---- src/store/sqlite.ts | 15 + src/views/index.hbs | 354 ++++-------------- src/views/layouts/main.hbs | 44 ++- src/views/partials/m3ter-manager.hbs | 45 +++ tests/logic/codec.test.ts | 20 ++ tests/logic/hooks.test.ts | 20 ++ tests/logic/jobs.test.ts | 29 ++ tests/logic/manager-commands.test.ts | 28 ++ tests/logic/manager-decoder.test.ts | 27 ++ tests/logic/modules.test.ts | 46 +++ tests/logic/power.test.ts | 12 + tests/logic/publishing.test.ts | 20 ++ tests/logic/sync.test.ts | 16 +- tests/services/auth.test.ts | 38 ++ tests/services/chirpstack.test.ts | 35 ++ tests/services/install.test.ts | 39 ++ tests/services/manager-auth.test.ts | 37 ++ tests/services/mqtt.test.ts | 94 +++++ tests/services/ssh.test.ts | 44 +++ tests/store/manager.test.ts | 100 ++++++ tests/store/sqlite.test.ts | 10 + tests/ui/auth.spec.cjs | 51 +++ tests/ui/chirpstack-upstream.cjs | 47 +++ tests/ui/chirpstack.spec.cjs | 75 ++++ tests/ui/desktop.spec.cjs | 297 +++++++++++++++ tests/ui/desktop.test.js | 60 ++++ tests/ui/manager-auth.spec.cjs | 25 ++ tests/ui/manager-fixture.cjs | 93 +++++ tests/ui/manager-preview.cjs | 23 ++ tests/ui/manager.spec.cjs | 139 +++++++ tests/ui/serve-auth.cjs | 20 ++ tests/ui/serve.cjs | 26 ++ tests/ui/streamr.test.ts | 34 ++ 86 files changed, 5080 insertions(+), 1212 deletions(-) create mode 100644 compose.local.yaml create mode 100755 install.sh create mode 100644 jest.config.cjs create mode 100644 playwright.config.cjs create mode 100644 scripts/healthcheck.cjs create mode 100644 scripts/install-modules.cjs create mode 100644 src/lib/modules.ts create mode 100644 src/m3ter/api.ts create mode 100644 src/m3ter/auth.ts create mode 100644 src/m3ter/chirpstack.ts create mode 100644 src/m3ter/commands.ts create mode 100644 src/m3ter/decoder.ts create mode 100644 src/m3ter/monitor.ts create mode 100644 src/m3ter/store.ts create mode 100644 src/public/css/m3ter-manager.css create mode 100644 src/public/js/chirpstack-bridge.js create mode 100644 src/public/js/desktop-layout.js create mode 100644 src/public/js/desktop-preferences.js create mode 100644 src/public/js/desktop.js create mode 100644 src/public/js/m3ter-charts.js create mode 100644 src/public/js/m3ter-commands.js create mode 100644 src/public/js/m3ter-manager.js create mode 100644 src/services/auth.ts create mode 100644 src/services/chirpstack.ts create mode 100644 src/services/socket-router.ts create mode 100644 src/views/partials/m3ter-manager.hbs create mode 100644 tests/logic/codec.test.ts create mode 100644 tests/logic/hooks.test.ts create mode 100644 tests/logic/jobs.test.ts create mode 100644 tests/logic/manager-commands.test.ts create mode 100644 tests/logic/manager-decoder.test.ts create mode 100644 tests/logic/modules.test.ts create mode 100644 tests/logic/power.test.ts create mode 100644 tests/logic/publishing.test.ts create mode 100644 tests/services/auth.test.ts create mode 100644 tests/services/chirpstack.test.ts create mode 100644 tests/services/install.test.ts create mode 100644 tests/services/manager-auth.test.ts create mode 100644 tests/services/mqtt.test.ts create mode 100644 tests/services/ssh.test.ts create mode 100644 tests/store/manager.test.ts create mode 100644 tests/ui/auth.spec.cjs create mode 100644 tests/ui/chirpstack-upstream.cjs create mode 100644 tests/ui/chirpstack.spec.cjs create mode 100644 tests/ui/desktop.spec.cjs create mode 100644 tests/ui/desktop.test.js create mode 100644 tests/ui/manager-auth.spec.cjs create mode 100644 tests/ui/manager-fixture.cjs create mode 100644 tests/ui/manager-preview.cjs create mode 100644 tests/ui/manager.spec.cjs create mode 100644 tests/ui/serve-auth.cjs create mode 100644 tests/ui/serve.cjs create mode 100644 tests/ui/streamr.test.ts diff --git a/.dockerignore b/.dockerignore index ea3d8cc..a7239bc 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,5 @@ node_modules +src/extensions npm-debug.log .env.local .env.development.local @@ -21,3 +22,12 @@ build # ignore test files **/*.test.ts **/*.spec.ts + +# Local secrets and runtime/test artifacts never belong in the build context. +.env +.env.* +.data +.data-dev +test-results +playwright-report +tests diff --git a/.env.example b/.env.example index dd0b25f..68d573e 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,14 @@ # Server Configuration PORT=3000 +CONSOLE_HOST=127.0.0.1 +CONSOLE_USERNAME=admin +CONSOLE_PASSWORD= +# Set a strong unique CONSOLE_PASSWORD. For a TLS reverse proxy, set its public origin: +# CONSOLE_ORIGIN=https://console.example.com + +# M3ter Manager login (separate from console access; required to unlock the app) +M3TER_MANAGER_USERNAME=admin +M3TER_MANAGER_PASSWORD= # Module Configuration BACKEND_MODULES="core/arweave,core/is_on,core/prover,core/streamr" @@ -9,6 +18,21 @@ UI_MODULES="streamr:core/streamr/ui" API_TOKEN=... APPLICATION_ID=... CHIRPSTACK_HOST=localhost +# Optional web UI origin; defaults to http://CHIRPSTACK_HOST:8080. +# Browsers access it through the console's /chirpstack/ proxy. +# CHIRPSTACK_WEB_URL=http://localhost:8080 +# M3ter Manager uses the existing ChirpStack v4 REST proxy and the same API_TOKEN. +# This is the REST proxy's port, NOT the ChirpStack web UI port. +# CHIRPSTACK_REST_URL=http://localhost:8090 +# Optional MQTT URL and broker credentials (kept on the server). +# MQTT_URL=mqtt://localhost:1883 +# MQTT_USERNAME= +# MQTT_PASSWORD= +# Activity is observational; a quiet meter is not necessarily offline. +# M3TER_INACTIVE_SECONDS=300 +# Optional: start the console for monitoring/control without loading billing, +# blockchain or delivery extensions. Default false preserves existing behavior. +# CONSOLE_MONITOR_ONLY=true # Contract & Network Configuration CONTRACT_LABEL=M3ters diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6456be..835ac6d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,12 @@ jobs: - name: Run tests run: npm test + - name: Install browser for desktop UI tests + run: npx playwright install --with-deps chromium + + - name: Test desktop themes and responsive interactions + run: npm run test:ui + build-platform: needs: [test] strategy: diff --git a/.gitignore b/.gitignore index 195e462..1d72804 100644 --- a/.gitignore +++ b/.gitignore @@ -138,4 +138,10 @@ dist .yarn/install-state.gz .pnp.* cache/ -db/ \ No newline at end of file +db/ +# Browser test artifacts +playwright-report/ +test-results/ + +# Downloaded external extensions +src/extensions/ diff --git a/Dockerfile b/Dockerfile index 9a99712..631fc18 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,12 +11,13 @@ RUN apk add --no-cache cmake make g++ python3 openssl-dev py3-setuptools git # Copy and install dependencies COPY package*.json ./ -RUN npm install --include=dev && npm cache clean --force +RUN npm ci --include=dev && npm cache clean --force # Copy application files COPY babel.config.js . COPY tsconfig.json . COPY src ./src +COPY scripts ./scripts # Build project RUN npm run build diff --git a/README.md b/README.md index 1782790..998e0a0 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,9 @@ A modular, extensible service console for providers on the M3tering protocol. Fe ``` # Server Configuration PORT=3000 + CONSOLE_HOST=127.0.0.1 + CONSOLE_USERNAME=admin + CONSOLE_PASSWORD= # Module Configuration BACKEND_MODULES="core/arweave,core/is_on,core/prover,core/streamr" @@ -44,7 +47,7 @@ A modular, extensible service console for providers on the M3tering protocol. Fe STREAMR_STREAM_ID="0x567853282663b601bfdb9203819b1fbb3fe18926/m3tering/test" STREAMR_CRONSCHEDULE="0 * * * *" # Every hour - # Optional: Prover Node (defaults to automatic selection) + # Optional: Prover Node (publishing is disabled when unset) # PREFERRED_PROVER_NODE="https://prover.m3ter.ing" # PROVER_CRONSCHEDULE="0 0 * * *" # Every 24 hours ``` @@ -73,6 +76,334 @@ npm install npm run dev ``` +## M3ter Manager + +**M3ter Manager** is a built-in desktop application for Switch Cumulus telemetry +and technician downlinks. Launch it from the desktop, dock, or application +launcher. Its Overview, Live monitoring, Analytics, Commands, Queue, and Meter +information sections share the selected device, desktop theme, and responsive +window environment. On phones the desktop presents one active full-screen window. + +### Configuration and startup + +Configure the console credentials, separate manager login, and existing ChirpStack connection: + +```dotenv +CONSOLE_USERNAME=admin +CONSOLE_PASSWORD=your-strong-console-password +M3TER_MANAGER_USERNAME=operator +M3TER_MANAGER_PASSWORD=your-strong-manager-password +APPLICATION_ID=your-chirpstack-application-uuid +CHIRPSTACK_HOST=localhost +API_TOKEN=your-server-side-chirpstack-api-token +CHIRPSTACK_REST_URL=http://localhost:8090 +MQTT_URL=mqtt://localhost:1883 +# MQTT_USERNAME=your-broker-user +# MQTT_PASSWORD=your-broker-password +M3TER_INACTIVE_SECONDS=300 +``` + +`CHIRPSTACK_REST_URL` is the origin of **chirpstack-rest-api**, not the web UI. +It defaults to `http://CHIRPSTACK_HOST:8090`. The separately configured +`CHIRPSTACK_WEB_URL` continues to serve the embedded ChirpStack web application. +The REST proxy must be reachable from the console process/container. For a +loopback-only proxy connected to a local plaintext gRPC server, its command is: + +```sh +chirpstack-rest-api --server 127.0.0.1:8080 --bind 127.0.0.1:8090 --insecure +``` + +See the [official REST proxy documentation](https://github.com/chirpstack/chirpstack-rest-api) +for installation and TLS options. No browser CORS or direct access to port 8090 +is needed. The API token needs device/application/profile read access and device +queue enqueue/read/flush access for the configured application. MQTT requires +permission to subscribe to that application's events. Configure ChirpStack's +MQTT integration to publish JSON. `mqtts://` URLs use normal certificate +verification; broker credentials remain on the backend. + +For monitoring and technician control **without the existing billing/blockchain +workflow**, set `CONSOLE_MONITOR_ONLY=true`. This skips backend/UI extension +loading, contract initialization, and the legacy billing uplink consumer. Built-in +desktop applications remain available. The default is false to preserve existing +console installations. When false, existing billing automation can still send +its own commands; M3ter Manager displays this explicitly. Manager itself never +initiates blockchain, wallet, payment, or tokenization operations. + +```sh +npm run build +npm start +``` + +Then open the console on its configured port (3000 by default), sign in, and +launch **M3ter Manager**. The dashboard stays accessible while MQTT reconnects. + +### Architecture and API + +The application uses the same Express authentication boundary and SQLite +connection as the console. Manager access additionally requires its own username/password +from `.env`. Missing manager credentials leave the app locked. The login uses an +eight-hour HttpOnly, SameSite cookie; logout, expiry, credential changes, and server +restarts invalidate sessions. Failed sign-ins are rate limited. The API and live +stream enforce both access checks; credentials never enter browser storage. +All manager operators share the configured administrator identity. Records and operations are scoped to `APPLICATION_ID`; +this does not introduce a separate multi-user/tenant authorization system. + +| Responsibility | Implementation | +| --- | --- | +| Desktop view and theme integration | `src/views/partials/m3ter-manager.hbs`, `src/public/css/m3ter-manager.css` | +| Selection, telemetry, navigation, live connection | `src/public/js/m3ter-manager.js` | +| Accessible SVG charts with pointer/keyboard inspection | `src/public/js/m3ter-charts.js` | +| Command forms, previews, confirmation, queue/history | `src/public/js/m3ter-commands.js` | +| Device discovery and scoped REST access | `src/m3ter/chirpstack.ts` | +| Decoder registry and existing decoder/signature reuse | `src/m3ter/decoder.ts` | +| MQTT ingestion, diagnostics, activity, delivery correlation | `src/m3ter/monitor.ts`, existing `src/services/mqtt.ts` | +| SQLite tables and historical queries | `src/m3ter/store.ts` | +| Command catalogue and exact frame generation | `src/m3ter/commands.ts` | +| Authenticated API and real-time stream | `src/m3ter/api.ts`, `src/services/socket-router.ts` | + +The shared WebSocket upgrade router protects both `/terminal` and +`/m3ter-manager/live` with console authentication and an exact-origin check. +The manager stream additionally requires a manager session and closes on logout or expiry. +The manager stream carries sanitized change notifications; the browser retrieves +the selected device's data from authenticated, bounded HTTP endpoints. + +All HTTP routes below are prefixed with `/api/m3ter-manager`: + +| Method | Route | Purpose | +| --- | --- | --- | +| GET / POST / DELETE | `/session` | Check access / sign in / sign out | +| GET | `/config` | Command catalogue, MQTT state, activity threshold | +| GET | `/devices?search=&offset=` | Name/DevEUI search, 50 devices per page | +| GET | `/devices/:devEui` | Sanitized device metadata, latest reading, known key | +| GET | `/devices/:devEui/history?from=&to=&offset=&limit=` | Millisecond UTC date range, reading page and chart samples | +| GET | `/devices/:devEui/events?offset=` | Device events and application-wide MQTT observations | +| GET | `/devices/:devEui/commands?offset=` | Persistent command history | +| POST | `/commands/preview` | Validate a command ID/parameter and produce exact bytes | +| POST | `/devices/:devEui/commands` | Validate and enqueue an unconfirmed downlink | +| GET | `/devices/:devEui/queue` | Up to 100 pending ChirpStack queue items | +| DELETE | `/devices/:devEui/queue` | Clear all queued items after explicit DevEUI confirmation | + +### Telemetry and historical data + +One MQTT client subscribes to +`application/{APPLICATION_ID}/device/+/event/+`. It validates both the topic and +event identity, handles `up`, `ack`, `txack`, `join`, `location`, `log`, and `status`, +and reconnects/resubscribes without creating another client when a meter changes. +Telemetry is persisted before the optional legacy billing consumer runs. + +The current decoder accepts **only FPort 2, 74 or 106 bytes**. It wraps the +existing `decodePayload` implementation: uint32 BE nonce; uint32 BE energy divided +by 1,000,000; 64-byte Ed25519 signature; uint16 BE voltage divided by 10; optional +32-byte public key. Existing console keys and subsequently learned keys support +74-byte uplinks. Signature verification covers **only bytes 0–7**, not voltage. +A first-seen key establishes cryptographic consistency, not independently verified +device identity. Invalid/unverified signatures are labeled, never claimed valid. +No GPS is extracted from these payloads. Device location comes only from validated +ChirpStack device location events. A `phaseMode` device tag of `three-phase`, +`phase-a`, `phase-b`, or `phase-c` may describe configured metadata; it is not a +firmware acknowledgment. In three-phase metadata mode the dashboard separately +labels the transmitted voltage sum and calculated mean (sum / 3). + +Additive SQLite tables store raw MQTT payloads/metadata separately from decoded +readings, device state, and command audit history. Device/time indexes support +bounded queries. Uplinks deduplicate by ChirpStack event ID, or by a stable tuple +of device/event type/source time/frame counter/payload when an ID is absent. +Identical values with distinct events are preserved. Without an event ID or +source timestamp, events are retained separately rather than risking data loss. +Source timestamps are preserved in metadata; invalid timestamps use receipt time. + +Charts plot **accumulator snapshots**, not interval consumption, and sample to at +most 401 points. A nonce identifies an accumulation cycle ending when the main +collector acknowledges/reset commands advance the nonce. Within a cycle only +increases above its previous highest total add observed energy: repeated totals +add zero, even with different MQTT event IDs. A higher nonce starts a fresh cycle +and contributes its own accumulator, even when greater than the preceding total. +The first observed report establishes a baseline. Lower totals without a nonce +advance and regressed nonces (including ambiguous reboot/wrap behavior) are flagged +as uncertain and never credited as a fresh reset. Charts split at cycle changes +and decreases. Calculations include prior history before applying date filters, +so pagination/range changes do not erase the baseline. Raw reports are preserved. +This is observed incremental energy, **not the collector's acknowledged billing +total**. Missing cycles, unobserved consumption before resets, and ambiguous nonce +resets cannot be reconstructed. Manager never automatically acknowledges reports. + +Reading pages contain at most +100 records (50 in the UI), activity pages 100, and command-history pages 50. +History ranges are capped at 366 days. Data is retained until an operator manages +the database; no automatic deletion policy is introduced. + +### Command safety and delivery evidence + +All 13 command types and their listed parameter variations are defined centrally. +The backend reconstructs payloads from IDs and validated integer parameters, +enforces lengths and FPorts 2/3, and rejects raw payload/FPort overrides. Class B, +calibration, and FUOTA ports 200–202 are not exposed. Billing, restart, relay +hardware, and Class A controls require explicit confirmation. Queue clearing +requires a confirmation naming the selected DevEUI and removes all pending items, +including items created by other applications. + +Commands are recorded before enqueueing. A UUID request ID makes a repeated +submission idempotent, including retry after a lost HTTP response. A timeout or +ambiguous upstream failure is **unknown**, not automatically retried. Inspect the +queue before issuing a new request. A console restart marks interrupted enqueues +unknown. The upstream queue item uses the same UUID for event correlation. + +`queued` means REST acceptance; the Queue tab shows pending delivery. +`transmitted` means a gateway `txack`, **not** proven device delivery. Only an +acknowledged `ack` event marks `delivered`; even this does not prove firmware +execution. Commands default to unconfirmed, so device acknowledgments may never +arrive. Events match both DevEUI and queue item ID; no relay state or applied +configuration is inferred from queue acceptance. Confirmed deliveries are retained +when a queue is cleared. MQTT activity/inactivity is explicitly observational. + +### Validation and preview boundaries + +```sh +npm test -- --runInBand +npm run test:ui +npm run preview:ui +``` + +The preview at `http://127.0.0.1:4173` includes a **labeled simulated M3TER network**. +Sign in there with **`demo` / `demo-manager`** (preview only). +Its local REST and MQTT simulators never contact real meters; downlinks there only +modify fixture queues. Browser integration tests exercise the production API, +SQLite store, authenticated WebSocket routing, and a real MQTT.js TCP connection +to a simulator. Unit tests cover every supplied command Base64 value, parameter +boundaries, payload lengths and scaling, signatures, isolation, deduplication, +reset segments, persistence, and pagination. Browser tests cover switching meters, +MQTT reconnection, command confirmation/idempotency, queue operations, error +recovery, charts and all four themes on desktop/tablet/phone sizes. + +The referenced firmware source is not included in this checkout; implementation +uses the supplied firmware specification and existing console decoder. No live +ChirpStack/meter validation is implied by simulator test results. Richer telemetry +decoders and command-specific firmware acknowledgments are not implemented without +their firmware specifications. The current protocol cannot verify relay state, +the applied reporting interval, restart completion, or applied phase configuration. + +## ChirpStack desktop application + +Open **ChirpStack** from the desktop, dock, or application launcher. Its web +interface opens inside a console window; the browser uses `/chirpstack/` on the +console's own port. The console server connects to +`http://CHIRPSTACK_HOST:8080` (localhost by default). Set +`CHIRPSTACK_WEB_URL=http://your-chirpstack-host:8080` to override the web endpoint, +or use an HTTPS origin. Only an origin is supported, without credentials or a +subpath. In Docker this address must be reachable from the console container. + +Sign in with your **ChirpStack credentials** inside the app. The console login +protects the proxy; neither console credentials nor the server's `API_TOKEN` are +forwarded as ChirpStack credentials. An HttpOnly, SameSite cookie scoped to +`/chirpstack` allows ChirpStack's own Bearer authentication. It expires after +eight hours; use **Reload** to renew access. Console restarts invalidate it. +ChirpStack browser storage is namespaced so its logout cannot erase desktop +preferences. Reload restarts the embedded page; theme changes and minimizing +preserve it. The toolbar also opens the proxied interface in a new tab. + +The integration targets the ChirpStack v4 hash-routed UI and gRPC-Web API, +including streamed responses. ChirpStack retains its own interface inside the +responsive console window. External SSO redirects and customized upstream builds +may need deployment-specific configuration. Configure only a trusted ChirpStack +server: its interface runs on the console origin. If the upstream cannot be +reached, the app shows a connection error with a retry link. The UI-only preview +does not connect to a real ChirpStack server. + +## Console access and reliability + +The production console requires `CONSOLE_USERNAME` and `CONSOLE_PASSWORD` and +binds to `127.0.0.1` by default. The browser prompts for these credentials before +loading the desktop; API routes and terminal upgrades require the same login. +For remote access, use an SSH tunnel or a TLS reverse proxy. Set `CONSOLE_ORIGIN` +to the proxy's exact public origin (for example `https://console.example.com`, +without a trailing slash). Set `CONSOLE_HOST` only if the proxy needs a different +bind address, and keep the backend port private. + +Terminal host credentials are separate from the console login. They are sent in +the first authenticated WebSocket message to `/terminal`, never in the URL or +connection logs. There is no built-in SSH password. Cross-origin browser writes +and terminal upgrades are rejected. + +Meter transactions and their local nonces commit atomically. Device downlinks +are attempted before external delivery hooks; a delivery failure does not block +acknowledgement or later delivery extensions. Exact retransmissions can be +acknowledged without storing or distributing the same transaction twice. +Transactions remain in SQLite for chain synchronization and scheduled publishing; +this does not provide an exactly-once delivery guarantee for external services. +Scheduled batches wait for synchronization, exclude confirmed nonces, and skip +meters whose synchronization failed until a later run. + +`core/is_on` compares cross-chain revenue with owed amounts using exact integers. +Bootstrap messages use the same check. Failed or incomplete balance reads produce +an off response instead of silently permitting power; configure the revenue and +price contracts for your network before using this module with live devices. + +The transaction encoder matches the decoder's scales and interprets signature +and public-key strings as hexadecimal bytes. Values outside the current wire +format are rejected. In particular, its signed 24-bit coordinate fields at +`1e5` precision cover approximately ±83.886 degrees; extending that range requires +a coordinated device protocol change. + +## Desktop personalization + +Open **Settings** from the desktop, dock, or application launcher. All applications +share one desktop environment; changing themes preserves open windows and their +contents. + +- **Appearance:** Retro 8-Bit (default), macOS Inspired, Linux Inspired, and + Windows Inspired. Preview cards show each theme's chrome before selecting it. + Background choices apply independently of the theme. +- **Desktop:** automatic grid arrangement, or manual positioning with grid + snapping. Dropping onto another icon swaps their positions. On a touch screen, + hold an icon briefly to move it; swiping before the hold scrolls the desktop. + With an icon focused, **Alt + arrow keys** moves it in manual mode. Plain arrow + keys navigate the grid. Icon sizing and a confirmed layout reset are included. +- **General:** reduced motion, optional interface sounds, and 24-hour time. + The operating system's reduced-motion preference is always respected. + +Preferences live in this browser's `localStorage` under `m3tering.desktop.v1`. +Invalid or incompatible values fall back to defaults. Custom positions use stable +application IDs; viewport changes reflow them without overwriting the saved +desktop layout. Unavailable applications are ignored and new applications occupy +free cells. Browser storage restrictions leave the interface usable and display +a persistence notice. Preferences are local to the browser, not account-synced. + +On desktop, windows support dragging, resizing, maximizing, minimizing, and +stacking. Use the dock to switch applications or **Show desktop** to hide/restore +open windows. At 700px and below, one active application occupies the available +screen, with the dock always accessible. The desktop and launcher scroll when +there are more applications than fit on screen. + +### Frontend structure + +| File | Responsibility | +| --- | --- | +| `src/public/js/desktop-preferences.js` | Theme metadata, versioned preference validation, storage, and early theme application | +| `src/public/js/desktop-layout.js` | Pure grid sizing, collision handling, and placement calculations | +| `src/public/js/desktop.js` | Shared application registry, window management, icon gestures, launcher, and Settings | +| `src/public/css/global.css` | Shared design tokens, theme chrome, application styling, and responsive presentation | +| `src/public/js/toggle.js` | Existing `toggleApp` compatibility entry point for UI extensions | + +Backend-provided UI icons and windows automatically join the registry. Existing +extension HTML and `invokeAction(moduleId, actionId)` continue to use the same +action endpoint. There are no new runtime dependencies for the desktop shell. + +### UI development and verification + +```bash +npm test # Type check and unit tests, including grid/preferences +npx playwright install chromium # Once, for browser tests +npm run test:ui # Chromium interaction and responsive-layout tests +npm run preview:ui # http://127.0.0.1:4173 +``` + +The UI preview and browser tests render the real templates with fixture meters +and an extension. They do not connect to MQTT, Ethereum, SSH, or publishing +services, and their mutation responses are simulated. Browser tests intentionally +block third-party resources for repeatability. Live external integrations still +require the normal configured application. If using an existing Chromium binary, +set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` to its absolute path. + --- # Extension System @@ -104,6 +435,26 @@ STREAMR_CRONSCHEDULE="0 * * * *" # Every hour - **`UI_MODULES`**: Comma-separated list of `moduleId:/` pairs - **Module-specific variables**: Each module can have its own configuration variables (e.g., `STREAMR_STREAM_ID`) +External references resolve consistently to `src/extensions//` and +`dist/extensions//`. `#branch` and `#tag` select the checkout revision; +the suffix is not part of the runtime import path. Backend and UI references to +the same repository share one checkout and must use the same revision. +Built-in `core/...` modules are never cloned. The legacy `MODULES` variable may +still specify extra repositories to install, but loading is controlled by +`BACKEND_MODULES` and `UI_MODULES`. + +For a local checkout, run `npm run modules:install` after setting the environment +variables. Docker runs the same installer automatically. A custom repository must +export a default extension from `index.ts` or CommonJS `index.js`. TypeScript +extensions compile with the console's `tsconfig.json`; their package dependencies +and runtime assets are copied alongside the compiled module. Installation errors +stop startup rather than leaving a silently missing backend module. + +The Compose module volumes now mount only `src/extensions` and `dist/extensions`. +They no longer mask the built-in code shipped in updated images. Existing meter +data remains on the same `.data` mount; old module volumes are left untouched and +configured external modules are downloaded into the new scoped volumes. + ### Publishing Custom Modules To use your own extensions: @@ -204,7 +555,7 @@ UI Hooks allow modules to extend the web interface at `http://localhost:3000`. M 1. **Create your module repository** with the following structure: ```typescript -// ui.ts (or index.ts) +// index.ts import type { UIHooks, UIAppIcon, UIAppWindow, UIAction } from "../../../types"; export default class implements UIHooks { @@ -484,3 +835,34 @@ Do it in one go: docker compose pull console docker compose up -d --force-recreate console ``` + +## Application appearance and local Docker updates + +Each application title bar has a **Theme / Light / Dark** selector. Preferences +are saved by application ID through the shared desktop preference store, and +survive desktop theme changes and reloads. Native content, dialogs, and terminal +colors follow the chosen palette. Embedded external websites retain their own +appearance controls; the containing window follows the application setting. + +To build and install the current checkout on the existing Linux Docker host: + +```sh +# First-time setup only: copy .env.example to .env and fill in your settings. +./install.sh +# If the existing deployment used a custom Compose project name: +./install.sh --project-name your-existing-project +``` + +Requires Docker with a current Compose plugin (`up --wait`). The script uses +`compose.yaml` plus `compose.local.yaml`, builds `m3tering-console:local` first, +then recreates **only the console service** and waits up to 240 seconds for the +HTTP authentication boundary to be ready. Mounted database and extension volumes, +`.env`, and other services are preserved. A build failure leaves the running +container untouched. A startup failure is reported; the script does not claim +success or delete data, and does not automatically roll back. Readiness does not +verify connectivity to external ChirpStack, MQTT, or chain services. + +Use the same Compose project name and checkout/data directory as the existing +installation so Compose replaces the intended service and reuses its volumes. +Standalone `docker run` containers are not removed by this script. The replacement +uses Compose's [documented recreate behavior](https://docs.docker.com/reference/cli/docker/compose/up/). diff --git a/compose.dev.yaml b/compose.dev.yaml index f526379..3f73d8a 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -10,9 +10,9 @@ services: - .env volumes: - ./.data-dev:/opt/app/.data - - console_dev_src_modules:/opt/app/src/lib - - console_dev_dist_modules:/opt/app/dist/lib + - console_dev_extension_sources:/opt/app/src/extensions + - console_dev_extension_builds:/opt/app/dist/extensions volumes: - console_dev_src_modules: - console_dev_dist_modules: + console_dev_extension_sources: + console_dev_extension_builds: diff --git a/compose.local.yaml b/compose.local.yaml new file mode 100644 index 0000000..377bafd --- /dev/null +++ b/compose.local.yaml @@ -0,0 +1,13 @@ +# Used by ./install.sh to deploy the current checkout with production data volumes. +services: + console: + image: m3tering-console:local + build: + context: . + dockerfile: Dockerfile + healthcheck: + test: ["CMD", "node", "scripts/healthcheck.cjs"] + interval: 5s + timeout: 4s + start_period: 30s + retries: 24 diff --git a/compose.yaml b/compose.yaml index 893e1ba..2d15b41 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,10 +9,10 @@ services: - "3000:3000" volumes: - ./.data:/opt/app/.data - - console_src_modules:/opt/app/src/lib - - console_dist_modules:/opt/app/dist/lib + - console_extension_sources:/opt/app/src/extensions + - console_extension_builds:/opt/app/dist/extensions volumes: console_db: - console_src_modules: - console_dist_modules: + console_extension_sources: + console_extension_builds: diff --git a/entrypoint.sh b/entrypoint.sh index d5c32ef..66a1968 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,85 +1,5 @@ #!/usr/bin/env sh set -e - -APP_DIR="/opt/app" -SRC_LIB="$APP_DIR/src/lib" -DIST_LIB="$APP_DIR/dist/lib" - -mkdir -p "$SRC_LIB" -mkdir -p "$DIST_LIB" - -if [ -n "$MODULES" ]; then - echo "Requested modules: $MODULES" - IFS=',' - - for repo in $MODULES; do - CLEAN_REPO=$(echo "$repo" | cut -d'#' -f1) - NAME=$(basename "$CLEAN_REPO") - VERSION=$(echo "$repo" | grep -o '#.*' | sed 's/#//') - - SRC_DEST="$SRC_LIB/$NAME" - DIST_DEST="$DIST_LIB/$NAME" - - # ----------------------------- - # 1️⃣ Download source if missing - # ----------------------------- - if [ -d "$SRC_DEST" ]; then - echo "✔ Module $NAME already downloaded" - else - echo "⬇ Downloading module: $NAME" - git clone --depth=1 "https://github.com/$CLEAN_REPO.git" "$SRC_DEST" - - if [ -n "$VERSION" ]; then - git -C "$SRC_DEST" fetch --tags - git -C "$SRC_DEST" checkout "$VERSION" - fi - fi - - # ----------------------------- - # 2️⃣ Install plugin dependencies (isolated) - # ----------------------------- - if [ -f "$SRC_DEST/package.json" ] && [ ! -d "$SRC_DEST/node_modules" ]; then - echo "📦 Installing dependencies for $NAME (isolated)" - cd "$SRC_DEST" - npm install --production - cd "$APP_DIR" - fi - - # ----------------------------- - # 3️⃣ Build or copy plugin - # ----------------------------- - if [ -f "$DIST_DEST/.built" ]; then - echo "🏁 Plugin $NAME already built" - continue - fi - - echo "🔧 Building plugin: $NAME" - mkdir -p "$DIST_DEST" - - # TypeScript project - if [ -f "$SRC_DEST/tsconfig.json" ]; then - npx tsc --project "$SRC_DEST/tsconfig.json" --outDir "$DIST_DEST" - - # Single TS file - elif [ -f "$SRC_DEST/index.ts" ]; then - npx tsc "$SRC_DEST/index.ts" --outDir "$DIST_DEST" - - # Plain JS project - else - cp -r "$SRC_DEST"/* "$DIST_DEST/" - fi - - # ----------------------------- - # 4️⃣ Copy plugin's node_modules to dist - # ----------------------------- - if [ -d "$SRC_DEST/node_modules" ]; then - echo "📦 Copying isolated dependencies for $NAME" - cp -r "$SRC_DEST/node_modules" "$DIST_DEST/" - fi - - # Mark as built to avoid rebuilding every restart - touch "$DIST_DEST/.built" - done -fi - +cd /opt/app +node scripts/install-modules.cjs exec "$@" diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..92d6e6e --- /dev/null +++ b/install.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Build first; replace only this Compose project's console service. Keep all data. +set -euo pipefail +project_args=() +case "${1:-}" in + --help|-h) + printf '%s\n' 'Usage: ./install.sh [--project-name NAME]' 'Builds this checkout, recreates the console container, and waits for readiness.' 'Use the existing Compose project name to update a deployment with a custom name.' + exit 0 ;; + --project-name) + if [[ $# != 2 || ! $2 =~ ^[a-z0-9][a-z0-9_-]*$ ]]; then + printf '%s\n' 'Provide a valid Compose project name.' >&2; exit 2 + fi + project_args=(--project-name "$2") ;; + '') ;; + *) printf '%s\n' 'Unknown option. Run ./install.sh --help.' >&2; exit 2 ;; +esac +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" +if [[ ! -f .env ]]; then + printf '%s\n' 'Missing .env. Copy .env.example to .env and configure your credentials and services first.' >&2 + exit 1 +fi +command -v docker >/dev/null || { printf '%s\n' 'Docker with the Compose plugin is required.' >&2; exit 1; } +docker compose version >/dev/null +docker info >/dev/null +compose=(docker compose "${project_args[@]}" -f compose.yaml -f compose.local.yaml) +"${compose[@]}" config --quiet +printf '%s\n' 'Building the current checkout. The running console stays available during the build.' +"${compose[@]}" build console +printf '%s\n' 'Replacing the console container and waiting for the new build to become ready…' +if ! "${compose[@]}" up --detach --no-deps --no-build --pull never --force-recreate --wait --wait-timeout 240 console; then + printf '%s\n' 'The replacement did not become ready. Data volumes were preserved.' 'Inspect the console logs with docker compose -f compose.yaml -f compose.local.yaml logs console (include your project name if set).' >&2 + exit 1 +fi +printf '%s\n' 'The current build is running. Your .env, database, and extension volumes are preserved.' +"${compose[@]}" ps console diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..a9ea754 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,3 @@ +module.exports = { + testPathIgnorePatterns: ['/node_modules/', '/tests/ui/.*\\.spec\\.cjs$'], +}; diff --git a/package-lock.json b/package-lock.json index bfa77aa..e64ffc5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "devDependencies": { "@babel/preset-env": "^7.28.3", "@babel/preset-typescript": "^7.27.1", + "@playwright/test": "1.61.1", "@types/better-sqlite3": "^7.6.13", "@types/express": "^4.17.21", "@types/jest": "^30.0.0", @@ -5090,6 +5091,22 @@ "url": "https://opencollective.com/pkgr" } }, + "node_modules/@playwright/test": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz", + "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@protobuf-ts/runtime": { "version": "2.11.1", "resolved": "https://registry.npmjs.org/@protobuf-ts/runtime/-/runtime-2.11.1.tgz", @@ -17696,6 +17713,53 @@ "node": ">=8" } }, + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/plimit-lit": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/plimit-lit/-/plimit-lit-3.0.1.tgz", diff --git a/package.json b/package.json index 73562d8..2e1a204 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,10 @@ "start": "node dist/index.js", "build": "tsc", "dev": "nodemon --exec ts-node src/index.ts", - "test": "tsc --noEmit && jest" + "test": "tsc --noEmit && jest", + "test:ui": "npm run build && playwright test", + "preview:ui": "npm run build && node tests/ui/serve.cjs", + "modules:install": "npm run build && node scripts/install-modules.cjs" }, "author": "Emmo00", "license": "MIT", @@ -31,6 +34,7 @@ "devDependencies": { "@babel/preset-env": "^7.28.3", "@babel/preset-typescript": "^7.27.1", + "@playwright/test": "1.61.1", "@types/better-sqlite3": "^7.6.13", "@types/express": "^4.17.21", "@types/jest": "^30.0.0", diff --git a/playwright.config.cjs b/playwright.config.cjs new file mode 100644 index 0000000..ba8e30b --- /dev/null +++ b/playwright.config.cjs @@ -0,0 +1,16 @@ +const { defineConfig } = require('@playwright/test'); +module.exports = defineConfig({ + testDir: './tests/ui', testMatch: '**/*.spec.cjs', timeout: 60000, + fullyParallel: false, workers: 1, + use: { + baseURL: 'http://127.0.0.1:4173', headless: true, + viewport: { width: 1440, height: 900 }, + launchOptions: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE ? { executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE } : {}, + screenshot: 'only-on-failure', trace: 'retain-on-failure', + }, + webServer: [ + { command: 'node tests/ui/serve.cjs', url: 'http://127.0.0.1:4173', reuseExistingServer: !process.env.CI }, + // Always own this fixture; reusing an interrupted run can lose its server mid-test. + { command: 'node tests/ui/serve-auth.cjs', url: 'http://127.0.0.1:4174', reuseExistingServer: false }, + ], +}); diff --git a/scripts/healthcheck.cjs b/scripts/healthcheck.cjs new file mode 100644 index 0000000..7a21205 --- /dev/null +++ b/scripts/healthcheck.cjs @@ -0,0 +1,9 @@ +// An authenticated HTTP boundary proves that the console listener has started. +const http = require('node:http'); +const host = process.env.CONSOLE_HOST; +const request = http.get({ hostname: !host || host === '0.0.0.0' ? '127.0.0.1' : host === '::' ? '::1' : host, + port: Number(process.env.PORT || 3000), path: '/', timeout: 2500 }, response => { + response.resume(); process.exitCode = response.statusCode === 401 && /^Basic /i.test(response.headers['www-authenticate'] || '') ? 0 : 1; +}); +request.on('timeout', () => request.destroy(new Error('timeout'))); +request.on('error', () => { process.exitCode = 1; }); diff --git a/scripts/install-modules.cjs b/scripts/install-modules.cjs new file mode 100644 index 0000000..05899ed --- /dev/null +++ b/scripts/install-modules.cjs @@ -0,0 +1,46 @@ +/* Uses the same parsed references and paths as the runtime loader. */ +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +function installModules({ appDir = path.resolve(__dirname, '..'), env = process.env, run = execFileSync } = {}) { + const { getModuleConfiguration } = require(path.join(appDir, 'dist/lib/modules.js')); + const { external } = getModuleConfiguration(env); + if (!external.length) return; + const execute = (command, args, cwd) => run(command, args, { cwd, stdio: 'inherit', env }); + for (const module of external) { + const source = path.join(appDir, 'src/extensions', module.repository); + const destination = path.join(appDir, 'dist/extensions', module.repository); + fs.mkdirSync(path.dirname(source), { recursive: true }); + if (!fs.existsSync(source)) { + const args = ['clone', '--depth=1']; + if (module.ref) args.push('--branch', module.ref); + execute('git', [...args, `https://github.com/${module.repository}.git`, source], appDir); + } else { + // Refresh the requested ref on every start; changing a tag/branch must not + // silently reuse an unrelated .built marker or a stale checkout. + execute('git', ['fetch', '--depth=1', 'origin', module.ref || 'HEAD'], source); + execute('git', ['checkout', '--detach', 'FETCH_HEAD'], source); + } + if (!fs.existsSync(path.join(source, 'index.ts')) && !fs.existsSync(path.join(source, 'index.js'))) { + throw new Error(`${module.repository} must export its extension from index.ts or index.js`); + } + if (fs.existsSync(path.join(source, 'package.json'))) { + execute('npm', [fs.existsSync(path.join(source, 'package-lock.json')) ? 'ci' : 'install', '--include=dev'], source); + } + fs.mkdirSync(destination, { recursive: true }); + fs.cpSync(source, destination, { + recursive: true, + filter: entry => path.basename(entry) !== '.git', + }); + // Plain JS entrypoints and assets are copied; TS modules are compiled below + // using the console's CommonJS settings and shared src/types.ts imports. + } + execute('npm', ['run', 'build'], appDir); +} + +module.exports = { installModules }; +if (require.main === module) { + require('dotenv/config'); + installModules(); +} diff --git a/src/index.ts b/src/index.ts index d870e54..75ec15a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,9 @@ import 'dotenv/config'; +import { validateConsoleAuth } from './services/auth'; import { handleUplinks } from './services/mqtt'; -import { contractsReady } from './services/contracts'; import { startServer } from './services/server'; import './services/ssh'; // attaches ssh and websocket to server -import { loadExtensionsFromConfig, loadUIExtensionsFromConfig, runHook } from './lib/utils'; +import { loadExtensionsFromConfig, loadUIExtensionsFromConfig, runHook, notifyHook } from './lib/utils'; import setupDatabase from './store/sqlite'; import { createLogger } from './utils/logger'; @@ -11,26 +11,28 @@ const logger = createLogger('[index]'); (async function () { try { + validateConsoleAuth(); logger.info('Starting application initialization(v1.0.0)...'); // Load extensions from config - await loadExtensionsFromConfig(); + const monitoringOnly = process.env.CONSOLE_MONITOR_ONLY === 'true'; + if (!monitoringOnly) await loadExtensionsFromConfig(); logger.info('Extensions loaded successfully'); // Load UI extensions - await loadUIExtensionsFromConfig(); + if (!monitoringOnly) await loadUIExtensionsFromConfig(); logger.info('UI extensions loaded successfully'); - await contractsReady(); + if (!monitoringOnly) await (await import('./services/contracts')).contractsReady(); - runHook('onBeforeInit'); + await runHook('onBeforeInit'); // Initialize database tables and jobs setupDatabase(); logger.info('Database setup completed'); - runHook('onDatabaseSetup'); + await runHook('onDatabaseSetup'); try { logger.info('Initializing MQTT handling...'); @@ -48,10 +50,10 @@ const logger = createLogger('[index]'); startServer(); - runHook('onAfterInit'); + await runHook('onAfterInit'); } catch (error) { logger.error('[fatal] Failed to initialize application:', error); - runHook('onInitError', error); + await notifyHook('onInitError', error); process.exit(1); } })(); diff --git a/src/lib/core/is_on/index.ts b/src/lib/core/is_on/index.ts index 040e0cf..0b4ae53 100644 --- a/src/lib/core/is_on/index.ts +++ b/src/lib/core/is_on/index.ts @@ -1,7 +1,11 @@ import type { Hooks } from "../../../types"; +import { getCrossChainRevenue, getOwedFromPriceContext } from "../../sync"; export default class implements Hooks { - isOnStateCompute(m3terId: number) { - return true; + async isOnStateCompute(m3terId: number): Promise { + const [revenue, owed] = await Promise.all([ + getCrossChainRevenue(m3terId), getOwedFromPriceContext(m3terId), + ]); + return revenue >= owed; } } diff --git a/src/lib/core/prover/index.ts b/src/lib/core/prover/index.ts index 61bc7e6..75c0c91 100644 --- a/src/lib/core/prover/index.ts +++ b/src/lib/core/prover/index.ts @@ -1,7 +1,7 @@ import cron from 'node-cron'; -import { pruneAndSyncOnchain } from '../../sync'; +import { getSyncedPendingTransactions } from '../../sync'; import { buildBatchPayload, retry } from '../../utils'; -import { getAllMeterRecords, getAllTransactionRecords, getTransactionByNonce } from '../../../store/sqlite'; +import { getAllTransactionRecords, getTransactionByNonce } from '../../../store/sqlite'; import type { BatchTransactionPayload, DecodedPayload, Hooks, TransactionRecord } from '../../../types'; import { createLogger } from '../../../utils/logger'; @@ -27,18 +27,7 @@ export default class implements Hooks { logger.info( `Prover cron job started: Pruning meters and sending pending transactions to the prover at ${PREFERRED_PROVER_NODE}...`, ); - const m3ters = getAllMeterRecords(); - for (const m3ter of m3ters) { - try { - pruneAndSyncOnchain(m3ter.publicKey); - } catch (error) { - logger.error(`Error pruning and syncing meter ${m3ter.publicKey}:`, error); - } - } - - logger.info('sending pending transactions to prover...'); - - const pendingTransactions = getAllTransactionRecords(); + const pendingTransactions = await getSyncedPendingTransactions(); const proverUrl = await this.getProverURL(); if (pendingTransactions.length > 0) { diff --git a/src/lib/core/streamr/index.ts b/src/lib/core/streamr/index.ts index 0a4812d..a3d7fae 100644 --- a/src/lib/core/streamr/index.ts +++ b/src/lib/core/streamr/index.ts @@ -1,9 +1,9 @@ import cron from "node-cron"; import { StreamrClient } from "@streamr/sdk"; -import { getAllMeterRecords, getAllTransactionRecords } from "../../../store/sqlite"; +import { getAllTransactionRecords } from "../../../store/sqlite"; import { buildBatchPayload, retry } from "../../utils"; import type { Hooks, TransactionRecord } from "../../../types"; -import { pruneAndSyncOnchain } from "../../sync"; +import { getSyncedPendingTransactions } from "../../sync"; import { createLogger } from "../../../utils/logger"; const logger = createLogger("[streamr]"); @@ -31,18 +31,7 @@ export default class implements Hooks { this.cronSchedule, async () => { logger.info("Streamr cron job started: Pruning meters and publishing pending transactions..."); - const m3ters = getAllMeterRecords(); - for (const m3ter of m3ters) { - try { - pruneAndSyncOnchain(m3ter.publicKey); - } catch (error) { - logger.error(`Error pruning and syncing meter ${m3ter.publicKey}:`, error); - } - } - - logger.info("Publishing pending transactions to Streamr..."); - - const pendingTransactions = await this.getPendingTransactions(); + const pendingTransactions = await getSyncedPendingTransactions(); if (pendingTransactions.length > 0) { await Promise.all( this.streamIds.map(async (STREAMR_STREAM_ID) => { diff --git a/src/lib/core/streamr/ui.ts b/src/lib/core/streamr/ui.ts index 2f584e8..42501ba 100644 --- a/src/lib/core/streamr/ui.ts +++ b/src/lib/core/streamr/ui.ts @@ -8,6 +8,14 @@ const logger = createLogger("[streamr-ui]"); const { ETHEREUM_PRIVATE_KEY } = process.env; +// Configuration values are text content in the extension's HTML presentation. +function escapeHtml(value: string): string { + const entities: Record = { + "&": "&", "<": "<", ">": ">", '"': """, "'": "'", + }; + return value.replace(/[&<>"']/g, (character) => entities[character]); +} + /** * Streamr UI Module * Provides UI components for the Streamr integration, including @@ -23,7 +31,7 @@ export default class implements UIHooks { return { id: "streamr", label: "Streamr", - iconHtml: '', + iconHtml: '', buttonClass: "is-primary", }; } @@ -38,47 +46,24 @@ export default class implements UIHooks { title: "Streamr Publisher", containerClass: "", contentHtml: ` -
-

Configuration

-
- Cron Schedule: - ${cronSchedule} -
-
- Stream IDs: -
    - ${streamIds.map((id) => `
  • ${id}
  • `).join("")} -
-
+
+
STREAMR NETWORK

Keep the data flowing.

+

Publish your pending meter transactions to connected streams.

+ ${pendingCount} pending
- -
-

Status

-
- Pending Transactions: - ${pendingCount} -
-
- Last Publish: - ${this.lastPublishTime ? this.lastPublishTime.toLocaleString() : "Never"} - ${this.lastPublishStatus ? `(${this.lastPublishStatus})` : ""} -
+
+
Pending transactions${pendingCount}
+
Last publish${this.lastPublishTime ? this.lastPublishTime.toLocaleString() : "Never"} + ${this.lastPublishStatus ? `${this.lastPublishStatus === "success" ? "Published successfully" : "Publish failed"}` : ""}
- -
- - +

Configuration

+
Publish schedule${escapeHtml(cronSchedule)}
+

Connected streams

+
    ${streamIds.map((id) => `
  • ${escapeHtml(id)}
  • `).join("") || '
  • No streams configured.
  • '}
+
+
+ +
`, }; diff --git a/src/lib/encode.ts b/src/lib/encode.ts index fa4e133..f3fdbbb 100644 --- a/src/lib/encode.ts +++ b/src/lib/encode.ts @@ -1,4 +1,4 @@ -import { State, TransactionRecord } from "../types"; +import { State } from "../types"; export function intToByteArray(num: number, byteLength: number = 4) { const byteArray = new Uint8Array(byteLength); @@ -70,21 +70,24 @@ export function encodeTransaction({ longitude: number; latitude: number; }) { - const encodedNonce = intToByteArray(nonce, 4); - const encodedEnergy = intToByteArray(energy * 10e6, 4); - const encodedSignature = stringToByteArray(signature, 64); - const encodedVoltage = intToByteArray(voltage * 10, 2); - const encodedDeviceId = stringToByteArray(deviceId, 32); - const encodedLongitude = intToByteArray(longitude * 10e5, 3); - const encodedLatitude = intToByteArray(latitude * 10e5, 3); - - return [ - ...encodedNonce, - ...encodedEnergy, - ...encodedSignature, - ...encodedVoltage, - ...encodedDeviceId, - ...encodedLongitude, - ...encodedLatitude, - ]; + const hexBytes = (value: string, length: number, name: string): Buffer => { + const raw = value.replace(/^0x/, ''); + if (!new RegExp(`^[0-9a-fA-F]{${length * 2}}$`).test(raw)) throw new Error(`${name} must contain ${length} hexadecimal bytes`); + return Buffer.from(raw, 'hex'); + }; + const scaled = (value: number, scale: number, name: string): number => { + if (!Number.isFinite(value)) throw new Error(`${name} must be finite`); + return Math.round(value * scale); + }; + if (!Number.isInteger(nonce) || nonce < 0) throw new Error('Nonce must be a non-negative integer'); + const result = Buffer.alloc(112); + result.writeUInt32BE(nonce, 0); + result.writeUInt32BE(scaled(energy, 1e6, 'Energy'), 4); + hexBytes(signature, 64, 'Signature').copy(result, 8); + result.writeUInt16BE(scaled(voltage, 10, 'Voltage'), 72); + hexBytes(deviceId, 32, 'Device ID').copy(result, 74); + // Signed 24-bit coordinates retain the existing device wire format. + result.writeIntBE(scaled(longitude, 1e5, 'Longitude'), 106, 3); + result.writeIntBE(scaled(latitude, 1e5, 'Latitude'), 109, 3); + return Array.from(result); } diff --git a/src/lib/modules.ts b/src/lib/modules.ts new file mode 100644 index 0000000..0151325 --- /dev/null +++ b/src/lib/modules.ts @@ -0,0 +1,45 @@ +import path from 'path'; + +export interface ModuleReference { + reference: string; + builtIn: boolean; + repository?: string; + ref?: string; +} + +export function parseModuleReference(input: string): ModuleReference { + const reference = input.trim(); + if (/^core\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(reference)) return { reference, builtIn: true }; + const match = /^([a-zA-Z0-9][a-zA-Z0-9_.-]*)\/([a-zA-Z0-9][a-zA-Z0-9_.-]*)(?:#([a-zA-Z0-9][a-zA-Z0-9_./-]*))?$/.exec(reference); + if (!match || match[3]?.split('/').some(part => !part || part === '.' || part === '..')) { + throw new Error(`Invalid module reference: ${reference}. Use core/name or owner/repository#branch-or-tag`); + } + return { reference, builtIn: false, repository: `${match[1]}/${match[2]}`, ref: match[3] }; +} + +export function getModuleConfiguration(env: NodeJS.ProcessEnv = process.env) { + const modules = (env.BACKEND_MODULES || '').split(',').map(value => value.trim()).filter(Boolean); + const uiModules: Record = Object.create(null); + for (const entry of (env.UI_MODULES || '').split(',').map(value => value.trim()).filter(Boolean)) { + const delimiter = entry.indexOf(':'); + const id = entry.slice(0, delimiter).trim(), reference = entry.slice(delimiter + 1).trim(); + if (delimiter < 1 || !/^[a-zA-Z0-9_-]+$/.test(id) || !reference) throw new Error(`Invalid UI module: ${entry}`); + if (Object.hasOwnProperty.call(uiModules, id)) throw new Error(`Duplicate UI module ID: ${id}`); + uiModules[id] = reference; + } + const references = [...modules, ...Object.values(uiModules), ...(env.MODULES || '').split(',').map(value => value.trim()).filter(Boolean)].map(parseModuleReference); + const repositories = new Map(); + for (const reference of references) { + if (reference.builtIn) continue; + const previous = repositories.get(reference.repository!); + if (previous && previous.ref !== reference.ref) throw new Error(`Conflicting versions for ${reference.repository}`); + repositories.set(reference.repository!, reference); + } + return { modules, uiModules, external: [...repositories.values()] }; +} + +export function resolveModulePath(libDirectory: string, reference: string): string { + const parsed = parseModuleReference(reference); + return parsed.builtIn ? path.resolve(libDirectory, parsed.reference) : + path.resolve(libDirectory, '..', 'extensions', parsed.repository!); +} diff --git a/src/lib/sync.ts b/src/lib/sync.ts index 38e40ac..7b2a4f9 100644 --- a/src/lib/sync.ts +++ b/src/lib/sync.ts @@ -1,7 +1,8 @@ import { getMeterByPublicKey, getMeterByTokenId, - getTransactionByNonce, + getAllMeterRecords, + getAllTransactionRecords, pruneTransactionsAfter, pruneTransactionsBefore, updateMeterNonce, @@ -120,7 +121,8 @@ export async function pruneAndSyncOnchain(meterIdentifier: number | string): Pro // If the onchain nonce is greater, update the local record updateMeterNonce(publicKey, onchainNonce); } - // prune transactions with nonce less than or equal to onchainNonce + // Retain the latest confirmed record for exact retransmission comparison. + // Scheduled publishers exclude it from their pending batches. pruneTransactionsBefore(onchainNonce, meter.tokenId); return onchainNonce; @@ -143,12 +145,12 @@ export async function getLatestTransactionNonce(meterIdentifier: number): Promis } // get revenue across supported chains -export async function getCrossChainRevenue(tokenId: number): Promise { +export async function getCrossChainRevenue(tokenId: number): Promise { try { // Use cached verifiers instead of fetching them each time const verifiers = await getCachedVerifiers(); - let totalRevenue = 0; + let totalRevenue = 0n; // Iterate through all cached verifiers and get revenue from each chain for (const verifier of verifiers) { @@ -164,13 +166,13 @@ export async function getCrossChainRevenue(tokenId: number): Promise { enableCcipRead: true, }), ); - const revenueAmount = Number(revenue); + const revenueAmount = BigInt(revenue); logger.info(`Revenue from ${verifier.ensName} (${verifier.verifierAddress}): ${revenueAmount}`); totalRevenue += revenueAmount; } catch (error) { logger.error(`Failed to get revenue from verifier ${verifier.ensName}:`, error); - // Continue with other verifiers even if one fails + throw error; // A partial total must not be used to decide a meter's balance. } } @@ -183,14 +185,14 @@ export async function getCrossChainRevenue(tokenId: number): Promise { } // get owed from price context -export async function getOwedFromPriceContext(tokenId: number): Promise { +export async function getOwedFromPriceContext(tokenId: number): Promise { try { return await retry(async () => { logger.info(`Getting owed amount for token ${tokenId} from price context`); // Call the price context to get the amount the user owes with CCIP read enabled const owedAmount = await priceContextContract.owed(tokenId); - const owed = Number(owedAmount); + const owed = BigInt(owedAmount); logger.info(`Owed amount for token ${tokenId}: ${owed}`); return owed; @@ -200,3 +202,13 @@ export async function getOwedFromPriceContext(tokenId: number): Promise throw error; } } + +/** Only publish records for meters whose chain synchronization succeeded. */ +export async function getSyncedPendingTransactions() { + const synced = new Map(); + for (const meter of getAllMeterRecords()) { + try { const nonce = await pruneAndSyncOnchain(meter.publicKey); synced.set(meter.tokenId, nonce); } + catch (error) { logger.error(`Could not synchronize meter ${meter.tokenId}:`, error); } + } + return getAllTransactionRecords().filter(record => synced.has(record.identifier) && record.nonce > synced.get(record.identifier)!); +} diff --git a/src/lib/utils.ts b/src/lib/utils.ts index eae218c..1e1b0c0 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,4 +1,4 @@ -import path from "path"; +import { getModuleConfiguration, resolveModulePath } from "./modules"; import { createPublicKey, verify } from "crypto"; import type { TransactionRecord, @@ -27,25 +27,13 @@ if (!UI_MODULES) { logger.warn("No UI_MODULES specified"); } -export const defaultConfigurations: AppConfig = { - modules: (BACKEND_MODULES || "").split(",").filter(Boolean), // ["core/arweave", "core/prover", "core/streamr", "core/is_on"], - uiModules: Object.fromEntries( - (UI_MODULES || "") - .split(",") - .filter(Boolean) - .map((entry) => { - const [moduleId, modulePath] = entry.split(":"); - return [moduleId, modulePath]; - }) - .filter(([moduleId, modulePath]) => moduleId && modulePath), - ), -}; +export const defaultConfigurations: AppConfig = getModuleConfiguration(); export async function loadExtensionsFromConfig(): Promise { const config: AppConfig = defaultConfigurations; for (const modulePath of config.modules) { - const resolved = path.resolve(__dirname, modulePath); + const resolved = resolveModulePath(__dirname, modulePath); const mod = await import(resolved); extensions.push(new mod.default()); @@ -57,19 +45,32 @@ export async function loadExtensionsFromConfig(): Promise { export async function runHook(hook: K, ...args: Parameters>) { let result: ReturnType> | boolean = true; + const errors: unknown[] = []; for (const ext of extensions) { const fn = ext[hook]; let functionReturn; - if (fn) functionReturn = await (fn as any).call(ext, ...args); + try { + if (fn) functionReturn = await (fn as any).call(ext, ...args); + } catch (error) { + errors.push(error); + logger.error(`Extension hook ${hook} failed:`, error); + } if (typeof functionReturn === "boolean" && hook === "isOnStateCompute") { result = result && functionReturn; } } + if (errors.length) throw new Error(`${errors.length} extension(s) failed in ${hook}`); return result; } +/** Observational hooks must never leave a rejected, unobserved promise. */ +export async function notifyHook(hook: K, ...args: Parameters>) { + try { await runHook(hook, ...args); } + catch (error) { logger.error(`Notification hook ${hook} failed:`, error); } +} + /** * Load UI extensions from configuration file * Looks for 'uiModules' key in config, which maps module IDs to their paths @@ -84,7 +85,7 @@ export async function loadUIExtensionsFromConfig(): Promise for (const [moduleId, modulePath] of Object.entries(config.uiModules)) { try { - const resolved = path.resolve(__dirname, modulePath); + const resolved = resolveModulePath(__dirname, modulePath); const mod = await import(resolved); const instance = new mod.default(); uiExtensions.set(moduleId, instance); diff --git a/src/m3ter/api.ts b/src/m3ter/api.ts new file mode 100644 index 0000000..859e5c7 --- /dev/null +++ b/src/m3ter/api.ts @@ -0,0 +1,138 @@ +import { Router, Request, Response, NextFunction } from 'express'; +import type http from 'http'; +import WebSocket from 'ws'; +import { registerSocket } from '../services/socket-router'; +import { applicationId, chirpstackRest, deviceDetails, deviceId, getDevice, listDevices, ManagerError } from './chirpstack'; +import { commandCatalogue, generateCommand } from './commands'; +import { checkActivity, inactiveMilliseconds, managerEvents, monitoring } from './monitor'; +import * as store from './store'; +import { managerAuthRouter, requireManagerAuth, managerAuthenticated, managerSessions } from './auth'; + +export const managerRouter = Router(); +managerRouter.use(managerAuthRouter); +managerRouter.use(requireManagerAuth); +const wrap = (handler: (req: Request, res: Response) => Promise | void) => (req: Request, res: Response, next: NextFunction) => Promise.resolve().then(() => handler(req, res)).catch(next); +function integer(value: unknown, fallback: number, min: number, max: number): number { + if (value === undefined) return fallback; + const n = Number(value); + if (typeof value !== 'string' || !/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min || n > max) throw new ManagerError('Invalid pagination or date range.'); + return n; +} +function commandInput(body: any) { + if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(key => !['commandId','value','confirmedSafety','requestId'].includes(key))) { + throw new ManagerError('Supply a supported command and parameter; raw payloads and FPorts are not accepted.'); + } + try { return generateCommand(body.commandId, body.value); } catch (error) { throw new ManagerError((error as Error).message); } +} +const busy = new Set(); +async function exclusive(devEui: string, work: () => Promise) { + if (busy.has(devEui)) throw new ManagerError('Another queue operation is in progress for this meter.', 409); + busy.add(devEui); try { await work(); } finally { busy.delete(devEui); } +} +managerRouter.get('/config', wrap((_req, res) => { + res.json({ commands: commandCatalogue, monitoring, inactiveMilliseconds: inactiveMilliseconds(), applicationId: applicationId(), + billingAutomationActive: process.env.CONSOLE_MONITOR_ONLY !== 'true' }); +})); +managerRouter.get('/devices', wrap(async (req, res) => { + const search = typeof req.query.search === 'string' ? req.query.search.trim() : ''; + if (search.length > 100) throw new ManagerError('Search is too long.'); + res.json(await listDevices(search, integer(req.query.offset, 0, 0, 1_000_000))); +})); +managerRouter.get('/devices/:devEui', wrap(async (req, res) => { + const devEui = deviceId(req.params.devEui), application = applicationId(); + const details = await deviceDetails(devEui); + store.updateDevice(application, devEui, details); + res.json({ device: details, state: store.deviceState(application, devEui), latest: store.latestReading(application, devEui) }); +})); +managerRouter.get('/devices/:devEui/history', wrap((req, res) => { + const devEui = deviceId(req.params.devEui), application = applicationId(); + const to = integer(req.query.to, Date.now(), 1, 8640000000000000); + const from = integer(req.query.from, to - 86400000, 0, to); + if (to - from > 366 * 86400000) throw new ManagerError('Choose a range of at most 366 days.'); + res.json({ ...store.history(application, devEui, from, to, integer(req.query.offset, 0, 0, 1_000_000), integer(req.query.limit, 50, 1, 100)), + latest: store.latestReading(application, devEui), state: store.deviceState(application, devEui), monitoring }); +})); +managerRouter.get('/devices/:devEui/events', wrap((req, res) => { + res.json({ events: store.events(applicationId(), deviceId(req.params.devEui), integer(req.query.offset, 0, 0, 1_000_000)) }); +})); +managerRouter.get('/devices/:devEui/commands', wrap((req, res) => { + res.json({ commands: store.commandHistory(applicationId(), deviceId(req.params.devEui), integer(req.query.offset, 0, 0, 1_000_000)) }); +})); +managerRouter.post('/commands/preview', wrap((req, res) => { res.json(commandInput(req.body)); })); +managerRouter.post('/devices/:devEui/commands', wrap(async (req, res) => { + const devEui = deviceId(req.params.devEui), application = applicationId(), command = commandInput(req.body); + if (command.requiresConfirmation && req.body.confirmedSafety !== true) throw new ManagerError('Explicit safety confirmation is required.'); + const id = req.body.requestId; + if (typeof id !== 'string' || !/^[a-f\d]{8}-[a-f\d]{4}-4[a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/i.test(id)) throw new ManagerError('A UUID requestId is required.'); + const fingerprint = JSON.stringify([devEui, command.id, command.value]); + const previous = store.getCommand(application, id); + if (previous) { + if (previous.fingerprint !== fingerprint) throw new ManagerError('This request ID belongs to a different command.', 409); + res.json(previous); return; + } + await exclusive(devEui, async () => { + await getDevice(devEui); + store.insertCommand(application, devEui, id, command, fingerprint); + try { + await chirpstackRest(`/api/devices/${devEui}/queue`, 'POST', { queueItem: { id, devEui, confirmed: false, fPort: command.fPort, data: command.data } }); + store.commandStatus(application, devEui, id, 'queued', 'Accepted by ChirpStack; delivery and execution are not verified'); + store.applicationEvent(application, devEui, 'command-queued', `${command.name} accepted into the downlink queue`); + } catch (error) { + const uncertain = !(error instanceof ManagerError) || error.uncertain; + store.commandStatus(application, devEui, id, uncertain ? 'unknown' : 'failed', uncertain ? 'Enqueue outcome unknown. Inspect the queue before creating another command.' : (error as Error).message); + } + managerEvents.emit('update', { type: 'device', devEui, kind: 'command' }); + res.json(store.getCommand(application, id)); + }); +})); +managerRouter.get('/devices/:devEui/queue', wrap(async (req, res) => { + const devEui = deviceId(req.params.devEui); await getDevice(devEui); + const queue = await chirpstackRest(`/api/devices/${devEui}/queue?limit=100&offset=0`); + const items = (Array.isArray(queue.result) ? queue.result : []).map((item: any) => ({ + id: item.id || null, fPort: item.fPort, data: item.data || '', hex: typeof item.data === 'string' ? Buffer.from(item.data, 'base64').toString('hex').toUpperCase() : '', + confirmed: item.confirmed === true, isPending: item.isPending === true, fCntDown: item.fCntDown ?? null, + expiresAt: item.expiresAt || null, createdAt: item.createdAt || null, + })); + res.json({ items, total: Number(queue.totalCount) || items.length }); +})); +managerRouter.delete('/devices/:devEui/queue', wrap(async (req, res) => { + const devEui = deviceId(req.params.devEui), application = applicationId(); + if (req.body?.confirmDevEui !== devEui) throw new ManagerError('Confirm the selected DevEUI to clear all pending downlinks.'); + await exclusive(devEui, async () => { + await getDevice(devEui); await chirpstackRest(`/api/devices/${devEui}/queue`, 'DELETE'); + store.clearedCommands(application, devEui); + store.applicationEvent(application, devEui, 'queue-cleared', 'All pending downlinks cleared. Previously transmitted commands cannot be recalled.'); + managerEvents.emit('update', { type: 'device', devEui, kind: 'queue' }); res.json({ cleared: true }); + }); +})); +managerRouter.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => { + res.status(error instanceof ManagerError ? error.status : 503).json({ error: error instanceof ManagerError ? error.message : 'Meter data is temporarily unavailable. Check database availability and retry.' }); +}); + +export function attachManagerStream(server: http.Server): void { + const wss = new WebSocket.Server({ noServer: true, maxPayload: 1024 }); + registerSocket(server, '/m3ter-manager/live', wss, managerAuthenticated); + const requests = new Map(); + const revoke = () => { for (const [ws, req] of requests) if (!managerAuthenticated(req)) { ws.close(4001, 'Sign in required'); requests.delete(ws); } }; + managerSessions.on('change', revoke); + const clients = new Map(); + const send = (ws: WebSocket, data: unknown) => { + if (ws.readyState === WebSocket.OPEN) { if (ws.bufferedAmount > 64 * 1024) ws.terminate(); else ws.send(JSON.stringify(data)); } + }; + const broadcast = (update: unknown) => { revoke(); for (const ws of clients.keys()) if (requests.has(ws)) send(ws, update); }; + managerEvents.on('update', broadcast); + wss.on('connection', (ws, req) => { + if (clients.size >= 100) { ws.close(1013, 'Too many monitoring clients'); return; } + requests.set(ws, req); clients.set(ws, true); send(ws, { type: 'connection', monitoring }); + ws.on('pong', () => clients.set(ws, true)); + ws.on('error', () => ws.terminate()); ws.on('close', () => { clients.delete(ws); requests.delete(ws); }); + ws.on('message', () => ws.close(1008, 'This is a receive-only monitoring stream')); + }); + const timer = setInterval(() => { + checkActivity(); + for (const [ws, alive] of clients) { if (!alive) { ws.terminate(); clients.delete(ws); } else { clients.set(ws, false); ws.ping(); } } + broadcast({ type: 'connection', monitoring }); + }, 30_000); + timer.unref(); + server.on('close', () => { clearInterval(timer); managerSessions.off('change', revoke); managerEvents.off('update', broadcast); for (const ws of clients.keys()) ws.terminate(); wss.close(); }); +} diff --git a/src/m3ter/auth.ts b/src/m3ter/auth.ts new file mode 100644 index 0000000..ff55f56 --- /dev/null +++ b/src/m3ter/auth.ts @@ -0,0 +1,63 @@ +import { createHash, randomBytes, timingSafeEqual } from 'crypto'; +import { EventEmitter } from 'events'; +import type { IncomingMessage } from 'http'; +import { Router, Request, Response, NextFunction } from 'express'; + +const cookie = 'm3ter_manager_session'; +const lifetime = 8 * 60 * 60 * 1000; +const sessions = new Map(); +const failures = new Map(); +export const managerSessions = new EventEmitter(); +const hash = (value: string) => createHash('sha256').update(value).digest(); +function configured() { return !!(process.env.M3TER_MANAGER_USERNAME && process.env.M3TER_MANAGER_PASSWORD); } +function identity() { return hash(JSON.stringify([process.env.M3TER_MANAGER_USERNAME, process.env.M3TER_MANAGER_PASSWORD])).toString('hex'); } +function token(req: IncomingMessage): string { + return (req.headers.cookie || '').split(';').map(part => part.trim()).find(part => part.startsWith(cookie + '='))?.slice(cookie.length + 1) || ''; +} +export function managerAuthenticated(req: IncomingMessage): boolean { + const session = sessions.get(token(req)); + return !!(configured() && session && session.expires > Date.now() && session.identity === identity()); +} +export function requireManagerAuth(req: Request, res: Response, next: NextFunction): void { + res.setHeader('Cache-Control', 'no-store'); + if (!managerAuthenticated(req)) { res.status(401).json({ error: 'Sign in to M3ter Manager to continue.' }); return; } + next(); +} +function setCookie(req: Request, res: Response, value: string, maxAge: number) { + res.cookie(cookie, value, { httpOnly: true, sameSite: 'strict', path: '/', maxAge, + secure: req.secure || process.env.CONSOLE_ORIGIN?.startsWith('https://') === true }); +} +export const managerAuthRouter = Router(); +managerAuthRouter.use((_req, res, next) => { res.setHeader('Cache-Control', 'no-store'); next(); }); +managerAuthRouter.get('/session', (req, res) => { + const authenticated = managerAuthenticated(req); + res.json({ authenticated, configured: configured(), username: authenticated ? process.env.M3TER_MANAGER_USERNAME : undefined }); +}); +managerAuthRouter.post('/session', (req, res) => { + if (!configured()) { res.status(503).json({ error: 'Set M3TER_MANAGER_USERNAME and M3TER_MANAGER_PASSWORD in .env, then restart the console.' }); return; } + const now = Date.now(), address = req.socket.remoteAddress || 'unknown'; + for (const [key, value] of failures) if (value.until <= now) failures.delete(key); + for (const [key, value] of sessions) if (value.expires <= now || value.identity !== identity()) sessions.delete(key); + const attempts = failures.get(address); + if (attempts && attempts.count >= 10) { res.setHeader('Retry-After', Math.ceil((attempts.until - now) / 1000)); res.status(429).json({ error: 'Too many sign-in attempts. Try again in 15 minutes.' }); return; } + const { username, password } = req.body || {}; + const validInput = typeof username === 'string' && typeof password === 'string' && username.length <= 256 && password.length <= 4096; + // Compare both fixed-length hashes, without exposing which field was incorrect. + const userMatches = timingSafeEqual(hash(validInput ? username : ''), hash(process.env.M3TER_MANAGER_USERNAME!)); + const passwordMatches = timingSafeEqual(hash(validInput ? password : ''), hash(process.env.M3TER_MANAGER_PASSWORD!)); + if (!validInput || !userMatches || !passwordMatches) { + if (failures.size >= 10000 && !failures.has(address)) { res.status(429).json({ error: 'Sign-in is temporarily busy. Try again later.' }); return; } + failures.set(address, { count: (attempts?.count || 0) + 1, until: attempts?.until || now + 900000 }); + // This form login is separate from the console's HTTP Basic challenge. + // A 401 here can evict the browser's Basic credentials and break WS upgrades. + res.status(403).json({ error: 'Incorrect username or password.' }); return; + } + failures.delete(address); + if (sessions.size >= 1000) { res.status(503).json({ error: 'Too many active sessions. Try again later.' }); return; } + sessions.delete(token(req)); + const value = randomBytes(32).toString('hex'); sessions.set(value, { expires: now + lifetime, identity: identity() }); + setCookie(req, res, value, lifetime); res.json({ authenticated: true }); managerSessions.emit('change'); +}); +managerAuthRouter.delete('/session', (req, res) => { + sessions.delete(token(req)); setCookie(req, res, '', 0); managerSessions.emit('change'); res.json({ authenticated: false }); +}); diff --git a/src/m3ter/chirpstack.ts b/src/m3ter/chirpstack.ts new file mode 100644 index 0000000..ed898f9 --- /dev/null +++ b/src/m3ter/chirpstack.ts @@ -0,0 +1,61 @@ +export class ManagerError extends Error { + constructor(message: string, public status = 400, public uncertain = false) { super(message); } +} +export function applicationId(): string { + const id = process.env.APPLICATION_ID; + if (!id || !/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(id)) throw new ManagerError('Configure APPLICATION_ID with your ChirpStack application UUID.', 503); + return id.toLowerCase(); +} +export function deviceId(value: unknown): string { + if (typeof value !== 'string' || !/^[\da-f]{16}$/i.test(value)) throw new ManagerError('DevEUI must contain exactly 16 hexadecimal characters.'); + return value.toLowerCase(); +} +export async function chirpstackRest(path: string, method = 'GET', body?: unknown): Promise { + if (!process.env.API_TOKEN || process.env.API_TOKEN === '...') throw new ManagerError('Configure the ChirpStack API_TOKEN on the console server.', 503); + let origin: URL; + try { + const host = process.env.CHIRPSTACK_HOST || 'localhost'; + origin = new URL(process.env.CHIRPSTACK_REST_URL || `http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:8090`); + if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash) throw new Error(); + } catch { throw new ManagerError('CHIRPSTACK_REST_URL must be an HTTP(S) origin without credentials or a path.', 503); } + let response: globalThis.Response; + try { + response = await fetch(new URL(path, origin), { method, redirect: 'error', signal: AbortSignal.timeout(10_000), + headers: { Authorization: `Bearer ${process.env.API_TOKEN}`, 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); + } catch { throw new ManagerError('ChirpStack REST proxy is unreachable or timed out. Check its address and service status.', 502, method !== 'GET'); } + if (!response.ok) { + const message = response.status === 401 || response.status === 403 ? 'ChirpStack rejected the API token or its permissions.' : + response.status === 404 ? 'The device or ChirpStack REST endpoint was not found.' : 'ChirpStack rejected the request. Refresh the queue before retrying.'; + throw new ManagerError(message, response.status === 404 ? 404 : 502, method !== 'GET' && response.status >= 500); + } + if (response.status === 204) return {}; + try { const text = await response.text(); return text ? JSON.parse(text) : {}; } + catch { throw new ManagerError('ChirpStack returned an invalid response.', 502, method !== 'GET'); } +} +export async function listDevices(search: string, offset: number) { + const query = new URLSearchParams({ applicationId: applicationId(), limit: '50', offset: String(offset), search }); + const result = await chirpstackRest(`/api/devices?${query}`); + return { total: Number(result.totalCount) || 0, offset, limit: 50, devices: (Array.isArray(result.result) ? result.result : []).map((device: any) => ({ + devEui: deviceId(device.devEui), name: String(device.name || device.devEui), deviceProfileName: device.deviceProfileName || null, + deviceProfileId: device.deviceProfileId || null, lastSeenAt: device.lastSeenAt || null, description: device.description || null, + })) }; +} +export async function getDevice(devEui: string) { + const result = await chirpstackRest(`/api/devices/${deviceId(devEui)}`); + if (result.device?.applicationId !== applicationId()) throw new ManagerError('This meter is outside the configured application.', 403); + return result; +} +export async function deviceDetails(devEui: string) { + const result = await getDevice(devEui); + const device = result.device; + const [profile, application] = await Promise.allSettled([ + chirpstackRest(`/api/device-profiles/${encodeURIComponent(device.deviceProfileId || '')}`), + chirpstackRest(`/api/applications/${applicationId()}`), + ]); + const phase = device.tags?.phaseMode; + return { devEui, name: device.name || devEui, description: device.description || null, applicationId: applicationId(), + applicationName: application.status === 'fulfilled' ? application.value.application?.name || null : null, + deviceProfileId: device.deviceProfileId || null, deviceProfileName: profile.status === 'fulfilled' ? profile.value.deviceProfile?.name || null : null, + enabledClass: result.enabledClass || null, lastSeenAt: result.lastSeenAt || null, isDisabled: device.isDisabled === true, + phaseMode: ['three-phase', 'phase-a', 'phase-b', 'phase-c'].includes(phase) ? phase : null }; +} diff --git a/src/m3ter/commands.ts b/src/m3ter/commands.ts new file mode 100644 index 0000000..93cd34a --- /dev/null +++ b/src/m3ter/commands.ts @@ -0,0 +1,45 @@ +export type CommandDefinition = { + id: string; name: string; category: string; fPort: 2 | 3; code: number; + description: string; confirmation?: string; options?: { value: number; label: string }[]; + min?: number; max?: number; defaultValue?: number; +}; +const gain = [1, 2, 4].map(value => ({ value, label: `×${value}` })); +const billing = 'The relay will change state, the energy accumulator will reset to zero, and the nonce will increment.'; +export const commandCatalogue: CommandDefinition[] = [ + { id: 'relay-on', name: 'Relay ON', category: 'Relay control', fPort: 2, code: 0x1b, description: 'Close the relay. Energy and nonce remain unchanged.' }, + { id: 'relay-off', name: 'Relay OFF', category: 'Relay control', fPort: 2, code: 0x1c, description: 'Open the relay. Energy and nonce remain unchanged.' }, + { id: 'billing-disconnect', name: 'Disconnect (Billing)', category: 'Billing connectivity', fPort: 2, code: 0, description: 'Open the relay and reset the billing accumulator.', confirmation: billing }, + { id: 'billing-connect', name: 'Connect (Billing)', category: 'Billing connectivity', fPort: 2, code: 1, description: 'Close the relay and reset the billing accumulator.', confirmation: billing }, + { id: 'report-interval', name: 'Set report interval', category: 'Reporting configuration', fPort: 2, code: 2, min: 10, max: 65535, defaultValue: 60, description: 'Set the reporting interval in seconds. Values below 60 seconds consume more LoRaWAN airtime.' }, + { id: 'restart', name: 'Restart meter', category: 'Maintenance', fPort: 2, code: 0x1d, description: 'Software reset and rejoin; telemetry may stop for approximately 10–60 seconds.', confirmation: 'Restart this meter? Telemetry may stop while it restarts and rejoins. Enqueueing does not confirm a restart.' }, + { id: 'relay-drive', name: 'Relay drive level', category: 'Relay hardware', fPort: 2, code: 0x1e, options: [{ value: 1, label: 'Active high' }, { value: 0, label: 'Active low' }], description: 'Set the output level that activates the physical relay.', confirmation: 'An incorrect drive level can invert relay ON/OFF behavior. Check the physical driver circuit before continuing.' }, + { id: 'relay-fitted', name: 'Relay fitted', category: 'Relay hardware', fPort: 2, code: 0x1f, options: [{ value: 1, label: 'Relay fitted' }, { value: 0, label: 'No relay fitted' }], description: 'Configure whether a relay is installed.', confirmation: 'When no relay is fitted, firmware ignores disconnect commands. Confirm the actual hardware configuration.' }, + { id: 'current-gain', name: 'Current gain (PGA)', category: 'Amplifier gain', fPort: 2, code: 0x20, options: gain, description: 'Firmware converts saved calibration. For 2000:1 CTs and a 5.6 Ω burden, ×2 suits up to approximately 128 A; ×4 suits lighter loads up to approximately 64 A.' }, + { id: 'voltage-gain', name: 'Voltage gain (PGA)', category: 'Amplifier gain', fPort: 2, code: 0x21, options: gain, description: 'Set voltage-channel gain. The normal configuration is ×1.' }, + { id: 'phase-mode', name: 'Phase mode', category: 'Phase configuration', fPort: 2, code: 0x22, options: [{ value: 0, label: 'Three-phase' }, { value: 1, label: 'Phase A' }, { value: 2, label: 'Phase B' }, { value: 3, label: 'Phase C' }], description: 'Select reported phases without resetting energy. Three-phase reports total energy and the SUM of phase voltages (about 690 V on a 230 V system). A queued mode is not verified configuration.' }, + { id: 'class-a', name: 'Switch to Class A', category: 'LoRaWAN class', fPort: 3, code: 0, description: 'Downlinks become available only after an uplink.', confirmation: 'Switch to Class A? Future downlinks must wait for an uplink. Class C is the normal operating mode.' }, + { id: 'class-c', name: 'Switch to Class C', category: 'LoRaWAN class', fPort: 3, code: 2, description: 'Request the normal Class C operating mode. A reachable Class C meter can receive downlinks without waiting for an uplink.' }, +]; + +export function generateCommand(id: unknown, value?: unknown) { + const command = commandCatalogue.find(item => item.id === id); + if (!command) throw new Error('Unsupported command'); + const bytes = [command.code]; + if (command.min !== undefined || command.options) { + if (typeof value !== 'number' || !Number.isInteger(value)) throw new Error('An integer parameter is required'); + if (command.options) { + if (!command.options.some(option => option.value === value)) throw new Error('Unsupported parameter value'); + bytes.push(value); + } else { + if (value < command.min! || value > command.max!) throw new Error('Report interval must be 10–65535 seconds'); + bytes.push(value >> 8, value & 255); + } + } else if (value !== undefined && value !== null) throw new Error('This command takes no parameters'); + const expectedLength = command.min !== undefined ? 3 : command.options ? 2 : 1; + if (bytes.length !== expectedLength || ![2, 3].includes(command.fPort)) throw new Error('Invalid command frame'); + const payload = Buffer.from(bytes); + return { id: command.id, name: command.name, description: command.description, fPort: command.fPort, + hex: payload.toString('hex').toUpperCase(), data: payload.toString('base64'), length: payload.length, + value: value ?? null, parameter: command.options?.find(option => option.value === value)?.label || (command.min !== undefined ? `${value} seconds` : null), + requiresConfirmation: !!command.confirmation, confirmation: command.confirmation || null, confirmed: false }; +} diff --git a/src/m3ter/decoder.ts b/src/m3ter/decoder.ts new file mode 100644 index 0000000..571ef4e --- /dev/null +++ b/src/m3ter/decoder.ts @@ -0,0 +1,23 @@ +import { decodePayload } from '../lib/decode'; +import { verifyPayloadSignature } from '../lib/utils'; + +export type Telemetry = { + decoder: string; nonce: number; rawEnergy: number; energy: number; rawVoltage: number; voltage: number; + signature: string; publicKey: string | null; verificationKey: string | null; verification: 'verified' | 'invalid' | 'unverified'; +}; +// Additional firmware ports can register their own decoder without changing raw event storage. +export const telemetryDecoders = new Map Telemetry>([[2, (data, knownKey) => { + if (![74, 106].includes(data.length)) throw new Error('FPort 2 requires exactly 74 or 106 bytes'); + const decoded = decodePayload(data); + const publicKey = decoded.extensions.deviceId || null; + const key = knownKey || publicKey; + const verification = key ? (verifyPayloadSignature(data, Buffer.from(key.replace(/^0x/, ''), 'hex')) ? 'verified' : 'invalid') : 'unverified'; + return { decoder: 'switch-cumulus-v1', nonce: decoded.nonce, rawEnergy: data.readUInt32BE(4), energy: decoded.energy, + rawVoltage: data.readUInt16BE(72), voltage: decoded.extensions.voltage!, signature: decoded.signature, publicKey, verificationKey: key?.replace(/^0x/, '') || null, verification }; +}]]); + +export function decodeTelemetry(fPort: number, data: Buffer, knownKey?: string): Telemetry { + const decode = telemetryDecoders.get(fPort); + if (!decode) throw new Error(`No telemetry decoder for FPort ${fPort}`); + return decode(data, knownKey); +} diff --git a/src/m3ter/monitor.ts b/src/m3ter/monitor.ts new file mode 100644 index 0000000..f0ec14e --- /dev/null +++ b/src/m3ter/monitor.ts @@ -0,0 +1,96 @@ +import { EventEmitter } from 'events'; +import { createHash, randomUUID } from 'crypto'; +import { decodeTelemetry } from './decoder'; +import * as store from './store'; +import { applicationId, deviceId } from './chirpstack'; +import { getMeterByDevEui } from '../store/sqlite'; + +export const managerEvents = new EventEmitter(); +managerEvents.setMaxListeners(128); +export const monitoring = { state: 'disconnected', lastMessage: null as number | null, error: null as string | null, since: Date.now() }; +export function inactiveMilliseconds(): number { + const seconds = Number(process.env.M3TER_INACTIVE_SECONDS || 300); + return (Number.isFinite(seconds) && seconds >= 10 ? seconds : 300) * 1000; +} +export function connectionState(state: string, error: string | null = null): void { + const changed = monitoring.state !== state; + Object.assign(monitoring, { state, error, since: Date.now() }); + if (changed) { + try { store.applicationEvent(applicationId(), null, 'mqtt', `MQTT ${state}${error ? ': ' + error : ''}`); } catch { /* Startup/configuration errors remain visible in status. */ } + managerEvents.emit('update', { type: 'connection', monitoring }); + } +} +export function validLocation(value: any): { latitude: number; longitude: number } | null { + if (!value || typeof value.latitude !== 'number' || typeof value.longitude !== 'number' || + !Number.isFinite(value.latitude) || !Number.isFinite(value.longitude) || Math.abs(value.latitude) > 90 || Math.abs(value.longitude) > 180) return null; + return { latitude: value.latitude, longitude: value.longitude }; +} +export function ingestEvent(topic: string, blob: Buffer): boolean { + let application: string; + try { application = applicationId(); } catch { return false; } + let devEui: string | null = null; + try { + if (blob.length > 512 * 1024) throw new Error('MQTT event exceeds the size limit'); + const parts = topic.match(/^application\/([^/]+)\/device\/([\da-f]{16})\/event\/(up|ack|txack|join|location|log|status)$/i); + if (!parts || parts[1].toLowerCase() !== application) return false; + monitoring.lastMessage = Date.now(); + const event = JSON.parse(blob.toString()); + devEui = deviceId(event.deviceInfo?.devEui); + if (devEui !== parts[2].toLowerCase() || event.deviceInfo?.applicationId?.toLowerCase() !== application) throw new Error('MQTT topic and device identity do not match'); + const receivedAt = Date.now(), parsedTime = Date.parse(event.time); + const timestamp = Number.isFinite(parsedTime) && parsedTime > 0 && parsedTime < receivedAt + 300_000 ? parsedTime : receivedAt; + const kind = parts[3].toLowerCase(); + const identity = event.deduplicationId || (event.time ? [event.time, event.fCnt, event.devAddr, event.data, event.queueItemId, event.acknowledged, event.downlinkId] : randomUUID()); + const eventKey = createHash('sha256').update(JSON.stringify([devEui, kind, identity])).digest('hex'); + const rx = Array.isArray(event.rxInfo) ? event.rxInfo[0] : null; + const metadata: Record = { sourceTime: typeof event.time === 'string' ? event.time.slice(0,100) : null, timestampSource: timestamp === parsedTime ? 'ChirpStack' : 'console receipt', name: String(event.deviceInfo.deviceName || devEui).slice(0, 200), + applicationName: String(event.deviceInfo.applicationName || '').slice(0, 200), deviceProfileName: String(event.deviceInfo.deviceProfileName || '').slice(0, 200), + fCnt: Number.isInteger(event.fCnt) ? event.fCnt : null, rssi: typeof rx?.rssi === 'number' ? rx.rssi : null, + snr: typeof rx?.snr === 'number' ? rx.snr : null, gatewayId: typeof rx?.gatewayId === 'string' ? rx.gatewayId.slice(0, 32) : null }; + const rawPayload = typeof event.data === 'string' ? event.data.slice(0, 4096) : null; + const record: store.ManagerEvent = { application, devEui, kind, source: 'ChirpStack', timestamp, receivedAt, eventKey, rawPayload, + fPort: Number.isInteger(event.fPort) ? event.fPort : null, metadata, message: `ChirpStack ${kind} event` }; + let inserted: boolean; + if (kind === 'up') { + let telemetry; + try { + if (!rawPayload || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(rawPayload) || rawPayload !== event.data) throw new Error('Invalid Base64 payload'); + const knownKey = store.deviceState(application, devEui)?.publicKey || getMeterByDevEui(devEui)?.publicKey; + telemetry = decodeTelemetry(event.fPort, Buffer.from(rawPayload, 'base64'), knownKey); + record.message = telemetry.verification === 'invalid' ? 'Telemetry decoded; signature INVALID. Voltage is outside the signed fields.' : 'Uplink decoded'; + } catch (error) { record.kind = 'decode-error'; record.message = (error as Error).message; } + inserted = store.recordUplink(record, telemetry, inactiveMilliseconds()); + } else { + if (kind === 'location') { + const location = validLocation(event.location); + if (location) { + if (timestamp >= (store.deviceState(application, devEui)?.metadata?.locationTime || 0)) { + metadata.location = location; metadata.locationTime = timestamp; + } + record.message = 'Device location received from ChirpStack'; + } + } + if (kind === 'log') record.message = `ChirpStack diagnostic: ${String(event.code || 'unknown').slice(0, 80)}`; + if (kind === 'ack') record.message = event.acknowledged === true ? 'Confirmed downlink acknowledged by device; command execution is not verified' : 'Downlink was not acknowledged'; + if (kind === 'txack') record.message = 'Gateway reported downlink transmission; device delivery is not confirmed'; + inserted = store.addEvent(record) !== null; + if (inserted) { + store.updateDevice(application, devEui, metadata); + if (typeof event.queueItemId === 'string' && ['ack', 'txack'].includes(kind)) { + store.commandStatus(application, devEui, event.queueItemId, + kind === 'txack' ? 'transmitted' : event.acknowledged === true ? 'delivered' : 'failed', record.message); + } + } + } + if (inserted) managerEvents.emit('update', { type: 'device', devEui, kind: record.kind, timestamp }); + return inserted; + } catch { + // Do not persist an untrusted identity when the topic and payload disagree. + try { store.applicationEvent(application, null, 'diagnostic', 'Malformed MQTT event ignored; check event JSON and device identity.'); } catch { /* Database failures must not crash MQTT. */ } + managerEvents.emit('update', { type: 'diagnostic', message: 'Unable to process an MQTT event. Check diagnostics and database availability.' }); + return false; + } +} +export function checkActivity(): void { + try { store.markInactive(applicationId(), inactiveMilliseconds()); } catch { /* Exposed by API error and next reconnect. */ } +} diff --git a/src/m3ter/store.ts b/src/m3ter/store.ts new file mode 100644 index 0000000..46da7b4 --- /dev/null +++ b/src/m3ter/store.ts @@ -0,0 +1,145 @@ +import type { Database } from 'better-sqlite3'; +import { randomUUID } from 'crypto'; +import type { Telemetry } from './decoder'; +let db: Database; +export function initializeManagerStore(connection: Database): void { + db = connection; + db.exec(` + CREATE TABLE IF NOT EXISTS manager_devices (application TEXT, devEui TEXT, metadata TEXT NOT NULL DEFAULT '{}', publicKey TEXT, + lastUplink INTEGER, activity TEXT, PRIMARY KEY(application, devEui)); + CREATE TABLE IF NOT EXISTS manager_events (id INTEGER PRIMARY KEY, application TEXT NOT NULL, devEui TEXT, + timestamp INTEGER NOT NULL, receivedAt INTEGER NOT NULL, kind TEXT NOT NULL, source TEXT NOT NULL, + eventKey TEXT NOT NULL, rawPayload TEXT, fPort INTEGER, metadata TEXT NOT NULL, message TEXT NOT NULL, + UNIQUE(application,eventKey)); + CREATE INDEX IF NOT EXISTS manager_events_device_time ON manager_events(application,devEui,timestamp DESC,id DESC); + CREATE TABLE IF NOT EXISTS manager_readings (id INTEGER PRIMARY KEY, application TEXT NOT NULL, devEui TEXT NOT NULL, + timestamp INTEGER NOT NULL, receivedAt INTEGER NOT NULL, fPort INTEGER NOT NULL, nonce INTEGER NOT NULL, + rawEnergy INTEGER NOT NULL, energy REAL NOT NULL, rawVoltage INTEGER NOT NULL, voltage REAL NOT NULL, + signature TEXT NOT NULL, publicKey TEXT, verification TEXT NOT NULL, decoded TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS manager_readings_device_time ON manager_readings(application,devEui,timestamp DESC,id DESC); + CREATE TABLE IF NOT EXISTS manager_commands (id TEXT PRIMARY KEY, application TEXT NOT NULL, devEui TEXT NOT NULL, + timestamp INTEGER NOT NULL, updatedAt INTEGER NOT NULL, actor TEXT NOT NULL, command TEXT NOT NULL, + fingerprint TEXT NOT NULL, status TEXT NOT NULL, detail TEXT, queueId TEXT); + CREATE INDEX IF NOT EXISTS manager_commands_device_time ON manager_commands(application,devEui,timestamp DESC); + CREATE INDEX IF NOT EXISTS manager_commands_queue ON manager_commands(application,devEui,queueId); + `); + // A process may have stopped after the upstream accepted a command. Never resend automatically. + db.prepare("UPDATE manager_commands SET status='unknown', detail='Console restarted during enqueue; inspect the queue before retrying' WHERE status='enqueuing'").run(); +} +export type ManagerEvent = { application: string; devEui: string | null; timestamp: number; receivedAt: number; + kind: string; source: string; eventKey: string; rawPayload?: string | null; fPort?: number | null; metadata: Record; message: string }; +export function addEvent(event: ManagerEvent): number | null { + const result = db.prepare(`INSERT OR IGNORE INTO manager_events(application,devEui,timestamp,receivedAt,kind,source,eventKey,rawPayload,fPort,metadata,message) + VALUES(@application,@devEui,@timestamp,@receivedAt,@kind,@source,@eventKey,@rawPayload,@fPort,@metadata,@message)`) + .run({ ...event, rawPayload: event.rawPayload ?? null, fPort: event.fPort ?? null, metadata: JSON.stringify(event.metadata) }); + return result.changes ? Number(result.lastInsertRowid) : null; +} +export function applicationEvent(application: string, devEui: string | null, kind: string, message: string): void { + addEvent({ application, devEui, kind, message, source: 'console observation', eventKey: randomUUID(), timestamp: Date.now(), receivedAt: Date.now(), metadata: {} }); +} +export function deviceState(application: string, devEui: string): any { + const row: any = db.prepare('SELECT * FROM manager_devices WHERE application=? AND devEui=?').get(application, devEui); + return row ? { ...row, metadata: JSON.parse(row.metadata) } : null; +} +export function updateDevice(application: string, devEui: string, metadata: Record): void { + const previous = deviceState(application, devEui); + db.prepare(`INSERT INTO manager_devices(application,devEui,metadata) VALUES(?,?,?) + ON CONFLICT(application,devEui) DO UPDATE SET metadata=excluded.metadata`).run(application, devEui, JSON.stringify({ ...previous?.metadata, ...metadata })); +} +export function recordUplink(event: ManagerEvent, telemetry?: Telemetry, inactiveAfter = 300000): boolean { + return db.transaction(() => { + const id = addEvent(event); if (id === null) return false; + const old = deviceState(event.application, event.devEui!); + updateDevice(event.application, event.devEui!, event.metadata); + const recent = Math.max(event.timestamp, old?.lastUplink || 0) >= Date.now() - inactiveAfter; + if (recent && (!old?.lastUplink || old.activity === 'inactive')) applicationEvent(event.application, event.devEui, 'active', 'Uplink observed after no recent activity'); + db.prepare('UPDATE manager_devices SET lastUplink=MAX(COALESCE(lastUplink,0),?),activity=? WHERE application=? AND devEui=?') + .run(event.timestamp, recent ? 'active' : 'inactive', event.application, event.devEui); + if (!telemetry) return true; + db.prepare(`INSERT INTO manager_readings(id,application,devEui,timestamp,receivedAt,fPort,nonce,rawEnergy,energy,rawVoltage,voltage,signature,publicKey,verification,decoded) + VALUES(@id,@application,@devEui,@timestamp,@receivedAt,@fPort,@nonce,@rawEnergy,@energy,@rawVoltage,@voltage,@signature,@publicKey,@verification,@decoded)`) + .run({ id, application: event.application, devEui: event.devEui, timestamp: event.timestamp, receivedAt: event.receivedAt, fPort: event.fPort, + nonce: telemetry.nonce, rawEnergy: telemetry.rawEnergy, energy: telemetry.energy, rawVoltage: telemetry.rawVoltage, voltage: telemetry.voltage, + signature: telemetry.signature, publicKey: telemetry.publicKey, verification: telemetry.verification, decoded: JSON.stringify(telemetry) }); + if (telemetry.verificationKey && telemetry.verification === 'verified' && !old?.publicKey) { + db.prepare('UPDATE manager_devices SET publicKey=? WHERE application=? AND devEui=?').run(telemetry.verificationKey, event.application, event.devEui); + applicationEvent(event.application, event.devEui, 'public-key', telemetry.publicKey ? 'Public key received; signature over nonce and energy verified (first-seen key)' : 'Existing console public key reused to verify nonce and energy'); + } + return true; + })(); +} +export function markInactive(application: string, threshold: number): void { + db.transaction(() => { + const rows: any[] = db.prepare("SELECT devEui FROM manager_devices WHERE application=? AND activity='active' AND lastUplinkpreviousNonce THEN rawEnergy/1000000.0 + ELSE MAX(0,rawEnergy-highWater)/1000000.0 END AS intervalEnergy, + CASE WHEN previousNonce IS NULL THEN 'initial-baseline' + WHEN noncepreviousNonce THEN 'new-cycle' + WHEN rawEnergy=@from + ) `; + const rows = db.prepare(ledger + `SELECT r.*,e.rawPayload,e.metadata FROM selected r JOIN manager_events e ON e.id=r.id + ORDER BY r.timestamp DESC,r.id DESC LIMIT @limit OFFSET @offset`).all({ ...args, limit, offset }); + const chart = db.prepare(ledger + `SELECT timestamp,energy,voltage,nonce,segment,intervalEnergy,accounting FROM selected + WHERE (rn-1) % MAX(1,CAST((total+399)/400 AS INTEGER))=0 OR rn=total ORDER BY timestamp,id`).all(args); + const summary: any = db.prepare(ledger + `SELECT COUNT(*) AS reports, COALESCE(SUM(intervalEnergy),0) AS observedConsumption, + COALESCE(SUM(accounting='new-cycle'),0) AS resets, + COALESCE(SUM(accounting IN ('nonce-regression','below-high-water')),0) AS uncertainReports, + COALESCE(SUM(accounting='repeated-total'),0) AS repeatedReports FROM selected`).get(args); + const total = summary.reports; + return { rows, chart, total, offset, limit, summary, sampled: total > chart.length }; +} +export function events(application: string, devEui: string, offset = 0): any[] { + return db.prepare(`SELECT * FROM manager_events WHERE application=? AND (devEui=? OR devEui IS NULL) + ORDER BY timestamp DESC,id DESC LIMIT 100 OFFSET ?`).all(application, devEui, offset); +} +export function getCommand(application: string, id: string): any { + const row: any = db.prepare('SELECT * FROM manager_commands WHERE application=? AND id=?').get(application, id); + return row ? { ...row, command: JSON.parse(row.command) } : null; +} +export function commandHistory(application: string, devEui: string, offset = 0): any[] { + return (db.prepare('SELECT * FROM manager_commands WHERE application=? AND devEui=? ORDER BY timestamp DESC LIMIT 50 OFFSET ?').all(application, devEui, offset) as any[]) + .map(row => ({ ...row, command: JSON.parse(row.command) })); +} +export function insertCommand(application: string, devEui: string, id: string, command: unknown, fingerprint: string): void { + db.prepare(`INSERT INTO manager_commands(id,application,devEui,timestamp,updatedAt,actor,command,fingerprint,status,queueId) + VALUES(?,?,?,?,?,?,?,?,?,?)`).run(id, application, devEui, Date.now(), Date.now(), process.env.M3TER_MANAGER_USERNAME || 'manager', JSON.stringify(command), fingerprint, 'enqueuing', id); +} +export function commandStatus(application: string, devEui: string, queueId: string, status: string, detail: string): void { + const predicate = status === 'queued' ? "status='enqueuing'" : "status NOT IN ('delivered','failed')"; + db.prepare(`UPDATE manager_commands SET status=?,detail=?,updatedAt=? WHERE application=? AND devEui=? AND queueId=? + AND ${predicate}`).run(status, detail, Date.now(), application, devEui, queueId); +} +export function clearedCommands(application: string, devEui: string): void { + db.prepare("UPDATE manager_commands SET status='cleared',detail='Queue cleared; any earlier transmission cannot be recalled',updatedAt=? WHERE application=? AND devEui=? AND status IN ('queued','pending','unknown')") + .run(Date.now(), application, devEui); +} diff --git a/src/public/css/global.css b/src/public/css/global.css index 9e0a657..5cc4108 100644 --- a/src/public/css/global.css +++ b/src/public/css/global.css @@ -1,98 +1,352 @@ -body { - height: 100vh; - background-image: url("/assets/8-bit-13.jpg"); - background-repeat: no-repeat; - background-attachment: fixed; +/* Shared tokens. Theme selectors only affect presentation, never application state. */ +:root { + --font: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + --display-font: var(--font); --text:#243630; --muted:#64736a; --accent:#316a4d; + --accent-ink:#fff; --surface:#f8faf7; --surface-alt:#edf1e9; --panel:#e5eadf; + --border:#c1cbbf; --radius:0px; --small-radius:0px; --shadow:5px 5px 0 #152c37; + --window-border:2px solid #263b39; --panel-border:2px solid #263b39; + --wallpaper:linear-gradient(0deg,#05272144,#05272122),url('/assets/8-bit-13.jpg'); + --desktop-ink:#fff; --panel-height:48px; --dock-height:76px; --dock-bottom:16px; + --icon-radius:0px; --icon-shadow:4px 4px 0 #162b3980; --icon-size:56px; + --duration:160ms; --window-header:#dae3d5; --glass:none; --wallpaper-color:#173c39; + color-scheme:light; } - -#m3ter-data, -.empty { - color: lime; - font-size: 15px; - overflow-wrap: break-word; - transition: content 0.5s ease-in-out; -} - -#nav { - padding: 7px; - font-size: 10px; - background-color: lightgray; - border-bottom: solid black; -} - -.bbtn { - float: right; -} - -iframe { - height: 700px; - width: 100%; -} - -.subtle { - border-color: #0000 !important; -} - -.hidden { - display: none; -} - -/* Terminal specific styles */ -#terminal-auth { - background-color: #212529 !important; -} - -#terminal-auth h4 { - color: #ffffff; - margin-bottom: 15px; -} - -#terminal-auth label { - color: #ffffff; - margin-bottom: 5px; - display: block; -} - -#terminal-container { - background-color: #000000 !important; - padding: 0 !important; - height: 700px; - min-height: 700px; - max-height: 700px; - display: flex; - flex-direction: column; - overflow: hidden; +:root[data-theme="retro"] { --display-font:"Press Start 2P",monospace; } +:root[data-theme="macos"] { + --text:#302d3c; --muted:#797182; --accent:#7450ab; --surface:#faf8fc; --surface-alt:#efebf3; + --panel:#f5f0f2dc; --border:#d8d0df; --radius:16px; --small-radius:9px; + --shadow:0 24px 80px #21102b40,0 2px 8px #21102b15; --window-border:1px solid #ffffff80; + --panel-border:1px solid #ffffff80; --icon-radius:24%; --icon-shadow:0 5px 10px #24113030,inset 0 1px #ffffff70; + --wallpaper:radial-gradient(ellipse at 70% 80%,#eeaf8e 0%,transparent 42%),radial-gradient(ellipse at 90% 5%,#8e8ba7 0%,transparent 55%),linear-gradient(135deg,#45465e 0%,#897185 48%,#cea094 100%); + --window-header:#f4f0f5; --glass:blur(22px); --wallpaper-color:#52445d; } - -#xterm-terminal { - flex: 1; - width: 100%; - height: 100%; - overflow: hidden; - padding: 0; - padding-bottom: 50px; +:root[data-theme="linux"] { + color-scheme:dark; --text:#eef0f4; --muted:#afb6c4; --accent:#b6cc75; --accent-ink:#222a12; + --surface:#292e38; --surface-alt:#333a46; --panel:#20242ef0; --border:#49505d; + --radius:12px; --small-radius:7px; --shadow:0 20px 65px #0006; --window-border:1px solid #525968; + --panel-border:1px solid #4e5360; --icon-radius:12px; --icon-shadow:0 5px 12px #0004; + --wallpaper:radial-gradient(ellipse at 78% 40%,#52644655,transparent 60%),repeating-linear-gradient(135deg,transparent 0 110px,#ffffff03 110px 111px),linear-gradient(125deg,#20232c,#2c3437); + --window-header:#343a45; --glass:blur(16px); --wallpaper-color:#21252f; } - -.xterm { - height: 100% !important; - width: 100% !important; - padding-bottom: 50px !important; +:root[data-theme="windows"] { + --text:#20334f; --muted:#64748b; --accent:#2267b5; --surface:#f7faff; --surface-alt:#eaf0f8; + --panel:#eaf4ffdf; --border:#ccdae9; --radius:9px; --small-radius:5px; + --shadow:0 15px 60px #051b4440,0 2px 6px #051b4410; --window-border:1px solid #ffffffaa; + --panel-border:1px solid #ffffffaa; --icon-radius:14px; --icon-shadow:0 5px 10px #08294b30; + --wallpaper:radial-gradient(ellipse at 65% 75%,#77c3e9 0%,transparent 42%),radial-gradient(ellipse at 80% 15%,#477bcc 0%,transparent 50%),linear-gradient(135deg,#0e274b,#225790 55%,#5a97c3); + --window-header:#eff5fc; --glass:blur(22px); --dock-bottom:0px; --dock-height:64px; --wallpaper-color:#173b68; } - -.xterm-viewport { - height: 100% !important; +:root[data-background="dusk"] { --wallpaper:radial-gradient(ellipse at 70% 90%,#cc987e,transparent 60%),linear-gradient(145deg,#302f4e,#896d89); } +:root[data-background="forest"] { --wallpaper:radial-gradient(ellipse at 80% 100%,#87a68b,transparent 65%),linear-gradient(135deg,#10332e,#3c6a56); } +:root[data-background="plain"] { --wallpaper:linear-gradient(#243d42,#243d42); } +:root[data-icon-size="small"] { --icon-size:44px; } +:root[data-icon-size="large"] { --icon-size:68px; } +* { box-sizing:border-box; } +html,body { margin:0; width:100%; height:100%; overflow:hidden; } +body { font:14px/1.5 var(--font); color:var(--text); cursor:auto; } +button,input,select,textarea { font:inherit; } +button,a,input,select,label { -webkit-tap-highlight-color:transparent; } +button,a { cursor:pointer; } +button { color:inherit; } +button:disabled { cursor:not-allowed; opacity:.5; } +button { border:0; background:none; } +a { color:var(--accent); } +button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,[tabindex]:focus-visible { outline:3px solid var(--accent); outline-offset:3px; } +button:focus:not(:focus-visible) { outline:none; } +[hidden],.hidden { display:none !important; } +svg { width:24px; height:24px; flex-shrink:0; vertical-align:middle; fill:none; stroke:currentColor; stroke-width:1.7; stroke-linecap:round; stroke-linejoin:round; } +h1,h2,h3,p { margin-top:0; } +h2 { font-size:26px; font-weight:650; letter-spacing:-.8px; margin-bottom:8px; } +h3 { font-size:14px; font-weight:650; margin:25px 0 12px; } +small { display:block; font-size:12px; line-height:1.6; color:var(--muted); } +.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; } +.skip-link { position:fixed; left:12px; top:-70px; z-index:2000; background:var(--surface); padding:12px; } +.skip-link:focus { top:8px; } +.desktop-shell { height:100dvh; background:var(--wallpaper) center/cover no-repeat; background-color:var(--wallpaper-color); position:relative; isolation:isolate; } +.topbar { height:calc(var(--panel-height) + env(safe-area-inset-top)); padding:env(safe-area-inset-top) 24px 0; display:flex; align-items:center; justify-content:space-between; gap:16px; background:var(--panel); border-bottom:var(--panel-border); backdrop-filter:var(--glass); position:relative; z-index:500; } +.brand { display:flex; align-items:center; gap:11px; padding:0; font-weight:650; letter-spacing:-.3px; min-height:44px; } +.brand-mark { font-family:var(--font); font-size:23px; font-weight:800; line-height:1; letter-spacing:-2px; display:inline-grid; place-items:center; width:32px; height:32px; background:var(--accent); color:var(--accent-ink); border-radius:var(--small-radius); } +.brand-secondary { opacity:.6; font-weight:400; } +.topbar-location { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--muted); } +.status-dot { display:inline-block; height:6px; width:6px; border-radius:50%; background:#65a87c; flex-shrink:0; } +.topbar-trailing { display:flex; align-items:center; gap:14px; } +#desktop-clock { font-size:12px; font-variant-numeric:tabular-nums; white-space:nowrap; } +.quiet-button { display:inline-flex; align-items:center; justify-content:center; gap:6px; min-width:40px; min-height:40px; padding:8px; border-radius:var(--small-radius); } +.quiet-button:hover { background:var(--surface-alt); } +#desktop { position:absolute; top:calc(var(--panel-height) + env(safe-area-inset-top)); bottom:calc(var(--dock-height) + var(--dock-bottom) + 16px + env(safe-area-inset-bottom)); width:100%; } +.desktop-heading { position:absolute; right:7%; top:23%; color:var(--desktop-ink); pointer-events:none; text-shadow:0 2px 12px #102b3f38; max-width:47%; } +.eyebrow { font-size:10px; font-weight:700; letter-spacing:1.8px; color:var(--muted); } +.desktop-heading .eyebrow { color:inherit; opacity:.7; font-size:9px; } +.desktop-heading h1 { font-size:clamp(38px,5.2vw,80px); line-height:1.08; font-weight:400; letter-spacing:-3px; margin:22px 0; } +.desktop-heading p { font-size:12px; opacity:.7; } +.desktop-heading p span { margin:0 12px; } +.desktop-caption { position:absolute; bottom:2px; right:32px; color:var(--desktop-ink); opacity:.7; font-size:11px; display:flex; align-items:center; gap:8px; pointer-events:none; } +#desktop-scroll { position:absolute; inset:16px 20px 24px; overflow:auto; scrollbar-width:thin; } +#desktop-icons { position:relative; min-height:100%; } +.desktop-icon { position:absolute; top:0; left:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; width:100px; height:108px; border:1px solid transparent; padding:8px 4px; border-radius:var(--small-radius); color:#fff; user-select:none; transition:background var(--duration),border-color var(--duration); touch-action:pan-y; } +.desktop-icon:hover { background:#ffffff16; border-color:#ffffff25; } +.desktop-icon:focus-visible,.desktop-icon.selected { background:#ffffff24; border-color:#ffffff70; outline-color:#fff; } +.desktop-icon.dragging { z-index:5; opacity:.86; background:#ffffff25; cursor:grabbing; transition:none; } +[data-arrangement="manual"] .desktop-icon { touch-action:none; cursor:grab; } +.app-art { width:var(--icon-size); height:var(--icon-size); display:inline-flex; align-items:center; justify-content:center; border-radius:var(--icon-radius); background:linear-gradient(140deg,#eeedd4,#bbcda2); color:#35513b; box-shadow:var(--icon-shadow); flex-shrink:0; overflow:hidden; } +.app-art svg { width:56%; height:56%; stroke-width:1.6; } +[data-app-id="terminal"] .app-art { background:linear-gradient(140deg,#384e48,#172d28); color:#d4eeb3; } +[data-app-id="browser"] .app-art { background:linear-gradient(140deg,#a9e1e5,#497fba); color:#fff; } +[data-app-id="paint"] .app-art { background:linear-gradient(140deg,#f9d79d,#d97e7c); color:#713d46; } +[data-app-id="settings"] .app-art { background:linear-gradient(140deg,#e6e8e8,#9da9b1); color:#43535d; } +.extension-art { background:linear-gradient(140deg,#efdc8e,#cbae43); color:#5d4c22; } +.extension-art > * { max-width:85%; max-height:85%; } +.extension-art .nes-icon { transform:scale(1.5); margin:0; } +.icon-label { font-size:12px; line-height:1.25; text-align:center; text-shadow:0 1px 5px #0008; max-width:100%; overflow-wrap:anywhere; padding:2px 4px; border-radius:3px; background:#071f3029; } +#drop-target { position:absolute; top:0; left:0; border:2px dashed #fff; background:#ffffff20; border-radius:var(--small-radius); pointer-events:none; } +.taskbar { position:absolute; z-index:600; bottom:calc(var(--dock-bottom) + env(safe-area-inset-bottom)); left:50%; transform:translateX(-50%); display:flex; align-items:center; gap:10px; padding:8px 12px; max-width:calc(100% - 32px); height:var(--dock-height); background:var(--panel); border:var(--panel-border); box-shadow:0 5px 20px #102b3b30; border-radius:var(--radius); backdrop-filter:var(--glass); } +.launcher-toggle { display:flex; align-items:center; justify-content:center; gap:9px; min-height:44px; min-width:44px; border-radius:var(--small-radius); padding:8px; } +.launcher-toggle:hover,.launcher-toggle[aria-expanded="true"] { background:var(--surface-alt); } +.launcher-label { font-size:12px; } +.dock-divider { width:1px; height:30px; background:var(--border); flex-shrink:0; } +#dock-apps { display:flex; align-items:center; gap:5px; overflow-x:auto; scrollbar-width:none; min-width:0; } +.dock-app { position:relative; flex-shrink:0; width:52px; height:58px; display:grid; place-items:center; border-radius:var(--small-radius); padding:4px 4px 10px; } +.dock-app .app-art { width:40px; height:40px; box-shadow:none; } +.dock-app:hover { background:var(--surface-alt); } +.dock-app.open::after { content:''; position:absolute; bottom:2px; width:4px; height:4px; background:var(--muted); border-radius:4px; } +.dock-app.active::after { width:16px; background:var(--accent); } +.launcher { position:absolute; z-index:700; bottom:calc(var(--dock-height) + var(--dock-bottom) + 12px + env(safe-area-inset-bottom)); left:50%; transform:translateX(-50%); width:460px; max-width:calc(100% - 24px); max-height:calc(100dvh - 160px); overflow:auto; padding:26px; border:var(--panel-border); border-radius:var(--radius); background:var(--panel); box-shadow:var(--shadow); backdrop-filter:var(--glass); } +.launcher-heading { display:flex; justify-content:space-between; align-items:center; } +.launcher h2 { font-size:23px; margin:7px 0 18px; } +.launcher-search { display:flex; gap:10px; align-items:center; padding:10px 12px; border:1px solid var(--border); border-radius:var(--small-radius); background:var(--surface); margin-bottom:18px; } +.launcher-search svg { width:18px; height:18px; color:var(--muted); } +.launcher-search input { width:100%; min-width:0; border:0; background:none; color:var(--text); outline-offset:0; } +#launcher-apps { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; } +.launcher-app { display:flex; flex-direction:column; align-items:center; padding:12px 5px; border-radius:var(--small-radius); gap:9px; font-size:12px; min-width:0; overflow-wrap:anywhere; } +.launcher-app .app-art { width:44px; height:44px; box-shadow:none; } +.launcher-app:hover { background:var(--surface-alt); } +.launcher-footer { display:flex; align-items:center; gap:8px; border-top:1px solid var(--border); margin-top:18px; padding-top:12px; font-size:11px; color:var(--muted); } +.launcher-footer button { margin-left:auto; font-size:11px; } +#window-layer { position:absolute; inset:0; pointer-events:none; } +.app-window { position:absolute; display:flex; flex-direction:column; width:min(820px,calc(100% - 48px)); height:min(620px,calc(100% - 24px)); left:12%; top:12px; overflow:hidden; pointer-events:auto; background:var(--surface); border:var(--window-border); border-radius:var(--radius); box-shadow:var(--shadow); min-width:0; } +.app-window.is-active { z-index:2; } +.app-window.is-maximized { left:8px !important; top:8px !important; width:calc(100% - 16px) !important; height:calc(100% - 16px) !important; } +.window-titlebar { display:flex; align-items:center; justify-content:space-between; gap:8px; height:48px; min-height:48px; padding:0 8px 0 16px; background:var(--window-header); border-bottom:1px solid var(--border); user-select:none; touch-action:none; } +.window-title { display:flex; align-items:center; gap:8px; font-size:12px; font-weight:600; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; } +.window-title svg { width:16px; height:16px; } +.window-controls { display:flex; align-items:center; gap:2px; } +.window-controls button { width:38px; height:36px; display:grid; place-items:center; border-radius:var(--small-radius); } +.window-controls svg { width:15px; height:15px; } +.window-controls button:hover { background:var(--border); } +.window-controls .window-close:hover { background:#bd4747; color:white; } +.window-resize { position:absolute; right:0; bottom:0; width:24px; height:24px; cursor:nwse-resize; touch-action:none; background:linear-gradient(135deg,transparent 70%,var(--border) 71%,var(--border) 75%,transparent 76%); } +.window-content { flex:1; overflow:auto; min-height:0; padding:28px; } +.page-heading { display:flex; justify-content:space-between; align-items:center; gap:15px; margin-bottom:24px; } +.page-heading h2 { margin-top:8px; } +.page-heading p,.section-description { color:var(--muted); font-size:13px; margin-bottom:0; } +.count-badge { background:var(--surface-alt); border:1px solid var(--border); padding:6px 10px; border-radius:30px; font-size:11px; white-space:nowrap; } +label { display:block; } +.nes-btn { border:1px solid var(--border); background:var(--surface-alt); color:var(--text); padding:10px 16px; border-radius:var(--small-radius); box-shadow:none; margin:0; min-height:42px; font:500 12px/1.4 var(--font); cursor:pointer; } +.nes-btn::after { display:none; } +.nes-btn:hover,.nes-btn:focus { background:var(--panel); color:var(--text); } +.nes-btn.is-primary,.nes-btn.is-success,.nes-btn.is-warning { background:var(--accent); color:var(--accent-ink); border-color:var(--accent); } +.nes-btn:is(.is-primary,.is-success,.is-warning):hover,.nes-btn:is(.is-primary,.is-success,.is-warning):focus { background:var(--accent); color:var(--accent-ink); filter:brightness(.94); } +.nes-btn.is-error { background:#a53a43; color:#fff; border-color:#a53a43; } +.nes-btn:active { transform:translateY(1px); } +.nes-input,select { border:1px solid var(--border); background:var(--surface); border-radius:var(--small-radius); padding:10px 12px; color:var(--text); min-height:42px; width:auto; margin:0; font:14px var(--font); outline-offset:2px; } +.nes-input { width:100%; } +.input-row { display:flex; gap:10px; } +.input-row input { flex:1; min-width:0; } +.input-row button { white-space:nowrap; } +.meter-form { padding:18px; background:var(--surface-alt); border:1px solid var(--border); border-radius:var(--small-radius); margin-bottom:24px; } +.meter-form label { font-size:11px; margin-bottom:8px; } +.table-scroll { max-width:100%; overflow:auto; } +.meter-table { width:100%; border-collapse:collapse; font-size:12px; } +.meter-table th { color:var(--muted); font-weight:500; font-size:11px; text-align:left; padding:12px; border-bottom:1px solid var(--border); } +.meter-table td { padding:14px 12px; border-bottom:1px solid var(--border); } +.meter-table td:first-child { white-space:nowrap; } +.public-key { overflow-wrap:anywhere; font:11px/1.6 ui-monospace,monospace; } +.meter-avatar { display:inline-grid; place-items:center; background:var(--surface-alt); width:32px; height:32px; border-radius:var(--small-radius); margin-right:10px; } +.meter-avatar svg { width:20px; height:20px; } +.danger { color:#b54d51; } +.empty-state { text-align:center; padding:40px 10px; color:var(--muted); } +.empty-state svg { width:36px; height:36px; } +.empty-state h3 { color:var(--text); margin-top:16px; } +.terminal-content { display:flex; flex-direction:column; } +.terminal-emblem svg { width:48px; height:48px; } +#auth-form { max-width:380px; margin:20px auto; } +#auth-form label { margin:15px 0 7px; font-size:12px; } +#auth-form button { margin-top:22px; width:100%; display:flex; justify-content:space-between; } +#terminal-container { flex:1; min-height:180px; flex-direction:column; overflow:hidden; background:#15211e; border-radius:var(--small-radius); } +.terminal-toolbar { display:flex; align-items:center; justify-content:space-between; color:#c6d4cd; gap:12px; padding:8px 12px; background:#22332d; font-size:11px; } +.terminal-toolbar button { min-height:32px; padding:5px 10px; } +#xterm-terminal { flex:1; min-height:100px; padding:10px; overflow:hidden; } +#terminal-status { color:var(--muted); font-size:12px; padding-top:14px; } +#terminal-status p { margin-bottom:0; } +.browser-toolbar { padding:9px 16px; display:flex; align-items:center; gap:10px; background:var(--surface-alt); font-size:12px; } +.browser-toolbar a { margin-left:auto; font-size:11px; } +#browser iframe, #chirpstack iframe { border:0; width:100%; flex:1; min-height:0; background:white; } +.app-art[data-icon="radio"] { background:linear-gradient(145deg,#259aa0,#145275); color:#fff; } +.chirpstack-toolbar { flex-wrap:wrap; gap:8px; } +.chirpstack-toolbar small { display:block; font-size:10px; color:var(--muted); } +.chirpstack-toolbar .nes-btn { margin-left:auto; } +.settings-window { width:min(900px,calc(100% - 48px)); } +.settings-layout { display:flex; flex:1; min-height:0; } +.settings-nav { width:210px; flex-shrink:0; background:var(--surface-alt); border-right:1px solid var(--border); padding:24px 12px; display:flex; flex-direction:column; gap:6px; } +.settings-identity { display:flex; align-items:center; gap:10px; padding:0 4px 24px; } +.settings-identity strong { font-size:12px; } +.settings-identity small { font-size:10px; } +.settings-nav button { display:flex; align-items:center; gap:11px; padding:12px; font-size:12px; border-radius:var(--small-radius); text-align:left; } +.settings-nav button svg { width:19px; height:19px; } +.settings-nav button:hover { background:var(--panel); } +.settings-nav button[aria-current="page"] { background:var(--accent); color:var(--accent-ink); } +.settings-footnote { margin:auto 12px 0; padding-top:24px; font-size:10px; line-height:1.8; } +.settings-footnote span { color:var(--muted); font-size:9px; } +.settings-content { padding:28px 32px; overflow:auto; flex:1; min-width:0; } +.settings-content h2 { margin-top:8px; } +.theme-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; } +.theme-card { border:1px solid var(--border); border-radius:var(--small-radius); padding:5px; text-align:left; background:var(--surface); min-width:0; transition:border-color var(--duration),box-shadow var(--duration); } +.theme-card:hover { border-color:var(--accent); } +.theme-card[aria-pressed="true"] { border-color:var(--accent); box-shadow:0 0 0 2px var(--accent); } +.theme-card-copy { display:block; padding:10px 7px 8px; } +.theme-card-title { display:flex; gap:8px; align-items:center; justify-content:space-between; font-size:12px; font-weight:650; } +.theme-check { display:grid; place-items:center; border-radius:50%; width:17px; height:17px; border:1px solid var(--border); color:transparent; font-size:11px; } +[aria-pressed="true"] .theme-check { background:var(--accent); border-color:var(--accent); color:var(--accent-ink); } +.theme-card small { font-size:10px; margin-top:4px; } +.theme-preview { height:103px; border-radius:calc(var(--small-radius) / 2); position:relative; display:block; overflow:hidden; background:#597862; } +.preview-retro { background:url('/assets/8-bit-13.jpg') center/cover; } +.preview-macos { background:radial-gradient(ellipse at 85% 90%,#f0b48c,transparent 65%),linear-gradient(135deg,#45465e,#b18e9b); } +.preview-linux { background:linear-gradient(135deg,#20232c,#4c5c48); } +.preview-windows { background:radial-gradient(ellipse at 85% 100%,#9ee0ee,transparent 65%),linear-gradient(135deg,#133459,#4489d1); } +.preview-bar { position:absolute; height:8px; background:#efefdfcc; left:0; right:0; top:0; } +.preview-window { position:absolute; width:52%; height:57%; top:18%; left:31%; background:#f8f6f0; border:1px solid #7c878c; box-shadow:3px 3px #0003; } +.preview-window::before { content:'•••'; display:block; height:13px; line-height:9px; padding-left:4px; font-size:9px; color:#8b9f8e; border-bottom:1px solid #d3d7cd; background:#e3e6dd; } +.preview-window::after { content:''; position:absolute; inset:22px 10px 10px; border-left:16px solid #d5dece; border-top:5px solid #e5e8e0; } +.preview-icons { position:absolute; left:9px; top:17px; display:flex; flex-direction:column; gap:7px; } +.preview-icons i { display:block; width:11px; height:11px; background:#e4dcb6; box-shadow:1px 1px #0005; } +.preview-icons i:nth-child(2) { background:#79aaaf; }.preview-icons i:nth-child(3) { background:#d69e75; } +.preview-dock { position:absolute; bottom:5px; left:30%; width:40%; height:12px; background:#efefdfcc; } +.preview-macos .preview-window { border-radius:5px; border:0; }.preview-macos .preview-dock { border-radius:5px; }.preview-macos .preview-icons i { border-radius:3px; } +.preview-linux .preview-window { background:#323943; border-color:#626773; border-radius:3px; }.preview-linux .preview-window::before { background:#454d58; border-color:#5d6879; }.preview-linux .preview-dock { left:0; top:8px; bottom:0; height:auto; width:8px; background:#20232c; }.preview-linux .preview-bar { background:#20232c; }.preview-linux .preview-icons { flex-direction:row; left:16px; top:14px; } +.preview-windows .preview-dock { bottom:0; left:0; width:100%; }.preview-windows .preview-window { border-radius:3px; }.preview-windows .preview-bar { display:none; } +.background-options { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:10px; } +.background-options button { text-align:center; font-size:10px; padding:4px; border:1px solid transparent; border-radius:var(--small-radius); } +.background-options button[aria-pressed="true"] { border-color:var(--accent); background:var(--surface-alt); } +.wallpaper-swatch { display:block; height:42px; margin-bottom:6px; border-radius:var(--small-radius); border:1px solid #ffffff33; } +.swatch-theme { background:var(--wallpaper-color); }.swatch-dusk { background:linear-gradient(135deg,#302f4e,#bd8d88); }.swatch-forest { background:linear-gradient(135deg,#10332e,#87a68b); }.swatch-plain { background:#243d42; } +.setting-hint { font-size:12px; color:var(--muted); } +.setting-block { padding:16px; margin-top:24px; border:1px solid var(--border); border-radius:var(--small-radius); } +.setting-block legend { width:auto; font-size:13px; padding:0 5px; } +.choice-row { display:flex; gap:12px; align-items:flex-start; padding:12px 0; cursor:pointer; } +.choice-row input { margin:4px 0 0; width:18px; height:18px; flex-shrink:0; accent-color:var(--accent); } +.choice-row strong,.setting-row strong { font-size:13px; font-weight:600; } +.choice-row small,.setting-row small { margin-top:4px; } +.setting-row { display:flex; justify-content:space-between; align-items:center; gap:20px; padding:24px 0; border-bottom:1px solid var(--border); } +.setting-row > :first-child { flex:1; }.setting-row button,.setting-row select { flex-shrink:0; } +.switch { appearance:none; width:40px; height:24px; border:1px solid var(--border); border-radius:20px; background:var(--border); cursor:pointer; position:relative; flex-shrink:0; } +.switch::after { content:''; display:block; width:16px; height:16px; position:absolute; top:3px; left:3px; border-radius:50%; background:var(--surface); transition:transform var(--duration); } +.switch:checked { background:var(--accent); border-color:var(--accent); }.switch:checked::after { transform:translateX(16px); background:var(--accent-ink); } +.settings-note { display:flex; gap:14px; padding:18px; background:var(--surface-alt); border-radius:var(--small-radius); margin-top:28px; color:var(--muted); font-size:12px; }.settings-note p { margin:0; } +.nes-container { border:1px solid var(--border); border-radius:var(--small-radius); background:var(--surface-alt); padding:20px; color:var(--text); } +.nes-container.with-title > .title { background:var(--surface); color:var(--text); font:600 13px var(--font); } +.nes-text.is-primary,.nes-text.is-success { color:var(--accent); }.nes-text.is-warning { color:var(--text); } +.publisher-summary { display:grid; grid-template-columns:1fr 1fr; gap:14px; } +.publisher-stat { padding:22px; border:1px solid var(--border); border-radius:var(--small-radius); background:var(--surface-alt); } +.publisher-stat > span { display:block; color:var(--muted); font-size:12px; margin-bottom:10px; } +.publisher-stat > strong { display:block; font-size:25px; font-weight:600; overflow-wrap:anywhere; } +.publisher-stat #streamr-last-publish { font-size:18px; } +.publisher-config { margin-top:26px; }.publisher-config code { color:var(--text); font-size:12px; overflow-wrap:anywhere; } +.publisher-config .setting-row { padding:12px 0; } +.stream-list { list-style:none; padding:0; margin:0; }.stream-list li { display:flex; gap:12px; align-items:center; padding:14px 0; border-bottom:1px solid var(--border); } +.publisher-actions { display:flex; gap:10px; margin-top:26px; } +.context-menu { position:fixed; z-index:900; width:220px; padding:6px; border:var(--panel-border); border-radius:var(--small-radius); background:var(--surface); box-shadow:var(--shadow); } +.context-menu button { display:block; padding:12px; width:100%; text-align:left; font-size:12px; border-radius:var(--small-radius); }.context-menu button:hover { background:var(--surface-alt); } +dialog { width:min(430px,calc(100% - 32px)); padding:30px; background:var(--surface); color:var(--text); border:var(--window-border); border-radius:var(--radius); box-shadow:var(--shadow); } +dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { font-size:22px; margin:16px 0 12px; }dialog p { font-size:13px; color:var(--muted); }.dialog-actions { display:flex; flex-wrap:wrap; justify-content:flex-end; gap:8px; margin-top:24px; } +#notification-area { position:fixed; z-index:1200; right:20px; bottom:calc(var(--dock-height) + var(--dock-bottom) + 22px); max-width:min(380px,calc(100% - 40px)); } +.notification { background:var(--surface); border:1px solid var(--border); border-left:4px solid var(--accent); color:var(--text); border-radius:var(--small-radius); padding:16px; font-size:13px; box-shadow:var(--shadow); }.notification.error { border-left-color:#b94b51; } +/* Distinct chrome: classic pixel desktop, floating glass dock, Linux side panel, Windows taskbar. */ +[data-theme="retro"] .brand { font-family:var(--display-font); font-size:10px; } +[data-theme="retro"] .desktop-heading h1 { font-family:var(--display-font); font-size:clamp(20px,2.5vw,38px); line-height:1.8; letter-spacing:-1px; } +[data-theme="retro"] .icon-label { font-family:var(--display-font); font-size:9px; line-height:1.6; } +[data-theme="retro"] .window-title { font-family:var(--display-font); font-size:9px; } +[data-theme="retro"] .window-controls button { border:1px solid var(--border); box-shadow:1px 1px #68786a; margin-left:4px; width:30px; height:28px; } +[data-theme="retro"] .app-art { border:2px solid #233b38; }.app-art svg { shape-rendering:geometricPrecision; } +[data-theme="retro"] .taskbar { box-shadow:4px 4px #152c37; } +[data-theme="macos"] .window-titlebar { flex-direction:row; justify-content:flex-start; padding:0 16px 0 10px; } +[data-theme="macos"] .window-title { position:absolute; left:50%; transform:translateX(-50%); pointer-events:none; } +[data-theme="macos"] .window-controls { flex-direction:row; gap:0; } +[data-theme="macos"] .window-close { order:-1; } +[data-theme="macos"] .window-controls button { width:28px; height:36px; position:relative; background:none; } +[data-theme="macos"] .window-controls button::before { content:''; position:absolute; width:12px; height:12px; background:#edc25b; border-radius:50%; } +[data-theme="macos"] .window-controls .window-close::before { background:#ed7971; } +[data-theme="macos"] .window-controls .window-maximize::before { background:#84c685; } +[data-theme="macos"] .window-controls svg { width:10px; height:10px; z-index:1; opacity:0; color:#402a2a; } +[data-theme="macos"] .window-controls button:hover svg,[data-theme="macos"] .window-controls button:focus-visible svg { opacity:1; } +[data-theme="macos"] .taskbar { border-radius:22px; padding:8px 10px; } +[data-theme="macos"] .launcher-label { display:none; } +[data-theme="macos"] .dock-app { transition:transform var(--duration); }[data-theme="macos"] .dock-app:hover { transform:translateY(-3px); } +[data-theme="linux"] #desktop { left:84px; width:calc(100% - 84px); bottom:12px; } +[data-theme="linux"] .taskbar { top:calc(var(--panel-height) + 22px); bottom:22px; left:12px; transform:none; width:66px; height:auto; max-height:calc(100% - var(--panel-height) - 44px); flex-direction:column; padding:10px 5px; } +[data-theme="linux"] #dock-apps { flex-direction:column; overflow-y:auto; overflow-x:hidden; } +[data-theme="linux"] .dock-divider { height:1px; width:32px; } +[data-theme="linux"] .launcher-label { display:none; } +[data-theme="linux"] .launcher { left:90px; bottom:20px; transform:none; } +[data-theme="linux"] .desktop-heading { top:28%; } +[data-theme="linux"] .window-titlebar { justify-content:center; } +[data-theme="linux"] .window-controls { position:static; } +[data-theme="windows"] .taskbar { width:100%; max-width:100%; border-radius:0; justify-content:center; padding:6px 16px; border-width:1px 0 0; } +[data-theme="windows"] #dock-apps { flex:0 1 auto; } +[data-theme="windows"] .launcher-label { display:none; } +[data-theme="windows"] .dock-app .app-art { width:32px; height:32px; border-radius:8px; } +[data-theme="windows"] .dock-app { height:48px; width:48px; } +[data-theme="windows"] .dock-app.active { background:#ffffff80; } +[data-theme="windows"] .window-controls { gap:0; }[data-theme="windows"] .window-controls button { width:44px; border-radius:0; } +@media (min-width:1500px) { .desktop-heading { right:13%; } #desktop-scroll { left:40px; } } +@media (max-width:1000px) { .settings-nav { width:175px; padding-inline:8px; }.settings-identity { gap:6px; }.settings-content { padding:24px; }.desktop-heading { right:5%; }.app-window { left:5%; } } +@media (max-width:700px) { + :root { --panel-height:52px; --dock-height:64px; --dock-bottom:10px; } + .topbar { padding-inline:14px; gap:8px; }.brand { font-size:13px; gap:8px; }.brand-secondary,.topbar-location { display:none; }.brand-mark { width:28px; height:28px; font-size:21px; }.topbar-trailing { gap:3px; }#desktop-clock { font-size:11px; } + [data-theme="retro"] .brand { font-size:9px; } + #desktop,[data-theme="linux"] #desktop { left:0; width:100%; bottom:calc(var(--dock-height) + var(--dock-bottom) + 12px + env(safe-area-inset-bottom)); } + #desktop-scroll { inset:12px 10px 0; }.desktop-heading { display:none; }.desktop-caption { display:none; } + .desktop-icon { gap:9px; }.icon-label { font-size:12px; }[data-theme="retro"] .icon-label { font-size:8px; } + .taskbar,[data-theme="linux"] .taskbar { top:auto; left:50%; transform:translateX(-50%); bottom:calc(var(--dock-bottom) + env(safe-area-inset-bottom)); width:auto; max-width:calc(100% - 20px); height:var(--dock-height); flex-direction:row; padding:6px; gap:3px; border-radius:var(--radius); } + #dock-apps,[data-theme="linux"] #dock-apps { flex-direction:row; overflow-x:auto; overflow-y:hidden; gap:2px; }.dock-app { width:43px; height:50px; }.dock-app .app-art { width:33px; height:33px; } + .launcher-label { display:none; }.dock-divider,[data-theme="linux"] .dock-divider { width:1px; height:28px; }.show-desktop { min-width:36px; } + [data-theme="windows"] .taskbar { width:100%; max-width:100%; bottom:env(safe-area-inset-bottom); border-radius:0; } + [data-theme="windows"] .dock-app { width:40px; height:50px; } + .launcher,[data-theme="linux"] .launcher { left:50%; transform:translateX(-50%); bottom:calc(var(--dock-height) + var(--dock-bottom) + 12px + env(safe-area-inset-bottom)); width:calc(100% - 24px); max-height:calc(100dvh - 160px); padding:20px; } + .app-window,.app-window.is-maximized { left:0 !important; top:0 !important; width:100% !important; height:100% !important; border-radius:0; border-width:0 0 1px; box-shadow:none; } + .app-window:not(.is-active) { visibility:hidden; pointer-events:none; } + .window-titlebar { padding-left:14px; min-height:48px; }.window-controls button { min-width:40px; height:42px; }.window-maximize,.window-resize { display:none !important; } + [data-theme="retro"] .window-controls button { height:34px; min-width:40px; } + [data-theme="macos"] .window-controls button { width:40px; }[data-theme="macos"] .window-controls button::before { width:22px; height:22px; }[data-theme="macos"] .window-controls svg { opacity:1; } + .window-content { padding:22px 16px; }.page-heading { flex-wrap:wrap; gap:10px; margin-bottom:18px; }h2 { font-size:24px; }.count-badge { font-size:10px; } + .settings-layout { flex-direction:column; }.settings-nav { width:100%; padding:8px; flex-direction:row; gap:5px; border-right:0; border-bottom:1px solid var(--border); }.settings-identity,.settings-footnote { display:none; }.settings-nav button { flex:1; justify-content:center; gap:6px; padding:10px 6px; min-height:44px; font-size:11px; }.settings-nav button svg { width:16px; height:16px; }.settings-content { padding:22px 18px; } + .theme-grid { gap:12px; }.theme-preview { height:90px; }.theme-card-title { font-size:11px; }.theme-card small { font-size:10px; }.theme-card-copy { padding:8px 4px; }.theme-check { flex-shrink:0; } + .setting-row { gap:12px; }.setting-row select { max-width:110px; }.setting-row .nes-btn { padding:8px 10px; }.switch { width:44px; height:28px; }.switch::after { width:20px; height:20px; } + .browser-toolbar { flex-wrap:wrap; gap:6px; font-size:11px; }.meter-table td,.meter-table th { padding:10px 6px; }.meter-avatar { display:none; }.input-row { flex-wrap:wrap; }.input-row button { flex:1; }.input-row input { flex-basis:160px; } + .nes-btn,.quiet-button { min-height:44px; }.extension-window .window-content { overflow-wrap:anywhere; }.extension-window .nes-container { padding:14px; } + .publisher-stat { padding:16px; }.publisher-stat #streamr-last-publish { font-size:15px; } } +@media (max-height:500px) and (min-width:701px) { .desktop-heading { display:none; }.app-window { top:4px; height:calc(100% - 8px); }.window-titlebar { min-height:40px; height:40px; }.taskbar { --dock-height:56px; }.launcher { max-height:calc(100dvh - 130px); } } +@media (prefers-reduced-motion:reduce) { *,*::before,*::after { animation:none !important; transition:none !important; scroll-behavior:auto !important; } } +[data-reduced-motion="true"] *,[data-reduced-motion="true"] *::before,[data-reduced-motion="true"] *::after { animation:none !important; transition:none !important; scroll-behavior:auto !important; } -.xterm-screen { - height: 100% !important; +/* Per-application palettes preserve the desktop theme's geometry and typography. */ +.app-window[data-color-mode="light"] { + color-scheme:light; --text:#243449; --muted:#59697d; --accent:#285fac; --accent-ink:#fff; + --surface:#fafcfe; --surface-alt:#edf2f8; --panel:#e5ecf5; --border:#c3cfdf; + --window-header:#e9eff7; --window-border:1px solid var(--border); --panel-border:1px solid var(--border); } - -#terminal-status { - background-color: #212529 !important; +.app-window[data-color-mode="dark"] { + color-scheme:dark; --text:#edf2fa; --muted:#aab8cb; --accent:#9dc5ff; --accent-ink:#122b4c; + --surface:#1d2532; --surface-alt:#273243; --panel:#303e52; --border:#495971; + --window-header:#243044; --window-border:1px solid var(--border); --panel-border:1px solid var(--border); } - -#terminal-status p { - color: #ffffff; - margin: 10px 0; - font-size: 12px; -} \ No newline at end of file +.app-window { color:var(--text); } +.window-title { flex:1; min-width:0; } +.window-controls { flex-shrink:0; } +.window-color-mode { flex-shrink:0; width:76px; min-height:36px; padding:6px; font-size:12px; touch-action:manipulation; } +[data-theme="macos"] .window-title { position:static; left:auto; transform:none; order:1; justify-content:center; } +[data-theme="macos"] .window-controls { order:0; } +[data-theme="macos"] .window-color-mode { order:2; } +.app-window[data-color-mode] #terminal-container { background:var(--surface); } +.app-window[data-color-mode] .terminal-toolbar { background:var(--surface-alt); color:var(--text); } +@media(max-width:700px) { .window-color-mode { min-height:42px; width:68px; } .window-titlebar { padding-left:8px; gap:4px; } } diff --git a/src/public/css/m3ter-manager.css b/src/public/css/m3ter-manager.css new file mode 100644 index 0000000..5fba011 --- /dev/null +++ b/src/public/css/m3ter-manager.css @@ -0,0 +1,85 @@ +.mm-app { display:flex; flex-direction:column; min-height:0; flex:1; font-family:var(--font); color:var(--text); } +.app-art[data-icon="manager"] { background:var(--accent); color:var(--accent-ink); } +.mm-header { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px 22px 12px; } +.mm-brand { display:flex; align-items:center; gap:12px; min-width:0; } +.mm-brand strong { font-size:18px; letter-spacing:-.5px; } +.mm-brand small { font-size:11px; } +.mm-mark { background:var(--accent); color:var(--accent-ink); width:42px; height:42px; display:grid; place-items:center; border-radius:var(--small-radius); } +.mm-connection { text-align:right; } +.mm-pill { display:inline-block; background:var(--surface-alt); border:1px solid var(--border); border-radius:var(--small-radius); padding:4px 9px; font-size:10px; line-height:1.5; } +.mm-pill[data-state="connected"],.mm-pill[data-state="active"] { color:var(--accent); border-color:var(--accent); } +.mm-selector { display:flex; gap:8px; padding:0 22px 14px; align-items:center; } +.mm-selector select { flex:1; min-width:0; max-width:100%; } +.mm-app input,.mm-app select { min-height:40px; padding:8px 10px; background:var(--surface); color:var(--text); border:1px solid var(--border); border-radius:var(--small-radius); max-width:100%; } +.mm-search { display:flex; align-items:center; width:38%; min-width:0; } +.mm-search svg { width:17px; margin-right:6px; } +.mm-search input { width:100%; min-width:0; } +.mm-nav { display:flex; flex-shrink:0; overflow:auto; padding:0 14px; gap:4px; border-bottom:1px solid var(--border); } +.mm-nav button { padding:12px 10px; font-size:12px; white-space:nowrap; border-bottom:2px solid transparent; min-height:44px; } +.mm-nav button[aria-current="page"] { color:var(--accent); border-color:var(--accent); font-weight:700; } +.mm-scroll { overflow:auto; padding:22px; min-height:0; flex:1; container-type:inline-size; } +.mm-identity { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:20px; } +.mm-identity h2 { font-size:25px; margin:6px 0 0; overflow-wrap:anywhere; } +.mm-identity code { font-size:11px; color:var(--muted); } +.mm-metrics { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; } +.mm-metric { border:1px solid var(--border); border-radius:var(--radius); padding:16px; background:var(--surface-alt); min-width:0; } +.mm-metric>span { font-size:12px; } +.mm-metric>strong { display:block; font-size:32px; line-height:1.6; font-weight:550; font-variant-numeric:tabular-nums; letter-spacing:-1px; overflow-wrap:anywhere; } +.mm-metric em { font-size:14px; font-style:normal; color:var(--muted); letter-spacing:0; } +.mm-metric.mm-energy { background:var(--accent); color:var(--accent-ink); border-color:var(--accent); } +.mm-energy small,.mm-energy em { color:inherit; opacity:.85; } +.mm-metric .mm-small-number { font-size:23px; letter-spacing:-.5px; } +.mm-section-heading { display:flex; align-items:center; justify-content:space-between; gap:12px; margin:24px 0 14px; flex-wrap:wrap; } +.mm-section-heading h3 { margin:0 0 4px; } +.mm-section-heading label { font-size:12px; } +.mm-charts { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; } +.mm-chart-card { min-width:0; padding:16px 12px 10px; border:1px solid var(--border); border-radius:var(--radius); } +.mm-chart-card h3 { margin:0 0 12px; display:flex; flex-wrap:wrap; justify-content:space-between; gap:4px; } +.mm-chart { min-height:200px; position:relative; color:var(--accent); } +.mm-chart svg { display:block; width:100%; height:160px; overflow:visible; touch-action:pan-y; } +.mm-chart-axis { display:flex; justify-content:space-between; font-size:10px; color:var(--muted); gap:8px; margin:6px 0; } +.mm-chart-tooltip { min-height:36px; font-size:11px; color:var(--text); line-height:1.5; overflow-wrap:anywhere; } +.mm-note,.mm-notice { font-size:12px; line-height:1.7; color:var(--muted); padding:12px 14px; background:var(--surface-alt); border-radius:var(--small-radius); margin:14px 0; } +.mm-notice { border-left:3px solid var(--accent); color:var(--text); margin-top:0; } +.mm-error { border-left-color:#cc5b45; } +.mm-actions { display:flex; align-items:center; gap:8px; flex-wrap:wrap; } +.mm-app .nes-btn { min-height:40px; font-family:var(--font); font-size:12px; white-space:normal; } +.mm-table { width:100%; font-size:11px; border-collapse:collapse; } +.mm-table td,.mm-table th { padding:12px 8px; border-bottom:1px solid var(--border); text-align:left; } +.mm-table th { color:var(--muted); font-weight:500; } +.mm-pagination { display:flex; justify-content:space-between; align-items:center; gap:10px; font-size:11px; margin:14px 0; } +.mm-command-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; } +.mm-command-card { border:1px solid var(--border); padding:16px; border-radius:var(--radius); display:flex; flex-direction:column; gap:8px; min-width:0; } +.mm-command-card h4 { font-size:14px; margin:0; } +.mm-command-card small { flex:1; } +.mm-command-card select,.mm-command-card input { width:100%; } +.mm-command-card .eyebrow { font-size:9px; } +.mm-command-card button { align-self:flex-start; } +.mm-record { padding:12px 0; border-bottom:1px solid var(--border); font-size:12px; overflow-wrap:anywhere; } +.mm-record strong { display:block; } +.mm-record summary { cursor:pointer; min-height:44px; } +.mm-record code { font-size:11px; } +.mm-info { display:grid; grid-template-columns:minmax(100px,1fr) minmax(0,2fr); gap:0; font-size:12px; } +.mm-info dt,.mm-info dd { margin:0; padding:10px 0; border-bottom:1px solid var(--border); overflow-wrap:anywhere; } +.mm-info dt { color:var(--muted); padding-right:12px; } +.mm-long-code { display:block; overflow-wrap:anywhere; font-size:11px; padding:12px; background:var(--surface-alt); margin-bottom:12px; white-space:pre-wrap; } +.mm-timeline { list-style:none; margin:0; padding:0 0 0 14px; border-left:1px solid var(--border); } +.mm-timeline li { position:relative; margin:0 0 18px; padding-left:12px; font-size:12px; overflow-wrap:anywhere; } +.mm-timeline li:before { content:''; position:absolute; left:-18px; top:5px; width:7px; height:7px; border-radius:50%; background:var(--accent); } +.mm-timeline small { font-size:10px; } +#mm-dialog { width:min(540px,calc(100vw - 24px)); max-height:85dvh; overflow:auto; } +#mm-dialog h2 { font-size:23px; margin:12px 0; } +.mm-confirm { display:flex; align-items:flex-start; gap:10px; font-size:12px; padding:14px 0; } +.mm-confirm input { flex-shrink:0; min-height:24px; width:24px; } +#mm-dialog-content { overflow-wrap:anywhere; font-size:13px; } +#mm-dialog-content p { margin-bottom:10px; } +@container (min-width:900px) { .mm-metrics { grid-template-columns:repeat(4,minmax(0,1fr)); } } +@container (max-width:520px) { .mm-charts,.mm-command-grid { grid-template-columns:1fr; } .mm-metric { padding:12px; } .mm-metric>strong { font-size:25px; } .mm-identity { align-items:flex-start; flex-direction:column; } .mm-info { grid-template-columns:1fr; } .mm-info dt { border:0; padding-bottom:0; } .mm-table td,.mm-table th { padding:8px 4px; font-size:10px; } } +@media(max-width:700px) { .mm-header { padding:10px 12px; } .mm-mark { display:none; } .mm-brand strong { font-size:15px; } .mm-header small { font-size:9px; } .mm-selector { padding:0 12px 10px; flex-wrap:wrap; } .mm-search { width:100%; } .mm-scroll { padding:14px; } .mm-nav { padding:0 6px; } .mm-nav button { padding:10px 8px; font-size:11px; } .mm-pill { font-size:9px; } .mm-identity h2 { font-size:22px; } } +.mm-login { flex:1; min-height:0; overflow:auto; display:grid; place-items:center; padding:24px; background:radial-gradient(ellipse at top,var(--surface-alt),var(--surface)); } +.mm-login-card { width:min(100%,360px); display:grid; gap:12px; color:var(--text); } +.mm-login-card h2 { margin:4px 0 0; font-size:24px; } +.mm-login-card p,.mm-login-card small { color:var(--muted); margin:0 0 8px; } +.mm-login-card input { width:100%; min-width:0; min-height:44px; background:var(--surface); color:var(--text); border:1px solid var(--border); border-radius:var(--small-radius); padding:10px 12px; } +.mm-login-card #mm-login-error { color:var(--text); border-left:3px solid #d45f69; padding-left:12px; } +.mm-login-card .mm-mark { width:52px; height:52px; } diff --git a/src/public/js/actions.js b/src/public/js/actions.js index 0de1df0..58cdf24 100644 --- a/src/public/js/actions.js +++ b/src/public/js/actions.js @@ -15,8 +15,9 @@ async function invokeAction(moduleId, actionId, buttonElement) { let originalContent = null; if (buttonElement) { originalContent = buttonElement.innerHTML; - buttonElement.innerHTML = "..."; + buttonElement.textContent = "Working…"; buttonElement.disabled = true; + buttonElement.setAttribute('aria-busy', 'true'); } try { @@ -46,74 +47,20 @@ async function invokeAction(moduleId, actionId, buttonElement) { if (buttonElement && originalContent !== null) { buttonElement.innerHTML = originalContent; buttonElement.disabled = false; + buttonElement.removeAttribute('aria-busy'); } } } -/** - * Show a notification message using NES.css styling - * @param {string} message - The message to display - * @param {string} type - 'success' or 'error' - */ +// Shared themed feedback for built-in applications and extensions. +let notificationTimer; function showNotification(message, type) { - // Remove any existing notification - const existing = document.getElementById("action-notification"); - if (existing) { - existing.remove(); - } - - // Create notification element - const notification = document.createElement("div"); - notification.id = "action-notification"; - notification.className = `nes-container ${type === "success" ? "is-success" : "is-error"}`; - notification.style.cssText = ` - position: fixed; - bottom: 20px; - right: 20px; - z-index: 9999; - max-width: 400px; - animation: slideIn 0.3s ease-out; - `; - notification.innerHTML = ` -

${message}

- `; - - document.body.appendChild(notification); - - // Play click sound for feedback - if (typeof clickButton === "function") { - clickButton(); - } - - // Auto-remove after 4 seconds - setTimeout(() => { - notification.style.animation = "slideOut 0.3s ease-in"; - setTimeout(() => notification.remove(), 300); - }, 4000); + const area = document.getElementById('notification-area'); + if (!area) return; + clearTimeout(notificationTimer); + const notification = document.createElement('div'); + notification.className = 'notification ' + (type === 'error' ? 'error' : 'success'); + notification.textContent = message; + area.replaceChildren(notification); + notificationTimer = setTimeout(() => notification.remove(), 6000); } - -// Add CSS animation styles -const styleSheet = document.createElement("style"); -styleSheet.textContent = ` - @keyframes slideIn { - from { - transform: translateX(100%); - opacity: 0; - } - to { - transform: translateX(0); - opacity: 1; - } - } - @keyframes slideOut { - from { - transform: translateX(0); - opacity: 1; - } - to { - transform: translateX(100%); - opacity: 0; - } - } -`; -document.head.appendChild(styleSheet); diff --git a/src/public/js/chirpstack-bridge.js b/src/public/js/chirpstack-bridge.js new file mode 100644 index 0000000..809198a --- /dev/null +++ b/src/public/js/chirpstack-bridge.js @@ -0,0 +1,51 @@ +/* Compatibility boundary for ChirpStack v4's root-based gRPC-Web client. */ +(function () { + 'use strict'; + if (!location.pathname.startsWith('/chirpstack/')) return; + function proxied(value) { + const url = new URL(String(value), location.href); + if (url.origin === location.origin && !url.pathname.startsWith('/chirpstack/')) { + url.pathname = '/chirpstack' + url.pathname; + } + return url.href; + } + const open = XMLHttpRequest.prototype.open; + XMLHttpRequest.prototype.open = function (method, url, ...args) { + return open.call(this, method, proxied(url), ...args); + }; + const fetch = window.fetch; + window.fetch = function (input, options) { + return fetch.call(this, input instanceof Request ? new Request(proxied(input.url), input) : proxied(input), options); + }; + // Bundlers construct some lazy CSS/script URLs at runtime, after HTML rewriting. + // Map them before the browser starts loading; leave hash-router anchors alone. + const resources = [[HTMLImageElement, 'src'], [HTMLScriptElement, 'src'], [HTMLLinkElement, 'href']]; + for (const [Type, property] of resources) { + const descriptor = Object.getOwnPropertyDescriptor(Type.prototype, property); + if (descriptor?.set) Object.defineProperty(Type.prototype, property, { + ...descriptor, set(value) { descriptor.set.call(this, proxied(value)); }, + }); + } + const setAttribute = Element.prototype.setAttribute; + Element.prototype.setAttribute = function (name, value) { + const resource = resources.some(([Type, property]) => this instanceof Type && name.toLowerCase() === property); + return setAttribute.call(this, name, resource ? proxied(value) : value); + }; + // ChirpStack clears localStorage on logout. Keep console preferences intact. + for (const name of ['localStorage', 'sessionStorage']) { + try { + const storage = window[name]; + const prefix = 'm3tering.chirpstack.'; + const keys = () => Object.keys(storage).filter(key => key.startsWith(prefix)); + const scoped = { + get length() { return keys().length; }, + key(index) { return keys()[index]?.slice(prefix.length) ?? null; }, + getItem(key) { return storage.getItem(prefix + key); }, + setItem(key, value) { storage.setItem(prefix + key, value); }, + removeItem(key) { storage.removeItem(prefix + key); }, + clear() { keys().forEach(key => storage.removeItem(key)); }, + }; + Object.defineProperty(window, name, { value: scoped }); + } catch { /* Browser storage restrictions are handled by the upstream UI. */ } + } +})(); diff --git a/src/public/js/click.js b/src/public/js/click.js index 5b8578b..a894b63 100644 --- a/src/public/js/click.js +++ b/src/public/js/click.js @@ -1,14 +1,15 @@ +let interfaceClick; function clickButton() { - var click = new Audio("/assets/rclick-13693.mp3"); - click.play(); + if (!window.Desktop?.getPreferences().sounds) return; + interfaceClick ||= new Audio('/assets/rclick-13693.mp3'); + interfaceClick.currentTime = 0; + interfaceClick.play().catch(() => {}); } - function deleteMeter(publicKey) { - console.log(encodeURIComponent(publicKey)); clickButton(); - fetch("/delete-meter?publicKey=" + encodeURIComponent(publicKey), { - method: 'DELETE', - }).then(_res => { - window.location.reload() - }, err => console.log(err)); + fetch('/delete-meter?publicKey=' + encodeURIComponent(publicKey), { method: 'DELETE' }) + .then(async response => { + if (!response.ok) throw new Error((await response.json()).message || 'Unable to delete meter'); + window.location.reload(); + }).catch(error => showNotification(error.message, 'error')); } diff --git a/src/public/js/desktop-layout.js b/src/public/js/desktop-layout.js new file mode 100644 index 0000000..798b338 --- /dev/null +++ b/src/public/js/desktop-layout.js @@ -0,0 +1,51 @@ +/* Pure grid calculations shared by pointer, keyboard, resize, and tests. */ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.DesktopLayout = api; +})(typeof globalThis !== 'undefined' ? globalThis : this, function () { + 'use strict'; + const clamp = (n, min, max) => Math.min(max, Math.max(min, n)); + function dimensions(width, height, size, count) { + const cell = { small: [88, 100], medium: [108, 116], large: [128, 138] }[size] || [108, 116]; + const cols = Math.max(1, Math.floor(width / cell[0])); + const visibleRows = Math.max(1, Math.floor(height / cell[1])); + const rows = Math.max(visibleRows, Math.ceil(count / cols)); + return { cols, rows, cellWidth: Math.min(cell[0], width), cellHeight: cell[1], height: rows * cell[1] }; + } + function arrange(ids, grid, saved = {}, flow = 'row') { + const positions = Object.create(null); + const occupied = new Set(); + const cells = []; + for (let i = 0; i < grid.cols * grid.rows; i++) { + cells.push(flow === 'column' ? { col: Math.floor(i / grid.rows), row: i % grid.rows } : + { col: i % grid.cols, row: Math.floor(i / grid.cols) }); + } + const key = p => `${p.col},${p.row}`; + const pending = []; + // Reserve existing positions before assigning new applications. + ids.forEach(id => { + const original = Object.hasOwn(saved, id) && saved[id]; + if (!original) { pending.push(id); return; } + const p = { col: clamp(original.col, 0, grid.cols - 1), row: clamp(original.row, 0, grid.rows - 1) }; + if (occupied.has(key(p))) pending.push(id); + else { positions[id] = p; occupied.add(key(p)); } + }); + let cursor = 0; + pending.forEach(id => { + while (cursor < cells.length && occupied.has(key(cells[cursor]))) cursor++; + if (cursor < cells.length) { positions[id] = cells[cursor]; occupied.add(key(cells[cursor++])); } + }); + return positions; + } + function move(positions, id, target, grid) { + const next = Object.assign(Object.create(null), positions); + if (!Object.hasOwn(next, id)) return next; + const dest = { col: clamp(target.col, 0, grid.cols - 1), row: clamp(target.row, 0, grid.rows - 1) }; + const occupant = Object.keys(next).find(other => other !== id && next[other].col === dest.col && next[other].row === dest.row); + if (occupant) next[occupant] = next[id]; + next[id] = dest; + return next; + } + return { clamp, dimensions, arrange, move }; +}); diff --git a/src/public/js/desktop-preferences.js b/src/public/js/desktop-preferences.js new file mode 100644 index 0000000..97dbdb5 --- /dev/null +++ b/src/public/js/desktop-preferences.js @@ -0,0 +1,66 @@ +/* Shared, versioned preferences. Loaded before CSS to avoid a theme flash. */ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.DesktopPreferences = api; +})(typeof globalThis !== 'undefined' ? globalThis : this, function () { + 'use strict'; + const KEY = 'm3tering.desktop.v1'; + const themes = Object.freeze({ + retro: { name: 'Retro 8-Bit', description: 'Pixel soul. A familiar classic.', flow: 'column', color: '#173c39' }, + macos: { name: 'macOS Inspired', description: 'Soft light. Room to breathe.', flow: 'column', color: '#52445d' }, + linux: { name: 'Linux Inspired', description: 'Focused. Flexible. Yours.', flow: 'row', color: '#21252f' }, + windows: { name: 'Windows Inspired', description: 'A fresh perspective on work.', flow: 'column', color: '#173b68' }, + }); + function normalize(value) { + const data = value && typeof value === 'object' && !Array.isArray(value) ? value : {}; + const positions = Object.create(null); + // Unknown versions fail back to defaults instead of interpreting an incompatible schema. + if (data.version !== undefined && data.version !== 1) return normalize({}); + if (data.positions && typeof data.positions === 'object' && !Array.isArray(data.positions)) { + Object.entries(data.positions).slice(0, 2000).forEach(([id, point]) => { + if (point && Number.isInteger(point.col) && Number.isInteger(point.row) && + point.col >= 0 && point.col < 1000 && point.row >= 0 && point.row < 1000) { + positions[id] = { col: point.col, row: point.row }; + } + }); + } + const appColorModes = Object.create(null); + if (data.appColorModes && typeof data.appColorModes === 'object') { + Object.entries(data.appColorModes).slice(0, 2000).forEach(([id, mode]) => { + if (['light', 'dark'].includes(mode)) appColorModes[id] = mode; + }); + } + return { + appColorModes, + version: 1, + theme: Object.hasOwn(themes, data.theme) ? data.theme : 'retro', + mode: data.mode === 'manual' ? 'manual' : 'auto', + iconSize: ['small', 'medium', 'large'].includes(data.iconSize) ? data.iconSize : 'medium', + background: ['theme', 'dusk', 'forest', 'plain'].includes(data.background) ? data.background : 'theme', + reduceMotion: data.reduceMotion === true, + sounds: data.sounds === true, + clock24: data.clock24 !== false, + positions, + }; + } + function load(storage) { + try { return normalize(JSON.parse((storage || localStorage).getItem(KEY))); } + catch (_) { return normalize({}); } + } + function save(value, storage) { + try { (storage || localStorage).setItem(KEY, JSON.stringify(normalize(value))); return true; } + catch (_) { return false; } + } + function apply(value) { + if (typeof document === 'undefined') return; + const prefs = normalize(value); + Object.assign(document.documentElement.dataset, { + theme: prefs.theme, background: prefs.background, iconSize: prefs.iconSize, + arrangement: prefs.mode, reducedMotion: String(prefs.reduceMotion), + }); + const meta = document.querySelector('meta[name="theme-color"]'); + if (meta) meta.content = themes[prefs.theme].color; + } + return { KEY, themes, normalize, load, save, apply }; +}); diff --git a/src/public/js/desktop.js b/src/public/js/desktop.js new file mode 100644 index 0000000..b95a092 --- /dev/null +++ b/src/public/js/desktop.js @@ -0,0 +1,519 @@ +/* One application registry and window environment, independent of visual theme. */ +(function () { + 'use strict'; + const P = DesktopPreferences; + const L = DesktopLayout; + let preferences = P.load(); + const $ = id => document.getElementById(id); + const all = (selector, parent = document) => [...parent.querySelectorAll(selector)]; + const mobile = window.matchMedia('(max-width: 700px)'); + const paths = { + manager: '', + radio: '', + meter: '', + terminal: '', + browser: '', + paint: '', + settings: '', + appearance: '', + grid: '', + sliders: '', + desktop: '', + search: '', + trash: '', + close: '', + minimize: '', + maximize: '', + }; + function svg(name) { return ``; } + all('[data-icon]').forEach(el => { el.innerHTML = svg(el.dataset.icon); }); + const registry = new Map(); + all('.desktop-icon').forEach(el => { + const id = el.dataset.appId; + if (registry.has(id)) return; + registry.set(id, { id, label: el.dataset.appLabel, description: el.dataset.appDescription, + windowId: el.dataset.windowId || id, icon: el.dataset.iconName || 'grid', element: el }); + el.setAttribute('aria-label', `Open ${el.dataset.appLabel}`); + el.setAttribute('aria-keyshortcuts', 'Alt+ArrowUp Alt+ArrowDown Alt+ArrowLeft Alt+ArrowRight'); + }); + const windows = new Map(); + let activeWindow = null; + let z = 5; + let grid; + let positions = Object.create(null); + let layoutFrame = 0; + let storageWarning = false; + const announce = message => { $('desktop-announcement').textContent = message; }; + function persist() { + if (!P.save(preferences) && !storageWarning) { + storageWarning = true; + showNotification('Browser storage is unavailable. Preferences will last for this visit only.', 'error'); + } + } + function updatePreferences(patch) { + preferences = P.normalize({ ...preferences, ...patch }); + P.apply(preferences); + windows.forEach(applyAppMode); + persist(); + syncSettings(); + scheduleLayout(); + updateClock(); + fitWindows(); + } + function updateClock() { + const now = new Date(); + $('desktop-clock').dateTime = now.toISOString(); + $('desktop-clock').textContent = new Intl.DateTimeFormat(undefined, { + ...(mobile.matches ? {} : { weekday: 'short' }), hour: '2-digit', minute: '2-digit', hour12: !preferences.clock24, + }).format(now); + $('desktop-clock').title = now.toLocaleDateString(undefined, { dateStyle: 'full' }); + } + function layout() { + const area = $('desktop-scroll'); + const width = Math.max(1, area.clientWidth - 4); + grid = L.dimensions(width, area.clientHeight, preferences.iconSize, registry.size); + positions = L.arrange([...registry.keys()], grid, preferences.mode === 'manual' ? preferences.positions : {}, + mobile.matches ? 'row' : P.themes[preferences.theme].flow); + $('desktop-icons').style.height = `${grid.height}px`; + const margin = mobile.matches ? Math.max(0, (width - grid.cols * grid.cellWidth) / 2) : 0; + $('desktop-icons').style.marginLeft = `${margin}px`; + registry.forEach(app => { + const p = positions[app.id]; + if (!p) return; + app.element.style.width = `${grid.cellWidth - 4}px`; + app.element.style.height = `${grid.cellHeight - 4}px`; + app.element.style.transform = `translate(${p.col * grid.cellWidth}px, ${p.row * grid.cellHeight}px)`; + }); + } + function scheduleLayout() { + cancelAnimationFrame(layoutFrame); + layoutFrame = requestAnimationFrame(layout); + } + function setMode(mode) { + const patch = { mode }; + if (mode === 'manual' && !Object.keys(preferences.positions).length) patch.positions = positions; + updatePreferences(patch); + announce(mode === 'manual' ? 'Manual arrangement enabled. Hold and drag icons, or use Alt and arrow keys.' : 'Automatic arrangement enabled.'); + } + function commitMove(id, destination) { + const next = L.move(positions, id, destination, grid); + // Save by stable application ID only on drop or keyboard movement, not during pointer motion. + updatePreferences({ positions: next }); + const p = next[id]; + announce(`${registry.get(id).label} moved to column ${p.col + 1}, row ${p.row + 1}.`); + } + function resetLayout() { + if (Object.keys(preferences.positions).length) { + // Native dialogs retain returnValue between openings, including Escape. + $('reset-dialog').returnValue = 'cancel'; + $('reset-dialog').showModal(); + } + else updatePreferences({ mode: 'auto', positions: {} }); + } + $('reset-dialog').addEventListener('close', () => { + if ($('reset-dialog').returnValue === 'reset') { + updatePreferences({ mode: 'auto', positions: {} }); + announce('Desktop layout reset.'); + } + }); + // Pointer gestures support mouse, pen, and a deliberate touch hold. Before the + // hold, vertical motion scrolls the desktop instead of moving an application. + registry.forEach(app => { + const el = app.element; + let suppressClickUntil = 0; + el.addEventListener('click', () => { + if (performance.now() < suppressClickUntil) return; + all('.desktop-icon.selected').forEach(other => other.classList.remove('selected')); + el.classList.add('selected'); + launch(app.id); + }); + el.addEventListener('keydown', event => { + const directions = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }; + const dir = directions[event.key]; + if (!dir) return; + event.preventDefault(); + const p = positions[app.id]; + if (event.altKey && preferences.mode === 'manual') commitMove(app.id, { col: p.col + dir[0], row: p.row + dir[1] }); + else { + const candidates = [...registry.values()].filter(other => { + const q = positions[other.id]; + return dir[0] ? q.row === p.row && Math.sign(q.col - p.col) === dir[0] : q.col === p.col && Math.sign(q.row - p.row) === dir[1]; + }).sort((a, b) => Math.abs(positions[a.id].col - p.col) + Math.abs(positions[a.id].row - p.row) - Math.abs(positions[b.id].col - p.col) - Math.abs(positions[b.id].row - p.row)); + candidates[0]?.element.focus(); + } + }); + el.addEventListener('pointerdown', event => { + if (preferences.mode !== 'manual' || event.button !== 0 || !event.isPrimary) return; + const start = { x: event.clientX, y: event.clientY, scroll: $('desktop-scroll').scrollTop }; + const source = { ...positions[app.id] }; + const touch = event.pointerType === 'touch'; + let dragging = false; + let scrolling = false; + let destination = source; + const abort = new AbortController(); + const options = { signal: abort.signal }; + el.setPointerCapture(event.pointerId); + function begin() { + if (scrolling) return; + dragging = true; + el.classList.add('dragging'); + $('drop-target').hidden = false; + $('drop-target').style.width = `${grid.cellWidth - 4}px`; + $('drop-target').style.height = `${grid.cellHeight - 4}px`; + $('drop-target').style.transform = `translate(${source.col * grid.cellWidth}px,${source.row * grid.cellHeight}px)`; + announce(`Moving ${app.label}. Release to place, or press Escape to cancel.`); + } + const timer = touch ? setTimeout(begin, 350) : null; + function move(event) { + if (event.pointerId !== startPointer) return; + const dx = event.clientX - start.x; + const dy = event.clientY - start.y; + if (!dragging && Math.hypot(dx, dy) > 7) { + if (touch) { scrolling = true; clearTimeout(timer); } + else begin(); + } + if (scrolling) { $('desktop-scroll').scrollTop = start.scroll - dy; return; } + if (!dragging) return; + const bounds = $('desktop-scroll').getBoundingClientRect(); + if (event.clientY > bounds.bottom - 30) $('desktop-scroll').scrollTop += 12; + if (event.clientY < bounds.top + 30) $('desktop-scroll').scrollTop -= 12; + const y = source.row * grid.cellHeight + dy + $('desktop-scroll').scrollTop - start.scroll; + const x = source.col * grid.cellWidth + dx; + destination = { col: L.clamp(Math.round(x / grid.cellWidth), 0, grid.cols - 1), row: L.clamp(Math.round(y / grid.cellHeight), 0, grid.rows - 1) }; + el.style.transform = `translate(${L.clamp(x, 0, (grid.cols - 1) * grid.cellWidth)}px,${L.clamp(y, 0, (grid.rows - 1) * grid.cellHeight)}px)`; + $('drop-target').style.transform = `translate(${destination.col * grid.cellWidth}px,${destination.row * grid.cellHeight}px)`; + } + const startPointer = event.pointerId; + function finish(cancelled) { + clearTimeout(timer); + abort.abort(); + el.classList.remove('dragging'); + $('drop-target').hidden = true; + if (el.hasPointerCapture(startPointer)) el.releasePointerCapture(startPointer); + if (dragging || scrolling) suppressClickUntil = performance.now() + 500; + if (dragging && !cancelled) commitMove(app.id, destination); + else scheduleLayout(); + } + el.addEventListener('pointermove', move, options); + el.addEventListener('pointerup', () => finish(false), options); + el.addEventListener('pointercancel', () => finish(true), options); + el.addEventListener('lostpointercapture', () => finish(true), options); + window.addEventListener('blur', () => finish(true), options); + window.addEventListener('resize', () => finish(true), options); + document.addEventListener('keydown', e => { if (e.key === 'Escape') finish(true); }, options); + }); + }); + + function clearSelection(event) { + if (!event.target.closest?.('.desktop-icon')) all('.desktop-icon.selected').forEach(icon => icon.classList.remove('selected')); + } + document.addEventListener('pointerdown', clearSelection); + document.addEventListener('focusin', clearSelection); + + function applyAppMode(win) { + const mode = preferences.appColorModes[win.appId] || 'theme'; + win.element.dataset.colorMode = mode; + const control = win.element.querySelector('.window-color-mode'); + if (control) control.value = mode; + window.dispatchEvent(new CustomEvent('desktop:app-mode', { detail: { id: win.id, mode } })); + } + function windowBounds() { return { width: $('window-layer').clientWidth, height: $('window-layer').clientHeight }; } + function fitWindow(win) { + if (mobile.matches) return; + const area = windowBounds(); + const r = win.rect; + const width = Math.min(r.width, Math.max(1, area.width - 16)); + const height = Math.min(r.height, Math.max(1, area.height - 16)); + const x = L.clamp(r.x, 8, Math.max(8, area.width - width - 8)); + const y = L.clamp(r.y, 8, Math.max(8, area.height - height - 8)); + Object.assign(win.element.style, { left: `${x}px`, top: `${y}px`, width: `${width}px`, height: `${height}px` }); + } + function fitWindows() { windows.forEach(fitWindow); } + function syncDock() { + registry.forEach(app => { + const win = windows.get(app.windowId); + app.dock.classList.toggle('open', !!win?.open); + app.dock.classList.toggle('active', activeWindow === app.windowId && win?.appId === app.id && !win?.minimized); + app.dock.setAttribute('aria-label', `${app.label}${win?.open ? ' (open)' : ''}`); + }); + } + function activate(win, focus = false) { + windows.forEach(other => other.element.classList.toggle('is-active', other === win)); + activeWindow = win?.id || null; + if (win) { + win.element.style.zIndex = ++z; + if (focus) win.element.querySelector('.window-titlebar').focus({ preventScroll: true }); + } + $('active-app-name').textContent = win ? win.element.dataset.windowTitle : 'Desktop'; + syncDock(); + } + function nextWindow() { + const remaining = [...windows.values()].filter(win => win.open && !win.minimized).sort((a, b) => Number(b.element.style.zIndex) - Number(a.element.style.zIndex)); + activate(remaining[0] || null, !!remaining.length); + } + function minimize(win) { + win.minimized = true; win.element.hidden = true; nextWindow(); + if (!activeWindow) registry.get(win.appId)?.dock.focus(); + } + function close(win) { + win.open = false; win.minimized = false; win.element.hidden = true; + if (win.id === 'terminal') cleanupTerminal(); + window.dispatchEvent(new CustomEvent('desktop:close', { detail: { id: win.id } })); + nextWindow(); + if (!activeWindow) registry.get(win.appId)?.element.focus(); + } + function maximize(win) { + win.maximized = !win.maximized; + win.element.classList.toggle('is-maximized', win.maximized); + win.element.querySelector('.window-maximize').setAttribute('aria-label', win.maximized ? 'Restore window' : 'Maximize window'); + fitWindow(win); + } + all('.app-window').forEach((element, index) => { + const app = [...registry.values()].find(app => app.windowId === element.id); + const win = { id: element.id, appId: app?.id, element, open: false, minimized: false, maximized: false, + rect: { x: 110 + index * 18, y: 28 + index * 10, width: Number(element.dataset.windowWidth) || (element.id === 'settings' ? 900 : 820), height: Number(element.dataset.windowHeight) || 620 } }; + windows.set(win.id, win); + const header = document.createElement('header'); + header.className = 'window-titlebar'; + header.tabIndex = -1; + const title = document.createElement('span'); + title.className = 'window-title'; + title.innerHTML = svg(app?.icon || 'grid'); + title.append(document.createTextNode(element.dataset.windowTitle)); + header.append(title); + const controls = document.createElement('div'); + controls.className = 'window-controls'; + [['minimize', 'Minimize window', () => minimize(win)], ['maximize', 'Maximize window', () => maximize(win)], ['close', 'Close window', () => close(win)]].forEach(([action, label, callback]) => { + const button = document.createElement('button'); + button.className = `window-${action}`; + button.setAttribute('aria-label', label); + button.title = label; + button.innerHTML = svg(action); + button.addEventListener('click', callback); + controls.append(button); + }); + const colorMode = document.createElement('select'); + colorMode.className = 'window-color-mode'; colorMode.setAttribute('aria-label', 'Application color mode'); + colorMode.title = element.querySelector('iframe') ? 'Window appearance. Embedded websites have their own appearance settings.' : 'Choose this application’s appearance'; + [['theme','Theme'],['light','Light'],['dark','Dark']].forEach(([value,label]) => { + const option = document.createElement('option'); option.value = value; option.textContent = label; colorMode.append(option); + }); + colorMode.addEventListener('change', () => { + const modes = { ...preferences.appColorModes }; + if (colorMode.value === 'theme') delete modes[win.appId]; else modes[win.appId] = colorMode.value; + updatePreferences({ appColorModes: modes }); + }); + header.append(colorMode, controls); + applyAppMode(win); + element.prepend(header); + const resize = document.createElement('button'); + resize.className = 'window-resize'; + resize.setAttribute('aria-label', 'Resize window with arrow keys'); + resize.title = 'Drag to resize, or focus and use arrow keys'; + element.append(resize); + element.addEventListener('pointerdown', () => { if (activeWindow !== win.id) activate(win); }); + element.addEventListener('focusin', () => { if (activeWindow !== win.id) activate(win); }); + header.addEventListener('dblclick', event => { if (!event.target.closest('button, select') && !mobile.matches) maximize(win); }); + function gesture(event, resizing) { + if (mobile.matches || win.maximized || event.button !== 0 || !event.isPrimary || (!resizing && event.target.closest('button, select'))) return; + event.preventDefault(); + activate(win); + const rect = element.getBoundingClientRect(); + const area = $('window-layer').getBoundingClientRect(); + const initial = { x: rect.left - area.left, y: rect.top - area.top, width: rect.width, height: rect.height }; + const start = { x: event.clientX, y: event.clientY }; + const abort = new AbortController(); + const target = event.currentTarget; + target.setPointerCapture(event.pointerId); + const id = event.pointerId; + function finish() { abort.abort(); if (target.hasPointerCapture(id)) target.releasePointerCapture(id); } + target.addEventListener('pointermove', e => { + const bounds = windowBounds(); + const dx = e.clientX - start.x; + const dy = e.clientY - start.y; + win.rect = resizing ? { ...initial, width: L.clamp(initial.width + dx, Math.min(360, bounds.width - 16), bounds.width - initial.x - 8), height: L.clamp(initial.height + dy, Math.min(240, bounds.height - 16), bounds.height - initial.y - 8) } : + { ...initial, x: L.clamp(initial.x + dx, 8, Math.max(8, bounds.width - initial.width - 8)), y: L.clamp(initial.y + dy, 8, Math.max(8, bounds.height - initial.height - 8)) }; + fitWindow(win); + }, { signal: abort.signal }); + ['pointerup', 'pointercancel', 'lostpointercapture'].forEach(type => target.addEventListener(type, finish, { signal: abort.signal })); + window.addEventListener('blur', finish, { signal: abort.signal }); + window.addEventListener('resize', finish, { signal: abort.signal }); + } + header.addEventListener('pointerdown', e => gesture(e, false)); + resize.addEventListener('pointerdown', e => gesture(e, true)); + resize.addEventListener('keydown', e => { + if (!e.key.startsWith('Arrow')) return; + e.preventDefault(); + const bounds = windowBounds(); + win.rect.width = L.clamp(win.rect.width + (e.key === 'ArrowRight' ? 20 : e.key === 'ArrowLeft' ? -20 : 0), 360, Math.max(360, bounds.width - 16)); + win.rect.height = L.clamp(win.rect.height + (e.key === 'ArrowDown' ? 20 : e.key === 'ArrowUp' ? -20 : 0), 240, Math.max(240, bounds.height - 16)); + fitWindow(win); + }); + }); + function launch(id) { + const app = registry.get(id); + const win = app && windows.get(app.windowId); + if (!win) { showNotification('This extension has no application window available.', 'error'); return; } + closeLauncher(false); + $('desktop-context').hidden = true; + const wasOpen = win.open; + win.open = true; win.minimized = false; win.appId = id; + applyAppMode(win); + win.element.hidden = false; + fitWindow(win); + activate(win, true); + if (!wasOpen && win.id === 'terminal') showTerminalAuth(); + window.dispatchEvent(new CustomEvent('desktop:open', { detail: { id: win.id } })); + const frame = win.element.querySelector('iframe[data-src]'); + if (frame && !frame.hasAttribute('src')) frame.src = frame.dataset.src; + if (id === 'paint') { + win.element.querySelector('iframe').src = 'https://basepaint.xyz/'; + $('browser-location').textContent = 'basepaint.xyz'; + $('browser-external').href = 'https://basepaint.xyz/'; + } + clickButton(); + } + $('chirpstack-reload').addEventListener('click', () => { + const frame = $('chirpstack-frame'); + frame.src = frame.dataset.src; + }); + registry.forEach(app => { + const art = app.element.querySelector('.app-art'); + const dock = document.createElement('button'); + dock.className = 'dock-app'; + dock.dataset.appId = app.id; + dock.title = app.label; + dock.append(art.cloneNode(true)); + dock.addEventListener('click', () => { + const win = windows.get(app.windowId); + if (win?.open && !win.minimized && activeWindow === win.id && win.appId === app.id) minimize(win); + else launch(app.id); + }); + app.dock = dock; + $('dock-apps').append(dock); + const item = document.createElement('button'); + item.className = 'launcher-app'; + item.dataset.appId = app.id; + item.append(art.cloneNode(true)); + const label = document.createElement('span'); label.textContent = app.label; item.append(label); + item.title = app.description; + item.addEventListener('click', () => launch(app.id)); + app.launcher = item; + $('launcher-apps').append(item); + }); + let launcherOpener; + function closeLauncher(restoreFocus = true) { + const wasOpen = !$('app-launcher').hidden; + $('app-launcher').hidden = true; + all('[data-launcher-toggle]').forEach(el => el.setAttribute('aria-expanded', 'false')); + if (wasOpen && restoreFocus) launcherOpener?.focus(); + } + all('[data-launcher-toggle]').forEach(button => button.addEventListener('click', () => { + if (!$('app-launcher').hidden) { closeLauncher(); return; } + launcherOpener = button; + $('desktop-context').hidden = true; + $('app-launcher').hidden = false; + all('[data-launcher-toggle]').forEach(el => el.setAttribute('aria-expanded', 'true')); + $('app-search').value = ''; + filterLauncher(); + $('app-search').focus(); + })); + $('close-launcher').addEventListener('click', () => closeLauncher()); + function filterLauncher() { + const query = $('app-search').value.trim().toLocaleLowerCase(); + let count = 0; + registry.forEach(app => { app.launcher.hidden = !`${app.label} ${app.description}`.toLocaleLowerCase().includes(query); if (!app.launcher.hidden) count++; }); + $('launcher-empty').hidden = count > 0; + } + $('app-search').addEventListener('input', filterLauncher); + $('app-search').addEventListener('keydown', e => { + if (e.key === 'Enter') [...registry.values()].find(app => !app.launcher.hidden)?.launcher.click(); + if (e.key === 'ArrowDown') { e.preventDefault(); [...registry.values()].find(app => !app.launcher.hidden)?.launcher.focus(); } + }); + $('app-launcher').addEventListener('keydown', e => { + if (e.key !== 'Tab') return; + const items = all('button:not([hidden]), input', $('app-launcher')); + const first = items[0], last = items.at(-1); + if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } + }); + let desktopHidden = []; + $('show-desktop').addEventListener('click', () => { + closeLauncher(false); + const visible = [...windows.values()].filter(win => win.open && !win.minimized); + if (visible.length) { + desktopHidden = visible.sort((a, b) => Number(a.element.style.zIndex) - Number(b.element.style.zIndex)).map(win => win.id); + visible.forEach(win => { win.minimized = true; win.element.hidden = true; }); + activate(null); + $('show-desktop').setAttribute('aria-label', 'Restore open windows'); + } else { + desktopHidden.forEach(id => { const win = windows.get(id); if (win.open) { win.minimized = false; win.element.hidden = false; activate(win); } }); + desktopHidden = []; + $('show-desktop').setAttribute('aria-label', 'Show desktop'); + } + }); + + Object.entries(P.themes).forEach(([id, theme]) => { + const card = document.createElement('button'); + card.className = 'theme-card'; card.dataset.themeChoice = id; + card.setAttribute('aria-label', `Apply ${theme.name} theme`); + card.innerHTML = `${theme.name}✓${theme.description}`; + card.addEventListener('click', () => { updatePreferences({ theme: id }); announce(`${theme.name} theme applied.`); }); + $('theme-cards').append(card); + }); + function syncSettings() { + all('[data-theme-choice]').forEach(el => el.setAttribute('aria-pressed', String(el.dataset.themeChoice === preferences.theme))); + all('[data-background]').filter(el => el.tagName === 'BUTTON').forEach(el => el.setAttribute('aria-pressed', String(el.dataset.background === preferences.background))); + all('input[name="arrangement"]').forEach(el => { el.checked = el.value === preferences.mode; }); + $('icon-size').value = preferences.iconSize; + $('reduce-motion').checked = preferences.reduceMotion; + $('interface-sounds').checked = preferences.sounds; + $('clock-24').checked = preferences.clock24; + $('context-arrange').textContent = preferences.mode === 'auto' ? 'Arrange icons manually' : 'Arrange icons automatically'; + } + all('[data-open-settings]').forEach(el => el.addEventListener('click', () => launch('settings'))); + all('[data-settings-tab]').forEach(el => el.addEventListener('click', () => { + all('[data-settings-tab]').forEach(tab => { if (tab === el) tab.setAttribute('aria-current', 'page'); else tab.removeAttribute('aria-current'); }); + all('[data-settings-panel]').forEach(panel => { panel.hidden = panel.dataset.settingsPanel !== el.dataset.settingsTab; }); + document.querySelector('.settings-content').scrollTop = 0; + })); + all('button[data-background]').forEach(el => el.addEventListener('click', () => updatePreferences({ background: el.dataset.background }))); + all('input[name="arrangement"]').forEach(el => el.addEventListener('change', () => setMode(el.value))); + $('icon-size').addEventListener('change', e => updatePreferences({ iconSize: e.target.value })); + [['reduce-motion', 'reduceMotion'], ['interface-sounds', 'sounds'], ['clock-24', 'clock24']].forEach(([id, key]) => $(id).addEventListener('change', e => updatePreferences({ [key]: e.target.checked }))); + $('reset-layout').addEventListener('click', resetLayout); + $('context-reset').addEventListener('click', () => { $('desktop-context').hidden = true; resetLayout(); }); + $('context-arrange').addEventListener('click', () => { $('desktop-context').hidden = true; setMode(preferences.mode === 'auto' ? 'manual' : 'auto'); }); + $('desktop').addEventListener('contextmenu', event => { + if (event.target.closest('.app-window')) return; + event.preventDefault(); + closeLauncher(false); + const menu = $('desktop-context'); menu.hidden = false; + menu.style.left = `${L.clamp(event.clientX, 8, innerWidth - menu.offsetWidth - 8)}px`; + menu.style.top = `${L.clamp(event.clientY, 8, innerHeight - menu.offsetHeight - 8)}px`; + menu.querySelector('button').focus(); + }); + document.addEventListener('pointerdown', e => { + if (!e.target.closest('#app-launcher,[data-launcher-toggle]')) closeLauncher(false); + if (!e.target.closest('#desktop-context')) $('desktop-context').hidden = true; + }); + document.addEventListener('keydown', e => { + if (e.key === 'Escape') { closeLauncher(); $('desktop-context').hidden = true; } + }); + const observer = new ResizeObserver(() => { scheduleLayout(); fitWindows(); }); + observer.observe($('desktop-scroll')); + mobile.addEventListener('change', () => { scheduleLayout(); fitWindows(); updateClock(); }); + window.addEventListener('storage', e => { + if (e.key !== P.KEY) return; + preferences = P.load(); P.apply(preferences); syncSettings(); scheduleLayout(); fitWindows(); updateClock(); + }); + P.apply(preferences); + syncSettings(); layout(); fitWindows(); syncDock(); updateClock(); + const clockTimer = setInterval(updateClock, 1000 * 15); + window.addEventListener('pagehide', e => { if (!e.persisted) { observer.disconnect(); clearInterval(clockTimer); } }); + window.Desktop = Object.freeze({ + launch, + close: id => { const win = windows.get(registry.get(id)?.windowId || id); if (win) close(win); }, + getPreferences: () => P.normalize(preferences), + }); +})(); diff --git a/src/public/js/m3ter-charts.js b/src/public/js/m3ter-charts.js new file mode 100644 index 0000000..4ec09fd --- /dev/null +++ b/src/public/js/m3ter-charts.js @@ -0,0 +1,41 @@ +(function () { + 'use strict'; + const svgNS = 'http://www.w3.org/2000/svg'; + const label = (tag, text, className) => { const node = document.createElement(tag); node.textContent = text; if (className) node.className = className; return node; }; + window.M3terCharts = { + render(container, readings, field) { + container.replaceChildren(); + const unit = field === 'energy' ? 'kWh' : 'V'; + const rows = readings.filter(row => Number.isFinite(row[field]) && Number.isFinite(row.timestamp)); + if (!rows.length) { container.append(label('p', 'No readings in this range. Waiting for a valid uplink.', 'mm-note')); return; } + const minTime = rows[0].timestamp, maxTime = rows[rows.length - 1].timestamp; + const values = rows.map(row => row[field]); + const bottom = Math.min(...values), top = Math.max(...values), pad = Math.max((top - bottom) * .12, field === 'energy' ? .000001 : 1); + const low = Math.max(0, bottom - pad), high = top + pad; + const x = row => maxTime === minTime ? 320 : 8 + (row.timestamp - minTime) / (maxTime - minTime) * 624; + const y = row => 150 - (row[field] - low) / (high - low) * 140; + const axes = label('div', '', 'mm-chart-axis'); axes.append(label('span', `${high.toFixed(field === 'energy' ? 6 : 1)} ${unit}`), label('span', `${low.toFixed(field === 'energy' ? 6 : 1)} ${unit}`)); + const svg = document.createElementNS(svgNS, 'svg'); svg.setAttribute('viewBox', '0 0 640 160'); svg.setAttribute('preserveAspectRatio', 'none'); svg.setAttribute('tabindex', '0'); svg.setAttribute('role', 'img'); + svg.setAttribute('aria-label', `${field === 'energy' ? 'Cumulative energy' : 'Voltage'} chart, ${rows.length} points. Use left and right arrows to inspect readings. Energy lines break at observed accumulator decreases.`); + const grid = document.createElementNS(svgNS, 'path'); grid.setAttribute('d', 'M0 10H640 M0 80H640 M0 150H640'); grid.setAttribute('stroke', 'var(--border)'); grid.setAttribute('stroke-width', '1'); svg.append(grid); + const line = document.createElementNS(svgNS, 'path'); + line.setAttribute('d', rows.map((row, i) => `${i === 0 || (field === 'energy' && row.segment !== rows[i - 1].segment) ? 'M' : 'L'}${x(row).toFixed(2)} ${y(row).toFixed(2)}`).join(' ')); + line.setAttribute('stroke-width', '2'); line.setAttribute('vector-effect', 'non-scaling-stroke'); line.setAttribute('fill', 'none'); svg.append(line); + const point = document.createElementNS(svgNS, 'circle'); point.setAttribute('r', '4'); point.setAttribute('fill', 'var(--accent)'); svg.append(point); + const times = label('div', '', 'mm-chart-axis'); times.append(label('span', new Date(minTime).toLocaleString()), label('span', new Date(maxTime).toLocaleString())); + const tooltip = label('div', '', 'mm-chart-tooltip'); tooltip.setAttribute('aria-live', 'polite'); + let index = rows.length - 1; + function inspect(next) { + index = Math.max(0, Math.min(rows.length - 1, next)); const row = rows[index]; + point.setAttribute('cx', x(row)); point.setAttribute('cy', y(row)); + tooltip.textContent = `${new Date(row.timestamp).toLocaleString()} · ${row[field].toFixed(field === 'energy' ? 6 : 1)} ${unit}`; + } + svg.addEventListener('pointermove', event => { + const bounds = svg.getBoundingClientRect(), target = (event.clientX - bounds.left) / bounds.width * 640; + let nearest = 0; rows.forEach((row, i) => { if (Math.abs(x(row) - target) < Math.abs(x(rows[nearest]) - target)) nearest = i; }); inspect(nearest); + }); + svg.addEventListener('keydown', event => { if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) { event.preventDefault(); inspect(event.key === 'Home' ? 0 : event.key === 'End' ? rows.length - 1 : index + (event.key === 'ArrowLeft' ? -1 : 1)); } }); + inspect(index); container.append(axes, svg, times, tooltip); + }, + }; +})(); diff --git a/src/public/js/m3ter-commands.js b/src/public/js/m3ter-commands.js new file mode 100644 index 0000000..426ff5c --- /dev/null +++ b/src/public/js/m3ter-commands.js @@ -0,0 +1,120 @@ +(function () { + 'use strict'; + window.M3terCommands = function ({ api, selected, showError, clearError, notice, element, refresh, text, node }) { + const $ = element; + const dialog = $('mm-dialog'), submit = $('mm-submit'), confirm = $('mm-confirm'); + let intent = null, working = false, catalogue = [], historyOffset = 0; + const uuid = () => crypto.randomUUID ? crypto.randomUUID() : '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c => (Number(c) ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> Number(c) / 4).toString(16)); + function display(title, content, button, sensitive) { + text('mm-dialog-title', title); $('mm-dialog-content').replaceChildren(...content); + submit.textContent = button || 'Close'; submit.hidden = !button; + $('mm-cancel').textContent = button ? 'Cancel' : 'Close'; + $('mm-confirm-label').hidden = !sensitive; confirm.checked = false; submit.disabled = !!sensitive; + if (!dialog.open) dialog.showModal(); + } + confirm.addEventListener('change', () => { submit.disabled = !confirm.checked; }); + $('mm-cancel').addEventListener('click', () => { if (!working) dialog.close(); }); + dialog.addEventListener('cancel', event => { if (working) event.preventDefault(); }); + dialog.addEventListener('close', () => { if (!working) intent = null; }); + async function preview(id, value) { + const device = selected(); if (!device?.devEui || working) return; + notice('Preparing command preview…'); + try { + const command = await api('/commands/preview', { method: 'POST', body: { commandId: id, ...(value === undefined ? {} : { value }) } }); + if (selected()?.devEui !== device.devEui) return; + intent = { type: 'command', devEui: device.devEui, command, requestId: uuid() }; + const parts = [node('p', `${device.name} · ${device.devEui}`), node('p', command.description), + node('code', `FPort ${command.fPort} · ${command.length} byte${command.length === 1 ? '' : 's'}\nHex: ${command.hex}\nBase64: ${command.data}`, 'mm-long-code'), + node('p', 'Unconfirmed downlink. Acceptance into the queue does not verify delivery or execution.', 'mm-note')]; + if (command.confirmation) parts.push(node('p', command.confirmation, 'mm-notice')); + if (command.parameter) parts.splice(1, 0, node('p', `Selected setting: ${command.parameter}`, 'mm-notice')); + if (id === 'report-interval' && value < 60) parts.push(node('p', 'Short intervals consume more LoRaWAN airtime.', 'mm-notice')); + display(command.name, parts, 'Enqueue command', command.requiresConfirmation); notice(''); + } catch (error) { showError(error); } + } + $('mm-dialog-form').addEventListener('submit', async event => { + event.preventDefault(); if (!intent || working || (! $('mm-confirm-label').hidden && !confirm.checked)) return; + const current = intent; working = true; submit.disabled = true; $('mm-cancel').disabled = true; + try { + if (current.type === 'clear') { + notice('Clearing pending downlinks…'); + await api(`/devices/${current.devEui}/queue`, { method: 'DELETE', body: { confirmDevEui: current.devEui } }); + notice('Pending queue cleared. Previously transmitted commands cannot be recalled.'); + } else { + notice('Enqueuing command…'); + const result = await api(`/devices/${current.devEui}/commands`, { method: 'POST', body: { requestId: current.requestId, + commandId: current.command.id, value: current.command.value, confirmedSafety: confirm.checked } }); + notice(`${result.command.name}: ${result.status}. ${result.detail || ''}`); + } + intent = null; working = false; dialog.close(); + if (selected()?.devEui === current.devEui) await refresh(); + } catch (error) { + // Retain the request ID after a lost response so retry cannot enqueue twice. + showError(error); notice(current.type === 'clear' ? 'Queue clearing did not complete. Inspect the queue before retrying: another clear removes ALL items pending at that time.' : 'The request did not complete. Retry uses the same request ID; inspect the queue if the outcome is uncertain.'); + if (current.type === 'clear') confirm.checked = false; + $('mm-dialog-content').append(node('p', error.message, 'mm-notice mm-error')); + } finally { working = false; submit.disabled = !$('mm-confirm-label').hidden && !confirm.checked; $('mm-cancel').disabled = false; } + }); + $('mm-queue-clear').addEventListener('click', () => { + const device = selected(); if (!device?.devEui || working) return; + intent = { type: 'clear', devEui: device.devEui }; + display('Clear this meter’s queue?', [node('p', `${device.name} · ${device.devEui}`), node('p', 'This removes ALL currently queued downlinks for this meter, including commands queued outside M3ter Manager. Previously transmitted commands cannot be recalled.')], 'Clear all pending downlinks', true); + }); + function renderCatalogue(commands) { + catalogue = commands; const parent = $('mm-commands'); parent.replaceChildren(); + for (const command of catalogue) { + const card = node('article', '', 'mm-command-card'); card.append(node('span', command.category, 'eyebrow'), node('h4', command.name), node('small', command.description)); + let control; + if (command.options) { + control = node('select'); control.setAttribute('aria-label', command.name); + command.options.forEach(option => { const item = node('option', option.label); item.value = option.value; control.append(item); }); + } else if (command.min !== undefined) { + const presets = node('select'); presets.setAttribute('aria-label', 'Report interval presets'); + [10,15,30,60,300,900,1800,3600].forEach(seconds => { const option = node('option', seconds < 60 ? `${seconds} seconds` : `${seconds / 60} minutes`); option.value = seconds; presets.append(option); }); + const custom = node('option', 'Custom'); custom.value = 'custom'; presets.append(custom); presets.value = '60'; + control = node('input'); control.type = 'number'; control.min = command.min; control.max = command.max; control.step = 1; control.value = command.defaultValue; control.setAttribute('aria-label', 'Report interval seconds'); + presets.addEventListener('change', () => { if (presets.value !== 'custom') control.value = presets.value; }); + control.addEventListener('input', () => { presets.value = 'custom'; }); card.append(presets); + } + if (control) card.append(control); + const button = node('button', 'Preview command', 'nes-btn'); button.dataset.commandId = command.id; + button.addEventListener('click', () => { if (control && !control.reportValidity()) return; preview(command.id, control ? Number(control.value) : undefined); }); card.append(button); parent.append(card); + } + } + function recordDetails(title, command, detail) { + const section = node('details', '', 'mm-record'); section.append(node('summary', title), node('p', detail || 'No additional delivery information'), + node('code', `FPort ${command.fPort} · HEX ${command.hex} · Base64 ${command.data}`, 'mm-long-code')); + return section; + } + async function loadHistory(append = false) { + const device = selected(); if (!device?.devEui) return; + if (!append) historyOffset = 0; + const data = await api(`/devices/${device.devEui}/commands?offset=${historyOffset}`); + if (selected()?.devEui !== device.devEui) return; + const parent = $('mm-command-history'); if (!append) parent.replaceChildren(); + if (!data.commands.length && !append) parent.append(node('p', 'No commands have been submitted from M3ter Manager.', 'mm-note')); + data.commands.forEach(row => parent.append(recordDetails(`${new Date(row.timestamp).toLocaleString()} · ${row.command.name}${row.command.parameter ? ' · ' + row.command.parameter : ''} · ${row.status}`, row.command, + `${row.detail || 'Awaiting delivery evidence.'} Queue ID: ${row.queueId || 'Unavailable'} · Submitted by ${row.actor}`))); + historyOffset += data.commands.length; $('mm-commands-more').hidden = data.commands.length < 50; + } + async function loadQueue() { + const device = selected(); if (!device?.devEui) return; + const parent = $('mm-queue'); parent.replaceChildren(node('p', 'Loading pending queue…', 'mm-note')); + try { + const data = await api(`/devices/${device.devEui}/queue`); if (selected()?.devEui !== device.devEui) return; + parent.replaceChildren(); + if (!data.items.length) parent.append(node('p', 'No pending downlinks.', 'mm-note')); + if (data.total > data.items.length) parent.append(node('p', `Showing ${data.items.length} of ${data.total} queued items. Clear queue applies to ALL items.`, 'mm-note')); + data.items.forEach(item => parent.append(recordDetails(`${item.id || 'Queue item'} · ${item.isPending ? 'Pending delivery' : 'Queued'} · ${item.confirmed ? 'Confirmed' : 'Unconfirmed'}`, item, + `Created: ${item.createdAt ? new Date(item.createdAt).toLocaleString() : 'Unavailable'} · Expires: ${item.expiresAt ? new Date(item.expiresAt).toLocaleString() : 'Unavailable'}`))); + } catch (error) { if (selected()?.devEui === device.devEui) { parent.replaceChildren(node('p', error.message, 'mm-note')); } throw error; } + } + $('mm-queue-refresh').addEventListener('click', () => { clearError(); loadQueue().catch(showError); }); + $('mm-commands-more').addEventListener('click', () => loadHistory(true).catch(showError)); + document.querySelectorAll('[data-mm-command]').forEach(button => button.addEventListener('click', () => preview(button.dataset.mmCommand))); + return { renderCatalogue, loadHistory, loadQueue, + inspect(title, details) { intent = null; display(title, [node('code', details, 'mm-long-code')], null, false); }, + close(force = false) { if (force || !working) { dialog.close(); intent = null; } }, + }; + }; +})(); diff --git a/src/public/js/m3ter-manager.js b/src/public/js/m3ter-manager.js new file mode 100644 index 0000000..2153148 --- /dev/null +++ b/src/public/js/m3ter-manager.js @@ -0,0 +1,220 @@ +(function () { + 'use strict'; + const root = document.getElementById('m3ter-manager'); if (!root) return; + const $ = id => document.getElementById(id); + const text = (id, value) => { $(id).textContent = value; }; + const node = (tag, value = '', className = '') => { const result = document.createElement(tag); result.textContent = value; if (className) result.className = className; return result; }; + const date = value => value ? new Date(value).toLocaleString() : 'Unavailable'; + const fixed = (value, places) => typeof value === 'number' && Number.isFinite(value) ? value.toFixed(places) : '—'; + let authenticated = false, authVersion = 0; + let active = false, device = null, latest = null, state = null, config = null, tab = 'overview', monitoring = { state: 'disconnected' }; + let socket, reconnectTimer, clockTimer, refreshTimer, searchTimer, reconnectAttempt = 0, snapshotVersion = 0, searchVersion = 0; + let devices = [], deviceOffset = 0, historyOffset = 0, eventOffset = 0, historyData = null; + function notice(message) { text('mm-notice', message); $('mm-notice').hidden = !message; } + function showError(error) { if (!authenticated) return; if (error?.name === 'AbortError') return; text('mm-error', error.message || 'Unable to load meter data. Retry using Refresh.'); $('mm-error').hidden = false; } + function clearError() { $('mm-error').hidden = true; } + async function api(path, options = {}) { + const version = authVersion; + const response = await fetch('/api/m3ter-manager' + path, { ...options, headers: { 'Content-Type': 'application/json' }, + body: options.body === undefined ? undefined : JSON.stringify(options.body) }); + let data; try { data = await response.json(); } catch { throw new Error('Meter service is unavailable. Open M3ter Manager in the running console and retry.'); } + if (path !== '/session' && version !== authVersion) throw new DOMException('Session changed', 'AbortError'); + if (response.status === 401 && path !== '/session') lock('Your session ended. Sign in again.'); + if (!response.ok) throw new Error(data.error || 'Meter request failed. Please retry.'); return data; + } + const commands = M3terCommands({ api, selected: () => device, showError, clearError, notice, element: $, refresh, text, node }); + function range() { + const selected = $('mm-range').value; + if (selected !== 'custom') { const to = Date.now(); return { from: to - Number(selected), to }; } + const from = new Date($('mm-from').value).getTime(), to = new Date($('mm-to').value).getTime(); + if (!Number.isFinite(from) || !Number.isFinite(to) || from >= to || to - from > 366 * 86400000) throw new Error('Choose a valid date range of at most 366 days.'); + return { from, to }; + } + function relative(timestamp) { + if (!timestamp) return 'Never observed'; + const seconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)); + return seconds < 60 ? `${seconds}s ago` : seconds < 3600 ? `${Math.floor(seconds / 60)}m ago` : seconds < 86400 ? `${Math.floor(seconds / 3600)}h ago` : `${Math.floor(seconds / 86400)}d ago`; + } + function renderActivity() { + const status = monitoring.state || 'disconnected'; text('mm-mqtt', `MQTT ${status}`); $('mm-mqtt').dataset.state = status; + text('mm-last-message', `Last MQTT message: ${date(monitoring.lastMessage)}`); + const last = state?.lastUplink || null, recent = last && Date.now() - last <= (config?.inactiveMilliseconds || 300000); + text('mm-age', relative(last)); text('mm-uplink-time', date(last)); + text('mm-activity', !last ? 'No uplink observed' : recent ? 'Recent uplink' : 'No recent uplink'); $('mm-activity').dataset.state = recent ? 'active' : 'inactive'; + $('mm-activity').title = `Activity threshold: ${(config?.inactiveMilliseconds || 300000) / 1000} seconds. Connectivity is not verified.`; + } + function renderInfo() { + if (!device) return; + text('mm-name', device.name || device.devEui); text('mm-eui', device.devEui); + text('mm-energy', fixed(latest?.energy, 6)); text('mm-voltage', fixed(latest?.voltage, 1)); text('mm-nonce', latest?.nonce ?? '—'); + text('mm-energy-time', latest ? `${date(latest.timestamp)} · signed fields ${latest.verification}` : 'Awaiting telemetry'); + text('mm-voltage-note', device.phaseMode === 'three-phase' && latest ? `Sum of phases · calculated mean ${fixed(latest.voltage / 3, 1)} V (metadata mode)` : `Transmitted value · ${device.phaseMode || 'phase mode unknown'}`); + const values = [ + ['Meter', device.name], ['DevEUI', device.devEui], ['Application', device.applicationName || state?.metadata?.applicationName], + ['Device profile', device.deviceProfileName || state?.metadata?.deviceProfileName], ['LoRaWAN class (ChirpStack)', device.enabledClass], + ['Device enabled', device.isDisabled === undefined ? null : device.isDisabled ? 'Disabled in ChirpStack' : 'Enabled in ChirpStack'], + ['Last observed uplink', date(state?.lastUplink)], ['ChirpStack last seen', date(device.lastSeenAt)], ['Energy', latest ? `${fixed(latest.energy,6)} kWh` : null], + ['Voltage', latest ? `${fixed(latest.voltage,1)} V` : null], ['Nonce', latest?.nonce], ['Phase mode (metadata)', device.phaseMode], + ]; + $('mm-info').replaceChildren(...values.flatMap(([name, value]) => [node('dt', name), node('dd', value === null || value === undefined || value === '' ? 'Unavailable' : String(value))])); + const key = state?.publicKey || latest?.publicKey; + text('mm-public-key', key || 'Unavailable'); $('mm-copy-key').disabled = !key; + text('mm-verification', latest ? `Latest signed fields: ${latest.verification}. ${latest.verification === 'invalid' ? 'Do not treat this reading as authenticated.' : latest.verification === 'unverified' ? 'No known public key was available to verify this signature.' : 'Nonce and energy were checked with Ed25519.'}` : 'No signature available.'); + const location = state?.metadata?.location; $('mm-location').hidden = !location; + if (location) { + const link = node('a', 'View device location on OpenStreetMap ↗'); link.href = `https://www.openstreetmap.org/?mlat=${encodeURIComponent(location.latitude)}&mlon=${encodeURIComponent(location.longitude)}#map=15/${encodeURIComponent(location.latitude)}/${encodeURIComponent(location.longitude)}`; link.target = '_blank'; link.rel = 'noopener noreferrer'; + $('mm-location').replaceChildren(node('p', `Device location: ${location.latitude}, ${location.longitude} · ChirpStack location event`), link); + } + renderActivity(); + } + function renderHistory() { + if (!historyData) return; + for (const view of ['overview', 'history']) for (const field of ['energy','voltage']) M3terCharts.render($(`mm-${view}-${field}`), historyData.chart, field); + const summary = historyData.summary; + text('mm-summary', `${historyData.total} accumulator reports${historyData.sampled ? ' · chart sampled to at most 401 points' : ''}. Observed incremental energy: ${fixed(summary?.observedConsumption || 0, 6)} kWh. ${summary?.resets || 0} new nonce cycle(s), ${summary?.repeatedReports || 0} repeated total(s), ${summary?.uncertainReports || 0} uncertain report(s). Same-cycle repeats add zero; new cycles count their own accumulator. Initial baselines, missed cycles, and nonce regressions are not estimated. This is observed energy, not the collector’s acknowledged billing total.`); + const parent = $('mm-readings'); parent.replaceChildren(); + historyData.rows.forEach(row => { + const tr = node('tr'); [date(row.timestamp), fixed(row.energy,6), fixed(row.voltage,1), row.nonce, row.fPort].forEach(value => tr.append(node('td', String(value)))); + const td = node('td'), button = node('button', 'Inspect', 'nes-btn'); button.addEventListener('click', () => commands.inspect('Uplink details', + `Meter: ${row.devEui}\nUTC: ${new Date(row.timestamp).toISOString()}\nReceived: ${new Date(row.receivedAt).toISOString()}\nFPort: ${row.fPort}\nNonce: ${row.nonce}\nRaw energy: ${row.rawEnergy}\nAccumulator: ${row.energy} kWh\nIncremental energy: ${row.intervalEnergy ?? 'Unknown baseline'} kWh\nAccounting: ${row.accounting}\nRaw voltage: ${row.rawVoltage}\nVoltage: ${row.voltage} V\nSignature status: ${row.verification}\nSignature (hex): ${row.signature}\nPublic key: ${row.publicKey || 'Not present in this uplink'}\nRaw payload (Base64): ${row.rawPayload}\nRadio metadata: ${row.metadata}`)); td.append(button); tr.append(td); parent.append(tr); + }); + if (!historyData.rows.length) { const tr = node('tr'), cell = node('td', 'No readings in this range.'); cell.colSpan = 6; tr.append(cell); parent.append(tr); } + text('mm-history-count', `${historyData.total ? historyOffset + 1 : 0}–${Math.min(historyOffset + historyData.rows.length, historyData.total)} of ${historyData.total}`); + $('mm-history-prev').disabled = !historyOffset; $('mm-history-next').disabled = historyOffset + 50 >= historyData.total; + } + async function loadEvents(append = false) { + const current = device?.devEui; if (!current) return; + if (!append) eventOffset = 0; + const data = await api(`/devices/${current}/events?offset=${eventOffset}`); if (device?.devEui !== current) return; + const parent = $('mm-events'); if (!append) parent.replaceChildren(); + if (!data.events.length && !append) parent.append(node('li', 'No activity recorded yet.')); + data.events.forEach(event => { const li = node('li'); li.append(node('strong', event.message), node('small', `${date(event.timestamp)} · ${event.source}${event.devEui ? '' : ' · application-wide'}`)); parent.append(li); }); + eventOffset += data.events.length; $('mm-events-more').hidden = data.events.length < 100; + } + async function refresh(telemetryOnly = false) { + if (!device) return; + const current = device.devEui, version = ++snapshotVersion; + let times; try { times = range(); } catch (error) { showError(error); return; } + $('mm-selected').setAttribute('aria-busy', 'true'); + const results = await Promise.allSettled([ + telemetryOnly ? Promise.resolve({ device, state, latest }) : api(`/devices/${current}`), api(`/devices/${current}/history?${new URLSearchParams({ ...times, offset: historyOffset })}`), + ]); + if (version !== snapshotVersion || device?.devEui !== current || !active) return; + if (results[0].status === 'fulfilled') { device = { ...device, ...results[0].value.device }; state = results[0].value.state; latest = results[0].value.latest; } + else showError(results[0].reason); + if (results[1].status === 'fulfilled') { historyData = results[1].value; latest = historyData.latest; state = historyData.state; monitoring = historyData.monitoring; renderHistory(); } + else showError(results[1].reason); + renderInfo(); $('mm-selected').setAttribute('aria-busy', 'false'); + if (tab === 'live') await loadEvents().catch(showError); + if (tab === 'commands') await commands.loadHistory().catch(showError); + if (tab === 'queue') await commands.loadQueue().catch(showError); + } + async function loadDevices(append = false) { + const version = ++searchVersion, search = $('mm-search').value.trim(); + if (!append) deviceOffset = 0; + try { + const data = await api(`/devices?${new URLSearchParams({ search, offset: deviceOffset })}`); + if (version !== searchVersion || !active) return; + devices = append ? [...devices, ...data.devices] : data.devices; deviceOffset = data.offset + data.devices.length; + $('mm-more-devices').hidden = deviceOffset >= data.total; $('mm-device').replaceChildren(node('option', data.total ? 'Choose a meter…' : 'No matching meters')); + $('mm-device').firstChild.value = ''; + const available = device && !devices.some(item => item.devEui === device.devEui) ? [device, ...devices] : devices; + available.forEach(item => { const option = node('option', `${item.name} · ${item.devEui}`); option.value = item.devEui; $('mm-device').append(option); }); + $('mm-device').value = device?.devEui || ''; + if (!device) { + let saved; try { saved = localStorage.getItem('m3tering.manager.selected'); } catch { /* Optional preference. */ } + if (saved && devices.some(item => item.devEui === saved)) { $('mm-device').value = saved; selectDevice(saved); } + } + } catch (error) { if (version === searchVersion) showError(error); } + } + function selectDevice(devEui) { + snapshotVersion++; device = devices.find(item => item.devEui === devEui) || (device?.devEui === devEui ? device : null); + latest = null; state = null; historyData = null; historyOffset = 0; commands.close(); + $('mm-empty').hidden = !!device; $('mm-selected').hidden = !device; clearError(); notice(''); + for (const view of ['overview','history']) for (const field of ['energy','voltage']) $(`mm-${view}-${field}`).replaceChildren(node('p', 'Loading readings…', 'mm-note')); + ['mm-readings','mm-events','mm-command-history','mm-queue'].forEach(id => $(id).replaceChildren()); + if (device) { try { localStorage.setItem('m3tering.manager.selected', device.devEui); } catch { /* Optional preference. */ } renderInfo(); refresh().catch(showError); } + } + function selectTab(next) { + tab = next; + root.querySelectorAll('[data-mm-tab]').forEach(button => { if (button.dataset.mmTab === next) button.setAttribute('aria-current','page'); else button.removeAttribute('aria-current'); }); + root.querySelectorAll('[data-mm-panel]').forEach(panel => { panel.hidden = panel.dataset.mmPanel !== next; }); + if (next === 'live') loadEvents().catch(showError); + if (next === 'commands') commands.loadHistory().catch(showError); + if (next === 'queue') commands.loadQueue().catch(showError); + } + function connectStream() { + if (!active || !authenticated || socket?.readyState === WebSocket.OPEN || socket?.readyState === WebSocket.CONNECTING) return; + text('mm-feed', 'Live feed connecting…'); socket = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/m3ter-manager/live`); + const currentSocket = socket; + socket.onopen = () => { if (socket !== currentSocket || !active) return; reconnectAttempt = 0; text('mm-feed', 'Live feed connected'); if (device) refresh().catch(showError); }; + socket.onmessage = event => { + if (socket !== currentSocket || !active) return; + let update; try { update = JSON.parse(event.data); } catch { return; } + if (update.type === 'connection') { monitoring = update.monitoring; renderActivity(); } + if (update.type === 'diagnostic') showError(new Error(update.message)); + if (update.type === 'device' && update.devEui === device?.devEui && !refreshTimer) refreshTimer = setTimeout(() => { refreshTimer = null; if (active) refresh(true).catch(showError); }, 500); + }; + socket.onerror = () => { if (socket === currentSocket && active) text('mm-feed', 'Live feed connection error'); }; + socket.onclose = event => { if (socket !== currentSocket) return; if (event.code === 4001) { lock('Your session ended. Sign in again.'); return; } text('mm-feed', active ? 'Live feed reconnecting…' : 'Live feed closed'); if (active) reconnectTimer = setTimeout(async () => { + const version = authVersion; + try { const session = await api('/session'); if (version !== authVersion || !active) return; if (!session.authenticated) { lock('Your session ended. Sign in again.'); return; } } catch { /* Retry the stream when the server returns. */ } + if (version === authVersion && active) connectStream(); + }, Math.min(30000, 1000 * 2 ** reconnectAttempt++)); }; + } + function lock(message = '') { + authVersion++; close(); authenticated = false; config = null; device = null; state = null; latest = null; historyData = null; devices = []; + commands.close(true); $('mm-workspace').hidden = true; $('mm-login').hidden = false; + $('mm-password').value = ''; $('mm-device').replaceChildren(node('option', 'Choose a meter…')); + ['mm-readings','mm-events','mm-command-history','mm-queue','mm-info','mm-dialog-content'].forEach(id => $(id).replaceChildren()); + $('mm-selected').hidden = true; $('mm-empty').hidden = false; + text('mm-login-error', message); $('mm-login-error').hidden = !message; + } + async function startSession() { + authenticated = true; active = true; $('mm-login').hidden = true; $('mm-workspace').hidden = false; + notice('Loading meters…'); clearError(); const version = authVersion; + try { config = await api('/config'); if (!active || version !== authVersion) return; monitoring = config.monitoring; commands.renderCatalogue(config.commands); + if (config.demo) root.querySelector('.mm-brand small').textContent = 'Demo network · simulated meters'; + await loadDevices(); if (!active || version !== authVersion) return; + notice(config.billingAutomationActive ? 'Existing console billing automation is enabled and may also control these meters. M3ter Manager only observes telemetry; it does not acknowledge energy reports automatically.' : ''); + connectStream(); clockTimer = setInterval(renderActivity, 1000); if (device) await refresh(); + } catch (error) { notice(''); showError(error); } + } + async function open() { + if (active) return; active = true; $('mm-workspace').hidden = true; $('mm-login').hidden = false; + const version = authVersion; + try { + const session = await api('/session'); if (!active || version !== authVersion) return; + text('mm-login-help', session.configured ? 'Use the manager credentials configured by your console administrator.' : 'Set M3TER_MANAGER_USERNAME and M3TER_MANAGER_PASSWORD in .env, then restart the console.'); + if (session.authenticated) await startSession(); + } catch (error) { text('mm-login-error', error.message); $('mm-login-error').hidden = false; } + } + $('mm-login-form').addEventListener('submit', async event => { + event.preventDefault(); $('mm-login-submit').disabled = true; $('mm-login-error').hidden = true; + try { + await api('/session', { method: 'POST', body: { username: $('mm-username').value, password: $('mm-password').value } }); + $('mm-password').value = ''; if (!root.hidden) await startSession(); + } catch (error) { text('mm-login-error', error.message); $('mm-login-error').hidden = false; } + finally { $('mm-login-submit').disabled = false; } + }); + $('mm-logout').addEventListener('click', async () => { + try { await api('/session', { method: 'DELETE' }); lock(); } + catch (error) { showError(new Error('Sign-out could not reach the server. Please retry.')); } + }); + function close() { active = false; snapshotVersion++; searchVersion++; clearTimeout(reconnectTimer); clearTimeout(refreshTimer); clearTimeout(searchTimer); clearInterval(clockTimer); refreshTimer = null; socket?.close(); commands.close(); } + $('mm-device').addEventListener('change', () => selectDevice($('mm-device').value)); + $('mm-search').addEventListener('input', () => { clearTimeout(searchTimer); searchTimer = setTimeout(() => loadDevices(), 250); }); + $('mm-more-devices').addEventListener('click', () => loadDevices(true)); + $('mm-refresh').addEventListener('click', async () => { if (!config) { close(); await open(); } else { clearError(); await loadDevices(); await refresh(); } }); + root.querySelectorAll('[data-mm-tab]').forEach(button => button.addEventListener('click', () => selectTab(button.dataset.mmTab))); + root.querySelectorAll('[data-mm-go]').forEach(button => button.addEventListener('click', () => selectTab(button.dataset.mmGo))); + $('mm-range').addEventListener('change', () => { $('mm-dates').hidden = $('mm-range').value !== 'custom'; historyOffset = 0; if ($('mm-range').value !== 'custom') { clearError(); refresh().catch(showError); } }); + $('mm-dates').addEventListener('submit', event => { event.preventDefault(); historyOffset = 0; clearError(); refresh().catch(showError); }); + $('mm-history-prev').addEventListener('click', () => { historyOffset = Math.max(0, historyOffset - 50); refresh().catch(showError); }); + $('mm-history-next').addEventListener('click', () => { historyOffset += 50; refresh().catch(showError); }); + $('mm-events-more').addEventListener('click', () => loadEvents(true).catch(showError)); + $('mm-copy-key').addEventListener('click', async () => { try { await navigator.clipboard.writeText(state?.publicKey || latest?.publicKey); notice('Public key copied.'); } catch { notice('Clipboard unavailable. Select and copy the displayed public key.'); } }); + window.addEventListener('desktop:open', event => { if (event.detail.id === 'm3ter-manager') open(); }); + window.addEventListener('desktop:close', event => { if (event.detail.id === 'm3ter-manager') close(); }); + window.addEventListener('pagehide', close); +})(); diff --git a/src/public/js/terminal.js b/src/public/js/terminal.js index 90c8d6f..6bdf69b 100644 --- a/src/public/js/terminal.js +++ b/src/public/js/terminal.js @@ -1,207 +1,126 @@ -// Terminal connection variables +// The existing SSH/WebSocket transport, fitted to a resizable desktop window. let terminal = null; let socket = null; let isConnected = false; let resizeObserver = null; - -// Initialize xterm with proper configuration and addons +let terminalFitFrame = 0; +let terminalSubscriptions = []; function initializeTerminal() { - if (terminal) return; // Already initialized - - const xtermContainer = document.getElementById('xterm-terminal'); - + if (terminal) return; + if (typeof Terminal === 'undefined') throw new Error('Terminal could not load. Check your connection and try again.'); terminal = new Terminal({ - cursorBlink: true, - cursorStyle: 'block', - scrollback: 1000, - fontSize: 12, + cursorBlink: !window.Desktop?.getPreferences().reduceMotion, + cursorStyle: 'block', scrollback: 1000, fontSize: 12, fontFamily: 'Courier New, monospace', - theme: { - background: '#212529', - foreground: '#ffffff', - cursor: '#ffffff', - selection: 'rgba(255, 255, 255, 0.3)' - }, - allowTransparency: false, - rendererType: 'canvas', - lineHeight: 1.2 + theme: { background: '#15211e', foreground: '#e4eee7', cursor: '#d4eeb3', selectionBackground: '#ffffff44' }, + allowTransparency: false, lineHeight: 1.2, }); - - terminal.open(xtermContainer); - - // Fit terminal to container dimensions - fitTerminal(); - - // Set up resize observer to fit terminal when container size changes + applyTerminalColors(); + terminal.open(document.getElementById('xterm-terminal')); + // Register once per terminal instance, not again on every reconnect. + terminalSubscriptions = [ + terminal.onData(data => { if (socket?.readyState === WebSocket.OPEN) socket.send(data); }), + terminal.onResize(({ cols, rows }) => { + if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'resize', cols, rows })); + }), + ]; resizeObserver = new ResizeObserver(() => { - if (terminal) { - fitTerminal(); - } + cancelAnimationFrame(terminalFitFrame); + terminalFitFrame = requestAnimationFrame(fitTerminal); }); - - resizeObserver.observe(xtermContainer); + resizeObserver.observe(document.getElementById('xterm-terminal')); } - -// Properly fit terminal to container function fitTerminal() { if (!terminal) return; - const container = document.getElementById('xterm-terminal'); - if (!container) return; - - const { width, height } = container.getBoundingClientRect(); - const charWidth = terminal._core._charWidth || 7; - const charHeight = terminal._core._charHeight || 14; - - const cols = Math.max(80, Math.floor(width / charWidth) - 2); - const rows = Math.max(24, Math.floor(height / charHeight) - 8); - - if (terminal.cols !== cols || terminal.rows !== rows) { - terminal.resize(cols, rows); - } + if (!container.clientWidth || !container.clientHeight) return; + // Prefer rendered cell dimensions; fall back to the configured font before + // the first render. Neither path depends on xterm's private APIs. + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); + context.font = `${terminal.options.fontSize}px ${terminal.options.fontFamily}`; + const screen = container.querySelector('.xterm-screen'); + const charWidth = screen?.clientWidth ? screen.clientWidth / terminal.cols : context.measureText('W').width || 7.2; + const charHeight = screen?.clientHeight ? screen.clientHeight / terminal.rows : Math.ceil(terminal.options.fontSize * terminal.options.lineHeight); + const cols = Math.max(10, Math.floor((container.clientWidth - 36) / charWidth)); + const rows = Math.max(3, Math.floor((container.clientHeight - 20) / charHeight)); + if (terminal.cols !== cols || terminal.rows !== rows) terminal.resize(cols, rows); } - function connectTerminal(event) { event.preventDefault(); - + const status = document.getElementById('status-message'); + try { initializeTerminal(); } catch (error) { status.textContent = error.message; return; } + if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) return; const username = document.getElementById('username').value; const password = document.getElementById('password').value; - const statusMessage = document.getElementById('status-message'); - const authForm = document.getElementById('terminal-auth'); - const terminalContainer = document.getElementById('terminal-container'); - - // Show connecting status - statusMessage.textContent = 'Connecting to terminal...'; - - // Initialize xterm terminal if not already done - initializeTerminal(); - - - // Determine protocol - const protocol = (location.protocol === 'https:') ? 'wss' : 'ws'; - const cols = terminal.cols; - const rows = terminal.rows; - - // Create WebSocket connection with credentials and terminal size - const socketUrl = `${protocol}://${location.host}/?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&cols=${cols}&rows=${rows}`; - - socket = new WebSocket(socketUrl); - socket.binaryType = 'arraybuffer'; - - socket.onopen = () => { - isConnected = true; - statusMessage.textContent = 'Connected to terminal'; - authForm.style.display = 'none'; - terminalContainer.style.display = 'block'; - - terminal.write('Connected to M3tering Console Terminal.\r\n'); - - // Send initial resize - socket.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows })); + status.textContent = 'Connecting to terminal…'; + const protocol = location.protocol === 'https:' ? 'wss' : 'ws'; + const connection = new WebSocket(`${protocol}://${location.host}/terminal`); + socket = connection; + connection.binaryType = 'arraybuffer'; + connection.onopen = () => { + if (socket !== connection || !terminal) return; + status.textContent = 'Authenticating with the host…'; + connection.send(JSON.stringify({ type: 'auth', username, password, cols: terminal.cols, rows: terminal.rows })); }; - - socket.onmessage = (event) => { - // Handle incoming terminal data - if (typeof event.data === 'string') { - terminal.write(event.data); - } else { - terminal.write(new Uint8Array(event.data)); + connection.onmessage = event => { + if (socket !== connection || !terminal) return; + if (!isConnected) { + let control; + try { control = JSON.parse(event.data); } catch { status.textContent = String(event.data); return; } + if (control.type !== 'ready') return; + isConnected = true; + status.textContent = 'Terminal session connected'; + document.getElementById('terminal-auth').style.display = 'none'; + document.getElementById('terminal-container').style.display = 'flex'; + terminal.write('Connected to M3tering Console Terminal.\r\n'); + fitTerminal(); + connection.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows })); + terminal.focus(); + return; } + terminal.write(typeof event.data === 'string' ? event.data : new Uint8Array(event.data)); }; - - socket.onclose = () => { - isConnected = false; - statusMessage.textContent = 'Terminal connection closed'; - authForm.style.display = 'block'; - terminalContainer.style.display = 'none'; - - if (terminal) { - terminal.write('\r\nConnection closed.\r\n'); - } + connection.onclose = () => { + if (socket !== connection) return; + isConnected = false; socket = null; + document.getElementById('terminal-auth').style.display = 'block'; + document.getElementById('terminal-container').style.display = 'none'; + status.textContent = 'Terminal connection closed'; + terminal?.write('\r\nConnection closed.\r\n'); }; - - socket.onerror = (error) => { - console.error('WebSocket error:', error); - statusMessage.textContent = 'Connection error. Please check credentials and try again.'; - authForm.style.display = 'block'; - terminalContainer.style.display = 'none'; - isConnected = false; + connection.onerror = () => { + if (socket !== connection) return; + status.textContent = 'Connection error. Check your credentials and try again.'; }; - - // Handle terminal input - if (terminal) { - terminal.onData(data => { - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(data); - } - }); - - // Handle terminal resize - terminal.onResize(({ cols, rows }) => { - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ type: 'resize', cols, rows })); - } - }); - } - - // Handle window resize - window.addEventListener('resize', () => { - if (terminal) { - fitTerminal(); - } - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows })); - } - }); } - function disconnectTerminal() { - if (socket) { - socket.close(); - } - - const authForm = document.getElementById('terminal-auth'); - const terminalContainer = document.getElementById('terminal-container'); - const statusMessage = document.getElementById('status-message'); - - authForm.style.display = 'block'; - terminalContainer.style.display = 'none'; - statusMessage.textContent = 'Terminal disconnected'; - - if (terminal) { - terminal.reset(); - } - - isConnected = false; + const previous = socket; + socket = null; isConnected = false; + previous?.close(); + document.getElementById('terminal-auth').style.display = 'block'; + document.getElementById('terminal-container').style.display = 'none'; + document.getElementById('status-message').textContent = 'Terminal disconnected'; + terminal?.reset(); } - -// Show terminal authentication form when terminal is opened function showTerminalAuth() { - const authForm = document.getElementById('terminal-auth'); - const terminalContainer = document.getElementById('terminal-container'); - const statusMessage = document.getElementById('status-message'); - - // Reset UI to show auth form - authForm.style.display = 'block'; - terminalContainer.style.display = 'none'; - statusMessage.textContent = 'Enter credentials and click Connect to start terminal session'; - - // Focus on username field + document.getElementById('terminal-auth').style.display = 'block'; + document.getElementById('terminal-container').style.display = 'none'; + document.getElementById('status-message').textContent = 'Enter your credentials to start a terminal session.'; document.getElementById('username').focus(); } - -// Clean up when terminal app is closed function cleanupTerminal() { - if (resizeObserver) { - resizeObserver.disconnect(); - resizeObserver = null; - } - if (socket) { - socket.close(); - } - if (terminal) { - terminal.dispose(); - terminal = null; - } - isConnected = false; -} \ No newline at end of file + disconnectTerminal(); + resizeObserver?.disconnect(); resizeObserver = null; + cancelAnimationFrame(terminalFitFrame); + terminalSubscriptions.forEach(subscription => subscription.dispose()); terminalSubscriptions = []; + terminal?.dispose(); terminal = null; +} + +function applyTerminalColors() { + if (!terminal) return; + const style = getComputedStyle(document.getElementById('terminal')); + terminal.options.theme = { background: style.getPropertyValue('--surface').trim(), foreground: style.getPropertyValue('--text').trim(), + cursor: style.getPropertyValue('--accent').trim(), selectionBackground: '#6688aa66' }; +} +window.addEventListener('desktop:app-mode', event => { if (event.detail.id === 'terminal') applyTerminalColors(); }); diff --git a/src/public/js/toggle.js b/src/public/js/toggle.js index c66c178..555781e 100644 --- a/src/public/js/toggle.js +++ b/src/public/js/toggle.js @@ -1,19 +1,5 @@ +// Compatibility entry point for existing UI extensions. function toggleApp(appId, state) { - const iconState = state === true ? "none" : "block"; - const appState = state === true ? "block" : "none"; - var app = document.getElementById(appId); - app.style.display = appState; - - // Clean up terminal when closing - if (appId === 'terminal' && state === false && typeof cleanupTerminal === 'function') { - cleanupTerminal(); - } - - ["m3ters-icon", "browser-icon", "terminal-icon", "paint-icon"].forEach( - (iconId) => { - var icon = document.getElementById(iconId); - icon.style.display = iconState; - } - ); - + if (state) window.Desktop.launch(appId); + else window.Desktop.close(appId); } diff --git a/src/services/auth.ts b/src/services/auth.ts new file mode 100644 index 0000000..21e893b --- /dev/null +++ b/src/services/auth.ts @@ -0,0 +1,50 @@ +import { createHash, timingSafeEqual } from 'crypto'; +import type { IncomingMessage } from 'http'; +import type { NextFunction, Request, Response } from 'express'; + +export function validateConsoleAuth(): void { + if (!process.env.CONSOLE_USERNAME || !process.env.CONSOLE_PASSWORD) { + throw new Error('Set CONSOLE_USERNAME and CONSOLE_PASSWORD before starting the console'); + } + if (process.env.CONSOLE_USERNAME.includes(':')) throw new Error('CONSOLE_USERNAME must not contain a colon'); + if (process.env.CONSOLE_ORIGIN) { + const url = new URL(process.env.CONSOLE_ORIGIN); + if (!['http:', 'https:'].includes(url.protocol) || url.origin !== process.env.CONSOLE_ORIGIN) { + throw new Error('CONSOLE_ORIGIN must be an HTTP(S) origin without a trailing slash or path'); + } + } +} + +export function isAuthenticated(request: IncomingMessage): boolean { + const { CONSOLE_USERNAME, CONSOLE_PASSWORD } = process.env; + if (!CONSOLE_USERNAME || !CONSOLE_PASSWORD) return false; + const authorization = request.headers.authorization; + if (!authorization || !/^Basic [A-Za-z0-9+/]+=*$/i.test(authorization)) return false; + const supplied = Buffer.from(authorization.slice(6), 'base64'); + const expected = Buffer.from(`${CONSOLE_USERNAME}:${CONSOLE_PASSWORD}`, 'utf8'); + // Fixed-length hashes avoid both length leaks and timingSafeEqual length errors. + return timingSafeEqual(createHash('sha256').update(supplied).digest(), createHash('sha256').update(expected).digest()); +} + +export function isSameOrigin(request: IncomingMessage, requireOrigin = false): boolean { + const origin = request.headers.origin; + if (!origin) return !requireOrigin && request.headers['sec-fetch-site'] !== 'cross-site'; + const expected = process.env.CONSOLE_ORIGIN || + `${(request.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http'}://${request.headers.host}`; + return origin === expected; +} + +export function requireConsoleAuth(req: Request, res: Response, next: NextFunction): void { + if (!isAuthenticated(req)) { + res.setHeader('WWW-Authenticate', 'Basic realm="M3tering Console", charset="UTF-8"'); + res.status(401).send('Console authentication required'); + return; + } + if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !isSameOrigin(req)) { + res.status(403).send('Cross-origin requests are not permitted'); + return; + } + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Referrer-Policy', 'no-referrer'); + next(); +} diff --git a/src/services/chirpstack.ts b/src/services/chirpstack.ts new file mode 100644 index 0000000..88366c4 --- /dev/null +++ b/src/services/chirpstack.ts @@ -0,0 +1,140 @@ +import http, { IncomingHttpHeaders } from 'http'; +import https from 'https'; +import { createHmac, randomBytes, timingSafeEqual } from 'crypto'; +import type { Request, Response } from 'express'; +import { isAuthenticated, isSameOrigin } from './auth'; + +const prefix = '/chirpstack'; +const cookieName = 'console_chirpstack'; +const sessionKey = randomBytes(32); +const lifetime = 8 * 60 * 60; +const hopHeaders = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']; + +export function chirpstackTarget(): URL { + const host = process.env.CHIRPSTACK_HOST || 'localhost'; + const target = new URL(process.env.CHIRPSTACK_WEB_URL || `http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:8080`); + if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password || target.pathname !== '/' || target.search || target.hash) { + throw new Error('CHIRPSTACK_WEB_URL must be an HTTP(S) origin without credentials or a path'); + } + return target; +} + +function signature(expiry: string): string { + // Restarting the console or changing its credentials invalidates these scoped sessions. + return createHmac('sha256', sessionKey).update(JSON.stringify([ + expiry, process.env.CONSOLE_USERNAME, process.env.CONSOLE_PASSWORD, + ])).digest('hex'); +} + +export function hasChirpstackSession(cookie: string | undefined): boolean { + if (!process.env.CONSOLE_USERNAME || !process.env.CONSOLE_PASSWORD) return false; + const token = cookie?.split(';').map(part => part.trim()).find(part => part.startsWith(`${cookieName}=`))?.slice(cookieName.length + 1); + if (!token || !/^\d+\.[a-f0-9]{64}$/.test(token)) return false; + const [expiry, mac] = token.split('.'); + const now = Math.floor(Date.now() / 1000); + return Number(expiry) > now && Number(expiry) <= now + lifetime && timingSafeEqual(Buffer.from(mac, 'hex'), Buffer.from(signature(expiry), 'hex')); +} + +function cleanHeaders(headers: IncomingHttpHeaders): IncomingHttpHeaders { + const result = { ...headers }; + for (const name of [...hopHeaders, ...(headers.connection || '').toLowerCase().split(',').map(s => s.trim())]) delete result[name]; + return result; +} + +export function rewriteChirpstackText(body: string, html: boolean): string { + if (!html) { + // Vite / CRA asset references in bundles and stylesheets (including lazy chunks). + return body.replace(/(["'`(])\/(assets|static)\//g, `$1${prefix}/$2/`) + .replace(/(["'`(])\/(?!chirpstack\/)([^"'`()\s]+\.(?:png|svg|ico|jpe?g|webp|gif|woff2?)(?:\?[^"'`()\s]*)?)(?=["'`)])/g, `$1${prefix}/$2`); + } + const rewritten = body.replace(/\b(src|href|action)=(['"])\/(?!\/|chirpstack(?:\/|['"]))([^'"]*)\2/gi, + (_, attr, quote, path) => `${attr}=${quote}${prefix}/${path}${quote}`); + // Runs before the upstream application: remaps gRPC-Web and isolates storage. + return rewritten.replace(/]*)?>/i, '$&'); +} + +function unavailable(res: Response, configuration = false): void { + if (res.headersSent) { res.destroy(); return; } + res.removeHeader('Content-Length'); + res.removeHeader('Content-Encoding'); + res.status(502).type('html').send(`ChirpStack unavailable

ChirpStack is unavailable

${configuration ? 'Check the CHIRPSTACK_WEB_URL configuration on the console server.' : 'The console could not reach ChirpStack. Make sure the ChirpStack server is running and CHIRPSTACK_HOST or CHIRPSTACK_WEB_URL points to it.'}

Try again

`); +} + +/** Mount before JSON/body middleware: gRPC-Web bodies and event streams stay intact. */ +export function proxyChirpstack(req: Request, res: Response): void { + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Referrer-Policy', 'no-referrer'); + res.setHeader('X-Frame-Options', 'SAMEORIGIN'); + res.setHeader('Content-Security-Policy', "frame-ancestors 'self'"); + if (!isSameOrigin(req)) { res.status(403).send('Cross-origin requests are not permitted'); return; } + const basic = isAuthenticated(req); + if (!basic && !hasChirpstackSession(req.headers.cookie)) { + res.setHeader('WWW-Authenticate', 'Basic realm="M3tering Console", charset="UTF-8"'); + res.status(401).send('Open ChirpStack from the console to authenticate'); + return; + } + if (basic) { + const expiry = String(Math.floor(Date.now() / 1000) + lifetime); + const secure = req.secure || process.env.CONSOLE_ORIGIN?.startsWith('https:'); + res.setHeader('Set-Cookie', `${cookieName}=${expiry}.${signature(expiry)}; Path=${prefix}; HttpOnly; SameSite=Strict; Max-Age=${lifetime}${secure ? '; Secure' : ''}`); + } + if (req.originalUrl.split('?')[0] === prefix) { + res.redirect(307, `${prefix}/${req.originalUrl.includes('?') ? req.originalUrl.slice(req.originalUrl.indexOf('?')) : ''}`); + return; + } + let target: URL; + try { target = chirpstackTarget(); } catch { unavailable(res, true); return; } + const headers = cleanHeaders(req.headers); + headers.host = target.host; + headers['accept-encoding'] = 'identity'; + // Never disclose console credentials/cookies or inject the server's API_TOKEN. + delete headers.cookie; + delete headers.origin; + delete headers.referer; + for (const name of Object.keys(headers)) if (name.startsWith('x-forwarded-') || name === 'forwarded') delete headers[name]; + if (!/^Bearer /i.test(headers.authorization || '')) delete headers.authorization; + const upstream = (target.protocol === 'https:' ? https : http).request(target, { + method: req.method, path: req.url, headers, + }, response => { + const responseHeaders = cleanHeaders(response.headers); + for (const name of ['set-cookie', 'www-authenticate', 'content-security-policy', 'content-security-policy-report-only', 'x-frame-options', 'cache-control', 'etag', 'last-modified']) delete responseHeaders[name]; + for (const name of Object.keys(responseHeaders)) if (name.startsWith('access-control-')) delete responseHeaders[name]; + if (responseHeaders.location) { + try { + const location = new URL(responseHeaders.location, new URL(target.origin + req.url)); + if (location.origin === target.origin) responseHeaders.location = prefix + location.pathname + location.search + location.hash; + } catch { delete responseHeaders.location; } + } + const type = String(responseHeaders['content-type'] || ''); + // Device event feeds can legitimately remain silent for minutes. Keep them + // open after headers arrive; closing the iframe still cancels the request. + if (/grpc-web|text\/event-stream/.test(type)) upstream.setTimeout(0); + const html = type.includes('text/html'); + const transform = req.method !== 'HEAD' && (html || /(?:javascript|text\/css)/.test(type)); + if (transform) { + delete responseHeaders['content-length']; + if (responseHeaders['content-encoding'] && responseHeaders['content-encoding'] !== 'identity') { + response.destroy(); unavailable(res); return; + } + } + res.statusCode = response.statusCode || 502; + for (const [name, value] of Object.entries(responseHeaders)) if (value !== undefined) res.setHeader(name, value); + response.on('error', () => unavailable(res)); + if (!transform) { response.pipe(res); return; } + const chunks: Buffer[] = []; + let length = 0; + response.on('data', (chunk: Buffer) => { + length += chunk.length; + if (length > 32 * 1024 * 1024) { response.destroy(); unavailable(res); return; } + chunks.push(chunk); + }); + response.on('end', () => { + if (!res.destroyed && !res.writableEnded) res.end(rewriteChirpstackText(Buffer.concat(chunks).toString('utf8'), html)); + }); + }); + upstream.setTimeout(60_000, () => upstream.destroy(new Error('ChirpStack upstream timeout'))); + upstream.on('error', () => unavailable(res)); + req.on('aborted', () => upstream.destroy()); + res.on('close', () => { if (!res.writableFinished) upstream.destroy(); }); + req.pipe(upstream); +} diff --git a/src/services/grpc.ts b/src/services/grpc.ts index ba07918..e8f6565 100644 --- a/src/services/grpc.ts +++ b/src/services/grpc.ts @@ -10,7 +10,7 @@ const deviceService = new DeviceServiceClient(`${process.env.CHIRPSTACK_HOST}:80 const metadata = new Metadata(); metadata.set("authorization", "Bearer " + process.env.API_TOKEN); -export function enqueue(devEui: string, data: number[]) { +export function enqueue(devEui: string, data: number[]): Promise { const item = new DeviceQueueItem(); const enqueueReq = new EnqueueDeviceQueueItemRequest(); @@ -20,8 +20,11 @@ export function enqueue(devEui: string, data: number[]) { item.setData(new Uint8Array(data)); enqueueReq.setQueueItem(item); - deviceService.enqueue(enqueueReq, metadata, (err: any, resp: any) => { - if (err !== null) return logger.error("Failed to enqueue device data:", err); - logger.info(`${data} has been enqueued with id: ` + resp.getId()); + return new Promise((resolve, reject) => { + deviceService.enqueue(enqueueReq, metadata, (err, resp) => { + if (err || !resp) { reject(err || new Error("Missing enqueue response")); return; } + logger.info(`${data} has been enqueued with id: ` + resp.getId()); + resolve(); + }); }); } diff --git a/src/services/mqtt.ts b/src/services/mqtt.ts index 9f2b357..a9516b6 100644 --- a/src/services/mqtt.ts +++ b/src/services/mqtt.ts @@ -1,252 +1,165 @@ -import { connect } from 'mqtt'; +import { connect, MqttClient } from 'mqtt'; +import { connectionState, ingestEvent } from '../m3ter/monitor'; +import { applicationId } from '../m3ter/chirpstack'; import { enqueue } from './grpc'; import { encode } from '../lib/encode'; import { - getAllTransactionRecords, - getMeterByDevEui, - getMeterByPublicKey, - insertTransaction, - saveMeter, - updateMeterDevEui, - updateMeterNonce, + getAllTransactionRecords, getMeterByDevEui, getMeterByPublicKey, + getTransactionByNonce, recordMeterTransaction, saveMeter, updateMeterDevEui, updateMeterNonce, } from '../store/sqlite'; import type { State, TransactionRecord } from '../types'; import { decodePayload } from '../lib/decode'; -import { runHook, verifyPayloadSignature } from '../lib/utils'; -import { getLatestTransactionNonce, getCrossChainRevenue, getOwedFromPriceContext } from '../lib/sync'; +import { runHook, notifyHook, verifyPayloadSignature } from '../lib/utils'; +import { getLatestTransactionNonce } from '../lib/sync'; import { createMeterLogger, createLogger } from '../utils/logger'; import { meterIdFromPublicKeyContractCall } from '../utils/contracts'; const logger = createLogger('[mqtt]'); -const CHIRPSTACK_HOST = process.env.CHIRPSTACK_HOST; -const deviceLocks = new Map(); // Lock per devEUI to prevent concurrent message processing +const deviceLocks = new Set(); +const meterLocks = new Set(); +let monitoringClient: MqttClient | undefined; export async function handleUplinks(): Promise { - return new Promise(function (resolve, reject) { - const client = connect({ - host: CHIRPSTACK_HOST, - port: 1883, - clean: true, - connectTimeout: 9000, - reconnectPeriod: 1000, - }); - - client.on('reconnect', () => { - runHook('onMqttReconnect', client); - }); - - client.on('message', async (_, blob) => { - return await handleMessage(blob); - }); - - client.on('connect', () => { - const topic = `application/${process.env.APPLICATION_ID}/device/+/event/up`; - client.subscribe(topic, () => { - logger.info(`\nConnected & Subscribed to CHIRPSTACK_HOST: ${CHIRPSTACK_HOST}\n`); - - runHook('onMqttSubscribed', client, topic); - resolve(true); - }); - - runHook('onMqttConnect', client); - }); - - client.on('error', (err) => { - logger.error('Connection error: ', err); - - runHook('onMqttError', err, client); - - client.end(); - reject(err); + if (monitoringClient) return true; + const topic = `application/${applicationId()}/device/+/event/+`; + connectionState('connecting'); + const options = { clean: true, resubscribe: false, connectTimeout: 9000, reconnectPeriod: 2000, + username: process.env.MQTT_USERNAME, password: process.env.MQTT_PASSWORD }; + const client = monitoringClient = process.env.MQTT_URL ? connect(process.env.MQTT_URL, options) : + connect({ ...options, host: process.env.CHIRPSTACK_HOST || 'localhost', port: 1883 }); + client.on('reconnect', () => { connectionState('reconnecting'); void notifyHook('onMqttReconnect', client); }); + client.on('offline', () => connectionState('disconnected')); + client.on('close', () => connectionState('disconnected')); + client.on('message', (topic, blob) => { + ingestEvent(topic, blob); + // Preserve the existing billing handler as a separate, optional consumer. + // Telemetry is already durable before this workflow can fail or wait on a chain. + if (process.env.CONSOLE_MONITOR_ONLY !== 'true' && topic.endsWith('/event/up')) { + try { + const event = JSON.parse(blob.toString()); + if (event.fPort === 2 && event.deviceInfo?.applicationId?.toLowerCase() === applicationId() && + topic.toLowerCase().endsWith(`/device/${String(event.deviceInfo.devEui).toLowerCase()}/event/up`)) { + void handleMessage(blob).catch(() => logger.error('Billing uplink handler failed')); + } + } + catch { /* The monitoring ingestion boundary records malformed messages. */ } + } + }); + client.on('connect', () => { + client.subscribe(topic, { qos: 1 }, (error, granted) => { + if (error || granted?.some(subscription => subscription.qos === 128)) { + connectionState('error', 'MQTT subscription rejected. Check broker permissions.'); + client.stream.destroy(); return; // reconnect, then subscribe exactly once again + } + connectionState('connected'); void notifyHook('onMqttSubscribed', client, topic); }); + void notifyHook('onMqttConnect', client); + }); + client.on('error', error => { + connectionState('error', 'MQTT connection failed. Check broker address and credentials.'); + void notifyHook('onMqttError', error, client); + // MQTT.js owns reconnection. Do not end the client on a transient error. }); + return true; // The dashboard stays available while MQTT is connecting/reconnecting. } -export async function handleMessage(blob: Buffer) { - runHook('onMessageReceived', blob); - - const message = JSON.parse(blob.toString()); - const devEui = message['deviceInfo']['devEui'] || null; - - // Create a logger with devEui context - const logger = createMeterLogger({ devEui }); +export function stopUplinks(): void { + monitoringClient?.end(true); monitoringClient = undefined; connectionState('disconnected'); +} +export async function handleMessage(blob: Buffer): Promise { + let devEui: string | undefined; + let lockedMeter: string | undefined; + let ownsDeviceLock = false; + let log = logger; try { - if (!devEui) { - logger.warn('Message dropped - no devEui found in message'); - return; + void notifyHook('onMessageReceived', blob); + const message = JSON.parse(blob.toString()); + if (typeof message?.deviceInfo?.devEui !== 'string' || !message.deviceInfo.devEui) { + throw new Error('Message has no valid device EUI'); } - - // Check if this specific device is already being processed - if (deviceLocks.get(devEui)) { - logger.warn(`Message dropped - device is already being processed`); - runHook('onMessageDropped', 'locked', devEui); + devEui = message.deviceInfo.devEui; + log = createMeterLogger({ devEui }); + if (deviceLocks.has(devEui!)) { + void notifyHook('onMessageDropped', 'locked', devEui!); return; } - - let is_on = true; - - // Set lock for this specific device - deviceLocks.set(devEui, true); - - logger.info(`Received uplink from device: ${JSON.stringify(message)}`); - - // encoded transaction in standard format (payload is hex string) - // format: nonce | energy | signature | voltage | device_id | longitude | latitude - const transactionHex = Buffer.from(message['data'], 'base64'); - const decoded = decodePayload(transactionHex); - let publicKey = decoded.extensions.deviceId; - let payloadHadPublicKey = !!publicKey; - - logger.info(`Decoded payload: ${JSON.stringify(decoded)}`); - - if (!publicKey) { - // try to find public key by DevEui - const meterByDevEui = getMeterByDevEui(devEui); - - if (!meterByDevEui) { - throw new Error('Device EUI not associated with any meter: ' + devEui); - } - - publicKey = meterByDevEui.publicKey.replace('0x', ''); + deviceLocks.add(devEui!); + ownsDeviceLock = true; + if (typeof message.data !== 'string' || !message.data || !/^[A-Za-z0-9+/]+={0,2}$/.test(message.data)) { + throw new Error('Message has no valid base64 payload'); } - - // verify transaction signature - const isValid = verifyPayloadSignature(transactionHex, Buffer.from(publicKey!, 'hex')); - if (!isValid) { - throw new Error('Invalid transaction signature for meter with public key: ' + publicKey); + const transaction = Buffer.from(message.data, 'base64'); + const decoded = decodePayload(transaction); + const payloadHadPublicKey = !!decoded.extensions.deviceId; + const publicKey = decoded.extensions.deviceId || getMeterByDevEui(devEui!)?.publicKey.replace(/^0x/, ''); + if (!publicKey || !verifyPayloadSignature(transaction, Buffer.from(publicKey, 'hex'))) { + throw new Error('Unknown meter or invalid transaction signature'); } - - logger.info('Verified signature'); - + const key = `0x${publicKey}`; + // Two device EUIs can identify the same meter. Serialize that identity too. + if (meterLocks.has(key)) { + void notifyHook('onMessageDropped', 'meter-locked', devEui!); + return; + } + meterLocks.add(key); + lockedMeter = key; if (payloadHadPublicKey) { - logger.info(`Payload contained public key: ${publicKey}`); - // save public key with device EUI mapping if not already saved - const existingMeter = getMeterByPublicKey(`0x${publicKey}`); - - if (!existingMeter) { - const tokenId = await meterIdFromPublicKeyContractCall(`0x${publicKey}`); - + const existing = getMeterByPublicKey(key); + if (!existing) { + const tokenId = await meterIdFromPublicKeyContractCall(key); const latestNonce = await getLatestTransactionNonce(tokenId); - - logger.info(`Fetched tokenId and latestNonce from chain and local state: ${tokenId}, ${latestNonce}`); - - // save new meter with devEui - const newMeter = { - publicKey: `0x${publicKey}`, - devEui: message['deviceInfo']['devEui'], - tokenId, - latestNonce, - }; - - saveMeter(newMeter); - logger.info(`Saved new meter: ${JSON.stringify(newMeter)}`); - - runHook('onMeterCreated', newMeter); + const meter = { publicKey: key, devEui: devEui!, tokenId, latestNonce }; + saveMeter(meter); + void notifyHook('onMeterCreated', meter); } else { - // update existing meter with devEui if not already set - if (!existingMeter.devEui || existingMeter.devEui !== message['deviceInfo']['devEui']) { - logger.info(`Updating meter with DevEui: ${message['deviceInfo']['devEui']}`); - updateMeterDevEui(`0x${publicKey}`, message['deviceInfo']['devEui']); - } - - // fetch and update latest nonce from chain - const latestNonce = await getLatestTransactionNonce(existingMeter.tokenId); - - logger.info(`Fetched latestNonce from chain and local state: ${latestNonce}`); - - updateMeterNonce(`0x${publicKey}`, latestNonce); + if (existing.devEui !== devEui && !updateMeterDevEui(key, devEui!)) throw new Error('Could not update meter device EUI'); + const latestNonce = await getLatestTransactionNonce(existing.tokenId); + if (!updateMeterNonce(key, latestNonce)) throw new Error('Could not synchronize meter nonce'); } } - - let m3ter = getMeterByPublicKey(`0x${publicKey}`) ?? null; - - if (!m3ter) { - throw new Error('Meter not found for public key: ' + publicKey); - } - - logger.info(`Found meter: ${JSON.stringify(m3ter)}`); - - // If both latest nonce and received nonce are 0, enqueue 0 immediately - if (m3ter.latestNonce === 0 && decoded.nonce === 0) { - logger.info('Both latest nonce and received nonce are 0, enqueuing 0 immediately'); - - try { - is_on = true; // Always on - // (await getCrossChainRevenue(m3ter.tokenId)) >= - // (await getOwedFromPriceContext(m3ter.tokenId)); - } catch (error) { - logger.error(`Error fetching cross chain revenue or owed amount: ${error}`); + const meter = getMeterByPublicKey(key); + if (!meter) throw new Error('Meter not found'); + const expectedNonce = meter.latestNonce + 1; + let newTransaction = false; + if (decoded.nonce === expectedNonce) { + const record: TransactionRecord = { nonce: decoded.nonce, identifier: meter.tokenId, receivedAt: Date.now(), raw: transaction.toString('hex') }; + // Acknowledgement means both the transaction and its nonce are durable. + recordMeterTransaction(key, record); + newTransaction = true; + } else if (decoded.nonce !== 0) { + const previous = getTransactionByNonce(decoded.nonce, meter.tokenId); + if (decoded.nonce !== meter.latestNonce || previous?.raw !== transaction.toString('hex')) { + throw new Error(`Invalid nonce. Expected ${expectedNonce}, got ${decoded.nonce}`); } - - const state = { nonce: 0, is_on }; - - logger.info(`Enqueuing state: ${JSON.stringify(state)}`); - - enqueue( - message['deviceInfo']['devEui'], - encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0), - ); - - return; // Exit early without processing the transaction + // A lost downlink may cause an exact retransmission. Acknowledge without + // inserting or redistributing it. Different data at the same nonce is rejected. } - - const expectedNonce = m3ter.latestNonce + 1; - - logger.info(`Received blob for meter ${m3ter?.tokenId}, expected nonce: ${expectedNonce}, got: ${decoded.nonce}`); - - if (decoded.nonce !== expectedNonce && decoded.nonce !== 0) { - throw new Error(`Invalid nonce. Expected ${expectedNonce}, got ${decoded.nonce}. Public key: ${publicKey}`); - } - - // if device nonce is correct - if (decoded.nonce === expectedNonce) { - logger.info(`Nonce is valid: ${decoded.nonce}`); - - // save transaction to local store - const transactionRecord = { - nonce: decoded.nonce, - identifier: m3ter.tokenId, - receivedAt: Date.now(), - raw: transactionHex.toString('hex'), - } as TransactionRecord; - insertTransaction(transactionRecord); - updateMeterNonce(`0x${publicKey}`, expectedNonce); - - logger.info(`Updated meter nonce to: ${expectedNonce}`); - - const pendingTransactions = getAllTransactionRecords(); - logger.info(`${pendingTransactions.length} Pending transactions: ${JSON.stringify(pendingTransactions)}`); - await runHook('onTransactionDistribution', m3ter.tokenId, decoded, pendingTransactions); + let is_on = false; + try { is_on = await runHook('isOnStateCompute', meter.tokenId); } + catch (error) { + log.error('Could not determine meter power state:', error); + void notifyHook('onIsOnStateComputeError', meter.tokenId, error); } - + void notifyHook('onIsOnStateComputed', meter.tokenId, is_on); + const state = decoded.nonce === 0 ? { nonce: meter.latestNonce, is_on } : { is_on }; try { - is_on = await runHook('isOnStateCompute', m3ter.tokenId); - } catch (error) { - runHook('onIsOnStateComputeError', m3ter.tokenId, error); - logger.error(`Error in isOnStateCompute hook: ${error}`); + await enqueue(devEui!, encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0)); + void notifyHook('onStateEnqueued', state, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0); + } finally { + // Delivery services run after the downlink attempt and cannot prevent it. + // notifyHook isolates failures so later delivery extensions still run. + if (newTransaction) void notifyHook('onTransactionDistribution', meter.tokenId, decoded, getAllTransactionRecords()); } - - runHook('onIsOnStateComputed', m3ter.tokenId, is_on); - - const state = decoded.nonce === expectedNonce ? { is_on } : { nonce: m3ter.latestNonce, is_on }; - - logger.info(`Enqueuing state: ${JSON.stringify(state)}`); - - enqueue( - message['deviceInfo']['devEui'], - encode(state as State, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0), - ); - runHook('onStateEnqueued', state, decoded.extensions.latitude ?? 0, decoded.extensions.longitude ?? 0); } catch (error) { - logger.error(`Error handling MQTT message: ${error}`); - runHook('onMessageError', error); + log.error('Error handling MQTT message:', error); + void notifyHook('onMessageError', error); } finally { - // Release lock for this specific device - if (devEui) { + if (lockedMeter) meterLocks.delete(lockedMeter); + if (ownsDeviceLock && devEui) { deviceLocks.delete(devEui); - runHook('onDeviceUnlocked', devEui); + void notifyHook('onDeviceUnlocked', devEui); } - runHook('onMessageProcessingComplete'); + void notifyHook('onMessageProcessingComplete'); } } diff --git a/src/services/server.ts b/src/services/server.ts index a78cb22..9d3ece9 100644 --- a/src/services/server.ts +++ b/src/services/server.ts @@ -1,6 +1,9 @@ import http from 'http'; import { create } from 'express-handlebars'; import express, { Express, Request, Response } from 'express'; +import { requireConsoleAuth, validateConsoleAuth } from './auth'; +import { proxyChirpstack } from './chirpstack'; +import { managerRouter, attachManagerStream } from '../m3ter/api'; import { createLogger } from '../utils/logger'; import { getAllMeterRecords, deleteMeterByPublicKey } from '../store/sqlite'; import { getUIComponents, invokeUIAction } from '../lib/utils'; @@ -10,6 +13,7 @@ export const app: Express = express(); const port = process.env.PORT || 3000; const hbs = create({ + partialsDir: './src/views/partials', defaultLayout: 'main', extname: 'hbs', helpers: { @@ -22,56 +26,67 @@ const hbs = create({ app.engine('hbs', hbs.engine); app.set('view engine', 'hbs'); app.set('views', './src/views'); +app.use('/chirpstack', proxyChirpstack); +app.use(requireConsoleAuth); app.use(express.json()); app.use(express.static('./src/public')); app.use(express.urlencoded({ extended: true })); +app.use('/api/m3ter-manager', managerRouter); -app.get('/', async (req: Request, res: Response) => { - const m3ters = getAllMeterRecords(); +app.get('/', async (req: Request, res: Response, next) => { + try { + const m3ters = getAllMeterRecords(); - // Get UI components from loaded UI extensions - const { icons, windows } = await getUIComponents(); + // Get UI components from loaded UI extensions + const { icons, windows } = await getUIComponents(); - logger.info('Rendering index page with m3ters, icons, and windows'); + logger.info('Rendering index page with m3ters, icons, and windows'); - res.render('index', { m3ters, icons, windows }); - logger.info('Server handled GET request at `/`'); + res.render('index', { m3ters, icons, windows }); + logger.info('Server handled GET request at `/`'); + } catch (error) { next(error); } }); // API endpoint to invoke UI actions -app.post('/api/actions/:moduleId/:actionId', async (req: Request, res: Response) => { - const { moduleId, actionId } = req.params; - logger.info(`Invoking action '${actionId}' from module '${moduleId}'`); +app.post('/api/actions/:moduleId/:actionId', async (req: Request, res: Response, next) => { + try { + const { moduleId, actionId } = req.params; + logger.info(`Invoking action '${actionId}' from module '${moduleId}'`); - const result = await invokeUIAction(moduleId, actionId); + const result = await invokeUIAction(moduleId, actionId); - if (result.success) { - res.status(200).json(result); - } else { - res.status(400).json(result); - } + if (result.success) { + res.status(200).json(result); + } else { + res.status(400).json(result); + } + } catch (error) { next(error); } }); -app.delete('/delete-meter', async (req: Request, res: Response) => { - let publicKey = decodeURIComponent(req.query?.publicKey?.toString() as string); - if (publicKey) { - const deleted = deleteMeterByPublicKey(publicKey.toString()); - if (!deleted) { - res.status(404).send({ message: 'meter not found' }); +app.delete('/delete-meter', async (req: Request, res: Response, next) => { + try { + const publicKey = typeof req.query.publicKey === 'string' ? req.query.publicKey : ''; + if (publicKey) { + const deleted = deleteMeterByPublicKey(publicKey.toString()); + if (!deleted) { + res.status(404).send({ message: 'meter not found' }); + return; + } + } else { + res.status(400).send({ message: 'public key not specified' }); return; } - } else { - res.status(400).send({ message: 'public key not specified' }); - return; - } - logger.info('Server handled DELETE request at `/delete-meter`'); - res.status(200).send({ message: 'deleted meter' }); + logger.info('Server handled DELETE request at `/delete-meter`'); + res.status(200).send({ message: 'deleted meter' }); + } catch (error) { next(error); } }); export const server = http.createServer(app); +attachManagerStream(server); export function startServer() { - server.listen(port, () => { + validateConsoleAuth(); + server.listen(Number(port), process.env.CONSOLE_HOST || '127.0.0.1', () => { logger.info(`Server is running at port ${port}`); }); } diff --git a/src/services/socket-router.ts b/src/services/socket-router.ts new file mode 100644 index 0000000..0c0efdd --- /dev/null +++ b/src/services/socket-router.ts @@ -0,0 +1,22 @@ +import type http from 'http'; +import { Socket } from 'net'; +import WebSocket from 'ws'; +import { isAuthenticated, isSameOrigin } from './auth'; +const servers = new WeakMap boolean }>>(); + +/** Shared authenticated upgrade boundary for terminal and application streams. */ +export function registerSocket(server: http.Server, path: string, wss: WebSocket.Server, authorize?: (req: http.IncomingMessage) => boolean): void { + let routes = servers.get(server); + if (!routes) { + routes = new Map(); servers.set(server, routes); + server.on('upgrade', (request, socket, head) => { + const target = routes!.get(request.url || ''); + if (!target || !isAuthenticated(request) || !isSameOrigin(request, true) || (target.authorize && !target.authorize(request))) { + socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return; + } + if (!(socket instanceof Socket)) { socket.destroy(); return; } + target.wss.handleUpgrade(request, socket, head, ws => target.wss.emit('connection', ws, request)); + }); + } + routes.set(path, { wss, authorize }); +} diff --git a/src/services/ssh.ts b/src/services/ssh.ts index 235369b..b3dd0f6 100644 --- a/src/services/ssh.ts +++ b/src/services/ssh.ts @@ -1,95 +1,75 @@ import http from 'http'; import WebSocket from 'ws'; -import { ConnectConfig, Client as SSHClient } from 'ssh2'; +import { Client as SSHClient, ClientChannel } from 'ssh2'; import { server } from './server'; +import { registerSocket } from './socket-router'; import { createLogger } from '../utils/logger'; const logger = createLogger('[ssh]'); -const wss = new WebSocket.Server({ server }); +export function attachTerminal(httpServer: http.Server): WebSocket.Server { + const wss = new WebSocket.Server({ noServer: true, maxPayload: 64 * 1024 }); + registerSocket(httpServer, '/terminal', wss); + wss.on('connection', (ws: WebSocket) => { + logger.info('Authenticated terminal connection established'); + let ssh: SSHClient | undefined; + let stream: ClientChannel | undefined; + let started = false; + const send = (message: string | Buffer) => { if (ws.readyState === WebSocket.OPEN) ws.send(message); }; + const timer = setTimeout(() => ws.close(1008, 'SSH credentials required'), 15000); + const cleanup = () => { clearTimeout(timer); stream?.end(); ssh?.end(); }; + ws.on('close', cleanup); + ws.on('error', cleanup); + const dimension = (value: unknown, fallback: number) => + typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 500 ? value : fallback; -wss.on('connection', (ws: WebSocket, request: http.IncomingMessage) => { - logger.info('[ws]: New WebSocket connection established', { url: request.url }); - - const url = new URL(request.url!, 'http://localhost'); - const cols = url.searchParams.get('cols') ?? '80'; - const rows = url.searchParams.get('rows') ?? '24'; - const username = url.searchParams.get('username') ?? 'ubuntu'; - const password = url.searchParams.get('password') ?? 'Mauchly92618'; - - const ssh = new SSHClient(); - const sshConfig: ConnectConfig = { - host: '127.0.0.1', - port: 22, - username, - password, - }; - - ssh - .on('ready', () => { - logger.info('[ws/ssh]: SSH connection established'); - ssh.shell({ term: 'xterm', cols: parseInt(cols), rows: parseInt(rows) }, (err, stream) => { - if (err) { - ws.send(`[ws/ssh]: SSH shell error: ${err.message}`); - ws.close(); - ssh.end(); + ws.on('message', data => { + if (!started) { + let auth; + try { auth = JSON.parse(data.toString()); } catch { ws.close(1008, 'Invalid authentication message'); return; } + if (auth?.type !== 'auth' || typeof auth.username !== 'string' || !auth.username || auth.username.length > 256 || + typeof auth.password !== 'string' || !auth.password || auth.password.length > 4096) { + ws.close(1008, 'SSH username and password are required'); return; } - - // SSH -> WebSocket - stream.on('data', (data: Buffer) => { - if (ws.readyState === WebSocket.OPEN) { - ws.send(data); - } - }); - - stream.on('close', () => { - logger.info('[ws/ssh]: SSH stream closed'); - ws.close(); - ssh.end(); - }); - - stream.stderr.on('data', (data: Buffer) => { - if (ws.readyState === WebSocket.OPEN) { - ws.send(`[ws/ssh]: SSH stderr: ${data.toString()}`); - } - }); - - logger.info('[ws/ssh]: Setting up WebSocket message handler'); - ws.on('message', (msg) => { - // support JSON control messages for resize - try { - const parsed = JSON.parse(msg.toString()); - if (parsed.type === 'resize') { - const { cols, rows } = parsed; - stream.setWindow(rows, cols, cols * 8, rows * 16); // width/height px optional - return; + started = true; + clearTimeout(timer); + const cols = dimension(auth.cols, 80), rows = dimension(auth.rows, 24); + ssh = new SSHClient(); + ssh.on('ready', () => { + if (ws.readyState !== WebSocket.OPEN) { ssh?.end(); return; } + ssh!.shell({ term: 'xterm', cols, rows }, (error, channel) => { + if (error || ws.readyState !== WebSocket.OPEN) { + channel?.end(); send('Unable to open SSH shell.'); ws.close(); ssh?.end(); return; } - } catch (e) { - /* not JSON - treat as raw data */ - } - - if (stream.writable) stream.write(msg); - }); - - ws.on('close', () => { - logger.info('[ws]: WebSocket closed, closing SSH stream'); - stream.end(); - ssh.end(); + stream = channel; + channel.on('data', send); + channel.stderr.on('data', send); + channel.on('close', () => { ws.close(); ssh?.end(); }); + channel.on('error', () => { send('SSH shell disconnected.'); ws.close(); }); + ws.send(JSON.stringify({ type: 'ready' })); + }); }); + ssh.on('error', () => { send('SSH connection failed. Check your credentials and host availability.'); ws.close(); ssh?.end(); }); + ssh.on('close', () => ws.close()); + try { + ssh.connect({ host: '127.0.0.1', port: 22, username: auth.username, password: auth.password, readyTimeout: 15000 }); + } catch { send('Unable to connect to SSH.'); ws.close(); cleanup(); } + return; + } + if (!stream) return; + try { + const control = JSON.parse(data.toString()); + if (control.type === 'resize') { + const cols = dimension(control.cols, 80), rows = dimension(control.rows, 24); + stream.setWindow(rows, cols, cols * 8, rows * 16); + return; + } + } catch { /* Terminal keystrokes are ordinary text, not control messages. */ } + if (stream.writable) stream.write(data.toString()); + }); + }); + return wss; +} - ws.on('error', () => { - logger.error('[ws]: WebSocket error, closing SSH stream'); - stream.end(); - ssh.end(); - }); - }); - }) - .on('error', (err) => { - logger.error('[ws/ssh]: SSH connection error:', err); - ws.send(`[ws/ssh]: SSH connection error: ${err.message}`); - ws.close(); - ssh.end(); - }) - .connect(sshConfig); -}); +attachTerminal(server); diff --git a/src/store/sqlite.ts b/src/store/sqlite.ts index 4804fb1..1b80716 100644 --- a/src/store/sqlite.ts +++ b/src/store/sqlite.ts @@ -3,6 +3,7 @@ import Database from "better-sqlite3"; import type { Database as DatabaseType, Statement as DatabaseStatementType } from "better-sqlite3"; import { MeterRecord, TransactionRecord } from "../types"; import { createLogger } from "../utils/logger"; +import { initializeManagerStore } from '../m3ter/store'; const logger = createLogger("[sqlite]"); @@ -26,11 +27,14 @@ let getTransactionByNonceQuery: DatabaseStatementType; * @param databaseName name of the database file */ export default function setupDatabase(databaseName = "m3tering.db") { + if (db?.open) db.close(); + fs.mkdirSync("./.data", { recursive: true }); db = new Database(`./.data/${databaseName}`, {}); initializeTransactionsTable(); initializeMetersTable(); prepareQueries(); + initializeManagerStore(db); } export function deleteDatabase(databaseName = "m3tering.db") { @@ -253,6 +257,17 @@ export function insertTransaction(transactionData: TransactionRecord): void { } } +/** Persist a transaction and advance its meter nonce as one SQLite commit. */ +export function recordMeterTransaction(publicKey: string, record: TransactionRecord): void { + db.transaction(() => { + createTransactionQuery.run(record); + const result = db.prepare(`UPDATE meters SET latestNonce = ? + WHERE publicKey = ? AND tokenId = ? AND latestNonce = ?`) + .run(record.nonce, publicKey, record.identifier, record.nonce - 1); + if (result.changes !== 1) throw new Error('Meter nonce changed or meter was not found'); + })(); +} + export function getAllTransactionRecords(): TransactionRecord[] { try { const results = db.prepare(`SELECT * FROM transactions`).all() as TransactionRecord[]; diff --git a/src/views/index.hbs b/src/views/index.hbs index 249a735..49a9015 100644 --- a/src/views/index.hbs +++ b/src/views/index.hbs @@ -1,295 +1,71 @@ -
- -
- {{! {/* Apps */} }} -
-
- {{! {/* M3ters Icon */} }} -
-
-
-
-
- M3ter - M3ter -
-
- M3ter - M3ter -
-
-

M3ters

-
-
-
- - {{! {/* Paint Icon */} }} -
-
- - - -

Paint

-
-
- - {{! {/* terminal Icon */} }} -
-
- -

Terminal

-
-
- - {{! {/* Browser Icon */} }} -
-
- -

browse

-
+ +
+
+ +
Desktop
+
+
+
+ +
+ + + + + + + {{#each icons}} + + {{/each}} + + +
+
A workspace for a connected world.
+
+ + + + + {{> m3ter-manager}} + {{#each windows}} + + {{/each}} +
-
- - {{! {/* google app */} }} - - - {{! }} -
-
\ No newline at end of file + + +
+ +

Reset your desktop?

Your custom icon positions will be cleared. Your applications and other preferences will stay as they are.

+
+
+
diff --git a/src/views/layouts/main.hbs b/src/views/layouts/main.hbs index 4d12805..ee10278 100644 --- a/src/views/layouts/main.hbs +++ b/src/views/layouts/main.hbs @@ -1,24 +1,30 @@ - + + - Mqtt-express - - - - + + + + M3tering Console · Desktop + + + + + + + + - {{{body}}} + + + + + + + + + + - - - - - - \ No newline at end of file + diff --git a/src/views/partials/m3ter-manager.hbs b/src/views/partials/m3ter-manager.hbs new file mode 100644 index 0000000..5b17133 --- /dev/null +++ b/src/views/partials/m3ter-manager.hbs @@ -0,0 +1,45 @@ + diff --git a/tests/logic/codec.test.ts b/tests/logic/codec.test.ts new file mode 100644 index 0000000..5dcf62f --- /dev/null +++ b/tests/logic/codec.test.ts @@ -0,0 +1,20 @@ +import { generateKeyPairSync, sign } from 'crypto'; +import { encodeTransaction } from '../../src/lib/encode'; +import { decodePayload } from '../../src/lib/decode'; +import { verifyPayloadSignature } from '../../src/lib/utils'; + +const record = { nonce: 12, energy: 1.234567, signature: 'ab'.repeat(64), deviceId: 'cd'.repeat(32), voltage: 230.1, longitude: -12.34567, latitude: 43.21098 }; +test('transaction bytes round trip without scaling or hex corruption', () => { + const decoded = decodePayload(Buffer.from(encodeTransaction(record))); + expect(decoded).toMatchObject({ nonce: record.nonce, energy: record.energy, signature: record.signature, extensions: { deviceId: record.deviceId, voltage: record.voltage, longitude: record.longitude, latitude: record.latitude } }); +}); +test('a real Ed25519 signature remains valid after encoding', () => { + const { publicKey, privateKey } = generateKeyPairSync('ed25519'); + const message = Buffer.alloc(8); message.writeUInt32BE(record.nonce, 0); message.writeUInt32BE(1234567, 4); + const rawKey = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32); + const encoded = Buffer.from(encodeTransaction({ ...record, signature: sign(null, message, privateKey).toString('hex'), deviceId: '0x' + rawKey.toString('hex') })); + expect(verifyPayloadSignature(encoded, rawKey)).toBe(true); +}); +test.each([{ signature: 'bad' }, { deviceId: 'zz'.repeat(32) }, { energy: NaN }, { nonce: -1 }, { longitude: 180 }])('rejects malformed or unrepresentable values %j', override => { + expect(() => encodeTransaction({ ...record, ...override })).toThrow(); +}); diff --git a/tests/logic/hooks.test.ts b/tests/logic/hooks.test.ts new file mode 100644 index 0000000..76a9ccd --- /dev/null +++ b/tests/logic/hooks.test.ts @@ -0,0 +1,20 @@ +import { defaultConfigurations, loadExtensionsFromConfig, runHook, notifyHook } from '../../src/lib/utils'; +let extensions: any[]; +beforeEach(async () => { defaultConfigurations.modules = []; extensions = await loadExtensionsFromConfig(); extensions.splice(0); }); +afterEach(() => extensions.splice(0)); +test('one rejected delivery hook does not skip later services', async () => { + const delivered = jest.fn(); + extensions.push({ onTransactionDistribution: async () => { throw new Error('upload failed'); } }, { onTransactionDistribution: delivered }); + await expect(notifyHook('onTransactionDistribution', 1, {} as any, [])).resolves.toBeUndefined(); + expect(delivered).toHaveBeenCalledTimes(1); +}); +test('lifecycle hooks remain awaited and propagate failures to startup', async () => { + let resolve!: () => void; + extensions.push({ onBeforeInit: () => new Promise(r => { resolve = r; }) }); + let finished = false; + const task = runHook('onBeforeInit').then(() => { finished = true; }); + await Promise.resolve(); expect(finished).toBe(false); + resolve(); await task; expect(finished).toBe(true); + extensions.push({ onAfterInit: () => { throw new Error('invalid cron'); } }); + await expect(runHook('onAfterInit')).rejects.toThrow('onAfterInit'); +}); diff --git a/tests/logic/jobs.test.ts b/tests/logic/jobs.test.ts new file mode 100644 index 0000000..388c56e --- /dev/null +++ b/tests/logic/jobs.test.ts @@ -0,0 +1,29 @@ +import cron from 'node-cron'; +import { getSyncedPendingTransactions } from '../../src/lib/sync'; +jest.mock('node-cron', () => ({ schedule: jest.fn() })); +jest.mock('@streamr/sdk', () => ({ StreamrClient: jest.fn() })); +jest.mock('../../src/lib/sync', () => ({ getSyncedPendingTransactions: jest.fn() })); +jest.mock('../../src/store/sqlite', () => ({})); +const old = { prover: process.env.PREFERRED_PROVER_NODE, key: process.env.ETHEREUM_PRIVATE_KEY, stream: process.env.STREAMR_STREAM_ID }; +beforeAll(() => { process.env.PREFERRED_PROVER_NODE = 'https://prover.example'; process.env.ETHEREUM_PRIVATE_KEY = 'test-only'; process.env.STREAMR_STREAM_ID = 'test-stream'; }); +afterAll(() => { + for (const [name, value] of Object.entries({ PREFERRED_PROVER_NODE: old.prover, ETHEREUM_PRIVATE_KEY: old.key, STREAMR_STREAM_ID: old.stream })) { + if (value === undefined) delete process.env[name]; else process.env[name] = value; + } +}); +test.each(['prover', 'streamr'])('%s cron waits for a synchronized batch before delivery', async type => { + jest.clearAllMocks(); + const Module = require(`../../src/lib/core/${type}`).default; + const extension = new Module(); + const method = type === 'prover' ? 'sendPendingTransactionsToProver' : 'publishPendingTransactionsToStreamr'; + const deliver = jest.spyOn(extension, method).mockResolvedValue({ text: async () => 'ok' }); + let resume!: (records: any[]) => void; + (getSyncedPendingTransactions as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { resume = resolve; })); + await extension.onAfterInit(); + const callback = (cron.schedule as jest.Mock).mock.calls[0][1]; + const running = callback(); + expect(deliver).not.toHaveBeenCalled(); + const records = [{ nonce: 3, identifier: 42, raw: 'abc', receivedAt: 1 }]; + resume(records); await running; + expect(deliver).toHaveBeenCalledWith(type === 'prover' ? 'https://prover.example' : 'test-stream', records); +}); diff --git a/tests/logic/manager-commands.test.ts b/tests/logic/manager-commands.test.ts new file mode 100644 index 0000000..d76c007 --- /dev/null +++ b/tests/logic/manager-commands.test.ts @@ -0,0 +1,28 @@ +import { commandCatalogue, generateCommand } from '../../src/m3ter/commands'; +test.each([ + ['relay-on', undefined, 'Gw==', 2, 1], ['relay-off', undefined, 'HA==', 2, 1], + ['billing-disconnect', undefined, 'AA==', 2, 1], ['billing-connect', undefined, 'AQ==', 2, 1], ['restart', undefined, 'HQ==', 2, 1], + ['report-interval', 60, 'AgA8', 2, 3], ['report-interval', 900, 'AgOE', 2, 3], + ['relay-drive', 1, 'HgE=', 2, 2], ['relay-drive', 0, 'HgA=', 2, 2], ['relay-fitted', 1, 'HwE=', 2, 2], ['relay-fitted', 0, 'HwA=', 2, 2], + ['current-gain', 1, 'IAE=', 2, 2], ['current-gain', 2, 'IAI=', 2, 2], ['current-gain', 4, 'IAQ=', 2, 2], + ['voltage-gain', 1, 'IQE=', 2, 2], ['voltage-gain', 2, 'IQI=', 2, 2], ['voltage-gain', 4, 'IQQ=', 2, 2], + ['phase-mode', 0, 'IgA=', 2, 2], ['phase-mode', 1, 'IgE=', 2, 2], ['phase-mode', 2, 'IgI=', 2, 2], ['phase-mode', 3, 'IgM=', 2, 2], + ['class-a', undefined, 'AA==', 3, 1], ['class-c', undefined, 'Ag==', 3, 1], +])('%s %s matches the firmware frame', (id, value, data, fPort, length) => { + expect(generateCommand(id, value)).toMatchObject({ data, fPort, length, confirmed: false }); +}); +test('catalogue has exactly thirteen supported types and explicit safety controls', () => { + expect(commandCatalogue).toHaveLength(13); + for (const id of ['billing-connect','billing-disconnect','restart','relay-drive','relay-fitted','class-a']) expect(generateCommand(id, id === 'relay-drive' || id === 'relay-fitted' ? 1 : undefined).requiresConfirmation).toBe(true); + for (const id of ['class-b', 'calibrate', 'fuota', 200, null]) expect(() => generateCommand(id)).toThrow(); +}); +test('report intervals use exact unsigned big endian boundaries', () => { + expect(generateCommand('report-interval', 10).hex).toBe('02000A'); + expect(generateCommand('report-interval', 65535).hex).toBe('02FFFF'); + for (const value of [9,65536,-1,1.1,NaN,Infinity,'60',null,undefined]) expect(() => generateCommand('report-interval',value)).toThrow(); +}); +test('unsupported parameters are never encoded', () => { + for (const id of ['current-gain','voltage-gain']) for (const value of [0,3,8,256,'2']) expect(() => generateCommand(id,value)).toThrow(); + for (const value of [-1,4,200,'1']) expect(() => generateCommand('phase-mode',value)).toThrow(); + expect(() => generateCommand('relay-on',1)).toThrow(); +}); diff --git a/tests/logic/manager-decoder.test.ts b/tests/logic/manager-decoder.test.ts new file mode 100644 index 0000000..9073fdb --- /dev/null +++ b/tests/logic/manager-decoder.test.ts @@ -0,0 +1,27 @@ +import { generateKeyPairSync, sign } from 'crypto'; +import { decodeTelemetry } from '../../src/m3ter/decoder'; +import { decodePayload } from '../../src/lib/decode'; +const keys = generateKeyPairSync('ed25519'); +const publicKey = keys.publicKey.export({ format: 'der', type: 'spki' }).subarray(-32); +function payload(length: number, nonce = 0) { + const bytes = Buffer.alloc(length); bytes.writeUInt32BE(nonce,0); bytes.writeUInt32BE(12345678,4); + sign(null, bytes.subarray(0,8), keys.privateKey).copy(bytes,8); bytes.writeUInt16BE(2301,72); + if (length === 106) publicKey.copy(bytes,74); return bytes; +} +test.each([74,106])('%d byte telemetry reuses the existing decoder and exact scaling', length => { + const data = payload(length, length === 74 ? 4294967295 : 0), decoded = decodeTelemetry(2,data, length === 74 ? publicKey.toString('hex') : undefined); + expect(decoded).toMatchObject({ nonce: length === 74 ? 4294967295 : 0, rawEnergy: 12345678, energy: 12.345678, rawVoltage: 2301, voltage: 230.1, verification:'verified' }); + expect(decoded.energy).toBe(decodePayload(data).energy); expect(decoded.voltage).toBe(decodePayload(data).extensions.voltage); + expect(decoded.signature).toHaveLength(128); expect(decoded.publicKey).toBe(length === 106 ? publicKey.toString('hex') : null); + expect(decoded).not.toHaveProperty('latitude'); expect(decoded).not.toHaveProperty('longitude'); +}); +test('never claims verification without a known key and detects tampering', () => { + const data = payload(74, 1); expect(decodeTelemetry(2,data).verification).toBe('unverified'); + data[0] ^= 1; expect(decodeTelemetry(2,data,publicKey.toString('hex')).verification).toBe('invalid'); +}); +test('voltage is explicitly outside the verified signature region', () => { + const data = payload(106); data.writeUInt16BE(6900,72); + expect(decodeTelemetry(2,data)).toMatchObject({ voltage: 690, verification:'verified' }); +}); +test.each([0,1,72,73,75,105,107,112,256])('rejects invalid length %d', length => { expect(() => decodeTelemetry(2,Buffer.alloc(length))).toThrow(); }); +test.each([0,1,3,200,201,202])('does not decode unrelated FPort %d', port => { expect(() => decodeTelemetry(port,payload(74))).toThrow(); }); diff --git a/tests/logic/modules.test.ts b/tests/logic/modules.test.ts new file mode 100644 index 0000000..fd61e26 --- /dev/null +++ b/tests/logic/modules.test.ts @@ -0,0 +1,46 @@ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import ts from 'typescript'; +import { getModuleConfiguration, parseModuleReference, resolveModulePath } from '../../src/lib/modules'; +const { installModules } = require('../../scripts/install-modules.cjs'); + +test('runtime and installer share owner/repo paths, UI references, and pinned refs', () => { + const config = getModuleConfiguration({ BACKEND_MODULES: ' core/is_on, alice/extension#v1 ', UI_MODULES: 'custom:alice/extension#v1, streamr:core/streamr/ui' }); + expect(config.external).toEqual([{ reference: 'alice/extension#v1', builtIn: false, repository: 'alice/extension', ref: 'v1' }]); + expect(resolveModulePath('/app/dist/lib', config.modules[1])).toBe('/app/dist/extensions/alice/extension'); + expect(resolveModulePath('/app/dist/lib', config.uiModules.streamr)).toBe('/app/dist/lib/core/streamr/ui'); + expect(() => getModuleConfiguration({ BACKEND_MODULES: 'a/b#v1', UI_MODULES: 'test:a/b#v2' })).toThrow('Conflicting'); +}); +test.each(['../outside', '/tmp/module', 'a/b#../../escape', 'a/b#-flag', 'core/../outside', 'https://github.com/a/b'])('invalid module reference %s is rejected', reference => expect(() => parseModuleReference(reference)).toThrow()); +test('external modules install and rebuild at the exact runtime location without downloading core modules', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'console-modules-')); + try { + fs.mkdirSync(path.join(root, 'dist/lib'), { recursive: true }); + fs.mkdirSync(path.join(root, 'src'), { recursive: true }); + fs.writeFileSync(path.join(root, 'src/index.ts'), 'export {};'); + fs.writeFileSync(path.join(root, 'src/types.ts'), 'export interface Hooks { onAfterInit(): void }'); + const compiled = ts.transpileModule(fs.readFileSync(path.resolve('src/lib/modules.ts'), 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true } }).outputText; + fs.writeFileSync(path.join(root, 'dist/lib/modules.js'), compiled); + const run = jest.fn((command, args) => { + if (command === 'git' && args[0] === 'clone') { + const dest = args.at(-1); fs.mkdirSync(dest, { recursive: true }); + fs.writeFileSync(path.join(dest, 'index.ts'), 'import type { Hooks } from "../../../types"; export default class implements Hooks { onAfterInit() {} }'); + fs.writeFileSync(path.join(dest, 'package.json'), '{}'); + } + if (command === 'npm' && args[0] === 'run') { + const program = ts.createProgram([path.join(root, 'src/index.ts'), path.join(root, 'src/extensions/alice/custom/index.ts')], { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.CommonJS, rootDir: path.join(root, 'src'), outDir: path.join(root, 'dist'), skipLibCheck: true, types: [] }); + expect(ts.getPreEmitDiagnostics(program)).toEqual([]); + program.emit(); + } + }); + installModules({ appDir: root, env: { BACKEND_MODULES: 'core/is_on,alice/custom#v1', UI_MODULES: 'custom:alice/custom#v1' }, run }); + expect(run).toHaveBeenCalledWith('git', ['clone', '--depth=1', '--branch', 'v1', 'https://github.com/alice/custom.git', path.join(root, 'src/extensions/alice/custom')], expect.anything()); + const Loaded = require(resolveModulePath(path.join(root, 'dist/lib'), 'alice/custom#v1')).default; + expect(typeof new Loaded().onAfterInit).toBe('function'); + expect(run).toHaveBeenLastCalledWith('npm', ['run', 'build'], expect.objectContaining({ cwd: root })); + installModules({ appDir: root, env: { BACKEND_MODULES: 'alice/custom#v2' }, run }); + expect(run).toHaveBeenCalledWith('git', ['fetch', '--depth=1', 'origin', 'v2'], expect.anything()); + expect(run).toHaveBeenCalledWith('git', ['checkout', '--detach', 'FETCH_HEAD'], expect.anything()); + } finally { fs.rmSync(root, { recursive: true, force: true }); } +}); diff --git a/tests/logic/power.test.ts b/tests/logic/power.test.ts new file mode 100644 index 0000000..df87f63 --- /dev/null +++ b/tests/logic/power.test.ts @@ -0,0 +1,12 @@ +import Power from '../../src/lib/core/is_on'; +import { getCrossChainRevenue, getOwedFromPriceContext } from '../../src/lib/sync'; +jest.mock('../../src/lib/sync', () => ({ getCrossChainRevenue: jest.fn(), getOwedFromPriceContext: jest.fn() })); +test.each([[10n, 10n, true], [20n, 10n, true], [9n, 10n, false], [9007199254740992n, 9007199254740993n, false]])('compares revenue %s against debt %s exactly', async (revenue, owed, expected) => { + (getCrossChainRevenue as jest.Mock).mockResolvedValue(revenue); + (getOwedFromPriceContext as jest.Mock).mockResolvedValue(owed); + expect(await new Power().isOnStateCompute(42)).toBe(expected); +}); +test('a failed balance read is not silently treated as paid', async () => { + (getCrossChainRevenue as jest.Mock).mockRejectedValue(new Error('RPC unavailable')); + await expect(new Power().isOnStateCompute(42)).rejects.toThrow('RPC unavailable'); +}); diff --git a/tests/logic/publishing.test.ts b/tests/logic/publishing.test.ts new file mode 100644 index 0000000..53d57e0 --- /dev/null +++ b/tests/logic/publishing.test.ts @@ -0,0 +1,20 @@ +import { getSyncedPendingTransactions } from '../../src/lib/sync'; +import * as store from '../../src/store/sqlite'; +import { meterLatestNonceContractCall } from '../../src/utils/contracts'; +jest.mock('../../src/services/contracts', () => ({})); +jest.mock('../../src/utils/contracts', () => ({ meterLatestNonceContractCall: jest.fn() })); +jest.mock('../../src/store/sqlite', () => ({ getAllMeterRecords: jest.fn(), getAllTransactionRecords: jest.fn(), getMeterByPublicKey: jest.fn(), getMeterByTokenId: jest.fn(), pruneTransactionsBefore: jest.fn(), updateMeterNonce: jest.fn() })); +test('batch reads wait for pruning and exclude failed meters and already confirmed nonces', async () => { + const meters = [{ publicKey: 'a', tokenId: 1, latestNonce: 4 }, { publicKey: 'b', tokenId: 2, latestNonce: 4 }]; + (store.getAllMeterRecords as jest.Mock).mockReturnValue(meters); + (store.getMeterByPublicKey as jest.Mock).mockImplementation(key => meters.find(meter => meter.publicKey === key)); + (store.getAllTransactionRecords as jest.Mock).mockReturnValue([{ identifier: 1, nonce: 2 }, { identifier: 1, nonce: 3 }, { identifier: 2, nonce: 3 }]); + let resume!: (nonce: number) => void; + (meterLatestNonceContractCall as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { resume = resolve; })).mockRejectedValueOnce(new Error('RPC unavailable')); + const batch = getSyncedPendingTransactions(); + expect(store.getAllTransactionRecords).not.toHaveBeenCalled(); + resume(2); + await expect(batch).resolves.toEqual([{ identifier: 1, nonce: 3 }]); + expect(store.pruneTransactionsBefore).toHaveBeenCalledWith(2, 1); + expect((store.pruneTransactionsBefore as jest.Mock).mock.invocationCallOrder[0]).toBeLessThan((store.getAllTransactionRecords as jest.Mock).mock.invocationCallOrder[0]); +}); diff --git a/tests/logic/sync.test.ts b/tests/logic/sync.test.ts index 2e9d28c..3ae637c 100644 --- a/tests/logic/sync.test.ts +++ b/tests/logic/sync.test.ts @@ -11,6 +11,7 @@ jest.mock("../../src/services/contracts", () => ({ provider: { resolveName: jest.fn(), }, + priceContext: { owed: jest.fn() }, ccipRevenueReader: { verifierCount: jest.fn(), verifiers: jest.fn(), @@ -98,7 +99,7 @@ describe("Verifiers Cache", () => { const result = await getCrossChainRevenue(123); - expect(result).toBe(1000); + expect(result).toBe(1000n); expect(ccipRevenueReader.read).toHaveBeenCalledWith( 123, "0x1234567890123456789012345678901234567890", @@ -111,3 +112,16 @@ describe("Verifiers Cache", () => { expect(ccipRevenueReader.verifiers).toHaveBeenCalledTimes(1); }); }); + + +it("preserves large revenues and rejects incomplete verifier totals", async () => { + const { provider, ccipRevenueReader } = require("../../src/services/contracts"); + ccipRevenueReader.verifierCount.mockResolvedValue(1n); + ccipRevenueReader.verifiers.mockResolvedValue(["test.eth", "0x1234567890123456789012345678901234567890"]); + provider.resolveName.mockResolvedValue("0x1111111111111111111111111111111111111111"); + await initializeVerifiersCache(); + ccipRevenueReader.read.mockResolvedValueOnce(9007199254740993n); + await expect(getCrossChainRevenue(123)).resolves.toBe(9007199254740993n); + ccipRevenueReader.read.mockRejectedValueOnce(new Error("gateway failed")); + await expect(getCrossChainRevenue(123)).rejects.toThrow("gateway failed"); +}); diff --git a/tests/services/auth.test.ts b/tests/services/auth.test.ts new file mode 100644 index 0000000..c7d7f93 --- /dev/null +++ b/tests/services/auth.test.ts @@ -0,0 +1,38 @@ +import { isAuthenticated, isSameOrigin, requireConsoleAuth, validateConsoleAuth } from '../../src/services/auth'; +const originalEnv = process.env; +beforeEach(() => { process.env = { ...originalEnv, CONSOLE_USERNAME: 'admin', CONSOLE_PASSWORD: 'test-only-password' }; delete process.env.CONSOLE_ORIGIN; }); +afterEach(() => { process.env = originalEnv; }); +const request = (headers = {}, method = 'GET'): any => ({ headers: { host: 'localhost:3000', ...headers }, socket: {}, method }); +const credentials = { authorization: 'Basic ' + Buffer.from('admin:test-only-password').toString('base64') }; +test('credentials are required and compared without accepting malformed or partial values', () => { + expect(isAuthenticated(request(credentials))).toBe(true); + for (const value of ['', 'Bearer token', 'Basic !!!', 'Basic ' + Buffer.from('admin:wrong').toString('base64')]) expect(isAuthenticated(request({ authorization: value }))).toBe(false); + delete process.env.CONSOLE_PASSWORD; + expect(isAuthenticated(request(credentials))).toBe(false); + expect(validateConsoleAuth).toThrow('CONSOLE_PASSWORD'); +}); +test('cross-origin browser requests are rejected; proxy origins are explicit', () => { + expect(isSameOrigin(request({ origin: 'http://localhost:3000' }), true)).toBe(true); + expect(isSameOrigin(request({ origin: 'https://attacker.example' }), true)).toBe(false); + expect(isSameOrigin(request(), true)).toBe(false); + expect(isSameOrigin(request())).toBe(true); + process.env.CONSOLE_ORIGIN = 'https://console.example'; + expect(isSameOrigin(request({ origin: 'https://console.example' }), true)).toBe(true); + expect(isSameOrigin(request({ origin: 'http://localhost:3000' }), true)).toBe(false); + process.env.CONSOLE_ORIGIN = 'https://console.example/path'; + expect(validateConsoleAuth).toThrow('CONSOLE_ORIGIN'); +}); +test.each(['GET', 'POST', 'DELETE'])('%s routes do not proceed without authentication', method => { + const response: any = { setHeader: jest.fn(), status: jest.fn().mockReturnThis(), send: jest.fn() }; + const next = jest.fn(); + requireConsoleAuth(request({}, method), response, next); + expect(response.status).toHaveBeenCalledWith(401); expect(next).not.toHaveBeenCalled(); + requireConsoleAuth(request(credentials, method), response, next); + expect(next).toHaveBeenCalledTimes(1); +}); +test('authenticated cross-site mutations still fail', () => { + const response: any = { setHeader: jest.fn(), status: jest.fn().mockReturnThis(), send: jest.fn() }; + const next = jest.fn(); + requireConsoleAuth(request({ ...credentials, origin: 'https://attacker.example' }, 'POST'), response, next); + expect(response.status).toHaveBeenCalledWith(403); expect(next).not.toHaveBeenCalled(); +}); diff --git a/tests/services/chirpstack.test.ts b/tests/services/chirpstack.test.ts new file mode 100644 index 0000000..6a2eabf --- /dev/null +++ b/tests/services/chirpstack.test.ts @@ -0,0 +1,35 @@ +import { chirpstackTarget, hasChirpstackSession, rewriteChirpstackText } from '../../src/services/chirpstack'; + +const originalEnv = process.env; +afterEach(() => { process.env = originalEnv; }); + +test('web endpoint defaults to the existing host and accepts only configured HTTP origins', () => { + process.env = { ...originalEnv, CHIRPSTACK_HOST: 'network-server' }; + delete process.env.CHIRPSTACK_WEB_URL; + expect(chirpstackTarget().href).toBe('http://network-server:8080/'); + process.env.CHIRPSTACK_HOST = '::1'; + expect(chirpstackTarget().href).toBe('http://[::1]:8080/'); + process.env.CHIRPSTACK_WEB_URL = 'https://chirpstack.example:8443'; + expect(chirpstackTarget().origin).toBe('https://chirpstack.example:8443'); + for (const value of ['file:///etc/passwd', 'http://user:secret@host', 'http://host/ui', 'http://host/?token=secret', 'http://host/#foo']) { + process.env.CHIRPSTACK_WEB_URL = value; + expect(chirpstackTarget).toThrow(); + } +}); + +test('HTML bootstraps the compatibility bridge before app assets and preserves external URLs', () => { + const output = rewriteChirpstackText('Login', true); + expect(output.indexOf('chirpstack-bridge.js')).toBeLessThan(output.indexOf('/chirpstack/assets/app.js')); + expect(output).toContain('href="/chirpstack/icon.png"'); + expect(output).toContain('href="//external.test/a.css"'); + expect(output).toContain('href="#/login"'); + expect(rewriteChirpstackText('import("/assets/chunk.js");url(/static/font.woff)', false)).toBe('import("/chirpstack/assets/chunk.js");url(/chirpstack/static/font.woff)'); + expect(rewriteChirpstackText('src:"/logo.png",path:"/tenants"', false)).toBe('src:"/chirpstack/logo.png",path:"/tenants"'); +}); + +test('proxy sessions reject malformed, forged and expired tokens', () => { + process.env = { ...originalEnv, CONSOLE_USERNAME: 'admin', CONSOLE_PASSWORD: 'test' }; + for (const value of [undefined, '', 'console_chirpstack=oops', 'console_chirpstack=1.' + 'a'.repeat(64), `console_chirpstack=${Math.floor(Date.now()/1000)+3600}.${'b'.repeat(64)}`]) { + expect(hasChirpstackSession(value)).toBe(false); + } +}); diff --git a/tests/services/install.test.ts b/tests/services/install.test.ts new file mode 100644 index 0000000..200d49b --- /dev/null +++ b/tests/services/install.test.ts @@ -0,0 +1,39 @@ +import { mkdtempSync, mkdirSync, copyFileSync, writeFileSync, readFileSync, rmSync } from 'fs'; +import { tmpdir } from 'os'; +import { join, resolve } from 'path'; +import { spawnSync } from 'child_process'; +let directory:string; +beforeEach(()=>{ + directory=mkdtempSync(join(tmpdir(),'console install ')); mkdirSync(join(directory,'bin')); + copyFileSync(resolve('install.sh'),join(directory,'install.sh')); writeFileSync(join(directory,'.env'),'# fixture\n'); + writeFileSync(join(directory,'bin','docker'),`#!/usr/bin/env bash +printf '%s\\n' "$*" >> "$INSTALL_TEST_LOG" +if [[ "$*" == *"build console"* && "\${INSTALL_TEST_FAIL_BUILD:-}" == 1 ]]; then exit 1; fi +if [[ "$*" == *"up --detach"* && "\${INSTALL_TEST_FAIL_START:-}" == 1 ]]; then exit 1; fi +`,{mode:0o755}); +}); +afterEach(()=>rmSync(directory,{recursive:true,force:true})); +function run(args:string[]=[],extra:Record={}) { + return spawnSync('bash',[join(directory,'install.sh'),...args],{encoding:'utf8',cwd:tmpdir(),env:{...process.env, + PATH:join(directory,'bin')+':'+process.env.PATH,INSTALL_TEST_LOG:join(directory,'calls'),...extra}}); +} +const calls=()=>readFileSync(join(directory,'calls'),'utf8'); +test('builds before recreating only the selected service and retains data volumes',()=>{ + expect(run(['--project-name','existing-console']).status).toBe(0);const log=calls(); + expect(log.indexOf('build console')).toBeLessThan(log.indexOf('up --detach')); + expect(log).toContain('--project-name existing-console -f compose.yaml -f compose.local.yaml'); + expect(log).toContain('up --detach --no-deps --no-build --pull never --force-recreate --wait --wait-timeout 240 console'); + expect(log).not.toMatch(/down|prune|--volumes|\brm\b/); +}); +test('a failed build leaves the current service untouched',()=>{ + expect(run([],{INSTALL_TEST_FAIL_BUILD:'1'}).status).toBe(1);expect(calls()).not.toContain('up --detach'); +}); +test('startup failures are reported without deleting data or claiming success',()=>{ + const result=run([],{INSTALL_TEST_FAIL_START:'1'});expect(result.status).toBe(1); + expect(result.stderr).toContain('did not become ready');expect(result.stdout).not.toContain('current build is running'); +}); +test('requires environment configuration and rejects invalid arguments',()=>{ + rmSync(join(directory,'.env'));expect(run().stderr).toContain('Missing .env'); + expect(run(['--project-name','../invalid']).status).toBe(2); + expect(run(['--help']).status).toBe(0); +}); diff --git a/tests/services/manager-auth.test.ts b/tests/services/manager-auth.test.ts new file mode 100644 index 0000000..e8caa2a --- /dev/null +++ b/tests/services/manager-auth.test.ts @@ -0,0 +1,37 @@ +import { managerAuthRouter, managerAuthenticated, requireManagerAuth } from '../../src/m3ter/auth'; +const original = process.env; +let address = 0; +beforeEach(() => { process.env = { ...original, M3TER_MANAGER_USERNAME: 'operator', M3TER_MANAGER_PASSWORD: 'unique-password' }; address++; }); +afterEach(() => { process.env = original; jest.restoreAllMocks(); }); +function request(body?: any, cookie = ''): any { return { body, headers: { cookie }, socket: { remoteAddress: String(address) }, secure: false }; } +function response(): any { + const res:any = { code: 200, headers: {}, status(n:number) { this.code=n;return this; }, json(body:any) { this.body=body;return this; }, + cookie(name:string,value:string,options:any) { this.value=name+'='+value;this.options=options; }, setHeader(name:string,value:any) { this.headers[name]=value; } }; + return res; +} +function call(method:string, req:any) { + const res=response(), route=managerAuthRouter.stack.find((layer:any)=>layer.route?.path==='/session' && layer.route.methods[method]); + route.route.stack[0].handle(req,res,()=>{}); return res; +} +function login() { return call('post',request({username:'operator',password:'unique-password'})); } +test('missing configuration fails closed and credentials never enter the response', () => { + delete process.env.M3TER_MANAGER_PASSWORD; + expect(login().code).toBe(503); expect(call('get',request()).body).toMatchObject({authenticated:false,configured:false}); + const res=response(); requireManagerAuth(request(),res,jest.fn()); expect(res.code).toBe(401); +}); +test('login, HttpOnly cookie, revocation, expiry and credential rotation', () => { + const first=login(); expect(first.code).toBe(200); + expect(first.options).toMatchObject({httpOnly:true,sameSite:'strict',path:'/'}); + expect(JSON.stringify(first.body)).not.toContain('password'); + const req=request(undefined,first.value); expect(managerAuthenticated(req)).toBe(true); + call('delete',req); expect(managerAuthenticated(req)).toBe(false); + const next=login(), later=Date.now()+8*3600000+1; + jest.spyOn(Date,'now').mockReturnValue(later); expect(managerAuthenticated(request(undefined,next.value))).toBe(false); + jest.restoreAllMocks(); const third=login(); process.env.M3TER_MANAGER_PASSWORD='rotated'; + expect(managerAuthenticated(request(undefined,third.value))).toBe(false); +}); +test('generic errors, bounded attempts and secure proxy cookies', () => { + for(let i=0;i<10;i++) expect(call('post',request({username:'operator',password:'wrong'})).code).toBe(403); + const locked=login(); expect(locked.code).toBe(429); expect(locked.headers['Retry-After']).toBeGreaterThan(0); + address++; process.env.CONSOLE_ORIGIN='https://console.example.com'; expect(login().options.secure).toBe(true); +}); diff --git a/tests/services/mqtt.test.ts b/tests/services/mqtt.test.ts new file mode 100644 index 0000000..7c452dc --- /dev/null +++ b/tests/services/mqtt.test.ts @@ -0,0 +1,94 @@ +import { handleMessage } from '../../src/services/mqtt'; +import * as store from '../../src/store/sqlite'; +import { getLatestTransactionNonce } from '../../src/lib/sync'; +import { runHook, notifyHook, verifyPayloadSignature } from '../../src/lib/utils'; +import { enqueue } from '../../src/services/grpc'; + +jest.mock('mqtt', () => ({ connect: jest.fn() })); +jest.mock('../../src/services/grpc', () => ({ enqueue: jest.fn() })); +jest.mock('../../src/store/sqlite', () => ({ getAllTransactionRecords: jest.fn(), getMeterByDevEui: jest.fn(), getMeterByPublicKey: jest.fn(), getTransactionByNonce: jest.fn(), recordMeterTransaction: jest.fn(), saveMeter: jest.fn(), updateMeterDevEui: jest.fn(), updateMeterNonce: jest.fn() })); +jest.mock('../../src/lib/sync', () => ({ getLatestTransactionNonce: jest.fn() })); +jest.mock('../../src/utils/contracts', () => ({ meterIdFromPublicKeyContractCall: jest.fn() })); +jest.mock('../../src/lib/utils', () => ({ runHook: jest.fn(), notifyHook: jest.fn(), verifyPayloadSignature: jest.fn() })); + +const key = '0x' + 'ab'.repeat(32); +let meter: any; +let records: any[]; +function uplink(nonce = 1, device = 'device-a', energy = 1000000) { + const data = Buffer.alloc(112); + data.writeUInt32BE(nonce, 0); data.writeUInt32BE(energy, 4); + Buffer.from(key.slice(2), 'hex').copy(data, 74); + return Buffer.from(JSON.stringify({ deviceInfo: { devEui: device }, data: data.toString('base64') })); +} +beforeEach(() => { + jest.resetAllMocks(); + meter = { publicKey: key, tokenId: 1, latestNonce: 0, devEui: 'device-a' }; records = []; + (verifyPayloadSignature as jest.Mock).mockReturnValue(true); + (runHook as jest.Mock).mockResolvedValue(true); + (notifyHook as jest.Mock).mockResolvedValue(undefined); + (enqueue as jest.Mock).mockResolvedValue(undefined); + (store.getMeterByPublicKey as jest.Mock).mockImplementation(() => ({ ...meter })); + (store.getMeterByDevEui as jest.Mock).mockImplementation(() => ({ ...meter })); + (getLatestTransactionNonce as jest.Mock).mockImplementation(async () => meter.latestNonce); + (store.updateMeterNonce as jest.Mock).mockImplementation((_, nonce) => { meter.latestNonce = nonce; return true; }); + (store.updateMeterDevEui as jest.Mock).mockReturnValue(true); + (store.getAllTransactionRecords as jest.Mock).mockImplementation(() => records); + (store.getTransactionByNonce as jest.Mock).mockImplementation(nonce => records.find(record => record.nonce === nonce)); + (store.recordMeterTransaction as jest.Mock).mockImplementation((_, record) => { records.push(record); meter.latestNonce = record.nonce; }); +}); + +test.each(['{', '{}', 'null', '{"deviceInfo":{}}', '{"deviceInfo":{"devEui":"device-a"}}'])('malformed uplink %s stays inside the error boundary', async input => { + await expect(handleMessage(Buffer.from(input))).resolves.toBeUndefined(); + expect(enqueue).not.toHaveBeenCalled(); + expect(notifyHook).toHaveBeenCalledWith('onMessageError', expect.any(Error)); +}); +test('dropped messages cannot release the in-flight device lock', async () => { + let resume!: (value: number) => void; + (getLatestTransactionNonce as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { resume = resolve; })); + const first = handleMessage(uplink()); + await handleMessage(uplink()); await handleMessage(uplink()); + expect(getLatestTransactionNonce).toHaveBeenCalledTimes(1); + expect(notifyHook).not.toHaveBeenCalledWith('onDeviceUnlocked', 'device-a'); + resume(0); await first; + expect(enqueue).toHaveBeenCalledTimes(1); + await handleMessage(uplink(2)); + expect(enqueue).toHaveBeenCalledTimes(2); +}); +test('different device EUIs cannot concurrently advance the same meter', async () => { + let resume!: (value: number) => void; + (getLatestTransactionNonce as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { resume = resolve; })); + const first = handleMessage(uplink()); + await handleMessage(uplink(1, 'device-b')); + expect(notifyHook).toHaveBeenCalledWith('onMessageDropped', 'meter-locked', 'device-b'); + expect(getLatestTransactionNonce).toHaveBeenCalledTimes(1); + resume(0); await first; +}); +test('acknowledgement precedes delivery and never waits for a delivery hook', async () => { + (notifyHook as jest.Mock).mockImplementation(hook => hook === 'onTransactionDistribution' ? new Promise(() => {}) : Promise.resolve()); + await handleMessage(uplink()); + expect(enqueue).toHaveBeenCalledTimes(1); + const distribution = (notifyHook as jest.Mock).mock.calls.findIndex(([name]) => name === 'onTransactionDistribution'); + expect((enqueue as jest.Mock).mock.invocationCallOrder[0]).toBeLessThan((notifyHook as jest.Mock).mock.invocationCallOrder[distribution]); + expect(records).toHaveLength(1); +}); +test('lost acknowledgements accept exact retransmissions without duplicate writes or delivery', async () => { + (enqueue as jest.Mock).mockRejectedValueOnce(new Error('gRPC unavailable')); + await handleMessage(uplink()); await handleMessage(uplink()); + expect(enqueue).toHaveBeenCalledTimes(2); + expect(store.recordMeterTransaction).toHaveBeenCalledTimes(1); + expect((notifyHook as jest.Mock).mock.calls.filter(([name]) => name === 'onTransactionDistribution')).toHaveLength(1); + await handleMessage(uplink(1, 'device-a', 2000000)); + expect(enqueue).toHaveBeenCalledTimes(2); +}); +test('bootstrap messages use the balance hook and computation failures return off', async () => { + (runHook as jest.Mock).mockRejectedValueOnce(new Error('RPC unavailable')); + await handleMessage(uplink(0)); + expect(runHook).toHaveBeenCalledWith('isOnStateCompute', 1); + expect((enqueue as jest.Mock).mock.calls[0][1][0]).toBe(0); + expect(store.recordMeterTransaction).not.toHaveBeenCalled(); +}); +test('persistence failure never acknowledges uncommitted data and releases the lock', async () => { + (store.recordMeterTransaction as jest.Mock).mockImplementationOnce(() => { throw new Error('disk full'); }); + await handleMessage(uplink()); expect(enqueue).not.toHaveBeenCalled(); + await handleMessage(uplink()); expect(enqueue).toHaveBeenCalledTimes(1); +}); diff --git a/tests/services/ssh.test.ts b/tests/services/ssh.test.ts new file mode 100644 index 0000000..9c33276 --- /dev/null +++ b/tests/services/ssh.test.ts @@ -0,0 +1,44 @@ +import http from 'http'; +import { EventEmitter } from 'events'; +import WebSocket from 'ws'; +import { Client } from 'ssh2'; +import { attachTerminal } from '../../src/services/ssh'; +jest.mock('../../src/services/server', () => ({ server: new (require('http').Server)() })); +jest.mock('ssh2', () => ({ Client: jest.fn() })); +let bridge: WebSocket.Server; +let ws: any; +let ssh: any; +beforeEach(() => { + jest.useFakeTimers(); jest.clearAllMocks(); + ssh = new EventEmitter(); ssh.connect = jest.fn(); ssh.end = jest.fn(); ssh.shell = jest.fn(); + (Client as unknown as jest.Mock).mockImplementation(() => ssh); + bridge = attachTerminal(new http.Server()); + ws = new EventEmitter(); ws.readyState = WebSocket.OPEN; ws.send = jest.fn(); + ws.close = jest.fn(() => { ws.readyState = WebSocket.CLOSED; ws.emit('close'); }); + bridge.emit('connection', ws); +}); +afterEach(() => { ws.emit('close'); bridge.close(); jest.useRealTimers(); }); +test('no fallback credentials are used and idle connections time out', () => { + expect(Client).not.toHaveBeenCalled(); + jest.advanceTimersByTime(15000); + expect(ws.close).toHaveBeenCalledWith(1008, 'SSH credentials required'); +}); +test.each(['not json', '{}', '{"type":"auth","username":"user","password":""}'])('invalid first frames %s never connect to SSH', frame => { + ws.emit('message', Buffer.from(frame)); expect(Client).not.toHaveBeenCalled(); + expect(ws.close).toHaveBeenCalledWith(1008, expect.any(String)); +}); +test('credentials arrive in the first frame and disconnecting before SSH readiness cleans up', () => { + ws.emit('message', Buffer.from(JSON.stringify({ type: 'auth', username: 'user', password: 'test-frame-only', cols: 40, rows: 10 }))); + expect(ssh.connect).toHaveBeenCalledWith(expect.objectContaining({ username: 'user', password: 'test-frame-only' })); + ws.close(); expect(ssh.end).toHaveBeenCalled(); + ssh.emit('ready'); expect(ssh.shell).not.toHaveBeenCalled(); +}); +test('terminal-ready handshake is emitted only after the shell exists', () => { + ws.emit('message', Buffer.from(JSON.stringify({ type: 'auth', username: 'user', password: 'test-frame-only' }))); + expect(ws.send).not.toHaveBeenCalled(); + const channel: any = new EventEmitter(); channel.stderr = new EventEmitter(); channel.end = jest.fn(); channel.setWindow = jest.fn(); + ssh.shell.mockImplementation((_, done) => done(null, channel)); + ssh.emit('ready'); expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: 'ready' })); + ws.emit('message', Buffer.from(JSON.stringify({ type: 'resize', cols: 9000, rows: -1 }))); + expect(channel.setWindow).toHaveBeenCalledWith(24, 80, 640, 384); +}); diff --git a/tests/store/manager.test.ts b/tests/store/manager.test.ts new file mode 100644 index 0000000..52b623b --- /dev/null +++ b/tests/store/manager.test.ts @@ -0,0 +1,100 @@ +import { randomUUID, generateKeyPairSync, sign } from 'crypto'; +import setupDatabase, { deleteDatabase, saveMeter } from '../../src/store/sqlite'; +import * as store from '../../src/m3ter/store'; +import { ingestEvent } from '../../src/m3ter/monitor'; +const app = '11111111-1111-4111-8111-111111111111', a = '0102030405060708', b = '1112131415161718'; +const originalEnv = process.env; +beforeEach(() => { process.env = { ...originalEnv, APPLICATION_ID: app }; setupDatabase('manager-test.db'); }); +afterEach(() => { deleteDatabase('manager-test.db'); process.env = originalEnv; }); +function event(devEui = a, energy = 1000000, time = Date.now(), id = randomUUID(), port = 2, length = 74, nonce = 0) { + const bytes = Buffer.alloc(length); if (length >= 74) { bytes.writeUInt32BE(nonce,0); bytes.writeUInt32BE(energy,4); bytes.writeUInt16BE(2300,72); } + const topic = `application/${app}/device/${devEui}/event/up`; + return { topic, body: { deduplicationId: id, time: new Date(time).toISOString(), deviceInfo: { devEui, applicationId: app }, fPort: port, data: bytes.toString('base64') } }; +} +const ingest = (e: ReturnType) => ingestEvent(e.topic, Buffer.from(JSON.stringify(e.body))); +test('routes multiple devices correctly and deduplicates events, not equal readings', () => { + const first = event(); expect(ingest(first)).toBe(true); expect(ingest(first)).toBe(false); + ingest(event(a)); ingest(event(b,2000000)); + expect(store.history(app,a,0,Date.now()+1000,0,50).total).toBe(2); + expect(store.latestReading(app,b).energy).toBe(2); + expect(store.history('another-application',a,0,Date.now()+1000,0,50).total).toBe(0); +}); +test('history survives reopening and timestamps/raw payload remain intact', () => { + const first = event(a,1234567,Date.now()-60000); ingest(first); setupDatabase('manager-test.db'); + const history = store.history(app,a,0,Date.now()+1000,0,50); + expect(history.rows[0]).toMatchObject({ timestamp: Date.parse(first.body.time), rawPayload:first.body.data, energy:1.234567, fPort:2 }); +}); +test('new nonce cycles count their own accumulator while repeats add zero', () => { + const time = Date.now()-10000; [1,2,.1,.3].forEach((energy,index) => ingest(event(a,energy*1000000,time+index*1000,randomUUID(),2,74,index<2?7:8))); + const result = store.history(app,a,0,Date.now(),0,50); + expect(result.summary).toMatchObject({ observedConsumption:1.3, resets:1 }); + expect(result.chart.map((row:any) => row.segment)).toEqual([0,0,1,1]); + expect(result.chart.map((row:any) => row.intervalEnergy)).toEqual([null,1,.1,.2]); +}); +test('malformed lengths, FPorts and identity mismatches do not create readings', () => { + ingest(event(a,1,Date.now(),randomUUID(),2,73)); ingest(event(a,1,Date.now(),randomUUID(),3)); + const mismatch = event(); mismatch.body.deviceInfo.devEui = b; expect(ingest(mismatch)).toBe(false); + expect(ingestEvent(event().topic,Buffer.from('{'))).toBe(false); + expect(store.latestReading(app,a)).toBeNull(); expect(store.latestReading(app,b)).toBeNull(); + expect(store.events(app,a).filter(row => row.kind === 'decode-error')).toHaveLength(2); +}); +test('delivery events correlate by device and queue ID, never by selected meter or transmission alone', () => { + const id = randomUUID(); store.insertCommand(app,a,id,{name:'Relay ON'},'fingerprint'); + const topic = `application/${app}/device/${a}/event/txack`; + const data:any = { deviceInfo:{devEui:a,applicationId:app}, queueItemId:id, time:new Date().toISOString() }; + ingestEvent(topic,Buffer.from(JSON.stringify(data))); + expect(store.getCommand(app,id).status).toBe('transmitted'); + store.commandStatus(app,a,id,'queued','Late HTTP response'); expect(store.getCommand(app,id).status).toBe('transmitted'); + data.deviceInfo.devEui = b; data.acknowledged = true; + ingestEvent(topic.replace(a,b).replace('txack','ack'),Buffer.from(JSON.stringify(data))); expect(store.getCommand(app,id).status).toBe('transmitted'); + data.deviceInfo.devEui = a; ingestEvent(topic.replace('txack','ack'),Buffer.from(JSON.stringify(data))); expect(store.getCommand(app,id).status).toBe('delivered'); +}); +test('pagination and sampled charts stay bounded and preserve reset segments', () => { + const start = Date.now()-1000000; + for (let index=0;index<901;index++) ingest(event(a,(index%450)*1000,start+index*1000,randomUUID(),2,74,Math.floor(index/450))); + const result = store.history(app,a,0,Date.now(),50,50); + expect(result.rows).toHaveLength(50); expect(result.total).toBe(901); expect(result.chart.length).toBeLessThanOrEqual(401); + expect((result.summary as any).resets).toBe(2); +}); +test('normal uplinks reuse an existing console key without requiring another bootstrap', () => { + const keys = generateKeyPairSync('ed25519'), key = keys.publicKey.export({format:'der',type:'spki'}).subarray(-32).toString('hex'); + saveMeter({devEui:a,publicKey:'0x'+key,tokenId:42,latestNonce:0}); + const input = event(), bytes = Buffer.from(input.body.data,'base64'); + sign(null,bytes.subarray(0,8),keys.privateKey).copy(bytes,8); input.body.data = bytes.toString('base64'); ingest(input); + expect(store.latestReading(app,a)).toMatchObject({verification:'verified',publicKey:null}); + expect(store.deviceState(app,a).publicKey).toBe(key); +}); +test('location comes from valid device events and older locations cannot overwrite newer ones', () => { + const publish = (latitude:number, timestamp:number) => ingestEvent(`application/${app}/device/${a}/event/location`,Buffer.from(JSON.stringify({ + time:new Date(timestamp).toISOString(),deduplicationId:randomUUID(),deviceInfo:{devEui:a,applicationId:app},location:{latitude,longitude:10}, + }))); + publish(91,Date.now()); expect(store.deviceState(app,a).metadata.location).toBeUndefined(); + publish(51,Date.now()); publish(21,Date.now()-10000); + expect(store.deviceState(app,a).metadata.location).toEqual({latitude:51,longitude:10}); +}); +test('inactivity is an observation and late historical events do not make a meter active', () => { + ingest(event(a,1,Date.now()-600000)); expect(store.deviceState(app,a).activity).toBe('inactive'); + ingest(event()); expect(store.deviceState(app,a).activity).toBe('active'); + store.markInactive(app,-1); expect(store.deviceState(app,a).activity).toBe('inactive'); + expect(store.events(app,a).find(row=>row.kind==='inactive').source).toBe('console observation'); +}); + +test('acknowledgment cycles, high-water marks and range boundaries prevent double counting', () => { + const time = Date.now()-20000; + const reports = [[10,5],[10,6],[10,6],[11,8],[10,9],[11,7],[11,8],[11,9]]; + reports.forEach(([nonce,energy],index)=>ingest(event(a,energy*1e6,time+index*1000,randomUUID(),2,74,nonce))); + const full = store.history(app,a,0,Date.now(),0,50); + expect(full.chart.map((row:any)=>row.intervalEnergy)).toEqual([null,1,0,8,null,0,0,1]); + expect(full.summary).toMatchObject({observedConsumption:10,resets:1,repeatedReports:2,uncertainReports:2}); + const ranged = store.history(app,a,time+2000,Date.now(),0,2); + expect(ranged.summary.observedConsumption).toBe(9); // baseline comes from before the range + expect(ranged.rows).toHaveLength(2); + // A delayed report sorts into its source time and cannot create duplicate energy. + ingest(event(a,5500000,time+500,randomUUID(),2,74,10)); + expect(store.history(app,a,0,Date.now(),0,50).summary.observedConsumption).toBe(10); +}); +test('unexplained same-nonce decreases and nonce rollback are not fresh consumption', () => { + const time=Date.now()-10000; + [[8,2],[8,1],[8,2],[0,3],[1,4]].forEach(([nonce,energy],index)=>ingest(event(a,energy*1e6,time+index*1000,randomUUID(),2,74,nonce))); + expect(store.history(app,a,0,Date.now(),0,50).summary).toMatchObject({observedConsumption:0,resets:0,uncertainReports:3}); +}); diff --git a/tests/store/sqlite.test.ts b/tests/store/sqlite.test.ts index f41a05b..0fd7aa2 100644 --- a/tests/store/sqlite.test.ts +++ b/tests/store/sqlite.test.ts @@ -165,3 +165,13 @@ it("should prune transactions before a given nonce for a specific meter", () => expect(transactions).toHaveLength(5); expect(transactions.every((tx) => tx.nonce >= nonceToPrune)).toBe(true); }); + +it('commits transaction and nonce together, rolling back when the nonce is stale', () => { + const { recordMeterTransaction } = require('../../src/store/sqlite'); + saveMeter({ publicKey: 'atomic-meter', tokenId: 7, latestNonce: 0, devEui: 'dev' }); + recordMeterTransaction('atomic-meter', { identifier: 7, nonce: 1, receivedAt: 1, raw: '01' }); + expect(getMeterByPublicKey('atomic-meter')?.latestNonce).toBe(1); + expect(() => recordMeterTransaction('atomic-meter', { identifier: 7, nonce: 3, receivedAt: 2, raw: '03' })).toThrow(); + expect(getAllTransactionRecords().map(tx => tx.nonce)).toEqual([1]); + expect(getMeterByPublicKey('atomic-meter')?.latestNonce).toBe(1); +}); diff --git a/tests/ui/auth.spec.cjs b/tests/ui/auth.spec.cjs new file mode 100644 index 0000000..ae3b4aa --- /dev/null +++ b/tests/ui/auth.spec.cjs @@ -0,0 +1,51 @@ +const { test, expect } = require('@playwright/test'); +const base = 'http://127.0.0.1:4174'; +const credentials = { username: 'test-console', password: 'test-only-browser-password' }; + +test('production HTTP routes and assets require authentication; foreign-origin mutations are rejected', async ({ browser, request }) => { + for (const route of ['/', '/js/desktop.js', '/api/m3ter-manager/config', '/api/m3ter-manager/devices', '/api/actions/streamr/publish-now', '/delete-meter']) { + const response = await request.fetch(base + route, { method: route.includes('actions') ? 'POST' : route.includes('delete') ? 'DELETE' : 'GET' }); + expect(response.status()).toBe(401); + } + const context = await browser.newContext({ httpCredentials: credentials }); + expect((await context.request.get(base + '/js/desktop.js')).status()).toBe(200); + expect((await context.request.post(base + '/api/actions/streamr/publish-now', { headers: { origin: 'https://foreign.example' } })).status()).toBe(403); + expect((await context.request.delete(base + '/delete-meter', { headers: { origin: base } })).status()).toBe(400); + await context.close(); +}); + +test('authenticated browser can upgrade the terminal without URL credentials and legacy query URLs are rejected', async ({ browser }) => { + const context = await browser.newContext({ httpCredentials: credentials }); + const page = await context.newPage(); + await page.route(/https:\/\//, route => route.abort()); + await page.goto(base); + const valid = await page.evaluate(() => new Promise(resolve => { + let opened = false; + const ws = new WebSocket('ws://127.0.0.1:4174/terminal'); + ws.onopen = () => { opened = true; ws.send('{}'); }; // Invalid auth frame: never contacts SSH. + ws.onclose = event => resolve({ opened, code: event.code }); + })); + expect(valid).toEqual({ opened: true, code: 1008 }); + const legacy = await page.evaluate(() => new Promise(resolve => { + let opened = false; + const ws = new WebSocket('ws://127.0.0.1:4174/?username=user&password=fixture'); + ws.onopen = () => { opened = true; ws.close(); }; + ws.onclose = () => resolve(opened); + })); + expect(legacy).toBe(false); + await context.close(); +}); + +test('real-time upgrades reject missing credentials, missing origins, and foreign origins', async () => { + const WebSocket = require('ws'); + const authorization = 'Basic ' + Buffer.from(credentials.username + ':' + credentials.password).toString('base64'); + for (const path of ['/terminal', '/m3ter-manager/live']) for (const headers of [{ origin: base }, { authorization }, { authorization, origin: 'https://foreign.example' }]) { + const status = await new Promise(resolve => { + const ws = new WebSocket('ws://127.0.0.1:4174' + path, { headers }); + ws.on('unexpected-response', (request, response) => { response.resume(); request.destroy(); resolve(response.statusCode); }); + ws.on('error', () => resolve(0)); + ws.on('open', () => { ws.close(); resolve(101); }); + }); + expect(status).toBe(403); + } +}); diff --git a/tests/ui/chirpstack-upstream.cjs b/tests/ui/chirpstack-upstream.cjs new file mode 100644 index 0000000..8683e7b --- /dev/null +++ b/tests/ui/chirpstack-upstream.cjs @@ -0,0 +1,47 @@ +// A root-hosted, hash-routed UI with the same transport/storage behavior as v4. +const http = require('node:http'); +module.exports = http.createServer((req, res) => { + if (req.url === '/') { + res.setHeader('Content-Type', 'text/html'); + res.setHeader('X-Frame-Options', 'DENY'); + res.end('

ChirpStack test server

'); + } else if (req.url === '/assets/main.js') { + res.setHeader('Content-Type', 'application/javascript'); + res.end(`import { ready } from '/assets/chunk.js'; + document.body.dataset.ready = ready; + const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/' + 'assets/lazy.css'; document.head.appendChild(css); + const image = new Image(); image.alt = 'Network logo'; image.src = '/logo.svg'; document.body.appendChild(image); + location.hash = '/login'; + document.getElementById('login').onclick = () => { + localStorage.setItem('token', 'fixture-token'); + const xhr = new XMLHttpRequest(); + xhr.open('POST', '/api.InternalService/Login'); + xhr.setRequestHeader('authorization', 'Bearer fixture-token'); + xhr.setRequestHeader('content-type', 'application/grpc-web+proto'); + xhr.onload = () => document.getElementById('result').textContent = xhr.responseText; + xhr.send(new Uint8Array([0, 255, 13, 10])); + }; + document.getElementById('logout').onclick = () => { localStorage.clear(); document.getElementById('result').textContent = 'Signed out'; }; + `); + } else if (req.url === '/assets/lazy.css') { + res.setHeader('Content-Type', 'text/css'); res.end('h1 { color: rgb(1, 2, 3); }'); + } else if (req.url === '/logo.svg') { + res.setHeader('Content-Type', 'image/svg+xml'); res.end(''); + } else if (req.url === '/assets/chunk.js') { + res.setHeader('Content-Type', 'application/javascript'); res.end('export const ready = "yes";'); + } else if (req.url.startsWith('/api.InternalService/')) { + const chunks = []; + req.on('data', chunk => chunks.push(chunk)); + req.on('end', () => { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ authorization: req.headers.authorization || null, cookie: req.headers.cookie || null, bytes: [...Buffer.concat(chunks)], url: req.url })); + }); + } else if (req.url === '/events') { + res.setHeader('Content-Type', 'application/grpc-web-text'); + res.write('first'); setTimeout(() => res.end('last'), 200); + } else if (req.url === '/redirect') { + res.writeHead(302, { Location: '/#/tenants' }); res.end(); + } else if (req.url === '/unavailable') { + req.socket.destroy(); + } else { res.writeHead(404); res.end('Unknown fixture route'); } +}); diff --git a/tests/ui/chirpstack.spec.cjs b/tests/ui/chirpstack.spec.cjs new file mode 100644 index 0000000..74040c8 --- /dev/null +++ b/tests/ui/chirpstack.spec.cjs @@ -0,0 +1,75 @@ +const { test, expect } = require('@playwright/test'); +const base = 'http://127.0.0.1:4174'; +const credentials = { username: 'test-console', password: 'test-only-browser-password' }; + +test('ChirpStack launches inside the desktop, proxies assets and Bearer requests, and isolates logout', async ({ browser }) => { + const context = await browser.newContext({ httpCredentials: credentials }); + const page = await context.newPage(); + await page.route(/https:\/\//, route => route.abort()); + await page.goto(base); + await expect(page.locator('#chirpstack-frame')).not.toHaveAttribute('src', /./); + await page.locator('#chirpstack-icon').dblclick(); + const frame = page.frameLocator('#chirpstack-frame'); + await expect(frame.locator('body')).toHaveAttribute('data-ready', 'yes'); + await expect(frame.getByAltText('Network logo')).toHaveAttribute('src', base + '/chirpstack/logo.svg'); + await expect(frame.locator('h1')).toHaveCSS('color', 'rgb(1, 2, 3)'); + await frame.locator('#draft').fill('Keep this network draft'); + await frame.getByRole('button', { name: 'Sign in' }).click(); + await expect(frame.locator('#result')).toHaveText(JSON.stringify({ authorization: 'Bearer fixture-token', cookie: null, bytes: [0,255,13,10], url: '/api.InternalService/Login' })); + const appFrame = page.frames().find(f => f.url().includes('/chirpstack/')); + expect(await appFrame.evaluate(() => localStorage.getItem('token'))).toBe('fixture-token'); + await page.evaluate(() => Desktop.launch('settings')); + await page.locator('[data-theme-choice="linux"]').click(); + await page.evaluate(() => Desktop.launch('chirpstack')); + const desktopPreferences = await page.evaluate(() => localStorage.getItem('m3tering.desktop.v1')); + await expect(frame.locator('#draft')).toHaveValue('Keep this network draft'); + await frame.getByRole('button', { name: 'Sign out' }).click(); + expect(await page.evaluate(() => localStorage.getItem('m3tering.desktop.v1'))).toBe(desktopPreferences); + expect(await appFrame.evaluate(() => localStorage.getItem('token'))).toBeNull(); + await page.setViewportSize({ width: 390, height: 844 }); + const bounds = await page.locator('#chirpstack').boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); expect(bounds.x + bounds.width).toBeLessThanOrEqual(390); + await page.getByRole('button', { name: 'Reload ChirpStack', exact: true }).click(); + await expect(frame.locator('#draft')).toHaveValue(''); + const cookies = await context.cookies(base + '/chirpstack/'); + expect(cookies.find(cookie => cookie.name === 'console_chirpstack')).toMatchObject({ httpOnly: true, sameSite: 'Strict', path: '/chirpstack' }); + await context.close(); +}); + +test('proxy scopes authorization, preserves binary transport and redirects, and reports unavailable upstream', async ({ playwright }) => { + const anonymous = await playwright.request.newContext(); + expect((await anonymous.get(base + '/chirpstack/')).status()).toBe(401); + const auth = await playwright.request.newContext({ httpCredentials: credentials }); + const html = await auth.get(base + '/chirpstack/'); + expect(html.status()).toBe(200); + expect(html.headers()['x-frame-options']).toBe('SAMEORIGIN'); + const cookie = html.headers()['set-cookie'].split(';')[0]; + const headers = { cookie, authorization: 'Bearer fixture-token', origin: base, 'content-type': 'application/grpc-web+proto' }; + const binary = await anonymous.post(base + '/chirpstack/api.InternalService/Test?limit=2', { headers, data: Buffer.from([0,255,0,10]) }); + expect(await binary.json()).toEqual({ authorization: 'Bearer fixture-token', cookie: null, bytes: [0,255,0,10], url: '/api.InternalService/Test?limit=2' }); + expect((await anonymous.post(base + '/chirpstack/api.InternalService/Test', { headers: { ...headers, origin: 'https://foreign.example' } })).status()).toBe(403); + expect((await anonymous.get(base + '/', { headers: { cookie } })).status()).toBe(401); + expect((await anonymous.get(base + '/chirpstack/', { headers: { cookie: cookie + 'broken' } })).status()).toBe(401); + const noLeak = await auth.post(base + '/chirpstack/api.InternalService/Test', { headers: { origin: base } }); + expect((await noLeak.json()).authorization).toBeNull(); + const redirect = await auth.get(base + '/chirpstack/redirect', { maxRedirects: 0 }); + expect(redirect.headers().location).toBe('/chirpstack/#/tenants'); + const unavailable = await auth.get(base + '/chirpstack/unavailable'); + expect(unavailable.status()).toBe(502); expect(await unavailable.text()).toContain('Try again'); + await auth.dispose(); await anonymous.dispose(); +}); + +test('embedded fetch receives streaming responses without buffering the stream', async ({ browser }) => { + const context = await browser.newContext({ httpCredentials: credentials }); + const page = await context.newPage(); + await page.goto(base + '/chirpstack/'); + const chunks = await page.evaluate(async () => { + const response = await fetch('/events'); + const reader = response.body.getReader(); + const chunks = []; + for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(new TextDecoder().decode(value)); } + return chunks; + }); + expect(chunks).toEqual(['first', 'last']); + await context.close(); +}); diff --git a/tests/ui/desktop.spec.cjs b/tests/ui/desktop.spec.cjs new file mode 100644 index 0000000..ba61cd2 --- /dev/null +++ b/tests/ui/desktop.spec.cjs @@ -0,0 +1,297 @@ +const { test, expect } = require('@playwright/test'); +const key = 'm3tering.desktop.v1'; +const themes = ['retro', 'macos', 'linux', 'windows']; +const sizes = [[1440, 900], [1024, 768], [768, 1024], [390, 844], [320, 568], [844, 390]]; + +test.beforeEach(async ({ page }) => { + // Browser QA is deterministic/offline; third-party fonts, frame content, and + // terminal distribution are external integrations, not part of the fixture. + if (!process.env.UI_EXTERNAL_ASSETS) await page.route(/https:\/\//, route => route.abort()); +}); +async function openSettings(page) { + await page.evaluate(() => Desktop.launch('settings')); + await expect(page.locator('#settings')).toBeVisible(); +} +async function desktopSettings(page) { + await openSettings(page); + await page.locator('[data-settings-tab="desktop"]').click(); +} +async function cleanGrid(page) { + const result = await page.locator('.desktop-icon').evaluateAll(icons => { + const parent = document.getElementById('desktop-icons').getBoundingClientRect(); + const rects = icons.map(el => el.getBoundingClientRect()); + return { + within: rects.every(r => r.left >= parent.left - 1 && r.right <= parent.right + 1 && r.top >= parent.top - 1 && r.bottom <= parent.bottom + 1), + overlaps: rects.some((a, i) => rects.slice(i + 1).some(b => a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top)), + }; + }); + expect(result).toEqual({ within: true, overlaps: false }); +} + +test('four themes across desktop, tablet, phone, and landscape keep settings and windows inside viewport', async ({ page }) => { + const errors = []; page.on('pageerror', e => errors.push(e.message)); + await page.goto('/'); + for (const [width, height] of sizes) { + await page.setViewportSize({ width, height }); + await openSettings(page); + for (const theme of themes) { + await page.locator(`[data-theme-choice="${theme}"]`).click(); + await expect(page.locator('html')).toHaveAttribute('data-theme', theme); + await expect(page.locator(`[data-theme-choice="${theme}"]`)).toHaveAttribute('aria-pressed', 'true'); + await cleanGrid(page); + const bounds = await page.locator('#settings').boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); expect(bounds.y).toBeGreaterThanOrEqual(0); + expect(bounds.x + bounds.width).toBeLessThanOrEqual(width + 1); + expect(bounds.y + bounds.height).toBeLessThanOrEqual(height + 1); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + const settingsOverflow = await page.locator('.settings-content').evaluate(el => el.scrollWidth > el.clientWidth + 1); + expect(settingsOverflow).toBe(false); + } + } + expect(errors).toEqual([]); +}); + +test('switching theme retains application DOM, draft values, open windows, and saved preferences', async ({ page }) => { + await page.goto('/'); + await page.evaluate(() => Desktop.launch('streamr')); + await page.getByLabel('Extension draft').fill('Keep this draft'); + await page.evaluate(() => { window.originalExtension = document.getElementById('streamr'); }); + await openSettings(page); + await page.locator('[data-theme-choice="macos"]').click(); + await page.locator('button[data-background="dusk"]').click(); + await page.locator('[data-settings-tab="general"]').click(); + await page.locator('#reduce-motion').check(); + await page.locator('#interface-sounds').check(); + await page.locator('#clock-24').uncheck(); + await page.locator('[data-settings-tab="desktop"]').click(); + await page.locator('#icon-size').selectOption('large'); + expect(await page.evaluate(() => window.originalExtension === document.getElementById('streamr'))).toBe(true); + await expect(page.getByLabel('Extension draft')).toHaveValue('Keep this draft'); + await page.reload(); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'macos'); + expect(await page.evaluate(() => Desktop.getPreferences())).toMatchObject({ theme: 'macos', background: 'dusk', reduceMotion: true, sounds: true, clock24: false, iconSize: 'large' }); +}); + +test('manual mouse drag swaps occupied cells, suppresses launching, persists, and resets with confirmation', async ({ page }) => { + await page.goto('/'); + await desktopSettings(page); + await page.locator('input[value="manual"]').check(); + await page.locator('#settings .window-close').click(); + const meter = await page.locator('#m3ters-icon').boundingBox(); + const terminal = await page.locator('#terminal-icon').boundingBox(); + await page.mouse.move(meter.x + meter.width / 2, meter.y + meter.height / 2); + await page.mouse.down(); + await page.mouse.move(terminal.x + terminal.width / 2, terminal.y + terminal.height / 2, { steps: 12 }); + await expect(page.locator('#drop-target')).toBeVisible(); + await page.mouse.up(); + await expect(page.locator('#m3ters')).toBeHidden(); + await expect(page.locator('#drop-target')).toBeHidden(); + await cleanGrid(page); + const saved = await page.evaluate(() => Desktop.getPreferences().positions); + expect(saved.m3ters).toEqual({ col: 0, row: 1 }); + expect(saved.terminal).toEqual({ col: 0, row: 0 }); + await page.reload(); + expect(await page.evaluate(() => Desktop.getPreferences().positions)).toEqual(saved); + await desktopSettings(page); + await page.locator('#reset-layout').click(); + await expect(page.locator('#reset-dialog')).toBeVisible(); + await page.getByRole('button', { name: 'Keep my layout' }).click(); + expect(await page.evaluate(() => Desktop.getPreferences().mode)).toBe('manual'); + await page.locator('#reset-layout').click(); + await page.getByRole('button', { name: 'Reset layout', exact: true }).last().click(); + expect(await page.evaluate(() => Desktop.getPreferences())).toMatchObject({ mode: 'auto', positions: {} }); + await page.locator('input[value="manual"]').check(); + await page.locator('#reset-layout').click(); + await page.keyboard.press('Escape'); + await expect(page.locator('#reset-dialog')).toBeHidden(); + expect(await page.evaluate(() => Desktop.getPreferences().mode)).toBe('manual'); +}); + +test('keyboard movement, theme switching, and viewport reflow preserve the custom layout', async ({ page }) => { + await page.goto('/'); + await desktopSettings(page); await page.locator('input[value="manual"]').check(); + await page.locator('#settings .window-close').click(); + await page.locator('#m3ters-icon').focus(); + await page.keyboard.press('Alt+ArrowRight'); + await expect(page.locator('#desktop-announcement')).toContainText('column 2'); + const saved = await page.evaluate(() => Desktop.getPreferences().positions); + await openSettings(page); + await page.locator('[data-settings-tab="appearance"]').click(); + await page.locator('[data-theme-choice="linux"]').click(); + expect(await page.evaluate(() => Desktop.getPreferences().positions)).toEqual(saved); + await page.setViewportSize({ width: 320, height: 568 }); + await cleanGrid(page); + expect(await page.evaluate(() => Desktop.getPreferences().positions)).toEqual(saved); + await page.setViewportSize({ width: 1440, height: 900 }); + await cleanGrid(page); + expect(await page.evaluate(() => Desktop.getPreferences().positions)).toEqual(saved); +}); + +test('launcher search, extension actions, Paint routing, minimize, restore, close, and window resizing work', async ({ page }) => { + await page.goto('/'); + await page.locator('.taskbar [data-launcher-toggle]').click(); + await page.getByRole('searchbox').fill('streamr'); + await expect(page.locator('.launcher-app:visible')).toHaveCount(1); + await page.keyboard.press('Enter'); + await expect(page.locator('#streamr')).toBeVisible(); + const request = page.waitForRequest('**/api/actions/streamr/publish-now'); + await page.getByRole('button', { name: 'Publish Now' }).click(); + expect((await request).method()).toBe('POST'); + await expect(page.locator('#notification-area')).toContainText('Published 2'); + await page.locator('#streamr .window-minimize').click(); + await expect(page.locator('#streamr')).toBeHidden(); + await page.locator('.dock-app[data-app-id="streamr"]').click(); + await expect(page.locator('#streamr')).toBeVisible(); + await page.locator('#streamr .window-maximize').click(); + await expect(page.locator('#streamr')).toHaveClass(/is-maximized/); + await page.locator('#streamr .window-maximize').click(); + const before = await page.locator('#streamr').boundingBox(); + await page.locator('#streamr .window-resize').focus(); await page.keyboard.press('ArrowLeft'); + expect((await page.locator('#streamr').boundingBox()).width).toBeLessThan(before.width); + await page.locator('#show-desktop').click(); await expect(page.locator('#streamr')).toBeHidden(); + await page.locator('#show-desktop').click(); await expect(page.locator('#streamr')).toBeVisible(); + await page.locator('#streamr .window-close').click(); + await page.locator('#paint-icon').click(); + await expect(page.locator('#browser iframe')).toHaveAttribute('src', 'https://basepaint.xyz/'); + await page.locator('#browser .window-close').click(); + await expect(page.locator('#paint-icon')).toBeFocused(); +}); + +test('many applications, stale saved IDs, and corrupt storage recover without overlapping', async ({ page }) => { + await page.addInitScript(key => localStorage.setItem(key, '{invalid'), key); + await page.goto('/?apps=60'); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'retro'); + await page.setViewportSize({ width: 320, height: 568 }); + await cleanGrid(page); + expect(await page.locator('#desktop-scroll').evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true); + await page.evaluate(key => localStorage.setItem(key, JSON.stringify({ version: 1, mode: 'manual', positions: { removed: { col: 0, row: 0 }, streamr: { col: 999, row: 999 } } })), key); + // The init script intentionally resets corrupt storage on reload; use a new page navigation + // without reloading to inspect stale-ID behavior through the storage event instead. + await page.evaluate(key => dispatchEvent(new StorageEvent('storage', { key })), key); + await cleanGrid(page); +}); + +test('blocked storage remains usable and reports persistence limits', async ({ page }) => { + await page.addInitScript(() => { + Storage.prototype.getItem = () => { throw new Error('blocked'); }; + Storage.prototype.setItem = () => { throw new Error('blocked'); }; + }); + await page.goto('/'); await openSettings(page); + await page.locator('[data-theme-choice="windows"]').click(); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'windows'); + await expect(page.locator('#notification-area')).toContainText('Browser storage is unavailable'); +}); + +test('touch hold moves an icon without launching; mobile shows one active window and keeps dock navigation', async ({ browser }) => { + const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }); + const page = await context.newPage(); + await page.route(/https:\/\//, route => route.abort()); + await page.goto('http://127.0.0.1:4173/'); + await desktopSettings(page); await page.locator('input[value="manual"]').check(); + await page.locator('#settings .window-close').click(); + const a = await page.locator('#m3ters-icon').boundingBox(); + const b = await page.locator('#terminal-icon').boundingBox(); + const session = await context.newCDPSession(page); + const point = { x: a.x + a.width / 2, y: a.y + a.height / 2 }; + await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }); + await page.waitForTimeout(400); + await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: b.x + b.width / 2, y: b.y + b.height / 2 }] }); + await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await expect(page.locator('#m3ters')).toBeHidden(); + expect(await page.evaluate(() => Desktop.getPreferences().positions.m3ters)).toEqual({ col: 1, row: 0 }); + await cleanGrid(page); + await page.evaluate(() => { Desktop.launch('m3ters'); Desktop.launch('settings'); }); + await expect(page.locator('#settings')).toBeVisible(); + await expect(page.locator('#m3ters')).not.toBeVisible(); + await page.locator('.dock-app[data-app-id="m3ters"]').click(); + await expect(page.locator('#m3ters')).toBeVisible(); + await expect(page.locator('#settings')).not.toBeVisible(); + await page.locator('#show-desktop').click(); + await expect(page.locator('#desktop-icons')).toBeVisible(); + await context.close(); +}); + +test('terminal resizes on phones, preserves the session on theme changes, and does not duplicate input after reconnecting', async ({ page }) => { + await page.route('https://unpkg.com/xterm@5.3.0/lib/xterm.js', route => route.fulfill({ + contentType: 'application/javascript', + body: `window.testTerminals = []; window.testSockets = []; + window.Terminal = class { + constructor(options) { this.options = options; this.cols = 80; this.rows = 24; this.inputs = []; this.resizes = []; testTerminals.push(this); } + open() {} write() {} focus() {} reset() {} dispose() { this.disposed = true; } + onData(fn) { this.inputs.push(fn); return { dispose: () => this.inputs.splice(this.inputs.indexOf(fn), 1) }; } + onResize(fn) { this.resizes.push(fn); return { dispose: () => this.resizes.splice(this.resizes.indexOf(fn), 1) }; } + resize(cols, rows) { this.cols = cols; this.rows = rows; this.resizes.forEach(fn => fn({cols, rows})); } + }; + window.WebSocket = class { + static OPEN = 1; static CONNECTING = 0; + constructor() { this.readyState = 0; this.sent = []; testSockets.push(this); setTimeout(() => { this.readyState = 1; this.onopen?.(); }, 0); } + send(data) { this.sent.push(data); if (data.startsWith('{') && JSON.parse(data).type === 'auth') setTimeout(() => this.onmessage?.({ data: JSON.stringify({ type: 'ready' }) }), 0); } + close() { this.readyState = 3; this.onclose?.(); } + };`, + })); + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto('/'); + await page.evaluate(() => Desktop.launch('terminal')); + await page.locator('#password').fill('fixture-only'); + await page.getByRole('button', { name: /Connect to terminal/ }).click(); + await expect(page.locator('#terminal-container')).toBeVisible(); + expect(await page.evaluate(() => testTerminals[0].cols)).toBeLessThan(80); + await openSettings(page); await page.locator('[data-theme-choice="linux"]').click(); + await page.locator('.dock-app[data-app-id="terminal"]').click(); + expect(await page.evaluate(() => testSockets.length)).toBe(1); + await expect(page.locator('#terminal-container')).toBeVisible(); + await page.getByRole('button', { name: 'Disconnect', exact: true }).click(); + await page.getByRole('button', { name: /Connect to terminal/ }).click(); + await expect(page.locator('#terminal-container')).toBeVisible(); + expect(await page.evaluate(() => testTerminals[0].inputs.length)).toBe(1); + const inputs = await page.evaluate(() => { + testTerminals[0].inputs.forEach(fn => fn('a')); + return testSockets[1].sent.filter(value => value === 'a').length; + }); + expect(inputs).toBe(1); + await page.locator('#terminal .window-close').click(); + expect(await page.evaluate(() => testTerminals[0].disposed)).toBe(true); + expect(await page.evaluate(() => testTerminals[0].inputs.length)).toBe(0); +}); + +test('desktop visual references and large/small icon layouts remain usable', async ({ page }, testInfo) => { + await page.goto('/'); + for (const theme of themes) { + await openSettings(page); + await page.locator('[data-theme-choice="' + theme + '"]').click(); + await page.screenshot({ path: testInfo.outputPath(theme + '-desktop.png'), animations: 'disabled' }); + await page.setViewportSize({ width: 390, height: 844 }); + await page.screenshot({ path: testInfo.outputPath(theme + '-mobile.png'), animations: 'disabled' }); + await page.locator('[data-settings-tab="desktop"]').click(); + for (const size of ['large', 'small']) { + await page.locator('#icon-size').selectOption(size); + await cleanGrid(page); + } + await page.locator('#icon-size').selectOption('medium'); + await page.locator('[data-settings-tab="appearance"]').click(); + await page.setViewportSize({ width: 1440, height: 900 }); + } +}); + +test('icon selection clears outside the desktop and applications retain independent color modes', async ({page})=>{ + await page.goto('/');await page.locator('[data-app-id="m3ter-manager"].desktop-icon').click(); + await page.locator('#m3ter-manager .window-titlebar').click();await expect(page.locator('.desktop-icon.selected')).toHaveCount(0); + await page.locator('#m3ter-manager .window-color-mode').selectOption('dark'); + await openSettings(page);await page.locator('#settings .window-color-mode').selectOption('light'); + await page.locator('[data-theme-choice="linux"]').click(); + await expect(page.locator('#m3ter-manager')).toHaveAttribute('data-color-mode','dark');await expect(page.locator('#settings')).toHaveAttribute('data-color-mode','light'); + expect(await page.locator('#settings').evaluate(el=>getComputedStyle(el).colorScheme)).toBe('light'); + expect(await page.locator('#m3ter-manager').evaluate(el=>getComputedStyle(el).colorScheme)).toBe('dark'); + await page.reload();await page.evaluate(()=>{Desktop.launch('m3ter-manager');Desktop.launch('settings');}); + await expect(page.locator('#m3ter-manager')).toHaveAttribute('data-color-mode','dark');await expect(page.locator('#settings')).toHaveAttribute('data-color-mode','light'); + await page.locator('#settings .window-color-mode').selectOption('theme'); + expect(await page.locator('#settings').evaluate(el=>getComputedStyle(el).colorScheme)).toBe('dark'); + for(const width of [320,390,768,1440]) { + await page.setViewportSize({width,height:844}); + for (const theme of themes) { + await page.locator(`[data-theme-choice="${theme}"]`).click(); + expect(await page.locator('#settings .window-titlebar').evaluate(el=>el.scrollWidth<=el.clientWidth)).toBe(true); + expect(await page.locator('#settings .window-color-mode').evaluate(el=>{const r=el.getBoundingClientRect();return document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)===el;})).toBe(true); + } + } +}); diff --git a/tests/ui/desktop.test.js b/tests/ui/desktop.test.js new file mode 100644 index 0000000..d28cdd1 --- /dev/null +++ b/tests/ui/desktop.test.js @@ -0,0 +1,60 @@ +const P = require('../../src/public/js/desktop-preferences'); +const L = require('../../src/public/js/desktop-layout'); + +describe('desktop preferences', () => { + test('invalid, outdated, and partial preferences have safe defaults', () => { + expect(P.normalize(null).theme).toBe('retro'); + expect(P.normalize({ version: 99, theme: 'linux' }).theme).toBe('retro'); + expect(P.normalize({ theme: '__proto__', iconSize: 'huge', mode: 'bad' })).toMatchObject({ theme: 'retro', mode: 'auto', iconSize: 'medium' }); + const value = P.normalize({ theme: 'linux', positions: { good: { col: 2, row: 3 }, bad: { col: -1, row: 2 }, invalid: null } }); + expect(value.theme).toBe('linux'); + expect(Object.keys(value.positions)).toEqual(['good']); + }); + test('round trips all preferences and tolerates unavailable storage', () => { + let data; + const storage = { getItem: () => data, setItem: (_, value) => { data = value; } }; + const prefs = P.normalize({ theme: 'windows', mode: 'manual', background: 'dusk', iconSize: 'large', sounds: true, reduceMotion: true, clock24: false, positions: { m3ters: { col: 2, row: 1 } } }); + expect(P.save(prefs, storage)).toBe(true); + expect(P.load(storage)).toEqual(prefs); + expect(P.load({ getItem: () => '{bad json' }).theme).toBe('retro'); + expect(P.save(prefs, { setItem: () => { throw new Error('quota'); } })).toBe(false); + }); +}); +describe('desktop placement', () => { + test.each(['row', 'column'])('bounds and uniqueness hold in %s flow for many sizes and app counts', flow => { + for (const width of [260, 320, 390, 768, 1440, 2560]) { + for (const height of [180, 500, 900]) { + for (const count of [0, 1, 6, 30, 200]) { + const ids = Array.from({ length: count }, (_, i) => `app-${i}`); + const grid = L.dimensions(width, height, 'medium', count); + const result = L.arrange(ids, grid, {}, flow); + const occupied = Object.values(result).map(p => `${p.col},${p.row}`); + expect(new Set(occupied).size).toBe(count); + Object.values(result).forEach(p => { + expect(p.col).toBeGreaterThanOrEqual(0); expect(p.col).toBeLessThan(grid.cols); + expect(p.row).toBeGreaterThanOrEqual(0); expect(p.row).toBeLessThan(grid.rows); + }); + } + } + } + }); + test('reserves stable IDs, handles new and removed apps, and leaves saved wide-screen positions intact', () => { + const grid = L.dimensions(320, 500, 'medium', 4); + const saved = { second: { col: 1, row: 2 }, first: { col: 12, row: 30 }, removed: { col: 0, row: 0 } }; + const before = JSON.stringify(saved); + const result = L.arrange(['new', 'first', 'second', 'another'], grid, saved); + expect(result.second).toEqual({ col: 1, row: 2 }); + expect(result.removed).toBeUndefined(); + expect(new Set(Object.values(result).map(p => `${p.col},${p.row}`)).size).toBe(4); + expect(JSON.stringify(saved)).toBe(before); + }); + test('moving into an occupied cell swaps icons without overlap or mutation', () => { + const grid = L.dimensions(400, 500, 'medium', 3); + const positions = { a: { col: 0, row: 0 }, b: { col: 1, row: 0 }, c: { col: 2, row: 0 } }; + const moved = L.move(positions, 'a', { col: 1, row: 0 }, grid); + expect(moved.a).toEqual({ col: 1, row: 0 }); + expect(moved.b).toEqual({ col: 0, row: 0 }); + expect(positions.a).toEqual({ col: 0, row: 0 }); + expect(L.move(moved, 'a', { col: 999, row: -1 }, grid).a).toEqual({ col: grid.cols - 1, row: 0 }); + }); +}); diff --git a/tests/ui/manager-auth.spec.cjs b/tests/ui/manager-auth.spec.cjs new file mode 100644 index 0000000..53474b1 --- /dev/null +++ b/tests/ui/manager-auth.spec.cjs @@ -0,0 +1,25 @@ +const {test,expect}=require('@playwright/test'); +const base='http://127.0.0.1:4174',api='/api/m3ter-manager'; +test.use({baseURL:base,httpCredentials:{username:'test-console',password:'test-only-browser-password'}}); +test('manager login protects data and live stream; logout revokes every open app session',async({page,context})=>{ + await page.route(/https:\/\//,route=>route.abort()); + for(const path of ['/config','/devices','/devices/0102030405060708/history','/devices/0102030405060708/queue']) expect((await context.request.get(api+path)).status()).toBe(401); + expect((await context.request.post(api+'/commands/preview',{data:{commandId:'relay-on'}})).status()).toBe(401); + await page.goto('/'); await page.evaluate(()=>Desktop.launch('m3ter-manager')); + await expect(page.locator('#mm-login')).toBeVisible(); await expect(page.locator('#mm-workspace')).toBeHidden(); + const anonymousStream=await page.evaluate(()=>new Promise(resolve=>{let opened=false;const ws=new WebSocket('ws://127.0.0.1:4174/m3ter-manager/live');ws.onopen=()=>{opened=true;ws.close();};ws.onclose=()=>resolve(opened);})); + expect(anonymousStream).toBe(false); + await page.locator('#mm-username').fill('test-manager');await page.locator('#mm-password').fill('wrong');await page.locator('#mm-login-submit').click(); + await expect(page.locator('#mm-login-error')).toHaveText('Incorrect username or password.'); + await page.locator('#mm-password').fill('test-only-manager-password');await page.locator('#mm-login-submit').click(); + await expect(page.locator('#mm-workspace')).toBeVisible();await expect(page.locator('#mm-feed')).toHaveText('Live feed connected'); + expect((await context.request.get(api+'/devices')).status()).toBe(200); + expect(await page.evaluate(()=>document.cookie)).not.toContain('m3ter_manager_session'); + const cookies=await context.cookies();expect(cookies.find(c=>c.name==='m3ter_manager_session')).toMatchObject({httpOnly:true,sameSite:'Strict'}); + await page.reload();await page.evaluate(()=>Desktop.launch('m3ter-manager'));await expect(page.locator('#mm-workspace')).toBeVisible(); + const second=await context.newPage();await second.route(/https:\/\//,route=>route.abort());await second.goto('/');await second.evaluate(()=>Desktop.launch('m3ter-manager')); + await expect(second.locator('#mm-feed')).toHaveText('Live feed connected'); + await page.locator('#mm-logout').click();await expect(page.locator('#mm-login')).toBeVisible(); + await expect(second.locator('#mm-login')).toBeVisible();expect((await context.request.get(api+'/devices')).status()).toBe(401); + expect(await page.evaluate(()=>JSON.stringify(localStorage))).not.toContain('test-only-manager-password'); +}); diff --git a/tests/ui/manager-fixture.cjs b/tests/ui/manager-fixture.cjs new file mode 100644 index 0000000..832ea36 --- /dev/null +++ b/tests/ui/manager-fixture.cjs @@ -0,0 +1,93 @@ +// Test infrastructure only: an HTTP ChirpStack REST stub and a real TCP MQTT broker. +const http = require('node:http'); +const net = require('node:net'); +const { randomUUID, generateKeyPairSync, sign } = require('node:crypto'); +const mqttPacket = require('mqtt-packet'); +const application = '11111111-1111-4111-8111-111111111111'; +const devices = [ + { devEui: '0102030405060708', name: 'Cumulus · Workshop' }, + { devEui: '1112131415161718', name: 'Cumulus · Solar room' }, + { devEui: '2122232425262728', name: 'Cumulus · Awaiting installation' }, +]; +module.exports = async function managerFixture(app) { + process.env.APPLICATION_ID = application; + process.env.API_TOKEN = 'fixture-backend-token-never-in-browser'; + process.env.CONSOLE_MONITOR_ONLY = 'true'; + const { ingestEvent } = require('../../dist/m3ter/monitor'); + const keys = new Map(devices.map(device => [device.devEui, generateKeyPairSync('ed25519')])); + const queues = new Map(devices.map(device => [device.devEui, []])); + let enqueueCount = 0, listFailure = false, queueFailure = false; + const rest = http.createServer((req, res) => { + res.setHeader('Content-Type', 'application/json'); + const reply = (data, status = 200) => { res.statusCode = status; res.end(JSON.stringify(data)); }; + if (req.headers.authorization !== `Bearer ${process.env.API_TOKEN}`) { reply({error:'Unauthorized'},401); return; } + const url = new URL(req.url,'http://fixture'); + if (url.pathname === '/api/devices') { + if (listFailure) { reply({error:'Unavailable'},503); return; } + const search = (url.searchParams.get('search') || '').toLowerCase(); + const matches = devices.filter(device => (device.name + device.devEui).toLowerCase().includes(search)); + reply({ totalCount:matches.length, result:matches.map(device => ({...device,deviceProfileName:'Switch Cumulus',deviceProfileId:'profile-1'})) }); return; + } + if (url.pathname.startsWith('/api/device-profiles/')) { reply({deviceProfile:{name:'Switch Cumulus'}}); return; } + if (url.pathname.startsWith('/api/applications/')) { reply({application:{name:'Workshop network'}}); return; } + const match = url.pathname.match(/^\/api\/devices\/([a-f0-9]{16})(\/queue)?$/); + if (!match) { reply({},404); return; } + const id = match[1], device = devices.find(device => device.devEui === id); + if (!device) { reply({device:{devEui:id,applicationId:'22222222-2222-4222-8222-222222222222'} }); return; } + if (!match[2]) { reply({device:{...device,applicationId:application,deviceProfileId:'profile-1',tags:{phaseMode:'phase-a'},variables:{private:'must-not-leak'}},enabledClass:'CLASS_C'}); return; } + if (queueFailure) { reply({error:'upstream failure'},503); return; } + if (req.method === 'GET') { reply({totalCount:queues.get(id).length,result:queues.get(id)}); return; } + if (req.method === 'DELETE') { queues.set(id,[]); reply({}); return; } + let data = ''; req.on('data', chunk => data += chunk); req.on('end', () => { + const { queueItem } = JSON.parse(data); enqueueCount++; queues.get(id).push({...queueItem,isPending:true}); reply({id:queueItem.id}); + }); + }); + await new Promise(resolve => rest.listen(0,'127.0.0.1',resolve)); + process.env.CHIRPSTACK_REST_URL = `http://127.0.0.1:${rest.address().port}`; + const clients = new Set(); + const broker = net.createServer(socket => { + const parser = mqttPacket.parser(); socket.on('data', data => parser.parse(data)); socket.on('error',()=>{}); + socket.on('close',()=>clients.delete(socket)); parser.on('error',()=>socket.destroy()); + const send = packet => socket.write(mqttPacket.generate(packet)); + parser.on('packet', packet => { + if (packet.cmd === 'connect') send({cmd:'connack',returnCode:0,sessionPresent:false}); + if (packet.cmd === 'subscribe') { clients.add(socket); send({cmd:'suback',messageId:packet.messageId,granted:packet.subscriptions.map(()=>1)}); } + if (packet.cmd === 'pingreq') send({cmd:'pingresp'}); + if (packet.cmd === 'disconnect') socket.end(); + }); + }); + await new Promise(resolve => broker.listen(0,'127.0.0.1',resolve)); + process.env.MQTT_URL = `mqtt://127.0.0.1:${broker.address().port}`; + const { handleUplinks, stopUplinks } = require('../../dist/services/mqtt'); + await handleUplinks(); + function uplink(input = {}) { + const id = input.devEui || devices[0].devEui, key = keys.get(id); + const bytes = Buffer.alloc(input.length || ((input.nonce ?? 0) === 0 ? 106 : 74)); if (bytes.length >= 74) { + bytes.writeUInt32BE(input.nonce ?? 0,0); bytes.writeUInt32BE(Math.round((input.energy ?? 12.345678)*1e6),4); + sign(null,bytes.subarray(0,8),key.privateKey).copy(bytes,8); bytes.writeUInt16BE(Math.round((input.voltage ?? 230.1)*10),72); + if (bytes.length === 106) key.publicKey.export({format:'der',type:'spki'}).subarray(-32).copy(bytes,74); + } + return { deduplicationId:input.eventId || randomUUID(), time:new Date(input.timestamp || Date.now()).toISOString(), + deviceInfo:{ devEui:id, applicationId:application, deviceName:devices.find(d=>d.devEui===id).name, applicationName:'Workshop network',deviceProfileName:'Switch Cumulus' }, + data:bytes.toString('base64'), fPort:input.fPort ?? 2, fCnt:input.nonce ?? 0, rxInfo:[{rssi:-70,snr:9.5,gatewayId:'aabbccddeeff0011'}] }; + } + for (let i=0;i<80;i++) { + const event = uplink({nonce:i<40?1:2,energy:i<40?10+i*.01:(i-40)*.02,voltage:229+i%5,timestamp:Date.now()-(80-i)*60000}); + ingestEvent(`application/${application}/device/${event.deviceInfo.devEui}/event/up`,Buffer.from(JSON.stringify(event))); + } + const second = uplink({devEui:devices[1].devEui,energy:7.5,voltage:235}); + ingestEvent(`application/${application}/device/${second.deviceInfo.devEui}/event/up`,Buffer.from(JSON.stringify(second))); + app.post('/__test/manager', (req,res) => { + const body = req.body || {}; + if (body.action === 'stats') { res.json({enqueueCount,clients:clients.size}); return; } + if (body.action === 'list-failure') { listFailure = !!body.value; res.json({ok:true}); return; } + if (body.action === 'queue-failure') { queueFailure = !!body.value; res.json({ok:true}); return; } + if (body.action === 'disconnect') { for (const socket of clients) socket.destroy(); res.json({ok:true}); return; } + const event = body.kind && body.kind !== 'up' ? { deduplicationId:randomUUID(),time:new Date().toISOString(),deviceInfo:{devEui:body.devEui || devices[0].devEui,applicationId:application},queueItemId:body.queueItemId,acknowledged:body.acknowledged,location:body.location } : uplink(body); + const topic = `application/${application}/device/${event.deviceInfo.devEui}/event/${body.kind || 'up'}`; + const payload = body.action === 'malformed' ? '{' : JSON.stringify(event); + for (const socket of clients) socket.write(mqttPacket.generate({cmd:'publish',topic,payload,qos:0,retain:false,dup:false})); + res.json({event}); + }); + app.on('close', () => { stopUplinks(); for(const socket of clients) socket.destroy(); broker.close(); rest.close(); }); +}; diff --git a/tests/ui/manager-preview.cjs b/tests/ui/manager-preview.cjs new file mode 100644 index 0000000..754ab60 --- /dev/null +++ b/tests/ui/manager-preview.cjs @@ -0,0 +1,23 @@ +// UI preview only. All MQTT and REST endpoints are local simulators, never real meters. +module.exports = async function attachManagerPreview(app, server) { + process.env.M3TER_MANAGER_USERNAME = 'demo'; + process.env.M3TER_MANAGER_PASSWORD = 'demo-manager'; + const { requireManagerAuth, managerAuthenticated } = require('../../dist/m3ter/auth'); + const store = require('../../dist/store/sqlite'); + const database = `manager-preview-${process.pid}.db`; + store.default(database); process.on('exit',()=>store.deleteDatabase(database)); + await require('./manager-fixture.cjs')(app); + const { commandCatalogue } = require('../../dist/m3ter/commands'); + const { monitoring, managerEvents, inactiveMilliseconds } = require('../../dist/m3ter/monitor'); + app.get('/api/m3ter-manager/config',requireManagerAuth,(_req,res)=>res.json({commands:commandCatalogue,monitoring,inactiveMilliseconds:inactiveMilliseconds(),demo:true})); + app.use('/api/m3ter-manager',require('../../dist/m3ter/api').managerRouter); + const WebSocket = require('ws'); + const wss = new WebSocket.Server({noServer:true}); + server.on('upgrade',(req,socket,head)=>{ + if (req.url !== '/m3ter-manager/live' || !managerAuthenticated(req)) {socket.destroy();return;} + wss.handleUpgrade(req,socket,head,ws=>wss.emit('connection',ws,req)); + }); + const send = (ws,data)=>{if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(data));}; + wss.on('connection',(ws,req)=>{ ws.managerRequest=req; send(ws,{type:'connection',monitoring}); }); + managerEvents.on('update',data=>{for(const ws of wss.clients) { if(managerAuthenticated(ws.managerRequest))send(ws,data); else ws.close(4001,'Sign in required'); }}); +}; diff --git a/tests/ui/manager.spec.cjs b/tests/ui/manager.spec.cjs new file mode 100644 index 0000000..0eacf8d --- /dev/null +++ b/tests/ui/manager.spec.cjs @@ -0,0 +1,139 @@ +const { test, expect } = require('@playwright/test'); +const { randomUUID } = require('node:crypto'); +const base = 'http://127.0.0.1:4174', api = '/api/m3ter-manager'; +const a = '0102030405060708', b = '1112131415161718', empty = '2122232425262728'; +test.use({ baseURL: base, httpCredentials: { username:'test-console',password:'test-only-browser-password' } }); +test.beforeEach(async ({ page, request }) => { await page.route(/https:\/\//, route => route.abort()); + expect((await request.post(api+'/session',{data:{username:'test-manager',password:'test-only-manager-password'}})).status()).toBe(200); +}); +async function open(page, id = a) { + await page.goto('/'); await page.evaluate(() => Desktop.launch('m3ter-manager')); + await page.locator('#mm-username').fill('test-manager'); await page.locator('#mm-password').fill('test-only-manager-password'); + await page.locator('#mm-login-submit').click(); + await expect(page.locator('#mm-device option')).toHaveCount(4); + await page.locator('#mm-device').selectOption(id); + await expect(page.locator('#mm-eui')).toHaveText(id); + await expect(page.locator('#mm-selected')).toHaveAttribute('aria-busy','false'); +} +const control = (request, body) => request.post('/__test/manager',{data:body}); + +test('real MQTT client receives multi-meter telemetry, reconnects, persists, and reports diagnostics', async ({ page, request }) => { + await open(page); + await expect(page.locator('#mm-mqtt')).toHaveText('MQTT connected'); + const before = await page.locator('#mm-energy').textContent(); + await control(request,{devEui:b,energy:22.5,nonce:5}); + await expect.poll(async () => (await (await request.get(`${api}/devices/${b}/history`)).json()).latest.energy).toBe(22.5); + await expect(page.locator('#mm-energy')).toHaveText(before); + const event = {devEui:a,energy:1.234567,voltage:231.2,nonce:82,eventId:randomUUID(),timestamp:Date.now()}; + await control(request,event); + await expect(page.locator('#mm-energy')).toHaveText('1.234567'); await expect(page.locator('#mm-voltage')).toHaveText('231.2'); + const total = (await (await request.get(`${api}/devices/${a}/history`)).json()).total; + await control(request,event); + expect((await (await request.get(`${api}/devices/${a}/history`)).json()).total).toBe(total); + await page.reload(); await page.evaluate(() => Desktop.launch('m3ter-manager')); + await expect(page.locator('#mm-energy')).toHaveText('1.234567'); + await control(request,{action:'disconnect'}); + await expect(page.locator('#mm-mqtt')).toHaveText(/disconnected|reconnecting/); + await expect(page.locator('#mm-mqtt')).toHaveText('MQTT connected',{timeout:15000}); + await control(request,{devEui:a,energy:1.3,nonce:83}); await expect(page.locator('#mm-energy')).toHaveText('1.300000'); + await page.locator('[data-mm-tab="live"]').click(); + await control(request,{devEui:a,length:73}); + await expect(page.locator('#mm-events')).toContainText('requires exactly 74 or 106 bytes'); + await control(request,{action:'malformed'}); await expect(page.locator('#mm-error')).toContainText('Unable to process'); + await page.locator('#mm-device').selectOption(b); await expect(page.locator('#mm-energy')).toHaveText('22.500000'); +}); + +test('backend validates scope, commands, safety confirmation, idempotency and exact queue payloads', async ({ request, playwright }) => { + expect((await fetch(base+api+'/devices')).status).toBe(401); + expect((await request.get(api+'/devices/not-a-device/history')).status()).toBe(400); + expect((await request.get(api+'/devices/ffffffffffffffff')).status()).toBe(403); + const details = await (await request.get(`${api}/devices/${a}`)).json(); + expect(JSON.stringify(details)).not.toContain('must-not-leak'); expect(JSON.stringify(details)).not.toContain('fixture-backend-token'); + for (const data of [ + {commandId:'relay-on',fPort:200,data:'AA=='}, {commandId:'current-gain',value:3}, {commandId:'phase-mode',value:4}, + {commandId:'report-interval',value:9}, {commandId:'report-interval',value:65536}, {commandId:'class-b'}, + {commandId:'billing-connect'}, {commandId:'restart'}, + ]) expect((await request.post(`${api}/devices/${a}/commands`,{data:{requestId:randomUUID(),...data}})).status()).toBe(400); + expect((await request.post(`${api}/devices/${a}/commands`,{headers:{origin:'https://foreign.example'},data:{commandId:'relay-on',requestId:randomUUID()}})).status()).toBe(403); + const count = (await (await control(request,{action:'stats'})).json()).enqueueCount; + const requestId = randomUUID(), body = {commandId:'report-interval',value:900,requestId}; + const accepted = await (await request.post(`${api}/devices/${a}/commands`,{data:body})).json(); + expect(accepted).toMatchObject({status:'queued',queueId:requestId,command:{fPort:2,data:'AgOE',hex:'020384',length:3}}); + await request.post(`${api}/devices/${a}/commands`,{data:body}); + expect((await (await control(request,{action:'stats'})).json()).enqueueCount).toBe(count+1); + expect((await request.post(`${api}/devices/${a}/commands`,{data:{...body,value:60}})).status()).toBe(409); + const queue = await (await request.get(`${api}/devices/${a}/queue`)).json(); + expect(queue.items).toEqual(expect.arrayContaining([expect.objectContaining({id:requestId,fPort:2,data:'AgOE',confirmed:false})])); + await control(request,{kind:'txack',devEui:a,queueItemId:requestId}); + const status = async () => (await (await request.get(`${api}/devices/${a}/commands`)).json()).commands.find(item=>item.id===requestId)?.status; + await expect.poll(status).toBe('transmitted'); + await control(request,{kind:'ack',devEui:a,queueItemId:requestId,acknowledged:true}); await expect.poll(status).toBe('delivered'); + expect((await request.delete(`${api}/devices/${a}/queue`,{data:{}})).status()).toBe(400); + expect((await request.delete(`${api}/devices/${a}/queue`,{data:{confirmDevEui:a}})).status()).toBe(200); + expect((await (await request.get(`${api}/devices/${a}/queue`)).json()).items).toHaveLength(0); + expect(await status()).toBe('delivered'); +}); + +test('command UI previews frames, protects billing and hardware controls, and clears the queue explicitly', async ({ page }) => { + await open(page); + await page.locator('[data-mm-command="relay-on"]').click(); + await expect(page.locator('#mm-dialog')).toBeVisible(); await expect(page.locator('#mm-dialog-content')).toContainText('Base64: Gw=='); + await page.locator('#mm-submit').click(); await expect(page.locator('#mm-notice')).toContainText('Relay ON: queued'); + await page.locator('[data-mm-tab="commands"]').click(); + await page.locator('[data-command-id="billing-disconnect"]').click(); + await expect(page.locator('#mm-submit')).toBeDisabled(); await expect(page.locator('#mm-dialog-content')).toContainText('energy accumulator will reset'); + await page.locator('#mm-confirm').check(); await page.locator('#mm-submit').click(); + await expect(page.locator('#mm-command-history')).toContainText('Disconnect (Billing)'); + await page.getByLabel('Report interval presets').selectOption('60'); await page.locator('[data-command-id="report-interval"]').click(); + await expect(page.locator('#mm-dialog-content')).toContainText('AgA8'); await expect(page.locator('#mm-dialog-content')).toContainText('Selected setting: 60 seconds'); await page.locator('#mm-cancel').click(); + await page.getByLabel('Current gain (PGA)',{exact:true}).selectOption('4'); await page.locator('[data-command-id="current-gain"]').click(); + await expect(page.locator('#mm-dialog-content')).toContainText('IAQ='); await page.locator('#mm-cancel').click(); + await page.locator('[data-mm-tab="queue"]').click(); await expect(page.locator('#mm-queue')).toContainText('Pending delivery'); + await page.locator('#mm-queue-clear').click(); await expect(page.locator('#mm-submit')).toBeDisabled(); + await expect(page.locator('#mm-dialog-content')).toContainText('ALL currently queued downlinks'); + await page.locator('#mm-confirm').check(); await page.locator('#mm-submit').click(); await expect(page.locator('#mm-queue')).toContainText('No pending downlinks'); +}); + +test('search, empty meters, analytics, raw reading inspection and error recovery work', async ({ page, request }) => { + await open(page); + await page.locator('#mm-search').fill('111213'); await expect(page.locator('#mm-device option')).toHaveCount(3); // current selection stays pinned + await page.locator('#mm-device').selectOption(b); await expect(page.locator('#mm-name')).toContainText('Solar room'); + await page.locator('#mm-search').fill(''); await expect(page.locator('#mm-device option')).toHaveCount(4); + await page.locator('#mm-device').selectOption(empty); await expect(page.locator('#mm-energy')).toHaveText('—'); await expect(page.locator('#mm-age')).toHaveText('Never observed'); + await page.locator('#mm-device').selectOption(a); await page.locator('[data-mm-tab="analytics"]').click(); + await expect(page.locator('#mm-summary')).toContainText('new nonce cycle'); + await expect(page.locator('#mm-history-energy svg')).toBeVisible(); await page.locator('#mm-history-energy svg').focus(); await page.keyboard.press('ArrowLeft'); + await expect(page.locator('#mm-history-energy .mm-chart-tooltip')).toContainText('kWh'); + await page.locator('#mm-history-next').click(); await expect(page.locator('#mm-history-count')).toContainText('51–'); + await page.locator('#mm-readings button').first().click(); await expect(page.locator('#mm-dialog-content')).toContainText('Raw payload (Base64)'); await page.locator('#mm-cancel').click(); + await page.locator('#mm-range').selectOption('3600000'); await expect(page.locator('#mm-history-count')).toContainText('1–'); + await control(request,{action:'list-failure',value:true}); + try { await page.locator('#mm-refresh').click(); await expect(page.locator('#mm-error')).toBeVisible(); } + finally { await control(request,{action:'list-failure',value:false}); } + await page.locator('#mm-refresh').click(); await expect(page.locator('#mm-error')).toBeHidden(); + await control(request,{action:'queue-failure',value:true}); + try { await page.locator('[data-mm-tab="queue"]').click(); await expect(page.locator('#mm-queue')).toContainText('rejected the request'); } + finally { await control(request,{action:'queue-failure',value:false}); } + await page.locator('#mm-queue-refresh').click(); await expect(page.locator('#mm-queue')).toContainText('No pending downlinks'); +}); + +test('manager adapts to every desktop theme and desktop, tablet and phone dimensions', async ({ page }, testInfo) => { + await open(page); + const errors = []; page.on('pageerror',error=>errors.push(error.message)); + for (const [width,height] of [[1440,900],[768,1024],[390,844],[320,568]]) { + await page.setViewportSize({width,height}); + for (const theme of ['retro','macos','linux','windows']) { + await page.evaluate(()=>Desktop.launch('settings')); + await page.locator(`[data-theme-choice="${theme}"]`).click(); await page.evaluate(()=>Desktop.launch('m3ter-manager')); + await expect(page.locator('#mm-eui')).toHaveText(a); + const bounds = await page.locator('#m3ter-manager').boundingBox(); + expect(bounds.x).toBeGreaterThanOrEqual(0); expect(bounds.x+bounds.width).toBeLessThanOrEqual(width+1); + expect(await page.locator('.mm-scroll').evaluate(element=>element.scrollWidth<=element.clientWidth+1)).toBe(true); + await page.locator('[data-mm-tab="commands"]').click(); + expect(await page.locator('.mm-scroll').evaluate(element=>element.scrollWidth<=element.clientWidth+1)).toBe(true); + await page.locator('[data-mm-tab="overview"]').click(); + if (width===1440 || width===390) await page.screenshot({path:testInfo.outputPath(`manager-${theme}-${width}.png`)}); + } + } + expect(errors).toEqual([]); +}); diff --git a/tests/ui/serve-auth.cjs b/tests/ui/serve-auth.cjs new file mode 100644 index 0000000..aea0ead --- /dev/null +++ b/tests/ui/serve-auth.cjs @@ -0,0 +1,20 @@ +// Production HTTP/WebSocket access checks, with no MQTT, chain, or SSH login. +process.env.M3TER_MANAGER_USERNAME = 'test-manager'; +process.env.M3TER_MANAGER_PASSWORD = 'test-only-manager-password'; +process.env.CONSOLE_USERNAME = 'test-console'; +process.env.CONSOLE_PASSWORD = 'test-only-browser-password'; +process.env.BACKEND_MODULES = ''; +process.env.UI_MODULES = ''; +process.env.CONSOLE_ORIGIN = 'http://127.0.0.1:4174'; +const store = require('../../dist/store/sqlite'); +const database = `auth-browser-${process.pid}.db`; +store.default(database); +process.on('exit', () => store.deleteDatabase(database)); +const { server, app } = require('../../dist/services/server'); +require('../../dist/services/ssh'); +const upstream = require('./chirpstack-upstream.cjs'); +upstream.listen(0, '127.0.0.1', async () => { + process.env.CHIRPSTACK_WEB_URL = `http://127.0.0.1:${upstream.address().port}`; + await require('./manager-fixture.cjs')(app); + server.listen(4174, '127.0.0.1', () => console.log('Authentication test server ready on 4174')); +}); diff --git a/tests/ui/serve.cjs b/tests/ui/serve.cjs new file mode 100644 index 0000000..93924c4 --- /dev/null +++ b/tests/ui/serve.cjs @@ -0,0 +1,26 @@ +// UI-only fixture server: real templates/assets, deterministic data, no device or chain connections. +const express = require('express'); +const { create } = require('express-handlebars'); +const app = express(); +app.engine('hbs', create({ partialsDir: './src/views/partials', defaultLayout: 'main', extname: 'hbs', helpers: { encodeURIComponent } }).engine); +app.set('view engine', 'hbs'); +app.set('views', './src/views'); +app.use(express.static('./src/public')); +app.use(express.json()); +app.get('/chirpstack/', (req, res) => res.type('html').send('

ChirpStack

This UI preview uses sample data. Open ChirpStack in the running console to connect to your server.

')); +app.get('/', (req, res) => { + const count = Math.min(100, Math.max(1, Number(req.query.apps) || 1)); + const icons = [], windows = []; + for (let i = 0; i < count; i++) { + const id = i ? `extension-${i}` : 'streamr'; + icons.push({ id, label: i ? `Extension ${i}` : 'Streamr', iconHtml: '' }); + windows.push({ id, title: i ? `Extension ${i}` : 'Streamr Publisher', contentHtml: '

Configuration

Pending transactions: 2

' }); + } + res.render('index', { managerDemo: true, icons, windows, m3ters: [{ tokenId: 42, publicKey: '0x' + 'ab'.repeat(32) }] }); +}); +app.post('/api/actions/:moduleId/:actionId', (req, res) => res.json({ success: true, message: 'Published 2 transactions (test fixture)' })); +app.delete('/delete-meter', (req, res) => res.json({ message: 'deleted meter (test fixture)' })); +const server = require('node:http').createServer(app); +require('./manager-preview.cjs')(app, server).then(() => { + server.listen(4173, '127.0.0.1', () => console.log('UI preview (simulated meters): http://127.0.0.1:4173')); +}).catch(error => { console.error(error); process.exit(1); }); diff --git a/tests/ui/streamr.test.ts b/tests/ui/streamr.test.ts new file mode 100644 index 0000000..53bbff9 --- /dev/null +++ b/tests/ui/streamr.test.ts @@ -0,0 +1,34 @@ +import StreamrUI from '../../src/lib/core/streamr/ui'; +import { getAllTransactionRecords } from '../../src/store/sqlite'; + +jest.mock('@streamr/sdk', () => ({ StreamrClient: jest.fn() })); +jest.mock('../../src/store/sqlite', () => ({ getAllTransactionRecords: jest.fn(() => []) })); + +describe('Streamr desktop presentation', () => { + const originalStream = process.env.STREAMR_STREAM_ID; + afterEach(() => { + if (originalStream === undefined) delete process.env.STREAMR_STREAM_ID; + else process.env.STREAMR_STREAM_ID = originalStream; + jest.clearAllMocks(); + }); + it('preserves application and action identifiers and displays empty status', async () => { + delete process.env.STREAMR_STREAM_ID; + const ui = new StreamrUI(); + expect(ui.getAppIcon()).toMatchObject({ id: 'streamr', label: 'Streamr' }); + expect(ui.getActions()[0].id).toBe('publish-now'); + const window = await ui.getAppWindow(); + expect(window.id).toBe('streamr'); + expect(window.contentHtml).toContain('No streams configured.'); + expect(window.contentHtml).toContain('disabled'); + expect(window.contentHtml).toContain("invokeAction('streamr', 'publish-now', this)"); + }); + it('renders configured streams as text and enables publishing pending transactions', async () => { + process.env.STREAMR_STREAM_ID = 'example/