diff --git a/apps/frontend/app/auth/oauth/authorize/page.tsx b/apps/frontend/app/auth/oauth/authorize/page.tsx index 292540f..a2856c3 100644 --- a/apps/frontend/app/auth/oauth/authorize/page.tsx +++ b/apps/frontend/app/auth/oauth/authorize/page.tsx @@ -11,15 +11,10 @@ import { Button } from '@/components/ui/button'; import { approveOAuthAuthorization, checkOAuthConsent, - fetchAuthSession, fetchOAuthClientPublicInfo, type OAuthConsentCheckResponse } from '@/lib/api'; -import { - parseAuthorizationRedirect, - parsePopupOAuthParams, - postOneTapResult -} from '@/lib/oauth-popup-bridge'; +import { deliverOAuthPopupResult, parsePopupOAuthParams, postOneTapResult } from '@/lib/oauth-popup-bridge'; function buildOAuthQuery(searchParams: URLSearchParams) { const params = new URLSearchParams(); @@ -37,7 +32,6 @@ function OAuthAuthorizeContent() { const [submitting, setSubmitting] = useState(false); const [checkingConsent, setCheckingConsent] = useState(false); const [error, setError] = useState(null); - const [sessionChecked, setSessionChecked] = useState(false); const [consentInfo, setConsentInfo] = useState(null); const [clientName, setClientName] = useState(null); const autoApproveStartedRef = useRef(false); @@ -55,20 +49,26 @@ function OAuthAuthorizeContent() { const clientLabel = clientName ?? consentInfo?.client?.name ?? 'Приложение'; - useEffect(() => { - if (!clientId || isLoading) return; - let cancelled = false; - void fetchOAuthClientPublicInfo(clientId) - .then((info) => { - if (!cancelled && info.name.trim()) { - setClientName(info.name.trim()); - } - }) - .catch(() => undefined); - return () => { - cancelled = true; - }; - }, [clientId, isLoading]); + const approve = useCallback(async () => { + if (!token || !user || isPinLocked) return; + setSubmitting(true); + setError(null); + try { + const data = await approveOAuthAuthorization(oauthQuery, token); + if (!data.redirectUrl) { + throw new Error('Сервер не вернул redirect URL'); + } + if (deliverOAuthPopupResult(popupContext, data.redirectUrl) === 'popup') { + return; + } + window.location.href = data.redirectUrl; + } catch (err) { + setError(err instanceof Error ? err.message : 'Ошибка OAuth авторизации'); + autoApproveStartedRef.current = false; + } finally { + setSubmitting(false); + } + }, [isPinLocked, oauthQuery, popupContext, token, user]); useEffect(() => { if (!searchParams.has('userId')) return; @@ -84,72 +84,24 @@ function OAuthAuthorizeContent() { }, [clientId, isLoading, isPinLocked, redirectUri, returnUrl, router, token, user]); useEffect(() => { - if (isLoading || isPinLocked || !token || !user) { - setSessionChecked(false); - return; - } - - let cancelled = false; - void fetchAuthSession(token) - .then(() => { - if (!cancelled) setSessionChecked(true); - }) - .catch(() => { - if (!cancelled) { - setSessionChecked(false); - router.replace(`/auth/login?redirect=${encodeURIComponent(returnUrl)}`); - } - }); - - return () => { - cancelled = true; - }; - }, [isLoading, isPinLocked, returnUrl, router, token, user]); - - const finishPopupFlow = useCallback( - (redirectUrl: string) => { - if (!popupContext) return false; - const parsed = parseAuthorizationRedirect(redirectUrl); - postOneTapResult(popupContext.popupOrigin, { - code: parsed.code ?? undefined, - state: parsed.state ?? undefined, - token: parsed.code ?? undefined, - error: parsed.error ?? undefined, - errorDescription: parsed.errorDescription ?? undefined - }); - return true; - }, - [popupContext] - ); - - const approve = useCallback(async () => { - if (!token || !user || isPinLocked) return; - setSubmitting(true); - setError(null); - try { - const data = await approveOAuthAuthorization(oauthQuery, token); - if (!data.redirectUrl) { - throw new Error('Сервер не вернул redirect URL'); - } - if (finishPopupFlow(data.redirectUrl)) { - return; - } - window.location.href = data.redirectUrl; - } catch (err) { - setError(err instanceof Error ? err.message : 'Ошибка OAuth авторизации'); - autoApproveStartedRef.current = false; - } finally { - setSubmitting(false); - } - }, [finishPopupFlow, isPinLocked, oauthQuery, token, user]); - - useEffect(() => { - if (!token || !clientId || !sessionChecked || isPinLocked) return; + if (isLoading || !token || !clientId || isPinLocked) return; let cancelled = false; setCheckingConsent(true); - void checkOAuthConsent(oauthQuery, token) - .then((result) => { + setError(null); + + void (async () => { + try { + try { + const info = await fetchOAuthClientPublicInfo(clientId); + if (!cancelled && info.name.trim()) { + setClientName(info.name.trim()); + } + } catch { + // название приложения необязательно для consent + } + + const result = await checkOAuthConsent(oauthQuery, token); if (cancelled) return; setConsentInfo(result); if (result.client?.name?.trim()) { @@ -159,28 +111,27 @@ function OAuthAuthorizeContent() { autoApproveStartedRef.current = true; void approve(); } - }) - .catch((err) => { + } catch (err) { if (!cancelled) { setError(err instanceof Error ? err.message : 'Не удалось проверить согласие'); } - }) - .finally(() => { + } finally { if (!cancelled) setCheckingConsent(false); - }); + } + })(); return () => { cancelled = true; }; - }, [approve, clientId, isPinLocked, oauthQuery, sessionChecked, token]); + }, [approve, clientId, isLoading, isPinLocked, oauthQuery, token]); const cancel = useCallback(() => { if (popupContext) { - postOneTapResult(popupContext.popupOrigin, { + const delivered = postOneTapResult(popupContext.popupOrigin, { error: 'access_denied', errorDescription: 'Пользователь отклонил запрос' }); - return; + if (delivered) return; } if (!redirectUri) { @@ -198,7 +149,7 @@ function OAuthAuthorizeContent() { } }, [popupContext, redirectUri, router, state]); - const authReady = Boolean(user && token && !isPinLocked && sessionChecked); + const authReady = Boolean(user && token && !isPinLocked && !isLoading); const scopeItems = consentInfo?.requestedScopes ?? []; if (isLoading || (clientId && redirectUri && !authReady && !isPinLocked)) { diff --git a/apps/frontend/lib/api.ts b/apps/frontend/lib/api.ts index 538f185..87eca43 100644 --- a/apps/frontend/lib/api.ts +++ b/apps/frontend/lib/api.ts @@ -567,6 +567,7 @@ let fedcmSyncInFlight = false; /** Откладывает FedCM sync после OAuth/bootstrap, чтобы не конкурировать с consent/session. */ export function scheduleFedcmSessionSync(accessToken?: string | null, delayMs = 1500) { if (typeof window === 'undefined') return; + if (window.location.pathname.startsWith('/auth/oauth/authorize')) return; if (fedcmSyncTimer) { clearTimeout(fedcmSyncTimer); } @@ -676,12 +677,9 @@ export function buildSystemSettingPayload(setting: Pick { return new Promise((resolve) => setTimeout(resolve, ms)); @@ -722,30 +720,18 @@ async function probeGatewayAlive(): Promise { } async function waitForGatewayAlive(): Promise { - await sleep(GATEWAY_WARMUP_INITIAL_DELAY_MS); - const deadline = Date.now() + GATEWAY_WARMUP_MAX_TOTAL_MS; - let consecutiveOk = 0; - let attempt = 0; - - while (Date.now() < deadline) { + for (let attempt = 0; attempt < GATEWAY_PROBE_MAX_ATTEMPTS; attempt += 1) { if (await probeGatewayAlive()) { - consecutiveOk += 1; - if (consecutiveOk >= GATEWAY_READY_CONSECUTIVE_OK) { - gatewayReadyResolved = true; - return; - } - } else { - consecutiveOk = 0; + gatewayReadyResolved = true; + return; + } + if (attempt + 1 < GATEWAY_PROBE_MAX_ATTEMPTS) { + await sleep(GATEWAY_PROBE_DELAY_MS * (attempt + 1)); } - attempt += 1; - const delay = Math.min(GATEWAY_WARMUP_DELAY_MS * 1.28 ** attempt, GATEWAY_WARMUP_MAX_DELAY_MS); - await sleep(delay); } - - gatewayReadyResolved = true; } -/** Один общий прогрев перед API: без сброса promise и без десятков параллельных проб /health/ready. */ +/** Один общий прогрев: до 4 проб /health, без бесконечного цикла. */ export async function ensureApiGatewayReady(force = false): Promise { if (typeof window === 'undefined') return; if (gatewayReadyResolved && !force) return; @@ -763,7 +749,7 @@ export async function ensureApiGatewayReady(force = false): Promise { } function gatewayRetryDelay(attempt: number): number { - return Math.min(500 * (attempt + 1), 2800); + return 700 + attempt * 400; } /** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */ @@ -793,7 +779,7 @@ async function fetchWithGatewayRetry(url: string, init: RequestInit): Promise(path: string, options: RequestInit = {}, token?: string | null, allowRetry = true): Promise { - if (typeof window !== 'undefined' && !path.startsWith('/health')) { + if (typeof window !== 'undefined' && !gatewayReadyResolved && !path.startsWith('/health')) { await ensureApiGatewayReady(); } @@ -839,12 +825,6 @@ export async function apiFetch(path: string, options: RequestInit = {}, token } } - if (allowRetry && isGatewayUnavailableError(error)) { - invalidateApiGatewayReady(); - await sleep(900); - return apiFetch(path, options, token, false); - } - throw error; } diff --git a/apps/frontend/lib/oauth-popup-bridge.ts b/apps/frontend/lib/oauth-popup-bridge.ts index 2dc2b68..64cca19 100644 --- a/apps/frontend/lib/oauth-popup-bridge.ts +++ b/apps/frontend/lib/oauth-popup-bridge.ts @@ -14,14 +14,38 @@ export function parsePopupOAuthParams(searchParams: URLSearchParams) { } } -export function postOneTapResult(popupOrigin: string, payload: Record) { - if (!window.opener) { +export function postOneTapResult(popupOrigin: string, payload: Record): boolean { + if (!window.opener || window.opener.closed) { return false; } - window.opener.postMessage({ type: ONE_TAP_MESSAGE_TYPE, ...payload }, popupOrigin); - window.close(); - return true; + try { + window.opener.postMessage({ type: ONE_TAP_MESSAGE_TYPE, ...payload }, popupOrigin); + window.close(); + return true; + } catch { + return false; + } +} + +export function deliverOAuthPopupResult( + popupContext: { popupOrigin: string } | null, + redirectUrl: string +): 'popup' | 'redirect' { + if (!popupContext) { + return 'redirect'; + } + + const parsed = parseAuthorizationRedirect(redirectUrl); + const delivered = postOneTapResult(popupContext.popupOrigin, { + code: parsed.code ?? undefined, + state: parsed.state ?? undefined, + token: parsed.code ?? undefined, + error: parsed.error ?? undefined, + errorDescription: parsed.errorDescription ?? undefined + }); + + return delivered ? 'popup' : 'redirect'; } export function parseAuthorizationRedirect(redirectUrl: string) { diff --git a/apps/frontend/public/sso-widget.js b/apps/frontend/public/sso-widget.js index 289c7d8..88ca218 100644 --- a/apps/frontend/public/sso-widget.js +++ b/apps/frontend/public/sso-widget.js @@ -339,6 +339,7 @@ var height = 640; var left = Math.max(0, Math.round((global.screen.width - width) / 2)); var top = Math.max(0, Math.round((global.screen.height - height) / 2)); + // Без noopener/noreferrer: popup должен видеть window.opener для postMessage после «Разрешить». var features = 'popup=yes,width=' + width + @@ -347,8 +348,7 @@ ',left=' + left + ',top=' + - top + - ',noopener,noreferrer'; + top; var popup = global.open(url, 'lendry_sso_onetap', features); if (!popup) { diff --git a/install.sh b/install.sh index 5b7ef3e..1d9292b 100644 --- a/install.sh +++ b/install.sh @@ -1942,10 +1942,7 @@ nginx_proxy_headers=" proxy_set_header Host \$host; proxy_set_header X-Forwarded-Host \$host; proxy_set_header Authorization \$http_authorization; proxy_read_timeout 300s; - proxy_connect_timeout 75s; - proxy_next_upstream error timeout invalid_header http_502 http_503 http_504; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 10s;" + proxy_connect_timeout 75s;" # Встроенный DNS Docker. В docker-режиме nginx обязан перерезолвлять имена # бэкенд-контейнеров на каждый запрос — иначе после пересборки контейнера @@ -1986,16 +1983,16 @@ render_proxy_rewrite() { fi } -# proxy_pass для /idp-api/ — named capture надёжнее rewrite+break с переменной upstream. +# proxy_pass для /idp-api/ — prefix ^~ выше regex; rewrite снимает префикс перед api-gateway. render_proxy_idp_api() { local key="api" up var up="$(nginx_upstream "$key")" if [[ "$NGINX_MODE" == "docker" ]]; then var="$(nginx_upstream_var "$key")" - printf '%s\n set $%s %s;\n proxy_pass $%s/$api_path$is_args$args;' \ + printf '%s\n set $%s %s;\n rewrite ^/idp-api/?(.*)$ /$1 break;\n proxy_pass $%s;' \ "$NGINX_DOCKER_RESOLVER" "$var" "$up" "$var" else - printf ' proxy_pass %s/$api_path$is_args$args;' "$up" + printf ' rewrite ^/idp-api/?(.*)$ /$1 break;\n proxy_pass %s;' "$up" fi } @@ -2190,7 +2187,7 @@ ${proxy_ws} proxy_connect_timeout 75s; } - location ~ ^/idp-api/(?.*)$ { + location ^~ /idp-api/ { ${proxy_idp} proxy_http_version 1.1; ${nginx_proxy_headers} @@ -2501,7 +2498,7 @@ validate_docker_frontend_nginx_config() { local conf="${LOCAL_CONF_DIR}/${NGINX_PREFIX}-frontend.conf" [[ -f "$conf" ]] || fail "Не найден ${conf} — конфиг SSO-домена не записан" - if ! grep -q 'location.*idp-api' "$conf" 2>/dev/null; then + if ! grep -q 'location \^~ /idp-api/' "$conf" 2>/dev/null && ! grep -q 'location.*idp-api' "$conf" 2>/dev/null; then fail "Конфиг ${conf} без location /idp-api — браузер SPA получит 502. Выполните ./install.sh --fix-all" fi if ! grep -q 'resolver 127.0.0.11' "$conf" 2>/dev/null; then