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:
@@ -2,3 +2,13 @@ NODE_ENV=development
|
|||||||
PORT=3000
|
PORT=3000
|
||||||
APP_NAME=liquio-qa-bot
|
APP_NAME=liquio-qa-bot
|
||||||
APP_VERSION=1.0.0
|
APP_VERSION=1.0.0
|
||||||
|
|
||||||
|
# Directory (relative to cwd) containing *.json key descriptors
|
||||||
|
KEYS_DIR=keys
|
||||||
|
|
||||||
|
# SQLite database path
|
||||||
|
DB_PATH=data/sessions.db
|
||||||
|
|
||||||
|
# Login automation targets
|
||||||
|
ID_LOGIN_URL=https://id-liquio-diia-stg.kitsoft.ua/
|
||||||
|
CABINET_URL=https://cabinet-liquio-diia-stg.kitsoft.ua/messages
|
||||||
|
|||||||
Binary file not shown.
Generated
+1184
-20
File diff suppressed because it is too large
Load Diff
+6
-1
@@ -18,14 +18,19 @@
|
|||||||
"@nestjs/core": "^11.1.18",
|
"@nestjs/core": "^11.1.18",
|
||||||
"@nestjs/platform-express": "^11.1.18",
|
"@nestjs/platform-express": "^11.1.18",
|
||||||
"@nestjs/swagger": "^11.2.6",
|
"@nestjs/swagger": "^11.2.6",
|
||||||
|
"@nestjs/typeorm": "^11.0.1",
|
||||||
|
"better-sqlite3": "^12.8.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.4",
|
"class-validator": "^0.14.4",
|
||||||
|
"playwright": "^1.59.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"swagger-ui-express": "^5.0.1"
|
"swagger-ui-express": "^5.0.1",
|
||||||
|
"typeorm": "^0.3.28"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^11.0.17",
|
"@nestjs/cli": "^11.0.17",
|
||||||
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
"@types/node": "^25.5.2",
|
"@types/node": "^25.5.2",
|
||||||
"typescript": "^6.0.2"
|
"typescript": "^6.0.2"
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-1
@@ -1,6 +1,9 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { HealthController } from './health/health.controller';
|
import { HealthController } from './health/health.controller';
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { SessionEntity } from './session/session.entity';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -8,6 +11,16 @@ import { HealthController } from './health/health.controller';
|
|||||||
isGlobal: true,
|
isGlobal: true,
|
||||||
envFilePath: '.env',
|
envFilePath: '.env',
|
||||||
}),
|
}),
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
type: 'better-sqlite3',
|
||||||
|
database: config.get<string>('DB_PATH', 'data/sessions.db'),
|
||||||
|
entities: [SessionEntity],
|
||||||
|
synchronize: true,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
AuthModule,
|
||||||
],
|
],
|
||||||
controllers: [HealthController],
|
controllers: [HealthController],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import {
|
||||||
|
Entity,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('sessions')
|
||||||
|
export class SessionEntity {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Column({ unique: true })
|
||||||
|
sessionName: string;
|
||||||
|
|
||||||
|
@Column('text')
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@Column('text')
|
||||||
|
cookies: string; // JSON-serialised Cookie[] from Playwright
|
||||||
|
|
||||||
|
@Column('text')
|
||||||
|
localStorage: string; // JSON-serialised Record<string, string> from Playwright
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { SessionEntity } from './session.entity';
|
||||||
|
import { SessionService } from './session.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([SessionEntity])],
|
||||||
|
providers: [SessionService],
|
||||||
|
exports: [SessionService],
|
||||||
|
})
|
||||||
|
export class SessionModule {}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { SessionEntity } from './session.entity';
|
||||||
|
import type { Cookie } from 'playwright';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SessionService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(SessionEntity)
|
||||||
|
private readonly repo: Repository<SessionEntity>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async upsert(
|
||||||
|
sessionName: string,
|
||||||
|
token: string,
|
||||||
|
cookies: Cookie[],
|
||||||
|
localStorage: Record<string, string>,
|
||||||
|
): Promise<SessionEntity> {
|
||||||
|
const existing = await this.repo.findOneBy({ sessionName });
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
existing.token = token;
|
||||||
|
existing.cookies = JSON.stringify(cookies);
|
||||||
|
existing.localStorage = JSON.stringify(localStorage);
|
||||||
|
return this.repo.save(existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.repo.save(
|
||||||
|
this.repo.create({
|
||||||
|
sessionName,
|
||||||
|
token,
|
||||||
|
cookies: JSON.stringify(cookies),
|
||||||
|
localStorage: JSON.stringify(localStorage),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
findBySessionName(sessionName: string): Promise<SessionEntity | null> {
|
||||||
|
return this.repo.findOneBy({ sessionName });
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user