111 lines
5.3 KiB
TypeScript
111 lines
5.3 KiB
TypeScript
// Снять скриншоты страницы входа для памятки docs/acceptance.md (русский, казахский, английский):
|
||
// с сообщением о блокировке (lockout*.png) и с сообщением о неверном пароле (wrong-password*.png).
|
||
// 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";
|
||
import { LANGS, type Lang } from "../src/i18n.ts";
|
||
|
||
/** Придуманный логин из памятки: настоящих пользователей на снимке нет. */
|
||
export const SCREENSHOT_LOGIN = "proverka";
|
||
/** Имя файла снимка в docs/screenshots: русский — lockout.png, остальные — lockout-<язык>.png. */
|
||
export const screenshotName = (lang: Lang) =>
|
||
lang === "ru" ? "lockout.png" : `lockout-${lang}.png`;
|
||
export const screenshotFile = (lang: Lang) =>
|
||
fileURLToPath(new URL(`../docs/screenshots/${screenshotName(lang)}`, import.meta.url));
|
||
|
||
/** Придуманный логин из шага про неверный пароль в памятке (TR-51). */
|
||
export const WRONG_PASSWORD_LOGIN = "proba";
|
||
/** Снимок сообщения о неверном пароле: wrong-password.png, wrong-password-<язык>.png. */
|
||
export const wrongPasswordScreenshotName = (lang: Lang) =>
|
||
lang === "ru" ? "wrong-password.png" : `wrong-password-${lang}.png`;
|
||
export const wrongPasswordScreenshotFile = (lang: Lang) =>
|
||
fileURLToPath(
|
||
new URL(`../docs/screenshots/${wrongPasswordScreenshotName(lang)}`, import.meta.url),
|
||
);
|
||
|
||
/** HTML страницы блокировки со встроенными стилями — её можно открыть как файл. */
|
||
export const lockedPageHtml = (lang: Lang = "ru") =>
|
||
pageAfterFails(lang, SCREENSHOT_LOGIN, MAX_FAILS);
|
||
|
||
/** HTML страницы после одной неверной попытки: сообщение о неверном логине или пароле. */
|
||
export const wrongPasswordPageHtml = (lang: Lang = "ru") =>
|
||
pageAfterFails(lang, WRONG_PASSWORD_LOGIN, 1);
|
||
|
||
async function pageAfterFails(lang: Lang, login: string, fails: number): Promise<string> {
|
||
// Часы остановлены на 05:00 по времени Астаны, чтобы снимок не менялся от пересъёмки.
|
||
const app = createApp({
|
||
sessionSecret: Buffer.from("screenshot"),
|
||
cookieSecure: false,
|
||
now: () => Date.UTC(2026, 0, 1),
|
||
});
|
||
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 < fails; attempt++) {
|
||
const response = await fetch(`${base}/login?lang=${lang}`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||
body: new URLSearchParams({ 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 dir = mkdtempSync(join(tmpdir(), "tr-lockout-"));
|
||
const shots = LANGS.flatMap(({ code }) => [
|
||
{ name: `lockout-${code}`, file: screenshotFile(code), html: () => lockedPageHtml(code) },
|
||
{
|
||
name: `wrong-password-${code}`,
|
||
file: wrongPasswordScreenshotFile(code),
|
||
html: () => wrongPasswordPageHtml(code),
|
||
},
|
||
]);
|
||
for (const { name, file, html } of shots) {
|
||
const page = join(dir, `${name}.html`);
|
||
writeFileSync(page, await html());
|
||
mkdirSync(dirname(file), { recursive: true });
|
||
execFileSync(
|
||
chromeBinary(),
|
||
[
|
||
"--headless=new",
|
||
"--disable-gpu",
|
||
"--hide-scrollbars",
|
||
"--force-device-scale-factor=2",
|
||
"--window-size=720,640",
|
||
`--screenshot=${file}`,
|
||
pathToFileURL(page).href,
|
||
],
|
||
{ stdio: "ignore" },
|
||
);
|
||
console.log(`Скриншот сохранён: ${file}`);
|
||
}
|
||
}
|