/**
 * Authentication utility functions
 */

/**
 * Sanitize a redirect URL to prevent open redirect attacks.
 * Only allows relative paths starting with '/'.
 * Rejects protocol-relative URLs, absolute URLs, and javascript: URIs.
 */
export function sanitizeRedirectUrl(url: string | null | undefined): string {
	const fallback = '/dashboard';

	if (!url || typeof url !== 'string') {
		return fallback;
	}

	// Trim whitespace
	const trimmed = url.trim();

	// Reject empty strings
	if (!trimmed) {
		return fallback;
	}

	// Reject protocol-relative URLs (//evil.com)
	if (trimmed.startsWith('//')) {
		return fallback;
	}

	// Reject absolute URLs with protocols
	if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(trimmed)) {
		return fallback;
	}

	// Must start with a single forward slash (relative path)
	if (!trimmed.startsWith('/')) {
		return fallback;
	}

	// Reject paths that could be interpreted as protocol-relative after decoding
	try {
		const decoded = decodeURIComponent(trimmed);
		if (decoded.startsWith('//') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(decoded)) {
			return fallback;
		}
	} catch {
		// If decoding fails, reject the URL
		return fallback;
	}

	return trimmed;
}
