testirovanie-robot/scripts/lockout-screenshot.ts
Peppa ed6da1d233
All checks were successful
peppa/lint lint: success за 0с
peppa/typecheck typecheck: success за 0с
peppa/test test: success за 4с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 11s
deploy / deploy (pull_request) Successful in 2s
TR-15: снимок страницы блокировки в памятке для приёмки, команда пересъёмки, тесты
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 11:59:59 +05:00

74 lines
3.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Снять скриншот страницы входа с сообщением о блокировке для памятки docs/acceptance.md:
// npm run screenshot:lockout
// Страница берётся из самого приложения (пять неверных попыток под придуманным логином),
// поэтому на снимке те же текст и вёрстка, что увидит пользователь. Нужен Google Chrome
// (путь можно задать в CHROME_BIN).
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createApp } from "../src/app.ts";
import { MAX_FAILS } from "../src/auth.ts";
/** Придуманный логин из памятки: настоящих пользователей на снимке нет. */
export const SCREENSHOT_LOGIN = "proverka";
export const SCREENSHOT_FILE = fileURLToPath(
new URL("../docs/screenshots/lockout.png", import.meta.url),
);
/** HTML страницы блокировки со встроенными стилями — её можно открыть как файл. */
export async function lockedPageHtml(): Promise<string> {
const app = createApp({ sessionSecret: Buffer.from("screenshot"), cookieSecure: false });
const server = createServer((req, res) => void app(req, res));
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
try {
let html = "";
for (let attempt = 0; attempt < MAX_FAILS; attempt++) {
const response = await fetch(`${base}/login?lang=ru`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ login: SCREENSHOT_LOGIN, password: "wrong" }).toString(),
});
html = await response.text();
}
const css = await (await fetch(`${base}/static/style.css`)).text();
const link = '<link rel="stylesheet" href="/static/style.css">';
if (!html.includes(link)) throw new Error("На странице входа не найдена ссылка на стили");
return html.replace(link, () => `<style>${css}</style>`);
} finally {
server.close();
server.closeAllConnections();
}
}
function chromeBinary(): string {
if (process.env.CHROME_BIN) return process.env.CHROME_BIN;
return process.platform === "darwin"
? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
: "google-chrome";
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const page = join(mkdtempSync(join(tmpdir(), "tr-lockout-")), "login.html");
writeFileSync(page, await lockedPageHtml());
mkdirSync(dirname(SCREENSHOT_FILE), { recursive: true });
execFileSync(
chromeBinary(),
[
"--headless=new",
"--disable-gpu",
"--hide-scrollbars",
"--force-device-scale-factor=2",
"--window-size=720,640",
`--screenshot=${SCREENSHOT_FILE}`,
pathToFileURL(page).href,
],
{ stdio: "ignore" },
);
console.log(`Скриншот сохранён: ${SCREENSHOT_FILE}`);
}