brendmanager/test/brm155-owner-word-reset.test.js
peppa-bot 6bb0596b80
All checks were successful
peppa/lint lint: success за 1с
peppa/test test: success за 7с
ci / checks (pull_request) Successful in 28s
deploy / deploy (pull_request) Successful in 52s
BRM-167: форма нового слова и после привязки, смена только с текущим словом; архив change, память
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:48:04 +00:00

140 lines
8.1 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-155: статус привязки, новое слово для одобрения, одна проверка слова у сайта и бота.
import test from "node:test";
import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { webhookSecret, WEBHOOK_PATH } from "../src/bot-identity.js";
import { mockTelegramApi } from "../src/telegram.js";
import { createOwner, normalizeWord } from "../src/owner.js";
import { createApp } from "../src/server.js";
import { t } from "../src/i18n.js";
const TOKEN = "123456:MOCK_SECRET_TOKEN_VALUE";
const STAGING = "brendmanager-staging.telecom.quest";
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "brm155-"));
const OLD = "старое-слово-1", NEW = "Новое-Слово 2026";
// Старое слово, сохранённое до BRM-155 (хеш без нормализации).
function legacyOwner(dir, word) {
const salt = crypto.randomBytes(16);
fs.writeFileSync(path.join(dir, "owner.json"), JSON.stringify({ salt: salt.toString("hex"), hash: crypto.scryptSync(word, salt, 32).toString("hex") }));
}
async function startApp({ dir = tmp(), staging = true, siteUrl } = {}) {
const telegram = mockTelegramApi({ token: TOKEN, me: { id: 1, is_bot: true, username: "TanyaBrandManagerBot" }, webhook: { url: "" } });
const logs = [];
const orig = console.log;
console.log = (...a) => { logs.push(a.join(" ")); };
const app = createApp({ file: path.join(dir, "plan.json"), telegram, ownerCode: undefined, webhookSecret: webhookSecret(TOKEN, {}),
webhook: staging ? `https://${STAGING}${WEBHOOK_PATH}` : "", siteUrl: siteUrl ?? `https://${STAGING}` });
await new Promise((r) => app.listen(0, r));
const base = `http://127.0.0.1:${app.address().port}`;
const form = (url, body) => fetch(base + url, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() }).then((r) => r.headers.get("location"));
const say = async (text, id = 7) => {
await fetch(base + WEBHOOK_PATH, { method: "POST", headers: { "content-type": "application/json", "x-telegram-bot-api-secret-token": webhookSecret(TOKEN, {}) },
body: JSON.stringify({ message: { from: { id, first_name: "Татьяна", username: "tanya" }, chat: { id }, text } }) });
return telegram.posts[String(id)].at(-1).text;
};
const page = (q = "") => fetch(base + "/bot.html" + q).then((r) => r.text());
return { app, base, form, say, page, telegram, logs, close: () => { console.log = orig; app.close(); } };
}
test("normalizeWord: регистр и пробелы не важны", () => {
assert.equal(normalizeWord(" Новое-Слово 2026 "), "новое-слово 2026");
const dir = tmp();
const o = createOwner(path.join(dir, "o.json"));
assert.equal(o.reset(NEW, NEW.toLowerCase()), "ok"); // первое слово — текущее не нужно
assert.equal(o.verify("новое-слово 2026 "), "ok");
assert.equal(o.check("НОВОЕ-СЛОВО 2026"), "ok");
assert.equal(o.check("другое-слово"), "wrong");
});
test("старое слово (до BRM-155) продолжает работать, пока его не заменили", () => {
const dir = tmp();
legacyOwner(dir, "Tanya-Word");
const o = createOwner(path.join(dir, "owner.json"));
assert.equal(o.check("Tanya-Word"), "ok");
assert.equal(o.check("Tanya-Word "), "ok");
});
test("Сценарий: Ждёт слова — форма видна", async () => {
const dir = tmp();
legacyOwner(dir, OLD);
const s = await startApp({ dir });
try {
const html = await s.page();
assert.match(html, /id="tgstate"[^>]*>Сейчас: ждёт слова/);
assert.match(html, /<h3 id="tgnew">Задать новое слово/);
assert.match(html, /action="\/bot\/owner-word"/);
assert.match(html, /name="confirm" type="password"/);
assert.match(html, /action="\/bot\/word-check"/);
} finally { s.close(); }
});
test("Сценарий: Новое слово и привязка", async () => {
const dir = tmp();
legacyOwner(dir, OLD);
const s = await startApp({ dir });
try {
const before = await (await fetch(s.base + "/api/bot/status")).json();
assert.match(await s.form("/bot/owner-word", { current: OLD, word: NEW, confirm: NEW }), /word=saved#tgbot$/);
assert.match(await s.page("?word=saved"), /Новое слово для одобрения сохранено/);
// Старое больше не подходит ни на сайте, ни в боте — и ответы одинаковые.
assert.match(await s.form("/bot/word-check", { word: OLD }), /check=wrong/);
const wrongPage = await s.page("?check=wrong");
const wrongBot = await s.say(OLD);
assert.equal(wrongBot, t("ru", "bot.bind.wrong"));
assert.ok(wrongPage.includes(`id="tgcheck" class="st off" role="status">${t("ru", "bot.bind.wrong")}`));
assert.match(wrongBot, /задайте там новое/);
// Новое — на телефоне с заглавной буквой и пробелом.
assert.match(await s.form("/bot/word-check", { word: "новое-слово 2026" }), /check=ok/);
assert.equal(await s.say("Новое-слово 2026 "), "Готово, бот подключён к вашему аккаунту.");
const html = await s.page();
assert.match(html, /id="tgstate"[^>]*>Сейчас: привязано/);
assert.match(html, /Привязка не включает отправку в каналы/);
// BRM-167: форма видна и после привязки.
assert.ok(html.includes('action="/bot/owner-word"'));
// Привязка отправку не включает.
const st = await (await fetch(s.base + "/api/bot/status")).json();
for (const k of ["sending", "paused", "connected", "missing"]) assert.deepEqual(st[k], before[k]);
// Слова нет ни на страницах, ни в журнале.
for (const x of [html, wrongPage, JSON.stringify(st), s.logs.join("\n")]) for (const w of [OLD, NEW, NEW.toLowerCase()]) assert.ok(!x.includes(w));
} finally { s.close(); }
});
test("Сценарий: Подтверждение не совпало", async () => {
const dir = tmp();
legacyOwner(dir, OLD);
const s = await startApp({ dir });
try {
assert.match(await s.form("/bot/owner-word", { current: OLD, word: NEW, confirm: "другое-слово" }), /word=mismatch/);
assert.match(await s.page("?word=mismatch"), /Слова не совпали, слово не изменено/);
assert.match(await s.form("/bot/word-check", { word: OLD }), /check=ok/);
} finally { s.close(); }
});
test("Сценарий: Чужой человек после привязки", async () => {
const s = await startApp();
try {
assert.match(await s.form("/bot/owner-word", { word: NEW, confirm: NEW }), /word=saved/);
await s.say(NEW);
assert.match(await s.form("/bot/owner-word", { word: "чужое-слово", confirm: "чужое-слово" }), /word=notOwner/);
assert.match(await s.page("?word=notOwner"), /Слово не изменено: текущее слово не подошло/);
assert.match(await s.form("/bot/word-check", { word: NEW }), /check=ok/);
assert.match(await s.say("чужое-слово", 99), /отвечает только владельцу/);
} finally { s.close(); }
});
test("Сценарий: Не та версия", async () => {
const s = await startApp({ staging: false, siteUrl: "https://brendmanager-pr140.telecom.quest" });
try {
const html = await s.page();
assert.match(html, /id="tgstate"[^>]*>Сейчас: не привязано/);
assert.ok(!html.includes('action="/bot/owner-word"'));
assert.match(html, /id="tgwhere">Задать новое слово можно там, куда бот присылает сообщения, — ваш продукт:.*href="https:\/\/brendmanager-prod\.telecom\.quest\/bot\.html"/);
assert.match(await s.form("/bot/owner-word", { word: NEW, confirm: NEW }), /word=env/);
} finally { s.close(); }
});