fix and update
This commit is contained in:
@@ -1,13 +1,15 @@
|
||||
import { Body, Controller, Get, Headers, Ip, Post } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Headers, Ip, Post, UseInterceptors } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiBearerAuth, ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { BeginTotpLoginDto, IdentifyDto, LdapLoginDto, LoginDto, PasswordlessOtpDto, PasswordlessVerifyDto, PasswordLoginDto, RefreshSessionDto, RegisterDto, VerifyPinDto, VerifyTotpLoginDto } from '../dto/auth.dto';
|
||||
import { resolveAuthorizedPayload, verifyAccessToken } from '../session-auth';
|
||||
import { FedcmCookieInterceptor } from '../interceptors/fedcm-cookie.interceptor';
|
||||
|
||||
@ApiTags('Аутентификация')
|
||||
@Controller('auth')
|
||||
@UseInterceptors(FedcmCookieInterceptor)
|
||||
export class AuthController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
|
||||
192
apps/api-gateway/src/controllers/fedcm.controller.ts
Normal file
192
apps/api-gateway/src/controllers/fedcm.controller.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
Options,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UnauthorizedException
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import type { Request, Response } from 'express';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { applyFedcmCorsHeaders, applyFedcmPreflightHeaders } from '../lib/fedcm-cors';
|
||||
import { resolveFedcmSessionFromRequest, setFedcmSessionCookie } from '../lib/fedcm-cookie';
|
||||
import { resolveFrontendUrl, resolveOAuthIssuer } from '../lib/oauth-issuer';
|
||||
import { assertSessionUnlocked, verifyAccessToken } from '../session-auth';
|
||||
|
||||
type FedcmAccountsResponse = {
|
||||
accounts: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
given_name?: string;
|
||||
email?: string;
|
||||
picture?: string;
|
||||
approved_clients?: string[];
|
||||
}>;
|
||||
};
|
||||
|
||||
@ApiTags('FedCM')
|
||||
@Controller('fedcm')
|
||||
export class FedcmController {
|
||||
constructor(
|
||||
private readonly core: CoreGrpcService,
|
||||
private readonly jwt: JwtService
|
||||
) {}
|
||||
|
||||
@Options('accounts')
|
||||
@HttpCode(204)
|
||||
accountsPreflight(@Headers('origin') origin: string | undefined, @Res({ passthrough: true }) res: Response) {
|
||||
applyFedcmPreflightHeaders(res, origin);
|
||||
}
|
||||
|
||||
@Options('id_assertion')
|
||||
@HttpCode(204)
|
||||
idAssertionPreflight(@Headers('origin') origin: string | undefined, @Res({ passthrough: true }) res: Response) {
|
||||
applyFedcmPreflightHeaders(res, origin);
|
||||
}
|
||||
|
||||
@Options('client_metadata')
|
||||
@HttpCode(204)
|
||||
clientMetadataPreflight(@Headers('origin') origin: string | undefined, @Res({ passthrough: true }) res: Response) {
|
||||
applyFedcmPreflightHeaders(res, origin);
|
||||
}
|
||||
|
||||
@Get('config.json')
|
||||
@ApiOperation({ summary: 'FedCM provider config', description: 'Конфигурация Identity Provider для Federated Credential Management API.' })
|
||||
async config(@Res({ passthrough: true }) res: Response) {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.setHeader('Cache-Control', 'public, max-age=300');
|
||||
|
||||
const issuer = await resolveOAuthIssuer(this.core);
|
||||
const frontendUrl = await resolveFrontendUrl(this.core);
|
||||
let projectName = 'MVK ID';
|
||||
|
||||
try {
|
||||
const setting = (await firstValueFrom(this.core.settings.GetSetting({ key: 'PROJECT_NAME' }))) as { value?: string };
|
||||
if (setting.value?.trim()) {
|
||||
projectName = setting.value.trim();
|
||||
}
|
||||
} catch {
|
||||
// fallback
|
||||
}
|
||||
|
||||
return {
|
||||
accounts_endpoint: `${issuer}/fedcm/accounts`,
|
||||
client_metadata_endpoint: `${issuer}/fedcm/client_metadata`,
|
||||
id_assertion_endpoint: `${issuer}/fedcm/id_assertion`,
|
||||
login_url: `${frontendUrl}/auth/login`,
|
||||
signup_url: `${frontendUrl}/auth/register`,
|
||||
branding: {
|
||||
background_color: '#ffffff',
|
||||
color: '#3390ec',
|
||||
icons: [{ url: `${frontendUrl}/favicon.ico`, size: 32 }]
|
||||
},
|
||||
accounts: {
|
||||
include_anonymous: false
|
||||
},
|
||||
fields: ['name', 'email', 'picture'],
|
||||
display: projectName
|
||||
};
|
||||
}
|
||||
|
||||
@Get('accounts')
|
||||
@ApiOperation({ summary: 'FedCM accounts', description: 'Возвращает аккаунты пользователя по FedCM-сессии (cookie).' })
|
||||
async accounts(
|
||||
@Req() req: Request,
|
||||
@Headers('origin') origin: string | undefined,
|
||||
@Res({ passthrough: true }) res: Response
|
||||
): Promise<FedcmAccountsResponse> {
|
||||
applyFedcmCorsHeaders(res, origin);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
const session = await resolveFedcmSessionFromRequest(this.jwt, req.headers.cookie);
|
||||
if (!session) {
|
||||
return { accounts: [] };
|
||||
}
|
||||
|
||||
const result = (await firstValueFrom(
|
||||
this.core.fedcm.GetAccounts({ userId: session.sub, sessionId: session.sessionId })
|
||||
)) as FedcmAccountsResponse;
|
||||
|
||||
return result ?? { accounts: [] };
|
||||
}
|
||||
|
||||
@Get('client_metadata')
|
||||
@ApiOperation({ summary: 'FedCM client metadata', description: 'Метаданные клиента для UI FedCM.' })
|
||||
async clientMetadata(
|
||||
@Query('client_id') clientId: string | undefined,
|
||||
@Headers('origin') origin: string | undefined,
|
||||
@Res({ passthrough: true }) res: Response
|
||||
) {
|
||||
applyFedcmCorsHeaders(res, origin);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
if (!clientId?.trim()) {
|
||||
throw new UnauthorizedException('Передайте client_id');
|
||||
}
|
||||
|
||||
return firstValueFrom(this.core.fedcm.GetClientMetadata({ clientId: clientId.trim() }));
|
||||
}
|
||||
|
||||
@Post('id_assertion')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({ summary: 'FedCM id assertion', description: 'Выдаёт OIDC id_token для выбранного аккаунта и OAuth-клиента.' })
|
||||
async idAssertion(
|
||||
@Req() req: Request,
|
||||
@Headers('origin') origin: string | undefined,
|
||||
@Res({ passthrough: true }) res: Response
|
||||
) {
|
||||
applyFedcmCorsHeaders(res, origin);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
const session = await resolveFedcmSessionFromRequest(this.jwt, req.headers.cookie);
|
||||
if (!session) {
|
||||
throw new UnauthorizedException('Сессия FedCM не найдена');
|
||||
}
|
||||
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
const clientId = String(body.client_id ?? body.clientId ?? '').trim();
|
||||
const accountId = String(body.account_id ?? body.accountId ?? '').trim();
|
||||
if (!clientId || !accountId) {
|
||||
throw new UnauthorizedException('Передайте client_id и account_id');
|
||||
}
|
||||
|
||||
return firstValueFrom(
|
||||
this.core.fedcm.IssueIdAssertion({
|
||||
userId: session.sub,
|
||||
sessionId: session.sessionId,
|
||||
clientId,
|
||||
accountId
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@Post('session/sync')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({
|
||||
summary: 'Синхронизировать FedCM cookie',
|
||||
description: 'Устанавливает HttpOnly cookie для FedCM по Bearer access token (для уже авторизованных пользователей IdP).'
|
||||
})
|
||||
async syncSession(
|
||||
@Headers('authorization') authorization: string | undefined,
|
||||
@Res({ passthrough: true }) res: Response
|
||||
) {
|
||||
const payload = await verifyAccessToken(this.jwt, authorization);
|
||||
if (!payload.sessionId) {
|
||||
throw new UnauthorizedException('Сессия не найдена');
|
||||
}
|
||||
await assertSessionUnlocked(this.core, payload);
|
||||
await setFedcmSessionCookie(res, this.jwt, {
|
||||
sub: payload.sub,
|
||||
sessionId: payload.sessionId,
|
||||
pinVerified: true
|
||||
});
|
||||
return { synced: true };
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { Controller, Get, Res } from '@nestjs/common';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import type { Response } from 'express';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CoreGrpcService } from '../core-grpc.service';
|
||||
import { buildOpenIdConfiguration, resolveOAuthIssuer } from '../lib/oauth-issuer';
|
||||
|
||||
@@ -8,6 +10,20 @@ import { buildOpenIdConfiguration, resolveOAuthIssuer } from '../lib/oauth-issue
|
||||
export class WellKnownController {
|
||||
constructor(private readonly core: CoreGrpcService) {}
|
||||
|
||||
@Get('web-identity')
|
||||
@ApiOperation({
|
||||
summary: 'FedCM web identity manifest',
|
||||
description: 'Манифест Federated Credential Management API, указывающий на конфигурацию провайдера.'
|
||||
})
|
||||
async webIdentity(@Res({ passthrough: true }) res: Response) {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.setHeader('Cache-Control', 'public, max-age=300');
|
||||
const issuer = await resolveOAuthIssuer(this.core);
|
||||
return {
|
||||
provider_urls: [`${issuer}/fedcm/config.json`]
|
||||
};
|
||||
}
|
||||
|
||||
@Get('openid-configuration')
|
||||
@ApiOperation({
|
||||
summary: 'OpenID Connect Discovery',
|
||||
|
||||
Reference in New Issue
Block a user