feat(rbac): split setting:view into panel settings and a permission-free profile
Some checks failed
Backend Tests / pytest (Python 3.12) (push) Failing after 1m22s
Deploy to Production / Trigger production update (push) Failing after 11s

setting:view used to gate the whole /settings page, which mixed panel-wide
configuration with a user's own account. Revoking it to keep a standard user
out of the panel settings also took away their profile, password, 2FA and SSH
keys, so the permission could not be used for what it names.

The account half now lives at /profile: its endpoints are self-scoped and only
require a session, so the page carries no permission at all and is reached from
the user menu (and Ctrl+K) rather than a sidebar group. /settings keeps the
panel-wide tabs behind setting:view, with saving gated on setting:update,
security on setting:manage and the SMTP/Telegram channels on is_admin, matching
what each endpoint checks.

The shipped "user" role no longer gets setting:view. Migration 42 drops it from
roles holding it without setting:update/manage, since those grants only existed
to reach the profile page; it runs once (marker in panel_settings) so a later
deliberate grant is not reverted on the next start.
This commit is contained in:
2026-08-11 20:07:34 +05:00
parent 991daddd63
commit bddbf15652
15 changed files with 668 additions and 447 deletions

12
WIKI.md
View File

@@ -1388,7 +1388,7 @@ when the role holds `<resource>:manage` (rule 4 above).
| `role:manage` | Full role administration incl. assigning roles (requires `role:view`, `user:view`) | | `role:manage` | Full role administration incl. assigning roles (requires `role:view`, `user:view`) |
**Logs** (`log`): `log:view`, `log:export`, `log:delete`. **Logs** (`log`): `log:view`, `log:export`, `log:delete`.
**Settings** (`setting`): `setting:view`, `setting:update` (panel settings), `setting:manage` (security & advanced settings). **Settings** (`setting`): `setting:view`, `setting:update` (panel settings), `setting:manage` (security & advanced settings). These cover **panel-wide** configuration only — a user's own account (profile, password, 2FA, SSH keys, notification preferences) lives at `/profile`, is self-scoped, and needs no permission.
**Notifications** (`notification`): `notification:view`, `notification:manage`. **Notifications** (`notification`): `notification:view`, `notification:manage`.
> **Delegated role editing.** A non-admin with `role:manage` can only grant > **Delegated role editing.** A non-admin with `role:manage` can only grant
@@ -1400,7 +1400,10 @@ when the role holds `<resource>:manage` (rule 4 above).
The frontend (`frontend/src/lib/nav-items.ts`) hides a menu entry unless the The frontend (`frontend/src/lib/nav-items.ts`) hides a menu entry unless the
user is an admin or holds the listed permission. Items with **no** permission user is an admin or holds the listed permission. Items with **no** permission
are **admin-only**. are **admin-only**. The same permission also guards the route itself
(`RequirePermission` in `frontend/src/components/shared/route-guards.tsx`), so
a hidden page cannot be reached by typing its URL — denied users are redirected
to the first page they can open.
| Sidebar item | Required permission | | Sidebar item | Required permission |
|---|---| |---|---|
@@ -1419,7 +1422,8 @@ are **admin-only**.
| Users | `user:view` | | Users | `user:view` |
| Workspaces | *(admin-only)* | | Workspaces | *(admin-only)* |
| Logs | `log:view` | | Logs | `log:view` |
| Settings | `setting:view` | | Settings (panel-wide) | `setting:view` |
| Profile (user menu, not the sidebar) | *(none — any logged-in user)* |
#### Default (built-in) roles #### Default (built-in) roles
@@ -1437,7 +1441,7 @@ access.
|------|--------------|----------------| |------|--------------|----------------|
| **admin** | Platform administrator | Everything. Holds every permission *and* the `is_admin` bypass — sees all servers, all instances (regardless of owner), all users, settings, security. | | **admin** | Platform administrator | Everything. Holds every permission *and* the `is_admin` bypass — sees all servers, all instances (regardless of owner), all users, settings, security. |
| **moderator** | Operator without admin rights | View dashboard/servers; **create + power + console** VMs and LXC; view templates/storage/firewall/network/node/pool/backups/IPAM/users/logs; create backups; export logs; manage notifications. **No** delete, no settings changes, no user/role management. Note: without `vm:manage` a moderator is still subject to the ownership filter (see below). | | **moderator** | Operator without admin rights | View dashboard/servers; **create + power + console** VMs and LXC; view templates/storage/firewall/network/node/pool/backups/IPAM/users/logs; create backups; export logs; manage notifications. **No** delete, no settings changes, no user/role management. Note: without `vm:manage` a moderator is still subject to the ownership filter (see below). |
| **user** | Standard tenant (VPS-style) | View + **start/stop/restart/console** their **own** VMs and LXC; view templates/storage/firewall/network/node/pool/IPAM; manage own notifications; view settings (for the self-service profile/quota page). **No** create/delete by default, **no** dashboard. Scoped to owned instances because it lacks `vm:manage`. | | **user** | Standard tenant (VPS-style) | View + **start/stop/restart/console** their **own** VMs and LXC; view templates/storage/firewall/network/node/pool/IPAM; manage own notifications. Their own profile, SSH keys and quota live at `/profile` and need no permission, so this role deliberately has **no** `setting:view` (that would hand out the panel-wide settings page). **No** create/delete by default, **no** dashboard. Scoped to owned instances because it lacks `vm:manage`. |
| **demo** | Read-only showcase | View-only across dashboard, servers, VMs, LXC, templates, storage, firewall, network, node, pool, IPAM. No power actions, no writes. | | **demo** | Read-only showcase | View-only across dashboard, servers, VMs, LXC, templates, storage, firewall, network, node, pool, IPAM. No power actions, no writes. |
> The exact JSON for each role lives in `NEW_DEFAULT_ROLES` in > The exact JSON for each role lives in `NEW_DEFAULT_ROLES` in

View File

