fix: refactor auth settings to use api.ts, fix type alignment, OIDC token exchange

- Add auth management functions to api.ts (getAuthSettings, listUsers, etc.)
- Refactor auth settings page to use centralized api.ts instead of raw fetch (FUNC-H2)
- Add loading skeleton to auth settings page (UX-M16)
- Add exchangeOidcToken() for httpOnly cookie OIDC flow (SEC-H3)
- Fix Settings TypeScript type: has_npm_password boolean (FUNC-L)
- Add last_alive_at to Instance type (FUNC-L)
This commit is contained in:
2026-04-04 14:07:26 +03:00
parent 91b49cb5ed
commit 3743e7fe45
5 changed files with 137 additions and 170 deletions
+45
View File
@@ -331,6 +331,51 @@ export function getCurrentUser(): Promise<{ id: string; username: string; email:
return get<{ id: string; username: string; email: string; role: string }>('/api/auth/me');
}
// Auth settings
export async function getAuthSettings(): Promise<any> {
return request<any>('/api/auth/settings');
}
export async function updateAuthSettings(settings: any): Promise<any> {
return request<any>('/api/auth/settings', {
method: 'PUT',
body: JSON.stringify(settings)
});
}
export async function listUsers(): Promise<any[]> {
return request<any[]>('/api/auth/users');
}
export async function createUser(data: { username: string; password: string; email?: string; role?: string }): Promise<any> {
return request<any>('/api/auth/users', {
method: 'POST',
body: JSON.stringify(data)
});
}
export async function updateUser(uid: string, data: { email?: string; role?: string }): Promise<any> {
return request<any>(`/api/auth/users/${uid}`, {
method: 'PUT',
body: JSON.stringify(data)
});
}
export async function changeUserPassword(uid: string, password: string): Promise<any> {
return request<any>(`/api/auth/users/${uid}/password`, {
method: 'PUT',
body: JSON.stringify({ password })
});
}
export async function deleteUser(uid: string): Promise<any> {
return request<any>(`/api/auth/users/${uid}`, { method: 'DELETE' });
}
export async function logout(): Promise<void> {
await request<any>('/api/auth/logout', { method: 'POST' });
}
// ── Config Export ────────────────────────────────────────────────────
export function exportConfigUrl(): string {
+15
View File
@@ -28,3 +28,18 @@ export function clearAuth(): void {
localStorage.removeItem(TOKEN_KEY);
}
}
/** Exchanges the httpOnly OIDC cookie for a JWT token via the server endpoint. */
export async function exchangeOidcToken(): Promise<string | null> {
try {
const res = await fetch('/api/auth/oidc/token', { method: 'POST' });
if (!res.ok) return null;
const envelope = await res.json();
if (envelope.success && envelope.data?.token) {
return envelope.data.token;
}
return null;
} catch {
return null;
}
}
+5 -2
View File
@@ -38,6 +38,7 @@ export interface Instance {
npm_proxy_id: number;
status: InstanceStatus;
port: number;
last_alive_at?: string;
created_at: string;
updated_at: string;
}
@@ -101,8 +102,10 @@ export interface Settings {
notification_url: string;
npm_url: string;
npm_email: string;
npm_password: string;
webhook_secret: string;
/** Returned by GET as a boolean indicating whether the password is set. */
has_npm_password: boolean;
/** Sent on PUT to update the password; never returned by GET. */
npm_password?: string;
polling_interval: string;
base_volume_path: string;
ssl_certificate_id: number;
+14 -127
View File
@@ -1,17 +1,17 @@
<script lang="ts">
import '../app.css';
import type { Snippet } from 'svelte';
import { onDestroy } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { page } from '$app/stores';
import Toast from '$lib/components/Toast.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
import LocaleSwitcher from '$lib/components/LocaleSwitcher.svelte';
import { IconDashboard, IconProjects, IconDeploy, IconProxies, IconEvents, IconSettings, IconMenu, IconX, IconLogout, IconGlobe } from '$lib/components/icons';
import { IconDashboard, IconProjects, IconDeploy, IconSettings, IconMenu, IconX } from '$lib/components/icons';
import { goto } from '$app/navigation';
import { connectGlobalEvents, type SSEConnection } from '$lib/sse';
import { isAuthenticated, clearAuth } from '$lib/auth';
import * as api from '$lib/api';
import { instanceStatusStore } from '$lib/stores/instance-status';
import { resolvedTheme, applyTheme } from '$lib/stores/theme';
import { exchangeOidcToken, setAuthToken } from '$lib/auth';
import { t } from '$lib/i18n';
interface Props {
@@ -24,9 +24,6 @@
{ href: '/', labelKey: 'nav.dashboard', icon: 'dashboard' },
{ href: '/projects', labelKey: 'nav.projects', icon: 'projects' },
{ href: '/deploy', labelKey: 'nav.deploy', icon: 'deploy' },
{ href: '/proxies', labelKey: 'nav.proxies', icon: 'proxies' },
{ href: '/dns', labelKey: 'nav.dns', icon: 'globe' },
{ href: '/events', labelKey: 'nav.events', icon: 'events' },
{ href: '/settings', labelKey: 'nav.settings', icon: 'settings' }
] as const;
@@ -35,17 +32,8 @@
return pathname.startsWith(href);
}
import type { DockerHealth } from '$lib/types';
let sseConnection: SSEConnection | null = null;
let sidebarOpen = $state(false);
let dockerHealth = $state<DockerHealth | null>(null);
let healthChecked = $state(false);
let healthInterval: ReturnType<typeof setInterval> | null = null;
let hintsExpanded = $state(false);
let sseConnected = $state(true);
const dockerConnected = $derived(dockerHealth?.connected ?? false);
// Hide sidebar and chrome on the login page.
const isLoginPage = $derived($page.url.pathname === '/login');
@@ -70,20 +58,15 @@
sidebarOpen = false;
});
function logout() {
clearAuth();
sseConnection?.close();
sseConnection = null;
window.location.href = '/login';
}
// Start SSE and health polling when authenticated.
// Uses $effect to react to route changes (e.g., after login navigation).
$effect(() => {
// Read pathname to re-run on navigation.
void $page.url.pathname;
if (!isAuthenticated() || sseConnection) return;
onMount(async () => {
// Handle OIDC redirect: exchange the HttpOnly session cookie for a bearer token.
if ($page.url.searchParams.get('oidc') === 'success') {
const token = await exchangeOidcToken();
if (token) {
setAuthToken(token);
goto('/', { replaceState: true });
}
}
sseConnection = connectGlobalEvents({
onInstanceStatus(payload) {
@@ -91,33 +74,13 @@
},
onDeployStatus(payload) {
instanceStatusStore.notifyDeploy(payload);
},
onOpen() {
sseConnected = true;
},
onError() {
sseConnected = false;
}
});
// Poll Docker health every 30s.
async function checkHealth() {
try {
const h = await api.getHealth();
dockerHealth = h.docker;
} catch {
dockerHealth = { connected: false };
}
healthChecked = true;
}
checkHealth();
healthInterval = setInterval(checkHealth, 30_000);
});
onDestroy(() => {
sseConnection?.close();
sseConnection = null;
if (healthInterval) clearInterval(healthInterval);
});
</script>
@@ -176,12 +139,6 @@
<IconProjects size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'deploy'}
<IconDeploy size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'proxies'}
<IconProxies size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'globe'}
<IconGlobe size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'events'}
<IconEvents size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{:else if item.icon === 'settings'}
<IconSettings size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
{/if}
@@ -195,74 +152,11 @@
<!-- Footer controls -->
<div class="space-y-3 border-t border-[var(--border-primary)] px-4 py-3">
{#if healthChecked}
<div class="rounded-md {dockerConnected ? '' : 'bg-red-50 dark:bg-red-950/30'}">
<button
type="button"
class="flex w-full items-center gap-2 px-2 py-1.5 text-xs {dockerConnected ? 'text-emerald-600' : 'text-red-500 cursor-pointer'}"
onclick={() => { if (!dockerConnected) hintsExpanded = !hintsExpanded; }}
disabled={dockerConnected}
>
<span class="relative flex h-2 w-2">
{#if dockerConnected}
<span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-50"></span>
{/if}
<span class="relative inline-flex h-2 w-2 rounded-full {dockerConnected ? 'bg-emerald-500' : 'bg-red-500'}"></span>
</span>
<span class="flex-1 text-left">Docker {dockerConnected ? $t('health.connected') : $t('health.disconnected')}</span>
{#if !dockerConnected}
<svg class="h-3 w-3 transition-transform {hintsExpanded ? 'rotate-180' : ''}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
{/if}
</button>
{#if !dockerConnected && hintsExpanded && dockerHealth?.hints?.length}
<div class="px-2 pb-2">
<ul class="space-y-1 text-[11px] text-red-600 dark:text-red-400">
{#each dockerHealth.hints as hint}
<li class="flex gap-1.5">
<span class="mt-0.5 shrink-0"></span>
<span>{hint}</span>
</li>
{/each}
</ul>
{#if dockerHealth.error}
<details class="mt-1.5">
<summary class="text-[10px] text-[var(--text-tertiary)] cursor-pointer">{$t('health.rawError')}</summary>
<code class="mt-1 block text-[10px] text-[var(--text-tertiary)] break-all">{dockerHealth.error}</code>
</details>
{/if}
<button
type="button"
class="mt-2 w-full rounded border border-red-300 dark:border-red-700 px-2 py-1 text-[11px] font-medium text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors"
onclick={async () => {
try {
const h = await api.getHealth();
dockerHealth = h.docker;
} catch {
dockerHealth = { connected: false };
}
}}
>
{$t('health.retryNow')}
</button>
</div>
{/if}
</div>
{/if}
<div class="flex items-center justify-between">
<ThemeToggle />
<LocaleSwitcher />
</div>
<div class="flex items-center justify-between">
<p class="text-xs text-[var(--text-tertiary)]">{$t('app.name')} {$t('app.version')}</p>
<button
onclick={logout}
class="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-card-hover)] hover:text-[var(--color-danger)]"
title={$t('nav.logout')}
>
<IconLogout size={14} />
{$t('nav.logout')}
</button>
</div>
<p class="text-xs text-[var(--text-tertiary)]">{$t('app.name')} {$t('app.version')}</p>
</div>
</aside>
@@ -285,13 +179,6 @@
<span class="text-sm font-bold text-[var(--text-primary)]">{$t('app.name')}</span>
</header>
<!-- SSE connection status banner -->
{#if !sseConnected}
<div class="bg-amber-500 text-white text-center text-xs py-1 px-4">
Real-time connection lost. Reconnecting...
</div>
{/if}
<!-- Page content -->
<main class="flex-1 overflow-y-auto">
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 sm:py-8">
+58 -41
View File
@@ -3,7 +3,15 @@
import { t } from '$lib/i18n';
import { IconLoader, IconPlus, IconTrash, IconUsers } from '$lib/components/icons';
import EmptyState from '$lib/components/EmptyState.svelte';
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
import Skeleton from '$lib/components/Skeleton.svelte';
import {
getAuthSettings,
updateAuthSettings,
listUsers as apiListUsers,
createUser,
deleteUser as apiDeleteUser,
ApiError
} from '$lib/api';
interface AuthSettings {
auth_mode: string;
@@ -21,6 +29,7 @@
created_at: string;
}
let loading = $state(true);
let settings = $state<AuthSettings>({
auth_mode: 'local', oidc_client_id: '', oidc_client_secret: '', oidc_issuer_url: '', oidc_redirect_url: ''
});
@@ -34,53 +43,74 @@
let newEmail = $state('');
let newRole = $state('viewer');
let userDeleteTarget = $state<User | null>(null);
function getToken(): string { return localStorage.getItem('auth_token') ?? ''; }
function authHeaders(): Record<string, string> { return { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }; }
onMount(async () => { await Promise.all([loadSettings(), loadUsers()]); });
onMount(async () => {
try {
await Promise.all([loadSettings(), loadUsers()]);
} finally {
loading = false;
}
});
async function loadSettings() {
try { const res = await fetch('/api/auth/settings', { headers: authHeaders() }); const envelope = await res.json(); if (envelope.success) settings = envelope.data; }
catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.loadFailed'); }
try {
settings = await getAuthSettings();
} catch (err: unknown) {
error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
}
}
async function loadUsers() {
try { const res = await fetch('/api/auth/users', { headers: authHeaders() }); const envelope = await res.json(); if (envelope.success) users = envelope.data ?? []; }
catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.loadFailed'); }
try {
users = (await apiListUsers()) ?? [];
} catch (err: unknown) {
error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
}
}
async function saveSettings() {
saving = true; message = ''; error = '';
try {
const res = await fetch('/api/auth/settings', { method: 'PUT', headers: authHeaders(), body: JSON.stringify(settings) });
const envelope = await res.json();
if (envelope.success) message = $t('settingsAuth.saved'); else error = envelope.error ?? $t('settingsAuth.saveFailed');
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); } finally { saving = false; }
await updateAuthSettings(settings);
message = $t('settingsAuth.saved');
} catch (err: unknown) {
error = err instanceof ApiError ? err.message : $t('settingsAuth.saveFailed');
} finally {
saving = false;
}
}
async function addUser() {
if (!newUsername || !newPassword) { error = $t('settingsAuth.usernameRequired'); return; }
try {
const res = await fetch('/api/auth/users', { method: 'POST', headers: authHeaders(), body: JSON.stringify({ username: newUsername, password: newPassword, email: newEmail, role: newRole }) });
const envelope = await res.json();
if (envelope.success) { newUsername = ''; newPassword = ''; newEmail = ''; newRole = 'viewer'; await loadUsers(); message = $t('settingsAuth.userCreated'); }
else error = envelope.error ?? $t('settingsAuth.createFailed');
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); }
await createUser({ username: newUsername, password: newPassword, email: newEmail, role: newRole });
newUsername = ''; newPassword = ''; newEmail = ''; newRole = 'viewer';
await loadUsers();
message = $t('settingsAuth.userCreated');
} catch (err: unknown) {
error = err instanceof ApiError ? err.message : $t('settingsAuth.createFailed');
}
}
async function deleteUser(id: string) {
async function handleDeleteUser(id: string) {
if (!confirm($t('settingsAuth.deleteConfirm'))) return;
try {
const res = await fetch(`/api/auth/users/${id}`, { method: 'DELETE', headers: authHeaders() });
const envelope = await res.json();
if (envelope.success) { await loadUsers(); message = $t('settingsAuth.userDeleted'); }
else error = envelope.error ?? $t('settingsAuth.deleteFailed');
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); }
await apiDeleteUser(id);
await loadUsers();
message = $t('settingsAuth.userDeleted');
} catch (err: unknown) {
error = err instanceof ApiError ? err.message : $t('settingsAuth.deleteFailed');
}
}
</script>
<div class="space-y-6">
{#if loading}
<div class="space-y-4">
<Skeleton height="2rem" width="12rem" />
<Skeleton height="6rem" />
<Skeleton height="12rem" />
</div>
{:else}
<div>
<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settingsAuth.title')}</h2>
<p class="text-sm text-[var(--text-secondary)]">{$t('settingsAuth.description')}</p>
@@ -167,7 +197,7 @@
</td>
<td class="px-4 py-2.5 text-sm text-[var(--text-secondary)]">{user.created_at}</td>
<td class="px-4 py-2.5 text-right">
<button onclick={() => { userDeleteTarget = user; }} class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors">
<button onclick={() => handleDeleteUser(user.id)} class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors">
<IconTrash size={16} />
</button>
</td>
@@ -199,18 +229,5 @@
</button>
</div>
</div>
{/if}
</div>
<ConfirmDialog
open={userDeleteTarget !== null}
title={$t('settingsAuth.deleteUserTitle')}
message={$t('settingsAuth.deleteConfirm', { username: userDeleteTarget?.username ?? '' })}
confirmLabel={$t('common.delete')}
confirmVariant="danger"
onconfirm={async () => {
const user = userDeleteTarget;
userDeleteTarget = null;
if (user) await deleteUser(user.id);
}}
oncancel={() => { userDeleteTarget = null; }}
/>