fix and update

This commit is contained in:
lendry
2026-06-30 09:11:55 +03:00
parent f1d6a5167f
commit 250976ca08
5 changed files with 94 additions and 142 deletions

View File

@@ -11,15 +11,10 @@ import { Button } from '@/components/ui/button';
import { import {
approveOAuthAuthorization, approveOAuthAuthorization,
checkOAuthConsent, checkOAuthConsent,
fetchAuthSession,
fetchOAuthClientPublicInfo, fetchOAuthClientPublicInfo,
type OAuthConsentCheckResponse type OAuthConsentCheckResponse
} from '@/lib/api'; } from '@/lib/api';
import { import { deliverOAuthPopupResult, parsePopupOAuthParams, postOneTapResult } from '@/lib/oauth-popup-bridge';
parseAuthorizationRedirect,
parsePopupOAuthParams,
postOneTapResult
} from '@/lib/oauth-popup-bridge';
function buildOAuthQuery(searchParams: URLSearchParams) { function buildOAuthQuery(searchParams: URLSearchParams) {
const params = new URLSearchParams(); const params = new URLSearchParams();
@@ -37,7 +32,6 @@ function OAuthAuthorizeContent() {
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [checkingConsent, setCheckingConsent] = useState(false); const [checkingConsent, setCheckingConsent] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [sessionChecked, setSessionChecked] = useState(false);
const [consentInfo, setConsentInfo] = useState<OAuthConsentCheckResponse | null>(null); const [consentInfo, setConsentInfo] = useState<OAuthConsentCheckResponse | null>(null);
const [clientName, setClientName] = useState<string | null>(null); const [clientName, setClientName] = useState<string | null>(null);
const autoApproveStartedRef = useRef(false); const autoApproveStartedRef = useRef(false);
@@ -55,20 +49,26 @@ function OAuthAuthorizeContent() {
const clientLabel = clientName ?? consentInfo?.client?.name ?? 'Приложение'; const clientLabel = clientName ?? consentInfo?.client?.name ?? 'Приложение';
useEffect(() => { const approve = useCallback(async () => {
if (!clientId || isLoading) return; if (!token || !user || isPinLocked) return;
let cancelled = false; setSubmitting(true);
void fetchOAuthClientPublicInfo(clientId) setError(null);
.then((info) => { try {
if (!cancelled && info.name.trim()) { const data = await approveOAuthAuthorization(oauthQuery, token);
setClientName(info.name.trim()); if (!data.redirectUrl) {
} throw new Error('Сервер не вернул redirect URL');
}) }
.catch(() => undefined); if (deliverOAuthPopupResult(popupContext, data.redirectUrl) === 'popup') {
return () => { return;
cancelled = true; }
}; window.location.href = data.redirectUrl;
}, [clientId, isLoading]); } catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка OAuth авторизации');
autoApproveStartedRef.current = false;
} finally {
setSubmitting(false);
}
}, [isPinLocked, oauthQuery, popupContext, token, user]);
useEffect(() => { useEffect(() => {
if (!searchParams.has('userId')) return; if (!searchParams.has('userId')) return;
@@ -84,72 +84,24 @@ function OAuthAuthorizeContent() {
}, [clientId, isLoading, isPinLocked, redirectUri, returnUrl, router, token, user]); }, [clientId, isLoading, isPinLocked, redirectUri, returnUrl, router, token, user]);
useEffect(() => { useEffect(() => {
if (isLoading || isPinLocked || !token || !user) { if (isLoading || !token || !clientId || isPinLocked) return;
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;
let cancelled = false; let cancelled = false;
setCheckingConsent(true); setCheckingConsent(true);
void checkOAuthConsent(oauthQuery, token) setError(null);
.then((result) => {
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; if (cancelled) return;
setConsentInfo(result); setConsentInfo(result);
if (result.client?.name?.trim()) { if (result.client?.name?.trim()) {
@@ -159,28 +111,27 @@ function OAuthAuthorizeContent() {
autoApproveStartedRef.current = true; autoApproveStartedRef.current = true;
void approve(); void approve();
} }
}) } catch (err) {
.catch((err) => {
if (!cancelled) { if (!cancelled) {
setError(err instanceof Error ? err.message : 'Не удалось проверить согласие'); setError(err instanceof Error ? err.message : 'Не удалось проверить согласие');
} }
}) } finally {
.finally(() => {
if (!cancelled) setCheckingConsent(false); if (!cancelled) setCheckingConsent(false);
}); }
})();
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [approve, clientId, isPinLocked, oauthQuery, sessionChecked, token]); }, [approve, clientId, isLoading, isPinLocked, oauthQuery, token]);
const cancel = useCallback(() => { const cancel = useCallback(() => {
if (popupContext) { if (popupContext) {
postOneTapResult(popupContext.popupOrigin, { const delivered = postOneTapResult(popupContext.popupOrigin, {
error: 'access_denied', error: 'access_denied',
errorDescription: 'Пользователь отклонил запрос' errorDescription: 'Пользователь отклонил запрос'
}); });
return; if (delivered) return;
} }
if (!redirectUri) { if (!redirectUri) {
@@ -198,7 +149,7 @@ function OAuthAuthorizeContent() {
} }
}, [popupContext, redirectUri, router, state]); }, [popupContext, redirectUri, router, state]);
const authReady = Boolean(user && token && !isPinLocked && sessionChecked); const authReady = Boolean(user && token && !isPinLocked && !isLoading);
const scopeItems = consentInfo?.requestedScopes ?? []; const scopeItems = consentInfo?.requestedScopes ?? [];
if (isLoading || (clientId && redirectUri && !authReady && !isPinLocked)) { if (isLoading || (clientId && redirectUri && !authReady && !isPinLocked)) {

View File

@@ -567,6 +567,7 @@ let fedcmSyncInFlight = false;
/** Откладывает FedCM sync после OAuth/bootstrap, чтобы не конкурировать с consent/session. */ /** Откладывает FedCM sync после OAuth/bootstrap, чтобы не конкурировать с consent/session. */
export function scheduleFedcmSessionSync(accessToken?: string | null, delayMs = 1500) { export function scheduleFedcmSessionSync(accessToken?: string | null, delayMs = 1500) {
if (typeof window === 'undefined') return; if (typeof window === 'undefined') return;
if (window.location.pathname.startsWith('/auth/oauth/authorize')) return;
if (fedcmSyncTimer) { if (fedcmSyncTimer) {
clearTimeout(fedcmSyncTimer); clearTimeout(fedcmSyncTimer);
} }
@@ -676,12 +677,9 @@ export function buildSystemSettingPayload(setting: Pick<SystemSetting, 'key' | '
} }
const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]); const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]);
const GATEWAY_RETRY_ATTEMPTS = 6; const GATEWAY_RETRY_ATTEMPTS = 2;
const GATEWAY_WARMUP_INITIAL_DELAY_MS = 500; const GATEWAY_PROBE_MAX_ATTEMPTS = 4;
const GATEWAY_WARMUP_DELAY_MS = 450; const GATEWAY_PROBE_DELAY_MS = 600;
const GATEWAY_READY_CONSECUTIVE_OK = 1;
const GATEWAY_WARMUP_MAX_DELAY_MS = 2200;
const GATEWAY_WARMUP_MAX_TOTAL_MS = 90_000;
function sleep(ms: number): Promise<void> { function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
@@ -722,30 +720,18 @@ async function probeGatewayAlive(): Promise<boolean> {
} }
async function waitForGatewayAlive(): Promise<void> { async function waitForGatewayAlive(): Promise<void> {
await sleep(GATEWAY_WARMUP_INITIAL_DELAY_MS); for (let attempt = 0; attempt < GATEWAY_PROBE_MAX_ATTEMPTS; attempt += 1) {
const deadline = Date.now() + GATEWAY_WARMUP_MAX_TOTAL_MS;
let consecutiveOk = 0;
let attempt = 0;
while (Date.now() < deadline) {
if (await probeGatewayAlive()) { if (await probeGatewayAlive()) {
consecutiveOk += 1; gatewayReadyResolved = true;
if (consecutiveOk >= GATEWAY_READY_CONSECUTIVE_OK) { return;
gatewayReadyResolved = true; }
return; if (attempt + 1 < GATEWAY_PROBE_MAX_ATTEMPTS) {
} await sleep(GATEWAY_PROBE_DELAY_MS * (attempt + 1));
} else {
consecutiveOk = 0;
} }
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<void> { export async function ensureApiGatewayReady(force = false): Promise<void> {
if (typeof window === 'undefined') return; if (typeof window === 'undefined') return;
if (gatewayReadyResolved && !force) return; if (gatewayReadyResolved && !force) return;
@@ -763,7 +749,7 @@ export async function ensureApiGatewayReady(force = false): Promise<void> {
} }
function gatewayRetryDelay(attempt: number): number { function gatewayRetryDelay(attempt: number): number {
return Math.min(500 * (attempt + 1), 2800); return 700 + attempt * 400;
} }
/** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */ /** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */
@@ -793,7 +779,7 @@ async function fetchWithGatewayRetry(url: string, init: RequestInit): Promise<Re
} }
export async function apiFetch<T>(path: string, options: RequestInit = {}, token?: string | null, allowRetry = true): Promise<T> { export async function apiFetch<T>(path: string, options: RequestInit = {}, token?: string | null, allowRetry = true): Promise<T> {
if (typeof window !== 'undefined' && !path.startsWith('/health')) { if (typeof window !== 'undefined' && !gatewayReadyResolved && !path.startsWith('/health')) {
await ensureApiGatewayReady(); await ensureApiGatewayReady();
} }
@@ -839,12 +825,6 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}, token
} }
} }
if (allowRetry && isGatewayUnavailableError(error)) {
invalidateApiGatewayReady();
await sleep(900);
return apiFetch<T>(path, options, token, false);
}
throw error; throw error;
} }

View File

@@ -14,14 +14,38 @@ export function parsePopupOAuthParams(searchParams: URLSearchParams) {
} }
} }
export function postOneTapResult(popupOrigin: string, payload: Record<string, unknown>) { export function postOneTapResult(popupOrigin: string, payload: Record<string, unknown>): boolean {
if (!window.opener) { if (!window.opener || window.opener.closed) {
return false; return false;
} }
window.opener.postMessage({ type: ONE_TAP_MESSAGE_TYPE, ...payload }, popupOrigin); try {
window.close(); window.opener.postMessage({ type: ONE_TAP_MESSAGE_TYPE, ...payload }, popupOrigin);
return true; 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) { export function parseAuthorizationRedirect(redirectUrl: string) {

View File

@@ -339,6 +339,7 @@
var height = 640; var height = 640;
var left = Math.max(0, Math.round((global.screen.width - width) / 2)); var left = Math.max(0, Math.round((global.screen.width - width) / 2));
var top = Math.max(0, Math.round((global.screen.height - height) / 2)); var top = Math.max(0, Math.round((global.screen.height - height) / 2));
// Без noopener/noreferrer: popup должен видеть window.opener для postMessage после «Разрешить».
var features = var features =
'popup=yes,width=' + 'popup=yes,width=' +
width + width +
@@ -347,8 +348,7 @@
',left=' + ',left=' +
left + left +
',top=' + ',top=' +
top + top;
',noopener,noreferrer';
var popup = global.open(url, 'lendry_sso_onetap', features); var popup = global.open(url, 'lendry_sso_onetap', features);
if (!popup) { if (!popup) {

View File

@@ -1942,10 +1942,7 @@ nginx_proxy_headers=" proxy_set_header Host \$host;
proxy_set_header X-Forwarded-Host \$host; proxy_set_header X-Forwarded-Host \$host;
proxy_set_header Authorization \$http_authorization; proxy_set_header Authorization \$http_authorization;
proxy_read_timeout 300s; proxy_read_timeout 300s;
proxy_connect_timeout 75s; 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;"
# Встроенный DNS Docker. В docker-режиме nginx обязан перерезолвлять имена # Встроенный DNS Docker. В docker-режиме nginx обязан перерезолвлять имена
# бэкенд-контейнеров на каждый запрос — иначе после пересборки контейнера # бэкенд-контейнеров на каждый запрос — иначе после пересборки контейнера
@@ -1986,16 +1983,16 @@ render_proxy_rewrite() {
fi fi
} }
# proxy_pass для /idp-api/ — named capture надёжнее rewrite+break с переменной upstream. # proxy_pass для /idp-api/ — prefix ^~ выше regex; rewrite снимает префикс перед api-gateway.
render_proxy_idp_api() { render_proxy_idp_api() {
local key="api" up var local key="api" up var
up="$(nginx_upstream "$key")" up="$(nginx_upstream "$key")"
if [[ "$NGINX_MODE" == "docker" ]]; then if [[ "$NGINX_MODE" == "docker" ]]; then
var="$(nginx_upstream_var "$key")" 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" "$NGINX_DOCKER_RESOLVER" "$var" "$up" "$var"
else else
printf ' proxy_pass %s/$api_path$is_args$args;' "$up" printf ' rewrite ^/idp-api/?(.*)$ /$1 break;\n proxy_pass %s;' "$up"
fi fi
} }
@@ -2190,7 +2187,7 @@ ${proxy_ws}
proxy_connect_timeout 75s; proxy_connect_timeout 75s;
} }
location ~ ^/idp-api/(?<api_path>.*)$ { location ^~ /idp-api/ {
${proxy_idp} ${proxy_idp}
proxy_http_version 1.1; proxy_http_version 1.1;
${nginx_proxy_headers} ${nginx_proxy_headers}
@@ -2501,7 +2498,7 @@ validate_docker_frontend_nginx_config() {
local conf="${LOCAL_CONF_DIR}/${NGINX_PREFIX}-frontend.conf" local conf="${LOCAL_CONF_DIR}/${NGINX_PREFIX}-frontend.conf"
[[ -f "$conf" ]] || fail "Не найден ${conf} — конфиг SSO-домена не записан" [[ -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" fail "Конфиг ${conf} без location /idp-api — браузер SPA получит 502. Выполните ./install.sh --fix-all"
fi fi
if ! grep -q 'resolver 127.0.0.11' "$conf" 2>/dev/null; then if ! grep -q 'resolver 127.0.0.11' "$conf" 2>/dev/null; then