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

@@ -50,6 +50,18 @@ Proxy матчит сервисы по `Host` заголовку. Если PC on
В Docker volume монтируется: `./data/proxy:/app/data`.
## Аутентификация
Опциональная auth по логину/паролю через env-переменные `AUTH_USERNAME` и `AUTH_PASSWORD`. Если не заданы — auth отключена.
- `POST /api/auth/login` — возвращает `{ token }` (UUID v4)
- `POST /api/auth/logout` — удаляет сессию
- `GET /api/auth/check` — проверяет, нужна ли auth и валиден ли токен
- Сессии in-memory (`Map`), теряются при рестарте
- Auth middleware защищает `/api/*` кроме `/api/auth/*`
- WebSocket: токен через query `?token=...`
- Сервис-прокси (по Host) — без auth
## Деплой
Два приложения в Dokploy из одного git repo:

View File

@@ -0,0 +1,18 @@
import type { MiddlewareHandler } from 'hono';
import { isAuthEnabled } from '../config.js';
import { validateSession } from './sessionStore.js';
export const authMiddleware: MiddlewareHandler = async (c, next) => {
if (!isAuthEnabled()) {
return next();
}
const header = c.req.header('Authorization');
const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
if (!token || !validateSession(token)) {
return c.json({ error: 'Unauthorized' }, 401);
}
return next();
};

View File

@@ -0,0 +1,57 @@
import { Hono } from 'hono';
import { timingSafeEqual } from 'node:crypto';
import { config, isAuthEnabled } from '../config.js';
import { createSession, validateSession, removeSession } from './sessionStore.js';
const authRoutes = new Hono();
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
authRoutes.post('/login', async (c) => {
if (!isAuthEnabled()) {
return c.json({ error: 'Auth is not enabled' }, 400);
}
const body = await c.req.json<{ username: string; password: string }>();
const { username, password } = body;
if (!username || !password) {
return c.json({ error: 'Username and password required' }, 400);
}
const validUser = safeEqual(username, config.auth.username);
const validPass = safeEqual(password, config.auth.password);
if (!validUser || !validPass) {
return c.json({ error: 'Invalid credentials' }, 401);
}
const token = createSession(username);
return c.json({ token });
});
authRoutes.post('/logout', (c) => {
const header = c.req.header('Authorization');
const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
if (token) {
removeSession(token);
}
return c.json({ ok: true });
});
authRoutes.get('/check', (c) => {
if (!isAuthEnabled()) {
return c.json({ authRequired: false });
}
const header = c.req.header('Authorization');
const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
const valid = token ? validateSession(token) !== null : false;
return c.json({ authRequired: true, valid });
});
export { authRoutes };

View File

@@ -0,0 +1,22 @@
import { randomUUID } from 'node:crypto';
interface Session {
username: string;
createdAt: number;
}
const sessions = new Map<string, Session>();
export function createSession(username: string): string {
const token = randomUUID();
sessions.set(token, { username, createdAt: Date.now() });
return token;
}
export function validateSession(token: string): Session | null {
return sessions.get(token) ?? null;
}
export function removeSession(token: string): void {
sessions.delete(token);
}

View File

@@ -30,5 +30,14 @@ export const config = {
healthCheckIntervalSeconds: intEnv('HEALTH_CHECK_INTERVAL_SECONDS', 10),
wakingTimeoutSeconds: intEnv('WAKING_TIMEOUT_SECONDS', 120),
auth: {
username: optionalEnv('AUTH_USERNAME', ''),
password: optionalEnv('AUTH_PASSWORD', ''),
},
services: parseServices(),
} as const;
export function isAuthEnabled(): boolean {
return config.auth.username !== '' && config.auth.password !== '';
}

View File

@@ -5,7 +5,8 @@ import { app } from './server/app.js';
import { proxyRequest, proxyWebSocket } from './server/proxy.js';
import { initOrchestrator, getState, onRequest } from './services/orchestrator.js';
import { addClient, removeClient } from './server/ws.js';
import { config } from './config.js';
import { config, isAuthEnabled } from './config.js';
import { validateSession } from './auth/sessionStore.js';
import { initServiceManager, getServiceManager } from './services/serviceManager.js';
import { WebSocketServer } from 'ws';
@@ -52,7 +53,17 @@ server.on('upgrade', (req, socket, head) => {
}
// Dashboard WebSocket at /api/ws
if (req.url === '/api/ws') {
if (req.url?.startsWith('/api/ws')) {
if (isAuthEnabled()) {
const url = new URL(req.url, `http://${req.headers.host}`);
const token = url.searchParams.get('token');
if (!token || !validateSession(token)) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
}
wss.handleUpgrade(req, socket, head, (ws) => {
addClient(ws);
ws.on('close', () => removeClient(ws));

View File

@@ -2,6 +2,8 @@ import { Hono } from 'hono';
import { serveStatic } from '@hono/node-server/serve-static';
import { MachineState } from '@sleepguard/shared';
import { corsMiddleware } from '../api/middleware.js';
import { authRoutes } from '../auth/routes.js';
import { authMiddleware } from '../auth/middleware.js';
import { api } from '../api/routes.js';
import { getState, onRequest } from '../services/orchestrator.js';
import { getWakingPageHtml } from './wakingPage.js';
@@ -12,6 +14,12 @@ const app = new Hono();
// CORS for API
app.use('/api/*', corsMiddleware);
// Auth routes (before auth middleware)
app.route('/api/auth', authRoutes);
// Auth middleware (after auth routes)
app.use('/api/*', authMiddleware);
// API routes
app.route('/api', api);

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,19 +2,51 @@
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(() => {
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>
{#if !ready}
<!-- loading -->
{:else if $authRequired && !$isAuthenticated}
<LoginForm />
{:else}
<div class="app">
<header>
<nav>
@@ -22,6 +54,9 @@
<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>
@@ -29,6 +64,7 @@
{@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;