brendmanager/src/word-proof.js
peppa-bot 0d8c860e8a
All checks were successful
peppa/lint lint: success за 2с
peppa/test test: success за 25с
ci / checks (pull_request) Successful in 41s
deploy / deploy (pull_request) Successful in 17s
BRM-182: «Как проверено слово для одобрения» на «Бот и отчёты» — цепочка на отдельной копии проверочными словами
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 18:57:41 +00:00

67 lines
4.8 KiB
JavaScript
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.

// BRM-182: видимая проверка слова для одобрения. При запуске версии прогоняет цепочку
// «задать слово → заменить → проверить на сайте → бот принимает → перезапуск → чужой отклонён»
// на отдельной временной копии данных — теми же проверками, что у страницы и бота (owner.js, bot.js),
// с проверочными словами и моком Telegram. Настоящее слово и привязка не трогаются.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createOwner } from "./owner.js";
import { createBot, createBotStore } from "./bot.js";
import { mockTelegramApi } from "./telegram.js";
import { t } from "./i18n.js";
// Проверочные слова — не слово владелицы; кириллица и пробел внутри нарочно.
export const PROOF_OLD = "проба-слово первое";
export const PROOF_NEW = "Проба-Слово Второе";
const OWNER_ID = 701, STRANGER_ID = 702;
const BOT_KEYS = ["bot.bind.done", "bot.bind.wrong", "bot.denied", "bot.bind.start", "bot.bind.startNoWord"];
/**
* @returns {Promise<{at:string, ok:boolean, rows:{step:string, word?:string, got:string[], ok:boolean}[]}>}
* got — ключи текстов (страница показывает их на своём языке).
*/
export async function runWordProof({ now = () => new Date(), mockBreak = null } = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm-word-proof-"));
const rows = [];
const row = (step, got, want, word) => rows.push({ step, ...(word ? { word } : {}), got, ok: got.join("|") === want.join("|") });
const pageMsg = (r) => "botp.tg.word." + (r === "ok" ? "saved" : r);
const checkMsg = (r) => (r === "wrong" ? "bot.bind.wrong" : "botp.tg.check." + r);
try {
const open = () => {
const owner = createOwner(path.join(dir, "owner.json"), undefined);
const store = createBotStore(path.join(dir, "bot.json"));
const telegram = mockTelegramApi({ token: "123456:MOCK_PROOF_TOKEN" });
const pub = { status: () => ({}), stop() {}, resume() {} };
const bot = createBot({ store, telegram, pub, owner, getPlan: () => ({ ideas: [] }), savePlan() {}, transcriber: null, now });
const state = () => "botp.tg.state." + (store.owner() ? "bound" : owner.isSet() ? "waiting" : "none");
const say = async (text, id) => {
await bot.handleUpdate({ message: { from: { id, first_name: "Проба" }, chat: { id }, text } });
const reply = telegram.posts[String(id)]?.at(-1)?.text ?? "";
const key = BOT_KEYS.find((k) => t("ru", k) === reply) ?? "botp.proof.other";
return mockBreak === key ? "botp.proof.other" : key;
};
return { owner, store, state, say };
};
let a = open();
row("set", [pageMsg(a.owner.reset(PROOF_OLD, PROOF_OLD))], ["botp.tg.word.saved"], PROOF_OLD);
row("replace", [pageMsg(a.owner.reset(PROOF_NEW, PROOF_NEW, PROOF_OLD))], ["botp.tg.word.saved"], PROOF_NEW);
row("checkSpaces", [checkMsg(a.owner.check(" " + PROOF_NEW.toLowerCase() + " "))], ["botp.tg.check.ok"], " " + PROOF_NEW.toLowerCase() + " ");
row("checkCase", [checkMsg(a.owner.check(PROOF_NEW.toUpperCase()))], ["botp.tg.check.ok"], PROOF_NEW.toUpperCase());
row("checkOld", [checkMsg(a.owner.check(PROOF_OLD))], ["bot.bind.wrong"], PROOF_OLD);
row("stateBefore", [a.state()], ["botp.tg.state.waiting"]);
row("botOld", [await a.say(PROOF_OLD, OWNER_ID)], ["bot.bind.wrong"], PROOF_OLD);
row("botNew", [await a.say(" " + PROOF_NEW.toUpperCase() + " ", OWNER_ID), a.state()], ["bot.bind.done", "botp.tg.state.bound"], " " + PROOF_NEW.toUpperCase() + " ");
a = open(); // перезапуск: всё заново из тех же файлов
row("restart", [a.state(), checkMsg(a.owner.check(PROOF_NEW)), checkMsg(a.owner.check(PROOF_OLD))], ["botp.tg.state.bound", "botp.tg.check.ok", "bot.bind.wrong"], PROOF_NEW);
const stranger = await a.say(PROOF_NEW, STRANGER_ID);
row("stranger", [stranger, String(a.store.chatId()) === String(OWNER_ID) ? "botp.proof.stillOwner" : "botp.proof.ownerChanged"], ["bot.denied", "botp.proof.stillOwner"], PROOF_NEW);
const saved = fs.readFileSync(path.join(dir, "owner.json"), "utf8").toLowerCase();
row("stored", [saved.includes("проба") ? "botp.proof.plain" : "botp.proof.hashed"], ["botp.proof.hashed"]);
} catch (e) {
rows.push({ step: "crash", got: ["botp.proof.crash"], ok: false });
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
return { at: now().toISOString(), ok: rows.length > 0 && rows.every((r) => r.ok), rows };
}