feat: add Russian translation and readme #428

Merged
sliva-dev merged 28 commits from russian-translation into dev-1.8.0 2025-11-04 05:47:59 +00:00
14 changed files with 2872 additions and 885 deletions

View File

@@ -6,14 +6,11 @@ on:
version:
description: "Version to build (e.g., 1.8.0)"
required: true
build_type:
description: "Build type"
production:
description: "Is this a production build?"
required: true
default: "Development"
type: choice
options:
- Development
- Production
default: false
type: boolean
jobs:
build:
@@ -36,25 +33,29 @@ jobs:
id: tags
run: |
VERSION=${{ github.event.inputs.version }}
BUILD_TYPE=${{ github.event.inputs.build_type }}
PROD=${{ github.event.inputs.production }}
TAGS=()
ALL_TAGS=()
if [ "$BUILD_TYPE" = "Production" ]; then
if [ "$PROD" = "true" ]; then
# Production build → push release + latest to both GHCR and Docker Hub
TAGS+=("release-$VERSION" "latest")
for tag in "${TAGS[@]}"; do
ALL_TAGS+=("ghcr.io/lukegus/termix:$tag")
ALL_TAGS+=("docker.io/bugattiguy527/termix:$tag")
done
else
# Dev build → push only dev-x.x.x to GHCR
TAGS+=("dev-$VERSION")
for tag in "${TAGS[@]}"; do
ALL_TAGS+=("ghcr.io/lukegus/termix:$tag")
done
fi
echo "ALL_TAGS=$(printf '%s\n' "${ALL_TAGS[@]}")" >> $GITHUB_ENV
echo "ALL_TAGS=${ALL_TAGS[*]}" >> $GITHUB_ENV
echo "All tags to build:"
printf '%s\n' "${ALL_TAGS[@]}"
- name: Login to GHCR
uses: docker/login-action@v3
@@ -64,7 +65,7 @@ jobs:
password: ${{ secrets.GHCR_TOKEN }}
- name: Login to Docker Hub (prod only)
if: ${{ github.event.inputs.build_type == 'Production' }}
if: ${{ github.event.inputs.production == 'true' }}
uses: docker/login-action@v3
with:
username: bugattiguy527

File diff suppressed because it is too large Load Diff

137
README-RU.md Normal file
View File

