brendmanager/test/bot-identity.test.js

158 lines
10 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-150: бот найден и назван Telegram, вебхук версии для проверки, привязка на /start, раздел «Бот в Telegram».
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createBotIdentity, webhookUrl, webhookSecret, WEBHOOK_PATH } from "../src/bot-identity.js";
import { createBot, createBotStore, mockTranscriber } from "../src/bot.js";
import { botPage } from "../src/bot-page.js";
import { createTelegram, mockTelegramApi } from "../src/telegram.js";
import { createOwner } from "../src/owner.js";
import { createApp } from "../src/server.js";
const TOKEN = "123456:MOCK_SECRET_TOKEN_VALUE";
const STAGING = "brendmanager-staging.telecom.quest";
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "brm150-"));
test("адрес вебхука: только у версии-владельца или явный", () => {
assert.equal(webhookUrl({ BOT_WEBHOOK: "1", PUBLIC_HOST: STAGING }), `https://${STAGING}${WEBHOOK_PATH}`);
assert.equal(webhookUrl({ PUBLIC_HOST: "brendmanager-pr5.telecom.quest" }), null);
assert.equal(webhookUrl({ TELEGRAM_WEBHOOK_URL: "https://x.example/h" }), "https://x.example/h");
const s = webhookSecret(TOKEN, {});
assert.match(s, /^[0-9a-f]{48}$/);
assert.ok(!s.includes(TOKEN));
assert.equal(webhookSecret(TOKEN, { TELEGRAM_WEBHOOK_SECRET: "explicit" }), "explicit");
assert.equal(webhookSecret("", {}), null);
});
test("Сценарий: версия для проверки ставит вебхук", async () => {
const telegram = mockTelegramApi({ token: TOKEN, me: { id: 1, is_bot: true, username: "TanyaBrandManagerBot" }, webhook: { url: "" } });
const url = webhookUrl({ BOT_WEBHOOK: "1", PUBLIC_HOST: STAGING });
const id = createBotIdentity({ telegram, url, secret: webhookSecret(TOKEN, {}) });
const v = await id.refresh();
assert.equal(v.found, true);
assert.equal(v.username, "TanyaBrandManagerBot");
assert.equal(v.receiving, true);
const set = telegram.calls.find((c) => c.method === "setWebhook");
assert.equal(set.url, `https://${STAGING}/api/telegram/webhook`);
assert.deepEqual(set.allowed_updates, ["message", "callback_query", "my_chat_member"]);
// повторно в пределах 10 минут Telegram не дёргаем
const n = telegram.calls.length;
await id.refresh();
assert.equal(telegram.calls.length, n);
});
test("Сценарий: превью вебхук не трогает", async () => {
const telegram = mockTelegramApi({ token: TOKEN, webhook: { url: "" } });
const v = await createBotIdentity({ telegram, url: null, secret: webhookSecret(TOKEN, {}) }).refresh();
assert.equal(v.found, true);
assert.equal(v.receiving, false);
assert.ok(!telegram.calls.some((c) => c.method === "setWebhook"));
});
test("нет ключа и неверный ключ называются по-разному", async () => {
assert.equal((await createBotIdentity({ telegram: mockTelegramApi({ token: "" }) }).refresh()).error, "key");
assert.equal((await createBotIdentity({ telegram: mockTelegramApi({ token: "bad-x" }) }).refresh()).error, "bad");
});
function botSetup(word) {
const dir = tmp();
const telegram = mockTelegramApi({ token: TOKEN });
const store = createBotStore(path.join(dir, "b.json"));
const owner = createOwner(path.join(dir, "o.json"), word);
const pub = { status: () => ({ stopped: false, channels: {} }), stop() {}, resume() {} };
const bot = createBot({ store, telegram, pub, owner, getPlan: () => ({ ideas: [] }), savePlan() {}, transcriber: mockTranscriber(), siteUrl: `https://${STAGING}`, now: () => new Date("2026-11-22T09:05:00Z") });
const msg = (from, text) => bot.handleUpdate({ message: { from, chat: { id: from.id }, text } });
const last = () => telegram.posts[Object.keys(telegram.posts).at(-1)].at(-1).text;
return { telegram, store, owner, msg, last };
}
test("Сценарий: слово ещё не задано", async () => {
const s = botSetup(undefined);
await s.msg({ id: 7, first_name: "Татьяна" }, "/start");
const text = s.last();
assert.match(text, /1\. Откройте https:\/\/brendmanager-staging\.telecom\.quest\/bot\.html/);
assert.match(text, /2\. Напишите это слово сюда/);
assert.ok(!text.includes(TOKEN));
assert.equal(s.store.chatId(), null);
});
test("Сценарий: слово задано, привязка", async () => {
const s = botSetup("tanya-2026");
await s.msg({ id: 7, first_name: "Татьяна", username: "tanya" }, "/start");
assert.match(s.last(), /напишите сюда слово для одобрения/);
await s.msg({ id: 7, first_name: "Татьяна", username: "tanya" }, "tanya-2026");
assert.match(s.last(), /Готово, бот подключён к вашему аккаунту/);
assert.deepEqual(s.store.owner(), { name: "Татьяна", username: "tanya", at: "2026-11-22T09:05:00.000Z" });
});
test("Сценарий: чужой аккаунт после привязки", async () => {
const s = botSetup("tanya-2026");
await s.msg({ id: 7, first_name: "Татьяна" }, "tanya-2026");
const r = await s.msg({ id: 99, first_name: "Чужой" }, "/start");
assert.equal(r.denied, true);
assert.match(s.last(), /Этот бот отвечает только владельцу/);
assert.equal(s.store.chatId(), 7);
});
const baseView = { sending: false, paused: false, connected: false, missing: "chat", reports: { day: { last: null, next: null }, week: { last: null, next: null } }, errors: [], testRun: null };
test("Сценарий: бот найден и привязан", () => {
const html = botPage("ru", { ...baseView, bot: { checkedAt: Date.parse("2026-11-22T09:00:00Z"), found: true, username: "TanyaBrandManagerBot", receiving: true }, bound: { name: "Татьяна", username: "tanya", at: "2026-11-22T09:05:00Z" }, wordSet: true });
assert.match(html, /id="tgname">Бот найден: @TanyaBrandManagerBot/);
assert.match(html, /Имя бота подтвердил Telegram, проверено 22\.11\.2026 14:00 по Алматы/);
assert.match(html, /id="tgowner">Привязка выполнена: Татьяна \(@tanya\)\. С 22\.11\.2026 14:05 по Алматы\./);
assert.match(html, /каждая публикация ждёт вашего одобрения/);
assert.ok(!html.includes(TOKEN));
});
test("Сценарий: нет ключа", () => {
const html = botPage("ru", { ...baseView, missing: "key", bot: { checkedAt: 1, found: false, error: "key" }, bound: null, wordSet: false });
assert.match(html, /id="tgname">Нет ключа бота/);
assert.match(html, /команда подключит отдельного бота/);
assert.doesNotMatch(html, /Секрет/);
});
test("Сценарий: привязки нет", () => {
const html = botPage("ru", { ...baseView, bot: { checkedAt: 1, found: true, username: "TanyaBrandManagerBot", receiving: true }, bound: null, wordSet: false, wordSetup: true });
assert.match(html, /id="tgowner">Привязки нет/);
assert.match(html, /Откройте @TanyaBrandManagerBot в Telegram и нажмите «Start»/);
assert.match(html, /action="\/bot\/owner-word"/);
const other = botPage("ru", { ...baseView, bot: { found: true, username: "B", receiving: true }, bound: null, wordSet: true, wordSetup: false });
assert.ok(!other.includes('action="/bot/owner-word"'));
});
test("приложение: вебхук с выведенным секретом принимается, без него — отказ; слово задаётся один раз; ключа нет в ответах", async () => {
const dir = tmp();
const telegram = mockTelegramApi({ token: TOKEN, me: { id: 1, is_bot: true, username: "TanyaBrandManagerBot" }, webhook: { url: "" } });
const app = createApp({ file: path.join(dir, "plan.json"), telegram, ownerCode: undefined, webhookSecret: webhookSecret(TOKEN, {}), webhook: `https://${STAGING}${WEBHOOK_PATH}`, siteUrl: `https://${STAGING}` });
await new Promise((r) => app.listen(0, r));
const base = `http://127.0.0.1:${app.address().port}`;
try {
const up = (h) => fetch(base + WEBHOOK_PATH, { method: "POST", headers: { "content-type": "application/json", ...h }, body: JSON.stringify({ message: { from: { id: 7, first_name: "Татьяна", username: "tanya" }, chat: { id: 7 }, text: "/start" } }) });
assert.equal((await up({})).status, 403);
assert.equal((await up({ "x-telegram-bot-api-secret-token": webhookSecret(TOKEN, {}) })).status, 200);
assert.match(telegram.posts["7"].at(-1).text, /bot\.html/);
let page = await (await fetch(base + "/bot.html")).text();
assert.match(page, /Бот найден: @TanyaBrandManagerBot/);
assert.match(page, /Привязки нет/);
const post = (word) => fetch(base + "/bot/owner-word", { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ word, confirm: word }).toString() });
assert.match((await post("abc")).headers.get("location"), /word=short/);
assert.match((await post("tanya-2026")).headers.get("location"), /word=saved/);
await up({ "x-telegram-bot-api-secret-token": webhookSecret(TOKEN, {}) }).then(() => 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: 7, first_name: "Татьяна", username: "tanya" }, chat: { id: 7 }, text: "tanya-2026" } }) }));
page = await (await fetch(base + "/bot.html")).text();
assert.match(page, /Привязка выполнена: Татьяна \(@tanya\)/);
const status = await (await fetch(base + "/api/bot/status")).text();
for (const s of [page, status]) assert.ok(!s.includes(TOKEN) && !s.includes(webhookSecret(TOKEN, {})));
} finally { app.close(); }
});
test("публичная отправка выключена: ключ есть, чата для отправки нет", () => {
const tg = createTelegram({ token: TOKEN, chatId: undefined, fetchImpl: () => { throw new Error("no network"); } });
assert.equal(tg.connected(), false);
assert.equal(tg.missing(), "chat");
});