pr-hw1/test/web.test.ts
peppa-bot b4f907d1d5 PH-1: образ продукта, форматирование
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:02:48 +00:00

295 lines
12 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.

import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, describe, it } from "node:test";
import { Assistant } from "../src/assistant.ts";
import { loadConfig } from "../src/config.ts";
import { Store } from "../src/store.ts";
import { zonedToUtc } from "../src/time.ts";
import { Web } from "../src/web.ts";
import { combine, mockGoogle, mockTelegram } from "./mocks.ts";
const servers: Server[] = [];
after(() => {
for (const s of servers) s.close();
});
async function start(env: Record<string, string>) {
const g = mockGoogle();
const tg = mockTelegram();
const store = new Store();
const now = zonedToUtc(2026, 12, 1, 8, 0, "Asia/Almaty");
const a = new Assistant(loadConfig(env), store, {
fetch: combine(g.fetchFn, tg.fetchFn),
now: () => now,
log: () => {},
});
const web = new Web(a);
const server = createServer((req, res) => void web.handle(req, res));
servers.push(server);
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
let cookie = "";
const req = async (path: string, init: RequestInit & { form?: Record<string, string> } = {}) => {
const headers: Record<string, string> = { ...(init.headers as Record<string, string>) };
if (cookie) headers.Cookie = cookie;
let body = init.body;
if (init.form) {
headers["Content-Type"] = "application/x-www-form-urlencoded";
body = new URLSearchParams(init.form).toString();
}
const res = await fetch(base + path, { ...init, headers, body, redirect: "manual" });
const set = res.headers.get("set-cookie");
if (set?.startsWith("sid=")) cookie = set.split(";")[0] ?? "";
return { res, text: await res.text() };
};
return {
a,
store,
g,
tg,
req,
login: () => req("/login", { method: "POST", form: { password: "tanya-2026" } }),
};
}
const FULL = {
ASSISTANT_PASSWORD: "tanya-2026",
GOOGLE_CLIENT_ID: "mock-client",
GOOGLE_CLIENT_SECRET: "mock-secret",
TELEGRAM_BOT_TOKEN: "mock-token",
WHATSAPP_VERIFY_TOKEN: "mock-verify",
WHATSAPP_APP_SECRET: "mock-app-secret",
};
describe("Требование: Вход владельца", () => {
it("Scenario: Успешный вход", async () => {
const s = await start(FULL);
const r = await s.login();
assert.equal(r.res.status, 303);
assert.equal(r.res.headers.get("location"), "/");
const page = await s.req("/");
assert.equal(page.res.status, 200);
assert.match(page.text, /<h1>Задачи<\/h1>/);
assert.match(page.text, />Выйти</);
});
it("Scenario: Неверный пароль", async () => {
const s = await start(FULL);
const r = await s.req("/login", { method: "POST", form: { password: "12345" } });
assert.equal(r.res.status, 401);
assert.match(r.text, /Пароль не подошёл. Проверьте раскладку и попробуйте ещё раз./);
const page = await s.req("/");
assert.equal(page.res.status, 303);
assert.equal(page.res.headers.get("location"), "/login");
});
});
describe("Требование: Демо-режим", () => {
it("Scenario: Пароль не задан", async () => {
const s = await start({});
const r = await s.req("/");
assert.equal(r.res.status, 200);
assert.match(r.text, /Ассистент пока работает в демо-режиме/);
assert.equal((r.text.match(/badge demo">Пример</g) ?? []).length, 3);
});
it("Scenario: Подключение в демо-режиме недоступно", async () => {
const s = await start({ GOOGLE_CLIENT_ID: "x", GOOGLE_CLIENT_SECRET: "y" });
const r = await s.req("/oauth/google/start");
assert.equal(r.res.headers.get("location"), "/login");
assert.equal(s.g.calls.length, 0);
});
});
describe("Требование: Проверка здоровья и языки", () => {
for (const [lang, button] of [
["ru", "Войти"],
["kk", "Кіру"],
["en", "Sign in"],
]) {
it(`Scenario Outline: Выбор языка — ${lang}`, async () => {
const s = await start(FULL);
const r = await s.req(`/login?lang=${lang}`);
assert.match(r.text, new RegExp(`<button class="btn">${button}</button>`));
});
}
it("Scenario: Проверка здоровья без настроек", async () => {
const s = await start({});
const r = await s.req("/healthz");
assert.equal(r.res.status, 200);
assert.equal(r.text, "ok");
});
it("страница «Как это работает» открывается без входа", async () => {
const s = await start(FULL);
const r = await s.req("/how");
assert.equal(r.res.status, 200);
assert.match(r.text, /@MyFoxy_bot_bot/);
});
});
describe("Требование: Подключение Google штатным входом (страница)", () => {
it("Scenario: Данные приложения Google не заданы", async () => {
const s = await start({ ASSISTANT_PASSWORD: "tanya-2026" });
await s.login();
const r = await s.req("/connections");
assert.match(r.text, /Подключение Google пока не настроено владельцем продукта/);
assert.doesNotMatch(r.text, /href="\/oauth\/google\/start"/);
});
it("Scenario: Успешное подключение", async () => {
const s = await start(FULL);
await s.login();
const startR = await s.req("/oauth/google/start", {
headers: { "X-Forwarded-Host": "pr-hw1-pr1.telecom.quest" },
});
const loc = new URL(startR.res.headers.get("location") ?? "");
assert.equal(loc.host, "accounts.google.com");
assert.equal(
loc.searchParams.get("redirect_uri"),
"https://pr-hw1-pr1.telecom.quest/oauth/google/callback",
);
const state = loc.searchParams.get("state") ?? "";
const cb = await s.req(`/oauth/google/callback?code=good-code&state=${state}`, {
headers: { "X-Forwarded-Host": "pr-hw1-pr1.telecom.quest" },
});
assert.equal(cb.res.headers.get("location"), "/connections?m=flash.googleConnected");
const page = await s.req("/connections");
assert.match(page.text, /Подключено: tanya@example.com/);
assert.doesNotMatch(page.text, /mock-refresh|mock-access/);
});
it("Scenario: Владелец отказал в доступе", async () => {
const s = await start(FULL);
await s.login();
const startR = await s.req("/oauth/google/start");
const state = new URL(startR.res.headers.get("location") ?? "").searchParams.get("state");
await s.req(`/oauth/google/callback?error=access_denied&state=${state}`);
const page = await s.req("/connections");
assert.match(
page.text,
/Google не подключён: вы отменили доступ. Нажмите «Подключить Google», чтобы попробовать снова./,
);
});
it("чужой state отклоняется", async () => {
const s = await start(FULL);
await s.login();
await s.req("/oauth/google/start");
await s.req("/oauth/google/callback?code=good-code&state=forged");
assert.equal(s.store.state.google, undefined);
});
});
describe("Требование: Подтверждённый чат Telegram (страница)", () => {
it("ссылка на бота с кодом", async () => {
const s = await start(FULL);
await s.a.telegramInit();
await s.login();
const r = await s.req("/connections");
const code = s.store.state.telegram.pendingCode?.code;
assert.ok(code);
assert.match(r.text, new RegExp(`https://t.me/MyFoxy_bot_bot\\?start=${code}`));
});
});
describe("Требование: Границы чтения мессенджеров (WhatsApp)", () => {
const payload = JSON.stringify({
entry: [
{
changes: [
{
value: {
contacts: [{ wa_id: "77011234567", profile: { name: "Айгуль" } }],
messages: [
{
id: "wamid.1",
from: "77011234567",
timestamp: "1764561600",
type: "text",
text: { body: "Прошу отправить счёт до 04.12" },
},
],
},
},
],
},
],
});
const sig = `sha256=${createHmac("sha256", "mock-app-secret").update(payload).digest("hex")}`;
it("проверка адреса для WhatsApp Business", async () => {
const s = await start(FULL);
const ok = await s.req(
"/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=mock-verify&hub.challenge=42",
);
assert.equal(ok.text, "42");
const bad = await s.req("/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=wrong&hub.challenge=42");
assert.equal(bad.res.status, 403);
});
it("сообщение с верной подписью становится задачей", async () => {
const s = await start(FULL);
const r = await s.req("/webhooks/whatsapp", {
method: "POST",
body: payload,
headers: { "X-Hub-Signature-256": sig, "Content-Type": "application/json" },
});
assert.equal(r.res.status, 200);
const [task] = s.store.state.tasks;
assert.equal(task?.title, "отправить счёт");
assert.equal(task?.source, "whatsapp");
assert.equal(task?.link, "https://wa.me/77011234567");
});
it("Scenario: Сообщение WhatsApp с неверной подписью", async () => {
const s = await start(FULL);
const r = await s.req("/webhooks/whatsapp", {
method: "POST",
body: payload,
headers: { "X-Hub-Signature-256": "sha256=00" },
});
assert.equal(r.res.status, 401);
assert.equal(s.store.state.tasks.length, 0);
});
});
describe("Требование: План дня и запись по подтверждению (страницы)", () => {
it("принять время → подтверждение календаря → событие", async () => {
const s = await start(FULL);
await s.login();
await s.a.connectGoogle("good-code", "https://x/cb");
s.a.ingest({
source: "gmail",
sourceId: "gmail:1",
sourceTitle: "Отчёт",
text: "Прошу подготовить отчёт сегодня",
link: "https://mail.google.com/x",
});
const id = s.store.state.tasks[0]?.id ?? "";
const tasks = await s.req("/");
assert.match(tasks.text, /Открыть письмо/);
assert.match(tasks.text, /Предлагаю:/);
const acc = await s.req(`/tasks/${id}/accept`, { method: "POST", form: { back: "tasks" } });
assert.equal(acc.res.headers.get("location"), "/?m=flash.acceptedNoChat");
const warn = await s.req("/?m=flash.acceptedNoChat");
assert.match(
warn.text,
/Напоминание сохранено, но чат Telegram не подтверждён. Подтвердите чат на странице «Подключения»./,
);
const confirmPage = await s.req(`/tasks/${id}/calendar`);
assert.match(confirmPage.text, /Да, добавить/);
assert.equal(s.g.created.length, 0, "открытие страницы подтверждения ничего не создаёт");
await s.req(`/tasks/${id}/calendar`, { method: "POST", form: {} });
assert.equal(s.g.created.length, 1);
const after = await s.req("/");
assert.match(after.text, /В календаре/);
});
it("план дня показывает предложенное время", async () => {
const s = await start(FULL);
await s.login();
s.a.ingest({
source: "gmail",
sourceId: "gmail:1",
sourceTitle: "Отчёт",
text: "Прошу подготовить отчёт сегодня",
});
const r = await s.req("/plan");
assert.match(r.text, /09:00–09:30/);
});
});