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('/\\outside.example.test'), 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('parses shared pinned links, defaulting the icon and dropping unsafe or duplicate entries', () => {
+ const cfg = parsePortalConfig({
+ links: [
+ { name: 'Docs', url: 'https://docs.example.test', icon: '๐' },
+ { name: 'Wiki', url: '/wiki' },
+ { name: 'Docs again', url: 'https://docs.example.test' },
+ { name: 'Bad', url: 'javascript:alert(1)' },
+ { url: 'https://nameless.example.test' }
+ ]
+ });
+ assert.deepEqual(cfg.links, [
+ { id: 'cfg:https://docs.example.test', name: 'Docs', url: 'https://docs.example.test', icon: '๐' },
+ { id: 'cfg:/wiki', name: 'Wiki', url: '/wiki', icon: '๐' }
+ ]);
+ assert.equal(parsePortalConfig({ links: [] }).links, undefined);
+ });
+
+ 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..aa34332
--- /dev/null
+++ b/test/gatus.test.ts
@@ -0,0 +1,236 @@
+import * as assert from 'node:assert/strict';
+import { afterEach, describe, it } from 'node:test';
+import { fetchGatusSnapshot, fetchGatusStatuses, resolveDetail, 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');
+ });
+});
+
+describe('fetchGatusSnapshot', () => {
+ const NS = 1e6;
+ function respondWith(endpoints: unknown) {
+ globalThis.fetch = (async () => new Response(JSON.stringify(endpoints), { status: 200 })) as typeof fetch;
+ }
+
+ it('reports response time, check time and history of a healthy endpoint', async () => {
+ respondWith([
+ {
+ name: 'Grafana',
+ key: 'infra_grafana',
+ results: [
+ { success: false, duration: 5 * NS, timestamp: '2026-11-13T10:00:00Z' },
+ { success: true, duration: 83.4 * NS, timestamp: '2026-11-13T10:03:00Z' }
+ ]
+ }
+ ]);
+ const snapshot = await fetchGatusSnapshot();
+ assert.ok(snapshot);
+ assert.deepEqual(snapshot.details.grafana, {
+ name: 'Grafana',
+ status: 'healthy',
+ history: [false, true],
+ checkedAt: '2026-11-13T10:03:00Z',
+ responseMs: 83
+ });
+ assert.equal(snapshot.details.infra_grafana, snapshot.details.grafana);
+ assert.equal(snapshot.statuses.grafana, 'healthy');
+ });
+
+ it('gives the reason and start of the current failing run', async () => {
+ respondWith([
+ {
+ name: 'Paperless',
+ results: [
+ { success: true, duration: NS, timestamp: '2026-11-13T10:00:00Z' },
+ {
+ success: false, duration: NS, timestamp: '2026-11-13T10:03:00Z',
+ conditionResults: [{ condition: '[STATUS] (502) == 200', success: false }]
+ },
+ {
+ success: false, duration: NS, timestamp: '2026-11-13T10:06:00Z',
+ errors: ['dial tcp: connection refused'],
+ conditionResults: [
+ { condition: '[CONNECTED] == true', success: false },
+ { condition: '[RESPONSE_TIME] < 3000', success: true }
+ ]
+ }
+ ]
+ },
+ {
+ name: 'Conditions Only',
+ results: [
+ {
+ success: false, duration: NS, timestamp: '2026-11-13T10:06:00Z',
+ conditionResults: [
+ { condition: '[STATUS] (503) == 200', success: false },
+ { condition: '[BODY].ok == true', success: false },
+ { condition: '[RESPONSE_TIME] < 3000', success: true }
+ ]
+ }
+ ]
+ }
+ ]);
+ const snapshot = await fetchGatusSnapshot();
+ assert.ok(snapshot);
+ const paperless = snapshot.details.paperless;
+ assert.equal(paperless.status, 'down');
+ assert.equal(paperless.reason, 'dial tcp: connection refused');
+ assert.equal(paperless.downSince, '2026-11-13T10:03:00Z');
+ assert.deepEqual(paperless.history, [true, false, false]);
+
+ // Every result in the window failed: the run started before it.
+ const conditionsOnly = snapshot.details.conditionsonly;
+ assert.equal(conditionsOnly.reason, '[STATUS] (503) == 200; [BODY].ok == true');
+ assert.equal(conditionsOnly.downSince, undefined);
+ });
+
+ it('keeps the last 20 results, truncates long reasons and ignores malformed fields', async () => {
+ const results = Array.from({ length: 30 }, (_, i) => ({
+ success: i % 2 === 0, duration: NS, timestamp: `2026-11-13T10:${String(i).padStart(2, '0')}:00Z`
+ }));
+ respondWith([
+ { name: 'Long History', results },
+ {
+ name: 'Odd Fields',
+ results: [
+ null,
+ { success: 'yes' },
+ { success: false, duration: 'slow', timestamp: 'not a date', errors: ['x'.repeat(500), 7] }
+ ]
+ }
+ ]);
+ const snapshot = await fetchGatusSnapshot();
+ assert.ok(snapshot);
+ assert.equal(snapshot.details.longhistory.history.length, 20);
+ assert.equal(snapshot.details.longhistory.history.at(-1), false);
+
+ const odd = snapshot.details.oddfields;
+ assert.equal(odd.status, 'down');
+ assert.deepEqual(odd.history, [false]);
+ assert.equal(odd.responseMs, undefined);
+ assert.equal(odd.checkedAt, undefined);
+ assert.equal(odd.reason?.length, 160);
+ assert.ok(odd.reason?.endsWith('โฆ'));
+ });
+
+ it('returns null when Gatus is unreachable', async () => {
+ globalThis.fetch = (async () => new Response('', { status: 502 })) as typeof fetch;
+ assert.equal(await fetchGatusSnapshot(), null);
+ });
+});
+
+describe('resolveDetail', () => {
+ it('finds a service by its configured endpoint, then by id', () => {
+ const grafana = { name: 'Grafana', status: 'healthy' as const, history: [true] };
+ assert.equal(resolveDetail({ id: 'monitoring', gatusEndpoint: 'Grafana' }, { grafana }), grafana);
+ assert.equal(resolveDetail({ id: 'grafana' }, { grafana }), grafana);
+ assert.equal(resolveDetail({ id: 'other' }, { grafana }), undefined);
+ });
+});
diff --git a/test/hub.test.ts b/test/hub.test.ts
new file mode 100644
index 0000000..0b71f11
--- /dev/null
+++ b/test/hub.test.ts
@@ -0,0 +1,259 @@
+import * as assert from 'node:assert/strict';
+import { afterEach, describe, it } from 'node:test';
+import { render } from 'svelte/server';
+import AttentionPanel from '#lib/components/AttentionPanel.svelte';
+import CategorySection from '#lib/components/CategorySection.svelte';
+import HostBar from '#lib/components/HostBar.svelte';
+import ServiceCard from '#lib/components/ServiceCard.svelte';
+import { loadPortalConfig, parseCachedConfig, parsePortalConfig } from '#lib/config';
+import {
+ computeServiceMetrics, describeHealth, filterPaletteEntries, formatRelativeTime, formatResponseTime, isTypeToSearchKey
+} from '#lib/portal';
+import type { PaletteEntry } from '#lib/portal';
+import type { AttentionItem, EndpointDetail, ServiceItem } from '#lib/types';
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const NOW = new Date('2026-11-16T12:00:00Z');
+
+const service: ServiceItem = {
+ id: 'paperless', name: 'Paperless', category: 'Documents', icon: '๐', description: 'Document archive.',
+ url: 'https://paperless.example.test', host: 'nasbook', network: 'mesh'
+};
+
+const healthyDetail: EndpointDetail = {
+ name: 'Paperless', status: 'healthy', history: [true, false, true, true], responseMs: 83,
+ checkedAt: '2026-11-16T11:58:00Z'
+};
+
+const downDetail: EndpointDetail = {
+ name: 'Paperless', status: 'down', history: [true, false, false], responseMs: 12,
+ checkedAt: '2026-11-16T11:59:30Z', downSince: '2026-11-16T09:00:00Z', reason: 'connection refused'
+};
+
+describe('formatRelativeTime', () => {
+ it('uses minutes, hours and days, and is empty for missing, invalid or future times', () => {
+ assert.equal(formatRelativeTime('2026-11-16T11:59:30Z', NOW), 'just now');
+ assert.equal(formatRelativeTime('2026-11-16T11:55:00Z', NOW), '5 min ago');
+ assert.equal(formatRelativeTime('2026-11-16T09:00:00Z', NOW), '3 h ago');
+ assert.equal(formatRelativeTime('2026-11-14T13:00:00Z', NOW), '47 h ago');
+ assert.equal(formatRelativeTime('2026-11-13T12:00:00Z', NOW), '3 d ago');
+ assert.equal(formatRelativeTime(undefined, NOW), '');
+ assert.equal(formatRelativeTime('soon', NOW), '');
+ assert.equal(formatRelativeTime('2026-11-16T12:05:00Z', NOW), '');
+ });
+});
+
+describe('filterPaletteEntries ranking', () => {
+ const entry = (name: string, description = ''): PaletteEntry => ({
+ id: name, kind: 'service', name, description, icon: '๐ฆ', category: 'Apps'
+ });
+ const entries = [
+ entry('Buzz', 'Team chat with pairing relay'),
+ entry('Status', 'Fleet uptime page'),
+ entry('Nix Detour', 'Nixpkgs patch tracker'),
+ entry('Paperless-ngx', 'Document archive'),
+ entry('Grafana', 'Dashboards'),
+ entry('Spa Control', 'Pool')
+ ];
+ const names = (query: string) => filterPaletteEntries(entries, query).map((e) => e.name);
+
+ it('puts name matches before description matches, prefixes first', () => {
+ assert.deepEqual(names('pa'), ['Paperless-ngx', 'Spa Control', 'Buzz', 'Status', 'Nix Detour']);
+ assert.deepEqual(names('det'), ['Nix Detour']);
+ });
+
+ it('keeps the configured order without search words and among equal matches', () => {
+ assert.deepEqual(names(''), entries.map((e) => e.name));
+ assert.deepEqual(names('@apps'), entries.map((e) => e.name));
+ // All four match "t" in the name only as a later letter or word start: order as configured.
+ assert.deepEqual(names('tr'), ['Spa Control', 'Nix Detour']);
+ assert.deepEqual(names('s'), ['Status', 'Spa Control', 'Paperless-ngx', 'Buzz', 'Nix Detour', 'Grafana']);
+ });
+});
+
+describe('formatResponseTime', () => {
+ it('never shows 0 ms and switches to seconds from one second on', () => {
+ assert.equal(formatResponseTime(0), '<1 ms');
+ assert.equal(formatResponseTime(83), '83 ms');
+ assert.equal(formatResponseTime(999), '999 ms');
+ assert.equal(formatResponseTime(1240), '1.2 s');
+ });
+});
+
+describe('describeHealth', () => {
+ it('summarises a healthy, a failing and an unchecked service', () => {
+ assert.equal(describeHealth('healthy', healthyDetail, NOW), 'Operational ยท 83 ms ยท checked 2 min ago');
+ assert.equal(
+ describeHealth('down', downDetail, NOW),
+ 'Offline ยท connection refused ยท since 3 h ago ยท checked just now'
+ );
+ assert.equal(describeHealth('unknown', undefined, NOW), 'No health check');
+ });
+});
+
+describe('isTypeToSearchKey', () => {
+ const key = (k: string, mods: Partial = {}) =>
+ ({ key: k, ctrlKey: false, metaKey: false, altKey: false, isComposing: false, ...mods }) as KeyboardEvent;
+
+ it('accepts single letters and digits, also non-ASCII ones', () => {
+ for (const k of ['a', 'Z', '7', 'รค', 'รฉ']) assert.equal(isTypeToSearchKey(key(k)), true, k);
+ });
+
+ it('rejects named keys, punctuation, space, shortcuts and IME composition', () => {
+ for (const k of ['Enter', 'Tab', 'F5', 'ArrowDown', ' ', '.', '?', 'Dead']) {
+ assert.equal(isTypeToSearchKey(key(k)), false, k);
+ }
+ assert.equal(isTypeToSearchKey(key('r', { ctrlKey: true })), false);
+ assert.equal(isTypeToSearchKey(key('l', { metaKey: true })), false);
+ assert.equal(isTypeToSearchKey(key('d', { altKey: true })), false);
+ assert.equal(isTypeToSearchKey(key('k', { isComposing: true })), false);
+ });
+});
+
+describe('computeServiceMetrics host health', () => {
+ it('marks a host down when any of its services is, healthy when all checked ones are', () => {
+ const svc = (id: string, host: string): ServiceItem => ({ ...service, id, host });
+ const metrics = computeServiceMetrics(
+ [svc('a', 'mixed'), svc('b', 'mixed'), svc('c', 'fine'), svc('d', 'fine'), svc('e', 'unchecked')],
+ { a: 'healthy', b: 'down', c: 'healthy' }
+ );
+ assert.equal(metrics.hostHealth.mixed, 'down');
+ assert.equal(metrics.hostHealth.fine, 'healthy');
+ assert.equal(metrics.hostHealth.unchecked, undefined);
+ assert.equal(metrics.hostHealth.toString, undefined);
+
+ const downFirst = computeServiceMetrics([svc('b', 'h'), svc('a', 'h')], { a: 'healthy', b: 'down' });
+ assert.equal(downFirst.hostHealth.h, 'down');
+ });
+});
+
+describe('config: attention feed, type-to-search and the cached copy', () => {
+ it('accepts a safe attentionUrl and an explicit typeToSearch only', () => {
+ const on = parsePortalConfig({ attentionUrl: '/attention.json', typeToSearch: true });
+ assert.equal(on.attentionUrl, '/attention.json');
+ assert.equal(on.typeToSearch, true);
+
+ const off = parsePortalConfig({ attentionUrl: 'javascript:alert(1)', typeToSearch: 'yes' });
+ assert.equal(off.attentionUrl, undefined);
+ assert.equal(off.typeToSearch, false);
+ assert.equal(parsePortalConfig({ attentionUrl: '//evil.example.test/feed' }).attentionUrl, undefined);
+ });
+
+ it('returns the raw body with a loaded config, and none with the default', async () => {
+ const body = JSON.stringify({ title: 'Lab', links: [{ name: 'Docs', url: 'https://docs.example.test' }] });
+ globalThis.fetch = (async () => new Response(body)) as typeof fetch;
+ const loaded = await loadPortalConfig();
+ assert.equal(loaded.raw, body);
+ assert.equal(loaded.config.title, 'Lab');
+
+ // Parsing the cached body again gives the same config: link ids are not prefixed twice.
+ assert.deepEqual(parseCachedConfig(loaded.raw ?? null), loaded.config);
+
+ globalThis.fetch = (async () => new Response('', { status: 404 })) as typeof fetch;
+ assert.equal((await loadPortalConfig()).raw, undefined);
+ globalThis.fetch = (async () => new Response('[1]')) as typeof fetch;
+ assert.equal((await loadPortalConfig()).raw, undefined);
+ });
+
+ it('ignores a missing or damaged cached copy', () => {
+ for (const bad of [null, '', '{broken', '[]', '"text"', 'null']) assert.equal(parseCachedConfig(bad), null);
+ });
+});
+
+describe('ServiceCard health detail', () => {
+ it('shows response time, recent checks and a descriptive tooltip when healthy', () => {
+ const { body } = render(ServiceCard, { props: { service, health: 'healthy', detail: healthyDetail } });
+ assert.match(body, /83 ms/);
+ assert.match(body, /3 of 4 recent checks passed/);
+ assert.match(body, /title="Operational ยท 83 ms ยท checked/);
+ });
+
+ it('shows why a service is down, without a response time', () => {
+ const { body } = render(ServiceCard, { props: { service, health: 'down', detail: downDetail } });
+ assert.match(body, /connection refused/);
+ assert.match(body, /1 of 3 recent checks passed/);
+ assert.doesNotMatch(body, /12 ms/);
+ });
+
+ it('renders as before without detail, in every density', () => {
+ for (const density of ['comfortable', 'compact', 'list'] as const) {
+ const { body } = render(ServiceCard, { props: { service, density } });
+ assert.match(body, /title="No health check"/);
+ assert.doesNotMatch(body, /recent checks passed/);
+ }
+ });
+
+ it('escapes a failure reason that contains markup', () => {
+ const detail: EndpointDetail = { ...downDetail, reason: '
' };
+ const { body } = render(ServiceCard, { props: { service, health: 'down', detail } });
+ assert.doesNotMatch(body, /
{
+ const { body } = render(CategorySection, {
+ props: {
+ category: 'Documents', services: [service],
+ healthMap: { paperless: 'down' }, healthDetails: { paperless: downDetail }
+ }
+ });
+ assert.match(body, /connection refused/);
+ });
+});
+
+describe('HostBar health', () => {
+ it('labels hosts with checked services and leaves the others unmarked', () => {
+ const { body } = render(HostBar, {
+ props: {
+ hosts: [
+ { id: 'up', name: 'up-host', role: 'Node' },
+ { id: 'bad', name: 'bad-host', role: 'Node' },
+ { id: 'none', name: 'quiet-host', role: 'Node' }
+ ],
+ health: { up: 'healthy', bad: 'down' }
+ }
+ });
+ assert.equal(body.match(/All checked services up/g)?.length, 3);
+ assert.equal(body.match(/Has services that are down/g)?.length, 3);
+ assert.equal(body.match(/role="status"/g)?.length, 2);
+ });
+});
+
+describe('AttentionPanel', () => {
+ const item = (n: number, extra: Partial = {}): AttentionItem => ({
+ id: `i${n}`, title: `Item ${n}`, severity: 'info', ...extra
+ });
+
+ it('renders nothing without items', () => {
+ assert.doesNotMatch(render(AttentionPanel, { props: { items: [] } }).body, / {
+ const items = [
+ item(1, {
+ severity: 'critical', url: 'https://example.test/1', detail: 'connection refused', source: 'nasbook'
+ }),
+ ...[2, 3, 4, 5, 6, 7].map((n) => item(n))
+ ];
+ const { body } = render(AttentionPanel, { props: { items } });
+ assert.match(body, /Needs attention/);
+ assert.match(body, /href="https:\/\/example\.test\/1"/);
+ assert.match(body, /rel="noopener noreferrer"/);
+ assert.match(body, /connection refused/);
+ assert.match(body, /nasbook/);
+ assert.match(body, /Item 5/);
+ assert.doesNotMatch(body, /Item 6/);
+ assert.match(body, /Show 2 more/);
+ assert.match(body, /border-status-danger-border/);
+ });
+
+ it('renders an item without a URL as plain text', () => {
+ const { body } = render(AttentionPanel, { props: { items: [item(1)] } });
+ assert.doesNotMatch(body, / void>();
+ const doc = {
+ hidden,
+ addEventListener: (_type: 'visibilitychange', l: () => void) => void listeners.add(l),
+ removeEventListener: (_type: 'visibilitychange', l: () => void) => void listeners.delete(l)
+ };
+ return {
+ doc: doc as VisibilitySource,
+ listeners,
+ show() {
+ doc.hidden = false;
+ for (const l of listeners) l();
+ },
+ hide() {
+ doc.hidden = true;
+ for (const l of listeners) l();
+ }
+ };
+}
+
+/** A loader whose requests stay pending until the test settles them. */
+function deferredLoader() {
+ const calls: Array<{ signal: AbortSignal; resolve: (value: string) => void }> = [];
+ const load = (signal: AbortSignal) =>
+ new Promise((resolve) => {
+ calls.push({ signal, resolve });
+ });
+ return { calls, load };
+}
+
+const settle = () => new Promise((r) => setTimeout(r, 0));
+const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+describe('startPolling', () => {
+ it('loads at once, then on every interval, and stops when told', async () => {
+ const { doc } = fakeDocument();
+ const results: number[] = [];
+ let n = 0;
+ const stop = startPolling(async () => ++n, (v) => results.push(v), 15, doc);
+ await settle();
+ assert.deepEqual(results, [1]);
+
+ await wait(80);
+ assert.ok(results.length >= 3, `expected repeated loads, got ${results.length}`);
+
+ stop();
+ const seen = results.length;
+ await wait(60);
+ assert.equal(results.length, seen);
+ });
+
+ it('does not start a second request while one is in flight', async () => {
+ const { doc, show } = fakeDocument();
+ const { calls, load } = deferredLoader();
+ const stop = startPolling(load, () => {}, 10, doc);
+ await wait(50);
+ show();
+ assert.equal(calls.length, 1);
+
+ calls[0].resolve('done');
+ await wait(40);
+ assert.ok(calls.length >= 2);
+ stop();
+ });
+
+ it('a stopped poller aborts its request, drops the late result, and does not block its successor', async () => {
+ const { doc } = fakeDocument();
+ const first = deferredLoader();
+ const second = deferredLoader();
+ const results: string[] = [];
+
+ const stopFirst = startPolling(first.load, (v) => results.push(v), 60_000, doc);
+ stopFirst();
+ assert.equal(first.calls[0].signal.aborted, true);
+
+ // The successor fetches immediately although the first request has not settled.
+ const stopSecond = startPolling(second.load, (v) => results.push(v), 60_000, doc);
+ assert.equal(second.calls.length, 1);
+
+ first.calls[0].resolve('stale');
+ second.calls[0].resolve('fresh');
+ await settle();
+ assert.deepEqual(results, ['fresh']);
+ stopSecond();
+ });
+
+ it('waits while the page is hidden and refreshes when it is shown again', async () => {
+ const page = fakeDocument(true);
+ const results: string[] = [];
+ const stop = startPolling(async () => 'value', (v) => results.push(v), 60_000, page.doc);
+ await settle();
+ assert.deepEqual(results, []);
+
+ page.show();
+ await settle();
+ assert.deepEqual(results, ['value']);
+
+ page.hide();
+ await settle();
+ assert.deepEqual(results, ['value']);
+
+ stop();
+ assert.equal(page.listeners.size, 0);
+ page.show();
+ await settle();
+ assert.deepEqual(results, ['value']);
+ });
+
+ it('survives a loader that throws', async () => {
+ const { doc } = fakeDocument();
+ const results: string[] = [];
+ let fail = true;
+ const stop = startPolling(
+ async () => {
+ if (fail) throw new Error('boom');
+ return 'ok';
+ },
+ (v) => results.push(v),
+ 10,
+ doc
+ );
+ await settle();
+ assert.deepEqual(results, []);
+ fail = false;
+ await wait(50);
+ assert.equal(results[0], 'ok');
+ stop();
+ });
+});
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);
+ }
+});