Skip to content

Modern Docker Management, Designed for Everyone

7.8 KB
Raw Blame
<script lang="ts">
	import { goto, refreshAll } from '$app/navigation';
	import { page } from '$app/state';
	import { createMutation, useQueryClient } from '@tanstack/svelte-query';
	import { onMount } from 'svelte';
	import { toast } from 'svelte-sonner';

	import MFAChallenge from '#lib/components/auth/mfa-challenge.svelte';
	import OidcStatusPanel from '#lib/components/oidc-status-panel.svelte';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import { authService } from '#lib/services/auth-service.js';
	import { settingsService } from '#lib/services/settings-service.js';
	import settingsStore from '#lib/stores/config-store.svelte.js';
	import { environmentStore } from '#lib/stores/environment.store.svelte.js';
	import type { AuthenticationResponse, MFAChallenge as MFAChallengeData, User } from '#lib/types/auth.js';
	import { getAuthRedirectPath, normalizeAuthenticationError } from '#lib/utils/auth.js';
	import { getEffectiveLandingPage } from '#lib/utils/navigation.js';
	import { tryCatch } from '#lib/utils/try-catch.js';

	let error = $state('');
	let mfaChallenge = $state<MFAChallengeData | null>(null);
	let pendingRedirect = $state('');
	const queryClient = useQueryClient();

	const buildLoginRedirect = (errorCode: string, message?: string) => {
		const params = new URLSearchParams({ error: errorCode });
		if (message) {
			params.set('message', message);
		}
		return `/login?${params.toString()}`;
	};

	// Returns '' when no explicit target was carried across the OIDC round trip.
	// This runs before the user is in the store, so the account landing page must
	// not be resolved here — it is resolved after sign-in, below.
	const getStoredRedirect = () => {
		const storedRedirect = localStorage.getItem('oidc_redirect');
		return storedRedirect?.startsWith('/') && !storedRedirect.startsWith('//') ? storedRedirect : '';
	};

	type CallbackFailure = {
		code: string;
		userMessage: string;
	};

	function failure(code: string, userMessage: string): CallbackFailure {
		return { code, userMessage };
	}

	async function finalizeAuthentication(user: User, redirectTo: string) {
		// refreshAll re-runs the root +layout.ts loader, which fetches settings
		// (with a graceful catch). We don't fetch them here directly — a user with
		// zero/limited permissions would 403 on settings:read and crash this handler.
		await refreshAll();
		const operationResult = await tryCatch(
			(async () => {
				const settings = await queryClient.query({
					queryKey: queryKeys.settings.global(),
					queryFn: () => settingsService.getSettings()
				});
				settingsStore.set(settings);
			})()
		);
		if (operationResult.error !== null) {
			const settingsError = operationResult.error;

			// User lacks settings:read or settings fetch failed — not fatal; the root
			// layout already pulls public settings as a fallback.
			console.warn('Skipping post-login settings fetch:', settingsError);
		}
		toast.success(m.auth_login_success());
		// Navigate straight to a route the user can actually reach. Computing the
		// reachable target here avoids the (app) layout's auth-redirect superseding
		// this navigation for environment-scoped users.
		const landingUser = page.data['user'] ?? user;
		const landingPage = getEffectiveLandingPage();
		const requestedTarget = redirectTo || landingPage;
		const target =
			getAuthRedirectPath(
				requestedTarget,
				landingUser,
				environmentStore.selected?.id,
				page.data['permissionsManifest'],
				page.data['permissionsManifestLoadFailed'] ?? false,
				landingPage
			) ?? requestedTarget;
		await goto(target, { replace: true });
	}

	async function completeMFA(response: AuthenticationResponse) {
		const user = await authService.completeAuthentication(response);
		await finalizeAuthentication(user, pendingRedirect);
	}

	const callbackMutation = createMutation(() => ({
		mutationFn: async () => {
			const code = page.url.searchParams.get('code');
			const stateFromUrl = page.url.searchParams.get('state');
			const errorParam = page.url.searchParams.get('error');
			const errorDescription = page.url.searchParams.get('error_description');

			const redirectTo = getStoredRedirect();
			localStorage.removeItem('oidc_redirect');

			if (errorParam) {
				let userMessage = m.auth_oidc_provider_error();
				let redirectCode = 'oidc_provider_error';
				if (errorParam === 'access_denied') {
					userMessage = m.auth_oidc_access_denied();
					redirectCode = 'oidc_access_denied';
				} else if (errorParam === 'invalid_request') {
					userMessage = m.auth_oidc_invalid_request();
					redirectCode = 'oidc_invalid_request';
				}

				throw failure(redirectCode, errorDescription || userMessage);
			}

			if (!code || !stateFromUrl) {
				throw failure('oidc_invalid_response', m.auth_oidc_invalid_response());
			}

			const authResult = await authService.handleCallback(code, stateFromUrl);

			if (!authResult.success) {
				let userMessage = m.auth_oidc_auth_failed();
				if (authResult.error?.includes('state')) {
					userMessage = m.auth_oidc_state_mismatch();
				} else if (authResult.error?.includes('expired')) {
					userMessage = m.auth_oidc_session_expired();
				}

				throw failure('oidc_auth_failed', authResult.error || userMessage);
			}

			if (authResult.status === 'mfa_required') {
				if (!authResult.mfa) {
					throw failure('oidc_mfa_missing', m.auth_oidc_auth_failed());
				}
				return {
					authResult,
					redirectTo
				};
			}

			if (!authResult.user) {
				throw failure('oidc_user_info_missing', m.auth_oidc_user_info_missing());
			}

			return {
				authResult,
				redirectTo
			};
		},
		onSuccess: async ({ authResult, redirectTo }) => {
			if (authResult.status === 'mfa_required' && authResult.mfa) {
				pendingRedirect = redirectTo;
				mfaChallenge = authResult.mfa;
				return;
			}
			const user = await authService.completeAuthentication(authResult);
			await finalizeAuthentication(user, redirectTo);
		},
		onError: (err: unknown) => {
			console.error('OIDC callback error:', err);

			let redirectCode = 'oidc_callback_error';
			let userMessage: string = String(m.auth_oidc_callback_error());

			if (err && typeof err === 'object' && 'code' in err && 'userMessage' in err) {
				redirectCode = String((err as CallbackFailure).code);
				userMessage = String((err as CallbackFailure).userMessage);
			} else {
				const normalized = normalizeAuthenticationError(err, m.auth_oidc_callback_error());
				const unknownError = err as { message?: string };
				if (normalized.kind === 'proxy') {
					userMessage = normalized.message;
					redirectCode = 'proxy_authentication_failed';
				} else if (unknownError?.message?.includes('network') || unknownError?.message?.includes('timeout')) {
					userMessage = String(m.auth_oidc_network_error());
					redirectCode = 'oidc_network_error';
				} else if (normalized.message && !normalized.message.includes('Request failed')) {
					userMessage = normalized.message;
				}
			}

			error = userMessage;
			setTimeout(() => goto(buildLoginRedirect(redirectCode, userMessage)), 3000);
		}
	}));

	const isProcessing = $derived(callbackMutation.isPending);

	onMount(() => {
		callbackMutation.mutate();
	});
</script>

{#if mfaChallenge}
	<div class="flex min-h-dvh items-center justify-center p-6">
		<div class="w-full max-w-md">
			<MFAChallenge challenge={mfaChallenge} onComplete={completeMFA} />
		</div>
	</div>
{:else}
	<OidcStatusPanel
		busy={isProcessing}
		busyTitle={m.auth_processing_login()}
		busyDescription={m.auth_processing_login_description()}
		{error}
	>
		<!-- Defensive fallback: if neither branch matches (e.g. an
			     unexpected throw inside onSuccess), the user would otherwise
			     see a blank page with no way out. Always show a logout link. -->
		<p class="text-sm text-muted-foreground">{m.auth_processing_login()}</p>
		<a href="/logout" class="mt-6 text-xs text-primary underline">{m.common_logout()}</a>
	</OidcStatusPanel>
{/if}