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:
2026-04-07 12:07:13 +03:00
parent 70f016d113
commit 41dbddd2a1
12 changed files with 1478 additions and 22 deletions
+130
View File
@@ -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();
}
}
}