feat: монорепо миграция, Discover/SearxNG улучшения

- Миграция на монорепозиторий (apps/frontend, apps/chat-service, etc.)
- Discover: проверка SearxNG, понятное empty state при ненастроенном поиске
- searxng.ts: валидация URL, проверка JSON-ответа, авто-добавление http://
- docker/searxng-config: настройки для JSON API SearxNG

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
home
2026-02-20 17:03:43 +03:00
parent c839a0c472
commit 783569b8e7
344 changed files with 28299 additions and 6034 deletions

View File

@@ -0,0 +1,4 @@
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
export const { GET, POST } = toNextJsHandler(auth);

View File

@@ -0,0 +1,31 @@
'use client';
import { authClient } from '@/lib/auth-client';
import { useRouter } from 'next/navigation';
export function SignOutButton() {
const router = useRouter();
const handleSignOut = async () => {
await authClient.signOut();
router.push('/sign-in');
router.refresh();
};
return (
<button
onClick={handleSignOut}
type="button"
style={{
padding: '8px 16px',
background: '#f1f5f9',
border: '1px solid #e2e8f0',
borderRadius: 8,
cursor: 'pointer',
fontWeight: 500,
}}
>
Выйти
</button>
);
}

View File

@@ -0,0 +1,101 @@
import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { auth } from '@/lib/auth';
import { SignOutButton } from './SignOutButton';
export default async function DashboardPage() {
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session) {
redirect('/sign-in');
}
const discoveryUrl = `${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/.well-known/openid-configuration`;
return (
<div
style={{
minHeight: '100vh',
padding: 32,
background: '#f8fafc',
}}
>
<div style={{ maxWidth: 800, margin: '0 auto' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 32,
}}
>
<h1 style={{ margin: 0, fontSize: 28, fontWeight: 700 }}>
Auth Service Identity Provider
</h1>
<SignOutButton />
</div>
<div
style={{
background: '#fff',
padding: 24,
borderRadius: 12,
boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
marginBottom: 24,
}}
>
<h2 style={{ margin: '0 0 16px', fontSize: 18 }}>Ваш профиль</h2>
<p style={{ margin: 0, color: '#64748b' }}>
<strong>Email:</strong> {session.user.email}
</p>
<p style={{ margin: '8px 0 0', color: '#64748b' }}>
<strong>Имя:</strong> {session.user.name || '—'}
</p>
</div>
<div
style={{
background: '#fff',
padding: 24,
borderRadius: 12,
boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
}}
>
<h2 style={{ margin: '0 0 16px', fontSize: 18 }}>
Интеграция с приложениями
</h2>
<p style={{ margin: '0 0 16px', color: '#64748b', fontSize: 14 }}>
Этот сервис выступает как OIDC Identity Provider. Подключите ваши
приложения, указав следующие параметры:
</p>
<pre
style={{
padding: 16,
background: '#1e293b',
color: '#e2e8f0',
borderRadius: 8,
overflow: 'auto',
fontSize: 13,
}}
>
{`Authorization URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/authorize
Token URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/token
UserInfo URL: ${process.env.BETTER_AUTH_URL || 'http://localhost:3001'}/api/auth/oauth2/userinfo
Discovery: ${discoveryUrl}
Scopes: openid profile email`}
</pre>
<p style={{ margin: '16px 0 0', color: '#64748b', fontSize: 14 }}>
Зарегистрируйте клиента через API{' '}
<code style={{ background: '#f1f5f9', padding: '2px 6px', borderRadius: 4 }}>
POST /api/auth/oauth2/register
</code>{' '}
или настройте trusted clients в конфигурации сервиса.
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,18 @@
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Auth Service — Identity Provider',
description: 'Централизованный сервис аутентификации с SSO, LDAP и OIDC',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ru">
<body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>
</html>
);
}

View File

@@ -0,0 +1,13 @@
import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { auth } from '@/lib/auth';
export default async function HomePage() {
const session = await auth.api.getSession({ headers: await headers() });
if (session) {
redirect('/dashboard');
}
redirect('/sign-in');
}

View File

