diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e88d610..3fd3203 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,10 +22,6 @@ jobs: persist-credentials: false - uses: kleinbem/actions/nix-setup@f1b4f5fc52ea31b1f9e53ca29170570fe4651c7d # v1.7.1 - name: Flake check - run: nix flake check - - name: Svelte check - run: | - nix develop --command npm ci - nix develop --command npm run check - - name: Build web - run: nix build .#default + run: nix flake check -L + - name: Build package + run: nix build --no-link .#default diff --git a/AGENTS.md b/AGENTS.md index 2f62f63..15f7005 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,31 +2,31 @@ Guidance for AI assistants working on Foyer. -## What Foyer is +## Architecture -Foyer is the lightweight, next-generation homelab portal and service launchpad for the kleinbem fleet (`home.kleinbem.dev`). -It replaces legacy heavy dashboards (like Homepage) with a fast, modern static SvelteKit application styled with `@kleinbem/web-config` and Tailwind CSS 4. +Foyer is a pure static SvelteKit 5 SPA (`ssr = false`, `prerender = true`, `200.html` fallback) styled with Tailwind CSS 4 and `@kleinbem/web-config`. -## Key Capabilities +- **`src/lib/config.ts`**: Runtime `/config.json` parser and loader (`parsePortalConfig`, `loadPortalConfig`, URL scheme sanitization, duplicate-ID filtering). Upstream ships a neutral default in `static/config.json`; fleet deployments inject site inventory via `/config.json`. +- **`src/lib/portal.ts`**: Pure domain logic for bookmark validation/creation, multi-token `โŒ˜K` palette search (`#host`, `@category`, `!network`, `>`), category grouping, health metrics, and Open-Meteo parsing. +- **`src/lib/data/gatus.ts`**: Optional client-side Gatus `/api/v1/endpoints/statuses` health polling and endpoint resolution. +- **`src/lib/components/`**: Svelte 5 runes UI components (`Header`, `WeatherWidget`, `HostBar`, `LayoutToggle`, `BookmarksSection`, `CategorySection`, `ServiceCard`, `CommandPalette`). Modals use native `` (`showModal()`). +- **`test/`**: Hermetic Node `node:test` + Svelte 5 SSR test suite (`test/setup.ts` compiles `.svelte` and `.svelte.js`/`.svelte.ts` on the fly with zero extra npm dependencies). +- **`nix/package.nix`**: `nixpkgs`-compliant `buildNpmPackage` derivation (`fetchNpmDeps`, `strictDeps = true`, `__structuredAttrs = true`, `checkPhase`, `installCheckPhase`, and offline Caddy `passthru.tests.smoke`). -- **Fleet Design System**: Uses `@kleinbem/web-config` themes (dark/light, system preference, zero-FOUC). -- **Service catalogue**: hand-maintained `FLEET_SERVICES` in `src/lib/data/services.ts` and `FLEET_HOSTS` in `src/lib/data/hosts.ts` (not generated from `inventory.nix`). -- **Network Reachability Indicators**: Highlights Public (Cloudflare Tunnel), Mesh-Only (NetBird), and LAN endpoints. -- **Gatus Live Health**: Queries live service statuses from `status.kleinbem.dev`. -- **Command Palette (`โŒ˜K`)**: Instant fuzzy search across services, hosts, and tools. -- **Zero Runtime Overhead**: Packaged via Nix (`buildNpmPackage`) as a pure static SPA served directly by Caddy. - -## Development +## Development & Verification ```bash -just dev # Run Vite dev server -just check # Run svelte-check and TypeScript checks -just build # Build static production assets -just preview # Preview production build +just dev # Run Vite dev server +just test # Run unit and SSR component tests +just check # Run svelte-check and TypeScript checks (--fail-on-warnings) +just build # Build static production assets +nix flake check # Run sandboxed package build, checks, installCheck, and Caddy smoke test ``` +When editing `.svelte` files, verify with `npx --offline @sveltejs/mcp svelte-autofixer `. + ## TypeScript `typescript` is aliased to `@typescript/typescript6` and TypeScript 7 sits beside it as -`@typescript/native`: svelte-check and the Svelte tooling need the TS 6 JavaScript API, which the +`@typescript/native`: `svelte-check` and the Svelte tooling need the TS 6 JavaScript API, which the native TS 7 compiler does not ship. Same setup in every fleet Svelte repo. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e697fc3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Martin Kleinberger + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 2addcac..3df6b1b 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,87 @@ -# Foyer ๐Ÿ  +# Foyer -> *The elegant, lightweight homelab portal and service launchpad for the kleinbem fleet.* +Lightweight static homelab portal and service launchpad built with SvelteKit 5, Tailwind CSS 4, and [`@kleinbem/web-config`](https://github.com/kleinbem/web-config). -Foyer serves as the front door to [`home.kleinbem.dev`](https://home.kleinbem.dev). Built with modern SvelteKit and Tailwind CSS 4 using the shared [`@kleinbem/web-config`](https://github.com/kleinbem/web-config) design system, Foyer delivers instantaneous page loads with zero runtime overhead on host infrastructure. +Foyer compiles to a pure static SPA (`index.html`, `200.html`, `_app/`) with zero backend process or database, and loads its service and host catalogue at runtime from `/config.json`. -## โœจ Features +## Features -- **Fleet Design System**: Fully synchronized theme tokens, typography, and dark/light modes powered by `@kleinbem/web-config`. -- **Zero Runtime Overhead**: Packaged via Nix as a pure static SPA served directly by Caddy; no persistent Node.js or container runtime required on `core-pi`. -- **Network Reachability Awareness**: Clear visual badges for **Public** (Cloudflare Tunnel), **Mesh-Only** (NetBird), and **LAN-Only** services. -- **Real-Time Health & Uptime**: Direct live status integration with the fleet's [Gatus](https://status.kleinbem.dev) instance. -- **Command Palette (`โŒ˜K` / `/`)**: Fast keyboard-driven fuzzy search across all services, host nodes, and quick links. -- **Host Node Filtering**: Filter services dynamically by node (`core-pi`, `nixos-nvme`, `mac-mini`, `nasbook`, `orin-nano`, `bpi-r4`). -- **Live Weather & Telemetry**: Built-in weather widget (Open-Meteo) and system clocks. +- **Runtime `/config.json` Catalogue**: Deploy one immutable static build anywhere and mount or serve `/config.json` per environment with strict runtime schema and URL validation. +- **Command Palette (`โŒ˜K` / `/`)**: Multi-token keyboard search across services, pinned bookmarks, and host nodes with `#host`, `@category`, `!network`, and `>` web-search prefixes. +- **Network Reachability Badges**: Distinct indicators for `public`, `mesh`, and `lan` endpoints plus one-click filter chips. +- **Live Gatus Health**: Optional client-side polling against a [Gatus](https://gatus.io) `/api/v1/endpoints/statuses` endpoint with visibility-aware refresh and stale-data indication. +- **Host Node Bar**: Per-host service counts, one-click host filtering, and IP clipboard copy. +- **Local Quick Bookmarks**: Browser-stored personal links (`localStorage`) in a dedicated native `` modal, immediately searchable from `โŒ˜K`. +- **Optional Weather & Clock**: Minute-aligned UTC/local header clock and optional [Open-Meteo](https://open-meteo.com) telemetry widget. -## ๐Ÿ› ๏ธ Development +## Runtime Configuration (`/config.json`) + +Serve a `/config.json` file at the web root alongside Foyer's static assets (an empty neutral config ships by default): + +```json +{ + "title": "Foyer", + "subtitle": "Homelab Launchpad", + "gatusUrl": "https://status.example.com", + "searchUrlTemplate": "https://duckduckgo.com/?q=%s", + "weather": { + "latitude": 51.5072, + "longitude": -0.1276, + "label": "London" + }, + "categoryOrder": ["Infrastructure", "Media"], + "hosts": [ + { + "id": "core-01", + "name": "core-01", + "ip": "192.0.2.10", + "role": "Edge & Ingress" + } + ], + "services": [ + { + "id": "grafana", + "name": "Grafana", + "description": "Metrics and dashboards", + "url": "https://grafana.example.com", + "icon": "๐Ÿ“Š", + "category": "Infrastructure", + "host": "core-01", + "network": "mesh", + "gatusEndpoint": "grafana", + "tags": ["metrics", "observability"] + } + ], + "footerLinks": [ + { + "label": "Status", + "url": "https://status.example.com" + } + ] +} +``` + +## Development ```bash -just dev # Start local development server -just check # Run Svelte and TypeScript checks -just build # Build static assets (to build/) -just preview # Preview production build +just dev # Start Vite development server +just test # Run Node + Svelte SSR unit & component tests +just check # Run svelte-check and TypeScript checks (--fail-on-warnings) +just build # Build production static assets to build/ +just preview # Preview production build locally ``` -## ๐Ÿ“ฆ Deployment & Nix +## Nix & Deployment -Packaged using `pkgs.buildNpmPackage` with reproducible npm locks: +Foyer builds reproducibly in the Nix sandbox via `buildNpmPackage` (`nix/package.nix`): ```bash nix build .#default +nix flake check ``` + +Serve the resulting store path with any static file server (such as Caddy or nginx) configured with `try_files {path} /200.html` and mount your site-specific `/config.json` over the web root. + +## License + +[MIT](./LICENSE) diff --git a/flake.lock b/flake.lock index a38e600..4524ce8 100644 --- a/flake.lock +++ b/flake.lock @@ -1,23 +1,5 @@ { "nodes": { - "flake-utils": { - "inputs": { - "systems": "systems" - }, - "locked": { - "lastModified": 1791914995, - "narHash": "sha256-Zf/xfQEAasnwnmEfHqW/4hjDE/s44yn2hD4RuVIZRjA=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "b7a79d3fea1e214f6d668d521cecec0c01e26544", - "type": "github" - }, - "original": { - "owner": "numtide", - "repo": "flake-utils", - "type": "github" - } - }, "nixpkgs": { "locked": { "lastModified": 1793876309, @@ -36,24 +18,8 @@ }, "root": { "inputs": { - "flake-utils": "flake-utils", "nixpkgs": "nixpkgs" } - }, - "systems": { - "locked": { - "lastModified": 1681028828, - "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", - "owner": "nix-systems", - "repo": "default", - "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", - "type": "github" - }, - "original": { - "owner": "nix-systems", - "repo": "default", - "type": "github" - } } }, "root": "root", diff --git a/flake.nix b/flake.nix index 6d4caa0..9f0eb30 100644 --- a/flake.nix +++ b/flake.nix @@ -1,48 +1,58 @@ { - description = "Lightweight homelab portal and service launchpad for the kleinbem fleet"; + description = "Lightweight static homelab portal and service launchpad"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; - flake-utils.url = "github:numtide/flake-utils"; }; outputs = + { self, nixpkgs }: + let + inherit (nixpkgs) lib; + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + forAllSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in { - nixpkgs, - flake-utils, - ... - }: - flake-utils.lib.eachDefaultSystem ( - system: - let - pkgs = nixpkgs.legacyPackages.${system}; - in - { - formatter = pkgs.nixfmt; + overlays.default = final: _: { + foyer = final.callPackage ./nix/package.nix { }; + }; - packages.default = pkgs.buildNpmPackage { - pname = "foyer"; - version = "0.1.0"; - src = ./.; - npmDeps = pkgs.importNpmLock { npmRoot = ./.; }; - npmConfigHook = pkgs.importNpmLock.npmConfigHook; - installPhase = '' - mkdir -p $out - cp -r build/* $out/ - ''; - meta = with pkgs.lib; { - description = "Lightweight homelab portal and service launchpad"; - homepage = "https://github.com/kleinbem-dev/foyer"; - license = licenses.mit; - }; - }; + formatter = forAllSystems (pkgs: pkgs.nixfmt); + + packages = forAllSystems ( + pkgs: + let + foyer = pkgs.callPackage ./nix/package.nix { }; + in + { + inherit foyer; + default = foyer; + } + ); + + checks = forAllSystems ( + pkgs: + let + inherit (self.packages.${pkgs.stdenv.hostPlatform.system}) foyer; + in + { + default = foyer; + smoke = foyer.tests.smoke; + } + ); - devShells.default = pkgs.mkShell { + devShells = forAllSystems (pkgs: { + default = pkgs.mkShell { packages = with pkgs; [ - nodejs_22 + nodejs just ]; }; - } - ); + }); + }; } diff --git a/justfile b/justfile index 81ba108..54ec4ec 100644 --- a/justfile +++ b/justfile @@ -13,6 +13,10 @@ build: check: npm run check +# Run automated unit and component tests +test: + npm test + # Preview production build locally preview: npm run preview diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..14efe64 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,140 @@ +{ + lib, + buildNpmPackage, + nodejs, + nix-update-script, + runCommand, + caddy, + curl, + jq, +}: + +buildNpmPackage (finalAttrs: { + pname = "foyer"; + version = "0.1.0"; + + # In nixpkgs (`pkgs/by-name/fo/foyer/package.nix`), swap `fileset` for + # `fetchFromGitHub { owner = "kleinbem-dev"; repo = "foyer"; tag = "v${finalAttrs.version}"; hash = "..."; }`. + src = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + ../package.json + ../package-lock.json + ../tsconfig.json + ../vite.config.ts + ../src + ../static + ../test + ]; + }; + + npmDepsHash = "sha256-rFIpfCDb2SYN6SVz9K+sA0ht3KWCP3JjgsDj7rw+WJw="; + # pacote creates `_cacache/tmp` when unpacking git dependencies (`@kleinbem/web-config`). + # no-link: standard buildNpmPackage option for git lockfile entries, not an upstream bug. + makeCacheWritable = true; + + strictDeps = true; + __structuredAttrs = true; + + doCheck = true; + + checkPhase = '' + runHook preCheck + + npm test + npm run check + + runHook postCheck + ''; + + installPhase = '' + runHook preInstall + + mkdir -p "$out" + cp -r build/* "$out/" + + runHook postInstall + ''; + + doInstallCheck = true; + + installCheckPhase = '' + runHook preInstallCheck + + for expected in index.html 200.html config.json _app; do + if [ ! -e "$out/$expected" ]; then + echo "missing expected build output: $expected" >&2 + exit 1 + fi + done + + if grep -rn '/nix/store/' "$out"; then + echo "unexpected /nix/store reference leaked into static assets" >&2 + exit 1 + fi + + runHook postInstallCheck + ''; + + passthru = { + updateScript = nix-update-script { }; + tests.smoke = + runCommand "${finalAttrs.pname}-smoke-test" + { + nativeBuildInputs = [ + caddy + curl + jq + ]; + } + '' + sock="$TMPDIR/caddy.sock" + cat > Caddyfile <"$TMPDIR/caddy.log" 2>&1 & + caddy_pid=$! + trap 'kill "$caddy_pid" 2>/dev/null || true' EXIT + + ready=0 + for _ in $(seq 1 50); do + if curl -fsS --unix-socket "$sock" http://localhost/ >/dev/null 2>&1; then + ready=1 + break + fi + sleep 0.1 + done + if [ "$ready" -ne 1 ]; then + cat "$TMPDIR/caddy.log" >&2 + echo "caddy failed to start on $sock" >&2 + exit 1 + fi + + curl -fsS --unix-socket "$sock" http://localhost/ | grep -q "sveltekit" + curl -fsS --unix-socket "$sock" http://localhost/deep/spa/route | grep -q "sveltekit" + curl -fsS --unix-socket "$sock" http://localhost/config.json | jq -e '.title == "Foyer" and (.services | type == "array")' >/dev/null + + touch "$out" + ''; + }; + + meta = { + description = "Lightweight static homelab portal and service launchpad"; + homepage = "https://github.com/kleinbem-dev/foyer"; + changelog = "https://github.com/kleinbem-dev/foyer/releases/tag/v${finalAttrs.version}"; + license = lib.licenses.mit; + maintainers = with lib.maintainers; [ kleinbem ]; + inherit (nodejs.meta) platforms; + }; +}) diff --git a/package-lock.json b/package-lock.json index ee298c2..f4a0ffc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,8 +7,9 @@ "": { "name": "foyer", "version": "0.1.0", + "license": "MIT", "dependencies": { - "@kleinbem/web-config": "git+https://github.com/kleinbem/web-config.git#main" + "@kleinbem/web-config": "git+https://github.com/kleinbem/web-config.git#91a902ed6aec552ba103aa90b5597b1d2081148d" }, "devDependencies": { "@sveltejs/adapter-static": "^4.0.1", @@ -73,7 +74,7 @@ }, "node_modules/@kleinbem/web-config": { "version": "0.1.0", - "resolved": "git+https://github.com/kleinbem/web-config.git#d3c926ff1214be46312a81aca13ab51ad73ef2db", + "resolved": "git+https://github.com/kleinbem/web-config.git#91a902ed6aec552ba103aa90b5597b1d2081148d", "license": "MIT", "peerDependencies": { "@sveltejs/adapter-static": "^3.0.0 || ^4.0.0", diff --git a/package.json b/package.json index 02ccdf6..f1d8821 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,8 @@ "name": "foyer", "private": true, "version": "0.1.0", - "description": "Next-generation lightweight homelab portal and service launchpad for the kleinbem fleet", + "license": "MIT", + "description": "Lightweight homelab portal and service launchpad", "type": "module", "engines": { "node": "^22.17.0 || >=24.0.0" @@ -11,8 +12,9 @@ "dev": "vite dev", "build": "vite build", "preview": "vite preview", - "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "prepare": "svelte-kit sync", + "test": "node --experimental-strip-types --import ./test/setup.ts --test 'test/**/*.test.ts'", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" }, "devDependencies": { @@ -32,6 +34,6 @@ "#lib/*": "./src/lib/*" }, "dependencies": { - "@kleinbem/web-config": "git+https://github.com/kleinbem/web-config.git#main" + "@kleinbem/web-config": "git+https://github.com/kleinbem/web-config.git#91a902ed6aec552ba103aa90b5597b1d2081148d" } } diff --git a/src/app.css b/src/app.css index 75a5100..119098b 100644 --- a/src/app.css +++ b/src/app.css @@ -1,29 +1,26 @@ @import "tailwindcss"; @import "@kleinbem/web-config/theme"; @import "@kleinbem/web-config/base.css"; -@import "@kleinbem/web-config/badges.css"; -/* App-level names for web-config's tokens; without these the *-brand, bg-bg-surface and - text-text-primary utilities generate no CSS. */ -@theme inline { - --color-bg-surface: var(--color-bg); - --color-bg-elevated: var(--color-surface); - --color-text-primary: var(--color-heading); - --color-border-subtle: var(--color-line); - --color-brand: var(--color-accent); -} +@source "../node_modules/@kleinbem/web-config"; @custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *, .dark, .dark *)); -/* Glassmorphism utility for modern card and navbar styling */ .glass-panel { - background: color-mix(in srgb, var(--color-bg-elevated, #18181b) 75%, transparent); + background: color-mix(in srgb, var(--color-surface, #151a21) 80%, transparent); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); - border: 1px solid var(--color-border-subtle, rgba(255, 255, 255, 0.08)); + border: 1px solid var(--color-line, rgba(255, 255, 255, 0.08)); +} + +dialog:modal { + overscroll-behavior: contain; } -.light .glass-panel, [data-theme="light"] .glass-panel { - background: color-mix(in srgb, #ffffff 80%, transparent); - border: 1px solid var(--color-border-subtle, rgba(0, 0, 0, 0.06)); +dialog::backdrop { + background: rgb(9 9 11 / 0.6); + backdrop-filter: blur(4px); + -webkit-backdrop-filter: blur(4px); + overflow: hidden; + overscroll-behavior: contain; } diff --git a/src/app.html b/src/app.html index 6c79349..d10c90c 100644 --- a/src/app.html +++ b/src/app.html @@ -5,18 +5,18 @@ - Foyer โ€” kleinbem fleet + Foyer %sveltekit.head% - +
%sveltekit.body%
diff --git a/src/lib/components/BookmarksSection.svelte b/src/lib/components/BookmarksSection.svelte index 2fb18a7..f798935 100644 --- a/src/lib/components/BookmarksSection.svelte +++ b/src/lib/components/BookmarksSection.svelte @@ -1,99 +1,76 @@ -
+ { + if (e.key === STORAGE_KEY) loadSaved(); + }} +/> + +
- - โญ +

