feat(proxy): add optional auth for dashboard and API

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Vadim Sobinin
2026-03-15 00:23:15 +03:00
parent f8df3ae14b
commit 6bd6a6c8c8
12 changed files with 445 additions and 20 deletions

View File

@@ -1,12 +1,32 @@
import type { ProxyStatus, ServiceHealth, LogEntry } from '@sleepguard/shared';
import { getToken, clearToken } from './stores/auth.js';
const BASE = '/api';
export class AuthError extends Error {
constructor() {
super('Unauthorized');
this.name = 'AuthError';
}
}
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const token = getToken();
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const res = await fetch(`${BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
headers: { ...headers, ...options?.headers },
});
if (res.status === 401) {
clearToken();
throw new AuthError();
}
if (!res.ok) {
throw new Error(`API error: ${res.status} ${res.statusText}`);
}
@@ -44,3 +64,40 @@ export function updateService(host: string, updates: { name?: string; target?: s
export function deleteService(host: string): Promise<{ ok: boolean }> {
return request(`/services/${encodeURIComponent(host)}`, { method: 'DELETE' });
}
export async function login(username: string, password: string): Promise<string> {
const res = await fetch(`${BASE}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({ error: 'Login failed' })) as { error: string };
throw new Error(body.error || 'Login failed');
}
const data = (await res.json()) as { token: string };
return data.token;
}
export async function logout(): Promise<void> {
const token = getToken();
await fetch(`${BASE}/auth/logout`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : {},
}).catch(() => {});
clearToken();
}
export async function checkAuth(): Promise<{ authRequired: boolean; valid: boolean }> {
const token = getToken();
const headers: Record<string, string> = {};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const res = await fetch(`${BASE}/auth/check`, { headers });
const data = (await res.json()) as { authRequired: boolean; valid?: boolean };
return { authRequired: data.authRequired, valid: data.valid ?? false };
}

View File

@@ -0,0 +1,148 @@
<script lang="ts">
import { login } from '$lib/api.js';
import { setToken } from '$lib/stores/auth.js';
let username = $state('');
let password = $state('');
let errorMsg = $state('');
let loading = $state(false);
async function handleSubmit(e: Event) {
e.preventDefault();
errorMsg = '';
loading = true;
try {
const token = await login(username, password);
setToken(token);
} catch (err) {
errorMsg = err instanceof Error ? err.message : 'Login failed';
} finally {
loading = false;
}
}
</script>
<div class="login-container">
<div class="login-card">
<h1>SleepGuard</h1>
<p class="subtitle">Sign in to continue</p>
<form onsubmit={handleSubmit}>
<div class="field">
<label for="username">Username</label>
<input
id="username"
type="text"
bind:value={username}
autocomplete="username"
required
disabled={loading}
/>
</div>
<div class="field">
<label for="password">Password</label>
<input
id="password"
type="password"
bind:value={password}
autocomplete="current-password"
required
disabled={loading}
/>
</div>
{#if errorMsg}
<div class="error">{errorMsg}</div>
{/if}
<button type="submit" class="primary" disabled={loading}>
{loading ? 'Signing in...' : 'Sign in'}
</button>
</form>
</div>
</div>
<style>
.login-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.login-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 2.5rem;
width: 100%;
max-width: 380px;
}
h1 {
color: var(--accent);
font-size: 1.5rem;
font-weight: 700;
margin-bottom: 0.25rem;
}
.subtitle {
color: var(--text-muted);
font-size: 0.875rem;
margin-bottom: 1.5rem;
}
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
label {
font-size: 0.8125rem;
font-weight: 500;
color: var(--text-muted);
}
input {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.625rem 0.75rem;
color: var(--text);
font-size: 0.875rem;
outline: none;
transition: border-color 0.15s;
}
input:focus {
border-color: var(--accent);
}
input:disabled {
opacity: 0.5;
}
.error {
color: var(--red);
font-size: 0.8125rem;
padding: 0.5rem 0.75rem;
background: rgba(239, 68, 68, 0.1);
border-radius: var(--radius);
}
button {
margin-top: 0.5rem;
width: 100%;
padding: 0.625rem 1rem;
}
</style>

