fix idp on started

This commit is contained in:
lendry
2026-06-24 17:53:58 +03:00
parent b6987f4aea
commit 21f2a1c227
7 changed files with 211 additions and 50 deletions

View File

@@ -28,6 +28,8 @@ PUBLIC_API_URL=http://localhost:3000
PUBLIC_FRONTEND_URL=http://localhost:3002 PUBLIC_FRONTEND_URL=http://localhost:3002
PUBLIC_DOCS_URL=http://localhost:3003 PUBLIC_DOCS_URL=http://localhost:3003
PUBLIC_WS_URL=ws://localhost:8085/ws PUBLIC_WS_URL=ws://localhost:8085/ws
INTERNAL_API_URL=http://api-gateway:3000
INTERNAL_WS_URL=http://media-ws:8085
# Nginx (USE_NGINX_SSL=true только при SSL_TYPE=letsencrypt|selfsigned) # Nginx (USE_NGINX_SSL=true только при SSL_TYPE=letsencrypt|selfsigned)
USE_NGINX_SSL=false USE_NGINX_SSL=false

View File

@@ -7,6 +7,8 @@ WORKDIR /app
ARG NPM_REGISTRY=https://registry.npmjs.org ARG NPM_REGISTRY=https://registry.npmjs.org
ARG NEXT_PUBLIC_API_URL=http://localhost:3000 ARG NEXT_PUBLIC_API_URL=http://localhost:3000
ARG NEXT_PUBLIC_WS_URL=ws://localhost:8085/ws ARG NEXT_PUBLIC_WS_URL=ws://localhost:8085/ws
ARG INTERNAL_API_URL=http://api-gateway:3000
ARG INTERNAL_WS_URL=http://media-ws:8085
COPY package.json package-lock.json .npmrc ./ COPY package.json package-lock.json .npmrc ./
COPY apps/sso-core/package.json ./apps/sso-core/ COPY apps/sso-core/package.json ./apps/sso-core/
@@ -34,6 +36,8 @@ ENV PORT="3000"
ENV HOSTNAME="0.0.0.0" ENV HOSTNAME="0.0.0.0"
ENV NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}" ENV NEXT_PUBLIC_API_URL="${NEXT_PUBLIC_API_URL}"
ENV NEXT_PUBLIC_WS_URL="${NEXT_PUBLIC_WS_URL}" ENV NEXT_PUBLIC_WS_URL="${NEXT_PUBLIC_WS_URL}"
ENV INTERNAL_API_URL="${INTERNAL_API_URL}"
ENV INTERNAL_WS_URL="${INTERNAL_WS_URL}"
RUN npm --workspace @lendry/frontend run build RUN npm --workspace @lendry/frontend run build

View File