+ Pinned & Quick Links - - +

+ {bookmarks.length}
{#if bookmarks.length === 0} -
- {#if showAddModal} -
{/if} diff --git a/src/lib/components/CategorySection.svelte b/src/lib/components/CategorySection.svelte index 4290ea0..7e22596 100644 --- a/src/lib/components/CategorySection.svelte +++ b/src/lib/components/CategorySection.svelte @@ -1,68 +1,43 @@ {#if services.length > 0}
- {getCategoryIcon(category)} -

+ +

{category}

- + ({services.length}) -
+
diff --git a/src/lib/components/CommandPalette.svelte b/src/lib/components/CommandPalette.svelte index f8e168c..66915df 100644 --- a/src/lib/components/CommandPalette.svelte +++ b/src/lib/components/CommandPalette.svelte @@ -1,158 +1,139 @@ - + {#if open} -
{/if} diff --git a/src/lib/components/Header.svelte b/src/lib/components/Header.svelte index bad84e1..2e87c90 100644 --- a/src/lib/components/Header.svelte +++ b/src/lib/components/Header.svelte @@ -1,77 +1,99 @@ -
+ { + if (!document.hidden) now = new Date(); + }} +/> + +
- -
- ๐Ÿ  -
+
+ +
-

- Foyer +

+ {title}

- - fleet - + {#if badge} + + {badge} + + {/if}
- + {#if subtitle} + + {/if}
- - -
- +
- - + {#if weather} + + {/if} - -
+
diff --git a/src/lib/components/HostBar.svelte b/src/lib/components/HostBar.svelte index 89c1fe9..644bdd4 100644 --- a/src/lib/components/HostBar.svelte +++ b/src/lib/components/HostBar.svelte @@ -1,77 +1,114 @@ -
-
-
- Fleet Conductors - - {FLEET_HOSTS.length} nodes +{#if hosts.length > 0} +
+
+
+ Hosts + + {hosts.length} {hosts.length === 1 ? 'node' : 'nodes'} + +
+
- -
-
- {#each FLEET_HOSTS as host} - {@const isSelected = selectedHost === host.id} -
- +

+ {host.role} +

+ - -
- {/each} -
-
+ {#if host.ip} + {@const ip = host.ip} + + {/if} +
+ {/each} +
+ +{/if} diff --git a/src/lib/components/HostFilter.svelte b/src/lib/components/HostFilter.svelte deleted file mode 100644 index 180290a..0000000 --- a/src/lib/components/HostFilter.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - -
- {#each hosts as h} - {@const active = selectedHost === h.id} - {@const count = h.id === 'all' ? counts.total : (counts[h.id] ?? 0)} - {#if h.id === 'all' || count > 0} - - {/if} - {/each} -
diff --git a/src/lib/components/LayoutToggle.svelte b/src/lib/components/LayoutToggle.svelte index 73147e4..b64c02d 100644 --- a/src/lib/components/LayoutToggle.svelte +++ b/src/lib/components/LayoutToggle.svelte @@ -15,15 +15,15 @@ } -
+
+{/snippet} + +{#if density === 'compact'} +
- - {service.icon} - +
-

- {service.name} -

- - {service.host} - +

{service.name}

+ {service.host}
-
- + {@render copyBtn(copied ? 'โœ“' : '๐Ÿ“‹', 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-muted hover:text-heading p-1 rounded transition-opacity text-[10px] font-mono')}
{:else if density === 'list'} - -
- - - {service.icon} - - +
+ +
-

- {service.name} -

- - {service.description} - +

{service.name}

+ {#if service.description} + {service.description} + {/if}
- -
- - {service.host} - - - {service.category} - + {service.host} + {service.category}
-
- - {networkBadge.icon} - - - + {@render netBadge(true)} - - - - - - - - + {@render copyBtn(copied ? 'โœ“' : '๐Ÿ“‹', 'text-muted hover:text-heading p-1 rounded transition-colors text-xs font-mono')}
{:else} - -
+
- - - {service.icon} - -
-

- {service.name} -

- - {service.host} - +
+ +
+

{service.name}

+ {service.host}
- -
+
- - {networkBadge.icon} - {networkBadge.label} - + {@render netBadge(false)}
- -

- {service.description} -

+ {#if service.description} +

{service.description}

+ {/if}
- -
- - {service.url.replace(/^https?:\/\//, '')} - -
- -
+
+ {displayUrl} + {@render copyBtn(copied ? 'โœ“ Copied' : 'Copy', 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-heading transition-opacity p-0.5')}
{/if} diff --git a/src/lib/components/StatusDot.svelte b/src/lib/components/StatusDot.svelte deleted file mode 100644 index a6e15d8..0000000 --- a/src/lib/components/StatusDot.svelte +++ /dev/null @@ -1,38 +0,0 @@ - - -
- - {label} -
diff --git a/src/lib/components/WeatherWidget.svelte b/src/lib/components/WeatherWidget.svelte index 0e4475f..e702191 100644 --- a/src/lib/components/WeatherWidget.svelte +++ b/src/lib/components/WeatherWidget.svelte @@ -1,66 +1,65 @@ {#if weather}
- {weather.icon} + {weather.temp}ยฐC
{:else if loading} -
- โ›… --ยฐC +
+ โ›… --ยฐC
{/if} diff --git a/src/lib/config.ts b/src/lib/config.ts new file mode 100644 index 0000000..de75741 --- /dev/null +++ b/src/lib/config.ts @@ -0,0 +1,220 @@ +import type { FooterLink, HostInfo, NetworkType, PortalConfig, ServiceItem, WeatherConfig } from './types'; + +export const DEFAULT_SEARCH_URL_TEMPLATE = 'https://duckduckgo.com/?q=%s'; + +export const DEFAULT_CATEGORY_ORDER = [ + 'Infrastructure', 'Identity', 'AI', 'AI Engineering', 'Dev', 'Apps', 'Documents', 'Security', 'Media' +]; + +export const DEFAULT_CATEGORY_ICONS: Record = { + Infrastructure: 'โšก', Identity: '๐Ÿ›ก๏ธ', AI: '๐Ÿค–', 'AI Engineering': '๐Ÿงฌ', + Dev: '๐Ÿ’ป', Apps: '๐Ÿ“ฑ', Documents: '๐Ÿ“', Security: '๐Ÿ”’', Media: '๐Ÿ“ป', Other: '๐Ÿ“ฆ' +}; + +export const DEFAULT_CONFIG: PortalConfig = { + title: 'Foyer', + subtitle: 'Self-hosted service launchpad', + welcomeTitle: 'Welcome home', + welcomeSubtitle: 'Configure /config.json to populate your hosts, services, and live health checks.', + hosts: [], + services: [], + categoryOrder: DEFAULT_CATEGORY_ORDER, + searchUrlTemplate: DEFAULT_SEARCH_URL_TEMPLATE, + footerLinks: [{ label: 'source', url: 'https://github.com/kleinbem-dev/foyer' }] +}; + +/** Allows only absolute http(s) URLs with a non-empty hostname. */ +export function isValidHttpUrl(candidate: string): boolean { + try { + const u = new URL(candidate); + return (u.protocol === 'http:' || u.protocol === 'https:') && u.hostname.length > 0; + } catch { + return false; + } +} + +/** Allows http(s) URLs or single-slash same-origin paths, rejecting protocol-relative and script schemes. */ +export function isSafePortalUrl(candidate: string): boolean { + if (candidate.startsWith('/') && !candidate.startsWith('//')) { + return !/[\s\0]/.test(candidate); + } + return isValidHttpUrl(candidate); +} + +function asNonEmptyString(val: unknown): string | undefined { + const trimmed = typeof val === 'string' ? val.trim() : ''; + return trimmed.length > 0 ? trimmed : undefined; +} + +function isNetworkType(val: unknown): val is NetworkType { + return val === 'public' || val === 'mesh' || val === 'lan'; +} + +function parseHosts(raw: unknown): HostInfo[] { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const hosts: HostInfo[] = []; + + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const obj = entry as Record; + const id = asNonEmptyString(obj.id); + const name = asNonEmptyString(obj.name) ?? id; + if (!id || !name || seen.has(id)) continue; + seen.add(id); + hosts.push({ + id, + name, + role: asNonEmptyString(obj.role) ?? 'Node', + ip: asNonEmptyString(obj.ip), + arch: asNonEmptyString(obj.arch), + icon: asNonEmptyString(obj.icon) + }); + } + return hosts; +} + +function parseServices(raw: unknown): ServiceItem[] { + if (!Array.isArray(raw)) return []; + const seen = new Set(); + const services: ServiceItem[] = []; + + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const obj = entry as Record; + const id = asNonEmptyString(obj.id); + const name = asNonEmptyString(obj.name); + const url = asNonEmptyString(obj.url); + if (!id || !name || !url || !isSafePortalUrl(url) || seen.has(id)) continue; + seen.add(id); + + const tags = Array.isArray(obj.tags) + ? obj.tags.map(asNonEmptyString).filter((t): t is string => t !== undefined) + : undefined; + + services.push({ + id, + name, + category: asNonEmptyString(obj.category) ?? 'Other', + icon: asNonEmptyString(obj.icon) ?? '๐Ÿ“ฆ', + description: typeof obj.description === 'string' ? obj.description.trim() : '', + url, + host: asNonEmptyString(obj.host) ?? 'local', + network: isNetworkType(obj.network) ? obj.network : 'lan', + gatusEndpoint: asNonEmptyString(obj.gatusEndpoint), + tags: tags && tags.length > 0 ? tags : undefined + }); + } + return services; +} + +function parseWeather(raw: unknown): WeatherConfig | undefined { + if (!raw || typeof raw !== 'object') return undefined; + const obj = raw as Record; + const lat = typeof obj.latitude === 'number' ? obj.latitude : Number.NaN; + const lon = typeof obj.longitude === 'number' ? obj.longitude : Number.NaN; + if (!Number.isFinite(lat) || lat < -90 || lat > 90) return undefined; + if (!Number.isFinite(lon) || lon < -180 || lon > 180) return undefined; + return { + latitude: lat, + longitude: lon, + timezone: asNonEmptyString(obj.timezone), + label: asNonEmptyString(obj.label) + }; +} + +function parseFooterLinks(raw: unknown): FooterLink[] | undefined { + if (!Array.isArray(raw)) return undefined; + const links: FooterLink[] = []; + for (const entry of raw) { + if (!entry || typeof entry !== 'object') continue; + const obj = entry as Record; + const label = asNonEmptyString(obj.label); + const url = asNonEmptyString(obj.url); + if (label && url && isSafePortalUrl(url)) links.push({ label, url }); + } + return links; +} + +/** + * Validates an untrusted JSON payload into a safe PortalConfig and deduplicates host/service IDs + * so Svelte keyed each-blocks cannot throw on duplicate keys. + */ +export function parsePortalConfig(raw: unknown): PortalConfig { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return structuredClone(DEFAULT_CONFIG); + } + const obj = raw as Record; + const gatusCandidate = asNonEmptyString(obj.gatusUrl); + const searchCandidate = asNonEmptyString(obj.searchUrlTemplate); + const categoryOrder = Array.isArray(obj.categoryOrder) + ? obj.categoryOrder.map(asNonEmptyString).filter((c): c is string => c !== undefined) + : DEFAULT_CATEGORY_ORDER; + + let categoryIcons: Record | undefined; + if (obj.categoryIcons && typeof obj.categoryIcons === 'object' && !Array.isArray(obj.categoryIcons)) { + categoryIcons = {}; + for (const [k, v] of Object.entries(obj.categoryIcons as Record)) { + const icon = asNonEmptyString(v); + if (k.trim() && icon) categoryIcons[k.trim()] = icon; + } + } + + return { + title: asNonEmptyString(obj.title) ?? DEFAULT_CONFIG.title, + badge: asNonEmptyString(obj.badge), + subtitle: asNonEmptyString(obj.subtitle), + welcomeTitle: asNonEmptyString(obj.welcomeTitle) ?? DEFAULT_CONFIG.welcomeTitle, + welcomeSubtitle: asNonEmptyString(obj.welcomeSubtitle), + hosts: parseHosts(obj.hosts), + services: parseServices(obj.services), + categoryOrder: categoryOrder.length > 0 ? categoryOrder : DEFAULT_CATEGORY_ORDER, + categoryIcons, + gatusUrl: gatusCandidate && isSafePortalUrl(gatusCandidate) ? gatusCandidate : undefined, + weather: parseWeather(obj.weather), + searchUrlTemplate: + searchCandidate && isValidHttpUrl(searchCandidate.replace('%s', 'test')) + ? searchCandidate + : DEFAULT_SEARCH_URL_TEMPLATE, + footerLinks: parseFooterLinks(obj.footerLinks) ?? DEFAULT_CONFIG.footerLinks + }; +} + +export async function loadPortalConfig( + configPath = './config.json', + signal?: AbortSignal +): Promise<{ config: PortalConfig; warning?: string }> { + try { + const timeout = AbortSignal.timeout(5000); + const res = await fetch(configPath, { + headers: { Accept: 'application/json' }, + cache: 'no-cache', + signal: signal ? AbortSignal.any([signal, timeout]) : timeout + }); + + if (res.status === 404) return { config: structuredClone(DEFAULT_CONFIG) }; + if (!res.ok) { + return { + config: structuredClone(DEFAULT_CONFIG), + warning: `Failed to load ${configPath} (HTTP ${res.status}); using default configuration.` + }; + } + + const json: unknown = await res.json(); + if (!json || typeof json !== 'object' || Array.isArray(json)) { + return { + config: structuredClone(DEFAULT_CONFIG), + warning: `${configPath} must contain a JSON object; using default configuration.` + }; + } + return { config: parsePortalConfig(json) }; + } catch (err) { + if (signal?.aborted) return { config: structuredClone(DEFAULT_CONFIG) }; + return { + config: structuredClone(DEFAULT_CONFIG), + warning: err instanceof SyntaxError + ? `Invalid JSON in ${configPath}; using default configuration.` + : `Failed to load ${configPath}; using default configuration.` + }; + } +} diff --git a/src/lib/data/gatus.ts b/src/lib/data/gatus.ts index 443a129..ea4b368 100644 --- a/src/lib/data/gatus.ts +++ b/src/lib/data/gatus.ts @@ -11,15 +11,35 @@ export interface EndpointStatus { }>; } +const ENDPOINTS_STATUS_PATH = '/api/v1/endpoints/statuses'; + +export function buildGatusStatusesUrl(gatusUrl: string): string { + const trimmed = gatusUrl.trim(); + const isRelative = trimmed.startsWith('/'); + const parsed = new URL(trimmed || ENDPOINTS_STATUS_PATH, 'http://foyer.local'); + const basePath = parsed.pathname.replace(/\/+$/, ''); + parsed.pathname = basePath.endsWith(ENDPOINTS_STATUS_PATH) + ? basePath + : `${basePath}${ENDPOINTS_STATUS_PATH}`; + return isRelative ? `${parsed.pathname}${parsed.search}${parsed.hash}` : parsed.toString(); +} + /** - * Fetch endpoint statuses from the fleet Gatus instance. - * Returns null when Gatus is unreachable, so callers can keep the last known state. + * Fetch endpoint statuses from a Gatus instance. + * Returns null when Gatus is unreachable or returns malformed data so callers can keep the last known state. */ -export async function fetchGatusStatuses(): Promise | null> { +export async function fetchGatusStatuses( + gatusUrl = ENDPOINTS_STATUS_PATH, + signal?: AbortSignal +): Promise | null> { try { - const res = await fetch('https://status.kleinbem.dev/api/v1/endpoints/statuses', { + const endpoint = buildGatusStatusesUrl(gatusUrl); + const timeout = AbortSignal.timeout(4000); + const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout; + + const res = await fetch(endpoint, { headers: { Accept: 'application/json' }, - signal: AbortSignal.timeout(4000) + signal: combinedSignal }); if (!res.ok) { @@ -34,52 +54,38 @@ export async function fetchGatusStatuses(): Promise if (!ep || typeof ep.name !== 'string') continue; const results = Array.isArray(ep.results) ? ep.results : []; const latest = results[results.length - 1]; - const status: HealthStatus = !latest - ? 'unknown' - : latest.success - ? 'healthy' - : 'down'; + const status: HealthStatus = !latest ? 'unknown' : latest.success ? 'healthy' : 'down'; - // Normalize keys for matching (e.g. "status", "dashboard", "authentik") const normName = ep.name.toLowerCase().replace(/[^a-z0-9]/g, ''); - map[normName] = status; + if (normName) map[normName] = status; map[ep.name.toLowerCase()] = status; - if (typeof ep.key === 'string' && ep.key) map[ep.key] = status; - - // Common aliases for fleet probes - if (normName === 'chat') { - map['openwebui'] = status; - map['open-webui'] = status; - } else if (normName === 'enteauthweb') { - map['enteweb'] = status; - map['ente-web'] = status; - map['ente'] = status; - } else if (normName === 'atticcache') { - map['attic'] = status; - } else if (normName === 'homeassistant') { - map['home-assistant'] = status; - map['ha'] = status; + if (typeof ep.key === 'string' && ep.key) { + map[ep.key] = status; + map[ep.key.toLowerCase()] = status; } } return map; } catch { - // Offline / CORS / unreachable return null; } } /** - * Health of one service: its Gatus endpoint, then its normalised id, then its raw id. + * Health of one service: its configured Gatus endpoint/key, then its normalised id, then its raw id. */ export function resolveHealth( service: Pick, healthMap: Record ): HealthStatus { - const normKey = service.id.toLowerCase().replace(/[^a-z0-9]/g, ''); + const endpointKey = service.gatusEndpoint?.trim(); + const normEndpoint = endpointKey?.toLowerCase().replace(/[^a-z0-9]/g, ''); + const normId = service.id.toLowerCase().replace(/[^a-z0-9]/g, ''); + return ( - (service.gatusEndpoint ? healthMap[service.gatusEndpoint] : undefined) ?? - healthMap[normKey] ?? + (endpointKey ? (healthMap[endpointKey] ?? healthMap[endpointKey.toLowerCase()]) : undefined) ?? + (normEndpoint ? healthMap[normEndpoint] : undefined) ?? + healthMap[normId] ?? healthMap[service.id] ?? 'unknown' ); diff --git a/src/lib/data/hosts.ts b/src/lib/data/hosts.ts deleted file mode 100644 index ced201a..0000000 --- a/src/lib/data/hosts.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { HostInfo } from '../types'; - -export const FLEET_HOSTS: HostInfo[] = [ - { - id: 'core-pi', - name: 'core-pi', - role: 'Gateway & Auth Conductor', - ip: '10.0.0.22', - arch: 'aarch64' - }, - { - id: 'nixos-nvme', - name: 'nixos-nvme', - role: 'Primary Workstation & Build Fleet', - ip: '10.0.0.20', - arch: 'x86_64' - }, - { - id: 'mac-mini', - name: 'mac-mini', - role: 'Media & LLM Inference Conductor', - ip: '10.0.0.23', - arch: 'aarch64' - }, - { - id: 'nasbook', - name: 'nasbook', - role: 'Storage & Persistent Vault', - ip: '10.0.0.21', - arch: 'x86_64' - }, - { - id: 'orin-nano', - name: 'orin-nano', - role: 'Edge AI & Acceleration', - ip: '10.0.0.24', - arch: 'aarch64' - }, - { - id: 'bpi-r4', - name: 'bpi-r4', - role: 'Fleet OpenWrt Router', - ip: '10.0.0.1', - arch: 'aarch64' - } -]; diff --git a/src/lib/data/services.ts b/src/lib/data/services.ts deleted file mode 100644 index e064b64..0000000 --- a/src/lib/data/services.ts +++ /dev/null @@ -1,346 +0,0 @@ -import type { ServiceItem } from '../types'; - -export const FLEET_SERVICES: ServiceItem[] = [ - // Identity - { - id: 'authentik', - name: 'Authentik', - category: 'Identity', - icon: '๐Ÿชช', - description: 'Shared identity provider (SSO, social login, persona OIDC).', - url: 'https://auth.kleinbem.dev', - host: 'core-pi', - network: 'public', - authRequired: false, - gatusEndpoint: 'authentik', - tags: ['sso', 'oidc', 'auth'] - }, - { - id: 'vaultwarden', - name: 'Vaultwarden', - category: 'Identity', - icon: '๐Ÿ”', - description: 'Self-hosted password manager for people & personas.', - url: 'https://vault.kleinbem.dev', - host: 'core-pi', - network: 'public', - authRequired: false, - gatusEndpoint: 'vaultwarden', - tags: ['passwords', 'bitwarden', 'security'] - }, - { - id: 'ente-web', - name: 'Ente Auth Web', - category: 'Identity', - icon: '๐Ÿ”‘', - description: 'End-to-end encrypted 2FA token manager web app.', - url: 'https://2fa.kleinbem.dev', - host: 'core-pi', - network: 'public', - authRequired: false, - gatusEndpoint: 'ente-web', - tags: ['2fa', 'totp', 'security'] - }, - - // Infrastructure - { - id: 'status', - name: 'Fleet Status', - category: 'Infrastructure', - icon: '๐ŸŸข', - description: 'Real-time Gatus fleet uptime and endpoint latency monitor.', - url: 'https://status.kleinbem.dev', - host: 'core-pi', - network: 'public', - authRequired: false, - gatusEndpoint: 'status', - tags: ['gatus', 'monitoring', 'uptime'] - }, - { - id: 'attic', - name: 'Attic UI', - category: 'Infrastructure', - icon: '๐Ÿ“ฆ', - description: 'Deduplicated Nix binary cache explorer & store inspector.', - url: 'https://attic.kleinbem.dev', - host: 'core-pi', - network: 'mesh', - authRequired: false, - gatusEndpoint: 'attic', - tags: ['nix', 'cache', 'nar', 'attic', 'store'] - }, - { - id: 'ntfy', - name: 'ntfy Push', - category: 'Infrastructure', - icon: '๐Ÿ“ฃ', - description: 'Pub/sub notifications and fleet deploy signals.', - url: 'https://ntfy.kleinbem.dev', - host: 'core-pi', - network: 'public', - authRequired: false, - gatusEndpoint: 'ntfy', - tags: ['alerts', 'push', 'notifications'] - }, - { - id: 'stalwart', - name: 'Stalwart Mail', - category: 'Infrastructure', - icon: '๐Ÿ“ฌ', - description: 'Persona-fleet mail server (JMAP/IMAP/SMTP).', - url: 'https://mail.kleinbem.dev', - host: 'mac-mini', - network: 'mesh', - authRequired: true, - tags: ['email', 'jmap', 'mail'] - }, - { - id: 'garage-ui', - name: 'Garage UI', - category: 'Infrastructure', - icon: '๐Ÿชฃ', - description: 'Distributed S3 object storage dashboard and cluster manager.', - url: 'https://garage.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - tags: ['s3', 'storage', 'backup'] - }, - { - id: 'cockpit', - name: 'Cockpit', - category: 'Infrastructure', - icon: '๐ŸŽ›๏ธ', - description: 'Web-based host management interface for Linux.', - url: 'https://cockpit.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: true, - tags: ['admin', 'host', 'system'] - }, - { - id: 'syncthing', - name: 'Syncthing', - category: 'Infrastructure', - icon: '๐Ÿ”„', - description: 'Continuous decentralized file synchronization.', - url: 'https://syncthing.kleinbem.dev', - host: 'nasbook', - network: 'mesh', - authRequired: true, - tags: ['sync', 'files', 'storage'] - }, - { - id: 'cups', - name: 'Cups Printing', - category: 'Infrastructure', - icon: '๐Ÿ–จ๏ธ', - description: 'Fleet print server and network queue management.', - url: 'http://10.85.48.115:631', - host: 'core-pi', - network: 'lan', - authRequired: false, - tags: ['print', 'cups'] - }, - - // AI & AI Engineering - { - id: 'open-webui', - name: 'Open WebUI', - category: 'AI', - icon: '๐Ÿค–', - description: 'Full-featured AI chat interface powered by local Ollama models.', - url: 'https://chat.kleinbem.dev', - host: 'mac-mini', - network: 'public', - authRequired: false, - gatusEndpoint: 'open-webui', - tags: ['llm', 'chat', 'ollama'] - }, - { - id: 'cadre', - name: 'Cadre Teammates', - category: 'AI Engineering', - icon: '๐Ÿฆพ', - description: 'Private AI teammates on your own compute (Goose over local inference).', - url: 'https://cadre.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: true, - tags: ['agents', 'goose', 'mesh-llm'] - }, - { - id: 'revue', - name: 'Revue AI', - category: 'Dev', - icon: '๐Ÿ‘๏ธ', - description: 'Nix-native AI PR review daemon for Forgejo & GitHub.', - url: 'https://revue.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - gatusEndpoint: 'revue', - tags: ['code-review', 'ci', 'forgejo'] - }, - { - id: 'buzz', - name: 'Buzz Workspace', - category: 'AI Engineering', - icon: '๐Ÿ', - description: 'Team chat, git forge, and agent collaborative workspace.', - url: 'https://buzz.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: true, - tags: ['chat', 'nostr', 'agents'] - }, - { - id: 'comfyui', - name: 'ComfyUI', - category: 'AI Engineering', - icon: '๐ŸŽจ', - description: 'Node-based modular visual image and video generation.', - url: 'http://10.85.46.108:8188', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - tags: ['sd', 'diffusion', 'images'] - }, - { - id: 'langflow', - name: 'Langflow', - category: 'AI Engineering', - icon: '๐ŸŒŠ', - description: 'Visual UI builder for multi-agent workflows and RAG pipelines.', - url: 'http://10.85.46.109:7860', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - tags: ['rag', 'agents', 'flow'] - }, - { - id: 'langfuse', - name: 'Langfuse', - category: 'AI Engineering', - icon: '๐Ÿ“Š', - description: 'Open source LLM engineering platform, tracing, and evals.', - url: 'http://10.85.46.110:3000', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - tags: ['observability', 'telemetry', 'tracing'] - }, - - // Dev - { - id: 'forgejo', - name: 'Forgejo', - category: 'Dev', - icon: '๐ŸŒณ', - description: 'Self-hosted Git forge mirroring fleet GitHub repos.', - url: 'https://git.kleinbem.dev', - host: 'core-pi', - network: 'mesh', - authRequired: false, - tags: ['git', 'forge', 'repo'] - }, - { - id: 'code-server', - name: 'Code Server', - category: 'Dev', - icon: '๐Ÿ’ป', - description: 'VS Code in a hardened container reachable from browser.', - url: 'https://code.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: true, - tags: ['ide', 'vscode', 'editor'] - }, - { - id: 'caido', - name: 'Caido Security', - category: 'Security', - icon: '๐Ÿ›ก๏ธ', - description: 'Headless web security proxy and penetration testing daemon.', - url: 'https://caido.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: true, - tags: ['proxy', 'audit', 'security'] - }, - - // Apps & Media - { - id: 'home-assistant', - name: 'Home Assistant', - category: 'Apps', - icon: '๐Ÿก', - description: 'Open-source home automation hub and device dashboard.', - url: 'https://hass.kleinbem.dev', - host: 'core-pi', - network: 'mesh', - authRequired: false, - gatusEndpoint: 'home-assistant', - tags: ['smarthome', 'iot', 'automation'] - }, - { - id: 'n8n', - name: 'n8n Automation', - category: 'Apps', - icon: '๐Ÿ“ก', - description: 'Fair-code workflow automation tool connecting fleet APIs.', - url: 'https://n8n.kleinbem.dev', - host: 'nixos-nvme', - network: 'mesh', - authRequired: false, - tags: ['workflows', 'automation', 'webhooks'] - }, - { - id: 'miniflux', - name: 'Miniflux', - category: 'Media', - icon: '๐Ÿ“ฐ', - description: 'Minimalist, fast, and opinionated RSS feed reader.', - url: 'https://news.kleinbem.dev', - host: 'nasbook', - network: 'public', - authRequired: false, - tags: ['rss', 'news', 'feeds'] - }, - { - id: 'paperless', - name: 'Paperless-ngx', - category: 'Documents', - icon: '๐Ÿ“„', - description: 'Document archive with automatic OCR, indexing, and tags.', - url: 'https://paperless.kleinbem.dev', - host: 'nasbook', - network: 'mesh', - authRequired: true, - tags: ['docs', 'ocr', 'archive'] - }, - { - id: 'qbittorrent', - name: 'qBittorrent', - category: 'Apps', - icon: '๐Ÿ“ฅ', - description: 'Headless BitTorrent client with Web UI.', - url: 'https://torrents.kleinbem.dev', - host: 'nasbook', - network: 'mesh', - authRequired: true, - tags: ['torrents', 'downloads'] - } -]; - -export const CATEGORY_ORDER: ServiceItem['category'][] = [ - 'Infrastructure', - 'Identity', - 'AI', - 'AI Engineering', - 'Dev', - 'Apps', - 'Documents', - 'Security', - 'Media' -]; diff --git a/src/lib/index.ts b/src/lib/index.ts index 7781a32..4a77445 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -1,3 +1,4 @@ export * from './types'; -export * from './data/services'; +export * from './config'; +export * from './portal'; export * from './data/gatus'; diff --git a/src/lib/portal.ts b/src/lib/portal.ts new file mode 100644 index 0000000..29f458f --- /dev/null +++ b/src/lib/portal.ts @@ -0,0 +1,259 @@ +import { + DEFAULT_CATEGORY_ICONS, + DEFAULT_CATEGORY_ORDER, + DEFAULT_SEARCH_URL_TEMPLATE, + isValidHttpUrl +} from './config'; +import { resolveHealth } from './data/gatus'; +import type { HealthStatus, HostInfo, PinnedBookmark, ServiceItem, WeatherConfig } from './types'; + +export type NetworkFilter = 'all' | 'public' | 'mesh' | 'issues'; + +export interface PaletteEntry { + id: string; + kind: 'service' | 'bookmark' | 'host'; + name: string; + description: string; + icon: string; + category: string; + host?: string; + network?: string; + url?: string; + ip?: string; + tags?: string[]; +} + +export interface WeatherSnapshot { + temp: number; + condition: string; + icon: string; +} + +export function isValidBookmark(item: unknown): item is PinnedBookmark { + if (!item || typeof item !== 'object') return false; + const bm = item as Record; + return ( + typeof bm.id === 'string' && bm.id.trim().length > 0 && + typeof bm.name === 'string' && bm.name.trim().length > 0 && + typeof bm.icon === 'string' && bm.icon.trim().length > 0 && + typeof bm.createdAt === 'number' && Number.isFinite(bm.createdAt) && + typeof bm.url === 'string' && isValidHttpUrl(bm.url) + ); +} + +export function parseStoredBookmarks(raw: string | null): PinnedBookmark[] { + if (!raw) return []; + try { + const parsed: unknown = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + const seen = new Set(); + const valid: PinnedBookmark[] = []; + for (const item of parsed) { + if (isValidBookmark(item) && !seen.has(item.id)) { + seen.add(item.id); + valid.push(item); + } + } + return valid; + } catch { + return []; + } +} + +export function createBookmark( + nameInput: string, + urlInput: string, + iconInput: string +): { bookmark?: PinnedBookmark; error?: string } { + const name = nameInput.trim(); + const rawUrl = urlInput.trim(); + if (!name || !rawUrl) return { error: 'Name and URL are required' }; + + const hasScheme = + /^[a-z][a-z0-9+.-]*:/i.test(rawUrl) && !/^[a-z0-9.-]+:\d{1,5}(?:[/?#]|$)/i.test(rawUrl); + const url = hasScheme ? rawUrl : `https://${rawUrl}`; + if (!isValidHttpUrl(url)) return { error: 'Please enter a valid HTTP or HTTPS URL' }; + + const id = typeof crypto?.randomUUID === 'function' + ? `bm-${crypto.randomUUID()}` + : `bm-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + + return { + bookmark: { id, name, url, icon: iconInput.trim() || '๐Ÿ”—', createdAt: Date.now() } + }; +} + +export function buildPaletteEntries( + services: ServiceItem[], + bookmarks: PinnedBookmark[] = [], + hosts: HostInfo[] = [] +): PaletteEntry[] { + return [ + ...services.map((s): PaletteEntry => ({ + id: `svc:${s.id}`, kind: 'service', name: s.name, description: s.description, + icon: s.icon, category: s.category, host: s.host, network: s.network, url: s.url, tags: s.tags + })), + ...bookmarks.map((bm): PaletteEntry => ({ + id: `bm:${bm.id}`, kind: 'bookmark', name: bm.name, + description: bm.url.replace(/^https?:\/\//, ''), icon: bm.icon, category: 'Pinned', url: bm.url + })), + ...hosts.map((h): PaletteEntry => ({ + id: `host:${h.id}`, kind: 'host', name: h.name, + description: h.ip ? `${h.role} ยท ${h.ip}` : h.role, + icon: h.icon ?? '๐Ÿ–ฅ๏ธ', category: 'Host', host: h.id, ip: h.ip, tags: h.arch ? [h.arch] : undefined + })) + ]; +} + +/** Multi-token search with `#host`, `@category`, and `!network` prefix filters. */ +export function filterPaletteEntries(entries: PaletteEntry[], rawQuery: string): PaletteEntry[] { + const raw = rawQuery.trim(); + if (!raw) return entries; + if (raw.startsWith('>')) return []; + + const hostFilters: string[] = []; + const catFilters: string[] = []; + const netFilters: string[] = []; + const words: string[] = []; + + for (const token of raw.toLowerCase().split(/\s+/)) { + if (token.startsWith('#') && token.length > 1) hostFilters.push(token.slice(1)); + else if (token.startsWith('@') && token.length > 1) catFilters.push(token.slice(1)); + else if (token.startsWith('!') && token.length > 1) netFilters.push(token.slice(1)); + else if (!['#', '@', '!'].includes(token)) words.push(token); + } + + return entries.filter((entry) => { + const host = entry.host?.toLowerCase() ?? ''; + const cat = entry.category.toLowerCase(); + const net = entry.network?.toLowerCase() ?? ''; + + if (hostFilters.some((f) => !host.includes(f))) return false; + if (catFilters.some((f) => !cat.includes(f))) return false; + if (netFilters.some((f) => !net.includes(f))) return false; + if (words.length === 0) return true; + + const fields = [entry.name, entry.description, entry.category, host, net, ...(entry.tags ?? [])] + .map((s) => s.toLowerCase()); + return words.every((w) => fields.some((f) => f.includes(w))); + }); +} + +export function formatWebSearchUrl(term: string, template = DEFAULT_SEARCH_URL_TEMPLATE): string | null { + const clean = term.trim(); + if (!clean) return null; + const encoded = encodeURIComponent(clean); + const url = template.includes('%s') ? template.replaceAll('%s', encoded) : `${template}${encoded}`; + return isValidHttpUrl(url) ? url : null; +} + +export function filterServices( + services: ServiceItem[], + selectedHost: string | null, + networkFilter: NetworkFilter, + healthMap: Record +): ServiceItem[] { + return services.filter((s) => { + if (selectedHost !== null && s.host !== selectedHost) return false; + if (networkFilter === 'public') return s.network === 'public'; + if (networkFilter === 'mesh') return s.network === 'mesh'; + if (networkFilter === 'issues') { + const h = resolveHealth(s, healthMap); + return h === 'down' || h === 'degraded'; + } + return true; + }); +} + +export function groupServicesByCategory( + services: ServiceItem[], + categoryOrder: string[] = DEFAULT_CATEGORY_ORDER +): Array<{ category: string; services: ServiceItem[] }> { + const buckets = new Map(); + for (const svc of services) { + const list = buckets.get(svc.category); + if (list) list.push(svc); + else buckets.set(svc.category, [svc]); + } + + const groups: Array<{ category: string; services: ServiceItem[] }> = []; + const visited = new Set(); + for (const cat of [...categoryOrder, ...buckets.keys()]) { + if (visited.has(cat)) continue; + const inCat = buckets.get(cat); + if (inCat?.length) { + groups.push({ category: cat, services: inCat }); + visited.add(cat); + } + } + return groups; +} + +export function getCategoryIcon(category: string, customIcons?: Record): string { + return customIcons?.[category] ?? DEFAULT_CATEGORY_ICONS[category] ?? '๐Ÿ“ฆ'; +} + +export function computeServiceMetrics( + services: ServiceItem[], + healthMap: Record +) { + let publicCount = 0; + let meshCount = 0; + let healthyCount = 0; + let issueCount = 0; + const hostCounts: Record = Object.create(null); + + for (const s of services) { + hostCounts[s.host] = (hostCounts[s.host] ?? 0) + 1; + if (s.network === 'public') publicCount++; + else if (s.network === 'mesh') meshCount++; + + const status = resolveHealth(s, healthMap); + if (status === 'healthy') healthyCount++; + else if (status === 'down' || status === 'degraded') issueCount++; + } + return { totalCount: services.length, publicCount, meshCount, healthyCount, issueCount, hostCounts }; +} + +export function describeWeatherCode(code: number): { icon: string; condition: string } { + if (code === 0) return { icon: 'โ˜€๏ธ', condition: 'Clear' }; + if (code === 1 || code === 2) return { icon: '๐ŸŒค๏ธ', condition: 'Partly Cloudy' }; + if (code === 3) return { icon: 'โ˜๏ธ', condition: 'Overcast' }; + if (code >= 45 && code <= 48) return { icon: '๐ŸŒซ๏ธ', condition: 'Foggy' }; + if (code >= 51 && code <= 67) return { icon: '๐ŸŒง๏ธ', condition: 'Rain' }; + if (code >= 71 && code <= 77) return { icon: '๐ŸŒจ๏ธ', condition: 'Snow' }; + if (code >= 80 && code <= 82) return { icon: '๐ŸŒฆ๏ธ', condition: 'Showers' }; + if (code >= 95) return { icon: 'โ›ˆ๏ธ', condition: 'Thunderstorm' }; + return { icon: 'โ›…', condition: 'Fair' }; +} + +export async function fetchWeather( + config: WeatherConfig, + signal?: AbortSignal +): Promise { + try { + const params = new URLSearchParams({ + latitude: String(config.latitude), + longitude: String(config.longitude), + current: 'temperature_2m,weather_code', + timezone: config.timezone ?? 'auto' + }); + const timeout = AbortSignal.timeout(5000); + const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params.toString()}`, { + headers: { Accept: 'application/json' }, + signal: signal ? AbortSignal.any([signal, timeout]) : timeout + }); + if (!res.ok) return null; + + const cur = ((await res.json()) as { current?: { temperature_2m?: unknown; weather_code?: unknown } } | null)?.current; + if ( + typeof cur?.temperature_2m !== 'number' || !Number.isFinite(cur.temperature_2m) || + typeof cur.weather_code !== 'number' || !Number.isFinite(cur.weather_code) + ) { + return null; + } + return { temp: Math.round(cur.temperature_2m), ...describeWeatherCode(cur.weather_code) }; + } catch { + return null; + } +} diff --git a/src/lib/types.ts b/src/lib/types.ts index 8dfa8a5..9e25189 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -1,19 +1,5 @@ -export type ServiceCategory = - | 'Infrastructure' - | 'AI Engineering' - | 'AI' - | 'Identity' - | 'Dev' - | 'Apps' - | 'Documents' - | 'Security' - | 'Media' - | 'Other'; - export type NetworkType = 'public' | 'mesh' | 'lan'; -export type HostNode = 'core-pi' | 'nixos-nvme' | 'mac-mini' | 'nasbook' | 'orin-nano' | 'bpi-r4'; - export type HealthStatus = 'healthy' | 'degraded' | 'down' | 'unknown' | 'checking'; export type LayoutDensity = 'comfortable' | 'compact' | 'list'; @@ -23,37 +9,55 @@ export interface PinnedBookmark { name: string; url: string; icon: string; - description?: string; - category?: string; createdAt: number; } export interface HostInfo { - id: HostNode; + id: string; name: string; role: string; - ip: string; - arch: string; + ip?: string; + arch?: string; + icon?: string; } export interface ServiceItem { id: string; name: string; - category: ServiceCategory; + category: string; icon: string; description: string; url: string; - host: HostNode; + host: string; network: NetworkType; - authRequired: boolean; gatusEndpoint?: string; tags?: string[]; } -export interface GatusStatus { - key: string; - name: string; - group: string; - status: HealthStatus; - durationMs?: number; +export interface WeatherConfig { + latitude: number; + longitude: number; + timezone?: string; + label?: string; +} + +export interface FooterLink { + label: string; + url: string; +} + +export interface PortalConfig { + title: string; + badge?: string; + subtitle?: string; + welcomeTitle: string; + welcomeSubtitle?: string; + hosts: HostInfo[]; + services: ServiceItem[]; + categoryOrder?: string[]; + categoryIcons?: Record; + gatusUrl?: string; + weather?: WeatherConfig; + searchUrlTemplate?: string; + footerLinks?: FooterLink[]; } diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index ea18736..b93e9ba 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -1,35 +1,7 @@ -
-
(commandPaletteOpen = true)} /> - -
- {@render children()} -
- - - - -
+{@render children()} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 75d3e2c..d3c70d8 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,99 +1,85 @@ -
- -
-
-

- Welcome home -

-

- Central gateway to self-hosted compute, storage, and AI agents. -

- {#if healthStale} -

- Gatus unreachable{healthUpdatedAt - ? ` ยท health as of ${healthUpdatedAt.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' })}` - : ' ยท no health data yet'} -

- {/if} -
+ { + if (!document.hidden && config.gatusUrl) { + refreshHealth(config.gatusUrl, AbortSignal.timeout(4000)); + } + }} +/> + +
+
(commandPaletteOpen = true)} + /> + +
+ {#if configWarning} + + {/if} -
- - - - - - - {#if metrics.issueCount > 0} - - {/if} -
-
- - - - - - - - -
-
- - - {#if selectedHost !== 'all' || networkFilter !== 'all'} - +
+
+

{config.welcomeTitle}

+ {#if config.welcomeSubtitle} +

{config.welcomeSubtitle}

+ {/if} + {#if healthStale} +

+ Gatus unreachable{healthUpdatedAt + ? ` ยท health as of ${healthUpdatedAt.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' })}` + : ' ยท no health data yet'} +

+ {/if} +
+ + {#if config.services.length > 0} +
+ {#each filterPills as pill (pill.id)} + + {/each} +
{/if}
- - -
- - -
- {#if groupedServices.length === 0} -
- No services match the current filters. + + + + {#if config.services.length > 0} +
+
+ {#if selectedHost !== null || networkFilter !== 'all'} + + Showing {filteredServices.length} of {config.services.length} services + + + {/if} +
+
- {:else} - {#each groupedServices as group (group.category)} - - {/each} {/if} -
+ +
+ {#if config.services.length === 0} +
+

No services configured

+

+ Serve a /config.json file at the web root to populate hosts, service categories, Gatus health checks, and weather. +

+
+ {:else if groupedServices.length === 0} +
No services match the current filters.
+ {:else} + {#each groupedServices as group (group.category)} + + {/each} + {/if} +
+ + +
+
+ {config.title.toLowerCase()} + {#each config.footerLinks ?? [] as link, i (`${i}:${link.url}`)} + + + {link.label} + + {/each} +
+
+ + (selectedHost = selectedHost === hostId ? null : hostId)} + bind:open={commandPaletteOpen} + />
diff --git a/static/config.json b/static/config.json new file mode 100644 index 0000000..d21c862 --- /dev/null +++ b/static/config.json @@ -0,0 +1,14 @@ +{ + "title": "Foyer", + "subtitle": "Self-hosted service launchpad", + "welcomeTitle": "Welcome home", + "welcomeSubtitle": "Provide a /config.json file in your web root to configure hosts, services, and health probes.", + "hosts": [], + "services": [], + "footerLinks": [ + { + "label": "source", + "url": "https://github.com/kleinbem-dev/foyer" + } + ] +} diff --git a/test/app-shell.test.ts b/test/app-shell.test.ts new file mode 100644 index 0000000..15193cc --- /dev/null +++ b/test/app-shell.test.ts @@ -0,0 +1,124 @@ +import * as assert from 'node:assert/strict'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { describe, it } from 'node:test'; +import { runInNewContext } from 'node:vm'; + +function extractHeadInitScript(html: string): string { + const match = html.match(/[\s\S]*?'), false); + assert.equal(isValidHttpUrl('file:///etc/passwd'), false); + assert.equal(isValidHttpUrl('//evil.example.test'), false); + assert.equal(isValidHttpUrl('not a url'), false); + }); + + it('accepts single-slash root-relative paths in isSafePortalUrl while blocking protocol-relative URLs', () => { + assert.equal(isSafePortalUrl('/grafana/'), true); + assert.equal(isSafePortalUrl('//evil.example.test'), false); + assert.equal(isSafePortalUrl('/bad path with spaces'), false); + assert.equal(isSafePortalUrl('javascript:void(0)'), false); + }); +}); + +describe('parsePortalConfig & static/config.json', () => { + it('parses shipped static/config.json cleanly with zero personal defaults', () => { + const raw = JSON.parse(readFileSync('static/config.json', 'utf8')); + const cfg = parsePortalConfig(raw); + assert.equal(cfg.title, 'Foyer'); + assert.deepEqual(cfg.hosts, []); + assert.deepEqual(cfg.services, []); + assert.equal(cfg.gatusUrl, undefined); + assert.equal(cfg.weather, undefined); + }); + + it('falls back safely on non-object payloads, sanitizes invalid URLs, and deduplicates IDs', () => { + for (const bad of [null, undefined, 'str', 123, []]) { + assert.deepEqual(parsePortalConfig(bad), DEFAULT_CONFIG); + } + + const cfg = parsePortalConfig({ + title: ' Homelab ', + badge: 'prod', + gatusUrl: 'javascript:alert(1)', + searchUrlTemplate: 'javascript:%s', + weather: { latitude: 999, longitude: 10 }, + hosts: [ + { id: 'node-a', name: 'Node A', role: 'Compute', ip: '192.0.2.10', arch: 'x86_64' }, + { id: 'node-a', name: 'Duplicate Node', role: 'Ignored' }, + { id: '' } + ], + services: [ + { + id: 'svc-1', + name: 'Grafana', + category: 'Infra', + url: 'https://grafana.example.test', + host: 'node-a', + network: 'mesh', + tags: ['metrics', ' ', 42] + }, + { + id: 'svc-1', + name: 'Duplicate Grafana', + url: 'https://dup.example.test' + }, + { + id: 'xss', + name: 'Bad Scheme', + url: 'javascript:alert(1)' + } + ], + footerLinks: [ + { label: 'Docs', url: '/docs' }, + { label: 'Bad', url: 'data:text/plain,bad' } + ] + }); + + assert.equal(cfg.title, 'Homelab'); + assert.equal(cfg.badge, 'prod'); + assert.equal(cfg.gatusUrl, undefined); + assert.equal(cfg.searchUrlTemplate, DEFAULT_CONFIG.searchUrlTemplate); + assert.equal(cfg.weather, undefined); + assert.equal(cfg.hosts.length, 1); + assert.equal(cfg.hosts[0].name, 'Node A'); + assert.equal(cfg.services.length, 1); + assert.deepEqual(cfg.services[0].tags, ['metrics']); + assert.deepEqual(cfg.footerLinks, [{ label: 'Docs', url: '/docs' }]); + }); + + it('accepts valid boundary weather coordinates', () => { + const cfg = parsePortalConfig({ + weather: { latitude: -53.8, longitude: 151.2, timezone: 'UTC', label: 'Harbor' } + }); + assert.deepEqual(cfg.weather, { + latitude: -53.8, + longitude: 151.2, + timezone: 'UTC', + label: 'Harbor' + }); + }); +}); + +describe('loadPortalConfig', () => { + it('returns default config silently on 404 and surfaces warning on invalid JSON or 500', async () => { + globalThis.fetch = (async () => new Response('Not Found', { status: 404 })) as typeof fetch; + const missing = await loadPortalConfig(); + assert.equal(missing.warning, undefined); + assert.deepEqual(missing.config, DEFAULT_CONFIG); + + globalThis.fetch = (async () => new Response('Server Error', { status: 500 })) as typeof fetch; + const serverErr = await loadPortalConfig(); + assert.match(serverErr.warning ?? '', /HTTP 500/); + + globalThis.fetch = (async () => + new Response('{broken json', { status: 200 })) as typeof fetch; + const badJson = await loadPortalConfig(); + assert.match(badJson.warning ?? '', /Invalid JSON/); + + globalThis.fetch = (async () => { + throw new TypeError('Failed to fetch'); + }) as typeof fetch; + const netErr = await loadPortalConfig(); + assert.match(netErr.warning ?? '', /Failed to load/); + + const callerAbort = new AbortController(); + callerAbort.abort(); + const cancelled = await loadPortalConfig('./config.json', callerAbort.signal); + assert.equal(cancelled.warning, undefined); + }); +}); + +describe('Gatus URL normalization', () => { + it('appends /api/v1/endpoints/statuses once without duplicating path or trailing slashes', () => { + assert.equal( + buildGatusStatusesUrl('https://status.example.test/'), + 'https://status.example.test/api/v1/endpoints/statuses' + ); + assert.equal( + buildGatusStatusesUrl('https://status.example.test/api/v1/endpoints/statuses'), + 'https://status.example.test/api/v1/endpoints/statuses' + ); + assert.equal( + buildGatusStatusesUrl('/gatus?view=public'), + '/gatus/api/v1/endpoints/statuses?view=public' + ); + assert.equal( + buildGatusStatusesUrl('https://status.example.test/api/v1/endpoints/statuses?view=public'), + 'https://status.example.test/api/v1/endpoints/statuses?view=public' + ); + }); +}); + +describe('Bookmarks validation & creation', () => { + it('rejects partial/malformed stored bookmarks and deduplicates IDs', () => { + assert.equal(isValidBookmark({ id: '1', name: 'A', url: 'https://a.example' }), false); + const raw = JSON.stringify([ + { id: 'b1', name: 'Docs', url: 'https://docs.example.test', icon: '๐Ÿ“š', createdAt: 100 }, + { id: 'b1', name: 'Dup', url: 'https://dup.example.test', icon: '๐Ÿ“š', createdAt: 101 }, + { id: 'b2', name: 'XSS', url: 'javascript:alert(1)', icon: '๐Ÿ’€', createdAt: 102 }, + { id: 'b3', name: 'MissingIcon', url: 'https://ok.example.test', createdAt: 103 } + ]); + const parsed = parseStoredBookmarks(raw); + assert.equal(parsed.length, 1); + assert.equal(parsed[0].id, 'b1'); + assert.deepEqual(parseStoredBookmarks('{invalid'), []); + }); + + it('normalizes bare domains and host:port to https:// and rejects non-http schemes in createBookmark', () => { + const ok = createBookmark('Grafana', 'grafana.example.test', ''); + assert.ok(ok.bookmark); + assert.equal(ok.bookmark.url, 'https://grafana.example.test'); + assert.equal(ok.bookmark.icon, '๐Ÿ”—'); + + const withPort = createBookmark('Local Grafana', 'grafana.example.test:3000/dash', '๐Ÿ“Š'); + assert.ok(withPort.bookmark); + assert.equal(withPort.bookmark.url, 'https://grafana.example.test:3000/dash'); + + const xss = createBookmark('Bad', 'javascript:alert(1)', 'โญ'); + assert.equal(xss.bookmark, undefined); + assert.match(xss.error ?? '', /valid HTTP or HTTPS/); + }); +}); + +describe('Palette multi-token search, filtering, grouping & weather', () => { + const services = [ + { + id: 'attic', + name: 'Attic Cache', + category: 'Infrastructure', + icon: '๐Ÿ“ฆ', + description: 'Binary cache store', + url: 'https://cache.example.test', + host: 'node-1', + network: 'mesh' as const, + tags: ['nix', 'nar'] + }, + { + id: 'auth', + name: 'Authentik', + category: 'Identity', + icon: '๐Ÿชช', + description: 'SSO login', + url: 'https://auth.example.test', + host: 'node-2', + network: 'public' as const, + tags: ['oidc'] + } + ]; + const bookmarks = [ + { + id: 'bm-1', + name: 'Router UI', + url: 'https://192.0.2.1', + icon: '๐Ÿ“ก', + createdAt: 1 + } + ]; + const hosts = [{ id: 'node-1', name: 'node-1', role: 'Builder', ip: '192.0.2.10', arch: 'x86_64' }]; + + it('searches across services, pinned bookmarks, and hosts with multi-token & prefix filters', () => { + const entries = buildPaletteEntries(services, bookmarks, hosts); + assert.equal(entries.length, 4); + + // Multi-word cross-field query ("attic" in name + "nix" in tags) + const multi = filterPaletteEntries(entries, 'attic nix'); + assert.equal(multi.length, 1); + assert.equal(multi[0].name, 'Attic Cache'); + + // Pinned bookmark match + const pinned = filterPaletteEntries(entries, '@pinned router'); + assert.equal(pinned.length, 1); + assert.equal(pinned[0].kind, 'bookmark'); + + // Host prefix + network prefix + assert.equal(filterPaletteEntries(entries, '#node-2 !public').length, 1); + assert.equal(filterPaletteEntries(entries, '>duckduckgo query').length, 0); + }); + + it('formats web search URLs safely and blocks unsafe templates', () => { + assert.equal( + formatWebSearchUrl('nix flake', 'https://duckduckgo.com/?q=%s'), + 'https://duckduckgo.com/?q=nix%20flake' + ); + assert.equal(formatWebSearchUrl(' '), null); + assert.equal(formatWebSearchUrl('test', 'javascript:%s'), null); + }); + + it('computes metrics, filters issues, and preserves custom category ordering', () => { + const health = { attic: 'down' as const, auth: 'healthy' as const }; + const metrics = computeServiceMetrics(services, health); + assert.equal(metrics.totalCount, 2); + assert.equal(metrics.publicCount, 1); + assert.equal(metrics.meshCount, 1); + assert.equal(metrics.healthyCount, 1); + assert.equal(metrics.issueCount, 1); + assert.equal(metrics.hostCounts['node-1'], 1); + assert.equal(metrics.hostCounts.total, undefined); + + const totalHostMetrics = computeServiceMetrics( + [{ ...services[0], host: 'total' }], + health + ); + assert.equal(totalHostMetrics.totalCount, 1); + assert.equal(totalHostMetrics.hostCounts.total, 1); + + const issues = filterServices(services, null, 'issues', health); + assert.equal(issues.length, 1); + assert.equal(issues[0].id, 'attic'); + + const allIdHost = filterServices( + [...services, { ...services[0], id: 'edge-svc', host: 'all' }], + 'all', + 'all', + health + ); + assert.equal(allIdHost.length, 1); + assert.equal(allIdHost[0].id, 'edge-svc'); + + const groups = groupServicesByCategory(services, ['Identity']); + assert.deepEqual( + groups.map((g) => g.category), + ['Identity', 'Infrastructure'] + ); + }); + + it('guards fetchWeather against missing or non-finite Open-Meteo fields', async () => { + assert.equal(describeWeatherCode(0).condition, 'Clear'); + assert.equal(describeWeatherCode(95).condition, 'Thunderstorm'); + + globalThis.fetch = (async () => + new Response(JSON.stringify({ current: { temperature_2m: 'bad', weather_code: 0 } }), { + status: 200 + })) as typeof fetch; + assert.equal(await fetchWeather({ latitude: 50, longitude: 8 }), null); + + globalThis.fetch = (async () => + new Response(JSON.stringify({ current: { temperature_2m: 18.6, weather_code: 2 } }), { + status: 200 + })) as typeof fetch; + assert.deepEqual(await fetchWeather({ latitude: 50, longitude: 8 }), { + temp: 19, + condition: 'Partly Cloudy', + icon: '๐ŸŒค๏ธ' + }); + }); +}); diff --git a/test/env.d.ts b/test/env.d.ts new file mode 100644 index 0000000..c7d7f99 --- /dev/null +++ b/test/env.d.ts @@ -0,0 +1,68 @@ +declare module 'node:test' { + export function describe(name: string, fn: () => void | Promise): Promise; + export function it(name: string, fn: () => void | Promise): Promise; + export function beforeEach(fn: () => void | Promise): void; + export function afterEach(fn: () => void | Promise): void; +} + +declare module 'node:assert/strict' { + export function equal(actual: unknown, expected: T, message?: string): asserts actual is T; + export function deepEqual(actual: unknown, expected: T, message?: string): asserts actual is T; + export function ok(value: unknown, message?: string): asserts value; + export function match(string: string, regexp: RegExp, message?: string): void; + export function doesNotMatch(string: string, regexp: RegExp, message?: string): void; + export function throws(block: () => unknown, error?: RegExp | ErrorConstructor, message?: string): void; + export function rejects( + block: (() => Promise) | Promise, + error?: RegExp | ErrorConstructor, + message?: string + ): Promise; +} + +declare module 'node:fs' { + export function existsSync(path: string): boolean; + export function readFileSync(path: string, encoding: 'utf8'): string; + export function readdirSync(path: string, options?: { recursive?: boolean }): string[]; +} + +declare module 'node:path' { + export function dirname(path: string): string; + export function resolve(...paths: string[]): string; +} + +declare module 'node:url' { + export function fileURLToPath(url: string | URL): string; + export function pathToFileURL(path: string): URL; +} + +declare module 'node:module' { + export interface ResolveContext { + conditions?: string[]; + parentURL?: string; + } + export interface ResolveResult { + shortCircuit?: boolean; + url: string; + } + export interface LoadResult { + format: string; + shortCircuit?: boolean; + source: string; + } + export function registerHooks(hooks: { + resolve?: ( + specifier: string, + context: ResolveContext, + nextResolve: (specifier: string, context?: ResolveContext) => ResolveResult + ) => ResolveResult; + load?: ( + url: string, + context: Record, + nextLoad: (url: string, context?: Record) => LoadResult + ) => LoadResult; + }): void; +} + +declare module 'node:vm' { + export function runInNewContext(code: string, contextObject?: Record): unknown; +} diff --git a/test/gatus.test.ts b/test/gatus.test.ts new file mode 100644 index 0000000..2a84f01 --- /dev/null +++ b/test/gatus.test.ts @@ -0,0 +1,114 @@ +import * as assert from 'node:assert/strict'; +import { afterEach, describe, it } from 'node:test'; +import { fetchGatusStatuses, resolveHealth } from '#lib/data/gatus'; + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +describe('fetchGatusStatuses', () => { + it('maps healthy, down, and empty-result endpoints using latest probe result', async () => { + globalThis.fetch = (async () => + new Response( + JSON.stringify([ + { + name: 'Authentik', + group: 'Identity', + key: 'identity_authentik', + results: [ + { success: false, duration: 100, timestamp: '2026-11-13T10:00:00Z' }, + { success: true, duration: 42, timestamp: '2026-11-13T10:03:00Z' } + ] + }, + { + name: 'Home Assistant', + group: 'Apps', + key: 'apps_home-assistant', + results: [{ success: false, duration: 500, timestamp: '2026-11-13T10:03:00Z' }] + }, + { + name: 'Pending Probe', + group: 'Infra', + key: 'infra_pending', + results: [] + } + ]), + { status: 200, headers: { 'Content-Type': 'application/json' } } + )) as typeof fetch; + + const map = await fetchGatusStatuses(); + assert.ok(map !== null); + assert.equal(map.authentik, 'healthy'); + assert.equal(map.identity_authentik, 'healthy'); + assert.equal(map.homeassistant, 'down'); + assert.equal(map['home assistant'], 'down'); + assert.equal(map['apps_home-assistant'], 'down'); + assert.equal(map.pendingprobe, 'unknown'); + }); + + it('returns null on non-2xx HTTP status so caller retains stale map', async () => { + globalThis.fetch = (async () => new Response('Bad Gateway', { status: 502 })) as typeof fetch; + const map = await fetchGatusStatuses(); + assert.equal(map, null); + }); + + it('returns null when network request rejects or aborts', async () => { + globalThis.fetch = (async () => { + throw new DOMException('The operation was aborted', 'TimeoutError'); + }) as typeof fetch; + const map = await fetchGatusStatuses(); + assert.equal(map, null); + }); + + it('rejects non-array JSON bodies and skips malformed array entries without throwing', async () => { + for (const invalidBody of ['{}', 'null', '"text"', '42']) { + globalThis.fetch = (async () => + new Response(invalidBody, { status: 200 })) as typeof fetch; + assert.equal(await fetchGatusStatuses(), null); + } + + globalThis.fetch = (async () => + new Response( + JSON.stringify([ + null, + 42, + { name: 123 }, + { name: 'No Results Field', group: 'Test', key: '' }, + { name: 'Malformed Results', group: 'Test', key: 'bad_res', results: 'invalid' }, + { + name: 'Grafana', + group: 'Infra', + key: 'infra_grafana', + results: [{ success: true, duration: 15, timestamp: '2026-11-13T10:00:00Z' }] + } + ]), + { status: 200 } + )) as typeof fetch; + + const map = await fetchGatusStatuses(); + assert.ok(map !== null); + assert.equal(map.noresultsfield, 'unknown'); + assert.equal(map.malformedresults, 'unknown'); + assert.equal(map.grafana, 'healthy'); + }); +}); + +describe('resolveHealth', () => { + it('prioritizes explicit gatusEndpoint over normalized id and raw id, defaulting to unknown', () => { + const healthMap = { + custom_key: 'healthy' as const, + myservice: 'down' as const, + 'raw-id': 'degraded' as const + }; + + assert.equal( + resolveHealth({ id: 'my-service', gatusEndpoint: 'custom_key' }, healthMap), + 'healthy' + ); + assert.equal(resolveHealth({ id: 'my-service' }, healthMap), 'down'); + assert.equal(resolveHealth({ id: 'raw-id' }, { 'raw-id': 'degraded' }), 'degraded'); + assert.equal(resolveHealth({ id: 'unlisted' }, healthMap), 'unknown'); + }); +}); diff --git a/test/setup.ts b/test/setup.ts new file mode 100644 index 0000000..2633485 --- /dev/null +++ b/test/setup.ts @@ -0,0 +1,82 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { registerHooks } from 'node:module'; +import { dirname, resolve as resolvePath } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { compile, compileModule } from 'svelte/compiler'; + +const ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), '..'); +const ROOT_PKG_URL = pathToFileURL(resolvePath(ROOT, 'package.json')).href; + +function tryFileWithTs(candidatePath: string): string | null { + if (existsSync(candidatePath) && !candidatePath.endsWith('/')) { + return pathToFileURL(candidatePath).href; + } + for (const ext of ['.ts', '.js', '/index.ts', '/index.js']) { + if (existsSync(candidatePath + ext)) { + return pathToFileURL(candidatePath + ext).href; + } + } + return null; +} + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier === '#lib') { + return { shortCircuit: true, url: pathToFileURL(resolvePath(ROOT, 'src/lib/index.ts')).href }; + } + if (specifier.startsWith('#lib/')) { + const hit = tryFileWithTs(resolvePath(ROOT, 'src/lib', specifier.slice('#lib/'.length))); + if (hit) return { shortCircuit: true, url: hit }; + } + if ( + (specifier.startsWith('./') || specifier.startsWith('../')) && + context.parentURL?.startsWith('file:') + ) { + const parentDir = dirname(fileURLToPath(context.parentURL)); + const hit = tryFileWithTs(resolvePath(parentDir, specifier)); + if (hit) return { shortCircuit: true, url: hit }; + } + const withSvelte = { + ...context, + conditions: [...(context.conditions ?? []), 'svelte'] + }; + try { + return nextResolve(specifier, withSvelte); + } catch (err) { + if (!specifier.startsWith('.') && !specifier.startsWith('/') && context.parentURL !== ROOT_PKG_URL) { + return nextResolve(specifier, { ...withSvelte, parentURL: ROOT_PKG_URL }); + } + throw err; + } + }, + load(url, context, nextLoad) { + if (url.endsWith('.svelte.js') || url.endsWith('.svelte.ts')) { + const filename = fileURLToPath(url); + const source = readFileSync(filename, 'utf8'); + const compiled = compileModule(source, { + filename, + generate: 'server' + }); + return { + format: 'module', + shortCircuit: true, + source: compiled.js.code + }; + } + if (url.endsWith('.svelte')) { + const filename = fileURLToPath(url); + const source = readFileSync(filename, 'utf8'); + const compiled = compile(source, { + filename, + generate: 'server', + runes: filename.includes('node_modules') ? undefined : true + }); + return { + format: 'module', + shortCircuit: true, + source: compiled.js.code + }; + } + return nextLoad(url, context); + } +}); diff --git a/tsconfig.json b/tsconfig.json index 448d448..42f8a7b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,21 +2,12 @@ "extends": "$app/tsconfig", "compilerOptions": { "strict": true, - "rootDirs": [ - ".", - "./.svelte-kit/types" - ], + "rootDirs": [".", "./.svelte-kit/types"], "paths": { "#lib": ["./src/lib/index.ts"], "#lib/*": ["./src/lib/*"] } }, - "include": [ - "src", - "test", - "*" - ], - "exclude": [ - "src/service-worker" - ] + "include": ["src", "test", "*"], + "exclude": ["src/service-worker"] } diff --git a/vite.config.ts b/vite.config.ts index 6483d57..c557cb1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,32 +1,9 @@ -import adapter from '@sveltejs/adapter-static'; -import { sveltekit } from '@sveltejs/kit/vite'; -import tailwindcss from '@tailwindcss/vite'; -import { defineConfig } from 'vite'; +import { defineWebConfig } from '@kleinbem/web-config'; -export default defineConfig({ - plugins: [ - tailwindcss(), - sveltekit({ - adapter: adapter({ - fallback: '200.html', - pages: 'build', - assets: 'build', - strict: true - }), - compilerOptions: { - experimental: { - async: true - }, - fragments: 'html' - }, - dynamicCompileOptions({ filename }) { - if (!filename.includes('node_modules')) { - return { runes: true }; - } - }, - experimental: { - forkPreloads: true - } - }) - ] +export default defineWebConfig({ + adapterOptions: { + fallback: '200.html', + pages: 'build', + assets: 'build' + } });