View File

@@ -0,0 +1,29 @@
import { writable, derived } from 'svelte/store';
const STORAGE_KEY = 'sleepguard_token';
function loadToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem(STORAGE_KEY);
}
export const token = writable<string | null>(loadToken());
export const authRequired = writable(false);
export const isAuthenticated = derived(
[token, authRequired],
([$token, $authRequired]) => !$authRequired || $token !== null,
);
export function setToken(t: string): void {
localStorage.setItem(STORAGE_KEY, t);
token.set(t);
}
export function clearToken(): void {
localStorage.removeItem(STORAGE_KEY);
token.set(null);
}
export function getToken(): string | null {
return loadToken();
}

View File

@@ -2,6 +2,7 @@ import { writable, derived } from 'svelte/store';
import type { ProxyStatus, WsMessage } from '@sleepguard/shared';
import { MachineState } from '@sleepguard/shared';
import { fetchStatus } from '../api.js';
import { getToken } from './auth.js';
export const status = writable<ProxyStatus | null>(null);
export const connected = writable(false);
@@ -15,7 +16,12 @@ let pollTimer: ReturnType<typeof setInterval> | null = null;
function getWsUrl(): string {
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${proto}//${window.location.host}/api/ws`;
let url = `${proto}//${window.location.host}/api/ws`;
const token = getToken();
if (token) {
url += `?token=${encodeURIComponent(token)}`;
}
return url;
}
export function connectWs(): void {

View File

@@ -2,33 +2,69 @@
import '../app.css';
import { onMount, onDestroy } from 'svelte';
import { connectWs, disconnectWs } from '$lib/stores/machine.js';
import { token, authRequired, isAuthenticated } from '$lib/stores/auth.js';
import { checkAuth, logout as apiLogout } from '$lib/api.js';
import LoginForm from '$lib/components/LoginForm.svelte';
import type { Snippet } from 'svelte';
let { children }: { children: Snippet } = $props();
let ready = $state(false);
onMount(() => {
connectWs();
onMount(async () => {
try {
const auth = await checkAuth();
authRequired.set(auth.authRequired);
if (!auth.authRequired || auth.valid) {
connectWs();
}
} catch {
// If check fails, assume auth not required
}
ready = true;
});
onDestroy(() => {
disconnectWs();
});
// Reconnect WS when token changes (e.g. after login)
$effect(() => {
if ($token && ready) {
disconnectWs();
connectWs();
}
});
async function handleLogout() {
disconnectWs();
await apiLogout();
}
</script>
<div class="app">
<header>
<nav>
<a href="/dashboard" class="logo">SleepGuard</a>
<div class="nav-links">
<a href="/dashboard">Dashboard</a>
<a href="/dashboard/settings">Settings</a>
</div>
</nav>
</header>
<main>
{@render children()}
</main>
</div>
{#if !ready}
<!-- loading -->
{:else if $authRequired && !$isAuthenticated}
<LoginForm />
{:else}
<div class="app">
<header>
<nav>
<a href="/dashboard" class="logo">SleepGuard</a>
<div class="nav-links">
<a href="/dashboard">Dashboard</a>
<a href="/dashboard/settings">Settings</a>
{#if $authRequired}
<button class="logout-btn" onclick={handleLogout}>Logout</button>
{/if}
</div>
</nav>
</header>
<main>
{@render children()}
</main>
</div>
{/if}
<style>
.app {
@@ -57,6 +93,7 @@
.nav-links {
display: flex;
gap: 1.5rem;
align-items: center;
}
.nav-links a {
color: var(--text-muted);
@@ -68,6 +105,17 @@
.nav-links a:hover {
color: var(--text);
}
.logout-btn {
background: transparent;
color: var(--text-muted);
font-size: 0.875rem;
font-weight: 500;
padding: 0.25rem 0.5rem;
transition: color 0.15s;
}
.logout-btn:hover {
color: var(--red);
}
main {
flex: 1;
max-width: 1200px;