Add secure five-digit LAN pairing with automatic host discovery, encrypted credential handoff, polished host/client setup UI, persistence, tests, and documentation.

Hop-State: A_06FNQN729W1JAHZXV6PY1N0
Hop-Proposal: R_06FNQN68SGDZRN85WXQGSWG
Hop-Task: T_06FNQHGRCHN66DEC5171JF8
Hop-Attempt: AT_06FNQHGRCHPM6DR3BVFFMXG
This commit is contained in:
2026-07-13 07:15:06 -07:00
committed by Hop
parent 38dc9b80e2
commit 76ec2ecd46
11 changed files with 1009 additions and 21 deletions
+38
View File
@@ -5,9 +5,13 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
const managedServer = vi.hoisted(() => ({
chooseMusicFolder: vi.fn(),
beginDevicePairing: vi.fn(),
cancelDevicePairing: vi.fn(),
getManagedServerStatus: vi.fn(),
getPairingStatus: vi.fn(),
getSavedCredentials: vi.fn(),
isDesktopRuntime: vi.fn(),
pairWithCode: vi.fn(),
saveRemotePassword: vi.fn(),
startManagedServer: vi.fn(),
stopManagedServer: vi.fn(),
@@ -55,6 +59,7 @@ describe("App bootstrap", () => {
localStorage.clear();
vi.clearAllMocks();
managedServer.isDesktopRuntime.mockReturnValue(false);
managedServer.getPairingStatus.mockResolvedValue({ available: false, active: false, attemptsRemaining: 0, paired: false });
});
it("keeps a saved library behind the launch gate while credentials load", () => {
@@ -108,6 +113,39 @@ describe("App bootstrap", () => {
expect(screen.queryByRole("heading", { level: 2, name: "Heavy rotation" })).toBeNull();
});
it("pairs with another Resonant computer using only five digits", async () => {
const message = "No Resonant host is sharing a pairing code on this network.";
managedServer.pairWithCode.mockRejectedValue(new Error(message));
await renderDemoApp();
fireEvent.click(screen.getByRole("button", { name: /Demo library/ }));
fireEvent.click(screen.getByRole("button", { name: /Another computer/ }));
const code = screen.getByLabelText("Pairing code") as HTMLInputElement;
fireEvent.change(code, { target: { value: "12a345" } });
expect(code.value).toBe("12345");
fireEvent.click(screen.getByRole("button", { name: "Pair computer" }));
expect((await screen.findByRole("alert")).textContent).toBe(message);
expect(managedServer.pairWithCode).toHaveBeenCalledWith("12345");
});
it("shows a temporary five-digit code on a running host", async () => {
managedServer.isDesktopRuntime.mockReturnValue(true);
managedServer.getManagedServerStatus.mockResolvedValue({ running: true, url: "http://127.0.0.1:4533", lanUrls: ["http://192.168.1.10:4533"], version: "0.61.2" });
managedServer.getSavedCredentials.mockResolvedValue({});
managedServer.getPairingStatus.mockResolvedValue({ available: true, active: false, attemptsRemaining: 0, paired: false });
managedServer.beginDevicePairing.mockResolvedValue({ available: true, active: true, code: "40721", expiresAt: Date.now() + 120_000, attemptsRemaining: 5, paired: false });
render(<App />);
await screen.findByText("Let it find you again.");
fireEvent.click(screen.getByRole("button", { name: /This computer/ }));
fireEvent.click(screen.getByRole("button", { name: "Show pairing code" }));
expect((await screen.findByLabelText("Pairing code")).textContent).toBe("40721");
expect(screen.queryByText("http://192.168.1.10:4533")).toBeNull();
});
it("defaults Albums and Songs to AZ and remembers reordered views", async () => {
await renderDemoApp();
+117 -8
View File
@@ -49,12 +49,17 @@ import { fetchAllPages, pollForLibrary } from "./lib/librarySync";
import {
chooseMusicFolder,
getManagedServerStatus,
getPairingStatus,
getSavedCredentials,
beginDevicePairing,
cancelDevicePairing,
isDesktopRuntime,
pairWithCode,
saveRemotePassword,
startManagedServer,
stopManagedServer,
type ManagedServerStatus,
type PairingStatus,
} from "./lib/managedServer";
import { buildApiUrl, requestSubsonic, setSubsonicFavorite, streamUrl, submitSubsonicScrobble } from "./lib/subsonic";
import type { Album, ConnectionStatus, CoverTone, ServerConfig, Track, View } from "./types";
@@ -141,6 +146,10 @@ interface ServerSong { id: string; title: string; artist?: string; album?: strin
interface LoadedLibrary { albums: Album[]; tracks: Track[] }
type LibraryPhase = "ready" | "scanning" | "empty";
function formatPairingTime(seconds: number): string {
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}
export default function App() {
const [view, setView] = useState<View>("home");
const [mobileNav, setMobileNav] = useState(false);
@@ -167,6 +176,12 @@ export default function App() {
const [libraryPhase, setLibraryPhase] = useState<LibraryPhase>("ready");
const [sourceMode, setSourceMode] = useState<"local" | "remote">(() => localStorage.getItem("resonant.sourceMode") === "remote" ? "remote" : "local");
const [managedStatus, setManagedStatus] = useState<ManagedServerStatus | null>(null);
const [hostPairing, setHostPairing] = useState<PairingStatus | null>(null);
const [hostPairingError, setHostPairingError] = useState<string | null>(null);
const [pairingCode, setPairingCode] = useState("");
const [pairingBusy, setPairingBusy] = useState(false);
const [pairingError, setPairingError] = useState<string | null>(null);
const [pairingNow, setPairingNow] = useState(Date.now());
const [localSetup, setLocalSetup] = useState({
musicFolder: localStorage.getItem("resonant.musicFolder") ?? "",
password: "",
@@ -391,6 +406,7 @@ export default function App() {
const connect = async (event: FormEvent) => {
event.preventDefault();
setPairingError(null);
setConnectionStatus("connecting");
setConnectionMessage("Reaching your library…");
try {
@@ -405,6 +421,54 @@ export default function App() {
}
};
const showPairingCode = async () => {
setHostPairingError(null);
try {
setHostPairing(await beginDevicePairing());
setPairingNow(Date.now());
} catch (error) {
setHostPairingError(error instanceof Error ? error.message : "A pairing code could not be created.");
}
};
const cancelPairing = async () => {
setHostPairingError(null);
try {
setHostPairing(await cancelDevicePairing());
} catch (error) {
setHostPairingError(error instanceof Error ? error.message : "Pairing could not be cancelled.");
}
};
const pairComputer = async (event: FormEvent) => {
event.preventDefault();
if (!/^\d{5}$/.test(pairingCode)) {
setPairingError("Enter the five-digit code shown on the host computer.");
return;
}
setPairingBusy(true);
setPairingError(null);
setConnectionStatus("connecting");
setConnectionMessage("Looking for your Resonant host…");
try {
const config = await pairWithCode(pairingCode);
setServer(config);
localStorage.setItem("resonant.serverUrl", config.url);
localStorage.setItem("resonant.username", config.username);
localStorage.setItem("resonant.sourceMode", "remote");
await loadServerLibrary(config, "Paired with your Resonant host");
setPairingCode("");
} catch (error) {
const message = error instanceof Error ? error.message : "This computer could not be paired.";
setPairingError(message);
setConnectionStatus("error");
setConnectionMessage(message);
} finally {
setPairingBusy(false);
}
};
const pickMusicFolder = async () => {
if (!isDesktopRuntime()) {
setConnectionStatus("error");
@@ -552,6 +616,35 @@ export default function App() {
};
}, []);
useEffect(() => {
if (!managedStatus?.running || !isDesktopRuntime()) {
setHostPairing(null);
return;
}
let active = true;
const refresh = async () => {
try {
const next = await getPairingStatus();
if (active) {
setHostPairing(next);
setHostPairingError(next.available ? null : "Device pairing is unavailable on this computer.");
}
} catch (error) {
if (active) setHostPairingError(error instanceof Error ? error.message : "Pairing status is unavailable.");
}
};
void refresh();
const timer = window.setInterval(() => {
setPairingNow(Date.now());
void refresh();
}, 1000);
return () => {
active = false;
window.clearInterval(timer);
};
}, [managedStatus?.running]);
const goTo = (next: View) => {
if (next === "home") {
setSpotlightTrackId((current) => pickRandomTrack(libraryTracks, current)?.id ?? "");
@@ -616,7 +709,7 @@ export default function App() {
<div className="source-switch" role="group" aria-label="Library source">
<button type="button" aria-pressed={sourceMode === "local"} onClick={() => setSourceMode("local")}><HardDrive size={18} /><span><strong>This computer</strong><small>Managed by Resonant</small></span></button>
<button type="button" aria-pressed={sourceMode === "remote"} onClick={() => setSourceMode("remote")}><Server size={18} /><span><strong>Existing server</strong><small>Navidrome or OpenSubsonic</small></span></button>
<button type="button" aria-pressed={sourceMode === "remote"} onClick={() => setSourceMode("remote")}><Server size={18} /><span><strong>Another computer</strong><small>Pair or connect manually</small></span></button>
</div>
{sourceMode === "local" ? (
@@ -625,7 +718,14 @@ export default function App() {
<label>Music folder<div className="folder-field"><input required readOnly placeholder="Choose the folder that holds your music" value={localSetup.musicFolder} /><button type="button" className="button-secondary" onClick={pickMusicFolder}><FolderOpen size={16} /> Choose folder</button></div></label>
<label>Library password<input type="password" required minLength={8} autoComplete="current-password" placeholder="At least 8 characters" value={localSetup.password} onChange={(event) => setLocalSetup({ ...localSetup, password: event.target.value })} /><small className="field-hint">Saved in your operating system credential store and used by your other music apps.</small></label>
<div className={`connection-feedback connection-feedback--${connectionStatus}`} role="status"><span className={`status-dot status-dot--${connectionStatus}`} />{connectionMessage}</div>
{managedStatus?.running && managedStatus.lanUrls.length > 0 && <div className="device-addresses"><strong>Listen from another computer</strong><p>Use this address in Resonant or any OpenSubsonic app on the same private network. Sign in as <b>admin</b> with your library password.</p>{managedStatus.lanUrls.map((url) => <code key={url}>{url}</code>)}</div>}
{managedStatus?.running && <div className="pairing-panel">
<div className="pairing-panel-head"><div><strong>Pair another computer</strong><p>Open Resonant there and enter a temporary code. Your server credentials stay hidden.</p></div>{hostPairing?.paired && <span className="pairing-success"><Check size={15} /> Device connected</span>}</div>
{hostPairing?.active && hostPairing.code ? <>
<div className="pairing-code-row"><output className="pairing-code" aria-label="Pairing code">{hostPairing.code}</output><span>Expires in {formatPairingTime(Math.max(0, Math.ceil(((hostPairing.expiresAt ?? pairingNow) - pairingNow) / 1000)))}<small>{hostPairing.attemptsRemaining} attempts remaining</small></span></div>
<div className="pairing-actions"><button type="button" className="button-secondary" onClick={showPairingCode}>New code</button><button type="button" className="button-quiet" onClick={cancelPairing}>Cancel pairing</button></div>
</> : <button type="button" className="button-secondary pairing-start" onClick={showPairingCode}>Show pairing code</button>}
{hostPairingError && <p className="pairing-error" role="alert">{hostPairingError}</p>}
</div>}
<div className="form-actions">
{managedStatus?.running && <button type="button" className="button-secondary button-danger" onClick={stopLocalLibrary}><Power size={16} /> Stop server</button>}
<button type="button" className="button-secondary" onClick={() => goTo("home")}>Cancel</button>
@@ -633,12 +733,21 @@ export default function App() {
</div>
</form>
) : (
<form className="connection-form" onSubmit={connect}>
<label>Server address<input type="url" required placeholder="https://music.example.com" value={server.url} onChange={(event) => setServer({ ...server, url: event.target.value })} /></label>
<div className="form-row"><label>Username<input required autoComplete="username" value={server.username} onChange={(event) => setServer({ ...server, username: event.target.value })} /></label><label>Password<input type="password" required autoComplete="current-password" value={server.password} onChange={(event) => setServer({ ...server, password: event.target.value })} /></label></div>
<div className={`connection-feedback connection-feedback--${connectionStatus}`} role="status"><span className={`status-dot status-dot--${connectionStatus}`} />{connectionMessage}</div>
<div className="form-actions"><button type="button" className="button-secondary" onClick={() => goTo("home")}>Cancel</button><button type="submit" className="button-primary" disabled={connectionStatus === "connecting"}>{connectionStatus === "connecting" ? "Connecting…" : "Connect library"}<ChevronRight size={17} /></button></div>
</form>
<div className="remote-connection-stack">
<form className="connection-form pairing-form" onSubmit={pairComputer}>
<div className="pairing-heading"><div><strong>Pair with a Resonant host</strong><p>Make sure both computers are on the same network, then enter the code shown by the host.</p></div><span>5 digits</span></div>
<label>Pairing code<div className="pairing-entry"><input inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{5}" maxLength={5} placeholder="12345" value={pairingCode} onChange={(event) => setPairingCode(event.target.value.replace(/\D/g, "").slice(0, 5))} /><button type="submit" className="button-primary" disabled={pairingBusy || pairingCode.length !== 5}>{pairingBusy ? "Pairing…" : "Pair computer"}<ChevronRight size={17} /></button></div></label>
{pairingError && <p className="pairing-error" role="alert">{pairingError}</p>}
</form>
<div className="connection-divider"><span>or connect manually</span></div>
<form className="connection-form" onSubmit={connect}>
<div className="pairing-heading"><div><strong>Navidrome or OpenSubsonic server</strong><p>Use this for an existing server that is not hosted by Resonant.</p></div></div>
<label>Server address<input type="url" required placeholder="https://music.example.com" value={server.url} onChange={(event) => setServer({ ...server, url: event.target.value })} /></label>
<div className="form-row"><label>Username<input required autoComplete="username" value={server.username} onChange={(event) => setServer({ ...server, username: event.target.value })} /></label><label>Password<input type="password" required autoComplete="current-password" value={server.password} onChange={(event) => setServer({ ...server, password: event.target.value })} /></label></div>
{!pairingError && <div className={`connection-feedback connection-feedback--${connectionStatus}`} role="status"><span className={`status-dot status-dot--${connectionStatus}`} />{connectionMessage}</div>}
<div className="form-actions"><button type="button" className="button-secondary" onClick={() => goTo("home")}>Cancel</button><button type="submit" className="button-primary" disabled={connectionStatus === "connecting"}>{connectionStatus === "connecting" ? "Connecting…" : "Connect library"}<ChevronRight size={17} /></button></div>
</form>
</div>
)}
<div className="privacy-note"><Disc3 size={22} /><div><strong>{sourceMode === "local" ? "Available on your private network" : "Your server stays yours"}</strong><p>{sourceMode === "local" ? "The managed server accepts devices on your LAN, keeps its database in Resonants app data, and stops when Resonant closes. Avoid exposing port 4533 directly to the internet." : "Resonant speaks OpenSubsonic directly and saves the password in your operating system credential store."}</p></div></div>
</section>
+11 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getManagedServerStatus, getSavedCredentials, isDesktopRuntime } from "./managedServer";
import { getManagedServerStatus, getPairingStatus, getSavedCredentials, isDesktopRuntime, pairWithCode } from "./managedServer";
describe("managed server bridge", () => {
it("reports the browser preview as a non-desktop runtime", () => {
@@ -18,4 +18,14 @@ describe("managed server bridge", () => {
it("does not expose credentials in the browser preview", async () => {
await expect(getSavedCredentials()).resolves.toEqual({});
});
it("keeps device pairing inside the desktop app", async () => {
await expect(getPairingStatus()).resolves.toEqual({
available: false,
active: false,
attemptsRemaining: 0,
paired: false,
});
await expect(pairWithCode("12345")).rejects.toThrow("desktop app");
});
});
+42
View File
@@ -14,6 +14,28 @@ export interface SavedCredentials {
remotePassword?: string;
}
export interface PairingStatus {
available: boolean;
active: boolean;
code?: string;
expiresAt?: number;
attemptsRemaining: number;
paired: boolean;
}
export interface PairedServerConfig {
url: string;
username: string;
password: string;
}
const unavailablePairingStatus: PairingStatus = {
available: false,
active: false,
attemptsRemaining: 0,
paired: false,
};
export function isDesktopRuntime(): boolean {
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
}
@@ -45,6 +67,26 @@ export async function saveRemotePassword(password: string): Promise<void> {
await invoke("save_remote_password", { password });
}
export async function getPairingStatus(): Promise<PairingStatus> {
if (!isDesktopRuntime()) return unavailablePairingStatus;
return invoke<PairingStatus>("pairing_status");
}
export async function beginDevicePairing(): Promise<PairingStatus> {
if (!isDesktopRuntime()) throw new Error("Device pairing is available in the Resonant desktop app.");
return invoke<PairingStatus>("begin_device_pairing");
}
export async function cancelDevicePairing(): Promise<PairingStatus> {
if (!isDesktopRuntime()) return unavailablePairingStatus;
return invoke<PairingStatus>("cancel_device_pairing");
}
export async function pairWithCode(code: string): Promise<PairedServerConfig> {
if (!isDesktopRuntime()) throw new Error("Device pairing is available in the Resonant desktop app.");
return invoke<PairedServerConfig>("pair_with_code", { code });
}
export async function startManagedServer(musicFolder: string, password: string): Promise<ManagedServerStatus> {
if (!isDesktopRuntime()) throw new Error("The managed library is available in the Resonant desktop app.");
return invoke<ManagedServerStatus>("start_managed_server", { musicFolder, password });
+25 -4
View File
@@ -220,10 +220,27 @@ main { min-width: 0; height: calc(100vh - var(--player-height)); overflow-y: aut
.connection-feedback { display: flex; align-items: center; gap: 10px; min-height: 40px; padding: 0 12px; border-radius: 8px; color: var(--muted); background: oklch(0.21 0.012 275); font-size: 0.73rem; }
.connection-feedback--error { color: oklch(0.81 0.09 25); background: oklch(0.28 0.055 24); }
.connection-feedback--connected { color: oklch(0.81 0.08 145); background: oklch(0.26 0.05 145); }
.device-addresses { display: grid; gap: 6px; padding: 14px; border: 1px solid oklch(0.39 0.035 145); border-radius: 10px; background: oklch(0.21 0.025 145); }
.device-addresses strong { font-size: 0.75rem; }
.device-addresses p { margin: 0 0 3px; color: var(--muted); font-size: 0.68rem; line-height: 1.5; }
.device-addresses code { width: fit-content; padding: 5px 8px; border: 1px solid var(--line); border-radius: 6px; color: oklch(0.84 0.08 145); background: oklch(0.14 0.012 275); font-size: 0.7rem; user-select: all; }
.remote-connection-stack { display: grid; gap: 14px; }
.pairing-panel { display: grid; gap: 15px; padding: 17px; border: 1px solid oklch(0.38 0.02 275); border-radius: 12px; background: oklch(0.18 0.011 275); }
.pairing-panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.pairing-panel-head strong, .pairing-heading strong { color: var(--ink); font-size: 0.8rem; }
.pairing-panel-head p, .pairing-heading p { max-width: 54ch; margin: 4px 0 0; color: var(--faint); font-size: 0.68rem; line-height: 1.5; }
.pairing-success { display: inline-flex; flex: 0 0 auto; align-items: center; gap: 5px; color: oklch(0.82 0.08 145); font-size: 0.66rem; font-weight: 700; }
.pairing-code-row { display: flex; align-items: center; gap: 19px; }
.pairing-code { color: oklch(0.94 0.008 275); font-size: 2rem; font-weight: 650; letter-spacing: 0.18em; font-variant-numeric: tabular-nums; }
.pairing-code-row > span { color: var(--muted); font-size: 0.68rem; font-variant-numeric: tabular-nums; }
.pairing-code-row small { display: block; margin-top: 3px; color: var(--faint); }
.pairing-actions { display: flex; align-items: center; gap: 8px; }
.pairing-actions .button-quiet { border-color: transparent; background: transparent; }
.pairing-start { width: fit-content; }
.pairing-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 17px; border-bottom: 1px solid var(--line); }
.pairing-heading > span { padding: 4px 7px; border: 1px solid var(--line); border-radius: 6px; color: var(--faint); font-size: 0.6rem; font-variant-numeric: tabular-nums; }
.pairing-entry { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 9px; }
.pairing-entry input { height: 47px; font-size: 1.12rem; font-weight: 650; letter-spacing: 0.2em; font-variant-numeric: tabular-nums; }
.pairing-entry .button-primary { min-width: 146px; }
.pairing-error { margin: -4px 0 0; color: oklch(0.81 0.09 25); font-size: 0.7rem; line-height: 1.45; }
.connection-divider { display: flex; align-items: center; gap: 13px; color: var(--faint); font-size: 0.62rem; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; }
.connection-divider::before, .connection-divider::after { height: 1px; flex: 1; background: var(--line); content: ""; }
.button-danger { margin-right: auto; color: oklch(0.78 0.1 25); }
.privacy-note { display: flex; gap: 14px; margin-top: 20px; padding: 7px 14px; color: var(--muted); }
.privacy-note svg { flex: 0 0 auto; margin-top: 3px; color: var(--accent-bright); }
@@ -339,6 +356,10 @@ input[type="range"]:hover::-webkit-slider-thumb, input[type="range"]:focus-visib
.source-switch { grid-template-columns: 1fr; }
.folder-field { grid-template-columns: 1fr; }
.form-row { grid-template-columns: 1fr; }
.pairing-panel-head, .pairing-code-row { align-items: flex-start; flex-direction: column; gap: 10px; }
.pairing-entry { grid-template-columns: 1fr; }
.pairing-entry .button-primary, .pairing-start { width: 100%; }
.pairing-actions { align-items: stretch; flex-direction: column; }
.form-actions { flex-direction: column-reverse; }
.form-actions button { width: 100%; }
.player-bar { grid-template-columns: minmax(0, 1fr) auto; gap: 6px; padding: 8px 10px; }