@@ -0,0 +1,137 @@
# Статистика репозитория
<p align="center">
<img src="https://flagcdn.com/us.svg" alt="English" width="24" height="16"> English |
<a href="README-CN.md"><img src="https://flagcdn.com/cn.svg" alt="中文" width="24" height="16"> 中文</a> |
<a href="README-RU.md"><img src="https://flagcdn.com/ru.svg" alt="Русский" width="24" height="16"> Русский</a>
</p>
![GitHub Repo stars](https://img.shields.io/github/stars/Termix-SSH/Termix?style=flat&label=Stars)
![GitHub forks](https://img.shields.io/github/forks/Termix-SSH/Termix?style=flat&label=Forks)
![GitHub Release](https://img.shields.io/github/v/release/Termix-SSH/Termix?style=flat&label=Release)
<a href="https://discord.gg/jVQGdvHDrf"><img alt="Discord" src="https://img.shields.io/discord/1347374268253470720"></a>
<p align="center">
<img src="./repo-images/RepoOfTheDay.png" alt="Достижение дня" style="width: 300px; height: auto;">
<br>
<small style="color: #666;">Достигнуто 1 сентября 2025 года</small>
</p>
#### Лучшие технологии
[![React Badge](https://img.shields.io/badge/-React-61DBFB?style=flat-square&labelColor=black&logo=react&logoColor=61DBFB)](#)
[![TypeScript Badge](https://img.shields.io/badge/-TypeScript-3178C6?style=flat-square&labelColor=black&logo=typescript&logoColor=3178C6)](#)
[![Node.js Badge](https://img.shields.io/badge/-Node.js-3C873A?style=flat-square&labelColor=black&logo=node.js&logoColor=3C873A)](#)
[![Vite Badge](https://img.shields.io/badge/-Vite-646CFF?style=flat-square&labelColor=black&logo=vite&logoColor=646CFF)](#)
[![Tailwind CSS Badge](https://img.shields.io/badge/-TailwindCSS-38B2AC?style=flat-square&labelColor=black&logo=tailwindcss&logoColor=38B2AC)](#)
[![Docker Badge](https://img.shields.io/badge/-Docker-2496ED?style=flat-square&labelColor=black&logo=docker&logoColor=2496ED)](#)
[![SQLite Badge](https://img.shields.io/badge/-SQLite-003B57?style=flat-square&labelColor=black&logo=sqlite&logoColor=003B57)](#)
[![Radix UI Badge](https://img.shields.io/badge/-Radix%20UI-161618?style=flat-square&labelColor=black&logo=radixui&logoColor=161618)](#)
<br />
<p align="center">
<a href="https://github.com/Termix-SSH/Termix">
<img alt="Баннер Termix" src=./repo-images/HeaderImage.png style="width: auto; height: auto;"> </a>
</p>
Если хотите, вы можете поддержать проект здесь!\
[![GitHub Sponsor](https://img.shields.io/badge/Sponsor-LukeGus-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/sponsors/LukeGus)
# Обзор
<p align="center">
<a href="https://github.com/Termix-SSH/Termix">
<img alt="Баннер Termix" src=./public/icon.svg style="width: 250px; height: 250px;"> </a>
</p>
Termix — это открытая, бесплатная и самохостинговая универсальная платформа для управления серверами. Она предоставляет веб-решение
для управления вашими серверами и инфраструктурой через единый интуитивно понятный интерфейс. Termix предлагает доступ к SSH-терминалу,
возможности SSH-туннелирования и удаленное управление файлами, а в будущем появится еще больше инструментов.
# Особенности
- **Доступ к SSH-терминалу** — полнофункциональный терминал с поддержкой разделения экрана (до 4 панелей) и системой вкладок
- **Управление SSH-туннелями** — создание и управление SSH-туннелями с автоматической переподключением и мониторингом работоспособности
- **Удаленный файловый менеджер** — управление файлами непосредственно на удаленных серверах с поддержкой просмотра и редактирования кода, изображений, аудио и видео. Беспроблемная загрузка, скачивание, переименование, удаление и перемещение файлов.
- **Менеджер хостов SSH** — сохраняйте, систематизируйте и управляйте своими SSH-соединениями с помощью тегов и папок, а также легко сохраняйте повторно используемую информацию для входа в систему, имея возможность автоматизировать развертывание SSH-ключей
- **Статистика сервера** — просмотр использования ЦП, памяти и жесткого диска на любом SSH-сервере
- **Аутентификация пользователей** - Безопасное управление пользователями с помощью элементов управления администратора и поддержки OIDC и 2FA (TOTP).
- **Шифрование базы данных** - Файлы базы данных SQLite шифруются в режиме ожидания с помощью автоматического шифрования/дешифрования.
- **Экспорт/импорт данных** - Экспорт и импорт SSH-хостов, учетных данных и данных файлового менеджера с инкрементной синхронизацией.
- **Автоматическая настройка SSL** - Встроенная генерация и управление SSL-сертификатами с перенаправлением HTTPS.
- **Современный интерфейс** - Чистый интерфейс, удобный для настольных компьютеров и мобильных устройств, созданный с помощью React, Tailwind CSS и Shadcn
- **Языки** - Встроенная поддержка английского, китайского и немецкого языков
- **Поддержка платформ** - Доступно в виде веб-приложения, настольного приложения (Windows и Linux) и специального мобильного приложения для iOS и Android. Планируется поддержка macOS и iPadOS.
# Планируемые функции
Смотрите [Projects](https://github.com/orgs/Termix-SSH/projects/2) для ознакомления со всеми запланированными функциями. Если вы хотите внести свой вклад смотрите [Contributing](https://github.com/Termix-SSH/Termix/blob/main/CONTRIBUTING.md).
# Установка
Поддерживаемые устройства:
- Веб-сайт (любой современный браузер, такой как Google, Safari и Firefox)
- Windows (приложение)
- Linux (приложение)
- iOS (приложение)
- Android (приложение)
- iPadOS и macOS находятся в стадии разработки
Посетите Termix [Docs](https://docs.termix.site/install) для получения дополнительной информации об установке Termix на всех платформах. В противном случае,
просмотрите пример файла Docker Compose здесь:
```yaml
services:
termix:
image: ghcr.io/lukegus/termix:latest
container_name: termix
restart: unless-stopped
ports:
- '8080:8080'
volumes:
- termix-data:/app/data
environment:
PORT: '8080'
volumes:
termix-data:
driver: local
```
# Поддержка
Если вам нужна помощь или вы хотите запросить функцию в Termix, посетите [Issues](https://github.com/Termix-SSH/Support/issues), войдите в систему и нажмите `New Issue`.
Пожалуйста, опишите свою проблему как можно подробнее, желательно на английском языке. Вы также можете присоединиться к [Discord](https://discord.gg/jVQGdvHDrf) серверу и посетите канал
службы поддержки, однако время отклика может быть более длительным.
# Внешний вид
<p align="center">
<img src="./repo-images/Image 1.png" width="400" alt="Termix Demo 1"/>
<img src="./repo-images/Image 2.png" width="400" alt="Termix Demo 2"/>
</p>
<p align="center">
<img src="./repo-images/Image 3.png" width="400" alt="Termix Demo 3"/>
<img src="./repo-images/Image 4.png" width="400" alt="Termix Demo 4"/>
</p>
<p align="center">
<img src="./repo-images/Image 5.png" width="400" alt="Termix Demo 5"/>
<img src="./repo-images/Image 6.png" width="400" alt="Termix Demo 6"/>
</p>
<p align="center">
<img src="./repo-images/Image 7.png" width="400" alt="Termix Demo 7"/>
</p>
<p align="center">
<video src="https://github.com/user-attachments/assets/88936e0d-2399-4122-8eee-c255c25da48c" width="800" controls>
Ваш браузер не поддерживает тег видео.
</video>
</p>
# Лицензия
Распространяется по лицензии Apache версии 2.0. Дополнительную информацию смотрите в файле LICENSE.

View File

@@ -578,19 +578,6 @@ class AuthManager {
sessionId,
});
}
} else {
try {
await db.delete(sessions).where(eq(sessions.userId, userId));
} catch (error) {
databaseLogger.error(
"Failed to delete user sessions on logout",
error,
{
operation: "sessions_delete_logout_failed",
userId,
},
);
}
}
}

View File

@@ -6,12 +6,13 @@ import enTranslation from "../locales/en/translation.json";
import zhTranslation from "../locales/zh/translation.json";
import deTranslation from "../locales/de/translation.json";
import ptbrTranslation from "../locales/pt-BR/translation.json";
import ruTranslation from "../locales/ru/translation.json";
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
supportedLngs: ["en", "zh", "de", "ptbr"],
supportedLngs: ["en", "zh", "de", "ptbr", "ru"],
fallbackLng: "en",
debug: false,
@@ -36,6 +37,9 @@ i18n
ptbr: {
translation: ptbrTranslation,
},
ru: {
translation: ruTranslation,
},
},
interpolation: {

View File

@@ -1252,6 +1252,7 @@
"enterCode": "Enter verification code",
"backupCode": "Or use backup code",
"verifyCode": "Verify Code",
"redirectingToApp": "Redirecting to app...",
"enableTwoFactor": "Enable Two-Factor Authentication",
"disableTwoFactor": "Disable Two-Factor Authentication",
"scanQRCode": "Scan this QR code with your authenticator app",

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useCallback } from "react";
import { LeftSidebar } from "@/ui/desktop/navigation/LeftSidebar.tsx";
import { Dashboard } from "@/ui/desktop/apps/dashboard/Dashboard.tsx";
import { AppView } from "@/ui/desktop/navigation/AppView.tsx";
@@ -68,15 +68,18 @@ function AppContent() {
const handleSelectView = () => {};
const handleAuthSuccess = (authData: {
isAdmin: boolean;
username: string | null;
userId: string | null;
}) => {
setIsAuthenticated(true);
setIsAdmin(authData.isAdmin);
setUsername(authData.username);
};
const handleAuthSuccess = useCallback(
(authData: {
isAdmin: boolean;
username: string | null;
userId: string | null;
}) => {
setIsAuthenticated(true);
setIsAdmin(authData.isAdmin);
setUsername(authData.username);
},
[],
);
const currentTabData = tabs.find((tab) => tab.id === currentTab);
const showTerminalView =

View File

@@ -52,6 +52,9 @@ import {
getUserInfo,
getCookie,
isElectron,
getSessions,
revokeSession,
revokeAllUserSessions,
} from "@/ui/main-axios.ts";
interface AdminSettingsProps {
@@ -126,6 +129,7 @@ export function AdminSettings({
expiresAt: string;
lastActiveAt: string;
jwtToken: string;
isRevoked?: boolean;
}>
>([]);
const [sessionsLoading, setSessionsLoading] = React.useState(false);
@@ -565,35 +569,8 @@ export function AdminSettings({
setSessionsLoading(true);
try {
const isDev =
!isElectron() &&
process.env.NODE_ENV === "development" &&
(window.location.port === "3000" ||
window.location.port === "5173" ||
window.location.port === "" ||
window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1");
const apiUrl = isElectron()
? `${(window as { configuredServerUrl?: string }).configuredServerUrl}/users/sessions`
: isDev
? `http://localhost:30001/users/sessions`
: `/users/sessions`;
const response = await fetch(apiUrl, {
method: "GET",
credentials: "include",
headers: {
Authorization: `Bearer ${getCookie("jwt")}`,
},
});
if (response.ok) {
const data = await response.json();
setSessions(data.sessions || []);
} else {
toast.error(t("admin.failedToFetchSessions"));
}
const data = await getSessions();
setSessions(data.sessions || []);
} catch (err) {
if (!err?.message?.includes("No server configured")) {
toast.error(t("admin.failedToFetchSessions"));
@@ -612,41 +589,15 @@ export function AdminSettings({
t("admin.confirmRevokeSession"),
async () => {
try {
const isDev =
!isElectron() &&
process.env.NODE_ENV === "development" &&
(window.location.port === "3000" ||
window.location.port === "5173" ||
window.location.port === "" ||
window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1");
await revokeSession(sessionId);
toast.success(t("admin.sessionRevokedSuccessfully"));
const apiUrl = isElectron()
? `${(window as { configuredServerUrl?: string }).configuredServerUrl}/users/sessions/${sessionId}`
: isDev
? `http://localhost:30001/users/sessions/${sessionId}`
: `/users/sessions/${sessionId}`;
const response = await fetch(apiUrl, {
method: "DELETE",
credentials: "include",
headers: {
Authorization: `Bearer ${getCookie("jwt")}`,
},
});
if (response.ok) {
toast.success(t("admin.sessionRevokedSuccessfully"));
if (isCurrentSession) {
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
fetchSessions();
}
if (isCurrentSession) {
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
toast.error(t("admin.failedToRevokeSession"));
fetchSessions();
}
} catch {
toast.error(t("admin.failedToRevokeSession"));
@@ -663,49 +614,15 @@ export function AdminSettings({
t("admin.confirmRevokeAllSessions"),
async () => {
try {
const isDev =
!isElectron() &&
process.env.NODE_ENV === "development" &&
(window.location.port === "3000" ||
window.location.port === "5173" ||
window.location.port === "" ||
window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1");
const data = await revokeAllUserSessions(userId);
toast.success(data.message || t("admin.sessionsRevokedSuccessfully"));
const apiUrl = isElectron()
? `${(window as { configuredServerUrl?: string }).configuredServerUrl}/users/sessions/revoke-all`
: isDev
? `http://localhost:30001/users/sessions/revoke-all`
: `/users/sessions/revoke-all`;
const response = await fetch(apiUrl, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getCookie("jwt")}`,
},
body: JSON.stringify({
targetUserId: userId,
exceptCurrent: false,
}),
});
if (response.ok) {
const data = await response.json();
toast.success(
data.message || t("admin.sessionsRevokedSuccessfully"),
);
if (isCurrentUser) {
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
fetchSessions();
}
if (isCurrentUser) {
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
toast.error(t("admin.failedToRevokeSessions"));
fetchSessions();
}
} catch {
toast.error(t("admin.failedToRevokeSessions"));

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useCallback } from "react";
import { cn } from "@/lib/utils.ts";
import { Button } from "@/components/ui/button.tsx";
import { Input } from "@/components/ui/input.tsx";
@@ -105,6 +105,33 @@ export function Auth({
const [totpLoading, setTotpLoading] = useState(false);
const [webviewAuthSuccess, setWebviewAuthSuccess] = useState(false);
const handleElectronAuthSuccess = useCallback(async () => {
try {
const meRes = await getUserInfo();
setInternalLoggedIn(true);
setLoggedIn(true);
setIsAdmin(!!meRes.is_admin);
setUsername(meRes.username || null);
setUserId(meRes.userId || null);
onAuthSuccess({
isAdmin: !!meRes.is_admin,
username: meRes.username || null,
userId: meRes.userId || null,
});
toast.success(t("messages.loginSuccess"));
} catch (err) {
toast.error(t("errors.failedUserInfo"));
}
}, [
onAuthSuccess,
setLoggedIn,
setIsAdmin,
setUsername,
setUserId,
t,
setInternalLoggedIn,
]);
useEffect(() => {
setInternalLoggedIn(loggedIn);
}, [loggedIn]);
@@ -243,6 +270,7 @@ export function Auth({
"*",
);
setWebviewAuthSuccess(true);
setTimeout(() => window.location.reload(), 100);
setLoading(false);
return;
} catch (e) {}
@@ -419,6 +447,7 @@ export function Auth({
"*",
);
setWebviewAuthSuccess(true);
setTimeout(() => window.location.reload(), 100);
setTotpLoading(false);
return;
} catch (e) {}
@@ -526,6 +555,7 @@ export function Auth({
"*",
);
setWebviewAuthSuccess(true);
setTimeout(() => window.location.reload(), 100);
setOidcLoading(false);
return;
} catch (e) {}
@@ -688,24 +718,7 @@ export function Auth({
<div className="w-full max-w-4xl h-[90vh]">
<ElectronLoginForm
serverUrl={currentServerUrl}
onAuthSuccess={async () => {
try {
const meRes = await getUserInfo();
setInternalLoggedIn(true);
setLoggedIn(true);
setIsAdmin(!!meRes.is_admin);
setUsername(meRes.username || null);
setUserId(meRes.userId || null);
onAuthSuccess({
isAdmin: !!meRes.is_admin,
username: meRes.username || null,
userId: meRes.userId || null,
});
toast.success(t("messages.loginSuccess"));
} catch (err) {
toast.error(t("errors.failedUserInfo"));
}
}}
onAuthSuccess={handleElectronAuthSuccess}
onChangeServer={() => {
setShowServerConfig(true);
}}

View File

@@ -3,23 +3,7 @@ import { Button } from "@/components/ui/button.tsx";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert.tsx";
import { useTranslation } from "react-i18next";
import { AlertCircle, Loader2, ArrowLeft, RefreshCw } from "lucide-react";
import { getCookie, getUserInfo } from "@/ui/main-axios.ts";
declare global {
namespace JSX {
interface IntrinsicElements {
webview: React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement>,
HTMLElement
> & {
src?: string;
partition?: string;
allowpopups?: string;
ref?: React.Ref<any>;
};
}
}
}
import { getCookie } from "@/ui/main-axios.ts";
interface ElectronLoginFormProps {
serverUrl: string;
@@ -36,12 +20,10 @@ export function ElectronLoginForm({
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [isAuthenticating, setIsAuthenticating] = useState(false);
const webviewRef = useRef<any>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const hasAuthenticatedRef = useRef(false);
const [currentUrl, setCurrentUrl] = useState(serverUrl);
const hasLoadedOnce = useRef(false);
const urlCheckInterval = useRef<NodeJS.Timeout | null>(null);
const loadTimeout = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
const handleMessage = async (event: MessageEvent) => {
@@ -71,32 +53,11 @@ export function ElectronLoginForm({
throw new Error("Failed to save JWT to localStorage");
}
try {
await getUserInfo();
} catch (verifyErr) {
localStorage.removeItem("jwt");
const errorMsg =
verifyErr instanceof Error
? verifyErr.message
: "Failed to verify authentication";
console.error("Authentication verification failed:", verifyErr);
throw new Error(
errorMsg.includes("registration") ||
errorMsg.includes("allowed")
? "Authentication failed. Please check your server connection and try again."
: errorMsg,
);
}
await new Promise((resolve) => setTimeout(resolve, 500));
onAuthSuccess();
} catch (err) {
const errorMessage =
err instanceof Error
? err.message
: t("errors.authTokenSaveFailed");
setError(errorMessage);
setError(t("errors.authTokenSaveFailed"));
setIsAuthenticating(false);
hasAuthenticatedRef.current = false;
}
@@ -113,187 +74,124 @@ export function ElectronLoginForm({
}, [serverUrl, isAuthenticating, onAuthSuccess, t]);
useEffect(() => {
const checkWebviewUrl = () => {
const webview = webviewRef.current;
if (!webview) return;
try {
const webviewUrl = webview.getURL();
if (webviewUrl && webviewUrl !== currentUrl) {
setCurrentUrl(webviewUrl);
}
} catch (e) {}
};
urlCheckInterval.current = setInterval(checkWebviewUrl, 500);
return () => {
if (urlCheckInterval.current) {
clearInterval(urlCheckInterval.current);
urlCheckInterval.current = null;
}
};
}, [currentUrl]);
useEffect(() => {
const webview = webviewRef.current;
if (!webview) return;
loadTimeout.current = setTimeout(() => {
if (!hasLoadedOnce.current && loading) {
setLoading(false);
setError(
"Unable to connect to server. Please check the server URL and try again.",
);
}
}, 15000);
const iframe = iframeRef.current;
if (!iframe) return;
const handleLoad = () => {
if (loadTimeout.current) {
clearTimeout(loadTimeout.current);
loadTimeout.current = null;
}
setLoading(false);
hasLoadedOnce.current = true;
setError(null);
try {
const webviewUrl = webview.getURL();
setCurrentUrl(webviewUrl || serverUrl);
if (iframe.contentWindow) {
setCurrentUrl(iframe.contentWindow.location.href);
}
} catch (e) {
setCurrentUrl(serverUrl);
}
const injectedScript = `
(function() {
window.IS_ELECTRON = true;
window.IS_ELECTRON_WEBVIEW = true;
if (typeof window.electronAPI === 'undefined') {
window.electronAPI = { isElectron: true };
}
try {
const injectedScript = `
(function() {
let hasNotified = false;
let hasNotified = false;
function postJWTToParent(token, source) {
if (hasNotified) {
return;
}
hasNotified = true;
function postJWTToParent(token, source) {
if (hasNotified) {
return;
try {
window.parent.postMessage({
type: 'AUTH_SUCCESS',
token: token,
source: source,
platform: 'desktop',
timestamp: Date.now()
}, '*');
} catch (e) {
}
}
hasNotified = true;
try {
window.parent.postMessage({
type: 'AUTH_SUCCESS',
token: token,
source: source,
platform: 'desktop',
timestamp: Date.now()
}, '*');
} catch (e) {
}
}
function clearAuthData() {
try {
localStorage.removeItem('jwt');
sessionStorage.removeItem('jwt');
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i];
const eqPos = cookie.indexOf('=');
const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
if (name === 'jwt') {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=' + window.location.hostname;
function checkAuth() {
try {
const localToken = localStorage.getItem('jwt');
if (localToken && localToken.length > 20) {
postJWTToParent(localToken, 'localStorage');
return true;
}
}
} catch (error) {
}
}
window.addEventListener('message', function(event) {
try {
if (event.data && typeof event.data === 'object') {
if (event.data.type === 'CLEAR_AUTH_DATA') {
clearAuthData();
const sessionToken = sessionStorage.getItem('jwt');
if (sessionToken && sessionToken.length > 20) {
postJWTToParent(sessionToken, 'sessionStorage');
return true;
}
}
} catch (error) {
}
});
function checkAuth() {
try {
const localToken = localStorage.getItem('jwt');
if (localToken && localToken.length > 20) {
postJWTToParent(localToken, 'localStorage');
return true;
}
const cookies = document.cookie;
if (cookies && cookies.length > 0) {
const cookieArray = cookies.split('; ');
const tokenCookie = cookieArray.find(row => row.startsWith('jwt='));
const sessionToken = sessionStorage.getItem('jwt');
if (sessionToken && sessionToken.length > 20) {
postJWTToParent(sessionToken, 'sessionStorage');
return true;
}
const cookies = document.cookie;
if (cookies && cookies.length > 0) {
const cookieArray = cookies.split('; ');
const tokenCookie = cookieArray.find(row => row.startsWith('jwt='));
if (tokenCookie) {
const token = tokenCookie.split('=')[1];
if (token && token.length > 20) {
postJWTToParent(token, 'cookie');
return true;
if (tokenCookie) {
const token = tokenCookie.split('=')[1];
if (token && token.length > 20) {
postJWTToParent(token, 'cookie');
return true;
}
}
}
} catch (error) {
}
} catch (error) {
return false;
}
const originalSetItem = localStorage.setItem;
localStorage.setItem = function(key, value) {
originalSetItem.apply(this, arguments);
if (key === 'jwt' && value && value.length > 20 && !hasNotified) {
setTimeout(() => checkAuth(), 100);
}
};
const originalSessionSetItem = sessionStorage.setItem;
sessionStorage.setItem = function(key, value) {
originalSessionSetItem.apply(this, arguments);
if (key === 'jwt' && value && value.length > 20 && !hasNotified) {
setTimeout(() => checkAuth(), 100);
}
};
const intervalId = setInterval(() => {
if (hasNotified) {
clearInterval(intervalId);
return;
}
if (checkAuth()) {
clearInterval(intervalId);
}
}, 500);
setTimeout(() => {
clearInterval(intervalId);
}, 300000);
setTimeout(() => checkAuth(), 500);
})();
`;
try {
if (iframe.contentWindow) {
try {
iframe.contentWindow.eval(injectedScript);
} catch (evalError) {
iframe.contentWindow.postMessage(
{ type: "INJECT_SCRIPT", script: injectedScript },
"*",
);
}
return false;
}
const originalSetItem = localStorage.setItem;
localStorage.setItem = function(key, value) {
originalSetItem.apply(this, arguments);
if (key === 'jwt' && value && value.length > 20 && !hasNotified) {
setTimeout(() => checkAuth(), 100);
}
};
const originalSessionSetItem = sessionStorage.setItem;
sessionStorage.setItem = function(key, value) {
originalSessionSetItem.apply(this, arguments);
if (key === 'jwt' && value && value.length > 20 && !hasNotified) {
setTimeout(() => checkAuth(), 100);
}
};
const intervalId = setInterval(() => {
if (hasNotified) {
clearInterval(intervalId);
return;
}
if (checkAuth()) {
clearInterval(intervalId);
}
}, 500);
setTimeout(() => {
clearInterval(intervalId);
}, 300000);
setTimeout(() => checkAuth(), 500);
})();
`;
try {
webview.executeJavaScript(injectedScript);
} catch (err) {
console.error("Failed to inject authentication script:", err);
}
} catch (err) {}
} catch (err) {}
};
const handleError = () => {
@@ -303,27 +201,18 @@ export function ElectronLoginForm({
}
};
webview.addEventListener("did-finish-load", handleLoad);
webview.addEventListener("did-fail-load", handleError);
iframe.addEventListener("load", handleLoad);
iframe.addEventListener("error", handleError);
return () => {
webview.removeEventListener("did-finish-load", handleLoad);
webview.removeEventListener("did-fail-load", handleError);
if (loadTimeout.current) {
clearTimeout(loadTimeout.current);
loadTimeout.current = null;
}
iframe.removeEventListener("load", handleLoad);
iframe.removeEventListener("error", handleError);
};
}, [t, loading, serverUrl]);
}, [t]);
const handleRefresh = () => {
if (webviewRef.current) {
if (loadTimeout.current) {
clearTimeout(loadTimeout.current);
loadTimeout.current = null;
}
webviewRef.current.src = serverUrl;
if (iframeRef.current) {
iframeRef.current.src = serverUrl;
setLoading(true);
setError(null);
}
@@ -386,28 +275,14 @@ export function ElectronLoginForm({
</div>
)}
{isAuthenticating && (
<div
className="absolute inset-0 flex items-center justify-center bg-dark-bg/80 z-40"
style={{ marginTop: "60px" }}
>
<div className="flex items-center">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span className="ml-3 text-muted-foreground">
{t("auth.authenticating")}
</span>
</div>
</div>
)}
<div className="flex-1 overflow-hidden">
<webview
ref={webviewRef}
<iframe
ref={iframeRef}
src={serverUrl}
className="w-full h-full border-0"
partition="persist:termix"
allowpopups="false"
style={{ width: "100%", height: "100%" }}
title="Server Authentication"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-storage-access-by-user-activation allow-top-navigation allow-top-navigation-by-user-activation allow-modals allow-downloads"
allow="clipboard-read; clipboard-write; cross-origin-isolated; camera; microphone; geolocation"
/>
</div>
</div>

View File

@@ -18,6 +18,7 @@ const languages = [
name: "Brazilian Portuguese",
nativeName: "Português Brasileiro",
},
{ code: "ru", name: "Russian", nativeName: "Русский" },
];
export function LanguageSwitcher() {

View File

@@ -342,6 +342,7 @@ function createApiInstance(
import("sonner").then(({ toast }) => {
toast.warning("Session expired. Please log in again.");
window.location.reload();
});
const currentPath = window.location.pathname;
@@ -1944,6 +1945,53 @@ export async function getUserList(): Promise<{ users: UserInfo[] }> {
}
}
export async function getSessions(): Promise<{
sessions: {
id: string;
userId: string;
username?: string;
deviceType: string;
deviceInfo: string;
createdAt: string;
expiresAt: string;
lastActiveAt: string;
jwtToken: string;
isRevoked?: boolean;
}[];
}> {
try {
const response = await authApi.get("/users/sessions");
return response.data;
} catch (error) {
handleApiError(error, "fetch sessions");
}
}
export async function revokeSession(
sessionId: string,
): Promise<{ success: boolean; message: string }> {
try {
const response = await authApi.delete(`/users/sessions/${sessionId}`);
return response.data;
} catch (error) {
handleApiError(error, "revoke session");
}
}
export async function revokeAllUserSessions(
userId: string,
): Promise<{ success: boolean; message: string }> {
try {
const response = await authApi.post("/users/sessions/revoke-all", {
targetUserId: userId,
exceptCurrent: false,
});
return response.data;
} catch (error) {
handleApiError(error, "revoke all user sessions");
}
}
export async function makeUserAdmin(
username: string,
): Promise<Record<string, unknown>> {

File diff suppressed because it is too large Load Diff