@@ -1343,14 +1343,14 @@ resource:action
| `role:manage` | Полное администрирование ролей, включая назначение (требует `role:view`, `user:view`) | | `role:manage` | Полное администрирование ролей, включая назначение (требует `role:view`, `user:view`) |
**Логи** (`log`): `log:view`, `log:export`, `log:delete`. **Логи** (`log`): `log:view`, `log:export`, `log:delete`.
**Настройки** (`setting`): `setting:view`, `setting:update` (настройки панели), `setting:manage` (безопасность и расширенные настройки). **Настройки** (`setting`): `setting:view`, `setting:update` (настройки панели), `setting:manage` (безопасность и расширенные настройки). Эти права относятся **только к настройкам панели** — собственная учётная запись пользователя (профиль, пароль, 2FA, SSH-ключи, предпочтения уведомлений) живёт на `/profile`, ограничена самим пользователем и не требует никаких прав.
**Уведомления** (`notification`): `notification:view`, `notification:manage`. **Уведомления** (`notification`): `notification:view`, `notification:manage`.
> **Делегированное редактирование ролей.** Не-админ с `role:manage` может выдавать только те права, которыми **владеет сам** (`can_assign_permission` / `validate_role_permissions`). Это предотвращает эскалацию привилегий — нельзя раздать доступ, которого у вас нет. Админы освобождены от этого и могут выдавать что угодно. > **Делегированное редактирование ролей.** Не-админ с `role:manage` может выдавать только те права, которыми **владеет сам** (`can_assign_permission` / `validate_role_permissions`). Это предотвращает эскалацию привилегий — нельзя раздать доступ, которого у вас нет. Админы освобождены от этого и могут выдавать что угодно.
#### Какое право открывает какую страницу в меню #### Какое право открывает какую страницу в меню
Фронтенд (`frontend/src/lib/nav-items.ts`) скрывает пункт меню, если пользователь не админ и не держит указанное право. Пункты **без** права — **только для админа**. Фронтенд (`frontend/src/lib/nav-items.ts`) скрывает пункт меню, если пользователь не админ и не держит указанное право. Пункты **без** права — **только для админа**. То же право защищает и сам маршрут (`RequirePermission` в `frontend/src/components/shared/route-guards.tsx`), поэтому скрытую страницу нельзя открыть вводом URL — при отказе пользователя перебрасывает на первую доступную ему страницу.
| Пункт меню | Требуемое право | | Пункт меню | Требуемое право |
|---|---| |---|---|
@@ -1369,7 +1369,8 @@ resource:action
| Users | `user:view` | | Users | `user:view` |
| Workspaces | *(только админ)* | | Workspaces | *(только админ)* |
| Logs | `log:view` | | Logs | `log:view` |
| Settings | `setting:view` | | Settings (настройки панели) | `setting:view` |
| Профиль (меню пользователя, не сайдбар) | *(без права — любой вошедший)* |
#### Роли по умолчанию (встроенные) #### Роли по умолчанию (встроенные)
@@ -1379,7 +1380,7 @@ resource:action
|------|--------------|----------------| |------|--------------|----------------|
| **admin** | Администратор платформы | Всё. Держит каждое право *и* обход `is_admin` — видит все серверы, все инстансы (независимо от владельца), всех пользователей, настройки, безопасность. | | **admin** | Администратор платформы | Всё. Держит каждое право *и* обход `is_admin` — видит все серверы, все инстансы (независимо от владельца), всех пользователей, настройки, безопасность. |
| **moderator** | Оператор без прав админа | Смотреть дашборд/серверы; **создавать + управлять питанием + консоль** ВМ и LXC; смотреть шаблоны/хранилище/firewall/сеть/узел/пулы/копии/IPAM/пользователей/логи; создавать копии; экспортировать логи; управлять уведомлениями. **Нет** удаления, изменения настроек, управления пользователями/ролями. Заметьте: без `vm:manage` модератор всё равно подчиняется фильтру владельца (см. ниже). | | **moderator** | Оператор без прав админа | Смотреть дашборд/серверы; **создавать + управлять питанием + консоль** ВМ и LXC; смотреть шаблоны/хранилище/firewall/сеть/узел/пулы/копии/IPAM/пользователей/логи; создавать копии; экспортировать логи; управлять уведомлениями. **Нет** удаления, изменения настроек, управления пользователями/ролями. Заметьте: без `vm:manage` модератор всё равно подчиняется фильтру владельца (см. ниже). |
| **user** | Стандартный арендатор (стиль VPS) | Смотреть + **start/stop/restart/console** для **своих** ВМ и LXC; смотреть шаблоны/хранилище/firewall/сеть/узел/пулы/IPAM; управлять своими уведомлениями; смотреть настройки (для self-service страницы профиля/квоты). **Нет** create/delete по умолчанию, **нет** дашборда. Ограничен своими инстансами, так как не имеет `vm:manage`. | | **user** | Стандартный арендатор (стиль VPS) | Смотреть + **start/stop/restart/console** для **своих** ВМ и LXC; смотреть шаблоны/хранилище/firewall/сеть/узел/пулы/IPAM; управлять своими уведомлениями. Собственный профиль, SSH-ключи и квота живут на `/profile` и не требуют прав, поэтому у роли намеренно **нет** `setting:view` (он открыл бы страницу настроек панели). **Нет** create/delete по умолчанию, **нет** дашборда. Ограничен своими инстансами, так как не имеет `vm:manage`. |
| **demo** | Read-only витрина | Только просмотр: дашборд, серверы, ВМ, LXC, шаблоны, хранилище, firewall, сеть, узел, пулы, IPAM. Ни действий питания, ни записи. | | **demo** | Read-only витрина | Только просмотр: дашборд, серверы, ВМ, LXC, шаблоны, хранилище, firewall, сеть, узел, пулы, IPAM. Ни действий питания, ни записи. |
> Точный JSON каждой роли лежит в `NEW_DEFAULT_ROLES` в `backend/app/rbac/migration.py` — сверяйтесь с ним, если нужен побайтовый набор прав. > Точный JSON каждой роли лежит в `NEW_DEFAULT_ROLES` в `backend/app/rbac/migration.py` — сверяйтесь с ним, если нужен побайтовый набор прав.

View File

@@ -176,7 +176,8 @@ NEW_DEFAULT_ROLES = [
"node:view": True, "node:view": True,
"pool:view": True, "pool:view": True,
"ipam:view": True, "ipam:view": True,
"setting:view": True, # No setting:view — that grants the panel-wide settings page. A
# user's own profile lives at /profile and needs no permission.
"notification:view": True, "notification:view": True,
"notification:manage": True, "notification:manage": True,
} }

View File

@@ -616,17 +616,19 @@ def _create_permissions() -> PermissionRegistry:
requires=["log:view"] requires=["log:view"]
)) ))
# Settings permissions # Settings permissions. These cover panel-wide configuration only — a user's
# own account (profile, password, 2FA, SSH keys, notification preferences)
# is self-scoped and needs no permission at all.
registry.register(Permission( registry.register(Permission(
resource="setting", action="view", resource="setting", action="view",
display_name="View Settings", display_name="View Panel Settings",
description="View panel settings", description="View panel-wide settings (not needed for one's own profile)",
category="Settings" category="Settings"
)) ))
registry.register(Permission( registry.register(Permission(
resource="setting", action="update", resource="setting", action="update",
display_name="Update Settings", display_name="Update Panel Settings",
description="Modify panel settings", description="Modify panel-wide settings",
category="Settings", category="Settings",
requires=["setting:view"] requires=["setting:view"]
)) ))

View File

@@ -1838,6 +1838,65 @@ def migrate_app_operations_server_id(conn):
logger.info("✓ app_operations.server_id already exists") logger.info("✓ app_operations.server_id already exists")
def migrate_setting_view_panel_only(conn):
"""Migration 42: drop setting:view where it was only granting the profile page.
`setting:view` used to gate the whole /settings page, which mixed panel-wide
configuration with a user's own account (password, 2FA, SSH keys,
notification preferences). The account half now lives at /profile and needs
no permission, so roles that were given setting:view just to let their users
reach their own settings would silently gain the panel settings page.
Only roles that clearly were not meant to administer the panel are touched:
those holding setting:view without setting:update or setting:manage. Runs
once — a marker in panel_settings keeps a later admin grant from being
reverted on the next startup.
"""
if not table_exists(conn, 'roles') or not table_exists(conn, 'panel_settings'):
logger.info("Tables roles/panel_settings missing, skipping setting:view split")
return
marker = 'migration_setting_view_panel_only'
done = conn.execute(
text("SELECT 1 FROM panel_settings WHERE key = :k"), {"k": marker}
).fetchone()
if done:
logger.info("✓ setting:view split already applied, skipping")
return
import json as _json
rows = conn.execute(text("SELECT id, name, permissions FROM roles")).fetchall()
changed = []
for role_id, role_name, permissions in rows:
perms = permissions if isinstance(permissions, dict) else _json.loads(permissions or '{}')
if not perms.get('setting:view'):
continue
if perms.get('setting:update') or perms.get('setting:manage'):
continue # a real panel administrator — leave the grant alone
del perms['setting:view']
conn.execute(
text("UPDATE roles SET permissions = :p WHERE id = :id"),
{"p": _json.dumps(perms), "id": role_id},
)
changed.append(role_name)
conn.execute(
text("""
INSERT INTO panel_settings (key, value, description)
VALUES (:k, 'done', 'setting:view no longer gates a user''s own profile page')
ON CONFLICT (key) DO NOTHING
"""),
{"k": marker},
)
if changed:
logger.info(f"✓ Removed panel-only setting:view from role(s): {', '.join(changed)}")
else:
logger.info("✓ No roles needed the setting:view split")
def run_all_migrations(engine, db_session=None): def run_all_migrations(engine, db_session=None):
""" """
Run all migrations in order. Run all migrations in order.
@@ -2180,6 +2239,14 @@ def run_all_migrations(engine, db_session=None):
logger.warning(f"Instance owner backfill migration: {e}") logger.warning(f"Instance owner backfill migration: {e}")
conn.rollback() conn.rollback()
# Migration 42: setting:view now covers panel settings only
try:
migrate_setting_view_panel_only(conn)
conn.commit()
except Exception as e:
logger.warning(f"setting:view split migration: {e}")
conn.rollback()
logger.info("=" * 50) logger.info("=" * 50)
logger.info("✓ All migrations completed successfully") logger.info("✓ All migrations completed successfully")
logger.info("=" * 50) logger.info("=" * 50)

View File