@@ -0,0 +1,244 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { authClient } from '@/lib/auth-client';
import Link from 'next/link';
type Tab = 'password' | 'ldap';
export default function SignInPage() {
const router = useRouter();
const [tab, setTab] = useState<Tab>('password');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [credential, setCredential] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const ldapEnabled = process.env.NEXT_PUBLIC_LDAP_ENABLED === 'true';
const handleEmailSignIn = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const { error } = await authClient.signIn.email({ email, password });
if (error) throw new Error(error.message);
router.push('/dashboard');
router.refresh();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Ошибка входа');
} finally {
setLoading(false);
}
};
const handleLdapSignIn = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const res = await fetch('/api/auth/sign-in/ldap', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential, password, callbackURL: '/dashboard' }),
credentials: 'include',
});
const data = await res.json();
if (!res.ok || data?.error) throw new Error(data?.message || data?.error?.message || 'Ошибка входа');
router.push('/dashboard');
router.refresh();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Ошибка LDAP входа');
} finally {
setLoading(false);
}
};
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
}}
>
<div
style={{
width: '100%',
maxWidth: 400,
padding: 32,
background: '#fff',
borderRadius: 12,
boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
}}
>
<h1 style={{ margin: '0 0 24px', fontSize: 24, fontWeight: 600 }}>
Вход в систему
</h1>
{ldapEnabled && (
<div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
<button
type="button"
onClick={() => setTab('password')}
style={{
flex: 1,
padding: '10px 16px',
border: tab === 'password' ? '2px solid #6366f1' : '1px solid #ddd',
borderRadius: 8,
background: tab === 'password' ? '#eef2ff' : '#fff',
cursor: 'pointer',
fontWeight: 500,
}}
>
Email
</button>
<button
type="button"
onClick={() => setTab('ldap')}
style={{
flex: 1,
padding: '10px 16px',
border: tab === 'ldap' ? '2px solid #6366f1' : '1px solid #ddd',
borderRadius: 8,
background: tab === 'ldap' ? '#eef2ff' : '#fff',
cursor: 'pointer',
fontWeight: 500,
}}
>
LDAP / AD
</button>
</div>
)}
{error && (
<div
style={{
padding: 12,
marginBottom: 16,
background: '#fef2f2',
color: '#dc2626',
borderRadius: 8,
fontSize: 14,
}}
>
{error}
</div>
)}
{tab === 'password' ? (
<form onSubmit={handleEmailSignIn}>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 12,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<input
type="password"
placeholder="Пароль"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 16,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<button
type="submit"
disabled={loading}
style={{
width: '100%',
padding: 12,
background: '#6366f1',
color: '#fff',
border: 'none',
borderRadius: 8,
fontSize: 16,
fontWeight: 600,
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? 'Вход...' : 'Войти'}
</button>
</form>
) : (
<form onSubmit={handleLdapSignIn}>
<input
type="text"
placeholder="Логин или DN"
value={credential}
onChange={(e) => setCredential(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 12,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<input
type="password"
placeholder="Пароль"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 16,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<button
type="submit"
disabled={loading}
style={{
width: '100%',
padding: 12,
background: '#6366f1',
color: '#fff',
border: 'none',
borderRadius: 8,
fontSize: 16,
fontWeight: 600,
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? 'Вход...' : 'Войти через LDAP'}
</button>
</form>
)}
<p style={{ marginTop: 24, textAlign: 'center', fontSize: 14, color: '#666' }}>
Нет аккаунта?{' '}
<Link href="/sign-up" style={{ color: '#6366f1', textDecoration: 'none' }}>
Регистрация
</Link>
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,150 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { authClient } from '@/lib/auth-client';
import Link from 'next/link';
export default function SignUpPage() {
const router = useRouter();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const { error } = await authClient.signUp.email({
name,
email,
password,
});
if (error) throw new Error(error.message);
router.push('/dashboard');
router.refresh();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Ошибка регистрации');
} finally {
setLoading(false);
}
};
return (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
}}
>
<div
style={{
width: '100%',
maxWidth: 400,
padding: 32,
background: '#fff',
borderRadius: 12,
boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
}}
>
<h1 style={{ margin: '0 0 24px', fontSize: 24, fontWeight: 600 }}>
Регистрация
</h1>
{error && (
<div
style={{
padding: 12,
marginBottom: 16,
background: '#fef2f2',
color: '#dc2626',
borderRadius: 8,
fontSize: 14,
}}
>
{error}
</div>
)}
<form onSubmit={handleSignUp}>
<input
type="text"
placeholder="Имя"
value={name}
onChange={(e) => setName(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 12,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
style={{
width: '100%',
padding: 12,
marginBottom: 12,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<input
type="password"
placeholder="Пароль"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
style={{
width: '100%',
padding: 12,
marginBottom: 16,
border: '1px solid #ddd',
borderRadius: 8,
boxSizing: 'border-box',
}}
/>
<button
type="submit"
disabled={loading}
style={{
width: '100%',
padding: 12,
background: '#6366f1',
color: '#fff',
border: 'none',
borderRadius: 8,
fontSize: 16,
fontWeight: 600,
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
</button>
</form>
<p style={{ marginTop: 24, textAlign: 'center', fontSize: 14, color: '#666' }}>
Уже есть аккаунт?{' '}
<Link href="/sign-in" style={{ color: '#6366f1', textDecoration: 'none' }}>
Войти
</Link>
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,11 @@
'use client';
import { createAuthClient } from 'better-auth/react';
import { ssoClient } from '@better-auth/sso/client';
import { oidcClient } from 'better-auth/client/plugins';
export const authClient = createAuthClient({
baseURL:
typeof window !== 'undefined' ? window.location.origin : process.env.NEXT_PUBLIC_AUTH_URL,
plugins: [ssoClient(), oidcClient()],
});

View File

@@ -0,0 +1,97 @@
import { betterAuth } from 'better-auth';
import { sso } from '@better-auth/sso';
import { oidcProvider } from 'better-auth/plugins';
import { credentials } from 'better-auth-credentials-plugin';
import { authenticate } from 'ldap-authentication';
import { z } from 'zod';
import { db } from './db';
const baseUrl = process.env.BETTER_AUTH_URL || 'http://localhost:3001';
export const auth = betterAuth({
database: db,
basePath: '/api/auth',
baseURL: baseUrl,
trustedOrigins: [
baseUrl,
'http://localhost:3000',
'http://localhost:3001',
...(process.env.TRUSTED_ORIGINS || '').split(',').filter(Boolean),
],
emailAndPassword: {
enabled: true,
},
plugins: [
// SSO — вход через внешние IdP (Okta, Google, Azure AD)
sso(),
// OIDC Provider — этот сервис выступает как IdP для других приложений
oidcProvider({
loginPage: '/sign-in',
allowDynamicClientRegistration: true,
trustedClients: (() => {
try {
if (process.env.TRUSTED_CLIENTS) {
return JSON.parse(process.env.TRUSTED_CLIENTS);
}
} catch {
/* ignore */
}
return [
{
clientId: process.env.DEFAULT_CLIENT_ID || 'perplexica',
clientSecret: process.env.DEFAULT_CLIENT_SECRET || 'perplexica-secret-change-me',
name: 'Perplexica',
type: 'web',
redirectUrls: ['http://localhost:3000/api/auth/callback/better-auth'],
disabled: false,
skipConsent: true,
},
];
})(),
}),
// LDAP — вход через Active Directory / OpenLDAP
...(process.env.LDAP_URL
? [
credentials({
autoSignUp: true,
linkAccountIfExisting: true,
providerId: 'ldap',
path: '/sign-in/ldap',
inputSchema: z.object({
credential: z.string().min(1, 'Username or DN required'),
password: z.string().min(1, 'Password required'),
}),
async callback(_ctx, parsed) {
const ldapResult = await authenticate({
ldapOpts: {
url: process.env.LDAP_URL!,
connectTimeout: 5000,
...(process.env.LDAP_URL!.startsWith('ldaps://')
? { tlsOptions: { minVersion: 'TLSv1.2' } }
: {}),
},
adminDn: process.env.LDAP_BIND_DN || '',
adminPassword: process.env.LDAP_PASSWORD || '',
userSearchBase: process.env.LDAP_BASE_DN || '',
usernameAttribute: process.env.LDAP_USERNAME_ATTR || 'uid',
username: parsed.credential,
userPassword: parsed.password,
});
const uid = ldapResult[process.env.LDAP_USERNAME_ATTR || 'uid'];
const email =
(Array.isArray(ldapResult.mail) ? ldapResult.mail[0] : ldapResult.mail) ||
`${uid}@local`;
return {
email,
name: ldapResult.displayName || ldapResult.cn || String(uid),
};
},
}),
]
: []),
],
});

View File

@@ -0,0 +1,15 @@
import Database from 'better-sqlite3';
import path from 'node:path';
import fs from 'node:fs';
const defaultPath = path.join(process.cwd(), 'data', 'auth.db');
const dbPath = process.env.DATABASE_URL?.startsWith('file:')
? process.env.DATABASE_URL.replace(/^file:/, '')
: process.env.DATABASE_PATH || defaultPath;
const dir = path.dirname(dbPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
export const db = new Database(dbPath);