/** * Connection data store: server host + user credentials, persisted to * localStorage. Single source of truth for "which server are we talking * to"; the Subsonic client is built from these settings. * * Security note: we deliberately store the *password* (per product * decision) rather than a derived token — Subsonic token auth derives a * fresh salted md5 per request and the protocol has no session token. * localStorage is readable by any XSS on this origin: acceptable for * self-hosted music-server creds, revisit before hosting on untrusted * origins. */ import * as v from "valibot"; import { SubsonicClient } from "./subsonic/client"; import { clearPersistent, createPersistentSignal } from "./persist"; import type { ConnectionSettings } from "./subsonic/types"; export type { ConnectionSettings } from "./subsonic/types"; const STORAGE_KEY = "hackermusic.connection.v1"; function shallowEqualSettings(a: ConnectionSettings | null, b: ConnectionSettings | null): boolean { if (a === b) return true; if (!a || !b) return false; return a.host === b.host && a.username === b.username && a.password === b.password; } /** * What a stored connection must look like before we trust it. * * `host` is the only stored string this app turns into a URL it attaches a * username, a salt and an md5 of the password to, so it is checked against the * exact output of `normalizeHost` rather than merely being a string: a hand-edited * or injected `host` — `javascript:…`, `//evil.example`, a trailing slash from an * older build — is rejected at load and the user is returned to the login gate, * instead of being trusted indefinitely because it happens to parse. (An empty * username and password are legal: `isConnected` is what decides they are useless, * and an anonymous server has both empty.) * * Nullable as a whole because "not configured yet" is stored as `null`, and that is * a value, not corruption. */ const connectionSchema = v.nullable( v.object({ host: v.pipe( v.string(), v.check((host) => normalizeHost(host) === host, "stored host is not a normalized origin"), ), username: v.string(), password: v.string(), }), ); const connectionStore = createPersistentSignal(STORAGE_KEY, null, { equals: (a, b) => shallowEqualSettings(a, b), schema: connectionSchema, }); /** * Synchronous read for imperative code (client construction, guards, * tests). Not reactive — see connectionSignal() for JSX/memos. */ export function connection(): ConnectionSettings | null { return connectionStore.peek(); } /** Reactive accessor for components/JSX/memos. */ export function connectionSignal(): ConnectionSettings | null { return connectionStore.get(); } export function isConnected(): boolean { const c = connectionStore.peek(); return c !== null && c.host !== "" && c.username !== ""; } /** * Normalize a user-typed host into a clean origin: * - trims whitespace, prepends https:// when no scheme is given * - only http/https allowed * - strips trailing slashes; a base-path (e.g. `/navidrome`) IS preserved * Returns null when the input can't form a valid URL. */ export function normalizeHost(raw: string): string | null { const trimmed = raw.trim(); if (!trimmed) return null; const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`; try { const url = new URL(withScheme); if (url.protocol !== "https:" && url.protocol !== "http:") return null; // WHATWG URL is permissive about hostnames ("!!!" parses!); require a // sane host: alnum, dots, hyphens, IPv6 brackets, IDN punycode, port ok. if (!/^[a-z0-9.\-_[\]:]+$/i.test(url.hostname) || url.hostname === "") return null; const path = url.pathname.replace(/\/+$/, ""); return `${url.protocol}//${url.host}${path}`; } catch { return null; } } /** Save + activate a connection. Throws on invalid host. */ export function saveConnection(next: ConnectionSettings): ConnectionSettings { const host = normalizeHost(next.host); if (!host) throw new Error(`Invalid server host: ${next.host}`); const settings: ConnectionSettings = { host, username: next.username.trim(), password: next.password, }; connectionStore.set(settings); return settings; } /** Patch fields without full re-validation (login-form live edits). */ export function updateConnection(patch: Partial): void { const current = connectionStore.peek(); if (!current) return; connectionStore.set({ ...current, ...patch }); } export function clearConnection(): void { connectionStore.set(null); clearPersistent(STORAGE_KEY); } /** * Who a connection belongs to, as one string: same host and same user, or it is * not the same session. * * One definition because two would be two ideas of what "the same" means, and the * two users of it have to agree exactly: startPlayerSync silences the previous * stream when this moves, and the stored session (player/session.ts) decides * whether the queue in localStorage is being put back where it came from or left * where it is. * * The username is in it because the library is: the same Navidrome answers two * accounts with two track lists, so the ids one queues mean nothing to the other. * Password is deliberately not — rotating a credential should not lose the queue. */ export function connectionKey( c: { host: string; username: string } | null | undefined, ): string | null { return c ? `${c.host}\u0000${c.username}` : null; } export interface ConnectionTestResult { ok: boolean; /** e.g. `v0.54.0 (linux-amd64)` on Navidrome. */ serverVersion?: string; openSubsonic?: boolean; error?: string; } /** * Verify credentials against the server with `ping` WITHOUT persisting — * the login screen calls this first and only saves successful attempts. */ export async function testConnection( candidate: ConnectionSettings, signal?: AbortSignal, ): Promise { const host = normalizeHost(candidate.host); if (!host) return { ok: false, error: `Invalid server host: ${candidate.host}` }; const client = new SubsonicClient({ host, username: candidate.username, password: candidate.password, }); try { const info = await client.ping(signal); return { ok: true, serverVersion: info.serverVersion, openSubsonic: info.openSubsonic }; } catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; } }