feat(auth): add POST /login with Playwright automation and SQLite session storage
- automates file-key login on the ID portal using Playwright/Chromium - captures token, cookies, and localStorage after successful redirect - stores session data in SQLite via TypeORM (better-sqlite3) - sessions are keyed by sessionName (auto-generated UUID if not provided) - login URL, cabinet redirect URL, keys dir, and DB path are all configurable via env
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller()
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: 'Log in using a file key and return the session token' })
|
||||
@ApiResponse({ status: 201, description: 'Login successful', schema: { properties: { token: { type: 'string' }, sessionName: { type: 'string' } } } })
|
||||
@ApiResponse({ status: 400, description: 'Key not found or invalid' })
|
||||
@ApiResponse({ status: 500, description: 'Automation failed' })
|
||||
login(@Body() dto: LoginDto): Promise<{ token: string; sessionName: string }> {
|
||||
return this.authService.login(dto.key, dto.sessionName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SessionModule } from '../session/session.module';
|
||||
|
||||
@Module({
|
||||
imports: [SessionModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { chromium } from 'playwright';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as crypto from 'crypto';
|
||||
import { SessionService } from '../session/session.service';
|
||||
|
||||
interface KeyDescriptor {
|
||||
keyFile: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
private readonly keysDir: string;
|
||||
private readonly loginUrl: string;
|
||||
private readonly cabinetUrl: string;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly sessionService: SessionService,
|
||||
) {
|
||||
this.keysDir = path.resolve(
|
||||
this.config.get<string>('KEYS_DIR', 'keys'),
|
||||
);
|
||||
this.loginUrl = this.config.get<string>(
|
||||
'ID_LOGIN_URL',
|
||||
'https://id-liquio-diia-stg.kitsoft.ua/',
|
||||
);
|
||||
this.cabinetUrl = this.config.get<string>(
|
||||
'CABINET_URL',
|
||||
'https://cabinet-liquio-diia-stg.kitsoft.ua/messages',
|
||||
);
|
||||
}
|
||||
|
||||
async login(keyId: string, sessionName?: string): Promise<{ token: string; sessionName: string }> {
|
||||
const resolvedSession = sessionName ?? crypto.randomUUID();
|
||||
|
||||
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
|
||||
|
||||
if (!fs.existsSync(keyJsonPath)) {
|
||||
throw new BadRequestException(`Key not found: ${keyId}`);
|
||||
}
|
||||
|
||||
let descriptor: KeyDescriptor;
|
||||
try {
|
||||
descriptor = JSON.parse(fs.readFileSync(keyJsonPath, 'utf-8'));
|
||||
} catch {
|
||||
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`);
|
||||
}
|
||||
|
||||
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
|
||||
if (!fs.existsSync(keyFilePath)) {
|
||||
throw new BadRequestException(`Key file not found: ${descriptor.keyFile}`);
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
this.logger.log(`Navigating to ${this.loginUrl}`);
|
||||
await page.goto(this.loginUrl, { waitUntil: 'networkidle' });
|
||||
|
||||
// Click "Файловий ключ" button
|
||||
await page.getByText('Файловий ключ').click();
|
||||
|
||||
// Upload key file via hidden file input
|
||||
const fileInput = page.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]');
|
||||
await fileInput.setInputFiles(keyFilePath);
|
||||
|
||||
// Enter password
|
||||
await page
|
||||
.locator('#id-app-login-file-key-password')
|
||||
.fill(descriptor.password);
|
||||
|
||||
// Click "Продовжити"
|
||||
await page.locator('#id-app-login-file-key-sign-button').click();
|
||||
|
||||
// Wait until redirected to cabinet
|
||||
this.logger.log(`Waiting for redirect to ${this.cabinetUrl}`);
|
||||
await page.waitForURL(this.cabinetUrl, { timeout: 30000 });
|
||||
|
||||
// Extract token from localStorage
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'));
|
||||
|
||||
if (!token) {
|
||||
throw new InternalServerErrorException(
|
||||
'Login succeeded but token was not found in localStorage',
|
||||
);
|
||||
}
|
||||
|
||||
// Capture all cookies and localStorage from the browser context
|
||||
const cookies = await context.cookies();
|
||||
const localStorageData = await page.evaluate(() => {
|
||||
const entries: Record<string, string> = {};
|
||||
for (let i = 0; i < window.localStorage.length; i++) {
|
||||
const k = window.localStorage.key(i);
|
||||
if (k !== null) entries[k] = window.localStorage.getItem(k) ?? '';
|
||||
}
|
||||
return entries;
|
||||
});
|
||||
|
||||
await this.sessionService.upsert(resolvedSession, token, cookies, localStorageData);
|
||||
|
||||
this.logger.log(`Login successful for key ${keyId}, session: ${resolvedSession}`);
|
||||
return { token, sessionName: resolvedSession };
|
||||
} catch (err) {
|
||||
if (
|
||||
err instanceof BadRequestException ||
|
||||
err instanceof InternalServerErrorException
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
this.logger.error(`Login failed: ${(err as Error).message}`);
|
||||
throw new InternalServerErrorException(
|
||||
`Login automation failed: ${(err as Error).message}`,
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({
|
||||
description: 'Key identifier — filename (without extension) from the keys/ directory',
|
||||
example: '3273334361',
|
||||
})
|
||||
@IsString()
|
||||
key: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Session name to store credentials under. Auto-generated UUID if omitted.',
|
||||
example: 'my-test-session',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sessionName?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user