@@ -0,0 +1,85 @@
"""Tests for the setting:view split (migration 42).
``table_exists`` queries ``information_schema`` and is therefore
PostgreSQL-only; it is stubbed so the migration itself — whose statements are
portable — can run against the SQLite test database.
"""
from __future__ import annotations
import json
import pytest
from sqlalchemy import text
from migrations import migrations as mig
from migrations.migrations import migrate_setting_view_panel_only
from app.models import Role
@pytest.fixture(autouse=True)
def postgres_only_checks(monkeypatch):
monkeypatch.setattr(mig, "table_exists", lambda conn, table: True)
def _run(db_session):
"""Run the migration on a connection sharing the session's transaction."""
migrate_setting_view_panel_only(db_session.connection())
def _role(db_session, name, permissions):
role = Role(
name=name, display_name=name.title(), permissions=permissions,
is_system=False, is_active=True,
)
db_session.add(role)
db_session.commit()
return role
def _perms(db_session, name) -> dict:
raw = db_session.connection().execute(
text("SELECT permissions FROM roles WHERE name = :n"), {"n": name}
).scalar()
return raw if isinstance(raw, dict) else json.loads(raw or "{}")
def test_view_only_role_loses_the_grant(db_session):
_role(db_session, "viewer", {"vm:view": True, "setting:view": True})
_run(db_session)
assert "setting:view" not in _perms(db_session, "viewer")
assert _perms(db_session, "viewer")["vm:view"] is True
def test_panel_administrator_keeps_the_grant(db_session):
_role(db_session, "ops", {"setting:view": True, "setting:update": True})
_role(db_session, "sec", {"setting:view": True, "setting:manage": True})
_run(db_session)
assert _perms(db_session, "ops")["setting:view"] is True
assert _perms(db_session, "sec")["setting:view"] is True
def test_role_without_the_grant_is_untouched(db_session):
_role(db_session, "plain", {"vm:view": True})
_run(db_session)
assert _perms(db_session, "plain") == {"vm:view": True}
def test_runs_once_so_a_later_grant_survives(db_session):
_role(db_session, "viewer", {"setting:view": True})
_run(db_session)
# An admin re-grants it deliberately after the upgrade.
db_session.connection().execute(
text("UPDATE roles SET permissions = :p WHERE name = 'viewer'"),
{"p": json.dumps({"setting:view": True})},
)
_run(db_session)
assert _perms(db_session, "viewer")["setting:view"] is True

View File

