141 lines
6.1 KiB
TypeScript
141 lines
6.1 KiB
TypeScript
import { Body, Controller, ForbiddenException, Get, Headers, Param, Post, Req } from '@nestjs/common';
|
|
import type { Request } from 'express';
|
|
import { firstValueFrom } from 'rxjs';
|
|
import { enrichAuthClientMeta } from '../client-request.util';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
|
|
import { CoreGrpcService } from '../core-grpc.service';
|
|
import { QrSessionDto, WebAuthnDto } from '../dto/identity.dto';
|
|
import { resolveAuthorizedPayload } from '../session-auth';
|
|
import { resolveFrontendUrl } from '../lib/oauth-issuer';
|
|
|
|
@ApiTags('Биометрия и QR-вход')
|
|
@Controller('auth/advanced')
|
|
export class AdvancedAuthController {
|
|
constructor(
|
|
private readonly core: CoreGrpcService,
|
|
private readonly jwt: JwtService
|
|
) {}
|
|
|
|
@Post('webauthn/register/challenge')
|
|
@ApiOperation({ summary: 'Challenge регистрации WebAuthn', description: 'Создает challenge для регистрации лица/отпечатка. Endpoint готов для подключения настоящего WebAuthn attestation.' })
|
|
@ApiBody({ type: WebAuthnDto })
|
|
@ApiResponse({ status: 201, description: 'Challenge создан' })
|
|
webAuthnRegister(@Body() dto: WebAuthnDto) {
|
|
return this.core.advancedAuth.CreateWebAuthnRegistrationChallenge(dto);
|
|
}
|
|
|
|
@Post('webauthn/login/challenge')
|
|
@ApiOperation({ summary: 'Challenge входа WebAuthn', description: 'Создает challenge для входа по лицу или отпечатку.' })
|
|
@ApiBody({ type: WebAuthnDto })
|
|
@ApiResponse({ status: 201, description: 'Challenge создан' })
|
|
webAuthnLogin(@Body() dto: WebAuthnDto) {
|
|
return this.core.advancedAuth.CreateWebAuthnLoginChallenge(dto);
|
|
}
|
|
|
|
@Post('qr/session')
|
|
@ApiOperation({ summary: 'Создать QR-сессию', description: 'Создает временную QR-сессию для входа с другого устройства.' })
|
|
@ApiBody({ type: QrSessionDto })
|
|
@ApiResponse({ status: 201, description: 'QR-сессия создана' })
|
|
createQr(@Body() dto: QrSessionDto, @Req() req: Request) {
|
|
return this.core.advancedAuth.CreateQrSession(
|
|
enrichAuthClientMeta(req, {
|
|
deviceName: dto.deviceName,
|
|
fingerprint: dto.fingerprint,
|
|
deviceType: dto.deviceType ?? 'WEB'
|
|
})
|
|
);
|
|
}
|
|
|
|
@Get('qr/session/:sessionId')
|
|
@ApiOperation({ summary: 'Проверить QR-сессию', description: 'Возвращает текущий статус QR-сессии: PENDING/APPROVED/EXPIRED.' })
|
|
@ApiParam({ name: 'sessionId', description: 'ID QR-сессии' })
|
|
@ApiResponse({ status: 200, description: 'Статус QR-сессии получен' })
|
|
async pollQr(@Param('sessionId') sessionId: string) {
|
|
const response = await firstValueFrom(this.core.advancedAuth.PollQrSession({ sessionId }));
|
|
return this.normalizeQrResponse(response);
|
|
}
|
|
|
|
@Post('qr/session/:sessionId/claim')
|
|
@ApiOperation({
|
|
summary: 'Привязать QR-сессию к устройству',
|
|
description: 'Новое устройство подтверждает сканирование QR-кода для подключения из раздела «Безопасность».'
|
|
})
|
|
@ApiParam({ name: 'sessionId', description: 'ID QR-сессии' })
|
|
@ApiBody({ type: QrSessionDto })
|
|
@ApiResponse({ status: 201, description: 'QR-сессия привязана к устройству' })
|
|
claimQr(@Param('sessionId') sessionId: string, @Body() dto: QrSessionDto, @Req() req: Request) {
|
|
const enriched = enrichAuthClientMeta(req, {
|
|
deviceName: dto.deviceName,
|
|
fingerprint: dto.fingerprint,
|
|
deviceType: dto.deviceType ?? 'WEB'
|
|
});
|
|
return this.core.advancedAuth.ClaimQrSession({
|
|
sessionId,
|
|
deviceName: enriched.deviceName,
|
|
fingerprint: enriched.fingerprint,
|
|
deviceType: enriched.deviceType,
|
|
ipAddress: enriched.ipAddress,
|
|
userAgent: enriched.userAgent
|
|
});
|
|
}
|
|
|
|
@Post('qr/session/:sessionId/approve')
|
|
@ApiBearerAuth()
|
|
@ApiOperation({ summary: 'Подтвердить QR-вход', description: 'Подтверждает QR-сессию с мобильного приложения уже авторизованным пользователем.' })
|
|
@ApiParam({ name: 'sessionId', description: 'ID QR-сессии' })
|
|
@ApiResponse({ status: 201, description: 'QR-сессия подтверждена' })
|
|
async approveQr(@Param('sessionId') sessionId: string, @Headers('authorization') authorization?: string) {
|
|
const payload = await resolveAuthorizedPayload(this.jwt, this.core, authorization);
|
|
const response = await firstValueFrom(this.core.advancedAuth.ApproveQrSession({ sessionId, userId: payload.sub }));
|
|
return this.normalizeQrResponse(response);
|
|
}
|
|
|
|
private normalizeQrResponse(response: unknown) {
|
|
const value = response as {
|
|
sessionId?: string;
|
|
status?: string;
|
|
expiresAt?: string;
|
|
qrPayload?: string;
|
|
claimed?: boolean;
|
|
claimedDeviceName?: string;
|
|
accessToken?: string;
|
|
refreshToken?: string;
|
|
authSessionId?: string;
|
|
pinVerified?: boolean;
|
|
auth?: {
|
|
accessToken?: string;
|
|
refreshToken?: string;
|
|
sessionId?: string;
|
|
pinVerified?: boolean;
|
|
expiresAt?: string;
|
|
user?: unknown;
|
|
};
|
|
};
|
|
const auth = value.auth;
|
|
|
|
return {
|
|
sessionId: value.sessionId,
|
|
status: value.status,
|
|
expiresAt: value.expiresAt,
|
|
qrPayload: value.qrPayload,
|
|
claimed: value.claimed,
|
|
claimedDeviceName: value.claimedDeviceName,
|
|
accessToken: value.accessToken ?? auth?.accessToken,
|
|
refreshToken: value.refreshToken ?? auth?.refreshToken,
|
|
authSessionId: value.authSessionId ?? auth?.sessionId,
|
|
pinVerified: value.pinVerified ?? auth?.pinVerified,
|
|
auth: auth
|
|
? {
|
|
accessToken: auth.accessToken,
|
|
refreshToken: auth.refreshToken,
|
|
sessionId: auth.sessionId,
|
|
pinVerified: auth.pinVerified,
|
|
expiresAt: auth.expiresAt,
|
|
user: auth.user
|
|
}
|
|
: undefined
|
|
};
|
|
}
|
|
}
|