@@ -3,33 +3,59 @@
import Link from 'next/link'; import Link from 'next/link';
import { FormEvent, useState } from 'react'; import { FormEvent, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { ShieldCheck } from 'lucide-react'; import { ChevronLeft, UserRound } from 'lucide-react';
import { BrandLogo } from '@/components/id/brand-logo'; import { BrandLogo } from '@/components/id/brand-logo';
import { useAuth } from '@/components/id/auth-provider'; import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider'; import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { OtpInput } from '@/components/ui/otp-input';
import { PhoneInput, phoneCountries, toE164 } from '@/components/ui/phone-input'; import { PhoneInput, phoneCountries, toE164 } from '@/components/ui/phone-input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
type Step = 'contact' | 'otp' | 'pin';
export default function RegisterPage() { export default function RegisterPage() {
const router = useRouter(); const router = useRouter();
const { sendLoginOtp } = useAuth(); const { sendLoginOtp, verifyLoginOtp, completePin } = useAuth();
const { showToast } = useToast(); const { showToast } = useToast();
const [authTab, setAuthTab] = useState<'email' | 'phone'>('email'); const [authTab, setAuthTab] = useState<'email' | 'phone'>('email');
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [phoneNumber, setPhoneNumber] = useState(''); const [phoneNumber, setPhoneNumber] = useState('');
const [country, setCountry] = useState(phoneCountries[0]); const [country, setCountry] = useState(phoneCountries[0]);
const [recipient, setRecipient] = useState('');
const [maskedTarget, setMaskedTarget] = useState('');
const [otp, setOtp] = useState('');
const [pin, setPin] = useState('');
const [pendingSessionId, setPendingSessionId] = useState<string | null>(null);
const [step, setStep] = useState<Step>('contact');
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
async function handleSubmit(event: FormEvent<HTMLFormElement>) { function getIdentifier() {
return authTab === 'email' ? email.trim() : toE164(country, phoneNumber);
}
function finishRegistration(pinVerified: boolean, sessionId: string) {
if (!pinVerified) {
setPendingSessionId(sessionId);
setStep('pin');
return;
}
showToast('Добро пожаловать! ID успешно создан.');
router.push('/');
}
async function handleSendCode(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); event.preventDefault();
setIsSubmitting(true); setIsSubmitting(true);
try { try {
const recipient = authTab === 'email' ? email.trim() : toE164(country, phoneNumber); const identifier = getIdentifier();
await sendLoginOtp(recipient); setRecipient(identifier);
showToast('Код отправлен. Подтвердите его на экране входа.'); const masked = await sendLoginOtp(identifier);
router.push('/auth/login'); setMaskedTarget(masked);
setOtp('');
setStep('otp');
showToast('Код отправлен. Введите его ниже.');
} catch (error) { } catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось отправить код'); showToast(error instanceof Error ? error.message : 'Не удалось отправить код');
} finally { } finally {
@@ -37,15 +63,65 @@ export default function RegisterPage() {
} }
} }
async function verifyOtp(code: string) {
setIsSubmitting(true);
try {
const response = await verifyLoginOtp(recipient, code);
if (response.auth) {
finishRegistration(response.auth.pinVerified, response.auth.sessionId);
} else {
showToast('Не удалось завершить регистрацию');
}
} catch (error) {
setOtp('');
showToast(error instanceof Error ? error.message : 'Неверный код');
} finally {
setIsSubmitting(false);
}
}
async function handlePinSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!pendingSessionId) return;
setIsSubmitting(true);
try {
await completePin(pendingSessionId, pin);
showToast('Добро пожаловать! ID успешно создан.');
router.push('/');
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось проверить PIN-код');
} finally {
setIsSubmitting(false);
}
}
function resetToContact() {
setStep('contact');
setOtp('');
setPin('');
setPendingSessionId(null);
}
return ( return (
<main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_center,#5d6578_0%,#2c2736_48%,#111016_100%)] px-5"> <main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_center,#5d6578_0%,#2c2736_48%,#111016_100%)] px-5">
<section className="w-full max-w-[430px] rounded-[34px] bg-[#1f2028] px-9 py-10 text-white shadow-2xl"> <section className="w-full max-w-[430px] rounded-[34px] bg-[#1f2028] px-9 py-10 text-white shadow-2xl">
<div className="flex flex-col items-center text-center"> <div className="flex flex-col items-center text-center">
<BrandLogo size="lg" variant="light" /> <BrandLogo size="lg" variant="light" />
<h1 className="mt-8 text-xl font-bold">Создайте ID</h1> <h1 className="mt-8 text-xl font-bold">Создайте ID</h1>
<p className="mt-2 text-sm text-[#b9bdc9]">Введите почту или телефон. Пароль не нужен.</p> <p className="mt-2 text-sm text-[#b9bdc9]">
{step === 'contact' ? 'Введите почту или телефон. Пароль не нужен.' : 'Подтвердите код — аккаунт создастся автоматически.'}
</p>
</div> </div>
<form className="mt-8 space-y-3" onSubmit={handleSubmit}>
{step !== 'contact' ? (
<button type="button" onClick={resetToContact} className="mt-6 flex items-center gap-1 text-sm text-[#b9bdc9] hover:text-white">
<ChevronLeft className="h-4 w-4" />
Изменить почту или телефон
</button>
) : null}
{step === 'contact' ? (
<form className="mt-8 space-y-3" onSubmit={handleSendCode}>
<Tabs value={authTab} onValueChange={(value) => setAuthTab(value as 'email' | 'phone')} className="w-full"> <Tabs value={authTab} onValueChange={(value) => setAuthTab(value as 'email' | 'phone')} className="w-full">
<TabsList className="grid w-full grid-cols-2"> <TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="email">Почта</TabsTrigger> <TabsTrigger value="email">Почта</TabsTrigger>
@@ -69,9 +145,47 @@ export default function RegisterPage() {
{isSubmitting ? 'Отправляем...' : 'Получить код'} {isSubmitting ? 'Отправляем...' : 'Получить код'}
</Button> </Button>
</form> </form>
) : null}
{step === 'otp' ? (
<div className="mt-8">
<div className="mb-5 flex items-center gap-3 rounded-[20px] bg-[#2a2c36] p-3">
<div className="flex h-11 w-11 items-center justify-center rounded-full bg-white/10">
<UserRound className="h-5 w-5" />
</div>
<div className="min-w-0 text-left">
<p className="text-sm text-[#b9bdc9]">Код отправлен на</p>
<p className="truncate text-sm font-semibold">{maskedTarget || recipient}</p>
</div>
</div>
<OtpInput value={otp} onChange={setOtp} onComplete={verifyOtp} disabled={isSubmitting} />
{isSubmitting ? <p className="mt-3 text-center text-sm text-[#b9bdc9]">Создаём ваш ID...</p> : null}
</div>
) : null}
{step === 'pin' && pendingSessionId ? (
<form onSubmit={handlePinSubmit} className="mt-8 space-y-3">
<p className="text-center text-sm text-[#b9bdc9]">Установите PIN для завершения регистрации</p>
<Input
className="h-[58px] border-[#555762] bg-transparent text-center text-lg tracking-[0.4em] text-white placeholder:text-[#8f92a0]"
placeholder="PIN"
value={pin}
onChange={(event) => setPin(event.target.value)}
required
minLength={4}
maxLength={6}
/>
<Button variant="white" size="lg" className="w-full rounded-[18px] text-base" disabled={isSubmitting}>
{isSubmitting ? 'Проверяем...' : 'Подтвердить PIN'}
</Button>
</form>
) : null}
{step === 'contact' ? (
<Button asChild variant="ghost" className="mt-5 w-full text-white hover:bg-[#2a2c36]"> <Button asChild variant="ghost" className="mt-5 w-full text-white hover:bg-[#2a2c36]">
<Link href="/auth/login">У меня уже есть ID</Link> <Link href="/auth/login">У меня уже есть ID</Link>
</Button> </Button>
) : null}
</section> </section>
</main> </main>
); );

View File

@@ -9,8 +9,8 @@ function resolveBrowserApiBaseUrl(): string {
try { try {
const configured = new URL(configuredApiUrl); const configured = new URL(configuredApiUrl);
if (configured.origin !== window.location.origin) { if (configured.hostname !== window.location.hostname) {
return `${window.location.origin}${API_ORIGIN_PROXY_PREFIX}`; return API_ORIGIN_PROXY_PREFIX;
} }
} catch { } catch {
// keep configured URL // keep configured URL
@@ -24,9 +24,15 @@ function resolveBrowserWsBaseUrl(): string {
return configuredWsUrl; return configuredWsUrl;
} }
const apiBase = resolveBrowserApiBaseUrl();
if (apiBase === API_ORIGIN_PROXY_PREFIX) {
const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${scheme}//${window.location.host}${API_ORIGIN_PROXY_PREFIX}/ws`;
}
try { try {
const configured = new URL(configuredWsUrl); const configured = new URL(configuredWsUrl);
if (configured.origin !== window.location.origin) { if (configured.hostname !== window.location.hostname) {
const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const scheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${scheme}//${window.location.host}${API_ORIGIN_PROXY_PREFIX}/ws`; return `${scheme}//${window.location.host}${API_ORIGIN_PROXY_PREFIX}/ws`;
} }

View File

@@ -1,7 +1,27 @@
import type { NextConfig } from 'next'; import type { NextConfig } from 'next';
const internalApiUrl = (
process.env.INTERNAL_API_URL ??
process.env.NEXT_PUBLIC_API_URL ??
'http://localhost:3000'
).replace(/\/$/, '');
const internalWsUrl = (process.env.INTERNAL_WS_URL ?? 'http://media-ws:8085').replace(/\/$/, '');
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
typedRoutes: false typedRoutes: false,
async rewrites() {
return [
{
source: '/idp-api/ws',
destination: `${internalWsUrl}/ws`
},
{
source: '/idp-api/:path*',
destination: `${internalApiUrl}/:path*`
}
];
}
}; };
export default nextConfig; export default nextConfig;

View File

@@ -201,6 +201,8 @@ services:
NPM_REGISTRY: ${NPM_REGISTRY:-https://registry.npmjs.org} NPM_REGISTRY: ${NPM_REGISTRY:-https://registry.npmjs.org}
NEXT_PUBLIC_API_URL: ${PUBLIC_API_URL:-http://localhost:3000} NEXT_PUBLIC_API_URL: ${PUBLIC_API_URL:-http://localhost:3000}
NEXT_PUBLIC_WS_URL: ${PUBLIC_WS_URL:-ws://localhost:8085/ws} NEXT_PUBLIC_WS_URL: ${PUBLIC_WS_URL:-ws://localhost:8085/ws}
INTERNAL_API_URL: ${INTERNAL_API_URL:-http://api-gateway:3000}
INTERNAL_WS_URL: ${INTERNAL_WS_URL:-http://media-ws:8085}
container_name: lendry-id-frontend container_name: lendry-id-frontend
restart: unless-stopped restart: unless-stopped
environment: environment:
@@ -209,6 +211,8 @@ services:
NEXT_TELEMETRY_DISABLED: 1 NEXT_TELEMETRY_DISABLED: 1
NEXT_PUBLIC_API_URL: ${PUBLIC_API_URL:-http://localhost:3000} NEXT_PUBLIC_API_URL: ${PUBLIC_API_URL:-http://localhost:3000}
NEXT_PUBLIC_WS_URL: ${PUBLIC_WS_URL:-ws://localhost:8085/ws} NEXT_PUBLIC_WS_URL: ${PUBLIC_WS_URL:-ws://localhost:8085/ws}
INTERNAL_API_URL: ${INTERNAL_API_URL:-http://api-gateway:3000}
INTERNAL_WS_URL: ${INTERNAL_WS_URL:-http://media-ws:8085}
ports: ports:
- "127.0.0.1:3002:3000" - "127.0.0.1:3002:3000"
depends_on: depends_on:

View File

@@ -10,7 +10,7 @@
set -euo pipefail set -euo pipefail
SCRIPT_VERSION="2.2.2" SCRIPT_VERSION="2.2.3"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR" cd "$ROOT_DIR"
@@ -1323,11 +1323,12 @@ EOF
} }
build_nginx_idp_api_proxy_block() { build_nginx_idp_api_proxy_block() {
local api_upstream local api_upstream ws_upstream
api_upstream="$(nginx_upstream api)" api_upstream="$(nginx_upstream api)"
ws_upstream="$(nginx_upstream ws)"
cat <<EOF cat <<EOF
location /idp-api/ws { location /idp-api/ws {
proxy_pass ${api_upstream}/ws; proxy_pass ${ws_upstream}/ws;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade; proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
@@ -1893,6 +1894,22 @@ action_configure_domains() {
print_summary print_summary
} }
apply_intranet_selfsigned_runtime() {
load_env
[[ "$(env_get SSL_TYPE none)" == "selfsigned" ]] || return 0
[[ -n "$(env_get DOMAIN_FRONTEND "")" ]] || return 0
derive_public_urls "selfsigned"
env_set PUBLIC_API_URL "${PUBLIC_API_URL}"
env_set PUBLIC_WS_URL "${PUBLIC_WS_URL}"
env_set INTERNAL_API_URL "http://api-gateway:3000"
env_set INTERNAL_WS_URL "http://media-ws:8085"
log "Пересборка frontend (same-origin /idp-api)..."
build_compose_stack_cmd
docker_cmd "${COMPOSE_STACK_CMD[@]}" up -d --build frontend
}
action_renew_ssl() { action_renew_ssl() {
load_env load_env
local ssl_type local ssl_type
@@ -1908,7 +1925,8 @@ action_renew_ssl() {
selfsigned) selfsigned)
generate_all_self_signed_certs --force generate_all_self_signed_certs --force
write_all_nginx_configs "selfsigned" write_all_nginx_configs "selfsigned"
ok "Самоподписанные сертификаты пересозданы" apply_intranet_selfsigned_runtime
ok "Самоподписанные сертификаты пересозданы, frontend обновлён"
;; ;;
none) none)
fail "SSL отключён (SSL_TYPE=none). Выберите --ssl selfsigned или letsencrypt." fail "SSL отключён (SSL_TYPE=none). Выберите --ssl selfsigned или letsencrypt."
@@ -1939,14 +1957,7 @@ action_fix_host_proxy() {
log "Шаг 4/4: конфиги системного Nginx..." log "Шаг 4/4: конфиги системного Nginx..."
refresh_host_nginx_configs refresh_host_nginx_configs
if [[ "$(env_get SSL_TYPE none)" == "selfsigned" && -n "$(env_get DOMAIN_FRONTEND "")" ]]; then apply_intranet_selfsigned_runtime
derive_public_urls "selfsigned"
env_set PUBLIC_API_URL "${PUBLIC_API_URL}"
env_set PUBLIC_WS_URL "${PUBLIC_WS_URL}"
log "Шаг 5/5: пересборка frontend (same-origin API для HTTPS)..."
build_compose_stack_cmd
docker_cmd "${COMPOSE_STACK_CMD[@]}" up -d --build frontend
fi
ok "Прокси исправлен — проверьте: curl -I http://127.0.0.1:3002" ok "Прокси исправлен — проверьте: curl -I http://127.0.0.1:3002"
show_status show_status