@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { DialogPortal, DialogOverlay } from '@/components/ui/dialog'; import { DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { useCommandPaletteStore } from '@/stores/command-palette-store'; import { useCommandPaletteStore } from '@/stores/command-palette-store';
import { navGroups, canSeeNavItem } from '@/lib/nav-items'; import { navGroups, canSeeNavItem, personalNavItems } from '@/lib/nav-items';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
/** /**
@@ -39,16 +39,21 @@ export default function CommandPalette() {
const flatItems = useMemo(() => { const flatItems = useMemo(() => {
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
return navGroups.flatMap((group) => const matches = (item: { label: string; path: string }) => {
group.items
.filter((item) => canSeeNavItem(item, isAdmin, permissions))
.filter((item) => {
if (!q) return true; if (!q) return true;
const label = t(`nav.${item.label.toLowerCase()}`, item.label); const label = t(`nav.${item.label.toLowerCase()}`, item.label);
return label.toLowerCase().includes(q) || item.path.toLowerCase().includes(q); return label.toLowerCase().includes(q) || item.path.toLowerCase().includes(q);
}) };
return [
...navGroups.flatMap((group) =>
group.items
.filter((item) => canSeeNavItem(item, isAdmin, permissions))
.filter(matches)
.map((item) => ({ ...item, group: group.title })) .map((item) => ({ ...item, group: group.title }))
); ),
// Not permission-gated: reachable by anyone who is logged in.
...personalNavItems.filter(matches).map((item) => ({ ...item, group: 'Account' })),
];
}, [query, isAdmin, permissions, t]); }, [query, isAdmin, permissions, t]);
// Reset transient UI state whenever the dialog's open state changes, driven // Reset transient UI state whenever the dialog's open state changes, driven

View File

@@ -0,0 +1,421 @@
import { useState, useEffect } from 'react';
import i18n from '@/lib/i18n';
import { useTranslation } from 'react-i18next';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { toast } from 'sonner';
import {
useProfile, useUpdateProfile, useChangePassword,
useMyQuota,
} from '@/hooks/use-settings';
import {
useNotificationPreferences, useUpdateNotificationPreferences,
useChannelsStatus, useSendTestNotification, useVerifyTelegramChat,
} from '@/hooks/use-notifications';
import { SSHKeysManager } from './SSHKeysManager';
import { apiClient } from '@/lib/api-client';
import { useAuthStore } from '@/stores/auth-store';
/**
* Every user's own account: profile, password, 2FA, SSH keys, quota and
* personal notification preferences. All of it is self-scoped — the endpoints
* behind it only require a session, never a permission — so this page is
* reachable by anyone who is logged in. Panel-wide configuration lives in
* SettingsPage behind `setting:view`.
*/
export default function ProfilePage() {
const { t } = useTranslation();
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">{t('nav.profile')}</h1>
<Tabs defaultValue="profile">
<TabsList>
<TabsTrigger value="profile">{t('settings.profile')}</TabsTrigger>
<TabsTrigger value="ssh-keys">{t('ssh_keys.title')}</TabsTrigger>
<TabsTrigger value="notifications">{t('settings.notifications')}</TabsTrigger>
</TabsList>
<TabsContent value="profile"><ProfileTab /></TabsContent>
<TabsContent value="ssh-keys">
<Card>
<CardHeader><CardTitle className="text-sm">{t('ssh_keys.title')}</CardTitle></CardHeader>
<CardContent><SSHKeysManager /></CardContent>
</Card>
</TabsContent>
<TabsContent value="notifications"><NotificationPreferencesCard /></TabsContent>
</Tabs>
</div>
);
}
function ProfileTab() {
const { t } = useTranslation();
const { data: profile } = useProfile();
const updateProfile = useUpdateProfile();
const changePassword = useChangePassword();
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
const [lang, setLang] = useState('ru');
const [currentPwd, setCurrentPwd] = useState('');
const [newPwd, setNewPwd] = useState('');
const [confirmPwd, setConfirmPwd] = useState('');
useEffect(() => {
if (profile) {
setDisplayName(profile.full_name || '');
setEmail(profile.email || '');
setLang(profile.language || 'ru');
}
}, [profile]);
return (
<div className="space-y-4">
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.profile_info')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<div><Label>{t('settings.username')}</Label><Input value={profile?.username || ''} disabled className="mt-1" /></div>
<div><Label>{t('settings.display_name')}</Label><Input value={displayName} onChange={e => setDisplayName(e.target.value)} className="mt-1" /></div>
<div><Label>Email</Label><Input value={email} onChange={e => setEmail(e.target.value)} className="mt-1" /></div>
<div>
<Label>{t('settings.language')}</Label>
<select value={lang} onChange={e => setLang(e.target.value)} className="mt-1 block w-full rounded-md border bg-background px-3 py-2 text-sm">
<option value="ru">Русский</option>
<option value="en">English</option>
</select>
</div>
<Button size="sm" onClick={() => updateProfile.mutate({ full_name: displayName, email, language: lang }, {
onSuccess: (r) => { i18n.changeLanguage(lang); toast.success(r.message); },
onError: (e: Error) => toast.error(e.message),
})}>{t('common.save')}</Button>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.change_password')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<div><Label>{t('settings.current_password')}</Label><Input type="password" value={currentPwd} onChange={e => setCurrentPwd(e.target.value)} className="mt-1" /></div>
<div><Label>{t('settings.new_password')}</Label><Input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} className="mt-1" /></div>
<div><Label>{t('settings.confirm_password')}</Label><Input type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)} className="mt-1" /></div>
<Button size="sm" onClick={() => {
if (newPwd !== confirmPwd) { toast.error(t('settings.password_mismatch')); return; }
changePassword.mutate({ current_password: currentPwd, new_password: newPwd, confirm_password: confirmPwd }, {
onSuccess: (r) => { toast.success(r.message); setCurrentPwd(''); setNewPwd(''); setConfirmPwd(''); },
onError: (e: Error) => toast.error(e.message),
});
}}>{t('settings.change_password')}</Button>
</CardContent>
</Card>
<TwoFactorCard />
<QuotaCard />
</div>
);
}
interface TwoFactorStatus { enabled: boolean; backup_codes_remaining: number }
interface TwoFactorSetup { secret: string; otpauth_uri: string; qr_svg: string }
function TwoFactorCard() {
const { t } = useTranslation();
const loadUser = useAuthStore((s) => s.loadUser);
const [status, setStatus] = useState<TwoFactorStatus | null>(null);
const [setup, setSetup] = useState<TwoFactorSetup | null>(null);
const [code, setCode] = useState('');
const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
const [busy, setBusy] = useState(false);
// Disable flow
const [showDisable, setShowDisable] = useState(false);
const [disablePwd, setDisablePwd] = useState('');
const [disableCode, setDisableCode] = useState('');
const refresh = () =>
apiClient.get<TwoFactorStatus>('/api/auth/2fa/status').then(setStatus).catch(() => {});
useEffect(() => { refresh(); }, []);
const startSetup = async () => {
setBusy(true);
try {
const data = await apiClient.post<TwoFactorSetup>('/api/auth/2fa/setup');
setSetup(data);
setBackupCodes(null);
setCode('');
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
const confirmEnable = async () => {
setBusy(true);
try {
const res = await apiClient.post<{ backup_codes: string[] }>('/api/auth/2fa/enable', { code });
setBackupCodes(res.backup_codes);
setSetup(null);
setCode('');
await refresh();
loadUser();
toast.success(t('settings.tfa.enabled_ok'));
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
const confirmDisable = async () => {
setBusy(true);
try {
await apiClient.post('/api/auth/2fa/disable', { password: disablePwd, code: disableCode });
setShowDisable(false);
setDisablePwd('');
setDisableCode('');
setBackupCodes(null);
await refresh();
loadUser();
toast.success(t('settings.tfa.disabled_ok'));
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
return (
<Card>
<CardHeader>
<CardTitle className="text-sm flex items-center gap-2">
{t('settings.tfa.title')}
{status?.enabled
? <Badge variant="default">{t('settings.tfa.on')}</Badge>
: <Badge variant="secondary">{t('settings.tfa.off')}</Badge>}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-xs text-muted-foreground">{t('settings.tfa.description')}</p>
{/* Freshly generated backup codes (shown once, right after enabling) */}
{backupCodes && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 space-y-2">
<p className="text-sm font-medium">{t('settings.tfa.backup_codes_title')}</p>
<p className="text-xs text-muted-foreground">{t('settings.tfa.backup_codes_hint')}</p>
<div className="grid grid-cols-2 gap-1.5 font-mono text-sm">
{backupCodes.map((c) => <span key={c} className="select-all">{c}</span>)}
</div>
<Button size="sm" variant="outline" onClick={() => navigator.clipboard?.writeText(backupCodes.join('\n'))}>
{t('settings.tfa.copy_codes')}
</Button>
</div>
)}
{/* Not enabled — offer setup */}
{!status?.enabled && !setup && !backupCodes && (
<Button size="sm" onClick={startSetup} disabled={busy}>{t('settings.tfa.enable')}</Button>
)}
{/* Setup in progress — QR + verify */}
{setup && (
<div className="space-y-3">
<div className="flex flex-col items-start gap-2 sm:flex-row sm:items-center">
<div
className="h-40 w-40 rounded-md bg-white p-2 [&>svg]:h-full [&>svg]:w-full"
dangerouslySetInnerHTML={{ __html: setup.qr_svg }}
/>
<div className="space-y-1 text-xs">
<p className="text-muted-foreground">{t('settings.tfa.scan_hint')}</p>
<p className="text-muted-foreground">{t('settings.tfa.manual_key')}</p>
<code className="select-all break-all font-mono text-foreground">{setup.secret}</code>
</div>
</div>
<div className="max-w-xs space-y-1">
<Label>{t('settings.tfa.enter_code')}</Label>
<Input value={code} inputMode="numeric" onChange={(e) => setCode(e.target.value)} placeholder="123456" />
</div>
<div className="flex gap-2">
<Button size="sm" onClick={confirmEnable} disabled={busy || code.length < 6}>{t('settings.tfa.verify_enable')}</Button>
<Button size="sm" variant="ghost" onClick={() => { setSetup(null); setCode(''); }}>{t('common.cancel')}</Button>
</div>
</div>
)}
{/* Enabled — show remaining backup codes + disable */}
{status?.enabled && !backupCodes && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
{t('settings.tfa.backup_remaining', { count: status.backup_codes_remaining })}
</p>
{!showDisable ? (
<Button size="sm" variant="destructive" onClick={() => setShowDisable(true)}>{t('settings.tfa.disable')}</Button>
) : (
<div className="space-y-2 rounded-md border p-3">
<div className="max-w-xs space-y-1">
<Label>{t('settings.current_password')}</Label>
<Input type="password" value={disablePwd} onChange={(e) => setDisablePwd(e.target.value)} />
</div>
<div className="max-w-xs space-y-1">
<Label>{t('settings.tfa.current_code')}</Label>
<Input value={disableCode} inputMode="numeric" onChange={(e) => setDisableCode(e.target.value)} placeholder="123456" />
</div>
<div className="flex gap-2">
<Button size="sm" variant="destructive" onClick={confirmDisable} disabled={busy || !disablePwd}>{t('settings.tfa.confirm_disable')}</Button>
<Button size="sm" variant="ghost" onClick={() => { setShowDisable(false); setDisablePwd(''); setDisableCode(''); }}>{t('common.cancel')}</Button>
</div>
</div>
)}
</div>
)}
</CardContent>
</Card>
);
}
function QuotaCard() {
const { t } = useTranslation();
const { data: quota, isLoading } = useMyQuota();
// Hide the card entirely if the user has no limits set (all unlimited)
const hasAnyLimit = quota && (
quota.max_instances !== null || quota.max_cores !== null ||
quota.max_memory_mb !== null || quota.max_disk_gb !== null
);
if (isLoading || !quota || !hasAnyLimit) return null;
const rows: Array<{ label: string; used: number; limit: number | null }> = [
{ label: t('users.quota.instances'), used: quota.used_instances, limit: quota.max_instances },
{ label: t('users.quota.cores'), used: quota.used_cores, limit: quota.max_cores },
{ label: t('users.quota.memory_mb'), used: quota.used_memory_mb, limit: quota.max_memory_mb },
{ label: t('users.quota.disk_gb'), used: quota.used_disk_gb, limit: quota.max_disk_gb },
];
return (
<Card>
<CardHeader><CardTitle className="text-sm">{t('users.quota.manage')}</CardTitle></CardHeader>
<CardContent className="space-y-4">
{rows.map(r => {
const pct = r.limit && r.limit > 0 ? Math.min(100, (r.used / r.limit) * 100) : 0;
const over = r.limit !== null && r.used > r.limit;
return (
<div key={r.label} className="space-y-1.5">
<div className="flex items-center justify-between text-sm">
<span>{r.label}</span>
<span className={over ? 'text-destructive' : 'text-muted-foreground'}>
{r.used}{r.limit !== null ? ` / ${r.limit}` : ` / ${t('users.quota.unlimited')}`}
</span>
</div>
{r.limit !== null && (
<div className="h-1.5 rounded-full bg-muted overflow-hidden">
<div className={`h-full ${over ? 'bg-destructive' : 'bg-primary'}`} style={{ width: `${pct}%` }} />
</div>
)}
</div>
);
})}
</CardContent>
</Card>
);
}
function Toggle({ id, checked, onChange, label }: { id: string; checked: boolean; onChange: (v: boolean) => void; label: string }) {
return (
<div className="flex items-center gap-2">
<Checkbox id={id} checked={checked} onChange={e => onChange(e.target.checked)} />
<Label htmlFor={id} className="cursor-pointer">{label}</Label>
</div>
);
}
function NotificationPreferencesCard() {
const { t } = useTranslation();
const { data: prefs } = useNotificationPreferences();
const update = useUpdateNotificationPreferences();
const sendTest = useSendTestNotification();
const verifyTg = useVerifyTelegramChat();
const { data: channelsStatus } = useChannelsStatus();
const [enabled, setEnabled] = useState(true);
const [emailEnabled, setEmailEnabled] = useState(false);
const [emailCritical, setEmailCritical] = useState(false);
const [tgEnabled, setTgEnabled] = useState(false);
const [tgChatId, setTgChatId] = useState('');
const [webhook, setWebhook] = useState('');
const [quietStart, setQuietStart] = useState('');
const [quietEnd, setQuietEnd] = useState('');
const [testChannel, setTestChannel] = useState('all');
useEffect(() => {
if (!prefs) return;
setEnabled(prefs.enabled);
setEmailEnabled(prefs.email_enabled);
setEmailCritical(prefs.email_critical_only);
setTgEnabled(prefs.telegram_enabled);
setTgChatId(prefs.telegram_chat_id ?? '');
setWebhook(prefs.webhook_url ?? '');
setQuietStart(prefs.quiet_hours_start ?? '');
setQuietEnd(prefs.quiet_hours_end ?? '');
}, [prefs]);
const handleSave = () => {
update.mutate({
enabled, email_enabled: emailEnabled, email_critical_only: emailCritical,
telegram_enabled: tgEnabled, telegram_chat_id: tgChatId || undefined,
webhook_url: webhook || undefined,
quiet_hours_start: quietStart || undefined, quiet_hours_end: quietEnd || undefined,
}, {
onSuccess: () => toast.success(t('settings.prefs_saved')),
onError: (e: Error) => toast.error(e.message),
});
};
const handleVerify = () => {
if (!tgChatId) { toast.error(t('settings.chat_id_required')); return; }
verifyTg.mutate(tgChatId, {
onSuccess: (r) => toast.success(r.message),
onError: (e: Error) => toast.error(e.message),
});
};
const handleTest = () => {
sendTest.mutate(testChannel, {
onSuccess: () => toast.success(t('settings.test_sent')),
onError: (e: Error) => toast.error(e.message),
});
};
return (
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.my_notifications')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<Toggle id="np_enabled" checked={enabled} onChange={setEnabled} label={t('settings.notifications_enabled')} />
<Toggle id="np_email" checked={emailEnabled} onChange={setEmailEnabled} label={t('settings.email_enabled')} />
<Toggle id="np_email_crit" checked={emailCritical} onChange={setEmailCritical} label={t('settings.email_critical_only')} />
<Toggle id="np_tg" checked={tgEnabled} onChange={setTgEnabled} label={t('settings.telegram_enabled')} />
<div className="flex items-end gap-2">
<div className="flex-1"><Label>Telegram Chat ID</Label><Input value={tgChatId} onChange={e => setTgChatId(e.target.value)} className="mt-1" /></div>
<Button size="sm" variant="outline" onClick={handleVerify} disabled={verifyTg.isPending}>{t('settings.verify')}</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div><Label>{t('settings.quiet_start')}</Label><Input value={quietStart} onChange={e => setQuietStart(e.target.value)} className="mt-1" placeholder="22:00" /></div>
<div><Label>{t('settings.quiet_end')}</Label><Input value={quietEnd} onChange={e => setQuietEnd(e.target.value)} className="mt-1" placeholder="08:00" /></div>
</div>
<Button size="sm" onClick={handleSave} disabled={update.isPending}>{t('common.save')}</Button>
<div className="flex items-center gap-2 border-t pt-3">
<Select value={testChannel} onValueChange={v => { if (v) setTestChannel(v); }}>
<SelectTrigger className="w-[160px]"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('common.all')}</SelectItem>
<SelectItem value="email">Email</SelectItem>
<SelectItem value="telegram">Telegram</SelectItem>
<SelectItem value="inapp">In-app</SelectItem>
</SelectContent>
</Select>
<Button size="sm" variant="outline" onClick={handleTest} disabled={sendTest.isPending}>{t('settings.send_test_notification')}</Button>
{channelsStatus && (
<span className="ml-auto text-xs text-muted-foreground">
{Object.entries(channelsStatus).map(([k, v]) => {
const conf = (v as { configured?: boolean })?.configured;
return typeof conf === 'boolean' ? `${k}: ${conf ? '✓' : '✗'}` : null;
}).filter(Boolean).join(' ')}
</span>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,17 +1,13 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import i18n from '@/lib/i18n';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
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 { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { import {
useProfile, useUpdateProfile, useChangePassword,
useMyQuota,
usePanelSettings, useUpdatePanelSettings, usePanelSettings, useUpdatePanelSettings,
useSecuritySettings, useUpdateSecuritySettings, useSecuritySettings, useUpdateSecuritySettings,
useNotificationChannels, useUpdateSMTP, useUpdateTelegram, useNotificationChannels, useUpdateSMTP, useUpdateTelegram,
@@ -19,310 +15,44 @@ import {
useUpdateRepository, useSetUpdateRepository, useUpdateStatus, usePerformUpdate, useResetUpdate, useUpdateRepository, useSetUpdateRepository, useUpdateStatus, usePerformUpdate, useResetUpdate,
useTestSMTP, useTestSMTP,
} from '@/hooks/use-settings'; } from '@/hooks/use-settings';
import { import { useTelegramBotInfo } from '@/hooks/use-notifications';
useNotificationPreferences, useUpdateNotificationPreferences,
useChannelsStatus, useSendTestNotification, useVerifyTelegramChat, useTelegramBotInfo,
} from '@/hooks/use-notifications';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { SSHKeysManager } from './SSHKeysManager';
import { useConfirm } from '@/components/shared/ConfirmDialog'; import { useConfirm } from '@/components/shared/ConfirmDialog';
import { apiClient } from '@/lib/api-client';
import { useAuthStore } from '@/stores/auth-store';
import { useHasPermission } from '@/lib/permissions'; import { useHasPermission } from '@/lib/permissions';
/**
* Panel-wide configuration, reachable with `setting:view`. Each tab is gated on
* the permission its own API requires, so a role that may only read the panel
* settings does not get security or notification-channel forms it cannot use.
* A user's own account settings live in ProfilePage, which needs no permission.
*/
export default function SettingsPage() { export default function SettingsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
// Profile, SSH keys and personal notification preferences belong to every
// user; the panel-wide tabs are gated on the permission their API requires.
const canEditPanel = useHasPermission('setting:update'); const canEditPanel = useHasPermission('setting:update');
const canManageSecurity = useHasPermission('setting:manage'); const canManageSecurity = useHasPermission('setting:manage');
// The SMTP/Telegram endpoints check `is_admin` literally, not a permission.
const isAdmin = useHasPermission();
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<h1 className="text-2xl font-bold">{t('nav.settings')}</h1> <h1 className="text-2xl font-bold">{t('nav.settings')}</h1>
<Tabs defaultValue="profile"> <Tabs defaultValue="panel">
<TabsList> <TabsList>
<TabsTrigger value="profile">{t('settings.profile')}</TabsTrigger> <TabsTrigger value="panel">{t('settings.panel')}</TabsTrigger>
<TabsTrigger value="ssh-keys">{t('ssh_keys.title')}</TabsTrigger>
{canEditPanel && <TabsTrigger value="panel">{t('settings.panel')}</TabsTrigger>}
{canManageSecurity && <TabsTrigger value="security">{t('settings.security')}</TabsTrigger>} {canManageSecurity && <TabsTrigger value="security">{t('settings.security')}</TabsTrigger>}
<TabsTrigger value="notifications">{t('settings.notifications')}</TabsTrigger> {isAdmin && <TabsTrigger value="notifications">{t('settings.notification_channels')}</TabsTrigger>}
<TabsTrigger value="about">{t('settings.about')}</TabsTrigger> <TabsTrigger value="about">{t('settings.about')}</TabsTrigger>
</TabsList> </TabsList>
<TabsContent value="profile"><ProfileTab /></TabsContent> <TabsContent value="panel"><PanelTab canEdit={canEditPanel} /></TabsContent>
<TabsContent value="ssh-keys">
<Card>
<CardHeader><CardTitle className="text-sm">{t('ssh_keys.title')}</CardTitle></CardHeader>
<CardContent><SSHKeysManager /></CardContent>
</Card>
</TabsContent>
{canEditPanel && <TabsContent value="panel"><PanelTab /></TabsContent>}
{canManageSecurity && <TabsContent value="security"><SecurityTab /></TabsContent>} {canManageSecurity && <TabsContent value="security"><SecurityTab /></TabsContent>}
<TabsContent value="notifications"><NotificationsTab /></TabsContent> {isAdmin && <TabsContent value="notifications"><NotificationChannelsCards /></TabsContent>}
<TabsContent value="about"><AboutTab /></TabsContent> <TabsContent value="about"><AboutTab /></TabsContent>
</Tabs> </Tabs>
</div> </div>
); );
} }
function ProfileTab() { /** `setting:view` shows the panel settings; saving them needs `setting:update`. */
const { t } = useTranslation(); function PanelTab({ canEdit }: { canEdit: boolean }) {
const { data: profile } = useProfile();
const updateProfile = useUpdateProfile();
const changePassword = useChangePassword();
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
const [lang, setLang] = useState('ru');
const [currentPwd, setCurrentPwd] = useState('');
const [newPwd, setNewPwd] = useState('');
const [confirmPwd, setConfirmPwd] = useState('');
useEffect(() => {
if (profile) {
setDisplayName(profile.full_name || '');
setEmail(profile.email || '');
setLang(profile.language || 'ru');
}
}, [profile]);
return (
<div className="space-y-4">
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.profile_info')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<div><Label>{t('settings.username')}</Label><Input value={profile?.username || ''} disabled className="mt-1" /></div>
<div><Label>{t('settings.display_name')}</Label><Input value={displayName} onChange={e => setDisplayName(e.target.value)} className="mt-1" /></div>
<div><Label>Email</Label><Input value={email} onChange={e => setEmail(e.target.value)} className="mt-1" /></div>
<div>
<Label>{t('settings.language')}</Label>
<select value={lang} onChange={e => setLang(e.target.value)} className="mt-1 block w-full rounded-md border bg-background px-3 py-2 text-sm">
<option value="ru">Русский</option>
<option value="en">English</option>
</select>
</div>
<Button size="sm" onClick={() => updateProfile.mutate({ full_name: displayName, email, language: lang }, {
onSuccess: (r) => { i18n.changeLanguage(lang); toast.success(r.message); },
onError: (e: Error) => toast.error(e.message),
})}>{t('common.save')}</Button>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.change_password')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<div><Label>{t('settings.current_password')}</Label><Input type="password" value={currentPwd} onChange={e => setCurrentPwd(e.target.value)} className="mt-1" /></div>
<div><Label>{t('settings.new_password')}</Label><Input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} className="mt-1" /></div>
<div><Label>{t('settings.confirm_password')}</Label><Input type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)} className="mt-1" /></div>
<Button size="sm" onClick={() => {
if (newPwd !== confirmPwd) { toast.error(t('settings.password_mismatch')); return; }
changePassword.mutate({ current_password: currentPwd, new_password: newPwd, confirm_password: confirmPwd }, {
onSuccess: (r) => { toast.success(r.message); setCurrentPwd(''); setNewPwd(''); setConfirmPwd(''); },
onError: (e: Error) => toast.error(e.message),
});
}}>{t('settings.change_password')}</Button>
</CardContent>
</Card>
<TwoFactorCard />
<QuotaCard />
</div>
);
}
interface TwoFactorStatus { enabled: boolean; backup_codes_remaining: number }
interface TwoFactorSetup { secret: string; otpauth_uri: string; qr_svg: string }
function TwoFactorCard() {
const { t } = useTranslation();
const loadUser = useAuthStore((s) => s.loadUser);
const [status, setStatus] = useState<TwoFactorStatus | null>(null);
const [setup, setSetup] = useState<TwoFactorSetup | null>(null);
const [code, setCode] = useState('');
const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
const [busy, setBusy] = useState(false);
// Disable flow
const [showDisable, setShowDisable] = useState(false);
const [disablePwd, setDisablePwd] = useState('');
const [disableCode, setDisableCode] = useState('');
const refresh = () =>
apiClient.get<TwoFactorStatus>('/api/auth/2fa/status').then(setStatus).catch(() => {});
useEffect(() => { refresh(); }, []);
const startSetup = async () => {
setBusy(true);
try {
const data = await apiClient.post<TwoFactorSetup>('/api/auth/2fa/setup');
setSetup(data);
setBackupCodes(null);
setCode('');
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
const confirmEnable = async () => {
setBusy(true);
try {
const res = await apiClient.post<{ backup_codes: string[] }>('/api/auth/2fa/enable', { code });
setBackupCodes(res.backup_codes);
setSetup(null);
setCode('');
await refresh();
loadUser();
toast.success(t('settings.tfa.enabled_ok'));
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
const confirmDisable = async () => {
setBusy(true);
try {
await apiClient.post('/api/auth/2fa/disable', { password: disablePwd, code: disableCode });
setShowDisable(false);
setDisablePwd('');
setDisableCode('');
setBackupCodes(null);
await refresh();
loadUser();
toast.success(t('settings.tfa.disabled_ok'));
} catch (e) { toast.error((e as Error).message); }
finally { setBusy(false); }
};
return (
<Card>
<CardHeader>
<CardTitle className="text-sm flex items-center gap-2">
{t('settings.tfa.title')}
{status?.enabled
? <Badge variant="default">{t('settings.tfa.on')}</Badge>
: <Badge variant="secondary">{t('settings.tfa.off')}</Badge>}
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-xs text-muted-foreground">{t('settings.tfa.description')}</p>
{/* Freshly generated backup codes (shown once, right after enabling) */}
{backupCodes && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 space-y-2">
<p className="text-sm font-medium">{t('settings.tfa.backup_codes_title')}</p>
<p className="text-xs text-muted-foreground">{t('settings.tfa.backup_codes_hint')}</p>
<div className="grid grid-cols-2 gap-1.5 font-mono text-sm">
{backupCodes.map((c) => <span key={c} className="select-all">{c}</span>)}
</div>
<Button size="sm" variant="outline" onClick={() => navigator.clipboard?.writeText(backupCodes.join('\n'))}>
{t('settings.tfa.copy_codes')}
</Button>
</div>
)}
{/* Not enabled — offer setup */}
{!status?.enabled && !setup && !backupCodes && (
<Button size="sm" onClick={startSetup} disabled={busy}>{t('settings.tfa.enable')}</Button>
)}
{/* Setup in progress — QR + verify */}
{setup && (
<div className="space-y-3">
<div className="flex flex-col items-start gap-2 sm:flex-row sm:items-center">
<div
className="h-40 w-40 rounded-md bg-white p-2 [&>svg]:h-full [&>svg]:w-full"
dangerouslySetInnerHTML={{ __html: setup.qr_svg }}
/>
<div className="space-y-1 text-xs">
<p className="text-muted-foreground">{t('settings.tfa.scan_hint')}</p>
<p className="text-muted-foreground">{t('settings.tfa.manual_key')}</p>
<code className="select-all break-all font-mono text-foreground">{setup.secret}</code>
</div>
</div>
<div className="max-w-xs space-y-1">
<Label>{t('settings.tfa.enter_code')}</Label>
<Input value={code} inputMode="numeric" onChange={(e) => setCode(e.target.value)} placeholder="123456" />
</div>
<div className="flex gap-2">
<Button size="sm" onClick={confirmEnable} disabled={busy || code.length < 6}>{t('settings.tfa.verify_enable')}</Button>
<Button size="sm" variant="ghost" onClick={() => { setSetup(null); setCode(''); }}>{t('common.cancel')}</Button>
</div>
</div>
)}
{/* Enabled — show remaining backup codes + disable */}
{status?.enabled && !backupCodes && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
{t('settings.tfa.backup_remaining', { count: status.backup_codes_remaining })}
</p>
{!showDisable ? (
<Button size="sm" variant="destructive" onClick={() => setShowDisable(true)}>{t('settings.tfa.disable')}</Button>
) : (
<div className="space-y-2 rounded-md border p-3">
<div className="max-w-xs space-y-1">
<Label>{t('settings.current_password')}</Label>
<Input type="password" value={disablePwd} onChange={(e) => setDisablePwd(e.target.value)} />
</div>
<div className="max-w-xs space-y-1">
<Label>{t('settings.tfa.current_code')}</Label>
<Input value={disableCode} inputMode="numeric" onChange={(e) => setDisableCode(e.target.value)} placeholder="123456" />
</div>
<div className="flex gap-2">
<Button size="sm" variant="destructive" onClick={confirmDisable} disabled={busy || !disablePwd}>{t('settings.tfa.confirm_disable')}</Button>
<Button size="sm" variant="ghost" onClick={() => { setShowDisable(false); setDisablePwd(''); setDisableCode(''); }}>{t('common.cancel')}</Button>
</div>
</div>
)}
</div>
)}
</CardContent>
</Card>
);
}
function QuotaCard() {
const { t } = useTranslation();
const { data: quota, isLoading } = useMyQuota();
// Hide the card entirely if the user has no limits set (all unlimited)
const hasAnyLimit = quota && (
quota.max_instances !== null || quota.max_cores !== null ||
quota.max_memory_mb !== null || quota.max_disk_gb !== null
);
if (isLoading || !quota || !hasAnyLimit) return null;
const rows: Array<{ label: string; used: number; limit: number | null }> = [
{ label: t('users.quota.instances'), used: quota.used_instances, limit: quota.max_instances },
{ label: t('users.quota.cores'), used: quota.used_cores, limit: quota.max_cores },
{ label: t('users.quota.memory_mb'), used: quota.used_memory_mb, limit: quota.max_memory_mb },
{ label: t('users.quota.disk_gb'), used: quota.used_disk_gb, limit: quota.max_disk_gb },
];
return (
<Card>
<CardHeader><CardTitle className="text-sm">{t('users.quota.manage')}</CardTitle></CardHeader>
<CardContent className="space-y-4">
{rows.map(r => {
const pct = r.limit && r.limit > 0 ? Math.min(100, (r.used / r.limit) * 100) : 0;
const over = r.limit !== null && r.used > r.limit;
return (
<div key={r.label} className="space-y-1.5">
<div className="flex items-center justify-between text-sm">
<span>{r.label}</span>
<span className={over ? 'text-destructive' : 'text-muted-foreground'}>
{r.used}{r.limit !== null ? ` / ${r.limit}` : ` / ${t('users.quota.unlimited')}`}
</span>
</div>
{r.limit !== null && (
<div className="h-1.5 rounded-full bg-muted overflow-hidden">
<div className={`h-full ${over ? 'bg-destructive' : 'bg-primary'}`} style={{ width: `${pct}%` }} />
</div>
)}
</div>
);
})}
</CardContent>
</Card>
);
}
function PanelTab() {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: settings } = usePanelSettings(); const { data: settings } = usePanelSettings();
const updatePanel = useUpdatePanelSettings(); const updatePanel = useUpdatePanelSettings();
@@ -341,13 +71,15 @@ function PanelTab() {
<div><Label>{t('settings.panel_name')}</Label><Input value={settings?.panel_name || ''} disabled className="mt-1" /></div> <div><Label>{t('settings.panel_name')}</Label><Input value={settings?.panel_name || ''} disabled className="mt-1" /></div>
<div> <div>
<Label>{t('settings.log_retention_days')}</Label> <Label>{t('settings.log_retention_days')}</Label>
<Input type="number" value={logRetention} onChange={e => setLogRetention(e.target.value)} className="mt-1" min={1} max={365} /> <Input type="number" value={logRetention} onChange={e => setLogRetention(e.target.value)} className="mt-1" min={1} max={365} disabled={!canEdit} />
<p className="text-xs text-muted-foreground mt-1">{t('settings.days')}</p> <p className="text-xs text-muted-foreground mt-1">{t('settings.days')}</p>
</div> </div>
{canEdit && (
<Button size="sm" onClick={() => updatePanel.mutate({ log_retention_days: Number(logRetention) }, { <Button size="sm" onClick={() => updatePanel.mutate({ log_retention_days: Number(logRetention) }, {
onSuccess: (r) => toast.success(r.message), onSuccess: (r) => toast.success(r.message),
onError: (e: Error) => toast.error(e.message), onError: (e: Error) => toast.error(e.message),
})}>{t('common.save')}</Button> })}>{t('common.save')}</Button>
)}
</CardContent> </CardContent>
</Card> </Card>
); );
@@ -389,18 +121,6 @@ function SecurityTab() {
); );
} }
function NotificationsTab() {
// The SMTP/Telegram channels are panel-wide and admin-only on the backend;
// the preferences card below is every user's own notification settings.
const isAdmin = useHasPermission();
return (
<div className="space-y-4">
{isAdmin && <NotificationChannelsCards />}
<NotificationPreferencesCard />
</div>
);
}
function NotificationChannelsCards() { function NotificationChannelsCards() {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: channels } = useNotificationChannels(); const { data: channels } = useNotificationChannels();
@@ -483,114 +203,6 @@ function NotificationChannelsCards() {
); );
} }
function Toggle({ id, checked, onChange, label }: { id: string; checked: boolean; onChange: (v: boolean) => void; label: string }) {
return (
<div className="flex items-center gap-2">
<Checkbox id={id} checked={checked} onChange={e => onChange(e.target.checked)} />
<Label htmlFor={id} className="cursor-pointer">{label}</Label>
</div>
);
}
function NotificationPreferencesCard() {
const { t } = useTranslation();
const { data: prefs } = useNotificationPreferences();
const update = useUpdateNotificationPreferences();
const sendTest = useSendTestNotification();
const verifyTg = useVerifyTelegramChat();
const { data: channelsStatus } = useChannelsStatus();
const [enabled, setEnabled] = useState(true);
const [emailEnabled, setEmailEnabled] = useState(false);
const [emailCritical, setEmailCritical] = useState(false);
const [tgEnabled, setTgEnabled] = useState(false);
const [tgChatId, setTgChatId] = useState('');
const [webhook, setWebhook] = useState('');
const [quietStart, setQuietStart] = useState('');
const [quietEnd, setQuietEnd] = useState('');
const [testChannel, setTestChannel] = useState('all');
useEffect(() => {
if (!prefs) return;
setEnabled(prefs.enabled);
setEmailEnabled(prefs.email_enabled);
setEmailCritical(prefs.email_critical_only);
setTgEnabled(prefs.telegram_enabled);
setTgChatId(prefs.telegram_chat_id ?? '');
setWebhook(prefs.webhook_url ?? '');
setQuietStart(prefs.quiet_hours_start ?? '');
setQuietEnd(prefs.quiet_hours_end ?? '');
}, [prefs]);
const handleSave = () => {
update.mutate({
enabled, email_enabled: emailEnabled, email_critical_only: emailCritical,
telegram_enabled: tgEnabled, telegram_chat_id: tgChatId || undefined,
webhook_url: webhook || undefined,
quiet_hours_start: quietStart || undefined, quiet_hours_end: quietEnd || undefined,
}, {
onSuccess: () => toast.success(t('settings.prefs_saved')),
onError: (e: Error) => toast.error(e.message),
});
};
const handleVerify = () => {
if (!tgChatId) { toast.error(t('settings.chat_id_required')); return; }
verifyTg.mutate(tgChatId, {
onSuccess: (r) => toast.success(r.message),
onError: (e: Error) => toast.error(e.message),
});
};
const handleTest = () => {
sendTest.mutate(testChannel, {
onSuccess: () => toast.success(t('settings.test_sent')),
onError: (e: Error) => toast.error(e.message),
});
};
return (
<Card>
<CardHeader><CardTitle className="text-sm">{t('settings.my_notifications')}</CardTitle></CardHeader>
<CardContent className="space-y-3">
<Toggle id="np_enabled" checked={enabled} onChange={setEnabled} label={t('settings.notifications_enabled')} />
<Toggle id="np_email" checked={emailEnabled} onChange={setEmailEnabled} label={t('settings.email_enabled')} />
<Toggle id="np_email_crit" checked={emailCritical} onChange={setEmailCritical} label={t('settings.email_critical_only')} />
<Toggle id="np_tg" checked={tgEnabled} onChange={setTgEnabled} label={t('settings.telegram_enabled')} />
<div className="flex items-end gap-2">
<div className="flex-1"><Label>Telegram Chat ID</Label><Input value={tgChatId} onChange={e => setTgChatId(e.target.value)} className="mt-1" /></div>
<Button size="sm" variant="outline" onClick={handleVerify} disabled={verifyTg.isPending}>{t('settings.verify')}</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div><Label>{t('settings.quiet_start')}</Label><Input value={quietStart} onChange={e => setQuietStart(e.target.value)} className="mt-1" placeholder="22:00" /></div>
<div><Label>{t('settings.quiet_end')}</Label><Input value={quietEnd} onChange={e => setQuietEnd(e.target.value)} className="mt-1" placeholder="08:00" /></div>
</div>
<Button size="sm" onClick={handleSave} disabled={update.isPending}>{t('common.save')}</Button>
<div className="flex items-center gap-2 border-t pt-3">
<Select value={testChannel} onValueChange={v => { if (v) setTestChannel(v); }}>
<SelectTrigger className="w-[160px]"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('common.all')}</SelectItem>
<SelectItem value="email">Email</SelectItem>
<SelectItem value="telegram">Telegram</SelectItem>
<SelectItem value="inapp">In-app</SelectItem>
</SelectContent>
</Select>
<Button size="sm" variant="outline" onClick={handleTest} disabled={sendTest.isPending}>{t('settings.send_test_notification')}</Button>
{channelsStatus && (
<span className="ml-auto text-xs text-muted-foreground">
{Object.entries(channelsStatus).map(([k, v]) => {
const conf = (v as { configured?: boolean })?.configured;
return typeof conf === 'boolean' ? `${k}: ${conf ? '✓' : '✗'}` : null;
}).filter(Boolean).join(' ')}
</span>
)}
</div>
</CardContent>
</Card>
);
}
function AboutTab() { function AboutTab() {
const { t } = useTranslation(); const { t } = useTranslation();

View File

@@ -1,6 +1,5 @@
import { Link, useLocation, Outlet, useNavigate } from 'react-router'; import { Link, useLocation, Outlet, useNavigate } from 'react-router';
import { import {
Settings,
Sun, Sun,
Moon, Moon,
Menu, Menu,
@@ -127,9 +126,9 @@ function UserSection() {
<ChevronDown className="h-3.5 w-3.5 text-muted-foreground" /> <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48"> <DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem onClick={() => navigate('/settings')}> <DropdownMenuItem onClick={() => navigate('/profile')}>
<Settings className="mr-2 h-4 w-4" /> <UserCog className="mr-2 h-4 w-4" />
{t('nav.settings')} {t('nav.profile')}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-destructive"> <DropdownMenuItem onClick={handleLogout} className="text-destructive">

View File

@@ -15,6 +15,7 @@ import {
Store, Store,
Package, Package,
Terminal, Terminal,
UserCog,
} from 'lucide-react'; } from 'lucide-react';
import { hasPermission } from './permissions'; import { hasPermission } from './permissions';
@@ -73,11 +74,22 @@ export const navGroups: NavGroup[] = [
{ label: 'Users', icon: Users, path: '/users', permission: 'user:view' }, { label: 'Users', icon: Users, path: '/users', permission: 'user:view' },
{ label: 'Workspaces', icon: FolderKanban, path: '/workspaces' }, // admin-only { label: 'Workspaces', icon: FolderKanban, path: '/workspaces' }, // admin-only
{ label: 'Logs', icon: FileText, path: '/logs', permission: 'log:view' }, { label: 'Logs', icon: FileText, path: '/logs', permission: 'log:view' },
// Panel-wide settings only; a user's own account is /profile below.
{ label: 'Settings', icon: Settings, path: '/settings', permission: 'setting:view' }, { label: 'Settings', icon: Settings, path: '/settings', permission: 'setting:view' },
], ],
}, },
]; ];
/**
* Pages every logged-in user may open. They are self-scoped (the endpoints
* behind them only require a session), so unlike `navGroups` these carry no
* permission — the type omits the field so they can never be mistaken for
* admin-only entries. Reached from the user menu, not the sidebar groups.
*/
export const personalNavItems: Omit<NavItem, 'permission'>[] = [
{ label: 'Profile', icon: UserCog, path: '/profile' },
];
/** Whether the current user may see a given nav item. Admins see everything. */ /** Whether the current user may see a given nav item. Admins see everything. */
export function canSeeNavItem( export function canSeeNavItem(
item: NavItem, item: NavItem,
@@ -88,9 +100,10 @@ export function canSeeNavItem(
} }
/** /**
* Path of the first nav item the user may open, or null when nothing is * Path of the first nav item the user may open, falling back to their own
* reachable. Used as the landing page for users who lack `dashboard:view` and * profile when no permission-gated page is reachable. Used as the landing page
* as the redirect target when a route guard denies access. * for users who lack `dashboard:view` and as the redirect target when a route
* guard denies access.
*/ */
export function firstAccessiblePath( export function firstAccessiblePath(
isAdmin: boolean, isAdmin: boolean,
@@ -101,5 +114,5 @@ export function firstAccessiblePath(
if (canSeeNavItem(item, isAdmin, permissions)) return item.path; if (canSeeNavItem(item, isAdmin, permissions)) return item.path;
} }
} }
return null; return personalNavItems[0]?.path ?? null;
} }

