This commit is contained in:
lendry
2026-06-25 07:23:34 +03:00
parent f2366a69a0
commit 71b270fcb3
19 changed files with 1410 additions and 112 deletions

View File

@@ -1,10 +1,17 @@
import { Body, Controller, ForbiddenException, Get, Headers, Param, Patch, Post } from '@nestjs/common'; import { Body, Controller, Delete, ForbiddenException, Get, Headers, Param, Patch, Post } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
import { CoreGrpcService } from '../core-grpc.service'; import { CoreGrpcService } from '../core-grpc.service';
import { getAuthorizedUserId } from '../document-access'; import { getAuthorizedUserId } from '../document-access';
import {
import { CoreGrpcService } from '../core-grpc.service'; ChangePasswordDto,
PasswordVerificationDto,
SendPasswordVerificationOtpDto,
SetPasswordDto,
UpdateAvatarDto,
UpdateContactsDto,
UpdateProfileDto
} from '../dto/profile.dto';
@ApiTags('Профиль и биометрия') @ApiTags('Профиль и биометрия')
@ApiBearerAuth() @ApiBearerAuth()
@Controller('profile/users/:userId') @Controller('profile/users/:userId')
@@ -60,14 +67,52 @@ export class ProfileController {
} }
@Post('password') @Post('password')
} @ApiOperation({ summary: 'Установить пароль', description: 'Устанавливает пароль для аккаунта без ранее заданного пароля.' })
@ApiParam({ name: 'userId', description: 'ID пользователя' }) @ApiParam({ name: 'userId', description: 'ID пользователя' })
@ApiBody({ type: SetPasswordDto }) @ApiBody({ type: SetPasswordDto })
@ApiResponse({ status: 201, description: 'Пароль установлен' }) @ApiResponse({ status: 201, description: 'Пароль установлен' })
@Patch('avatar') async setPassword(
@Headers('authorization') authorization: string | undefined,
@Param('userId') userId: string,
@Body() dto: SetPasswordDto
) {
await this.assertSelfAccess(authorization, userId);
return this.core.profile.SetPassword({ userId, password: dto.password }); return this.core.profile.SetPassword({ userId, password: dto.password });
} }
@Post('password/otp')
@ApiOperation({ summary: 'Отправить OTP для смены пароля' })
async sendPasswordVerificationOtp(
@Headers('authorization') authorization: string | undefined,
@Param('userId') userId: string,
@Body() dto: SendPasswordVerificationOtpDto
) {
await this.assertSelfAccess(authorization, userId);
return this.core.profile.SendPasswordVerificationOtp({ userId, channel: dto.channel });
}
@Patch('password')
@ApiOperation({ summary: 'Сменить пароль с подтверждением личности' })
async changePassword(
@Headers('authorization') authorization: string | undefined,
@Param('userId') userId: string,
@Body() dto: ChangePasswordDto
) {
await this.assertSelfAccess(authorization, userId);
return this.core.profile.ChangePassword({ userId, ...dto });
}
@Delete('password')
@ApiOperation({ summary: 'Удалить пароль с подтверждением личности' })
async removePassword(
@Headers('authorization') authorization: string | undefined,
@Param('userId') userId: string,
@Body() dto: PasswordVerificationDto
) {
await this.assertSelfAccess(authorization, userId);
return this.core.profile.RemovePassword({ userId, ...dto });
}
@Post('self-delete') @Post('self-delete')
@ApiOperation({ @ApiOperation({
summary: 'Удалить свой профиль', summary: 'Удалить свой профиль',

View File

@@ -76,6 +76,41 @@ export class SetPasswordDto {
password!: string; password!: string;
} }
export class SendPasswordVerificationOtpDto {
@ApiProperty({ description: 'Канал OTP', enum: ['sms', 'email'] })
@IsString({ message: 'Канал должен быть строкой' })
channel!: 'sms' | 'email';
}
export class PasswordVerificationDto {
@ApiPropertyOptional({ description: 'Текущий пароль' })
@IsOptional()
@IsString({ message: 'Текущий пароль должен быть строкой' })
currentPassword?: string;
@ApiPropertyOptional({ description: 'OTP-код из SMS или почты' })
@IsOptional()
@IsString({ message: 'OTP-код должен быть строкой' })
otpCode?: string;
@ApiPropertyOptional({ description: 'Канал OTP', enum: ['sms', 'email'] })
@IsOptional()
@IsString({ message: 'Канал OTP должен быть строкой' })
otpChannel?: 'sms' | 'email';
@ApiPropertyOptional({ description: 'Код из приложения-аутентификатора' })
@IsOptional()
@IsString({ message: 'Код аутентификатора должен быть строкой' })
totpCode?: string;
}
export class ChangePasswordDto extends PasswordVerificationDto {
@ApiProperty({ description: 'Новый пароль', minLength: 8 })
@IsString({ message: 'Пароль должен быть строкой' })
@MinLength(8, { message: 'Пароль должен содержать минимум 8 символов' })
newPassword!: string;
}
export class UserIdParamDto { export class UserIdParamDto {
@ApiProperty({ description: 'ID пользователя' }) @ApiProperty({ description: 'ID пользователя' })
@IsString({ message: 'ID пользователя должен быть строкой' }) @IsString({ message: 'ID пользователя должен быть строкой' })

View File

@@ -24,7 +24,8 @@ import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { OtpInput } from '@/components/ui/otp-input'; import { OtpInput } from '@/components/ui/otp-input';
import { ActiveDevice, apiFetch, SignInEvent, TotpSetupResponse, TotpStatusResponse } from '@/lib/api'; import { ActiveDevice, apiFetch, getApiErrorMessage, SignInEvent, TotpSetupResponse, TotpStatusResponse } from '@/lib/api';
import { cn } from '@/lib/utils';
import { QRCodeSVG } from 'qrcode.react'; import { QRCodeSVG } from 'qrcode.react';
import { useRequireAuth } from '@/hooks/use-require-auth'; import { useRequireAuth } from '@/hooks/use-require-auth';
@@ -56,8 +57,13 @@ const dialogConfig: Record<Exclude<DialogMode, null | 'totpSetup' | 'totpDisable
backupPhone: { title: 'Резервный телефон', placeholder: '+79991234567', type: 'tel' } backupPhone: { title: 'Резервный телефон', placeholder: '+79991234567', type: 'tel' }
}; };
const passwordChangeHint =
'Чтобы сменить или удалить пароль, подтвердите личность одним из доступных способов ниже.';
type PasswordVerifyMethod = 'current' | 'sms' | 'email' | 'totp';
export default function SecurityPage() { export default function SecurityPage() {
const { user, token } = useAuth(); const { user, token, refreshProfile } = useAuth();
const { isReady } = useRequireAuth(); const { isReady } = useRequireAuth();
const { showToast } = useToast(); const { showToast } = useToast();
const [devices, setDevices] = useState<ActiveDevice[]>([]); const [devices, setDevices] = useState<ActiveDevice[]>([]);
@@ -70,6 +76,17 @@ export default function SecurityPage() {
const [totpEnabled, setTotpEnabled] = useState(false); const [totpEnabled, setTotpEnabled] = useState(false);
const [totpSetup, setTotpSetup] = useState<TotpSetupResponse | null>(null); const [totpSetup, setTotpSetup] = useState<TotpSetupResponse | null>(null);
const [totpCode, setTotpCode] = useState(''); const [totpCode, setTotpCode] = useState('');
const [passwordVerifyMethod, setPasswordVerifyMethod] = useState<PasswordVerifyMethod>('current');
const [currentPassword, setCurrentPassword] = useState('');
const [passwordOtpCode, setPasswordOtpCode] = useState('');
const [passwordOtpSent, setPasswordOtpSent] = useState(false);
const [passwordOtpMasked, setPasswordOtpMasked] = useState('');
const [passwordTotpCode, setPasswordTotpCode] = useState('');
const [newPassword, setNewPassword] = useState('');
const [passwordOtpSending, setPasswordOtpSending] = useState(false);
const hasSmsContact = Boolean(user?.phone || user?.backupPhone);
const hasEmailContact = Boolean(user?.email || user?.backupEmail);
const loadSecurity = useCallback(async () => { const loadSecurity = useCallback(async () => {
if (!user || !token) return; if (!user || !token) return;
@@ -178,6 +195,108 @@ export default function SecurityPage() {
} }
} }
function buildPasswordVerification() {
if (passwordVerifyMethod === 'current') {
return { currentPassword: currentPassword.trim() };
}
if (passwordVerifyMethod === 'sms' || passwordVerifyMethod === 'email') {
return { otpCode: passwordOtpCode.trim(), otpChannel: passwordVerifyMethod };
}
return { totpCode: passwordTotpCode.trim() };
}
function isPasswordVerificationReady() {
if (passwordVerifyMethod === 'current') return currentPassword.trim().length > 0;
if (passwordVerifyMethod === 'sms' || passwordVerifyMethod === 'email') {
return passwordOtpSent && passwordOtpCode.trim().length === 6;
}
return passwordTotpCode.trim().length === 6;
}
async function sendPasswordVerificationOtp() {
if (!user || !token || (passwordVerifyMethod !== 'sms' && passwordVerifyMethod !== 'email')) return;
setPasswordOtpSending(true);
try {
const response = await apiFetch<{ maskedTarget?: string }>(
`/profile/users/${user.id}/password/otp`,
{ method: 'POST', body: JSON.stringify({ channel: passwordVerifyMethod }) },
token
);
setPasswordOtpSent(true);
setPasswordOtpMasked(response.maskedTarget ?? '');
setPasswordOtpCode('');
showToast(`Код отправлен${response.maskedTarget ? ` на ${response.maskedTarget}` : ''}`);
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось отправить код') ?? 'Ошибка');
} finally {
setPasswordOtpSending(false);
}
}
async function submitPasswordChange() {
if (!user || !token || !newPassword.trim()) {
showToast('Укажите новый пароль');
return;
}
if (!isPasswordVerificationReady()) {
showToast('Подтвердите личность перед сменой пароля');
return;
}
setIsDialogSaving(true);
try {
await apiFetch(
`/profile/users/${user.id}/password`,
{
method: 'PATCH',
body: JSON.stringify({ newPassword: newPassword.trim(), ...buildPasswordVerification() })
},
token
);
showToast('Пароль изменён');
resetPasswordDialog();
setDialogMode(null);
await refreshProfile();
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось сменить пароль') ?? 'Ошибка');
} finally {
setIsDialogSaving(false);
}
}
async function submitPasswordRemove() {
if (!user || !token) return;
if (!isPasswordVerificationReady()) {
showToast('Подтвердите личность перед удалением пароля');
return;
}
setIsDialogSaving(true);
try {
await apiFetch(
`/profile/users/${user.id}/password`,
{ method: 'DELETE', body: JSON.stringify(buildPasswordVerification()) },
token
);
showToast('Пароль удалён');
resetPasswordDialog();
setDialogMode(null);
await refreshProfile();
} catch (error) {
showToast(getApiErrorMessage(error, 'Не удалось удалить пароль') ?? 'Ошибка');
} finally {
setIsDialogSaving(false);
}
}
function resetPasswordDialog() {
setPasswordVerifyMethod('current');
setCurrentPassword('');
setPasswordOtpCode('');
setPasswordOtpSent(false);
setPasswordOtpMasked('');
setPasswordTotpCode('');
setNewPassword('');
}
async function submitDialog() { async function submitDialog() {
if (!user || !token || !dialogMode) return; if (!user || !token || !dialogMode) return;
setIsDialogSaving(true); setIsDialogSaving(true);
@@ -188,6 +307,7 @@ export default function SecurityPage() {
} else if (dialogMode === 'password') { } else if (dialogMode === 'password') {
await apiFetch(`/profile/users/${user.id}/password`, { method: 'POST', body: JSON.stringify({ password: dialogValue }) }, token); await apiFetch(`/profile/users/${user.id}/password`, { method: 'POST', body: JSON.stringify({ password: dialogValue }) }, token);
showToast('Пароль установлен'); showToast('Пароль установлен');
await refreshProfile();
} else if (dialogMode === 'backupEmail') { } else if (dialogMode === 'backupEmail') {
await apiFetch(`/profile/users/${user.id}/contacts`, { method: 'PATCH', body: JSON.stringify({ backupEmail: dialogValue.trim() }) }, token); await apiFetch(`/profile/users/${user.id}/contacts`, { method: 'PATCH', body: JSON.stringify({ backupEmail: dialogValue.trim() }) }, token);
showToast('Резервная почта добавлена'); showToast('Резервная почта добавлена');
@@ -206,6 +326,9 @@ export default function SecurityPage() {
function openDialog(mode: Exclude<DialogMode, null>) { function openDialog(mode: Exclude<DialogMode, null>) {
setDialogValue(''); setDialogValue('');
if (mode === 'password') {
resetPasswordDialog();
}
setDialogMode(mode); setDialogMode(mode);
} }
@@ -280,7 +403,11 @@ export default function SecurityPage() {
<KeyRound className="h-5 w-5" /> <KeyRound className="h-5 w-5" />
<div className="flex-1"> <div className="flex-1">
<p className="font-medium">Пароль</p> <p className="font-medium">Пароль</p>
<p className="text-sm text-[#667085]">{user?.email || user?.phone ? 'Добавить пароль как способ входа' : 'Установить пароль'}</p> <p className="text-sm text-[#667085]">
{user?.hasPassword
? 'Пароль установлен. Для смены или удаления потребуется подтверждение.'
: 'Добавить пароль как способ входа'}
</p>
</div> </div>
<ChevronRight className="h-5 w-5 text-[#a8adbc]" /> <ChevronRight className="h-5 w-5 text-[#a8adbc]" />
</button> </button>
@@ -335,6 +462,7 @@ export default function SecurityPage() {
setTotpSetup(null); setTotpSetup(null);
} }
setTotpCode(''); setTotpCode('');
resetPasswordDialog();
} }
}}> }}>
<DialogContent> <DialogContent>
@@ -369,8 +497,118 @@ export default function SecurityPage() {
{dialogMode && dialogMode !== 'totpSetup' && dialogMode !== 'totpDisable' ? ( {dialogMode && dialogMode !== 'totpSetup' && dialogMode !== 'totpDisable' ? (
<> <>
<DialogHeader> <DialogHeader>
<DialogTitle>{dialogConfig[dialogMode].title}</DialogTitle> <DialogTitle>
{dialogMode === 'password' && user?.hasPassword ? 'Пароль установлен' : dialogConfig[dialogMode].title}
</DialogTitle>
</DialogHeader> </DialogHeader>
{dialogMode === 'password' && user?.hasPassword ? (
<div className="space-y-4">
<p className="text-sm leading-relaxed text-[#667085]">{passwordChangeHint}</p>
<div className="flex flex-wrap gap-2">
{[
{ id: 'current' as const, label: 'Текущий пароль' },
...(hasSmsContact ? [{ id: 'sms' as const, label: 'SMS' }] : []),
...(hasEmailContact ? [{ id: 'email' as const, label: 'Почта' }] : []),
...(totpEnabled ? [{ id: 'totp' as const, label: 'Аутентификатор' }] : [])
].map((method) => (
<button
key={method.id}
type="button"
className={cn(
'rounded-full px-3 py-1.5 text-sm transition',
passwordVerifyMethod === method.id
? 'bg-[#111827] text-white'
: 'bg-[#f4f5f8] text-[#667085] hover:bg-[#eceef4]'
)}
onClick={() => {
setPasswordVerifyMethod(method.id);
setPasswordOtpSent(false);
setPasswordOtpCode('');
setPasswordTotpCode('');
setCurrentPassword('');
}}
>
{method.label}
</button>
))}
</div>
{passwordVerifyMethod === 'current' ? (
<div className="rounded-2xl bg-[#f4f5f8] px-4">
<Input
className="border-0 bg-transparent focus-visible:ring-0"
type="password"
placeholder="Текущий пароль"
value={currentPassword}
onChange={(event) => setCurrentPassword(event.target.value)}
/>
</div>
) : null}
{passwordVerifyMethod === 'sms' || passwordVerifyMethod === 'email' ? (
<div className="space-y-3">
<Button
type="button"
variant="secondary"
className="w-full rounded-xl"
disabled={passwordOtpSending}
onClick={() => void sendPasswordVerificationOtp()}
>
{passwordOtpSending ? 'Отправляем код...' : `Отправить код ${passwordVerifyMethod === 'sms' ? 'в SMS' : 'на почту'}`}
</Button>
{passwordOtpSent ? (
<p className="text-center text-sm text-[#667085]">
Код отправлен{passwordOtpMasked ? ` на ${passwordOtpMasked}` : ''}
</p>
) : null}
<OtpInput
variant="light"
value={passwordOtpCode}
onChange={setPasswordOtpCode}
disabled={!passwordOtpSent || isDialogSaving}
/>
</div>
) : null}
{passwordVerifyMethod === 'totp' ? (
<div className="space-y-2">
<p className="text-sm text-[#667085]">Введите код из приложения-аутентификатора</p>
<OtpInput variant="light" value={passwordTotpCode} onChange={setPasswordTotpCode} disabled={isDialogSaving} />
</div>
) : null}
<div className="rounded-2xl bg-[#f4f5f8] px-4">
<Input
className="border-0 bg-transparent focus-visible:ring-0"
type="password"
placeholder="Новый пароль (мин. 8 символов)"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
/>
</div>
<div className="flex flex-col gap-2 pt-1">
<Button
className="w-full rounded-xl"
disabled={isDialogSaving || newPassword.trim().length < 8 || !isPasswordVerificationReady()}
onClick={() => void submitPasswordChange()}
>
{isDialogSaving ? 'Сохраняем...' : 'Сохранить новый пароль'}
</Button>
<Button
type="button"
variant="ghost"
className="w-full rounded-xl text-red-600 hover:bg-red-50 hover:text-red-700"
disabled={isDialogSaving || !isPasswordVerificationReady()}
onClick={() => void submitPasswordRemove()}
>
Удалить пароль
</Button>
</div>
</div>
) : (
<>
<div className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-4"> <div className="flex items-center gap-3 rounded-2xl bg-[#f4f5f8] px-4">
<ShieldCheck className="h-5 w-5 text-[#667085]" /> <ShieldCheck className="h-5 w-5 text-[#667085]" />
<Input <Input
@@ -385,6 +623,8 @@ export default function SecurityPage() {
{isDialogSaving ? 'Сохраняем...' : 'Сохранить'} {isDialogSaving ? 'Сохраняем...' : 'Сохранить'}
</Button> </Button>
</> </>
)}
</>
) : null} ) : null}
</DialogContent> </DialogContent>
</Dialog> </Dialog>

View File

@@ -36,6 +36,14 @@ function shouldShowMessagingField(setting: SystemSetting, settings: SystemSettin
const provider = getSettingValue(settings, 'SMS_PROVIDER'); const provider = getSettingValue(settings, 'SMS_PROVIDER');
if (setting.key === 'SMS_API_KEY') return provider === 'smsru'; if (setting.key === 'SMS_API_KEY') return provider === 'smsru';
if (setting.key === 'SMS_LOGIN' || setting.key === 'SMS_PASSWORD') return provider === 'smsc'; if (setting.key === 'SMS_LOGIN' || setting.key === 'SMS_PASSWORD') return provider === 'smsc';
if (
setting.key === 'SMS_GATEWAY_URL' ||
setting.key === 'SMS_GATEWAY_USERNAME' ||
setting.key === 'SMS_GATEWAY_PASSWORD' ||
setting.key === 'SMS_GATEWAY_MESSAGE_TEMPLATE'
) {
return provider === 'huawei_modem';
}
const emailProvider = getSettingValue(settings, 'EMAIL_PROVIDER'); const emailProvider = getSettingValue(settings, 'EMAIL_PROVIDER');
if (setting.key.startsWith('EMAIL_SMTP_') || setting.key.startsWith('EMAIL_FROM_')) { if (setting.key.startsWith('EMAIL_SMTP_') || setting.key.startsWith('EMAIL_FROM_')) {
@@ -180,7 +188,7 @@ export function MessagingSettingsSection({
<MessagingBlock <MessagingBlock
title="SMS" title="SMS"
description="Отправка OTP-кодов по SMS через sms.ru или smsc.ru." description="Отправка OTP-кодов по SMS через sms.ru, smsc.ru или локальный модем Huawei."
groupKey="messaging-sms" groupKey="messaging-sms"
blockSettings={smsSettings} blockSettings={smsSettings}
allSettings={settings} allSettings={settings}
@@ -222,6 +230,7 @@ export function MessagingSettingsSection({
</p> </p>
<div className="mt-4"> <div className="mt-4">
<PhoneInput <PhoneInput
variant="light"
country={testPhoneCountry} country={testPhoneCountry}
value={testPhone} value={testPhone}
onCountryChange={setTestPhoneCountry} onCountryChange={setTestPhoneCountry}

View File

@@ -51,6 +51,13 @@ export function SettingsFieldRow({ setting, onChange }: SettingsFieldRowProps) {
</option> </option>
))} ))}
</select> </select>
) : type === 'textarea' ? (
<textarea
value={setting.value}
rows={3}
className="min-h-[88px] w-full min-w-[280px] resize-y rounded-xl border border-[#e4e7ec] bg-white px-3 py-2 text-sm outline-none focus:border-[#98a2b3] md:w-[360px]"
onChange={(event) => onChange(event.target.value)}
/>
) : ( ) : (
<> <>
<Input <Input

View File

@@ -75,6 +75,7 @@ export interface PublicUser {
canManageSettings?: boolean; canManageSettings?: boolean;
canViewUsers?: boolean; canViewUsers?: boolean;
canViewUserDocuments?: boolean; canViewUserDocuments?: boolean;
hasPassword?: boolean;
} }
export interface AdminUser { export interface AdminUser {

View File

@@ -1,4 +1,4 @@
export type SystemSettingFieldType = 'text' | 'number' | 'boolean' | 'select'; export type SystemSettingFieldType = 'text' | 'number' | 'boolean' | 'select' | 'textarea';
export interface SystemSettingMeta { export interface SystemSettingMeta {
key: string; key: string;
@@ -78,10 +78,43 @@ export const SYSTEM_SETTING_CATALOG: SystemSettingMeta[] = [
options: [ options: [
{ value: 'smsru', label: 'sms.ru' }, { value: 'smsru', label: 'sms.ru' },
{ value: 'smsc', label: 'smsc.ru' }, { value: 'smsc', label: 'smsc.ru' },
{ value: 'huawei_modem', label: 'Huawei E5573 (локальный шлюз)' },
{ value: 'console', label: 'Только лог (отладка)' } { value: 'console', label: 'Только лог (отладка)' }
], ],
showWhen: { key: 'SMS_ENABLED', equals: 'true' } showWhen: { key: 'SMS_ENABLED', equals: 'true' }
}, },
{
key: 'SMS_GATEWAY_URL',
label: 'URL локального SMS-шлюза',
group: 'messaging',
type: 'text',
hint: 'IP или URL модема Huawei HiLink, например http://192.168.8.1',
showWhen: { key: 'SMS_ENABLED', equals: 'true' }
},
{
key: 'SMS_GATEWAY_USERNAME',
label: 'Логин модема Huawei',
group: 'messaging',
type: 'text',
hint: 'Обычно admin',
showWhen: { key: 'SMS_ENABLED', equals: 'true' }
},
{
key: 'SMS_GATEWAY_PASSWORD',
label: 'Пароль модема Huawei',
group: 'messaging',
type: 'text',
hint: 'Пароль веб-интерфейса модема (требуется для отправки SMS)',
showWhen: { key: 'SMS_ENABLED', equals: 'true' }
},
{
key: 'SMS_GATEWAY_MESSAGE_TEMPLATE',
label: 'Шаблон текста SMS (Huawei)',
group: 'messaging',
type: 'textarea',
hint: 'Теги: {{appname}} — название проекта, {{code}} — OTP-код, {{expiry}} — срок действия в минутах',
showWhen: { key: 'SMS_ENABLED', equals: 'true' }
},
{ key: 'SMS_API_KEY', label: 'API-ключ sms.ru', group: 'messaging', type: 'text', hint: 'api_id из личного кабинета sms.ru', showWhen: { key: 'SMS_ENABLED', equals: 'true' } }, { key: 'SMS_API_KEY', label: 'API-ключ sms.ru', group: 'messaging', type: 'text', hint: 'api_id из личного кабинета sms.ru', showWhen: { key: 'SMS_ENABLED', equals: 'true' } },
{ key: 'SMS_LOGIN', label: 'Логин smsc.ru', group: 'messaging', type: 'text', showWhen: { key: 'SMS_ENABLED', equals: 'true' } }, { key: 'SMS_LOGIN', label: 'Логин smsc.ru', group: 'messaging', type: 'text', showWhen: { key: 'SMS_ENABLED', equals: 'true' } },
{ key: 'SMS_PASSWORD', label: 'Пароль smsc.ru', group: 'messaging', type: 'text', showWhen: { key: 'SMS_ENABLED', equals: 'true' } }, { key: 'SMS_PASSWORD', label: 'Пароль smsc.ru', group: 'messaging', type: 'text', showWhen: { key: 'SMS_ENABLED', equals: 'true' } },

View File

@@ -0,0 +1,36 @@
import grpc from '@grpc/grpc-js';
import protoLoader from '@grpc/proto-loader';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const protoPath = path.resolve(__dirname, '../../../shared/proto/security.proto');
const grpcUrl = process.env.SSO_CORE_GRPC_URL ?? 'localhost:50051';
const target = process.argv[2] ?? '+79591913202';
const packageDefinition = protoLoader.loadSync(protoPath, {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs: [path.resolve(__dirname, '../../../shared/proto')]
});
const proto = grpc.loadPackageDefinition(packageDefinition);
const client = new proto.security.SettingsService(
grpcUrl,
grpc.credentials.createInsecure()
);
client.TestMessagingDelivery(
{ channel: 'sms', target },
(error, response) => {
if (error) {
console.error('gRPC error:', error.message);
process.exit(1);
}
console.log('Response:', response);
process.exit(0);
}
);

View File

@@ -31,6 +31,7 @@ import { NotificationPublisherService } from './infra/notification-publisher.ser
import { MinioService } from './infra/minio.service'; import { MinioService } from './infra/minio.service';
import { LdapClientService } from './infra/ldap-client.service'; import { LdapClientService } from './infra/ldap-client.service';
import { MessagingService } from './infra/messaging.service'; import { MessagingService } from './infra/messaging.service';
import { SmsService } from './infra/sms.service';
import { TotpService } from './domain/totp.service'; import { TotpService } from './domain/totp.service';
@Module({ @Module({
@@ -68,7 +69,8 @@ import { TotpService } from './domain/totp.service';
NotificationPublisherService, NotificationPublisherService,
MinioService, MinioService,
LdapClientService, LdapClientService,
MessagingService MessagingService,
SmsService
] ]
}) })
export class AppModule {} export class AppModule {}

View File

@@ -514,6 +514,34 @@ export class AuthGrpcController {
return this.profile.setPassword(command.userId, command.password); return this.profile.setPassword(command.userId, command.password);
} }
@GrpcMethod('ProfileService', 'SendPasswordVerificationOtp')
sendPasswordVerificationOtp(command: { userId: string; channel: string }) {
return this.profile.sendPasswordVerificationOtp(command.userId, command.channel as 'sms' | 'email');
}
@GrpcMethod('ProfileService', 'ChangePassword')
changePassword(command: {
userId: string;
newPassword: string;
currentPassword?: string;
otpCode?: string;
otpChannel?: string;
totpCode?: string;
}) {
return this.profile.changePassword(command.userId, command.newPassword, command);
}
@GrpcMethod('ProfileService', 'RemovePassword')
removePassword(command: {
userId: string;
currentPassword?: string;
otpCode?: string;
otpChannel?: string;
totpCode?: string;
}) {
return this.profile.removePassword(command.userId, command);
}
@GrpcMethod('ProfileService', 'SoftDeleteProfile') @GrpcMethod('ProfileService', 'SoftDeleteProfile')
softDeleteProfile(command: { userId: string }) { softDeleteProfile(command: { userId: string }) {
return this.profile.softDeleteProfile(command.userId); return this.profile.softDeleteProfile(command.userId);

View File

@@ -716,7 +716,7 @@ export class AuthService {
return this.toPublicUser(user); return this.toPublicUser(user);
} }
async toPublicUser(user: Pick<User, 'id' | 'email' | 'phone' | 'backupEmail' | 'backupPhone' | 'displayName' | 'username' | 'avatarUrl' | 'avatarStorageKey' | 'isSuperAdmin' | 'status'>): Promise<PublicUser> { async toPublicUser(user: Pick<User, 'id' | 'email' | 'phone' | 'backupEmail' | 'backupPhone' | 'displayName' | 'username' | 'avatarUrl' | 'avatarStorageKey' | 'isSuperAdmin' | 'status' | 'passwordHash'>): Promise<PublicUser> {
const access = await this.access.getUserAccess(user.id, user.isSuperAdmin); const access = await this.access.getUserAccess(user.id, user.isSuperAdmin);
return { return {
id: user.id, id: user.id,
@@ -730,6 +730,7 @@ export class AuthService {
hasAvatar: Boolean(user.avatarStorageKey || user.avatarUrl), hasAvatar: Boolean(user.avatarStorageKey || user.avatarUrl),
isSuperAdmin: user.isSuperAdmin, isSuperAdmin: user.isSuperAdmin,
status: user.status, status: user.status,
hasPassword: Boolean(user.passwordHash),
roles: access.roles, roles: access.roles,
permissions: access.permissions, permissions: access.permissions,
canAccessAdmin: access.canAccessAdmin, canAccessAdmin: access.canAccessAdmin,

View File

@@ -48,6 +48,7 @@ export interface PublicUser {
canManageSettings?: boolean; canManageSettings?: boolean;
canViewUsers?: boolean; canViewUsers?: boolean;
canViewUserDocuments?: boolean; canViewUserDocuments?: boolean;
hasPassword?: boolean;
} }
export interface VerifyPinCommand { export interface VerifyPinCommand {

View File

@@ -97,6 +97,8 @@ export class OtpService {
return 'Вход в аккаунт'; return 'Вход в аккаунт';
case 'password-reset': case 'password-reset':
return 'Сброс пароля'; return 'Сброс пароля';
case 'password-change':
return 'Смена пароля';
default: default:
return 'Подтверждение действия'; return 'Подтверждение действия';
} }

View File

@@ -1,10 +1,12 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcryptjs'; import * as bcrypt from 'bcryptjs';
import { SessionStatus, UserStatus } from '../generated/prisma/client'; import { SessionStatus, UserStatus } from '../generated/prisma/client';
import { PrismaService } from '../infra/prisma.service'; import { PrismaService } from '../infra/prisma.service';
import { OtpService } from './otp.service';
import { TotpService } from './totp.service';
@@ -58,11 +60,22 @@ function prefixNullable(userId: string, value: string | null | undefined): strin
interface PasswordVerificationCommand {
currentPassword?: string;
otpCode?: string;
otpChannel?: string;
totpCode?: string;
}
@Injectable() @Injectable()
export class ProfileService { export class ProfileService {
constructor(private readonly prisma: PrismaService) {} constructor(
private readonly prisma: PrismaService,
private readonly otp: OtpService,
private readonly totp: TotpService
) {}
@@ -215,6 +228,20 @@ export class ProfileService {
} }
const existing = await this.prisma.user.findUnique({ where: { id: userId } });
if (!existing) {
throw new NotFoundException('Пользователь не найден');
}
if (existing.passwordHash) {
throw new BadRequestException('Пароль уже установлен. Для смены подтвердите личность.');
}
const user = await this.prisma.user.update({ const user = await this.prisma.user.update({
where: { id: userId }, where: { id: userId },
@@ -227,6 +254,164 @@ export class ProfileService {
} }
async sendPasswordVerificationOtp(userId: string, channel: 'sms' | 'email') {
const user = await this.requireUserWithPassword(userId);
const target = channel === 'sms' ? user.phone ?? user.backupPhone : user.email ?? user.backupEmail;
if (!target) {
throw new BadRequestException(
channel === 'sms' ? 'Не указан телефон для отправки SMS-кода' : 'Не указана почта для отправки кода'
);
}
await this.otp.send({
target,
channel,
purpose: 'password-change',
userId
});
return { sent: true, maskedTarget: this.maskVerificationTarget(target, channel) };
}
async changePassword(userId: string, newPassword: string, verification: PasswordVerificationCommand) {
if (!newPassword || newPassword.length < 8) {
throw new BadRequestException('Новый пароль должен содержать минимум 8 символов');
}
const user = await this.requireUserWithPassword(userId);
await this.assertPasswordVerification(userId, user, verification);
const updated = await this.prisma.user.update({
where: { id: userId },
data: { passwordHash: await bcrypt.hash(newPassword, 12) }
});
return { hasPassword: Boolean(updated.passwordHash) };
}
async removePassword(userId: string, verification: PasswordVerificationCommand) {
const user = await this.requireUserWithPassword(userId);
await this.assertPasswordVerification(userId, user, verification);
await this.prisma.user.update({
where: { id: userId },
data: { passwordHash: null }
});
return { hasPassword: false };
}
private async requireUserWithPassword(userId: string) {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new NotFoundException('Пользователь не найден');
}
if (!user.passwordHash) {
throw new BadRequestException('Пароль не установлен');
}
return user;
}
private async assertPasswordVerification(
userId: string,
user: { passwordHash: string | null; email: string | null; phone: string | null; backupEmail: string | null; backupPhone: string | null },
verification: PasswordVerificationCommand
) {
if (verification.currentPassword?.trim()) {
const matches = await bcrypt.compare(verification.currentPassword.trim(), user.passwordHash!);
if (!matches) {
throw new UnauthorizedException('Неверный текущий пароль');
}
return;
}
if (verification.otpCode?.trim() && verification.otpChannel) {
const channel = verification.otpChannel === 'sms' ? 'sms' : 'email';
const target = channel === 'sms' ? user.phone ?? user.backupPhone : user.email ?? user.backupEmail;
if (!target) {
throw new BadRequestException('Контакт для проверки OTP не найден');
}
await this.otp.verify({ target, code: verification.otpCode.trim(), purpose: 'password-change' });
return;
}
if (verification.totpCode?.trim()) {
const isValid = await this.totp.verifyEnabledCode(userId, verification.totpCode.trim());
if (!isValid) {
throw new UnauthorizedException('Неверный код аутентификатора');
}
return;
}
throw new BadRequestException(
'Подтвердите личность: укажите текущий пароль, код OTP или код из приложения-аутентификатора'
);
}
private maskVerificationTarget(target: string, channel: 'sms' | 'email') {
if (channel === 'email' && target.includes('@')) {
const [name, domain] = target.split('@');
return `${name.slice(0, 1)}***@${domain}`;
}
const digits = target.replace(/\D/g, '');
return `***${digits.slice(-4)}`;
}
async softDeleteProfile(userId: string) { async softDeleteProfile(userId: string) {
@@ -399,7 +584,9 @@ export class ProfileService {
backupPhone: user.backupPhone, backupPhone: user.backupPhone,
birthDate: user.birthDate?.toISOString().slice(0, 10) ?? null birthDate: user.birthDate?.toISOString().slice(0, 10) ?? null,
hasPassword: Boolean(user.passwordHash)
}; };

View File

@@ -47,14 +47,40 @@ export const DEFAULT_SYSTEM_SETTINGS = [
{ key: 'EMAIL_FROM_ADDRESS', value: '', description: 'Адрес отправителя, например noreply@example.com' }, { key: 'EMAIL_FROM_ADDRESS', value: '', description: 'Адрес отправителя, например noreply@example.com' },
{ key: 'EMAIL_FROM_NAME', value: '', description: 'Имя отправителя в письме (пусто = название проекта)' }, { key: 'EMAIL_FROM_NAME', value: '', description: 'Имя отправителя в письме (пусто = название проекта)' },
{ key: 'SMS_ENABLED', value: 'false', description: 'Отправлять OTP-коды по SMS через настроенного провайдера' }, { key: 'SMS_ENABLED', value: 'false', description: 'Отправлять OTP-коды по SMS через настроенного провайдера' },
{ key: 'SMS_PROVIDER', value: 'smsru', description: 'SMS-провайдер: smsru, smsc или console (только лог)' }, { key: 'SMS_PROVIDER', value: 'smsru', description: 'SMS-провайдер: smsru, smsc, huawei_modem или console (только лог)' },
{ key: 'SMS_API_KEY', value: '', description: 'API-ключ sms.ru (api_id)' }, { key: 'SMS_API_KEY', value: '', description: 'API-ключ sms.ru (api_id)' },
{ key: 'SMS_LOGIN', value: '', description: 'Логин smsc.ru' }, { key: 'SMS_LOGIN', value: '', description: 'Логин smsc.ru' },
{ key: 'SMS_PASSWORD', value: '', description: 'Пароль smsc.ru' }, { key: 'SMS_PASSWORD', value: '', description: 'Пароль smsc.ru' },
{ key: 'SMS_SENDER', value: '', description: 'Имя отправителя SMS (если поддерживается провайдером)' } { key: 'SMS_SENDER', value: '', description: 'Имя отправителя SMS (если поддерживается провайдером)' },
{
key: 'SMS_GATEWAY_URL',
value: '',
description: 'URL локального SMS-шлюза Huawei HiLink, например http://192.168.8.1'
},
{
key: 'SMS_GATEWAY_USERNAME',
value: 'admin',
description: 'Логин веб-интерфейса модема Huawei HiLink (обычно admin)'
},
{
key: 'SMS_GATEWAY_PASSWORD',
value: '',
description: 'Пароль веб-интерфейса модема Huawei HiLink'
},
{
key: 'SMS_GATEWAY_MESSAGE_TEMPLATE',
value: '{{appname}}: код {{code}}. Действует {{expiry}} мин.',
description: 'Шаблон текста SMS для Huawei HiLink с тегами {{appname}}, {{code}}, {{expiry}}'
}
] as const; ] as const;
const SECRET_SETTING_KEYS = new Set(['LDAP_BIND_PASSWORD', 'EMAIL_SMTP_PASSWORD', 'SMS_API_KEY', 'SMS_PASSWORD']); const SECRET_SETTING_KEYS = new Set([
'LDAP_BIND_PASSWORD',
'EMAIL_SMTP_PASSWORD',
'SMS_API_KEY',
'SMS_PASSWORD',
'SMS_GATEWAY_PASSWORD'
]);
export const PUBLIC_SETTING_KEYS = [ export const PUBLIC_SETTING_KEYS = [
'PROJECT_NAME', 'PROJECT_NAME',

View File

@@ -1,6 +1,7 @@
import { BadRequestException, Injectable, Logger } from '@nestjs/common'; import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import nodemailer from 'nodemailer'; import nodemailer from 'nodemailer';
import { SettingsService } from '../domain/settings.service'; import { SettingsService } from '../domain/settings.service';
import { SmsService } from './sms.service';
type MessagingChannel = 'email' | 'sms'; type MessagingChannel = 'email' | 'sms';
@@ -15,7 +16,10 @@ interface VerificationPayload {
export class MessagingService { export class MessagingService {
private readonly logger = new Logger(MessagingService.name); private readonly logger = new Logger(MessagingService.name);
constructor(private readonly settings: SettingsService) {} constructor(
private readonly settings: SettingsService,
private readonly smsService: SmsService
) {}
async sendVerificationCode(payload: VerificationPayload): Promise<void> { async sendVerificationCode(payload: VerificationPayload): Promise<void> {
if (payload.channel === 'email') { if (payload.channel === 'email') {
@@ -122,7 +126,10 @@ export class MessagingService {
const projectName = await this.settings.getValue('PROJECT_NAME', 'MVK ID'); const projectName = await this.settings.getValue('PROJECT_NAME', 'MVK ID');
const phone = this.normalizePhone(payload.target); const phone = this.normalizePhone(payload.target);
const text = `${projectName}: код ${payload.code}. Действует ${payload.expiryMinutes} мин.`; const text =
provider === 'huawei_modem'
? await this.buildHuaweiSmsText(projectName, payload.code, payload.expiryMinutes)
: `${projectName}: код ${payload.code}. Действует ${payload.expiryMinutes} мин.`;
if (provider === 'smsru') { if (provider === 'smsru') {
await this.sendViaSmsRu(phone, text); await this.sendViaSmsRu(phone, text);
@@ -134,6 +141,14 @@ export class MessagingService {
return; return;
} }
if (provider === 'huawei_modem') {
const sent = await this.smsService.sendOtp(phone, text);
if (!sent) {
throw new BadRequestException('Не удалось отправить SMS через локальный шлюз Huawei');
}
return;
}
throw new BadRequestException(`Неизвестный SMS-провайдер: ${provider}`); throw new BadRequestException(`Неизвестный SMS-провайдер: ${provider}`);
} }
@@ -189,6 +204,31 @@ export class MessagingService {
} }
} }
private async buildHuaweiSmsText(projectName: string, code: string, expiryMinutes: number) {
const template = (await this.settings.getValue('SMS_GATEWAY_MESSAGE_TEMPLATE', '')).trim();
const fallback = `${projectName}: код ${code}. Действует ${expiryMinutes} мин.`;
if (!template) {
return fallback;
}
const rendered = this.applySmsTemplate(template, {
appname: projectName,
code,
expiry: String(expiryMinutes),
expiryminutes: String(expiryMinutes)
});
return rendered.trim() || fallback;
}
private applySmsTemplate(template: string, variables: Record<string, string>) {
return template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (match, rawKey: string) => {
const key = rawKey.toLowerCase();
return variables[key] ?? match;
});
}
private normalizePhone(value: string) { private normalizePhone(value: string) {
const digits = value.replace(/\D/g, ''); const digits = value.replace(/\D/g, '');
if (digits.length === 11 && digits.startsWith('8')) return `7${digits.slice(1)}`; if (digits.length === 11 && digits.startsWith('8')) return `7${digits.slice(1)}`;

View File

@@ -0,0 +1,573 @@
import { createHash } from 'node:crypto';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SettingsService } from '../domain/settings.service';
interface ModemSessionTokens {
sesInfo: string;
tokInfo: string;
}
interface ModemCredentials {
username: string;
password: string;
}
@Injectable()
export class SmsService {
private readonly logger = new Logger(SmsService.name);
private readonly requestTimeoutMs = 15_000;
private readonly logTokenChunkSize = 60;
constructor(
private readonly settings: SettingsService,
private readonly config: ConfigService
) {}
async sendOtp(phoneNumber: string, messageText: string): Promise<boolean> {
let modemUrl = '';
try {
modemUrl = await this.resolveModemUrl();
const tokens = await this.fetchSessionTokens(modemUrl);
await this.postSms(modemUrl, tokens, phoneNumber, messageText);
this.logger.log(`SMS отправлено через Huawei HiLink на ${this.maskPhone(phoneNumber)}`);
return true;
} catch (error) {
const message = this.formatError(error, modemUrl);
this.logger.error(`Не удалось отправить SMS через Huawei HiLink: ${message}`);
return false;
}
}
private async resolveModemUrl(): Promise<string> {
const fromDb = (await this.settings.getValue('SMS_GATEWAY_URL', '')).trim();
if (fromDb) {
return this.normalizeModemUrl(fromDb);
}
const fromEnv = (this.config.get<string>('HUAWEI_MODEM_URL') ?? '').trim();
if (fromEnv) {
return this.normalizeModemUrl(fromEnv);
}
return 'http://192.168.8.1';
}
private async resolveModemCredentials(): Promise<ModemCredentials> {
const usernameFromDb = (await this.settings.getValue('SMS_GATEWAY_USERNAME', '')).trim();
const passwordFromDb = (await this.settings.getValue('SMS_GATEWAY_PASSWORD', '')).trim();
const username =
usernameFromDb ||
(this.config.get<string>('HUAWEI_MODEM_USERNAME') ?? '').trim() ||
'admin';
const password =
passwordFromDb || (this.config.get<string>('HUAWEI_MODEM_PASSWORD') ?? '').trim();
return { username, password };
}
private normalizeModemUrl(value: string): string {
const trimmed = value.trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(trimmed)) {
return `http://${trimmed}`;
}
return trimmed;
}
private async fetchSessionTokens(modemUrl: string): Promise<ModemSessionTokens> {
const initial = await this.requestSesTokInfo(modemUrl);
let sessionCookie = initial.sesInfo;
this.logDebugBlock('SesTokInfo (initial) Cookie / SesInfo', sessionCookie);
this.logDebugBlock('SesTokInfo (initial) TokInfo', initial.tokInfo);
const loginState = await this.resolveModemLoginState(modemUrl, sessionCookie);
if (loginState.required) {
const credentials = await this.resolveModemCredentials();
if (!credentials.password) {
throw new Error(
'Модем Huawei требует авторизацию (код 100003). Укажите SMS_GATEWAY_USERNAME и SMS_GATEWAY_PASSWORD в настройках SMS или переменные HUAWEI_MODEM_USERNAME / HUAWEI_MODEM_PASSWORD'
);
}
this.logger.debug(
`Huawei HiLink: выполняется вход под пользователем ${credentials.username}`
);
const loggedIn = await this.loginToModem(
modemUrl,
sessionCookie,
initial.tokInfo,
credentials,
loginState.passwordType
);
sessionCookie = loggedIn.sesInfo;
this.logDebugBlock('Huawei login: новый Cookie / SesInfo', sessionCookie);
this.logDebugBlock('Huawei login: __RequestVerificationToken', loggedIn.tokInfo);
}
const refreshed = await this.requestSesTokInfo(modemUrl, sessionCookie);
this.logDebugBlock('SesTokInfo (refreshed) Cookie / SesInfo', refreshed.sesInfo);
this.logDebugBlock('SesTokInfo (refreshed) TokInfo for POST', refreshed.tokInfo);
return {
sesInfo: refreshed.sesInfo,
tokInfo: refreshed.tokInfo
};
}
private async resolveModemLoginState(
modemUrl: string,
sessionCookie: string
): Promise<{ required: boolean; passwordType: string }> {
const loginDisabled = await this.isModemLoginDisabled(modemUrl, sessionCookie);
if (loginDisabled) {
return { required: false, passwordType: '4' };
}
const { loggedIn, passwordType } = await this.fetchLoginState(modemUrl, sessionCookie);
return { required: !loggedIn, passwordType };
}
private async isModemLoginDisabled(modemUrl: string, sessionCookie: string): Promise<boolean> {
try {
const response = await this.fetchWithTimeout(`${modemUrl}/config/global/config.xml`, {
method: 'GET',
headers: {
Cookie: sessionCookie,
Accept: '*/*',
'X-Requested-With': 'XMLHttpRequest'
}
});
if (!response.ok) {
return false;
}
const configXml = await response.text();
const loginFlag = this.extractXmlValue(configXml, 'login');
return loginFlag === '0';
} catch {
return false;
}
}
private async fetchLoginState(
modemUrl: string,
sessionCookie: string
): Promise<{ loggedIn: boolean; passwordType: string; state: string | null }> {
const response = await this.fetchWithTimeout(`${modemUrl}/api/user/state-login`, {
method: 'GET',
headers: {
Cookie: sessionCookie,
Accept: '*/*',
'X-Requested-With': 'XMLHttpRequest'
}
});
if (!response.ok) {
throw new Error(`state-login HTTP ${response.status}`);
}
const xml = await response.text();
this.logger.debug(`state-login raw XML:\n${this.formatMultilineForLog(xml, 120, false)}`);
const state = this.extractXmlValue(xml, 'State');
const passwordType = this.extractXmlValue(xml, 'password_type') ?? '4';
const loggedIn = state === '0';
this.logger.debug(
`state-login: State=${state ?? 'unknown'}, loggedIn=${loggedIn}, password_type=${passwordType}`
);
return { loggedIn, passwordType, state };
}
private async loginToModem(
modemUrl: string,
sessionCookie: string,
verificationToken: string,
credentials: ModemCredentials,
passwordType: string
): Promise<ModemSessionTokens> {
const encodedPassword = this.encodeHuaweiPassword(
credentials.username,
credentials.password,
verificationToken
);
const body = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<request>',
` <Username>${this.escapeXml(credentials.username)}</Username>`,
` <Password>${encodedPassword}</Password>`,
` <password_type>${this.escapeXml(passwordType)}</password_type>`,
'</request>'
].join('\n');
this.logDebugBlock('Huawei login POST Cookie', sessionCookie);
this.logDebugBlock('Huawei login POST __RequestVerificationToken', verificationToken);
console.log('[SmsService] Huawei login POST body:\n' + body);
const response = await this.fetchWithTimeout(`${modemUrl}/api/user/login`, {
method: 'POST',
headers: {
Cookie: sessionCookie,
__RequestVerificationToken: verificationToken,
'Content-Type': 'text/xml; charset=UTF-8',
Accept: '*/*',
'X-Requested-With': 'XMLHttpRequest',
Origin: modemUrl,
Referer: `${modemUrl}/html/index.html`
},
body
});
const responseText = await response.text();
this.logger.debug(`login response:\n${this.formatMultilineForLog(responseText, 120, false)}`);
const errorCode = this.extractXmlValue(responseText, 'code');
if (errorCode && errorCode !== '0') {
const errorMessage = this.extractXmlValue(responseText, 'message');
throw new Error(
errorMessage?.trim() || `login: код ошибки модема ${errorCode}`
);
}
if (!/OK/i.test(responseText) && !response.ok) {
throw new Error(`login HTTP ${response.status}: ${responseText.slice(0, 200).trim() || 'пустой ответ'}`);
}
const newCookie =
this.extractSessionCookieFromHeaders(response) ??
this.normalizeSesInfoCookie(this.extractXmlValue(responseText, 'SesInfo') ?? sessionCookie);
const newToken =
this.extractVerificationTokenFromHeaders(response) ?? verificationToken;
return {
sesInfo: newCookie,
tokInfo: newToken
};
}
private encodeHuaweiPassword(username: string, rawPassword: string, token: string): string {
const sha256Hex = (value: string) =>
createHash('sha256').update(value, 'utf8').digest('hex');
const passwordHashB64 = Buffer.from(sha256Hex(rawPassword), 'utf8').toString('base64');
const combined = username + passwordHashB64 + token;
return Buffer.from(sha256Hex(combined), 'utf8').toString('base64');
}
private async requestSesTokInfo(modemUrl: string, sessionCookie?: string): Promise<ModemSessionTokens> {
const headers: Record<string, string> = {
Accept: '*/*',
'X-Requested-With': 'XMLHttpRequest'
};
if (sessionCookie) {
headers.Cookie = sessionCookie;
}
const response = await this.fetchWithTimeout(`${modemUrl}/api/webserver/SesTokInfo`, {
method: 'GET',
headers
});
if (!response.ok) {
throw new Error(`SesTokInfo HTTP ${response.status}`);
}
const xml = await response.text();
this.logger.debug(

View File

@@ -184,6 +184,7 @@ message PublicUser {
bool canManageSettings = 18; bool canManageSettings = 18;
bool canViewUsers = 19; bool canViewUsers = 19;
bool canViewUserDocuments = 20; bool canViewUserDocuments = 20;
bool hasPassword = 21;
} }
message AuthTokens { message AuthTokens {

View File

@@ -8,6 +8,9 @@ service ProfileService {
rpc UpdateProfile (UpdateProfileRequest) returns (ProfileResponse); rpc UpdateProfile (UpdateProfileRequest) returns (ProfileResponse);
rpc UpdateContacts (UpdateContactsRequest) returns (ProfileResponse); rpc UpdateContacts (UpdateContactsRequest) returns (ProfileResponse);
rpc SetPassword (SetPasswordRequest) returns (SetPasswordResponse); rpc SetPassword (SetPasswordRequest) returns (SetPasswordResponse);
rpc SendPasswordVerificationOtp (SendPasswordVerificationOtpRequest) returns (PasswordVerificationOtpResponse);
rpc ChangePassword (ChangePasswordRequest) returns (SetPasswordResponse);
rpc RemovePassword (RemovePasswordRequest) returns (SetPasswordResponse);
rpc SoftDeleteProfile (UserProfileRequest) returns (SoftDeleteProfileResponse); rpc SoftDeleteProfile (UserProfileRequest) returns (SoftDeleteProfileResponse);
} }
@@ -16,6 +19,33 @@ message SetPasswordRequest {
string password = 2; string password = 2;
} }
message SendPasswordVerificationOtpRequest {
string userId = 1;
string channel = 2;
}
message PasswordVerificationOtpResponse {
bool sent = 1;
string maskedTarget = 2;
}
message ChangePasswordRequest {
string userId = 1;
string newPassword = 2;
optional string currentPassword = 3;
optional string otpCode = 4;
optional string otpChannel = 5;
optional string totpCode = 6;
}
message RemovePasswordRequest {
string userId = 1;
optional string currentPassword = 2;
optional string otpCode = 3;
optional string otpChannel = 4;
optional string totpCode = 5;
}
message SetPasswordResponse { message SetPasswordResponse {
bool hasPassword = 1; bool hasPassword = 1;
} }
@@ -64,6 +94,7 @@ message ProfileResponse {
optional string backupEmail = 12; optional string backupEmail = 12;
optional string backupPhone = 13; optional string backupPhone = 13;
optional string birthDate = 15; optional string birthDate = 15;
bool hasPassword = 16;
} }
message SoftDeleteProfileResponse { message SoftDeleteProfileResponse {