feat(scenario): run logs, lint/format tooling, CONTRIBUTING

- add ScenarioRunLogEntity to persist step script output to DB
- stepLogger dual-writes to NestJS logger and DB (fire-and-forget)
- add GET /scenarios/:id/run/:runId returning run, stepRuns and logs
- add POST /scenarios/:id/run/:runId/wait (polls until terminal state)
- 9 new integration tests for the two endpoints (136 total)
- add eslint with typescript-eslint and eslint-config-prettier
- add npm scripts: format, lint, lint:fix
- resolve all lint errors across src and test (no any types)
- add CONTRIBUTING.md covering dev workflow
This commit is contained in:
ars9 committed 2026-04-08 18:10:42 +03:00
1 parent b0c02a1cdc
commit 9a9ccbfe37
67 files changed
+3809 -1412

No files matched your search

+93 -45
View File
@@ -3,16 +3,16 @@ import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { TraceLogger } from '../common/trace-logger';
import { ConfigService } from '@nestjs/config';
import { chromium } from 'playwright';
import type { Page } from 'playwright';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import { SessionService } from '../session/session.service';
import { EnvironmentService } from '../environment/environment.service';
} from "@nestjs/common";
import { TraceLogger } from "../common/trace-logger";
import { ConfigService } from "@nestjs/config";
import { chromium } from "playwright";
import type { Page } from "playwright";
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import { SessionService } from "../session/session.service";
import { EnvironmentService } from "../environment/environment.service";
interface KeyDescriptor {
keyFile?: string;
@@ -30,16 +30,15 @@ export class AuthService {
private readonly sessionService: SessionService,
private readonly environmentService: EnvironmentService,
) {
this.keysDir = path.resolve(
this.config.get<string>('KEYS_DIR', 'keys'),
);
this.keysDir = path.resolve(this.config.get<string>("KEYS_DIR", "keys"));
}
listKeys(): string[] {
if (!fs.existsSync(this.keysDir)) return [];
return fs.readdirSync(this.keysDir)
.filter(f => f.endsWith('.json'))
.map(f => path.basename(f, '.json'));
return fs
.readdirSync(this.keysDir)
.filter((f) => f.endsWith(".json"))
.map((f) => path.basename(f, ".json"));
}
private loadKeyDescriptor(keyId: string): KeyDescriptor {
@@ -48,51 +47,73 @@ export class AuthService {
throw new BadRequestException(`Key not found: ${keyId}`);
}
try {
return JSON.parse(fs.readFileSync(keyJsonPath, 'utf-8')) as KeyDescriptor;
return JSON.parse(fs.readFileSync(keyJsonPath, "utf-8")) as KeyDescriptor;
} catch (err) {
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, { cause: err });
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, {
cause: err,
});
}
}
async login(keyId: string, environmentName: string, sessionName?: string): Promise<{ token: string; sessionName: string }> {
async login(
keyId: string,
environmentName: string,
sessionName?: string,
): Promise<{ token: string; sessionName: string }> {
const resolvedSession = sessionName ?? crypto.randomUUID();
const env = await this.environmentService.findAll().then(({ data }) => data.find(e => e.name === environmentName));
if (!env) throw new NotFoundException(`Environment "${environmentName}" not found`);
const env = await this.environmentService
.findAll()
.then(({ data }) => data.find((e) => e.name === environmentName));
if (!env)
throw new NotFoundException(`Environment "${environmentName}" not found`);
const loginUrl = env.urls.id_url;
const cabinetUrl = env.urls.cabinet_url;
if (!loginUrl) throw new BadRequestException(`Environment "${environmentName}" is missing id_url`);
if (!cabinetUrl) throw new BadRequestException(`Environment "${environmentName}" is missing cabinet_url`);
if (!loginUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing id_url`,
);
if (!cabinetUrl)
throw new BadRequestException(
`Environment "${environmentName}" is missing cabinet_url`,
);
const descriptor = this.loadKeyDescriptor(keyId);
const useLoginPassword = !!descriptor.login;
if (!useLoginPassword) {
if (!descriptor.keyFile) {
throw new BadRequestException(`Key descriptor for "${keyId}" must have either "login" or "keyFile"`);
throw new BadRequestException(
`Key descriptor for "${keyId}" must have either "login" or "keyFile"`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(`Key file not found: ${descriptor.keyFile}`);
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
}
const browser = await chromium.launch({ headless: true, executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH });
const browser = await chromium.launch({
headless: true,
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
});
try {
const context = await browser.newContext();
const page = await context.newPage();
this.logger.log(`Navigating to ${loginUrl}`);
await page.goto(loginUrl, { waitUntil: 'networkidle' });
await page.goto(loginUrl, { waitUntil: "networkidle" });
if (useLoginPassword) {
// Click "Логін і пароль" auth method
await page.locator('p[aria-label="Логін і пароль"]').click();
// Fill login and password
await page.getByLabel('Електронна пошта').fill(descriptor.login!);
await page.getByLabel('Пароль').fill(descriptor.password);
await page.getByLabel("Електронна пошта").fill(descriptor.login!);
await page.getByLabel("Пароль").fill(descriptor.password);
// Click "Увійти"
await page.locator('button:has-text("Увійти")').click();
@@ -100,19 +121,21 @@ export class AuthService {
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile!);
// Click "Файловий ключ" button
await page.getByText('Файловий ключ').click();
await page.getByText("Файловий ключ").click();
// Upload key file via hidden file input
const fileInput = page.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]');
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')
.locator("#id-app-login-file-key-password")
.fill(descriptor.password);
// Click "Продовжити"
await page.locator('#id-app-login-file-key-sign-button').click();
await page.locator("#id-app-login-file-key-sign-button").click();
}
// Wait until redirected to cabinet
@@ -120,11 +143,11 @@ export class AuthService {
await page.waitForURL(cabinetUrl, { timeout: 30000 });
// Extract token from localStorage
const token = await page.evaluate(() => localStorage.getItem('token'));
const token = await page.evaluate(() => localStorage.getItem("token"));
if (!token) {
throw new InternalServerErrorException(
'Login succeeded but token was not found in localStorage',
"Login succeeded but token was not found in localStorage",
);
}
@@ -134,14 +157,21 @@ export class AuthService {
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) ?? '';
if (k !== null) entries[k] = window.localStorage.getItem(k) ?? "";
}
return entries;
});
await this.sessionService.upsert(resolvedSession, token, cookies, localStorageData);
await this.sessionService.upsert(
resolvedSession,
token,
cookies,
localStorageData,
);
this.logger.log(`Login successful for key ${keyId}, session: ${resolvedSession}`);
this.logger.log(
`Login successful for key ${keyId}, session: ${resolvedSession}`,
);
return { token, sessionName: resolvedSession };
} catch (err) {
if (
@@ -164,26 +194,40 @@ export class AuthService {
const descriptor = this.loadKeyDescriptor(keyId);
if (!descriptor.keyFile) {
throw new BadRequestException(`Key descriptor for "${keyId}" must have "keyFile" to sign`);
throw new BadRequestException(
`Key descriptor for "${keyId}" must have "keyFile" to sign`,
);
}
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
if (!fs.existsSync(keyFilePath)) {
throw new BadRequestException(`Key file not found: ${descriptor.keyFile}`);
throw new BadRequestException(
`Key file not found: ${descriptor.keyFile}`,
);
}
this.logger.log(`Signing with key ${keyId} on page: ${page.url()}`);
// Open the EDS sign widget
await page.locator('button').filter({ hasText: /підпис|sign/i }).first().click();
await page
.locator("button")
.filter({ hasText: /підпис|sign/i })
.first()
.click();
await page.waitForTimeout(500);
// Select the file key tab inside the widget
await page.locator('button, [role="tab"], li').filter({ hasText: /файлов|file key/i }).first().click();
await page
.locator('button, [role="tab"], li')
.filter({ hasText: /файлов|file key/i })
.first()
.click();
await page.waitForTimeout(300);
// Upload the key file
const fileInput = page.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]');
const fileInput = page.locator(
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
);
await fileInput.setInputFiles(keyFilePath);
await page.waitForTimeout(300);
@@ -192,8 +236,12 @@ export class AuthService {
await page.waitForTimeout(200);
// Submit
await page.locator('button').filter({ hasText: /підпис|sign|підтвер/i }).last().click();
await page.waitForLoadState('networkidle');
await page
.locator("button")
.filter({ hasText: /підпис|sign|підтвер/i })
.last()
.click();
await page.waitForLoadState("networkidle");
this.logger.log(`Sign completed for key ${keyId}`);
}