View File

@@ -1,5 +1,7 @@
{ {
"nav": { "nav": {
"account": "Account",
"profile": "Profile",
"infrastructure": "Infrastructure", "infrastructure": "Infrastructure",
"network": "Network", "network": "Network",
"management": "Management", "management": "Management",
@@ -1328,6 +1330,7 @@
}, },
"settings": { "settings": {
"profile": "Profile", "profile": "Profile",
"notification_channels": "Notification channels",
"panel": "Panel", "panel": "Panel",
"security": "Security", "security": "Security",
"notifications": "Notifications", "notifications": "Notifications",

View File

@@ -1,5 +1,7 @@
{ {
"nav": { "nav": {
"account": "Учётная запись",
"profile": "Профиль",
"infrastructure": "Инфраструктура", "infrastructure": "Инфраструктура",
"network": "Сеть", "network": "Сеть",
"management": "Управление", "management": "Управление",
@@ -1328,6 +1330,7 @@
}, },
"settings": { "settings": {
"profile": "Профиль", "profile": "Профиль",
"notification_channels": "Каналы уведомлений",
"panel": "Панель", "panel": "Панель",
"security": "Безопасность", "security": "Безопасность",
"notifications": "Уведомления", "notifications": "Уведомления",
@@ -1658,8 +1661,8 @@
"log_view": "Просмотр логов", "log_view": "Просмотр логов",
"log_export": "Экспорт логов", "log_export": "Экспорт логов",
"log_delete": "Удаление логов", "log_delete": "Удаление логов",
"setting_view": "Просмотр настроек", "setting_view": "Просмотр настроек панели",
"setting_update": "Изменение настроек", "setting_update": "Изменение настроек панели",
"setting_manage": "Управление безопасностью", "setting_manage": "Управление безопасностью",
"notification_view": "Просмотр уведомлений", "notification_view": "Просмотр уведомлений",
"notification_manage": "Управление уведомлениями", "notification_manage": "Управление уведомлениями",

View File

@@ -35,6 +35,7 @@ const UsersPage = lazy(() => import('./features/users/UsersPage.tsx'));
const WorkspacesPage = lazy(() => import('./features/workspaces/WorkspacesPage.tsx')); const WorkspacesPage = lazy(() => import('./features/workspaces/WorkspacesPage.tsx'));
const LogsPage = lazy(() => import('./features/logs/LogsPage.tsx')); const LogsPage = lazy(() => import('./features/logs/LogsPage.tsx'));
const SettingsPage = lazy(() => import('./features/settings/SettingsPage.tsx')); const SettingsPage = lazy(() => import('./features/settings/SettingsPage.tsx'));
const ProfilePage = lazy(() => import('./features/settings/ProfilePage.tsx'));
const AppStorePage = lazy(() => import('./features/appstore/AppStorePage.tsx')); const AppStorePage = lazy(() => import('./features/appstore/AppStorePage.tsx'));
const AppDetailPage = lazy(() => import('./features/appstore/AppDetailPage.tsx')); const AppDetailPage = lazy(() => import('./features/appstore/AppDetailPage.tsx'));
const MyAppsPage = lazy(() => import('./features/appstore/MyAppsPage.tsx')); const MyAppsPage = lazy(() => import('./features/appstore/MyAppsPage.tsx'));
@@ -121,6 +122,8 @@ export const router = createBrowserRouter([
{ path: '/workspaces', element: <Page><WorkspacesPage /></Page> }, { path: '/workspaces', element: <Page><WorkspacesPage /></Page> },
{ path: '/logs', element: <Page perm="log:view"><LogsPage /></Page> }, { path: '/logs', element: <Page perm="log:view"><LogsPage /></Page> },
{ path: '/settings', element: <Page perm="setting:view"><SettingsPage /></Page> }, { path: '/settings', element: <Page perm="setting:view"><SettingsPage /></Page> },
// Own account — self-scoped endpoints, so no permission gates it.
{ path: '/profile', element: <SuspenseWrap><ProfilePage /></SuspenseWrap> },
], ],
}, },
], ],

View File

@@ -513,6 +513,9 @@ INSERT INTO roles (name, display_name, description, permissions, is_system, is_a
"setting:view": true, "setting:view": true,
"notification:view": true, "notification:manage": true "notification:view": true, "notification:manage": true
}', TRUE, TRUE), }', TRUE, TRUE),
-- No setting:view here: it grants the panel-wide settings page. A user's own
-- profile (password, 2FA, SSH keys, notification preferences) lives at /profile
-- and is reachable without any permission.
('user', 'User', 'Standard user with limited access', '{ ('user', 'User', 'Standard user with limited access', '{
"dashboard:view": true, "dashboard:view": true,
"server:view": true, "server:view": true,
@@ -521,7 +524,6 @@ INSERT INTO roles (name, display_name, description, permissions, is_system, is_a
"template:view": true, "template:view": true,
"storage:view": true, "storage:view": true,
"ipam:view": true, "ipam:view": true,
"setting:view": true,
"notification:view": true, "notification:manage": true "notification:view": true, "notification:manage": true
}', TRUE, TRUE), }', TRUE, TRUE),
('demo', 'Demo User', 'Read-only access for demonstration', '{ ('demo', 'Demo User', 'Read-only access for demonstration', '{