From 0d86c6e91c08bcff8af4281cda8c4ab2c3016d23 Mon Sep 17 00:00:00 2001 From: WonderAliceUwU Date: Sun, 6 Sep 2026 21:59:07 +0200 Subject: [PATCH] feat: add Jellyfin profile authentication --- README.md | 8 +- server/index.ts | 135 ++++++++++++++-- server/lib/services.ts | 46 +++++- server/lib/store.ts | 29 ++-- shared/contracts.ts | 7 + src/App.tsx | 341 ++++++++++++++++++++++++++++++--------- src/api.ts | 8 + src/index.css | 354 ++++++++++++++++++++++++++++++++++++----- 8 files changed, 771 insertions(+), 157 deletions(-) diff --git a/README.md b/README.md index 5873d1e..be60c25 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ React + TypeScript frontend with a built-in Node backend for: -- master-password login with `HttpOnly` session cookie -- encrypted storage of service settings +- Jellyfin-profile login with an `HttpOnly` session cookie +- master-password protected administration and server-side service settings - Jellyfin, Sonarr, Radarr, qBittorrent and TMDb integration - a single production process for Docker/TrueNAS @@ -27,7 +27,7 @@ That file contains: - master-password verifier - encryption salt -- encrypted application settings +- server-managed encryption key and encrypted application settings If you do not persist `/app/data`, you will lose: @@ -139,6 +139,6 @@ That dataset is the piece that must survive updates and image replacements. On first boot there is no default password. -You create the master password in the UI. +You create the master password in the UI. It protects the Administration area; viewers sign in from the profile screen using their own Jellyfin password. After that, OmniArr stores only the verifier and encrypted settings in `/app/data/omniarr.secure.json`. diff --git a/server/index.ts b/server/index.ts index e7926d5..f185127 100644 --- a/server/index.ts +++ b/server/index.ts @@ -8,12 +8,14 @@ import { type EpisodeRequestPayload, type EpisodeWatchStateRequest, type DiskSpaceStatus, + type HubPageResponse, + type JellyfinLoginPayload, type SeasonDeletePayload, type SeasonRequestPayload, type TitleDetailsRequest } from '../shared/contracts.js'; import { decryptJson, deriveEncryptionKey, encryptJson, randomToken, verifyPassword, createPasswordRecord } from './lib/security.js'; -import { loadState, readAdmin, readEncryptedConfig, saveAdminAndConfig, updateEncryptedConfig } from './lib/store.js'; +import { loadState, migrateConfig, readAdmin, readEncryptedConfig, saveAdminAndConfig, updateEncryptedConfig } from './lib/store.js'; import { getCalendar, getConnectionStatuses, @@ -26,6 +28,7 @@ import { deleteSeasonFiles, getServiceOptions, loadJellyfinUsers, + authenticateJellyfinUser, proxyJellyfinImage, removeDownload, requestEpisode, @@ -40,7 +43,9 @@ import { } from './lib/services.js'; interface SessionRecord { - encryptionKey: Buffer; + role: 'admin' | 'user'; + userId?: string; + encryptionKey?: Buffer; expiresAt: number; } @@ -48,6 +53,7 @@ const PORT = Number(process.env.PORT || 8787); const SESSION_COOKIE = 'omniarr_session'; const SESSION_TTL_MS = 1000 * 60 * 60 * 12; const sessions = new Map(); +const sessionUsers = new WeakMap(); const failedAttempts = new Map(); const server = createServer(async (request, response) => { @@ -84,7 +90,9 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): const session = getSession(request); sendJson(response, 200, { needsSetup: !state.admin, - authenticated: Boolean(session) + authenticated: Boolean(session), + role: session?.role, + userId: session?.userId }); return; } @@ -106,16 +114,17 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): } const record = createPasswordRecord(password); - const encryptionKey = deriveEncryptionKey(password, record.encryptionSalt); + const configKey = createConfigKey(); await saveAdminAndConfig( { ...record, createdAt: new Date().toISOString() }, - encryptJson(defaultConfig, encryptionKey) + encryptJson(defaultConfig, Buffer.from(configKey)), + configKey ); - const token = createSession(encryptionKey); + const token = createSession({ role: 'admin', encryptionKey: Buffer.from(randomToken()) }); setSessionCookie(request, response, token); resetFailedAttempts(getClientAddress(request)); console.log('Register completed successfully'); @@ -149,8 +158,14 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } - const encryptionKey = deriveEncryptionKey(password, admin.encryptionSalt); - const token = createSession(encryptionKey); + const legacyEncryptionKey = deriveEncryptionKey(password, admin.encryptionSalt); + const state = await loadState(); + if (!state.configKey && state.config) { + const config = await readConfig(legacyEncryptionKey); + const configKey = createConfigKey(); + await migrateConfig(encryptJson(config, Buffer.from(configKey)), configKey); + } + const token = createSession({ role: 'admin', encryptionKey: Buffer.from(randomToken()) }); setSessionCookie(request, response, token); resetFailedAttempts(getClientAddress(request)); console.log('Login completed successfully'); @@ -161,6 +176,53 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/auth/profiles' && method === 'GET') { + try { + const config = await readConfig(); + const [jellyfinUsers, connections] = await Promise.all([ + loadJellyfinUsers(config.jellyfin.baseUrl, config.jellyfin.apiKey), + getConnectionStatuses(config) + ]); + sendJson(response, 200, { jellyfinUsers, connections }); + } catch { + sendJson(response, 409, { error: 'An administrator must sign in once to migrate the existing configuration.' }); + } + return; + } + + if (url.pathname.startsWith('/api/auth/profile-image/') && method === 'GET') { + const config = await readConfig(); + const userId = decodeURIComponent(url.pathname.replace('/api/auth/profile-image/', '')); + const image = await proxyJellyfinImage(config, userId, 'Primary', 160, url.searchParams.get('tag') || '', true); + if (!image) { + sendJson(response, 404, { error: 'Profile image not found.' }); + return; + } + response.writeHead(200, { 'Content-Type': image.contentType || 'image/jpeg', 'Cache-Control': 'private, max-age=3600' }); + response.end(Buffer.from(image.data)); + return; + } + + if (url.pathname === '/api/auth/profile-login' && method === 'POST') { + if (isRateLimited(getClientAddress(request))) { + sendJson(response, 429, { error: 'Too many attempts. Wait one minute.' }); + return; + } + const body = await readJson(request); + const config = await readConfig(); + const userId = String(body.userId || ''); + if (!await authenticateJellyfinUser(config, userId, String(body.password || ''))) { + trackFailedAttempt(getClientAddress(request)); + sendJson(response, 401, { error: 'Incorrect Jellyfin password.' }); + return; + } + const token = createSession({ role: 'user', userId, encryptionKey: Buffer.from(randomToken()) }); + setSessionCookie(request, response, token); + resetFailedAttempts(getClientAddress(request)); + sendJson(response, 200, { ok: true, needsSetup: false }); + return; + } + if (url.pathname === '/api/auth/logout' && method === 'POST') { const token = getSessionToken(request); if (token) { @@ -178,16 +240,21 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/settings' && method === 'PUT' && session?.role !== 'admin') { + sendJson(response, 403, { error: 'Administrator access is required.' }); + return; + } + if (url.pathname === '/api/settings' && method === 'GET') { const config = await readConfig(session!.encryptionKey); - sendJson(response, 200, config); + sendJson(response, 200, session!.role === 'admin' ? config : redactConfig(config)); return; } if (url.pathname === '/api/settings' && method === 'PUT') { const body = await readJson(request); const config = sanitizeConfig(body); - await updateEncryptedConfig(encryptJson(config, session!.encryptionKey)); + await updateEncryptedConfig(encryptJson(config, await getConfigEncryptionKey())); const connections = await getConnectionStatuses(config); sendJson(response, 200, { config, @@ -227,7 +294,7 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): const page = decodeURIComponent(url.pathname.replace('/api/hubs/', '')); console.log(`[API] GET /api/hubs/${page}`); try { - const result = await getHubPage(config, page as any); + const result = await getHubPage(config, page as HubPageResponse['page']); sendJson(response, 200, result); } catch (err) { console.error(`[API] Error in GET /api/hubs/${page}:`, err); @@ -259,7 +326,7 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): if (startParam) { try { start = new Date(startParam); - } catch (e) { + } catch { // ignore invalid date } } @@ -267,7 +334,7 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): if (endParam) { try { end = new Date(endParam); - } catch (e) { + } catch { // ignore invalid date } } @@ -401,15 +468,22 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): await serveApp(url.pathname, response); } -function createSession(encryptionKey: Buffer): string { +function createSession(session: Omit): string { const token = randomToken(); + if (session.userId && session.encryptionKey) { + sessionUsers.set(session.encryptionKey, session.userId); + } sessions.set(token, { - encryptionKey, + ...session, expiresAt: Date.now() + SESSION_TTL_MS }); return token; } +function createConfigKey(): string { + return randomToken().slice(0, 32); +} + async function getDiskSpaceStatus(config: AppConfig): Promise { return getMediaDiskSpace(config); } @@ -466,15 +540,21 @@ function clearSessionCookie(request: IncomingMessage, response: ServerResponse): ); } -async function readConfig(encryptionKey: Buffer): Promise { +async function readConfig(legacyEncryptionKey?: Buffer): Promise { const encrypted = await readEncryptedConfig(); if (!encrypted) { return defaultConfig; } + const state = await loadState(); + const encryptionKey = state.configKey ? Buffer.from(state.configKey) : legacyEncryptionKey; + if (!encryptionKey) { + throw new Error('The configuration must be unlocked by an administrator.'); + } + const stored = decryptJson>(encrypted, encryptionKey); - return sanitizeConfig({ + const config = sanitizeConfig({ preferences: { ...defaultConfig.preferences, ...(stored.preferences || {}) @@ -500,6 +580,27 @@ async function readConfig(encryptionKey: Buffer): Promise { ...(stored.tvdb || {}) } }); + const userId = legacyEncryptionKey ? sessionUsers.get(legacyEncryptionKey) : undefined; + return userId ? { ...config, jellyfin: { ...config.jellyfin, userId } } : config; +} + +async function getConfigEncryptionKey(): Promise { + const state = await loadState(); + if (!state.configKey) { + throw new Error('The configuration must be unlocked by an administrator.'); + } + return Buffer.from(state.configKey); +} + +function redactConfig(config: AppConfig): AppConfig { + return { + ...config, + jellyfin: { ...config.jellyfin, apiKey: 'configured' }, + sonarr: { ...config.sonarr, apiKey: '' }, + radarr: { ...config.radarr, apiKey: '' }, + tmdb: { ...config.tmdb, bearerToken: '' }, + tvdb: { ...config.tvdb, apiKey: '' } + }; } async function readJson(request: IncomingMessage): Promise { diff --git a/server/lib/services.ts b/server/lib/services.ts index d219dc2..6976f46 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -517,6 +517,33 @@ export async function loadJellyfinUsers(baseUrl: string, apiKey: string): Promis return getJellyfinUsersFromConfig(normalizeBaseUrl(baseUrl), apiKey.trim()); } +export async function authenticateJellyfinUser(config: AppConfig, userId: string, password: string): Promise { + if (!config.jellyfin.baseUrl || !userId || !password) { + return false; + } + + const authorization = 'MediaBrowser Client="OmniArr", Device="OmniArr", DeviceId="omniarr-web", Version="1.0.0"'; + const response = await fetch(`${config.jellyfin.baseUrl}/Users/AuthenticateByName`, { + method: 'POST', + headers: { + Authorization: authorization, + 'X-Emby-Authorization': authorization, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + Username: (await getJellyfinUsers(config)).find((user) => user.id === userId)?.label || '', + Pw: password + }) + }); + + if (!response.ok) { + return false; + } + + const payload = await response.json() as { User?: { Id?: string } }; + return payload.User?.Id === userId; +} + export async function getDashboard(config: AppConfig): Promise { const [connections, library, downloads, tmdb] = await Promise.all([ getConnectionStatuses(config), @@ -2743,12 +2770,14 @@ export async function proxyJellyfinImage( itemId: string, kind: string, maxWidth: number, - tag: string + tag: string, + isUser = false ): Promise<{ data: ArrayBuffer; contentType: string | null } | null> { const candidates = kind === 'Primary' ? ['Primary'] : [kind, 'Primary']; for (const candidate of candidates) { - const path = `/Items/${encodeURIComponent(itemId)}/Images/${encodeURIComponent(candidate)}?quality=90&maxWidth=${maxWidth}&tag=${encodeURIComponent(tag)}`; + const collection = isUser ? 'Users' : 'Items'; + const path = `/${collection}/${encodeURIComponent(itemId)}/Images/${encodeURIComponent(candidate)}?quality=90&maxWidth=${maxWidth}&tag=${encodeURIComponent(tag)}`; const response = await fetch(`${config.jellyfin.baseUrl}${path}`, { headers: { 'X-Emby-Token': config.jellyfin.apiKey @@ -3361,10 +3390,15 @@ async function getJellyfinUsersFromConfig(baseUrl: string, apiKey: string): Prom } ); - return users.map((user) => ({ - id: String(user.Id || ''), - label: String(user.Name || user.Id || 'User') - })); + return users.map((user) => { + const id = String(user.Id || ''); + const imageTag = String(user.PrimaryImageTag || ''); + return { + id, + label: String(user.Name || user.Id || 'User'), + ...(imageTag ? { imageUrl: `/api/auth/profile-image/${encodeURIComponent(id)}?tag=${encodeURIComponent(imageTag)}` } : {}) + }; + }); } async function getSonarrRootFolders(config: AppConfig): Promise { diff --git a/server/lib/store.ts b/server/lib/store.ts index a46aa6f..8cc13d1 100644 --- a/server/lib/store.ts +++ b/server/lib/store.ts @@ -13,9 +13,10 @@ interface EncryptedConfig { } interface StoredState { - version: 1; + version: 1 | 2; admin: StoredAdmin | null; config: EncryptedConfig | null; + configKey: string | null; } const DATA_DIR = resolve(process.env.OMNIARR_DATA_DIR || resolve(process.cwd(), 'data')); @@ -24,7 +25,8 @@ const STORE_FILE = resolve(DATA_DIR, 'omniarr.secure.json'); const EMPTY_STATE: StoredState = { version: 1, admin: null, - config: null + config: null, + configKey: null }; export async function loadState(): Promise { @@ -33,9 +35,10 @@ export async function loadState(): Promise { const parsed = JSON.parse(raw) as Partial; return { - version: 1, + version: parsed.configKey ? 2 : 1, admin: parsed.admin ?? null, - config: parsed.config ?? null + config: parsed.config ?? null, + configKey: typeof parsed.configKey === 'string' ? parsed.configKey : null }; } catch { return EMPTY_STATE; @@ -47,11 +50,6 @@ export async function saveState(state: StoredState): Promise { await writeFile(STORE_FILE, JSON.stringify(state, null, 2), 'utf8'); } -export async function needsSetup(): Promise { - const state = await loadState(); - return !state.admin; -} - export async function readEncryptedConfig(): Promise { const state = await loadState(); return state.config; @@ -59,12 +57,14 @@ export async function readEncryptedConfig(): Promise { export async function saveAdminAndConfig( admin: StoredAdmin, - config: EncryptedConfig + config: EncryptedConfig, + configKey: string ): Promise { await saveState({ - version: 1, + version: 2, admin, - config + config, + configKey }); } @@ -81,4 +81,9 @@ export async function readAdmin(): Promise { return state.admin; } +export async function migrateConfig(config: EncryptedConfig, configKey: string): Promise { + const state = await loadState(); + await saveState({ ...state, version: 2, config, configKey }); +} + export type { EncryptedConfig, StoredAdmin, StoredState }; diff --git a/shared/contracts.ts b/shared/contracts.ts index 3754f28..24d09b7 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -67,6 +67,7 @@ export interface AppConfig { export interface SelectOption { id: string; label: string; + imageUrl?: string; } export interface ServiceOptionsResponse { @@ -313,12 +314,18 @@ export interface HubPageResponse { export interface SessionResponse { needsSetup: boolean; authenticated: boolean; + role?: 'admin' | 'user'; + userId?: string; } export interface AuthPayload { password: string; } +export interface JellyfinLoginPayload extends AuthPayload { + userId: string; +} + export interface AuthResponse { ok: boolean; needsSetup: boolean; diff --git a/src/App.tsx b/src/App.tsx index 9817fbb..d9695ea 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -31,7 +31,7 @@ import { type TitleDetailsResponse, } from '../shared/contracts' -type AuthState = 'loading' | 'setup' | 'login' | 'app' +type AuthState = 'loading' | 'setup' | 'login' | 'profiles' | 'admin' | 'app' type EntryStage = 'onboarding' | 'profiles' | 'dashboard' type EntryTransitionState = 'idle' | 'forward-enter' | 'forward-exit' | 'back-enter' | 'back-exit' const MAX_CACHED_HUB_PAGES = 3 @@ -67,6 +67,7 @@ const networkSidebarItems: Array<{ route: AppRoute; label: string; icon: string; function App() { const [authState, setAuthState] = useState('loading') + const [sessionRole, setSessionRole] = useState<'admin' | 'user' | null>(null) const [entryStage, setEntryStage] = useState('profiles') const [route, setRoute] = useState('home') const [busy, setBusy] = useState(false) @@ -171,18 +172,21 @@ function App() { } if (!session.authenticated) { - setAuthState('login') + const profiles = await api.getProfiles() + if (cancelled) return + setOptions((current) => ({ ...current, jellyfinUsers: profiles.jellyfinUsers })) + setConnections(profiles.connections) + setAuthState('profiles') return } + setSessionRole(session.role ?? null) await refreshBaseData() - if (!cancelled) { - setAuthState('app') - } + if (!cancelled) setAuthState(session.role === 'admin' ? 'admin' : 'app') } catch (bootError) { if (!cancelled) { setError(bootError instanceof Error ? bootError.message : 'Failed to start OmniArr.') - setAuthState('login') + setAuthState('profiles') } } } @@ -258,10 +262,13 @@ function App() { } await refreshBaseData() setPassword('') + setSessionRole('admin') if (authState === 'setup') { setNotice('Instance initialized.') + } else { + setRoute('settings') } - setAuthState('app') + setAuthState(authState === 'setup' ? 'app' : 'admin') } catch (authError) { setError(authError instanceof Error ? authError.message : 'Authentication failed.') } finally { @@ -288,23 +295,17 @@ function App() { } } - async function handleSelectJellyfinUser(userId: string) { + async function handleSelectJellyfinUser(userId: string, jellyfinPassword: string) { setBusy(true) setError('') setNotice('') try { - const nextConfig = { - ...config, - jellyfin: { - ...config.jellyfin, - userId, - }, - } - const response = await api.saveSettings(nextConfig) - setConfig(response.config) + await api.loginProfile({ userId, password: jellyfinPassword }) + setSessionRole('user') await refreshBaseData() await transitionEntryStage('dashboard') setRoute('home') + setAuthState('app') } catch (selectError) { setError(selectError instanceof Error ? selectError.message : 'Failed to select Jellyfin profile.') } finally { @@ -422,12 +423,11 @@ function App() { return } - if (authState === 'setup' || authState === 'login') { + if (authState === 'setup') { return ( { setPassword(''); setAuthState('profiles') }} + onSubmit={handleAuthSubmit} + password={password} + setPassword={setPassword} + /> + ) + } + + if (authState === 'profiles') { + return ( + !connection.ok)} + error={error} + notice={notice} + onAdmin={() => setAuthState(sessionRole === 'admin' ? 'admin' : 'login')} + onSelectUser={handleSelectJellyfinUser} + users={options.jellyfinUsers} + /> + ) + } + + if (authState === 'admin') { + return ( + setAuthState('profiles')} + onLoadJellyfinUsers={handleLoadJellyfinUsers} + onSave={handleSaveSettings} + options={options} + updateConfig={updateConfig} + /> + ) + } + if (entryStage === 'onboarding') { return ( !connection.ok)} error={error} notice={notice} - onBackToOnboarding={() => void transitionEntryStage('onboarding')} + onAdmin={() => setAuthState(sessionRole === 'admin' ? 'admin' : 'login')} + onContinue={() => void transitionEntryStage('dashboard')} onSelectUser={handleSelectJellyfinUser} users={options.jellyfinUsers} /> @@ -471,8 +517,9 @@ function App() { ) } - const currentJellyfinUser = - options.jellyfinUsers.find((option) => option.id === config.jellyfin.userId)?.label || 'Media cockpit' + const currentJellyfinUser = sessionRole === 'admin' + ? 'Administration' + : options.jellyfinUsers.find((option) => option.id === config.jellyfin.userId)?.label || 'Media cockpit' const currentHub = route !== 'downloads' && route !== 'settings' && route !== 'calendar' && route !== 'search' ? hubPages[route as HubPageResponse['page']] : undefined return ( @@ -483,6 +530,7 @@ function App() { currentUser={currentJellyfinUser} diskSpace={diskSpace} onExitProfile={() => void transitionEntryStage('profiles')} + canManage={sessionRole === 'admin'} route={route} setRoute={setRoute} /> @@ -564,6 +612,7 @@ function Sidebar(props: { diskSpace: DiskSpaceStatus | null connections: ConnectionStatus[] busy: boolean + canManage: boolean onExitProfile: () => void }) { const [menuOpen, setMenuOpen] = useState(false) @@ -673,7 +722,7 @@ function Sidebar(props: {
{props.diskSpace ? : null} - + : null}
@@ -817,14 +867,12 @@ function ActionButton(props: { } function AuthScreen({ - mode, password, setPassword, onSubmit, busy, error, }: { - mode: 'setup' | 'login' password: string setPassword: (value: string) => void onSubmit: () => Promise @@ -832,7 +880,6 @@ function AuthScreen({ error: string }) { const isPasswordValid = password.trim().length >= 8 - const isSetup = mode === 'setup' function handleSubmit() { if (busy || !isPasswordValid) { @@ -843,15 +890,11 @@ function AuthScreen({ } return ( -
-
+
+
-

{isSetup ? 'Create your master password' : 'Sign in to OmniArr'}

-

- {isSetup - ? 'This password protects the session and encrypts service settings on the server.' - : 'Unlock the server session with your master password.'} -

+

Create your master password

+

This password protects the administration area and service settings.

- {isSetup && !isPasswordValid && password.length > 0 ?

Password must be at least 8 non-space characters.

: null} + {!isPasswordValid && password.length > 0 ?

Password must be at least 8 non-space characters.

: null} {error ?

{error}

: null} {busy ?

Contacting backend…

: null}
- {isSetup ? ( -
-
-
-

Migration

-
    -
  • Server-side session auth
  • -
  • Encrypted persisted settings
  • -
  • Jellyfin, Sonarr and Radarr
  • -
  • Rebuilt React UI with shared layout
  • -
-
-
- ) : ( - - )} +
+
+
+

Migration

+
    +
  • Server-side session auth
  • +
  • Encrypted persisted settings
  • +
  • Jellyfin, Sonarr and Radarr
  • +
  • Rebuilt React UI with shared layout
  • +
+
+
) } @@ -947,7 +984,7 @@ function JellyfinOnboardingScreen(props: {
{props.users.map((user) => (
-
{user.label.slice(0, 1).toUpperCase()}
+ {user.label}
))} @@ -961,43 +998,152 @@ function JellyfinOnboardingScreen(props: { function ProfileSelectionScreen(props: { users: SelectOption[] currentUserId: string + hasServiceFailure: boolean busy: boolean error: string notice: string - onSelectUser: (userId: string) => Promise - onBackToOnboarding: () => void + onSelectUser: (userId: string, password: string) => Promise + onAdmin: () => void + onContinue?: () => void }) { + const [selectedUserId, setSelectedUserId] = useState('') + const [password, setPassword] = useState('') + const [isReturning, setIsReturning] = useState(false) + const [hasReturned, setHasReturned] = useState(false) + const [isSelecting, setIsSelecting] = useState(false) + const [isEntering, setIsEntering] = useState(false) + + function submit() { + if (selectedUserId && password) { + void props.onSelectUser(selectedUserId, password) + } + } + + function goBack() { + setIsReturning(true) + window.setTimeout(() => { + setSelectedUserId('') + setPassword('') + setIsReturning(false) + setHasReturned(true) + window.setTimeout(() => setHasReturned(false), 520) + }, 240) + } + + function selectProfile(userId: string) { + setIsSelecting(true) + window.setTimeout(() => { + setSelectedUserId(userId) + setIsSelecting(false) + setIsEntering(true) + window.setTimeout(() => setIsEntering(false), 520) + }, 240) + } + + const selectedUser = props.users.find((user) => user.id === selectedUserId) + return ( -
+
-

Profiles

-

Who's watching?

+

{selectedUser ? `Sign in as ${selectedUser.label}` : 'Who\'s watching?'}

{props.error ?

{props.error}

: null} {props.notice ?

{props.notice}

: null}
-
+ {selectedUser ? } onBack={goBack} onSubmit={submit} password={password} placeholder="Enter the password" setPassword={setPassword} /> :
{props.users.map((user) => ( ))} -
-
-
} + {!selectedUser ?
+ -
+
: null}
) } +function ProfileAvatar({ user }: { user: SelectOption }) { + return
{user.imageUrl ? : user.label.slice(0, 1).toUpperCase()}
+} + +function AdministrationLoginScreen(props: { + busy: boolean + error: string + password: string + setPassword: (value: string) => void + onBack: () => void + onSubmit: () => Promise +}) { + const [isReturning, setIsReturning] = useState(false) + + function goBack() { + setIsReturning(true) + window.setTimeout(props.onBack, 240) + } + + return ( +
+
+

Administration

+ {props.error ?

{props.error}

: null} +
+
} onBack={goBack} onSubmit={() => { void props.onSubmit() }} password={props.password} placeholder="Enter the master password" setPassword={props.setPassword} /> +
+ ) +} + +function ProfileLoginForm(props: { + busy: boolean + icon: ReactNode + password: string + placeholder: string + setPassword: (value: string) => void + onBack: () => void + onSubmit: () => void +}) { + return ( +
{ event.preventDefault(); props.onSubmit() }}> + {props.icon} + +
+ + +
+
+ ) +} + +function SignInGlyph() { + return ( + + ) +} + function HubPageView(props: { route: AppRoute hub?: HubPageResponse @@ -3159,6 +3305,47 @@ function formatCalendarTime(startsAt: string) { }).format(date) } +function AdministrationScreen(props: { + config: AppConfig + connections: ConnectionStatus[] + jellyfinUsersBusy: boolean + onExit: () => void + onLoadJellyfinUsers: () => Promise + updateConfig: (key: K, value: AppConfig[K]) => void + options: ServiceOptionsResponse + onSave: (event: FormEvent) => Promise + busy: boolean +}) { + return ( +
+
+ +
+

Administration

+

Settings

+
+ +
+ +
+ ) +} + function SettingsView(props: { config: AppConfig connections: ConnectionStatus[] @@ -3168,9 +3355,11 @@ function SettingsView(props: { options: ServiceOptionsResponse onSave: (event: FormEvent) => Promise busy: boolean + formId?: string + showSubmit?: boolean }) { return ( -
void props.onSave(event)}> + void props.onSave(event)}>
{props.connections.map((connection) => ( @@ -3249,11 +3438,11 @@ function SettingsView(props: { -
+ {props.showSubmit !== false ?
-
+
: null} ) } diff --git a/src/api.ts b/src/api.ts index 2db26ff..689fb86 100644 --- a/src/api.ts +++ b/src/api.ts @@ -3,10 +3,12 @@ import type { AuthPayload, AuthResponse, CalendarResponse, + ConnectionStatus, DashboardResponse, DiskSpaceStatus, DownloadsResponse, HubPageResponse, + JellyfinLoginPayload, MediaCard, SearchResponse, ServiceOptionsResponse, @@ -67,6 +69,12 @@ export const api = { method: 'POST', body: JSON.stringify(payload), }), + getProfiles: () => request<{ jellyfinUsers: ServiceOptionsResponse['jellyfinUsers']; connections: ConnectionStatus[] }>('/api/auth/profiles'), + loginProfile: (payload: JellyfinLoginPayload) => + request('/api/auth/profile-login', { + method: 'POST', + body: JSON.stringify(payload), + }), logout: () => request('/api/auth/logout', { method: 'POST', diff --git a/src/index.css b/src/index.css index 952f57d..63cc552 100644 --- a/src/index.css +++ b/src/index.css @@ -20,7 +20,7 @@ body, #root { height: 100%; margin: 0; - overflow: hidden; + overflow: visible; } body { @@ -1878,7 +1878,7 @@ img { display: grid; grid-template-columns: minmax(0, 52rem) auto; align-items: end; - gap: 1.25rem; + gap: 1rem; } .title-details-summary-copy { @@ -3155,7 +3155,7 @@ img { .download-row { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(18rem, 0.7fr); - gap: 1.25rem; + gap: 2rem; padding: 1.1rem; border-radius: 1.35rem; background: rgba(255, 255, 255, 0.045); @@ -3454,14 +3454,6 @@ img { linear-gradient(180deg, #05070b, #090c12 42%, #06080d 100%); } -.auth-layout-login { - position: relative; - grid-template-columns: minmax(0, 34rem); - justify-content: center; - align-content: center; - padding: 2rem; -} - .auth-panel, .auth-visual { padding: 3rem; @@ -3473,13 +3465,6 @@ img { gap: 1.25rem; } -.auth-panel-login { - position: relative; - z-index: 1; - min-height: auto; - padding: 0; -} - .auth-panel-shell { display: grid; gap: 1rem; @@ -3522,15 +3507,6 @@ img { url('/omniarr/server-wallpaper.png') center/cover no-repeat; } -.auth-visual-login { - position: fixed; - inset: 0; - z-index: 0; - padding: 0; - opacity: 0.6; - mask-image: linear-gradient(90deg, transparent 0%, rgba(0, 0, 0, 0.88) 18%, #000 100%); -} - .glass-card { position: relative; z-index: 1; @@ -3576,7 +3552,8 @@ img { } .profiles-layout { - min-height: 100vh; + height: 100%; + overflow-y: auto; display: grid; align-content: center; gap: 2rem; @@ -3595,31 +3572,253 @@ img { font-family: var(--font-display); } +.profiles-layout.is-profile-login.is-entering .profiles-header, +.profiles-layout.is-profile-login.is-entering .profile-login-form { + animation: entryStageForwardEnter 520ms cubic-bezier(0.16, 1, 0.3, 1) both; +} + +.profiles-layout.is-profile-login.is-returning .profiles-header, +.profiles-layout.is-profile-login.is-returning .profile-login-form { + animation: entryStageBackExit 240ms cubic-bezier(0.32, 0.9, 0.42, 1) both; +} + +.profiles-layout.is-profile-return .profiles-header, +.profiles-layout.is-profile-return .profile-grid, +.profiles-layout.is-profile-return .profiles-actions { + animation: entryStageBackEnter 520ms cubic-bezier(0.16, 1, 0.3, 1) both; +} + +.profiles-layout.is-profile-selecting .profiles-header, +.profiles-layout.is-profile-selecting .profile-grid, +.profiles-layout.is-profile-selecting .profiles-actions { + animation: entryStageForwardExit 240ms cubic-bezier(0.32, 0.9, 0.42, 1) both; +} + +.profile-login-back { + display: grid; + place-items: center; + width: 2.6rem; + height: 2.6rem; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 999px; + background: rgba(255, 255, 255, 0.07); + color: #f5f7fb; +} + +.profile-login-actions { + display: flex; + justify-content: space-between; + width: 100%; +} + +.profile-login-submit { + display: grid; + place-items: center; + width: 2.6rem; + height: 2.6rem; + border: 0; + border-radius: 999px; + background: #68d391; + color: #07120d; + box-shadow: 0 0.35rem 1.1rem rgba(104, 211, 145, 0.28); +} + +.profile-login-submit:hover { + filter: brightness(1.08); + transform: translateX(0.1rem); +} + +.profile-login-back:hover { + background: rgba(255, 255, 255, 0.16); + transform: translateX(-0.15rem); +} + +.profile-login-form { + display: grid; + justify-items: center; + gap: 1.15rem; + width: min(25rem, 100%); + margin: 0 auto; + padding: 1.5rem; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 1.5rem; + background: rgba(8, 12, 18, 0.72); +} + +.profile-login-form label { + display: grid; + gap: 0.55rem; + width: 100%; + color: #c9d5e6; +} + +.administration-login-icon { + display: grid; + place-items: center; + width: 4.5rem; + height: 4.5rem; + border-radius: 999px; + background: rgba(255, 255, 255, 0.1); + color: #e8edf8; +} + +.administration-login-icon .sidebar-glyph-icon { + width: 1.7rem; + height: 1.7rem; +} + + + .profiles-actions { display: flex; justify-content: center; } -.profile-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(10rem, 12rem)); - justify-content: center; - gap: 1.25rem; +.administration-layout { + height: 100%; + overflow-y: auto; + padding: clamp(1.5rem, 5vw, 4rem); + background: #080c12; } -.profile-grid.compact { - grid-template-columns: repeat(auto-fit, minmax(8rem, 10rem)); +.administration-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + max-width: 76rem; + margin: 0 auto 2rem; +} + +.administration-header h1 { + margin: 0.25rem 0 0; + font-family: var(--font-display); +} + +.administration-back-button { + display: grid; + place-items: center; + width: 2.9rem; + height: 2.9rem; + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 999px; + background: rgba(255, 255, 255, 0.08); + color: #f5f7fb; +} + +.administration-back-button:hover { + background: rgba(255, 255, 255, 0.18); + box-shadow: -3px 6px 13px rgba(0, 0, 0, 0.25); +} + +.administration-save-button { + display: grid; + place-items: center; + width: 2.9rem; + height: 2.9rem; + border: 0; + border-radius: 999px; + background: #68d391; + color: #07120d; + box-shadow: 0 0.35rem 1.1rem rgba(104, 211, 145, 0.28); + transition: transform 180ms ease, box-shadow 180ms ease, filter 180ms ease; +} + +.administration-save-button svg { + width: 1.35rem; + height: 1.35rem; +} + +.administration-save-button:hover { + filter: brightness(1.08); + transform: scale(1.08); + box-shadow: 0 0.5rem 1.4rem rgba(104, 211, 145, 0.46); +} + +.administration-save-button.is-saving { + animation: administration-save-pulse 700ms ease-in-out infinite alternate; +} + +.administration-save-button.is-saving svg { + animation: administration-save-check 700ms ease-in-out infinite; +} + +@keyframes administration-save-pulse { + from { box-shadow: 0 0 0 0 rgba(104, 211, 145, 0.48); } + to { box-shadow: 0 0 0 0.65rem rgba(104, 211, 145, 0); } +} + +@keyframes administration-save-check { + 0%, 100% { transform: scale(1); } + 50% { transform: scale(0.72) rotate(-10deg); } +} + +.profile-admin-button { + display: grid; + place-items: center; + width: 2.9rem; + height: 2.9rem; + border: 0; + background: transparent; + color: #f5f7fb; + cursor: pointer; +} + +.profile-admin-icon { + position: relative; + display: grid; + place-items: center; + width: 2rem; + height: 2rem; + border-radius: 0.7rem; + background: rgba(255, 255, 255, 0.1); + color: #e8edf8; +} + +.profile-admin-icon .sidebar-glyph-icon { + width: 1rem; + height: 1rem; +} + +.profile-admin-status { + position: absolute; + inset: -0.2rem; + border: 0.12rem solid currentColor; + border-radius: 999px; + pointer-events: none; +} + +.profile-admin-status.ok { color: #59df8a; } +.profile-admin-status.down { color: #ff5d73; } + +.profile-admin-button:hover { + transform: scale(1.04); +} + +.profile-admin-button:hover .profile-admin-status { + box-shadow: 0 0 0.65rem currentColor; +} + +.profile-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(7.2rem, 1fr)); + justify-content: center; + gap: 2rem; + width: min(100%, 72rem); + margin: 0 auto; } .profile-card { + position: relative; display: grid; gap: 0.85rem; justify-items: center; - padding: 1.25rem; - border: 1px solid rgba(255, 255, 255, 0.08); - border-radius: 1.5rem; - background: rgba(8, 12, 18, 0.72); + padding: 0.75rem; + border: 0; + border-radius: 1rem; + background: transparent; color: #eef4ff; + transition: color 220ms ease; } .profile-card.static { @@ -3627,8 +3826,15 @@ img { } .profile-card.active { - border-color: rgba(255, 209, 102, 0.45); - box-shadow: 0 0 0 1px rgba(255, 209, 102, 0.24) inset; + box-shadow: none; +} + +.profile-card:not(:disabled):hover .profile-avatar { + transform: scale(1.08); +} + +.profile-card:not(:disabled):hover strong { + color: #ffffff; } .profile-avatar { @@ -3636,11 +3842,75 @@ img { place-items: center; width: 4.5rem; height: 4.5rem; - border-radius: 1.2rem; + border-radius: 999px; background: linear-gradient(135deg, #68abff, #ffd166); color: #0f1420; font-size: 1.5rem; font-weight: 800; + overflow: hidden; + transition: transform 220ms cubic-bezier(.2, .8, .2, 1); +} + +.profile-avatar img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.profile-active-check { + position: absolute; + top: 0.65rem; + right: 0.65rem; + display: grid; + place-items: center; + width: 1.4rem; + height: 1.4rem; + border-radius: 999px; + background: #68d391; + color: #07120d; + font-weight: 900; +} + +@media (max-width: 600px) { + .profiles-layout { + align-content: start; + gap: 1.5rem; + padding: 2rem 1.25rem; + } + + .profiles-header h1 { + font-size: clamp(1.8rem, 9vw, 2.5rem); + } + + .profile-grid { + grid-template-columns: repeat(auto-fit, minmax(5.8rem, 1fr)); + gap: 1rem; + width: 100%; + } + + .profile-card { + gap: 0.55rem; + padding: 0.35rem; + min-width: 0; + } + + .profile-avatar { + width: clamp(4.1rem, 20vw, 5.5rem); + height: clamp(4.1rem, 20vw, 5.5rem); + font-size: 1.35rem; + } + + .profile-card strong { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .profile-login-form { + width: min(100%, 24rem); + padding: 1.25rem; + } } .eyebrow {