feat(scenario): shared browser per run, sign step type, key loading helper
- all steps in a run share one browser/page instance so wizard state persists
- add 'sign' step type: execCode is {keyId} and signs via EDS widget on current page
- extract AuthService.loadKeyDescriptor() to deduplicate key file parsing
- extend StepType, DTOs, and MCP enums to include 'sign'
This commit is contained in:
1 parent
eeece70866
commit
e85acc8fb2
7 files changed
+376
-61
No files matched your search
+52
-13
@@ -7,6 +7,7 @@ import {
|
||||
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';
|
||||
@@ -41,6 +42,18 @@ export class AuthService {
|
||||
.map(f => path.basename(f, '.json'));
|
||||
}
|
||||
|
||||
private loadKeyDescriptor(keyId: string): KeyDescriptor {
|
||||
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
|
||||
if (!fs.existsSync(keyJsonPath)) {
|
||||
throw new BadRequestException(`Key not found: ${keyId}`);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(keyJsonPath, 'utf-8')) as KeyDescriptor;
|
||||
} catch (err) {
|
||||
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
async login(keyId: string, environmentName: string, sessionName?: string): Promise<{ token: string; sessionName: string }> {
|
||||
const resolvedSession = sessionName ?? crypto.randomUUID();
|
||||
|
||||
@@ -52,19 +65,7 @@ export class AuthService {
|
||||
if (!loginUrl) throw new BadRequestException(`Environment "${environmentName}" is missing id_url`);
|
||||
if (!cabinetUrl) throw new BadRequestException(`Environment "${environmentName}" is missing cabinet_url`);
|
||||
|
||||
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 (err) {
|
||||
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, { cause: err });
|
||||
}
|
||||
|
||||
const descriptor = this.loadKeyDescriptor(keyId);
|
||||
const useLoginPassword = !!descriptor.login;
|
||||
|
||||
if (!useLoginPassword) {
|
||||
@@ -158,4 +159,42 @@ export class AuthService {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
async signWithKey(keyId: string, page: Page): Promise<void> {
|
||||
const descriptor = this.loadKeyDescriptor(keyId);
|
||||
|
||||
if (!descriptor.keyFile) {
|
||||
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}`);
|
||||
}
|
||||
|
||||
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.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.waitForTimeout(300);
|
||||
|
||||
// Upload the key file
|
||||
const fileInput = page.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]');
|
||||
await fileInput.setInputFiles(keyFilePath);
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// Enter password
|
||||
await page.locator('input[type="password"]').fill(descriptor.password);
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
// Submit
|
||||
await page.locator('button').filter({ hasText: /підпис|sign|підтвер/i }).last().click();
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
this.logger.log(`Sign completed for key ${keyId}`);
|
||||
}
|
||||
}
|
||||
@@ -333,7 +333,7 @@ export class McpService {
|
||||
inputSchema: {
|
||||
scenarioId: z.number().int().describe('Parent scenario ID'),
|
||||
order: z.number().int().min(0).describe('Execution order (ascending)'),
|
||||
type: z.enum(['login', 'exec']).describe('Step type'),
|
||||
type: z.enum(['login', 'exec', 'sign']).describe('Step type'),
|
||||
sessionName: z.string().describe('Session name used by this step'),
|
||||
execCode: z.string().optional().describe('Playwright JS code to execute (exec steps)'),
|
||||
validateCode: z.string().optional().describe('Validation JS code returning { success, description }'),
|
||||
@@ -376,7 +376,7 @@ export class McpService {
|
||||
scenarioId: z.number().int().describe('Scenario ID'),
|
||||
stepId: z.number().int().describe('Step ID'),
|
||||
order: z.number().int().min(0).optional().describe('New execution order'),
|
||||
type: z.enum(['login', 'exec']).optional().describe('New step type'),
|
||||
type: z.enum(['login', 'exec', 'sign']).optional().describe('New step type'),
|
||||
sessionName: z.string().optional().describe('New session name'),
|
||||
execCode: z.string().optional().describe('New exec code'),
|
||||
validateCode: z.string().optional().describe('New validation code'),
|
||||
|
||||
@@ -8,8 +8,8 @@ export class CreateScenarioStepDto {
|
||||
@Min(0)
|
||||
order: number;
|
||||
|
||||
@ApiProperty({ enum: ['login', 'exec'], example: 'exec' })
|
||||
@IsIn(['login', 'exec'])
|
||||
@ApiProperty({ enum: ['login', 'exec', 'sign'], example: 'exec' })
|
||||
@IsIn(['login', 'exec', 'sign'])
|
||||
type: StepType;
|
||||
|
||||
@ApiProperty({ description: 'Session name used by this step. login steps create it; exec steps consume it.', example: 'my-session' })
|
||||
|
||||
@@ -9,9 +9,9 @@ export class UpdateScenarioStepDto {
|
||||
@Min(0)
|
||||
order?: number;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['login', 'exec'] })
|
||||
@ApiPropertyOptional({ enum: ['login', 'exec', 'sign'] })
|
||||
@IsOptional()
|
||||
@IsIn(['login', 'exec'])
|
||||
@IsIn(['login', 'exec', 'sign'])
|
||||
type?: StepType;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Interval } from '@nestjs/schedule';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { chromium } from 'playwright';
|
||||
import type { Browser, BrowserContext, Page } from 'playwright';
|
||||
import { ScenarioRunEntity } from './scenario-run.entity';
|
||||
import { ScenarioRunStepEntity } from './scenario-run-step.entity';
|
||||
import { ScenarioStepEntity } from './scenario-step.entity';
|
||||
@@ -16,10 +17,17 @@ interface ValidateResult {
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface BrowserHandle {
|
||||
browser: Browser;
|
||||
context: BrowserContext;
|
||||
page: Page;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ScenarioSchedulerService {
|
||||
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
|
||||
private isProcessingStep = false;
|
||||
private readonly runBrowsers = new Map<number, BrowserHandle>();
|
||||
|
||||
constructor(
|
||||
@InjectRepository(ScenarioRunEntity)
|
||||
@@ -76,6 +84,8 @@ export class ScenarioSchedulerService {
|
||||
try {
|
||||
if (step.type === 'login') {
|
||||
await this.executeLoginStep(stepRun, step);
|
||||
} else if (step.type === 'sign') {
|
||||
await this.executeSignStep(stepRun, step);
|
||||
} else {
|
||||
await this.executeExecStep(stepRun, step);
|
||||
}
|
||||
@@ -86,6 +96,47 @@ export class ScenarioSchedulerService {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared browser per run ─────────────────────────────────────────────────
|
||||
|
||||
private async getOrCreateBrowserHandle(runId: number, sessionName: string): Promise<BrowserHandle> {
|
||||
const existing = this.runBrowsers.get(runId);
|
||||
if (existing) return existing;
|
||||
|
||||
const session = await this.sessionService.findBySessionName(sessionName);
|
||||
if (!session) throw new Error(`Session not found: ${sessionName}`);
|
||||
|
||||
const cookies = JSON.parse(session.cookies) as Parameters<BrowserContext['addCookies']>[0];
|
||||
const localStorageData: Record<string, string> = JSON.parse(session.localStorage);
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
await context.addCookies(cookies);
|
||||
await context.addInitScript((entries: Record<string, string>) => {
|
||||
for (const [k, v] of Object.entries(entries)) window.localStorage.setItem(k, v);
|
||||
}, localStorageData);
|
||||
const page = await context.newPage();
|
||||
|
||||
const handle: BrowserHandle = { browser, context, page };
|
||||
this.runBrowsers.set(runId, handle);
|
||||
this.logger.log(`Run #${runId}: browser created (session: ${sessionName})`);
|
||||
return handle;
|
||||
}
|
||||
|
||||
private async closeBrowserHandle(runId: number): Promise<void> {
|
||||
const handle = this.runBrowsers.get(runId);
|
||||
if (!handle) return;
|
||||
this.runBrowsers.delete(runId);
|
||||
try {
|
||||
await handle.browser.close();
|
||||
this.logger.log(`Run #${runId}: browser closed`);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Run #${runId}: error closing browser: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Login step ─────────────────────────────────────────────────────────────
|
||||
|
||||
private async executeLoginStep(stepRun: ScenarioRunStepEntity, step: ScenarioStepEntity): Promise<void> {
|
||||
@@ -103,12 +154,12 @@ export class ScenarioSchedulerService {
|
||||
const loginResult = await this.authService.login(params.keyId, params.environmentName, step.sessionName);
|
||||
this.logger.log(`StepRun #${stepRun.id}: login OK, session=${loginResult.sessionName}`);
|
||||
|
||||
// Optional validation
|
||||
if (step.validateCode) {
|
||||
const validateResult = await this.runValidateCode(step.sessionName, step.validateCode);
|
||||
if (!validateResult.success) {
|
||||
throw new Error(validateResult.description ?? 'Validation failed');
|
||||
}
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(stepRun.runId, step.sessionName);
|
||||
this.codeExecutor.validate(step.validateCode);
|
||||
const { result } = await this.codeExecutor.execute(page, context, step.validateCode);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? 'Validation failed');
|
||||
}
|
||||
|
||||
await this.passStepRun(stepRun, null);
|
||||
@@ -117,57 +168,52 @@ export class ScenarioSchedulerService {
|
||||
// ── Exec step ──────────────────────────────────────────────────────────────
|
||||
|
||||
private async executeExecStep(stepRun: ScenarioRunStepEntity, step: ScenarioStepEntity): Promise<void> {
|
||||
if (!step.execCode) {
|
||||
throw new Error('exec step has no execCode');
|
||||
}
|
||||
if (!step.execCode) throw new Error('exec step has no execCode');
|
||||
|
||||
this.codeExecutor.validate(step.execCode);
|
||||
await this.runExecCode(step.sessionName, step.execCode);
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(stepRun.runId, step.sessionName);
|
||||
await this.codeExecutor.execute(page, context, step.execCode);
|
||||
this.logger.log(`StepRun #${stepRun.id}: exec OK`);
|
||||
|
||||
// Optional validation
|
||||
if (step.validateCode) {
|
||||
const validateResult = await this.runValidateCode(step.sessionName, step.validateCode);
|
||||
if (!validateResult.success) {
|
||||
throw new Error(validateResult.description ?? 'Validation failed');
|
||||
}
|
||||
this.codeExecutor.validate(step.validateCode);
|
||||
const { result } = await this.codeExecutor.execute(page, context, step.validateCode);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? 'Validation failed');
|
||||
}
|
||||
|
||||
await this.passStepRun(stepRun, null);
|
||||
}
|
||||
|
||||
// ── Browser helpers ────────────────────────────────────────────────────────
|
||||
// ── Sign step ──────────────────────────────────────────────────────────────
|
||||
|
||||
private async runExecCode(sessionName: string, code: string): Promise<unknown> {
|
||||
const session = await this.sessionService.findBySessionName(sessionName);
|
||||
if (!session) throw new Error(`Session not found: ${sessionName}`);
|
||||
|
||||
const cookies: unknown[] = JSON.parse(session.cookies);
|
||||
const localStorageData: Record<string, string> = JSON.parse(session.localStorage);
|
||||
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH });
|
||||
private async executeSignStep(stepRun: ScenarioRunStepEntity, step: ScenarioStepEntity): Promise<void> {
|
||||
// execCode must be a JSON object: { "keyId": "..." }
|
||||
let params: { keyId: string };
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
await context.addCookies(cookies as Parameters<typeof context.addCookies>[0]);
|
||||
const page = await context.newPage();
|
||||
await context.addInitScript((entries: Record<string, string>) => {
|
||||
for (const [k, v] of Object.entries(entries)) window.localStorage.setItem(k, v);
|
||||
}, localStorageData);
|
||||
const { result } = await this.codeExecutor.execute(page, context, code);
|
||||
return result;
|
||||
} finally {
|
||||
await browser.close();
|
||||
params = JSON.parse(step.execCode ?? '{}');
|
||||
} catch {
|
||||
throw new Error('sign step execCode must be valid JSON with keyId');
|
||||
}
|
||||
if (!params.keyId) throw new Error('sign step execCode must include keyId');
|
||||
|
||||
const { page, context } = await this.getOrCreateBrowserHandle(stepRun.runId, step.sessionName);
|
||||
await this.authService.signWithKey(params.keyId, page);
|
||||
this.logger.log(`StepRun #${stepRun.id}: sign OK`);
|
||||
|
||||
if (step.validateCode) {
|
||||
this.codeExecutor.validate(step.validateCode);
|
||||
const { result } = await this.codeExecutor.execute(page, context, step.validateCode);
|
||||
const vr = this.parseValidateResult(result);
|
||||
if (!vr.success) throw new Error(vr.description ?? 'Validation failed');
|
||||
}
|
||||
|
||||
await this.passStepRun(stepRun, null);
|
||||
}
|
||||
|
||||
private async runValidateCode(sessionName: string, validateCode: string): Promise<ValidateResult> {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await this.runExecCode(sessionName, validateCode);
|
||||
} catch (err) {
|
||||
return { success: false, description: (err as Error).message };
|
||||
}
|
||||
// ── Validation helper ──────────────────────────────────────────────────────
|
||||
|
||||
private parseValidateResult(raw: unknown): ValidateResult {
|
||||
if (typeof raw === 'boolean') return { success: raw };
|
||||
if (raw && typeof raw === 'object') {
|
||||
const r = raw as Record<string, unknown>;
|
||||
@@ -176,7 +222,6 @@ export class ScenarioSchedulerService {
|
||||
description: r['description'] != null ? String(r['description']) : undefined,
|
||||
};
|
||||
}
|
||||
// Anything truthy = pass
|
||||
return { success: Boolean(raw) };
|
||||
}
|
||||
|
||||
@@ -208,6 +253,7 @@ export class ScenarioSchedulerService {
|
||||
],
|
||||
});
|
||||
if (remaining === 0) {
|
||||
await this.closeBrowserHandle(stepRun.runId);
|
||||
await this.runRepo.update(stepRun.runId, { status: 'pass' });
|
||||
this.logger.log(`Run #${stepRun.runId} → pass (all steps passed)`);
|
||||
}
|
||||
@@ -233,6 +279,7 @@ export class ScenarioSchedulerService {
|
||||
|
||||
this.logger.log(`Run #${stepRun.runId}: remaining steps cancelled`);
|
||||
|
||||
await this.closeBrowserHandle(stepRun.runId);
|
||||
await this.runRepo.update(stepRun.runId, { status: 'fail' });
|
||||
this.logger.log(`Run #${stepRun.runId} → fail`);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
} from 'typeorm';
|
||||
import { ScenarioEntity } from './scenario.entity';
|
||||
|
||||
export type StepType = 'login' | 'exec';
|
||||
export type StepType = 'login' | 'exec' | 'sign';
|
||||
|
||||
@Entity('scenario_steps')
|
||||
export class ScenarioStepEntity {
|
||||
|
||||
Reference in new issue
Block a user